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.

259955 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. const String& extraHeaders)
  5422. : position (0),
  5423. finished (false),
  5424. isPost (isPost_),
  5425. progressCallback (progressCallback_),
  5426. progressCallbackContext (progressCallbackContext_)
  5427. {
  5428. server = url.toString (! isPost);
  5429. if (isPost_)
  5430. createHeadersAndPostData (url);
  5431. headers += extraHeaders;
  5432. if (! headers.endsWithChar (T('\n')))
  5433. headers << "\r\n";
  5434. handle = juce_openInternetFile (server, headers, postData, isPost,
  5435. progressCallback_, progressCallbackContext_);
  5436. }
  5437. ~WebInputStream()
  5438. {
  5439. juce_closeInternetFile (handle);
  5440. }
  5441. bool isError() const throw()
  5442. {
  5443. return handle == 0;
  5444. }
  5445. int64 getTotalLength()
  5446. {
  5447. return -1;
  5448. }
  5449. bool isExhausted()
  5450. {
  5451. return finished;
  5452. }
  5453. int read (void* dest, int bytes)
  5454. {
  5455. if (finished || isError())
  5456. {
  5457. return 0;
  5458. }
  5459. else
  5460. {
  5461. const int bytesRead = juce_readFromInternetFile (handle, dest, bytes);
  5462. position += bytesRead;
  5463. if (bytesRead == 0)
  5464. finished = true;
  5465. return bytesRead;
  5466. }
  5467. }
  5468. int64 getPosition()
  5469. {
  5470. return position;
  5471. }
  5472. bool setPosition (int64 wantedPos)
  5473. {
  5474. if (wantedPos != position)
  5475. {
  5476. finished = false;
  5477. const int actualPos = juce_seekInInternetFile (handle, (int) wantedPos);
  5478. if (actualPos == wantedPos)
  5479. {
  5480. position = wantedPos;
  5481. }
  5482. else
  5483. {
  5484. if (wantedPos < position)
  5485. {
  5486. juce_closeInternetFile (handle);
  5487. position = 0;
  5488. finished = false;
  5489. handle = juce_openInternetFile (server, headers, postData, isPost,
  5490. progressCallback, progressCallbackContext);
  5491. }
  5492. skipNextBytes (wantedPos - position);
  5493. }
  5494. }
  5495. return true;
  5496. }
  5497. juce_UseDebuggingNewOperator
  5498. private:
  5499. String server, headers;
  5500. MemoryBlock postData;
  5501. int64 position;
  5502. bool finished;
  5503. const bool isPost;
  5504. void* handle;
  5505. URL::OpenStreamProgressCallback* const progressCallback;
  5506. void* const progressCallbackContext;
  5507. void createHeadersAndPostData (const URL& url)
  5508. {
  5509. if (url.getFilesToUpload().size() > 0)
  5510. {
  5511. // need to upload some files, so do it as multi-part...
  5512. String boundary (String::toHexString (Random::getSystemRandom().nextInt64()));
  5513. headers << "Content-Type: multipart/form-data; boundary=" << boundary << "\r\n";
  5514. appendUTF8ToPostData ("--" + boundary);
  5515. int i;
  5516. for (i = 0; i < url.getParameters().size(); ++i)
  5517. {
  5518. String s;
  5519. s << "\r\nContent-Disposition: form-data; name=\""
  5520. << url.getParameters().getAllKeys() [i]
  5521. << "\"\r\n\r\n"
  5522. << url.getParameters().getAllValues() [i]
  5523. << "\r\n--"
  5524. << boundary;
  5525. appendUTF8ToPostData (s);
  5526. }
  5527. for (i = 0; i < url.getFilesToUpload().size(); ++i)
  5528. {
  5529. const File f (url.getFilesToUpload().getAllValues() [i]);
  5530. const String paramName (url.getFilesToUpload().getAllKeys() [i]);
  5531. String s;
  5532. s << "\r\nContent-Disposition: form-data; name=\""
  5533. << paramName
  5534. << "\"; filename=\""
  5535. << f.getFileName()
  5536. << "\"\r\n";
  5537. const String mimeType (url.getMimeTypesOfUploadFiles()
  5538. .getValue (paramName, String::empty));
  5539. if (mimeType.isNotEmpty())
  5540. s << "Content-Type: " << mimeType << "\r\n";
  5541. s << "Content-Transfer-Encoding: binary\r\n\r\n";
  5542. appendUTF8ToPostData (s);
  5543. f.loadFileAsData (postData);
  5544. s = "\r\n--" + boundary;
  5545. appendUTF8ToPostData (s);
  5546. }
  5547. appendUTF8ToPostData ("--\r\n");
  5548. }
  5549. else
  5550. {
  5551. // just a short text attachment, so use simple url encoding..
  5552. const String params (getMangledParameters (url.getParameters()));
  5553. headers = "Content-Type: application/x-www-form-urlencoded\r\nContent-length: "
  5554. + String ((int) strlen (params.toUTF8()))
  5555. + "\r\n";
  5556. appendUTF8ToPostData (params);
  5557. }
  5558. }
  5559. void appendUTF8ToPostData (const String& text) throw()
  5560. {
  5561. postData.append (text.toUTF8(),
  5562. (int) strlen (text.toUTF8()));
  5563. }
  5564. WebInputStream (const WebInputStream&);
  5565. const WebInputStream& operator= (const WebInputStream&);
  5566. };
  5567. InputStream* URL::createInputStream (const bool usePostCommand,
  5568. OpenStreamProgressCallback* const progressCallback,
  5569. void* const progressCallbackContext,
  5570. const String& extraHeaders) const
  5571. {
  5572. WebInputStream* wi = new WebInputStream (*this, usePostCommand,
  5573. progressCallback, progressCallbackContext,
  5574. extraHeaders);
  5575. if (wi->isError())
  5576. {
  5577. delete wi;
  5578. wi = 0;
  5579. }
  5580. return wi;
  5581. }
  5582. bool URL::readEntireBinaryStream (MemoryBlock& destData,
  5583. const bool usePostCommand) const
  5584. {
  5585. InputStream* const in = createInputStream (usePostCommand);
  5586. if (in != 0)
  5587. {
  5588. in->readIntoMemoryBlock (destData, -1);
  5589. delete in;
  5590. return true;
  5591. }
  5592. return false;
  5593. }
  5594. const String URL::readEntireTextStream (const bool usePostCommand) const
  5595. {
  5596. String result;
  5597. InputStream* const in = createInputStream (usePostCommand);
  5598. if (in != 0)
  5599. {
  5600. result = in->readEntireStreamAsString();
  5601. delete in;
  5602. }
  5603. return result;
  5604. }
  5605. XmlElement* URL::readEntireXmlStream (const bool usePostCommand) const
  5606. {
  5607. XmlDocument doc (readEntireTextStream (usePostCommand));
  5608. return doc.getDocumentElement();
  5609. }
  5610. const URL URL::withParameter (const String& parameterName,
  5611. const String& parameterValue) const
  5612. {
  5613. URL u (*this);
  5614. u.parameters.set (parameterName, parameterValue);
  5615. return u;
  5616. }
  5617. const URL URL::withFileToUpload (const String& parameterName,
  5618. const File& fileToUpload,
  5619. const String& mimeType) const
  5620. {
  5621. URL u (*this);
  5622. u.filesToUpload.set (parameterName, fileToUpload.getFullPathName());
  5623. u.mimeTypes.set (parameterName, mimeType);
  5624. return u;
  5625. }
  5626. const StringPairArray& URL::getParameters() const throw()
  5627. {
  5628. return parameters;
  5629. }
  5630. const StringPairArray& URL::getFilesToUpload() const throw()
  5631. {
  5632. return filesToUpload;
  5633. }
  5634. const StringPairArray& URL::getMimeTypesOfUploadFiles() const throw()
  5635. {
  5636. return mimeTypes;
  5637. }
  5638. const String URL::removeEscapeChars (const String& s)
  5639. {
  5640. const int len = s.length();
  5641. uint8* const resultUTF8 = (uint8*) juce_calloc (len * 4);
  5642. uint8* r = resultUTF8;
  5643. for (int i = 0; i < len; ++i)
  5644. {
  5645. char c = (char) s[i];
  5646. if (c == 0)
  5647. break;
  5648. if (c == '+')
  5649. {
  5650. c = ' ';
  5651. }
  5652. else if (c == '%')
  5653. {
  5654. c = (char) s.substring (i + 1, i + 3).getHexValue32();
  5655. i += 2;
  5656. }
  5657. *r++ = c;
  5658. }
  5659. const String stringResult (String::fromUTF8 (resultUTF8));
  5660. juce_free (resultUTF8);
  5661. return stringResult;
  5662. }
  5663. const String URL::addEscapeChars (const String& s)
  5664. {
  5665. String result;
  5666. result.preallocateStorage (s.length() + 8);
  5667. const char* utf8 = s.toUTF8();
  5668. while (*utf8 != 0)
  5669. {
  5670. const char c = *utf8++;
  5671. if (c == ' ')
  5672. {
  5673. result += T('+');
  5674. }
  5675. else if (CharacterFunctions::isLetterOrDigit (c)
  5676. || CharacterFunctions::indexOfChar ("_-$.*!'(),", c, false) >= 0)
  5677. {
  5678. result << c;
  5679. }
  5680. else
  5681. {
  5682. const int v = (int) (uint8) c;
  5683. if (v < 0x10)
  5684. result << T("%0");
  5685. else
  5686. result << T('%');
  5687. result << String::toHexString (v);
  5688. }
  5689. }
  5690. return result;
  5691. }
  5692. extern bool juce_launchFile (const String& fileName,
  5693. const String& parameters) throw();
  5694. bool URL::launchInDefaultBrowser() const
  5695. {
  5696. String u (toString (true));
  5697. if (u.contains (T("@")) && ! u.contains (T(":")))
  5698. u = "mailto:" + u;
  5699. return juce_launchFile (u, String::empty);
  5700. }
  5701. END_JUCE_NAMESPACE
  5702. /********* End of inlined file: juce_URL.cpp *********/
  5703. /********* Start of inlined file: juce_BufferedInputStream.cpp *********/
  5704. BEGIN_JUCE_NAMESPACE
  5705. BufferedInputStream::BufferedInputStream (InputStream* const source_,
  5706. const int bufferSize_,
  5707. const bool deleteSourceWhenDestroyed_) throw()
  5708. : source (source_),
  5709. deleteSourceWhenDestroyed (deleteSourceWhenDestroyed_),
  5710. bufferSize (jmax (256, bufferSize_)),
  5711. position (source_->getPosition()),
  5712. lastReadPos (0),
  5713. bufferOverlap (128)
  5714. {
  5715. const int sourceSize = (int) source_->getTotalLength();
  5716. if (sourceSize >= 0)
  5717. bufferSize = jmin (jmax (32, sourceSize), bufferSize);
  5718. bufferStart = position;
  5719. buffer = (char*) juce_malloc (bufferSize);
  5720. }
  5721. BufferedInputStream::~BufferedInputStream() throw()
  5722. {
  5723. if (deleteSourceWhenDestroyed)
  5724. delete source;
  5725. juce_free (buffer);
  5726. }
  5727. int64 BufferedInputStream::getTotalLength()
  5728. {
  5729. return source->getTotalLength();
  5730. }
  5731. int64 BufferedInputStream::getPosition()
  5732. {
  5733. return position;
  5734. }
  5735. bool BufferedInputStream::setPosition (int64 newPosition)
  5736. {
  5737. position = jmax ((int64) 0, newPosition);
  5738. return true;
  5739. }
  5740. bool BufferedInputStream::isExhausted()
  5741. {
  5742. return (position >= lastReadPos)
  5743. && source->isExhausted();
  5744. }
  5745. void BufferedInputStream::ensureBuffered()
  5746. {
  5747. const int64 bufferEndOverlap = lastReadPos - bufferOverlap;
  5748. if (position < bufferStart || position >= bufferEndOverlap)
  5749. {
  5750. int bytesRead;
  5751. if (position < lastReadPos
  5752. && position >= bufferEndOverlap
  5753. && position >= bufferStart)
  5754. {
  5755. const int bytesToKeep = (int) (lastReadPos - position);
  5756. memmove (buffer, buffer + position - bufferStart, bytesToKeep);
  5757. bufferStart = position;
  5758. bytesRead = source->read (buffer + bytesToKeep,
  5759. bufferSize - bytesToKeep);
  5760. lastReadPos += bytesRead;
  5761. bytesRead += bytesToKeep;
  5762. }
  5763. else
  5764. {
  5765. bufferStart = position;
  5766. source->setPosition (bufferStart);
  5767. bytesRead = source->read (buffer, bufferSize);
  5768. lastReadPos = bufferStart + bytesRead;
  5769. }
  5770. while (bytesRead < bufferSize)
  5771. buffer [bytesRead++] = 0;
  5772. }
  5773. }
  5774. int BufferedInputStream::read (void* destBuffer, int maxBytesToRead)
  5775. {
  5776. if (position >= bufferStart
  5777. && position + maxBytesToRead < lastReadPos)
  5778. {
  5779. memcpy (destBuffer, buffer + (position - bufferStart), maxBytesToRead);
  5780. position += maxBytesToRead;
  5781. return maxBytesToRead;
  5782. }
  5783. else
  5784. {
  5785. int bytesRead = 0;
  5786. while (maxBytesToRead > 0)
  5787. {
  5788. ensureBuffered();
  5789. if (isExhausted())
  5790. break;
  5791. const int bytesAvailable = jmin (maxBytesToRead, (int) (lastReadPos - position));
  5792. memcpy (destBuffer, buffer + (position - bufferStart), bytesAvailable);
  5793. maxBytesToRead -= bytesAvailable;
  5794. bytesRead += bytesAvailable;
  5795. position += bytesAvailable;
  5796. destBuffer = (void*) (((char*) destBuffer) + bytesAvailable);
  5797. }
  5798. return bytesRead;
  5799. }
  5800. }
  5801. const String BufferedInputStream::readString()
  5802. {
  5803. if (position >= bufferStart
  5804. && position < lastReadPos)
  5805. {
  5806. const int maxChars = (int) (lastReadPos - position);
  5807. const char* const src = buffer + (position - bufferStart);
  5808. for (int i = 0; i < maxChars; ++i)
  5809. {
  5810. if (src[i] == 0)
  5811. {
  5812. position += i + 1;
  5813. return String::fromUTF8 ((const uint8*) src, i);
  5814. }
  5815. }
  5816. }
  5817. return InputStream::readString();
  5818. }
  5819. END_JUCE_NAMESPACE
  5820. /********* End of inlined file: juce_BufferedInputStream.cpp *********/
  5821. /********* Start of inlined file: juce_FileInputSource.cpp *********/
  5822. BEGIN_JUCE_NAMESPACE
  5823. FileInputSource::FileInputSource (const File& file_) throw()
  5824. : file (file_)
  5825. {
  5826. }
  5827. FileInputSource::~FileInputSource()
  5828. {
  5829. }
  5830. InputStream* FileInputSource::createInputStream()
  5831. {
  5832. return file.createInputStream();
  5833. }
  5834. InputStream* FileInputSource::createInputStreamFor (const String& relatedItemPath)
  5835. {
  5836. return file.getSiblingFile (relatedItemPath).createInputStream();
  5837. }
  5838. int64 FileInputSource::hashCode() const
  5839. {
  5840. return file.hashCode();
  5841. }
  5842. END_JUCE_NAMESPACE
  5843. /********* End of inlined file: juce_FileInputSource.cpp *********/
  5844. /********* Start of inlined file: juce_MemoryInputStream.cpp *********/
  5845. BEGIN_JUCE_NAMESPACE
  5846. MemoryInputStream::MemoryInputStream (const void* const sourceData,
  5847. const int sourceDataSize,
  5848. const bool keepInternalCopy) throw()
  5849. : data ((const char*) sourceData),
  5850. dataSize (sourceDataSize),
  5851. position (0)
  5852. {
  5853. if (keepInternalCopy)
  5854. {
  5855. internalCopy.append (data, sourceDataSize);
  5856. data = (const char*) internalCopy.getData();
  5857. }
  5858. }
  5859. MemoryInputStream::~MemoryInputStream() throw()
  5860. {
  5861. }
  5862. int64 MemoryInputStream::getTotalLength()
  5863. {
  5864. return dataSize;
  5865. }
  5866. int MemoryInputStream::read (void* buffer, int howMany)
  5867. {
  5868. const int num = jmin (howMany, dataSize - position);
  5869. memcpy (buffer, data + position, num);
  5870. position += num;
  5871. return num;
  5872. }
  5873. bool MemoryInputStream::isExhausted()
  5874. {
  5875. return (position >= dataSize);
  5876. }
  5877. bool MemoryInputStream::setPosition (int64 pos)
  5878. {
  5879. position = (int) jlimit ((int64) 0, (int64) dataSize, pos);
  5880. return true;
  5881. }
  5882. int64 MemoryInputStream::getPosition()
  5883. {
  5884. return position;
  5885. }
  5886. END_JUCE_NAMESPACE
  5887. /********* End of inlined file: juce_MemoryInputStream.cpp *********/
  5888. /********* Start of inlined file: juce_MemoryOutputStream.cpp *********/
  5889. BEGIN_JUCE_NAMESPACE
  5890. MemoryOutputStream::MemoryOutputStream (const int initialSize,
  5891. const int blockSizeToIncreaseBy,
  5892. MemoryBlock* const memoryBlockToWriteTo) throw()
  5893. : data (memoryBlockToWriteTo),
  5894. position (0),
  5895. size (0),
  5896. blockSize (jmax (16, blockSizeToIncreaseBy)),
  5897. ownsMemoryBlock (memoryBlockToWriteTo == 0)
  5898. {
  5899. if (memoryBlockToWriteTo == 0)
  5900. data = new MemoryBlock (initialSize);
  5901. else
  5902. memoryBlockToWriteTo->setSize (initialSize, false);
  5903. }
  5904. MemoryOutputStream::~MemoryOutputStream() throw()
  5905. {
  5906. if (ownsMemoryBlock)
  5907. delete data;
  5908. else
  5909. flush();
  5910. }
  5911. void MemoryOutputStream::flush()
  5912. {
  5913. if (! ownsMemoryBlock)
  5914. data->setSize (size, false);
  5915. }
  5916. void MemoryOutputStream::reset() throw()
  5917. {
  5918. position = 0;
  5919. size = 0;
  5920. }
  5921. bool MemoryOutputStream::write (const void* buffer, int howMany)
  5922. {
  5923. int storageNeeded = position + howMany + 1;
  5924. storageNeeded = storageNeeded - (storageNeeded % blockSize) + blockSize;
  5925. data->ensureSize (storageNeeded);
  5926. data->copyFrom (buffer, position, howMany);
  5927. position += howMany;
  5928. size = jmax (size, position);
  5929. return true;
  5930. }
  5931. const char* MemoryOutputStream::getData() throw()
  5932. {
  5933. if (data->getSize() > size)
  5934. ((char*) data->getData()) [size] = 0;
  5935. return (const char*) data->getData();
  5936. }
  5937. int MemoryOutputStream::getDataSize() const throw()
  5938. {
  5939. return size;
  5940. }
  5941. int64 MemoryOutputStream::getPosition()
  5942. {
  5943. return position;
  5944. }
  5945. bool MemoryOutputStream::setPosition (int64 newPosition)
  5946. {
  5947. if (newPosition <= size)
  5948. {
  5949. // ok to seek backwards
  5950. position = jlimit (0, size, (int) newPosition);
  5951. return true;
  5952. }
  5953. else
  5954. {
  5955. // trying to make it bigger isn't a good thing to do..
  5956. return false;
  5957. }
  5958. }
  5959. END_JUCE_NAMESPACE
  5960. /********* End of inlined file: juce_MemoryOutputStream.cpp *********/
  5961. /********* Start of inlined file: juce_SubregionStream.cpp *********/
  5962. BEGIN_JUCE_NAMESPACE
  5963. SubregionStream::SubregionStream (InputStream* const sourceStream,
  5964. const int64 startPositionInSourceStream_,
  5965. const int64 lengthOfSourceStream_,
  5966. const bool deleteSourceWhenDestroyed_) throw()
  5967. : source (sourceStream),
  5968. deleteSourceWhenDestroyed (deleteSourceWhenDestroyed_),
  5969. startPositionInSourceStream (startPositionInSourceStream_),
  5970. lengthOfSourceStream (lengthOfSourceStream_)
  5971. {
  5972. setPosition (0);
  5973. }
  5974. SubregionStream::~SubregionStream() throw()
  5975. {
  5976. if (deleteSourceWhenDestroyed)
  5977. delete source;
  5978. }
  5979. int64 SubregionStream::getTotalLength()
  5980. {
  5981. const int64 srcLen = source->getTotalLength() - startPositionInSourceStream;
  5982. return (lengthOfSourceStream >= 0) ? jmin (lengthOfSourceStream, srcLen)
  5983. : srcLen;
  5984. }
  5985. int64 SubregionStream::getPosition()
  5986. {
  5987. return source->getPosition() - startPositionInSourceStream;
  5988. }
  5989. bool SubregionStream::setPosition (int64 newPosition)
  5990. {
  5991. return source->setPosition (jmax ((int64) 0, newPosition + startPositionInSourceStream));
  5992. }
  5993. int SubregionStream::read (void* destBuffer, int maxBytesToRead)
  5994. {
  5995. if (lengthOfSourceStream < 0)
  5996. {
  5997. return source->read (destBuffer, maxBytesToRead);
  5998. }
  5999. else
  6000. {
  6001. maxBytesToRead = (int) jmin ((int64) maxBytesToRead, lengthOfSourceStream - getPosition());
  6002. if (maxBytesToRead <= 0)
  6003. return 0;
  6004. return source->read (destBuffer, maxBytesToRead);
  6005. }
  6006. }
  6007. bool SubregionStream::isExhausted()
  6008. {
  6009. if (lengthOfSourceStream >= 0)
  6010. return (getPosition() >= lengthOfSourceStream) || source->isExhausted();
  6011. else
  6012. return source->isExhausted();
  6013. }
  6014. END_JUCE_NAMESPACE
  6015. /********* End of inlined file: juce_SubregionStream.cpp *********/
  6016. /********* Start of inlined file: juce_PerformanceCounter.cpp *********/
  6017. BEGIN_JUCE_NAMESPACE
  6018. PerformanceCounter::PerformanceCounter (const String& name_,
  6019. int runsPerPrintout,
  6020. const File& loggingFile)
  6021. : name (name_),
  6022. numRuns (0),
  6023. runsPerPrint (runsPerPrintout),
  6024. totalTime (0),
  6025. outputFile (loggingFile)
  6026. {
  6027. if (outputFile != File::nonexistent)
  6028. {
  6029. String s ("**** Counter for \"");
  6030. s << name_ << "\" started at: "
  6031. << Time::getCurrentTime().toString (true, true)
  6032. << "\r\n";
  6033. outputFile.appendText (s, false, false);
  6034. }
  6035. }
  6036. PerformanceCounter::~PerformanceCounter()
  6037. {
  6038. printStatistics();
  6039. }
  6040. void PerformanceCounter::start()
  6041. {
  6042. started = Time::getHighResolutionTicks();
  6043. }
  6044. void PerformanceCounter::stop()
  6045. {
  6046. const int64 now = Time::getHighResolutionTicks();
  6047. totalTime += 1000.0 * Time::highResolutionTicksToSeconds (now - started);
  6048. if (++numRuns == runsPerPrint)
  6049. printStatistics();
  6050. }
  6051. void PerformanceCounter::printStatistics()
  6052. {
  6053. if (numRuns > 0)
  6054. {
  6055. String s ("Performance count for \"");
  6056. s << name << "\" - average over " << numRuns << " run(s) = ";
  6057. const int micros = (int) (totalTime * (1000.0 / numRuns));
  6058. if (micros > 10000)
  6059. s << (micros/1000) << " millisecs";
  6060. else
  6061. s << micros << " microsecs";
  6062. s << ", total = " << String (totalTime / 1000, 5) << " seconds";
  6063. Logger::outputDebugString (s);
  6064. s << "\r\n";
  6065. if (outputFile != File::nonexistent)
  6066. outputFile.appendText (s, false, false);
  6067. numRuns = 0;
  6068. totalTime = 0;
  6069. }
  6070. }
  6071. END_JUCE_NAMESPACE
  6072. /********* End of inlined file: juce_PerformanceCounter.cpp *********/
  6073. /********* Start of inlined file: juce_Uuid.cpp *********/
  6074. BEGIN_JUCE_NAMESPACE
  6075. Uuid::Uuid()
  6076. {
  6077. // do some serious mixing up of our MAC addresses and different types of time info,
  6078. // plus a couple of passes of pseudo-random numbers over the whole thing.
  6079. SystemStats::getMACAddresses (value.asInt64, 2);
  6080. int i;
  6081. for (i = 16; --i >= 0;)
  6082. {
  6083. Random r (Time::getHighResolutionTicks()
  6084. + Random::getSystemRandom().nextInt()
  6085. + value.asInt [i & 3]);
  6086. value.asBytes[i] ^= (uint8) r.nextInt();
  6087. }
  6088. value.asInt64 [0] ^= Time::getHighResolutionTicks();
  6089. value.asInt64 [1] ^= Time::currentTimeMillis();
  6090. for (i = 4; --i >= 0;)
  6091. {
  6092. Random r (Time::getHighResolutionTicks() ^ value.asInt[i]);
  6093. value.asInt[i] ^= r.nextInt();
  6094. }
  6095. }
  6096. Uuid::~Uuid() throw()
  6097. {
  6098. }
  6099. Uuid::Uuid (const Uuid& other)
  6100. : value (other.value)
  6101. {
  6102. }
  6103. Uuid& Uuid::operator= (const Uuid& other)
  6104. {
  6105. if (this != &other)
  6106. value = other.value;
  6107. return *this;
  6108. }
  6109. bool Uuid::operator== (const Uuid& other) const
  6110. {
  6111. return memcmp (value.asBytes, other.value.asBytes, 16) == 0;
  6112. }
  6113. bool Uuid::operator!= (const Uuid& other) const
  6114. {
  6115. return ! operator== (other);
  6116. }
  6117. bool Uuid::isNull() const throw()
  6118. {
  6119. return (value.asInt64 [0] == 0) && (value.asInt64 [1] == 0);
  6120. }
  6121. const String Uuid::toString() const
  6122. {
  6123. return String::toHexString (value.asBytes, 16, 0);
  6124. }
  6125. Uuid::Uuid (const String& uuidString)
  6126. {
  6127. operator= (uuidString);
  6128. }
  6129. Uuid& Uuid::operator= (const String& uuidString)
  6130. {
  6131. int destIndex = 0;
  6132. int i = 0;
  6133. for (;;)
  6134. {
  6135. int byte = 0;
  6136. for (int loop = 2; --loop >= 0;)
  6137. {
  6138. byte <<= 4;
  6139. for (;;)
  6140. {
  6141. const tchar c = uuidString [i++];
  6142. if (c >= T('0') && c <= T('9'))
  6143. {
  6144. byte |= c - T('0');
  6145. break;
  6146. }
  6147. else if (c >= T('a') && c <= T('z'))
  6148. {
  6149. byte |= c - (T('a') - 10);
  6150. break;
  6151. }
  6152. else if (c >= T('A') && c <= T('Z'))
  6153. {
  6154. byte |= c - (T('A') - 10);
  6155. break;
  6156. }
  6157. else if (c == 0)
  6158. {
  6159. while (destIndex < 16)
  6160. value.asBytes [destIndex++] = 0;
  6161. return *this;
  6162. }
  6163. }
  6164. }
  6165. value.asBytes [destIndex++] = (uint8) byte;
  6166. }
  6167. }
  6168. Uuid::Uuid (const uint8* const rawData)
  6169. {
  6170. operator= (rawData);
  6171. }
  6172. Uuid& Uuid::operator= (const uint8* const rawData)
  6173. {
  6174. if (rawData != 0)
  6175. memcpy (value.asBytes, rawData, 16);
  6176. else
  6177. zeromem (value.asBytes, 16);
  6178. return *this;
  6179. }
  6180. END_JUCE_NAMESPACE
  6181. /********* End of inlined file: juce_Uuid.cpp *********/
  6182. /********* Start of inlined file: juce_ZipFile.cpp *********/
  6183. BEGIN_JUCE_NAMESPACE
  6184. struct ZipEntryInfo
  6185. {
  6186. ZipFile::ZipEntry entry;
  6187. int streamOffset;
  6188. int compressedSize;
  6189. bool compressed;
  6190. };
  6191. class ZipInputStream : public InputStream
  6192. {
  6193. public:
  6194. ZipInputStream (ZipFile& file_,
  6195. ZipEntryInfo& zei) throw()
  6196. : file (file_),
  6197. zipEntryInfo (zei),
  6198. pos (0),
  6199. headerSize (0),
  6200. inputStream (0)
  6201. {
  6202. inputStream = file_.inputStream;
  6203. if (file_.inputSource != 0)
  6204. {
  6205. inputStream = file.inputSource->createInputStream();
  6206. }
  6207. else
  6208. {
  6209. #ifdef JUCE_DEBUG
  6210. file_.numOpenStreams++;
  6211. #endif
  6212. }
  6213. char buffer [30];
  6214. if (inputStream != 0
  6215. && inputStream->setPosition (zei.streamOffset)
  6216. && inputStream->read (buffer, 30) == 30
  6217. && littleEndianInt (buffer) == 0x04034b50)
  6218. {
  6219. headerSize = 30 + littleEndianShort (buffer + 26)
  6220. + littleEndianShort (buffer + 28);
  6221. }
  6222. }
  6223. ~ZipInputStream() throw()
  6224. {
  6225. #ifdef JUCE_DEBUG
  6226. if (inputStream != 0 && inputStream == file.inputStream)
  6227. file.numOpenStreams--;
  6228. #endif
  6229. if (inputStream != file.inputStream)
  6230. delete inputStream;
  6231. }
  6232. int64 getTotalLength() throw()
  6233. {
  6234. return zipEntryInfo.compressedSize;
  6235. }
  6236. int read (void* buffer, int howMany) throw()
  6237. {
  6238. if (headerSize <= 0)
  6239. return 0;
  6240. howMany = (int) jmin ((int64) howMany, zipEntryInfo.compressedSize - pos);
  6241. if (inputStream == 0)
  6242. return 0;
  6243. int num;
  6244. if (inputStream == file.inputStream)
  6245. {
  6246. const ScopedLock sl (file.lock);
  6247. inputStream->setPosition (pos + zipEntryInfo.streamOffset + headerSize);
  6248. num = inputStream->read (buffer, howMany);
  6249. }
  6250. else
  6251. {
  6252. inputStream->setPosition (pos + zipEntryInfo.streamOffset + headerSize);
  6253. num = inputStream->read (buffer, howMany);
  6254. }
  6255. pos += num;
  6256. return num;
  6257. }
  6258. bool isExhausted() throw()
  6259. {
  6260. return pos >= zipEntryInfo.compressedSize;
  6261. }
  6262. int64 getPosition() throw()
  6263. {
  6264. return pos;
  6265. }
  6266. bool setPosition (int64 newPos) throw()
  6267. {
  6268. pos = jlimit ((int64) 0, (int64) zipEntryInfo.compressedSize, newPos);
  6269. return true;
  6270. }
  6271. private:
  6272. ZipFile& file;
  6273. ZipEntryInfo zipEntryInfo;
  6274. int64 pos;
  6275. int headerSize;
  6276. InputStream* inputStream;
  6277. ZipInputStream (const ZipInputStream&);
  6278. const ZipInputStream& operator= (const ZipInputStream&);
  6279. };
  6280. ZipFile::ZipFile (InputStream* const source_,
  6281. const bool deleteStreamWhenDestroyed_) throw()
  6282. : inputStream (source_),
  6283. inputSource (0),
  6284. deleteStreamWhenDestroyed (deleteStreamWhenDestroyed_)
  6285. #ifdef JUCE_DEBUG
  6286. , numOpenStreams (0)
  6287. #endif
  6288. {
  6289. init();
  6290. }
  6291. ZipFile::ZipFile (const File& file)
  6292. : inputStream (0),
  6293. deleteStreamWhenDestroyed (false)
  6294. #ifdef JUCE_DEBUG
  6295. , numOpenStreams (0)
  6296. #endif
  6297. {
  6298. inputSource = new FileInputSource (file);
  6299. init();
  6300. }
  6301. ZipFile::ZipFile (InputSource* const inputSource_)
  6302. : inputStream (0),
  6303. inputSource (inputSource_),
  6304. deleteStreamWhenDestroyed (false)
  6305. #ifdef JUCE_DEBUG
  6306. , numOpenStreams (0)
  6307. #endif
  6308. {
  6309. init();
  6310. }
  6311. ZipFile::~ZipFile() throw()
  6312. {
  6313. for (int i = entries.size(); --i >= 0;)
  6314. {
  6315. ZipEntryInfo* const zei = (ZipEntryInfo*) entries [i];
  6316. delete zei;
  6317. }
  6318. if (deleteStreamWhenDestroyed)
  6319. delete inputStream;
  6320. delete inputSource;
  6321. #ifdef JUCE_DEBUG
  6322. // If you hit this assertion, it means you've created a stream to read
  6323. // one of the items in the zipfile, but you've forgotten to delete that
  6324. // stream object before deleting the file.. Streams can't be kept open
  6325. // after the file is deleted because they need to share the input
  6326. // stream that the file uses to read itself.
  6327. jassert (numOpenStreams == 0);
  6328. #endif
  6329. }
  6330. int ZipFile::getNumEntries() const throw()
  6331. {
  6332. return entries.size();
  6333. }
  6334. const ZipFile::ZipEntry* ZipFile::getEntry (const int index) const throw()
  6335. {
  6336. ZipEntryInfo* const zei = (ZipEntryInfo*) entries [index];
  6337. return (zei != 0) ? &(zei->entry)
  6338. : 0;
  6339. }
  6340. int ZipFile::getIndexOfFileName (const String& fileName) const throw()
  6341. {
  6342. for (int i = 0; i < entries.size(); ++i)
  6343. if (((ZipEntryInfo*) entries.getUnchecked (i))->entry.filename == fileName)
  6344. return i;
  6345. return -1;
  6346. }
  6347. const ZipFile::ZipEntry* ZipFile::getEntry (const String& fileName) const throw()
  6348. {
  6349. return getEntry (getIndexOfFileName (fileName));
  6350. }
  6351. InputStream* ZipFile::createStreamForEntry (const int index)
  6352. {
  6353. ZipEntryInfo* const zei = (ZipEntryInfo*) entries[index];
  6354. InputStream* stream = 0;
  6355. if (zei != 0)
  6356. {
  6357. stream = new ZipInputStream (*this, *zei);
  6358. if (zei->compressed)
  6359. {
  6360. stream = new GZIPDecompressorInputStream (stream, true, true,
  6361. zei->entry.uncompressedSize);
  6362. // (much faster to unzip in big blocks using a buffer..)
  6363. stream = new BufferedInputStream (stream, 32768, true);
  6364. }
  6365. }
  6366. return stream;
  6367. }
  6368. class ZipFilenameComparator
  6369. {
  6370. public:
  6371. static int compareElements (const void* const first, const void* const second) throw()
  6372. {
  6373. return ((const ZipEntryInfo*) first)->entry.filename
  6374. .compare (((const ZipEntryInfo*) second)->entry.filename);
  6375. }
  6376. };
  6377. void ZipFile::sortEntriesByFilename()
  6378. {
  6379. ZipFilenameComparator sorter;
  6380. entries.sort (sorter);
  6381. }
  6382. void ZipFile::init()
  6383. {
  6384. InputStream* in = inputStream;
  6385. bool deleteInput = false;
  6386. if (inputSource != 0)
  6387. {
  6388. deleteInput = true;
  6389. in = inputSource->createInputStream();
  6390. }
  6391. if (in != 0)
  6392. {
  6393. numEntries = 0;
  6394. int pos = findEndOfZipEntryTable (in);
  6395. const int size = (int) (in->getTotalLength() - pos);
  6396. in->setPosition (pos);
  6397. MemoryBlock headerData;
  6398. if (in->readIntoMemoryBlock (headerData, size) == size)
  6399. {
  6400. pos = 0;
  6401. for (int i = 0; i < numEntries; ++i)
  6402. {
  6403. if (pos + 46 > size)
  6404. break;
  6405. const char* const buffer = ((const char*) headerData.getData()) + pos;
  6406. const int fileNameLen = littleEndianShort (buffer + 28);
  6407. if (pos + 46 + fileNameLen > size)
  6408. break;
  6409. ZipEntryInfo* const zei = new ZipEntryInfo();
  6410. zei->entry.filename = String (buffer + 46, fileNameLen);
  6411. const int time = littleEndianShort (buffer + 12);
  6412. const int date = littleEndianShort (buffer + 14);
  6413. const int year = 1980 + (date >> 9);
  6414. const int month = ((date >> 5) & 15) - 1;
  6415. const int day = date & 31;
  6416. const int hours = time >> 11;
  6417. const int minutes = (time >> 5) & 63;
  6418. const int seconds = (time & 31) << 1;
  6419. zei->entry.fileTime = Time (year, month, day, hours, minutes, seconds);
  6420. zei->compressed = littleEndianShort (buffer + 10) != 0;
  6421. zei->compressedSize = littleEndianInt (buffer + 20);
  6422. zei->entry.uncompressedSize = littleEndianInt (buffer + 24);
  6423. zei->streamOffset = littleEndianInt (buffer + 42);
  6424. entries.add (zei);
  6425. pos += 46 + fileNameLen
  6426. + littleEndianShort (buffer + 30)
  6427. + littleEndianShort (buffer + 32);
  6428. }
  6429. }
  6430. if (deleteInput)
  6431. delete in;
  6432. }
  6433. }
  6434. int ZipFile::findEndOfZipEntryTable (InputStream* input)
  6435. {
  6436. BufferedInputStream in (input, 8192, false);
  6437. in.setPosition (in.getTotalLength());
  6438. int64 pos = in.getPosition();
  6439. char buffer [32];
  6440. zeromem (buffer, sizeof (buffer));
  6441. while (pos > 0)
  6442. {
  6443. in.setPosition (pos - 22);
  6444. pos = in.getPosition();
  6445. memcpy (buffer + 22, buffer, 4);
  6446. if (in.read (buffer, 22) != 22)
  6447. return 0;
  6448. for (int i = 0; i < 22; ++i)
  6449. {
  6450. if (littleEndianInt (buffer + i) == 0x06054b50)
  6451. {
  6452. in.setPosition (pos + i);
  6453. in.read (buffer, 22);
  6454. numEntries = littleEndianShort (buffer + 10);
  6455. return littleEndianInt (buffer + 16);
  6456. }
  6457. }
  6458. }
  6459. return 0;
  6460. }
  6461. void ZipFile::uncompressTo (const File& targetDirectory,
  6462. const bool shouldOverwriteFiles)
  6463. {
  6464. for (int i = 0; i < entries.size(); ++i)
  6465. {
  6466. const ZipEntryInfo& zei = *(ZipEntryInfo*) entries[i];
  6467. const File targetFile (targetDirectory.getChildFile (zei.entry.filename));
  6468. if (zei.entry.filename.endsWithChar (T('/')))
  6469. {
  6470. targetFile.createDirectory(); // (entry is a directory, not a file)
  6471. }
  6472. else
  6473. {
  6474. InputStream* const in = createStreamForEntry (i);
  6475. if (in != 0)
  6476. {
  6477. if (shouldOverwriteFiles)
  6478. targetFile.deleteFile();
  6479. if ((! targetFile.exists())
  6480. && targetFile.getParentDirectory().createDirectory())
  6481. {
  6482. FileOutputStream* const out = targetFile.createOutputStream();
  6483. if (out != 0)
  6484. {
  6485. out->writeFromInputStream (*in, -1);
  6486. delete out;
  6487. targetFile.setCreationTime (zei.entry.fileTime);
  6488. targetFile.setLastModificationTime (zei.entry.fileTime);
  6489. targetFile.setLastAccessTime (zei.entry.fileTime);
  6490. }
  6491. }
  6492. delete in;
  6493. }
  6494. }
  6495. }
  6496. }
  6497. END_JUCE_NAMESPACE
  6498. /********* End of inlined file: juce_ZipFile.cpp *********/
  6499. /********* Start of inlined file: juce_CharacterFunctions.cpp *********/
  6500. #ifdef _MSC_VER
  6501. #pragma warning (disable: 4514 4996)
  6502. #pragma warning (push)
  6503. #endif
  6504. #include <cwctype>
  6505. #include <cctype>
  6506. #include <ctime>
  6507. #ifdef _MSC_VER
  6508. #pragma warning (pop)
  6509. #endif
  6510. BEGIN_JUCE_NAMESPACE
  6511. int CharacterFunctions::length (const char* const s) throw()
  6512. {
  6513. return (int) strlen (s);
  6514. }
  6515. int CharacterFunctions::length (const juce_wchar* const s) throw()
  6516. {
  6517. #if MACOS_10_2_OR_EARLIER
  6518. int n = 0;
  6519. while (s[n] != 0)
  6520. ++n;
  6521. return n;
  6522. #else
  6523. return (int) wcslen (s);
  6524. #endif
  6525. }
  6526. void CharacterFunctions::copy (char* dest, const char* src, const int maxChars) throw()
  6527. {
  6528. strncpy (dest, src, maxChars);
  6529. }
  6530. void CharacterFunctions::copy (juce_wchar* dest, const juce_wchar* src, int maxChars) throw()
  6531. {
  6532. #if MACOS_10_2_OR_EARLIER
  6533. while (--maxChars >= 0 && *src != 0)
  6534. *dest++ = *src++;
  6535. *dest = 0;
  6536. #else
  6537. wcsncpy (dest, src, maxChars);
  6538. #endif
  6539. }
  6540. void CharacterFunctions::copy (juce_wchar* dest, const char* src, const int maxChars) throw()
  6541. {
  6542. mbstowcs (dest, src, maxChars);
  6543. }
  6544. void CharacterFunctions::copy (char* dest, const juce_wchar* src, const int maxChars) throw()
  6545. {
  6546. wcstombs (dest, src, maxChars);
  6547. }
  6548. int CharacterFunctions::bytesRequiredForCopy (const juce_wchar* src) throw()
  6549. {
  6550. return (int) wcstombs (0, src, 0);
  6551. }
  6552. void CharacterFunctions::append (char* dest, const char* src) throw()
  6553. {
  6554. strcat (dest, src);
  6555. }
  6556. void CharacterFunctions::append (juce_wchar* dest, const juce_wchar* src) throw()
  6557. {
  6558. #if MACOS_10_2_OR_EARLIER
  6559. while (*dest != 0)
  6560. ++dest;
  6561. while (*src != 0)
  6562. *dest++ = *src++;
  6563. *dest = 0;
  6564. #else
  6565. wcscat (dest, src);
  6566. #endif
  6567. }
  6568. int CharacterFunctions::compare (const char* const s1, const char* const s2) throw()
  6569. {
  6570. return strcmp (s1, s2);
  6571. }
  6572. int CharacterFunctions::compare (const juce_wchar* s1, const juce_wchar* s2) throw()
  6573. {
  6574. jassert (s1 != 0 && s2 != 0);
  6575. #if MACOS_10_2_OR_EARLIER
  6576. for (;;)
  6577. {
  6578. if (*s1 != *s2)
  6579. {
  6580. const int diff = *s1 - *s2;
  6581. if (diff != 0)
  6582. return diff < 0 ? -1 : 1;
  6583. }
  6584. else if (*s1 == 0)
  6585. break;
  6586. ++s1;
  6587. ++s2;
  6588. }
  6589. return 0;
  6590. #else
  6591. return wcscmp (s1, s2);
  6592. #endif
  6593. }
  6594. int CharacterFunctions::compare (const char* const s1, const char* const s2, const int maxChars) throw()
  6595. {
  6596. jassert (s1 != 0 && s2 != 0);
  6597. return strncmp (s1, s2, maxChars);
  6598. }
  6599. int CharacterFunctions::compare (const juce_wchar* s1, const juce_wchar* s2, int maxChars) throw()
  6600. {
  6601. jassert (s1 != 0 && s2 != 0);
  6602. #if MACOS_10_2_OR_EARLIER
  6603. while (--maxChars >= 0)
  6604. {
  6605. if (*s1 != *s2)
  6606. return (*s1 < *s2) ? -1 : 1;
  6607. else if (*s1 == 0)
  6608. break;
  6609. ++s1;
  6610. ++s2;
  6611. }
  6612. return 0;
  6613. #else
  6614. return wcsncmp (s1, s2, maxChars);
  6615. #endif
  6616. }
  6617. int CharacterFunctions::compareIgnoreCase (const char* const s1, const char* const s2) throw()
  6618. {
  6619. jassert (s1 != 0 && s2 != 0);
  6620. #if JUCE_WIN32
  6621. return stricmp (s1, s2);
  6622. #else
  6623. return strcasecmp (s1, s2);
  6624. #endif
  6625. }
  6626. int CharacterFunctions::compareIgnoreCase (const juce_wchar* s1, const juce_wchar* s2) throw()
  6627. {
  6628. jassert (s1 != 0 && s2 != 0);
  6629. #if JUCE_WIN32
  6630. return _wcsicmp (s1, s2);
  6631. #else
  6632. for (;;)
  6633. {
  6634. if (*s1 != *s2)
  6635. {
  6636. const int diff = toUpperCase (*s1) - toUpperCase (*s2);
  6637. if (diff != 0)
  6638. return diff < 0 ? -1 : 1;
  6639. }
  6640. else if (*s1 == 0)
  6641. break;
  6642. ++s1;
  6643. ++s2;
  6644. }
  6645. return 0;
  6646. #endif
  6647. }
  6648. int CharacterFunctions::compareIgnoreCase (const char* const s1, const char* const s2, const int maxChars) throw()
  6649. {
  6650. jassert (s1 != 0 && s2 != 0);
  6651. #if JUCE_WIN32
  6652. return strnicmp (s1, s2, maxChars);
  6653. #else
  6654. return strncasecmp (s1, s2, maxChars);
  6655. #endif
  6656. }
  6657. int CharacterFunctions::compareIgnoreCase (const juce_wchar* s1, const juce_wchar* s2, int maxChars) throw()
  6658. {
  6659. jassert (s1 != 0 && s2 != 0);
  6660. #if JUCE_WIN32
  6661. return _wcsnicmp (s1, s2, maxChars);
  6662. #else
  6663. while (--maxChars >= 0)
  6664. {
  6665. if (*s1 != *s2)
  6666. {
  6667. const int diff = toUpperCase (*s1) - toUpperCase (*s2);
  6668. if (diff != 0)
  6669. return diff < 0 ? -1 : 1;
  6670. }
  6671. else if (*s1 == 0)
  6672. break;
  6673. ++s1;
  6674. ++s2;
  6675. }
  6676. return 0;
  6677. #endif
  6678. }
  6679. const char* CharacterFunctions::find (const char* const haystack, const char* const needle) throw()
  6680. {
  6681. return strstr (haystack, needle);
  6682. }
  6683. const juce_wchar* CharacterFunctions::find (const juce_wchar* haystack, const juce_wchar* const needle) throw()
  6684. {
  6685. #if MACOS_10_2_OR_EARLIER
  6686. while (*haystack != 0)
  6687. {
  6688. const juce_wchar* s1 = haystack;
  6689. const juce_wchar* s2 = needle;
  6690. for (;;)
  6691. {
  6692. if (*s2 == 0)
  6693. return haystack;
  6694. if (*s1 != *s2 || *s2 == 0)
  6695. break;
  6696. ++s1;
  6697. ++s2;
  6698. }
  6699. ++haystack;
  6700. }
  6701. return 0;
  6702. #else
  6703. return wcsstr (haystack, needle);
  6704. #endif
  6705. }
  6706. int CharacterFunctions::indexOfChar (const char* const haystack, const char needle, const bool ignoreCase) throw()
  6707. {
  6708. if (haystack != 0)
  6709. {
  6710. int i = 0;
  6711. if (ignoreCase)
  6712. {
  6713. const char n1 = toLowerCase (needle);
  6714. const char n2 = toUpperCase (needle);
  6715. if (n1 != n2) // if the char is the same in upper/lower case, fall through to the normal search
  6716. {
  6717. while (haystack[i] != 0)
  6718. {
  6719. if (haystack[i] == n1 || haystack[i] == n2)
  6720. return i;
  6721. ++i;
  6722. }
  6723. return -1;
  6724. }
  6725. jassert (n1 == needle);
  6726. }
  6727. while (haystack[i] != 0)
  6728. {
  6729. if (haystack[i] == needle)
  6730. return i;
  6731. ++i;
  6732. }
  6733. }
  6734. return -1;
  6735. }
  6736. int CharacterFunctions::indexOfChar (const juce_wchar* const haystack, const juce_wchar needle, const bool ignoreCase) throw()
  6737. {
  6738. if (haystack != 0)
  6739. {
  6740. int i = 0;
  6741. if (ignoreCase)
  6742. {
  6743. const juce_wchar n1 = toLowerCase (needle);
  6744. const juce_wchar n2 = toUpperCase (needle);
  6745. if (n1 != n2) // if the char is the same in upper/lower case, fall through to the normal search
  6746. {
  6747. while (haystack[i] != 0)
  6748. {
  6749. if (haystack[i] == n1 || haystack[i] == n2)
  6750. return i;
  6751. ++i;
  6752. }
  6753. return -1;
  6754. }
  6755. jassert (n1 == needle);
  6756. }
  6757. while (haystack[i] != 0)
  6758. {
  6759. if (haystack[i] == needle)
  6760. return i;
  6761. ++i;
  6762. }
  6763. }
  6764. return -1;
  6765. }
  6766. int CharacterFunctions::indexOfCharFast (const char* const haystack, const char needle) throw()
  6767. {
  6768. jassert (haystack != 0);
  6769. int i = 0;
  6770. while (haystack[i] != 0)
  6771. {
  6772. if (haystack[i] == needle)
  6773. return i;
  6774. ++i;
  6775. }
  6776. return -1;
  6777. }
  6778. int CharacterFunctions::indexOfCharFast (const juce_wchar* const haystack, const juce_wchar needle) throw()
  6779. {
  6780. jassert (haystack != 0);
  6781. int i = 0;
  6782. while (haystack[i] != 0)
  6783. {
  6784. if (haystack[i] == needle)
  6785. return i;
  6786. ++i;
  6787. }
  6788. return -1;
  6789. }
  6790. int CharacterFunctions::getIntialSectionContainingOnly (const char* const text, const char* const allowedChars) throw()
  6791. {
  6792. return allowedChars == 0 ? 0 : (int) strspn (text, allowedChars);
  6793. }
  6794. int CharacterFunctions::getIntialSectionContainingOnly (const juce_wchar* const text, const juce_wchar* const allowedChars) throw()
  6795. {
  6796. if (allowedChars == 0)
  6797. return 0;
  6798. int i = 0;
  6799. for (;;)
  6800. {
  6801. if (indexOfCharFast (allowedChars, text[i]) < 0)
  6802. break;
  6803. ++i;
  6804. }
  6805. return i;
  6806. }
  6807. int CharacterFunctions::ftime (char* const dest, const int maxChars, const char* const format, const struct tm* const tm) throw()
  6808. {
  6809. return (int) strftime (dest, maxChars, format, tm);
  6810. }
  6811. int CharacterFunctions::ftime (juce_wchar* const dest, const int maxChars, const juce_wchar* const format, const struct tm* const tm) throw()
  6812. {
  6813. #if MACOS_10_2_OR_EARLIER
  6814. const String formatTemp (format);
  6815. size_t num = strftime ((char*) dest, maxChars, (const char*) formatTemp, tm);
  6816. String temp ((char*) dest);
  6817. temp.copyToBuffer (dest, num);
  6818. dest [num] = 0;
  6819. return (int) num;
  6820. #else
  6821. return (int) wcsftime (dest, maxChars, format, tm);
  6822. #endif
  6823. }
  6824. int CharacterFunctions::getIntValue (const char* const s) throw()
  6825. {
  6826. return atoi (s);
  6827. }
  6828. int CharacterFunctions::getIntValue (const juce_wchar* s) throw()
  6829. {
  6830. #if JUCE_WIN32
  6831. return _wtoi (s);
  6832. #else
  6833. int v = 0;
  6834. while (isWhitespace (*s))
  6835. ++s;
  6836. const bool isNeg = *s == T('-');
  6837. if (isNeg)
  6838. ++s;
  6839. for (;;)
  6840. {
  6841. const wchar_t c = *s++;
  6842. if (c >= T('0') && c <= T('9'))
  6843. v = v * 10 + (int) (c - T('0'));
  6844. else
  6845. break;
  6846. }
  6847. return isNeg ? -v : v;
  6848. #endif
  6849. }
  6850. int64 CharacterFunctions::getInt64Value (const char* s) throw()
  6851. {
  6852. #if JUCE_LINUX
  6853. return atoll (s);
  6854. #elif defined (JUCE_WIN32)
  6855. return _atoi64 (s);
  6856. #else
  6857. int64 v = 0;
  6858. while (isWhitespace (*s))
  6859. ++s;
  6860. const bool isNeg = *s == T('-');
  6861. if (isNeg)
  6862. ++s;
  6863. for (;;)
  6864. {
  6865. const char c = *s++;
  6866. if (c >= '0' && c <= '9')
  6867. v = v * 10 + (int64) (c - '0');
  6868. else
  6869. break;
  6870. }
  6871. return isNeg ? -v : v;
  6872. #endif
  6873. }
  6874. int64 CharacterFunctions::getInt64Value (const juce_wchar* s) throw()
  6875. {
  6876. #if JUCE_WIN32
  6877. return _wtoi64 (s);
  6878. #else
  6879. int64 v = 0;
  6880. while (isWhitespace (*s))
  6881. ++s;
  6882. const bool isNeg = *s == T('-');
  6883. if (isNeg)
  6884. ++s;
  6885. for (;;)
  6886. {
  6887. const juce_wchar c = *s++;
  6888. if (c >= T('0') && c <= T('9'))
  6889. v = v * 10 + (int64) (c - T('0'));
  6890. else
  6891. break;
  6892. }
  6893. return isNeg ? -v : v;
  6894. #endif
  6895. }
  6896. double CharacterFunctions::getDoubleValue (const char* const s) throw()
  6897. {
  6898. return atof (s);
  6899. }
  6900. double CharacterFunctions::getDoubleValue (const juce_wchar* const s) throw()
  6901. {
  6902. #if MACOS_10_2_OR_EARLIER
  6903. String temp (s);
  6904. return atof ((const char*) temp);
  6905. #else
  6906. wchar_t* endChar;
  6907. return wcstod (s, &endChar);
  6908. #endif
  6909. }
  6910. char CharacterFunctions::toUpperCase (const char character) throw()
  6911. {
  6912. return (char) toupper (character);
  6913. }
  6914. juce_wchar CharacterFunctions::toUpperCase (const juce_wchar character) throw()
  6915. {
  6916. #if MACOS_10_2_OR_EARLIER
  6917. return toupper ((char) character);
  6918. #else
  6919. return towupper (character);
  6920. #endif
  6921. }
  6922. void CharacterFunctions::toUpperCase (char* s) throw()
  6923. {
  6924. #if JUCE_WIN32
  6925. strupr (s);
  6926. #else
  6927. while (*s != 0)
  6928. {
  6929. *s = toUpperCase (*s);
  6930. ++s;
  6931. }
  6932. #endif
  6933. }
  6934. void CharacterFunctions::toUpperCase (juce_wchar* s) throw()
  6935. {
  6936. #if JUCE_WIN32
  6937. _wcsupr (s);
  6938. #else
  6939. while (*s != 0)
  6940. {
  6941. *s = toUpperCase (*s);
  6942. ++s;
  6943. }
  6944. #endif
  6945. }
  6946. bool CharacterFunctions::isUpperCase (const char character) throw()
  6947. {
  6948. return isupper (character) != 0;
  6949. }
  6950. bool CharacterFunctions::isUpperCase (const juce_wchar character) throw()
  6951. {
  6952. #if JUCE_WIN32
  6953. return iswupper (character) != 0;
  6954. #else
  6955. return toLowerCase (character) != character;
  6956. #endif
  6957. }
  6958. char CharacterFunctions::toLowerCase (const char character) throw()
  6959. {
  6960. return (char) tolower (character);
  6961. }
  6962. juce_wchar CharacterFunctions::toLowerCase (const juce_wchar character) throw()
  6963. {
  6964. #if MACOS_10_2_OR_EARLIER
  6965. return tolower ((char) character);
  6966. #else
  6967. return towlower (character);
  6968. #endif
  6969. }
  6970. void CharacterFunctions::toLowerCase (char* s) throw()
  6971. {
  6972. #if JUCE_WIN32
  6973. strlwr (s);
  6974. #else
  6975. while (*s != 0)
  6976. {
  6977. *s = toLowerCase (*s);
  6978. ++s;
  6979. }
  6980. #endif
  6981. }
  6982. void CharacterFunctions::toLowerCase (juce_wchar* s) throw()
  6983. {
  6984. #if JUCE_WIN32
  6985. _wcslwr (s);
  6986. #else
  6987. while (*s != 0)
  6988. {
  6989. *s = toLowerCase (*s);
  6990. ++s;
  6991. }
  6992. #endif
  6993. }
  6994. bool CharacterFunctions::isLowerCase (const char character) throw()
  6995. {
  6996. return islower (character) != 0;
  6997. }
  6998. bool CharacterFunctions::isLowerCase (const juce_wchar character) throw()
  6999. {
  7000. #if JUCE_WIN32
  7001. return iswlower (character) != 0;
  7002. #else
  7003. return toUpperCase (character) != character;
  7004. #endif
  7005. }
  7006. bool CharacterFunctions::isWhitespace (const char character) throw()
  7007. {
  7008. return character == T(' ') || (character <= 13 && character >= 9);
  7009. }
  7010. bool CharacterFunctions::isWhitespace (const juce_wchar character) throw()
  7011. {
  7012. #if MACOS_10_2_OR_EARLIER
  7013. return isWhitespace ((char) character);
  7014. #else
  7015. return iswspace (character) != 0;
  7016. #endif
  7017. }
  7018. bool CharacterFunctions::isDigit (const char character) throw()
  7019. {
  7020. return (character >= '0' && character <= '9');
  7021. }
  7022. bool CharacterFunctions::isDigit (const juce_wchar character) throw()
  7023. {
  7024. #if MACOS_10_2_OR_EARLIER
  7025. return isdigit ((char) character) != 0;
  7026. #else
  7027. return iswdigit (character) != 0;
  7028. #endif
  7029. }
  7030. bool CharacterFunctions::isLetter (const char character) throw()
  7031. {
  7032. return (character >= 'a' && character <= 'z')
  7033. || (character >= 'A' && character <= 'Z');
  7034. }
  7035. bool CharacterFunctions::isLetter (const juce_wchar character) throw()
  7036. {
  7037. #if MACOS_10_2_OR_EARLIER
  7038. return isLetter ((char) character);
  7039. #else
  7040. return iswalpha (character) != 0;
  7041. #endif
  7042. }
  7043. bool CharacterFunctions::isLetterOrDigit (const char character) throw()
  7044. {
  7045. return (character >= 'a' && character <= 'z')
  7046. || (character >= 'A' && character <= 'Z')
  7047. || (character >= '0' && character <= '9');
  7048. }
  7049. bool CharacterFunctions::isLetterOrDigit (const juce_wchar character) throw()
  7050. {
  7051. #if MACOS_10_2_OR_EARLIER
  7052. return isLetterOrDigit ((char) character);
  7053. #else
  7054. return iswalnum (character) != 0;
  7055. #endif
  7056. }
  7057. int CharacterFunctions::getHexDigitValue (const tchar digit) throw()
  7058. {
  7059. if (digit >= T('0') && digit <= T('9'))
  7060. return digit - T('0');
  7061. else if (digit >= T('a') && digit <= T('f'))
  7062. return digit - (T('a') - 10);
  7063. else if (digit >= T('A') && digit <= T('F'))
  7064. return digit - (T('A') - 10);
  7065. return -1;
  7066. }
  7067. int CharacterFunctions::printf (char* const dest, const int maxLength, const char* const format, ...) throw()
  7068. {
  7069. va_list list;
  7070. va_start (list, format);
  7071. return vprintf (dest, maxLength, format, list);
  7072. }
  7073. int CharacterFunctions::printf (juce_wchar* const dest, const int maxLength, const juce_wchar* const format, ...) throw()
  7074. {
  7075. va_list list;
  7076. va_start (list, format);
  7077. return vprintf (dest, maxLength, format, list);
  7078. }
  7079. int CharacterFunctions::vprintf (char* const dest, const int maxLength, const char* const format, va_list& args) throw()
  7080. {
  7081. #if JUCE_WIN32
  7082. return (int) _vsnprintf (dest, maxLength, format, args);
  7083. #else
  7084. return (int) vsnprintf (dest, maxLength, format, args);
  7085. #endif
  7086. }
  7087. int CharacterFunctions::vprintf (juce_wchar* const dest, const int maxLength, const juce_wchar* const format, va_list& args) throw()
  7088. {
  7089. #if MACOS_10_3_OR_EARLIER
  7090. const String formatTemp (format);
  7091. size_t num = vprintf ((char*) dest, maxLength, formatTemp, args);
  7092. String temp ((char*) dest);
  7093. temp.copyToBuffer (dest, num);
  7094. dest [num] = 0;
  7095. return (int) num;
  7096. #elif defined (JUCE_WIN32)
  7097. return (int) _vsnwprintf (dest, maxLength, format, args);
  7098. #else
  7099. return (int) vswprintf (dest, maxLength, format, args);
  7100. #endif
  7101. }
  7102. END_JUCE_NAMESPACE
  7103. /********* End of inlined file: juce_CharacterFunctions.cpp *********/
  7104. /********* Start of inlined file: juce_LocalisedStrings.cpp *********/
  7105. BEGIN_JUCE_NAMESPACE
  7106. LocalisedStrings::LocalisedStrings (const String& fileContents) throw()
  7107. {
  7108. loadFromText (fileContents);
  7109. }
  7110. LocalisedStrings::LocalisedStrings (const File& fileToLoad) throw()
  7111. {
  7112. loadFromText (fileToLoad.loadFileAsString());
  7113. }
  7114. LocalisedStrings::~LocalisedStrings() throw()
  7115. {
  7116. }
  7117. const String LocalisedStrings::translate (const String& text) const throw()
  7118. {
  7119. return translations.getValue (text, text);
  7120. }
  7121. static int findCloseQuote (const String& text, int startPos) throw()
  7122. {
  7123. tchar lastChar = 0;
  7124. for (;;)
  7125. {
  7126. const tchar c = text [startPos];
  7127. if (c == 0 || (c == T('"') && lastChar != T('\\')))
  7128. break;
  7129. lastChar = c;
  7130. ++startPos;
  7131. }
  7132. return startPos;
  7133. }
  7134. static const String unescapeString (const String& s) throw()
  7135. {
  7136. return s.replace (T("\\\""), T("\""))
  7137. .replace (T("\\\'"), T("\'"))
  7138. .replace (T("\\t"), T("\t"))
  7139. .replace (T("\\r"), T("\r"))
  7140. .replace (T("\\n"), T("\n"));
  7141. }
  7142. void LocalisedStrings::loadFromText (const String& fileContents) throw()
  7143. {
  7144. StringArray lines;
  7145. lines.addLines (fileContents);
  7146. for (int i = 0; i < lines.size(); ++i)
  7147. {
  7148. String line (lines[i].trim());
  7149. if (line.startsWithChar (T('"')))
  7150. {
  7151. int closeQuote = findCloseQuote (line, 1);
  7152. const String originalText (unescapeString (line.substring (1, closeQuote)));
  7153. if (originalText.isNotEmpty())
  7154. {
  7155. const int openingQuote = findCloseQuote (line, closeQuote + 1);
  7156. closeQuote = findCloseQuote (line, openingQuote + 1);
  7157. const String newText (unescapeString (line.substring (openingQuote + 1, closeQuote)));
  7158. if (newText.isNotEmpty())
  7159. translations.set (originalText, newText);
  7160. }
  7161. }
  7162. else if (line.startsWithIgnoreCase (T("language:")))
  7163. {
  7164. languageName = line.substring (9).trim();
  7165. }
  7166. else if (line.startsWithIgnoreCase (T("countries:")))
  7167. {
  7168. countryCodes.addTokens (line.substring (10).trim(), true);
  7169. countryCodes.trim();
  7170. countryCodes.removeEmptyStrings();
  7171. }
  7172. }
  7173. }
  7174. static CriticalSection currentMappingsLock;
  7175. static LocalisedStrings* currentMappings = 0;
  7176. void LocalisedStrings::setCurrentMappings (LocalisedStrings* newTranslations) throw()
  7177. {
  7178. const ScopedLock sl (currentMappingsLock);
  7179. delete currentMappings;
  7180. currentMappings = newTranslations;
  7181. }
  7182. LocalisedStrings* LocalisedStrings::getCurrentMappings() throw()
  7183. {
  7184. return currentMappings;
  7185. }
  7186. const String LocalisedStrings::translateWithCurrentMappings (const String& text) throw()
  7187. {
  7188. const ScopedLock sl (currentMappingsLock);
  7189. if (currentMappings != 0)
  7190. return currentMappings->translate (text);
  7191. return text;
  7192. }
  7193. const String LocalisedStrings::translateWithCurrentMappings (const char* text) throw()
  7194. {
  7195. return translateWithCurrentMappings (String (text));
  7196. }
  7197. END_JUCE_NAMESPACE
  7198. /********* End of inlined file: juce_LocalisedStrings.cpp *********/
  7199. /********* Start of inlined file: juce_String.cpp *********/
  7200. #ifdef _MSC_VER
  7201. #pragma warning (disable: 4514)
  7202. #pragma warning (push)
  7203. #endif
  7204. #include <locale>
  7205. #if JUCE_MSVC
  7206. #include <float.h>
  7207. #endif
  7208. BEGIN_JUCE_NAMESPACE
  7209. #ifdef _MSC_VER
  7210. #pragma warning (pop)
  7211. #endif
  7212. static const char* const emptyCharString = "\0\0\0\0JUCE";
  7213. static const int safeEmptyStringRefCount = 0x3fffffff;
  7214. String::InternalRefCountedStringHolder String::emptyString = { safeEmptyStringRefCount, 0, { 0 } };
  7215. static tchar decimalPoint = T('.');
  7216. void juce_initialiseStrings()
  7217. {
  7218. decimalPoint = String::fromUTF8 ((const uint8*) localeconv()->decimal_point) [0];
  7219. }
  7220. void String::deleteInternal() throw()
  7221. {
  7222. if (atomicDecrementAndReturn (text->refCount) == 0)
  7223. juce_free (text);
  7224. }
  7225. void String::createInternal (const int numChars) throw()
  7226. {
  7227. jassert (numChars > 0);
  7228. text = (InternalRefCountedStringHolder*) juce_malloc (sizeof (InternalRefCountedStringHolder)
  7229. + numChars * sizeof (tchar));
  7230. text->refCount = 1;
  7231. text->allocatedNumChars = numChars;
  7232. text->text[0] = 0;
  7233. }
  7234. void String::createInternal (const tchar* const t, const tchar* const textEnd) throw()
  7235. {
  7236. jassert (*(textEnd - 1) == 0); // must have a null terminator
  7237. const int numChars = (int) (textEnd - t);
  7238. createInternal (numChars - 1);
  7239. memcpy (text->text, t, numChars * sizeof (tchar));
  7240. }
  7241. void String::appendInternal (const tchar* const newText,
  7242. const int numExtraChars) throw()
  7243. {
  7244. if (numExtraChars > 0)
  7245. {
  7246. const int oldLen = CharacterFunctions::length (text->text);
  7247. const int newTotalLen = oldLen + numExtraChars;
  7248. if (text->refCount > 1)
  7249. {
  7250. // it's in use by other strings as well, so we need to make a private copy before messing with it..
  7251. InternalRefCountedStringHolder* const newTextHolder
  7252. = (InternalRefCountedStringHolder*) juce_malloc (sizeof (InternalRefCountedStringHolder)
  7253. + newTotalLen * sizeof (tchar));
  7254. newTextHolder->refCount = 1;
  7255. newTextHolder->allocatedNumChars = newTotalLen;
  7256. memcpy (newTextHolder->text, text->text, oldLen * sizeof (tchar));
  7257. memcpy (newTextHolder->text + oldLen, newText, numExtraChars * sizeof (tchar));
  7258. InternalRefCountedStringHolder* const old = text;
  7259. text = newTextHolder;
  7260. if (atomicDecrementAndReturn (old->refCount) == 0)
  7261. juce_free (old);
  7262. }
  7263. else
  7264. {
  7265. // no other strings using it, so just expand it if needed..
  7266. if (newTotalLen > text->allocatedNumChars)
  7267. {
  7268. text = (InternalRefCountedStringHolder*)
  7269. juce_realloc (text, sizeof (InternalRefCountedStringHolder)
  7270. + newTotalLen * sizeof (tchar));
  7271. text->allocatedNumChars = newTotalLen;
  7272. }
  7273. memcpy (text->text + oldLen, newText, numExtraChars * sizeof (tchar));
  7274. }
  7275. text->text [newTotalLen] = 0;
  7276. }
  7277. }
  7278. void String::dupeInternalIfMultiplyReferenced() throw()
  7279. {
  7280. if (text->refCount > 1)
  7281. {
  7282. InternalRefCountedStringHolder* const old = text;
  7283. const int len = old->allocatedNumChars;
  7284. InternalRefCountedStringHolder* const newTextHolder
  7285. = (InternalRefCountedStringHolder*) juce_malloc (sizeof (InternalRefCountedStringHolder)
  7286. + len * sizeof (tchar));
  7287. newTextHolder->refCount = 1;
  7288. newTextHolder->allocatedNumChars = len;
  7289. memcpy (newTextHolder->text, old->text, (len + 1) * sizeof (tchar));
  7290. text = newTextHolder;
  7291. if (atomicDecrementAndReturn (old->refCount) == 0)
  7292. juce_free (old);
  7293. }
  7294. }
  7295. const String String::empty;
  7296. String::String() throw()
  7297. : text (&emptyString)
  7298. {
  7299. }
  7300. String::String (const String& other) throw()
  7301. : text (other.text)
  7302. {
  7303. atomicIncrement (text->refCount);
  7304. }
  7305. String::String (const int numChars,
  7306. const int /*dummyVariable*/) throw()
  7307. {
  7308. createInternal (numChars);
  7309. }
  7310. String::String (const char* const t) throw()
  7311. {
  7312. if (t != 0 && *t != 0)
  7313. {
  7314. const int len = CharacterFunctions::length (t);
  7315. createInternal (len);
  7316. #if JUCE_STRINGS_ARE_UNICODE
  7317. CharacterFunctions::copy (text->text, t, len + 1);
  7318. #else
  7319. memcpy (text->text, t, len + 1);
  7320. #endif
  7321. }
  7322. else
  7323. {
  7324. text = &emptyString;
  7325. emptyString.refCount = safeEmptyStringRefCount;
  7326. }
  7327. }
  7328. String::String (const juce_wchar* const t) throw()
  7329. {
  7330. if (t != 0 && *t != 0)
  7331. {
  7332. #if JUCE_STRINGS_ARE_UNICODE
  7333. const int len = CharacterFunctions::length (t);
  7334. createInternal (len);
  7335. memcpy (text->text, t, (len + 1) * sizeof (tchar));
  7336. #else
  7337. const int len = CharacterFunctions::bytesRequiredForCopy (t);
  7338. createInternal (len);
  7339. CharacterFunctions::copy (text->text, t, len + 1);
  7340. #endif
  7341. }
  7342. else
  7343. {
  7344. text = &emptyString;
  7345. emptyString.refCount = safeEmptyStringRefCount;
  7346. }
  7347. }
  7348. String::String (const char* const t,
  7349. const int maxChars) throw()
  7350. {
  7351. int i;
  7352. for (i = 0; i < maxChars; ++i)
  7353. if (t[i] == 0)
  7354. break;
  7355. if (i > 0)
  7356. {
  7357. createInternal (i);
  7358. #if JUCE_STRINGS_ARE_UNICODE
  7359. CharacterFunctions::copy (text->text, t, i);
  7360. #else
  7361. memcpy (text->text, t, i);
  7362. #endif
  7363. text->text [i] = 0;
  7364. }
  7365. else
  7366. {
  7367. text = &emptyString;
  7368. emptyString.refCount = safeEmptyStringRefCount;
  7369. }
  7370. }
  7371. String::String (const juce_wchar* const t,
  7372. const int maxChars) throw()
  7373. {
  7374. int i;
  7375. for (i = 0; i < maxChars; ++i)
  7376. if (t[i] == 0)
  7377. break;
  7378. if (i > 0)
  7379. {
  7380. createInternal (i);
  7381. #if JUCE_STRINGS_ARE_UNICODE
  7382. memcpy (text->text, t, i * sizeof (tchar));
  7383. #else
  7384. CharacterFunctions::copy (text->text, t, i);
  7385. #endif
  7386. text->text [i] = 0;
  7387. }
  7388. else
  7389. {
  7390. text = &emptyString;
  7391. emptyString.refCount = safeEmptyStringRefCount;
  7392. }
  7393. }
  7394. const String String::charToString (const tchar character) throw()
  7395. {
  7396. tchar temp[2];
  7397. temp[0] = character;
  7398. temp[1] = 0;
  7399. return String (temp);
  7400. }
  7401. // pass in a pointer to the END of a buffer..
  7402. static tchar* int64ToCharString (tchar* t, const int64 n) throw()
  7403. {
  7404. *--t = 0;
  7405. int64 v = (n >= 0) ? n : -n;
  7406. do
  7407. {
  7408. *--t = (tchar) (T('0') + (int) (v % 10));
  7409. v /= 10;
  7410. } while (v > 0);
  7411. if (n < 0)
  7412. *--t = T('-');
  7413. return t;
  7414. }
  7415. static tchar* intToCharString (tchar* t, const int n) throw()
  7416. {
  7417. if (n == (int) 0x80000000) // (would cause an overflow)
  7418. return int64ToCharString (t, n);
  7419. *--t = 0;
  7420. int v = abs (n);
  7421. do
  7422. {
  7423. *--t = (tchar) (T('0') + (v % 10));
  7424. v /= 10;
  7425. } while (v > 0);
  7426. if (n < 0)
  7427. *--t = T('-');
  7428. return t;
  7429. }
  7430. static tchar* uintToCharString (tchar* t, unsigned int v) throw()
  7431. {
  7432. *--t = 0;
  7433. do
  7434. {
  7435. *--t = (tchar) (T('0') + (v % 10));
  7436. v /= 10;
  7437. } while (v > 0);
  7438. return t;
  7439. }
  7440. String::String (const int number) throw()
  7441. {
  7442. tchar buffer [16];
  7443. tchar* const end = buffer + 16;
  7444. createInternal (intToCharString (end, number), end);
  7445. }
  7446. String::String (const unsigned int number) throw()
  7447. {
  7448. tchar buffer [16];
  7449. tchar* const end = buffer + 16;
  7450. createInternal (uintToCharString (end, number), end);
  7451. }
  7452. String::String (const short number) throw()
  7453. {
  7454. tchar buffer [16];
  7455. tchar* const end = buffer + 16;
  7456. createInternal (intToCharString (end, (int) number), end);
  7457. }
  7458. String::String (const unsigned short number) throw()
  7459. {
  7460. tchar buffer [16];
  7461. tchar* const end = buffer + 16;
  7462. createInternal (uintToCharString (end, (unsigned int) number), end);
  7463. }
  7464. String::String (const int64 number) throw()
  7465. {
  7466. tchar buffer [32];
  7467. tchar* const end = buffer + 32;
  7468. createInternal (int64ToCharString (end, number), end);
  7469. }
  7470. String::String (const uint64 number) throw()
  7471. {
  7472. tchar buffer [32];
  7473. tchar* const end = buffer + 32;
  7474. tchar* t = end;
  7475. *--t = 0;
  7476. int64 v = number;
  7477. do
  7478. {
  7479. *--t = (tchar) (T('0') + (int) (v % 10));
  7480. v /= 10;
  7481. } while (v > 0);
  7482. createInternal (t, end);
  7483. }
  7484. // a double-to-string routine that actually uses the number of dec. places you asked for
  7485. // without resorting to exponent notation if the number's too big or small (which is what printf does).
  7486. void String::doubleToStringWithDecPlaces (double n, int numDecPlaces) throw()
  7487. {
  7488. const int bufSize = 80;
  7489. tchar buffer [bufSize];
  7490. int len;
  7491. tchar* t;
  7492. if (numDecPlaces > 0 && n > -1.0e20 && n < 1.0e20)
  7493. {
  7494. int64 v = (int64) (pow (10.0, numDecPlaces) * fabs (n) + 0.5);
  7495. t = buffer + bufSize;
  7496. *--t = (tchar) 0;
  7497. while (numDecPlaces >= 0 || v > 0)
  7498. {
  7499. if (numDecPlaces == 0)
  7500. *--t = decimalPoint;
  7501. *--t = (tchar) (T('0') + (v % 10));
  7502. v /= 10;
  7503. --numDecPlaces;
  7504. }
  7505. if (n < 0)
  7506. *--t = T('-');
  7507. len = (int) ((buffer + bufSize) - t);
  7508. }
  7509. else
  7510. {
  7511. len = CharacterFunctions::printf (buffer, bufSize, T("%.9g"), n) + 1;
  7512. t = buffer;
  7513. }
  7514. if (len > 1)
  7515. {
  7516. jassert (len < numElementsInArray (buffer));
  7517. createInternal (len - 1);
  7518. memcpy (text->text, t, len * sizeof (tchar));
  7519. }
  7520. else
  7521. {
  7522. jassert (*t == 0);
  7523. text = &emptyString;
  7524. emptyString.refCount = safeEmptyStringRefCount;
  7525. }
  7526. }
  7527. String::String (const float number,
  7528. const int numberOfDecimalPlaces) throw()
  7529. {
  7530. doubleToStringWithDecPlaces ((double) number,
  7531. numberOfDecimalPlaces);
  7532. }
  7533. String::String (const double number,
  7534. const int numberOfDecimalPlaces) throw()
  7535. {
  7536. doubleToStringWithDecPlaces (number,
  7537. numberOfDecimalPlaces);
  7538. }
  7539. String::~String() throw()
  7540. {
  7541. if (atomicDecrementAndReturn (text->refCount) == 0)
  7542. juce_free (text);
  7543. }
  7544. void String::preallocateStorage (const int numChars) throw()
  7545. {
  7546. if (numChars > text->allocatedNumChars)
  7547. {
  7548. dupeInternalIfMultiplyReferenced();
  7549. text = (InternalRefCountedStringHolder*) juce_realloc (text, sizeof (InternalRefCountedStringHolder)
  7550. + numChars * sizeof (tchar));
  7551. text->allocatedNumChars = numChars;
  7552. }
  7553. }
  7554. #if JUCE_STRINGS_ARE_UNICODE
  7555. String::operator const char*() const throw()
  7556. {
  7557. if (isEmpty())
  7558. {
  7559. return (const char*) emptyCharString;
  7560. }
  7561. else
  7562. {
  7563. String* const mutableThis = const_cast <String*> (this);
  7564. mutableThis->dupeInternalIfMultiplyReferenced();
  7565. int len = CharacterFunctions::bytesRequiredForCopy (text->text) + 1;
  7566. mutableThis->text = (InternalRefCountedStringHolder*)
  7567. juce_realloc (text, sizeof (InternalRefCountedStringHolder)
  7568. + (len * sizeof (juce_wchar) + len));
  7569. char* otherCopy = (char*) (text->text + len);
  7570. --len;
  7571. CharacterFunctions::copy (otherCopy, text->text, len);
  7572. otherCopy [len] = 0;
  7573. return otherCopy;
  7574. }
  7575. }
  7576. #else
  7577. String::operator const juce_wchar*() const throw()
  7578. {
  7579. if (isEmpty())
  7580. {
  7581. return (const juce_wchar*) emptyCharString;
  7582. }
  7583. else
  7584. {
  7585. String* const mutableThis = const_cast <String*> (this);
  7586. mutableThis->dupeInternalIfMultiplyReferenced();
  7587. int len = CharacterFunctions::length (text->text) + 1;
  7588. mutableThis->text = (InternalRefCountedStringHolder*)
  7589. juce_realloc (text, sizeof (InternalRefCountedStringHolder)
  7590. + (len * sizeof (juce_wchar) + len));
  7591. juce_wchar* otherCopy = (juce_wchar*) (text->text + len);
  7592. --len;
  7593. CharacterFunctions::copy (otherCopy, text->text, len);
  7594. otherCopy [len] = 0;
  7595. return otherCopy;
  7596. }
  7597. }
  7598. #endif
  7599. void String::copyToBuffer (char* const destBuffer,
  7600. const int bufferSizeBytes) const throw()
  7601. {
  7602. #if JUCE_STRINGS_ARE_UNICODE
  7603. const int len = jmin (bufferSizeBytes, CharacterFunctions::bytesRequiredForCopy (text->text));
  7604. CharacterFunctions::copy (destBuffer, text->text, len);
  7605. #else
  7606. const int len = jmin (bufferSizeBytes, length());
  7607. memcpy (destBuffer, text->text, len * sizeof (tchar));
  7608. #endif
  7609. destBuffer [len] = 0;
  7610. }
  7611. void String::copyToBuffer (juce_wchar* const destBuffer,
  7612. const int maxCharsToCopy) const throw()
  7613. {
  7614. const int len = jmin (maxCharsToCopy, length());
  7615. #if JUCE_STRINGS_ARE_UNICODE
  7616. memcpy (destBuffer, text->text, len * sizeof (juce_wchar));
  7617. #else
  7618. CharacterFunctions::copy (destBuffer, text->text, len);
  7619. #endif
  7620. destBuffer [len] = 0;
  7621. }
  7622. int String::length() const throw()
  7623. {
  7624. return CharacterFunctions::length (text->text);
  7625. }
  7626. int String::hashCode() const throw()
  7627. {
  7628. const tchar* t = text->text;
  7629. int result = 0;
  7630. while (*t != (tchar) 0)
  7631. result = 31 * result + *t++;
  7632. return result;
  7633. }
  7634. int64 String::hashCode64() const throw()
  7635. {
  7636. const tchar* t = text->text;
  7637. int64 result = 0;
  7638. while (*t != (tchar) 0)
  7639. result = 101 * result + *t++;
  7640. return result;
  7641. }
  7642. const String& String::operator= (const tchar* const otherText) throw()
  7643. {
  7644. if (otherText != 0 && *otherText != 0)
  7645. {
  7646. const int otherLen = CharacterFunctions::length (otherText);
  7647. if (otherLen > 0)
  7648. {
  7649. // avoid resizing the memory block if the string is
  7650. // shrinking..
  7651. if (text->refCount > 1
  7652. || otherLen > text->allocatedNumChars
  7653. || otherLen <= (text->allocatedNumChars >> 1))
  7654. {
  7655. deleteInternal();
  7656. createInternal (otherLen);
  7657. }
  7658. memcpy (text->text, otherText, (otherLen + 1) * sizeof (tchar));
  7659. return *this;
  7660. }
  7661. }
  7662. deleteInternal();
  7663. text = &emptyString;
  7664. emptyString.refCount = safeEmptyStringRefCount;
  7665. return *this;
  7666. }
  7667. const String& String::operator= (const String& other) throw()
  7668. {
  7669. if (this != &other)
  7670. {
  7671. atomicIncrement (other.text->refCount);
  7672. if (atomicDecrementAndReturn (text->refCount) == 0)
  7673. juce_free (text);
  7674. text = other.text;
  7675. }
  7676. return *this;
  7677. }
  7678. bool String::operator== (const String& other) const throw()
  7679. {
  7680. return text == other.text
  7681. || CharacterFunctions::compare (text->text, other.text->text) == 0;
  7682. }
  7683. bool String::operator== (const tchar* const t) const throw()
  7684. {
  7685. return t != 0 ? CharacterFunctions::compare (text->text, t) == 0
  7686. : isEmpty();
  7687. }
  7688. bool String::equalsIgnoreCase (const tchar* t) const throw()
  7689. {
  7690. return t != 0 ? CharacterFunctions::compareIgnoreCase (text->text, t) == 0
  7691. : isEmpty();
  7692. }
  7693. bool String::equalsIgnoreCase (const String& other) const throw()
  7694. {
  7695. return text == other.text
  7696. || CharacterFunctions::compareIgnoreCase (text->text, other.text->text) == 0;
  7697. }
  7698. bool String::operator!= (const String& other) const throw()
  7699. {
  7700. return text != other.text
  7701. && CharacterFunctions::compare (text->text, other.text->text) != 0;
  7702. }
  7703. bool String::operator!= (const tchar* const t) const throw()
  7704. {
  7705. return t != 0 ? (CharacterFunctions::compare (text->text, t) != 0)
  7706. : isNotEmpty();
  7707. }
  7708. bool String::operator> (const String& other) const throw()
  7709. {
  7710. return compare (other) > 0;
  7711. }
  7712. bool String::operator< (const tchar* const other) const throw()
  7713. {
  7714. return compare (other) < 0;
  7715. }
  7716. bool String::operator>= (const String& other) const throw()
  7717. {
  7718. return compare (other) >= 0;
  7719. }
  7720. bool String::operator<= (const tchar* const other) const throw()
  7721. {
  7722. return compare (other) <= 0;
  7723. }
  7724. int String::compare (const tchar* const other) const throw()
  7725. {
  7726. return other != 0 ? CharacterFunctions::compare (text->text, other)
  7727. : isEmpty();
  7728. }
  7729. int String::compareIgnoreCase (const tchar* const other) const throw()
  7730. {
  7731. return other != 0 ? CharacterFunctions::compareIgnoreCase (text->text, other)
  7732. : isEmpty();
  7733. }
  7734. int String::compareLexicographically (const tchar* other) const throw()
  7735. {
  7736. if (other == 0)
  7737. return isEmpty();
  7738. const tchar* s1 = text->text;
  7739. while (*s1 != 0 && ! CharacterFunctions::isLetterOrDigit (*s1))
  7740. ++s1;
  7741. while (*other != 0 && ! CharacterFunctions::isLetterOrDigit (*other))
  7742. ++other;
  7743. return CharacterFunctions::compareIgnoreCase (s1, other);
  7744. }
  7745. const String String::operator+ (const String& other) const throw()
  7746. {
  7747. if (*(other.text->text) == 0)
  7748. return *this;
  7749. if (isEmpty())
  7750. return other;
  7751. const int len = CharacterFunctions::length (text->text);
  7752. const int otherLen = CharacterFunctions::length (other.text->text);
  7753. String result (len + otherLen, (int) 0);
  7754. memcpy (result.text->text, text->text, len * sizeof (tchar));
  7755. memcpy (result.text->text + len, other.text->text, otherLen * sizeof (tchar));
  7756. result.text->text [len + otherLen] = 0;
  7757. return result;
  7758. }
  7759. const String String::operator+ (const tchar* const textToAppend) const throw()
  7760. {
  7761. if (textToAppend == 0 || *textToAppend == 0)
  7762. return *this;
  7763. const int len = CharacterFunctions::length (text->text);
  7764. const int otherLen = CharacterFunctions::length (textToAppend);
  7765. String result (len + otherLen, (int) 0);
  7766. memcpy (result.text->text, text->text, len * sizeof (tchar));
  7767. memcpy (result.text->text + len, textToAppend, otherLen * sizeof (tchar));
  7768. result.text->text [len + otherLen] = 0;
  7769. return result;
  7770. }
  7771. const String String::operator+ (const tchar characterToAppend) const throw()
  7772. {
  7773. if (characterToAppend == 0)
  7774. return *this;
  7775. const int len = CharacterFunctions::length (text->text);
  7776. String result ((int) (len + 1), (int) 0);
  7777. memcpy (result.text->text, text->text, len * sizeof (tchar));
  7778. result.text->text[len] = characterToAppend;
  7779. result.text->text[len + 1] = 0;
  7780. return result;
  7781. }
  7782. const String JUCE_PUBLIC_FUNCTION operator+ (const char* const string1,
  7783. const String& string2) throw()
  7784. {
  7785. String s (string1);
  7786. s += string2;
  7787. return s;
  7788. }
  7789. const String JUCE_PUBLIC_FUNCTION operator+ (const juce_wchar* const string1,
  7790. const String& string2) throw()
  7791. {
  7792. String s (string1);
  7793. s += string2;
  7794. return s;
  7795. }
  7796. const String& String::operator+= (const tchar* const t) throw()
  7797. {
  7798. if (t != 0)
  7799. appendInternal (t, CharacterFunctions::length (t));
  7800. return *this;
  7801. }
  7802. const String& String::operator+= (const String& other) throw()
  7803. {
  7804. if (isEmpty())
  7805. operator= (other);
  7806. else
  7807. appendInternal (other.text->text,
  7808. CharacterFunctions::length (other.text->text));
  7809. return *this;
  7810. }
  7811. const String& String::operator+= (const char ch) throw()
  7812. {
  7813. char asString[2];
  7814. asString[0] = ch;
  7815. asString[1] = 0;
  7816. #if JUCE_STRINGS_ARE_UNICODE
  7817. operator+= (String (asString));
  7818. #else
  7819. appendInternal (asString, 1);
  7820. #endif
  7821. return *this;
  7822. }
  7823. const String& String::operator+= (const juce_wchar ch) throw()
  7824. {
  7825. juce_wchar asString[2];
  7826. asString[0] = ch;
  7827. asString[1] = 0;
  7828. #if JUCE_STRINGS_ARE_UNICODE
  7829. appendInternal (asString, 1);
  7830. #else
  7831. operator+= (String (asString));
  7832. #endif
  7833. return *this;
  7834. }
  7835. void String::append (const tchar* const other,
  7836. const int howMany) throw()
  7837. {
  7838. if (howMany > 0)
  7839. {
  7840. int i;
  7841. for (i = 0; i < howMany; ++i)
  7842. if (other[i] == 0)
  7843. break;
  7844. appendInternal (other, i);
  7845. }
  7846. }
  7847. String& String::operator<< (const int number) throw()
  7848. {
  7849. tchar buffer [64];
  7850. tchar* const end = buffer + 64;
  7851. const tchar* const t = intToCharString (end, number);
  7852. appendInternal (t, (int) (end - t) - 1);
  7853. return *this;
  7854. }
  7855. String& String::operator<< (const unsigned int number) throw()
  7856. {
  7857. tchar buffer [64];
  7858. tchar* const end = buffer + 64;
  7859. const tchar* const t = uintToCharString (end, number);
  7860. appendInternal (t, (int) (end - t) - 1);
  7861. return *this;
  7862. }
  7863. String& String::operator<< (const short number) throw()
  7864. {
  7865. tchar buffer [64];
  7866. tchar* const end = buffer + 64;
  7867. const tchar* const t = intToCharString (end, (int) number);
  7868. appendInternal (t, (int) (end - t) - 1);
  7869. return *this;
  7870. }
  7871. String& String::operator<< (const double number) throw()
  7872. {
  7873. operator+= (String (number));
  7874. return *this;
  7875. }
  7876. String& String::operator<< (const float number) throw()
  7877. {
  7878. operator+= (String (number));
  7879. return *this;
  7880. }
  7881. String& String::operator<< (const char character) throw()
  7882. {
  7883. operator+= (character);
  7884. return *this;
  7885. }
  7886. String& String::operator<< (const juce_wchar character) throw()
  7887. {
  7888. operator+= (character);
  7889. return *this;
  7890. }
  7891. String& String::operator<< (const char* const t) throw()
  7892. {
  7893. #if JUCE_STRINGS_ARE_UNICODE
  7894. operator+= (String (t));
  7895. #else
  7896. operator+= (t);
  7897. #endif
  7898. return *this;
  7899. }
  7900. String& String::operator<< (const juce_wchar* const t) throw()
  7901. {
  7902. #if JUCE_STRINGS_ARE_UNICODE
  7903. operator+= (t);
  7904. #else
  7905. operator+= (String (t));
  7906. #endif
  7907. return *this;
  7908. }
  7909. String& String::operator<< (const String& t) throw()
  7910. {
  7911. operator+= (t);
  7912. return *this;
  7913. }
  7914. int String::indexOfChar (const tchar character) const throw()
  7915. {
  7916. const tchar* t = text->text;
  7917. for (;;)
  7918. {
  7919. if (*t == character)
  7920. return (int) (t - text->text);
  7921. if (*t++ == 0)
  7922. return -1;
  7923. }
  7924. }
  7925. int String::lastIndexOfChar (const tchar character) const throw()
  7926. {
  7927. for (int i = CharacterFunctions::length (text->text); --i >= 0;)
  7928. if (text->text[i] == character)
  7929. return i;
  7930. return -1;
  7931. }
  7932. int String::indexOf (const tchar* const t) const throw()
  7933. {
  7934. const tchar* const r = CharacterFunctions::find (text->text, t);
  7935. return (r == 0) ? -1
  7936. : (int) (r - text->text);
  7937. }
  7938. int String::indexOfChar (const int startIndex,
  7939. const tchar character) const throw()
  7940. {
  7941. if (startIndex >= 0 && startIndex >= CharacterFunctions::length (text->text))
  7942. return -1;
  7943. const tchar* t = text->text + jmax (0, startIndex);
  7944. for (;;)
  7945. {
  7946. if (*t == character)
  7947. return (int) (t - text->text);
  7948. if (*t++ == 0)
  7949. return -1;
  7950. }
  7951. }
  7952. int String::indexOfAnyOf (const tchar* const charactersToLookFor,
  7953. const int startIndex,
  7954. const bool ignoreCase) const throw()
  7955. {
  7956. if (charactersToLookFor == 0
  7957. || (startIndex >= 0 && startIndex >= CharacterFunctions::length (text->text)))
  7958. return -1;
  7959. const tchar* t = text->text + jmax (0, startIndex);
  7960. while (*t != 0)
  7961. {
  7962. if (CharacterFunctions::indexOfChar (charactersToLookFor, *t, ignoreCase) >= 0)
  7963. return (int) (t - text->text);
  7964. ++t;
  7965. }
  7966. return -1;
  7967. }
  7968. int String::indexOf (const int startIndex,
  7969. const tchar* const other) const throw()
  7970. {
  7971. if (other == 0 || startIndex >= CharacterFunctions::length (text->text))
  7972. return -1;
  7973. const tchar* const found = CharacterFunctions::find (text->text + jmax (0, startIndex),
  7974. other);
  7975. return (found == 0) ? -1
  7976. : (int) (found - text->text);
  7977. }
  7978. int String::indexOfIgnoreCase (const tchar* const other) const throw()
  7979. {
  7980. if (other != 0 && *other != 0)
  7981. {
  7982. const int len = CharacterFunctions::length (other);
  7983. const int end = CharacterFunctions::length (text->text) - len;
  7984. for (int i = 0; i <= end; ++i)
  7985. if (CharacterFunctions::compareIgnoreCase (text->text + i, other, len) == 0)
  7986. return i;
  7987. }
  7988. return -1;
  7989. }
  7990. int String::indexOfIgnoreCase (const int startIndex,
  7991. const tchar* const other) const throw()
  7992. {
  7993. if (other != 0 && *other != 0)
  7994. {
  7995. const int len = CharacterFunctions::length (other);
  7996. const int end = length() - len;
  7997. for (int i = jmax (0, startIndex); i <= end; ++i)
  7998. if (CharacterFunctions::compareIgnoreCase (text->text + i, other, len) == 0)
  7999. return i;
  8000. }
  8001. return -1;
  8002. }
  8003. int String::lastIndexOf (const tchar* const other) const throw()
  8004. {
  8005. if (other != 0 && *other != 0)
  8006. {
  8007. const int len = CharacterFunctions::length (other);
  8008. int i = length() - len;
  8009. if (i >= 0)
  8010. {
  8011. const tchar* n = text->text + i;
  8012. while (i >= 0)
  8013. {
  8014. if (CharacterFunctions::compare (n--, other, len) == 0)
  8015. return i;
  8016. --i;
  8017. }
  8018. }
  8019. }
  8020. return -1;
  8021. }
  8022. int String::lastIndexOfIgnoreCase (const tchar* const other) const throw()
  8023. {
  8024. if (other != 0 && *other != 0)
  8025. {
  8026. const int len = CharacterFunctions::length (other);
  8027. int i = length() - len;
  8028. if (i >= 0)
  8029. {
  8030. const tchar* n = text->text + i;
  8031. while (i >= 0)
  8032. {
  8033. if (CharacterFunctions::compareIgnoreCase (n--, other, len) == 0)
  8034. return i;
  8035. --i;
  8036. }
  8037. }
  8038. }
  8039. return -1;
  8040. }
  8041. int String::lastIndexOfAnyOf (const tchar* const charactersToLookFor,
  8042. const bool ignoreCase) const throw()
  8043. {
  8044. for (int i = CharacterFunctions::length (text->text); --i >= 0;)
  8045. if (CharacterFunctions::indexOfChar (charactersToLookFor, text->text [i], ignoreCase) >= 0)
  8046. return i;
  8047. return -1;
  8048. }
  8049. bool String::contains (const tchar* const other) const throw()
  8050. {
  8051. return indexOf (other) >= 0;
  8052. }
  8053. bool String::containsChar (const tchar character) const throw()
  8054. {
  8055. return indexOfChar (character) >= 0;
  8056. }
  8057. bool String::containsIgnoreCase (const tchar* const t) const throw()
  8058. {
  8059. return indexOfIgnoreCase (t) >= 0;
  8060. }
  8061. int String::indexOfWholeWord (const tchar* const word) const throw()
  8062. {
  8063. if (word != 0 && *word != 0)
  8064. {
  8065. const int wordLen = CharacterFunctions::length (word);
  8066. const int end = length() - wordLen;
  8067. const tchar* t = text->text;
  8068. for (int i = 0; i <= end; ++i)
  8069. {
  8070. if (CharacterFunctions::compare (t, word, wordLen) == 0
  8071. && (i == 0 || ! CharacterFunctions::isLetterOrDigit (* (t - 1)))
  8072. && ! CharacterFunctions::isLetterOrDigit (t [wordLen]))
  8073. {
  8074. return i;
  8075. }
  8076. ++t;
  8077. }
  8078. }
  8079. return -1;
  8080. }
  8081. int String::indexOfWholeWordIgnoreCase (const tchar* const word) const throw()
  8082. {
  8083. if (word != 0 && *word != 0)
  8084. {
  8085. const int wordLen = CharacterFunctions::length (word);
  8086. const int end = length() - wordLen;
  8087. const tchar* t = text->text;
  8088. for (int i = 0; i <= end; ++i)
  8089. {
  8090. if (CharacterFunctions::compareIgnoreCase (t, word, wordLen) == 0
  8091. && (i == 0 || ! CharacterFunctions::isLetterOrDigit (* (t - 1)))
  8092. && ! CharacterFunctions::isLetterOrDigit (t [wordLen]))
  8093. {
  8094. return i;
  8095. }
  8096. ++t;
  8097. }
  8098. }
  8099. return -1;
  8100. }
  8101. bool String::containsWholeWord (const tchar* const wordToLookFor) const throw()
  8102. {
  8103. return indexOfWholeWord (wordToLookFor) >= 0;
  8104. }
  8105. bool String::containsWholeWordIgnoreCase (const tchar* const wordToLookFor) const throw()
  8106. {
  8107. return indexOfWholeWordIgnoreCase (wordToLookFor) >= 0;
  8108. }
  8109. static int indexOfMatch (const tchar* const wildcard,
  8110. const tchar* const test,
  8111. const bool ignoreCase) throw()
  8112. {
  8113. int start = 0;
  8114. while (test [start] != 0)
  8115. {
  8116. int i = 0;
  8117. for (;;)
  8118. {
  8119. const tchar wc = wildcard [i];
  8120. const tchar c = test [i + start];
  8121. if (wc == c
  8122. || (ignoreCase && CharacterFunctions::toLowerCase (wc) == CharacterFunctions::toLowerCase (c))
  8123. || (wc == T('?') && c != 0))
  8124. {
  8125. if (wc == 0)
  8126. return start;
  8127. ++i;
  8128. }
  8129. else
  8130. {
  8131. if (wc == T('*') && (wildcard [i + 1] == 0
  8132. || indexOfMatch (wildcard + i + 1,
  8133. test + start + i,
  8134. ignoreCase) >= 0))
  8135. {
  8136. return start;
  8137. }
  8138. break;
  8139. }
  8140. }
  8141. ++start;
  8142. }
  8143. return -1;
  8144. }
  8145. bool String::matchesWildcard (const tchar* wildcard, const bool ignoreCase) const throw()
  8146. {
  8147. int i = 0;
  8148. for (;;)
  8149. {
  8150. const tchar wc = wildcard [i];
  8151. const tchar c = text->text [i];
  8152. if (wc == c
  8153. || (ignoreCase && CharacterFunctions::toLowerCase (wc) == CharacterFunctions::toLowerCase (c))
  8154. || (wc == T('?') && c != 0))
  8155. {
  8156. if (wc == 0)
  8157. return true;
  8158. ++i;
  8159. }
  8160. else
  8161. {
  8162. return wc == T('*') && (wildcard [i + 1] == 0
  8163. || indexOfMatch (wildcard + i + 1,
  8164. text->text + i,
  8165. ignoreCase) >= 0);
  8166. }
  8167. }
  8168. }
  8169. void String::printf (const tchar* const pf, ...) throw()
  8170. {
  8171. va_list list;
  8172. va_start (list, pf);
  8173. vprintf (pf, list);
  8174. }
  8175. const String String::formatted (const tchar* const pf, ...) throw()
  8176. {
  8177. va_list list;
  8178. va_start (list, pf);
  8179. String result;
  8180. result.vprintf (pf, list);
  8181. return result;
  8182. }
  8183. void String::vprintf (const tchar* const pf, va_list& args) throw()
  8184. {
  8185. tchar stackBuf [256];
  8186. unsigned int bufSize = 256;
  8187. tchar* buf = stackBuf;
  8188. deleteInternal();
  8189. do
  8190. {
  8191. #if JUCE_LINUX && JUCE_64BIT
  8192. va_list tempArgs;
  8193. va_copy (tempArgs, args);
  8194. const int num = CharacterFunctions::vprintf (buf, bufSize - 1, pf, tempArgs);
  8195. va_end (tempArgs);
  8196. #else
  8197. const int num = CharacterFunctions::vprintf (buf, bufSize - 1, pf, args);
  8198. #endif
  8199. if (num > 0)
  8200. {
  8201. createInternal (num);
  8202. memcpy (text->text, buf, (num + 1) * sizeof (tchar));
  8203. break;
  8204. }
  8205. else if (num == 0)
  8206. {
  8207. text = &emptyString;
  8208. emptyString.refCount = safeEmptyStringRefCount;
  8209. break;
  8210. }
  8211. if (buf != stackBuf)
  8212. juce_free (buf);
  8213. bufSize += 256;
  8214. buf = (tchar*) juce_malloc (bufSize * sizeof (tchar));
  8215. }
  8216. while (bufSize < 65536); // this is a sanity check to avoid situations where vprintf repeatedly
  8217. // returns -1 because of an error rather than because it needs more space.
  8218. if (buf != stackBuf)
  8219. juce_free (buf);
  8220. }
  8221. const String String::repeatedString (const tchar* const stringToRepeat,
  8222. int numberOfTimesToRepeat) throw()
  8223. {
  8224. const int len = CharacterFunctions::length (stringToRepeat);
  8225. String result ((int) (len * numberOfTimesToRepeat + 1), (int) 0);
  8226. tchar* n = result.text->text;
  8227. n[0] = 0;
  8228. while (--numberOfTimesToRepeat >= 0)
  8229. {
  8230. CharacterFunctions::append (n, stringToRepeat);
  8231. n += len;
  8232. }
  8233. return result;
  8234. }
  8235. const String String::replaceSection (int index,
  8236. int numCharsToReplace,
  8237. const tchar* const stringToInsert) const throw()
  8238. {
  8239. if (index < 0)
  8240. {
  8241. // a negative index to replace from?
  8242. jassertfalse
  8243. index = 0;
  8244. }
  8245. if (numCharsToReplace < 0)
  8246. {
  8247. // replacing a negative number of characters?
  8248. numCharsToReplace = 0;
  8249. jassertfalse;
  8250. }
  8251. const int len = length();
  8252. if (index + numCharsToReplace > len)
  8253. {
  8254. if (index > len)
  8255. {
  8256. // replacing beyond the end of the string?
  8257. index = len;
  8258. jassertfalse
  8259. }
  8260. numCharsToReplace = len - index;
  8261. }
  8262. const int newStringLen = (stringToInsert != 0) ? CharacterFunctions::length (stringToInsert) : 0;
  8263. const int newTotalLen = len + newStringLen - numCharsToReplace;
  8264. String result (newTotalLen, (int) 0);
  8265. memcpy (result.text->text,
  8266. text->text,
  8267. index * sizeof (tchar));
  8268. if (newStringLen > 0)
  8269. memcpy (result.text->text + index,
  8270. stringToInsert,
  8271. newStringLen * sizeof (tchar));
  8272. const int endStringLen = newTotalLen - (index + newStringLen);
  8273. if (endStringLen > 0)
  8274. memcpy (result.text->text + (index + newStringLen),
  8275. text->text + (index + numCharsToReplace),
  8276. endStringLen * sizeof (tchar));
  8277. result.text->text [newTotalLen] = 0;
  8278. return result;
  8279. }
  8280. const String String::replace (const tchar* const stringToReplace,
  8281. const tchar* const stringToInsert,
  8282. const bool ignoreCase) const throw()
  8283. {
  8284. const int stringToReplaceLen = CharacterFunctions::length (stringToReplace);
  8285. const int stringToInsertLen = CharacterFunctions::length (stringToInsert);
  8286. int i = 0;
  8287. String result (*this);
  8288. while ((i = (ignoreCase ? result.indexOfIgnoreCase (i, stringToReplace)
  8289. : result.indexOf (i, stringToReplace))) >= 0)
  8290. {
  8291. result = result.replaceSection (i, stringToReplaceLen, stringToInsert);
  8292. i += stringToInsertLen;
  8293. }
  8294. return result;
  8295. }
  8296. const String String::replaceCharacter (const tchar charToReplace,
  8297. const tchar charToInsert) const throw()
  8298. {
  8299. const int index = indexOfChar (charToReplace);
  8300. if (index < 0)
  8301. return *this;
  8302. String result (*this);
  8303. result.dupeInternalIfMultiplyReferenced();
  8304. tchar* t = result.text->text + index;
  8305. while (*t != 0)
  8306. {
  8307. if (*t == charToReplace)
  8308. *t = charToInsert;
  8309. ++t;
  8310. }
  8311. return result;
  8312. }
  8313. const String String::replaceCharacters (const String& charactersToReplace,
  8314. const tchar* const charactersToInsertInstead) const throw()
  8315. {
  8316. String result (*this);
  8317. result.dupeInternalIfMultiplyReferenced();
  8318. tchar* t = result.text->text;
  8319. const int len2 = CharacterFunctions::length (charactersToInsertInstead);
  8320. // the two strings passed in are supposed to be the same length!
  8321. jassert (len2 == charactersToReplace.length());
  8322. while (*t != 0)
  8323. {
  8324. const int index = charactersToReplace.indexOfChar (*t);
  8325. if (((unsigned int) index) < (unsigned int) len2)
  8326. *t = charactersToInsertInstead [index];
  8327. ++t;
  8328. }
  8329. return result;
  8330. }
  8331. bool String::startsWith (const tchar* const other) const throw()
  8332. {
  8333. return other != 0
  8334. && CharacterFunctions::compare (text->text, other, CharacterFunctions::length (other)) == 0;
  8335. }
  8336. bool String::startsWithIgnoreCase (const tchar* const other) const throw()
  8337. {
  8338. return other != 0
  8339. && CharacterFunctions::compareIgnoreCase (text->text, other, CharacterFunctions::length (other)) == 0;
  8340. }
  8341. bool String::startsWithChar (const tchar character) const throw()
  8342. {
  8343. return text->text[0] == character;
  8344. }
  8345. bool String::endsWithChar (const tchar character) const throw()
  8346. {
  8347. return text->text[0] != 0
  8348. && text->text [length() - 1] == character;
  8349. }
  8350. bool String::endsWith (const tchar* const other) const throw()
  8351. {
  8352. if (other == 0)
  8353. return false;
  8354. const int thisLen = length();
  8355. const int otherLen = CharacterFunctions::length (other);
  8356. return thisLen >= otherLen
  8357. && CharacterFunctions::compare (text->text + thisLen - otherLen, other) == 0;
  8358. }
  8359. bool String::endsWithIgnoreCase (const tchar* const other) const throw()
  8360. {
  8361. if (other == 0)
  8362. return false;
  8363. const int thisLen = length();
  8364. const int otherLen = CharacterFunctions::length (other);
  8365. return thisLen >= otherLen
  8366. && CharacterFunctions::compareIgnoreCase (text->text + thisLen - otherLen, other) == 0;
  8367. }
  8368. const String String::toUpperCase() const throw()
  8369. {
  8370. String result (*this);
  8371. result.dupeInternalIfMultiplyReferenced();
  8372. CharacterFunctions::toUpperCase (result.text->text);
  8373. return result;
  8374. }
  8375. const String String::toLowerCase() const throw()
  8376. {
  8377. String result (*this);
  8378. result.dupeInternalIfMultiplyReferenced();
  8379. CharacterFunctions::toLowerCase (result.text->text);
  8380. return result;
  8381. }
  8382. tchar& String::operator[] (const int index) throw()
  8383. {
  8384. jassert (((unsigned int) index) <= (unsigned int) length());
  8385. dupeInternalIfMultiplyReferenced();
  8386. return text->text [index];
  8387. }
  8388. tchar String::getLastCharacter() const throw()
  8389. {
  8390. return (isEmpty()) ? ((tchar) 0)
  8391. : text->text [CharacterFunctions::length (text->text) - 1];
  8392. }
  8393. const String String::substring (int start, int end) const throw()
  8394. {
  8395. if (start < 0)
  8396. start = 0;
  8397. else if (end <= start)
  8398. return empty;
  8399. int len = 0;
  8400. const tchar* const t = text->text;
  8401. while (len <= end && t [len] != 0)
  8402. ++len;
  8403. if (end >= len)
  8404. {
  8405. if (start == 0)
  8406. return *this;
  8407. end = len;
  8408. }
  8409. return String (text->text + start,
  8410. end - start);
  8411. }
  8412. const String String::substring (const int start) const throw()
  8413. {
  8414. if (start <= 0)
  8415. return *this;
  8416. const int len = CharacterFunctions::length (text->text);
  8417. if (start >= len)
  8418. return empty;
  8419. else
  8420. return String (text->text + start,
  8421. len - start);
  8422. }
  8423. const String String::dropLastCharacters (const int numberToDrop) const throw()
  8424. {
  8425. return String (text->text,
  8426. jmax (0, CharacterFunctions::length (text->text) - numberToDrop));
  8427. }
  8428. const String String::fromFirstOccurrenceOf (const tchar* const sub,
  8429. const bool includeSubString,
  8430. const bool ignoreCase) const throw()
  8431. {
  8432. const int i = ignoreCase ? indexOf (sub)
  8433. : indexOfIgnoreCase (sub);
  8434. if (i < 0)
  8435. return empty;
  8436. else
  8437. return substring ((includeSubString) ? i : i + CharacterFunctions::length (sub));
  8438. }
  8439. const String String::fromLastOccurrenceOf (const tchar* const sub,
  8440. const bool includeSubString,
  8441. const bool ignoreCase) const throw()
  8442. {
  8443. const int i = ignoreCase ? lastIndexOf (sub)
  8444. : lastIndexOfIgnoreCase (sub);
  8445. if (i < 0)
  8446. return *this;
  8447. else
  8448. return substring ((includeSubString) ? i : i + CharacterFunctions::length (sub));
  8449. }
  8450. const String String::upToFirstOccurrenceOf (const tchar* const sub,
  8451. const bool includeSubString,
  8452. const bool ignoreCase) const throw()
  8453. {
  8454. const int i = ignoreCase ? indexOfIgnoreCase (sub)
  8455. : indexOf (sub);
  8456. if (i < 0)
  8457. return *this;
  8458. else
  8459. return substring (0, (includeSubString) ? i + CharacterFunctions::length (sub) : i);
  8460. }
  8461. const String String::upToLastOccurrenceOf (const tchar* const sub,
  8462. const bool includeSubString,
  8463. const bool ignoreCase) const throw()
  8464. {
  8465. const int i = ignoreCase ? lastIndexOfIgnoreCase (sub)
  8466. : lastIndexOf (sub);
  8467. if (i < 0)
  8468. return *this;
  8469. return substring (0, (includeSubString) ? i + CharacterFunctions::length (sub) : i);
  8470. }
  8471. bool String::isQuotedString() const throw()
  8472. {
  8473. const String trimmed (trimStart());
  8474. return trimmed[0] == T('"')
  8475. || trimmed[0] == T('\'');
  8476. }
  8477. const String String::unquoted() const throw()
  8478. {
  8479. String s (*this);
  8480. if (s[0] == T('"') || s[0] == T('\''))
  8481. s = s.substring (1);
  8482. const int lastCharIndex = s.length() - 1;
  8483. if (lastCharIndex >= 0
  8484. && (s [lastCharIndex] == T('"') || s[lastCharIndex] == T('\'')))
  8485. s [lastCharIndex] = 0;
  8486. return s;
  8487. }
  8488. const String String::quoted (const tchar quoteCharacter) const throw()
  8489. {
  8490. if (isEmpty())
  8491. return charToString (quoteCharacter) + quoteCharacter;
  8492. String t (*this);
  8493. if (! t.startsWithChar (quoteCharacter))
  8494. t = charToString (quoteCharacter) + t;
  8495. if (! t.endsWithChar (quoteCharacter))
  8496. t += quoteCharacter;
  8497. return t;
  8498. }
  8499. const String String::trim() const throw()
  8500. {
  8501. if (isEmpty())
  8502. return empty;
  8503. int start = 0;
  8504. while (CharacterFunctions::isWhitespace (text->text [start]))
  8505. ++start;
  8506. const int len = CharacterFunctions::length (text->text);
  8507. int end = len - 1;
  8508. while ((end >= start) && CharacterFunctions::isWhitespace (text->text [end]))
  8509. --end;
  8510. ++end;
  8511. if (end <= start)
  8512. return empty;
  8513. else if (start > 0 || end < len)
  8514. return String (text->text + start, end - start);
  8515. else
  8516. return *this;
  8517. }
  8518. const String String::trimStart() const throw()
  8519. {
  8520. if (isEmpty())
  8521. return empty;
  8522. const tchar* t = text->text;
  8523. while (CharacterFunctions::isWhitespace (*t))
  8524. ++t;
  8525. if (t == text->text)
  8526. return *this;
  8527. else
  8528. return String (t);
  8529. }
  8530. const String String::trimEnd() const throw()
  8531. {
  8532. if (isEmpty())
  8533. return empty;
  8534. const tchar* endT = text->text + (CharacterFunctions::length (text->text) - 1);
  8535. while ((endT >= text->text) && CharacterFunctions::isWhitespace (*endT))
  8536. --endT;
  8537. return String (text->text, (int) (++endT - text->text));
  8538. }
  8539. const String String::retainCharacters (const tchar* const charactersToRetain) const throw()
  8540. {
  8541. jassert (charactersToRetain != 0);
  8542. if (isEmpty())
  8543. return empty;
  8544. String result (text->allocatedNumChars, (int) 0);
  8545. tchar* dst = result.text->text;
  8546. const tchar* src = text->text;
  8547. while (*src != 0)
  8548. {
  8549. if (CharacterFunctions::indexOfCharFast (charactersToRetain, *src) >= 0)
  8550. *dst++ = *src;
  8551. ++src;
  8552. }
  8553. *dst = 0;
  8554. return result;
  8555. }
  8556. const String String::removeCharacters (const tchar* const charactersToRemove) const throw()
  8557. {
  8558. jassert (charactersToRemove != 0);
  8559. if (isEmpty())
  8560. return empty;
  8561. String result (text->allocatedNumChars, (int) 0);
  8562. tchar* dst = result.text->text;
  8563. const tchar* src = text->text;
  8564. while (*src != 0)
  8565. {
  8566. if (CharacterFunctions::indexOfCharFast (charactersToRemove, *src) < 0)
  8567. *dst++ = *src;
  8568. ++src;
  8569. }
  8570. *dst = 0;
  8571. return result;
  8572. }
  8573. const String String::initialSectionContainingOnly (const tchar* const permittedCharacters) const throw()
  8574. {
  8575. return substring (0, CharacterFunctions::getIntialSectionContainingOnly (text->text, permittedCharacters));
  8576. }
  8577. const String String::initialSectionNotContaining (const tchar* const charactersToStopAt) const throw()
  8578. {
  8579. jassert (charactersToStopAt != 0);
  8580. const tchar* const t = text->text;
  8581. int i = 0;
  8582. while (t[i] != 0)
  8583. {
  8584. if (CharacterFunctions::indexOfCharFast (charactersToStopAt, t[i]) >= 0)
  8585. return String (text->text, i);
  8586. ++i;
  8587. }
  8588. return empty;
  8589. }
  8590. bool String::containsOnly (const tchar* const chars) const throw()
  8591. {
  8592. jassert (chars != 0);
  8593. const tchar* t = text->text;
  8594. while (*t != 0)
  8595. if (CharacterFunctions::indexOfCharFast (chars, *t++) < 0)
  8596. return false;
  8597. return true;
  8598. }
  8599. bool String::containsAnyOf (const tchar* const chars) const throw()
  8600. {
  8601. jassert (chars != 0);
  8602. const tchar* t = text->text;
  8603. while (*t != 0)
  8604. if (CharacterFunctions::indexOfCharFast (chars, *t++) >= 0)
  8605. return true;
  8606. return false;
  8607. }
  8608. int String::getIntValue() const throw()
  8609. {
  8610. return CharacterFunctions::getIntValue (text->text);
  8611. }
  8612. int String::getTrailingIntValue() const throw()
  8613. {
  8614. int n = 0;
  8615. int mult = 1;
  8616. const tchar* t = text->text + length();
  8617. while (--t >= text->text)
  8618. {
  8619. const tchar c = *t;
  8620. if (! CharacterFunctions::isDigit (c))
  8621. {
  8622. if (c == T('-'))
  8623. n = -n;
  8624. break;
  8625. }
  8626. n += mult * (c - T('0'));
  8627. mult *= 10;
  8628. }
  8629. return n;
  8630. }
  8631. int64 String::getLargeIntValue() const throw()
  8632. {
  8633. return CharacterFunctions::getInt64Value (text->text);
  8634. }
  8635. float String::getFloatValue() const throw()
  8636. {
  8637. return (float) CharacterFunctions::getDoubleValue (text->text);
  8638. }
  8639. double String::getDoubleValue() const throw()
  8640. {
  8641. return CharacterFunctions::getDoubleValue (text->text);
  8642. }
  8643. static const tchar* const hexDigits = T("0123456789abcdef");
  8644. const String String::toHexString (const int number) throw()
  8645. {
  8646. tchar buffer[32];
  8647. tchar* const end = buffer + 32;
  8648. tchar* t = end;
  8649. *--t = 0;
  8650. unsigned int v = (unsigned int) number;
  8651. do
  8652. {
  8653. *--t = hexDigits [v & 15];
  8654. v >>= 4;
  8655. } while (v != 0);
  8656. return String (t, (int) (((char*) end) - (char*) t) - 1);
  8657. }
  8658. const String String::toHexString (const int64 number) throw()
  8659. {
  8660. tchar buffer[32];
  8661. tchar* const end = buffer + 32;
  8662. tchar* t = end;
  8663. *--t = 0;
  8664. uint64 v = (uint64) number;
  8665. do
  8666. {
  8667. *--t = hexDigits [(int) (v & 15)];
  8668. v >>= 4;
  8669. } while (v != 0);
  8670. return String (t, (int) (((char*) end) - (char*) t));
  8671. }
  8672. const String String::toHexString (const short number) throw()
  8673. {
  8674. return toHexString ((int) (unsigned short) number);
  8675. }
  8676. const String String::toHexString (const unsigned char* data,
  8677. const int size,
  8678. const int groupSize) throw()
  8679. {
  8680. if (size <= 0)
  8681. return empty;
  8682. int numChars = (size * 2) + 2;
  8683. if (groupSize > 0)
  8684. numChars += size / groupSize;
  8685. String s (numChars, (int) 0);
  8686. tchar* d = s.text->text;
  8687. for (int i = 0; i < size; ++i)
  8688. {
  8689. *d++ = hexDigits [(*data) >> 4];
  8690. *d++ = hexDigits [(*data) & 0xf];
  8691. ++data;
  8692. if (groupSize > 0 && (i % groupSize) == 0)
  8693. *d++ = T(' ');
  8694. }
  8695. if (groupSize > 0)
  8696. --d;
  8697. *d = 0;
  8698. return s;
  8699. }
  8700. int String::getHexValue32() const throw()
  8701. {
  8702. int result = 0;
  8703. const tchar* c = text->text;
  8704. for (;;)
  8705. {
  8706. const int hexValue = CharacterFunctions::getHexDigitValue (*c);
  8707. if (hexValue >= 0)
  8708. result = (result << 4) | hexValue;
  8709. else if (*c == 0)
  8710. break;
  8711. ++c;
  8712. }
  8713. return result;
  8714. }
  8715. int64 String::getHexValue64() const throw()
  8716. {
  8717. int64 result = 0;
  8718. const tchar* c = text->text;
  8719. for (;;)
  8720. {
  8721. const int hexValue = CharacterFunctions::getHexDigitValue (*c);
  8722. if (hexValue >= 0)
  8723. result = (result << 4) | hexValue;
  8724. else if (*c == 0)
  8725. break;
  8726. ++c;
  8727. }
  8728. return result;
  8729. }
  8730. const String String::createStringFromData (const void* const data_,
  8731. const int size) throw()
  8732. {
  8733. const char* const data = (const char*) data_;
  8734. if (size <= 0 || data == 0)
  8735. {
  8736. return empty;
  8737. }
  8738. else if (size < 2)
  8739. {
  8740. return charToString (data[0]);
  8741. }
  8742. else if ((data[0] == (char)-2 && data[1] == (char)-1)
  8743. || (data[0] == (char)-1 && data[1] == (char)-2))
  8744. {
  8745. // assume it's 16-bit unicode
  8746. const bool bigEndian = (data[0] == (char)-2);
  8747. const int numChars = size / 2 - 1;
  8748. String result;
  8749. result.preallocateStorage (numChars + 2);
  8750. const uint16* const src = (const uint16*) (data + 2);
  8751. tchar* const dst = const_cast <tchar*> ((const tchar*) result);
  8752. if (bigEndian)
  8753. {
  8754. for (int i = 0; i < numChars; ++i)
  8755. dst[i] = (tchar) swapIfLittleEndian (src[i]);
  8756. }
  8757. else
  8758. {
  8759. for (int i = 0; i < numChars; ++i)
  8760. dst[i] = (tchar) swapIfBigEndian (src[i]);
  8761. }
  8762. dst [numChars] = 0;
  8763. return result;
  8764. }
  8765. else
  8766. {
  8767. #if JUCE_STRINGS_ARE_UNICODE && JUCE_LINUX
  8768. // (workaround for strange behaviour of mbstowcs)
  8769. int i;
  8770. for (i = 0; i < size; ++i)
  8771. if (data[i] == 0)
  8772. break;
  8773. String result;
  8774. result.preallocateStorage (i + 1);
  8775. tchar* const dst = const_cast <tchar*> ((const tchar*) result);
  8776. for (int j = 0; j < i; ++j)
  8777. dst[j] = (juce_wchar) (unsigned char) data[j];
  8778. dst[i] = 0;
  8779. return result;
  8780. #else
  8781. return String (data, size);
  8782. #endif
  8783. }
  8784. }
  8785. const char* String::toUTF8() const throw()
  8786. {
  8787. if (isEmpty())
  8788. {
  8789. return (const char*) emptyCharString;
  8790. }
  8791. else
  8792. {
  8793. String* const mutableThis = const_cast <String*> (this);
  8794. mutableThis->dupeInternalIfMultiplyReferenced();
  8795. const int currentLen = CharacterFunctions::length (text->text) + 1;
  8796. const int utf8BytesNeeded = copyToUTF8 (0);
  8797. mutableThis->text = (InternalRefCountedStringHolder*)
  8798. juce_realloc (text, sizeof (InternalRefCountedStringHolder)
  8799. + (currentLen * sizeof (juce_wchar) + utf8BytesNeeded));
  8800. char* const otherCopy = (char*) (text->text + currentLen);
  8801. copyToUTF8 ((uint8*) otherCopy);
  8802. return otherCopy;
  8803. }
  8804. }
  8805. int String::copyToUTF8 (uint8* const buffer) const throw()
  8806. {
  8807. #if JUCE_STRINGS_ARE_UNICODE
  8808. int num = 0, index = 0;
  8809. for (;;)
  8810. {
  8811. const uint32 c = (uint32) text->text [index++];
  8812. if (c >= 0x80)
  8813. {
  8814. int numExtraBytes = 1;
  8815. if (c >= 0x800)
  8816. {
  8817. ++numExtraBytes;
  8818. if (c >= 0x10000)
  8819. {
  8820. ++numExtraBytes;
  8821. if (c >= 0x200000)
  8822. {
  8823. ++numExtraBytes;
  8824. if (c >= 0x4000000)
  8825. ++numExtraBytes;
  8826. }
  8827. }
  8828. }
  8829. if (buffer != 0)
  8830. {
  8831. buffer [num++] = (uint8) ((0xff << (7 - numExtraBytes)) | (c >> (numExtraBytes * 6)));
  8832. while (--numExtraBytes >= 0)
  8833. buffer [num++] = (uint8) (0x80 | (0x3f & (c >> (numExtraBytes * 6))));
  8834. }
  8835. else
  8836. {
  8837. num += numExtraBytes + 1;
  8838. }
  8839. }
  8840. else
  8841. {
  8842. if (buffer != 0)
  8843. buffer [num] = (uint8) c;
  8844. ++num;
  8845. }
  8846. if (c == 0)
  8847. break;
  8848. }
  8849. return num;
  8850. #else
  8851. const int numBytes = length() + 1;
  8852. if (buffer != 0)
  8853. copyToBuffer ((char*) buffer, numBytes);
  8854. return numBytes;
  8855. #endif
  8856. }
  8857. const String String::fromUTF8 (const uint8* const buffer, int bufferSizeBytes) throw()
  8858. {
  8859. if (buffer == 0)
  8860. return empty;
  8861. if (bufferSizeBytes < 0)
  8862. bufferSizeBytes = INT_MAX;
  8863. int numBytes;
  8864. for (numBytes = 0; numBytes < bufferSizeBytes; ++numBytes)
  8865. if (buffer [numBytes] == 0)
  8866. break;
  8867. String result (numBytes + 1, 0);
  8868. tchar* dest = result.text->text;
  8869. int i = 0;
  8870. while (i < numBytes)
  8871. {
  8872. const uint8 c = buffer [i++];
  8873. if ((c & 0x80) != 0)
  8874. {
  8875. int mask = 0x7f;
  8876. int bit = 0x40;
  8877. int numExtraValues = 0;
  8878. while (bit != 0 && (c & bit) != 0)
  8879. {
  8880. bit >>= 1;
  8881. mask >>= 1;
  8882. ++numExtraValues;
  8883. }
  8884. int n = (c & mask);
  8885. while (--numExtraValues >= 0 && i < bufferSizeBytes)
  8886. {
  8887. const uint8 c = buffer[i];
  8888. if ((c & 0xc0) != 0x80)
  8889. break;
  8890. n <<= 6;
  8891. n |= (c & 0x3f);
  8892. ++i;
  8893. }
  8894. *dest++ = (tchar) n;
  8895. }
  8896. else
  8897. {
  8898. *dest++ = (tchar) c;
  8899. }
  8900. }
  8901. *dest = 0;
  8902. return result;
  8903. }
  8904. END_JUCE_NAMESPACE
  8905. /********* End of inlined file: juce_String.cpp *********/
  8906. /********* Start of inlined file: juce_StringArray.cpp *********/
  8907. BEGIN_JUCE_NAMESPACE
  8908. StringArray::StringArray() throw()
  8909. {
  8910. }
  8911. StringArray::StringArray (const StringArray& other) throw()
  8912. {
  8913. addArray (other);
  8914. }
  8915. StringArray::StringArray (const juce_wchar** 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 char** const strings,
  8922. const int numberOfStrings) throw()
  8923. {
  8924. for (int i = 0; i < numberOfStrings; ++i)
  8925. add (strings [i]);
  8926. }
  8927. StringArray::StringArray (const juce_wchar** const strings) throw()
  8928. {
  8929. int i = 0;
  8930. while (strings[i] != 0)
  8931. add (strings [i++]);
  8932. }
  8933. StringArray::StringArray (const char** const strings) throw()
  8934. {
  8935. int i = 0;
  8936. while (strings[i] != 0)
  8937. add (strings [i++]);
  8938. }
  8939. const StringArray& StringArray::operator= (const StringArray& other) throw()
  8940. {
  8941. if (this != &other)
  8942. {
  8943. clear();
  8944. addArray (other);
  8945. }
  8946. return *this;
  8947. }
  8948. StringArray::~StringArray() throw()
  8949. {
  8950. clear();
  8951. }
  8952. bool StringArray::operator== (const StringArray& other) const throw()
  8953. {
  8954. if (other.size() != size())
  8955. return false;
  8956. for (int i = size(); --i >= 0;)
  8957. {
  8958. if (*(String*) other.strings.getUnchecked(i)
  8959. != *(String*) strings.getUnchecked(i))
  8960. {
  8961. return false;
  8962. }
  8963. }
  8964. return true;
  8965. }
  8966. bool StringArray::operator!= (const StringArray& other) const throw()
  8967. {
  8968. return ! operator== (other);
  8969. }
  8970. void StringArray::clear() throw()
  8971. {
  8972. for (int i = size(); --i >= 0;)
  8973. {
  8974. String* const s = (String*) strings.getUnchecked(i);
  8975. delete s;
  8976. }
  8977. strings.clear();
  8978. }
  8979. const String& StringArray::operator[] (const int index) const throw()
  8980. {
  8981. if (((unsigned int) index) < (unsigned int) strings.size())
  8982. return *(const String*) (strings.getUnchecked (index));
  8983. return String::empty;
  8984. }
  8985. void StringArray::add (const String& newString) throw()
  8986. {
  8987. strings.add (new String (newString));
  8988. }
  8989. void StringArray::insert (const int index,
  8990. const String& newString) throw()
  8991. {
  8992. strings.insert (index, new String (newString));
  8993. }
  8994. void StringArray::addIfNotAlreadyThere (const String& newString,
  8995. const bool ignoreCase) throw()
  8996. {
  8997. if (! contains (newString, ignoreCase))
  8998. add (newString);
  8999. }
  9000. void StringArray::addArray (const StringArray& otherArray,
  9001. int startIndex,
  9002. int numElementsToAdd) throw()
  9003. {
  9004. if (startIndex < 0)
  9005. {
  9006. jassertfalse
  9007. startIndex = 0;
  9008. }
  9009. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > otherArray.size())
  9010. numElementsToAdd = otherArray.size() - startIndex;
  9011. while (--numElementsToAdd >= 0)
  9012. strings.add (new String (*(const String*) otherArray.strings.getUnchecked (startIndex++)));
  9013. }
  9014. void StringArray::set (const int index,
  9015. const String& newString) throw()
  9016. {
  9017. String* const s = (String*) strings [index];
  9018. if (s != 0)
  9019. {
  9020. *s = newString;
  9021. }
  9022. else if (index >= 0)
  9023. {
  9024. add (newString);
  9025. }
  9026. }
  9027. bool StringArray::contains (const String& stringToLookFor,
  9028. const bool ignoreCase) const throw()
  9029. {
  9030. if (ignoreCase)
  9031. {
  9032. for (int i = size(); --i >= 0;)
  9033. if (stringToLookFor.equalsIgnoreCase (*(const String*)(strings.getUnchecked(i))))
  9034. return true;
  9035. }
  9036. else
  9037. {
  9038. for (int i = size(); --i >= 0;)
  9039. if (stringToLookFor == *(const String*)(strings.getUnchecked(i)))
  9040. return true;
  9041. }
  9042. return false;
  9043. }
  9044. int StringArray::indexOf (const String& stringToLookFor,
  9045. const bool ignoreCase,
  9046. int i) const throw()
  9047. {
  9048. if (i < 0)
  9049. i = 0;
  9050. const int numElements = size();
  9051. if (ignoreCase)
  9052. {
  9053. while (i < numElements)
  9054. {
  9055. if (stringToLookFor.equalsIgnoreCase (*(const String*) strings.getUnchecked (i)))
  9056. return i;
  9057. ++i;
  9058. }
  9059. }
  9060. else
  9061. {
  9062. while (i < numElements)
  9063. {
  9064. if (stringToLookFor == *(const String*) strings.getUnchecked (i))
  9065. return i;
  9066. ++i;
  9067. }
  9068. }
  9069. return -1;
  9070. }
  9071. void StringArray::remove (const int index) throw()
  9072. {
  9073. String* const s = (String*) strings [index];
  9074. if (s != 0)
  9075. {
  9076. strings.remove (index);
  9077. delete s;
  9078. }
  9079. }
  9080. void StringArray::removeString (const String& stringToRemove,
  9081. const bool ignoreCase) throw()
  9082. {
  9083. if (ignoreCase)
  9084. {
  9085. for (int i = size(); --i >= 0;)
  9086. if (stringToRemove.equalsIgnoreCase (*(const String*) strings.getUnchecked (i)))
  9087. remove (i);
  9088. }
  9089. else
  9090. {
  9091. for (int i = size(); --i >= 0;)
  9092. if (stringToRemove == *(const String*) strings.getUnchecked (i))
  9093. remove (i);
  9094. }
  9095. }
  9096. void StringArray::removeEmptyStrings (const bool removeWhitespaceStrings) throw()
  9097. {
  9098. if (removeWhitespaceStrings)
  9099. {
  9100. for (int i = size(); --i >= 0;)
  9101. if (((const String*) strings.getUnchecked(i))->trim().isEmpty())
  9102. remove (i);
  9103. }
  9104. else
  9105. {
  9106. for (int i = size(); --i >= 0;)
  9107. if (((const String*) strings.getUnchecked(i))->isEmpty())
  9108. remove (i);
  9109. }
  9110. }
  9111. void StringArray::trim() throw()
  9112. {
  9113. for (int i = size(); --i >= 0;)
  9114. {
  9115. String& s = *(String*) strings.getUnchecked(i);
  9116. s = s.trim();
  9117. }
  9118. }
  9119. class InternalStringArrayComparator
  9120. {
  9121. public:
  9122. static int compareElements (void* const first, void* const second) throw()
  9123. {
  9124. return ((const String*) first)->compare (*(const String*) second);
  9125. }
  9126. };
  9127. class InsensitiveInternalStringArrayComparator
  9128. {
  9129. public:
  9130. static int compareElements (void* const first, void* const second) throw()
  9131. {
  9132. return ((const String*) first)->compareIgnoreCase (*(const String*) second);
  9133. }
  9134. };
  9135. void StringArray::sort (const bool ignoreCase) throw()
  9136. {
  9137. if (ignoreCase)
  9138. {
  9139. InsensitiveInternalStringArrayComparator comp;
  9140. strings.sort (comp);
  9141. }
  9142. else
  9143. {
  9144. InternalStringArrayComparator comp;
  9145. strings.sort (comp);
  9146. }
  9147. }
  9148. void StringArray::move (const int currentIndex, int newIndex) throw()
  9149. {
  9150. strings.move (currentIndex, newIndex);
  9151. }
  9152. const String StringArray::joinIntoString (const String& separator,
  9153. int start,
  9154. int numberToJoin) const throw()
  9155. {
  9156. const int last = (numberToJoin < 0) ? size()
  9157. : jmin (size(), start + numberToJoin);
  9158. if (start < 0)
  9159. start = 0;
  9160. if (start >= last)
  9161. return String::empty;
  9162. if (start == last - 1)
  9163. return *(const String*) strings.getUnchecked (start);
  9164. const int separatorLen = separator.length();
  9165. int charsNeeded = separatorLen * (last - start - 1);
  9166. for (int i = start; i < last; ++i)
  9167. charsNeeded += ((const String*) strings.getUnchecked(i))->length();
  9168. String result;
  9169. result.preallocateStorage (charsNeeded);
  9170. tchar* dest = (tchar*) (const tchar*) result;
  9171. while (start < last)
  9172. {
  9173. const String& s = *(const String*) strings.getUnchecked (start);
  9174. const int len = s.length();
  9175. if (len > 0)
  9176. {
  9177. s.copyToBuffer (dest, len);
  9178. dest += len;
  9179. }
  9180. if (++start < last && separatorLen > 0)
  9181. {
  9182. separator.copyToBuffer (dest, separatorLen);
  9183. dest += separatorLen;
  9184. }
  9185. }
  9186. *dest = 0;
  9187. return result;
  9188. }
  9189. int StringArray::addTokens (const tchar* const text,
  9190. const bool preserveQuotedStrings) throw()
  9191. {
  9192. return addTokens (text,
  9193. T(" \n\r\t"),
  9194. preserveQuotedStrings ? T("\"") : 0);
  9195. }
  9196. int StringArray::addTokens (const tchar* const text,
  9197. const tchar* breakCharacters,
  9198. const tchar* quoteCharacters) throw()
  9199. {
  9200. int num = 0;
  9201. if (text != 0 && *text != 0)
  9202. {
  9203. if (breakCharacters == 0)
  9204. breakCharacters = T("");
  9205. if (quoteCharacters == 0)
  9206. quoteCharacters = T("");
  9207. bool insideQuotes = false;
  9208. tchar currentQuoteChar = 0;
  9209. int i = 0;
  9210. int tokenStart = 0;
  9211. for (;;)
  9212. {
  9213. const tchar c = text[i];
  9214. bool isBreak = (c == 0);
  9215. if (! (insideQuotes || isBreak))
  9216. {
  9217. const tchar* b = breakCharacters;
  9218. while (*b != 0)
  9219. {
  9220. if (*b++ == c)
  9221. {
  9222. isBreak = true;
  9223. break;
  9224. }
  9225. }
  9226. }
  9227. if (! isBreak)
  9228. {
  9229. bool isQuote = false;
  9230. const tchar* q = quoteCharacters;
  9231. while (*q != 0)
  9232. {
  9233. if (*q++ == c)
  9234. {
  9235. isQuote = true;
  9236. break;
  9237. }
  9238. }
  9239. if (isQuote)
  9240. {
  9241. if (insideQuotes)
  9242. {
  9243. // only break out of quotes-mode if we find a matching quote to the
  9244. // one that we opened with..
  9245. if (currentQuoteChar == c)
  9246. insideQuotes = false;
  9247. }
  9248. else
  9249. {
  9250. insideQuotes = true;
  9251. currentQuoteChar = c;
  9252. }
  9253. }
  9254. }
  9255. else
  9256. {
  9257. add (String (text + tokenStart, i - tokenStart));
  9258. ++num;
  9259. tokenStart = i + 1;
  9260. }
  9261. if (c == 0)
  9262. break;
  9263. ++i;
  9264. }
  9265. }
  9266. return num;
  9267. }
  9268. int StringArray::addLines (const tchar* text) throw()
  9269. {
  9270. int numLines = 0;
  9271. if (text != 0)
  9272. {
  9273. while (*text != 0)
  9274. {
  9275. const tchar* const startOfLine = text;
  9276. while (*text != 0)
  9277. {
  9278. if (*text == T('\r'))
  9279. {
  9280. ++text;
  9281. if (*text == T('\n'))
  9282. ++text;
  9283. break;
  9284. }
  9285. if (*text == T('\n'))
  9286. {
  9287. ++text;
  9288. break;
  9289. }
  9290. ++text;
  9291. }
  9292. const tchar* endOfLine = text;
  9293. if (endOfLine > startOfLine && (*(endOfLine - 1) == T('\r') || *(endOfLine - 1) == T('\n')))
  9294. --endOfLine;
  9295. if (endOfLine > startOfLine && (*(endOfLine - 1) == T('\r') || *(endOfLine - 1) == T('\n')))
  9296. --endOfLine;
  9297. add (String (startOfLine, jmax (0, (int) (endOfLine - startOfLine))));
  9298. ++numLines;
  9299. }
  9300. }
  9301. return numLines;
  9302. }
  9303. void StringArray::removeDuplicates (const bool ignoreCase) throw()
  9304. {
  9305. for (int i = 0; i < size() - 1; ++i)
  9306. {
  9307. const String& s = *(String*) strings.getUnchecked(i);
  9308. int nextIndex = i + 1;
  9309. for (;;)
  9310. {
  9311. nextIndex = indexOf (s, ignoreCase, nextIndex);
  9312. if (nextIndex < 0)
  9313. break;
  9314. remove (nextIndex);
  9315. }
  9316. }
  9317. }
  9318. void StringArray::appendNumbersToDuplicates (const bool ignoreCase,
  9319. const bool appendNumberToFirstInstance,
  9320. const tchar* const preNumberString,
  9321. const tchar* const postNumberString) throw()
  9322. {
  9323. for (int i = 0; i < size() - 1; ++i)
  9324. {
  9325. String& s = *(String*) strings.getUnchecked(i);
  9326. int nextIndex = indexOf (s, ignoreCase, i + 1);
  9327. if (nextIndex >= 0)
  9328. {
  9329. const String original (s);
  9330. int number = 0;
  9331. if (appendNumberToFirstInstance)
  9332. s = original + preNumberString + String (++number) + postNumberString;
  9333. else
  9334. ++number;
  9335. while (nextIndex >= 0)
  9336. {
  9337. set (nextIndex, (*this)[nextIndex] + preNumberString + String (++number) + postNumberString);
  9338. nextIndex = indexOf (original, ignoreCase, nextIndex + 1);
  9339. }
  9340. }
  9341. }
  9342. }
  9343. void StringArray::minimiseStorageOverheads() throw()
  9344. {
  9345. strings.minimiseStorageOverheads();
  9346. }
  9347. END_JUCE_NAMESPACE
  9348. /********* End of inlined file: juce_StringArray.cpp *********/
  9349. /********* Start of inlined file: juce_StringPairArray.cpp *********/
  9350. BEGIN_JUCE_NAMESPACE
  9351. StringPairArray::StringPairArray (const bool ignoreCase_) throw()
  9352. : ignoreCase (ignoreCase_)
  9353. {
  9354. }
  9355. StringPairArray::StringPairArray (const StringPairArray& other) throw()
  9356. : keys (other.keys),
  9357. values (other.values),
  9358. ignoreCase (other.ignoreCase)
  9359. {
  9360. }
  9361. StringPairArray::~StringPairArray() throw()
  9362. {
  9363. }
  9364. const StringPairArray& StringPairArray::operator= (const StringPairArray& other) throw()
  9365. {
  9366. keys = other.keys;
  9367. values = other.values;
  9368. return *this;
  9369. }
  9370. bool StringPairArray::operator== (const StringPairArray& other) const throw()
  9371. {
  9372. for (int i = keys.size(); --i >= 0;)
  9373. if (other [keys[i]] != values[i])
  9374. return false;
  9375. return true;
  9376. }
  9377. bool StringPairArray::operator!= (const StringPairArray& other) const throw()
  9378. {
  9379. return ! operator== (other);
  9380. }
  9381. const String& StringPairArray::operator[] (const String& key) const throw()
  9382. {
  9383. return values [keys.indexOf (key, ignoreCase)];
  9384. }
  9385. const String StringPairArray::getValue (const String& key, const String& defaultReturnValue) const
  9386. {
  9387. const int i = keys.indexOf (key, ignoreCase);
  9388. if (i >= 0)
  9389. return values[i];
  9390. return defaultReturnValue;
  9391. }
  9392. void StringPairArray::set (const String& key,
  9393. const String& value) throw()
  9394. {
  9395. const int i = keys.indexOf (key, ignoreCase);
  9396. if (i >= 0)
  9397. {
  9398. values.set (i, value);
  9399. }
  9400. else
  9401. {
  9402. keys.add (key);
  9403. values.add (value);
  9404. }
  9405. }
  9406. void StringPairArray::addArray (const StringPairArray& other)
  9407. {
  9408. for (int i = 0; i < other.size(); ++i)
  9409. set (other.keys[i], other.values[i]);
  9410. }
  9411. void StringPairArray::clear() throw()
  9412. {
  9413. keys.clear();
  9414. values.clear();
  9415. }
  9416. void StringPairArray::remove (const String& key) throw()
  9417. {
  9418. remove (keys.indexOf (key, ignoreCase));
  9419. }
  9420. void StringPairArray::remove (const int index) throw()
  9421. {
  9422. keys.remove (index);
  9423. values.remove (index);
  9424. }
  9425. void StringPairArray::minimiseStorageOverheads() throw()
  9426. {
  9427. keys.minimiseStorageOverheads();
  9428. values.minimiseStorageOverheads();
  9429. }
  9430. END_JUCE_NAMESPACE
  9431. /********* End of inlined file: juce_StringPairArray.cpp *********/
  9432. /********* Start of inlined file: juce_XmlDocument.cpp *********/
  9433. BEGIN_JUCE_NAMESPACE
  9434. static bool isXmlIdentifierChar_Slow (const tchar c) throw()
  9435. {
  9436. return CharacterFunctions::isLetterOrDigit (c)
  9437. || c == T('_')
  9438. || c == T('-')
  9439. || c == T(':')
  9440. || c == T('.');
  9441. }
  9442. #define isXmlIdentifierChar(c) \
  9443. ((c > 0 && c <= 127) ? identifierLookupTable [(int) c] : isXmlIdentifierChar_Slow (c))
  9444. XmlDocument::XmlDocument (const String& documentText) throw()
  9445. : originalText (documentText),
  9446. inputSource (0)
  9447. {
  9448. }
  9449. XmlDocument::XmlDocument (const File& file)
  9450. {
  9451. inputSource = new FileInputSource (file);
  9452. }
  9453. XmlDocument::~XmlDocument() throw()
  9454. {
  9455. delete inputSource;
  9456. }
  9457. void XmlDocument::setInputSource (InputSource* const newSource) throw()
  9458. {
  9459. if (inputSource != newSource)
  9460. {
  9461. delete inputSource;
  9462. inputSource = newSource;
  9463. }
  9464. }
  9465. XmlElement* XmlDocument::getDocumentElement (const bool onlyReadOuterDocumentElement)
  9466. {
  9467. String textToParse (originalText);
  9468. if (textToParse.isEmpty() && inputSource != 0)
  9469. {
  9470. InputStream* const in = inputSource->createInputStream();
  9471. if (in != 0)
  9472. {
  9473. MemoryBlock data;
  9474. in->readIntoMemoryBlock (data, onlyReadOuterDocumentElement ? 8192 : -1);
  9475. delete in;
  9476. if (data.getSize() >= 2
  9477. && ((data[0] == (char)-2 && data[1] == (char)-1)
  9478. || (data[0] == (char)-1 && data[1] == (char)-2)))
  9479. {
  9480. textToParse = String::createStringFromData ((const char*) data.getData(), data.getSize());
  9481. }
  9482. else
  9483. {
  9484. textToParse = String::fromUTF8 ((const uint8*) data.getData(), data.getSize());
  9485. }
  9486. if (! onlyReadOuterDocumentElement)
  9487. originalText = textToParse;
  9488. }
  9489. }
  9490. input = textToParse;
  9491. lastError = String::empty;
  9492. errorOccurred = false;
  9493. outOfData = false;
  9494. needToLoadDTD = true;
  9495. for (int i = 0; i < 128; ++i)
  9496. identifierLookupTable[i] = isXmlIdentifierChar_Slow ((tchar) i);
  9497. if (textToParse.isEmpty())
  9498. {
  9499. lastError = "not enough input";
  9500. }
  9501. else
  9502. {
  9503. skipHeader();
  9504. if (input != 0)
  9505. {
  9506. XmlElement* const result = readNextElement (! onlyReadOuterDocumentElement);
  9507. if (errorOccurred)
  9508. delete result;
  9509. else
  9510. return result;
  9511. }
  9512. else
  9513. {
  9514. lastError = "incorrect xml header";
  9515. }
  9516. }
  9517. return 0;
  9518. }
  9519. const String& XmlDocument::getLastParseError() const throw()
  9520. {
  9521. return lastError;
  9522. }
  9523. void XmlDocument::setLastError (const String& desc, const bool carryOn) throw()
  9524. {
  9525. lastError = desc;
  9526. errorOccurred = ! carryOn;
  9527. }
  9528. const String XmlDocument::getFileContents (const String& filename) const
  9529. {
  9530. String result;
  9531. if (inputSource != 0)
  9532. {
  9533. InputStream* const in = inputSource->createInputStreamFor (filename.trim().unquoted());
  9534. if (in != 0)
  9535. {
  9536. result = in->readEntireStreamAsString();
  9537. delete in;
  9538. }
  9539. }
  9540. return result;
  9541. }
  9542. tchar XmlDocument::readNextChar() throw()
  9543. {
  9544. if (*input != 0)
  9545. {
  9546. return *input++;
  9547. }
  9548. else
  9549. {
  9550. outOfData = true;
  9551. return 0;
  9552. }
  9553. }
  9554. int XmlDocument::findNextTokenLength() throw()
  9555. {
  9556. int len = 0;
  9557. tchar c = *input;
  9558. while (isXmlIdentifierChar (c))
  9559. c = input [++len];
  9560. return len;
  9561. }
  9562. void XmlDocument::skipHeader() throw()
  9563. {
  9564. const tchar* const found = CharacterFunctions::find (input, T("<?xml"));
  9565. if (found != 0)
  9566. {
  9567. input = found;
  9568. input = CharacterFunctions::find (input, T("?>"));
  9569. if (input == 0)
  9570. return;
  9571. input += 2;
  9572. }
  9573. skipNextWhiteSpace();
  9574. const tchar* docType = CharacterFunctions::find (input, T("<!DOCTYPE"));
  9575. if (docType == 0)
  9576. return;
  9577. input = docType + 9;
  9578. int n = 1;
  9579. while (n > 0)
  9580. {
  9581. const tchar c = readNextChar();
  9582. if (outOfData)
  9583. return;
  9584. if (c == T('<'))
  9585. ++n;
  9586. else if (c == T('>'))
  9587. --n;
  9588. }
  9589. docType += 9;
  9590. dtdText = String (docType, (int) (input - (docType + 1))).trim();
  9591. }
  9592. void XmlDocument::skipNextWhiteSpace() throw()
  9593. {
  9594. for (;;)
  9595. {
  9596. tchar c = *input;
  9597. while (CharacterFunctions::isWhitespace (c))
  9598. c = *++input;
  9599. if (c == 0)
  9600. {
  9601. outOfData = true;
  9602. break;
  9603. }
  9604. else if (c == T('<'))
  9605. {
  9606. if (input[1] == T('!')
  9607. && input[2] == T('-')
  9608. && input[3] == T('-'))
  9609. {
  9610. const tchar* const closeComment = CharacterFunctions::find (input, T("-->"));
  9611. if (closeComment == 0)
  9612. {
  9613. outOfData = true;
  9614. break;
  9615. }
  9616. input = closeComment + 3;
  9617. continue;
  9618. }
  9619. else if (input[1] == T('?'))
  9620. {
  9621. const tchar* const closeBracket = CharacterFunctions::find (input, T("?>"));
  9622. if (closeBracket == 0)
  9623. {
  9624. outOfData = true;
  9625. break;
  9626. }
  9627. input = closeBracket + 2;
  9628. continue;
  9629. }
  9630. }
  9631. break;
  9632. }
  9633. }
  9634. void XmlDocument::readQuotedString (String& result) throw()
  9635. {
  9636. const tchar quote = readNextChar();
  9637. while (! outOfData)
  9638. {
  9639. const tchar character = readNextChar();
  9640. if (character == quote)
  9641. break;
  9642. if (character == T('&'))
  9643. {
  9644. --input;
  9645. readEntity (result);
  9646. }
  9647. else
  9648. {
  9649. --input;
  9650. const tchar* const start = input;
  9651. for (;;)
  9652. {
  9653. const tchar character = *input;
  9654. if (character == quote)
  9655. {
  9656. result.append (start, (int) (input - start));
  9657. ++input;
  9658. return;
  9659. }
  9660. else if (character == T('&'))
  9661. {
  9662. result.append (start, (int) (input - start));
  9663. break;
  9664. }
  9665. else if (character == 0)
  9666. {
  9667. outOfData = true;
  9668. setLastError ("unmatched quotes", false);
  9669. break;
  9670. }
  9671. ++input;
  9672. }
  9673. }
  9674. }
  9675. }
  9676. XmlElement* XmlDocument::readNextElement (const bool alsoParseSubElements) throw()
  9677. {
  9678. XmlElement* node = 0;
  9679. skipNextWhiteSpace();
  9680. if (outOfData)
  9681. return 0;
  9682. input = CharacterFunctions::find (input, T("<"));
  9683. if (input != 0)
  9684. {
  9685. ++input;
  9686. int tagLen = findNextTokenLength();
  9687. if (tagLen == 0)
  9688. {
  9689. // no tag name - but allow for a gap after the '<' before giving an error
  9690. skipNextWhiteSpace();
  9691. tagLen = findNextTokenLength();
  9692. if (tagLen == 0)
  9693. {
  9694. setLastError ("tag name missing", false);
  9695. return node;
  9696. }
  9697. }
  9698. node = new XmlElement (input, tagLen);
  9699. input += tagLen;
  9700. XmlElement::XmlAttributeNode* lastAttribute = 0;
  9701. // look for attributes
  9702. for (;;)
  9703. {
  9704. skipNextWhiteSpace();
  9705. const tchar c = *input;
  9706. // empty tag..
  9707. if (c == T('/') && input[1] == T('>'))
  9708. {
  9709. input += 2;
  9710. break;
  9711. }
  9712. // parse the guts of the element..
  9713. if (c == T('>'))
  9714. {
  9715. ++input;
  9716. skipNextWhiteSpace();
  9717. if (alsoParseSubElements)
  9718. readChildElements (node);
  9719. break;
  9720. }
  9721. // get an attribute..
  9722. if (isXmlIdentifierChar (c))
  9723. {
  9724. const int attNameLen = findNextTokenLength();
  9725. if (attNameLen > 0)
  9726. {
  9727. const tchar* attNameStart = input;
  9728. input += attNameLen;
  9729. skipNextWhiteSpace();
  9730. if (readNextChar() == T('='))
  9731. {
  9732. skipNextWhiteSpace();
  9733. const tchar c = *input;
  9734. if (c == T('"') || c == T('\''))
  9735. {
  9736. XmlElement::XmlAttributeNode* const newAtt
  9737. = new XmlElement::XmlAttributeNode (String (attNameStart, attNameLen),
  9738. String::empty);
  9739. readQuotedString (newAtt->value);
  9740. if (lastAttribute == 0)
  9741. node->attributes = newAtt;
  9742. else
  9743. lastAttribute->next = newAtt;
  9744. lastAttribute = newAtt;
  9745. continue;
  9746. }
  9747. }
  9748. }
  9749. }
  9750. else
  9751. {
  9752. if (! outOfData)
  9753. setLastError ("illegal character found in " + node->getTagName() + ": '" + c + "'", false);
  9754. }
  9755. break;
  9756. }
  9757. }
  9758. return node;
  9759. }
  9760. void XmlDocument::readChildElements (XmlElement* parent) throw()
  9761. {
  9762. XmlElement* lastChildNode = 0;
  9763. for (;;)
  9764. {
  9765. skipNextWhiteSpace();
  9766. if (outOfData)
  9767. {
  9768. setLastError ("unmatched tags", false);
  9769. break;
  9770. }
  9771. if (*input == T('<'))
  9772. {
  9773. if (input[1] == T('/'))
  9774. {
  9775. // our close tag..
  9776. input = CharacterFunctions::find (input, T(">"));
  9777. ++input;
  9778. break;
  9779. }
  9780. else if (input[1] == T('!')
  9781. && input[2] == T('[')
  9782. && input[3] == T('C')
  9783. && input[4] == T('D')
  9784. && input[5] == T('A')
  9785. && input[6] == T('T')
  9786. && input[7] == T('A')
  9787. && input[8] == T('['))
  9788. {
  9789. input += 9;
  9790. const tchar* const inputStart = input;
  9791. int len = 0;
  9792. for (;;)
  9793. {
  9794. if (*input == 0)
  9795. {
  9796. setLastError ("unterminated CDATA section", false);
  9797. outOfData = true;
  9798. break;
  9799. }
  9800. else if (input[0] == T(']')
  9801. && input[1] == T(']')
  9802. && input[2] == T('>'))
  9803. {
  9804. input += 3;
  9805. break;
  9806. }
  9807. ++input;
  9808. ++len;
  9809. }
  9810. XmlElement* const e = new XmlElement ((int) 0);
  9811. e->setText (String (inputStart, len));
  9812. if (lastChildNode != 0)
  9813. lastChildNode->nextElement = e;
  9814. else
  9815. parent->addChildElement (e);
  9816. lastChildNode = e;
  9817. }
  9818. else
  9819. {
  9820. // this is some other element, so parse and add it..
  9821. XmlElement* const n = readNextElement (true);
  9822. if (n != 0)
  9823. {
  9824. if (lastChildNode == 0)
  9825. parent->addChildElement (n);
  9826. else
  9827. lastChildNode->nextElement = n;
  9828. lastChildNode = n;
  9829. }
  9830. else
  9831. {
  9832. return;
  9833. }
  9834. }
  9835. }
  9836. else
  9837. {
  9838. // read character block..
  9839. XmlElement* const e = new XmlElement ((int)0);
  9840. if (lastChildNode != 0)
  9841. lastChildNode->nextElement = e;
  9842. else
  9843. parent->addChildElement (e);
  9844. lastChildNode = e;
  9845. String textElementContent;
  9846. for (;;)
  9847. {
  9848. const tchar c = *input;
  9849. if (c == T('<'))
  9850. break;
  9851. if (c == 0)
  9852. {
  9853. setLastError ("unmatched tags", false);
  9854. outOfData = true;
  9855. return;
  9856. }
  9857. if (c == T('&'))
  9858. {
  9859. String entity;
  9860. readEntity (entity);
  9861. if (entity.startsWithChar (T('<')) && entity [1] != 0)
  9862. {
  9863. const tchar* const oldInput = input;
  9864. const bool oldOutOfData = outOfData;
  9865. input = (const tchar*) entity;
  9866. outOfData = false;
  9867. for (;;)
  9868. {
  9869. XmlElement* const n = readNextElement (true);
  9870. if (n == 0)
  9871. break;
  9872. if (lastChildNode == 0)
  9873. parent->addChildElement (n);
  9874. else
  9875. lastChildNode->nextElement = n;
  9876. lastChildNode = n;
  9877. }
  9878. input = oldInput;
  9879. outOfData = oldOutOfData;
  9880. }
  9881. else
  9882. {
  9883. textElementContent += entity;
  9884. }
  9885. }
  9886. else
  9887. {
  9888. const tchar* start = input;
  9889. int len = 0;
  9890. for (;;)
  9891. {
  9892. const tchar c = *input;
  9893. if (c == T('<') || c == T('&'))
  9894. {
  9895. break;
  9896. }
  9897. else if (c == 0)
  9898. {
  9899. setLastError ("unmatched tags", false);
  9900. outOfData = true;
  9901. return;
  9902. }
  9903. ++input;
  9904. ++len;
  9905. }
  9906. textElementContent.append (start, len);
  9907. }
  9908. }
  9909. textElementContent = textElementContent.trim();
  9910. if (textElementContent.isNotEmpty())
  9911. e->setText (textElementContent);
  9912. }
  9913. }
  9914. }
  9915. void XmlDocument::readEntity (String& result) throw()
  9916. {
  9917. // skip over the ampersand
  9918. ++input;
  9919. if (CharacterFunctions::compareIgnoreCase (input, T("amp;"), 4) == 0)
  9920. {
  9921. input += 4;
  9922. result += T("&");
  9923. }
  9924. else if (CharacterFunctions::compareIgnoreCase (input, T("quot;"), 5) == 0)
  9925. {
  9926. input += 5;
  9927. result += T("\"");
  9928. }
  9929. else if (CharacterFunctions::compareIgnoreCase (input, T("apos;"), 5) == 0)
  9930. {
  9931. input += 5;
  9932. result += T("\'");
  9933. }
  9934. else if (CharacterFunctions::compareIgnoreCase (input, T("lt;"), 3) == 0)
  9935. {
  9936. input += 3;
  9937. result += T("<");
  9938. }
  9939. else if (CharacterFunctions::compareIgnoreCase (input, T("gt;"), 3) == 0)
  9940. {
  9941. input += 3;
  9942. result += T(">");
  9943. }
  9944. else if (*input == T('#'))
  9945. {
  9946. int charCode = 0;
  9947. ++input;
  9948. if (*input == T('x') || *input == T('X'))
  9949. {
  9950. ++input;
  9951. int numChars = 0;
  9952. while (input[0] != T(';'))
  9953. {
  9954. const int hexValue = CharacterFunctions::getHexDigitValue (input[0]);
  9955. if (hexValue < 0 || ++numChars > 8)
  9956. {
  9957. setLastError ("illegal escape sequence", true);
  9958. break;
  9959. }
  9960. charCode = (charCode << 4) | hexValue;
  9961. ++input;
  9962. }
  9963. ++input;
  9964. }
  9965. else if (input[0] >= T('0') && input[0] <= T('9'))
  9966. {
  9967. int numChars = 0;
  9968. while (input[0] != T(';'))
  9969. {
  9970. if (++numChars > 12)
  9971. {
  9972. setLastError ("illegal escape sequence", true);
  9973. break;
  9974. }
  9975. charCode = charCode * 10 + (input[0] - T('0'));
  9976. ++input;
  9977. }
  9978. ++input;
  9979. }
  9980. else
  9981. {
  9982. setLastError ("illegal escape sequence", true);
  9983. result += T("&");
  9984. return;
  9985. }
  9986. result << (tchar) charCode;
  9987. }
  9988. else
  9989. {
  9990. const tchar* const entityNameStart = input;
  9991. const tchar* const closingSemiColon = CharacterFunctions::find (input, T(";"));
  9992. if (closingSemiColon == 0)
  9993. {
  9994. outOfData = true;
  9995. result += T("&");
  9996. }
  9997. else
  9998. {
  9999. input = closingSemiColon + 1;
  10000. result += expandExternalEntity (String (entityNameStart,
  10001. (int) (closingSemiColon - entityNameStart)));
  10002. }
  10003. }
  10004. }
  10005. const String XmlDocument::expandEntity (const String& ent)
  10006. {
  10007. if (ent.equalsIgnoreCase (T("amp")))
  10008. {
  10009. return T("&");
  10010. }
  10011. else if (ent.equalsIgnoreCase (T("quot")))
  10012. {
  10013. return T("\"");
  10014. }
  10015. else if (ent.equalsIgnoreCase (T("apos")))
  10016. {
  10017. return T("\'");
  10018. }
  10019. else if (ent.equalsIgnoreCase (T("lt")))
  10020. {
  10021. return T("<");
  10022. }
  10023. else if (ent.equalsIgnoreCase (T("gt")))
  10024. {
  10025. return T(">");
  10026. }
  10027. else if (ent[0] == T('#'))
  10028. {
  10029. if (ent[1] == T('x') || ent[1] == T('X'))
  10030. {
  10031. return String::charToString ((tchar) ent.substring (2).getHexValue32());
  10032. }
  10033. else if (ent[1] >= T('0') && ent[1] <= T('9'))
  10034. {
  10035. return String::charToString ((tchar) ent.substring (1).getIntValue());
  10036. }
  10037. setLastError ("illegal escape sequence", false);
  10038. return T("&");
  10039. }
  10040. else
  10041. {
  10042. return expandExternalEntity (ent);
  10043. }
  10044. }
  10045. const String XmlDocument::expandExternalEntity (const String& entity)
  10046. {
  10047. if (needToLoadDTD)
  10048. {
  10049. if (dtdText.isNotEmpty())
  10050. {
  10051. while (dtdText.endsWithChar (T('>')))
  10052. dtdText = dtdText.dropLastCharacters (1);
  10053. tokenisedDTD.addTokens (dtdText, true);
  10054. if (tokenisedDTD [tokenisedDTD.size() - 2].equalsIgnoreCase (T("system"))
  10055. && tokenisedDTD [tokenisedDTD.size() - 1].isQuotedString())
  10056. {
  10057. const String fn (tokenisedDTD [tokenisedDTD.size() - 1]);
  10058. tokenisedDTD.clear();
  10059. tokenisedDTD.addTokens (getFileContents (fn), true);
  10060. }
  10061. else
  10062. {
  10063. tokenisedDTD.clear();
  10064. const int openBracket = dtdText.indexOfChar (T('['));
  10065. if (openBracket > 0)
  10066. {
  10067. const int closeBracket = dtdText.lastIndexOfChar (T(']'));
  10068. if (closeBracket > openBracket)
  10069. tokenisedDTD.addTokens (dtdText.substring (openBracket + 1,
  10070. closeBracket), true);
  10071. }
  10072. }
  10073. for (int i = tokenisedDTD.size(); --i >= 0;)
  10074. {
  10075. if (tokenisedDTD[i].startsWithChar (T('%'))
  10076. && tokenisedDTD[i].endsWithChar (T(';')))
  10077. {
  10078. const String parsed (getParameterEntity (tokenisedDTD[i].substring (1, tokenisedDTD[i].length() - 1)));
  10079. StringArray newToks;
  10080. newToks.addTokens (parsed, true);
  10081. tokenisedDTD.remove (i);
  10082. for (int j = newToks.size(); --j >= 0;)
  10083. tokenisedDTD.insert (i, newToks[j]);
  10084. }
  10085. }
  10086. }
  10087. needToLoadDTD = false;
  10088. }
  10089. for (int i = 0; i < tokenisedDTD.size(); ++i)
  10090. {
  10091. if (tokenisedDTD[i] == entity)
  10092. {
  10093. if (tokenisedDTD[i - 1].equalsIgnoreCase (T("<!entity")))
  10094. {
  10095. String ent (tokenisedDTD [i + 1]);
  10096. while (ent.endsWithChar (T('>')))
  10097. ent = ent.dropLastCharacters (1);
  10098. ent = ent.trim().unquoted();
  10099. // check for sub-entities..
  10100. int ampersand = ent.indexOfChar (T('&'));
  10101. while (ampersand >= 0)
  10102. {
  10103. const int semiColon = ent.indexOf (i + 1, T(";"));
  10104. if (semiColon < 0)
  10105. {
  10106. setLastError ("entity without terminating semi-colon", false);
  10107. break;
  10108. }
  10109. const String resolved (expandEntity (ent.substring (i + 1, semiColon)));
  10110. ent = ent.substring (0, ampersand)
  10111. + resolved
  10112. + ent.substring (semiColon + 1);
  10113. ampersand = ent.indexOfChar (semiColon + 1, T('&'));
  10114. }
  10115. return ent;
  10116. }
  10117. }
  10118. }
  10119. setLastError ("unknown entity", true);
  10120. return entity;
  10121. }
  10122. const String XmlDocument::getParameterEntity (const String& entity)
  10123. {
  10124. for (int i = 0; i < tokenisedDTD.size(); ++i)
  10125. {
  10126. if (tokenisedDTD[i] == entity)
  10127. {
  10128. if (tokenisedDTD [i - 1] == T("%")
  10129. && tokenisedDTD [i - 2].equalsIgnoreCase (T("<!entity")))
  10130. {
  10131. String ent (tokenisedDTD [i + 1]);
  10132. while (ent.endsWithChar (T('>')))
  10133. ent = ent.dropLastCharacters (1);
  10134. if (ent.equalsIgnoreCase (T("system")))
  10135. {
  10136. String filename (tokenisedDTD [i + 2]);
  10137. while (filename.endsWithChar (T('>')))
  10138. filename = filename.dropLastCharacters (1);
  10139. return getFileContents (filename);
  10140. }
  10141. else
  10142. {
  10143. return ent.trim().unquoted();
  10144. }
  10145. }
  10146. }
  10147. }
  10148. return entity;
  10149. }
  10150. END_JUCE_NAMESPACE
  10151. /********* End of inlined file: juce_XmlDocument.cpp *********/
  10152. /********* Start of inlined file: juce_XmlElement.cpp *********/
  10153. BEGIN_JUCE_NAMESPACE
  10154. XmlElement::XmlAttributeNode::XmlAttributeNode (const XmlAttributeNode& other) throw()
  10155. : name (other.name),
  10156. value (other.value),
  10157. next (0)
  10158. {
  10159. }
  10160. XmlElement::XmlAttributeNode::XmlAttributeNode (const String& name_,
  10161. const String& value_) throw()
  10162. : name (name_),
  10163. value (value_),
  10164. next (0)
  10165. {
  10166. }
  10167. XmlElement::XmlElement (const String& tagName_) throw()
  10168. : tagName (tagName_),
  10169. firstChildElement (0),
  10170. nextElement (0),
  10171. attributes (0)
  10172. {
  10173. // the tag name mustn't be empty, or it'll look like a text element!
  10174. jassert (tagName_.trim().isNotEmpty())
  10175. }
  10176. XmlElement::XmlElement (int /*dummy*/) throw()
  10177. : firstChildElement (0),
  10178. nextElement (0),
  10179. attributes (0)
  10180. {
  10181. }
  10182. XmlElement::XmlElement (const tchar* const tagName_,
  10183. const int nameLen) throw()
  10184. : tagName (tagName_, nameLen),
  10185. firstChildElement (0),
  10186. nextElement (0),
  10187. attributes (0)
  10188. {
  10189. }
  10190. XmlElement::XmlElement (const XmlElement& other) throw()
  10191. : tagName (other.tagName),
  10192. firstChildElement (0),
  10193. nextElement (0),
  10194. attributes (0)
  10195. {
  10196. copyChildrenAndAttributesFrom (other);
  10197. }
  10198. const XmlElement& XmlElement::operator= (const XmlElement& other) throw()
  10199. {
  10200. if (this != &other)
  10201. {
  10202. removeAllAttributes();
  10203. deleteAllChildElements();
  10204. tagName = other.tagName;
  10205. copyChildrenAndAttributesFrom (other);
  10206. }
  10207. return *this;
  10208. }
  10209. void XmlElement::copyChildrenAndAttributesFrom (const XmlElement& other) throw()
  10210. {
  10211. XmlElement* child = other.firstChildElement;
  10212. XmlElement* lastChild = 0;
  10213. while (child != 0)
  10214. {
  10215. XmlElement* const copiedChild = new XmlElement (*child);
  10216. if (lastChild != 0)
  10217. lastChild->nextElement = copiedChild;
  10218. else
  10219. firstChildElement = copiedChild;
  10220. lastChild = copiedChild;
  10221. child = child->nextElement;
  10222. }
  10223. const XmlAttributeNode* att = other.attributes;
  10224. XmlAttributeNode* lastAtt = 0;
  10225. while (att != 0)
  10226. {
  10227. XmlAttributeNode* const newAtt = new XmlAttributeNode (*att);
  10228. if (lastAtt != 0)
  10229. lastAtt->next = newAtt;
  10230. else
  10231. attributes = newAtt;
  10232. lastAtt = newAtt;
  10233. att = att->next;
  10234. }
  10235. }
  10236. XmlElement::~XmlElement() throw()
  10237. {
  10238. XmlElement* child = firstChildElement;
  10239. while (child != 0)
  10240. {
  10241. XmlElement* const nextChild = child->nextElement;
  10242. delete child;
  10243. child = nextChild;
  10244. }
  10245. XmlAttributeNode* att = attributes;
  10246. while (att != 0)
  10247. {
  10248. XmlAttributeNode* const nextAtt = att->next;
  10249. delete att;
  10250. att = nextAtt;
  10251. }
  10252. }
  10253. static bool isLegalXmlChar (const juce_wchar character)
  10254. {
  10255. if ((character >= 'a' && character <= 'z')
  10256. || (character >= 'A' && character <= 'Z')
  10257. || (character >= '0' && character <= '9'))
  10258. return true;
  10259. const char* t = " .,;:-()_+=?!'#@[]/\\*%~{}";
  10260. do
  10261. {
  10262. if (((juce_wchar) (uint8) *t) == character)
  10263. return true;
  10264. }
  10265. while (*++t != 0);
  10266. return false;
  10267. }
  10268. static void escapeIllegalXmlChars (OutputStream& outputStream,
  10269. const String& text,
  10270. const bool changeNewLines) throw()
  10271. {
  10272. const juce_wchar* t = (const juce_wchar*) text;
  10273. for (;;)
  10274. {
  10275. const juce_wchar character = *t++;
  10276. if (character == 0)
  10277. {
  10278. break;
  10279. }
  10280. else if (isLegalXmlChar (character))
  10281. {
  10282. outputStream.writeByte ((char) character);
  10283. }
  10284. else
  10285. {
  10286. switch (character)
  10287. {
  10288. case '&':
  10289. outputStream.write ("&amp;", 5);
  10290. break;
  10291. case '"':
  10292. outputStream.write ("&quot;", 6);
  10293. break;
  10294. case '>':
  10295. outputStream.write ("&gt;", 4);
  10296. break;
  10297. case '<':
  10298. outputStream.write ("&lt;", 4);
  10299. break;
  10300. case '\n':
  10301. if (changeNewLines)
  10302. outputStream.write ("&#10;", 5);
  10303. else
  10304. outputStream.writeByte ((char) character);
  10305. break;
  10306. case '\r':
  10307. if (changeNewLines)
  10308. outputStream.write ("&#13;", 5);
  10309. else
  10310. outputStream.writeByte ((char) character);
  10311. break;
  10312. default:
  10313. {
  10314. String encoded (T("&#"));
  10315. encoded << String ((int) (unsigned int) character).trim()
  10316. << T(';');
  10317. outputStream.write ((const char*) encoded, encoded.length());
  10318. }
  10319. }
  10320. }
  10321. }
  10322. }
  10323. static void writeSpaces (OutputStream& out, int numSpaces) throw()
  10324. {
  10325. if (numSpaces > 0)
  10326. {
  10327. const char* const blanks = " ";
  10328. const int blankSize = (int) sizeof (blanks) - 1;
  10329. while (numSpaces > blankSize)
  10330. {
  10331. out.write (blanks, blankSize);
  10332. numSpaces -= blankSize;
  10333. }
  10334. out.write (blanks, numSpaces);
  10335. }
  10336. }
  10337. void XmlElement::writeElementAsText (OutputStream& outputStream,
  10338. const int indentationLevel) const throw()
  10339. {
  10340. writeSpaces (outputStream, indentationLevel);
  10341. if (! isTextElement())
  10342. {
  10343. outputStream.writeByte ('<');
  10344. const int nameLen = tagName.length();
  10345. outputStream.write ((const char*) tagName, nameLen);
  10346. const int attIndent = indentationLevel + nameLen + 1;
  10347. int lineLen = 0;
  10348. const XmlAttributeNode* att = attributes;
  10349. while (att != 0)
  10350. {
  10351. if (lineLen > 60 && indentationLevel >= 0)
  10352. {
  10353. outputStream.write ("\r\n", 2);
  10354. writeSpaces (outputStream, attIndent);
  10355. lineLen = 0;
  10356. }
  10357. const int attNameLen = att->name.length();
  10358. outputStream.writeByte (' ');
  10359. outputStream.write ((const char*) (att->name), attNameLen);
  10360. outputStream.write ("=\"", 2);
  10361. escapeIllegalXmlChars (outputStream, att->value, true);
  10362. outputStream.writeByte ('"');
  10363. lineLen += 4 + attNameLen + att->value.length();
  10364. att = att->next;
  10365. }
  10366. if (firstChildElement != 0)
  10367. {
  10368. XmlElement* child = firstChildElement;
  10369. if (child->nextElement == 0 && child->isTextElement())
  10370. {
  10371. outputStream.writeByte ('>');
  10372. escapeIllegalXmlChars (outputStream, child->getText(), false);
  10373. }
  10374. else
  10375. {
  10376. if (indentationLevel >= 0)
  10377. outputStream.write (">\r\n", 3);
  10378. else
  10379. outputStream.writeByte ('>');
  10380. bool lastWasTextNode = false;
  10381. while (child != 0)
  10382. {
  10383. if (child->isTextElement())
  10384. {
  10385. if ((! lastWasTextNode) && (indentationLevel >= 0))
  10386. writeSpaces (outputStream, indentationLevel + 2);
  10387. escapeIllegalXmlChars (outputStream, child->getText(), false);
  10388. lastWasTextNode = true;
  10389. }
  10390. else
  10391. {
  10392. if (indentationLevel >= 0)
  10393. {
  10394. if (lastWasTextNode)
  10395. outputStream.write ("\r\n", 2);
  10396. child->writeElementAsText (outputStream, indentationLevel + 2);
  10397. }
  10398. else
  10399. {
  10400. child->writeElementAsText (outputStream, indentationLevel);
  10401. }
  10402. lastWasTextNode = false;
  10403. }
  10404. child = child->nextElement;
  10405. }
  10406. if (indentationLevel >= 0)
  10407. {
  10408. if (lastWasTextNode)
  10409. outputStream.write ("\r\n", 2);
  10410. writeSpaces (outputStream, indentationLevel);
  10411. }
  10412. }
  10413. outputStream.write ("</", 2);
  10414. outputStream.write ((const char*) tagName, nameLen);
  10415. if (indentationLevel >= 0)
  10416. outputStream.write (">\r\n", 3);
  10417. else
  10418. outputStream.writeByte ('>');
  10419. }
  10420. else
  10421. {
  10422. if (indentationLevel >= 0)
  10423. outputStream.write ("/>\r\n", 4);
  10424. else
  10425. outputStream.write ("/>", 2);
  10426. }
  10427. }
  10428. else
  10429. {
  10430. if (indentationLevel >= 0)
  10431. writeSpaces (outputStream, indentationLevel + 2);
  10432. escapeIllegalXmlChars (outputStream, getText(), false);
  10433. }
  10434. }
  10435. const String XmlElement::createDocument (const String& dtd,
  10436. const bool allOnOneLine,
  10437. const bool includeXmlHeader,
  10438. const tchar* const encoding) const throw()
  10439. {
  10440. String doc;
  10441. doc.preallocateStorage (1024);
  10442. if (includeXmlHeader)
  10443. {
  10444. doc << "<?xml version=\"1.0\" encoding=\""
  10445. << encoding;
  10446. if (allOnOneLine)
  10447. doc += "\"?> ";
  10448. else
  10449. doc += "\"?>\n\n";
  10450. }
  10451. if (dtd.isNotEmpty())
  10452. {
  10453. if (allOnOneLine)
  10454. doc << dtd << " ";
  10455. else
  10456. doc << dtd << "\r\n";
  10457. }
  10458. MemoryOutputStream mem (2048, 4096);
  10459. writeElementAsText (mem, allOnOneLine ? -1 : 0);
  10460. return doc + String (mem.getData(),
  10461. mem.getDataSize());
  10462. }
  10463. bool XmlElement::writeToFile (const File& f,
  10464. const String& dtd,
  10465. const tchar* const encoding) const throw()
  10466. {
  10467. if (f.hasWriteAccess())
  10468. {
  10469. const File tempFile (f.getNonexistentSibling());
  10470. FileOutputStream* const out = tempFile.createOutputStream();
  10471. if (out != 0)
  10472. {
  10473. *out << "<?xml version=\"1.0\" encoding=\"" << encoding << "\"?>\r\n\r\n"
  10474. << dtd << "\r\n";
  10475. writeElementAsText (*out, 0);
  10476. delete out;
  10477. if (tempFile.moveFileTo (f))
  10478. return true;
  10479. tempFile.deleteFile();
  10480. }
  10481. }
  10482. return false;
  10483. }
  10484. bool XmlElement::hasTagName (const tchar* const tagNameWanted) const throw()
  10485. {
  10486. #ifdef JUCE_DEBUG
  10487. // if debugging, check that the case is actually the same, because
  10488. // valid xml is case-sensitive, and although this lets it pass, it's
  10489. // better not to..
  10490. if (tagName.equalsIgnoreCase (tagNameWanted))
  10491. {
  10492. jassert (tagName == tagNameWanted);
  10493. return true;
  10494. }
  10495. else
  10496. {
  10497. return false;
  10498. }
  10499. #else
  10500. return tagName.equalsIgnoreCase (tagNameWanted);
  10501. #endif
  10502. }
  10503. XmlElement* XmlElement::getNextElementWithTagName (const tchar* const requiredTagName) const
  10504. {
  10505. XmlElement* e = nextElement;
  10506. while (e != 0 && ! e->hasTagName (requiredTagName))
  10507. e = e->nextElement;
  10508. return e;
  10509. }
  10510. int XmlElement::getNumAttributes() const throw()
  10511. {
  10512. const XmlAttributeNode* att = attributes;
  10513. int count = 0;
  10514. while (att != 0)
  10515. {
  10516. att = att->next;
  10517. ++count;
  10518. }
  10519. return count;
  10520. }
  10521. const String& XmlElement::getAttributeName (const int index) const throw()
  10522. {
  10523. const XmlAttributeNode* att = attributes;
  10524. int count = 0;
  10525. while (att != 0)
  10526. {
  10527. if (count == index)
  10528. return att->name;
  10529. att = att->next;
  10530. ++count;
  10531. }
  10532. return String::empty;
  10533. }
  10534. const String& XmlElement::getAttributeValue (const int index) const throw()
  10535. {
  10536. const XmlAttributeNode* att = attributes;
  10537. int count = 0;
  10538. while (att != 0)
  10539. {
  10540. if (count == index)
  10541. return att->value;
  10542. att = att->next;
  10543. ++count;
  10544. }
  10545. return String::empty;
  10546. }
  10547. bool XmlElement::hasAttribute (const tchar* const attributeName) const throw()
  10548. {
  10549. const XmlAttributeNode* att = attributes;
  10550. while (att != 0)
  10551. {
  10552. if (att->name.equalsIgnoreCase (attributeName))
  10553. return true;
  10554. att = att->next;
  10555. }
  10556. return false;
  10557. }
  10558. const String XmlElement::getStringAttribute (const tchar* const attributeName,
  10559. const tchar* const defaultReturnValue) const throw()
  10560. {
  10561. const XmlAttributeNode* att = attributes;
  10562. while (att != 0)
  10563. {
  10564. if (att->name.equalsIgnoreCase (attributeName))
  10565. return att->value;
  10566. att = att->next;
  10567. }
  10568. return defaultReturnValue;
  10569. }
  10570. int XmlElement::getIntAttribute (const tchar* const attributeName,
  10571. const int defaultReturnValue) const throw()
  10572. {
  10573. const XmlAttributeNode* att = attributes;
  10574. while (att != 0)
  10575. {
  10576. if (att->name.equalsIgnoreCase (attributeName))
  10577. return att->value.getIntValue();
  10578. att = att->next;
  10579. }
  10580. return defaultReturnValue;
  10581. }
  10582. double XmlElement::getDoubleAttribute (const tchar* const attributeName,
  10583. const double defaultReturnValue) const throw()
  10584. {
  10585. const XmlAttributeNode* att = attributes;
  10586. while (att != 0)
  10587. {
  10588. if (att->name.equalsIgnoreCase (attributeName))
  10589. return att->value.getDoubleValue();
  10590. att = att->next;
  10591. }
  10592. return defaultReturnValue;
  10593. }
  10594. bool XmlElement::getBoolAttribute (const tchar* const attributeName,
  10595. const bool defaultReturnValue) const throw()
  10596. {
  10597. const XmlAttributeNode* att = attributes;
  10598. while (att != 0)
  10599. {
  10600. if (att->name.equalsIgnoreCase (attributeName))
  10601. {
  10602. tchar firstChar = att->value[0];
  10603. if (CharacterFunctions::isWhitespace (firstChar))
  10604. firstChar = att->value.trimStart() [0];
  10605. return firstChar == T('1')
  10606. || firstChar == T('t')
  10607. || firstChar == T('y')
  10608. || firstChar == T('T')
  10609. || firstChar == T('Y');
  10610. }
  10611. att = att->next;
  10612. }
  10613. return defaultReturnValue;
  10614. }
  10615. bool XmlElement::compareAttribute (const tchar* const attributeName,
  10616. const tchar* const stringToCompareAgainst,
  10617. const bool ignoreCase) const throw()
  10618. {
  10619. const XmlAttributeNode* att = attributes;
  10620. while (att != 0)
  10621. {
  10622. if (att->name.equalsIgnoreCase (attributeName))
  10623. {
  10624. if (ignoreCase)
  10625. return att->value.equalsIgnoreCase (stringToCompareAgainst);
  10626. else
  10627. return att->value == stringToCompareAgainst;
  10628. }
  10629. att = att->next;
  10630. }
  10631. return false;
  10632. }
  10633. void XmlElement::setAttribute (const tchar* const attributeName,
  10634. const String& value) throw()
  10635. {
  10636. #ifdef JUCE_DEBUG
  10637. // check the identifier being passed in is legal..
  10638. const tchar* t = attributeName;
  10639. while (*t != 0)
  10640. {
  10641. jassert (CharacterFunctions::isLetterOrDigit (*t)
  10642. || *t == T('_')
  10643. || *t == T('-')
  10644. || *t == T(':'));
  10645. ++t;
  10646. }
  10647. #endif
  10648. if (attributes == 0)
  10649. {
  10650. attributes = new XmlAttributeNode (attributeName, value);
  10651. }
  10652. else
  10653. {
  10654. XmlAttributeNode* att = attributes;
  10655. for (;;)
  10656. {
  10657. if (att->name.equalsIgnoreCase (attributeName))
  10658. {
  10659. att->value = value;
  10660. break;
  10661. }
  10662. else if (att->next == 0)
  10663. {
  10664. att->next = new XmlAttributeNode (attributeName, value);
  10665. break;
  10666. }
  10667. att = att->next;
  10668. }
  10669. }
  10670. }
  10671. void XmlElement::setAttribute (const tchar* const attributeName,
  10672. const tchar* const text) throw()
  10673. {
  10674. setAttribute (attributeName, String (text));
  10675. }
  10676. void XmlElement::setAttribute (const tchar* const attributeName,
  10677. const int number) throw()
  10678. {
  10679. setAttribute (attributeName, String (number));
  10680. }
  10681. void XmlElement::setAttribute (const tchar* const attributeName,
  10682. const double number) throw()
  10683. {
  10684. tchar buffer [40];
  10685. CharacterFunctions::printf (buffer, numElementsInArray (buffer), T("%.9g"), number);
  10686. setAttribute (attributeName, buffer);
  10687. }
  10688. void XmlElement::removeAttribute (const tchar* const attributeName) throw()
  10689. {
  10690. XmlAttributeNode* att = attributes;
  10691. XmlAttributeNode* lastAtt = 0;
  10692. while (att != 0)
  10693. {
  10694. if (att->name.equalsIgnoreCase (attributeName))
  10695. {
  10696. if (lastAtt == 0)
  10697. attributes = att->next;
  10698. else
  10699. lastAtt->next = att->next;
  10700. delete att;
  10701. break;
  10702. }
  10703. lastAtt = att;
  10704. att = att->next;
  10705. }
  10706. }
  10707. void XmlElement::removeAllAttributes() throw()
  10708. {
  10709. while (attributes != 0)
  10710. {
  10711. XmlAttributeNode* const nextAtt = attributes->next;
  10712. delete attributes;
  10713. attributes = nextAtt;
  10714. }
  10715. }
  10716. int XmlElement::getNumChildElements() const throw()
  10717. {
  10718. int count = 0;
  10719. const XmlElement* child = firstChildElement;
  10720. while (child != 0)
  10721. {
  10722. ++count;
  10723. child = child->nextElement;
  10724. }
  10725. return count;
  10726. }
  10727. XmlElement* XmlElement::getChildElement (const int index) const throw()
  10728. {
  10729. int count = 0;
  10730. XmlElement* child = firstChildElement;
  10731. while (child != 0 && count < index)
  10732. {
  10733. child = child->nextElement;
  10734. ++count;
  10735. }
  10736. return child;
  10737. }
  10738. XmlElement* XmlElement::getChildByName (const tchar* const childName) const throw()
  10739. {
  10740. XmlElement* child = firstChildElement;
  10741. while (child != 0)
  10742. {
  10743. if (child->hasTagName (childName))
  10744. break;
  10745. child = child->nextElement;
  10746. }
  10747. return child;
  10748. }
  10749. void XmlElement::addChildElement (XmlElement* const newNode) throw()
  10750. {
  10751. if (newNode != 0)
  10752. {
  10753. if (firstChildElement == 0)
  10754. {
  10755. firstChildElement = newNode;
  10756. }
  10757. else
  10758. {
  10759. XmlElement* child = firstChildElement;
  10760. while (child->nextElement != 0)
  10761. child = child->nextElement;
  10762. child->nextElement = newNode;
  10763. // if this is non-zero, then something's probably
  10764. // gone wrong..
  10765. jassert (newNode->nextElement == 0);
  10766. }
  10767. }
  10768. }
  10769. void XmlElement::insertChildElement (XmlElement* const newNode,
  10770. int indexToInsertAt) throw()
  10771. {
  10772. if (newNode != 0)
  10773. {
  10774. removeChildElement (newNode, false);
  10775. if (indexToInsertAt == 0)
  10776. {
  10777. newNode->nextElement = firstChildElement;
  10778. firstChildElement = newNode;
  10779. }
  10780. else
  10781. {
  10782. if (firstChildElement == 0)
  10783. {
  10784. firstChildElement = newNode;
  10785. }
  10786. else
  10787. {
  10788. if (indexToInsertAt < 0)
  10789. indexToInsertAt = INT_MAX;
  10790. XmlElement* child = firstChildElement;
  10791. while (child->nextElement != 0 && --indexToInsertAt > 0)
  10792. child = child->nextElement;
  10793. newNode->nextElement = child->nextElement;
  10794. child->nextElement = newNode;
  10795. }
  10796. }
  10797. }
  10798. }
  10799. bool XmlElement::replaceChildElement (XmlElement* const currentChildElement,
  10800. XmlElement* const newNode) throw()
  10801. {
  10802. if (newNode != 0)
  10803. {
  10804. XmlElement* child = firstChildElement;
  10805. XmlElement* previousNode = 0;
  10806. while (child != 0)
  10807. {
  10808. if (child == currentChildElement)
  10809. {
  10810. if (child != newNode)
  10811. {
  10812. if (previousNode == 0)
  10813. firstChildElement = newNode;
  10814. else
  10815. previousNode->nextElement = newNode;
  10816. newNode->nextElement = child->nextElement;
  10817. delete child;
  10818. }
  10819. return true;
  10820. }
  10821. previousNode = child;
  10822. child = child->nextElement;
  10823. }
  10824. }
  10825. return false;
  10826. }
  10827. void XmlElement::removeChildElement (XmlElement* const childToRemove,
  10828. const bool shouldDeleteTheChild) throw()
  10829. {
  10830. if (childToRemove != 0)
  10831. {
  10832. if (firstChildElement == childToRemove)
  10833. {
  10834. firstChildElement = childToRemove->nextElement;
  10835. childToRemove->nextElement = 0;
  10836. }
  10837. else
  10838. {
  10839. XmlElement* child = firstChildElement;
  10840. XmlElement* last = 0;
  10841. while (child != 0)
  10842. {
  10843. if (child == childToRemove)
  10844. {
  10845. if (last == 0)
  10846. firstChildElement = child->nextElement;
  10847. else
  10848. last->nextElement = child->nextElement;
  10849. childToRemove->nextElement = 0;
  10850. break;
  10851. }
  10852. last = child;
  10853. child = child->nextElement;
  10854. }
  10855. }
  10856. if (shouldDeleteTheChild)
  10857. delete childToRemove;
  10858. }
  10859. }
  10860. bool XmlElement::isEquivalentTo (const XmlElement* const other,
  10861. const bool ignoreOrderOfAttributes) const throw()
  10862. {
  10863. if (this != other)
  10864. {
  10865. if (other == 0 || tagName != other->tagName)
  10866. {
  10867. return false;
  10868. }
  10869. if (ignoreOrderOfAttributes)
  10870. {
  10871. int totalAtts = 0;
  10872. const XmlAttributeNode* att = attributes;
  10873. while (att != 0)
  10874. {
  10875. if (! other->compareAttribute (att->name, att->value))
  10876. return false;
  10877. att = att->next;
  10878. ++totalAtts;
  10879. }
  10880. if (totalAtts != other->getNumAttributes())
  10881. return false;
  10882. }
  10883. else
  10884. {
  10885. const XmlAttributeNode* thisAtt = attributes;
  10886. const XmlAttributeNode* otherAtt = other->attributes;
  10887. for (;;)
  10888. {
  10889. if (thisAtt == 0 || otherAtt == 0)
  10890. {
  10891. if (thisAtt == otherAtt) // both 0, so it's a match
  10892. break;
  10893. return false;
  10894. }
  10895. if (thisAtt->name != otherAtt->name
  10896. || thisAtt->value != otherAtt->value)
  10897. {
  10898. return false;
  10899. }
  10900. thisAtt = thisAtt->next;
  10901. otherAtt = otherAtt->next;
  10902. }
  10903. }
  10904. const XmlElement* thisChild = firstChildElement;
  10905. const XmlElement* otherChild = other->firstChildElement;
  10906. for (;;)
  10907. {
  10908. if (thisChild == 0 || otherChild == 0)
  10909. {
  10910. if (thisChild == otherChild) // both 0, so it's a match
  10911. break;
  10912. return false;
  10913. }
  10914. if (! thisChild->isEquivalentTo (otherChild, ignoreOrderOfAttributes))
  10915. return false;
  10916. thisChild = thisChild->nextElement;
  10917. otherChild = otherChild->nextElement;
  10918. }
  10919. }
  10920. return true;
  10921. }
  10922. void XmlElement::deleteAllChildElements() throw()
  10923. {
  10924. while (firstChildElement != 0)
  10925. {
  10926. XmlElement* const nextChild = firstChildElement->nextElement;
  10927. delete firstChildElement;
  10928. firstChildElement = nextChild;
  10929. }
  10930. }
  10931. void XmlElement::deleteAllChildElementsWithTagName (const tchar* const name) throw()
  10932. {
  10933. XmlElement* child = firstChildElement;
  10934. while (child != 0)
  10935. {
  10936. if (child->hasTagName (name))
  10937. {
  10938. XmlElement* const nextChild = child->nextElement;
  10939. removeChildElement (child, true);
  10940. child = nextChild;
  10941. }
  10942. else
  10943. {
  10944. child = child->nextElement;
  10945. }
  10946. }
  10947. }
  10948. bool XmlElement::containsChildElement (const XmlElement* const possibleChild) const throw()
  10949. {
  10950. const XmlElement* child = firstChildElement;
  10951. while (child != 0)
  10952. {
  10953. if (child == possibleChild)
  10954. return true;
  10955. child = child->nextElement;
  10956. }
  10957. return false;
  10958. }
  10959. XmlElement* XmlElement::findParentElementOf (const XmlElement* const elementToLookFor) throw()
  10960. {
  10961. if (this == elementToLookFor || elementToLookFor == 0)
  10962. return 0;
  10963. XmlElement* child = firstChildElement;
  10964. while (child != 0)
  10965. {
  10966. if (elementToLookFor == child)
  10967. return this;
  10968. XmlElement* const found = child->findParentElementOf (elementToLookFor);
  10969. if (found != 0)
  10970. return found;
  10971. child = child->nextElement;
  10972. }
  10973. return 0;
  10974. }
  10975. XmlElement** XmlElement::getChildElementsAsArray (const int num) const throw()
  10976. {
  10977. XmlElement** const elems = new XmlElement* [num];
  10978. XmlElement* e = firstChildElement;
  10979. int i = 0;
  10980. while (e != 0)
  10981. {
  10982. elems [i++] = e;
  10983. e = e->nextElement;
  10984. }
  10985. return elems;
  10986. }
  10987. void XmlElement::reorderChildElements (XmlElement** const elems, const int num) throw()
  10988. {
  10989. XmlElement* e = firstChildElement = elems[0];
  10990. for (int i = 1; i < num; ++i)
  10991. {
  10992. e->nextElement = elems[i];
  10993. e = e->nextElement;
  10994. }
  10995. e->nextElement = 0;
  10996. }
  10997. bool XmlElement::isTextElement() const throw()
  10998. {
  10999. return tagName.isEmpty();
  11000. }
  11001. static const tchar* const juce_xmltextContentAttributeName = T("text");
  11002. const String XmlElement::getText() const throw()
  11003. {
  11004. jassert (isTextElement()); // you're trying to get the text from an element that
  11005. // isn't actually a text element.. If this contains text sub-nodes, you
  11006. // can use getAllSubText instead to
  11007. return getStringAttribute (juce_xmltextContentAttributeName);
  11008. }
  11009. void XmlElement::setText (const String& newText) throw()
  11010. {
  11011. if (isTextElement())
  11012. {
  11013. setAttribute (juce_xmltextContentAttributeName, newText);
  11014. }
  11015. else
  11016. {
  11017. jassertfalse // you can only change the text in a text element, not a normal one.
  11018. }
  11019. }
  11020. const String XmlElement::getAllSubText() const throw()
  11021. {
  11022. String result;
  11023. const XmlElement* child = firstChildElement;
  11024. while (child != 0)
  11025. {
  11026. if (child->isTextElement())
  11027. result += child->getText();
  11028. child = child->nextElement;
  11029. }
  11030. return result;
  11031. }
  11032. const String XmlElement::getChildElementAllSubText (const tchar* const childTagName,
  11033. const String& defaultReturnValue) const throw()
  11034. {
  11035. const XmlElement* const child = getChildByName (childTagName);
  11036. if (child != 0)
  11037. return child->getAllSubText();
  11038. return defaultReturnValue;
  11039. }
  11040. XmlElement* XmlElement::createTextElement (const String& text) throw()
  11041. {
  11042. XmlElement* const e = new XmlElement ((int) 0);
  11043. e->setAttribute (juce_xmltextContentAttributeName, text);
  11044. return e;
  11045. }
  11046. void XmlElement::addTextElement (const String& text) throw()
  11047. {
  11048. addChildElement (createTextElement (text));
  11049. }
  11050. void XmlElement::deleteAllTextElements() throw()
  11051. {
  11052. XmlElement* child = firstChildElement;
  11053. while (child != 0)
  11054. {
  11055. XmlElement* const next = child->nextElement;
  11056. if (child->isTextElement())
  11057. removeChildElement (child, true);
  11058. child = next;
  11059. }
  11060. }
  11061. END_JUCE_NAMESPACE
  11062. /********* End of inlined file: juce_XmlElement.cpp *********/
  11063. /********* Start of inlined file: juce_InterProcessLock.cpp *********/
  11064. BEGIN_JUCE_NAMESPACE
  11065. // (implemented in the platform-specific code files)
  11066. END_JUCE_NAMESPACE
  11067. /********* End of inlined file: juce_InterProcessLock.cpp *********/
  11068. /********* Start of inlined file: juce_ReadWriteLock.cpp *********/
  11069. BEGIN_JUCE_NAMESPACE
  11070. ReadWriteLock::ReadWriteLock() throw()
  11071. : numWaitingWriters (0),
  11072. numWriters (0),
  11073. writerThreadId (0)
  11074. {
  11075. }
  11076. ReadWriteLock::~ReadWriteLock() throw()
  11077. {
  11078. jassert (readerThreads.size() == 0);
  11079. jassert (numWriters == 0);
  11080. }
  11081. void ReadWriteLock::enterRead() const throw()
  11082. {
  11083. const int threadId = Thread::getCurrentThreadId();
  11084. const ScopedLock sl (accessLock);
  11085. for (;;)
  11086. {
  11087. jassert (readerThreads.size() % 2 == 0);
  11088. int i;
  11089. for (i = 0; i < readerThreads.size(); i += 2)
  11090. if (readerThreads.getUnchecked(i) == threadId)
  11091. break;
  11092. if (i < readerThreads.size()
  11093. || numWriters + numWaitingWriters == 0
  11094. || (threadId == writerThreadId && numWriters > 0))
  11095. {
  11096. if (i < readerThreads.size())
  11097. {
  11098. readerThreads.set (i + 1, readerThreads.getUnchecked (i + 1) + 1);
  11099. }
  11100. else
  11101. {
  11102. readerThreads.add (threadId);
  11103. readerThreads.add (1);
  11104. }
  11105. return;
  11106. }
  11107. const ScopedUnlock ul (accessLock);
  11108. waitEvent.wait (100);
  11109. }
  11110. }
  11111. void ReadWriteLock::exitRead() const throw()
  11112. {
  11113. const int threadId = Thread::getCurrentThreadId();
  11114. const ScopedLock sl (accessLock);
  11115. for (int i = 0; i < readerThreads.size(); i += 2)
  11116. {
  11117. if (readerThreads.getUnchecked(i) == threadId)
  11118. {
  11119. const int newCount = readerThreads.getUnchecked (i + 1) - 1;
  11120. if (newCount == 0)
  11121. {
  11122. readerThreads.removeRange (i, 2);
  11123. waitEvent.signal();
  11124. }
  11125. else
  11126. {
  11127. readerThreads.set (i + 1, newCount);
  11128. }
  11129. return;
  11130. }
  11131. }
  11132. jassertfalse // unlocking a lock that wasn't locked..
  11133. }
  11134. void ReadWriteLock::enterWrite() const throw()
  11135. {
  11136. const int threadId = Thread::getCurrentThreadId();
  11137. const ScopedLock sl (accessLock);
  11138. for (;;)
  11139. {
  11140. if (readerThreads.size() + numWriters == 0
  11141. || threadId == writerThreadId
  11142. || (readerThreads.size() == 2
  11143. && readerThreads.getUnchecked(0) == threadId))
  11144. {
  11145. writerThreadId = threadId;
  11146. ++numWriters;
  11147. break;
  11148. }
  11149. ++numWaitingWriters;
  11150. accessLock.exit();
  11151. waitEvent.wait (100);
  11152. accessLock.enter();
  11153. --numWaitingWriters;
  11154. }
  11155. }
  11156. void ReadWriteLock::exitWrite() const throw()
  11157. {
  11158. const ScopedLock sl (accessLock);
  11159. // check this thread actually had the lock..
  11160. jassert (numWriters > 0 && writerThreadId == Thread::getCurrentThreadId());
  11161. if (--numWriters == 0)
  11162. {
  11163. writerThreadId = 0;
  11164. waitEvent.signal();
  11165. }
  11166. }
  11167. END_JUCE_NAMESPACE
  11168. /********* End of inlined file: juce_ReadWriteLock.cpp *********/
  11169. /********* Start of inlined file: juce_Thread.cpp *********/
  11170. BEGIN_JUCE_NAMESPACE
  11171. // these functions are implemented in the platform-specific code.
  11172. void* juce_createThread (void* userData) throw();
  11173. void juce_killThread (void* handle) throw();
  11174. void juce_setThreadPriority (void* handle, int priority) throw();
  11175. void juce_setCurrentThreadName (const String& name) throw();
  11176. #if JUCE_WIN32
  11177. void juce_CloseThreadHandle (void* handle) throw();
  11178. #endif
  11179. static VoidArray runningThreads (4);
  11180. static CriticalSection runningThreadsLock;
  11181. void Thread::threadEntryPoint (Thread* const thread) throw()
  11182. {
  11183. runningThreadsLock.enter();
  11184. runningThreads.add (thread);
  11185. runningThreadsLock.exit();
  11186. JUCE_TRY
  11187. {
  11188. thread->threadId_ = Thread::getCurrentThreadId();
  11189. if (thread->threadName_.isNotEmpty())
  11190. juce_setCurrentThreadName (thread->threadName_);
  11191. if (thread->startSuspensionEvent_.wait (10000))
  11192. {
  11193. if (thread->affinityMask_ != 0)
  11194. setCurrentThreadAffinityMask (thread->affinityMask_);
  11195. thread->run();
  11196. }
  11197. }
  11198. JUCE_CATCH_ALL_ASSERT
  11199. runningThreadsLock.enter();
  11200. jassert (runningThreads.contains (thread));
  11201. runningThreads.removeValue (thread);
  11202. runningThreadsLock.exit();
  11203. #if JUCE_WIN32
  11204. juce_CloseThreadHandle (thread->threadHandle_);
  11205. #endif
  11206. thread->threadHandle_ = 0;
  11207. thread->threadId_ = 0;
  11208. }
  11209. // used to wrap the incoming call from the platform-specific code
  11210. void JUCE_API juce_threadEntryPoint (void* userData)
  11211. {
  11212. Thread::threadEntryPoint ((Thread*) userData);
  11213. }
  11214. Thread::Thread (const String& threadName)
  11215. : threadName_ (threadName),
  11216. threadHandle_ (0),
  11217. threadPriority_ (5),
  11218. threadId_ (0),
  11219. affinityMask_ (0),
  11220. threadShouldExit_ (false)
  11221. {
  11222. }
  11223. Thread::~Thread()
  11224. {
  11225. stopThread (100);
  11226. }
  11227. void Thread::startThread() throw()
  11228. {
  11229. const ScopedLock sl (startStopLock);
  11230. threadShouldExit_ = false;
  11231. if (threadHandle_ == 0)
  11232. {
  11233. threadHandle_ = juce_createThread ((void*) this);
  11234. juce_setThreadPriority (threadHandle_, threadPriority_);
  11235. startSuspensionEvent_.signal();
  11236. }
  11237. }
  11238. void Thread::startThread (const int priority) throw()
  11239. {
  11240. const ScopedLock sl (startStopLock);
  11241. if (threadHandle_ == 0)
  11242. {
  11243. threadPriority_ = priority;
  11244. startThread();
  11245. }
  11246. else
  11247. {
  11248. setPriority (priority);
  11249. }
  11250. }
  11251. bool Thread::isThreadRunning() const throw()
  11252. {
  11253. return threadHandle_ != 0;
  11254. }
  11255. void Thread::signalThreadShouldExit() throw()
  11256. {
  11257. threadShouldExit_ = true;
  11258. }
  11259. bool Thread::waitForThreadToExit (const int timeOutMilliseconds) const throw()
  11260. {
  11261. // Doh! So how exactly do you expect this thread to wait for itself to stop??
  11262. jassert (getThreadId() != getCurrentThreadId());
  11263. const int sleepMsPerIteration = 5;
  11264. int count = timeOutMilliseconds / sleepMsPerIteration;
  11265. while (isThreadRunning())
  11266. {
  11267. if (timeOutMilliseconds > 0 && --count < 0)
  11268. return false;
  11269. sleep (sleepMsPerIteration);
  11270. }
  11271. return true;
  11272. }
  11273. void Thread::stopThread (const int timeOutMilliseconds) throw()
  11274. {
  11275. // agh! You can't stop the thread that's calling this method! How on earth
  11276. // would that work??
  11277. jassert (getCurrentThreadId() != getThreadId());
  11278. const ScopedLock sl (startStopLock);
  11279. if (isThreadRunning())
  11280. {
  11281. signalThreadShouldExit();
  11282. notify();
  11283. if (timeOutMilliseconds != 0)
  11284. waitForThreadToExit (timeOutMilliseconds);
  11285. if (isThreadRunning())
  11286. {
  11287. // very bad karma if this point is reached, as
  11288. // there are bound to be locks and events left in
  11289. // silly states when a thread is killed by force..
  11290. jassertfalse
  11291. Logger::writeToLog ("!! killing thread by force !!");
  11292. juce_killThread (threadHandle_);
  11293. threadHandle_ = 0;
  11294. threadId_ = 0;
  11295. const ScopedLock sl (runningThreadsLock);
  11296. runningThreads.removeValue (this);
  11297. }
  11298. }
  11299. }
  11300. void Thread::setPriority (const int priority) throw()
  11301. {
  11302. const ScopedLock sl (startStopLock);
  11303. threadPriority_ = priority;
  11304. juce_setThreadPriority (threadHandle_, priority);
  11305. }
  11306. void Thread::setCurrentThreadPriority (const int priority) throw()
  11307. {
  11308. juce_setThreadPriority (0, priority);
  11309. }
  11310. void Thread::setAffinityMask (const uint32 affinityMask) throw()
  11311. {
  11312. affinityMask_ = affinityMask;
  11313. }
  11314. int Thread::getThreadId() const throw()
  11315. {
  11316. return threadId_;
  11317. }
  11318. bool Thread::wait (const int timeOutMilliseconds) const throw()
  11319. {
  11320. return defaultEvent_.wait (timeOutMilliseconds);
  11321. }
  11322. void Thread::notify() const throw()
  11323. {
  11324. defaultEvent_.signal();
  11325. }
  11326. int Thread::getNumRunningThreads() throw()
  11327. {
  11328. return runningThreads.size();
  11329. }
  11330. Thread* Thread::getCurrentThread() throw()
  11331. {
  11332. const int thisId = getCurrentThreadId();
  11333. Thread* result = 0;
  11334. runningThreadsLock.enter();
  11335. for (int i = runningThreads.size(); --i >= 0;)
  11336. {
  11337. Thread* const t = (Thread*) (runningThreads.getUnchecked(i));
  11338. if (t->threadId_ == thisId)
  11339. {
  11340. result = t;
  11341. break;
  11342. }
  11343. }
  11344. runningThreadsLock.exit();
  11345. return result;
  11346. }
  11347. void Thread::stopAllThreads (const int timeOutMilliseconds) throw()
  11348. {
  11349. runningThreadsLock.enter();
  11350. for (int i = runningThreads.size(); --i >= 0;)
  11351. ((Thread*) runningThreads.getUnchecked(i))->signalThreadShouldExit();
  11352. runningThreadsLock.exit();
  11353. for (;;)
  11354. {
  11355. runningThreadsLock.enter();
  11356. Thread* const t = (Thread*) runningThreads[0];
  11357. runningThreadsLock.exit();
  11358. if (t == 0)
  11359. break;
  11360. t->stopThread (timeOutMilliseconds);
  11361. }
  11362. }
  11363. END_JUCE_NAMESPACE
  11364. /********* End of inlined file: juce_Thread.cpp *********/
  11365. /********* Start of inlined file: juce_ThreadPool.cpp *********/
  11366. BEGIN_JUCE_NAMESPACE
  11367. ThreadPoolJob::ThreadPoolJob (const String& name)
  11368. : jobName (name),
  11369. pool (0),
  11370. shouldStop (false),
  11371. isActive (false),
  11372. shouldBeDeleted (false)
  11373. {
  11374. }
  11375. ThreadPoolJob::~ThreadPoolJob()
  11376. {
  11377. // you mustn't delete a job while it's still in a pool! Use ThreadPool::removeJob()
  11378. // to remove it first!
  11379. jassert (pool == 0 || ! pool->contains (this));
  11380. }
  11381. const String ThreadPoolJob::getJobName() const
  11382. {
  11383. return jobName;
  11384. }
  11385. void ThreadPoolJob::setJobName (const String& newName)
  11386. {
  11387. jobName = newName;
  11388. }
  11389. void ThreadPoolJob::signalJobShouldExit()
  11390. {
  11391. shouldStop = true;
  11392. }
  11393. class ThreadPoolThread : public Thread
  11394. {
  11395. ThreadPool& pool;
  11396. bool volatile busy;
  11397. ThreadPoolThread (const ThreadPoolThread&);
  11398. const ThreadPoolThread& operator= (const ThreadPoolThread&);
  11399. public:
  11400. ThreadPoolThread (ThreadPool& pool_)
  11401. : Thread (T("Pool")),
  11402. pool (pool_),
  11403. busy (false)
  11404. {
  11405. }
  11406. ~ThreadPoolThread()
  11407. {
  11408. }
  11409. void run()
  11410. {
  11411. while (! threadShouldExit())
  11412. {
  11413. if (! pool.runNextJob())
  11414. wait (500);
  11415. }
  11416. }
  11417. };
  11418. ThreadPool::ThreadPool (const int numThreads_,
  11419. const bool startThreadsOnlyWhenNeeded,
  11420. const int stopThreadsWhenNotUsedTimeoutMs)
  11421. : numThreads (jmax (1, numThreads_)),
  11422. threadStopTimeout (stopThreadsWhenNotUsedTimeoutMs),
  11423. priority (5)
  11424. {
  11425. jassert (numThreads_ > 0); // not much point having one of these with no threads in it.
  11426. threads = (Thread**) juce_calloc (sizeof (Thread*) * numThreads);
  11427. for (int i = numThreads; --i >= 0;)
  11428. {
  11429. threads[i] = new ThreadPoolThread (*this);
  11430. if (! startThreadsOnlyWhenNeeded)
  11431. threads[i]->startThread();
  11432. }
  11433. }
  11434. ThreadPool::~ThreadPool()
  11435. {
  11436. removeAllJobs (true, 4000);
  11437. int i;
  11438. for (i = numThreads; --i >= 0;)
  11439. threads[i]->signalThreadShouldExit();
  11440. for (i = numThreads; --i >= 0;)
  11441. {
  11442. threads[i]->stopThread (500);
  11443. delete threads[i];
  11444. }
  11445. juce_free (threads);
  11446. }
  11447. void ThreadPool::addJob (ThreadPoolJob* const job)
  11448. {
  11449. jassert (job->pool == 0);
  11450. if (job->pool == 0)
  11451. {
  11452. job->pool = this;
  11453. job->shouldStop = false;
  11454. job->isActive = false;
  11455. lock.enter();
  11456. jobs.add (job);
  11457. int numRunning = 0;
  11458. int i;
  11459. for (i = numThreads; --i >= 0;)
  11460. if (threads[i]->isThreadRunning() && ! threads[i]->threadShouldExit())
  11461. ++numRunning;
  11462. if (numRunning < numThreads)
  11463. {
  11464. bool startedOne = false;
  11465. int n = 1000;
  11466. while (--n >= 0 && ! startedOne)
  11467. {
  11468. for (int i = numThreads; --i >= 0;)
  11469. {
  11470. if (! threads[i]->isThreadRunning())
  11471. {
  11472. threads[i]->startThread();
  11473. startedOne = true;
  11474. }
  11475. }
  11476. if (! startedOne)
  11477. Thread::sleep (5);
  11478. }
  11479. }
  11480. lock.exit();
  11481. for (i = numThreads; --i >= 0;)
  11482. threads[i]->notify();
  11483. }
  11484. }
  11485. int ThreadPool::getNumJobs() const throw()
  11486. {
  11487. return jobs.size();
  11488. }
  11489. ThreadPoolJob* ThreadPool::getJob (const int index) const
  11490. {
  11491. const ScopedLock sl (lock);
  11492. return (ThreadPoolJob*) jobs [index];
  11493. }
  11494. bool ThreadPool::contains (const ThreadPoolJob* const job) const throw()
  11495. {
  11496. const ScopedLock sl (lock);
  11497. return jobs.contains ((void*) job);
  11498. }
  11499. bool ThreadPool::isJobRunning (const ThreadPoolJob* const job) const
  11500. {
  11501. const ScopedLock sl (lock);
  11502. return jobs.contains ((void*) job) && job->isActive;
  11503. }
  11504. bool ThreadPool::waitForJobToFinish (const ThreadPoolJob* const job,
  11505. const int timeOutMs) const
  11506. {
  11507. if (job != 0)
  11508. {
  11509. const uint32 start = Time::getMillisecondCounter();
  11510. while (contains (job))
  11511. {
  11512. if (timeOutMs >= 0 && Time::getMillisecondCounter() >= start + timeOutMs)
  11513. return false;
  11514. Thread::sleep (2);
  11515. }
  11516. }
  11517. return true;
  11518. }
  11519. bool ThreadPool::removeJob (ThreadPoolJob* const job,
  11520. const bool interruptIfRunning,
  11521. const int timeOutMs)
  11522. {
  11523. if (job != 0)
  11524. {
  11525. lock.enter();
  11526. if (jobs.contains (job))
  11527. {
  11528. if (job->isActive)
  11529. {
  11530. if (interruptIfRunning)
  11531. job->signalJobShouldExit();
  11532. lock.exit();
  11533. return waitForJobToFinish (job, timeOutMs);
  11534. }
  11535. else
  11536. {
  11537. jobs.removeValue (job);
  11538. }
  11539. }
  11540. lock.exit();
  11541. }
  11542. return true;
  11543. }
  11544. bool ThreadPool::removeAllJobs (const bool interruptRunningJobs,
  11545. const int timeOutMs)
  11546. {
  11547. lock.enter();
  11548. for (int i = jobs.size(); --i >= 0;)
  11549. {
  11550. ThreadPoolJob* const job = (ThreadPoolJob*) jobs.getUnchecked(i);
  11551. if (job->isActive)
  11552. {
  11553. if (interruptRunningJobs)
  11554. job->signalJobShouldExit();
  11555. }
  11556. else
  11557. {
  11558. jobs.remove (i);
  11559. }
  11560. }
  11561. lock.exit();
  11562. const uint32 start = Time::getMillisecondCounter();
  11563. while (jobs.size() > 0)
  11564. {
  11565. if (timeOutMs >= 0 && Time::getMillisecondCounter() >= start + timeOutMs)
  11566. return false;
  11567. Thread::sleep (2);
  11568. }
  11569. return true;
  11570. }
  11571. const StringArray ThreadPool::getNamesOfAllJobs (const bool onlyReturnActiveJobs) const
  11572. {
  11573. StringArray s;
  11574. const ScopedLock sl (lock);
  11575. for (int i = 0; i < jobs.size(); ++i)
  11576. {
  11577. const ThreadPoolJob* const job = (const ThreadPoolJob*) jobs.getUnchecked(i);
  11578. if (job->isActive || ! onlyReturnActiveJobs)
  11579. s.add (job->getJobName());
  11580. }
  11581. return s;
  11582. }
  11583. void ThreadPool::setThreadPriorities (const int newPriority)
  11584. {
  11585. if (priority != newPriority)
  11586. {
  11587. priority = newPriority;
  11588. for (int i = numThreads; --i >= 0;)
  11589. threads[i]->setPriority (newPriority);
  11590. }
  11591. }
  11592. bool ThreadPool::runNextJob()
  11593. {
  11594. lock.enter();
  11595. ThreadPoolJob* job = 0;
  11596. for (int i = 0; i < jobs.size(); ++i)
  11597. {
  11598. job = (ThreadPoolJob*) jobs [i];
  11599. if (job != 0 && ! (job->isActive || job->shouldStop))
  11600. break;
  11601. job = 0;
  11602. }
  11603. if (job != 0)
  11604. {
  11605. job->isActive = true;
  11606. lock.exit();
  11607. JUCE_TRY
  11608. {
  11609. ThreadPoolJob::JobStatus result = job->runJob();
  11610. lastJobEndTime = Time::getApproximateMillisecondCounter();
  11611. const ScopedLock sl (lock);
  11612. if (jobs.contains (job))
  11613. {
  11614. job->isActive = false;
  11615. if (result != ThreadPoolJob::jobNeedsRunningAgain || job->shouldStop)
  11616. {
  11617. job->pool = 0;
  11618. job->shouldStop = true;
  11619. jobs.removeValue (job);
  11620. if (result == ThreadPoolJob::jobHasFinishedAndShouldBeDeleted)
  11621. delete job;
  11622. }
  11623. else
  11624. {
  11625. // move the job to the end of the queue if it wants another go
  11626. jobs.move (jobs.indexOf (job), -1);
  11627. }
  11628. }
  11629. }
  11630. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  11631. catch (...)
  11632. {
  11633. lock.enter();
  11634. jobs.removeValue (job);
  11635. lock.exit();
  11636. }
  11637. #endif
  11638. }
  11639. else
  11640. {
  11641. lock.exit();
  11642. if (threadStopTimeout > 0
  11643. && Time::getApproximateMillisecondCounter() > lastJobEndTime + threadStopTimeout)
  11644. {
  11645. lock.enter();
  11646. if (jobs.size() == 0)
  11647. {
  11648. for (int i = numThreads; --i >= 0;)
  11649. threads[i]->signalThreadShouldExit();
  11650. }
  11651. lock.exit();
  11652. }
  11653. else
  11654. {
  11655. return false;
  11656. }
  11657. }
  11658. return true;
  11659. }
  11660. END_JUCE_NAMESPACE
  11661. /********* End of inlined file: juce_ThreadPool.cpp *********/
  11662. /********* Start of inlined file: juce_TimeSliceThread.cpp *********/
  11663. BEGIN_JUCE_NAMESPACE
  11664. TimeSliceThread::TimeSliceThread (const String& threadName)
  11665. : Thread (threadName),
  11666. index (0),
  11667. clientBeingCalled (0),
  11668. clientsChanged (false)
  11669. {
  11670. }
  11671. TimeSliceThread::~TimeSliceThread()
  11672. {
  11673. stopThread (2000);
  11674. }
  11675. void TimeSliceThread::addTimeSliceClient (TimeSliceClient* const client)
  11676. {
  11677. const ScopedLock sl (listLock);
  11678. clients.addIfNotAlreadyThere (client);
  11679. clientsChanged = true;
  11680. notify();
  11681. }
  11682. void TimeSliceThread::removeTimeSliceClient (TimeSliceClient* const client)
  11683. {
  11684. const ScopedLock sl1 (listLock);
  11685. clientsChanged = true;
  11686. // if there's a chance we're in the middle of calling this client, we need to
  11687. // also lock the outer lock..
  11688. if (clientBeingCalled == client)
  11689. {
  11690. const ScopedUnlock ul (listLock); // unlock first to get the order right..
  11691. const ScopedLock sl1 (callbackLock);
  11692. const ScopedLock sl2 (listLock);
  11693. clients.removeValue (client);
  11694. }
  11695. else
  11696. {
  11697. clients.removeValue (client);
  11698. }
  11699. }
  11700. int TimeSliceThread::getNumClients() const throw()
  11701. {
  11702. return clients.size();
  11703. }
  11704. TimeSliceClient* TimeSliceThread::getClient (const int index) const throw()
  11705. {
  11706. const ScopedLock sl (listLock);
  11707. return clients [index];
  11708. }
  11709. void TimeSliceThread::run()
  11710. {
  11711. int numCallsSinceBusy = 0;
  11712. while (! threadShouldExit())
  11713. {
  11714. int timeToWait = 500;
  11715. {
  11716. const ScopedLock sl (callbackLock);
  11717. {
  11718. const ScopedLock sl (listLock);
  11719. if (clients.size() > 0)
  11720. {
  11721. index = (index + 1) % clients.size();
  11722. clientBeingCalled = clients [index];
  11723. }
  11724. else
  11725. {
  11726. index = 0;
  11727. clientBeingCalled = 0;
  11728. }
  11729. if (clientsChanged)
  11730. {
  11731. clientsChanged = false;
  11732. numCallsSinceBusy = 0;
  11733. }
  11734. }
  11735. if (clientBeingCalled != 0)
  11736. {
  11737. if (clientBeingCalled->useTimeSlice())
  11738. numCallsSinceBusy = 0;
  11739. else
  11740. ++numCallsSinceBusy;
  11741. if (numCallsSinceBusy >= clients.size())
  11742. timeToWait = 500;
  11743. else if (index == 0)
  11744. timeToWait = 1; // throw in an occasional pause, to stop everything locking up
  11745. else
  11746. timeToWait = 0;
  11747. }
  11748. }
  11749. if (timeToWait > 0)
  11750. wait (timeToWait);
  11751. }
  11752. }
  11753. END_JUCE_NAMESPACE
  11754. /********* End of inlined file: juce_TimeSliceThread.cpp *********/
  11755. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  11756. /********* Start of inlined file: juce_Application.cpp *********/
  11757. #if JUCE_MSVC
  11758. #pragma warning (push)
  11759. #pragma warning (disable: 4245 4514 4100)
  11760. #include <crtdbg.h>
  11761. #pragma warning (pop)
  11762. #endif
  11763. BEGIN_JUCE_NAMESPACE
  11764. void juce_setCurrentExecutableFileName (const String& filename) throw();
  11765. void juce_setCurrentThreadName (const String& name) throw();
  11766. static JUCEApplication* appInstance = 0;
  11767. JUCEApplication::JUCEApplication()
  11768. : appReturnValue (0),
  11769. stillInitialising (true)
  11770. {
  11771. }
  11772. JUCEApplication::~JUCEApplication()
  11773. {
  11774. }
  11775. JUCEApplication* JUCEApplication::getInstance() throw()
  11776. {
  11777. return appInstance;
  11778. }
  11779. bool JUCEApplication::isInitialising() const throw()
  11780. {
  11781. return stillInitialising;
  11782. }
  11783. const String JUCEApplication::getApplicationVersion()
  11784. {
  11785. return String::empty;
  11786. }
  11787. bool JUCEApplication::moreThanOneInstanceAllowed()
  11788. {
  11789. return true;
  11790. }
  11791. void JUCEApplication::anotherInstanceStarted (const String&)
  11792. {
  11793. }
  11794. void JUCEApplication::systemRequestedQuit()
  11795. {
  11796. quit();
  11797. }
  11798. void JUCEApplication::quit (const bool useMaximumForce)
  11799. {
  11800. MessageManager::getInstance()->postQuitMessage (useMaximumForce);
  11801. }
  11802. void JUCEApplication::setApplicationReturnValue (const int newReturnValue) throw()
  11803. {
  11804. appReturnValue = newReturnValue;
  11805. }
  11806. void JUCEApplication::unhandledException (const std::exception*,
  11807. const String&,
  11808. const int)
  11809. {
  11810. jassertfalse
  11811. }
  11812. void JUCEApplication::sendUnhandledException (const std::exception* const e,
  11813. const char* const sourceFile,
  11814. const int lineNumber)
  11815. {
  11816. if (appInstance != 0)
  11817. appInstance->unhandledException (e, sourceFile, lineNumber);
  11818. }
  11819. ApplicationCommandTarget* JUCEApplication::getNextCommandTarget()
  11820. {
  11821. return 0;
  11822. }
  11823. void JUCEApplication::getAllCommands (Array <CommandID>& commands)
  11824. {
  11825. commands.add (StandardApplicationCommandIDs::quit);
  11826. }
  11827. void JUCEApplication::getCommandInfo (const CommandID commandID, ApplicationCommandInfo& result)
  11828. {
  11829. if (commandID == StandardApplicationCommandIDs::quit)
  11830. {
  11831. result.setInfo ("Quit",
  11832. "Quits the application",
  11833. "Application",
  11834. 0);
  11835. result.defaultKeypresses.add (KeyPress (T('q'), ModifierKeys::commandModifier, 0));
  11836. }
  11837. }
  11838. bool JUCEApplication::perform (const InvocationInfo& info)
  11839. {
  11840. if (info.commandID == StandardApplicationCommandIDs::quit)
  11841. {
  11842. systemRequestedQuit();
  11843. return true;
  11844. }
  11845. return false;
  11846. }
  11847. int JUCEApplication::main (String& commandLine, JUCEApplication* const app)
  11848. {
  11849. jassert (appInstance == 0);
  11850. appInstance = app;
  11851. bool useForce = true;
  11852. initialiseJuce_GUI();
  11853. InterProcessLock* appLock = 0;
  11854. if (! app->moreThanOneInstanceAllowed())
  11855. {
  11856. appLock = new InterProcessLock ("juceAppLock_" + app->getApplicationName());
  11857. if (! appLock->enter(0))
  11858. {
  11859. MessageManager::broadcastMessage (app->getApplicationName() + "/" + commandLine);
  11860. delete appInstance;
  11861. appInstance = 0;
  11862. commandLine = String::empty;
  11863. DBG ("Another instance is running - quitting...");
  11864. return 0;
  11865. }
  11866. }
  11867. JUCE_TRY
  11868. {
  11869. juce_setCurrentThreadName ("Juce Message Thread");
  11870. // let the app do its setting-up..
  11871. app->initialise (commandLine.trim());
  11872. commandLine = String::empty;
  11873. // register for broadcast new app messages
  11874. MessageManager::getInstance()->registerBroadcastListener (app);
  11875. app->stillInitialising = false;
  11876. // now loop until a quit message is received..
  11877. useForce = MessageManager::getInstance()->runDispatchLoop();
  11878. MessageManager::getInstance()->deregisterBroadcastListener (app);
  11879. if (appLock != 0)
  11880. {
  11881. appLock->exit();
  11882. delete appLock;
  11883. }
  11884. }
  11885. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  11886. catch (const std::exception& e)
  11887. {
  11888. app->unhandledException (&e, __FILE__, __LINE__);
  11889. }
  11890. catch (...)
  11891. {
  11892. app->unhandledException (0, __FILE__, __LINE__);
  11893. }
  11894. #endif
  11895. return shutdownAppAndClearUp (useForce);
  11896. }
  11897. int JUCEApplication::shutdownAppAndClearUp (const bool useMaximumForce)
  11898. {
  11899. jassert (appInstance != 0);
  11900. JUCEApplication* const app = appInstance;
  11901. int returnValue = 0;
  11902. static bool reentrancyCheck = false;
  11903. if (! reentrancyCheck)
  11904. {
  11905. reentrancyCheck = true;
  11906. JUCE_TRY
  11907. {
  11908. // give the app a chance to clean up..
  11909. app->shutdown();
  11910. }
  11911. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  11912. catch (const std::exception& e)
  11913. {
  11914. app->unhandledException (&e, __FILE__, __LINE__);
  11915. }
  11916. catch (...)
  11917. {
  11918. app->unhandledException (0, __FILE__, __LINE__);
  11919. }
  11920. #endif
  11921. JUCE_TRY
  11922. {
  11923. shutdownJuce_GUI();
  11924. returnValue = app->getApplicationReturnValue();
  11925. appInstance = 0;
  11926. delete app;
  11927. }
  11928. JUCE_CATCH_ALL_ASSERT
  11929. if (useMaximumForce)
  11930. {
  11931. Process::terminate();
  11932. }
  11933. reentrancyCheck = false;
  11934. }
  11935. return returnValue;
  11936. }
  11937. int JUCEApplication::main (int argc, char* argv[],
  11938. JUCEApplication* const newApp)
  11939. {
  11940. juce_setCurrentExecutableFileName (argv[0]);
  11941. String cmd;
  11942. for (int i = 1; i < argc; ++i)
  11943. cmd << argv[i] << T(' ');
  11944. return JUCEApplication::main (cmd, newApp);
  11945. }
  11946. void JUCEApplication::actionListenerCallback (const String& message)
  11947. {
  11948. if (message.startsWith (getApplicationName() + "/"))
  11949. anotherInstanceStarted (message.substring (getApplicationName().length() + 1));
  11950. }
  11951. static bool juceInitialisedGUI = false;
  11952. void JUCE_PUBLIC_FUNCTION initialiseJuce_GUI()
  11953. {
  11954. if (! juceInitialisedGUI)
  11955. {
  11956. juceInitialisedGUI = true;
  11957. initialiseJuce_NonGUI();
  11958. MessageManager::getInstance();
  11959. Font::initialiseDefaultFontNames();
  11960. LookAndFeel::setDefaultLookAndFeel (0);
  11961. #if JUCE_WIN32 && JUCE_DEBUG
  11962. // This section is just for catching people who mess up their project settings and
  11963. // turn RTTI off..
  11964. try
  11965. {
  11966. TextButton tb (String::empty);
  11967. Component* c = &tb;
  11968. // Got an exception here? Then TURN ON RTTI in your compiler settings!!
  11969. c = dynamic_cast <Button*> (c);
  11970. }
  11971. catch (...)
  11972. {
  11973. // Ended up here? If so, TURN ON RTTI in your compiler settings!! And if you
  11974. // got as far as this catch statement, then why haven't you got exception catching
  11975. // turned on in the debugger???
  11976. jassertfalse
  11977. }
  11978. #endif
  11979. }
  11980. }
  11981. void JUCE_PUBLIC_FUNCTION shutdownJuce_GUI()
  11982. {
  11983. if (juceInitialisedGUI)
  11984. {
  11985. DeletedAtShutdown::deleteAll();
  11986. LookAndFeel::clearDefaultLookAndFeel();
  11987. shutdownJuce_NonGUI();
  11988. juceInitialisedGUI = false;
  11989. }
  11990. }
  11991. END_JUCE_NAMESPACE
  11992. /********* End of inlined file: juce_Application.cpp *********/
  11993. /********* Start of inlined file: juce_ApplicationCommandInfo.cpp *********/
  11994. BEGIN_JUCE_NAMESPACE
  11995. ApplicationCommandInfo::ApplicationCommandInfo (const CommandID commandID_) throw()
  11996. : commandID (commandID_),
  11997. flags (0)
  11998. {
  11999. }
  12000. void ApplicationCommandInfo::setInfo (const String& shortName_,
  12001. const String& description_,
  12002. const String& categoryName_,
  12003. const int flags_) throw()
  12004. {
  12005. shortName = shortName_;
  12006. description = description_;
  12007. categoryName = categoryName_;
  12008. flags = flags_;
  12009. }
  12010. void ApplicationCommandInfo::setActive (const bool b) throw()
  12011. {
  12012. if (b)
  12013. flags &= ~isDisabled;
  12014. else
  12015. flags |= isDisabled;
  12016. }
  12017. void ApplicationCommandInfo::setTicked (const bool b) throw()
  12018. {
  12019. if (b)
  12020. flags |= isTicked;
  12021. else
  12022. flags &= ~isTicked;
  12023. }
  12024. void ApplicationCommandInfo::addDefaultKeypress (const int keyCode, const ModifierKeys& modifiers) throw()
  12025. {
  12026. defaultKeypresses.add (KeyPress (keyCode, modifiers, 0));
  12027. }
  12028. END_JUCE_NAMESPACE
  12029. /********* End of inlined file: juce_ApplicationCommandInfo.cpp *********/
  12030. /********* Start of inlined file: juce_ApplicationCommandManager.cpp *********/
  12031. BEGIN_JUCE_NAMESPACE
  12032. ApplicationCommandManager::ApplicationCommandManager()
  12033. : listeners (8),
  12034. firstTarget (0)
  12035. {
  12036. keyMappings = new KeyPressMappingSet (this);
  12037. Desktop::getInstance().addFocusChangeListener (this);
  12038. }
  12039. ApplicationCommandManager::~ApplicationCommandManager()
  12040. {
  12041. Desktop::getInstance().removeFocusChangeListener (this);
  12042. deleteAndZero (keyMappings);
  12043. }
  12044. void ApplicationCommandManager::clearCommands()
  12045. {
  12046. commands.clear();
  12047. keyMappings->clearAllKeyPresses();
  12048. triggerAsyncUpdate();
  12049. }
  12050. void ApplicationCommandManager::registerCommand (const ApplicationCommandInfo& newCommand)
  12051. {
  12052. // zero isn't a valid command ID!
  12053. jassert (newCommand.commandID != 0);
  12054. // the name isn't optional!
  12055. jassert (newCommand.shortName.isNotEmpty());
  12056. if (getCommandForID (newCommand.commandID) == 0)
  12057. {
  12058. ApplicationCommandInfo* const newInfo = new ApplicationCommandInfo (newCommand);
  12059. newInfo->flags &= ~ApplicationCommandInfo::isTicked;
  12060. commands.add (newInfo);
  12061. keyMappings->resetToDefaultMapping (newCommand.commandID);
  12062. triggerAsyncUpdate();
  12063. }
  12064. else
  12065. {
  12066. // trying to re-register the same command with different parameters?
  12067. jassert (newCommand.shortName == getCommandForID (newCommand.commandID)->shortName
  12068. && (newCommand.description == getCommandForID (newCommand.commandID)->description || newCommand.description.isEmpty())
  12069. && newCommand.categoryName == getCommandForID (newCommand.commandID)->categoryName
  12070. && newCommand.defaultKeypresses == getCommandForID (newCommand.commandID)->defaultKeypresses
  12071. && (newCommand.flags & (ApplicationCommandInfo::wantsKeyUpDownCallbacks | ApplicationCommandInfo::hiddenFromKeyEditor | ApplicationCommandInfo::readOnlyInKeyEditor))
  12072. == (getCommandForID (newCommand.commandID)->flags & (ApplicationCommandInfo::wantsKeyUpDownCallbacks | ApplicationCommandInfo::hiddenFromKeyEditor | ApplicationCommandInfo::readOnlyInKeyEditor)));
  12073. }
  12074. }
  12075. void ApplicationCommandManager::registerAllCommandsForTarget (ApplicationCommandTarget* target)
  12076. {
  12077. if (target != 0)
  12078. {
  12079. Array <CommandID> commandIDs;
  12080. target->getAllCommands (commandIDs);
  12081. for (int i = 0; i < commandIDs.size(); ++i)
  12082. {
  12083. ApplicationCommandInfo info (commandIDs.getUnchecked(i));
  12084. target->getCommandInfo (info.commandID, info);
  12085. registerCommand (info);
  12086. }
  12087. }
  12088. }
  12089. void ApplicationCommandManager::removeCommand (const CommandID commandID)
  12090. {
  12091. for (int i = commands.size(); --i >= 0;)
  12092. {
  12093. if (commands.getUnchecked (i)->commandID == commandID)
  12094. {
  12095. commands.remove (i);
  12096. triggerAsyncUpdate();
  12097. const Array <KeyPress> keys (keyMappings->getKeyPressesAssignedToCommand (commandID));
  12098. for (int j = keys.size(); --j >= 0;)
  12099. keyMappings->removeKeyPress (keys.getReference (j));
  12100. }
  12101. }
  12102. }
  12103. void ApplicationCommandManager::commandStatusChanged()
  12104. {
  12105. triggerAsyncUpdate();
  12106. }
  12107. const ApplicationCommandInfo* ApplicationCommandManager::getCommandForID (const CommandID commandID) const throw()
  12108. {
  12109. for (int i = commands.size(); --i >= 0;)
  12110. if (commands.getUnchecked(i)->commandID == commandID)
  12111. return commands.getUnchecked(i);
  12112. return 0;
  12113. }
  12114. const String ApplicationCommandManager::getNameOfCommand (const CommandID commandID) const throw()
  12115. {
  12116. const ApplicationCommandInfo* const ci = getCommandForID (commandID);
  12117. return (ci != 0) ? ci->shortName : String::empty;
  12118. }
  12119. const String ApplicationCommandManager::getDescriptionOfCommand (const CommandID commandID) const throw()
  12120. {
  12121. const ApplicationCommandInfo* const ci = getCommandForID (commandID);
  12122. return (ci != 0) ? (ci->description.isNotEmpty() ? ci->description : ci->shortName)
  12123. : String::empty;
  12124. }
  12125. const StringArray ApplicationCommandManager::getCommandCategories() const throw()
  12126. {
  12127. StringArray s;
  12128. for (int i = 0; i < commands.size(); ++i)
  12129. s.addIfNotAlreadyThere (commands.getUnchecked(i)->categoryName, false);
  12130. return s;
  12131. }
  12132. const Array <CommandID> ApplicationCommandManager::getCommandsInCategory (const String& categoryName) const throw()
  12133. {
  12134. Array <CommandID> results (4);
  12135. for (int i = 0; i < commands.size(); ++i)
  12136. if (commands.getUnchecked(i)->categoryName == categoryName)
  12137. results.add (commands.getUnchecked(i)->commandID);
  12138. return results;
  12139. }
  12140. bool ApplicationCommandManager::invokeDirectly (const CommandID commandID, const bool asynchronously)
  12141. {
  12142. ApplicationCommandTarget::InvocationInfo info (commandID);
  12143. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::direct;
  12144. return invoke (info, asynchronously);
  12145. }
  12146. bool ApplicationCommandManager::invoke (const ApplicationCommandTarget::InvocationInfo& info_, const bool asynchronously)
  12147. {
  12148. // This call isn't thread-safe for use from a non-UI thread without locking the message
  12149. // manager first..
  12150. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  12151. ApplicationCommandTarget* const target = getFirstCommandTarget (info_.commandID);
  12152. if (target == 0)
  12153. return false;
  12154. ApplicationCommandInfo commandInfo (0);
  12155. target->getCommandInfo (info_.commandID, commandInfo);
  12156. ApplicationCommandTarget::InvocationInfo info (info_);
  12157. info.commandFlags = commandInfo.flags;
  12158. sendListenerInvokeCallback (info);
  12159. const bool ok = target->invoke (info, asynchronously);
  12160. commandStatusChanged();
  12161. return ok;
  12162. }
  12163. ApplicationCommandTarget* ApplicationCommandManager::getFirstCommandTarget (const CommandID)
  12164. {
  12165. return firstTarget != 0 ? firstTarget
  12166. : findDefaultComponentTarget();
  12167. }
  12168. void ApplicationCommandManager::setFirstCommandTarget (ApplicationCommandTarget* const newTarget) throw()
  12169. {
  12170. firstTarget = newTarget;
  12171. }
  12172. ApplicationCommandTarget* ApplicationCommandManager::getTargetForCommand (const CommandID commandID,
  12173. ApplicationCommandInfo& upToDateInfo)
  12174. {
  12175. ApplicationCommandTarget* target = getFirstCommandTarget (commandID);
  12176. if (target == 0)
  12177. target = JUCEApplication::getInstance();
  12178. if (target != 0)
  12179. target = target->getTargetForCommand (commandID);
  12180. if (target != 0)
  12181. target->getCommandInfo (commandID, upToDateInfo);
  12182. return target;
  12183. }
  12184. ApplicationCommandTarget* ApplicationCommandManager::findTargetForComponent (Component* c)
  12185. {
  12186. ApplicationCommandTarget* target = dynamic_cast <ApplicationCommandTarget*> (c);
  12187. if (target == 0 && c != 0)
  12188. // (unable to use the syntax findParentComponentOfClass <ApplicationCommandTarget> () because of a VC6 compiler bug)
  12189. target = c->findParentComponentOfClass ((ApplicationCommandTarget*) 0);
  12190. return target;
  12191. }
  12192. ApplicationCommandTarget* ApplicationCommandManager::findDefaultComponentTarget()
  12193. {
  12194. Component* c = Component::getCurrentlyFocusedComponent();
  12195. if (c == 0)
  12196. {
  12197. TopLevelWindow* const activeWindow = TopLevelWindow::getActiveTopLevelWindow();
  12198. if (activeWindow != 0)
  12199. {
  12200. c = activeWindow->getPeer()->getLastFocusedSubcomponent();
  12201. if (c == 0)
  12202. c = activeWindow;
  12203. }
  12204. }
  12205. if (c == 0)
  12206. {
  12207. // getting a bit desperate now - try all desktop comps..
  12208. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  12209. {
  12210. ApplicationCommandTarget* const target
  12211. = findTargetForComponent (Desktop::getInstance().getComponent (i)
  12212. ->getPeer()->getLastFocusedSubcomponent());
  12213. if (target != 0)
  12214. return target;
  12215. }
  12216. }
  12217. if (c != 0)
  12218. {
  12219. ResizableWindow* const resizableWindow = dynamic_cast <ResizableWindow*> (c);
  12220. // if we're focused on a ResizableWindow, chances are that it's the content
  12221. // component that really should get the event. And if not, the event will
  12222. // still be passed up to the top level window anyway, so let's send it to the
  12223. // content comp.
  12224. if (resizableWindow != 0 && resizableWindow->getContentComponent() != 0)
  12225. c = resizableWindow->getContentComponent();
  12226. ApplicationCommandTarget* const target = findTargetForComponent (c);
  12227. if (target != 0)
  12228. return target;
  12229. }
  12230. return JUCEApplication::getInstance();
  12231. }
  12232. void ApplicationCommandManager::addListener (ApplicationCommandManagerListener* const listener) throw()
  12233. {
  12234. jassert (listener != 0);
  12235. if (listener != 0)
  12236. listeners.add (listener);
  12237. }
  12238. void ApplicationCommandManager::removeListener (ApplicationCommandManagerListener* const listener) throw()
  12239. {
  12240. listeners.removeValue (listener);
  12241. }
  12242. void ApplicationCommandManager::sendListenerInvokeCallback (const ApplicationCommandTarget::InvocationInfo& info) const
  12243. {
  12244. for (int i = listeners.size(); --i >= 0;)
  12245. {
  12246. ((ApplicationCommandManagerListener*) listeners.getUnchecked (i))->applicationCommandInvoked (info);
  12247. i = jmin (i, listeners.size());
  12248. }
  12249. }
  12250. void ApplicationCommandManager::handleAsyncUpdate()
  12251. {
  12252. for (int i = listeners.size(); --i >= 0;)
  12253. {
  12254. ((ApplicationCommandManagerListener*) listeners.getUnchecked (i))->applicationCommandListChanged();
  12255. i = jmin (i, listeners.size());
  12256. }
  12257. }
  12258. void ApplicationCommandManager::globalFocusChanged (Component*)
  12259. {
  12260. commandStatusChanged();
  12261. }
  12262. END_JUCE_NAMESPACE
  12263. /********* End of inlined file: juce_ApplicationCommandManager.cpp *********/
  12264. /********* Start of inlined file: juce_ApplicationCommandTarget.cpp *********/
  12265. BEGIN_JUCE_NAMESPACE
  12266. ApplicationCommandTarget::ApplicationCommandTarget()
  12267. : messageInvoker (0)
  12268. {
  12269. }
  12270. ApplicationCommandTarget::~ApplicationCommandTarget()
  12271. {
  12272. deleteAndZero (messageInvoker);
  12273. }
  12274. bool ApplicationCommandTarget::tryToInvoke (const InvocationInfo& info, const bool async)
  12275. {
  12276. if (isCommandActive (info.commandID))
  12277. {
  12278. if (async)
  12279. {
  12280. if (messageInvoker == 0)
  12281. messageInvoker = new CommandTargetMessageInvoker (this);
  12282. messageInvoker->postMessage (new Message (0, 0, 0, new ApplicationCommandTarget::InvocationInfo (info)));
  12283. return true;
  12284. }
  12285. else
  12286. {
  12287. const bool success = perform (info);
  12288. jassert (success); // hmm - your target should have been able to perform this command. If it can't
  12289. // do it at the moment for some reason, it should clear the 'isActive' flag when it
  12290. // returns the command's info.
  12291. return success;
  12292. }
  12293. }
  12294. return false;
  12295. }
  12296. ApplicationCommandTarget* ApplicationCommandTarget::findFirstTargetParentComponent()
  12297. {
  12298. Component* c = dynamic_cast <Component*> (this);
  12299. if (c != 0)
  12300. // (unable to use the syntax findParentComponentOfClass <ApplicationCommandTarget> () because of a VC6 compiler bug)
  12301. return c->findParentComponentOfClass ((ApplicationCommandTarget*) 0);
  12302. return 0;
  12303. }
  12304. ApplicationCommandTarget* ApplicationCommandTarget::getTargetForCommand (const CommandID commandID)
  12305. {
  12306. ApplicationCommandTarget* target = this;
  12307. int depth = 0;
  12308. while (target != 0)
  12309. {
  12310. Array <CommandID> commandIDs;
  12311. target->getAllCommands (commandIDs);
  12312. if (commandIDs.contains (commandID))
  12313. return target;
  12314. target = target->getNextCommandTarget();
  12315. ++depth;
  12316. jassert (depth < 100); // could be a recursive command chain??
  12317. jassert (target != this); // definitely a recursive command chain!
  12318. if (depth > 100 || target == this)
  12319. break;
  12320. }
  12321. if (target == 0)
  12322. {
  12323. target = JUCEApplication::getInstance();
  12324. if (target != 0)
  12325. {
  12326. Array <CommandID> commandIDs;
  12327. target->getAllCommands (commandIDs);
  12328. if (commandIDs.contains (commandID))
  12329. return target;
  12330. }
  12331. }
  12332. return 0;
  12333. }
  12334. bool ApplicationCommandTarget::isCommandActive (const CommandID commandID)
  12335. {
  12336. ApplicationCommandInfo info (commandID);
  12337. info.flags = ApplicationCommandInfo::isDisabled;
  12338. getCommandInfo (commandID, info);
  12339. return (info.flags & ApplicationCommandInfo::isDisabled) == 0;
  12340. }
  12341. bool ApplicationCommandTarget::invoke (const InvocationInfo& info, const bool async)
  12342. {
  12343. ApplicationCommandTarget* target = this;
  12344. int depth = 0;
  12345. while (target != 0)
  12346. {
  12347. if (target->tryToInvoke (info, async))
  12348. return true;
  12349. target = target->getNextCommandTarget();
  12350. ++depth;
  12351. jassert (depth < 100); // could be a recursive command chain??
  12352. jassert (target != this); // definitely a recursive command chain!
  12353. if (depth > 100 || target == this)
  12354. break;
  12355. }
  12356. if (target == 0)
  12357. {
  12358. target = JUCEApplication::getInstance();
  12359. if (target != 0)
  12360. return target->tryToInvoke (info, async);
  12361. }
  12362. return false;
  12363. }
  12364. bool ApplicationCommandTarget::invokeDirectly (const CommandID commandID, const bool asynchronously)
  12365. {
  12366. ApplicationCommandTarget::InvocationInfo info (commandID);
  12367. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::direct;
  12368. return invoke (info, asynchronously);
  12369. }
  12370. ApplicationCommandTarget::InvocationInfo::InvocationInfo (const CommandID commandID_) throw()
  12371. : commandID (commandID_),
  12372. commandFlags (0),
  12373. invocationMethod (direct),
  12374. originatingComponent (0),
  12375. isKeyDown (false),
  12376. millisecsSinceKeyPressed (0)
  12377. {
  12378. }
  12379. ApplicationCommandTarget::CommandTargetMessageInvoker::CommandTargetMessageInvoker (ApplicationCommandTarget* const owner_)
  12380. : owner (owner_)
  12381. {
  12382. }
  12383. ApplicationCommandTarget::CommandTargetMessageInvoker::~CommandTargetMessageInvoker()
  12384. {
  12385. }
  12386. void ApplicationCommandTarget::CommandTargetMessageInvoker::handleMessage (const Message& message)
  12387. {
  12388. InvocationInfo* const info = (InvocationInfo*) message.pointerParameter;
  12389. owner->tryToInvoke (*info, false);
  12390. delete info;
  12391. }
  12392. END_JUCE_NAMESPACE
  12393. /********* End of inlined file: juce_ApplicationCommandTarget.cpp *********/
  12394. /********* Start of inlined file: juce_ApplicationProperties.cpp *********/
  12395. BEGIN_JUCE_NAMESPACE
  12396. juce_ImplementSingleton (ApplicationProperties)
  12397. ApplicationProperties::ApplicationProperties() throw()
  12398. : userProps (0),
  12399. commonProps (0),
  12400. msBeforeSaving (3000),
  12401. options (PropertiesFile::storeAsBinary),
  12402. commonSettingsAreReadOnly (0)
  12403. {
  12404. }
  12405. ApplicationProperties::~ApplicationProperties()
  12406. {
  12407. closeFiles();
  12408. clearSingletonInstance();
  12409. }
  12410. void ApplicationProperties::setStorageParameters (const String& applicationName,
  12411. const String& fileNameSuffix,
  12412. const String& folderName_,
  12413. const int millisecondsBeforeSaving,
  12414. const int propertiesFileOptions) throw()
  12415. {
  12416. appName = applicationName;
  12417. fileSuffix = fileNameSuffix;
  12418. folderName = folderName_;
  12419. msBeforeSaving = millisecondsBeforeSaving;
  12420. options = propertiesFileOptions;
  12421. }
  12422. bool ApplicationProperties::testWriteAccess (const bool testUserSettings,
  12423. const bool testCommonSettings,
  12424. const bool showWarningDialogOnFailure)
  12425. {
  12426. const bool userOk = (! testUserSettings) || getUserSettings()->save();
  12427. const bool commonOk = (! testCommonSettings) || getCommonSettings (false)->save();
  12428. if (! (userOk && commonOk))
  12429. {
  12430. if (showWarningDialogOnFailure)
  12431. {
  12432. String filenames;
  12433. if (userProps != 0 && ! userOk)
  12434. filenames << '\n' << userProps->getFile().getFullPathName();
  12435. if (commonProps != 0 && ! commonOk)
  12436. filenames << '\n' << commonProps->getFile().getFullPathName();
  12437. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  12438. appName + TRANS(" - Unable to save settings"),
  12439. TRANS("An error occurred when trying to save the application's settings file...\n\nIn order to save and restore its settings, ")
  12440. + appName + TRANS(" needs to be able to write to the following files:\n")
  12441. + filenames
  12442. + TRANS("\n\nMake sure that these files aren't read-only, and that the disk isn't full."));
  12443. }
  12444. return false;
  12445. }
  12446. return true;
  12447. }
  12448. void ApplicationProperties::openFiles() throw()
  12449. {
  12450. // You need to call setStorageParameters() before trying to get hold of the
  12451. // properties!
  12452. jassert (appName.isNotEmpty());
  12453. if (appName.isNotEmpty())
  12454. {
  12455. if (userProps == 0)
  12456. userProps = PropertiesFile::createDefaultAppPropertiesFile (appName, fileSuffix, folderName,
  12457. false, msBeforeSaving, options);
  12458. if (commonProps == 0)
  12459. commonProps = PropertiesFile::createDefaultAppPropertiesFile (appName, fileSuffix, folderName,
  12460. true, msBeforeSaving, options);
  12461. userProps->setFallbackPropertySet (commonProps);
  12462. }
  12463. }
  12464. PropertiesFile* ApplicationProperties::getUserSettings() throw()
  12465. {
  12466. if (userProps == 0)
  12467. openFiles();
  12468. return userProps;
  12469. }
  12470. PropertiesFile* ApplicationProperties::getCommonSettings (const bool returnUserPropsIfReadOnly) throw()
  12471. {
  12472. if (commonProps == 0)
  12473. openFiles();
  12474. if (returnUserPropsIfReadOnly)
  12475. {
  12476. if (commonSettingsAreReadOnly == 0)
  12477. commonSettingsAreReadOnly = commonProps->save() ? -1 : 1;
  12478. if (commonSettingsAreReadOnly > 0)
  12479. return userProps;
  12480. }
  12481. return commonProps;
  12482. }
  12483. bool ApplicationProperties::saveIfNeeded()
  12484. {
  12485. return (userProps == 0 || userProps->saveIfNeeded())
  12486. && (commonProps == 0 || commonProps->saveIfNeeded());
  12487. }
  12488. void ApplicationProperties::closeFiles()
  12489. {
  12490. deleteAndZero (userProps);
  12491. deleteAndZero (commonProps);
  12492. }
  12493. END_JUCE_NAMESPACE
  12494. /********* End of inlined file: juce_ApplicationProperties.cpp *********/
  12495. /********* Start of inlined file: juce_DeletedAtShutdown.cpp *********/
  12496. BEGIN_JUCE_NAMESPACE
  12497. static VoidArray objectsToDelete (16);
  12498. static CriticalSection lock;
  12499. DeletedAtShutdown::DeletedAtShutdown() throw()
  12500. {
  12501. const ScopedLock sl (lock);
  12502. objectsToDelete.add (this);
  12503. }
  12504. DeletedAtShutdown::~DeletedAtShutdown()
  12505. {
  12506. const ScopedLock sl (lock);
  12507. objectsToDelete.removeValue (this);
  12508. }
  12509. void DeletedAtShutdown::deleteAll()
  12510. {
  12511. // make a local copy of the array, so it can't get into a loop if something
  12512. // creates another DeletedAtShutdown object during its destructor.
  12513. lock.enter();
  12514. const VoidArray localCopy (objectsToDelete);
  12515. lock.exit();
  12516. for (int i = localCopy.size(); --i >= 0;)
  12517. {
  12518. JUCE_TRY
  12519. {
  12520. DeletedAtShutdown* const deletee = (DeletedAtShutdown*) localCopy.getUnchecked(i);
  12521. // double-check that it's not already been deleted during another object's destructor.
  12522. lock.enter();
  12523. const bool okToDelete = objectsToDelete.contains (deletee);
  12524. lock.exit();
  12525. if (okToDelete)
  12526. delete deletee;
  12527. }
  12528. JUCE_CATCH_EXCEPTION
  12529. }
  12530. // if no objects got re-created during shutdown, this should have been emptied by their
  12531. // destructors
  12532. jassert (objectsToDelete.size() == 0);
  12533. objectsToDelete.clear(); // just to make sure the array doesn't have any memory still allocated
  12534. }
  12535. END_JUCE_NAMESPACE
  12536. /********* End of inlined file: juce_DeletedAtShutdown.cpp *********/
  12537. /********* Start of inlined file: juce_PropertiesFile.cpp *********/
  12538. BEGIN_JUCE_NAMESPACE
  12539. static const int propFileMagicNumber = ((int) littleEndianInt ("PROP"));
  12540. static const int propFileMagicNumberCompressed = ((int) littleEndianInt ("CPRP"));
  12541. static const tchar* const propertyFileXmlTag = T("PROPERTIES");
  12542. static const tchar* const propertyTagName = T("VALUE");
  12543. PropertiesFile::PropertiesFile (const File& f,
  12544. const int millisecondsBeforeSaving,
  12545. const int options_) throw()
  12546. : PropertySet (ignoreCaseOfKeyNames),
  12547. file (f),
  12548. timerInterval (millisecondsBeforeSaving),
  12549. options (options_),
  12550. needsWriting (false)
  12551. {
  12552. // You need to correctly specify just one storage format for the file
  12553. jassert ((options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsBinary
  12554. || (options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsCompressedBinary
  12555. || (options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsXML);
  12556. InputStream* fileStream = f.createInputStream();
  12557. if (fileStream != 0)
  12558. {
  12559. int magicNumber = fileStream->readInt();
  12560. if (magicNumber == propFileMagicNumberCompressed)
  12561. {
  12562. fileStream = new SubregionStream (fileStream, 4, -1, true);
  12563. fileStream = new GZIPDecompressorInputStream (fileStream, true);
  12564. magicNumber = propFileMagicNumber;
  12565. }
  12566. if (magicNumber == propFileMagicNumber)
  12567. {
  12568. BufferedInputStream in (fileStream, 2048, true);
  12569. int numValues = in.readInt();
  12570. while (--numValues >= 0 && ! in.isExhausted())
  12571. {
  12572. const String key (in.readString());
  12573. const String value (in.readString());
  12574. jassert (key.isNotEmpty());
  12575. if (key.isNotEmpty())
  12576. getAllProperties().set (key, value);
  12577. }
  12578. }
  12579. else
  12580. {
  12581. // Not a binary props file - let's see if it's XML..
  12582. delete fileStream;
  12583. XmlDocument parser (f);
  12584. XmlElement* doc = parser.getDocumentElement (true);
  12585. if (doc != 0 && doc->hasTagName (propertyFileXmlTag))
  12586. {
  12587. delete doc;
  12588. doc = parser.getDocumentElement();
  12589. if (doc != 0)
  12590. {
  12591. forEachXmlChildElementWithTagName (*doc, e, propertyTagName)
  12592. {
  12593. const String name (e->getStringAttribute (T("name")));
  12594. if (name.isNotEmpty())
  12595. getAllProperties().set (name, e->getStringAttribute (T("val")));
  12596. }
  12597. }
  12598. else
  12599. {
  12600. // must be a pretty broken XML file we're trying to parse here!
  12601. jassertfalse
  12602. }
  12603. delete doc;
  12604. }
  12605. }
  12606. }
  12607. }
  12608. PropertiesFile::~PropertiesFile()
  12609. {
  12610. saveIfNeeded();
  12611. }
  12612. bool PropertiesFile::saveIfNeeded()
  12613. {
  12614. const ScopedLock sl (getLock());
  12615. return (! needsWriting) || save();
  12616. }
  12617. bool PropertiesFile::needsToBeSaved() const throw()
  12618. {
  12619. const ScopedLock sl (getLock());
  12620. return needsWriting;
  12621. }
  12622. bool PropertiesFile::save()
  12623. {
  12624. const ScopedLock sl (getLock());
  12625. stopTimer();
  12626. if (file == File::nonexistent
  12627. || file.isDirectory()
  12628. || ! file.getParentDirectory().createDirectory())
  12629. return false;
  12630. if ((options & storeAsXML) != 0)
  12631. {
  12632. XmlElement* const doc = new XmlElement (propertyFileXmlTag);
  12633. for (int i = 0; i < getAllProperties().size(); ++i)
  12634. {
  12635. XmlElement* const e = new XmlElement (propertyTagName);
  12636. e->setAttribute (T("name"), getAllProperties().getAllKeys() [i]);
  12637. e->setAttribute (T("val"), getAllProperties().getAllValues() [i]);
  12638. doc->addChildElement (e);
  12639. }
  12640. const bool ok = doc->writeToFile (file, String::empty);
  12641. delete doc;
  12642. return ok;
  12643. }
  12644. else
  12645. {
  12646. const File tempFile (file.getNonexistentSibling (false));
  12647. OutputStream* out = tempFile.createOutputStream();
  12648. if (out != 0)
  12649. {
  12650. if ((options & storeAsCompressedBinary) != 0)
  12651. {
  12652. out->writeInt (propFileMagicNumberCompressed);
  12653. out->flush();
  12654. out = new GZIPCompressorOutputStream (out, 9, true);
  12655. }
  12656. else
  12657. {
  12658. // have you set up the storage option flags correctly?
  12659. jassert ((options & storeAsBinary) != 0);
  12660. out->writeInt (propFileMagicNumber);
  12661. }
  12662. const int numProperties = getAllProperties().size();
  12663. out->writeInt (numProperties);
  12664. for (int i = 0; i < numProperties; ++i)
  12665. {
  12666. out->writeString (getAllProperties().getAllKeys() [i]);
  12667. out->writeString (getAllProperties().getAllValues() [i]);
  12668. }
  12669. out->flush();
  12670. delete out;
  12671. if (tempFile.moveFileTo (file))
  12672. {
  12673. needsWriting = false;
  12674. return true;
  12675. }
  12676. tempFile.deleteFile();
  12677. }
  12678. }
  12679. return false;
  12680. }
  12681. void PropertiesFile::timerCallback()
  12682. {
  12683. saveIfNeeded();
  12684. }
  12685. void PropertiesFile::propertyChanged()
  12686. {
  12687. sendChangeMessage (this);
  12688. needsWriting = true;
  12689. if (timerInterval > 0)
  12690. startTimer (timerInterval);
  12691. else if (timerInterval == 0)
  12692. saveIfNeeded();
  12693. }
  12694. const File PropertiesFile::getFile() const throw()
  12695. {
  12696. return file;
  12697. }
  12698. const File PropertiesFile::getDefaultAppSettingsFile (const String& applicationName,
  12699. const String& fileNameSuffix,
  12700. const String& folderName,
  12701. const bool commonToAllUsers)
  12702. {
  12703. // mustn't have illegal characters in this name..
  12704. jassert (applicationName == File::createLegalFileName (applicationName));
  12705. #if JUCE_MAC
  12706. File dir (commonToAllUsers ? "/Library/Preferences"
  12707. : "~/Library/Preferences");
  12708. if (folderName.isNotEmpty())
  12709. dir = dir.getChildFile (folderName);
  12710. #endif
  12711. #ifdef JUCE_LINUX
  12712. const File dir ((commonToAllUsers ? T("/var/") : T("~/"))
  12713. + (folderName.isNotEmpty() ? folderName
  12714. : (T(".") + applicationName)));
  12715. #endif
  12716. #if JUCE_WIN32
  12717. File dir (File::getSpecialLocation (commonToAllUsers ? File::commonApplicationDataDirectory
  12718. : File::userApplicationDataDirectory));
  12719. if (dir == File::nonexistent)
  12720. return File::nonexistent;
  12721. dir = dir.getChildFile (folderName.isNotEmpty() ? folderName
  12722. : applicationName);
  12723. #endif
  12724. return dir.getChildFile (applicationName)
  12725. .withFileExtension (fileNameSuffix);
  12726. }
  12727. PropertiesFile* PropertiesFile::createDefaultAppPropertiesFile (const String& applicationName,
  12728. const String& fileNameSuffix,
  12729. const String& folderName,
  12730. const bool commonToAllUsers,
  12731. const int millisecondsBeforeSaving,
  12732. const int propertiesFileOptions)
  12733. {
  12734. const File file (getDefaultAppSettingsFile (applicationName,
  12735. fileNameSuffix,
  12736. folderName,
  12737. commonToAllUsers));
  12738. jassert (file != File::nonexistent);
  12739. if (file == File::nonexistent)
  12740. return 0;
  12741. return new PropertiesFile (file, millisecondsBeforeSaving, propertiesFileOptions);
  12742. }
  12743. END_JUCE_NAMESPACE
  12744. /********* End of inlined file: juce_PropertiesFile.cpp *********/
  12745. /********* Start of inlined file: juce_AiffAudioFormat.cpp *********/
  12746. BEGIN_JUCE_NAMESPACE
  12747. #undef chunkName
  12748. #define chunkName(a) (int)littleEndianInt(a)
  12749. #define aiffFormatName TRANS("AIFF file")
  12750. static const tchar* const aiffExtensions[] = { T(".aiff"), T(".aif"), 0 };
  12751. class AiffAudioFormatReader : public AudioFormatReader
  12752. {
  12753. public:
  12754. int bytesPerFrame;
  12755. int64 dataChunkStart;
  12756. bool littleEndian;
  12757. AiffAudioFormatReader (InputStream* in)
  12758. : AudioFormatReader (in, aiffFormatName)
  12759. {
  12760. if (input->readInt() == chunkName ("FORM"))
  12761. {
  12762. const int len = input->readIntBigEndian();
  12763. const int64 end = input->getPosition() + len;
  12764. const int nextType = input->readInt();
  12765. if (nextType == chunkName ("AIFF") || nextType == chunkName ("AIFC"))
  12766. {
  12767. bool hasGotVer = false;
  12768. bool hasGotData = false;
  12769. bool hasGotType = false;
  12770. while (input->getPosition() < end)
  12771. {
  12772. const int type = input->readInt();
  12773. const uint32 length = (uint32) input->readIntBigEndian();
  12774. const int64 chunkEnd = input->getPosition() + length;
  12775. if (type == chunkName ("FVER"))
  12776. {
  12777. hasGotVer = true;
  12778. const int ver = input->readIntBigEndian();
  12779. if (ver != 0 && ver != (int)0xa2805140)
  12780. break;
  12781. }
  12782. else if (type == chunkName ("COMM"))
  12783. {
  12784. hasGotType = true;
  12785. numChannels = (unsigned int)input->readShortBigEndian();
  12786. lengthInSamples = input->readIntBigEndian();
  12787. bitsPerSample = input->readShortBigEndian();
  12788. bytesPerFrame = (numChannels * bitsPerSample) >> 3;
  12789. unsigned char sampleRateBytes[10];
  12790. input->read (sampleRateBytes, 10);
  12791. const int byte0 = sampleRateBytes[0];
  12792. if ((byte0 & 0x80) != 0
  12793. || byte0 <= 0x3F || byte0 > 0x40
  12794. || (byte0 == 0x40 && sampleRateBytes[1] > 0x1C))
  12795. break;
  12796. unsigned int sampRate = bigEndianInt ((char*) sampleRateBytes + 2);
  12797. sampRate >>= (16414 - bigEndianShort ((char*) sampleRateBytes));
  12798. sampleRate = (int)sampRate;
  12799. if (length <= 18)
  12800. {
  12801. // some types don't have a chunk large enough to include a compression
  12802. // type, so assume it's just big-endian pcm
  12803. littleEndian = false;
  12804. }
  12805. else
  12806. {
  12807. const int compType = input->readInt();
  12808. if (compType == chunkName ("NONE") || compType == chunkName ("twos"))
  12809. {
  12810. littleEndian = false;
  12811. }
  12812. else if (compType == chunkName ("sowt"))
  12813. {
  12814. littleEndian = true;
  12815. }
  12816. else
  12817. {
  12818. sampleRate = 0;
  12819. break;
  12820. }
  12821. }
  12822. }
  12823. else if (type == chunkName ("SSND"))
  12824. {
  12825. hasGotData = true;
  12826. const int offset = input->readIntBigEndian();
  12827. dataChunkStart = input->getPosition() + 4 + offset;
  12828. lengthInSamples = (bytesPerFrame > 0) ? jmin (lengthInSamples, (int64) (length / bytesPerFrame)) : 0;
  12829. }
  12830. else if ((hasGotVer && hasGotData && hasGotType)
  12831. || chunkEnd < input->getPosition()
  12832. || input->isExhausted())
  12833. {
  12834. break;
  12835. }
  12836. input->setPosition (chunkEnd);
  12837. }
  12838. }
  12839. }
  12840. }
  12841. ~AiffAudioFormatReader()
  12842. {
  12843. }
  12844. bool read (int** destSamples,
  12845. int64 startSampleInFile,
  12846. int numSamples)
  12847. {
  12848. int64 start = startSampleInFile;
  12849. int startOffsetInDestBuffer = 0;
  12850. if (startSampleInFile < 0)
  12851. {
  12852. const int silence = (int) jmin (-startSampleInFile, (int64) numSamples);
  12853. int** destChan = destSamples;
  12854. for (int i = 2; --i >= 0;)
  12855. {
  12856. if (*destChan != 0)
  12857. {
  12858. zeromem (*destChan, sizeof (int) * silence);
  12859. ++destChan;
  12860. }
  12861. }
  12862. startOffsetInDestBuffer += silence;
  12863. numSamples -= silence;
  12864. start = 0;
  12865. }
  12866. int numToDo = jlimit (0, numSamples, (int) (lengthInSamples - start));
  12867. if (numToDo > 0)
  12868. {
  12869. input->setPosition (dataChunkStart + start * bytesPerFrame);
  12870. int num = numToDo;
  12871. int* left = destSamples[0];
  12872. if (left != 0)
  12873. left += startOffsetInDestBuffer;
  12874. int* right = destSamples[1];
  12875. if (right != 0)
  12876. right += startOffsetInDestBuffer;
  12877. // (keep this a multiple of 3)
  12878. const int tempBufSize = 1440 * 4;
  12879. char tempBuffer [tempBufSize];
  12880. while (num > 0)
  12881. {
  12882. const int numThisTime = jmin (tempBufSize / bytesPerFrame, num);
  12883. const int bytesRead = input->read (tempBuffer, numThisTime * bytesPerFrame);
  12884. if (bytesRead < numThisTime * bytesPerFrame)
  12885. zeromem (tempBuffer + bytesRead, numThisTime * bytesPerFrame - bytesRead);
  12886. if (bitsPerSample == 16)
  12887. {
  12888. if (littleEndian)
  12889. {
  12890. const short* src = (const short*) tempBuffer;
  12891. if (numChannels > 1)
  12892. {
  12893. if (left == 0)
  12894. {
  12895. for (int i = numThisTime; --i >= 0;)
  12896. {
  12897. *right++ = (int) swapIfBigEndian ((unsigned short) *src++) << 16;
  12898. ++src;
  12899. }
  12900. }
  12901. else if (right == 0)
  12902. {
  12903. for (int i = numThisTime; --i >= 0;)
  12904. {
  12905. ++src;
  12906. *left++ = (int) swapIfBigEndian ((unsigned short) *src++) << 16;
  12907. }
  12908. }
  12909. else
  12910. {
  12911. for (int i = numThisTime; --i >= 0;)
  12912. {
  12913. *left++ = (int) swapIfBigEndian ((unsigned short) *src++) << 16;
  12914. *right++ = (int) swapIfBigEndian ((unsigned short) *src++) << 16;
  12915. }
  12916. }
  12917. }
  12918. else
  12919. {
  12920. for (int i = numThisTime; --i >= 0;)
  12921. {
  12922. *left++ = (int) swapIfBigEndian ((unsigned short) *src++) << 16;
  12923. }
  12924. }
  12925. }
  12926. else
  12927. {
  12928. const char* src = (const char*) tempBuffer;
  12929. if (numChannels > 1)
  12930. {
  12931. if (left == 0)
  12932. {
  12933. for (int i = numThisTime; --i >= 0;)
  12934. {
  12935. *right++ = bigEndianShort (src) << 16;
  12936. src += 4;
  12937. }
  12938. }
  12939. else if (right == 0)
  12940. {
  12941. for (int i = numThisTime; --i >= 0;)
  12942. {
  12943. src += 2;
  12944. *left++ = bigEndianShort (src) << 16;
  12945. src += 2;
  12946. }
  12947. }
  12948. else
  12949. {
  12950. for (int i = numThisTime; --i >= 0;)
  12951. {
  12952. *left++ = bigEndianShort (src) << 16;
  12953. src += 2;
  12954. *right++ = bigEndianShort (src) << 16;
  12955. src += 2;
  12956. }
  12957. }
  12958. }
  12959. else
  12960. {
  12961. for (int i = numThisTime; --i >= 0;)
  12962. {
  12963. *left++ = bigEndianShort (src) << 16;
  12964. src += 2;
  12965. }
  12966. }
  12967. }
  12968. }
  12969. else if (bitsPerSample == 24)
  12970. {
  12971. const char* src = (const char*)tempBuffer;
  12972. if (littleEndian)
  12973. {
  12974. if (numChannels > 1)
  12975. {
  12976. if (left == 0)
  12977. {
  12978. for (int i = numThisTime; --i >= 0;)
  12979. {
  12980. *right++ = littleEndian24Bit (src) << 8;
  12981. src += 6;
  12982. }
  12983. }
  12984. else if (right == 0)
  12985. {
  12986. for (int i = numThisTime; --i >= 0;)
  12987. {
  12988. src += 3;
  12989. *left++ = littleEndian24Bit (src) << 8;
  12990. src += 3;
  12991. }
  12992. }
  12993. else
  12994. {
  12995. for (int i = numThisTime; --i >= 0;)
  12996. {
  12997. *left++ = littleEndian24Bit (src) << 8;
  12998. src += 3;
  12999. *right++ = littleEndian24Bit (src) << 8;
  13000. src += 3;
  13001. }
  13002. }
  13003. }
  13004. else
  13005. {
  13006. for (int i = numThisTime; --i >= 0;)
  13007. {
  13008. *left++ = littleEndian24Bit (src) << 8;
  13009. src += 3;
  13010. }
  13011. }
  13012. }
  13013. else
  13014. {
  13015. if (numChannels > 1)
  13016. {
  13017. if (left == 0)
  13018. {
  13019. for (int i = numThisTime; --i >= 0;)
  13020. {
  13021. *right++ = bigEndian24Bit (src) << 8;
  13022. src += 6;
  13023. }
  13024. }
  13025. else if (right == 0)
  13026. {
  13027. for (int i = numThisTime; --i >= 0;)
  13028. {
  13029. src += 3;
  13030. *left++ = bigEndian24Bit (src) << 8;
  13031. src += 3;
  13032. }
  13033. }
  13034. else
  13035. {
  13036. for (int i = numThisTime; --i >= 0;)
  13037. {
  13038. *left++ = bigEndian24Bit (src) << 8;
  13039. src += 3;
  13040. *right++ = bigEndian24Bit (src) << 8;
  13041. src += 3;
  13042. }
  13043. }
  13044. }
  13045. else
  13046. {
  13047. for (int i = numThisTime; --i >= 0;)
  13048. {
  13049. *left++ = bigEndian24Bit (src) << 8;
  13050. src += 3;
  13051. }
  13052. }
  13053. }
  13054. }
  13055. else if (bitsPerSample == 32)
  13056. {
  13057. const unsigned int* src = (const unsigned int*) tempBuffer;
  13058. unsigned int* l = (unsigned int*) left;
  13059. unsigned int* r = (unsigned int*) right;
  13060. if (littleEndian)
  13061. {
  13062. if (numChannels > 1)
  13063. {
  13064. if (l == 0)
  13065. {
  13066. for (int i = numThisTime; --i >= 0;)
  13067. {
  13068. ++src;
  13069. *r++ = swapIfBigEndian (*src++);
  13070. }
  13071. }
  13072. else if (r == 0)
  13073. {
  13074. for (int i = numThisTime; --i >= 0;)
  13075. {
  13076. *l++ = swapIfBigEndian (*src++);
  13077. ++src;
  13078. }
  13079. }
  13080. else
  13081. {
  13082. for (int i = numThisTime; --i >= 0;)
  13083. {
  13084. *l++ = swapIfBigEndian (*src++);
  13085. *r++ = swapIfBigEndian (*src++);
  13086. }
  13087. }
  13088. }
  13089. else
  13090. {
  13091. for (int i = numThisTime; --i >= 0;)
  13092. {
  13093. *l++ = swapIfBigEndian (*src++);
  13094. }
  13095. }
  13096. }
  13097. else
  13098. {
  13099. if (numChannels > 1)
  13100. {
  13101. if (l == 0)
  13102. {
  13103. for (int i = numThisTime; --i >= 0;)
  13104. {
  13105. ++src;
  13106. *r++ = swapIfLittleEndian (*src++);
  13107. }
  13108. }
  13109. else if (r == 0)
  13110. {
  13111. for (int i = numThisTime; --i >= 0;)
  13112. {
  13113. *l++ = swapIfLittleEndian (*src++);
  13114. ++src;
  13115. }
  13116. }
  13117. else
  13118. {
  13119. for (int i = numThisTime; --i >= 0;)
  13120. {
  13121. *l++ = swapIfLittleEndian (*src++);
  13122. *r++ = swapIfLittleEndian (*src++);
  13123. }
  13124. }
  13125. }
  13126. else
  13127. {
  13128. for (int i = numThisTime; --i >= 0;)
  13129. {
  13130. *l++ = swapIfLittleEndian (*src++);
  13131. }
  13132. }
  13133. }
  13134. left = (int*) l;
  13135. right = (int*) r;
  13136. }
  13137. else if (bitsPerSample == 8)
  13138. {
  13139. const char* src = (const char*) tempBuffer;
  13140. if (numChannels > 1)
  13141. {
  13142. if (left == 0)
  13143. {
  13144. for (int i = numThisTime; --i >= 0;)
  13145. {
  13146. *right++ = ((int) *src++) << 24;
  13147. ++src;
  13148. }
  13149. }
  13150. else if (right == 0)
  13151. {
  13152. for (int i = numThisTime; --i >= 0;)
  13153. {
  13154. ++src;
  13155. *left++ = ((int) *src++) << 24;
  13156. }
  13157. }
  13158. else
  13159. {
  13160. for (int i = numThisTime; --i >= 0;)
  13161. {
  13162. *left++ = ((int) *src++) << 24;
  13163. *right++ = ((int) *src++) << 24;
  13164. }
  13165. }
  13166. }
  13167. else
  13168. {
  13169. for (int i = numThisTime; --i >= 0;)
  13170. {
  13171. *left++ = ((int) *src++) << 24;
  13172. }
  13173. }
  13174. }
  13175. num -= numThisTime;
  13176. }
  13177. }
  13178. if (numToDo < numSamples)
  13179. {
  13180. int** destChan = destSamples;
  13181. while (*destChan != 0)
  13182. {
  13183. zeromem ((*destChan) + (startOffsetInDestBuffer + numToDo),
  13184. sizeof (int) * (numSamples - numToDo));
  13185. ++destChan;
  13186. }
  13187. }
  13188. return true;
  13189. }
  13190. juce_UseDebuggingNewOperator
  13191. private:
  13192. AiffAudioFormatReader (const AiffAudioFormatReader&);
  13193. const AiffAudioFormatReader& operator= (const AiffAudioFormatReader&);
  13194. };
  13195. class AiffAudioFormatWriter : public AudioFormatWriter
  13196. {
  13197. MemoryBlock tempBlock;
  13198. uint32 lengthInSamples, bytesWritten;
  13199. int64 headerPosition;
  13200. bool writeFailed;
  13201. AiffAudioFormatWriter (const AiffAudioFormatWriter&);
  13202. const AiffAudioFormatWriter& operator= (const AiffAudioFormatWriter&);
  13203. void writeHeader()
  13204. {
  13205. const bool couldSeekOk = output->setPosition (headerPosition);
  13206. (void) couldSeekOk;
  13207. // if this fails, you've given it an output stream that can't seek! It needs
  13208. // to be able to seek back to write the header
  13209. jassert (couldSeekOk);
  13210. const int headerLen = 54;
  13211. int audioBytes = lengthInSamples * ((bitsPerSample * numChannels) / 8);
  13212. audioBytes += (audioBytes & 1);
  13213. output->writeInt (chunkName ("FORM"));
  13214. output->writeIntBigEndian (headerLen + audioBytes - 8);
  13215. output->writeInt (chunkName ("AIFF"));
  13216. output->writeInt (chunkName ("COMM"));
  13217. output->writeIntBigEndian (18);
  13218. output->writeShortBigEndian ((short) numChannels);
  13219. output->writeIntBigEndian (lengthInSamples);
  13220. output->writeShortBigEndian ((short) bitsPerSample);
  13221. uint8 sampleRateBytes[10];
  13222. zeromem (sampleRateBytes, 10);
  13223. if (sampleRate <= 1)
  13224. {
  13225. sampleRateBytes[0] = 0x3f;
  13226. sampleRateBytes[1] = 0xff;
  13227. sampleRateBytes[2] = 0x80;
  13228. }
  13229. else
  13230. {
  13231. int mask = 0x40000000;
  13232. sampleRateBytes[0] = 0x40;
  13233. if (sampleRate >= mask)
  13234. {
  13235. jassertfalse
  13236. sampleRateBytes[1] = 0x1d;
  13237. }
  13238. else
  13239. {
  13240. int n = (int) sampleRate;
  13241. int i;
  13242. for (i = 0; i <= 32 ; ++i)
  13243. {
  13244. if ((n & mask) != 0)
  13245. break;
  13246. mask >>= 1;
  13247. }
  13248. n = n << (i + 1);
  13249. sampleRateBytes[1] = (uint8) (29 - i);
  13250. sampleRateBytes[2] = (uint8) ((n >> 24) & 0xff);
  13251. sampleRateBytes[3] = (uint8) ((n >> 16) & 0xff);
  13252. sampleRateBytes[4] = (uint8) ((n >> 8) & 0xff);
  13253. sampleRateBytes[5] = (uint8) (n & 0xff);
  13254. }
  13255. }
  13256. output->write (sampleRateBytes, 10);
  13257. output->writeInt (chunkName ("SSND"));
  13258. output->writeIntBigEndian (audioBytes + 8);
  13259. output->writeInt (0);
  13260. output->writeInt (0);
  13261. jassert (output->getPosition() == headerLen);
  13262. }
  13263. public:
  13264. AiffAudioFormatWriter (OutputStream* out,
  13265. const double sampleRate,
  13266. const unsigned int chans,
  13267. const int bits)
  13268. : AudioFormatWriter (out,
  13269. aiffFormatName,
  13270. sampleRate,
  13271. chans,
  13272. bits),
  13273. lengthInSamples (0),
  13274. bytesWritten (0),
  13275. writeFailed (false)
  13276. {
  13277. headerPosition = out->getPosition();
  13278. writeHeader();
  13279. }
  13280. ~AiffAudioFormatWriter()
  13281. {
  13282. if ((bytesWritten & 1) != 0)
  13283. output->writeByte (0);
  13284. writeHeader();
  13285. }
  13286. bool write (const int** data, int numSamples)
  13287. {
  13288. if (writeFailed)
  13289. return false;
  13290. const int bytes = numChannels * numSamples * bitsPerSample / 8;
  13291. tempBlock.ensureSize (bytes, false);
  13292. char* buffer = (char*) tempBlock.getData();
  13293. const int* left = data[0];
  13294. const int* right = data[1];
  13295. if (right == 0)
  13296. right = left;
  13297. if (bitsPerSample == 16)
  13298. {
  13299. short* b = (short*) buffer;
  13300. if (numChannels > 1)
  13301. {
  13302. for (int i = numSamples; --i >= 0;)
  13303. {
  13304. *b++ = (short) swapIfLittleEndian ((unsigned short) (*left++ >> 16));
  13305. *b++ = (short) swapIfLittleEndian ((unsigned short) (*right++ >> 16));
  13306. }
  13307. }
  13308. else
  13309. {
  13310. for (int i = numSamples; --i >= 0;)
  13311. {
  13312. *b++ = (short) swapIfLittleEndian ((unsigned short) (*left++ >> 16));
  13313. }
  13314. }
  13315. }
  13316. else if (bitsPerSample == 24)
  13317. {
  13318. char* b = (char*) buffer;
  13319. if (numChannels > 1)
  13320. {
  13321. for (int i = numSamples; --i >= 0;)
  13322. {
  13323. bigEndian24BitToChars (*left++ >> 8, b);
  13324. b += 3;
  13325. bigEndian24BitToChars (*right++ >> 8, b);
  13326. b += 3;
  13327. }
  13328. }
  13329. else
  13330. {
  13331. for (int i = numSamples; --i >= 0;)
  13332. {
  13333. bigEndian24BitToChars (*left++ >> 8, b);
  13334. b += 3;
  13335. }
  13336. }
  13337. }
  13338. else if (bitsPerSample == 32)
  13339. {
  13340. unsigned int* b = (unsigned int*) buffer;
  13341. if (numChannels > 1)
  13342. {
  13343. for (int i = numSamples; --i >= 0;)
  13344. {
  13345. *b++ = swapIfLittleEndian ((unsigned int) *left++);
  13346. *b++ = swapIfLittleEndian ((unsigned int) *right++);
  13347. }
  13348. }
  13349. else
  13350. {
  13351. for (int i = numSamples; --i >= 0;)
  13352. {
  13353. *b++ = swapIfLittleEndian ((unsigned int) *left++);
  13354. }
  13355. }
  13356. }
  13357. else if (bitsPerSample == 8)
  13358. {
  13359. char* b = (char*)buffer;
  13360. if (numChannels > 1)
  13361. {
  13362. for (int i = numSamples; --i >= 0;)
  13363. {
  13364. *b++ = (char) (*left++ >> 24);
  13365. *b++ = (char) (*right++ >> 24);
  13366. }
  13367. }
  13368. else
  13369. {
  13370. for (int i = numSamples; --i >= 0;)
  13371. {
  13372. *b++ = (char) (*left++ >> 24);
  13373. }
  13374. }
  13375. }
  13376. if (bytesWritten + bytes >= (uint32) 0xfff00000
  13377. || ! output->write (buffer, bytes))
  13378. {
  13379. // failed to write to disk, so let's try writing the header.
  13380. // If it's just run out of disk space, then if it does manage
  13381. // to write the header, we'll still have a useable file..
  13382. writeHeader();
  13383. writeFailed = true;
  13384. return false;
  13385. }
  13386. else
  13387. {
  13388. bytesWritten += bytes;
  13389. lengthInSamples += numSamples;
  13390. return true;
  13391. }
  13392. }
  13393. juce_UseDebuggingNewOperator
  13394. };
  13395. AiffAudioFormat::AiffAudioFormat()
  13396. : AudioFormat (aiffFormatName, (const tchar**) aiffExtensions)
  13397. {
  13398. }
  13399. AiffAudioFormat::~AiffAudioFormat()
  13400. {
  13401. }
  13402. const Array <int> AiffAudioFormat::getPossibleSampleRates()
  13403. {
  13404. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  13405. return Array <int> (rates);
  13406. }
  13407. const Array <int> AiffAudioFormat::getPossibleBitDepths()
  13408. {
  13409. const int depths[] = { 8, 16, 24, 0 };
  13410. return Array <int> (depths);
  13411. }
  13412. bool AiffAudioFormat::canDoStereo()
  13413. {
  13414. return true;
  13415. }
  13416. bool AiffAudioFormat::canDoMono()
  13417. {
  13418. return true;
  13419. }
  13420. #if JUCE_MAC
  13421. bool AiffAudioFormat::canHandleFile (const File& f)
  13422. {
  13423. if (AudioFormat::canHandleFile (f))
  13424. return true;
  13425. const OSType type = PlatformUtilities::getTypeOfFile (f.getFullPathName());
  13426. return type == 'AIFF' || type == 'AIFC'
  13427. || type == 'aiff' || type == 'aifc';
  13428. }
  13429. #endif
  13430. AudioFormatReader* AiffAudioFormat::createReaderFor (InputStream* sourceStream,
  13431. const bool deleteStreamIfOpeningFails)
  13432. {
  13433. AiffAudioFormatReader* w = new AiffAudioFormatReader (sourceStream);
  13434. if (w->sampleRate == 0)
  13435. {
  13436. if (! deleteStreamIfOpeningFails)
  13437. w->input = 0;
  13438. deleteAndZero (w);
  13439. }
  13440. return w;
  13441. }
  13442. AudioFormatWriter* AiffAudioFormat::createWriterFor (OutputStream* out,
  13443. double sampleRate,
  13444. unsigned int chans,
  13445. int bitsPerSample,
  13446. const StringPairArray& /*metadataValues*/,
  13447. int /*qualityOptionIndex*/)
  13448. {
  13449. if (getPossibleBitDepths().contains (bitsPerSample))
  13450. {
  13451. return new AiffAudioFormatWriter (out,
  13452. sampleRate,
  13453. chans,
  13454. bitsPerSample);
  13455. }
  13456. return 0;
  13457. }
  13458. END_JUCE_NAMESPACE
  13459. /********* End of inlined file: juce_AiffAudioFormat.cpp *********/
  13460. /********* Start of inlined file: juce_AudioCDReader.cpp *********/
  13461. BEGIN_JUCE_NAMESPACE
  13462. #if JUCE_MAC
  13463. // Mac version doesn't need any native code because it's all done with files..
  13464. // Windows + Linux versions are in the platform-dependent code sections.
  13465. static void findCDs (OwnedArray<File>& cds)
  13466. {
  13467. File volumes ("/Volumes");
  13468. volumes.findChildFiles (cds, File::findDirectories, false);
  13469. for (int i = cds.size(); --i >= 0;)
  13470. if (! cds[i]->getChildFile (".TOC.plist").exists())
  13471. cds.remove (i);
  13472. }
  13473. const StringArray AudioCDReader::getAvailableCDNames()
  13474. {
  13475. OwnedArray<File> cds;
  13476. findCDs (cds);
  13477. StringArray names;
  13478. for (int i = 0; i < cds.size(); ++i)
  13479. names.add (cds[i]->getFileName());
  13480. return names;
  13481. }
  13482. AudioCDReader* AudioCDReader::createReaderForCD (const int index)
  13483. {
  13484. OwnedArray<File> cds;
  13485. findCDs (cds);
  13486. if (cds[index] != 0)
  13487. return new AudioCDReader (*cds[index]);
  13488. else
  13489. return 0;
  13490. }
  13491. AudioCDReader::AudioCDReader (const File& volume)
  13492. : AudioFormatReader (0, "CD Audio"),
  13493. volumeDir (volume),
  13494. currentReaderTrack (-1),
  13495. reader (0)
  13496. {
  13497. sampleRate = 44100.0;
  13498. bitsPerSample = 16;
  13499. numChannels = 2;
  13500. usesFloatingPointData = false;
  13501. refreshTrackLengths();
  13502. }
  13503. AudioCDReader::~AudioCDReader()
  13504. {
  13505. if (reader != 0)
  13506. delete reader;
  13507. }
  13508. static int getTrackNumber (const File& file)
  13509. {
  13510. return file.getFileName()
  13511. .initialSectionContainingOnly (T("0123456789"))
  13512. .getIntValue();
  13513. }
  13514. int AudioCDReader::compareElements (const File* const first, const File* const second) throw()
  13515. {
  13516. const int firstTrack = getTrackNumber (*first);
  13517. const int secondTrack = getTrackNumber (*second);
  13518. jassert (firstTrack > 0 && secondTrack > 0);
  13519. return firstTrack - secondTrack;
  13520. }
  13521. void AudioCDReader::refreshTrackLengths()
  13522. {
  13523. tracks.clear();
  13524. trackStartSamples.clear();
  13525. volumeDir.findChildFiles (tracks, File::findFiles | File::ignoreHiddenFiles, false, T("*.aiff"));
  13526. tracks.sort (*this);
  13527. AiffAudioFormat format;
  13528. int sample = 0;
  13529. for (int i = 0; i < tracks.size(); ++i)
  13530. {
  13531. trackStartSamples.add (sample);
  13532. FileInputStream* const in = tracks[i]->createInputStream();
  13533. if (in != 0)
  13534. {
  13535. AudioFormatReader* const r = format.createReaderFor (in, true);
  13536. if (r != 0)
  13537. {
  13538. sample += r->lengthInSamples;
  13539. delete r;
  13540. }
  13541. }
  13542. }
  13543. trackStartSamples.add (sample);
  13544. lengthInSamples = sample;
  13545. }
  13546. bool AudioCDReader::read (int** destSamples,
  13547. int64 startSampleInFile,
  13548. int numSamples)
  13549. {
  13550. while (numSamples > 0)
  13551. {
  13552. int track = -1;
  13553. for (int i = 0; i < trackStartSamples.size() - 1; ++i)
  13554. {
  13555. if (startSampleInFile < trackStartSamples.getUnchecked (i + 1))
  13556. {
  13557. track = i;
  13558. break;
  13559. }
  13560. }
  13561. if (track < 0)
  13562. return false;
  13563. if (track != currentReaderTrack)
  13564. {
  13565. deleteAndZero (reader);
  13566. if (tracks [track] != 0)
  13567. {
  13568. FileInputStream* const in = tracks [track]->createInputStream();
  13569. if (in != 0)
  13570. {
  13571. BufferedInputStream* const bin = new BufferedInputStream (in, 65536, true);
  13572. AiffAudioFormat format;
  13573. reader = format.createReaderFor (bin, true);
  13574. if (reader == 0)
  13575. currentReaderTrack = -1;
  13576. else
  13577. currentReaderTrack = track;
  13578. }
  13579. }
  13580. }
  13581. if (reader == 0)
  13582. return false;
  13583. const int startPos = (int) (startSampleInFile - trackStartSamples.getUnchecked (track));
  13584. const int numAvailable = (int) jmin ((int64) numSamples, reader->lengthInSamples - startPos);
  13585. reader->read (destSamples, startPos, numAvailable);
  13586. numSamples -= numAvailable;
  13587. startSampleInFile += numAvailable;
  13588. }
  13589. return true;
  13590. }
  13591. bool AudioCDReader::isCDStillPresent() const
  13592. {
  13593. return volumeDir.exists();
  13594. }
  13595. int AudioCDReader::getNumTracks() const
  13596. {
  13597. return tracks.size();
  13598. }
  13599. int AudioCDReader::getPositionOfTrackStart (int trackNum) const
  13600. {
  13601. return trackStartSamples [trackNum];
  13602. }
  13603. bool AudioCDReader::isTrackAudio (int trackNum) const
  13604. {
  13605. return tracks [trackNum] != 0;
  13606. }
  13607. void AudioCDReader::enableIndexScanning (bool b)
  13608. {
  13609. // any way to do this on a Mac??
  13610. }
  13611. int AudioCDReader::getLastIndex() const
  13612. {
  13613. return 0;
  13614. }
  13615. const Array <int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  13616. {
  13617. return Array <int>();
  13618. }
  13619. int AudioCDReader::getCDDBId()
  13620. {
  13621. return 0; //xxx
  13622. }
  13623. #endif
  13624. END_JUCE_NAMESPACE
  13625. /********* End of inlined file: juce_AudioCDReader.cpp *********/
  13626. /********* Start of inlined file: juce_AudioFormat.cpp *********/
  13627. BEGIN_JUCE_NAMESPACE
  13628. AudioFormatReader::AudioFormatReader (InputStream* const in,
  13629. const String& formatName_)
  13630. : sampleRate (0),
  13631. bitsPerSample (0),
  13632. lengthInSamples (0),
  13633. numChannels (0),
  13634. usesFloatingPointData (false),
  13635. input (in),
  13636. formatName (formatName_)
  13637. {
  13638. }
  13639. AudioFormatReader::~AudioFormatReader()
  13640. {
  13641. delete input;
  13642. }
  13643. static void findMaxMin (const float* src, const int num,
  13644. float& maxVal, float& minVal)
  13645. {
  13646. float mn = src[0];
  13647. float mx = mn;
  13648. for (int i = 1; i < num; ++i)
  13649. {
  13650. const float s = src[i];
  13651. if (s > mx)
  13652. mx = s;
  13653. if (s < mn)
  13654. mn = s;
  13655. }
  13656. maxVal = mx;
  13657. minVal = mn;
  13658. }
  13659. void AudioFormatReader::readMaxLevels (int64 startSampleInFile,
  13660. int64 numSamples,
  13661. float& lowestLeft, float& highestLeft,
  13662. float& lowestRight, float& highestRight)
  13663. {
  13664. if (numSamples <= 0)
  13665. {
  13666. lowestLeft = 0;
  13667. lowestRight = 0;
  13668. highestLeft = 0;
  13669. highestRight = 0;
  13670. return;
  13671. }
  13672. const int bufferSize = (int) jmin (numSamples, (int64) 4096);
  13673. MemoryBlock tempSpace (bufferSize * sizeof (int) * 2 + 64);
  13674. int* tempBuffer[3];
  13675. tempBuffer[0] = (int*) tempSpace.getData();
  13676. tempBuffer[1] = ((int*) tempSpace.getData()) + bufferSize;
  13677. tempBuffer[2] = 0;
  13678. if (usesFloatingPointData)
  13679. {
  13680. float lmin = 1.0e6;
  13681. float lmax = -lmin;
  13682. float rmin = lmin;
  13683. float rmax = lmax;
  13684. while (numSamples > 0)
  13685. {
  13686. const int numToDo = (int) jmin (numSamples, (int64) bufferSize);
  13687. read ((int**) tempBuffer, startSampleInFile, numToDo);
  13688. numSamples -= numToDo;
  13689. float bufmin, bufmax;
  13690. findMaxMin ((float*) tempBuffer[0], numToDo, bufmax, bufmin);
  13691. lmin = jmin (lmin, bufmin);
  13692. lmax = jmax (lmax, bufmax);
  13693. if (numChannels > 1)
  13694. {
  13695. findMaxMin ((float*) tempBuffer[1], numToDo, bufmax, bufmin);
  13696. rmin = jmin (rmin, bufmin);
  13697. rmax = jmax (rmax, bufmax);
  13698. }
  13699. }
  13700. if (numChannels <= 1)
  13701. {
  13702. rmax = lmax;
  13703. rmin = lmin;
  13704. }
  13705. lowestLeft = lmin;
  13706. highestLeft = lmax;
  13707. lowestRight = rmin;
  13708. highestRight = rmax;
  13709. }
  13710. else
  13711. {
  13712. int lmax = INT_MIN;
  13713. int lmin = INT_MAX;
  13714. int rmax = INT_MIN;
  13715. int rmin = INT_MAX;
  13716. while (numSamples > 0)
  13717. {
  13718. const int numToDo = (int) jmin (numSamples, (int64) bufferSize);
  13719. read ((int**) tempBuffer, startSampleInFile, numToDo);
  13720. numSamples -= numToDo;
  13721. for (int j = numChannels; --j >= 0;)
  13722. {
  13723. int bufMax = INT_MIN;
  13724. int bufMin = INT_MAX;
  13725. const int* const b = tempBuffer[j];
  13726. for (int i = 0; i < numToDo; ++i)
  13727. {
  13728. const int samp = b[i];
  13729. if (samp < bufMin)
  13730. bufMin = samp;
  13731. if (samp > bufMax)
  13732. bufMax = samp;
  13733. }
  13734. if (j == 0)
  13735. {
  13736. lmax = jmax (lmax, bufMax);
  13737. lmin = jmin (lmin, bufMin);
  13738. }
  13739. else
  13740. {
  13741. rmax = jmax (rmax, bufMax);
  13742. rmin = jmin (rmin, bufMin);
  13743. }
  13744. }
  13745. }
  13746. if (numChannels <= 1)
  13747. {
  13748. rmax = lmax;
  13749. rmin = lmin;
  13750. }
  13751. lowestLeft = lmin / (float)INT_MAX;
  13752. highestLeft = lmax / (float)INT_MAX;
  13753. lowestRight = rmin / (float)INT_MAX;
  13754. highestRight = rmax / (float)INT_MAX;
  13755. }
  13756. }
  13757. int64 AudioFormatReader::searchForLevel (int64 startSample,
  13758. int64 numSamplesToSearch,
  13759. const double magnitudeRangeMinimum,
  13760. const double magnitudeRangeMaximum,
  13761. const int minimumConsecutiveSamples)
  13762. {
  13763. if (numSamplesToSearch == 0)
  13764. return -1;
  13765. const int bufferSize = 4096;
  13766. MemoryBlock tempSpace (bufferSize * sizeof (int) * 2 + 64);
  13767. int* tempBuffer[3];
  13768. tempBuffer[0] = (int*) tempSpace.getData();
  13769. tempBuffer[1] = ((int*) tempSpace.getData()) + bufferSize;
  13770. tempBuffer[2] = 0;
  13771. int consecutive = 0;
  13772. int64 firstMatchPos = -1;
  13773. jassert (magnitudeRangeMaximum > magnitudeRangeMinimum);
  13774. const double doubleMin = jlimit (0.0, (double) INT_MAX, magnitudeRangeMinimum * INT_MAX);
  13775. const double doubleMax = jlimit (doubleMin, (double) INT_MAX, magnitudeRangeMaximum * INT_MAX);
  13776. const int intMagnitudeRangeMinimum = roundDoubleToInt (doubleMin);
  13777. const int intMagnitudeRangeMaximum = roundDoubleToInt (doubleMax);
  13778. while (numSamplesToSearch != 0)
  13779. {
  13780. const int numThisTime = (int) jmin (abs64 (numSamplesToSearch), (int64) bufferSize);
  13781. int64 bufferStart = startSample;
  13782. if (numSamplesToSearch < 0)
  13783. bufferStart -= numThisTime;
  13784. if (bufferStart >= (int) lengthInSamples)
  13785. break;
  13786. read ((int**) tempBuffer, bufferStart, numThisTime);
  13787. int num = numThisTime;
  13788. while (--num >= 0)
  13789. {
  13790. if (numSamplesToSearch < 0)
  13791. --startSample;
  13792. bool matches = false;
  13793. const int index = (int) (startSample - bufferStart);
  13794. if (usesFloatingPointData)
  13795. {
  13796. const float sample1 = fabsf (((float*) tempBuffer[0]) [index]);
  13797. if (sample1 >= magnitudeRangeMinimum
  13798. && sample1 <= magnitudeRangeMaximum)
  13799. {
  13800. matches = true;
  13801. }
  13802. else if (numChannels > 1)
  13803. {
  13804. const float sample2 = fabsf (((float*) tempBuffer[1]) [index]);
  13805. matches = (sample2 >= magnitudeRangeMinimum
  13806. && sample2 <= magnitudeRangeMaximum);
  13807. }
  13808. }
  13809. else
  13810. {
  13811. const int sample1 = abs (tempBuffer[0] [index]);
  13812. if (sample1 >= intMagnitudeRangeMinimum
  13813. && sample1 <= intMagnitudeRangeMaximum)
  13814. {
  13815. matches = true;
  13816. }
  13817. else if (numChannels > 1)
  13818. {
  13819. const int sample2 = abs (tempBuffer[1][index]);
  13820. matches = (sample2 >= intMagnitudeRangeMinimum
  13821. && sample2 <= intMagnitudeRangeMaximum);
  13822. }
  13823. }
  13824. if (matches)
  13825. {
  13826. if (firstMatchPos < 0)
  13827. firstMatchPos = startSample;
  13828. if (++consecutive >= minimumConsecutiveSamples)
  13829. {
  13830. if (firstMatchPos < 0 || firstMatchPos >= lengthInSamples)
  13831. return -1;
  13832. return firstMatchPos;
  13833. }
  13834. }
  13835. else
  13836. {
  13837. consecutive = 0;
  13838. firstMatchPos = -1;
  13839. }
  13840. if (numSamplesToSearch > 0)
  13841. ++startSample;
  13842. }
  13843. if (numSamplesToSearch > 0)
  13844. numSamplesToSearch -= numThisTime;
  13845. else
  13846. numSamplesToSearch += numThisTime;
  13847. }
  13848. return -1;
  13849. }
  13850. AudioFormatWriter::AudioFormatWriter (OutputStream* const out,
  13851. const String& formatName_,
  13852. const double rate,
  13853. const unsigned int numChannels_,
  13854. const unsigned int bitsPerSample_)
  13855. : sampleRate (rate),
  13856. numChannels (numChannels_),
  13857. bitsPerSample (bitsPerSample_),
  13858. usesFloatingPointData (false),
  13859. output (out),
  13860. formatName (formatName_)
  13861. {
  13862. }
  13863. AudioFormatWriter::~AudioFormatWriter()
  13864. {
  13865. delete output;
  13866. }
  13867. bool AudioFormatWriter::writeFromAudioReader (AudioFormatReader& reader,
  13868. int64 startSample,
  13869. int numSamplesToRead)
  13870. {
  13871. const int bufferSize = 16384;
  13872. const int maxChans = 128;
  13873. AudioSampleBuffer tempBuffer (reader.numChannels, bufferSize);
  13874. int* buffers [maxChans];
  13875. for (int i = maxChans; --i >= 0;)
  13876. buffers[i] = 0;
  13877. while (numSamplesToRead > 0)
  13878. {
  13879. const int numToDo = jmin (numSamplesToRead, bufferSize);
  13880. for (int i = tempBuffer.getNumChannels(); --i >= 0;)
  13881. buffers[i] = (int*) tempBuffer.getSampleData (i, 0);
  13882. if (! reader.read (buffers, startSample, numToDo))
  13883. return false;
  13884. if (reader.usesFloatingPointData != isFloatingPoint())
  13885. {
  13886. int** bufferChan = buffers;
  13887. while (*bufferChan != 0)
  13888. {
  13889. int* b = *bufferChan++;
  13890. if (isFloatingPoint())
  13891. {
  13892. // int -> float
  13893. const double factor = 1.0 / INT_MAX;
  13894. for (int i = 0; i < numToDo; ++i)
  13895. ((float*)b)[i] = (float) (factor * b[i]);
  13896. }
  13897. else
  13898. {
  13899. // float -> int
  13900. for (int i = 0; i < numToDo; ++i)
  13901. {
  13902. const double samp = *(const float*) b;
  13903. if (samp <= -1.0)
  13904. *b++ = INT_MIN;
  13905. else if (samp >= 1.0)
  13906. *b++ = INT_MAX;
  13907. else
  13908. *b++ = roundDoubleToInt (INT_MAX * samp);
  13909. }
  13910. }
  13911. }
  13912. }
  13913. if (! write ((const int**) buffers, numToDo))
  13914. return false;
  13915. numSamplesToRead -= numToDo;
  13916. startSample += numToDo;
  13917. }
  13918. return true;
  13919. }
  13920. bool AudioFormatWriter::writeFromAudioSource (AudioSource& source,
  13921. int numSamplesToRead,
  13922. const int samplesPerBlock)
  13923. {
  13924. const int maxChans = 128;
  13925. AudioSampleBuffer tempBuffer (getNumChannels(), samplesPerBlock);
  13926. int* buffers [maxChans];
  13927. while (numSamplesToRead > 0)
  13928. {
  13929. const int numToDo = jmin (numSamplesToRead, samplesPerBlock);
  13930. AudioSourceChannelInfo info;
  13931. info.buffer = &tempBuffer;
  13932. info.startSample = 0;
  13933. info.numSamples = numToDo;
  13934. info.clearActiveBufferRegion();
  13935. source.getNextAudioBlock (info);
  13936. int i;
  13937. for (i = maxChans; --i >= 0;)
  13938. buffers[i] = 0;
  13939. for (i = tempBuffer.getNumChannels(); --i >= 0;)
  13940. buffers[i] = (int*) tempBuffer.getSampleData (i, 0);
  13941. if (! isFloatingPoint())
  13942. {
  13943. int** bufferChan = buffers;
  13944. while (*bufferChan != 0)
  13945. {
  13946. int* b = *bufferChan++;
  13947. // float -> int
  13948. for (int j = numToDo; --j >= 0;)
  13949. {
  13950. const double samp = *(const float*) b;
  13951. if (samp <= -1.0)
  13952. *b++ = INT_MIN;
  13953. else if (samp >= 1.0)
  13954. *b++ = INT_MAX;
  13955. else
  13956. *b++ = roundDoubleToInt (INT_MAX * samp);
  13957. }
  13958. }
  13959. }
  13960. if (! write ((const int**) buffers, numToDo))
  13961. return false;
  13962. numSamplesToRead -= numToDo;
  13963. }
  13964. return true;
  13965. }
  13966. AudioFormat::AudioFormat (const String& name,
  13967. const tchar** const extensions)
  13968. : formatName (name),
  13969. fileExtensions (extensions)
  13970. {
  13971. }
  13972. AudioFormat::~AudioFormat()
  13973. {
  13974. }
  13975. const String& AudioFormat::getFormatName() const
  13976. {
  13977. return formatName;
  13978. }
  13979. const StringArray& AudioFormat::getFileExtensions() const
  13980. {
  13981. return fileExtensions;
  13982. }
  13983. bool AudioFormat::canHandleFile (const File& f)
  13984. {
  13985. for (int i = 0; i < fileExtensions.size(); ++i)
  13986. if (f.hasFileExtension (fileExtensions[i]))
  13987. return true;
  13988. return false;
  13989. }
  13990. bool AudioFormat::isCompressed()
  13991. {
  13992. return false;
  13993. }
  13994. const StringArray AudioFormat::getQualityOptions()
  13995. {
  13996. return StringArray();
  13997. }
  13998. END_JUCE_NAMESPACE
  13999. /********* End of inlined file: juce_AudioFormat.cpp *********/
  14000. /********* Start of inlined file: juce_AudioFormatManager.cpp *********/
  14001. BEGIN_JUCE_NAMESPACE
  14002. AudioFormatManager::AudioFormatManager()
  14003. : knownFormats (4),
  14004. defaultFormatIndex (0)
  14005. {
  14006. }
  14007. AudioFormatManager::~AudioFormatManager()
  14008. {
  14009. clearFormats();
  14010. clearSingletonInstance();
  14011. }
  14012. juce_ImplementSingleton (AudioFormatManager);
  14013. void AudioFormatManager::registerFormat (AudioFormat* newFormat,
  14014. const bool makeThisTheDefaultFormat)
  14015. {
  14016. jassert (newFormat != 0);
  14017. if (newFormat != 0)
  14018. {
  14019. #ifdef JUCE_DEBUG
  14020. for (int i = getNumKnownFormats(); --i >= 0;)
  14021. {
  14022. if (getKnownFormat (i)->getFormatName() == newFormat->getFormatName())
  14023. {
  14024. jassertfalse // trying to add the same format twice!
  14025. }
  14026. }
  14027. #endif
  14028. if (makeThisTheDefaultFormat)
  14029. defaultFormatIndex = knownFormats.size();
  14030. knownFormats.add (newFormat);
  14031. }
  14032. }
  14033. void AudioFormatManager::registerBasicFormats()
  14034. {
  14035. #if JUCE_MAC
  14036. registerFormat (new AiffAudioFormat(), true);
  14037. registerFormat (new WavAudioFormat(), false);
  14038. #else
  14039. registerFormat (new WavAudioFormat(), true);
  14040. registerFormat (new AiffAudioFormat(), false);
  14041. #endif
  14042. #if JUCE_USE_FLAC
  14043. registerFormat (new FlacAudioFormat(), false);
  14044. #endif
  14045. #if JUCE_USE_OGGVORBIS
  14046. registerFormat (new OggVorbisAudioFormat(), false);
  14047. #endif
  14048. }
  14049. void AudioFormatManager::clearFormats()
  14050. {
  14051. for (int i = getNumKnownFormats(); --i >= 0;)
  14052. {
  14053. AudioFormat* const af = getKnownFormat(i);
  14054. delete af;
  14055. }
  14056. knownFormats.clear();
  14057. defaultFormatIndex = 0;
  14058. }
  14059. int AudioFormatManager::getNumKnownFormats() const
  14060. {
  14061. return knownFormats.size();
  14062. }
  14063. AudioFormat* AudioFormatManager::getKnownFormat (const int index) const
  14064. {
  14065. return (AudioFormat*) knownFormats [index];
  14066. }
  14067. AudioFormat* AudioFormatManager::getDefaultFormat() const
  14068. {
  14069. return getKnownFormat (defaultFormatIndex);
  14070. }
  14071. AudioFormat* AudioFormatManager::findFormatForFileExtension (const String& fileExtension) const
  14072. {
  14073. String e (fileExtension);
  14074. if (! e.startsWithChar (T('.')))
  14075. e = T(".") + e;
  14076. for (int i = 0; i < getNumKnownFormats(); ++i)
  14077. if (getKnownFormat(i)->getFileExtensions().contains (e, true))
  14078. return getKnownFormat(i);
  14079. return 0;
  14080. }
  14081. const String AudioFormatManager::getWildcardForAllFormats() const
  14082. {
  14083. StringArray allExtensions;
  14084. int i;
  14085. for (i = 0; i < getNumKnownFormats(); ++i)
  14086. allExtensions.addArray (getKnownFormat (i)->getFileExtensions());
  14087. allExtensions.trim();
  14088. allExtensions.removeEmptyStrings();
  14089. String s;
  14090. for (i = 0; i < allExtensions.size(); ++i)
  14091. {
  14092. s << T('*');
  14093. if (! allExtensions[i].startsWithChar (T('.')))
  14094. s << T('.');
  14095. s << allExtensions[i];
  14096. if (i < allExtensions.size() - 1)
  14097. s << T(';');
  14098. }
  14099. return s;
  14100. }
  14101. AudioFormatReader* AudioFormatManager::createReaderFor (const File& file)
  14102. {
  14103. // you need to actually register some formats before the manager can
  14104. // use them to open a file!
  14105. jassert (knownFormats.size() > 0);
  14106. for (int i = 0; i < getNumKnownFormats(); ++i)
  14107. {
  14108. AudioFormat* const af = getKnownFormat(i);
  14109. if (af->canHandleFile (file))
  14110. {
  14111. InputStream* const in = file.createInputStream();
  14112. if (in != 0)
  14113. {
  14114. AudioFormatReader* const r = af->createReaderFor (in, true);
  14115. if (r != 0)
  14116. return r;
  14117. }
  14118. }
  14119. }
  14120. return 0;
  14121. }
  14122. AudioFormatReader* AudioFormatManager::createReaderFor (InputStream* in)
  14123. {
  14124. // you need to actually register some formats before the manager can
  14125. // use them to open a file!
  14126. jassert (knownFormats.size() > 0);
  14127. if (in != 0)
  14128. {
  14129. const int64 originalStreamPos = in->getPosition();
  14130. for (int i = 0; i < getNumKnownFormats(); ++i)
  14131. {
  14132. AudioFormatReader* const r = getKnownFormat(i)->createReaderFor (in, false);
  14133. if (r != 0)
  14134. return r;
  14135. in->setPosition (originalStreamPos);
  14136. // the stream that is passed-in must be capable of being repositioned so
  14137. // that all the formats can have a go at opening it.
  14138. jassert (in->getPosition() == originalStreamPos);
  14139. }
  14140. delete in;
  14141. }
  14142. return 0;
  14143. }
  14144. END_JUCE_NAMESPACE
  14145. /********* End of inlined file: juce_AudioFormatManager.cpp *********/
  14146. /********* Start of inlined file: juce_AudioSubsectionReader.cpp *********/
  14147. BEGIN_JUCE_NAMESPACE
  14148. AudioSubsectionReader::AudioSubsectionReader (AudioFormatReader* const source_,
  14149. const int64 startSample_,
  14150. const int64 length_,
  14151. const bool deleteSourceWhenDeleted_)
  14152. : AudioFormatReader (0, source_->getFormatName()),
  14153. source (source_),
  14154. startSample (startSample_),
  14155. deleteSourceWhenDeleted (deleteSourceWhenDeleted_)
  14156. {
  14157. length = jmin (jmax ((int64) 0, source->lengthInSamples - startSample), length_);
  14158. sampleRate = source->sampleRate;
  14159. bitsPerSample = source->bitsPerSample;
  14160. lengthInSamples = length;
  14161. numChannels = source->numChannels;
  14162. usesFloatingPointData = source->usesFloatingPointData;
  14163. }
  14164. AudioSubsectionReader::~AudioSubsectionReader()
  14165. {
  14166. if (deleteSourceWhenDeleted)
  14167. delete source;
  14168. }
  14169. bool AudioSubsectionReader::read (int** destSamples,
  14170. int64 startSampleInFile,
  14171. int numSamples)
  14172. {
  14173. if (startSampleInFile < 0 || startSampleInFile + numSamples > length)
  14174. {
  14175. int** d = destSamples;
  14176. while (*d != 0)
  14177. {
  14178. zeromem (*d, sizeof (int) * numSamples);
  14179. ++d;
  14180. }
  14181. startSampleInFile = jmax ((int64) 0, startSampleInFile);
  14182. numSamples = jmax (0, jmin (numSamples, (int) (length - startSampleInFile)));
  14183. }
  14184. return source->read (destSamples,
  14185. startSampleInFile + startSample,
  14186. numSamples);
  14187. }
  14188. void AudioSubsectionReader::readMaxLevels (int64 startSampleInFile,
  14189. int64 numSamples,
  14190. float& lowestLeft,
  14191. float& highestLeft,
  14192. float& lowestRight,
  14193. float& highestRight)
  14194. {
  14195. startSampleInFile = jmax ((int64) 0, startSampleInFile);
  14196. numSamples = jmax ((int64) 0, jmin (numSamples, length - startSampleInFile));
  14197. source->readMaxLevels (startSampleInFile + startSample,
  14198. numSamples,
  14199. lowestLeft,
  14200. highestLeft,
  14201. lowestRight,
  14202. highestRight);
  14203. }
  14204. END_JUCE_NAMESPACE
  14205. /********* End of inlined file: juce_AudioSubsectionReader.cpp *********/
  14206. /********* Start of inlined file: juce_AudioThumbnail.cpp *********/
  14207. BEGIN_JUCE_NAMESPACE
  14208. const int timeBeforeDeletingReader = 2000;
  14209. struct AudioThumbnailDataFormat
  14210. {
  14211. char thumbnailMagic[4];
  14212. int samplesPerThumbSample;
  14213. int64 totalSamples; // source samples
  14214. int64 numFinishedSamples; // source samples
  14215. int numThumbnailSamples;
  14216. int numChannels;
  14217. int sampleRate;
  14218. char future[16];
  14219. char data[1];
  14220. };
  14221. #if JUCE_BIG_ENDIAN
  14222. static void swap (int& n) { n = (int) swapByteOrder ((uint32) n); }
  14223. static void swap (int64& n) { n = (int64) swapByteOrder ((uint64) n); }
  14224. #endif
  14225. static void swapEndiannessIfNeeded (AudioThumbnailDataFormat* const d)
  14226. {
  14227. (void) d;
  14228. #if JUCE_BIG_ENDIAN
  14229. swap (d->samplesPerThumbSample);
  14230. swap (d->totalSamples);
  14231. swap (d->numFinishedSamples);
  14232. swap (d->numThumbnailSamples);
  14233. swap (d->numChannels);
  14234. swap (d->sampleRate);
  14235. #endif
  14236. }
  14237. AudioThumbnail::AudioThumbnail (const int orginalSamplesPerThumbnailSample_,
  14238. AudioFormatManager& formatManagerToUse_,
  14239. AudioThumbnailCache& cacheToUse)
  14240. : formatManagerToUse (formatManagerToUse_),
  14241. cache (cacheToUse),
  14242. source (0),
  14243. reader (0),
  14244. orginalSamplesPerThumbnailSample (orginalSamplesPerThumbnailSample_)
  14245. {
  14246. clear();
  14247. }
  14248. AudioThumbnail::~AudioThumbnail()
  14249. {
  14250. cache.removeThumbnail (this);
  14251. const ScopedLock sl (readerLock);
  14252. deleteAndZero (reader);
  14253. delete source;
  14254. }
  14255. void AudioThumbnail::setSource (InputSource* const newSource)
  14256. {
  14257. cache.removeThumbnail (this);
  14258. timerCallback(); // stops the timer and deletes the reader
  14259. delete source;
  14260. source = newSource;
  14261. clear();
  14262. if (! (cache.loadThumb (*this, newSource->hashCode())
  14263. && isFullyLoaded()))
  14264. {
  14265. {
  14266. const ScopedLock sl (readerLock);
  14267. reader = createReader();
  14268. }
  14269. if (reader != 0)
  14270. {
  14271. initialiseFromAudioFile (*reader);
  14272. cache.addThumbnail (this);
  14273. }
  14274. }
  14275. sendChangeMessage (this);
  14276. }
  14277. bool AudioThumbnail::useTimeSlice()
  14278. {
  14279. const ScopedLock sl (readerLock);
  14280. if (isFullyLoaded())
  14281. {
  14282. if (reader != 0)
  14283. startTimer (timeBeforeDeletingReader);
  14284. cache.removeThumbnail (this);
  14285. return false;
  14286. }
  14287. if (reader == 0)
  14288. reader = createReader();
  14289. if (reader != 0)
  14290. {
  14291. readNextBlockFromAudioFile (*reader);
  14292. stopTimer();
  14293. sendChangeMessage (this);
  14294. const bool justFinished = isFullyLoaded();
  14295. if (justFinished)
  14296. cache.storeThumb (*this, source->hashCode());
  14297. return ! justFinished;
  14298. }
  14299. return false;
  14300. }
  14301. AudioFormatReader* AudioThumbnail::createReader() const
  14302. {
  14303. if (source != 0)
  14304. {
  14305. InputStream* const audioFileStream = source->createInputStream();
  14306. if (audioFileStream != 0)
  14307. return formatManagerToUse.createReaderFor (audioFileStream);
  14308. }
  14309. return 0;
  14310. }
  14311. void AudioThumbnail::timerCallback()
  14312. {
  14313. stopTimer();
  14314. const ScopedLock sl (readerLock);
  14315. deleteAndZero (reader);
  14316. }
  14317. void AudioThumbnail::clear()
  14318. {
  14319. data.setSize (sizeof (AudioThumbnailDataFormat) + 3);
  14320. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  14321. d->thumbnailMagic[0] = 'j';
  14322. d->thumbnailMagic[1] = 'a';
  14323. d->thumbnailMagic[2] = 't';
  14324. d->thumbnailMagic[3] = 'm';
  14325. d->samplesPerThumbSample = orginalSamplesPerThumbnailSample;
  14326. d->totalSamples = 0;
  14327. d->numFinishedSamples = 0;
  14328. d->numThumbnailSamples = 0;
  14329. d->numChannels = 0;
  14330. d->sampleRate = 0;
  14331. numSamplesCached = 0;
  14332. cacheNeedsRefilling = true;
  14333. }
  14334. void AudioThumbnail::loadFrom (InputStream& input)
  14335. {
  14336. data.setSize (0);
  14337. input.readIntoMemoryBlock (data);
  14338. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  14339. swapEndiannessIfNeeded (d);
  14340. if (! (d->thumbnailMagic[0] == 'j'
  14341. && d->thumbnailMagic[1] == 'a'
  14342. && d->thumbnailMagic[2] == 't'
  14343. && d->thumbnailMagic[3] == 'm'))
  14344. {
  14345. clear();
  14346. }
  14347. numSamplesCached = 0;
  14348. cacheNeedsRefilling = true;
  14349. }
  14350. void AudioThumbnail::saveTo (OutputStream& output) const
  14351. {
  14352. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  14353. swapEndiannessIfNeeded (d);
  14354. output.write (data.getData(), data.getSize());
  14355. swapEndiannessIfNeeded (d);
  14356. }
  14357. bool AudioThumbnail::initialiseFromAudioFile (AudioFormatReader& reader)
  14358. {
  14359. AudioThumbnailDataFormat* d = (AudioThumbnailDataFormat*) data.getData();
  14360. d->totalSamples = reader.lengthInSamples;
  14361. d->numChannels = jmin (2, reader.numChannels);
  14362. d->numFinishedSamples = 0;
  14363. d->sampleRate = roundDoubleToInt (reader.sampleRate);
  14364. d->numThumbnailSamples = (int) (d->totalSamples / d->samplesPerThumbSample) + 1;
  14365. data.setSize (sizeof (AudioThumbnailDataFormat) + 3 + d->numThumbnailSamples * d->numChannels * 2);
  14366. d = (AudioThumbnailDataFormat*) data.getData();
  14367. zeromem (&(d->data[0]), d->numThumbnailSamples * d->numChannels * 2);
  14368. return d->totalSamples > 0;
  14369. }
  14370. bool AudioThumbnail::readNextBlockFromAudioFile (AudioFormatReader& reader)
  14371. {
  14372. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  14373. if (d->numFinishedSamples < d->totalSamples)
  14374. {
  14375. const int numToDo = (int) jmin ((int64) 65536, d->totalSamples - d->numFinishedSamples);
  14376. generateSection (reader,
  14377. d->numFinishedSamples,
  14378. numToDo);
  14379. d->numFinishedSamples += numToDo;
  14380. }
  14381. cacheNeedsRefilling = true;
  14382. return (d->numFinishedSamples < d->totalSamples);
  14383. }
  14384. int AudioThumbnail::getNumChannels() const throw()
  14385. {
  14386. const AudioThumbnailDataFormat* const d = (const AudioThumbnailDataFormat*) data.getData();
  14387. jassert (d != 0);
  14388. return d->numChannels;
  14389. }
  14390. double AudioThumbnail::getTotalLength() const throw()
  14391. {
  14392. const AudioThumbnailDataFormat* const d = (const AudioThumbnailDataFormat*) data.getData();
  14393. jassert (d != 0);
  14394. if (d->sampleRate > 0)
  14395. return d->totalSamples / (double)d->sampleRate;
  14396. else
  14397. return 0.0;
  14398. }
  14399. void AudioThumbnail::generateSection (AudioFormatReader& reader,
  14400. int64 startSample,
  14401. int numSamples)
  14402. {
  14403. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  14404. jassert (d != 0);
  14405. int firstDataPos = (int) (startSample / d->samplesPerThumbSample);
  14406. int lastDataPos = (int) ((startSample + numSamples) / d->samplesPerThumbSample);
  14407. char* l = getChannelData (0);
  14408. char* r = getChannelData (1);
  14409. for (int i = firstDataPos; i < lastDataPos; ++i)
  14410. {
  14411. const int sourceStart = i * d->samplesPerThumbSample;
  14412. const int sourceEnd = sourceStart + d->samplesPerThumbSample;
  14413. float lowestLeft, highestLeft, lowestRight, highestRight;
  14414. reader.readMaxLevels (sourceStart,
  14415. sourceEnd - sourceStart,
  14416. lowestLeft,
  14417. highestLeft,
  14418. lowestRight,
  14419. highestRight);
  14420. int n = i * 2;
  14421. if (r != 0)
  14422. {
  14423. l [n] = (char) jlimit (-128.0f, 127.0f, lowestLeft * 127.0f);
  14424. r [n++] = (char) jlimit (-128.0f, 127.0f, lowestRight * 127.0f);
  14425. l [n] = (char) jlimit (-128.0f, 127.0f, highestLeft * 127.0f);
  14426. r [n++] = (char) jlimit (-128.0f, 127.0f, highestRight * 127.0f);
  14427. }
  14428. else
  14429. {
  14430. l [n++] = (char) jlimit (-128.0f, 127.0f, lowestLeft * 127.0f);
  14431. l [n++] = (char) jlimit (-128.0f, 127.0f, highestLeft * 127.0f);
  14432. }
  14433. }
  14434. }
  14435. char* AudioThumbnail::getChannelData (int channel) const
  14436. {
  14437. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  14438. jassert (d != 0);
  14439. if (channel >= 0 && channel < d->numChannels)
  14440. return d->data + (channel * 2 * d->numThumbnailSamples);
  14441. return 0;
  14442. }
  14443. bool AudioThumbnail::isFullyLoaded() const throw()
  14444. {
  14445. const AudioThumbnailDataFormat* const d = (const AudioThumbnailDataFormat*) data.getData();
  14446. jassert (d != 0);
  14447. return d->numFinishedSamples >= d->totalSamples;
  14448. }
  14449. void AudioThumbnail::refillCache (const int numSamples,
  14450. double startTime,
  14451. const double timePerPixel)
  14452. {
  14453. const AudioThumbnailDataFormat* const d = (const AudioThumbnailDataFormat*) data.getData();
  14454. jassert (d != 0);
  14455. if (numSamples <= 0
  14456. || timePerPixel <= 0.0
  14457. || d->sampleRate <= 0)
  14458. {
  14459. numSamplesCached = 0;
  14460. cacheNeedsRefilling = true;
  14461. return;
  14462. }
  14463. if (numSamples == numSamplesCached
  14464. && numChannelsCached == d->numChannels
  14465. && startTime == cachedStart
  14466. && timePerPixel == cachedTimePerPixel
  14467. && ! cacheNeedsRefilling)
  14468. {
  14469. return;
  14470. }
  14471. numSamplesCached = numSamples;
  14472. numChannelsCached = d->numChannels;
  14473. cachedStart = startTime;
  14474. cachedTimePerPixel = timePerPixel;
  14475. cachedLevels.ensureSize (2 * numChannelsCached * numSamples);
  14476. const bool needExtraDetail = (timePerPixel * d->sampleRate <= d->samplesPerThumbSample);
  14477. const ScopedLock sl (readerLock);
  14478. cacheNeedsRefilling = false;
  14479. if (needExtraDetail && reader == 0)
  14480. reader = createReader();
  14481. if (reader != 0 && timePerPixel * d->sampleRate <= d->samplesPerThumbSample)
  14482. {
  14483. startTimer (timeBeforeDeletingReader);
  14484. char* cacheData = (char*) cachedLevels.getData();
  14485. int sample = roundDoubleToInt (startTime * d->sampleRate);
  14486. for (int i = numSamples; --i >= 0;)
  14487. {
  14488. const int nextSample = roundDoubleToInt ((startTime + timePerPixel) * d->sampleRate);
  14489. if (sample >= 0)
  14490. {
  14491. if (sample >= reader->lengthInSamples)
  14492. break;
  14493. float lmin, lmax, rmin, rmax;
  14494. reader->readMaxLevels (sample,
  14495. jmax (1, nextSample - sample),
  14496. lmin, lmax, rmin, rmax);
  14497. cacheData[0] = (char) jlimit (-128, 127, roundFloatToInt (lmin * 127.0f));
  14498. cacheData[1] = (char) jlimit (-128, 127, roundFloatToInt (lmax * 127.0f));
  14499. if (numChannelsCached > 1)
  14500. {
  14501. cacheData[2] = (char) jlimit (-128, 127, roundFloatToInt (rmin * 127.0f));
  14502. cacheData[3] = (char) jlimit (-128, 127, roundFloatToInt (rmax * 127.0f));
  14503. }
  14504. cacheData += 2 * numChannelsCached;
  14505. }
  14506. startTime += timePerPixel;
  14507. sample = nextSample;
  14508. }
  14509. }
  14510. else
  14511. {
  14512. for (int channelNum = 0; channelNum < numChannelsCached; ++channelNum)
  14513. {
  14514. char* const data = getChannelData (channelNum);
  14515. char* cacheData = ((char*) cachedLevels.getData()) + channelNum * 2;
  14516. const double timeToThumbSampleFactor = d->sampleRate / (double) d->samplesPerThumbSample;
  14517. startTime = cachedStart;
  14518. int sample = roundDoubleToInt (startTime * timeToThumbSampleFactor);
  14519. const int numFinished = (int) (d->numFinishedSamples / d->samplesPerThumbSample);
  14520. for (int i = numSamples; --i >= 0;)
  14521. {
  14522. const int nextSample = roundDoubleToInt ((startTime + timePerPixel) * timeToThumbSampleFactor);
  14523. if (sample >= 0 && data != 0)
  14524. {
  14525. char mx = -128;
  14526. char mn = 127;
  14527. while (sample <= nextSample)
  14528. {
  14529. if (sample >= numFinished)
  14530. break;
  14531. const int n = sample << 1;
  14532. const char sampMin = data [n];
  14533. const char sampMax = data [n + 1];
  14534. if (sampMin < mn)
  14535. mn = sampMin;
  14536. if (sampMax > mx)
  14537. mx = sampMax;
  14538. ++sample;
  14539. }
  14540. if (mn <= mx)
  14541. {
  14542. cacheData[0] = mn;
  14543. cacheData[1] = mx;
  14544. }
  14545. else
  14546. {
  14547. cacheData[0] = 1;
  14548. cacheData[1] = 0;
  14549. }
  14550. }
  14551. else
  14552. {
  14553. cacheData[0] = 1;
  14554. cacheData[1] = 0;
  14555. }
  14556. cacheData += numChannelsCached * 2;
  14557. startTime += timePerPixel;
  14558. sample = nextSample;
  14559. }
  14560. }
  14561. }
  14562. }
  14563. void AudioThumbnail::drawChannel (Graphics& g,
  14564. int x, int y, int w, int h,
  14565. double startTime,
  14566. double endTime,
  14567. int channelNum,
  14568. const float verticalZoomFactor)
  14569. {
  14570. refillCache (w, startTime, (endTime - startTime) / w);
  14571. if (numSamplesCached >= w
  14572. && channelNum >= 0
  14573. && channelNum < numChannelsCached)
  14574. {
  14575. const float topY = (float) y;
  14576. const float bottomY = topY + h;
  14577. const float midY = topY + h * 0.5f;
  14578. const float vscale = verticalZoomFactor * h / 256.0f;
  14579. const Rectangle clip (g.getClipBounds());
  14580. const int skipLeft = clip.getX() - x;
  14581. w -= skipLeft;
  14582. x += skipLeft;
  14583. const char* cacheData = ((const char*) cachedLevels.getData())
  14584. + (channelNum << 1)
  14585. + skipLeft * (numChannelsCached << 1);
  14586. while (--w >= 0)
  14587. {
  14588. const char mn = cacheData[0];
  14589. const char mx = cacheData[1];
  14590. cacheData += numChannelsCached << 1;
  14591. if (mn <= mx) // if the wrong way round, signifies that the sample's not yet known
  14592. g.drawLine ((float) x, jmax (midY - mx * vscale - 0.3f, topY),
  14593. (float) x, jmin (midY - mn * vscale + 0.3f, bottomY));
  14594. ++x;
  14595. if (x >= clip.getRight())
  14596. break;
  14597. }
  14598. }
  14599. }
  14600. END_JUCE_NAMESPACE
  14601. /********* End of inlined file: juce_AudioThumbnail.cpp *********/
  14602. /********* Start of inlined file: juce_AudioThumbnailCache.cpp *********/
  14603. BEGIN_JUCE_NAMESPACE
  14604. struct ThumbnailCacheEntry
  14605. {
  14606. int64 hash;
  14607. uint32 lastUsed;
  14608. MemoryBlock data;
  14609. juce_UseDebuggingNewOperator
  14610. };
  14611. AudioThumbnailCache::AudioThumbnailCache (const int maxNumThumbsToStore_)
  14612. : TimeSliceThread (T("thumb cache")),
  14613. maxNumThumbsToStore (maxNumThumbsToStore_)
  14614. {
  14615. startThread (2);
  14616. }
  14617. AudioThumbnailCache::~AudioThumbnailCache()
  14618. {
  14619. }
  14620. bool AudioThumbnailCache::loadThumb (AudioThumbnail& thumb, const int64 hashCode)
  14621. {
  14622. for (int i = thumbs.size(); --i >= 0;)
  14623. {
  14624. if (thumbs[i]->hash == hashCode)
  14625. {
  14626. MemoryInputStream in ((const char*) thumbs[i]->data.getData(),
  14627. thumbs[i]->data.getSize(),
  14628. false);
  14629. thumb.loadFrom (in);
  14630. thumbs[i]->lastUsed = Time::getMillisecondCounter();
  14631. return true;
  14632. }
  14633. }
  14634. return false;
  14635. }
  14636. void AudioThumbnailCache::storeThumb (const AudioThumbnail& thumb,
  14637. const int64 hashCode)
  14638. {
  14639. MemoryOutputStream out;
  14640. thumb.saveTo (out);
  14641. ThumbnailCacheEntry* te = 0;
  14642. for (int i = thumbs.size(); --i >= 0;)
  14643. {
  14644. if (thumbs[i]->hash == hashCode)
  14645. {
  14646. te = thumbs[i];
  14647. break;
  14648. }
  14649. }
  14650. if (te == 0)
  14651. {
  14652. te = new ThumbnailCacheEntry();
  14653. te->hash = hashCode;
  14654. if (thumbs.size() < maxNumThumbsToStore)
  14655. {
  14656. thumbs.add (te);
  14657. }
  14658. else
  14659. {
  14660. int oldest = 0;
  14661. unsigned int oldestTime = Time::getMillisecondCounter() + 1;
  14662. int i;
  14663. for (i = thumbs.size(); --i >= 0;)
  14664. if (thumbs[i]->lastUsed < oldestTime)
  14665. oldest = i;
  14666. thumbs.set (i, te);
  14667. }
  14668. }
  14669. te->lastUsed = Time::getMillisecondCounter();
  14670. te->data.setSize (0);
  14671. te->data.append (out.getData(), out.getDataSize());
  14672. }
  14673. void AudioThumbnailCache::clear()
  14674. {
  14675. thumbs.clear();
  14676. }
  14677. void AudioThumbnailCache::addThumbnail (AudioThumbnail* const thumb)
  14678. {
  14679. addTimeSliceClient (thumb);
  14680. }
  14681. void AudioThumbnailCache::removeThumbnail (AudioThumbnail* const thumb)
  14682. {
  14683. removeTimeSliceClient (thumb);
  14684. }
  14685. END_JUCE_NAMESPACE
  14686. /********* End of inlined file: juce_AudioThumbnailCache.cpp *********/
  14687. /********* Start of inlined file: juce_QuickTimeAudioFormat.cpp *********/
  14688. #if JUCE_QUICKTIME
  14689. #if ! defined (_WIN32)
  14690. #include <Quicktime/Movies.h>
  14691. #include <Quicktime/QTML.h>
  14692. #include <Quicktime/QuickTimeComponents.h>
  14693. #include <Quicktime/MediaHandlers.h>
  14694. #include <Quicktime/ImageCodec.h>
  14695. #else
  14696. #ifdef _MSC_VER
  14697. #pragma warning (push)
  14698. #pragma warning (disable : 4100)
  14699. #endif
  14700. /* If you've got an include error here, you probably need to install the QuickTime SDK and
  14701. add its header directory to your include path.
  14702. Alternatively, if you don't need any QuickTime services, just turn off the JUC_QUICKTIME
  14703. flag in juce_Config.h
  14704. */
  14705. #include <Movies.h>
  14706. #include <QTML.h>
  14707. #include <QuickTimeComponents.h>
  14708. #include <MediaHandlers.h>
  14709. #include <ImageCodec.h>
  14710. #ifdef _MSC_VER
  14711. #pragma warning (pop)
  14712. #endif
  14713. #endif
  14714. BEGIN_JUCE_NAMESPACE
  14715. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle);
  14716. #define quickTimeFormatName TRANS("QuickTime file")
  14717. static const tchar* const quickTimeExtensions[] = { T(".mov"), T(".mp3"), T(".mp4"), 0 };
  14718. class QTAudioReader : public AudioFormatReader
  14719. {
  14720. public:
  14721. QTAudioReader (InputStream* const input_, const int trackNum_)
  14722. : AudioFormatReader (input_, quickTimeFormatName),
  14723. ok (false),
  14724. movie (0),
  14725. trackNum (trackNum_),
  14726. extractor (0),
  14727. lastSampleRead (0),
  14728. lastThreadId (0),
  14729. dataHandle (0)
  14730. {
  14731. bufferList = (AudioBufferList*) juce_calloc (256);
  14732. #ifdef WIN32
  14733. if (InitializeQTML (0) != noErr)
  14734. return;
  14735. #elif JUCE_MAC
  14736. EnterMoviesOnThread (0);
  14737. #endif
  14738. if (EnterMovies() != noErr)
  14739. return;
  14740. bool opened = juce_OpenQuickTimeMovieFromStream (input_, movie, dataHandle);
  14741. if (! opened)
  14742. return;
  14743. {
  14744. const int numTracks = GetMovieTrackCount (movie);
  14745. int trackCount = 0;
  14746. for (int i = 1; i <= numTracks; ++i)
  14747. {
  14748. track = GetMovieIndTrack (movie, i);
  14749. media = GetTrackMedia (track);
  14750. OSType mediaType;
  14751. GetMediaHandlerDescription (media, &mediaType, 0, 0);
  14752. if (mediaType == SoundMediaType
  14753. && trackCount++ == trackNum_)
  14754. {
  14755. ok = true;
  14756. break;
  14757. }
  14758. }
  14759. }
  14760. if (! ok)
  14761. return;
  14762. ok = false;
  14763. lengthInSamples = GetMediaDecodeDuration (media);
  14764. usesFloatingPointData = false;
  14765. samplesPerFrame = (int) (GetMediaDecodeDuration (media) / GetMediaSampleCount (media));
  14766. trackUnitsPerFrame = GetMovieTimeScale (movie) * samplesPerFrame
  14767. / GetMediaTimeScale (media);
  14768. OSStatus err = MovieAudioExtractionBegin (movie, 0, &extractor);
  14769. unsigned long output_layout_size;
  14770. err = MovieAudioExtractionGetPropertyInfo (extractor,
  14771. kQTPropertyClass_MovieAudioExtraction_Audio,
  14772. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  14773. 0, &output_layout_size, 0);
  14774. if (err != noErr)
  14775. return;
  14776. AudioChannelLayout* const qt_audio_channel_layout
  14777. = (AudioChannelLayout*) juce_calloc (output_layout_size);
  14778. err = MovieAudioExtractionGetProperty (extractor,
  14779. kQTPropertyClass_MovieAudioExtraction_Audio,
  14780. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  14781. output_layout_size, qt_audio_channel_layout, 0);
  14782. qt_audio_channel_layout->mChannelLayoutTag = kAudioChannelLayoutTag_Stereo;
  14783. err = MovieAudioExtractionSetProperty (extractor,
  14784. kQTPropertyClass_MovieAudioExtraction_Audio,
  14785. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  14786. sizeof (qt_audio_channel_layout),
  14787. qt_audio_channel_layout);
  14788. juce_free (qt_audio_channel_layout);
  14789. err = MovieAudioExtractionGetProperty (extractor,
  14790. kQTPropertyClass_MovieAudioExtraction_Audio,
  14791. kQTMovieAudioExtractionAudioPropertyID_AudioStreamBasicDescription,
  14792. sizeof (inputStreamDesc),
  14793. &inputStreamDesc, 0);
  14794. if (err != noErr)
  14795. return;
  14796. inputStreamDesc.mFormatFlags = kAudioFormatFlagIsSignedInteger
  14797. | kAudioFormatFlagIsPacked
  14798. | kAudioFormatFlagsNativeEndian;
  14799. inputStreamDesc.mBitsPerChannel = sizeof (SInt16) * 8;
  14800. inputStreamDesc.mChannelsPerFrame = jmin (2, inputStreamDesc.mChannelsPerFrame);
  14801. inputStreamDesc.mBytesPerFrame = sizeof (SInt16) * inputStreamDesc.mChannelsPerFrame;
  14802. inputStreamDesc.mBytesPerPacket = inputStreamDesc.mBytesPerFrame;
  14803. err = MovieAudioExtractionSetProperty (extractor,
  14804. kQTPropertyClass_MovieAudioExtraction_Audio,
  14805. kQTMovieAudioExtractionAudioPropertyID_AudioStreamBasicDescription,
  14806. sizeof (inputStreamDesc),
  14807. &inputStreamDesc);
  14808. if (err != noErr)
  14809. return;
  14810. Boolean allChannelsDiscrete = false;
  14811. err = MovieAudioExtractionSetProperty (extractor,
  14812. kQTPropertyClass_MovieAudioExtraction_Movie,
  14813. kQTMovieAudioExtractionMoviePropertyID_AllChannelsDiscrete,
  14814. sizeof (allChannelsDiscrete),
  14815. &allChannelsDiscrete);
  14816. if (err != noErr)
  14817. return;
  14818. bufferList->mNumberBuffers = 1;
  14819. bufferList->mBuffers[0].mNumberChannels = inputStreamDesc.mChannelsPerFrame;
  14820. bufferList->mBuffers[0].mDataByteSize = (UInt32) (samplesPerFrame * inputStreamDesc.mBytesPerFrame) + 16;
  14821. bufferList->mBuffers[0].mData = malloc (bufferList->mBuffers[0].mDataByteSize);
  14822. sampleRate = inputStreamDesc.mSampleRate;
  14823. bitsPerSample = 16;
  14824. numChannels = inputStreamDesc.mChannelsPerFrame;
  14825. detachThread();
  14826. ok = true;
  14827. }
  14828. ~QTAudioReader()
  14829. {
  14830. if (dataHandle != 0)
  14831. DisposeHandle (dataHandle);
  14832. if (extractor != 0)
  14833. {
  14834. MovieAudioExtractionEnd (extractor);
  14835. extractor = 0;
  14836. }
  14837. checkThreadIsAttached();
  14838. DisposeMovie (movie);
  14839. juce_free (bufferList->mBuffers[0].mData);
  14840. juce_free (bufferList);
  14841. #if JUCE_MAC
  14842. ExitMoviesOnThread ();
  14843. #endif
  14844. }
  14845. bool read (int** destSamples,
  14846. int64 startSample,
  14847. int numSamples)
  14848. {
  14849. checkThreadIsAttached();
  14850. int done = 0;
  14851. while (numSamples > 0)
  14852. {
  14853. if (! loadFrame ((int) startSample))
  14854. return false;
  14855. const int numToDo = jmin (numSamples, samplesPerFrame);
  14856. for (unsigned int j = 0; j < inputStreamDesc.mChannelsPerFrame; ++j)
  14857. {
  14858. if (destSamples[j] != 0)
  14859. {
  14860. const short* const src = ((const short*) bufferList->mBuffers[0].mData) + j;
  14861. for (int i = 0; i < numToDo; ++i)
  14862. destSamples[j][done + i] = src [i << 1] << 16;
  14863. }
  14864. }
  14865. done += numToDo;
  14866. startSample += numToDo;
  14867. numSamples -= numToDo;
  14868. }
  14869. detachThread();
  14870. return true;
  14871. }
  14872. bool loadFrame (const int sampleNum)
  14873. {
  14874. if (lastSampleRead != sampleNum)
  14875. {
  14876. TimeRecord time;
  14877. time.scale = (TimeScale) inputStreamDesc.mSampleRate;
  14878. time.base = 0;
  14879. time.value.hi = 0;
  14880. time.value.lo = (UInt32) sampleNum;
  14881. OSStatus err = MovieAudioExtractionSetProperty (extractor,
  14882. kQTPropertyClass_MovieAudioExtraction_Movie,
  14883. kQTMovieAudioExtractionMoviePropertyID_CurrentTime,
  14884. sizeof (time), &time);
  14885. if (err != noErr)
  14886. return false;
  14887. }
  14888. bufferList->mBuffers[0].mDataByteSize = inputStreamDesc.mBytesPerFrame * samplesPerFrame;
  14889. UInt32 outFlags = 0;
  14890. UInt32 actualNumSamples = samplesPerFrame;
  14891. OSStatus err = MovieAudioExtractionFillBuffer (extractor, &actualNumSamples,
  14892. bufferList, &outFlags);
  14893. lastSampleRead = sampleNum + samplesPerFrame;
  14894. return err == noErr;
  14895. }
  14896. juce_UseDebuggingNewOperator
  14897. bool ok;
  14898. private:
  14899. Movie movie;
  14900. Media media;
  14901. Track track;
  14902. const int trackNum;
  14903. double trackUnitsPerFrame;
  14904. int samplesPerFrame;
  14905. int lastSampleRead, lastThreadId;
  14906. MovieAudioExtractionRef extractor;
  14907. AudioStreamBasicDescription inputStreamDesc;
  14908. AudioBufferList* bufferList;
  14909. Handle dataHandle;
  14910. /*OSErr readMovieStream (long offset, long size, void* dataPtr)
  14911. {
  14912. input->setPosition (offset);
  14913. input->read (dataPtr, size);
  14914. return noErr;
  14915. }
  14916. static OSErr readMovieStreamProc (long offset, long size, void* dataPtr, void* userRef)
  14917. {
  14918. return ((QTAudioReader*) userRef)->readMovieStream (offset, size, dataPtr);
  14919. }*/
  14920. void checkThreadIsAttached()
  14921. {
  14922. #if JUCE_MAC
  14923. if (Thread::getCurrentThreadId() != lastThreadId)
  14924. EnterMoviesOnThread (0);
  14925. AttachMovieToCurrentThread (movie);
  14926. #endif
  14927. }
  14928. void detachThread()
  14929. {
  14930. #if JUCE_MAC
  14931. DetachMovieFromCurrentThread (movie);
  14932. #endif
  14933. }
  14934. };
  14935. QuickTimeAudioFormat::QuickTimeAudioFormat()
  14936. : AudioFormat (quickTimeFormatName, (const tchar**) quickTimeExtensions)
  14937. {
  14938. }
  14939. QuickTimeAudioFormat::~QuickTimeAudioFormat()
  14940. {
  14941. }
  14942. const Array <int> QuickTimeAudioFormat::getPossibleSampleRates()
  14943. {
  14944. return Array<int>();
  14945. }
  14946. const Array <int> QuickTimeAudioFormat::getPossibleBitDepths()
  14947. {
  14948. return Array<int>();
  14949. }
  14950. bool QuickTimeAudioFormat::canDoStereo()
  14951. {
  14952. return true;
  14953. }
  14954. bool QuickTimeAudioFormat::canDoMono()
  14955. {
  14956. return true;
  14957. }
  14958. AudioFormatReader* QuickTimeAudioFormat::createReaderFor (InputStream* sourceStream,
  14959. const bool deleteStreamIfOpeningFails)
  14960. {
  14961. QTAudioReader* r = new QTAudioReader (sourceStream, 0);
  14962. if (! r->ok)
  14963. {
  14964. if (! deleteStreamIfOpeningFails)
  14965. r->input = 0;
  14966. deleteAndZero (r);
  14967. }
  14968. return r;
  14969. }
  14970. AudioFormatWriter* QuickTimeAudioFormat::createWriterFor (OutputStream* /*streamToWriteTo*/,
  14971. double /*sampleRateToUse*/,
  14972. unsigned int /*numberOfChannels*/,
  14973. int /*bitsPerSample*/,
  14974. const StringPairArray& /*metadataValues*/,
  14975. int /*qualityOptionIndex*/)
  14976. {
  14977. jassertfalse // not yet implemented!
  14978. return 0;
  14979. }
  14980. END_JUCE_NAMESPACE
  14981. #endif
  14982. /********* End of inlined file: juce_QuickTimeAudioFormat.cpp *********/
  14983. /********* Start of inlined file: juce_WavAudioFormat.cpp *********/
  14984. BEGIN_JUCE_NAMESPACE
  14985. #define wavFormatName TRANS("WAV file")
  14986. static const tchar* const wavExtensions[] = { T(".wav"), T(".bwf"), 0 };
  14987. const tchar* const WavAudioFormat::bwavDescription = T("bwav description");
  14988. const tchar* const WavAudioFormat::bwavOriginator = T("bwav originator");
  14989. const tchar* const WavAudioFormat::bwavOriginatorRef = T("bwav originator ref");
  14990. const tchar* const WavAudioFormat::bwavOriginationDate = T("bwav origination date");
  14991. const tchar* const WavAudioFormat::bwavOriginationTime = T("bwav origination time");
  14992. const tchar* const WavAudioFormat::bwavTimeReference = T("bwav time reference");
  14993. const tchar* const WavAudioFormat::bwavCodingHistory = T("bwav coding history");
  14994. const StringPairArray WavAudioFormat::createBWAVMetadata (const String& description,
  14995. const String& originator,
  14996. const String& originatorRef,
  14997. const Time& date,
  14998. const int64 timeReferenceSamples,
  14999. const String& codingHistory)
  15000. {
  15001. StringPairArray m;
  15002. m.set (bwavDescription, description);
  15003. m.set (bwavOriginator, originator);
  15004. m.set (bwavOriginatorRef, originatorRef);
  15005. m.set (bwavOriginationDate, date.formatted (T("%Y-%m-%d")));
  15006. m.set (bwavOriginationTime, date.formatted (T("%H:%M:%S")));
  15007. m.set (bwavTimeReference, String (timeReferenceSamples));
  15008. m.set (bwavCodingHistory, codingHistory);
  15009. return m;
  15010. }
  15011. #if JUCE_MSVC
  15012. #pragma pack (push, 1)
  15013. #define PACKED
  15014. #elif defined (JUCE_GCC)
  15015. #define PACKED __attribute__((packed))
  15016. #else
  15017. #define PACKED
  15018. #endif
  15019. struct BWAVChunk
  15020. {
  15021. char description [256];
  15022. char originator [32];
  15023. char originatorRef [32];
  15024. char originationDate [10];
  15025. char originationTime [8];
  15026. uint32 timeRefLow;
  15027. uint32 timeRefHigh;
  15028. uint16 version;
  15029. uint8 umid[64];
  15030. uint8 reserved[190];
  15031. char codingHistory[1];
  15032. void copyTo (StringPairArray& values) const
  15033. {
  15034. values.set (WavAudioFormat::bwavDescription, String (description, 256));
  15035. values.set (WavAudioFormat::bwavOriginator, String (originator, 32));
  15036. values.set (WavAudioFormat::bwavOriginatorRef, String (originatorRef, 32));
  15037. values.set (WavAudioFormat::bwavOriginationDate, String (originationDate, 10));
  15038. values.set (WavAudioFormat::bwavOriginationTime, String (originationTime, 8));
  15039. const uint32 timeLow = swapIfBigEndian (timeRefLow);
  15040. const uint32 timeHigh = swapIfBigEndian (timeRefHigh);
  15041. const int64 time = (((int64)timeHigh) << 32) + timeLow;
  15042. values.set (WavAudioFormat::bwavTimeReference, String (time));
  15043. values.set (WavAudioFormat::bwavCodingHistory, String (codingHistory));
  15044. }
  15045. static MemoryBlock createFrom (const StringPairArray& values)
  15046. {
  15047. const int sizeNeeded = sizeof (BWAVChunk) + values [WavAudioFormat::bwavCodingHistory].length();
  15048. MemoryBlock data ((sizeNeeded + 3) & ~3);
  15049. data.fillWith (0);
  15050. BWAVChunk* b = (BWAVChunk*) data.getData();
  15051. // although copyToBuffer may overrun by one byte, that's ok as long as these
  15052. // operations get done in the right order
  15053. values [WavAudioFormat::bwavDescription].copyToBuffer (b->description, 256);
  15054. values [WavAudioFormat::bwavOriginator].copyToBuffer (b->originator, 32);
  15055. values [WavAudioFormat::bwavOriginatorRef].copyToBuffer (b->originatorRef, 32);
  15056. values [WavAudioFormat::bwavOriginationDate].copyToBuffer (b->originationDate, 10);
  15057. values [WavAudioFormat::bwavOriginationTime].copyToBuffer (b->originationTime, 8);
  15058. const int64 time = values [WavAudioFormat::bwavTimeReference].getLargeIntValue();
  15059. b->timeRefLow = swapIfBigEndian ((uint32) (time & 0xffffffff));
  15060. b->timeRefHigh = swapIfBigEndian ((uint32) (time >> 32));
  15061. values [WavAudioFormat::bwavCodingHistory].copyToBuffer (b->codingHistory, 256 * 1024);
  15062. if (b->description[0] != 0
  15063. || b->originator[0] != 0
  15064. || b->originationDate[0] != 0
  15065. || b->originationTime[0] != 0
  15066. || b->codingHistory[0] != 0
  15067. || time != 0)
  15068. {
  15069. return data;
  15070. }
  15071. return MemoryBlock();
  15072. }
  15073. } PACKED;
  15074. #if JUCE_MSVC
  15075. #pragma pack (pop)
  15076. #endif
  15077. #undef PACKED
  15078. #undef chunkName
  15079. #define chunkName(a) ((int) littleEndianInt(a))
  15080. class WavAudioFormatReader : public AudioFormatReader
  15081. {
  15082. int bytesPerFrame;
  15083. int64 dataChunkStart, dataLength;
  15084. WavAudioFormatReader (const WavAudioFormatReader&);
  15085. const WavAudioFormatReader& operator= (const WavAudioFormatReader&);
  15086. public:
  15087. WavAudioFormatReader (InputStream* const in)
  15088. : AudioFormatReader (in, wavFormatName),
  15089. dataLength (0)
  15090. {
  15091. if (input->readInt() == chunkName ("RIFF"))
  15092. {
  15093. const uint32 len = (uint32) input->readInt();
  15094. const int64 end = input->getPosition() + len;
  15095. bool hasGotType = false;
  15096. bool hasGotData = false;
  15097. if (input->readInt() == chunkName ("WAVE"))
  15098. {
  15099. while (input->getPosition() < end
  15100. && ! input->isExhausted())
  15101. {
  15102. const int chunkType = input->readInt();
  15103. uint32 length = (uint32) input->readInt();
  15104. const int64 chunkEnd = input->getPosition() + length + (length & 1);
  15105. if (chunkType == chunkName ("fmt "))
  15106. {
  15107. // read the format chunk
  15108. const short format = input->readShort();
  15109. const short numChans = input->readShort();
  15110. sampleRate = input->readInt();
  15111. const int bytesPerSec = input->readInt();
  15112. numChannels = numChans;
  15113. bytesPerFrame = bytesPerSec / (int)sampleRate;
  15114. bitsPerSample = 8 * bytesPerFrame / numChans;
  15115. if (format == 3)
  15116. usesFloatingPointData = true;
  15117. else if (format != 1)
  15118. bytesPerFrame = 0;
  15119. hasGotType = true;
  15120. }
  15121. else if (chunkType == chunkName ("data"))
  15122. {
  15123. // get the data chunk's position
  15124. dataLength = length;
  15125. dataChunkStart = input->getPosition();
  15126. lengthInSamples = (bytesPerFrame > 0) ? (dataLength / bytesPerFrame) : 0;
  15127. hasGotData = true;
  15128. }
  15129. else if (chunkType == chunkName ("bext"))
  15130. {
  15131. // Broadcast-wav extension chunk..
  15132. BWAVChunk* const bwav = (BWAVChunk*) juce_calloc (jmax (length + 1, (int) sizeof (BWAVChunk)));
  15133. if (bwav != 0)
  15134. {
  15135. input->read (bwav, length);
  15136. bwav->copyTo (metadataValues);
  15137. juce_free (bwav);
  15138. }
  15139. }
  15140. else if ((hasGotType && hasGotData) || chunkEnd <= input->getPosition())
  15141. {
  15142. break;
  15143. }
  15144. input->setPosition (chunkEnd);
  15145. }
  15146. }
  15147. }
  15148. }
  15149. ~WavAudioFormatReader()
  15150. {
  15151. }
  15152. bool read (int** destSamples,
  15153. int64 startSampleInFile,
  15154. int numSamples)
  15155. {
  15156. int64 start = startSampleInFile;
  15157. int startOffsetInDestBuffer = 0;
  15158. if (startSampleInFile < 0)
  15159. {
  15160. const int silence = (int) jmin (-startSampleInFile, (int64) numSamples);
  15161. int** destChan = destSamples;
  15162. for (int i = 2; --i >= 0;)
  15163. {
  15164. if (*destChan != 0)
  15165. {
  15166. zeromem (*destChan, sizeof (int) * silence);
  15167. ++destChan;
  15168. }
  15169. }
  15170. startOffsetInDestBuffer += silence;
  15171. numSamples -= silence;
  15172. start = 0;
  15173. }
  15174. const int numToDo = (int) jlimit ((int64) 0, (int64) numSamples, lengthInSamples - start);
  15175. if (numToDo > 0)
  15176. {
  15177. input->setPosition (dataChunkStart + start * bytesPerFrame);
  15178. int num = numToDo;
  15179. int* left = destSamples[0];
  15180. if (left != 0)
  15181. left += startOffsetInDestBuffer;
  15182. int* right = destSamples[1];
  15183. if (right != 0)
  15184. right += startOffsetInDestBuffer;
  15185. // (keep this a multiple of 3)
  15186. const int tempBufSize = 1440 * 4;
  15187. char tempBuffer [tempBufSize];
  15188. while (num > 0)
  15189. {
  15190. const int numThisTime = jmin (tempBufSize / bytesPerFrame, num);
  15191. const int bytesRead = input->read (tempBuffer, numThisTime * bytesPerFrame);
  15192. if (bytesRead < numThisTime * bytesPerFrame)
  15193. zeromem (tempBuffer + bytesRead, numThisTime * bytesPerFrame - bytesRead);
  15194. if (bitsPerSample == 16)
  15195. {
  15196. const short* src = (const short*) tempBuffer;
  15197. if (numChannels > 1)
  15198. {
  15199. if (left == 0)
  15200. {
  15201. for (int i = numThisTime; --i >= 0;)
  15202. {
  15203. ++src;
  15204. *right++ = (int) swapIfBigEndian ((unsigned short) *src++) << 16;
  15205. }
  15206. }
  15207. else if (right == 0)
  15208. {
  15209. for (int i = numThisTime; --i >= 0;)
  15210. {
  15211. *left++ = (int) swapIfBigEndian ((unsigned short) *src++) << 16;
  15212. ++src;
  15213. }
  15214. }
  15215. else
  15216. {
  15217. for (int i = numThisTime; --i >= 0;)
  15218. {
  15219. *left++ = (int) swapIfBigEndian ((unsigned short) *src++) << 16;
  15220. *right++ = (int) swapIfBigEndian ((unsigned short) *src++) << 16;
  15221. }
  15222. }
  15223. }
  15224. else
  15225. {
  15226. for (int i = numThisTime; --i >= 0;)
  15227. {
  15228. *left++ = (int) swapIfBigEndian ((unsigned short) *src++) << 16;
  15229. }
  15230. }
  15231. }
  15232. else if (bitsPerSample == 24)
  15233. {
  15234. const char* src = (const char*) tempBuffer;
  15235. if (numChannels > 1)
  15236. {
  15237. if (left == 0)
  15238. {
  15239. for (int i = numThisTime; --i >= 0;)
  15240. {
  15241. src += 6;
  15242. *right++ = littleEndian24Bit (src) << 8;
  15243. }
  15244. }
  15245. else if (right == 0)
  15246. {
  15247. for (int i = numThisTime; --i >= 0;)
  15248. {
  15249. *left++ = littleEndian24Bit (src) << 8;
  15250. src += 6;
  15251. }
  15252. }
  15253. else
  15254. {
  15255. for (int i = 0; i < numThisTime; ++i)
  15256. {
  15257. *left++ = littleEndian24Bit (src) << 8;
  15258. src += 3;
  15259. *right++ = littleEndian24Bit (src) << 8;
  15260. src += 3;
  15261. }
  15262. }
  15263. }
  15264. else
  15265. {
  15266. for (int i = 0; i < numThisTime; ++i)
  15267. {
  15268. *left++ = littleEndian24Bit (src) << 8;
  15269. src += 3;
  15270. }
  15271. }
  15272. }
  15273. else if (bitsPerSample == 32)
  15274. {
  15275. const unsigned int* src = (const unsigned int*) tempBuffer;
  15276. unsigned int* l = (unsigned int*) left;
  15277. unsigned int* r = (unsigned int*) right;
  15278. if (numChannels > 1)
  15279. {
  15280. if (l == 0)
  15281. {
  15282. for (int i = numThisTime; --i >= 0;)
  15283. {
  15284. ++src;
  15285. *r++ = swapIfBigEndian (*src++);
  15286. }
  15287. }
  15288. else if (r == 0)
  15289. {
  15290. for (int i = numThisTime; --i >= 0;)
  15291. {
  15292. *l++ = swapIfBigEndian (*src++);
  15293. ++src;
  15294. }
  15295. }
  15296. else
  15297. {
  15298. for (int i = numThisTime; --i >= 0;)
  15299. {
  15300. *l++ = swapIfBigEndian (*src++);
  15301. *r++ = swapIfBigEndian (*src++);
  15302. }
  15303. }
  15304. }
  15305. else
  15306. {
  15307. for (int i = numThisTime; --i >= 0;)
  15308. {
  15309. *l++ = swapIfBigEndian (*src++);
  15310. }
  15311. }
  15312. left = (int*)l;
  15313. right = (int*)r;
  15314. }
  15315. else if (bitsPerSample == 8)
  15316. {
  15317. const unsigned char* src = (const unsigned char*) tempBuffer;
  15318. if (numChannels > 1)
  15319. {
  15320. if (left == 0)
  15321. {
  15322. for (int i = numThisTime; --i >= 0;)
  15323. {
  15324. ++src;
  15325. *right++ = ((int) *src++ - 128) << 24;
  15326. }
  15327. }
  15328. else if (right == 0)
  15329. {
  15330. for (int i = numThisTime; --i >= 0;)
  15331. {
  15332. *left++ = ((int) *src++ - 128) << 24;
  15333. ++src;
  15334. }
  15335. }
  15336. else
  15337. {
  15338. for (int i = numThisTime; --i >= 0;)
  15339. {
  15340. *left++ = ((int) *src++ - 128) << 24;
  15341. *right++ = ((int) *src++ - 128) << 24;
  15342. }
  15343. }
  15344. }
  15345. else
  15346. {
  15347. for (int i = numThisTime; --i >= 0;)
  15348. {
  15349. *left++ = ((int)*src++ - 128) << 24;
  15350. }
  15351. }
  15352. }
  15353. num -= numThisTime;
  15354. }
  15355. }
  15356. if (numToDo < numSamples)
  15357. {
  15358. int** destChan = destSamples;
  15359. while (*destChan != 0)
  15360. {
  15361. zeromem ((*destChan) + (startOffsetInDestBuffer + numToDo),
  15362. sizeof (int) * (numSamples - numToDo));
  15363. ++destChan;
  15364. }
  15365. }
  15366. return true;
  15367. }
  15368. juce_UseDebuggingNewOperator
  15369. };
  15370. class WavAudioFormatWriter : public AudioFormatWriter
  15371. {
  15372. MemoryBlock tempBlock, bwavChunk;
  15373. uint32 lengthInSamples, bytesWritten;
  15374. int64 headerPosition;
  15375. bool writeFailed;
  15376. WavAudioFormatWriter (const WavAudioFormatWriter&);
  15377. const WavAudioFormatWriter& operator= (const WavAudioFormatWriter&);
  15378. void writeHeader()
  15379. {
  15380. const bool seekedOk = output->setPosition (headerPosition);
  15381. (void) seekedOk;
  15382. // if this fails, you've given it an output stream that can't seek! It needs
  15383. // to be able to seek back to write the header
  15384. jassert (seekedOk);
  15385. const int bytesPerFrame = numChannels * bitsPerSample / 8;
  15386. output->writeInt (chunkName ("RIFF"));
  15387. output->writeInt (lengthInSamples * bytesPerFrame
  15388. + ((bwavChunk.getSize() > 0) ? (44 + bwavChunk.getSize()) : 36));
  15389. output->writeInt (chunkName ("WAVE"));
  15390. output->writeInt (chunkName ("fmt "));
  15391. output->writeInt (16);
  15392. output->writeShort ((bitsPerSample < 32) ? (short) 1 /*WAVE_FORMAT_PCM*/
  15393. : (short) 3 /*WAVE_FORMAT_IEEE_FLOAT*/);
  15394. output->writeShort ((short) numChannels);
  15395. output->writeInt ((int) sampleRate);
  15396. output->writeInt (bytesPerFrame * (int) sampleRate);
  15397. output->writeShort ((short) bytesPerFrame);
  15398. output->writeShort ((short) bitsPerSample);
  15399. if (bwavChunk.getSize() > 0)
  15400. {
  15401. output->writeInt (chunkName ("bext"));
  15402. output->writeInt (bwavChunk.getSize());
  15403. output->write (bwavChunk.getData(), bwavChunk.getSize());
  15404. }
  15405. output->writeInt (chunkName ("data"));
  15406. output->writeInt (lengthInSamples * bytesPerFrame);
  15407. usesFloatingPointData = (bitsPerSample == 32);
  15408. }
  15409. public:
  15410. WavAudioFormatWriter (OutputStream* const out,
  15411. const double sampleRate,
  15412. const unsigned int numChannels_,
  15413. const int bits,
  15414. const StringPairArray& metadataValues)
  15415. : AudioFormatWriter (out,
  15416. wavFormatName,
  15417. sampleRate,
  15418. numChannels_,
  15419. bits),
  15420. lengthInSamples (0),
  15421. bytesWritten (0),
  15422. writeFailed (false)
  15423. {
  15424. if (metadataValues.size() > 0)
  15425. bwavChunk = BWAVChunk::createFrom (metadataValues);
  15426. headerPosition = out->getPosition();
  15427. writeHeader();
  15428. }
  15429. ~WavAudioFormatWriter()
  15430. {
  15431. writeHeader();
  15432. }
  15433. bool write (const int** data, int numSamples)
  15434. {
  15435. if (writeFailed)
  15436. return false;
  15437. const int bytes = numChannels * numSamples * bitsPerSample / 8;
  15438. tempBlock.ensureSize (bytes, false);
  15439. char* buffer = (char*) tempBlock.getData();
  15440. const int* left = data[0];
  15441. const int* right = data[1];
  15442. if (right == 0)
  15443. right = left;
  15444. if (bitsPerSample == 16)
  15445. {
  15446. short* b = (short*) buffer;
  15447. if (numChannels > 1)
  15448. {
  15449. for (int i = numSamples; --i >= 0;)
  15450. {
  15451. *b++ = (short) swapIfBigEndian ((unsigned short) (*left++ >> 16));
  15452. *b++ = (short) swapIfBigEndian ((unsigned short) (*right++ >> 16));
  15453. }
  15454. }
  15455. else
  15456. {
  15457. for (int i = numSamples; --i >= 0;)
  15458. {
  15459. *b++ = (short) swapIfBigEndian ((unsigned short) (*left++ >> 16));
  15460. }
  15461. }
  15462. }
  15463. else if (bitsPerSample == 24)
  15464. {
  15465. char* b = (char*) buffer;
  15466. if (numChannels > 1)
  15467. {
  15468. for (int i = numSamples; --i >= 0;)
  15469. {
  15470. littleEndian24BitToChars ((*left++) >> 8, b);
  15471. b += 3;
  15472. littleEndian24BitToChars ((*right++) >> 8, b);
  15473. b += 3;
  15474. }
  15475. }
  15476. else
  15477. {
  15478. for (int i = numSamples; --i >= 0;)
  15479. {
  15480. littleEndian24BitToChars ((*left++) >> 8, b);
  15481. b += 3;
  15482. }
  15483. }
  15484. }
  15485. else if (bitsPerSample == 32)
  15486. {
  15487. unsigned int* b = (unsigned int*) buffer;
  15488. if (numChannels > 1)
  15489. {
  15490. for (int i = numSamples; --i >= 0;)
  15491. {
  15492. *b++ = swapIfBigEndian ((unsigned int) *left++);
  15493. *b++ = swapIfBigEndian ((unsigned int) *right++);
  15494. }
  15495. }
  15496. else
  15497. {
  15498. for (int i = numSamples; --i >= 0;)
  15499. {
  15500. *b++ = swapIfBigEndian ((unsigned int) *left++);
  15501. }
  15502. }
  15503. }
  15504. else if (bitsPerSample == 8)
  15505. {
  15506. unsigned char* b = (unsigned char*) buffer;
  15507. if (numChannels > 1)
  15508. {
  15509. for (int i = numSamples; --i >= 0;)
  15510. {
  15511. *b++ = (unsigned char) (128 + (*left++ >> 24));
  15512. *b++ = (unsigned char) (128 + (*right++ >> 24));
  15513. }
  15514. }
  15515. else
  15516. {
  15517. for (int i = numSamples; --i >= 0;)
  15518. {
  15519. *b++ = (unsigned char) (128 + (*left++ >> 24));
  15520. }
  15521. }
  15522. }
  15523. if (bytesWritten + bytes >= (uint32) 0xfff00000
  15524. || ! output->write (buffer, bytes))
  15525. {
  15526. // failed to write to disk, so let's try writing the header.
  15527. // If it's just run out of disk space, then if it does manage
  15528. // to write the header, we'll still have a useable file..
  15529. writeHeader();
  15530. writeFailed = true;
  15531. return false;
  15532. }
  15533. else
  15534. {
  15535. bytesWritten += bytes;
  15536. lengthInSamples += numSamples;
  15537. return true;
  15538. }
  15539. }
  15540. juce_UseDebuggingNewOperator
  15541. };
  15542. WavAudioFormat::WavAudioFormat()
  15543. : AudioFormat (wavFormatName, (const tchar**) wavExtensions)
  15544. {
  15545. }
  15546. WavAudioFormat::~WavAudioFormat()
  15547. {
  15548. }
  15549. const Array <int> WavAudioFormat::getPossibleSampleRates()
  15550. {
  15551. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  15552. return Array <int> (rates);
  15553. }
  15554. const Array <int> WavAudioFormat::getPossibleBitDepths()
  15555. {
  15556. const int depths[] = { 8, 16, 24, 32, 0 };
  15557. return Array <int> (depths);
  15558. }
  15559. bool WavAudioFormat::canDoStereo()
  15560. {
  15561. return true;
  15562. }
  15563. bool WavAudioFormat::canDoMono()
  15564. {
  15565. return true;
  15566. }
  15567. AudioFormatReader* WavAudioFormat::createReaderFor (InputStream* sourceStream,
  15568. const bool deleteStreamIfOpeningFails)
  15569. {
  15570. WavAudioFormatReader* r = new WavAudioFormatReader (sourceStream);
  15571. if (r->sampleRate == 0)
  15572. {
  15573. if (! deleteStreamIfOpeningFails)
  15574. r->input = 0;
  15575. deleteAndZero (r);
  15576. }
  15577. return r;
  15578. }
  15579. AudioFormatWriter* WavAudioFormat::createWriterFor (OutputStream* out,
  15580. double sampleRate,
  15581. unsigned int numChannels,
  15582. int bitsPerSample,
  15583. const StringPairArray& metadataValues,
  15584. int /*qualityOptionIndex*/)
  15585. {
  15586. if (getPossibleBitDepths().contains (bitsPerSample))
  15587. {
  15588. return new WavAudioFormatWriter (out,
  15589. sampleRate,
  15590. numChannels,
  15591. bitsPerSample,
  15592. metadataValues);
  15593. }
  15594. return 0;
  15595. }
  15596. END_JUCE_NAMESPACE
  15597. /********* End of inlined file: juce_WavAudioFormat.cpp *********/
  15598. /********* Start of inlined file: juce_AudioFormatReaderSource.cpp *********/
  15599. BEGIN_JUCE_NAMESPACE
  15600. AudioFormatReaderSource::AudioFormatReaderSource (AudioFormatReader* const reader_,
  15601. const bool deleteReaderWhenThisIsDeleted)
  15602. : reader (reader_),
  15603. deleteReader (deleteReaderWhenThisIsDeleted),
  15604. nextPlayPos (0),
  15605. looping (false)
  15606. {
  15607. jassert (reader != 0);
  15608. }
  15609. AudioFormatReaderSource::~AudioFormatReaderSource()
  15610. {
  15611. releaseResources();
  15612. if (deleteReader)
  15613. delete reader;
  15614. }
  15615. void AudioFormatReaderSource::setNextReadPosition (int newPosition)
  15616. {
  15617. nextPlayPos = newPosition;
  15618. }
  15619. void AudioFormatReaderSource::setLooping (const bool shouldLoop) throw()
  15620. {
  15621. looping = shouldLoop;
  15622. }
  15623. int AudioFormatReaderSource::getNextReadPosition() const
  15624. {
  15625. return (looping) ? (nextPlayPos % (int) reader->lengthInSamples)
  15626. : nextPlayPos;
  15627. }
  15628. int AudioFormatReaderSource::getTotalLength() const
  15629. {
  15630. return (int) reader->lengthInSamples;
  15631. }
  15632. void AudioFormatReaderSource::prepareToPlay (int /*samplesPerBlockExpected*/,
  15633. double /*sampleRate*/)
  15634. {
  15635. }
  15636. void AudioFormatReaderSource::releaseResources()
  15637. {
  15638. }
  15639. void AudioFormatReaderSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  15640. {
  15641. if (info.numSamples > 0)
  15642. {
  15643. const int start = nextPlayPos;
  15644. if (looping)
  15645. {
  15646. const int newStart = start % (int) reader->lengthInSamples;
  15647. const int newEnd = (start + info.numSamples) % (int) reader->lengthInSamples;
  15648. if (newEnd > newStart)
  15649. {
  15650. info.buffer->readFromAudioReader (reader,
  15651. info.startSample,
  15652. newEnd - newStart,
  15653. newStart,
  15654. true, true);
  15655. }
  15656. else
  15657. {
  15658. const int endSamps = (int) reader->lengthInSamples - newStart;
  15659. info.buffer->readFromAudioReader (reader,
  15660. info.startSample,
  15661. endSamps,
  15662. newStart,
  15663. true, true);
  15664. info.buffer->readFromAudioReader (reader,
  15665. info.startSample + endSamps,
  15666. newEnd,
  15667. 0,
  15668. true, true);
  15669. }
  15670. nextPlayPos = newEnd;
  15671. }
  15672. else
  15673. {
  15674. info.buffer->readFromAudioReader (reader,
  15675. info.startSample,
  15676. info.numSamples,
  15677. start,
  15678. true, true);
  15679. nextPlayPos += info.numSamples;
  15680. }
  15681. }
  15682. }
  15683. END_JUCE_NAMESPACE
  15684. /********* End of inlined file: juce_AudioFormatReaderSource.cpp *********/
  15685. /********* Start of inlined file: juce_AudioSourcePlayer.cpp *********/
  15686. BEGIN_JUCE_NAMESPACE
  15687. AudioSourcePlayer::AudioSourcePlayer()
  15688. : source (0),
  15689. sampleRate (0),
  15690. bufferSize (0),
  15691. tempBuffer (2, 8),
  15692. lastGain (1.0f),
  15693. gain (1.0f)
  15694. {
  15695. }
  15696. AudioSourcePlayer::~AudioSourcePlayer()
  15697. {
  15698. setSource (0);
  15699. }
  15700. void AudioSourcePlayer::setSource (AudioSource* newSource)
  15701. {
  15702. if (source != newSource)
  15703. {
  15704. AudioSource* const oldSource = source;
  15705. if (newSource != 0 && bufferSize > 0 && sampleRate > 0)
  15706. newSource->prepareToPlay (bufferSize, sampleRate);
  15707. {
  15708. const ScopedLock sl (readLock);
  15709. source = newSource;
  15710. }
  15711. if (oldSource != 0)
  15712. oldSource->releaseResources();
  15713. }
  15714. }
  15715. void AudioSourcePlayer::setGain (const float newGain) throw()
  15716. {
  15717. gain = newGain;
  15718. }
  15719. void AudioSourcePlayer::audioDeviceIOCallback (const float** inputChannelData,
  15720. int totalNumInputChannels,
  15721. float** outputChannelData,
  15722. int totalNumOutputChannels,
  15723. int numSamples)
  15724. {
  15725. // these should have been prepared by audioDeviceAboutToStart()...
  15726. jassert (sampleRate > 0 && bufferSize > 0);
  15727. const ScopedLock sl (readLock);
  15728. if (source != 0)
  15729. {
  15730. AudioSourceChannelInfo info;
  15731. int i, numActiveChans = 0, numInputs = 0, numOutputs = 0;
  15732. // messy stuff needed to compact the channels down into an array
  15733. // of non-zero pointers..
  15734. for (i = 0; i < totalNumInputChannels; ++i)
  15735. {
  15736. if (inputChannelData[i] != 0)
  15737. {
  15738. inputChans [numInputs++] = inputChannelData[i];
  15739. if (numInputs >= numElementsInArray (inputChans))
  15740. break;
  15741. }
  15742. }
  15743. for (i = 0; i < totalNumOutputChannels; ++i)
  15744. {
  15745. if (outputChannelData[i] != 0)
  15746. {
  15747. outputChans [numOutputs++] = outputChannelData[i];
  15748. if (numOutputs >= numElementsInArray (outputChans))
  15749. break;
  15750. }
  15751. }
  15752. if (numInputs > numOutputs)
  15753. {
  15754. // if there aren't enough output channels for the number of
  15755. // inputs, we need to create some temporary extra ones (can't
  15756. // use the input data in case it gets written to)
  15757. tempBuffer.setSize (numInputs - numOutputs, numSamples,
  15758. false, false, true);
  15759. for (i = 0; i < numOutputs; ++i)
  15760. {
  15761. channels[numActiveChans] = outputChans[i];
  15762. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  15763. ++numActiveChans;
  15764. }
  15765. for (i = numOutputs; i < numInputs; ++i)
  15766. {
  15767. channels[numActiveChans] = tempBuffer.getSampleData (i - numOutputs, 0);
  15768. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  15769. ++numActiveChans;
  15770. }
  15771. }
  15772. else
  15773. {
  15774. for (i = 0; i < numInputs; ++i)
  15775. {
  15776. channels[numActiveChans] = outputChans[i];
  15777. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  15778. ++numActiveChans;
  15779. }
  15780. for (i = numInputs; i < numOutputs; ++i)
  15781. {
  15782. channels[numActiveChans] = outputChans[i];
  15783. zeromem (channels[numActiveChans], sizeof (float) * numSamples);
  15784. ++numActiveChans;
  15785. }
  15786. }
  15787. AudioSampleBuffer buffer (channels, numActiveChans, numSamples);
  15788. info.buffer = &buffer;
  15789. info.startSample = 0;
  15790. info.numSamples = numSamples;
  15791. source->getNextAudioBlock (info);
  15792. for (int i = info.buffer->getNumChannels(); --i >= 0;)
  15793. info.buffer->applyGainRamp (i, info.startSample, info.numSamples, lastGain, gain);
  15794. lastGain = gain;
  15795. }
  15796. else
  15797. {
  15798. for (int i = 0; i < totalNumOutputChannels; ++i)
  15799. if (outputChannelData[i] != 0)
  15800. zeromem (outputChannelData[i], sizeof (float) * numSamples);
  15801. }
  15802. }
  15803. void AudioSourcePlayer::audioDeviceAboutToStart (AudioIODevice* device)
  15804. {
  15805. sampleRate = device->getCurrentSampleRate();
  15806. bufferSize = device->getCurrentBufferSizeSamples();
  15807. zeromem (channels, sizeof (channels));
  15808. if (source != 0)
  15809. source->prepareToPlay (bufferSize, sampleRate);
  15810. }
  15811. void AudioSourcePlayer::audioDeviceStopped()
  15812. {
  15813. if (source != 0)
  15814. source->releaseResources();
  15815. sampleRate = 0.0;
  15816. bufferSize = 0;
  15817. tempBuffer.setSize (2, 8);
  15818. }
  15819. END_JUCE_NAMESPACE
  15820. /********* End of inlined file: juce_AudioSourcePlayer.cpp *********/
  15821. /********* Start of inlined file: juce_AudioTransportSource.cpp *********/
  15822. BEGIN_JUCE_NAMESPACE
  15823. AudioTransportSource::AudioTransportSource()
  15824. : source (0),
  15825. resamplerSource (0),
  15826. bufferingSource (0),
  15827. positionableSource (0),
  15828. masterSource (0),
  15829. gain (1.0f),
  15830. lastGain (1.0f),
  15831. playing (false),
  15832. stopped (true),
  15833. sampleRate (44100.0),
  15834. sourceSampleRate (0.0),
  15835. blockSize (128),
  15836. readAheadBufferSize (0),
  15837. isPrepared (false),
  15838. inputStreamEOF (false)
  15839. {
  15840. }
  15841. AudioTransportSource::~AudioTransportSource()
  15842. {
  15843. setSource (0);
  15844. releaseResources();
  15845. }
  15846. void AudioTransportSource::setSource (PositionableAudioSource* const newSource,
  15847. int readAheadBufferSize_,
  15848. double sourceSampleRateToCorrectFor)
  15849. {
  15850. if (source == newSource)
  15851. {
  15852. if (source == 0)
  15853. return;
  15854. setSource (0, 0, 0); // deselect and reselect to avoid releasing resources wrongly
  15855. }
  15856. readAheadBufferSize = readAheadBufferSize_;
  15857. sourceSampleRate = sourceSampleRateToCorrectFor;
  15858. ResamplingAudioSource* newResamplerSource = 0;
  15859. BufferingAudioSource* newBufferingSource = 0;
  15860. PositionableAudioSource* newPositionableSource = 0;
  15861. AudioSource* newMasterSource = 0;
  15862. ResamplingAudioSource* oldResamplerSource = resamplerSource;
  15863. BufferingAudioSource* oldBufferingSource = bufferingSource;
  15864. AudioSource* oldMasterSource = masterSource;
  15865. if (newSource != 0)
  15866. {
  15867. newPositionableSource = newSource;
  15868. if (readAheadBufferSize_ > 0)
  15869. newPositionableSource = newBufferingSource
  15870. = new BufferingAudioSource (newPositionableSource, false, readAheadBufferSize_);
  15871. newPositionableSource->setNextReadPosition (0);
  15872. if (sourceSampleRateToCorrectFor != 0)
  15873. newMasterSource = newResamplerSource
  15874. = new ResamplingAudioSource (newPositionableSource, false);
  15875. else
  15876. newMasterSource = newPositionableSource;
  15877. if (isPrepared)
  15878. {
  15879. if (newResamplerSource != 0 && sourceSampleRate > 0 && sampleRate > 0)
  15880. newResamplerSource->setResamplingRatio (sourceSampleRate / sampleRate);
  15881. newMasterSource->prepareToPlay (blockSize, sampleRate);
  15882. }
  15883. }
  15884. {
  15885. const ScopedLock sl (callbackLock);
  15886. source = newSource;
  15887. resamplerSource = newResamplerSource;
  15888. bufferingSource = newBufferingSource;
  15889. masterSource = newMasterSource;
  15890. positionableSource = newPositionableSource;
  15891. playing = false;
  15892. }
  15893. if (oldMasterSource != 0)
  15894. oldMasterSource->releaseResources();
  15895. if (oldResamplerSource != 0)
  15896. delete oldResamplerSource;
  15897. if (oldBufferingSource != 0)
  15898. delete oldBufferingSource;
  15899. }
  15900. void AudioTransportSource::start()
  15901. {
  15902. if ((! playing) && masterSource != 0)
  15903. {
  15904. callbackLock.enter();
  15905. playing = true;
  15906. stopped = false;
  15907. inputStreamEOF = false;
  15908. callbackLock.exit();
  15909. sendChangeMessage (this);
  15910. }
  15911. }
  15912. void AudioTransportSource::stop()
  15913. {
  15914. if (playing)
  15915. {
  15916. callbackLock.enter();
  15917. playing = false;
  15918. callbackLock.exit();
  15919. int n = 500;
  15920. while (--n >= 0 && ! stopped)
  15921. Thread::sleep (2);
  15922. sendChangeMessage (this);
  15923. }
  15924. }
  15925. void AudioTransportSource::setPosition (double newPosition)
  15926. {
  15927. if (sampleRate > 0.0)
  15928. setNextReadPosition (roundDoubleToInt (newPosition * sampleRate));
  15929. }
  15930. double AudioTransportSource::getCurrentPosition() const
  15931. {
  15932. if (sampleRate > 0.0)
  15933. return getNextReadPosition() / sampleRate;
  15934. else
  15935. return 0.0;
  15936. }
  15937. void AudioTransportSource::setNextReadPosition (int newPosition)
  15938. {
  15939. if (positionableSource != 0)
  15940. {
  15941. if (sampleRate > 0 && sourceSampleRate > 0)
  15942. newPosition = roundDoubleToInt (newPosition * sourceSampleRate / sampleRate);
  15943. positionableSource->setNextReadPosition (newPosition);
  15944. }
  15945. }
  15946. int AudioTransportSource::getNextReadPosition() const
  15947. {
  15948. if (positionableSource != 0)
  15949. {
  15950. const double ratio = (sampleRate > 0 && sourceSampleRate > 0) ? sampleRate / sourceSampleRate : 1.0;
  15951. return roundDoubleToInt (positionableSource->getNextReadPosition() * ratio);
  15952. }
  15953. return 0;
  15954. }
  15955. int AudioTransportSource::getTotalLength() const
  15956. {
  15957. const ScopedLock sl (callbackLock);
  15958. if (positionableSource != 0)
  15959. {
  15960. const double ratio = (sampleRate > 0 && sourceSampleRate > 0) ? sampleRate / sourceSampleRate : 1.0;
  15961. return roundDoubleToInt (positionableSource->getTotalLength() * ratio);
  15962. }
  15963. return 0;
  15964. }
  15965. bool AudioTransportSource::isLooping() const
  15966. {
  15967. const ScopedLock sl (callbackLock);
  15968. return positionableSource != 0
  15969. && positionableSource->isLooping();
  15970. }
  15971. void AudioTransportSource::setGain (const float newGain) throw()
  15972. {
  15973. gain = newGain;
  15974. }
  15975. void AudioTransportSource::prepareToPlay (int samplesPerBlockExpected,
  15976. double sampleRate_)
  15977. {
  15978. const ScopedLock sl (callbackLock);
  15979. sampleRate = sampleRate_;
  15980. blockSize = samplesPerBlockExpected;
  15981. if (masterSource != 0)
  15982. masterSource->prepareToPlay (samplesPerBlockExpected, sampleRate);
  15983. if (resamplerSource != 0 && sourceSampleRate != 0)
  15984. resamplerSource->setResamplingRatio (sourceSampleRate / sampleRate);
  15985. isPrepared = true;
  15986. }
  15987. void AudioTransportSource::releaseResources()
  15988. {
  15989. const ScopedLock sl (callbackLock);
  15990. if (masterSource != 0)
  15991. masterSource->releaseResources();
  15992. isPrepared = false;
  15993. }
  15994. void AudioTransportSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  15995. {
  15996. const ScopedLock sl (callbackLock);
  15997. inputStreamEOF = false;
  15998. if (masterSource != 0 && ! stopped)
  15999. {
  16000. masterSource->getNextAudioBlock (info);
  16001. if (! playing)
  16002. {
  16003. // just stopped playing, so fade out the last block..
  16004. for (int i = info.buffer->getNumChannels(); --i >= 0;)
  16005. info.buffer->applyGainRamp (i, info.startSample, jmin (256, info.numSamples), 1.0f, 0.0f);
  16006. if (info.numSamples > 256)
  16007. info.buffer->clear (info.startSample + 256, info.numSamples - 256);
  16008. }
  16009. if (positionableSource->getNextReadPosition() > positionableSource->getTotalLength() + 1
  16010. && ! positionableSource->isLooping())
  16011. {
  16012. playing = false;
  16013. inputStreamEOF = true;
  16014. sendChangeMessage (this);
  16015. }
  16016. stopped = ! playing;
  16017. for (int i = info.buffer->getNumChannels(); --i >= 0;)
  16018. {
  16019. info.buffer->applyGainRamp (i, info.startSample, info.numSamples,
  16020. lastGain, gain);
  16021. }
  16022. }
  16023. else
  16024. {
  16025. info.clearActiveBufferRegion();
  16026. stopped = true;
  16027. }
  16028. lastGain = gain;
  16029. }
  16030. END_JUCE_NAMESPACE
  16031. /********* End of inlined file: juce_AudioTransportSource.cpp *********/
  16032. /********* Start of inlined file: juce_BufferingAudioSource.cpp *********/
  16033. BEGIN_JUCE_NAMESPACE
  16034. class SharedBufferingAudioSourceThread : public DeletedAtShutdown,
  16035. public Thread,
  16036. private Timer
  16037. {
  16038. public:
  16039. SharedBufferingAudioSourceThread()
  16040. : Thread ("Audio Buffer"),
  16041. sources (8)
  16042. {
  16043. }
  16044. ~SharedBufferingAudioSourceThread()
  16045. {
  16046. stopThread (10000);
  16047. clearSingletonInstance();
  16048. }
  16049. juce_DeclareSingleton (SharedBufferingAudioSourceThread, false)
  16050. void addSource (BufferingAudioSource* source)
  16051. {
  16052. const ScopedLock sl (lock);
  16053. if (! sources.contains ((void*) source))
  16054. {
  16055. sources.add ((void*) source);
  16056. startThread();
  16057. stopTimer();
  16058. }
  16059. notify();
  16060. }
  16061. void removeSource (BufferingAudioSource* source)
  16062. {
  16063. const ScopedLock sl (lock);
  16064. sources.removeValue ((void*) source);
  16065. if (sources.size() == 0)
  16066. startTimer (5000);
  16067. }
  16068. private:
  16069. VoidArray sources;
  16070. CriticalSection lock;
  16071. void run()
  16072. {
  16073. while (! threadShouldExit())
  16074. {
  16075. bool busy = false;
  16076. for (int i = sources.size(); --i >= 0;)
  16077. {
  16078. if (threadShouldExit())
  16079. return;
  16080. const ScopedLock sl (lock);
  16081. BufferingAudioSource* const b = (BufferingAudioSource*) sources[i];
  16082. if (b != 0 && b->readNextBufferChunk())
  16083. busy = true;
  16084. }
  16085. if (! busy)
  16086. wait (500);
  16087. }
  16088. }
  16089. void timerCallback()
  16090. {
  16091. stopTimer();
  16092. if (sources.size() == 0)
  16093. deleteInstance();
  16094. }
  16095. SharedBufferingAudioSourceThread (const SharedBufferingAudioSourceThread&);
  16096. const SharedBufferingAudioSourceThread& operator= (const SharedBufferingAudioSourceThread&);
  16097. };
  16098. juce_ImplementSingleton (SharedBufferingAudioSourceThread)
  16099. BufferingAudioSource::BufferingAudioSource (PositionableAudioSource* source_,
  16100. const bool deleteSourceWhenDeleted_,
  16101. int numberOfSamplesToBuffer_)
  16102. : source (source_),
  16103. deleteSourceWhenDeleted (deleteSourceWhenDeleted_),
  16104. numberOfSamplesToBuffer (jmax (1024, numberOfSamplesToBuffer_)),
  16105. buffer (2, 0),
  16106. bufferValidStart (0),
  16107. bufferValidEnd (0),
  16108. nextPlayPos (0),
  16109. wasSourceLooping (false)
  16110. {
  16111. jassert (source_ != 0);
  16112. jassert (numberOfSamplesToBuffer_ > 1024); // not much point using this class if you're
  16113. // not using a larger buffer..
  16114. }
  16115. BufferingAudioSource::~BufferingAudioSource()
  16116. {
  16117. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  16118. if (thread != 0)
  16119. thread->removeSource (this);
  16120. if (deleteSourceWhenDeleted)
  16121. delete source;
  16122. }
  16123. void BufferingAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate_)
  16124. {
  16125. source->prepareToPlay (samplesPerBlockExpected, sampleRate_);
  16126. sampleRate = sampleRate_;
  16127. buffer.setSize (2, jmax (samplesPerBlockExpected * 2, numberOfSamplesToBuffer));
  16128. buffer.clear();
  16129. bufferValidStart = 0;
  16130. bufferValidEnd = 0;
  16131. SharedBufferingAudioSourceThread::getInstance()->addSource (this);
  16132. while (bufferValidEnd - bufferValidStart < jmin (((int) sampleRate_) / 4,
  16133. buffer.getNumSamples() / 2))
  16134. {
  16135. SharedBufferingAudioSourceThread::getInstance()->notify();
  16136. Thread::sleep (5);
  16137. }
  16138. }
  16139. void BufferingAudioSource::releaseResources()
  16140. {
  16141. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  16142. if (thread != 0)
  16143. thread->removeSource (this);
  16144. buffer.setSize (2, 0);
  16145. source->releaseResources();
  16146. }
  16147. void BufferingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  16148. {
  16149. const ScopedLock sl (bufferStartPosLock);
  16150. const int validStart = jlimit (bufferValidStart, bufferValidEnd, nextPlayPos) - nextPlayPos;
  16151. const int validEnd = jlimit (bufferValidStart, bufferValidEnd, nextPlayPos + info.numSamples) - nextPlayPos;
  16152. if (validStart == validEnd)
  16153. {
  16154. // total cache miss
  16155. info.clearActiveBufferRegion();
  16156. }
  16157. else
  16158. {
  16159. if (validStart > 0)
  16160. info.buffer->clear (info.startSample, validStart); // partial cache miss at start
  16161. if (validEnd < info.numSamples)
  16162. info.buffer->clear (info.startSample + validEnd,
  16163. info.numSamples - validEnd); // partial cache miss at end
  16164. if (validStart < validEnd)
  16165. {
  16166. for (int chan = jmin (2, info.buffer->getNumChannels()); --chan >= 0;)
  16167. {
  16168. const int startBufferIndex = (validStart + nextPlayPos) % buffer.getNumSamples();
  16169. const int endBufferIndex = (validEnd + nextPlayPos) % buffer.getNumSamples();
  16170. if (startBufferIndex < endBufferIndex)
  16171. {
  16172. info.buffer->copyFrom (chan, info.startSample + validStart,
  16173. buffer,
  16174. chan, startBufferIndex,
  16175. validEnd - validStart);
  16176. }
  16177. else
  16178. {
  16179. const int initialSize = buffer.getNumSamples() - startBufferIndex;
  16180. info.buffer->copyFrom (chan, info.startSample + validStart,
  16181. buffer,
  16182. chan, startBufferIndex,
  16183. initialSize);
  16184. info.buffer->copyFrom (chan, info.startSample + validStart + initialSize,
  16185. buffer,
  16186. chan, 0,
  16187. (validEnd - validStart) - initialSize);
  16188. }
  16189. }
  16190. }
  16191. nextPlayPos += info.numSamples;
  16192. }
  16193. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  16194. if (thread != 0)
  16195. thread->notify();
  16196. }
  16197. int BufferingAudioSource::getNextReadPosition() const
  16198. {
  16199. return (source->isLooping() && nextPlayPos > 0)
  16200. ? nextPlayPos % source->getTotalLength()
  16201. : nextPlayPos;
  16202. }
  16203. void BufferingAudioSource::setNextReadPosition (int newPosition)
  16204. {
  16205. const ScopedLock sl (bufferStartPosLock);
  16206. nextPlayPos = newPosition;
  16207. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  16208. if (thread != 0)
  16209. thread->notify();
  16210. }
  16211. bool BufferingAudioSource::readNextBufferChunk()
  16212. {
  16213. bufferStartPosLock.enter();
  16214. if (wasSourceLooping != isLooping())
  16215. {
  16216. wasSourceLooping = isLooping();
  16217. bufferValidStart = 0;
  16218. bufferValidEnd = 0;
  16219. }
  16220. int newBVS = jmax (0, nextPlayPos);
  16221. int newBVE = newBVS + buffer.getNumSamples() - 4;
  16222. int sectionToReadStart = 0;
  16223. int sectionToReadEnd = 0;
  16224. const int maxChunkSize = 2048;
  16225. if (newBVS < bufferValidStart || newBVS >= bufferValidEnd)
  16226. {
  16227. newBVE = jmin (newBVE, newBVS + maxChunkSize);
  16228. sectionToReadStart = newBVS;
  16229. sectionToReadEnd = newBVE;
  16230. bufferValidStart = 0;
  16231. bufferValidEnd = 0;
  16232. }
  16233. else if (abs (newBVS - bufferValidStart) > 512
  16234. || abs (newBVE - bufferValidEnd) > 512)
  16235. {
  16236. newBVE = jmin (newBVE, bufferValidEnd + maxChunkSize);
  16237. sectionToReadStart = bufferValidEnd;
  16238. sectionToReadEnd = newBVE;
  16239. bufferValidStart = newBVS;
  16240. bufferValidEnd = jmin (bufferValidEnd, newBVE);
  16241. }
  16242. bufferStartPosLock.exit();
  16243. if (sectionToReadStart != sectionToReadEnd)
  16244. {
  16245. const int bufferIndexStart = sectionToReadStart % buffer.getNumSamples();
  16246. const int bufferIndexEnd = sectionToReadEnd % buffer.getNumSamples();
  16247. if (bufferIndexStart < bufferIndexEnd)
  16248. {
  16249. readBufferSection (sectionToReadStart,
  16250. sectionToReadEnd - sectionToReadStart,
  16251. bufferIndexStart);
  16252. }
  16253. else
  16254. {
  16255. const int initialSize = buffer.getNumSamples() - bufferIndexStart;
  16256. readBufferSection (sectionToReadStart,
  16257. initialSize,
  16258. bufferIndexStart);
  16259. readBufferSection (sectionToReadStart + initialSize,
  16260. (sectionToReadEnd - sectionToReadStart) - initialSize,
  16261. 0);
  16262. }
  16263. const ScopedLock sl2 (bufferStartPosLock);
  16264. bufferValidStart = newBVS;
  16265. bufferValidEnd = newBVE;
  16266. return true;
  16267. }
  16268. else
  16269. {
  16270. return false;
  16271. }
  16272. }
  16273. void BufferingAudioSource::readBufferSection (int start, int length, int bufferOffset)
  16274. {
  16275. if (source->getNextReadPosition() != start)
  16276. source->setNextReadPosition (start);
  16277. AudioSourceChannelInfo info;
  16278. info.buffer = &buffer;
  16279. info.startSample = bufferOffset;
  16280. info.numSamples = length;
  16281. source->getNextAudioBlock (info);
  16282. }
  16283. END_JUCE_NAMESPACE
  16284. /********* End of inlined file: juce_BufferingAudioSource.cpp *********/
  16285. /********* Start of inlined file: juce_ChannelRemappingAudioSource.cpp *********/
  16286. BEGIN_JUCE_NAMESPACE
  16287. ChannelRemappingAudioSource::ChannelRemappingAudioSource (AudioSource* const source_,
  16288. const bool deleteSourceWhenDeleted_)
  16289. : requiredNumberOfChannels (2),
  16290. source (source_),
  16291. deleteSourceWhenDeleted (deleteSourceWhenDeleted_),
  16292. buffer (2, 16)
  16293. {
  16294. remappedInfo.buffer = &buffer;
  16295. remappedInfo.startSample = 0;
  16296. }
  16297. ChannelRemappingAudioSource::~ChannelRemappingAudioSource()
  16298. {
  16299. if (deleteSourceWhenDeleted)
  16300. delete source;
  16301. }
  16302. void ChannelRemappingAudioSource::setNumberOfChannelsToProduce (const int requiredNumberOfChannels_) throw()
  16303. {
  16304. const ScopedLock sl (lock);
  16305. requiredNumberOfChannels = requiredNumberOfChannels_;
  16306. }
  16307. void ChannelRemappingAudioSource::clearAllMappings() throw()
  16308. {
  16309. const ScopedLock sl (lock);
  16310. remappedInputs.clear();
  16311. remappedOutputs.clear();
  16312. }
  16313. void ChannelRemappingAudioSource::setInputChannelMapping (const int destIndex, const int sourceIndex) throw()
  16314. {
  16315. const ScopedLock sl (lock);
  16316. while (remappedInputs.size() < destIndex)
  16317. remappedInputs.add (-1);
  16318. remappedInputs.set (destIndex, sourceIndex);
  16319. }
  16320. void ChannelRemappingAudioSource::setOutputChannelMapping (const int sourceIndex, const int destIndex) throw()
  16321. {
  16322. const ScopedLock sl (lock);
  16323. while (remappedOutputs.size() < sourceIndex)
  16324. remappedOutputs.add (-1);
  16325. remappedOutputs.set (sourceIndex, destIndex);
  16326. }
  16327. int ChannelRemappingAudioSource::getRemappedInputChannel (const int inputChannelIndex) const throw()
  16328. {
  16329. const ScopedLock sl (lock);
  16330. if (inputChannelIndex >= 0 && inputChannelIndex < remappedInputs.size())
  16331. return remappedInputs.getUnchecked (inputChannelIndex);
  16332. return -1;
  16333. }
  16334. int ChannelRemappingAudioSource::getRemappedOutputChannel (const int outputChannelIndex) const throw()
  16335. {
  16336. const ScopedLock sl (lock);
  16337. if (outputChannelIndex >= 0 && outputChannelIndex < remappedOutputs.size())
  16338. return remappedOutputs .getUnchecked (outputChannelIndex);
  16339. return -1;
  16340. }
  16341. void ChannelRemappingAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  16342. {
  16343. source->prepareToPlay (samplesPerBlockExpected, sampleRate);
  16344. }
  16345. void ChannelRemappingAudioSource::releaseResources()
  16346. {
  16347. source->releaseResources();
  16348. }
  16349. void ChannelRemappingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill)
  16350. {
  16351. const ScopedLock sl (lock);
  16352. buffer.setSize (requiredNumberOfChannels, bufferToFill.numSamples, false, false, true);
  16353. const int numChans = bufferToFill.buffer->getNumChannels();
  16354. int i;
  16355. for (i = 0; i < buffer.getNumChannels(); ++i)
  16356. {
  16357. const int remappedChan = getRemappedInputChannel (i);
  16358. if (remappedChan >= 0 && remappedChan < numChans)
  16359. {
  16360. buffer.copyFrom (i, 0, *bufferToFill.buffer,
  16361. remappedChan,
  16362. bufferToFill.startSample,
  16363. bufferToFill.numSamples);
  16364. }
  16365. else
  16366. {
  16367. buffer.clear (i, 0, bufferToFill.numSamples);
  16368. }
  16369. }
  16370. remappedInfo.numSamples = bufferToFill.numSamples;
  16371. source->getNextAudioBlock (remappedInfo);
  16372. bufferToFill.clearActiveBufferRegion();
  16373. for (i = 0; i < requiredNumberOfChannels; ++i)
  16374. {
  16375. const int remappedChan = getRemappedOutputChannel (i);
  16376. if (remappedChan >= 0 && remappedChan < numChans)
  16377. {
  16378. bufferToFill.buffer->addFrom (remappedChan, bufferToFill.startSample,
  16379. buffer, i, 0, bufferToFill.numSamples);
  16380. }
  16381. }
  16382. }
  16383. XmlElement* ChannelRemappingAudioSource::createXml() const throw()
  16384. {
  16385. XmlElement* e = new XmlElement (T("MAPPINGS"));
  16386. String ins, outs;
  16387. int i;
  16388. const ScopedLock sl (lock);
  16389. for (i = 0; i < remappedInputs.size(); ++i)
  16390. ins << remappedInputs.getUnchecked(i) << T(' ');
  16391. for (i = 0; i < remappedOutputs.size(); ++i)
  16392. outs << remappedOutputs.getUnchecked(i) << T(' ');
  16393. e->setAttribute (T("inputs"), ins.trimEnd());
  16394. e->setAttribute (T("outputs"), outs.trimEnd());
  16395. return e;
  16396. }
  16397. void ChannelRemappingAudioSource::restoreFromXml (const XmlElement& e) throw()
  16398. {
  16399. if (e.hasTagName (T("MAPPINGS")))
  16400. {
  16401. const ScopedLock sl (lock);
  16402. clearAllMappings();
  16403. StringArray ins, outs;
  16404. ins.addTokens (e.getStringAttribute (T("inputs")), false);
  16405. outs.addTokens (e.getStringAttribute (T("outputs")), false);
  16406. int i;
  16407. for (i = 0; i < ins.size(); ++i)
  16408. remappedInputs.add (ins[i].getIntValue());
  16409. for (i = 0; i < outs.size(); ++i)
  16410. remappedOutputs.add (outs[i].getIntValue());
  16411. }
  16412. }
  16413. END_JUCE_NAMESPACE
  16414. /********* End of inlined file: juce_ChannelRemappingAudioSource.cpp *********/
  16415. /********* Start of inlined file: juce_IIRFilterAudioSource.cpp *********/
  16416. BEGIN_JUCE_NAMESPACE
  16417. IIRFilterAudioSource::IIRFilterAudioSource (AudioSource* const inputSource,
  16418. const bool deleteInputWhenDeleted_)
  16419. : input (inputSource),
  16420. deleteInputWhenDeleted (deleteInputWhenDeleted_)
  16421. {
  16422. jassert (inputSource != 0);
  16423. for (int i = 2; --i >= 0;)
  16424. iirFilters.add (new IIRFilter());
  16425. }
  16426. IIRFilterAudioSource::~IIRFilterAudioSource()
  16427. {
  16428. if (deleteInputWhenDeleted)
  16429. delete input;
  16430. }
  16431. void IIRFilterAudioSource::setFilterParameters (const IIRFilter& newSettings)
  16432. {
  16433. for (int i = iirFilters.size(); --i >= 0;)
  16434. iirFilters.getUnchecked(i)->copyCoefficientsFrom (newSettings);
  16435. }
  16436. void IIRFilterAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  16437. {
  16438. input->prepareToPlay (samplesPerBlockExpected, sampleRate);
  16439. for (int i = iirFilters.size(); --i >= 0;)
  16440. iirFilters.getUnchecked(i)->reset();
  16441. }
  16442. void IIRFilterAudioSource::releaseResources()
  16443. {
  16444. input->releaseResources();
  16445. }
  16446. void IIRFilterAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill)
  16447. {
  16448. input->getNextAudioBlock (bufferToFill);
  16449. const int numChannels = bufferToFill.buffer->getNumChannels();
  16450. while (numChannels > iirFilters.size())
  16451. iirFilters.add (new IIRFilter (*iirFilters.getUnchecked (0)));
  16452. for (int i = 0; i < numChannels; ++i)
  16453. iirFilters.getUnchecked(i)
  16454. ->processSamples (bufferToFill.buffer->getSampleData (i, bufferToFill.startSample),
  16455. bufferToFill.numSamples);
  16456. }
  16457. END_JUCE_NAMESPACE
  16458. /********* End of inlined file: juce_IIRFilterAudioSource.cpp *********/
  16459. /********* Start of inlined file: juce_MixerAudioSource.cpp *********/
  16460. BEGIN_JUCE_NAMESPACE
  16461. MixerAudioSource::MixerAudioSource()
  16462. : tempBuffer (2, 0),
  16463. currentSampleRate (0.0),
  16464. bufferSizeExpected (0)
  16465. {
  16466. }
  16467. MixerAudioSource::~MixerAudioSource()
  16468. {
  16469. removeAllInputs();
  16470. }
  16471. void MixerAudioSource::addInputSource (AudioSource* input, const bool deleteWhenRemoved)
  16472. {
  16473. if (input != 0 && ! inputs.contains (input))
  16474. {
  16475. lock.enter();
  16476. double localRate = currentSampleRate;
  16477. int localBufferSize = bufferSizeExpected;
  16478. lock.exit();
  16479. if (localRate != 0.0)
  16480. input->prepareToPlay (localBufferSize, localRate);
  16481. const ScopedLock sl (lock);
  16482. inputsToDelete.setBit (inputs.size(), deleteWhenRemoved);
  16483. inputs.add (input);
  16484. }
  16485. }
  16486. void MixerAudioSource::removeInputSource (AudioSource* input, const bool deleteInput)
  16487. {
  16488. if (input != 0)
  16489. {
  16490. lock.enter();
  16491. const int index = inputs.indexOf ((void*) input);
  16492. if (index >= 0)
  16493. {
  16494. inputsToDelete.shiftBits (index, 1);
  16495. inputs.remove (index);
  16496. }
  16497. lock.exit();
  16498. if (index >= 0)
  16499. {
  16500. input->releaseResources();
  16501. if (deleteInput)
  16502. delete input;
  16503. }
  16504. }
  16505. }
  16506. void MixerAudioSource::removeAllInputs()
  16507. {
  16508. lock.enter();
  16509. VoidArray inputsCopy (inputs);
  16510. BitArray inputsToDeleteCopy (inputsToDelete);
  16511. inputs.clear();
  16512. lock.exit();
  16513. for (int i = inputsCopy.size(); --i >= 0;)
  16514. if (inputsToDeleteCopy[i])
  16515. delete (AudioSource*) inputsCopy[i];
  16516. }
  16517. void MixerAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  16518. {
  16519. tempBuffer.setSize (2, samplesPerBlockExpected);
  16520. const ScopedLock sl (lock);
  16521. currentSampleRate = sampleRate;
  16522. bufferSizeExpected = samplesPerBlockExpected;
  16523. for (int i = inputs.size(); --i >= 0;)
  16524. ((AudioSource*) inputs.getUnchecked(i))->prepareToPlay (samplesPerBlockExpected,
  16525. sampleRate);
  16526. }
  16527. void MixerAudioSource::releaseResources()
  16528. {
  16529. const ScopedLock sl (lock);
  16530. for (int i = inputs.size(); --i >= 0;)
  16531. ((AudioSource*) inputs.getUnchecked(i))->releaseResources();
  16532. tempBuffer.setSize (2, 0);
  16533. currentSampleRate = 0;
  16534. bufferSizeExpected = 0;
  16535. }
  16536. void MixerAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  16537. {
  16538. const ScopedLock sl (lock);
  16539. if (inputs.size() > 0)
  16540. {
  16541. ((AudioSource*) inputs.getUnchecked(0))->getNextAudioBlock (info);
  16542. if (inputs.size() > 1)
  16543. {
  16544. tempBuffer.setSize (jmax (1, info.buffer->getNumChannels()),
  16545. info.buffer->getNumSamples());
  16546. AudioSourceChannelInfo info2;
  16547. info2.buffer = &tempBuffer;
  16548. info2.numSamples = info.numSamples;
  16549. info2.startSample = 0;
  16550. for (int i = 1; i < inputs.size(); ++i)
  16551. {
  16552. ((AudioSource*) inputs.getUnchecked(i))->getNextAudioBlock (info2);
  16553. for (int chan = 0; chan < info.buffer->getNumChannels(); ++chan)
  16554. info.buffer->addFrom (chan, info.startSample, tempBuffer, chan, 0, info.numSamples);
  16555. }
  16556. }
  16557. }
  16558. else
  16559. {
  16560. info.clearActiveBufferRegion();
  16561. }
  16562. }
  16563. END_JUCE_NAMESPACE
  16564. /********* End of inlined file: juce_MixerAudioSource.cpp *********/
  16565. /********* Start of inlined file: juce_ResamplingAudioSource.cpp *********/
  16566. BEGIN_JUCE_NAMESPACE
  16567. ResamplingAudioSource::ResamplingAudioSource (AudioSource* const inputSource,
  16568. const bool deleteInputWhenDeleted_)
  16569. : input (inputSource),
  16570. deleteInputWhenDeleted (deleteInputWhenDeleted_),
  16571. ratio (1.0),
  16572. lastRatio (1.0),
  16573. buffer (2, 0),
  16574. sampsInBuffer (0)
  16575. {
  16576. jassert (input != 0);
  16577. }
  16578. ResamplingAudioSource::~ResamplingAudioSource()
  16579. {
  16580. if (deleteInputWhenDeleted)
  16581. delete input;
  16582. }
  16583. void ResamplingAudioSource::setResamplingRatio (const double samplesInPerOutputSample)
  16584. {
  16585. jassert (samplesInPerOutputSample > 0);
  16586. const ScopedLock sl (ratioLock);
  16587. ratio = jmax (0.0, samplesInPerOutputSample);
  16588. }
  16589. void ResamplingAudioSource::prepareToPlay (int samplesPerBlockExpected,
  16590. double sampleRate)
  16591. {
  16592. const ScopedLock sl (ratioLock);
  16593. input->prepareToPlay (samplesPerBlockExpected, sampleRate);
  16594. buffer.setSize (2, roundDoubleToInt (samplesPerBlockExpected * ratio) + 32);
  16595. buffer.clear();
  16596. sampsInBuffer = 0;
  16597. bufferPos = 0;
  16598. subSampleOffset = 0.0;
  16599. createLowPass (ratio);
  16600. resetFilters();
  16601. }
  16602. void ResamplingAudioSource::releaseResources()
  16603. {
  16604. input->releaseResources();
  16605. buffer.setSize (2, 0);
  16606. }
  16607. void ResamplingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  16608. {
  16609. const ScopedLock sl (ratioLock);
  16610. if (lastRatio != ratio)
  16611. {
  16612. createLowPass (ratio);
  16613. lastRatio = ratio;
  16614. }
  16615. const int sampsNeeded = roundDoubleToInt (info.numSamples * ratio) + 2;
  16616. int bufferSize = buffer.getNumSamples();
  16617. if (bufferSize < sampsNeeded + 8)
  16618. {
  16619. bufferPos %= bufferSize;
  16620. bufferSize = sampsNeeded + 32;
  16621. buffer.setSize (buffer.getNumChannels(), bufferSize, true, true);
  16622. }
  16623. bufferPos %= bufferSize;
  16624. int endOfBufferPos = bufferPos + sampsInBuffer;
  16625. while (sampsNeeded > sampsInBuffer)
  16626. {
  16627. endOfBufferPos %= bufferSize;
  16628. int numToDo = jmin (sampsNeeded - sampsInBuffer,
  16629. bufferSize - endOfBufferPos);
  16630. AudioSourceChannelInfo readInfo;
  16631. readInfo.buffer = &buffer;
  16632. readInfo.numSamples = numToDo;
  16633. readInfo.startSample = endOfBufferPos;
  16634. input->getNextAudioBlock (readInfo);
  16635. if (ratio > 1.0)
  16636. {
  16637. // for down-sampling, pre-apply the filter..
  16638. for (int i = jmin (2, info.buffer->getNumChannels()); --i >= 0;)
  16639. applyFilter (buffer.getSampleData (i, endOfBufferPos), numToDo, filterStates[i]);
  16640. }
  16641. sampsInBuffer += numToDo;
  16642. endOfBufferPos += numToDo;
  16643. }
  16644. float* dl = info.buffer->getSampleData (0, info.startSample);
  16645. float* dr = (info.buffer->getNumChannels() > 1) ? info.buffer->getSampleData (1, info.startSample) : 0;
  16646. const float* const bl = buffer.getSampleData (0, 0);
  16647. const float* const br = buffer.getSampleData (1, 0);
  16648. int nextPos = (bufferPos + 1) % bufferSize;
  16649. for (int m = info.numSamples; --m >= 0;)
  16650. {
  16651. const float alpha = (float) subSampleOffset;
  16652. const float invAlpha = 1.0f - alpha;
  16653. *dl++ = bl [bufferPos] * invAlpha + bl [nextPos] * alpha;
  16654. if (dr != 0)
  16655. *dr++ = br [bufferPos] * invAlpha + br [nextPos] * alpha;
  16656. subSampleOffset += ratio;
  16657. jassert (sampsInBuffer > 0);
  16658. while (subSampleOffset >= 1.0)
  16659. {
  16660. if (++bufferPos >= bufferSize)
  16661. bufferPos = 0;
  16662. --sampsInBuffer;
  16663. nextPos = (bufferPos + 1) % bufferSize;
  16664. subSampleOffset -= 1.0;
  16665. }
  16666. }
  16667. if (ratio < 1.0)
  16668. {
  16669. // for up-sampling, apply the filter after transposing..
  16670. for (int i = jmin (2, info.buffer->getNumChannels()); --i >= 0;)
  16671. applyFilter (info.buffer->getSampleData (i, info.startSample), info.numSamples, filterStates[i]);
  16672. }
  16673. jassert (sampsInBuffer >= 0);
  16674. }
  16675. void ResamplingAudioSource::createLowPass (const double ratio)
  16676. {
  16677. const double proportionalRate = (ratio > 1.0) ? 0.5 / ratio
  16678. : 0.5 * ratio;
  16679. const double n = 1.0 / tan (double_Pi * jmax (0.001, proportionalRate));
  16680. const double nSquared = n * n;
  16681. const double c1 = 1.0 / (1.0 + sqrt (2.0) * n + nSquared);
  16682. setFilterCoefficients (c1,
  16683. c1 * 2.0f,
  16684. c1,
  16685. 1.0,
  16686. c1 * 2.0 * (1.0 - nSquared),
  16687. c1 * (1.0 - sqrt (2.0) * n + nSquared));
  16688. }
  16689. void ResamplingAudioSource::setFilterCoefficients (double c1, double c2, double c3, double c4, double c5, double c6)
  16690. {
  16691. const double a = 1.0 / c4;
  16692. c1 *= a;
  16693. c2 *= a;
  16694. c3 *= a;
  16695. c5 *= a;
  16696. c6 *= a;
  16697. coefficients[0] = c1;
  16698. coefficients[1] = c2;
  16699. coefficients[2] = c3;
  16700. coefficients[3] = c4;
  16701. coefficients[4] = c5;
  16702. coefficients[5] = c6;
  16703. }
  16704. void ResamplingAudioSource::resetFilters()
  16705. {
  16706. zeromem (filterStates, sizeof (filterStates));
  16707. }
  16708. void ResamplingAudioSource::applyFilter (float* samples, int num, FilterState& fs)
  16709. {
  16710. while (--num >= 0)
  16711. {
  16712. const double in = *samples;
  16713. double out = coefficients[0] * in
  16714. + coefficients[1] * fs.x1
  16715. + coefficients[2] * fs.x2
  16716. - coefficients[4] * fs.y1
  16717. - coefficients[5] * fs.y2;
  16718. #if JUCE_INTEL
  16719. if (! (out < -1.0e-8 || out > 1.0e-8))
  16720. out = 0;
  16721. #endif
  16722. fs.x2 = fs.x1;
  16723. fs.x1 = in;
  16724. fs.y2 = fs.y1;
  16725. fs.y1 = out;
  16726. *samples++ = (float) out;
  16727. }
  16728. }
  16729. END_JUCE_NAMESPACE
  16730. /********* End of inlined file: juce_ResamplingAudioSource.cpp *********/
  16731. /********* Start of inlined file: juce_ToneGeneratorAudioSource.cpp *********/
  16732. BEGIN_JUCE_NAMESPACE
  16733. ToneGeneratorAudioSource::ToneGeneratorAudioSource()
  16734. : frequency (1000.0),
  16735. sampleRate (44100.0),
  16736. currentPhase (0.0),
  16737. phasePerSample (0.0),
  16738. amplitude (0.5f)
  16739. {
  16740. }
  16741. ToneGeneratorAudioSource::~ToneGeneratorAudioSource()
  16742. {
  16743. }
  16744. void ToneGeneratorAudioSource::setAmplitude (const float newAmplitude)
  16745. {
  16746. amplitude = newAmplitude;
  16747. }
  16748. void ToneGeneratorAudioSource::setFrequency (const double newFrequencyHz)
  16749. {
  16750. frequency = newFrequencyHz;
  16751. phasePerSample = 0.0;
  16752. }
  16753. void ToneGeneratorAudioSource::prepareToPlay (int /*samplesPerBlockExpected*/,
  16754. double sampleRate_)
  16755. {
  16756. currentPhase = 0.0;
  16757. phasePerSample = 0.0;
  16758. sampleRate = sampleRate_;
  16759. }
  16760. void ToneGeneratorAudioSource::releaseResources()
  16761. {
  16762. }
  16763. void ToneGeneratorAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  16764. {
  16765. if (phasePerSample == 0.0)
  16766. phasePerSample = double_Pi * 2.0 / (sampleRate / frequency);
  16767. for (int i = 0; i < info.numSamples; ++i)
  16768. {
  16769. const float sample = amplitude * (float) sin (currentPhase);
  16770. currentPhase += phasePerSample;
  16771. for (int j = info.buffer->getNumChannels(); --j >= 0;)
  16772. *info.buffer->getSampleData (j, info.startSample + i) = sample;
  16773. }
  16774. }
  16775. END_JUCE_NAMESPACE
  16776. /********* End of inlined file: juce_ToneGeneratorAudioSource.cpp *********/
  16777. /********* Start of inlined file: juce_AudioDeviceManager.cpp *********/
  16778. BEGIN_JUCE_NAMESPACE
  16779. AudioDeviceManager::AudioDeviceManager()
  16780. : currentAudioDevice (0),
  16781. currentCallback (0),
  16782. numInputChansNeeded (0),
  16783. numOutputChansNeeded (2),
  16784. lastExplicitSettings (0),
  16785. listNeedsScanning (true),
  16786. useInputNames (false),
  16787. enabledMidiInputs (4),
  16788. midiCallbacks (4),
  16789. midiCallbackDevices (4),
  16790. defaultMidiOutput (0),
  16791. cpuUsageMs (0),
  16792. timeToCpuScale (0)
  16793. {
  16794. callbackHandler.owner = this;
  16795. AudioIODeviceType::createDeviceTypes (availableDeviceTypes);
  16796. }
  16797. AudioDeviceManager::~AudioDeviceManager()
  16798. {
  16799. stopDevice();
  16800. deleteAndZero (currentAudioDevice);
  16801. deleteAndZero (defaultMidiOutput);
  16802. delete lastExplicitSettings;
  16803. }
  16804. const String AudioDeviceManager::initialise (const int numInputChannelsNeeded,
  16805. const int numOutputChannelsNeeded,
  16806. const XmlElement* const e,
  16807. const bool selectDefaultDeviceOnFailure,
  16808. const String& preferredDefaultDeviceName)
  16809. {
  16810. if (listNeedsScanning)
  16811. refreshDeviceList();
  16812. numInputChansNeeded = numInputChannelsNeeded;
  16813. numOutputChansNeeded = numOutputChannelsNeeded;
  16814. if (e != 0 && e->hasTagName (T("DEVICESETUP")))
  16815. {
  16816. lastExplicitSettings = new XmlElement (*e);
  16817. BitArray ins, outs;
  16818. ins.parseString (e->getStringAttribute (T("audioDeviceInChans"), T("11")), 2);
  16819. outs.parseString (e->getStringAttribute (T("audioDeviceOutChans"), T("11")), 2);
  16820. String error (setAudioDevice (e->getStringAttribute (T("audioDeviceName")),
  16821. e->getIntAttribute (T("audioDeviceBufferSize")),
  16822. e->getDoubleAttribute (T("audioDeviceRate")),
  16823. e->hasAttribute (T("audioDeviceInChans")) ? &ins : 0,
  16824. e->hasAttribute (T("audioDeviceOutChans")) ? &outs : 0,
  16825. true));
  16826. midiInsFromXml.clear();
  16827. forEachXmlChildElementWithTagName (*e, c, T("MIDIINPUT"))
  16828. midiInsFromXml.add (c->getStringAttribute (T("name")));
  16829. const StringArray allMidiIns (MidiInput::getDevices());
  16830. for (int i = allMidiIns.size(); --i >= 0;)
  16831. setMidiInputEnabled (allMidiIns[i], midiInsFromXml.contains (allMidiIns[i]));
  16832. if (error.isNotEmpty() && selectDefaultDeviceOnFailure)
  16833. error = initialise (numInputChannelsNeeded, numOutputChannelsNeeded, 0,
  16834. false, preferredDefaultDeviceName);
  16835. setDefaultMidiOutput (e->getStringAttribute (T("defaultMidiOutput")));
  16836. return error;
  16837. }
  16838. else
  16839. {
  16840. setInputDeviceNamesUsed (numOutputChannelsNeeded == 0);
  16841. String defaultDevice;
  16842. if (preferredDefaultDeviceName.isNotEmpty())
  16843. {
  16844. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  16845. {
  16846. const StringArray devs (availableDeviceTypes.getUnchecked(i)->getDeviceNames());
  16847. for (int j = 0; j < devs.size(); ++j)
  16848. {
  16849. if (devs[j].matchesWildcard (preferredDefaultDeviceName, true))
  16850. {
  16851. defaultDevice = devs[j];
  16852. break;
  16853. }
  16854. }
  16855. }
  16856. }
  16857. if (defaultDevice.isEmpty() && availableDeviceTypes [0] != 0)
  16858. defaultDevice = availableDeviceTypes[0]->getDefaultDeviceName (numOutputChannelsNeeded == 0,
  16859. numInputChannelsNeeded,
  16860. numOutputChannelsNeeded);
  16861. return setAudioDevice (defaultDevice, 0, 0, 0, 0, false);
  16862. }
  16863. }
  16864. XmlElement* AudioDeviceManager::createStateXml() const
  16865. {
  16866. return lastExplicitSettings != 0 ? new XmlElement (*lastExplicitSettings) : 0;
  16867. }
  16868. const StringArray AudioDeviceManager::getAvailableAudioDeviceNames() const
  16869. {
  16870. if (listNeedsScanning)
  16871. refreshDeviceList();
  16872. StringArray names;
  16873. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  16874. names.addArray (availableDeviceTypes[i]->getDeviceNames (useInputNames));
  16875. return names;
  16876. }
  16877. void AudioDeviceManager::refreshDeviceList() const
  16878. {
  16879. listNeedsScanning = false;
  16880. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  16881. availableDeviceTypes[i]->scanForDevices();
  16882. }
  16883. void AudioDeviceManager::setInputDeviceNamesUsed (const bool useInputNames_)
  16884. {
  16885. useInputNames = useInputNames_;
  16886. sendChangeMessage (this);
  16887. }
  16888. void AudioDeviceManager::addDeviceNamesToComboBox (ComboBox& combo) const
  16889. {
  16890. int n = 0;
  16891. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  16892. {
  16893. AudioIODeviceType* const type = availableDeviceTypes[i];
  16894. if (availableDeviceTypes.size() > 1)
  16895. combo.addSectionHeading (type->getTypeName() + T(" devices:"));
  16896. const StringArray names (type->getDeviceNames (useInputNames));
  16897. for (int j = 0; j < names.size(); ++j)
  16898. combo.addItem (names[j], ++n);
  16899. combo.addSeparator();
  16900. }
  16901. combo.addItem (TRANS("<< no audio device >>"), -1);
  16902. }
  16903. const String AudioDeviceManager::getCurrentAudioDeviceName() const
  16904. {
  16905. if (currentAudioDevice != 0)
  16906. return currentAudioDevice->getName();
  16907. return String::empty;
  16908. }
  16909. const String AudioDeviceManager::setAudioDevice (const String& deviceNameToUse,
  16910. int blockSizeToUse,
  16911. double sampleRateToUse,
  16912. const BitArray* inChans,
  16913. const BitArray* outChans,
  16914. const bool treatAsChosenDevice)
  16915. {
  16916. stopDevice();
  16917. String error;
  16918. if (deviceNameToUse.isNotEmpty())
  16919. {
  16920. const StringArray devNames (getAvailableAudioDeviceNames());
  16921. int index = devNames.indexOf (deviceNameToUse, true);
  16922. if (index >= 0)
  16923. {
  16924. if (currentAudioDevice == 0
  16925. || currentAudioDevice->getLastError().isNotEmpty()
  16926. || ! deviceNameToUse.equalsIgnoreCase (currentAudioDevice->getName()))
  16927. {
  16928. // change of device..
  16929. deleteAndZero (currentAudioDevice);
  16930. int n = 0;
  16931. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  16932. {
  16933. AudioIODeviceType* const type = availableDeviceTypes[i];
  16934. const StringArray names (type->getDeviceNames (useInputNames));
  16935. if (index >= n && index < n + names.size())
  16936. {
  16937. currentAudioDevice = type->createDevice (deviceNameToUse);
  16938. break;
  16939. }
  16940. n += names.size();
  16941. }
  16942. error = currentAudioDevice->getLastError();
  16943. if (error.isNotEmpty())
  16944. {
  16945. deleteAndZero (currentAudioDevice);
  16946. return error;
  16947. }
  16948. inputChannels.clear();
  16949. inputChannels.setRange (0, numInputChansNeeded, true);
  16950. outputChannels.clear();
  16951. outputChannels.setRange (0, numOutputChansNeeded, true);
  16952. }
  16953. if (inChans != 0)
  16954. inputChannels = *inChans;
  16955. if (outChans != 0)
  16956. outputChannels = *outChans;
  16957. error = restartDevice (blockSizeToUse,
  16958. sampleRateToUse,
  16959. inputChannels,
  16960. outputChannels);
  16961. if (error.isNotEmpty())
  16962. {
  16963. deleteAndZero (currentAudioDevice);
  16964. }
  16965. }
  16966. else
  16967. {
  16968. deleteAndZero (currentAudioDevice);
  16969. error << "No such device: " << deviceNameToUse;
  16970. }
  16971. }
  16972. else
  16973. {
  16974. deleteAndZero (currentAudioDevice);
  16975. }
  16976. if (treatAsChosenDevice && error.isEmpty())
  16977. updateXml();
  16978. return error;
  16979. }
  16980. const String AudioDeviceManager::restartDevice (int blockSizeToUse,
  16981. double sampleRateToUse,
  16982. const BitArray& inChans,
  16983. const BitArray& outChans)
  16984. {
  16985. stopDevice();
  16986. inputChannels = inChans;
  16987. outputChannels = outChans;
  16988. if (sampleRateToUse > 0)
  16989. {
  16990. bool ok = false;
  16991. for (int i = currentAudioDevice->getNumSampleRates(); --i >= 0;)
  16992. {
  16993. const double sr = currentAudioDevice->getSampleRate (i);
  16994. if (sr == sampleRateToUse)
  16995. ok = true;
  16996. }
  16997. if (! ok)
  16998. sampleRateToUse = 0;
  16999. }
  17000. if (sampleRateToUse == 0)
  17001. {
  17002. double lowestAbove44 = 0.0;
  17003. for (int i = currentAudioDevice->getNumSampleRates(); --i >= 0;)
  17004. {
  17005. const double sr = currentAudioDevice->getSampleRate (i);
  17006. if (sr >= 44100.0 && (lowestAbove44 == 0 || sr < lowestAbove44))
  17007. lowestAbove44 = sr;
  17008. }
  17009. if (lowestAbove44 == 0.0)
  17010. sampleRateToUse = currentAudioDevice->getSampleRate (0);
  17011. else
  17012. sampleRateToUse = lowestAbove44;
  17013. }
  17014. const String error (currentAudioDevice->open (inChans, outChans,
  17015. sampleRateToUse, blockSizeToUse));
  17016. if (error.isEmpty())
  17017. currentAudioDevice->start (&callbackHandler);
  17018. sendChangeMessage (this);
  17019. return error;
  17020. }
  17021. void AudioDeviceManager::stopDevice()
  17022. {
  17023. if (currentAudioDevice != 0)
  17024. currentAudioDevice->stop();
  17025. }
  17026. void AudioDeviceManager::closeAudioDevice()
  17027. {
  17028. if (currentAudioDevice != 0)
  17029. {
  17030. lastRunningDevice = currentAudioDevice->getName();
  17031. lastRunningBlockSize = currentAudioDevice->getCurrentBufferSizeSamples();
  17032. lastRunningSampleRate = currentAudioDevice->getCurrentSampleRate();
  17033. lastRunningIns = inputChannels;
  17034. lastRunningOuts = outputChannels;
  17035. stopDevice();
  17036. setAudioDevice (String::empty, 0, 0, 0, 0, false);
  17037. }
  17038. }
  17039. void AudioDeviceManager::restartLastAudioDevice()
  17040. {
  17041. if (currentAudioDevice == 0)
  17042. {
  17043. if (lastRunningDevice.isEmpty())
  17044. {
  17045. // This method will only reload the last device that was running
  17046. // before closeAudioDevice() was called - you need to actually open
  17047. // one first, with setAudioDevice().
  17048. jassertfalse
  17049. return;
  17050. }
  17051. setAudioDevice (lastRunningDevice,
  17052. lastRunningBlockSize,
  17053. lastRunningSampleRate,
  17054. &lastRunningIns,
  17055. &lastRunningOuts,
  17056. false);
  17057. }
  17058. }
  17059. void AudioDeviceManager::setInputChannels (const BitArray& newEnabledChannels,
  17060. const bool treatAsChosenDevice)
  17061. {
  17062. if (currentAudioDevice != 0
  17063. && newEnabledChannels != inputChannels)
  17064. {
  17065. setAudioDevice (currentAudioDevice->getName(),
  17066. currentAudioDevice->getCurrentBufferSizeSamples(),
  17067. currentAudioDevice->getCurrentSampleRate(),
  17068. &newEnabledChannels, 0,
  17069. treatAsChosenDevice);
  17070. }
  17071. }
  17072. void AudioDeviceManager::setOutputChannels (const BitArray& newEnabledChannels,
  17073. const bool treatAsChosenDevice)
  17074. {
  17075. if (currentAudioDevice != 0
  17076. && newEnabledChannels != outputChannels)
  17077. {
  17078. setAudioDevice (currentAudioDevice->getName(),
  17079. currentAudioDevice->getCurrentBufferSizeSamples(),
  17080. currentAudioDevice->getCurrentSampleRate(),
  17081. 0, &newEnabledChannels,
  17082. treatAsChosenDevice);
  17083. }
  17084. }
  17085. void AudioDeviceManager::updateXml()
  17086. {
  17087. delete lastExplicitSettings;
  17088. lastExplicitSettings = new XmlElement (T("DEVICESETUP"));
  17089. lastExplicitSettings->setAttribute (T("audioDeviceName"), getCurrentAudioDeviceName());
  17090. if (currentAudioDevice != 0)
  17091. {
  17092. lastExplicitSettings->setAttribute (T("audioDeviceRate"), currentAudioDevice->getCurrentSampleRate());
  17093. if (currentAudioDevice->getDefaultBufferSize() != currentAudioDevice->getCurrentBufferSizeSamples())
  17094. lastExplicitSettings->setAttribute (T("audioDeviceBufferSize"), currentAudioDevice->getCurrentBufferSizeSamples());
  17095. lastExplicitSettings->setAttribute (T("audioDeviceInChans"), inputChannels.toString (2));
  17096. lastExplicitSettings->setAttribute (T("audioDeviceOutChans"), outputChannels.toString (2));
  17097. }
  17098. for (int i = 0; i < enabledMidiInputs.size(); ++i)
  17099. {
  17100. XmlElement* const m = new XmlElement (T("MIDIINPUT"));
  17101. m->setAttribute (T("name"), enabledMidiInputs[i]->getName());
  17102. lastExplicitSettings->addChildElement (m);
  17103. }
  17104. if (midiInsFromXml.size() > 0)
  17105. {
  17106. // Add any midi devices that have been enabled before, but which aren't currently
  17107. // open because the device has been disconnected.
  17108. const StringArray availableMidiDevices (MidiInput::getDevices());
  17109. for (int i = 0; i < midiInsFromXml.size(); ++i)
  17110. {
  17111. if (! availableMidiDevices.contains (midiInsFromXml[i], true))
  17112. {
  17113. XmlElement* const m = new XmlElement (T("MIDIINPUT"));
  17114. m->setAttribute (T("name"), midiInsFromXml[i]);
  17115. lastExplicitSettings->addChildElement (m);
  17116. }
  17117. }
  17118. }
  17119. if (defaultMidiOutputName.isNotEmpty())
  17120. lastExplicitSettings->setAttribute (T("defaultMidiOutput"), defaultMidiOutputName);
  17121. }
  17122. void AudioDeviceManager::setAudioCallback (AudioIODeviceCallback* newCallback)
  17123. {
  17124. if (newCallback != currentCallback)
  17125. {
  17126. AudioIODeviceCallback* lastCallback = currentCallback;
  17127. audioCallbackLock.enter();
  17128. currentCallback = 0;
  17129. audioCallbackLock.exit();
  17130. if (currentAudioDevice != 0)
  17131. {
  17132. if (lastCallback != 0)
  17133. lastCallback->audioDeviceStopped();
  17134. if (newCallback != 0)
  17135. newCallback->audioDeviceAboutToStart (currentAudioDevice);
  17136. }
  17137. currentCallback = newCallback;
  17138. }
  17139. }
  17140. void AudioDeviceManager::audioDeviceIOCallbackInt (const float** inputChannelData,
  17141. int totalNumInputChannels,
  17142. float** outputChannelData,
  17143. int totalNumOutputChannels,
  17144. int numSamples)
  17145. {
  17146. const ScopedLock sl (audioCallbackLock);
  17147. if (currentCallback != 0)
  17148. {
  17149. const double callbackStartTime = Time::getMillisecondCounterHiRes();
  17150. currentCallback->audioDeviceIOCallback (inputChannelData,
  17151. totalNumInputChannels,
  17152. outputChannelData,
  17153. totalNumOutputChannels,
  17154. numSamples);
  17155. const double msTaken = Time::getMillisecondCounterHiRes() - callbackStartTime;
  17156. const double filterAmount = 0.2;
  17157. cpuUsageMs += filterAmount * (msTaken - cpuUsageMs);
  17158. }
  17159. else
  17160. {
  17161. for (int i = 0; i < totalNumOutputChannels; ++i)
  17162. if (outputChannelData [i] != 0)
  17163. zeromem (outputChannelData[i], sizeof (float) * numSamples);
  17164. }
  17165. }
  17166. void AudioDeviceManager::audioDeviceAboutToStartInt (AudioIODevice* const device)
  17167. {
  17168. cpuUsageMs = 0;
  17169. const double sampleRate = device->getCurrentSampleRate();
  17170. const int blockSize = device->getCurrentBufferSizeSamples();
  17171. if (sampleRate > 0.0 && blockSize > 0)
  17172. {
  17173. const double msPerBlock = 1000.0 * blockSize / sampleRate;
  17174. timeToCpuScale = (msPerBlock > 0.0) ? (1.0 / msPerBlock) : 0.0;
  17175. }
  17176. if (currentCallback != 0)
  17177. currentCallback->audioDeviceAboutToStart (device);
  17178. sendChangeMessage (this);
  17179. }
  17180. void AudioDeviceManager::audioDeviceStoppedInt()
  17181. {
  17182. cpuUsageMs = 0;
  17183. timeToCpuScale = 0;
  17184. sendChangeMessage (this);
  17185. if (currentCallback != 0)
  17186. currentCallback->audioDeviceStopped();
  17187. }
  17188. double AudioDeviceManager::getCpuUsage() const
  17189. {
  17190. return jlimit (0.0, 1.0, timeToCpuScale * cpuUsageMs);
  17191. }
  17192. void AudioDeviceManager::setMidiInputEnabled (const String& name,
  17193. const bool enabled)
  17194. {
  17195. if (enabled != isMidiInputEnabled (name))
  17196. {
  17197. if (enabled)
  17198. {
  17199. const int index = MidiInput::getDevices().indexOf (name);
  17200. if (index >= 0)
  17201. {
  17202. MidiInput* const min = MidiInput::openDevice (index, &callbackHandler);
  17203. if (min != 0)
  17204. {
  17205. enabledMidiInputs.add (min);
  17206. min->start();
  17207. }
  17208. }
  17209. }
  17210. else
  17211. {
  17212. for (int i = enabledMidiInputs.size(); --i >= 0;)
  17213. if (enabledMidiInputs[i]->getName() == name)
  17214. enabledMidiInputs.remove (i);
  17215. }
  17216. updateXml();
  17217. sendChangeMessage (this);
  17218. }
  17219. }
  17220. bool AudioDeviceManager::isMidiInputEnabled (const String& name) const
  17221. {
  17222. for (int i = enabledMidiInputs.size(); --i >= 0;)
  17223. if (enabledMidiInputs[i]->getName() == name)
  17224. return true;
  17225. return false;
  17226. }
  17227. void AudioDeviceManager::addMidiInputCallback (const String& name,
  17228. MidiInputCallback* callback)
  17229. {
  17230. removeMidiInputCallback (callback);
  17231. if (name.isEmpty())
  17232. {
  17233. midiCallbacks.add (callback);
  17234. midiCallbackDevices.add (0);
  17235. }
  17236. else
  17237. {
  17238. for (int i = enabledMidiInputs.size(); --i >= 0;)
  17239. {
  17240. if (enabledMidiInputs[i]->getName() == name)
  17241. {
  17242. const ScopedLock sl (midiCallbackLock);
  17243. if (! midiCallbacks.contains (callback))
  17244. {
  17245. midiCallbacks.add (callback);
  17246. midiCallbackDevices.add (enabledMidiInputs[i]);
  17247. }
  17248. break;
  17249. }
  17250. }
  17251. }
  17252. }
  17253. void AudioDeviceManager::removeMidiInputCallback (MidiInputCallback* callback)
  17254. {
  17255. const ScopedLock sl (midiCallbackLock);
  17256. const int index = midiCallbacks.indexOf (callback);
  17257. midiCallbacks.remove (index);
  17258. midiCallbackDevices.remove (index);
  17259. }
  17260. void AudioDeviceManager::handleIncomingMidiMessageInt (MidiInput* source,
  17261. const MidiMessage& message)
  17262. {
  17263. if (! message.isActiveSense())
  17264. {
  17265. const bool isDefaultSource = (source == 0 || source == enabledMidiInputs.getFirst());
  17266. const ScopedLock sl (midiCallbackLock);
  17267. for (int i = midiCallbackDevices.size(); --i >= 0;)
  17268. {
  17269. MidiInput* const md = midiCallbackDevices.getUnchecked(i);
  17270. if (md == source || (md == 0 && isDefaultSource))
  17271. midiCallbacks.getUnchecked(i)->handleIncomingMidiMessage (source, message);
  17272. }
  17273. }
  17274. }
  17275. void AudioDeviceManager::setDefaultMidiOutput (const String& deviceName)
  17276. {
  17277. if (defaultMidiOutputName != deviceName)
  17278. {
  17279. deleteAndZero (defaultMidiOutput);
  17280. defaultMidiOutputName = deviceName;
  17281. if (deviceName.isNotEmpty())
  17282. defaultMidiOutput = MidiOutput::openDevice (MidiOutput::getDevices().indexOf (deviceName));
  17283. updateXml();
  17284. sendChangeMessage (this);
  17285. }
  17286. }
  17287. void AudioDeviceManager::CallbackHandler::audioDeviceIOCallback (const float** inputChannelData,
  17288. int totalNumInputChannels,
  17289. float** outputChannelData,
  17290. int totalNumOutputChannels,
  17291. int numSamples)
  17292. {
  17293. owner->audioDeviceIOCallbackInt (inputChannelData, totalNumInputChannels, outputChannelData, totalNumOutputChannels, numSamples);
  17294. }
  17295. void AudioDeviceManager::CallbackHandler::audioDeviceAboutToStart (AudioIODevice* device)
  17296. {
  17297. owner->audioDeviceAboutToStartInt (device);
  17298. }
  17299. void AudioDeviceManager::CallbackHandler::audioDeviceStopped()
  17300. {
  17301. owner->audioDeviceStoppedInt();
  17302. }
  17303. void AudioDeviceManager::CallbackHandler::handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message)
  17304. {
  17305. owner->handleIncomingMidiMessageInt (source, message);
  17306. }
  17307. END_JUCE_NAMESPACE
  17308. /********* End of inlined file: juce_AudioDeviceManager.cpp *********/
  17309. /********* Start of inlined file: juce_AudioIODevice.cpp *********/
  17310. BEGIN_JUCE_NAMESPACE
  17311. AudioIODevice::AudioIODevice (const String& deviceName, const String& typeName_)
  17312. : name (deviceName),
  17313. typeName (typeName_)
  17314. {
  17315. }
  17316. AudioIODevice::~AudioIODevice()
  17317. {
  17318. }
  17319. bool AudioIODevice::hasControlPanel() const
  17320. {
  17321. return false;
  17322. }
  17323. bool AudioIODevice::showControlPanel()
  17324. {
  17325. jassertfalse // this should only be called for devices which return true from
  17326. // their hasControlPanel() method.
  17327. return false;
  17328. }
  17329. END_JUCE_NAMESPACE
  17330. /********* End of inlined file: juce_AudioIODevice.cpp *********/
  17331. /********* Start of inlined file: juce_AudioIODeviceType.cpp *********/
  17332. BEGIN_JUCE_NAMESPACE
  17333. AudioIODeviceType::AudioIODeviceType (const tchar* const name)
  17334. : typeName (name)
  17335. {
  17336. }
  17337. AudioIODeviceType::~AudioIODeviceType()
  17338. {
  17339. }
  17340. extern AudioIODeviceType* juce_createDefaultAudioIODeviceType();
  17341. #if JUCE_WIN32 && JUCE_ASIO
  17342. extern AudioIODeviceType* juce_createASIOAudioIODeviceType();
  17343. #endif
  17344. #if JUCE_WIN32 && JUCE_WDM_AUDIO
  17345. extern AudioIODeviceType* juce_createWDMAudioIODeviceType();
  17346. #endif
  17347. void AudioIODeviceType::createDeviceTypes (OwnedArray <AudioIODeviceType>& list)
  17348. {
  17349. AudioIODeviceType* const defaultDeviceType = juce_createDefaultAudioIODeviceType();
  17350. if (defaultDeviceType != 0)
  17351. list.add (defaultDeviceType);
  17352. #if JUCE_WIN32 && JUCE_ASIO
  17353. list.add (juce_createASIOAudioIODeviceType());
  17354. #endif
  17355. #if JUCE_WIN32 && JUCE_WDM_AUDIO
  17356. list.add (juce_createWDMAudioIODeviceType());
  17357. #endif
  17358. }
  17359. END_JUCE_NAMESPACE
  17360. /********* End of inlined file: juce_AudioIODeviceType.cpp *********/
  17361. /********* Start of inlined file: juce_MidiOutput.cpp *********/
  17362. BEGIN_JUCE_NAMESPACE
  17363. MidiOutput::MidiOutput() throw()
  17364. : Thread ("midi out"),
  17365. internal (0),
  17366. firstMessage (0)
  17367. {
  17368. }
  17369. MidiOutput::PendingMessage::PendingMessage (const uint8* const data,
  17370. const int len,
  17371. const double sampleNumber) throw()
  17372. : message (data, len, sampleNumber)
  17373. {
  17374. }
  17375. void MidiOutput::sendBlockOfMessages (const MidiBuffer& buffer,
  17376. const double millisecondCounterToStartAt,
  17377. double samplesPerSecondForBuffer) throw()
  17378. {
  17379. // You've got to call startBackgroundThread() for this to actually work..
  17380. jassert (isThreadRunning());
  17381. // this needs to be a value in the future - RTFM for this method!
  17382. jassert (millisecondCounterToStartAt > 0);
  17383. samplesPerSecondForBuffer *= 0.001;
  17384. MidiBuffer::Iterator i (buffer);
  17385. const uint8* data;
  17386. int len, time;
  17387. while (i.getNextEvent (data, len, time))
  17388. {
  17389. const double eventTime = millisecondCounterToStartAt + samplesPerSecondForBuffer * time;
  17390. PendingMessage* const m
  17391. = new PendingMessage (data, len, eventTime);
  17392. const ScopedLock sl (lock);
  17393. if (firstMessage == 0 || firstMessage->message.getTimeStamp() > eventTime)
  17394. {
  17395. m->next = firstMessage;
  17396. firstMessage = m;
  17397. }
  17398. else
  17399. {
  17400. PendingMessage* mm = firstMessage;
  17401. while (mm->next != 0 && mm->next->message.getTimeStamp() <= eventTime)
  17402. mm = mm->next;
  17403. m->next = mm->next;
  17404. mm->next = m;
  17405. }
  17406. }
  17407. notify();
  17408. }
  17409. void MidiOutput::clearAllPendingMessages() throw()
  17410. {
  17411. const ScopedLock sl (lock);
  17412. while (firstMessage != 0)
  17413. {
  17414. PendingMessage* const m = firstMessage;
  17415. firstMessage = firstMessage->next;
  17416. delete m;
  17417. }
  17418. }
  17419. void MidiOutput::startBackgroundThread() throw()
  17420. {
  17421. startThread (9);
  17422. }
  17423. void MidiOutput::stopBackgroundThread() throw()
  17424. {
  17425. stopThread (5000);
  17426. }
  17427. void MidiOutput::run()
  17428. {
  17429. while (! threadShouldExit())
  17430. {
  17431. uint32 now = Time::getMillisecondCounter();
  17432. uint32 eventTime = 0;
  17433. uint32 timeToWait = 500;
  17434. lock.enter();
  17435. PendingMessage* message = firstMessage;
  17436. if (message != 0)
  17437. {
  17438. eventTime = roundDoubleToInt (message->message.getTimeStamp());
  17439. if (eventTime > now + 20)
  17440. {
  17441. timeToWait = jmax (10, eventTime - now - 100);
  17442. message = 0;
  17443. }
  17444. else
  17445. {
  17446. firstMessage = message->next;
  17447. }
  17448. }
  17449. lock.exit();
  17450. if (message != 0)
  17451. {
  17452. if (eventTime > now)
  17453. {
  17454. Time::waitForMillisecondCounter (eventTime);
  17455. if (threadShouldExit())
  17456. break;
  17457. }
  17458. if (eventTime > now - 200)
  17459. sendMessageNow (message->message);
  17460. delete message;
  17461. }
  17462. else
  17463. {
  17464. jassert (timeToWait < 1000 * 30);
  17465. wait (timeToWait);
  17466. }
  17467. }
  17468. clearAllPendingMessages();
  17469. }
  17470. END_JUCE_NAMESPACE
  17471. /********* End of inlined file: juce_MidiOutput.cpp *********/
  17472. /********* Start of inlined file: juce_AudioDataConverters.cpp *********/
  17473. BEGIN_JUCE_NAMESPACE
  17474. void AudioDataConverters::convertFloatToInt16LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  17475. {
  17476. const double maxVal = (double) 0x7fff;
  17477. char* intData = (char*) dest;
  17478. for (int i = 0; i < numSamples; ++i)
  17479. {
  17480. *(uint16*)intData = swapIfBigEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  17481. intData += destBytesPerSample;
  17482. }
  17483. }
  17484. void AudioDataConverters::convertFloatToInt16BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  17485. {
  17486. const double maxVal = (double) 0x7fff;
  17487. char* intData = (char*) dest;
  17488. for (int i = 0; i < numSamples; ++i)
  17489. {
  17490. *(uint16*)intData = swapIfLittleEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  17491. intData += destBytesPerSample;
  17492. }
  17493. }
  17494. void AudioDataConverters::convertFloatToInt24LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  17495. {
  17496. const double maxVal = (double) 0x7fffff;
  17497. char* intData = (char*) dest;
  17498. for (int i = 0; i < numSamples; ++i)
  17499. {
  17500. littleEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  17501. intData += destBytesPerSample;
  17502. }
  17503. }
  17504. void AudioDataConverters::convertFloatToInt24BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  17505. {
  17506. const double maxVal = (double) 0x7fffff;
  17507. char* intData = (char*) dest;
  17508. for (int i = 0; i < numSamples; ++i)
  17509. {
  17510. bigEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  17511. intData += destBytesPerSample;
  17512. }
  17513. }
  17514. void AudioDataConverters::convertFloatToInt32LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  17515. {
  17516. const double maxVal = (double) 0x7fffffff;
  17517. char* intData = (char*) dest;
  17518. for (int i = 0; i < numSamples; ++i)
  17519. {
  17520. *(uint32*)intData = swapIfBigEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  17521. intData += destBytesPerSample;
  17522. }
  17523. }
  17524. void AudioDataConverters::convertFloatToInt32BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  17525. {
  17526. const double maxVal = (double) 0x7fffffff;
  17527. char* intData = (char*) dest;
  17528. for (int i = 0; i < numSamples; ++i)
  17529. {
  17530. *(uint32*)intData = swapIfLittleEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  17531. intData += destBytesPerSample;
  17532. }
  17533. }
  17534. void AudioDataConverters::convertFloatToFloat32LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  17535. {
  17536. char* d = (char*) dest;
  17537. for (int i = 0; i < numSamples; ++i)
  17538. {
  17539. *(float*)d = source[i];
  17540. #if JUCE_BIG_ENDIAN
  17541. *(uint32*)d = swapByteOrder (*(uint32*)d);
  17542. #endif
  17543. d += destBytesPerSample;
  17544. }
  17545. }
  17546. void AudioDataConverters::convertFloatToFloat32BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  17547. {
  17548. char* d = (char*) dest;
  17549. for (int i = 0; i < numSamples; ++i)
  17550. {
  17551. *(float*)d = source[i];
  17552. #if JUCE_LITTLE_ENDIAN
  17553. *(uint32*)d = swapByteOrder (*(uint32*)d);
  17554. #endif
  17555. d += destBytesPerSample;
  17556. }
  17557. }
  17558. void AudioDataConverters::convertInt16LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  17559. {
  17560. const float scale = 1.0f / 0x7fff;
  17561. const char* intData = (const char*) source;
  17562. for (int i = 0; i < numSamples; ++i)
  17563. {
  17564. dest[i] = scale * (short) swapIfBigEndian (*(uint16*)intData);
  17565. intData += srcBytesPerSample;
  17566. }
  17567. }
  17568. void AudioDataConverters::convertInt16BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  17569. {
  17570. const float scale = 1.0f / 0x7fff;
  17571. const char* intData = (const char*) source;
  17572. for (int i = 0; i < numSamples; ++i)
  17573. {
  17574. dest[i] = scale * (short) swapIfLittleEndian (*(uint16*)intData);
  17575. intData += srcBytesPerSample;
  17576. }
  17577. }
  17578. void AudioDataConverters::convertInt24LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  17579. {
  17580. const float scale = 1.0f / 0x7fffff;
  17581. const char* intData = (const char*) source;
  17582. for (int i = 0; i < numSamples; ++i)
  17583. {
  17584. dest[i] = scale * (short) littleEndian24Bit (intData);
  17585. intData += srcBytesPerSample;
  17586. }
  17587. }
  17588. void AudioDataConverters::convertInt24BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  17589. {
  17590. const float scale = 1.0f / 0x7fffff;
  17591. const char* intData = (const char*) source;
  17592. for (int i = 0; i < numSamples; ++i)
  17593. {
  17594. dest[i] = scale * (short) bigEndian24Bit (intData);
  17595. intData += srcBytesPerSample;
  17596. }
  17597. }
  17598. void AudioDataConverters::convertInt32LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  17599. {
  17600. const float scale = 1.0f / 0x7fffffff;
  17601. const char* intData = (const char*) source;
  17602. for (int i = 0; i < numSamples; ++i)
  17603. {
  17604. dest[i] = scale * (int) swapIfBigEndian (*(uint32*) intData);
  17605. intData += srcBytesPerSample;
  17606. }
  17607. }
  17608. void AudioDataConverters::convertInt32BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  17609. {
  17610. const float scale = 1.0f / 0x7fffffff;
  17611. const char* intData = (const char*) source;
  17612. for (int i = 0; i < numSamples; ++i)
  17613. {
  17614. dest[i] = scale * (int) (swapIfLittleEndian (*(uint32*) intData));
  17615. intData += srcBytesPerSample;
  17616. }
  17617. }
  17618. void AudioDataConverters::convertFloat32LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  17619. {
  17620. const char* s = (const char*) source;
  17621. for (int i = 0; i < numSamples; ++i)
  17622. {
  17623. dest[i] = *(float*)s;
  17624. #if JUCE_BIG_ENDIAN
  17625. uint32* const d = (uint32*) (dest + i);
  17626. *d = swapByteOrder (*d);
  17627. #endif
  17628. s += srcBytesPerSample;
  17629. }
  17630. }
  17631. void AudioDataConverters::convertFloat32BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  17632. {
  17633. const char* s = (const char*) source;
  17634. for (int i = 0; i < numSamples; ++i)
  17635. {
  17636. dest[i] = *(float*)s;
  17637. #if JUCE_LITTLE_ENDIAN
  17638. uint32* const d = (uint32*) (dest + i);
  17639. *d = swapByteOrder (*d);
  17640. #endif
  17641. s += srcBytesPerSample;
  17642. }
  17643. }
  17644. void AudioDataConverters::convertFloatToFormat (const DataFormat destFormat,
  17645. const float* const source,
  17646. void* const dest,
  17647. const int numSamples)
  17648. {
  17649. switch (destFormat)
  17650. {
  17651. case int16LE:
  17652. convertFloatToInt16LE (source, dest, numSamples);
  17653. break;
  17654. case int16BE:
  17655. convertFloatToInt16BE (source, dest, numSamples);
  17656. break;
  17657. case int24LE:
  17658. convertFloatToInt24LE (source, dest, numSamples);
  17659. break;
  17660. case int24BE:
  17661. convertFloatToInt24BE (source, dest, numSamples);
  17662. break;
  17663. case int32LE:
  17664. convertFloatToInt32LE (source, dest, numSamples);
  17665. break;
  17666. case int32BE:
  17667. convertFloatToInt32BE (source, dest, numSamples);
  17668. break;
  17669. case float32LE:
  17670. convertFloatToFloat32LE (source, dest, numSamples);
  17671. break;
  17672. case float32BE:
  17673. convertFloatToFloat32BE (source, dest, numSamples);
  17674. break;
  17675. default:
  17676. jassertfalse
  17677. break;
  17678. }
  17679. }
  17680. void AudioDataConverters::convertFormatToFloat (const DataFormat sourceFormat,
  17681. const void* const source,
  17682. float* const dest,
  17683. const int numSamples)
  17684. {
  17685. switch (sourceFormat)
  17686. {
  17687. case int16LE:
  17688. convertInt16LEToFloat (source, dest, numSamples);
  17689. break;
  17690. case int16BE:
  17691. convertInt16BEToFloat (source, dest, numSamples);
  17692. break;
  17693. case int24LE:
  17694. convertInt24LEToFloat (source, dest, numSamples);
  17695. break;
  17696. case int24BE:
  17697. convertInt24BEToFloat (source, dest, numSamples);
  17698. break;
  17699. case int32LE:
  17700. convertInt32LEToFloat (source, dest, numSamples);
  17701. break;
  17702. case int32BE:
  17703. convertInt32BEToFloat (source, dest, numSamples);
  17704. break;
  17705. case float32LE:
  17706. convertFloat32LEToFloat (source, dest, numSamples);
  17707. break;
  17708. case float32BE:
  17709. convertFloat32BEToFloat (source, dest, numSamples);
  17710. break;
  17711. default:
  17712. jassertfalse
  17713. break;
  17714. }
  17715. }
  17716. void AudioDataConverters::interleaveSamples (const float** const source,
  17717. float* const dest,
  17718. const int numSamples,
  17719. const int numChannels)
  17720. {
  17721. for (int chan = 0; chan < numChannels; ++chan)
  17722. {
  17723. int i = chan;
  17724. const float* src = source [chan];
  17725. for (int j = 0; j < numSamples; ++j)
  17726. {
  17727. dest [i] = src [j];
  17728. i += numChannels;
  17729. }
  17730. }
  17731. }
  17732. void AudioDataConverters::deinterleaveSamples (const float* const source,
  17733. float** const dest,
  17734. const int numSamples,
  17735. const int numChannels)
  17736. {
  17737. for (int chan = 0; chan < numChannels; ++chan)
  17738. {
  17739. int i = chan;
  17740. float* dst = dest [chan];
  17741. for (int j = 0; j < numSamples; ++j)
  17742. {
  17743. dst [j] = source [i];
  17744. i += numChannels;
  17745. }
  17746. }
  17747. }
  17748. END_JUCE_NAMESPACE
  17749. /********* End of inlined file: juce_AudioDataConverters.cpp *********/
  17750. /********* Start of inlined file: juce_AudioSampleBuffer.cpp *********/
  17751. BEGIN_JUCE_NAMESPACE
  17752. AudioSampleBuffer::AudioSampleBuffer (const int numChannels_,
  17753. const int numSamples) throw()
  17754. : numChannels (numChannels_),
  17755. size (numSamples)
  17756. {
  17757. jassert (numSamples >= 0);
  17758. jassert (numChannels_ > 0 && numChannels_ <= maxNumAudioSampleBufferChannels);
  17759. allocatedBytes = numChannels * numSamples * sizeof (float) + 32;
  17760. allocatedData = (float*) juce_malloc (allocatedBytes);
  17761. float* chan = allocatedData;
  17762. for (int i = 0; i < numChannels_; ++i)
  17763. {
  17764. channels[i] = chan;
  17765. chan += numSamples;
  17766. }
  17767. channels [numChannels_] = 0;
  17768. }
  17769. AudioSampleBuffer::AudioSampleBuffer (float** dataToReferTo,
  17770. const int numChannels_,
  17771. const int numSamples) throw()
  17772. : numChannels (numChannels_),
  17773. size (numSamples),
  17774. allocatedBytes (0),
  17775. allocatedData (0)
  17776. {
  17777. jassert (((unsigned int) numChannels_) <= (unsigned int) maxNumAudioSampleBufferChannels);
  17778. for (int i = 0; i < numChannels_; ++i)
  17779. {
  17780. // you have to pass in the same number of valid pointers as numChannels
  17781. jassert (dataToReferTo[i] != 0);
  17782. channels[i] = dataToReferTo[i];
  17783. }
  17784. channels [numChannels_] = 0;
  17785. }
  17786. void AudioSampleBuffer::setDataToReferTo (float** dataToReferTo,
  17787. const int numChannels_,
  17788. const int numSamples) throw()
  17789. {
  17790. jassert (((unsigned int) numChannels_) <= (unsigned int) maxNumAudioSampleBufferChannels);
  17791. juce_free (allocatedData);
  17792. allocatedData = 0;
  17793. allocatedBytes = 0;
  17794. numChannels = numChannels_;
  17795. size = numSamples;
  17796. for (int i = 0; i < numChannels_; ++i)
  17797. {
  17798. // you have to pass in the same number of valid pointers as numChannels
  17799. jassert (dataToReferTo[i] != 0);
  17800. channels[i] = dataToReferTo[i];
  17801. }
  17802. channels [numChannels_] = 0;
  17803. }
  17804. AudioSampleBuffer::AudioSampleBuffer (const AudioSampleBuffer& other) throw()
  17805. : numChannels (other.numChannels),
  17806. size (other.size)
  17807. {
  17808. if (other.allocatedData != 0)
  17809. {
  17810. allocatedBytes = numChannels * size * sizeof (float) + 32;
  17811. allocatedData = (float*) juce_malloc (allocatedBytes);
  17812. memcpy (allocatedData, other.allocatedData, allocatedBytes);
  17813. float* chan = allocatedData;
  17814. for (int i = 0; i < numChannels; ++i)
  17815. {
  17816. channels[i] = chan;
  17817. chan += size;
  17818. }
  17819. channels [numChannels] = 0;
  17820. }
  17821. else
  17822. {
  17823. allocatedData = 0;
  17824. allocatedBytes = 0;
  17825. memcpy (channels, other.channels, sizeof (channels));
  17826. }
  17827. }
  17828. const AudioSampleBuffer& AudioSampleBuffer::operator= (const AudioSampleBuffer& other) throw()
  17829. {
  17830. if (this != &other)
  17831. {
  17832. setSize (other.getNumChannels(), other.getNumSamples(), false, false, false);
  17833. const int numBytes = size * sizeof (float);
  17834. for (int i = 0; i < numChannels; ++i)
  17835. memcpy (channels[i], other.channels[i], numBytes);
  17836. }
  17837. return *this;
  17838. }
  17839. AudioSampleBuffer::~AudioSampleBuffer() throw()
  17840. {
  17841. juce_free (allocatedData);
  17842. }
  17843. float* AudioSampleBuffer::getSampleData (const int channelNumber,
  17844. const int sampleOffset) const throw()
  17845. {
  17846. jassert (((unsigned int) channelNumber) < (unsigned int) numChannels);
  17847. jassert (((unsigned int) sampleOffset) < (unsigned int) size);
  17848. return channels [channelNumber] + sampleOffset;
  17849. }
  17850. void AudioSampleBuffer::setSize (const int newNumChannels,
  17851. const int newNumSamples,
  17852. const bool keepExistingContent,
  17853. const bool clearExtraSpace,
  17854. const bool avoidReallocating) throw()
  17855. {
  17856. jassert (newNumChannels > 0 && newNumChannels <= maxNumAudioSampleBufferChannels);
  17857. if (newNumSamples != size || newNumChannels != numChannels)
  17858. {
  17859. const int newTotalBytes = newNumChannels * newNumSamples * sizeof (float) + 32;
  17860. if (keepExistingContent)
  17861. {
  17862. float* const newData = (clearExtraSpace) ? (float*) juce_calloc (newTotalBytes)
  17863. : (float*) juce_malloc (newTotalBytes);
  17864. const int sizeToCopy = sizeof (float) * jmin (newNumSamples, size);
  17865. for (int i = jmin (newNumChannels, numChannels); --i >= 0;)
  17866. {
  17867. memcpy (newData + i * newNumSamples,
  17868. channels[i],
  17869. sizeToCopy);
  17870. }
  17871. juce_free (allocatedData);
  17872. allocatedData = newData;
  17873. allocatedBytes = newTotalBytes;
  17874. }
  17875. else
  17876. {
  17877. if (avoidReallocating && allocatedBytes >= newTotalBytes)
  17878. {
  17879. if (clearExtraSpace)
  17880. zeromem (allocatedData, newTotalBytes);
  17881. }
  17882. else
  17883. {
  17884. juce_free (allocatedData);
  17885. allocatedData = (clearExtraSpace) ? (float*) juce_calloc (newTotalBytes)
  17886. : (float*) juce_malloc (newTotalBytes);
  17887. allocatedBytes = newTotalBytes;
  17888. }
  17889. }
  17890. size = newNumSamples;
  17891. numChannels = newNumChannels;
  17892. float* chan = allocatedData;
  17893. for (int i = 0; i < newNumChannels; ++i)
  17894. {
  17895. channels[i] = chan;
  17896. chan += size;
  17897. }
  17898. channels [newNumChannels] = 0;
  17899. }
  17900. }
  17901. void AudioSampleBuffer::clear() throw()
  17902. {
  17903. for (int i = 0; i < numChannels; ++i)
  17904. zeromem (channels[i], size * sizeof (float));
  17905. }
  17906. void AudioSampleBuffer::clear (const int startSample,
  17907. const int numSamples) throw()
  17908. {
  17909. jassert (startSample >= 0 && startSample + numSamples <= size);
  17910. for (int i = 0; i < numChannels; ++i)
  17911. zeromem (channels [i] + startSample, numSamples * sizeof (float));
  17912. }
  17913. void AudioSampleBuffer::clear (const int channel,
  17914. const int startSample,
  17915. const int numSamples) throw()
  17916. {
  17917. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  17918. jassert (startSample >= 0 && startSample + numSamples <= size);
  17919. zeromem (channels [channel] + startSample, numSamples * sizeof (float));
  17920. }
  17921. void AudioSampleBuffer::applyGain (const int channel,
  17922. const int startSample,
  17923. int numSamples,
  17924. const float gain) throw()
  17925. {
  17926. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  17927. jassert (startSample >= 0 && startSample + numSamples <= size);
  17928. if (gain != 1.0f)
  17929. {
  17930. float* d = channels [channel] + startSample;
  17931. if (gain == 0.0f)
  17932. {
  17933. zeromem (d, sizeof (float) * numSamples);
  17934. }
  17935. else
  17936. {
  17937. while (--numSamples >= 0)
  17938. *d++ *= gain;
  17939. }
  17940. }
  17941. }
  17942. void AudioSampleBuffer::applyGainRamp (const int channel,
  17943. const int startSample,
  17944. int numSamples,
  17945. float startGain,
  17946. float endGain) throw()
  17947. {
  17948. if (startGain == endGain)
  17949. {
  17950. applyGain (channel, startSample, numSamples, startGain);
  17951. }
  17952. else
  17953. {
  17954. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  17955. jassert (startSample >= 0 && startSample + numSamples <= size);
  17956. const float increment = (endGain - startGain) / numSamples;
  17957. float* d = channels [channel] + startSample;
  17958. while (--numSamples >= 0)
  17959. {
  17960. *d++ *= startGain;
  17961. startGain += increment;
  17962. }
  17963. }
  17964. }
  17965. void AudioSampleBuffer::applyGain (const int startSample,
  17966. const int numSamples,
  17967. const float gain) throw()
  17968. {
  17969. for (int i = 0; i < numChannels; ++i)
  17970. applyGain (i, startSample, numSamples, gain);
  17971. }
  17972. void AudioSampleBuffer::addFrom (const int destChannel,
  17973. const int destStartSample,
  17974. const AudioSampleBuffer& source,
  17975. const int sourceChannel,
  17976. const int sourceStartSample,
  17977. int numSamples,
  17978. const float gain) throw()
  17979. {
  17980. jassert (&source != this || sourceChannel != destChannel);
  17981. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  17982. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  17983. jassert (((unsigned int) sourceChannel) < (unsigned int) source.numChannels);
  17984. jassert (sourceStartSample >= 0 && sourceStartSample + numSamples <= source.size);
  17985. if (gain != 0.0f && numSamples > 0)
  17986. {
  17987. float* d = channels [destChannel] + destStartSample;
  17988. const float* s = source.channels [sourceChannel] + sourceStartSample;
  17989. if (gain != 1.0f)
  17990. {
  17991. while (--numSamples >= 0)
  17992. *d++ += gain * *s++;
  17993. }
  17994. else
  17995. {
  17996. while (--numSamples >= 0)
  17997. *d++ += *s++;
  17998. }
  17999. }
  18000. }
  18001. void AudioSampleBuffer::addFrom (const int destChannel,
  18002. const int destStartSample,
  18003. const float* source,
  18004. int numSamples,
  18005. const float gain) throw()
  18006. {
  18007. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  18008. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  18009. jassert (source != 0);
  18010. if (gain != 0.0f && numSamples > 0)
  18011. {
  18012. float* d = channels [destChannel] + destStartSample;
  18013. if (gain != 1.0f)
  18014. {
  18015. while (--numSamples >= 0)
  18016. *d++ += gain * *source++;
  18017. }
  18018. else
  18019. {
  18020. while (--numSamples >= 0)
  18021. *d++ += *source++;
  18022. }
  18023. }
  18024. }
  18025. void AudioSampleBuffer::addFromWithRamp (const int destChannel,
  18026. const int destStartSample,
  18027. const float* source,
  18028. int numSamples,
  18029. float startGain,
  18030. const float endGain) throw()
  18031. {
  18032. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  18033. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  18034. jassert (source != 0);
  18035. if (startGain == endGain)
  18036. {
  18037. addFrom (destChannel,
  18038. destStartSample,
  18039. source,
  18040. numSamples,
  18041. startGain);
  18042. }
  18043. else
  18044. {
  18045. if (numSamples > 0 && (startGain != 0.0f || endGain != 0.0f))
  18046. {
  18047. const float increment = (endGain - startGain) / numSamples;
  18048. float* d = channels [destChannel] + destStartSample;
  18049. while (--numSamples >= 0)
  18050. {
  18051. *d++ += startGain * *source++;
  18052. startGain += increment;
  18053. }
  18054. }
  18055. }
  18056. }
  18057. void AudioSampleBuffer::copyFrom (const int destChannel,
  18058. const int destStartSample,
  18059. const AudioSampleBuffer& source,
  18060. const int sourceChannel,
  18061. const int sourceStartSample,
  18062. int numSamples) throw()
  18063. {
  18064. jassert (&source != this || sourceChannel != destChannel);
  18065. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  18066. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  18067. jassert (((unsigned int) sourceChannel) < (unsigned int) source.numChannels);
  18068. jassert (sourceStartSample >= 0 && sourceStartSample + numSamples <= source.size);
  18069. if (numSamples > 0)
  18070. {
  18071. memcpy (channels [destChannel] + destStartSample,
  18072. source.channels [sourceChannel] + sourceStartSample,
  18073. sizeof (float) * numSamples);
  18074. }
  18075. }
  18076. void AudioSampleBuffer::copyFrom (const int destChannel,
  18077. const int destStartSample,
  18078. const float* source,
  18079. int numSamples) throw()
  18080. {
  18081. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  18082. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  18083. jassert (source != 0);
  18084. if (numSamples > 0)
  18085. {
  18086. memcpy (channels [destChannel] + destStartSample,
  18087. source,
  18088. sizeof (float) * numSamples);
  18089. }
  18090. }
  18091. void AudioSampleBuffer::findMinMax (const int channel,
  18092. const int startSample,
  18093. int numSamples,
  18094. float& minVal,
  18095. float& maxVal) const throw()
  18096. {
  18097. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  18098. jassert (startSample >= 0 && startSample + numSamples <= size);
  18099. if (numSamples <= 0)
  18100. {
  18101. minVal = 0.0f;
  18102. maxVal = 0.0f;
  18103. }
  18104. else
  18105. {
  18106. const float* d = channels [channel] + startSample;
  18107. float mn = *d++;
  18108. float mx = mn;
  18109. while (--numSamples > 0) // (> 0 rather than >= 0 because we've already taken the first sample)
  18110. {
  18111. const float samp = *d++;
  18112. if (samp > mx)
  18113. mx = samp;
  18114. if (samp < mn)
  18115. mn = samp;
  18116. }
  18117. maxVal = mx;
  18118. minVal = mn;
  18119. }
  18120. }
  18121. float AudioSampleBuffer::getMagnitude (const int channel,
  18122. const int startSample,
  18123. const int numSamples) const throw()
  18124. {
  18125. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  18126. jassert (startSample >= 0 && startSample + numSamples <= size);
  18127. float mn, mx;
  18128. findMinMax (channel, startSample, numSamples, mn, mx);
  18129. return jmax (mn, -mn, mx, -mx);
  18130. }
  18131. float AudioSampleBuffer::getMagnitude (const int startSample,
  18132. const int numSamples) const throw()
  18133. {
  18134. float mag = 0.0f;
  18135. for (int i = 0; i < numChannels; ++i)
  18136. mag = jmax (mag, getMagnitude (i, startSample, numSamples));
  18137. return mag;
  18138. }
  18139. float AudioSampleBuffer::getRMSLevel (const int channel,
  18140. const int startSample,
  18141. const int numSamples) const throw()
  18142. {
  18143. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  18144. jassert (startSample >= 0 && startSample + numSamples <= size);
  18145. if (numSamples <= 0 || channel < 0 || channel >= numChannels)
  18146. return 0.0f;
  18147. const float* const data = channels [channel] + startSample;
  18148. double sum = 0.0;
  18149. for (int i = 0; i < numSamples; ++i)
  18150. {
  18151. const float sample = data [i];
  18152. sum += sample * sample;
  18153. }
  18154. return (float) sqrt (sum / numSamples);
  18155. }
  18156. void AudioSampleBuffer::readFromAudioReader (AudioFormatReader* reader,
  18157. const int startSample,
  18158. const int numSamples,
  18159. const int readerStartSample,
  18160. const bool useLeftChan,
  18161. const bool useRightChan) throw()
  18162. {
  18163. jassert (reader != 0);
  18164. jassert (startSample >= 0 && startSample + numSamples <= size);
  18165. if (numSamples > 0)
  18166. {
  18167. int* chans[3];
  18168. if (useLeftChan == useRightChan)
  18169. {
  18170. chans[0] = (int*) getSampleData (0, startSample);
  18171. chans[1] = (reader->numChannels > 1 && getNumChannels() > 1) ? (int*) getSampleData (1, startSample) : 0;
  18172. }
  18173. else if (useLeftChan || (reader->numChannels == 1))
  18174. {
  18175. chans[0] = (int*) getSampleData (0, startSample);
  18176. chans[1] = 0;
  18177. }
  18178. else if (useRightChan)
  18179. {
  18180. chans[0] = 0;
  18181. chans[1] = (int*) getSampleData (0, startSample);
  18182. }
  18183. chans[2] = 0;
  18184. reader->read (chans, readerStartSample, numSamples);
  18185. if (! reader->usesFloatingPointData)
  18186. {
  18187. for (int j = 0; j < 2; ++j)
  18188. {
  18189. float* const d = (float*) (chans[j]);
  18190. if (d != 0)
  18191. {
  18192. const float multiplier = 1.0f / 0x7fffffff;
  18193. for (int i = 0; i < numSamples; ++i)
  18194. d[i] = *(int*)(d + i) * multiplier;
  18195. }
  18196. }
  18197. }
  18198. if (numChannels > 1 && (chans[0] == 0 || chans[1] == 0))
  18199. {
  18200. // if this is a stereo buffer and the source was mono, dupe the first channel..
  18201. memcpy (getSampleData (1, startSample),
  18202. getSampleData (0, startSample),
  18203. sizeof (float) * numSamples);
  18204. }
  18205. }
  18206. }
  18207. void AudioSampleBuffer::writeToAudioWriter (AudioFormatWriter* writer,
  18208. const int startSample,
  18209. const int numSamples) const throw()
  18210. {
  18211. jassert (startSample >= 0 && startSample + numSamples <= size);
  18212. if (numSamples > 0)
  18213. {
  18214. int* chans [3];
  18215. if (writer->isFloatingPoint())
  18216. {
  18217. chans[0] = (int*) getSampleData (0, startSample);
  18218. if (numChannels > 1)
  18219. chans[1] = (int*) getSampleData (1, startSample);
  18220. else
  18221. chans[1] = 0;
  18222. chans[2] = 0;
  18223. writer->write ((const int**) chans, numSamples);
  18224. }
  18225. else
  18226. {
  18227. chans[0] = (int*) juce_malloc (sizeof (int) * numSamples * 2);
  18228. if (numChannels > 1)
  18229. chans[1] = chans[0] + numSamples;
  18230. else
  18231. chans[1] = 0;
  18232. chans[2] = 0;
  18233. for (int j = 0; j < 2; ++j)
  18234. {
  18235. int* const dest = chans[j];
  18236. if (dest != 0)
  18237. {
  18238. const float* const src = channels [j] + startSample;
  18239. for (int i = 0; i < numSamples; ++i)
  18240. {
  18241. const double samp = src[i];
  18242. if (samp <= -1.0)
  18243. dest[i] = INT_MIN;
  18244. else if (samp >= 1.0)
  18245. dest[i] = INT_MAX;
  18246. else
  18247. dest[i] = roundDoubleToInt (INT_MAX * samp);
  18248. }
  18249. }
  18250. }
  18251. writer->write ((const int**) chans, numSamples);
  18252. juce_free (chans[0]);
  18253. }
  18254. }
  18255. }
  18256. END_JUCE_NAMESPACE
  18257. /********* End of inlined file: juce_AudioSampleBuffer.cpp *********/
  18258. /********* Start of inlined file: juce_IIRFilter.cpp *********/
  18259. BEGIN_JUCE_NAMESPACE
  18260. IIRFilter::IIRFilter() throw()
  18261. : active (false)
  18262. {
  18263. reset();
  18264. }
  18265. IIRFilter::IIRFilter (const IIRFilter& other) throw()
  18266. : active (other.active)
  18267. {
  18268. const ScopedLock sl (other.processLock);
  18269. memcpy (coefficients, other.coefficients, sizeof (coefficients));
  18270. reset();
  18271. }
  18272. IIRFilter::~IIRFilter() throw()
  18273. {
  18274. }
  18275. void IIRFilter::reset() throw()
  18276. {
  18277. const ScopedLock sl (processLock);
  18278. x1 = 0;
  18279. x2 = 0;
  18280. y1 = 0;
  18281. y2 = 0;
  18282. }
  18283. void IIRFilter::processSamples (float* const samples,
  18284. const int numSamples) throw()
  18285. {
  18286. const ScopedLock sl (processLock);
  18287. if (active)
  18288. {
  18289. for (int i = 0; i < numSamples; ++i)
  18290. {
  18291. const float in = samples[i];
  18292. float out = coefficients[0] * in
  18293. + coefficients[1] * x1
  18294. + coefficients[2] * x2
  18295. - coefficients[4] * y1
  18296. - coefficients[5] * y2;
  18297. #if JUCE_INTEL
  18298. if (! (out < -1.0e-8 || out > 1.0e-8))
  18299. out = 0;
  18300. #endif
  18301. x2 = x1;
  18302. x1 = in;
  18303. y2 = y1;
  18304. y1 = out;
  18305. samples[i] = out;
  18306. }
  18307. }
  18308. }
  18309. void IIRFilter::makeLowPass (const double sampleRate,
  18310. const double frequency) throw()
  18311. {
  18312. jassert (sampleRate > 0);
  18313. const double n = 1.0 / tan (double_Pi * frequency / sampleRate);
  18314. const double nSquared = n * n;
  18315. const double c1 = 1.0 / (1.0 + sqrt (2.0) * n + nSquared);
  18316. setCoefficients (c1,
  18317. c1 * 2.0f,
  18318. c1,
  18319. 1.0,
  18320. c1 * 2.0 * (1.0 - nSquared),
  18321. c1 * (1.0 - sqrt (2.0) * n + nSquared));
  18322. }
  18323. void IIRFilter::makeHighPass (const double sampleRate,
  18324. const double frequency) throw()
  18325. {
  18326. const double n = tan (double_Pi * frequency / sampleRate);
  18327. const double nSquared = n * n;
  18328. const double c1 = 1.0 / (1.0 + sqrt (2.0) * n + nSquared);
  18329. setCoefficients (c1,
  18330. c1 * -2.0f,
  18331. c1,
  18332. 1.0,
  18333. c1 * 2.0 * (nSquared - 1.0),
  18334. c1 * (1.0 - sqrt (2.0) * n + nSquared));
  18335. }
  18336. void IIRFilter::makeLowShelf (const double sampleRate,
  18337. const double cutOffFrequency,
  18338. const double Q,
  18339. const float gainFactor) throw()
  18340. {
  18341. jassert (sampleRate > 0);
  18342. jassert (Q > 0);
  18343. const double A = jmax (0.0f, gainFactor);
  18344. const double aminus1 = A - 1.0;
  18345. const double aplus1 = A + 1.0;
  18346. const double omega = (double_Pi * 2.0 * jmax (cutOffFrequency, 2.0)) / sampleRate;
  18347. const double coso = cos (omega);
  18348. const double beta = sin (omega) * sqrt (A) / Q;
  18349. const double aminus1TimesCoso = aminus1 * coso;
  18350. setCoefficients (A * (aplus1 - aminus1TimesCoso + beta),
  18351. A * 2.0 * (aminus1 - aplus1 * coso),
  18352. A * (aplus1 - aminus1TimesCoso - beta),
  18353. aplus1 + aminus1TimesCoso + beta,
  18354. -2.0 * (aminus1 + aplus1 * coso),
  18355. aplus1 + aminus1TimesCoso - beta);
  18356. }
  18357. void IIRFilter::makeHighShelf (const double sampleRate,
  18358. const double cutOffFrequency,
  18359. const double Q,
  18360. const float gainFactor) throw()
  18361. {
  18362. jassert (sampleRate > 0);
  18363. jassert (Q > 0);
  18364. const double A = jmax (0.0f, gainFactor);
  18365. const double aminus1 = A - 1.0;
  18366. const double aplus1 = A + 1.0;
  18367. const double omega = (double_Pi * 2.0 * jmax (cutOffFrequency, 2.0)) / sampleRate;
  18368. const double coso = cos (omega);
  18369. const double beta = sin (omega) * sqrt (A) / Q;
  18370. const double aminus1TimesCoso = aminus1 * coso;
  18371. setCoefficients (A * (aplus1 + aminus1TimesCoso + beta),
  18372. A * -2.0 * (aminus1 + aplus1 * coso),
  18373. A * (aplus1 + aminus1TimesCoso - beta),
  18374. aplus1 - aminus1TimesCoso + beta,
  18375. 2.0 * (aminus1 - aplus1 * coso),
  18376. aplus1 - aminus1TimesCoso - beta);
  18377. }
  18378. void IIRFilter::makeBandPass (const double sampleRate,
  18379. const double centreFrequency,
  18380. const double Q,
  18381. const float gainFactor) throw()
  18382. {
  18383. jassert (sampleRate > 0);
  18384. jassert (Q > 0);
  18385. const double A = jmax (0.0f, gainFactor);
  18386. const double omega = (double_Pi * 2.0 * jmax (centreFrequency, 2.0)) / sampleRate;
  18387. const double alpha = 0.5 * sin (omega) / Q;
  18388. const double c2 = -2.0 * cos (omega);
  18389. const double alphaTimesA = alpha * A;
  18390. const double alphaOverA = alpha / A;
  18391. setCoefficients (1.0 + alphaTimesA,
  18392. c2,
  18393. 1.0 - alphaTimesA,
  18394. 1.0 + alphaOverA,
  18395. c2,
  18396. 1.0 - alphaOverA);
  18397. }
  18398. void IIRFilter::makeInactive() throw()
  18399. {
  18400. const ScopedLock sl (processLock);
  18401. active = false;
  18402. }
  18403. void IIRFilter::copyCoefficientsFrom (const IIRFilter& other) throw()
  18404. {
  18405. const ScopedLock sl (processLock);
  18406. memcpy (coefficients, other.coefficients, sizeof (coefficients));
  18407. active = other.active;
  18408. }
  18409. void IIRFilter::setCoefficients (double c1,
  18410. double c2,
  18411. double c3,
  18412. double c4,
  18413. double c5,
  18414. double c6) throw()
  18415. {
  18416. const double a = 1.0 / c4;
  18417. c1 *= a;
  18418. c2 *= a;
  18419. c3 *= a;
  18420. c5 *= a;
  18421. c6 *= a;
  18422. const ScopedLock sl (processLock);
  18423. coefficients[0] = (float) c1;
  18424. coefficients[1] = (float) c2;
  18425. coefficients[2] = (float) c3;
  18426. coefficients[3] = (float) c4;
  18427. coefficients[4] = (float) c5;
  18428. coefficients[5] = (float) c6;
  18429. active = true;
  18430. }
  18431. END_JUCE_NAMESPACE
  18432. /********* End of inlined file: juce_IIRFilter.cpp *********/
  18433. /********* Start of inlined file: juce_MidiBuffer.cpp *********/
  18434. BEGIN_JUCE_NAMESPACE
  18435. MidiBuffer::MidiBuffer() throw()
  18436. : ArrayAllocationBase <uint8> (32),
  18437. bytesUsed (0)
  18438. {
  18439. }
  18440. MidiBuffer::MidiBuffer (const MidiBuffer& other) throw()
  18441. : ArrayAllocationBase <uint8> (32),
  18442. bytesUsed (other.bytesUsed)
  18443. {
  18444. ensureAllocatedSize (bytesUsed);
  18445. memcpy (elements, other.elements, bytesUsed);
  18446. }
  18447. const MidiBuffer& MidiBuffer::operator= (const MidiBuffer& other) throw()
  18448. {
  18449. if (this != &other)
  18450. {
  18451. bytesUsed = other.bytesUsed;
  18452. ensureAllocatedSize (bytesUsed);
  18453. if (bytesUsed > 0)
  18454. memcpy (elements, other.elements, bytesUsed);
  18455. }
  18456. return *this;
  18457. }
  18458. MidiBuffer::~MidiBuffer() throw()
  18459. {
  18460. }
  18461. void MidiBuffer::clear() throw()
  18462. {
  18463. bytesUsed = 0;
  18464. }
  18465. void MidiBuffer::clear (const int startSample,
  18466. const int numSamples) throw()
  18467. {
  18468. uint8* const start = findEventAfter (elements, startSample - 1);
  18469. uint8* const end = findEventAfter (start, startSample + numSamples - 1);
  18470. if (end > start)
  18471. {
  18472. const size_t bytesToMove = (size_t) (bytesUsed - (end - elements));
  18473. if (bytesToMove > 0)
  18474. memmove (start, end, bytesToMove);
  18475. bytesUsed -= (int) (end - start);
  18476. }
  18477. }
  18478. void MidiBuffer::addEvent (const MidiMessage& m,
  18479. const int sampleNumber) throw()
  18480. {
  18481. addEvent (m.getRawData(), m.getRawDataSize(), sampleNumber);
  18482. }
  18483. static int findActualEventLength (const uint8* const data,
  18484. const int maxBytes) throw()
  18485. {
  18486. unsigned int byte = (unsigned int) *data;
  18487. int size = 0;
  18488. if (byte == 0xf0 || byte == 0xf7)
  18489. {
  18490. const uint8* d = data + 1;
  18491. while (d < data + maxBytes)
  18492. if (*d++ == 0xf7)
  18493. break;
  18494. size = (int) (d - data);
  18495. }
  18496. else if (byte == 0xff)
  18497. {
  18498. int n;
  18499. const int bytesLeft = MidiMessage::readVariableLengthVal (data + 1, n);
  18500. size = jmin (maxBytes, n + 2 + bytesLeft);
  18501. }
  18502. else if (byte >= 0x80)
  18503. {
  18504. size = jmin (maxBytes, MidiMessage::getMessageLengthFromFirstByte ((uint8) byte));
  18505. }
  18506. return size;
  18507. }
  18508. void MidiBuffer::addEvent (const uint8* const newData,
  18509. const int maxBytes,
  18510. const int sampleNumber) throw()
  18511. {
  18512. const int numBytes = findActualEventLength (newData, maxBytes);
  18513. if (numBytes > 0)
  18514. {
  18515. ensureAllocatedSize (bytesUsed + numBytes + 6);
  18516. uint8* d = findEventAfter (elements, sampleNumber);
  18517. const size_t bytesToMove = (size_t) (bytesUsed - (d - elements));
  18518. if (bytesToMove > 0)
  18519. memmove (d + numBytes + 6,
  18520. d,
  18521. bytesToMove);
  18522. *(int*) d = sampleNumber;
  18523. d += 4;
  18524. *(uint16*) d = (uint16) numBytes;
  18525. d += 2;
  18526. memcpy (d, newData, numBytes);
  18527. bytesUsed += numBytes + 6;
  18528. }
  18529. }
  18530. void MidiBuffer::addEvents (const MidiBuffer& otherBuffer,
  18531. const int startSample,
  18532. const int numSamples,
  18533. const int sampleDeltaToAdd) throw()
  18534. {
  18535. Iterator i (otherBuffer);
  18536. i.setNextSamplePosition (startSample);
  18537. const uint8* data;
  18538. int size, position;
  18539. while (i.getNextEvent (data, size, position)
  18540. && (position < startSample + numSamples || numSamples < 0))
  18541. {
  18542. addEvent (data, size, position + sampleDeltaToAdd);
  18543. }
  18544. }
  18545. bool MidiBuffer::isEmpty() const throw()
  18546. {
  18547. return bytesUsed == 0;
  18548. }
  18549. int MidiBuffer::getNumEvents() const throw()
  18550. {
  18551. int n = 0;
  18552. const uint8* d = elements;
  18553. const uint8* const end = elements + bytesUsed;
  18554. while (d < end)
  18555. {
  18556. d += 4;
  18557. d += 2 + *(const uint16*) d;
  18558. ++n;
  18559. }
  18560. return n;
  18561. }
  18562. int MidiBuffer::getFirstEventTime() const throw()
  18563. {
  18564. return (bytesUsed > 0) ? *(const int*) elements : 0;
  18565. }
  18566. int MidiBuffer::getLastEventTime() const throw()
  18567. {
  18568. if (bytesUsed == 0)
  18569. return 0;
  18570. const uint8* d = elements;
  18571. const uint8* const endData = d + bytesUsed;
  18572. for (;;)
  18573. {
  18574. const uint8* nextOne = d + 6 + * (const uint16*) (d + 4);
  18575. if (nextOne >= endData)
  18576. return *(const int*) d;
  18577. d = nextOne;
  18578. }
  18579. }
  18580. uint8* MidiBuffer::findEventAfter (uint8* d, const int samplePosition) const throw()
  18581. {
  18582. const uint8* const endData = elements + bytesUsed;
  18583. while (d < endData && *(int*) d <= samplePosition)
  18584. {
  18585. d += 4;
  18586. d += 2 + *(uint16*) d;
  18587. }
  18588. return d;
  18589. }
  18590. MidiBuffer::Iterator::Iterator (const MidiBuffer& buffer) throw()
  18591. : buffer (buffer),
  18592. data (buffer.elements)
  18593. {
  18594. }
  18595. MidiBuffer::Iterator::~Iterator() throw()
  18596. {
  18597. }
  18598. void MidiBuffer::Iterator::setNextSamplePosition (const int samplePosition) throw()
  18599. {
  18600. data = buffer.elements;
  18601. const uint8* dataEnd = buffer.elements + buffer.bytesUsed;
  18602. while (data < dataEnd && *(int*) data < samplePosition)
  18603. {
  18604. data += 4;
  18605. data += 2 + *(uint16*) data;
  18606. }
  18607. }
  18608. bool MidiBuffer::Iterator::getNextEvent (const uint8* &midiData,
  18609. int& numBytes,
  18610. int& samplePosition) throw()
  18611. {
  18612. if (data >= buffer.elements + buffer.bytesUsed)
  18613. return false;
  18614. samplePosition = *(int*) data;
  18615. data += 4;
  18616. numBytes = *(uint16*) data;
  18617. data += 2;
  18618. midiData = data;
  18619. data += numBytes;
  18620. return true;
  18621. }
  18622. bool MidiBuffer::Iterator::getNextEvent (MidiMessage& result,
  18623. int& samplePosition) throw()
  18624. {
  18625. if (data >= buffer.elements + buffer.bytesUsed)
  18626. return false;
  18627. samplePosition = *(int*) data;
  18628. data += 4;
  18629. const int numBytes = *(uint16*) data;
  18630. data += 2;
  18631. result = MidiMessage (data, numBytes, samplePosition);
  18632. data += numBytes;
  18633. return true;
  18634. }
  18635. END_JUCE_NAMESPACE
  18636. /********* End of inlined file: juce_MidiBuffer.cpp *********/
  18637. /********* Start of inlined file: juce_MidiFile.cpp *********/
  18638. BEGIN_JUCE_NAMESPACE
  18639. struct TempoInfo
  18640. {
  18641. double bpm, timestamp;
  18642. };
  18643. struct TimeSigInfo
  18644. {
  18645. int numerator, denominator;
  18646. double timestamp;
  18647. };
  18648. MidiFile::MidiFile() throw()
  18649. : numTracks (0),
  18650. timeFormat ((short)(unsigned short)0xe728)
  18651. {
  18652. }
  18653. MidiFile::~MidiFile() throw()
  18654. {
  18655. clear();
  18656. }
  18657. void MidiFile::clear() throw()
  18658. {
  18659. while (numTracks > 0)
  18660. delete tracks [--numTracks];
  18661. }
  18662. int MidiFile::getNumTracks() const throw()
  18663. {
  18664. return numTracks;
  18665. }
  18666. const MidiMessageSequence* MidiFile::getTrack (const int index) const throw()
  18667. {
  18668. return (((unsigned int) index) < (unsigned int) numTracks) ? tracks[index] : 0;
  18669. }
  18670. void MidiFile::addTrack (const MidiMessageSequence& trackSequence) throw()
  18671. {
  18672. jassert (numTracks < numElementsInArray (tracks));
  18673. if (numTracks < numElementsInArray (tracks))
  18674. tracks [numTracks++] = new MidiMessageSequence (trackSequence);
  18675. }
  18676. short MidiFile::getTimeFormat() const throw()
  18677. {
  18678. return timeFormat;
  18679. }
  18680. void MidiFile::setTicksPerQuarterNote (const int ticks) throw()
  18681. {
  18682. timeFormat = (short)ticks;
  18683. }
  18684. void MidiFile::setSmpteTimeFormat (const int framesPerSecond,
  18685. const int subframeResolution) throw()
  18686. {
  18687. timeFormat = (short) (((-framesPerSecond) << 8) | subframeResolution);
  18688. }
  18689. void MidiFile::findAllTempoEvents (MidiMessageSequence& tempoChangeEvents) const
  18690. {
  18691. for (int i = numTracks; --i >= 0;)
  18692. {
  18693. const int numEvents = tracks[i]->getNumEvents();
  18694. for (int j = 0; j < numEvents; ++j)
  18695. {
  18696. const MidiMessage& m = tracks[i]->getEventPointer (j)->message;
  18697. if (m.isTempoMetaEvent())
  18698. tempoChangeEvents.addEvent (m);
  18699. }
  18700. }
  18701. }
  18702. void MidiFile::findAllTimeSigEvents (MidiMessageSequence& timeSigEvents) const
  18703. {
  18704. for (int i = numTracks; --i >= 0;)
  18705. {
  18706. const int numEvents = tracks[i]->getNumEvents();
  18707. for (int j = 0; j < numEvents; ++j)
  18708. {
  18709. const MidiMessage& m = tracks[i]->getEventPointer (j)->message;
  18710. if (m.isTimeSignatureMetaEvent())
  18711. timeSigEvents.addEvent (m);
  18712. }
  18713. }
  18714. }
  18715. double MidiFile::getLastTimestamp() const
  18716. {
  18717. double t = 0.0;
  18718. for (int i = numTracks; --i >= 0;)
  18719. t = jmax (t, tracks[i]->getEndTime());
  18720. return t;
  18721. }
  18722. static bool parseMidiHeader (const char* &data,
  18723. short& timeFormat,
  18724. short& fileType,
  18725. short& numberOfTracks)
  18726. {
  18727. unsigned int ch = (int) bigEndianInt (data);
  18728. data += 4;
  18729. if (ch != bigEndianInt ("MThd"))
  18730. {
  18731. bool ok = false;
  18732. if (ch == bigEndianInt ("RIFF"))
  18733. {
  18734. for (int i = 0; i < 8; ++i)
  18735. {
  18736. ch = bigEndianInt (data);
  18737. data += 4;
  18738. if (ch == bigEndianInt ("MThd"))
  18739. {
  18740. ok = true;
  18741. break;
  18742. }
  18743. }
  18744. }
  18745. if (! ok)
  18746. return false;
  18747. }
  18748. unsigned int bytesRemaining = bigEndianInt (data);
  18749. data += 4;
  18750. fileType = (short)bigEndianShort (data);
  18751. data += 2;
  18752. numberOfTracks = (short)bigEndianShort (data);
  18753. data += 2;
  18754. timeFormat = (short)bigEndianShort (data);
  18755. data += 2;
  18756. bytesRemaining -= 6;
  18757. data += bytesRemaining;
  18758. return true;
  18759. }
  18760. bool MidiFile::readFrom (InputStream& sourceStream)
  18761. {
  18762. clear();
  18763. MemoryBlock data;
  18764. const int maxSensibleMidiFileSize = 2 * 1024 * 1024;
  18765. // (put a sanity-check on the file size, as midi files are generally small)
  18766. if (sourceStream.readIntoMemoryBlock (data, maxSensibleMidiFileSize))
  18767. {
  18768. int size = data.getSize();
  18769. const char* d = (char*) data.getData();
  18770. short fileType, expectedTracks;
  18771. if (size > 16 && parseMidiHeader (d, timeFormat, fileType, expectedTracks))
  18772. {
  18773. size -= (int) (d - (char*) data.getData());
  18774. int track = 0;
  18775. while (size > 0 && track < expectedTracks)
  18776. {
  18777. const int chunkType = (int)bigEndianInt (d);
  18778. d += 4;
  18779. const int chunkSize = (int)bigEndianInt (d);
  18780. d += 4;
  18781. if (chunkSize <= 0)
  18782. break;
  18783. if (size < 0)
  18784. return false;
  18785. if (chunkType == (int)bigEndianInt ("MTrk"))
  18786. {
  18787. readNextTrack (d, chunkSize);
  18788. }
  18789. size -= chunkSize + 8;
  18790. d += chunkSize;
  18791. ++track;
  18792. }
  18793. return true;
  18794. }
  18795. }
  18796. return false;
  18797. }
  18798. // a comparator that puts all the note-offs before note-ons that have the same time
  18799. int MidiFile::compareElements (const MidiMessageSequence::MidiEventHolder* const first,
  18800. const MidiMessageSequence::MidiEventHolder* const second) throw()
  18801. {
  18802. const double diff = (first->message.getTimeStamp() - second->message.getTimeStamp());
  18803. if (diff == 0)
  18804. {
  18805. if (first->message.isNoteOff() && second->message.isNoteOn())
  18806. return -1;
  18807. else if (first->message.isNoteOn() && second->message.isNoteOff())
  18808. return 1;
  18809. else
  18810. return 0;
  18811. }
  18812. else
  18813. {
  18814. return (diff > 0) ? 1 : -1;
  18815. }
  18816. }
  18817. void MidiFile::readNextTrack (const char* data, int size)
  18818. {
  18819. double time = 0;
  18820. char lastStatusByte = 0;
  18821. MidiMessageSequence result;
  18822. while (size > 0)
  18823. {
  18824. int bytesUsed;
  18825. const int delay = MidiMessage::readVariableLengthVal ((const uint8*) data, bytesUsed);
  18826. data += bytesUsed;
  18827. size -= bytesUsed;
  18828. time += delay;
  18829. int messSize = 0;
  18830. const MidiMessage mm ((const uint8*) data, size, messSize, lastStatusByte, time);
  18831. if (messSize <= 0)
  18832. break;
  18833. size -= messSize;
  18834. data += messSize;
  18835. result.addEvent (mm);
  18836. const char firstByte = *(mm.getRawData());
  18837. if ((firstByte & 0xf0) != 0xf0)
  18838. lastStatusByte = firstByte;
  18839. }
  18840. // use a sort that puts all the note-offs before note-ons that have the same time
  18841. result.list.sort (*this, true);
  18842. result.updateMatchedPairs();
  18843. addTrack (result);
  18844. }
  18845. static double convertTicksToSeconds (const double time,
  18846. const MidiMessageSequence& tempoEvents,
  18847. const int timeFormat)
  18848. {
  18849. if (timeFormat > 0)
  18850. {
  18851. int numer = 4, denom = 4;
  18852. double tempoTime = 0.0, correctedTempoTime = 0.0;
  18853. const double tickLen = 1.0 / (timeFormat & 0x7fff);
  18854. double secsPerTick = 0.5 * tickLen;
  18855. const int numEvents = tempoEvents.getNumEvents();
  18856. for (int i = 0; i < numEvents; ++i)
  18857. {
  18858. const MidiMessage& m = tempoEvents.getEventPointer(i)->message;
  18859. if (time <= m.getTimeStamp())
  18860. break;
  18861. if (timeFormat > 0)
  18862. {
  18863. correctedTempoTime = correctedTempoTime
  18864. + (m.getTimeStamp() - tempoTime) * secsPerTick;
  18865. }
  18866. else
  18867. {
  18868. correctedTempoTime = tickLen * m.getTimeStamp() / (((timeFormat & 0x7fff) >> 8) * (timeFormat & 0xff));
  18869. }
  18870. tempoTime = m.getTimeStamp();
  18871. if (m.isTempoMetaEvent())
  18872. secsPerTick = tickLen * m.getTempoSecondsPerQuarterNote();
  18873. else if (m.isTimeSignatureMetaEvent())
  18874. m.getTimeSignatureInfo (numer, denom);
  18875. while (i + 1 < numEvents)
  18876. {
  18877. const MidiMessage& m2 = tempoEvents.getEventPointer(i + 1)->message;
  18878. if (m2.getTimeStamp() == tempoTime)
  18879. {
  18880. ++i;
  18881. if (m2.isTempoMetaEvent())
  18882. secsPerTick = tickLen * m2.getTempoSecondsPerQuarterNote();
  18883. else if (m2.isTimeSignatureMetaEvent())
  18884. m2.getTimeSignatureInfo (numer, denom);
  18885. }
  18886. else
  18887. {
  18888. break;
  18889. }
  18890. }
  18891. }
  18892. return correctedTempoTime + (time - tempoTime) * secsPerTick;
  18893. }
  18894. else
  18895. {
  18896. return time / (((timeFormat & 0x7fff) >> 8) * (timeFormat & 0xff));
  18897. }
  18898. }
  18899. void MidiFile::convertTimestampTicksToSeconds()
  18900. {
  18901. MidiMessageSequence tempoEvents;
  18902. findAllTempoEvents (tempoEvents);
  18903. findAllTimeSigEvents (tempoEvents);
  18904. for (int i = 0; i < numTracks; ++i)
  18905. {
  18906. MidiMessageSequence& ms = *tracks[i];
  18907. for (int j = ms.getNumEvents(); --j >= 0;)
  18908. {
  18909. MidiMessage& m = ms.getEventPointer(j)->message;
  18910. m.setTimeStamp (convertTicksToSeconds (m.getTimeStamp(),
  18911. tempoEvents,
  18912. timeFormat));
  18913. }
  18914. }
  18915. }
  18916. static void writeVariableLengthInt (OutputStream& out, unsigned int v)
  18917. {
  18918. unsigned int buffer = v & 0x7F;
  18919. while ((v >>= 7) != 0)
  18920. {
  18921. buffer <<= 8;
  18922. buffer |= ((v & 0x7F) | 0x80);
  18923. }
  18924. for (;;)
  18925. {
  18926. out.writeByte ((char) buffer);
  18927. if (buffer & 0x80)
  18928. buffer >>= 8;
  18929. else
  18930. break;
  18931. }
  18932. }
  18933. bool MidiFile::writeTo (OutputStream& out)
  18934. {
  18935. out.writeIntBigEndian ((int) bigEndianInt ("MThd"));
  18936. out.writeIntBigEndian (6);
  18937. out.writeShortBigEndian (1); // type
  18938. out.writeShortBigEndian (numTracks);
  18939. out.writeShortBigEndian (timeFormat);
  18940. for (int i = 0; i < numTracks; ++i)
  18941. writeTrack (out, i);
  18942. out.flush();
  18943. return true;
  18944. }
  18945. void MidiFile::writeTrack (OutputStream& mainOut,
  18946. const int trackNum)
  18947. {
  18948. MemoryOutputStream out;
  18949. const MidiMessageSequence& ms = *tracks[trackNum];
  18950. int lastTick = 0;
  18951. char lastStatusByte = 0;
  18952. for (int i = 0; i < ms.getNumEvents(); ++i)
  18953. {
  18954. const MidiMessage& mm = ms.getEventPointer(i)->message;
  18955. const int tick = roundDoubleToInt (mm.getTimeStamp());
  18956. const int delta = jmax (0, tick - lastTick);
  18957. writeVariableLengthInt (out, delta);
  18958. lastTick = tick;
  18959. const char statusByte = *(mm.getRawData());
  18960. if ((statusByte == lastStatusByte)
  18961. && ((statusByte & 0xf0) != 0xf0)
  18962. && i > 0
  18963. && mm.getRawDataSize() > 1)
  18964. {
  18965. out.write (mm.getRawData() + 1, mm.getRawDataSize() - 1);
  18966. }
  18967. else
  18968. {
  18969. out.write (mm.getRawData(), mm.getRawDataSize());
  18970. }
  18971. lastStatusByte = statusByte;
  18972. }
  18973. out.writeByte (0);
  18974. const MidiMessage m (MidiMessage::endOfTrack());
  18975. out.write (m.getRawData(),
  18976. m.getRawDataSize());
  18977. mainOut.writeIntBigEndian ((int)bigEndianInt ("MTrk"));
  18978. mainOut.writeIntBigEndian (out.getDataSize());
  18979. mainOut.write (out.getData(), out.getDataSize());
  18980. }
  18981. END_JUCE_NAMESPACE
  18982. /********* End of inlined file: juce_MidiFile.cpp *********/
  18983. /********* Start of inlined file: juce_MidiKeyboardState.cpp *********/
  18984. BEGIN_JUCE_NAMESPACE
  18985. MidiKeyboardState::MidiKeyboardState()
  18986. : listeners (2)
  18987. {
  18988. zeromem (noteStates, sizeof (noteStates));
  18989. }
  18990. MidiKeyboardState::~MidiKeyboardState()
  18991. {
  18992. }
  18993. void MidiKeyboardState::reset()
  18994. {
  18995. const ScopedLock sl (lock);
  18996. zeromem (noteStates, sizeof (noteStates));
  18997. eventsToAdd.clear();
  18998. }
  18999. bool MidiKeyboardState::isNoteOn (const int midiChannel, const int n) const throw()
  19000. {
  19001. jassert (midiChannel >= 0 && midiChannel <= 16);
  19002. return ((unsigned int) n) < 128
  19003. && (noteStates[n] & (1 << (midiChannel - 1))) != 0;
  19004. }
  19005. bool MidiKeyboardState::isNoteOnForChannels (const int midiChannelMask, const int n) const throw()
  19006. {
  19007. return ((unsigned int) n) < 128
  19008. && (noteStates[n] & midiChannelMask) != 0;
  19009. }
  19010. void MidiKeyboardState::noteOn (const int midiChannel, const int midiNoteNumber, const float velocity)
  19011. {
  19012. jassert (midiChannel >= 0 && midiChannel <= 16);
  19013. jassert (((unsigned int) midiNoteNumber) < 128);
  19014. const ScopedLock sl (lock);
  19015. if (((unsigned int) midiNoteNumber) < 128)
  19016. {
  19017. const int timeNow = (int) Time::getMillisecondCounter();
  19018. eventsToAdd.addEvent (MidiMessage::noteOn (midiChannel, midiNoteNumber, velocity), timeNow);
  19019. eventsToAdd.clear (0, timeNow - 500);
  19020. noteOnInternal (midiChannel, midiNoteNumber, velocity);
  19021. }
  19022. }
  19023. void MidiKeyboardState::noteOnInternal (const int midiChannel, const int midiNoteNumber, const float velocity)
  19024. {
  19025. if (((unsigned int) midiNoteNumber) < 128)
  19026. {
  19027. noteStates [midiNoteNumber] |= (1 << (midiChannel - 1));
  19028. for (int i = listeners.size(); --i >= 0;)
  19029. ((MidiKeyboardStateListener*) listeners.getUnchecked(i))
  19030. ->handleNoteOn (this, midiChannel, midiNoteNumber, velocity);
  19031. }
  19032. }
  19033. void MidiKeyboardState::noteOff (const int midiChannel, const int midiNoteNumber)
  19034. {
  19035. const ScopedLock sl (lock);
  19036. if (isNoteOn (midiChannel, midiNoteNumber))
  19037. {
  19038. const int timeNow = (int) Time::getMillisecondCounter();
  19039. eventsToAdd.addEvent (MidiMessage::noteOff (midiChannel, midiNoteNumber), timeNow);
  19040. eventsToAdd.clear (0, timeNow - 500);
  19041. noteOffInternal (midiChannel, midiNoteNumber);
  19042. }
  19043. }
  19044. void MidiKeyboardState::noteOffInternal (const int midiChannel, const int midiNoteNumber)
  19045. {
  19046. if (isNoteOn (midiChannel, midiNoteNumber))
  19047. {
  19048. noteStates [midiNoteNumber] &= ~(1 << (midiChannel - 1));
  19049. for (int i = listeners.size(); --i >= 0;)
  19050. ((MidiKeyboardStateListener*) listeners.getUnchecked(i))
  19051. ->handleNoteOff (this, midiChannel, midiNoteNumber);
  19052. }
  19053. }
  19054. void MidiKeyboardState::allNotesOff (const int midiChannel)
  19055. {
  19056. const ScopedLock sl (lock);
  19057. if (midiChannel <= 0)
  19058. {
  19059. for (int i = 1; i <= 16; ++i)
  19060. allNotesOff (i);
  19061. }
  19062. else
  19063. {
  19064. for (int i = 0; i < 128; ++i)
  19065. noteOff (midiChannel, i);
  19066. }
  19067. }
  19068. void MidiKeyboardState::processNextMidiEvent (const MidiMessage& message)
  19069. {
  19070. if (message.isNoteOn())
  19071. {
  19072. noteOnInternal (message.getChannel(), message.getNoteNumber(), message.getFloatVelocity());
  19073. }
  19074. else if (message.isNoteOff())
  19075. {
  19076. noteOffInternal (message.getChannel(), message.getNoteNumber());
  19077. }
  19078. else if (message.isAllNotesOff())
  19079. {
  19080. for (int i = 0; i < 128; ++i)
  19081. noteOffInternal (message.getChannel(), i);
  19082. }
  19083. }
  19084. void MidiKeyboardState::processNextMidiBuffer (MidiBuffer& buffer,
  19085. const int startSample,
  19086. const int numSamples,
  19087. const bool injectIndirectEvents)
  19088. {
  19089. MidiBuffer::Iterator i (buffer);
  19090. MidiMessage message (0xf4, 0.0);
  19091. int time;
  19092. const ScopedLock sl (lock);
  19093. while (i.getNextEvent (message, time))
  19094. processNextMidiEvent (message);
  19095. if (injectIndirectEvents)
  19096. {
  19097. MidiBuffer::Iterator i2 (eventsToAdd);
  19098. const int firstEventToAdd = eventsToAdd.getFirstEventTime();
  19099. const double scaleFactor = numSamples / (double) (eventsToAdd.getLastEventTime() + 1 - firstEventToAdd);
  19100. while (i2.getNextEvent (message, time))
  19101. {
  19102. const int pos = jlimit (0, numSamples - 1, roundDoubleToInt ((time - firstEventToAdd) * scaleFactor));
  19103. buffer.addEvent (message, startSample + pos);
  19104. }
  19105. }
  19106. eventsToAdd.clear();
  19107. }
  19108. void MidiKeyboardState::addListener (MidiKeyboardStateListener* const listener) throw()
  19109. {
  19110. const ScopedLock sl (lock);
  19111. listeners.addIfNotAlreadyThere (listener);
  19112. }
  19113. void MidiKeyboardState::removeListener (MidiKeyboardStateListener* const listener) throw()
  19114. {
  19115. const ScopedLock sl (lock);
  19116. listeners.removeValue (listener);
  19117. }
  19118. END_JUCE_NAMESPACE
  19119. /********* End of inlined file: juce_MidiKeyboardState.cpp *********/
  19120. /********* Start of inlined file: juce_MidiMessage.cpp *********/
  19121. BEGIN_JUCE_NAMESPACE
  19122. int MidiMessage::readVariableLengthVal (const uint8* data,
  19123. int& numBytesUsed) throw()
  19124. {
  19125. numBytesUsed = 0;
  19126. int v = 0;
  19127. int i;
  19128. do
  19129. {
  19130. i = (int) *data++;
  19131. if (++numBytesUsed > 6)
  19132. break;
  19133. v = (v << 7) + (i & 0x7f);
  19134. } while (i & 0x80);
  19135. return v;
  19136. }
  19137. int MidiMessage::getMessageLengthFromFirstByte (const uint8 firstByte) throw()
  19138. {
  19139. // this method only works for valid starting bytes of a short midi message
  19140. jassert (firstByte >= 0x80
  19141. && firstByte != 0xff
  19142. && firstByte != 0xf0
  19143. && firstByte != 0xf7);
  19144. static const char messageLengths[] =
  19145. {
  19146. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  19147. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  19148. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  19149. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  19150. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  19151. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  19152. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  19153. 1, 2, 3, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1
  19154. };
  19155. return messageLengths [firstByte & 0x7f];
  19156. }
  19157. MidiMessage::MidiMessage (const uint8* const d,
  19158. const int dataSize,
  19159. const double t) throw()
  19160. : timeStamp (t),
  19161. message (0),
  19162. size (dataSize)
  19163. {
  19164. jassert (dataSize > 0);
  19165. if (dataSize <= 4)
  19166. data = (uint8*) &message;
  19167. else
  19168. data = (uint8*) juce_malloc (dataSize);
  19169. memcpy (data, d, dataSize);
  19170. // check that the length matches the data..
  19171. jassert (size > 3 || *d >= 0xf0 || getMessageLengthFromFirstByte (*d) == size);
  19172. }
  19173. MidiMessage::MidiMessage (const int byte1,
  19174. const double t) throw()
  19175. : timeStamp (t),
  19176. data ((uint8*) &message),
  19177. size (1)
  19178. {
  19179. data[0] = (uint8) byte1;
  19180. // check that the length matches the data..
  19181. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 1);
  19182. }
  19183. MidiMessage::MidiMessage (const int byte1,
  19184. const int byte2,
  19185. const double t) throw()
  19186. : timeStamp (t),
  19187. data ((uint8*) &message),
  19188. size (2)
  19189. {
  19190. data[0] = (uint8) byte1;
  19191. data[1] = (uint8) byte2;
  19192. // check that the length matches the data..
  19193. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 2);
  19194. }
  19195. MidiMessage::MidiMessage (const int byte1,
  19196. const int byte2,
  19197. const int byte3,
  19198. const double t) throw()
  19199. : timeStamp (t),
  19200. data ((uint8*) &message),
  19201. size (3)
  19202. {
  19203. data[0] = (uint8) byte1;
  19204. data[1] = (uint8) byte2;
  19205. data[2] = (uint8) byte3;
  19206. // check that the length matches the data..
  19207. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 3);
  19208. }
  19209. MidiMessage::MidiMessage (const MidiMessage& other) throw()
  19210. : timeStamp (other.timeStamp),
  19211. message (other.message),
  19212. size (other.size)
  19213. {
  19214. if (other.data != (uint8*) &other.message)
  19215. {
  19216. data = (uint8*) juce_malloc (size);
  19217. memcpy (data, other.data, size);
  19218. }
  19219. else
  19220. {
  19221. data = (uint8*) &message;
  19222. }
  19223. }
  19224. MidiMessage::MidiMessage (const MidiMessage& other,
  19225. const double newTimeStamp) throw()
  19226. : timeStamp (newTimeStamp),
  19227. message (other.message),
  19228. size (other.size)
  19229. {
  19230. if (other.data != (uint8*) &other.message)
  19231. {
  19232. data = (uint8*) juce_malloc (size);
  19233. memcpy (data, other.data, size);
  19234. }
  19235. else
  19236. {
  19237. data = (uint8*) &message;
  19238. }
  19239. }
  19240. MidiMessage::MidiMessage (const uint8* src,
  19241. int sz,
  19242. int& numBytesUsed,
  19243. const uint8 lastStatusByte,
  19244. double t) throw()
  19245. : timeStamp (t),
  19246. data ((uint8*) &message),
  19247. message (0)
  19248. {
  19249. unsigned int byte = (unsigned int) *src;
  19250. if (byte < 0x80)
  19251. {
  19252. byte = (unsigned int) (uint8) lastStatusByte;
  19253. numBytesUsed = -1;
  19254. }
  19255. else
  19256. {
  19257. numBytesUsed = 0;
  19258. --sz;
  19259. ++src;
  19260. }
  19261. if (byte >= 0x80)
  19262. {
  19263. if (byte == 0xf0)
  19264. {
  19265. const uint8* d = (const uint8*) src;
  19266. while (d < src + sz)
  19267. {
  19268. if (*d >= 0x80) // stop if we hit a status byte, and don't include it in this message
  19269. {
  19270. if (*d == 0xf7) // include an 0xf7 if we hit one
  19271. ++d;
  19272. break;
  19273. }
  19274. ++d;
  19275. }
  19276. size = 1 + (int) (d - src);
  19277. data = (uint8*) juce_malloc (size);
  19278. *data = (uint8) byte;
  19279. memcpy (data + 1, src, size - 1);
  19280. }
  19281. else if (byte == 0xff)
  19282. {
  19283. int n;
  19284. const int bytesLeft = readVariableLengthVal (src + 1, n);
  19285. size = jmin (sz + 1, n + 2 + bytesLeft);
  19286. data = (uint8*) juce_malloc (size);
  19287. *data = (uint8) byte;
  19288. memcpy (data + 1, src, size - 1);
  19289. }
  19290. else
  19291. {
  19292. size = getMessageLengthFromFirstByte ((uint8) byte);
  19293. *data = (uint8) byte;
  19294. if (size > 1)
  19295. {
  19296. data[1] = src[0];
  19297. if (size > 2)
  19298. data[2] = src[1];
  19299. }
  19300. }
  19301. numBytesUsed += size;
  19302. }
  19303. else
  19304. {
  19305. message = 0;
  19306. size = 0;
  19307. }
  19308. }
  19309. const MidiMessage& MidiMessage::operator= (const MidiMessage& other) throw()
  19310. {
  19311. if (this == &other)
  19312. return *this;
  19313. timeStamp = other.timeStamp;
  19314. size = other.size;
  19315. message = other.message;
  19316. if (data != (uint8*) &message)
  19317. juce_free (data);
  19318. if (other.data != (uint8*) &other.message)
  19319. {
  19320. data = (uint8*) juce_malloc (size);
  19321. memcpy (data, other.data, size);
  19322. }
  19323. else
  19324. {
  19325. data = (uint8*) &message;
  19326. }
  19327. return *this;
  19328. }
  19329. MidiMessage::~MidiMessage() throw()
  19330. {
  19331. if (data != (uint8*) &message)
  19332. juce_free (data);
  19333. }
  19334. int MidiMessage::getChannel() const throw()
  19335. {
  19336. if ((data[0] & 0xf0) != 0xf0)
  19337. return (data[0] & 0xf) + 1;
  19338. else
  19339. return 0;
  19340. }
  19341. bool MidiMessage::isForChannel (const int channel) const throw()
  19342. {
  19343. return ((data[0] & 0xf) == channel - 1)
  19344. && ((data[0] & 0xf0) != 0xf0);
  19345. }
  19346. void MidiMessage::setChannel (const int channel) throw()
  19347. {
  19348. if ((data[0] & 0xf0) != (uint8) 0xf0)
  19349. data[0] = (uint8) ((data[0] & (uint8)0xf0)
  19350. | (uint8)(channel - 1));
  19351. }
  19352. bool MidiMessage::isNoteOn() const throw()
  19353. {
  19354. return ((data[0] & 0xf0) == 0x90)
  19355. && (data[2] != 0);
  19356. }
  19357. bool MidiMessage::isNoteOff() const throw()
  19358. {
  19359. return ((data[0] & 0xf0) == 0x80)
  19360. || ((data[2] == 0) && ((data[0] & 0xf0) == 0x90));
  19361. }
  19362. bool MidiMessage::isNoteOnOrOff() const throw()
  19363. {
  19364. const int d = data[0] & 0xf0;
  19365. return (d == 0x90) || (d == 0x80);
  19366. }
  19367. int MidiMessage::getNoteNumber() const throw()
  19368. {
  19369. return data[1];
  19370. }
  19371. void MidiMessage::setNoteNumber (const int newNoteNumber) throw()
  19372. {
  19373. if (isNoteOnOrOff())
  19374. data[1] = (uint8) jlimit (0, 127, newNoteNumber);
  19375. }
  19376. uint8 MidiMessage::getVelocity() const throw()
  19377. {
  19378. if (isNoteOnOrOff())
  19379. return data[2];
  19380. else
  19381. return 0;
  19382. }
  19383. float MidiMessage::getFloatVelocity() const throw()
  19384. {
  19385. return getVelocity() * (1.0f / 127.0f);
  19386. }
  19387. void MidiMessage::setVelocity (const float newVelocity) throw()
  19388. {
  19389. if (isNoteOnOrOff())
  19390. data[2] = (uint8) jlimit (0, 0x7f, roundFloatToInt (newVelocity * 127.0f));
  19391. }
  19392. void MidiMessage::multiplyVelocity (const float scaleFactor) throw()
  19393. {
  19394. if (isNoteOnOrOff())
  19395. data[2] = (uint8) jlimit (0, 0x7f, roundFloatToInt (scaleFactor * data[2]));
  19396. }
  19397. bool MidiMessage::isAftertouch() const throw()
  19398. {
  19399. return (data[0] & 0xf0) == 0xa0;
  19400. }
  19401. int MidiMessage::getAfterTouchValue() const throw()
  19402. {
  19403. return data[2];
  19404. }
  19405. const MidiMessage MidiMessage::aftertouchChange (const int channel,
  19406. const int noteNum,
  19407. const int aftertouchValue) throw()
  19408. {
  19409. jassert (channel > 0 && channel <= 16);
  19410. jassert (((unsigned int) noteNum) <= 127);
  19411. jassert (((unsigned int) aftertouchValue) <= 127);
  19412. return MidiMessage (0xa0 | jlimit (0, 15, channel - 1),
  19413. noteNum & 0x7f,
  19414. aftertouchValue & 0x7f);
  19415. }
  19416. bool MidiMessage::isChannelPressure() const throw()
  19417. {
  19418. return (data[0] & 0xf0) == 0xd0;
  19419. }
  19420. int MidiMessage::getChannelPressureValue() const throw()
  19421. {
  19422. jassert (isChannelPressure());
  19423. return data[1];
  19424. }
  19425. const MidiMessage MidiMessage::channelPressureChange (const int channel,
  19426. const int pressure) throw()
  19427. {
  19428. jassert (channel > 0 && channel <= 16);
  19429. jassert (((unsigned int) pressure) <= 127);
  19430. return MidiMessage (0xd0 | jlimit (0, 15, channel - 1),
  19431. pressure & 0x7f);
  19432. }
  19433. bool MidiMessage::isProgramChange() const throw()
  19434. {
  19435. return (data[0] & 0xf0) == 0xc0;
  19436. }
  19437. int MidiMessage::getProgramChangeNumber() const throw()
  19438. {
  19439. return data[1];
  19440. }
  19441. const MidiMessage MidiMessage::programChange (const int channel,
  19442. const int programNumber) throw()
  19443. {
  19444. jassert (channel > 0 && channel <= 16);
  19445. return MidiMessage (0xc0 | jlimit (0, 15, channel - 1),
  19446. programNumber & 0x7f);
  19447. }
  19448. bool MidiMessage::isPitchWheel() const throw()
  19449. {
  19450. return (data[0] & 0xf0) == 0xe0;
  19451. }
  19452. int MidiMessage::getPitchWheelValue() const throw()
  19453. {
  19454. return data[1] | (data[2] << 7);
  19455. }
  19456. const MidiMessage MidiMessage::pitchWheel (const int channel,
  19457. const int position) throw()
  19458. {
  19459. jassert (channel > 0 && channel <= 16);
  19460. jassert (((unsigned int) position) <= 0x3fff);
  19461. return MidiMessage (0xe0 | jlimit (0, 15, channel - 1),
  19462. position & 127,
  19463. (position >> 7) & 127);
  19464. }
  19465. bool MidiMessage::isController() const throw()
  19466. {
  19467. return (data[0] & 0xf0) == 0xb0;
  19468. }
  19469. int MidiMessage::getControllerNumber() const throw()
  19470. {
  19471. jassert (isController());
  19472. return data[1];
  19473. }
  19474. int MidiMessage::getControllerValue() const throw()
  19475. {
  19476. jassert (isController());
  19477. return data[2];
  19478. }
  19479. const MidiMessage MidiMessage::controllerEvent (const int channel,
  19480. const int controllerType,
  19481. const int value) throw()
  19482. {
  19483. // the channel must be between 1 and 16 inclusive
  19484. jassert (channel > 0 && channel <= 16);
  19485. return MidiMessage (0xb0 | jlimit (0, 15, channel - 1),
  19486. controllerType & 127,
  19487. value & 127);
  19488. }
  19489. const MidiMessage MidiMessage::noteOn (const int channel,
  19490. const int noteNumber,
  19491. const float velocity) throw()
  19492. {
  19493. return noteOn (channel, noteNumber, (uint8)(velocity * 127.0f));
  19494. }
  19495. const MidiMessage MidiMessage::noteOn (const int channel,
  19496. const int noteNumber,
  19497. const uint8 velocity) throw()
  19498. {
  19499. jassert (channel > 0 && channel <= 16);
  19500. jassert (((unsigned int) noteNumber) <= 127);
  19501. return MidiMessage (0x90 | jlimit (0, 15, channel - 1),
  19502. noteNumber & 127,
  19503. jlimit (0, 127, roundFloatToInt (velocity)));
  19504. }
  19505. const MidiMessage MidiMessage::noteOff (const int channel,
  19506. const int noteNumber) throw()
  19507. {
  19508. jassert (channel > 0 && channel <= 16);
  19509. jassert (((unsigned int) noteNumber) <= 127);
  19510. return MidiMessage (0x80 | jlimit (0, 15, channel - 1), noteNumber & 127, 0);
  19511. }
  19512. const MidiMessage MidiMessage::allNotesOff (const int channel) throw()
  19513. {
  19514. jassert (channel > 0 && channel <= 16);
  19515. return controllerEvent (channel, 123, 0);
  19516. }
  19517. bool MidiMessage::isAllNotesOff() const throw()
  19518. {
  19519. return (data[0] & 0xf0) == 0xb0
  19520. && data[1] == 123;
  19521. }
  19522. const MidiMessage MidiMessage::allSoundOff (const int channel) throw()
  19523. {
  19524. return controllerEvent (channel, 120, 0);
  19525. }
  19526. bool MidiMessage::isAllSoundOff() const throw()
  19527. {
  19528. return (data[0] & 0xf0) == 0xb0
  19529. && data[1] == 120;
  19530. }
  19531. const MidiMessage MidiMessage::allControllersOff (const int channel) throw()
  19532. {
  19533. return controllerEvent (channel, 121, 0);
  19534. }
  19535. const MidiMessage MidiMessage::masterVolume (const float volume) throw()
  19536. {
  19537. const int vol = jlimit (0, 0x3fff, roundFloatToInt (volume * 0x4000));
  19538. uint8 buf[8];
  19539. buf[0] = 0xf0;
  19540. buf[1] = 0x7f;
  19541. buf[2] = 0x7f;
  19542. buf[3] = 0x04;
  19543. buf[4] = 0x01;
  19544. buf[5] = (uint8) (vol & 0x7f);
  19545. buf[6] = (uint8) (vol >> 7);
  19546. buf[7] = 0xf7;
  19547. return MidiMessage (buf, 8);
  19548. }
  19549. bool MidiMessage::isSysEx() const throw()
  19550. {
  19551. return *data == 0xf0;
  19552. }
  19553. const MidiMessage MidiMessage::createSysExMessage (const uint8* sysexData,
  19554. const int dataSize) throw()
  19555. {
  19556. MemoryBlock mm (dataSize + 2);
  19557. uint8* const m = (uint8*) mm.getData();
  19558. m[0] = 0xf0;
  19559. memcpy (m + 1, sysexData, dataSize);
  19560. m[dataSize + 1] = 0xf7;
  19561. return MidiMessage (m, dataSize + 2);
  19562. }
  19563. const uint8* MidiMessage::getSysExData() const throw()
  19564. {
  19565. return (isSysEx()) ? getRawData() + 1
  19566. : 0;
  19567. }
  19568. int MidiMessage::getSysExDataSize() const throw()
  19569. {
  19570. return (isSysEx()) ? size - 2
  19571. : 0;
  19572. }
  19573. bool MidiMessage::isMetaEvent() const throw()
  19574. {
  19575. return *data == 0xff;
  19576. }
  19577. bool MidiMessage::isActiveSense() const throw()
  19578. {
  19579. return *data == 0xfe;
  19580. }
  19581. int MidiMessage::getMetaEventType() const throw()
  19582. {
  19583. if (*data != 0xff)
  19584. return -1;
  19585. else
  19586. return data[1];
  19587. }
  19588. int MidiMessage::getMetaEventLength() const throw()
  19589. {
  19590. if (*data == 0xff)
  19591. {
  19592. int n;
  19593. return jmin (size - 2, readVariableLengthVal (data + 2, n));
  19594. }
  19595. return 0;
  19596. }
  19597. const uint8* MidiMessage::getMetaEventData() const throw()
  19598. {
  19599. int n;
  19600. const uint8* d = data + 2;
  19601. readVariableLengthVal (d, n);
  19602. return d + n;
  19603. }
  19604. bool MidiMessage::isTrackMetaEvent() const throw()
  19605. {
  19606. return getMetaEventType() == 0;
  19607. }
  19608. bool MidiMessage::isEndOfTrackMetaEvent() const throw()
  19609. {
  19610. return getMetaEventType() == 47;
  19611. }
  19612. bool MidiMessage::isTextMetaEvent() const throw()
  19613. {
  19614. const int t = getMetaEventType();
  19615. return t > 0 && t < 16;
  19616. }
  19617. const String MidiMessage::getTextFromTextMetaEvent() const throw()
  19618. {
  19619. return String ((const char*) getMetaEventData(),
  19620. getMetaEventLength());
  19621. }
  19622. bool MidiMessage::isTrackNameEvent() const throw()
  19623. {
  19624. return (data[1] == 3)
  19625. && (*data == 0xff);
  19626. }
  19627. bool MidiMessage::isTempoMetaEvent() const throw()
  19628. {
  19629. return (data[1] == 81)
  19630. && (*data == 0xff);
  19631. }
  19632. bool MidiMessage::isMidiChannelMetaEvent() const throw()
  19633. {
  19634. return (data[1] == 0x20)
  19635. && (*data == 0xff)
  19636. && (data[2] == 1);
  19637. }
  19638. int MidiMessage::getMidiChannelMetaEventChannel() const throw()
  19639. {
  19640. return data[3] + 1;
  19641. }
  19642. double MidiMessage::getTempoSecondsPerQuarterNote() const throw()
  19643. {
  19644. if (! isTempoMetaEvent())
  19645. return 0.0;
  19646. const uint8* const d = getMetaEventData();
  19647. return (((unsigned int) d[0] << 16)
  19648. | ((unsigned int) d[1] << 8)
  19649. | d[2])
  19650. / 1000000.0;
  19651. }
  19652. double MidiMessage::getTempoMetaEventTickLength (const short timeFormat) const throw()
  19653. {
  19654. if (timeFormat > 0)
  19655. {
  19656. if (! isTempoMetaEvent())
  19657. return 0.5 / timeFormat;
  19658. return getTempoSecondsPerQuarterNote() / timeFormat;
  19659. }
  19660. else
  19661. {
  19662. const int frameCode = (-timeFormat) >> 8;
  19663. double framesPerSecond;
  19664. switch (frameCode)
  19665. {
  19666. case 24: framesPerSecond = 24.0; break;
  19667. case 25: framesPerSecond = 25.0; break;
  19668. case 29: framesPerSecond = 29.97; break;
  19669. case 30: framesPerSecond = 30.0; break;
  19670. default: framesPerSecond = 30.0; break;
  19671. }
  19672. return (1.0 / framesPerSecond) / (timeFormat & 0xff);
  19673. }
  19674. }
  19675. const MidiMessage MidiMessage::tempoMetaEvent (int microsecondsPerQuarterNote) throw()
  19676. {
  19677. uint8 d[8];
  19678. d[0] = 0xff;
  19679. d[1] = 81;
  19680. d[2] = 3;
  19681. d[3] = (uint8) (microsecondsPerQuarterNote >> 16);
  19682. d[4] = (uint8) ((microsecondsPerQuarterNote >> 8) & 0xff);
  19683. d[5] = (uint8) (microsecondsPerQuarterNote & 0xff);
  19684. return MidiMessage (d, 6, 0.0);
  19685. }
  19686. bool MidiMessage::isTimeSignatureMetaEvent() const throw()
  19687. {
  19688. return (data[1] == 0x58)
  19689. && (*data == (uint8) 0xff);
  19690. }
  19691. void MidiMessage::getTimeSignatureInfo (int& numerator,
  19692. int& denominator) const throw()
  19693. {
  19694. if (isTimeSignatureMetaEvent())
  19695. {
  19696. const uint8* const d = getMetaEventData();
  19697. numerator = d[0];
  19698. denominator = 1 << d[1];
  19699. }
  19700. else
  19701. {
  19702. numerator = 4;
  19703. denominator = 4;
  19704. }
  19705. }
  19706. const MidiMessage MidiMessage::timeSignatureMetaEvent (const int numerator,
  19707. const int denominator) throw()
  19708. {
  19709. uint8 d[8];
  19710. d[0] = 0xff;
  19711. d[1] = 0x58;
  19712. d[2] = 0x04;
  19713. d[3] = (uint8) numerator;
  19714. int n = 1;
  19715. int powerOfTwo = 0;
  19716. while (n < denominator)
  19717. {
  19718. n <<= 1;
  19719. ++powerOfTwo;
  19720. }
  19721. d[4] = (uint8) powerOfTwo;
  19722. d[5] = 0x01;
  19723. d[6] = 96;
  19724. return MidiMessage (d, 7, 0.0);
  19725. }
  19726. const MidiMessage MidiMessage::midiChannelMetaEvent (const int channel) throw()
  19727. {
  19728. uint8 d[8];
  19729. d[0] = 0xff;
  19730. d[1] = 0x20;
  19731. d[2] = 0x01;
  19732. d[3] = (uint8) jlimit (0, 0xff, channel - 1);
  19733. return MidiMessage (d, 4, 0.0);
  19734. }
  19735. bool MidiMessage::isKeySignatureMetaEvent() const throw()
  19736. {
  19737. return getMetaEventType() == 89;
  19738. }
  19739. int MidiMessage::getKeySignatureNumberOfSharpsOrFlats() const throw()
  19740. {
  19741. return (int) *getMetaEventData();
  19742. }
  19743. const MidiMessage MidiMessage::endOfTrack() throw()
  19744. {
  19745. return MidiMessage (0xff, 0x2f, 0, 0.0);
  19746. }
  19747. bool MidiMessage::isSongPositionPointer() const throw()
  19748. {
  19749. return *data == 0xf2;
  19750. }
  19751. int MidiMessage::getSongPositionPointerMidiBeat() const throw()
  19752. {
  19753. return data[1] | (data[2] << 7);
  19754. }
  19755. const MidiMessage MidiMessage::songPositionPointer (const int positionInMidiBeats) throw()
  19756. {
  19757. return MidiMessage (0xf2,
  19758. positionInMidiBeats & 127,
  19759. (positionInMidiBeats >> 7) & 127);
  19760. }
  19761. bool MidiMessage::isMidiStart() const throw()
  19762. {
  19763. return *data == 0xfa;
  19764. }
  19765. const MidiMessage MidiMessage::midiStart() throw()
  19766. {
  19767. return MidiMessage (0xfa);
  19768. }
  19769. bool MidiMessage::isMidiContinue() const throw()
  19770. {
  19771. return *data == 0xfb;
  19772. }
  19773. const MidiMessage MidiMessage::midiContinue() throw()
  19774. {
  19775. return MidiMessage (0xfb);
  19776. }
  19777. bool MidiMessage::isMidiStop() const throw()
  19778. {
  19779. return *data == 0xfc;
  19780. }
  19781. const MidiMessage MidiMessage::midiStop() throw()
  19782. {
  19783. return MidiMessage (0xfc);
  19784. }
  19785. bool MidiMessage::isMidiClock() const throw()
  19786. {
  19787. return *data == 0xf8;
  19788. }
  19789. const MidiMessage MidiMessage::midiClock() throw()
  19790. {
  19791. return MidiMessage (0xf8);
  19792. }
  19793. bool MidiMessage::isQuarterFrame() const throw()
  19794. {
  19795. return *data == 0xf1;
  19796. }
  19797. int MidiMessage::getQuarterFrameSequenceNumber() const throw()
  19798. {
  19799. return ((int) data[1]) >> 4;
  19800. }
  19801. int MidiMessage::getQuarterFrameValue() const throw()
  19802. {
  19803. return ((int) data[1]) & 0x0f;
  19804. }
  19805. const MidiMessage MidiMessage::quarterFrame (const int sequenceNumber,
  19806. const int value) throw()
  19807. {
  19808. return MidiMessage (0xf1, (sequenceNumber << 4) | value);
  19809. }
  19810. bool MidiMessage::isFullFrame() const throw()
  19811. {
  19812. return data[0] == 0xf0
  19813. && data[1] == 0x7f
  19814. && size >= 10
  19815. && data[3] == 0x01
  19816. && data[4] == 0x01;
  19817. }
  19818. void MidiMessage::getFullFrameParameters (int& hours,
  19819. int& minutes,
  19820. int& seconds,
  19821. int& frames,
  19822. MidiMessage::SmpteTimecodeType& timecodeType) const throw()
  19823. {
  19824. jassert (isFullFrame());
  19825. timecodeType = (SmpteTimecodeType) (data[5] >> 5);
  19826. hours = data[5] & 0x1f;
  19827. minutes = data[6];
  19828. seconds = data[7];
  19829. frames = data[8];
  19830. }
  19831. const MidiMessage MidiMessage::fullFrame (const int hours,
  19832. const int minutes,
  19833. const int seconds,
  19834. const int frames,
  19835. MidiMessage::SmpteTimecodeType timecodeType)
  19836. {
  19837. uint8 d[10];
  19838. d[0] = 0xf0;
  19839. d[1] = 0x7f;
  19840. d[2] = 0x7f;
  19841. d[3] = 0x01;
  19842. d[4] = 0x01;
  19843. d[5] = (uint8) ((hours & 0x01f) | (timecodeType << 5));
  19844. d[6] = (uint8) minutes;
  19845. d[7] = (uint8) seconds;
  19846. d[8] = (uint8) frames;
  19847. d[9] = 0xf7;
  19848. return MidiMessage (d, 10, 0.0);
  19849. }
  19850. bool MidiMessage::isMidiMachineControlMessage() const throw()
  19851. {
  19852. return data[0] == 0xf0
  19853. && data[1] == 0x7f
  19854. && data[3] == 0x06
  19855. && size > 5;
  19856. }
  19857. MidiMessage::MidiMachineControlCommand MidiMessage::getMidiMachineControlCommand() const throw()
  19858. {
  19859. jassert (isMidiMachineControlMessage());
  19860. return (MidiMachineControlCommand) data[4];
  19861. }
  19862. const MidiMessage MidiMessage::midiMachineControlCommand (MidiMessage::MidiMachineControlCommand command)
  19863. {
  19864. uint8 d[6];
  19865. d[0] = 0xf0;
  19866. d[1] = 0x7f;
  19867. d[2] = 0x00;
  19868. d[3] = 0x06;
  19869. d[4] = (uint8) command;
  19870. d[5] = 0xf7;
  19871. return MidiMessage (d, 6, 0.0);
  19872. }
  19873. bool MidiMessage::isMidiMachineControlGoto (int& hours,
  19874. int& minutes,
  19875. int& seconds,
  19876. int& frames) const throw()
  19877. {
  19878. if (size >= 12
  19879. && data[0] == 0xf0
  19880. && data[1] == 0x7f
  19881. && data[3] == 0x06
  19882. && data[4] == 0x44
  19883. && data[5] == 0x06
  19884. && data[6] == 0x01)
  19885. {
  19886. hours = data[7] % 24; // (that some machines send out hours > 24)
  19887. minutes = data[8];
  19888. seconds = data[9];
  19889. frames = data[10];
  19890. return true;
  19891. }
  19892. return false;
  19893. }
  19894. const MidiMessage MidiMessage::midiMachineControlGoto (int hours,
  19895. int minutes,
  19896. int seconds,
  19897. int frames)
  19898. {
  19899. uint8 d[12];
  19900. d[0] = 0xf0;
  19901. d[1] = 0x7f;
  19902. d[2] = 0x00;
  19903. d[3] = 0x06;
  19904. d[4] = 0x44;
  19905. d[5] = 0x06;
  19906. d[6] = 0x01;
  19907. d[7] = (uint8) hours;
  19908. d[8] = (uint8) minutes;
  19909. d[9] = (uint8) seconds;
  19910. d[10] = (uint8) frames;
  19911. d[11] = 0xf7;
  19912. return MidiMessage (d, 12, 0.0);
  19913. }
  19914. const String MidiMessage::getMidiNoteName (int note,
  19915. bool useSharps,
  19916. bool includeOctaveNumber,
  19917. int octaveNumForMiddleC) throw()
  19918. {
  19919. static const char* const sharpNoteNames[] = { "C", "C#", "D", "D#", "E",
  19920. "F", "F#", "G", "G#", "A",
  19921. "A#", "B" };
  19922. static const char* const flatNoteNames[] = { "C", "Db", "D", "Eb", "E",
  19923. "F", "Gb", "G", "Ab", "A",
  19924. "Bb", "B" };
  19925. if (((unsigned int) note) < 128)
  19926. {
  19927. const String s ((useSharps) ? sharpNoteNames [note % 12]
  19928. : flatNoteNames [note % 12]);
  19929. if (includeOctaveNumber)
  19930. return s + String (note / 12 + (octaveNumForMiddleC - 5));
  19931. else
  19932. return s;
  19933. }
  19934. return String::empty;
  19935. }
  19936. const double MidiMessage::getMidiNoteInHertz (int noteNumber) throw()
  19937. {
  19938. noteNumber -= 12 * 6 + 9; // now 0 = A440
  19939. return 440.0 * pow (2.0, noteNumber / 12.0);
  19940. }
  19941. const String MidiMessage::getGMInstrumentName (int n) throw()
  19942. {
  19943. const char *names[] =
  19944. {
  19945. "Acoustic Grand Piano", "Bright Acoustic Piano", "Electric Grand Piano", "Honky-tonk Piano",
  19946. "Electric Piano 1", "Electric Piano 2", "Harpsichord", "Clavinet", "Celesta", "Glockenspiel",
  19947. "Music Box", "Vibraphone", "Marimba", "Xylophone", "Tubular Bells", "Dulcimer", "Drawbar Organ",
  19948. "Percussive Organ", "Rock Organ", "Church Organ", "Reed Organ", "Accordion", "Harmonica",
  19949. "Tango Accordion", "Acoustic Guitar (nylon)", "Acoustic Guitar (steel)", "Electric Guitar (jazz)",
  19950. "Electric Guitar (clean)", "Electric Guitar (mute)", "Overdriven Guitar", "Distortion Guitar",
  19951. "Guitar Harmonics", "Acoustic Bass", "Electric Bass (finger)", "Electric Bass (pick)",
  19952. "Fretless Bass", "Slap Bass 1", "Slap Bass 2", "Synth Bass 1", "Synth Bass 2", "Violin",
  19953. "Viola", "Cello", "Contrabass", "Tremolo Strings", "Pizzicato Strings", "Orchestral Harp",
  19954. "Timpani", "String Ensemble 1", "String Ensemble 2", "SynthStrings 1", "SynthStrings 2",
  19955. "Choir Aahs", "Voice Oohs", "Synth Voice", "Orchestra Hit", "Trumpet", "Trombone", "Tuba",
  19956. "Muted Trumpet", "French Horn", "Brass Section", "SynthBrass 1", "SynthBrass 2", "Soprano Sax",
  19957. "Alto Sax", "Tenor Sax", "Baritone Sax", "Oboe", "English Horn", "Bassoon", "Clarinet",
  19958. "Piccolo", "Flute", "Recorder", "Pan Flute", "Blown Bottle", "Shakuhachi", "Whistle",
  19959. "Ocarina", "Lead 1 (square)", "Lead 2 (sawtooth)", "Lead 3 (calliope)", "Lead 4 (chiff)",
  19960. "Lead 5 (charang)", "Lead 6 (voice)", "Lead 7 (fifths)", "Lead 8 (bass+lead)", "Pad 1 (new age)",
  19961. "Pad 2 (warm)", "Pad 3 (polysynth)", "Pad 4 (choir)", "Pad 5 (bowed)", "Pad 6 (metallic)",
  19962. "Pad 7 (halo)", "Pad 8 (sweep)", "FX 1 (rain)", "FX 2 (soundtrack)", "FX 3 (crystal)",
  19963. "FX 4 (atmosphere)", "FX 5 (brightness)", "FX 6 (goblins)", "FX 7 (echoes)", "FX 8 (sci-fi)",
  19964. "Sitar", "Banjo", "Shamisen", "Koto", "Kalimba", "Bag pipe", "Fiddle", "Shanai", "Tinkle Bell",
  19965. "Agogo", "Steel Drums", "Woodblock", "Taiko Drum", "Melodic Tom", "Synth Drum", "Reverse Cymbal",
  19966. "Guitar Fret Noise", "Breath Noise", "Seashore", "Bird Tweet", "Telephone Ring", "Helicopter",
  19967. "Applause", "Gunshot"
  19968. };
  19969. return (((unsigned int) n) < 128) ? names[n]
  19970. : (const char*)0;
  19971. }
  19972. const String MidiMessage::getGMInstrumentBankName (int n) throw()
  19973. {
  19974. const char* names[] =
  19975. {
  19976. "Piano", "Chromatic Percussion", "Organ", "Guitar",
  19977. "Bass", "Strings", "Ensemble", "Brass",
  19978. "Reed", "Pipe", "Synth Lead", "Synth Pad",
  19979. "Synth Effects", "Ethnic", "Percussive", "Sound Effects"
  19980. };
  19981. return (((unsigned int) n) <= 15) ? names[n]
  19982. : (const char*)0;
  19983. }
  19984. const String MidiMessage::getRhythmInstrumentName (int n) throw()
  19985. {
  19986. const char* names[] =
  19987. {
  19988. "Acoustic Bass Drum", "Bass Drum 1", "Side Stick", "Acoustic Snare",
  19989. "Hand Clap", "Electric Snare", "Low Floor Tom", "Closed Hi-Hat", "High Floor Tom",
  19990. "Pedal Hi-Hat", "Low Tom", "Open Hi-Hat", "Low-Mid Tom", "Hi-Mid Tom", "Crash Cymbal 1",
  19991. "High Tom", "Ride Cymbal 1", "Chinese Cymbal", "Ride Bell", "Tambourine", "Splash Cymbal",
  19992. "Cowbell", "Crash Cymbal 2", "Vibraslap", "Ride Cymbal 2", "Hi Bongo", "Low Bongo",
  19993. "Mute Hi Conga", "Open Hi Conga", "Low Conga", "High Timbale", "Low Timbale", "High Agogo",
  19994. "Low Agogo", "Cabasa", "Maracas", "Short Whistle", "Long Whistle", "Short Guiro",
  19995. "Long Guiro", "Claves", "Hi Wood Block", "Low Wood Block", "Mute Cuica", "Open Cuica",
  19996. "Mute Triangle", "Open Triangle"
  19997. };
  19998. return (n >= 35 && n <= 81) ? names [n - 35]
  19999. : (const char*)0;
  20000. }
  20001. const String MidiMessage::getControllerName (int n) throw()
  20002. {
  20003. const char* names[] =
  20004. {
  20005. "Bank Select", "Modulation Wheel (coarse)", "Breath controller (coarse)",
  20006. 0, "Foot Pedal (coarse)", "Portamento Time (coarse)",
  20007. "Data Entry (coarse)", "Volume (coarse)", "Balance (coarse)",
  20008. 0, "Pan position (coarse)", "Expression (coarse)", "Effect Control 1 (coarse)",
  20009. "Effect Control 2 (coarse)", 0, 0, "General Purpose Slider 1", "General Purpose Slider 2",
  20010. "General Purpose Slider 3", "General Purpose Slider 4", 0, 0, 0, 0, 0, 0, 0, 0,
  20011. 0, 0, 0, 0, "Bank Select (fine)", "Modulation Wheel (fine)", "Breath controller (fine)",
  20012. 0, "Foot Pedal (fine)", "Portamento Time (fine)", "Data Entry (fine)", "Volume (fine)",
  20013. "Balance (fine)", 0, "Pan position (fine)", "Expression (fine)", "Effect Control 1 (fine)",
  20014. "Effect Control 2 (fine)", 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  20015. "Hold Pedal (on/off)", "Portamento (on/off)", "Sustenuto Pedal (on/off)", "Soft Pedal (on/off)",
  20016. "Legato Pedal (on/off)", "Hold 2 Pedal (on/off)", "Sound Variation", "Sound Timbre",
  20017. "Sound Release Time", "Sound Attack Time", "Sound Brightness", "Sound Control 6",
  20018. "Sound Control 7", "Sound Control 8", "Sound Control 9", "Sound Control 10",
  20019. "General Purpose Button 1 (on/off)", "General Purpose Button 2 (on/off)",
  20020. "General Purpose Button 3 (on/off)", "General Purpose Button 4 (on/off)",
  20021. 0, 0, 0, 0, 0, 0, 0, "Reverb Level", "Tremolo Level", "Chorus Level", "Celeste Level",
  20022. "Phaser Level", "Data Button increment", "Data Button decrement", "Non-registered Parameter (fine)",
  20023. "Non-registered Parameter (coarse)", "Registered Parameter (fine)", "Registered Parameter (coarse)",
  20024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, "All Sound Off", "All Controllers Off",
  20025. "Local Keyboard (on/off)", "All Notes Off", "Omni Mode Off", "Omni Mode On", "Mono Operation",
  20026. "Poly Operation"
  20027. };
  20028. return (((unsigned int) n) < 128) ? names[n]
  20029. : (const char*)0;
  20030. }
  20031. END_JUCE_NAMESPACE
  20032. /********* End of inlined file: juce_MidiMessage.cpp *********/
  20033. /********* Start of inlined file: juce_MidiMessageCollector.cpp *********/
  20034. BEGIN_JUCE_NAMESPACE
  20035. MidiMessageCollector::MidiMessageCollector()
  20036. : lastCallbackTime (0),
  20037. sampleRate (44100.0001)
  20038. {
  20039. }
  20040. MidiMessageCollector::~MidiMessageCollector()
  20041. {
  20042. }
  20043. void MidiMessageCollector::reset (const double sampleRate_)
  20044. {
  20045. jassert (sampleRate_ > 0);
  20046. const ScopedLock sl (midiCallbackLock);
  20047. sampleRate = sampleRate_;
  20048. incomingMessages.clear();
  20049. lastCallbackTime = Time::getMillisecondCounterHiRes();
  20050. }
  20051. void MidiMessageCollector::addMessageToQueue (const MidiMessage& message)
  20052. {
  20053. // you need to call reset() to set the correct sample rate before using this object
  20054. jassert (sampleRate != 44100.0001);
  20055. // the messages that come in here need to be time-stamped correctly - see MidiInput
  20056. // for details of what the number should be.
  20057. jassert (message.getTimeStamp() != 0);
  20058. const ScopedLock sl (midiCallbackLock);
  20059. const int sampleNumber
  20060. = (int) ((message.getTimeStamp() - 0.001 * lastCallbackTime) * sampleRate);
  20061. incomingMessages.addEvent (message, sampleNumber);
  20062. // if the messages don't get used for over a second, we'd better
  20063. // get rid of any old ones to avoid the queue getting too big
  20064. if (sampleNumber > sampleRate)
  20065. incomingMessages.clear (0, sampleNumber - (int) sampleRate);
  20066. }
  20067. void MidiMessageCollector::removeNextBlockOfMessages (MidiBuffer& destBuffer,
  20068. const int numSamples)
  20069. {
  20070. // you need to call reset() to set the correct sample rate before using this object
  20071. jassert (sampleRate != 44100.0001);
  20072. const double timeNow = Time::getMillisecondCounterHiRes();
  20073. const double msElapsed = timeNow - lastCallbackTime;
  20074. const ScopedLock sl (midiCallbackLock);
  20075. lastCallbackTime = timeNow;
  20076. if (! incomingMessages.isEmpty())
  20077. {
  20078. int numSourceSamples = jmax (1, roundDoubleToInt (msElapsed * 0.001 * sampleRate));
  20079. int startSample = 0;
  20080. int scale = 1 << 16;
  20081. const uint8* midiData;
  20082. int numBytes, samplePosition;
  20083. MidiBuffer::Iterator iter (incomingMessages);
  20084. if (numSourceSamples > numSamples)
  20085. {
  20086. // if our list of events is longer than the buffer we're being
  20087. // asked for, scale them down to squeeze them all in..
  20088. const int maxBlockLengthToUse = numSamples << 3;
  20089. if (numSourceSamples > maxBlockLengthToUse)
  20090. {
  20091. startSample = numSourceSamples - maxBlockLengthToUse;
  20092. numSourceSamples = maxBlockLengthToUse;
  20093. iter.setNextSamplePosition (startSample);
  20094. }
  20095. scale = (numSamples << 10) / numSourceSamples;
  20096. while (iter.getNextEvent (midiData, numBytes, samplePosition))
  20097. {
  20098. samplePosition = ((samplePosition - startSample) * scale) >> 10;
  20099. destBuffer.addEvent (midiData, numBytes,
  20100. jlimit (0, numSamples - 1, samplePosition));
  20101. }
  20102. }
  20103. else
  20104. {
  20105. // if our event list is shorter than the number we need, put them
  20106. // towards the end of the buffer
  20107. startSample = numSamples - numSourceSamples;
  20108. while (iter.getNextEvent (midiData, numBytes, samplePosition))
  20109. {
  20110. destBuffer.addEvent (midiData, numBytes,
  20111. jlimit (0, numSamples - 1, samplePosition + startSample));
  20112. }
  20113. }
  20114. incomingMessages.clear();
  20115. }
  20116. }
  20117. void MidiMessageCollector::handleNoteOn (MidiKeyboardState*, int midiChannel, int midiNoteNumber, float velocity)
  20118. {
  20119. MidiMessage m (MidiMessage::noteOn (midiChannel, midiNoteNumber, velocity));
  20120. m.setTimeStamp (Time::getMillisecondCounter() * 0.001);
  20121. addMessageToQueue (m);
  20122. }
  20123. void MidiMessageCollector::handleNoteOff (MidiKeyboardState*, int midiChannel, int midiNoteNumber)
  20124. {
  20125. MidiMessage m (MidiMessage::noteOff (midiChannel, midiNoteNumber));
  20126. m.setTimeStamp (Time::getMillisecondCounter() * 0.001);
  20127. addMessageToQueue (m);
  20128. }
  20129. void MidiMessageCollector::handleIncomingMidiMessage (MidiInput*, const MidiMessage& message)
  20130. {
  20131. addMessageToQueue (message);
  20132. }
  20133. END_JUCE_NAMESPACE
  20134. /********* End of inlined file: juce_MidiMessageCollector.cpp *********/
  20135. /********* Start of inlined file: juce_MidiMessageSequence.cpp *********/
  20136. BEGIN_JUCE_NAMESPACE
  20137. MidiMessageSequence::MidiMessageSequence()
  20138. {
  20139. }
  20140. MidiMessageSequence::MidiMessageSequence (const MidiMessageSequence& other)
  20141. {
  20142. list.ensureStorageAllocated (other.list.size());
  20143. for (int i = 0; i < other.list.size(); ++i)
  20144. list.add (new MidiEventHolder (other.list.getUnchecked(i)->message));
  20145. }
  20146. const MidiMessageSequence& MidiMessageSequence::operator= (const MidiMessageSequence& other)
  20147. {
  20148. if (this != &other)
  20149. {
  20150. clear();
  20151. for (int i = 0; i < other.list.size(); ++i)
  20152. list.add (new MidiEventHolder (other.list.getUnchecked(i)->message));
  20153. }
  20154. return *this;
  20155. }
  20156. MidiMessageSequence::~MidiMessageSequence()
  20157. {
  20158. }
  20159. void MidiMessageSequence::clear()
  20160. {
  20161. list.clear();
  20162. }
  20163. int MidiMessageSequence::getNumEvents() const
  20164. {
  20165. return list.size();
  20166. }
  20167. MidiMessageSequence::MidiEventHolder* MidiMessageSequence::getEventPointer (const int index) const
  20168. {
  20169. return list [index];
  20170. }
  20171. double MidiMessageSequence::getTimeOfMatchingKeyUp (const int index) const
  20172. {
  20173. const MidiEventHolder* const meh = list [index];
  20174. if (meh != 0 && meh->noteOffObject != 0)
  20175. return meh->noteOffObject->message.getTimeStamp();
  20176. else
  20177. return 0.0;
  20178. }
  20179. int MidiMessageSequence::getIndexOfMatchingKeyUp (const int index) const
  20180. {
  20181. const MidiEventHolder* const meh = list [index];
  20182. return (meh != 0) ? list.indexOf (meh->noteOffObject) : -1;
  20183. }
  20184. int MidiMessageSequence::getIndexOf (MidiEventHolder* const event) const
  20185. {
  20186. return list.indexOf (event);
  20187. }
  20188. int MidiMessageSequence::getNextIndexAtTime (const double timeStamp) const
  20189. {
  20190. const int numEvents = list.size();
  20191. int i;
  20192. for (i = 0; i < numEvents; ++i)
  20193. if (list.getUnchecked(i)->message.getTimeStamp() >= timeStamp)
  20194. break;
  20195. return i;
  20196. }
  20197. double MidiMessageSequence::getStartTime() const
  20198. {
  20199. if (list.size() > 0)
  20200. return list.getUnchecked(0)->message.getTimeStamp();
  20201. else
  20202. return 0;
  20203. }
  20204. double MidiMessageSequence::getEndTime() const
  20205. {
  20206. if (list.size() > 0)
  20207. return list.getLast()->message.getTimeStamp();
  20208. else
  20209. return 0;
  20210. }
  20211. double MidiMessageSequence::getEventTime (const int index) const
  20212. {
  20213. if (((unsigned int) index) < (unsigned int) list.size())
  20214. return list.getUnchecked (index)->message.getTimeStamp();
  20215. return 0.0;
  20216. }
  20217. void MidiMessageSequence::addEvent (const MidiMessage& newMessage,
  20218. double timeAdjustment)
  20219. {
  20220. MidiEventHolder* const newOne = new MidiEventHolder (newMessage);
  20221. timeAdjustment += newMessage.getTimeStamp();
  20222. newOne->message.setTimeStamp (timeAdjustment);
  20223. int i;
  20224. for (i = list.size(); --i >= 0;)
  20225. if (list.getUnchecked(i)->message.getTimeStamp() <= timeAdjustment)
  20226. break;
  20227. list.insert (i + 1, newOne);
  20228. }
  20229. void MidiMessageSequence::deleteEvent (const int index,
  20230. const bool deleteMatchingNoteUp)
  20231. {
  20232. if (((unsigned int) index) < (unsigned int) list.size())
  20233. {
  20234. if (deleteMatchingNoteUp)
  20235. deleteEvent (getIndexOfMatchingKeyUp (index), false);
  20236. list.remove (index);
  20237. }
  20238. }
  20239. void MidiMessageSequence::addSequence (const MidiMessageSequence& other,
  20240. double timeAdjustment,
  20241. double firstAllowableTime,
  20242. double endOfAllowableDestTimes)
  20243. {
  20244. firstAllowableTime -= timeAdjustment;
  20245. endOfAllowableDestTimes -= timeAdjustment;
  20246. for (int i = 0; i < other.list.size(); ++i)
  20247. {
  20248. const MidiMessage& m = other.list.getUnchecked(i)->message;
  20249. const double t = m.getTimeStamp();
  20250. if (t >= firstAllowableTime && t < endOfAllowableDestTimes)
  20251. {
  20252. MidiEventHolder* const newOne = new MidiEventHolder (m);
  20253. newOne->message.setTimeStamp (timeAdjustment + t);
  20254. list.add (newOne);
  20255. }
  20256. }
  20257. sort();
  20258. }
  20259. int MidiMessageSequence::compareElements (const MidiMessageSequence::MidiEventHolder* const first,
  20260. const MidiMessageSequence::MidiEventHolder* const second) throw()
  20261. {
  20262. const double diff = first->message.getTimeStamp()
  20263. - second->message.getTimeStamp();
  20264. return (diff == 0) ? 0
  20265. : ((diff > 0) ? 1
  20266. : -1);
  20267. }
  20268. void MidiMessageSequence::sort()
  20269. {
  20270. list.sort (*this, true);
  20271. }
  20272. void MidiMessageSequence::updateMatchedPairs()
  20273. {
  20274. for (int i = 0; i < list.size(); ++i)
  20275. {
  20276. const MidiMessage& m1 = list.getUnchecked(i)->message;
  20277. if (m1.isNoteOn())
  20278. {
  20279. list.getUnchecked(i)->noteOffObject = 0;
  20280. const int note = m1.getNoteNumber();
  20281. const int chan = m1.getChannel();
  20282. const int len = list.size();
  20283. for (int j = i + 1; j < len; ++j)
  20284. {
  20285. const MidiMessage& m = list.getUnchecked(j)->message;
  20286. if (m.getNoteNumber() == note && m.getChannel() == chan)
  20287. {
  20288. if (m.isNoteOff())
  20289. {
  20290. list.getUnchecked(i)->noteOffObject = list[j];
  20291. break;
  20292. }
  20293. else if (m.isNoteOn())
  20294. {
  20295. list.insert (j, new MidiEventHolder (MidiMessage::noteOff (chan, note)));
  20296. list.getUnchecked(j)->message.setTimeStamp (m.getTimeStamp());
  20297. list.getUnchecked(i)->noteOffObject = list[j];
  20298. break;
  20299. }
  20300. }
  20301. }
  20302. }
  20303. }
  20304. }
  20305. void MidiMessageSequence::addTimeToMessages (const double delta)
  20306. {
  20307. for (int i = list.size(); --i >= 0;)
  20308. list.getUnchecked (i)->message.setTimeStamp (list.getUnchecked (i)->message.getTimeStamp()
  20309. + delta);
  20310. }
  20311. void MidiMessageSequence::extractMidiChannelMessages (const int channelNumberToExtract,
  20312. MidiMessageSequence& destSequence,
  20313. const bool alsoIncludeMetaEvents) const
  20314. {
  20315. for (int i = 0; i < list.size(); ++i)
  20316. {
  20317. const MidiMessage& mm = list.getUnchecked(i)->message;
  20318. if (mm.isForChannel (channelNumberToExtract)
  20319. || (alsoIncludeMetaEvents && mm.isMetaEvent()))
  20320. {
  20321. destSequence.addEvent (mm);
  20322. }
  20323. }
  20324. }
  20325. void MidiMessageSequence::extractSysExMessages (MidiMessageSequence& destSequence) const
  20326. {
  20327. for (int i = 0; i < list.size(); ++i)
  20328. {
  20329. const MidiMessage& mm = list.getUnchecked(i)->message;
  20330. if (mm.isSysEx())
  20331. destSequence.addEvent (mm);
  20332. }
  20333. }
  20334. void MidiMessageSequence::deleteMidiChannelMessages (const int channelNumberToRemove)
  20335. {
  20336. for (int i = list.size(); --i >= 0;)
  20337. if (list.getUnchecked(i)->message.isForChannel (channelNumberToRemove))
  20338. list.remove(i);
  20339. }
  20340. void MidiMessageSequence::deleteSysExMessages()
  20341. {
  20342. for (int i = list.size(); --i >= 0;)
  20343. if (list.getUnchecked(i)->message.isSysEx())
  20344. list.remove(i);
  20345. }
  20346. void MidiMessageSequence::createControllerUpdatesForTime (const int channelNumber,
  20347. const double time,
  20348. OwnedArray<MidiMessage>& dest)
  20349. {
  20350. bool doneProg = false;
  20351. bool donePitchWheel = false;
  20352. Array <int> doneControllers (32);
  20353. for (int i = list.size(); --i >= 0;)
  20354. {
  20355. const MidiMessage& mm = list.getUnchecked(i)->message;
  20356. if (mm.isForChannel (channelNumber)
  20357. && mm.getTimeStamp() <= time)
  20358. {
  20359. if (mm.isProgramChange())
  20360. {
  20361. if (! doneProg)
  20362. {
  20363. dest.add (new MidiMessage (mm, 0.0));
  20364. doneProg = true;
  20365. }
  20366. }
  20367. else if (mm.isController())
  20368. {
  20369. if (! doneControllers.contains (mm.getControllerNumber()))
  20370. {
  20371. dest.add (new MidiMessage (mm, 0.0));
  20372. doneControllers.add (mm.getControllerNumber());
  20373. }
  20374. }
  20375. else if (mm.isPitchWheel())
  20376. {
  20377. if (! donePitchWheel)
  20378. {
  20379. dest.add (new MidiMessage (mm, 0.0));
  20380. donePitchWheel = true;
  20381. }
  20382. }
  20383. }
  20384. }
  20385. }
  20386. MidiMessageSequence::MidiEventHolder::MidiEventHolder (const MidiMessage& message_)
  20387. : message (message_),
  20388. noteOffObject (0)
  20389. {
  20390. }
  20391. MidiMessageSequence::MidiEventHolder::~MidiEventHolder()
  20392. {
  20393. }
  20394. END_JUCE_NAMESPACE
  20395. /********* End of inlined file: juce_MidiMessageSequence.cpp *********/
  20396. /********* Start of inlined file: juce_AudioPluginFormat.cpp *********/
  20397. BEGIN_JUCE_NAMESPACE
  20398. AudioPluginFormat::AudioPluginFormat() throw()
  20399. {
  20400. }
  20401. AudioPluginFormat::~AudioPluginFormat()
  20402. {
  20403. }
  20404. END_JUCE_NAMESPACE
  20405. /********* End of inlined file: juce_AudioPluginFormat.cpp *********/
  20406. /********* Start of inlined file: juce_AudioPluginFormatManager.cpp *********/
  20407. BEGIN_JUCE_NAMESPACE
  20408. AudioPluginFormatManager::AudioPluginFormatManager() throw()
  20409. {
  20410. }
  20411. AudioPluginFormatManager::~AudioPluginFormatManager() throw()
  20412. {
  20413. }
  20414. juce_ImplementSingleton_SingleThreaded (AudioPluginFormatManager);
  20415. void AudioPluginFormatManager::addDefaultFormats()
  20416. {
  20417. #ifdef JUCE_DEBUG
  20418. // you should only call this method once!
  20419. for (int i = formats.size(); --i >= 0;)
  20420. {
  20421. #if JUCE_PLUGINHOST_VST
  20422. jassert (dynamic_cast <VSTPluginFormat*> (formats[i]) == 0);
  20423. #endif
  20424. #if JUCE_PLUGINHOST_AU && JUCE_MAC
  20425. jassert (dynamic_cast <AudioUnitPluginFormat*> (formats[i]) == 0);
  20426. #endif
  20427. #if JUCE_PLUGINHOST_DX && JUCE_WIN32
  20428. jassert (dynamic_cast <DirectXPluginFormat*> (formats[i]) == 0);
  20429. #endif
  20430. #if JUCE_PLUGINHOST_LADSPA && JUCE_LINUX
  20431. jassert (dynamic_cast <LADSPAPluginFormat*> (formats[i]) == 0);
  20432. #endif
  20433. }
  20434. #endif
  20435. #if JUCE_PLUGINHOST_VST
  20436. formats.add (new VSTPluginFormat());
  20437. #endif
  20438. #if JUCE_PLUGINHOST_AU && JUCE_MAC
  20439. formats.add (new AudioUnitPluginFormat());
  20440. #endif
  20441. #if JUCE_PLUGINHOST_DX && JUCE_WIN32
  20442. formats.add (new DirectXPluginFormat());
  20443. #endif
  20444. #if JUCE_PLUGINHOST_LADSPA && JUCE_LINUX
  20445. formats.add (new LADSPAPluginFormat());
  20446. #endif
  20447. }
  20448. int AudioPluginFormatManager::getNumFormats() throw()
  20449. {
  20450. return formats.size();
  20451. }
  20452. AudioPluginFormat* AudioPluginFormatManager::getFormat (const int index) throw()
  20453. {
  20454. return formats [index];
  20455. }
  20456. void AudioPluginFormatManager::addFormat (AudioPluginFormat* const format) throw()
  20457. {
  20458. formats.add (format);
  20459. }
  20460. AudioPluginInstance* AudioPluginFormatManager::createPluginInstance (const PluginDescription& description,
  20461. String& errorMessage) const
  20462. {
  20463. AudioPluginInstance* result = 0;
  20464. for (int i = 0; i < formats.size(); ++i)
  20465. {
  20466. result = formats.getUnchecked(i)->createInstanceFromDescription (description);
  20467. if (result != 0)
  20468. break;
  20469. }
  20470. if (result == 0)
  20471. {
  20472. if (description.file != File::nonexistent && ! description.file.exists())
  20473. errorMessage = TRANS ("This plug-in file no longer exists");
  20474. else
  20475. errorMessage = TRANS ("This plug-in failed to load correctly");
  20476. }
  20477. return result;
  20478. }
  20479. END_JUCE_NAMESPACE
  20480. /********* End of inlined file: juce_AudioPluginFormatManager.cpp *********/
  20481. /********* Start of inlined file: juce_AudioPluginInstance.cpp *********/
  20482. #define JUCE_PLUGIN_HOST 1
  20483. BEGIN_JUCE_NAMESPACE
  20484. AudioPluginInstance::AudioPluginInstance()
  20485. {
  20486. }
  20487. AudioPluginInstance::~AudioPluginInstance()
  20488. {
  20489. }
  20490. END_JUCE_NAMESPACE
  20491. /********* End of inlined file: juce_AudioPluginInstance.cpp *********/
  20492. /********* Start of inlined file: juce_KnownPluginList.cpp *********/
  20493. BEGIN_JUCE_NAMESPACE
  20494. KnownPluginList::KnownPluginList()
  20495. {
  20496. }
  20497. KnownPluginList::~KnownPluginList()
  20498. {
  20499. }
  20500. void KnownPluginList::clear()
  20501. {
  20502. if (types.size() > 0)
  20503. {
  20504. types.clear();
  20505. sendChangeMessage (this);
  20506. }
  20507. }
  20508. PluginDescription* KnownPluginList::getTypeForFile (const File& file) const throw()
  20509. {
  20510. for (int i = 0; i < types.size(); ++i)
  20511. if (types.getUnchecked(i)->file == file)
  20512. return types.getUnchecked(i);
  20513. return 0;
  20514. }
  20515. PluginDescription* KnownPluginList::getTypeForIdentifierString (const String& identifierString) const throw()
  20516. {
  20517. for (int i = 0; i < types.size(); ++i)
  20518. if (types.getUnchecked(i)->createIdentifierString() == identifierString)
  20519. return types.getUnchecked(i);
  20520. return 0;
  20521. }
  20522. bool KnownPluginList::addType (const PluginDescription& type)
  20523. {
  20524. for (int i = types.size(); --i >= 0;)
  20525. {
  20526. if (types.getUnchecked(i)->isDuplicateOf (type))
  20527. {
  20528. // strange - found a duplicate plugin with different info..
  20529. jassert (types.getUnchecked(i)->name == type.name);
  20530. jassert (types.getUnchecked(i)->isInstrument == type.isInstrument);
  20531. *types.getUnchecked(i) = type;
  20532. return false;
  20533. }
  20534. }
  20535. types.add (new PluginDescription (type));
  20536. sendChangeMessage (this);
  20537. return true;
  20538. }
  20539. void KnownPluginList::removeType (const int index) throw()
  20540. {
  20541. types.remove (index);
  20542. sendChangeMessage (this);
  20543. }
  20544. bool KnownPluginList::isListingUpToDate (const File& possiblePluginFile) const throw()
  20545. {
  20546. if (getTypeForFile (possiblePluginFile) == 0)
  20547. return false;
  20548. for (int i = types.size(); --i >= 0;)
  20549. {
  20550. const PluginDescription* const d = types.getUnchecked(i);
  20551. if (d->file == possiblePluginFile
  20552. && d->lastFileModTime != possiblePluginFile.getLastModificationTime())
  20553. {
  20554. return false;
  20555. }
  20556. }
  20557. return true;
  20558. }
  20559. bool KnownPluginList::scanAndAddFile (const File& possiblePluginFile,
  20560. const bool dontRescanIfAlreadyInList,
  20561. OwnedArray <PluginDescription>& typesFound)
  20562. {
  20563. bool addedOne = false;
  20564. if (dontRescanIfAlreadyInList
  20565. && getTypeForFile (possiblePluginFile) != 0)
  20566. {
  20567. bool needsRescanning = false;
  20568. for (int i = types.size(); --i >= 0;)
  20569. {
  20570. const PluginDescription* const d = types.getUnchecked(i);
  20571. if (d->file == possiblePluginFile)
  20572. {
  20573. if (d->lastFileModTime != possiblePluginFile.getLastModificationTime())
  20574. needsRescanning = true;
  20575. else
  20576. typesFound.add (new PluginDescription (*d));
  20577. }
  20578. }
  20579. if (! needsRescanning)
  20580. return false;
  20581. }
  20582. for (int i = 0; i < AudioPluginFormatManager::getInstance()->getNumFormats(); ++i)
  20583. {
  20584. AudioPluginFormat* const format = AudioPluginFormatManager::getInstance()->getFormat (i);
  20585. OwnedArray <PluginDescription> found;
  20586. format->findAllTypesForFile (found, possiblePluginFile);
  20587. for (int i = 0; i < found.size(); ++i)
  20588. {
  20589. PluginDescription* const desc = found.getUnchecked(i);
  20590. jassert (desc != 0);
  20591. if (addType (*desc))
  20592. addedOne = true;
  20593. typesFound.add (new PluginDescription (*desc));
  20594. }
  20595. }
  20596. return addedOne;
  20597. }
  20598. void KnownPluginList::scanAndAddDragAndDroppedFiles (const StringArray& files,
  20599. OwnedArray <PluginDescription>& typesFound)
  20600. {
  20601. for (int i = 0; i < files.size(); ++i)
  20602. {
  20603. const File f (files [i]);
  20604. if (! scanAndAddFile (f, true, typesFound))
  20605. {
  20606. if (f.isDirectory())
  20607. {
  20608. StringArray s;
  20609. {
  20610. OwnedArray <File> subFiles;
  20611. f.findChildFiles (subFiles, File::findFilesAndDirectories, false);
  20612. for (int j = 0; j < subFiles.size(); ++j)
  20613. s.add (subFiles.getUnchecked (j)->getFullPathName());
  20614. }
  20615. scanAndAddDragAndDroppedFiles (s, typesFound);
  20616. }
  20617. }
  20618. }
  20619. }
  20620. class PluginSorter
  20621. {
  20622. public:
  20623. KnownPluginList::SortMethod method;
  20624. PluginSorter() throw() {}
  20625. int compareElements (const PluginDescription* const first,
  20626. const PluginDescription* const second) const throw()
  20627. {
  20628. int diff = 0;
  20629. if (method == KnownPluginList::sortByCategory)
  20630. diff = first->category.compareLexicographically (second->category);
  20631. else if (method == KnownPluginList::sortByManufacturer)
  20632. diff = first->manufacturerName.compareLexicographically (second->manufacturerName);
  20633. else if (method == KnownPluginList::sortByFileSystemLocation)
  20634. diff = first->file.getParentDirectory().getFullPathName().compare (second->file.getParentDirectory().getFullPathName());
  20635. if (diff == 0)
  20636. diff = first->name.compareLexicographically (second->name);
  20637. return diff;
  20638. }
  20639. };
  20640. void KnownPluginList::sort (const SortMethod method)
  20641. {
  20642. if (method != defaultOrder)
  20643. {
  20644. PluginSorter sorter;
  20645. sorter.method = method;
  20646. types.sort (sorter, true);
  20647. sendChangeMessage (this);
  20648. }
  20649. }
  20650. XmlElement* KnownPluginList::createXml() const
  20651. {
  20652. XmlElement* const e = new XmlElement (T("KNOWNPLUGINS"));
  20653. for (int i = 0; i < types.size(); ++i)
  20654. e->addChildElement (types.getUnchecked(i)->createXml());
  20655. return e;
  20656. }
  20657. void KnownPluginList::recreateFromXml (const XmlElement& xml)
  20658. {
  20659. clear();
  20660. if (xml.hasTagName (T("KNOWNPLUGINS")))
  20661. {
  20662. forEachXmlChildElement (xml, e)
  20663. {
  20664. PluginDescription info;
  20665. if (info.loadFromXml (*e))
  20666. addType (info);
  20667. }
  20668. }
  20669. }
  20670. const int menuIdBase = 0x324503f4;
  20671. // This is used to turn a bunch of paths into a nested menu structure.
  20672. struct PluginFilesystemTree
  20673. {
  20674. private:
  20675. String folder;
  20676. OwnedArray <PluginFilesystemTree> subFolders;
  20677. Array <PluginDescription*> plugins;
  20678. void addPlugin (PluginDescription* const pd, const String& path)
  20679. {
  20680. if (path.isEmpty())
  20681. {
  20682. plugins.add (pd);
  20683. }
  20684. else
  20685. {
  20686. const String firstSubFolder (path.upToFirstOccurrenceOf (T("/"), false, false));
  20687. const String remainingPath (path.fromFirstOccurrenceOf (T("/"), false, false));
  20688. for (int i = subFolders.size(); --i >= 0;)
  20689. {
  20690. if (subFolders.getUnchecked(i)->folder.equalsIgnoreCase (firstSubFolder))
  20691. {
  20692. subFolders.getUnchecked(i)->addPlugin (pd, remainingPath);
  20693. return;
  20694. }
  20695. }
  20696. PluginFilesystemTree* const newFolder = new PluginFilesystemTree();
  20697. newFolder->folder = firstSubFolder;
  20698. subFolders.add (newFolder);
  20699. newFolder->addPlugin (pd, remainingPath);
  20700. }
  20701. }
  20702. // removes any deeply nested folders that don't contain any actual plugins
  20703. void optimise()
  20704. {
  20705. for (int i = subFolders.size(); --i >= 0;)
  20706. {
  20707. PluginFilesystemTree* const sub = subFolders.getUnchecked(i);
  20708. sub->optimise();
  20709. if (sub->plugins.size() == 0)
  20710. {
  20711. for (int j = 0; j < sub->subFolders.size(); ++j)
  20712. subFolders.add (sub->subFolders.getUnchecked(j));
  20713. sub->subFolders.clear (false);
  20714. subFolders.remove (i);
  20715. }
  20716. }
  20717. }
  20718. public:
  20719. void buildTree (const Array <PluginDescription*>& allPlugins)
  20720. {
  20721. for (int i = 0; i < allPlugins.size(); ++i)
  20722. {
  20723. String path (allPlugins.getUnchecked(i)->file.getParentDirectory().getFullPathName());
  20724. if (path.substring (1, 2) == T(":"))
  20725. path = path.substring (2);
  20726. path = path.replaceCharacter (T('\\'), T('/'));
  20727. addPlugin (allPlugins.getUnchecked(i), path);
  20728. }
  20729. optimise();
  20730. }
  20731. void addToMenu (PopupMenu& m, const OwnedArray <PluginDescription>& allPlugins) const
  20732. {
  20733. int i;
  20734. for (i = 0; i < subFolders.size(); ++i)
  20735. {
  20736. const PluginFilesystemTree* const sub = subFolders.getUnchecked(i);
  20737. PopupMenu subMenu;
  20738. sub->addToMenu (subMenu, allPlugins);
  20739. m.addSubMenu (sub->folder, subMenu);
  20740. }
  20741. for (i = 0; i < plugins.size(); ++i)
  20742. {
  20743. PluginDescription* const plugin = plugins.getUnchecked(i);
  20744. m.addItem (allPlugins.indexOf (plugin) + menuIdBase,
  20745. plugin->name, true, false);
  20746. }
  20747. }
  20748. };
  20749. void KnownPluginList::addToMenu (PopupMenu& menu, const SortMethod sortMethod) const
  20750. {
  20751. Array <PluginDescription*> sorted;
  20752. {
  20753. PluginSorter sorter;
  20754. sorter.method = sortMethod;
  20755. for (int i = 0; i < types.size(); ++i)
  20756. sorted.addSorted (sorter, types.getUnchecked(i));
  20757. }
  20758. if (sortMethod == sortByCategory
  20759. || sortMethod == sortByManufacturer)
  20760. {
  20761. String lastSubMenuName;
  20762. PopupMenu sub;
  20763. for (int i = 0; i < sorted.size(); ++i)
  20764. {
  20765. const PluginDescription* const pd = sorted.getUnchecked(i);
  20766. String thisSubMenuName (sortMethod == sortByCategory ? pd->category
  20767. : pd->manufacturerName);
  20768. if (thisSubMenuName.trim().isEmpty())
  20769. thisSubMenuName = T("Other");
  20770. if (thisSubMenuName != lastSubMenuName)
  20771. {
  20772. if (sub.getNumItems() > 0)
  20773. {
  20774. menu.addSubMenu (lastSubMenuName, sub);
  20775. sub.clear();
  20776. }
  20777. lastSubMenuName = thisSubMenuName;
  20778. }
  20779. sub.addItem (types.indexOf (pd) + menuIdBase, pd->name, true, false);
  20780. }
  20781. if (sub.getNumItems() > 0)
  20782. menu.addSubMenu (lastSubMenuName, sub);
  20783. }
  20784. else if (sortMethod == sortByFileSystemLocation)
  20785. {
  20786. PluginFilesystemTree root;
  20787. root.buildTree (sorted);
  20788. root.addToMenu (menu, types);
  20789. }
  20790. else
  20791. {
  20792. for (int i = 0; i < sorted.size(); ++i)
  20793. {
  20794. const PluginDescription* const pd = sorted.getUnchecked(i);
  20795. menu.addItem (types.indexOf (pd) + menuIdBase, pd->name, true, false);
  20796. }
  20797. }
  20798. }
  20799. int KnownPluginList::getIndexChosenByMenu (const int menuResultCode) const
  20800. {
  20801. const int i = menuResultCode - menuIdBase;
  20802. return (((unsigned int) i) < (unsigned int) types.size()) ? i : -1;
  20803. }
  20804. END_JUCE_NAMESPACE
  20805. /********* End of inlined file: juce_KnownPluginList.cpp *********/
  20806. /********* Start of inlined file: juce_PluginDescription.cpp *********/
  20807. BEGIN_JUCE_NAMESPACE
  20808. PluginDescription::PluginDescription() throw()
  20809. : uid (0),
  20810. isInstrument (false),
  20811. numInputChannels (0),
  20812. numOutputChannels (0)
  20813. {
  20814. }
  20815. PluginDescription::~PluginDescription() throw()
  20816. {
  20817. }
  20818. PluginDescription::PluginDescription (const PluginDescription& other) throw()
  20819. : name (other.name),
  20820. pluginFormatName (other.pluginFormatName),
  20821. category (other.category),
  20822. manufacturerName (other.manufacturerName),
  20823. version (other.version),
  20824. file (other.file),
  20825. lastFileModTime (other.lastFileModTime),
  20826. uid (other.uid),
  20827. isInstrument (other.isInstrument),
  20828. numInputChannels (other.numInputChannels),
  20829. numOutputChannels (other.numOutputChannels)
  20830. {
  20831. }
  20832. const PluginDescription& PluginDescription::operator= (const PluginDescription& other) throw()
  20833. {
  20834. name = other.name;
  20835. pluginFormatName = other.pluginFormatName;
  20836. category = other.category;
  20837. manufacturerName = other.manufacturerName;
  20838. version = other.version;
  20839. file = other.file;
  20840. uid = other.uid;
  20841. isInstrument = other.isInstrument;
  20842. lastFileModTime = other.lastFileModTime;
  20843. numInputChannels = other.numInputChannels;
  20844. numOutputChannels = other.numOutputChannels;
  20845. return *this;
  20846. }
  20847. bool PluginDescription::isDuplicateOf (const PluginDescription& other) const
  20848. {
  20849. return file == other.file
  20850. && uid == other.uid;
  20851. }
  20852. const String PluginDescription::createIdentifierString() const throw()
  20853. {
  20854. return pluginFormatName
  20855. + T("-") + name
  20856. + T("-") + String::toHexString (file.getFileName().hashCode())
  20857. + T("-") + String::toHexString (uid);
  20858. }
  20859. XmlElement* PluginDescription::createXml() const
  20860. {
  20861. XmlElement* const e = new XmlElement (T("PLUGIN"));
  20862. e->setAttribute (T("name"), name);
  20863. e->setAttribute (T("format"), pluginFormatName);
  20864. e->setAttribute (T("category"), category);
  20865. e->setAttribute (T("manufacturer"), manufacturerName);
  20866. e->setAttribute (T("version"), version);
  20867. e->setAttribute (T("file"), file.getFullPathName());
  20868. e->setAttribute (T("uid"), String::toHexString (uid));
  20869. e->setAttribute (T("isInstrument"), isInstrument);
  20870. e->setAttribute (T("fileTime"), String::toHexString (lastFileModTime.toMilliseconds()));
  20871. e->setAttribute (T("numInputs"), numInputChannels);
  20872. e->setAttribute (T("numOutputs"), numOutputChannels);
  20873. return e;
  20874. }
  20875. bool PluginDescription::loadFromXml (const XmlElement& xml)
  20876. {
  20877. if (xml.hasTagName (T("PLUGIN")))
  20878. {
  20879. name = xml.getStringAttribute (T("name"));
  20880. pluginFormatName = xml.getStringAttribute (T("format"));
  20881. category = xml.getStringAttribute (T("category"));
  20882. manufacturerName = xml.getStringAttribute (T("manufacturer"));
  20883. version = xml.getStringAttribute (T("version"));
  20884. file = File (xml.getStringAttribute (T("file")));
  20885. uid = xml.getStringAttribute (T("uid")).getHexValue32();
  20886. isInstrument = xml.getBoolAttribute (T("isInstrument"), false);
  20887. lastFileModTime = Time (xml.getStringAttribute (T("fileTime")).getHexValue64());
  20888. numInputChannels = xml.getIntAttribute (T("numInputs"));
  20889. numOutputChannels = xml.getIntAttribute (T("numOutputs"));
  20890. return true;
  20891. }
  20892. return false;
  20893. }
  20894. END_JUCE_NAMESPACE
  20895. /********* End of inlined file: juce_PluginDescription.cpp *********/
  20896. /********* Start of inlined file: juce_PluginDirectoryScanner.cpp *********/
  20897. BEGIN_JUCE_NAMESPACE
  20898. PluginDirectoryScanner::PluginDirectoryScanner (KnownPluginList& listToAddTo,
  20899. AudioPluginFormat& formatToLookFor,
  20900. FileSearchPath directoriesToSearch,
  20901. const bool recursive,
  20902. const File& deadMansPedalFile_)
  20903. : list (listToAddTo),
  20904. format (formatToLookFor),
  20905. deadMansPedalFile (deadMansPedalFile_),
  20906. nextIndex (0),
  20907. progress (0)
  20908. {
  20909. directoriesToSearch.removeRedundantPaths();
  20910. for (int j = 0; j < directoriesToSearch.getNumPaths(); ++j)
  20911. recursiveFileSearch (directoriesToSearch [j], recursive);
  20912. // If any plugins have crashed recently when being loaded, move them to the
  20913. // end of the list to give the others a chance to load correctly..
  20914. const StringArray crashedPlugins (getDeadMansPedalFile());
  20915. for (int i = 0; i < crashedPlugins.size(); ++i)
  20916. {
  20917. const File f (crashedPlugins[i]);
  20918. for (int j = filesToScan.size(); --j >= 0;)
  20919. if (f == *filesToScan.getUnchecked (j))
  20920. filesToScan.move (j, -1);
  20921. }
  20922. }
  20923. void PluginDirectoryScanner::recursiveFileSearch (const File& dir, const bool recursive)
  20924. {
  20925. // avoid allowing the dir iterator to be recursive, because we want to avoid letting it delve inside
  20926. // .component or .vst directories.
  20927. DirectoryIterator iter (dir, false, "*", File::findFilesAndDirectories);
  20928. while (iter.next())
  20929. {
  20930. const File f (iter.getFile());
  20931. bool isPlugin = false;
  20932. if (format.fileMightContainThisPluginType (f))
  20933. {
  20934. isPlugin = true;
  20935. filesToScan.add (new File (f));
  20936. }
  20937. if (recursive && (! isPlugin) && f.isDirectory())
  20938. recursiveFileSearch (f, true);
  20939. }
  20940. }
  20941. PluginDirectoryScanner::~PluginDirectoryScanner()
  20942. {
  20943. }
  20944. const File PluginDirectoryScanner::getNextPluginFileThatWillBeScanned() const throw()
  20945. {
  20946. File* const file = filesToScan [nextIndex];
  20947. if (file != 0)
  20948. return *file;
  20949. return File::nonexistent;
  20950. }
  20951. bool PluginDirectoryScanner::scanNextFile (const bool dontRescanIfAlreadyInList)
  20952. {
  20953. File* const file = filesToScan [nextIndex];
  20954. if (file != 0)
  20955. {
  20956. if (! list.isListingUpToDate (*file))
  20957. {
  20958. OwnedArray <PluginDescription> typesFound;
  20959. // Add this plugin to the end of the dead-man's pedal list in case it crashes...
  20960. StringArray crashedPlugins (getDeadMansPedalFile());
  20961. crashedPlugins.removeString (file->getFullPathName());
  20962. crashedPlugins.add (file->getFullPathName());
  20963. setDeadMansPedalFile (crashedPlugins);
  20964. list.scanAndAddFile (*file,
  20965. dontRescanIfAlreadyInList,
  20966. typesFound);
  20967. // Managed to load without crashing, so remove it from the dead-man's-pedal..
  20968. crashedPlugins.removeString (file->getFullPathName());
  20969. setDeadMansPedalFile (crashedPlugins);
  20970. if (typesFound.size() == 0)
  20971. failedFiles.add (file->getFullPathName());
  20972. }
  20973. ++nextIndex;
  20974. progress = nextIndex / (float) filesToScan.size();
  20975. }
  20976. return nextIndex < filesToScan.size();
  20977. }
  20978. const StringArray PluginDirectoryScanner::getDeadMansPedalFile() throw()
  20979. {
  20980. StringArray lines;
  20981. if (deadMansPedalFile != File::nonexistent)
  20982. {
  20983. lines.addLines (deadMansPedalFile.loadFileAsString());
  20984. lines.removeEmptyStrings();
  20985. }
  20986. return lines;
  20987. }
  20988. void PluginDirectoryScanner::setDeadMansPedalFile (const StringArray& newContents) throw()
  20989. {
  20990. if (deadMansPedalFile != File::nonexistent)
  20991. deadMansPedalFile.replaceWithText (newContents.joinIntoString ("\n"), true, true);
  20992. }
  20993. END_JUCE_NAMESPACE
  20994. /********* End of inlined file: juce_PluginDirectoryScanner.cpp *********/
  20995. /********* Start of inlined file: juce_PluginListComponent.cpp *********/
  20996. BEGIN_JUCE_NAMESPACE
  20997. PluginListComponent::PluginListComponent (KnownPluginList& listToEdit,
  20998. const File& deadMansPedalFile_,
  20999. PropertiesFile* const propertiesToUse_)
  21000. : list (listToEdit),
  21001. deadMansPedalFile (deadMansPedalFile_),
  21002. propertiesToUse (propertiesToUse_)
  21003. {
  21004. addAndMakeVisible (listBox = new ListBox (String::empty, this));
  21005. addAndMakeVisible (optionsButton = new TextButton ("Options..."));
  21006. optionsButton->addButtonListener (this);
  21007. optionsButton->setTriggeredOnMouseDown (true);
  21008. setSize (400, 600);
  21009. list.addChangeListener (this);
  21010. }
  21011. PluginListComponent::~PluginListComponent()
  21012. {
  21013. list.removeChangeListener (this);
  21014. deleteAllChildren();
  21015. }
  21016. void PluginListComponent::resized()
  21017. {
  21018. listBox->setBounds (0, 0, getWidth(), getHeight() - 30);
  21019. optionsButton->changeWidthToFitText (24);
  21020. optionsButton->setTopLeftPosition (8, getHeight() - 28);
  21021. }
  21022. void PluginListComponent::changeListenerCallback (void*)
  21023. {
  21024. listBox->updateContent();
  21025. listBox->repaint();
  21026. }
  21027. int PluginListComponent::getNumRows()
  21028. {
  21029. return list.getNumTypes();
  21030. }
  21031. void PluginListComponent::paintListBoxItem (int row,
  21032. Graphics& g,
  21033. int width, int height,
  21034. bool rowIsSelected)
  21035. {
  21036. if (rowIsSelected)
  21037. g.fillAll (findColour (TextEditor::highlightColourId));
  21038. const PluginDescription* const pd = list.getType (row);
  21039. if (pd != 0)
  21040. {
  21041. GlyphArrangement ga;
  21042. ga.addCurtailedLineOfText (Font (height * 0.7f, Font::bold), pd->name, 8.0f, height * 0.8f, width - 10.0f, true);
  21043. g.setColour (Colours::black);
  21044. ga.draw (g);
  21045. float x, y, r, b;
  21046. ga.getBoundingBox (0, -1, x, y, r, b, false);
  21047. String desc;
  21048. desc << pd->pluginFormatName
  21049. << (pd->isInstrument ? " instrument" : " effect")
  21050. << " - "
  21051. << pd->numInputChannels << (pd->numInputChannels == 1 ? " in" : " ins")
  21052. << " / "
  21053. << pd->numOutputChannels << (pd->numOutputChannels == 1 ? " out" : " outs");
  21054. if (pd->manufacturerName.isNotEmpty())
  21055. desc << " - " << pd->manufacturerName;
  21056. if (pd->version.isNotEmpty())
  21057. desc << " - " << pd->version;
  21058. if (pd->category.isNotEmpty())
  21059. desc << " - category: '" << pd->category << '\'';
  21060. g.setColour (Colours::grey);
  21061. ga.clear();
  21062. ga.addCurtailedLineOfText (Font (height * 0.6f), desc, r + 10.0f, height * 0.8f, width - r - 12.0f, true);
  21063. ga.draw (g);
  21064. }
  21065. }
  21066. void PluginListComponent::deleteKeyPressed (int lastRowSelected)
  21067. {
  21068. list.removeType (lastRowSelected);
  21069. }
  21070. void PluginListComponent::buttonClicked (Button* b)
  21071. {
  21072. if (optionsButton == b)
  21073. {
  21074. PopupMenu menu;
  21075. menu.addItem (1, TRANS("Clear list"));
  21076. menu.addItem (5, TRANS("Remove selected plugin from list"), listBox->getNumSelectedRows() > 0);
  21077. menu.addItem (6, TRANS("Show folder containing selected plugin"), listBox->getNumSelectedRows() > 0);
  21078. menu.addItem (7, TRANS("Remove any plugins whose files no longer exist"));
  21079. menu.addSeparator();
  21080. menu.addItem (2, TRANS("Sort alphabetically"));
  21081. menu.addItem (3, TRANS("Sort by category"));
  21082. menu.addItem (4, TRANS("Sort by manufacturer"));
  21083. menu.addSeparator();
  21084. for (int i = 0; i < AudioPluginFormatManager::getInstance()->getNumFormats(); ++i)
  21085. {
  21086. AudioPluginFormat* const format = AudioPluginFormatManager::getInstance()->getFormat (i);
  21087. if (format->getDefaultLocationsToSearch().getNumPaths() > 0)
  21088. menu.addItem (10 + i, "Scan for new or updated " + format->getName() + " plugins...");
  21089. }
  21090. const int r = menu.showAt (optionsButton);
  21091. if (r == 1)
  21092. {
  21093. list.clear();
  21094. }
  21095. else if (r == 2)
  21096. {
  21097. list.sort (KnownPluginList::sortAlphabetically);
  21098. }
  21099. else if (r == 3)
  21100. {
  21101. list.sort (KnownPluginList::sortByCategory);
  21102. }
  21103. else if (r == 4)
  21104. {
  21105. list.sort (KnownPluginList::sortByManufacturer);
  21106. }
  21107. else if (r == 5)
  21108. {
  21109. const SparseSet <int> selected (listBox->getSelectedRows());
  21110. for (int i = list.getNumTypes(); --i >= 0;)
  21111. if (selected.contains (i))
  21112. list.removeType (i);
  21113. }
  21114. else if (r == 6)
  21115. {
  21116. const PluginDescription* const desc = list.getType (listBox->getSelectedRow());
  21117. if (desc != 0)
  21118. desc->file.getParentDirectory().startAsProcess();
  21119. }
  21120. else if (r == 7)
  21121. {
  21122. for (int i = list.getNumTypes(); --i >= 0;)
  21123. {
  21124. if (list.getType (i)->file != File::nonexistent
  21125. && ! list.getType (i)->file.exists())
  21126. {
  21127. list.removeType (i);
  21128. }
  21129. }
  21130. }
  21131. else if (r != 0)
  21132. {
  21133. typeToScan = r - 10;
  21134. startTimer (1);
  21135. }
  21136. }
  21137. }
  21138. void PluginListComponent::timerCallback()
  21139. {
  21140. stopTimer();
  21141. scanFor (AudioPluginFormatManager::getInstance()->getFormat (typeToScan));
  21142. }
  21143. bool PluginListComponent::isInterestedInFileDrag (const StringArray& /*files*/)
  21144. {
  21145. return true;
  21146. }
  21147. void PluginListComponent::filesDropped (const StringArray& files, int, int)
  21148. {
  21149. OwnedArray <PluginDescription> typesFound;
  21150. list.scanAndAddDragAndDroppedFiles (files, typesFound);
  21151. }
  21152. void PluginListComponent::scanFor (AudioPluginFormat* format)
  21153. {
  21154. if (format == 0)
  21155. return;
  21156. FileSearchPath path (format->getDefaultLocationsToSearch());
  21157. if (propertiesToUse != 0)
  21158. path = propertiesToUse->getValue ("lastPluginScanPath_" + format->getName(), path.toString());
  21159. {
  21160. AlertWindow aw (TRANS("Select folders to scan..."), String::empty, AlertWindow::NoIcon);
  21161. FileSearchPathListComponent pathList;
  21162. pathList.setSize (500, 300);
  21163. pathList.setPath (path);
  21164. aw.addCustomComponent (&pathList);
  21165. aw.addButton (TRANS("Scan"), 1, KeyPress::returnKey);
  21166. aw.addButton (TRANS("Cancel"), 0, KeyPress (KeyPress::escapeKey));
  21167. if (aw.runModalLoop() == 0)
  21168. return;
  21169. path = pathList.getPath();
  21170. }
  21171. if (propertiesToUse != 0)
  21172. {
  21173. propertiesToUse->setValue ("lastPluginScanPath_" + format->getName(), path.toString());
  21174. propertiesToUse->saveIfNeeded();
  21175. }
  21176. double progress = 0.0;
  21177. AlertWindow aw (TRANS("Scanning for plugins..."),
  21178. TRANS("Searching for all possible plugin files..."), AlertWindow::NoIcon);
  21179. aw.addButton (TRANS("Cancel"), 0, KeyPress (KeyPress::escapeKey));
  21180. aw.addProgressBarComponent (progress);
  21181. aw.enterModalState();
  21182. MessageManager::getInstance()->dispatchPendingMessages();
  21183. PluginDirectoryScanner scanner (list, *format, path, true, deadMansPedalFile);
  21184. for (;;)
  21185. {
  21186. aw.setMessage (TRANS("Testing:\n\n")
  21187. + scanner.getNextPluginFileThatWillBeScanned().getFileName());
  21188. MessageManager::getInstance()->dispatchPendingMessages (500);
  21189. if (! scanner.scanNextFile (true))
  21190. break;
  21191. if (! aw.isCurrentlyModal())
  21192. break;
  21193. progress = scanner.getProgress();
  21194. }
  21195. if (scanner.getFailedFiles().size() > 0)
  21196. {
  21197. StringArray shortNames;
  21198. for (int i = 0; i < scanner.getFailedFiles().size(); ++i)
  21199. shortNames.add (File (scanner.getFailedFiles()[i]).getFileName());
  21200. AlertWindow::showMessageBox (AlertWindow::InfoIcon,
  21201. TRANS("Scan complete"),
  21202. TRANS("Note that the following files appeared to be plugin files, but failed to load correctly:\n\n")
  21203. + shortNames.joinIntoString (", "));
  21204. }
  21205. }
  21206. END_JUCE_NAMESPACE
  21207. /********* End of inlined file: juce_PluginListComponent.cpp *********/
  21208. /********* Start of inlined file: juce_AudioUnitPluginFormat.cpp *********/
  21209. #if JUCE_PLUGINHOST_AU && (! (defined (LINUX) || defined (_WIN32)))
  21210. #include <Carbon/Carbon.h>
  21211. #include <AudioToolbox/AudioToolbox.h>
  21212. #include <AudioUnit/AudioUnitCarbonView.h>
  21213. BEGIN_JUCE_NAMESPACE
  21214. #if JUCE_MAC
  21215. extern void juce_callAnyTimersSynchronously();
  21216. extern bool juce_isHIViewCreatedByJuce (HIViewRef view);
  21217. extern bool juce_isWindowCreatedByJuce (WindowRef window);
  21218. #if MACOS_10_3_OR_EARLIER
  21219. #define kAudioUnitType_Generator 'augn'
  21220. #endif
  21221. // Change this to disable logging of various activities
  21222. #ifndef AU_LOGGING
  21223. #define AU_LOGGING 1
  21224. #endif
  21225. #if AU_LOGGING
  21226. #define log(a) Logger::writeToLog(a);
  21227. #else
  21228. #define log(a)
  21229. #endif
  21230. static int insideCallback = 0;
  21231. class AudioUnitPluginWindow;
  21232. class AudioUnitPluginInstance : public AudioPluginInstance
  21233. {
  21234. public:
  21235. ~AudioUnitPluginInstance();
  21236. // AudioPluginInstance methods:
  21237. void fillInPluginDescription (PluginDescription& desc) const
  21238. {
  21239. desc.name = pluginName;
  21240. desc.file = file;
  21241. desc.uid = ((int) componentDesc.componentType)
  21242. ^ ((int) componentDesc.componentSubType)
  21243. ^ ((int) componentDesc.componentManufacturer);
  21244. desc.lastFileModTime = file.getLastModificationTime();
  21245. desc.pluginFormatName = "AudioUnit";
  21246. desc.category = getCategory();
  21247. desc.manufacturerName = manufacturer;
  21248. desc.version = version;
  21249. desc.numInputChannels = getNumInputChannels();
  21250. desc.numOutputChannels = getNumOutputChannels();
  21251. desc.isInstrument = (componentDesc.componentType == kAudioUnitType_MusicDevice);
  21252. }
  21253. const String getName() const { return pluginName; }
  21254. bool acceptsMidi() const { return wantsMidiMessages; }
  21255. bool producesMidi() const { return false; }
  21256. // AudioProcessor methods:
  21257. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  21258. void releaseResources();
  21259. void processBlock (AudioSampleBuffer& buffer,
  21260. MidiBuffer& midiMessages);
  21261. AudioProcessorEditor* createEditor();
  21262. const String getInputChannelName (const int index) const;
  21263. bool isInputChannelStereoPair (int index) const;
  21264. const String getOutputChannelName (const int index) const;
  21265. bool isOutputChannelStereoPair (int index) const;
  21266. int getNumParameters();
  21267. float getParameter (int index);
  21268. void setParameter (int index, float newValue);
  21269. const String getParameterName (int index);
  21270. const String getParameterText (int index);
  21271. bool isParameterAutomatable (int index) const;
  21272. int getNumPrograms();
  21273. int getCurrentProgram();
  21274. void setCurrentProgram (int index);
  21275. const String getProgramName (int index);
  21276. void changeProgramName (int index, const String& newName);
  21277. void getStateInformation (MemoryBlock& destData);
  21278. void getCurrentProgramStateInformation (MemoryBlock& destData);
  21279. void setStateInformation (const void* data, int sizeInBytes);
  21280. void setCurrentProgramStateInformation (const void* data, int sizeInBytes);
  21281. juce_UseDebuggingNewOperator
  21282. private:
  21283. friend class AudioUnitPluginWindow;
  21284. friend class AudioUnitPluginFormat;
  21285. ComponentDescription componentDesc;
  21286. String pluginName, manufacturer, version;
  21287. File file;
  21288. CriticalSection lock;
  21289. bool initialised, wantsMidiMessages, wasPlaying;
  21290. AudioBufferList* outputBufferList;
  21291. AudioTimeStamp timeStamp;
  21292. AudioSampleBuffer* currentBuffer;
  21293. AudioUnit audioUnit;
  21294. Array <int> parameterIds;
  21295. bool getComponentDescFromFile (const File& file);
  21296. void initialise();
  21297. OSStatus renderGetInput (AudioUnitRenderActionFlags* ioActionFlags,
  21298. const AudioTimeStamp* inTimeStamp,
  21299. UInt32 inBusNumber,
  21300. UInt32 inNumberFrames,
  21301. AudioBufferList* ioData) const;
  21302. static OSStatus renderGetInputCallback (void* inRefCon,
  21303. AudioUnitRenderActionFlags* ioActionFlags,
  21304. const AudioTimeStamp* inTimeStamp,
  21305. UInt32 inBusNumber,
  21306. UInt32 inNumberFrames,
  21307. AudioBufferList* ioData)
  21308. {
  21309. return ((AudioUnitPluginInstance*) inRefCon)
  21310. ->renderGetInput (ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, ioData);
  21311. }
  21312. OSStatus getBeatAndTempo (Float64* outCurrentBeat, Float64* outCurrentTempo) const;
  21313. OSStatus getMusicalTimeLocation (UInt32* outDeltaSampleOffsetToNextBeat, Float32* outTimeSig_Numerator,
  21314. UInt32* outTimeSig_Denominator, Float64* outCurrentMeasureDownBeat) const;
  21315. OSStatus getTransportState (Boolean* outIsPlaying, Boolean* outTransportStateChanged,
  21316. Float64* outCurrentSampleInTimeLine, Boolean* outIsCycling,
  21317. Float64* outCycleStartBeat, Float64* outCycleEndBeat);
  21318. static OSStatus getBeatAndTempoCallback (void* inHostUserData, Float64* outCurrentBeat, Float64* outCurrentTempo)
  21319. {
  21320. return ((AudioUnitPluginInstance*) inHostUserData)->getBeatAndTempo (outCurrentBeat, outCurrentTempo);
  21321. }
  21322. static OSStatus getMusicalTimeLocationCallback (void* inHostUserData, UInt32* outDeltaSampleOffsetToNextBeat,
  21323. Float32* outTimeSig_Numerator, UInt32* outTimeSig_Denominator,
  21324. Float64* outCurrentMeasureDownBeat)
  21325. {
  21326. return ((AudioUnitPluginInstance*) inHostUserData)
  21327. ->getMusicalTimeLocation (outDeltaSampleOffsetToNextBeat, outTimeSig_Numerator,
  21328. outTimeSig_Denominator, outCurrentMeasureDownBeat);
  21329. }
  21330. static OSStatus getTransportStateCallback (void* inHostUserData, Boolean* outIsPlaying, Boolean* outTransportStateChanged,
  21331. Float64* outCurrentSampleInTimeLine, Boolean* outIsCycling,
  21332. Float64* outCycleStartBeat, Float64* outCycleEndBeat)
  21333. {
  21334. return ((AudioUnitPluginInstance*) inHostUserData)
  21335. ->getTransportState (outIsPlaying, outTransportStateChanged,
  21336. outCurrentSampleInTimeLine, outIsCycling,
  21337. outCycleStartBeat, outCycleEndBeat);
  21338. }
  21339. void getNumChannels (int& numIns, int& numOuts)
  21340. {
  21341. numIns = 0;
  21342. numOuts = 0;
  21343. AUChannelInfo supportedChannels [128];
  21344. UInt32 supportedChannelsSize = sizeof (supportedChannels);
  21345. if (AudioUnitGetProperty (audioUnit, kAudioUnitProperty_SupportedNumChannels, kAudioUnitScope_Global,
  21346. 0, supportedChannels, &supportedChannelsSize) == noErr
  21347. && supportedChannelsSize > 0)
  21348. {
  21349. for (int i = 0; i < supportedChannelsSize / sizeof (AUChannelInfo); ++i)
  21350. {
  21351. numIns = jmax (numIns, supportedChannels[i].inChannels);
  21352. numOuts = jmax (numOuts, supportedChannels[i].outChannels);
  21353. }
  21354. }
  21355. else
  21356. {
  21357. // (this really means the plugin will take any number of ins/outs as long
  21358. // as they are the same)
  21359. numIns = numOuts = 2;
  21360. }
  21361. }
  21362. const String getCategory() const;
  21363. AudioUnitPluginInstance (const File& file);
  21364. };
  21365. AudioUnitPluginInstance::AudioUnitPluginInstance (const File& file_)
  21366. : file (file_),
  21367. initialised (false),
  21368. wantsMidiMessages (false),
  21369. audioUnit (0),
  21370. outputBufferList (0),
  21371. currentBuffer (0)
  21372. {
  21373. try
  21374. {
  21375. ++insideCallback;
  21376. log (T("Opening AU: ") + file.getFullPathName());
  21377. if (getComponentDescFromFile (file))
  21378. {
  21379. ComponentRecord* const comp = FindNextComponent (0, &componentDesc);
  21380. if (comp != 0)
  21381. {
  21382. audioUnit = (AudioUnit) OpenComponent (comp);
  21383. wantsMidiMessages = componentDesc.componentType == kAudioUnitType_MusicDevice
  21384. || componentDesc.componentType == kAudioUnitType_MusicEffect;
  21385. }
  21386. }
  21387. --insideCallback;
  21388. }
  21389. catch (...)
  21390. {
  21391. --insideCallback;
  21392. }
  21393. }
  21394. AudioUnitPluginInstance::~AudioUnitPluginInstance()
  21395. {
  21396. {
  21397. const ScopedLock sl (lock);
  21398. jassert (insideCallback == 0);
  21399. if (audioUnit != 0)
  21400. {
  21401. AudioUnitUninitialize (audioUnit);
  21402. CloseComponent (audioUnit);
  21403. audioUnit = 0;
  21404. }
  21405. }
  21406. juce_free (outputBufferList);
  21407. }
  21408. bool AudioUnitPluginInstance::getComponentDescFromFile (const File& file)
  21409. {
  21410. zerostruct (componentDesc);
  21411. if (! file.hasFileExtension (T(".component")))
  21412. return false;
  21413. const String filename (file.getFullPathName());
  21414. const char* const utf8 = filename.toUTF8();
  21415. CFURLRef url = CFURLCreateFromFileSystemRepresentation (0, (const UInt8*) utf8,
  21416. strlen (utf8), file.isDirectory());
  21417. if (url != 0)
  21418. {
  21419. CFBundleRef bundleRef = CFBundleCreate (kCFAllocatorDefault, url);
  21420. CFRelease (url);
  21421. if (bundleRef != 0)
  21422. {
  21423. CFTypeRef name = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleName"));
  21424. if (name != 0 && CFGetTypeID (name) == CFStringGetTypeID())
  21425. pluginName = PlatformUtilities::cfStringToJuceString ((CFStringRef) name);
  21426. if (pluginName.isEmpty())
  21427. pluginName = file.getFileNameWithoutExtension();
  21428. CFTypeRef versionString = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleVersion"));
  21429. if (versionString != 0 && CFGetTypeID (versionString) == CFStringGetTypeID())
  21430. version = PlatformUtilities::cfStringToJuceString ((CFStringRef) versionString);
  21431. CFTypeRef manuString = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleGetInfoString"));
  21432. if (manuString != 0 && CFGetTypeID (manuString) == CFStringGetTypeID())
  21433. manufacturer = PlatformUtilities::cfStringToJuceString ((CFStringRef) manuString);
  21434. short resFileId = CFBundleOpenBundleResourceMap (bundleRef);
  21435. UseResFile (resFileId);
  21436. for (int i = 1; i <= Count1Resources ('thng'); ++i)
  21437. {
  21438. Handle h = Get1IndResource ('thng', i);
  21439. if (h != 0)
  21440. {
  21441. HLock (h);
  21442. const uint32* const types = (const uint32*) *h;
  21443. if (types[0] == kAudioUnitType_MusicDevice
  21444. || types[0] == kAudioUnitType_MusicEffect
  21445. || types[0] == kAudioUnitType_Effect
  21446. || types[0] == kAudioUnitType_Generator
  21447. || types[0] == kAudioUnitType_Panner)
  21448. {
  21449. componentDesc.componentType = types[0];
  21450. componentDesc.componentSubType = types[1];
  21451. componentDesc.componentManufacturer = types[2];
  21452. break;
  21453. }
  21454. HUnlock (h);
  21455. ReleaseResource (h);
  21456. }
  21457. }
  21458. CFBundleCloseBundleResourceMap (bundleRef, resFileId);
  21459. CFRelease (bundleRef);
  21460. }
  21461. }
  21462. return componentDesc.componentType != 0 && componentDesc.componentSubType != 0;
  21463. }
  21464. void AudioUnitPluginInstance::initialise()
  21465. {
  21466. if (initialised || audioUnit == 0)
  21467. return;
  21468. log (T("Initialising AU: ") + pluginName);
  21469. parameterIds.clear();
  21470. {
  21471. UInt32 paramListSize = 0;
  21472. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_ParameterList, kAudioUnitScope_Global,
  21473. 0, 0, &paramListSize);
  21474. if (paramListSize > 0)
  21475. {
  21476. parameterIds.insertMultiple (0, 0, paramListSize / sizeof (int));
  21477. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_ParameterList, kAudioUnitScope_Global,
  21478. 0, &parameterIds.getReference(0), &paramListSize);
  21479. }
  21480. }
  21481. {
  21482. AURenderCallbackStruct info;
  21483. zerostruct (info);
  21484. info.inputProcRefCon = this;
  21485. info.inputProc = renderGetInputCallback;
  21486. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input,
  21487. 0, &info, sizeof (info));
  21488. }
  21489. {
  21490. HostCallbackInfo info;
  21491. zerostruct (info);
  21492. info.hostUserData = this;
  21493. info.beatAndTempoProc = getBeatAndTempoCallback;
  21494. info.musicalTimeLocationProc = getMusicalTimeLocationCallback;
  21495. info.transportStateProc = getTransportStateCallback;
  21496. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_HostCallbacks, kAudioUnitScope_Global,
  21497. 0, &info, sizeof (info));
  21498. }
  21499. int numIns, numOuts;
  21500. getNumChannels (numIns, numOuts);
  21501. setPlayConfigDetails (numIns, numOuts, 0, 0);
  21502. initialised = AudioUnitInitialize (audioUnit) == noErr;
  21503. setLatencySamples (0);
  21504. }
  21505. void AudioUnitPluginInstance::prepareToPlay (double sampleRate_,
  21506. int samplesPerBlockExpected)
  21507. {
  21508. initialise();
  21509. if (initialised)
  21510. {
  21511. int numIns, numOuts;
  21512. getNumChannels (numIns, numOuts);
  21513. setPlayConfigDetails (numIns, numOuts, sampleRate_, samplesPerBlockExpected);
  21514. Float64 latencySecs = 0.0;
  21515. UInt32 latencySize = sizeof (latencySecs);
  21516. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_Latency, kAudioUnitScope_Global,
  21517. 0, &latencySecs, &latencySize);
  21518. setLatencySamples (roundDoubleToInt (latencySecs * sampleRate_));
  21519. AudioUnitReset (audioUnit, kAudioUnitScope_Input, 0);
  21520. AudioUnitReset (audioUnit, kAudioUnitScope_Output, 0);
  21521. AudioUnitReset (audioUnit, kAudioUnitScope_Global, 0);
  21522. AudioStreamBasicDescription stream;
  21523. zerostruct (stream);
  21524. stream.mSampleRate = sampleRate_;
  21525. stream.mFormatID = kAudioFormatLinearPCM;
  21526. stream.mFormatFlags = kAudioFormatFlagsNativeFloatPacked | kAudioFormatFlagIsNonInterleaved;
  21527. stream.mFramesPerPacket = 1;
  21528. stream.mBytesPerPacket = 4;
  21529. stream.mBytesPerFrame = 4;
  21530. stream.mBitsPerChannel = 32;
  21531. stream.mChannelsPerFrame = numIns;
  21532. OSStatus err = AudioUnitSetProperty (audioUnit,
  21533. kAudioUnitProperty_StreamFormat,
  21534. kAudioUnitScope_Input,
  21535. 0, &stream, sizeof (stream));
  21536. stream.mChannelsPerFrame = numOuts;
  21537. err = AudioUnitSetProperty (audioUnit,
  21538. kAudioUnitProperty_StreamFormat,
  21539. kAudioUnitScope_Output,
  21540. 0, &stream, sizeof (stream));
  21541. juce_free (outputBufferList);
  21542. outputBufferList = (AudioBufferList*) juce_calloc (sizeof (AudioBufferList) + sizeof (AudioBuffer) * (numOuts + 1));
  21543. outputBufferList->mNumberBuffers = numOuts;
  21544. for (int i = numOuts; --i >= 0;)
  21545. outputBufferList->mBuffers[i].mNumberChannels = 1;
  21546. zerostruct (timeStamp);
  21547. timeStamp.mSampleTime = 0;
  21548. timeStamp.mHostTime = AudioGetCurrentHostTime();
  21549. timeStamp.mFlags = kAudioTimeStampSampleTimeValid | kAudioTimeStampHostTimeValid;
  21550. currentBuffer = 0;
  21551. wasPlaying = false;
  21552. }
  21553. }
  21554. void AudioUnitPluginInstance::releaseResources()
  21555. {
  21556. if (initialised)
  21557. {
  21558. AudioUnitReset (audioUnit, kAudioUnitScope_Input, 0);
  21559. AudioUnitReset (audioUnit, kAudioUnitScope_Output, 0);
  21560. AudioUnitReset (audioUnit, kAudioUnitScope_Global, 0);
  21561. juce_free (outputBufferList);
  21562. outputBufferList = 0;
  21563. currentBuffer = 0;
  21564. }
  21565. }
  21566. OSStatus AudioUnitPluginInstance::renderGetInput (AudioUnitRenderActionFlags* ioActionFlags,
  21567. const AudioTimeStamp* inTimeStamp,
  21568. UInt32 inBusNumber,
  21569. UInt32 inNumberFrames,
  21570. AudioBufferList* ioData) const
  21571. {
  21572. if (inBusNumber == 0
  21573. && currentBuffer != 0)
  21574. {
  21575. jassert (inNumberFrames == currentBuffer->getNumSamples()); // if this ever happens, might need to add extra handling
  21576. for (int i = 0; i < ioData->mNumberBuffers; ++i)
  21577. {
  21578. if (i < currentBuffer->getNumChannels())
  21579. {
  21580. memcpy (ioData->mBuffers[i].mData,
  21581. currentBuffer->getSampleData (i, 0),
  21582. sizeof (float) * inNumberFrames);
  21583. }
  21584. else
  21585. {
  21586. zeromem (ioData->mBuffers[i].mData, sizeof (float) * inNumberFrames);
  21587. }
  21588. }
  21589. }
  21590. return noErr;
  21591. }
  21592. void AudioUnitPluginInstance::processBlock (AudioSampleBuffer& buffer,
  21593. MidiBuffer& midiMessages)
  21594. {
  21595. const int numSamples = buffer.getNumSamples();
  21596. if (initialised)
  21597. {
  21598. AudioUnitRenderActionFlags flags = 0;
  21599. timeStamp.mHostTime = AudioGetCurrentHostTime();
  21600. for (int i = getNumOutputChannels(); --i >= 0;)
  21601. {
  21602. outputBufferList->mBuffers[i].mDataByteSize = sizeof (float) * numSamples;
  21603. outputBufferList->mBuffers[i].mData = buffer.getSampleData (i, 0);
  21604. }
  21605. currentBuffer = &buffer;
  21606. if (wantsMidiMessages)
  21607. {
  21608. const uint8* midiEventData;
  21609. int midiEventSize, midiEventPosition;
  21610. MidiBuffer::Iterator i (midiMessages);
  21611. while (i.getNextEvent (midiEventData, midiEventSize, midiEventPosition))
  21612. {
  21613. if (midiEventSize <= 3)
  21614. MusicDeviceMIDIEvent (audioUnit,
  21615. midiEventData[0], midiEventData[1], midiEventData[2],
  21616. midiEventPosition);
  21617. else
  21618. MusicDeviceSysEx (audioUnit, midiEventData, midiEventSize);
  21619. }
  21620. midiMessages.clear();
  21621. }
  21622. AudioUnitRender (audioUnit, &flags, &timeStamp,
  21623. 0, numSamples, outputBufferList);
  21624. timeStamp.mSampleTime += numSamples;
  21625. }
  21626. else
  21627. {
  21628. // Not initialised, so just bypass..
  21629. for (int i = getNumInputChannels(); i < getNumOutputChannels(); ++i)
  21630. buffer.clear (i, 0, buffer.getNumSamples());
  21631. }
  21632. }
  21633. OSStatus AudioUnitPluginInstance::getBeatAndTempo (Float64* outCurrentBeat, Float64* outCurrentTempo) const
  21634. {
  21635. AudioPlayHead* const ph = getPlayHead();
  21636. AudioPlayHead::CurrentPositionInfo result;
  21637. if (ph != 0 && ph->getCurrentPosition (result))
  21638. {
  21639. *outCurrentBeat = result.ppqPosition;
  21640. *outCurrentTempo = result.bpm;
  21641. }
  21642. else
  21643. {
  21644. *outCurrentBeat = 0;
  21645. *outCurrentTempo = 120.0;
  21646. }
  21647. return noErr;
  21648. }
  21649. OSStatus AudioUnitPluginInstance::getMusicalTimeLocation (UInt32* outDeltaSampleOffsetToNextBeat,
  21650. Float32* outTimeSig_Numerator,
  21651. UInt32* outTimeSig_Denominator,
  21652. Float64* outCurrentMeasureDownBeat) const
  21653. {
  21654. AudioPlayHead* const ph = getPlayHead();
  21655. AudioPlayHead::CurrentPositionInfo result;
  21656. if (ph != 0 && ph->getCurrentPosition (result))
  21657. {
  21658. *outTimeSig_Numerator = result.timeSigNumerator;
  21659. *outTimeSig_Denominator = result.timeSigDenominator;
  21660. *outDeltaSampleOffsetToNextBeat = 0; //xxx
  21661. *outCurrentMeasureDownBeat = result.ppqPositionOfLastBarStart; //xxx wrong
  21662. }
  21663. else
  21664. {
  21665. *outDeltaSampleOffsetToNextBeat = 0;
  21666. *outTimeSig_Numerator = 4;
  21667. *outTimeSig_Denominator = 4;
  21668. *outCurrentMeasureDownBeat = 0;
  21669. }
  21670. return noErr;
  21671. }
  21672. OSStatus AudioUnitPluginInstance::getTransportState (Boolean* outIsPlaying,
  21673. Boolean* outTransportStateChanged,
  21674. Float64* outCurrentSampleInTimeLine,
  21675. Boolean* outIsCycling,
  21676. Float64* outCycleStartBeat,
  21677. Float64* outCycleEndBeat)
  21678. {
  21679. AudioPlayHead* const ph = getPlayHead();
  21680. AudioPlayHead::CurrentPositionInfo result;
  21681. if (ph != 0 && ph->getCurrentPosition (result))
  21682. {
  21683. *outIsPlaying = result.isPlaying;
  21684. *outTransportStateChanged = result.isPlaying != wasPlaying;
  21685. wasPlaying = result.isPlaying;
  21686. *outCurrentSampleInTimeLine = roundDoubleToInt (result.timeInSeconds * getSampleRate());
  21687. *outIsCycling = false;
  21688. *outCycleStartBeat = 0;
  21689. *outCycleEndBeat = 0;
  21690. }
  21691. else
  21692. {
  21693. *outIsPlaying = false;
  21694. *outTransportStateChanged = false;
  21695. *outCurrentSampleInTimeLine = 0;
  21696. *outIsCycling = false;
  21697. *outCycleStartBeat = 0;
  21698. *outCycleEndBeat = 0;
  21699. }
  21700. return noErr;
  21701. }
  21702. static VoidArray activeWindows;
  21703. class AudioUnitPluginWindow : public AudioProcessorEditor,
  21704. public Timer
  21705. {
  21706. public:
  21707. AudioUnitPluginWindow (AudioUnitPluginInstance& plugin_)
  21708. : AudioProcessorEditor (&plugin_),
  21709. plugin (plugin_),
  21710. isOpen (false),
  21711. pluginWantsKeys (false),
  21712. wasShowing (false),
  21713. recursiveResize (false),
  21714. viewComponent (0),
  21715. pluginViewRef (0)
  21716. {
  21717. movementWatcher = new CompMovementWatcher (this);
  21718. activeWindows.add (this);
  21719. setOpaque (true);
  21720. setVisible (true);
  21721. setSize (1, 1);
  21722. ComponentDescription viewList [16];
  21723. UInt32 viewListSize = sizeof (viewList);
  21724. AudioUnitGetProperty (plugin.audioUnit, kAudioUnitProperty_GetUIComponentList, kAudioUnitScope_Global,
  21725. 0, &viewList, &viewListSize);
  21726. componentRecord = FindNextComponent (0, &viewList[0]);
  21727. }
  21728. ~AudioUnitPluginWindow()
  21729. {
  21730. deleteAndZero (movementWatcher);
  21731. closePluginWindow();
  21732. activeWindows.removeValue (this);
  21733. plugin.editorBeingDeleted (this);
  21734. }
  21735. bool isValid() const throw() { return componentRecord != 0; }
  21736. void componentMovedOrResized()
  21737. {
  21738. if (recursiveResize)
  21739. return;
  21740. Component* const topComp = getTopLevelComponent();
  21741. if (topComp->getPeer() != 0)
  21742. {
  21743. int x = 0, y = 0;
  21744. relativePositionToOtherComponent (topComp, x, y);
  21745. recursiveResize = true;
  21746. if (pluginViewRef != 0)
  21747. {
  21748. HIRect r;
  21749. r.origin.x = (float) x;
  21750. r.origin.y = (float) y;
  21751. r.size.width = (float) getWidth();
  21752. r.size.height = (float) getHeight();
  21753. HIViewSetFrame (pluginViewRef, &r);
  21754. }
  21755. recursiveResize = false;
  21756. }
  21757. }
  21758. void componentVisibilityChanged()
  21759. {
  21760. const bool isShowingNow = isShowing();
  21761. if (wasShowing != isShowingNow)
  21762. {
  21763. wasShowing = isShowingNow;
  21764. if (isShowingNow)
  21765. openPluginWindow();
  21766. else
  21767. closePluginWindow();
  21768. }
  21769. componentMovedOrResized();
  21770. }
  21771. void componentPeerChanged()
  21772. {
  21773. closePluginWindow();
  21774. openPluginWindow();
  21775. }
  21776. void timerCallback()
  21777. {
  21778. if (pluginViewRef != 0)
  21779. {
  21780. HIRect bounds;
  21781. HIViewGetBounds (pluginViewRef, &bounds);
  21782. const int w = jmax (32, (int) bounds.size.width);
  21783. const int h = jmax (32, (int) bounds.size.height);
  21784. if (w != getWidth() || h != getHeight())
  21785. {
  21786. setSize (w, h);
  21787. startTimer (50);
  21788. }
  21789. else
  21790. {
  21791. startTimer (jlimit (50, 500, getTimerInterval() + 20));
  21792. }
  21793. }
  21794. }
  21795. bool keyStateChanged()
  21796. {
  21797. return pluginWantsKeys;
  21798. }
  21799. bool keyPressed (const KeyPress&)
  21800. {
  21801. return pluginWantsKeys;
  21802. }
  21803. void paint (Graphics& g)
  21804. {
  21805. if (isOpen)
  21806. {
  21807. ComponentPeer* const peer = getPeer();
  21808. if (peer != 0)
  21809. {
  21810. peer->addMaskedRegion (getScreenX() - peer->getScreenX(),
  21811. getScreenY() - peer->getScreenY(),
  21812. getWidth(), getHeight());
  21813. }
  21814. }
  21815. else
  21816. {
  21817. g.fillAll (Colours::black);
  21818. }
  21819. }
  21820. void broughtToFront()
  21821. {
  21822. activeWindows.removeValue (this);
  21823. activeWindows.add (this);
  21824. }
  21825. juce_UseDebuggingNewOperator
  21826. private:
  21827. AudioUnitPluginInstance& plugin;
  21828. bool isOpen, wasShowing, recursiveResize;
  21829. bool pluginWantsKeys;
  21830. ComponentRecord* componentRecord;
  21831. AudioUnitCarbonView viewComponent;
  21832. HIViewRef pluginViewRef;
  21833. void openPluginWindow()
  21834. {
  21835. if (isOpen || getWindowHandle() == 0 || componentRecord == 0)
  21836. return;
  21837. log (T("Opening AU GUI: ") + plugin.getName());
  21838. isOpen = true;
  21839. pluginWantsKeys = true; //xxx any way to find this out? Does it matter?
  21840. viewComponent = (AudioUnitCarbonView) OpenComponent (componentRecord);
  21841. if (viewComponent != 0)
  21842. {
  21843. Float32Point pos = { getScreenX() - getTopLevelComponent()->getScreenX(),
  21844. getScreenY() - getTopLevelComponent()->getScreenY() };
  21845. Float32Point size = { 250, 200 };
  21846. AudioUnitCarbonViewCreate (viewComponent,
  21847. plugin.audioUnit,
  21848. (WindowRef) getWindowHandle(),
  21849. HIViewGetRoot ((WindowRef) getWindowHandle()),
  21850. &pos, &size,
  21851. (ControlRef*) &pluginViewRef);
  21852. }
  21853. timerCallback(); // to set our comp to the right size
  21854. repaint();
  21855. }
  21856. void closePluginWindow()
  21857. {
  21858. stopTimer();
  21859. if (isOpen)
  21860. {
  21861. log (T("Closing AU GUI: ") + plugin.getName());
  21862. isOpen = false;
  21863. if (viewComponent != 0)
  21864. CloseComponent (viewComponent);
  21865. pluginViewRef = 0;
  21866. }
  21867. }
  21868. class CompMovementWatcher : public ComponentMovementWatcher
  21869. {
  21870. public:
  21871. CompMovementWatcher (AudioUnitPluginWindow* const owner_)
  21872. : ComponentMovementWatcher (owner_),
  21873. owner (owner_)
  21874. {
  21875. }
  21876. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  21877. {
  21878. owner->componentMovedOrResized();
  21879. }
  21880. void componentPeerChanged()
  21881. {
  21882. owner->componentPeerChanged();
  21883. }
  21884. void componentVisibilityChanged (Component&)
  21885. {
  21886. owner->componentVisibilityChanged();
  21887. }
  21888. private:
  21889. AudioUnitPluginWindow* const owner;
  21890. };
  21891. CompMovementWatcher* movementWatcher;
  21892. };
  21893. AudioProcessorEditor* AudioUnitPluginInstance::createEditor()
  21894. {
  21895. AudioUnitPluginWindow* w = new AudioUnitPluginWindow (*this);
  21896. if (! w->isValid())
  21897. deleteAndZero (w);
  21898. return w;
  21899. }
  21900. const String AudioUnitPluginInstance::getCategory() const
  21901. {
  21902. const char* result = 0;
  21903. switch (componentDesc.componentType)
  21904. {
  21905. case kAudioUnitType_Effect:
  21906. case kAudioUnitType_MusicEffect:
  21907. result = "Effect";
  21908. break;
  21909. case kAudioUnitType_MusicDevice:
  21910. result = "Synth";
  21911. break;
  21912. case kAudioUnitType_Generator:
  21913. result = "Generator";
  21914. break;
  21915. case kAudioUnitType_Panner:
  21916. result = "Panner";
  21917. break;
  21918. default:
  21919. break;
  21920. }
  21921. return result;
  21922. }
  21923. int AudioUnitPluginInstance::getNumParameters()
  21924. {
  21925. return parameterIds.size();
  21926. }
  21927. float AudioUnitPluginInstance::getParameter (int index)
  21928. {
  21929. const ScopedLock sl (lock);
  21930. Float32 value = 0.0f;
  21931. if (audioUnit != 0 && ((unsigned int) index) < (unsigned int) parameterIds.size())
  21932. {
  21933. AudioUnitGetParameter (audioUnit,
  21934. (UInt32) parameterIds.getUnchecked (index),
  21935. kAudioUnitScope_Global, 0,
  21936. &value);
  21937. }
  21938. return value;
  21939. }
  21940. void AudioUnitPluginInstance::setParameter (int index, float newValue)
  21941. {
  21942. const ScopedLock sl (lock);
  21943. if (audioUnit != 0 && ((unsigned int) index) < (unsigned int) parameterIds.size())
  21944. {
  21945. AudioUnitSetParameter (audioUnit,
  21946. (UInt32) parameterIds.getUnchecked (index),
  21947. kAudioUnitScope_Global, 0,
  21948. newValue, 0);
  21949. }
  21950. }
  21951. const String AudioUnitPluginInstance::getParameterName (int index)
  21952. {
  21953. AudioUnitParameterInfo info;
  21954. zerostruct (info);
  21955. UInt32 sz = sizeof (info);
  21956. String name;
  21957. if (AudioUnitGetProperty (audioUnit,
  21958. kAudioUnitProperty_ParameterInfo,
  21959. kAudioUnitScope_Global,
  21960. parameterIds [index], &info, &sz) == noErr)
  21961. {
  21962. if ((info.flags & kAudioUnitParameterFlag_HasCFNameString) != 0)
  21963. name = PlatformUtilities::cfStringToJuceString (info.cfNameString);
  21964. else
  21965. name = String (info.name, sizeof (info.name));
  21966. }
  21967. return name;
  21968. }
  21969. const String AudioUnitPluginInstance::getParameterText (int index)
  21970. {
  21971. return String (getParameter (index));
  21972. }
  21973. bool AudioUnitPluginInstance::isParameterAutomatable (int index) const
  21974. {
  21975. AudioUnitParameterInfo info;
  21976. UInt32 sz = sizeof (info);
  21977. if (AudioUnitGetProperty (audioUnit,
  21978. kAudioUnitProperty_ParameterInfo,
  21979. kAudioUnitScope_Global,
  21980. parameterIds [index], &info, &sz) == noErr)
  21981. {
  21982. return (info.flags & kAudioUnitParameterFlag_NonRealTime) == 0;
  21983. }
  21984. return true;
  21985. }
  21986. int AudioUnitPluginInstance::getNumPrograms()
  21987. {
  21988. CFArrayRef presets;
  21989. UInt32 sz = sizeof (CFArrayRef);
  21990. int num = 0;
  21991. if (AudioUnitGetProperty (audioUnit,
  21992. kAudioUnitProperty_FactoryPresets,
  21993. kAudioUnitScope_Global,
  21994. 0, &presets, &sz) == noErr)
  21995. {
  21996. num = (int) CFArrayGetCount (presets);
  21997. CFRelease (presets);
  21998. }
  21999. return num;
  22000. }
  22001. int AudioUnitPluginInstance::getCurrentProgram()
  22002. {
  22003. AUPreset current;
  22004. current.presetNumber = 0;
  22005. UInt32 sz = sizeof (AUPreset);
  22006. AudioUnitGetProperty (audioUnit,
  22007. kAudioUnitProperty_FactoryPresets,
  22008. kAudioUnitScope_Global,
  22009. 0, &current, &sz);
  22010. return current.presetNumber;
  22011. }
  22012. void AudioUnitPluginInstance::setCurrentProgram (int newIndex)
  22013. {
  22014. AUPreset current;
  22015. current.presetNumber = newIndex;
  22016. current.presetName = 0;
  22017. AudioUnitSetProperty (audioUnit,
  22018. kAudioUnitProperty_FactoryPresets,
  22019. kAudioUnitScope_Global,
  22020. 0, &current, sizeof (AUPreset));
  22021. }
  22022. const String AudioUnitPluginInstance::getProgramName (int index)
  22023. {
  22024. String s;
  22025. CFArrayRef presets;
  22026. UInt32 sz = sizeof (CFArrayRef);
  22027. if (AudioUnitGetProperty (audioUnit,
  22028. kAudioUnitProperty_FactoryPresets,
  22029. kAudioUnitScope_Global,
  22030. 0, &presets, &sz) == noErr)
  22031. {
  22032. for (CFIndex i = 0; i < CFArrayGetCount (presets); ++i)
  22033. {
  22034. const AUPreset* p = (const AUPreset*) CFArrayGetValueAtIndex (presets, i);
  22035. if (p != 0 && p->presetNumber == index)
  22036. {
  22037. s = PlatformUtilities::cfStringToJuceString (p->presetName);
  22038. break;
  22039. }
  22040. }
  22041. CFRelease (presets);
  22042. }
  22043. return s;
  22044. }
  22045. void AudioUnitPluginInstance::changeProgramName (int index, const String& newName)
  22046. {
  22047. jassertfalse // xxx not implemented!
  22048. }
  22049. const String AudioUnitPluginInstance::getInputChannelName (const int index) const
  22050. {
  22051. if (((unsigned int) index) < (unsigned int) getNumInputChannels())
  22052. return T("Input ") + String (index + 1);
  22053. return String::empty;
  22054. }
  22055. bool AudioUnitPluginInstance::isInputChannelStereoPair (int index) const
  22056. {
  22057. if (((unsigned int) index) >= (unsigned int) getNumInputChannels())
  22058. return false;
  22059. return true;
  22060. }
  22061. const String AudioUnitPluginInstance::getOutputChannelName (const int index) const
  22062. {
  22063. if (((unsigned int) index) < (unsigned int) getNumOutputChannels())
  22064. return T("Output ") + String (index + 1);
  22065. return String::empty;
  22066. }
  22067. bool AudioUnitPluginInstance::isOutputChannelStereoPair (int index) const
  22068. {
  22069. if (((unsigned int) index) >= (unsigned int) getNumOutputChannels())
  22070. return false;
  22071. return true;
  22072. }
  22073. void AudioUnitPluginInstance::getStateInformation (MemoryBlock& destData)
  22074. {
  22075. getCurrentProgramStateInformation (destData);
  22076. }
  22077. void AudioUnitPluginInstance::getCurrentProgramStateInformation (MemoryBlock& destData)
  22078. {
  22079. CFPropertyListRef propertyList = 0;
  22080. UInt32 sz = sizeof (CFPropertyListRef);
  22081. if (AudioUnitGetProperty (audioUnit,
  22082. kAudioUnitProperty_ClassInfo,
  22083. kAudioUnitScope_Global,
  22084. 0, &propertyList, &sz) == noErr)
  22085. {
  22086. CFWriteStreamRef stream = CFWriteStreamCreateWithAllocatedBuffers (kCFAllocatorDefault, kCFAllocatorDefault);
  22087. CFWriteStreamOpen (stream);
  22088. CFIndex bytesWritten = CFPropertyListWriteToStream (propertyList, stream, kCFPropertyListBinaryFormat_v1_0, 0);
  22089. CFWriteStreamClose (stream);
  22090. CFDataRef data = (CFDataRef) CFWriteStreamCopyProperty (stream, kCFStreamPropertyDataWritten);
  22091. destData.setSize (bytesWritten);
  22092. destData.copyFrom (CFDataGetBytePtr (data), 0, destData.getSize());
  22093. CFRelease (data);
  22094. CFRelease (stream);
  22095. CFRelease (propertyList);
  22096. }
  22097. }
  22098. void AudioUnitPluginInstance::setStateInformation (const void* data, int sizeInBytes)
  22099. {
  22100. setCurrentProgramStateInformation (data, sizeInBytes);
  22101. }
  22102. void AudioUnitPluginInstance::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  22103. {
  22104. CFReadStreamRef stream = CFReadStreamCreateWithBytesNoCopy (kCFAllocatorDefault,
  22105. (const UInt8*) data,
  22106. sizeInBytes,
  22107. kCFAllocatorNull);
  22108. CFReadStreamOpen (stream);
  22109. CFPropertyListFormat format = kCFPropertyListBinaryFormat_v1_0;
  22110. CFPropertyListRef propertyList = CFPropertyListCreateFromStream (kCFAllocatorDefault,
  22111. stream,
  22112. 0,
  22113. kCFPropertyListImmutable,
  22114. &format,
  22115. 0);
  22116. CFRelease (stream);
  22117. if (propertyList != 0)
  22118. AudioUnitSetProperty (audioUnit,
  22119. kAudioUnitProperty_ClassInfo,
  22120. kAudioUnitScope_Global,
  22121. 0, &propertyList, sizeof (propertyList));
  22122. }
  22123. AudioUnitPluginFormat::AudioUnitPluginFormat()
  22124. {
  22125. }
  22126. AudioUnitPluginFormat::~AudioUnitPluginFormat()
  22127. {
  22128. }
  22129. void AudioUnitPluginFormat::findAllTypesForFile (OwnedArray <PluginDescription>& results,
  22130. const File& file)
  22131. {
  22132. if (! fileMightContainThisPluginType (file))
  22133. return;
  22134. PluginDescription desc;
  22135. desc.file = file;
  22136. desc.uid = 0;
  22137. AudioUnitPluginInstance* instance = dynamic_cast <AudioUnitPluginInstance*> (createInstanceFromDescription (desc));
  22138. if (instance == 0)
  22139. return;
  22140. try
  22141. {
  22142. instance->fillInPluginDescription (desc);
  22143. results.add (new PluginDescription (desc));
  22144. }
  22145. catch (...)
  22146. {
  22147. // crashed while loading...
  22148. }
  22149. deleteAndZero (instance);
  22150. }
  22151. AudioPluginInstance* AudioUnitPluginFormat::createInstanceFromDescription (const PluginDescription& desc)
  22152. {
  22153. AudioUnitPluginInstance* result = 0;
  22154. if (fileMightContainThisPluginType (desc.file))
  22155. {
  22156. result = new AudioUnitPluginInstance (desc.file);
  22157. if (result->audioUnit != 0)
  22158. {
  22159. result->initialise();
  22160. }
  22161. else
  22162. {
  22163. deleteAndZero (result);
  22164. }
  22165. }
  22166. return result;
  22167. }
  22168. bool AudioUnitPluginFormat::fileMightContainThisPluginType (const File& f)
  22169. {
  22170. return f.hasFileExtension (T(".component"))
  22171. && f.isDirectory();
  22172. }
  22173. const FileSearchPath AudioUnitPluginFormat::getDefaultLocationsToSearch()
  22174. {
  22175. return FileSearchPath ("~/Library/Audio/Plug-Ins/Components;/Library/Audio/Plug-Ins/Components");
  22176. }
  22177. #endif
  22178. END_JUCE_NAMESPACE
  22179. #undef log
  22180. #endif
  22181. /********* End of inlined file: juce_AudioUnitPluginFormat.cpp *********/
  22182. /********* Start of inlined file: juce_VSTPluginFormat.cpp *********/
  22183. #if JUCE_PLUGINHOST_VST
  22184. #ifdef _WIN32
  22185. #undef _WIN32_WINNT
  22186. #define _WIN32_WINNT 0x500
  22187. #undef STRICT
  22188. #define STRICT
  22189. #include <windows.h>
  22190. #include <float.h>
  22191. #pragma warning (disable : 4312)
  22192. #elif defined (LINUX)
  22193. #include <float.h>
  22194. #include <sys/time.h>
  22195. #include <X11/Xlib.h>
  22196. #include <X11/Xutil.h>
  22197. #include <X11/Xatom.h>
  22198. #undef Font
  22199. #undef KeyPress
  22200. #undef Drawable
  22201. #undef Time
  22202. #else
  22203. #include <Carbon/Carbon.h>
  22204. #endif
  22205. BEGIN_JUCE_NAMESPACE
  22206. #undef PRAGMA_ALIGN_SUPPORTED
  22207. #define VST_FORCE_DEPRECATED 0
  22208. #ifdef _MSC_VER
  22209. #pragma warning (push)
  22210. #pragma warning (disable: 4996)
  22211. #endif
  22212. /* Obviously you're going to need the Steinberg vstsdk2.4 folder in
  22213. your include path if you want to add VST support.
  22214. If you're not interested in VSTs, you can disable them by changing the
  22215. JUCE_PLUGINHOST_VST flag in juce_Config.h
  22216. */
  22217. #include "pluginterfaces/vst2.x/aeffectx.h"
  22218. #ifdef _MSC_VER
  22219. #pragma warning (pop)
  22220. #endif
  22221. #if JUCE_LINUX
  22222. #define Font JUCE_NAMESPACE::Font
  22223. #define KeyPress JUCE_NAMESPACE::KeyPress
  22224. #define Drawable JUCE_NAMESPACE::Drawable
  22225. #define Time JUCE_NAMESPACE::Time
  22226. #endif
  22227. #if ! JUCE_WIN32
  22228. #define _fpreset()
  22229. #define _clearfp()
  22230. #endif
  22231. extern void juce_callAnyTimersSynchronously();
  22232. const int fxbVersionNum = 1;
  22233. struct fxProgram
  22234. {
  22235. long chunkMagic; // 'CcnK'
  22236. long byteSize; // of this chunk, excl. magic + byteSize
  22237. long fxMagic; // 'FxCk'
  22238. long version;
  22239. long fxID; // fx unique id
  22240. long fxVersion;
  22241. long numParams;
  22242. char prgName[28];
  22243. float params[1]; // variable no. of parameters
  22244. };
  22245. struct fxSet
  22246. {
  22247. long chunkMagic; // 'CcnK'
  22248. long byteSize; // of this chunk, excl. magic + byteSize
  22249. long fxMagic; // 'FxBk'
  22250. long version;
  22251. long fxID; // fx unique id
  22252. long fxVersion;
  22253. long numPrograms;
  22254. char future[128];
  22255. fxProgram programs[1]; // variable no. of programs
  22256. };
  22257. struct fxChunkSet
  22258. {
  22259. long chunkMagic; // 'CcnK'
  22260. long byteSize; // of this chunk, excl. magic + byteSize
  22261. long fxMagic; // 'FxCh', 'FPCh', or 'FBCh'
  22262. long version;
  22263. long fxID; // fx unique id
  22264. long fxVersion;
  22265. long numPrograms;
  22266. char future[128];
  22267. long chunkSize;
  22268. char chunk[8]; // variable
  22269. };
  22270. struct fxProgramSet
  22271. {
  22272. long chunkMagic; // 'CcnK'
  22273. long byteSize; // of this chunk, excl. magic + byteSize
  22274. long fxMagic; // 'FxCh', 'FPCh', or 'FBCh'
  22275. long version;
  22276. long fxID; // fx unique id
  22277. long fxVersion;
  22278. long numPrograms;
  22279. char name[28];
  22280. long chunkSize;
  22281. char chunk[8]; // variable
  22282. };
  22283. #ifdef JUCE_LITTLE_ENDIAN
  22284. static long vst_swap (const long x) throw() { return (long) swapByteOrder ((uint32) x); }
  22285. static float vst_swapFloat (const float x) throw()
  22286. {
  22287. union { uint32 asInt; float asFloat; } n;
  22288. n.asFloat = x;
  22289. n.asInt = swapByteOrder (n.asInt);
  22290. return n.asFloat;
  22291. }
  22292. #else
  22293. #define vst_swap(x) (x)
  22294. #define vst_swapFloat(x) (x)
  22295. #endif
  22296. typedef AEffect* (*MainCall) (audioMasterCallback);
  22297. static VstIntPtr VSTCALLBACK audioMaster (AEffect* effect, VstInt32 opcode, VstInt32 index, VstIntPtr value, void* ptr, float opt);
  22298. static int shellUIDToCreate = 0;
  22299. static int insideVSTCallback = 0;
  22300. class VSTPluginWindow;
  22301. // Change this to disable logging of various VST activities
  22302. #ifndef VST_LOGGING
  22303. #define VST_LOGGING 1
  22304. #endif
  22305. #if VST_LOGGING
  22306. #define log(a) Logger::writeToLog(a);
  22307. #else
  22308. #define log(a)
  22309. #endif
  22310. #if JUCE_MAC
  22311. extern bool juce_isHIViewCreatedByJuce (HIViewRef view);
  22312. extern bool juce_isWindowCreatedByJuce (WindowRef window);
  22313. #if JUCE_PPC
  22314. static void* NewCFMFromMachO (void* const machofp) throw()
  22315. {
  22316. void* result = juce_malloc (8);
  22317. ((void**) result)[0] = machofp;
  22318. ((void**) result)[1] = result;
  22319. return result;
  22320. }
  22321. #endif
  22322. #endif
  22323. #if JUCE_LINUX
  22324. extern Display* display;
  22325. extern XContext improbableNumber;
  22326. typedef void (*EventProcPtr) (XEvent* ev);
  22327. static bool xErrorTriggered;
  22328. static int temporaryErrorHandler (Display*, XErrorEvent*)
  22329. {
  22330. xErrorTriggered = true;
  22331. return 0;
  22332. }
  22333. static int getPropertyFromXWindow (Window handle, Atom atom)
  22334. {
  22335. XErrorHandler oldErrorHandler = XSetErrorHandler (temporaryErrorHandler);
  22336. xErrorTriggered = false;
  22337. int userSize;
  22338. unsigned long bytes, userCount;
  22339. unsigned char* data;
  22340. Atom userType;
  22341. XGetWindowProperty (display, handle, atom, 0, 1, false, AnyPropertyType,
  22342. &userType, &userSize, &userCount, &bytes, &data);
  22343. XSetErrorHandler (oldErrorHandler);
  22344. return (userCount == 1 && ! xErrorTriggered) ? *(int*) data
  22345. : 0;
  22346. }
  22347. static Window getChildWindow (Window windowToCheck)
  22348. {
  22349. Window rootWindow, parentWindow;
  22350. Window* childWindows;
  22351. unsigned int numChildren;
  22352. XQueryTree (display,
  22353. windowToCheck,
  22354. &rootWindow,
  22355. &parentWindow,
  22356. &childWindows,
  22357. &numChildren);
  22358. if (numChildren > 0)
  22359. return childWindows [0];
  22360. return 0;
  22361. }
  22362. static void translateJuceToXButtonModifiers (const MouseEvent& e, XEvent& ev) throw()
  22363. {
  22364. if (e.mods.isLeftButtonDown())
  22365. {
  22366. ev.xbutton.button = Button1;
  22367. ev.xbutton.state |= Button1Mask;
  22368. }
  22369. else if (e.mods.isRightButtonDown())
  22370. {
  22371. ev.xbutton.button = Button3;
  22372. ev.xbutton.state |= Button3Mask;
  22373. }
  22374. else if (e.mods.isMiddleButtonDown())
  22375. {
  22376. ev.xbutton.button = Button2;
  22377. ev.xbutton.state |= Button2Mask;
  22378. }
  22379. }
  22380. static void translateJuceToXMotionModifiers (const MouseEvent& e, XEvent& ev) throw()
  22381. {
  22382. if (e.mods.isLeftButtonDown())
  22383. ev.xmotion.state |= Button1Mask;
  22384. else if (e.mods.isRightButtonDown())
  22385. ev.xmotion.state |= Button3Mask;
  22386. else if (e.mods.isMiddleButtonDown())
  22387. ev.xmotion.state |= Button2Mask;
  22388. }
  22389. static void translateJuceToXCrossingModifiers (const MouseEvent& e, XEvent& ev) throw()
  22390. {
  22391. if (e.mods.isLeftButtonDown())
  22392. ev.xcrossing.state |= Button1Mask;
  22393. else if (e.mods.isRightButtonDown())
  22394. ev.xcrossing.state |= Button3Mask;
  22395. else if (e.mods.isMiddleButtonDown())
  22396. ev.xcrossing.state |= Button2Mask;
  22397. }
  22398. static void translateJuceToXMouseWheelModifiers (const MouseEvent& e, const float increment, XEvent& ev) throw()
  22399. {
  22400. if (increment < 0)
  22401. {
  22402. ev.xbutton.button = Button5;
  22403. ev.xbutton.state |= Button5Mask;
  22404. }
  22405. else if (increment > 0)
  22406. {
  22407. ev.xbutton.button = Button4;
  22408. ev.xbutton.state |= Button4Mask;
  22409. }
  22410. }
  22411. #endif
  22412. static VoidArray activeModules;
  22413. class ModuleHandle : public ReferenceCountedObject
  22414. {
  22415. public:
  22416. File file;
  22417. MainCall moduleMain;
  22418. String pluginName;
  22419. static ModuleHandle* findOrCreateModule (const File& file)
  22420. {
  22421. for (int i = activeModules.size(); --i >= 0;)
  22422. {
  22423. ModuleHandle* const module = (ModuleHandle*) activeModules.getUnchecked(i);
  22424. if (module->file == file)
  22425. return module;
  22426. }
  22427. _fpreset(); // (doesn't do any harm)
  22428. ++insideVSTCallback;
  22429. shellUIDToCreate = 0;
  22430. log ("Attempting to load VST: " + file.getFullPathName());
  22431. ModuleHandle* m = new ModuleHandle (file);
  22432. if (! m->open())
  22433. deleteAndZero (m);
  22434. --insideVSTCallback;
  22435. _fpreset(); // (doesn't do any harm)
  22436. return m;
  22437. }
  22438. ModuleHandle (const File& file_)
  22439. : file (file_),
  22440. moduleMain (0),
  22441. #if JUCE_WIN32 || JUCE_LINUX
  22442. hModule (0)
  22443. #elif JUCE_MAC
  22444. fragId (0),
  22445. resHandle (0),
  22446. bundleRef (0),
  22447. resFileId (0)
  22448. #endif
  22449. {
  22450. activeModules.add (this);
  22451. #if JUCE_WIN32 || JUCE_LINUX
  22452. fullParentDirectoryPathName = file_.getParentDirectory().getFullPathName();
  22453. #elif JUCE_MAC
  22454. PlatformUtilities::makeFSSpecFromPath (&parentDirFSSpec, file_.getParentDirectory().getFullPathName());
  22455. #endif
  22456. }
  22457. ~ModuleHandle()
  22458. {
  22459. activeModules.removeValue (this);
  22460. close();
  22461. }
  22462. juce_UseDebuggingNewOperator
  22463. #if JUCE_WIN32 || JUCE_LINUX
  22464. void* hModule;
  22465. String fullParentDirectoryPathName;
  22466. bool open()
  22467. {
  22468. #if JUCE_WIN32
  22469. static bool timePeriodSet = false;
  22470. if (! timePeriodSet)
  22471. {
  22472. timePeriodSet = true;
  22473. timeBeginPeriod (2);
  22474. }
  22475. #endif
  22476. pluginName = file.getFileNameWithoutExtension();
  22477. hModule = Process::loadDynamicLibrary (file.getFullPathName());
  22478. moduleMain = (MainCall) Process::getProcedureEntryPoint (hModule, "VSTPluginMain");
  22479. if (moduleMain == 0)
  22480. moduleMain = (MainCall) Process::getProcedureEntryPoint (hModule, "main");
  22481. return moduleMain != 0;
  22482. }
  22483. void close()
  22484. {
  22485. _fpreset(); // (doesn't do any harm)
  22486. Process::freeDynamicLibrary (hModule);
  22487. }
  22488. void closeEffect (AEffect* eff)
  22489. {
  22490. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  22491. }
  22492. #else
  22493. CFragConnectionID fragId;
  22494. Handle resHandle;
  22495. CFBundleRef bundleRef;
  22496. FSSpec parentDirFSSpec;
  22497. short resFileId;
  22498. bool open()
  22499. {
  22500. bool ok = false;
  22501. const String filename (file.getFullPathName());
  22502. if (file.hasFileExtension (T(".vst")))
  22503. {
  22504. const char* const utf8 = filename.toUTF8();
  22505. CFURLRef url = CFURLCreateFromFileSystemRepresentation (0, (const UInt8*) utf8,
  22506. strlen (utf8), file.isDirectory());
  22507. if (url != 0)
  22508. {
  22509. bundleRef = CFBundleCreate (kCFAllocatorDefault, url);
  22510. CFRelease (url);
  22511. if (bundleRef != 0)
  22512. {
  22513. if (CFBundleLoadExecutable (bundleRef))
  22514. {
  22515. moduleMain = (MainCall) CFBundleGetFunctionPointerForName (bundleRef, CFSTR("main_macho"));
  22516. if (moduleMain == 0)
  22517. moduleMain = (MainCall) CFBundleGetFunctionPointerForName (bundleRef, CFSTR("VSTPluginMain"));
  22518. if (moduleMain != 0)
  22519. {
  22520. CFTypeRef name = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleName"));
  22521. if (name != 0)
  22522. {
  22523. if (CFGetTypeID (name) == CFStringGetTypeID())
  22524. {
  22525. char buffer[1024];
  22526. if (CFStringGetCString ((CFStringRef) name, buffer, sizeof (buffer), CFStringGetSystemEncoding()))
  22527. pluginName = buffer;
  22528. }
  22529. }
  22530. if (pluginName.isEmpty())
  22531. pluginName = file.getFileNameWithoutExtension();
  22532. resFileId = CFBundleOpenBundleResourceMap (bundleRef);
  22533. ok = true;
  22534. }
  22535. }
  22536. if (! ok)
  22537. {
  22538. CFBundleUnloadExecutable (bundleRef);
  22539. CFRelease (bundleRef);
  22540. bundleRef = 0;
  22541. }
  22542. }
  22543. }
  22544. }
  22545. #if JUCE_PPC
  22546. else
  22547. {
  22548. FSRef fn;
  22549. if (FSPathMakeRef ((UInt8*) (const char*) filename, &fn, 0) == noErr)
  22550. {
  22551. resFileId = FSOpenResFile (&fn, fsRdPerm);
  22552. if (resFileId != -1)
  22553. {
  22554. const int numEffs = Count1Resources ('aEff');
  22555. for (int i = 0; i < numEffs; ++i)
  22556. {
  22557. resHandle = Get1IndResource ('aEff', i + 1);
  22558. if (resHandle != 0)
  22559. {
  22560. OSType type;
  22561. Str255 name;
  22562. SInt16 id;
  22563. GetResInfo (resHandle, &id, &type, name);
  22564. pluginName = String ((const char*) name + 1, name[0]);
  22565. DetachResource (resHandle);
  22566. HLock (resHandle);
  22567. Ptr ptr;
  22568. Str255 errorText;
  22569. OSErr err = GetMemFragment (*resHandle, GetHandleSize (resHandle),
  22570. name, kPrivateCFragCopy,
  22571. &fragId, &ptr, errorText);
  22572. if (err == noErr)
  22573. {
  22574. moduleMain = (MainCall) newMachOFromCFM (ptr);
  22575. ok = true;
  22576. }
  22577. else
  22578. {
  22579. HUnlock (resHandle);
  22580. }
  22581. break;
  22582. }
  22583. }
  22584. if (! ok)
  22585. CloseResFile (resFileId);
  22586. }
  22587. }
  22588. }
  22589. #endif
  22590. return ok;
  22591. }
  22592. void close()
  22593. {
  22594. #if JUCE_PPC
  22595. if (fragId != 0)
  22596. {
  22597. if (moduleMain != 0)
  22598. disposeMachOFromCFM ((void*) moduleMain);
  22599. CloseConnection (&fragId);
  22600. HUnlock (resHandle);
  22601. if (resFileId != 0)
  22602. CloseResFile (resFileId);
  22603. }
  22604. else
  22605. #endif
  22606. if (bundleRef != 0)
  22607. {
  22608. CFBundleCloseBundleResourceMap (bundleRef, resFileId);
  22609. if (CFGetRetainCount (bundleRef) == 1)
  22610. CFBundleUnloadExecutable (bundleRef);
  22611. if (CFGetRetainCount (bundleRef) > 0)
  22612. CFRelease (bundleRef);
  22613. }
  22614. }
  22615. void closeEffect (AEffect* eff)
  22616. {
  22617. #if JUCE_PPC
  22618. if (fragId != 0)
  22619. {
  22620. VoidArray thingsToDelete;
  22621. thingsToDelete.add ((void*) eff->dispatcher);
  22622. thingsToDelete.add ((void*) eff->process);
  22623. thingsToDelete.add ((void*) eff->setParameter);
  22624. thingsToDelete.add ((void*) eff->getParameter);
  22625. thingsToDelete.add ((void*) eff->processReplacing);
  22626. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  22627. for (int i = thingsToDelete.size(); --i >= 0;)
  22628. disposeMachOFromCFM (thingsToDelete[i]);
  22629. }
  22630. else
  22631. #endif
  22632. {
  22633. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  22634. }
  22635. }
  22636. #if JUCE_PPC
  22637. static void* newMachOFromCFM (void* cfmfp)
  22638. {
  22639. if (cfmfp == 0)
  22640. return 0;
  22641. UInt32* const mfp = (UInt32*) juce_malloc (sizeof (UInt32) * 6);
  22642. mfp[0] = 0x3d800000 | ((UInt32) cfmfp >> 16);
  22643. mfp[1] = 0x618c0000 | ((UInt32) cfmfp & 0xffff);
  22644. mfp[2] = 0x800c0000;
  22645. mfp[3] = 0x804c0004;
  22646. mfp[4] = 0x7c0903a6;
  22647. mfp[5] = 0x4e800420;
  22648. MakeDataExecutable (mfp, sizeof (UInt32) * 6);
  22649. return mfp;
  22650. }
  22651. static void disposeMachOFromCFM (void* ptr)
  22652. {
  22653. juce_free (ptr);
  22654. }
  22655. void coerceAEffectFunctionCalls (AEffect* eff)
  22656. {
  22657. if (fragId != 0)
  22658. {
  22659. eff->dispatcher = (AEffectDispatcherProc) newMachOFromCFM ((void*) eff->dispatcher);
  22660. eff->process = (AEffectProcessProc) newMachOFromCFM ((void*) eff->process);
  22661. eff->setParameter = (AEffectSetParameterProc) newMachOFromCFM ((void*) eff->setParameter);
  22662. eff->getParameter = (AEffectGetParameterProc) newMachOFromCFM ((void*) eff->getParameter);
  22663. eff->processReplacing = (AEffectProcessProc) newMachOFromCFM ((void*) eff->processReplacing);
  22664. }
  22665. }
  22666. #endif
  22667. #endif
  22668. };
  22669. /**
  22670. An instance of a plugin, created by a VSTPluginFormat.
  22671. */
  22672. class VSTPluginInstance : public AudioPluginInstance,
  22673. private Timer,
  22674. private AsyncUpdater
  22675. {
  22676. public:
  22677. ~VSTPluginInstance();
  22678. // AudioPluginInstance methods:
  22679. void fillInPluginDescription (PluginDescription& desc) const
  22680. {
  22681. desc.name = name;
  22682. desc.file = module->file;
  22683. desc.uid = getUID();
  22684. desc.lastFileModTime = desc.file.getLastModificationTime();
  22685. desc.pluginFormatName = "VST";
  22686. desc.category = getCategory();
  22687. {
  22688. char buffer [kVstMaxVendorStrLen + 8];
  22689. zerostruct (buffer);
  22690. dispatch (effGetVendorString, 0, 0, buffer, 0);
  22691. desc.manufacturerName = buffer;
  22692. }
  22693. desc.version = getVersion();
  22694. desc.numInputChannels = getNumInputChannels();
  22695. desc.numOutputChannels = getNumOutputChannels();
  22696. desc.isInstrument = (effect != 0 && (effect->flags & effFlagsIsSynth) != 0);
  22697. }
  22698. const String getName() const { return name; }
  22699. int getUID() const throw();
  22700. bool acceptsMidi() const { return wantsMidiMessages; }
  22701. bool producesMidi() const { return dispatch (effCanDo, 0, 0, (void*) "sendVstMidiEvent", 0) > 0; }
  22702. // AudioProcessor methods:
  22703. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  22704. void releaseResources();
  22705. void processBlock (AudioSampleBuffer& buffer,
  22706. MidiBuffer& midiMessages);
  22707. AudioProcessorEditor* createEditor();
  22708. const String getInputChannelName (const int index) const;
  22709. bool isInputChannelStereoPair (int index) const;
  22710. const String getOutputChannelName (const int index) const;
  22711. bool isOutputChannelStereoPair (int index) const;
  22712. int getNumParameters() { return effect != 0 ? effect->numParams : 0; }
  22713. float getParameter (int index);
  22714. void setParameter (int index, float newValue);
  22715. const String getParameterName (int index);
  22716. const String getParameterText (int index);
  22717. bool isParameterAutomatable (int index) const;
  22718. int getNumPrograms() { return effect != 0 ? effect->numPrograms : 0; }
  22719. int getCurrentProgram() { return dispatch (effGetProgram, 0, 0, 0, 0); }
  22720. void setCurrentProgram (int index);
  22721. const String getProgramName (int index);
  22722. void changeProgramName (int index, const String& newName);
  22723. void getStateInformation (MemoryBlock& destData);
  22724. void getCurrentProgramStateInformation (MemoryBlock& destData);
  22725. void setStateInformation (const void* data, int sizeInBytes);
  22726. void setCurrentProgramStateInformation (const void* data, int sizeInBytes);
  22727. void timerCallback();
  22728. void handleAsyncUpdate();
  22729. VstIntPtr handleCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt);
  22730. juce_UseDebuggingNewOperator
  22731. private:
  22732. friend class VSTPluginWindow;
  22733. friend class VSTPluginFormat;
  22734. AEffect* effect;
  22735. String name;
  22736. CriticalSection lock;
  22737. bool wantsMidiMessages, initialised, isPowerOn;
  22738. mutable StringArray programNames;
  22739. AudioSampleBuffer tempBuffer;
  22740. CriticalSection midiInLock;
  22741. MidiBuffer incomingMidi;
  22742. void* midiEventsToSend;
  22743. int numAllocatedMidiEvents;
  22744. VstTimeInfo vstHostTime;
  22745. float** channels;
  22746. ReferenceCountedObjectPtr <ModuleHandle> module;
  22747. int dispatch (const int opcode, const int index, const int value, void* const ptr, float opt) const;
  22748. bool restoreProgramSettings (const fxProgram* const prog);
  22749. const String getCurrentProgramName();
  22750. void setParamsInProgramBlock (fxProgram* const prog) throw();
  22751. void updateStoredProgramNames();
  22752. void initialise();
  22753. void ensureMidiEventSize (int numEventsNeeded);
  22754. void freeMidiEvents();
  22755. void handleMidiFromPlugin (const VstEvents* const events);
  22756. void createTempParameterStore (MemoryBlock& dest);
  22757. void restoreFromTempParameterStore (const MemoryBlock& mb);
  22758. const String getParameterLabel (int index) const;
  22759. bool usesChunks() const throw() { return effect != 0 && (effect->flags & effFlagsProgramChunks) != 0; }
  22760. void getChunkData (MemoryBlock& mb, bool isPreset, int maxSizeMB) const;
  22761. void setChunkData (const char* data, int size, bool isPreset);
  22762. bool loadFromFXBFile (const void* data, int numBytes);
  22763. bool saveToFXBFile (MemoryBlock& dest, bool isFXB, int maxSizeMB);
  22764. int getVersionNumber() const throw() { return effect != 0 ? effect->version : 0; }
  22765. const String getVersion() const throw();
  22766. const String getCategory() const throw();
  22767. bool hasEditor() const throw() { return effect != 0 && (effect->flags & effFlagsHasEditor) != 0; }
  22768. void setPower (const bool on);
  22769. VSTPluginInstance (const ReferenceCountedObjectPtr <ModuleHandle>& module);
  22770. };
  22771. VSTPluginInstance::VSTPluginInstance (const ReferenceCountedObjectPtr <ModuleHandle>& module_)
  22772. : effect (0),
  22773. wantsMidiMessages (false),
  22774. initialised (false),
  22775. isPowerOn (false),
  22776. numAllocatedMidiEvents (0),
  22777. midiEventsToSend (0),
  22778. tempBuffer (1, 1),
  22779. channels (0),
  22780. module (module_)
  22781. {
  22782. try
  22783. {
  22784. _fpreset();
  22785. ++insideVSTCallback;
  22786. name = module->pluginName;
  22787. log (T("Creating VST instance: ") + name);
  22788. #if JUCE_MAC
  22789. if (module->resFileId != 0)
  22790. UseResFile (module->resFileId);
  22791. #if JUCE_PPC
  22792. if (module->fragId != 0)
  22793. {
  22794. static void* audioMasterCoerced = 0;
  22795. if (audioMasterCoerced == 0)
  22796. audioMasterCoerced = NewCFMFromMachO ((void*) &audioMaster);
  22797. effect = module->moduleMain ((audioMasterCallback) audioMasterCoerced);
  22798. }
  22799. else
  22800. #endif
  22801. #endif
  22802. {
  22803. effect = module->moduleMain (&audioMaster);
  22804. }
  22805. --insideVSTCallback;
  22806. if (effect != 0 && effect->magic == kEffectMagic)
  22807. {
  22808. #if JUCE_PPC
  22809. module->coerceAEffectFunctionCalls (effect);
  22810. #endif
  22811. jassert (effect->resvd2 == 0);
  22812. jassert (effect->object != 0);
  22813. _fpreset(); // some dodgy plugs fuck around with this
  22814. }
  22815. else
  22816. {
  22817. effect = 0;
  22818. }
  22819. }
  22820. catch (...)
  22821. {
  22822. --insideVSTCallback;
  22823. }
  22824. }
  22825. VSTPluginInstance::~VSTPluginInstance()
  22826. {
  22827. {
  22828. const ScopedLock sl (lock);
  22829. jassert (insideVSTCallback == 0);
  22830. if (effect != 0 && effect->magic == kEffectMagic)
  22831. {
  22832. try
  22833. {
  22834. #if JUCE_MAC
  22835. if (module->resFileId != 0)
  22836. UseResFile (module->resFileId);
  22837. #endif
  22838. // Must delete any editors before deleting the plugin instance!
  22839. jassert (getActiveEditor() == 0);
  22840. _fpreset(); // some dodgy plugs fuck around with this
  22841. module->closeEffect (effect);
  22842. }
  22843. catch (...)
  22844. {}
  22845. }
  22846. module = 0;
  22847. effect = 0;
  22848. }
  22849. freeMidiEvents();
  22850. juce_free (channels);
  22851. channels = 0;
  22852. }
  22853. void VSTPluginInstance::initialise()
  22854. {
  22855. if (initialised || effect == 0)
  22856. return;
  22857. log (T("Initialising VST: ") + module->pluginName);
  22858. initialised = true;
  22859. dispatch (effIdentify, 0, 0, 0, 0);
  22860. // this code would ask the plugin for its name, but so few plugins
  22861. // actually bother implementing this correctly, that it's better to
  22862. // just ignore it and use the file name instead.
  22863. /* {
  22864. char buffer [256];
  22865. zerostruct (buffer);
  22866. dispatch (effGetEffectName, 0, 0, buffer, 0);
  22867. name = String (buffer).trim();
  22868. if (name.isEmpty())
  22869. name = module->pluginName;
  22870. }
  22871. */
  22872. if (getSampleRate() > 0)
  22873. dispatch (effSetSampleRate, 0, 0, 0, (float) getSampleRate());
  22874. if (getBlockSize() > 0)
  22875. dispatch (effSetBlockSize, 0, jmax (32, getBlockSize()), 0, 0);
  22876. dispatch (effOpen, 0, 0, 0, 0);
  22877. setPlayConfigDetails (effect->numInputs, effect->numOutputs,
  22878. getSampleRate(), getBlockSize());
  22879. if (getNumPrograms() > 1)
  22880. setCurrentProgram (0);
  22881. else
  22882. dispatch (effSetProgram, 0, 0, 0, 0);
  22883. int i;
  22884. for (i = effect->numInputs; --i >= 0;)
  22885. dispatch (effConnectInput, i, 1, 0, 0);
  22886. for (i = effect->numOutputs; --i >= 0;)
  22887. dispatch (effConnectOutput, i, 1, 0, 0);
  22888. updateStoredProgramNames();
  22889. wantsMidiMessages = dispatch (effCanDo, 0, 0, (void*) "receiveVstMidiEvent", 0) > 0;
  22890. setLatencySamples (effect->initialDelay);
  22891. }
  22892. void VSTPluginInstance::prepareToPlay (double sampleRate_,
  22893. int samplesPerBlockExpected)
  22894. {
  22895. setPlayConfigDetails (effect->numInputs, effect->numOutputs,
  22896. sampleRate_, samplesPerBlockExpected);
  22897. setLatencySamples (effect->initialDelay);
  22898. juce_free (channels);
  22899. channels = (float**) juce_calloc (sizeof (float*) * jmax (16, getNumOutputChannels() + 2, getNumInputChannels() + 2));
  22900. vstHostTime.tempo = 120.0;
  22901. vstHostTime.timeSigNumerator = 4;
  22902. vstHostTime.timeSigDenominator = 4;
  22903. vstHostTime.sampleRate = sampleRate_;
  22904. vstHostTime.samplePos = 0;
  22905. vstHostTime.flags = kVstNanosValid; /*| kVstTransportPlaying | kVstTempoValid | kVstTimeSigValid*/;
  22906. initialise();
  22907. if (initialised)
  22908. {
  22909. wantsMidiMessages = wantsMidiMessages
  22910. || (dispatch (effCanDo, 0, 0, (void*) "receiveVstMidiEvent", 0) > 0);
  22911. if (wantsMidiMessages)
  22912. ensureMidiEventSize (256);
  22913. else
  22914. freeMidiEvents();
  22915. incomingMidi.clear();
  22916. dispatch (effSetSampleRate, 0, 0, 0, (float) sampleRate_);
  22917. dispatch (effSetBlockSize, 0, jmax (16, samplesPerBlockExpected), 0, 0);
  22918. tempBuffer.setSize (jmax (1, effect->numOutputs), samplesPerBlockExpected);
  22919. if (! isPowerOn)
  22920. setPower (true);
  22921. // dodgy hack to force some plugins to initialise the sample rate..
  22922. if ((! hasEditor()) && getNumParameters() > 0)
  22923. {
  22924. const float old = getParameter (0);
  22925. setParameter (0, (old < 0.5f) ? 1.0f : 0.0f);
  22926. setParameter (0, old);
  22927. }
  22928. dispatch (effStartProcess, 0, 0, 0, 0);
  22929. }
  22930. }
  22931. void VSTPluginInstance::releaseResources()
  22932. {
  22933. if (initialised)
  22934. {
  22935. dispatch (effStopProcess, 0, 0, 0, 0);
  22936. setPower (false);
  22937. }
  22938. tempBuffer.setSize (1, 1);
  22939. incomingMidi.clear();
  22940. freeMidiEvents();
  22941. juce_free (channels);
  22942. channels = 0;
  22943. }
  22944. void VSTPluginInstance::processBlock (AudioSampleBuffer& buffer,
  22945. MidiBuffer& midiMessages)
  22946. {
  22947. const int numSamples = buffer.getNumSamples();
  22948. if (initialised)
  22949. {
  22950. #if JUCE_WIN32
  22951. vstHostTime.nanoSeconds = timeGetTime() * 1000000.0;
  22952. #elif JUCE_LINUX
  22953. timeval micro;
  22954. gettimeofday (&micro, 0);
  22955. vstHostTime.nanoSeconds = micro.tv_usec * 1000.0;
  22956. #elif JUCE_MAC
  22957. UnsignedWide micro;
  22958. Microseconds (&micro);
  22959. vstHostTime.nanoSeconds = micro.lo * 1000.0;
  22960. #endif
  22961. if (wantsMidiMessages)
  22962. {
  22963. MidiBuffer::Iterator iter (midiMessages);
  22964. int eventIndex = 0;
  22965. const uint8* midiData;
  22966. int numBytesOfMidiData, samplePosition;
  22967. while (iter.getNextEvent (midiData, numBytesOfMidiData, samplePosition))
  22968. {
  22969. if (numBytesOfMidiData < 4)
  22970. {
  22971. ensureMidiEventSize (eventIndex);
  22972. VstMidiEvent* const e
  22973. = (VstMidiEvent*) ((VstEvents*) midiEventsToSend)->events [eventIndex++];
  22974. // check that some plugin hasn't messed up our objects
  22975. jassert (e->type == kVstMidiType);
  22976. jassert (e->byteSize == 24);
  22977. e->deltaFrames = jlimit (0, numSamples - 1, samplePosition);
  22978. e->noteLength = 0;
  22979. e->noteOffset = 0;
  22980. e->midiData[0] = midiData[0];
  22981. e->midiData[1] = midiData[1];
  22982. e->midiData[2] = midiData[2];
  22983. e->detune = 0;
  22984. e->noteOffVelocity = 0;
  22985. }
  22986. }
  22987. if (midiEventsToSend == 0)
  22988. ensureMidiEventSize (1);
  22989. ((VstEvents*) midiEventsToSend)->numEvents = eventIndex;
  22990. try
  22991. {
  22992. effect->dispatcher (effect, effProcessEvents, 0, 0, midiEventsToSend, 0);
  22993. }
  22994. catch (...)
  22995. {}
  22996. }
  22997. int i;
  22998. const int maxChans = jmax (effect->numInputs, effect->numOutputs);
  22999. for (i = 0; i < maxChans; ++i)
  23000. channels[i] = buffer.getSampleData (i);
  23001. channels [maxChans] = 0;
  23002. _clearfp();
  23003. if ((effect->flags & effFlagsCanReplacing) != 0)
  23004. {
  23005. try
  23006. {
  23007. effect->processReplacing (effect, channels, channels, numSamples);
  23008. }
  23009. catch (...)
  23010. {}
  23011. }
  23012. else
  23013. {
  23014. tempBuffer.setSize (effect->numOutputs, numSamples);
  23015. tempBuffer.clear();
  23016. float* outs [64];
  23017. for (i = effect->numOutputs; --i >= 0;)
  23018. outs[i] = tempBuffer.getSampleData (i);
  23019. outs [effect->numOutputs] = 0;
  23020. try
  23021. {
  23022. effect->process (effect, channels, outs, numSamples);
  23023. }
  23024. catch (...)
  23025. {}
  23026. for (i = effect->numOutputs; --i >= 0;)
  23027. buffer.copyFrom (i, 0, outs[i], numSamples);
  23028. }
  23029. }
  23030. else
  23031. {
  23032. // Not initialised, so just bypass..
  23033. for (int i = getNumInputChannels(); i < getNumOutputChannels(); ++i)
  23034. buffer.clear (i, 0, buffer.getNumSamples());
  23035. }
  23036. {
  23037. // copy any incoming midi..
  23038. const ScopedLock sl (midiInLock);
  23039. midiMessages = incomingMidi;
  23040. incomingMidi.clear();
  23041. }
  23042. }
  23043. void VSTPluginInstance::ensureMidiEventSize (int numEventsNeeded)
  23044. {
  23045. if (numEventsNeeded > numAllocatedMidiEvents)
  23046. {
  23047. numEventsNeeded = (numEventsNeeded + 32) & ~31;
  23048. const int size = 20 + sizeof (VstEvent*) * numEventsNeeded;
  23049. if (midiEventsToSend == 0)
  23050. midiEventsToSend = juce_calloc (size);
  23051. else
  23052. midiEventsToSend = juce_realloc (midiEventsToSend, size);
  23053. for (int i = numAllocatedMidiEvents; i < numEventsNeeded; ++i)
  23054. {
  23055. VstMidiEvent* const e = (VstMidiEvent*) juce_calloc (sizeof (VstMidiEvent));
  23056. e->type = kVstMidiType;
  23057. e->byteSize = 24;
  23058. ((VstEvents*) midiEventsToSend)->events[i] = (VstEvent*) e;
  23059. }
  23060. numAllocatedMidiEvents = numEventsNeeded;
  23061. }
  23062. }
  23063. void VSTPluginInstance::freeMidiEvents()
  23064. {
  23065. if (midiEventsToSend != 0)
  23066. {
  23067. for (int i = numAllocatedMidiEvents; --i >= 0;)
  23068. juce_free (((VstEvents*) midiEventsToSend)->events[i]);
  23069. juce_free (midiEventsToSend);
  23070. midiEventsToSend = 0;
  23071. numAllocatedMidiEvents = 0;
  23072. }
  23073. }
  23074. void VSTPluginInstance::handleMidiFromPlugin (const VstEvents* const events)
  23075. {
  23076. if (events != 0)
  23077. {
  23078. const ScopedLock sl (midiInLock);
  23079. for (int i = 0; i < events->numEvents; ++i)
  23080. {
  23081. const VstEvent* const e = events->events[i];
  23082. if (e->type == kVstMidiType)
  23083. {
  23084. incomingMidi.addEvent ((const uint8*) ((const VstMidiEvent*) e)->midiData,
  23085. 3, e->deltaFrames);
  23086. }
  23087. }
  23088. }
  23089. }
  23090. static Array <VSTPluginWindow*> activeVSTWindows;
  23091. class VSTPluginWindow : public AudioProcessorEditor,
  23092. public Timer
  23093. {
  23094. public:
  23095. VSTPluginWindow (VSTPluginInstance& plugin_)
  23096. : AudioProcessorEditor (&plugin_),
  23097. plugin (plugin_),
  23098. isOpen (false),
  23099. wasShowing (false),
  23100. pluginRefusesToResize (false),
  23101. pluginWantsKeys (false),
  23102. alreadyInside (false),
  23103. recursiveResize (false)
  23104. {
  23105. #if JUCE_WIN32
  23106. sizeCheckCount = 0;
  23107. pluginHWND = 0;
  23108. #elif JUCE_LINUX
  23109. pluginWindow = None;
  23110. pluginProc = None;
  23111. #else
  23112. pluginViewRef = 0;
  23113. #endif
  23114. movementWatcher = new CompMovementWatcher (this);
  23115. activeVSTWindows.add (this);
  23116. setSize (1, 1);
  23117. setOpaque (true);
  23118. setVisible (true);
  23119. }
  23120. ~VSTPluginWindow()
  23121. {
  23122. deleteAndZero (movementWatcher);
  23123. closePluginWindow();
  23124. activeVSTWindows.removeValue (this);
  23125. plugin.editorBeingDeleted (this);
  23126. }
  23127. void componentMovedOrResized()
  23128. {
  23129. if (recursiveResize)
  23130. return;
  23131. Component* const topComp = getTopLevelComponent();
  23132. if (topComp->getPeer() != 0)
  23133. {
  23134. int x = 0, y = 0;
  23135. relativePositionToOtherComponent (topComp, x, y);
  23136. recursiveResize = true;
  23137. #if JUCE_MAC
  23138. if (pluginViewRef != 0)
  23139. {
  23140. HIRect r;
  23141. r.origin.x = (float) x;
  23142. r.origin.y = (float) y;
  23143. r.size.width = (float) getWidth();
  23144. r.size.height = (float) getHeight();
  23145. HIViewSetFrame (pluginViewRef, &r);
  23146. }
  23147. else if (pluginWindowRef != 0)
  23148. {
  23149. Rect r;
  23150. r.left = getScreenX();
  23151. r.top = getScreenY();
  23152. r.right = r.left + getWidth();
  23153. r.bottom = r.top + getHeight();
  23154. WindowGroupRef group = GetWindowGroup (pluginWindowRef);
  23155. WindowGroupAttributes atts;
  23156. GetWindowGroupAttributes (group, &atts);
  23157. ChangeWindowGroupAttributes (group, 0, kWindowGroupAttrMoveTogether);
  23158. SetWindowBounds (pluginWindowRef, kWindowContentRgn, &r);
  23159. if ((atts & kWindowGroupAttrMoveTogether) != 0)
  23160. ChangeWindowGroupAttributes (group, kWindowGroupAttrMoveTogether, 0);
  23161. }
  23162. else
  23163. {
  23164. repaint();
  23165. }
  23166. #elif JUCE_WIN32
  23167. if (pluginHWND != 0)
  23168. MoveWindow (pluginHWND, x, y, getWidth(), getHeight(), TRUE);
  23169. #elif JUCE_LINUX
  23170. if (pluginWindow != 0)
  23171. {
  23172. XResizeWindow (display, pluginWindow, getWidth(), getHeight());
  23173. XMoveWindow (display, pluginWindow, x, y);
  23174. XMapRaised (display, pluginWindow);
  23175. }
  23176. #endif
  23177. recursiveResize = false;
  23178. }
  23179. }
  23180. void componentVisibilityChanged()
  23181. {
  23182. const bool isShowingNow = isShowing();
  23183. if (wasShowing != isShowingNow)
  23184. {
  23185. wasShowing = isShowingNow;
  23186. if (isShowingNow)
  23187. openPluginWindow();
  23188. else
  23189. closePluginWindow();
  23190. }
  23191. componentMovedOrResized();
  23192. }
  23193. void componentPeerChanged()
  23194. {
  23195. closePluginWindow();
  23196. openPluginWindow();
  23197. }
  23198. bool keyStateChanged()
  23199. {
  23200. return pluginWantsKeys;
  23201. }
  23202. bool keyPressed (const KeyPress&)
  23203. {
  23204. return pluginWantsKeys;
  23205. }
  23206. void paint (Graphics& g)
  23207. {
  23208. if (isOpen)
  23209. {
  23210. ComponentPeer* const peer = getPeer();
  23211. if (peer != 0)
  23212. {
  23213. peer->addMaskedRegion (getScreenX() - peer->getScreenX(),
  23214. getScreenY() - peer->getScreenY(),
  23215. getWidth(), getHeight());
  23216. #if JUCE_MAC
  23217. if (pluginViewRef == 0)
  23218. {
  23219. ERect r;
  23220. r.left = getScreenX() - peer->getScreenX();
  23221. r.right = r.left + getWidth();
  23222. r.top = getScreenY() - peer->getScreenY();
  23223. r.bottom = r.top + getHeight();
  23224. dispatch (effEditDraw, 0, 0, &r, 0);
  23225. }
  23226. #elif JUCE_LINUX
  23227. if (pluginWindow != 0)
  23228. {
  23229. const Rectangle clip (g.getClipBounds());
  23230. XEvent ev;
  23231. zerostruct (ev);
  23232. ev.xexpose.type = Expose;
  23233. ev.xexpose.display = display;
  23234. ev.xexpose.window = pluginWindow;
  23235. ev.xexpose.x = clip.getX();
  23236. ev.xexpose.y = clip.getY();
  23237. ev.xexpose.width = clip.getWidth();
  23238. ev.xexpose.height = clip.getHeight();
  23239. sendEventToChild (&ev);
  23240. }
  23241. #endif
  23242. }
  23243. }
  23244. else
  23245. {
  23246. g.fillAll (Colours::black);
  23247. }
  23248. }
  23249. void timerCallback()
  23250. {
  23251. #if JUCE_WIN32
  23252. if (--sizeCheckCount <= 0)
  23253. {
  23254. sizeCheckCount = 10;
  23255. checkPluginWindowSize();
  23256. }
  23257. #endif
  23258. try
  23259. {
  23260. static bool reentrant = false;
  23261. if (! reentrant)
  23262. {
  23263. reentrant = true;
  23264. plugin.dispatch (effEditIdle, 0, 0, 0, 0);
  23265. reentrant = false;
  23266. }
  23267. }
  23268. catch (...)
  23269. {}
  23270. }
  23271. void mouseDown (const MouseEvent& e)
  23272. {
  23273. #if JUCE_MAC
  23274. if (! alreadyInside)
  23275. {
  23276. alreadyInside = true;
  23277. toFront (true);
  23278. dispatch (effEditMouse, e.x, e.y, 0, 0);
  23279. alreadyInside = false;
  23280. }
  23281. else
  23282. {
  23283. PostEvent (::mouseDown, 0);
  23284. }
  23285. #elif JUCE_LINUX
  23286. if (pluginWindow == 0)
  23287. return;
  23288. toFront (true);
  23289. XEvent ev;
  23290. zerostruct (ev);
  23291. ev.xbutton.display = display;
  23292. ev.xbutton.type = ButtonPress;
  23293. ev.xbutton.window = pluginWindow;
  23294. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  23295. ev.xbutton.time = CurrentTime;
  23296. ev.xbutton.x = e.x;
  23297. ev.xbutton.y = e.y;
  23298. ev.xbutton.x_root = e.getScreenX();
  23299. ev.xbutton.y_root = e.getScreenY();
  23300. translateJuceToXButtonModifiers (e, ev);
  23301. sendEventToChild (&ev);
  23302. #else
  23303. (void) e;
  23304. toFront (true);
  23305. #endif
  23306. }
  23307. void broughtToFront()
  23308. {
  23309. activeVSTWindows.removeValue (this);
  23310. activeVSTWindows.add (this);
  23311. #if JUCE_MAC
  23312. dispatch (effEditTop, 0, 0, 0, 0);
  23313. #endif
  23314. }
  23315. juce_UseDebuggingNewOperator
  23316. private:
  23317. VSTPluginInstance& plugin;
  23318. bool isOpen, wasShowing, recursiveResize;
  23319. bool pluginWantsKeys, pluginRefusesToResize, alreadyInside;
  23320. #if JUCE_WIN32
  23321. HWND pluginHWND;
  23322. void* originalWndProc;
  23323. int sizeCheckCount;
  23324. #elif JUCE_MAC
  23325. HIViewRef pluginViewRef;
  23326. WindowRef pluginWindowRef;
  23327. #elif JUCE_LINUX
  23328. Window pluginWindow;
  23329. EventProcPtr pluginProc;
  23330. #endif
  23331. void openPluginWindow()
  23332. {
  23333. if (isOpen || getWindowHandle() == 0)
  23334. return;
  23335. log (T("Opening VST UI: ") + plugin.name);
  23336. isOpen = true;
  23337. ERect* rect = 0;
  23338. dispatch (effEditGetRect, 0, 0, &rect, 0);
  23339. dispatch (effEditOpen, 0, 0, getWindowHandle(), 0);
  23340. // do this before and after like in the steinberg example
  23341. dispatch (effEditGetRect, 0, 0, &rect, 0);
  23342. dispatch (effGetProgram, 0, 0, 0, 0); // also in steinberg code
  23343. // Install keyboard hooks
  23344. pluginWantsKeys = (dispatch (effKeysRequired, 0, 0, 0, 0) == 0);
  23345. #if JUCE_WIN32
  23346. originalWndProc = 0;
  23347. pluginHWND = GetWindow ((HWND) getWindowHandle(), GW_CHILD);
  23348. if (pluginHWND == 0)
  23349. {
  23350. isOpen = false;
  23351. setSize (300, 150);
  23352. return;
  23353. }
  23354. #pragma warning (push)
  23355. #pragma warning (disable: 4244)
  23356. originalWndProc = (void*) GetWindowLongPtr (pluginHWND, GWL_WNDPROC);
  23357. if (! pluginWantsKeys)
  23358. SetWindowLongPtr (pluginHWND, GWL_WNDPROC, (LONG_PTR) vstHookWndProc);
  23359. #pragma warning (pop)
  23360. int w, h;
  23361. RECT r;
  23362. GetWindowRect (pluginHWND, &r);
  23363. w = r.right - r.left;
  23364. h = r.bottom - r.top;
  23365. if (rect != 0)
  23366. {
  23367. const int rw = rect->right - rect->left;
  23368. const int rh = rect->bottom - rect->top;
  23369. if ((rw > 50 && rh > 50 && rw < 2000 && rh < 2000 && rw != w && rh != h)
  23370. || ((w == 0 && rw > 0) || (h == 0 && rh > 0)))
  23371. {
  23372. // very dodgy logic to decide which size is right.
  23373. if (abs (rw - w) > 350 || abs (rh - h) > 350)
  23374. {
  23375. SetWindowPos (pluginHWND, 0,
  23376. 0, 0, rw, rh,
  23377. SWP_NOMOVE | SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER);
  23378. GetWindowRect (pluginHWND, &r);
  23379. w = r.right - r.left;
  23380. h = r.bottom - r.top;
  23381. pluginRefusesToResize = (w != rw) || (h != rh);
  23382. w = rw;
  23383. h = rh;
  23384. }
  23385. }
  23386. }
  23387. #elif JUCE_MAC
  23388. HIViewRef root = HIViewGetRoot ((WindowRef) getWindowHandle());
  23389. HIViewFindByID (root, kHIViewWindowContentID, &root);
  23390. pluginViewRef = HIViewGetFirstSubview (root);
  23391. while (pluginViewRef != 0 && juce_isHIViewCreatedByJuce (pluginViewRef))
  23392. pluginViewRef = HIViewGetNextView (pluginViewRef);
  23393. pluginWindowRef = 0;
  23394. if (pluginViewRef == 0)
  23395. {
  23396. WindowGroupRef ourGroup = GetWindowGroup ((WindowRef) getWindowHandle());
  23397. //DebugPrintWindowGroup (ourGroup);
  23398. //DebugPrintAllWindowGroups();
  23399. GetIndexedWindow (ourGroup, 1,
  23400. kWindowGroupContentsVisible,
  23401. &pluginWindowRef);
  23402. if (pluginWindowRef == (WindowRef) getWindowHandle()
  23403. || juce_isWindowCreatedByJuce (pluginWindowRef))
  23404. pluginWindowRef = 0;
  23405. }
  23406. int w = 250, h = 150;
  23407. if (rect != 0)
  23408. {
  23409. w = rect->right - rect->left;
  23410. h = rect->bottom - rect->top;
  23411. if (w == 0 || h == 0)
  23412. {
  23413. w = 250;
  23414. h = 150;
  23415. }
  23416. }
  23417. #elif JUCE_LINUX
  23418. pluginWindow = getChildWindow ((Window) getWindowHandle());
  23419. if (pluginWindow != 0)
  23420. pluginProc = (EventProcPtr) getPropertyFromXWindow (pluginWindow,
  23421. XInternAtom (display, "_XEventProc", False));
  23422. int w = 250, h = 150;
  23423. if (rect != 0)
  23424. {
  23425. w = rect->right - rect->left;
  23426. h = rect->bottom - rect->top;
  23427. if (w == 0 || h == 0)
  23428. {
  23429. w = 250;
  23430. h = 150;
  23431. }
  23432. }
  23433. if (pluginWindow != 0)
  23434. XMapRaised (display, pluginWindow);
  23435. #endif
  23436. // double-check it's not too tiny
  23437. w = jmax (w, 32);
  23438. h = jmax (h, 32);
  23439. setSize (w, h);
  23440. #if JUCE_WIN32
  23441. checkPluginWindowSize();
  23442. #endif
  23443. startTimer (18 + JUCE_NAMESPACE::Random::getSystemRandom().nextInt (5));
  23444. repaint();
  23445. }
  23446. void closePluginWindow()
  23447. {
  23448. if (isOpen)
  23449. {
  23450. log (T("Closing VST UI: ") + plugin.getName());
  23451. isOpen = false;
  23452. dispatch (effEditClose, 0, 0, 0, 0);
  23453. #if JUCE_WIN32
  23454. #pragma warning (push)
  23455. #pragma warning (disable: 4244)
  23456. if (pluginHWND != 0 && IsWindow (pluginHWND))
  23457. SetWindowLongPtr (pluginHWND, GWL_WNDPROC, (LONG_PTR) originalWndProc);
  23458. #pragma warning (pop)
  23459. stopTimer();
  23460. if (pluginHWND != 0 && IsWindow (pluginHWND))
  23461. DestroyWindow (pluginHWND);
  23462. pluginHWND = 0;
  23463. #elif JUCE_MAC
  23464. dispatch (effEditSleep, 0, 0, 0, 0);
  23465. pluginViewRef = 0;
  23466. stopTimer();
  23467. #elif JUCE_LINUX
  23468. stopTimer();
  23469. pluginWindow = 0;
  23470. pluginProc = 0;
  23471. #endif
  23472. }
  23473. }
  23474. #if JUCE_WIN32
  23475. void checkPluginWindowSize() throw()
  23476. {
  23477. RECT r;
  23478. GetWindowRect (pluginHWND, &r);
  23479. const int w = r.right - r.left;
  23480. const int h = r.bottom - r.top;
  23481. if (isShowing() && w > 0 && h > 0
  23482. && (w != getWidth() || h != getHeight())
  23483. && ! pluginRefusesToResize)
  23484. {
  23485. setSize (w, h);
  23486. sizeCheckCount = 0;
  23487. }
  23488. }
  23489. #endif
  23490. class CompMovementWatcher : public ComponentMovementWatcher
  23491. {
  23492. public:
  23493. CompMovementWatcher (VSTPluginWindow* const owner_)
  23494. : ComponentMovementWatcher (owner_),
  23495. owner (owner_)
  23496. {
  23497. }
  23498. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  23499. {
  23500. owner->componentMovedOrResized();
  23501. }
  23502. void componentPeerChanged()
  23503. {
  23504. owner->componentPeerChanged();
  23505. }
  23506. void componentVisibilityChanged (Component&)
  23507. {
  23508. owner->componentVisibilityChanged();
  23509. }
  23510. private:
  23511. VSTPluginWindow* const owner;
  23512. };
  23513. CompMovementWatcher* movementWatcher;
  23514. int dispatch (const int opcode, const int index, const int value, void* const ptr, float opt)
  23515. {
  23516. return plugin.dispatch (opcode, index, value, ptr, opt);
  23517. }
  23518. // hooks to get keyboard events from VST windows..
  23519. #if JUCE_WIN32
  23520. static LRESULT CALLBACK vstHookWndProc (HWND hW, UINT message, WPARAM wParam, LPARAM lParam)
  23521. {
  23522. for (int i = activeVSTWindows.size(); --i >= 0;)
  23523. {
  23524. const VSTPluginWindow* const w = (const VSTPluginWindow*) activeVSTWindows.getUnchecked (i);
  23525. if (w->pluginHWND == hW)
  23526. {
  23527. if (message == WM_CHAR
  23528. || message == WM_KEYDOWN
  23529. || message == WM_SYSKEYDOWN
  23530. || message == WM_KEYUP
  23531. || message == WM_SYSKEYUP
  23532. || message == WM_APPCOMMAND)
  23533. {
  23534. SendMessage ((HWND) w->getTopLevelComponent()->getWindowHandle(),
  23535. message, wParam, lParam);
  23536. }
  23537. return CallWindowProc ((WNDPROC) (w->originalWndProc),
  23538. (HWND) w->pluginHWND,
  23539. message,
  23540. wParam,
  23541. lParam);
  23542. }
  23543. }
  23544. return DefWindowProc (hW, message, wParam, lParam);
  23545. }
  23546. #endif
  23547. #if JUCE_LINUX
  23548. // overload mouse/keyboard events to forward them to the plugin's inner window..
  23549. void sendEventToChild (XEvent* event)
  23550. {
  23551. if (pluginProc != 0)
  23552. {
  23553. // if the plugin publishes an event procedure, pass the event directly..
  23554. pluginProc (event);
  23555. }
  23556. else if (pluginWindow != 0)
  23557. {
  23558. // if the plugin has a window, then send the event to the window so that
  23559. // its message thread will pick it up..
  23560. XSendEvent (display, pluginWindow, False, 0L, event);
  23561. XFlush (display);
  23562. }
  23563. }
  23564. void mouseEnter (const MouseEvent& e)
  23565. {
  23566. if (pluginWindow != 0)
  23567. {
  23568. XEvent ev;
  23569. zerostruct (ev);
  23570. ev.xcrossing.display = display;
  23571. ev.xcrossing.type = EnterNotify;
  23572. ev.xcrossing.window = pluginWindow;
  23573. ev.xcrossing.root = RootWindow (display, DefaultScreen (display));
  23574. ev.xcrossing.time = CurrentTime;
  23575. ev.xcrossing.x = e.x;
  23576. ev.xcrossing.y = e.y;
  23577. ev.xcrossing.x_root = e.getScreenX();
  23578. ev.xcrossing.y_root = e.getScreenY();
  23579. ev.xcrossing.mode = NotifyNormal; // NotifyGrab, NotifyUngrab
  23580. ev.xcrossing.detail = NotifyAncestor; // NotifyVirtual, NotifyInferior, NotifyNonlinear,NotifyNonlinearVirtual
  23581. translateJuceToXCrossingModifiers (e, ev);
  23582. sendEventToChild (&ev);
  23583. }
  23584. }
  23585. void mouseExit (const MouseEvent& e)
  23586. {
  23587. if (pluginWindow != 0)
  23588. {
  23589. XEvent ev;
  23590. zerostruct (ev);
  23591. ev.xcrossing.display = display;
  23592. ev.xcrossing.type = LeaveNotify;
  23593. ev.xcrossing.window = pluginWindow;
  23594. ev.xcrossing.root = RootWindow (display, DefaultScreen (display));
  23595. ev.xcrossing.time = CurrentTime;
  23596. ev.xcrossing.x = e.x;
  23597. ev.xcrossing.y = e.y;
  23598. ev.xcrossing.x_root = e.getScreenX();
  23599. ev.xcrossing.y_root = e.getScreenY();
  23600. ev.xcrossing.mode = NotifyNormal; // NotifyGrab, NotifyUngrab
  23601. ev.xcrossing.detail = NotifyAncestor; // NotifyVirtual, NotifyInferior, NotifyNonlinear,NotifyNonlinearVirtual
  23602. ev.xcrossing.focus = hasKeyboardFocus (true); // TODO - yes ?
  23603. translateJuceToXCrossingModifiers (e, ev);
  23604. sendEventToChild (&ev);
  23605. }
  23606. }
  23607. void mouseMove (const MouseEvent& e)
  23608. {
  23609. if (pluginWindow != 0)
  23610. {
  23611. XEvent ev;
  23612. zerostruct (ev);
  23613. ev.xmotion.display = display;
  23614. ev.xmotion.type = MotionNotify;
  23615. ev.xmotion.window = pluginWindow;
  23616. ev.xmotion.root = RootWindow (display, DefaultScreen (display));
  23617. ev.xmotion.time = CurrentTime;
  23618. ev.xmotion.is_hint = NotifyNormal;
  23619. ev.xmotion.x = e.x;
  23620. ev.xmotion.y = e.y;
  23621. ev.xmotion.x_root = e.getScreenX();
  23622. ev.xmotion.y_root = e.getScreenY();
  23623. sendEventToChild (&ev);
  23624. }
  23625. }
  23626. void mouseDrag (const MouseEvent& e)
  23627. {
  23628. if (pluginWindow != 0)
  23629. {
  23630. XEvent ev;
  23631. zerostruct (ev);
  23632. ev.xmotion.display = display;
  23633. ev.xmotion.type = MotionNotify;
  23634. ev.xmotion.window = pluginWindow;
  23635. ev.xmotion.root = RootWindow (display, DefaultScreen (display));
  23636. ev.xmotion.time = CurrentTime;
  23637. ev.xmotion.x = e.x ;
  23638. ev.xmotion.y = e.y;
  23639. ev.xmotion.x_root = e.getScreenX();
  23640. ev.xmotion.y_root = e.getScreenY();
  23641. ev.xmotion.is_hint = NotifyNormal;
  23642. translateJuceToXMotionModifiers (e, ev);
  23643. sendEventToChild (&ev);
  23644. }
  23645. }
  23646. void mouseUp (const MouseEvent& e)
  23647. {
  23648. if (pluginWindow != 0)
  23649. {
  23650. XEvent ev;
  23651. zerostruct (ev);
  23652. ev.xbutton.display = display;
  23653. ev.xbutton.type = ButtonRelease;
  23654. ev.xbutton.window = pluginWindow;
  23655. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  23656. ev.xbutton.time = CurrentTime;
  23657. ev.xbutton.x = e.x;
  23658. ev.xbutton.y = e.y;
  23659. ev.xbutton.x_root = e.getScreenX();
  23660. ev.xbutton.y_root = e.getScreenY();
  23661. translateJuceToXButtonModifiers (e, ev);
  23662. sendEventToChild (&ev);
  23663. }
  23664. }
  23665. void mouseWheelMove (const MouseEvent& e,
  23666. float incrementX,
  23667. float incrementY)
  23668. {
  23669. if (pluginWindow != 0)
  23670. {
  23671. XEvent ev;
  23672. zerostruct (ev);
  23673. ev.xbutton.display = display;
  23674. ev.xbutton.type = ButtonPress;
  23675. ev.xbutton.window = pluginWindow;
  23676. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  23677. ev.xbutton.time = CurrentTime;
  23678. ev.xbutton.x = e.x;
  23679. ev.xbutton.y = e.y;
  23680. ev.xbutton.x_root = e.getScreenX();
  23681. ev.xbutton.y_root = e.getScreenY();
  23682. translateJuceToXMouseWheelModifiers (e, incrementY, ev);
  23683. sendEventToChild (&ev);
  23684. // TODO - put a usleep here ?
  23685. ev.xbutton.type = ButtonRelease;
  23686. sendEventToChild (&ev);
  23687. }
  23688. }
  23689. #endif
  23690. };
  23691. AudioProcessorEditor* VSTPluginInstance::createEditor()
  23692. {
  23693. if (hasEditor())
  23694. return new VSTPluginWindow (*this);
  23695. return 0;
  23696. }
  23697. void VSTPluginInstance::handleAsyncUpdate()
  23698. {
  23699. // indicates that something about the plugin has changed..
  23700. updateHostDisplay();
  23701. }
  23702. bool VSTPluginInstance::restoreProgramSettings (const fxProgram* const prog)
  23703. {
  23704. if (vst_swap (prog->chunkMagic) == 'CcnK' && vst_swap (prog->fxMagic) == 'FxCk')
  23705. {
  23706. changeProgramName (getCurrentProgram(), prog->prgName);
  23707. for (int i = 0; i < vst_swap (prog->numParams); ++i)
  23708. setParameter (i, vst_swapFloat (prog->params[i]));
  23709. return true;
  23710. }
  23711. return false;
  23712. }
  23713. bool VSTPluginInstance::loadFromFXBFile (const void* const data,
  23714. const int dataSize)
  23715. {
  23716. if (dataSize < 28)
  23717. return false;
  23718. const fxSet* const set = (const fxSet*) data;
  23719. if ((vst_swap (set->chunkMagic) != 'CcnK' && vst_swap (set->chunkMagic) != 'KncC')
  23720. || vst_swap (set->version) > fxbVersionNum)
  23721. return false;
  23722. if (vst_swap (set->fxMagic) == 'FxBk')
  23723. {
  23724. // bank of programs
  23725. if (vst_swap (set->numPrograms) >= 0)
  23726. {
  23727. const int oldProg = getCurrentProgram();
  23728. const int numParams = vst_swap (((const fxProgram*) (set->programs))->numParams);
  23729. const int progLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  23730. for (int i = 0; i < vst_swap (set->numPrograms); ++i)
  23731. {
  23732. if (i != oldProg)
  23733. {
  23734. const fxProgram* const prog = (const fxProgram*) (((const char*) (set->programs)) + i * progLen);
  23735. if (((const char*) prog) - ((const char*) set) >= dataSize)
  23736. return false;
  23737. if (vst_swap (set->numPrograms) > 0)
  23738. setCurrentProgram (i);
  23739. if (! restoreProgramSettings (prog))
  23740. return false;
  23741. }
  23742. }
  23743. if (vst_swap (set->numPrograms) > 0)
  23744. setCurrentProgram (oldProg);
  23745. const fxProgram* const prog = (const fxProgram*) (((const char*) (set->programs)) + oldProg * progLen);
  23746. if (((const char*) prog) - ((const char*) set) >= dataSize)
  23747. return false;
  23748. if (! restoreProgramSettings (prog))
  23749. return false;
  23750. }
  23751. }
  23752. else if (vst_swap (set->fxMagic) == 'FxCk')
  23753. {
  23754. // single program
  23755. const fxProgram* const prog = (const fxProgram*) data;
  23756. if (vst_swap (prog->chunkMagic) != 'CcnK')
  23757. return false;
  23758. changeProgramName (getCurrentProgram(), prog->prgName);
  23759. for (int i = 0; i < vst_swap (prog->numParams); ++i)
  23760. setParameter (i, vst_swapFloat (prog->params[i]));
  23761. }
  23762. else if (vst_swap (set->fxMagic) == 'FBCh' || vst_swap (set->fxMagic) == 'hCBF')
  23763. {
  23764. // non-preset chunk
  23765. const fxChunkSet* const cset = (const fxChunkSet*) data;
  23766. if (vst_swap (cset->chunkSize) + sizeof (fxChunkSet) - 8 > (unsigned int) dataSize)
  23767. return false;
  23768. setChunkData (cset->chunk, vst_swap (cset->chunkSize), false);
  23769. }
  23770. else if (vst_swap (set->fxMagic) == 'FPCh' || vst_swap (set->fxMagic) == 'hCPF')
  23771. {
  23772. // preset chunk
  23773. const fxProgramSet* const cset = (const fxProgramSet*) data;
  23774. if (vst_swap (cset->chunkSize) + sizeof (fxProgramSet) - 8 > (unsigned int) dataSize)
  23775. return false;
  23776. setChunkData (cset->chunk, vst_swap (cset->chunkSize), true);
  23777. changeProgramName (getCurrentProgram(), cset->name);
  23778. }
  23779. else
  23780. {
  23781. return false;
  23782. }
  23783. return true;
  23784. }
  23785. void VSTPluginInstance::setParamsInProgramBlock (fxProgram* const prog) throw()
  23786. {
  23787. const int numParams = getNumParameters();
  23788. prog->chunkMagic = vst_swap ('CcnK');
  23789. prog->byteSize = 0;
  23790. prog->fxMagic = vst_swap ('FxCk');
  23791. prog->version = vst_swap (fxbVersionNum);
  23792. prog->fxID = vst_swap (getUID());
  23793. prog->fxVersion = vst_swap (getVersionNumber());
  23794. prog->numParams = vst_swap (numParams);
  23795. getCurrentProgramName().copyToBuffer (prog->prgName, sizeof (prog->prgName) - 1);
  23796. for (int i = 0; i < numParams; ++i)
  23797. prog->params[i] = vst_swapFloat (getParameter (i));
  23798. }
  23799. bool VSTPluginInstance::saveToFXBFile (MemoryBlock& dest, bool isFXB, int maxSizeMB)
  23800. {
  23801. const int numPrograms = getNumPrograms();
  23802. const int numParams = getNumParameters();
  23803. if (usesChunks())
  23804. {
  23805. if (isFXB)
  23806. {
  23807. MemoryBlock chunk;
  23808. getChunkData (chunk, false, maxSizeMB);
  23809. const int totalLen = sizeof (fxChunkSet) + chunk.getSize() - 8;
  23810. dest.setSize (totalLen, true);
  23811. fxChunkSet* const set = (fxChunkSet*) dest.getData();
  23812. set->chunkMagic = vst_swap ('CcnK');
  23813. set->byteSize = 0;
  23814. set->fxMagic = vst_swap ('FBCh');
  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. chunk.copyTo (set->chunk, 0, chunk.getSize());
  23821. }
  23822. else
  23823. {
  23824. MemoryBlock chunk;
  23825. getChunkData (chunk, true, maxSizeMB);
  23826. const int totalLen = sizeof (fxProgramSet) + chunk.getSize() - 8;
  23827. dest.setSize (totalLen, true);
  23828. fxProgramSet* const set = (fxProgramSet*) dest.getData();
  23829. set->chunkMagic = vst_swap ('CcnK');
  23830. set->byteSize = 0;
  23831. set->fxMagic = vst_swap ('FPCh');
  23832. set->version = vst_swap (fxbVersionNum);
  23833. set->fxID = vst_swap (getUID());
  23834. set->fxVersion = vst_swap (getVersionNumber());
  23835. set->numPrograms = vst_swap (numPrograms);
  23836. set->chunkSize = vst_swap (chunk.getSize());
  23837. getCurrentProgramName().copyToBuffer (set->name, sizeof (set->name) - 1);
  23838. chunk.copyTo (set->chunk, 0, chunk.getSize());
  23839. }
  23840. }
  23841. else
  23842. {
  23843. if (isFXB)
  23844. {
  23845. const int progLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  23846. const int len = (sizeof (fxSet) - sizeof (fxProgram)) + progLen * jmax (1, numPrograms);
  23847. dest.setSize (len, true);
  23848. fxSet* const set = (fxSet*) dest.getData();
  23849. set->chunkMagic = vst_swap ('CcnK');
  23850. set->byteSize = 0;
  23851. set->fxMagic = vst_swap ('FxBk');
  23852. set->version = vst_swap (fxbVersionNum);
  23853. set->fxID = vst_swap (getUID());
  23854. set->fxVersion = vst_swap (getVersionNumber());
  23855. set->numPrograms = vst_swap (numPrograms);
  23856. const int oldProgram = getCurrentProgram();
  23857. MemoryBlock oldSettings;
  23858. createTempParameterStore (oldSettings);
  23859. setParamsInProgramBlock ((fxProgram*) (((char*) (set->programs)) + oldProgram * progLen));
  23860. for (int i = 0; i < numPrograms; ++i)
  23861. {
  23862. if (i != oldProgram)
  23863. {
  23864. setCurrentProgram (i);
  23865. setParamsInProgramBlock ((fxProgram*) (((char*) (set->programs)) + i * progLen));
  23866. }
  23867. }
  23868. setCurrentProgram (oldProgram);
  23869. restoreFromTempParameterStore (oldSettings);
  23870. }
  23871. else
  23872. {
  23873. const int totalLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  23874. dest.setSize (totalLen, true);
  23875. setParamsInProgramBlock ((fxProgram*) dest.getData());
  23876. }
  23877. }
  23878. return true;
  23879. }
  23880. void VSTPluginInstance::getChunkData (MemoryBlock& mb, bool isPreset, int maxSizeMB) const
  23881. {
  23882. if (usesChunks())
  23883. {
  23884. void* data = 0;
  23885. const int bytes = dispatch (effGetChunk, isPreset ? 1 : 0, 0, &data, 0.0f);
  23886. if (data != 0 && bytes <= maxSizeMB * 1024 * 1024)
  23887. {
  23888. mb.setSize (bytes);
  23889. mb.copyFrom (data, 0, bytes);
  23890. }
  23891. }
  23892. }
  23893. void VSTPluginInstance::setChunkData (const char* data, int size, bool isPreset)
  23894. {
  23895. if (size > 0 && usesChunks())
  23896. {
  23897. dispatch (effSetChunk, isPreset ? 1 : 0, size, (void*) data, 0.0f);
  23898. if (! isPreset)
  23899. updateStoredProgramNames();
  23900. }
  23901. }
  23902. void VSTPluginInstance::timerCallback()
  23903. {
  23904. if (dispatch (effIdle, 0, 0, 0, 0) == 0)
  23905. stopTimer();
  23906. }
  23907. int VSTPluginInstance::dispatch (const int opcode, const int index, const int value, void* const ptr, float opt) const
  23908. {
  23909. const ScopedLock sl (lock);
  23910. ++insideVSTCallback;
  23911. int result = 0;
  23912. try
  23913. {
  23914. if (effect != 0)
  23915. {
  23916. #if JUCE_MAC
  23917. if (module->resFileId != 0)
  23918. UseResFile (module->resFileId);
  23919. CGrafPtr oldPort;
  23920. if (getActiveEditor() != 0)
  23921. {
  23922. int x = 0, y = 0;
  23923. getActiveEditor()->relativePositionToOtherComponent (getActiveEditor()->getTopLevelComponent(), x, y);
  23924. GetPort (&oldPort);
  23925. SetPortWindowPort ((WindowRef) getActiveEditor()->getWindowHandle());
  23926. SetOrigin (-x, -y);
  23927. }
  23928. #endif
  23929. result = effect->dispatcher (effect, opcode, index, value, ptr, opt);
  23930. #if JUCE_MAC
  23931. if (getActiveEditor() != 0)
  23932. SetPort (oldPort);
  23933. module->resFileId = CurResFile();
  23934. #endif
  23935. --insideVSTCallback;
  23936. return result;
  23937. }
  23938. }
  23939. catch (...)
  23940. {
  23941. //char s[512];
  23942. //sprintf (s, "dispatcher (%d, %d, %d, %x, %f)", opcode, index, value, (int)ptr, opt);
  23943. }
  23944. --insideVSTCallback;
  23945. return result;
  23946. }
  23947. // handles non plugin-specific callbacks..
  23948. static VstIntPtr handleGeneralCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt)
  23949. {
  23950. (void) index;
  23951. (void) value;
  23952. (void) opt;
  23953. switch (opcode)
  23954. {
  23955. case audioMasterCanDo:
  23956. {
  23957. static const char* canDos[] = { "supplyIdle",
  23958. "sendVstEvents",
  23959. "sendVstMidiEvent",
  23960. "sendVstTimeInfo",
  23961. "receiveVstEvents",
  23962. "receiveVstMidiEvent",
  23963. "supportShell",
  23964. "shellCategory" };
  23965. for (int i = 0; i < numElementsInArray (canDos); ++i)
  23966. if (strcmp (canDos[i], (const char*) ptr) == 0)
  23967. return 1;
  23968. return 0;
  23969. }
  23970. case audioMasterVersion:
  23971. return 0x2400;
  23972. case audioMasterCurrentId:
  23973. return shellUIDToCreate;
  23974. case audioMasterGetNumAutomatableParameters:
  23975. return 0;
  23976. case audioMasterGetAutomationState:
  23977. return 1;
  23978. case audioMasterGetVendorVersion:
  23979. return 0x0101;
  23980. case audioMasterGetVendorString:
  23981. case audioMasterGetProductString:
  23982. JUCEApplication::getInstance()
  23983. ->getApplicationName().copyToBuffer ((char*) ptr, jmin (kVstMaxVendorStrLen, kVstMaxProductStrLen) - 1);
  23984. break;
  23985. case audioMasterGetSampleRate:
  23986. return 44100;
  23987. case audioMasterGetBlockSize:
  23988. return 512;
  23989. case audioMasterSetOutputSampleRate:
  23990. return 0;
  23991. default:
  23992. DBG ("*** Unhandled VST Callback: " + String ((int) opcode));
  23993. break;
  23994. }
  23995. return 0;
  23996. }
  23997. // handles callbacks for a specific plugin
  23998. VstIntPtr VSTPluginInstance::handleCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt)
  23999. {
  24000. switch (opcode)
  24001. {
  24002. case audioMasterAutomate:
  24003. sendParamChangeMessageToListeners (index, opt);
  24004. break;
  24005. case audioMasterProcessEvents:
  24006. handleMidiFromPlugin ((const VstEvents*) ptr);
  24007. break;
  24008. case audioMasterGetTime:
  24009. #ifdef _MSC_VER
  24010. #pragma warning (push)
  24011. #pragma warning (disable: 4311)
  24012. #endif
  24013. return (VstIntPtr) &vstHostTime;
  24014. #ifdef _MSC_VER
  24015. #pragma warning (pop)
  24016. #endif
  24017. break;
  24018. case audioMasterIdle:
  24019. if (insideVSTCallback == 0 && MessageManager::getInstance()->isThisTheMessageThread())
  24020. {
  24021. ++insideVSTCallback;
  24022. #if JUCE_MAC
  24023. if (getActiveEditor() != 0)
  24024. dispatch (effEditIdle, 0, 0, 0, 0);
  24025. #endif
  24026. const MessageManagerLock mml;
  24027. juce_callAnyTimersSynchronously();
  24028. handleUpdateNowIfNeeded();
  24029. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  24030. ComponentPeer::getPeer (i)->performAnyPendingRepaintsNow();
  24031. --insideVSTCallback;
  24032. }
  24033. break;
  24034. case audioMasterUpdateDisplay:
  24035. triggerAsyncUpdate();
  24036. break;
  24037. case audioMasterTempoAt:
  24038. // returns (10000 * bpm)
  24039. break;
  24040. case audioMasterNeedIdle:
  24041. startTimer (50);
  24042. break;
  24043. case audioMasterSizeWindow:
  24044. if (getActiveEditor() != 0)
  24045. getActiveEditor()->setSize (index, value);
  24046. return 1;
  24047. case audioMasterGetSampleRate:
  24048. return (VstIntPtr) getSampleRate();
  24049. case audioMasterGetBlockSize:
  24050. return (VstIntPtr) getBlockSize();
  24051. case audioMasterWantMidi:
  24052. wantsMidiMessages = true;
  24053. break;
  24054. case audioMasterGetDirectory:
  24055. #if JUCE_MAC
  24056. return (VstIntPtr) (void*) &module->parentDirFSSpec;
  24057. #else
  24058. return (VstIntPtr) (pointer_sized_uint) (const char*) module->fullParentDirectoryPathName;
  24059. #endif
  24060. case audioMasterGetAutomationState:
  24061. // returns 0: not supported, 1: off, 2:read, 3:write, 4:read/write
  24062. break;
  24063. // none of these are handled (yet)..
  24064. case audioMasterBeginEdit:
  24065. case audioMasterEndEdit:
  24066. case audioMasterSetTime:
  24067. case audioMasterPinConnected:
  24068. case audioMasterGetParameterQuantization:
  24069. case audioMasterIOChanged:
  24070. case audioMasterGetInputLatency:
  24071. case audioMasterGetOutputLatency:
  24072. case audioMasterGetPreviousPlug:
  24073. case audioMasterGetNextPlug:
  24074. case audioMasterWillReplaceOrAccumulate:
  24075. case audioMasterGetCurrentProcessLevel:
  24076. case audioMasterOfflineStart:
  24077. case audioMasterOfflineRead:
  24078. case audioMasterOfflineWrite:
  24079. case audioMasterOfflineGetCurrentPass:
  24080. case audioMasterOfflineGetCurrentMetaPass:
  24081. case audioMasterVendorSpecific:
  24082. case audioMasterSetIcon:
  24083. case audioMasterGetLanguage:
  24084. case audioMasterOpenWindow:
  24085. case audioMasterCloseWindow:
  24086. break;
  24087. default:
  24088. return handleGeneralCallback (opcode, index, value, ptr, opt);
  24089. }
  24090. return 0;
  24091. }
  24092. // entry point for all callbacks from the plugin
  24093. static VstIntPtr VSTCALLBACK audioMaster (AEffect* effect, VstInt32 opcode, VstInt32 index, VstIntPtr value, void* ptr, float opt)
  24094. {
  24095. try
  24096. {
  24097. if (effect != 0 && effect->resvd2 != 0)
  24098. {
  24099. return ((VSTPluginInstance*)(effect->resvd2))
  24100. ->handleCallback (opcode, index, value, ptr, opt);
  24101. }
  24102. return handleGeneralCallback (opcode, index, value, ptr, opt);
  24103. }
  24104. catch (...)
  24105. {
  24106. return 0;
  24107. }
  24108. }
  24109. const String VSTPluginInstance::getVersion() const throw()
  24110. {
  24111. int v = dispatch (effGetVendorVersion, 0, 0, 0, 0);
  24112. String s;
  24113. if (v != 0)
  24114. {
  24115. int versionBits[4];
  24116. int n = 0;
  24117. while (v != 0)
  24118. {
  24119. versionBits [n++] = (v & 0xff);
  24120. v >>= 8;
  24121. }
  24122. s << 'V';
  24123. while (n > 0)
  24124. {
  24125. s << versionBits [--n];
  24126. if (n > 0)
  24127. s << '.';
  24128. }
  24129. }
  24130. return s;
  24131. }
  24132. int VSTPluginInstance::getUID() const throw()
  24133. {
  24134. int uid = effect != 0 ? effect->uniqueID : 0;
  24135. if (uid == 0)
  24136. uid = module->file.hashCode();
  24137. return uid;
  24138. }
  24139. const String VSTPluginInstance::getCategory() const throw()
  24140. {
  24141. const char* result = 0;
  24142. switch (dispatch (effGetPlugCategory, 0, 0, 0, 0))
  24143. {
  24144. case kPlugCategEffect:
  24145. result = "Effect";
  24146. break;
  24147. case kPlugCategSynth:
  24148. result = "Synth";
  24149. break;
  24150. case kPlugCategAnalysis:
  24151. result = "Anaylsis";
  24152. break;
  24153. case kPlugCategMastering:
  24154. result = "Mastering";
  24155. break;
  24156. case kPlugCategSpacializer:
  24157. result = "Spacial";
  24158. break;
  24159. case kPlugCategRoomFx:
  24160. result = "Reverb";
  24161. break;
  24162. case kPlugSurroundFx:
  24163. result = "Surround";
  24164. break;
  24165. case kPlugCategRestoration:
  24166. result = "Restoration";
  24167. break;
  24168. case kPlugCategGenerator:
  24169. result = "Tone generation";
  24170. break;
  24171. default:
  24172. break;
  24173. }
  24174. return result;
  24175. }
  24176. float VSTPluginInstance::getParameter (int index)
  24177. {
  24178. if (effect != 0 && ((unsigned int) index) < (unsigned int) effect->numParams)
  24179. {
  24180. try
  24181. {
  24182. const ScopedLock sl (lock);
  24183. return effect->getParameter (effect, index);
  24184. }
  24185. catch (...)
  24186. {
  24187. }
  24188. }
  24189. return 0.0f;
  24190. }
  24191. void VSTPluginInstance::setParameter (int index, float newValue)
  24192. {
  24193. if (effect != 0 && ((unsigned int) index) < (unsigned int) effect->numParams)
  24194. {
  24195. try
  24196. {
  24197. const ScopedLock sl (lock);
  24198. if (effect->getParameter (effect, index) != newValue)
  24199. effect->setParameter (effect, index, newValue);
  24200. }
  24201. catch (...)
  24202. {
  24203. }
  24204. }
  24205. }
  24206. const String VSTPluginInstance::getParameterName (int index)
  24207. {
  24208. if (effect != 0)
  24209. {
  24210. jassert (index >= 0 && index < effect->numParams);
  24211. char nm [256];
  24212. zerostruct (nm);
  24213. dispatch (effGetParamName, index, 0, nm, 0);
  24214. return String (nm).trim();
  24215. }
  24216. return String::empty;
  24217. }
  24218. const String VSTPluginInstance::getParameterLabel (int index) const
  24219. {
  24220. if (effect != 0)
  24221. {
  24222. jassert (index >= 0 && index < effect->numParams);
  24223. char nm [256];
  24224. zerostruct (nm);
  24225. dispatch (effGetParamLabel, index, 0, nm, 0);
  24226. return String (nm).trim();
  24227. }
  24228. return String::empty;
  24229. }
  24230. const String VSTPluginInstance::getParameterText (int index)
  24231. {
  24232. if (effect != 0)
  24233. {
  24234. jassert (index >= 0 && index < effect->numParams);
  24235. char nm [256];
  24236. zerostruct (nm);
  24237. dispatch (effGetParamDisplay, index, 0, nm, 0);
  24238. return String (nm).trim();
  24239. }
  24240. return String::empty;
  24241. }
  24242. bool VSTPluginInstance::isParameterAutomatable (int index) const
  24243. {
  24244. if (effect != 0)
  24245. {
  24246. jassert (index >= 0 && index < effect->numParams);
  24247. return dispatch (effCanBeAutomated, index, 0, 0, 0) != 0;
  24248. }
  24249. return false;
  24250. }
  24251. void VSTPluginInstance::createTempParameterStore (MemoryBlock& dest)
  24252. {
  24253. dest.setSize (64 + 4 * getNumParameters());
  24254. dest.fillWith (0);
  24255. getCurrentProgramName().copyToBuffer ((char*) dest.getData(), 63);
  24256. float* const p = (float*) (((char*) dest.getData()) + 64);
  24257. for (int i = 0; i < getNumParameters(); ++i)
  24258. p[i] = getParameter(i);
  24259. }
  24260. void VSTPluginInstance::restoreFromTempParameterStore (const MemoryBlock& m)
  24261. {
  24262. changeProgramName (getCurrentProgram(), (const char*) m.getData());
  24263. float* p = (float*) (((char*) m.getData()) + 64);
  24264. for (int i = 0; i < getNumParameters(); ++i)
  24265. setParameter (i, p[i]);
  24266. }
  24267. void VSTPluginInstance::setCurrentProgram (int newIndex)
  24268. {
  24269. if (getNumPrograms() > 0 && newIndex != getCurrentProgram())
  24270. dispatch (effSetProgram, 0, jlimit (0, getNumPrograms() - 1, newIndex), 0, 0);
  24271. }
  24272. const String VSTPluginInstance::getProgramName (int index)
  24273. {
  24274. if (index == getCurrentProgram())
  24275. {
  24276. return getCurrentProgramName();
  24277. }
  24278. else if (effect != 0)
  24279. {
  24280. char nm [256];
  24281. zerostruct (nm);
  24282. if (dispatch (effGetProgramNameIndexed,
  24283. jlimit (0, getNumPrograms(), index),
  24284. -1, nm, 0) != 0)
  24285. {
  24286. return String (nm).trim();
  24287. }
  24288. }
  24289. return programNames [index];
  24290. }
  24291. void VSTPluginInstance::changeProgramName (int index, const String& newName)
  24292. {
  24293. if (index == getCurrentProgram())
  24294. {
  24295. if (getNumPrograms() > 0 && newName != getCurrentProgramName())
  24296. dispatch (effSetProgramName, 0, 0, (void*) (const char*) newName.substring (0, 24), 0.0f);
  24297. }
  24298. else
  24299. {
  24300. jassertfalse // xxx not implemented!
  24301. }
  24302. }
  24303. void VSTPluginInstance::updateStoredProgramNames()
  24304. {
  24305. if (effect != 0 && getNumPrograms() > 0)
  24306. {
  24307. char nm [256];
  24308. zerostruct (nm);
  24309. // only do this if the plugin can't use indexed names..
  24310. if (dispatch (effGetProgramNameIndexed, 0, -1, nm, 0) == 0)
  24311. {
  24312. const int oldProgram = getCurrentProgram();
  24313. MemoryBlock oldSettings;
  24314. createTempParameterStore (oldSettings);
  24315. for (int i = 0; i < getNumPrograms(); ++i)
  24316. {
  24317. setCurrentProgram (i);
  24318. getCurrentProgramName(); // (this updates the list)
  24319. }
  24320. setCurrentProgram (oldProgram);
  24321. restoreFromTempParameterStore (oldSettings);
  24322. }
  24323. }
  24324. }
  24325. const String VSTPluginInstance::getCurrentProgramName()
  24326. {
  24327. if (effect != 0)
  24328. {
  24329. char nm [256];
  24330. zerostruct (nm);
  24331. dispatch (effGetProgramName, 0, 0, nm, 0);
  24332. const int index = getCurrentProgram();
  24333. if (programNames[index].isEmpty())
  24334. {
  24335. while (programNames.size() < index)
  24336. programNames.add (String::empty);
  24337. programNames.set (index, String (nm).trim());
  24338. }
  24339. return String (nm).trim();
  24340. }
  24341. return String::empty;
  24342. }
  24343. const String VSTPluginInstance::getInputChannelName (const int index) const
  24344. {
  24345. if (index >= 0 && index < getNumInputChannels())
  24346. {
  24347. VstPinProperties pinProps;
  24348. if (dispatch (effGetInputProperties, index, 0, &pinProps, 0.0f) != 0)
  24349. return String (pinProps.label, sizeof (pinProps.label));
  24350. }
  24351. return String::empty;
  24352. }
  24353. bool VSTPluginInstance::isInputChannelStereoPair (int index) const
  24354. {
  24355. if (index < 0 || index >= getNumInputChannels())
  24356. return false;
  24357. VstPinProperties pinProps;
  24358. if (dispatch (effGetInputProperties, index, 0, &pinProps, 0.0f) != 0)
  24359. return (pinProps.flags & kVstPinIsStereo) != 0;
  24360. return true;
  24361. }
  24362. const String VSTPluginInstance::getOutputChannelName (const int index) const
  24363. {
  24364. if (index >= 0 && index < getNumOutputChannels())
  24365. {
  24366. VstPinProperties pinProps;
  24367. if (dispatch (effGetOutputProperties, index, 0, &pinProps, 0.0f) != 0)
  24368. return String (pinProps.label, sizeof (pinProps.label));
  24369. }
  24370. return String::empty;
  24371. }
  24372. bool VSTPluginInstance::isOutputChannelStereoPair (int index) const
  24373. {
  24374. if (index < 0 || index >= getNumOutputChannels())
  24375. return false;
  24376. VstPinProperties pinProps;
  24377. if (dispatch (effGetOutputProperties, index, 0, &pinProps, 0.0f) != 0)
  24378. return (pinProps.flags & kVstPinIsStereo) != 0;
  24379. return true;
  24380. }
  24381. void VSTPluginInstance::setPower (const bool on)
  24382. {
  24383. dispatch (effMainsChanged, 0, on ? 1 : 0, 0, 0);
  24384. isPowerOn = on;
  24385. }
  24386. const int defaultMaxSizeMB = 64;
  24387. void VSTPluginInstance::getStateInformation (MemoryBlock& destData)
  24388. {
  24389. saveToFXBFile (destData, true, defaultMaxSizeMB);
  24390. }
  24391. void VSTPluginInstance::getCurrentProgramStateInformation (MemoryBlock& destData)
  24392. {
  24393. saveToFXBFile (destData, false, defaultMaxSizeMB);
  24394. }
  24395. void VSTPluginInstance::setStateInformation (const void* data, int sizeInBytes)
  24396. {
  24397. loadFromFXBFile (data, sizeInBytes);
  24398. }
  24399. void VSTPluginInstance::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  24400. {
  24401. loadFromFXBFile (data, sizeInBytes);
  24402. }
  24403. VSTPluginFormat::VSTPluginFormat()
  24404. {
  24405. }
  24406. VSTPluginFormat::~VSTPluginFormat()
  24407. {
  24408. }
  24409. void VSTPluginFormat::findAllTypesForFile (OwnedArray <PluginDescription>& results,
  24410. const File& file)
  24411. {
  24412. if (! fileMightContainThisPluginType (file))
  24413. return;
  24414. PluginDescription desc;
  24415. desc.file = file;
  24416. desc.uid = 0;
  24417. VSTPluginInstance* instance = dynamic_cast <VSTPluginInstance*> (createInstanceFromDescription (desc));
  24418. if (instance == 0)
  24419. return;
  24420. try
  24421. {
  24422. #if JUCE_MAC
  24423. if (instance->module->resFileId != 0)
  24424. UseResFile (instance->module->resFileId);
  24425. #endif
  24426. instance->fillInPluginDescription (desc);
  24427. VstPlugCategory category = (VstPlugCategory) instance->dispatch (effGetPlugCategory, 0, 0, 0, 0);
  24428. if (category != kPlugCategShell)
  24429. {
  24430. // Normal plugin...
  24431. results.add (new PluginDescription (desc));
  24432. ++insideVSTCallback;
  24433. instance->dispatch (effOpen, 0, 0, 0, 0);
  24434. --insideVSTCallback;
  24435. }
  24436. else
  24437. {
  24438. // It's a shell plugin, so iterate all the subtypes...
  24439. char shellEffectName [64];
  24440. for (;;)
  24441. {
  24442. zerostruct (shellEffectName);
  24443. const int uid = instance->dispatch (effShellGetNextPlugin, 0, 0, shellEffectName, 0);
  24444. if (uid == 0)
  24445. {
  24446. break;
  24447. }
  24448. else
  24449. {
  24450. desc.uid = uid;
  24451. desc.name = shellEffectName;
  24452. bool alreadyThere = false;
  24453. for (int i = results.size(); --i >= 0;)
  24454. {
  24455. PluginDescription* const d = results.getUnchecked(i);
  24456. if (d->isDuplicateOf (desc))
  24457. {
  24458. alreadyThere = true;
  24459. break;
  24460. }
  24461. }
  24462. if (! alreadyThere)
  24463. results.add (new PluginDescription (desc));
  24464. }
  24465. }
  24466. }
  24467. }
  24468. catch (...)
  24469. {
  24470. // crashed while loading...
  24471. }
  24472. deleteAndZero (instance);
  24473. }
  24474. AudioPluginInstance* VSTPluginFormat::createInstanceFromDescription (const PluginDescription& desc)
  24475. {
  24476. VSTPluginInstance* result = 0;
  24477. if (fileMightContainThisPluginType (desc.file))
  24478. {
  24479. const File previousWorkingDirectory (File::getCurrentWorkingDirectory());
  24480. desc.file.getParentDirectory().setAsCurrentWorkingDirectory();
  24481. const ReferenceCountedObjectPtr <ModuleHandle> module (ModuleHandle::findOrCreateModule (desc.file));
  24482. if (module != 0)
  24483. {
  24484. shellUIDToCreate = desc.uid;
  24485. result = new VSTPluginInstance (module);
  24486. if (result->effect != 0)
  24487. {
  24488. result->effect->resvd2 = (VstIntPtr) (pointer_sized_int) result;
  24489. result->initialise();
  24490. }
  24491. else
  24492. {
  24493. deleteAndZero (result);
  24494. }
  24495. }
  24496. previousWorkingDirectory.setAsCurrentWorkingDirectory();
  24497. }
  24498. return result;
  24499. }
  24500. bool VSTPluginFormat::fileMightContainThisPluginType (const File& f)
  24501. {
  24502. #if JUCE_MAC
  24503. if (f.isDirectory() && f.hasFileExtension (T(".vst")))
  24504. return true;
  24505. #if JUCE_PPC
  24506. FSRef fileRef;
  24507. if (PlatformUtilities::makeFSRefFromPath (&fileRef, f.getFullPathName()))
  24508. {
  24509. const short resFileId = FSOpenResFile (&fileRef, fsRdPerm);
  24510. if (resFileId != -1)
  24511. {
  24512. const int numEffects = Count1Resources ('aEff');
  24513. CloseResFile (resFileId);
  24514. if (numEffects > 0)
  24515. return true;
  24516. }
  24517. }
  24518. #endif
  24519. return false;
  24520. #elif JUCE_WIN32
  24521. return f.existsAsFile()
  24522. && f.hasFileExtension (T(".dll"));
  24523. #elif JUCE_LINUX
  24524. return f.existsAsFile()
  24525. && f.hasFileExtension (T(".so"));
  24526. #endif
  24527. }
  24528. const FileSearchPath VSTPluginFormat::getDefaultLocationsToSearch()
  24529. {
  24530. #if JUCE_MAC
  24531. return FileSearchPath ("~/Library/Audio/Plug-Ins/VST;/Library/Audio/Plug-Ins/VST");
  24532. #elif JUCE_WIN32
  24533. const String programFiles (File::getSpecialLocation (File::globalApplicationsDirectory).getFullPathName());
  24534. return FileSearchPath (programFiles + "\\Steinberg\\VstPlugins");
  24535. #elif JUCE_LINUX
  24536. return FileSearchPath ("/usr/lib/vst");
  24537. #endif
  24538. }
  24539. END_JUCE_NAMESPACE
  24540. #undef log
  24541. #endif
  24542. /********* End of inlined file: juce_VSTPluginFormat.cpp *********/
  24543. /********* Start of inlined file: juce_AudioProcessor.cpp *********/
  24544. BEGIN_JUCE_NAMESPACE
  24545. AudioProcessor::AudioProcessor()
  24546. : playHead (0),
  24547. activeEditor (0),
  24548. sampleRate (0),
  24549. blockSize (0),
  24550. numInputChannels (0),
  24551. numOutputChannels (0),
  24552. latencySamples (0),
  24553. suspended (false),
  24554. nonRealtime (false)
  24555. {
  24556. }
  24557. AudioProcessor::~AudioProcessor()
  24558. {
  24559. // ooh, nasty - the editor should have been deleted before the filter
  24560. // that it refers to is deleted..
  24561. jassert (activeEditor == 0);
  24562. #ifdef JUCE_DEBUG
  24563. // This will fail if you've called beginParameterChangeGesture() for one
  24564. // or more parameters without having made a corresponding call to endParameterChangeGesture...
  24565. jassert (changingParams.countNumberOfSetBits() == 0);
  24566. #endif
  24567. }
  24568. void AudioProcessor::setPlayHead (AudioPlayHead* const newPlayHead) throw()
  24569. {
  24570. playHead = newPlayHead;
  24571. }
  24572. void AudioProcessor::addListener (AudioProcessorListener* const newListener) throw()
  24573. {
  24574. const ScopedLock sl (listenerLock);
  24575. listeners.addIfNotAlreadyThere (newListener);
  24576. }
  24577. void AudioProcessor::removeListener (AudioProcessorListener* const listenerToRemove) throw()
  24578. {
  24579. const ScopedLock sl (listenerLock);
  24580. listeners.removeValue (listenerToRemove);
  24581. }
  24582. void AudioProcessor::setPlayConfigDetails (const int numIns,
  24583. const int numOuts,
  24584. const double sampleRate_,
  24585. const int blockSize_) throw()
  24586. {
  24587. numInputChannels = numIns;
  24588. numOutputChannels = numOuts;
  24589. sampleRate = sampleRate_;
  24590. blockSize = blockSize_;
  24591. }
  24592. void AudioProcessor::setNonRealtime (const bool nonRealtime_) throw()
  24593. {
  24594. nonRealtime = nonRealtime_;
  24595. }
  24596. void AudioProcessor::setLatencySamples (const int newLatency)
  24597. {
  24598. if (latencySamples != newLatency)
  24599. {
  24600. latencySamples = newLatency;
  24601. updateHostDisplay();
  24602. }
  24603. }
  24604. void AudioProcessor::setParameterNotifyingHost (const int parameterIndex,
  24605. const float newValue)
  24606. {
  24607. setParameter (parameterIndex, newValue);
  24608. sendParamChangeMessageToListeners (parameterIndex, newValue);
  24609. }
  24610. void AudioProcessor::sendParamChangeMessageToListeners (const int parameterIndex, const float newValue)
  24611. {
  24612. jassert (((unsigned int) parameterIndex) < (unsigned int) getNumParameters());
  24613. for (int i = listeners.size(); --i >= 0;)
  24614. {
  24615. listenerLock.enter();
  24616. AudioProcessorListener* const l = (AudioProcessorListener*) listeners [i];
  24617. listenerLock.exit();
  24618. if (l != 0)
  24619. l->audioProcessorParameterChanged (this, parameterIndex, newValue);
  24620. }
  24621. }
  24622. void AudioProcessor::beginParameterChangeGesture (int parameterIndex)
  24623. {
  24624. jassert (((unsigned int) parameterIndex) < (unsigned int) getNumParameters());
  24625. #ifdef JUCE_DEBUG
  24626. // This means you've called beginParameterChangeGesture twice in succession without a matching
  24627. // call to endParameterChangeGesture. That might be fine in most hosts, but better to avoid doing it.
  24628. jassert (! changingParams [parameterIndex]);
  24629. changingParams.setBit (parameterIndex);
  24630. #endif
  24631. for (int i = listeners.size(); --i >= 0;)
  24632. {
  24633. listenerLock.enter();
  24634. AudioProcessorListener* const l = (AudioProcessorListener*) listeners [i];
  24635. listenerLock.exit();
  24636. if (l != 0)
  24637. l->audioProcessorParameterChangeGestureBegin (this, parameterIndex);
  24638. }
  24639. }
  24640. void AudioProcessor::endParameterChangeGesture (int parameterIndex)
  24641. {
  24642. jassert (((unsigned int) parameterIndex) < (unsigned int) getNumParameters());
  24643. #ifdef JUCE_DEBUG
  24644. // This means you've called endParameterChangeGesture without having previously called
  24645. // endParameterChangeGesture. That might be fine in most hosts, but better to keep the
  24646. // calls matched correctly.
  24647. jassert (changingParams [parameterIndex]);
  24648. changingParams.clearBit (parameterIndex);
  24649. #endif
  24650. for (int i = listeners.size(); --i >= 0;)
  24651. {
  24652. listenerLock.enter();
  24653. AudioProcessorListener* const l = (AudioProcessorListener*) listeners [i];
  24654. listenerLock.exit();
  24655. if (l != 0)
  24656. l->audioProcessorParameterChangeGestureEnd (this, parameterIndex);
  24657. }
  24658. }
  24659. void AudioProcessor::updateHostDisplay()
  24660. {
  24661. for (int i = listeners.size(); --i >= 0;)
  24662. {
  24663. listenerLock.enter();
  24664. AudioProcessorListener* const l = (AudioProcessorListener*) listeners [i];
  24665. listenerLock.exit();
  24666. if (l != 0)
  24667. l->audioProcessorChanged (this);
  24668. }
  24669. }
  24670. bool AudioProcessor::isParameterAutomatable (int /*index*/) const
  24671. {
  24672. return true;
  24673. }
  24674. void AudioProcessor::suspendProcessing (const bool shouldBeSuspended)
  24675. {
  24676. const ScopedLock sl (callbackLock);
  24677. suspended = shouldBeSuspended;
  24678. }
  24679. void AudioProcessor::editorBeingDeleted (AudioProcessorEditor* const editor) throw()
  24680. {
  24681. const ScopedLock sl (callbackLock);
  24682. jassert (activeEditor == editor);
  24683. if (activeEditor == editor)
  24684. activeEditor = 0;
  24685. }
  24686. AudioProcessorEditor* AudioProcessor::createEditorIfNeeded()
  24687. {
  24688. if (activeEditor != 0)
  24689. return activeEditor;
  24690. AudioProcessorEditor* const ed = createEditor();
  24691. if (ed != 0)
  24692. {
  24693. // you must give your editor comp a size before returning it..
  24694. jassert (ed->getWidth() > 0 && ed->getHeight() > 0);
  24695. const ScopedLock sl (callbackLock);
  24696. activeEditor = ed;
  24697. }
  24698. return ed;
  24699. }
  24700. void AudioProcessor::getCurrentProgramStateInformation (JUCE_NAMESPACE::MemoryBlock& destData)
  24701. {
  24702. getStateInformation (destData);
  24703. }
  24704. void AudioProcessor::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  24705. {
  24706. setStateInformation (data, sizeInBytes);
  24707. }
  24708. // magic number to identify memory blocks that we've stored as XML
  24709. const uint32 magicXmlNumber = 0x21324356;
  24710. void AudioProcessor::copyXmlToBinary (const XmlElement& xml,
  24711. JUCE_NAMESPACE::MemoryBlock& destData)
  24712. {
  24713. const String xmlString (xml.createDocument (String::empty, true, false));
  24714. const int stringLength = xmlString.length();
  24715. destData.setSize (stringLength + 10);
  24716. char* const d = (char*) destData.getData();
  24717. *(uint32*) d = swapIfBigEndian ((const uint32) magicXmlNumber);
  24718. *(uint32*) (d + 4) = swapIfBigEndian ((const uint32) stringLength);
  24719. xmlString.copyToBuffer (d + 8, stringLength);
  24720. }
  24721. XmlElement* AudioProcessor::getXmlFromBinary (const void* data,
  24722. const int sizeInBytes)
  24723. {
  24724. if (sizeInBytes > 8
  24725. && littleEndianInt ((const char*) data) == magicXmlNumber)
  24726. {
  24727. const uint32 stringLength = littleEndianInt (((const char*) data) + 4);
  24728. if (stringLength > 0)
  24729. {
  24730. XmlDocument doc (String (((const char*) data) + 8,
  24731. jmin ((sizeInBytes - 8), stringLength)));
  24732. return doc.getDocumentElement();
  24733. }
  24734. }
  24735. return 0;
  24736. }
  24737. void AudioProcessorListener::audioProcessorParameterChangeGestureBegin (AudioProcessor*, int)
  24738. {
  24739. }
  24740. void AudioProcessorListener::audioProcessorParameterChangeGestureEnd (AudioProcessor*, int)
  24741. {
  24742. }
  24743. END_JUCE_NAMESPACE
  24744. /********* End of inlined file: juce_AudioProcessor.cpp *********/
  24745. /********* Start of inlined file: juce_AudioProcessorEditor.cpp *********/
  24746. BEGIN_JUCE_NAMESPACE
  24747. AudioProcessorEditor::AudioProcessorEditor (AudioProcessor* const owner_)
  24748. : owner (owner_)
  24749. {
  24750. // the filter must be valid..
  24751. jassert (owner != 0);
  24752. }
  24753. AudioProcessorEditor::~AudioProcessorEditor()
  24754. {
  24755. // if this fails, then the wrapper hasn't called editorBeingDeleted() on the
  24756. // filter for some reason..
  24757. jassert (owner->getActiveEditor() != this);
  24758. }
  24759. END_JUCE_NAMESPACE
  24760. /********* End of inlined file: juce_AudioProcessorEditor.cpp *********/
  24761. /********* Start of inlined file: juce_AudioProcessorGraph.cpp *********/
  24762. BEGIN_JUCE_NAMESPACE
  24763. const int AudioProcessorGraph::midiChannelIndex = 0x1000;
  24764. AudioProcessorGraph::Node::Node (const uint32 id_,
  24765. AudioProcessor* const processor_) throw()
  24766. : id (id_),
  24767. processor (processor_),
  24768. isPrepared (false)
  24769. {
  24770. jassert (processor_ != 0);
  24771. }
  24772. AudioProcessorGraph::Node::~Node()
  24773. {
  24774. delete processor;
  24775. }
  24776. void AudioProcessorGraph::Node::prepare (const double sampleRate, const int blockSize,
  24777. AudioProcessorGraph* const graph)
  24778. {
  24779. if (! isPrepared)
  24780. {
  24781. isPrepared = true;
  24782. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  24783. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (processor);
  24784. if (ioProc != 0)
  24785. ioProc->setParentGraph (graph);
  24786. processor->setPlayConfigDetails (processor->getNumInputChannels(),
  24787. processor->getNumOutputChannels(),
  24788. sampleRate, blockSize);
  24789. processor->prepareToPlay (sampleRate, blockSize);
  24790. }
  24791. }
  24792. void AudioProcessorGraph::Node::unprepare()
  24793. {
  24794. if (isPrepared)
  24795. {
  24796. isPrepared = false;
  24797. processor->releaseResources();
  24798. }
  24799. }
  24800. AudioProcessorGraph::AudioProcessorGraph()
  24801. : lastNodeId (0),
  24802. renderingBuffers (1, 1),
  24803. currentAudioOutputBuffer (1, 1)
  24804. {
  24805. }
  24806. AudioProcessorGraph::~AudioProcessorGraph()
  24807. {
  24808. clearRenderingSequence();
  24809. clear();
  24810. }
  24811. const String AudioProcessorGraph::getName() const
  24812. {
  24813. return "Audio Graph";
  24814. }
  24815. void AudioProcessorGraph::clear()
  24816. {
  24817. nodes.clear();
  24818. connections.clear();
  24819. triggerAsyncUpdate();
  24820. }
  24821. AudioProcessorGraph::Node* AudioProcessorGraph::getNodeForId (const uint32 nodeId) const throw()
  24822. {
  24823. for (int i = nodes.size(); --i >= 0;)
  24824. if (nodes.getUnchecked(i)->id == nodeId)
  24825. return nodes.getUnchecked(i);
  24826. return 0;
  24827. }
  24828. AudioProcessorGraph::Node* AudioProcessorGraph::addNode (AudioProcessor* const newProcessor,
  24829. uint32 nodeId)
  24830. {
  24831. if (newProcessor == 0)
  24832. {
  24833. jassertfalse
  24834. return 0;
  24835. }
  24836. if (nodeId == 0)
  24837. {
  24838. nodeId = ++lastNodeId;
  24839. }
  24840. else
  24841. {
  24842. // you can't add a node with an id that already exists in the graph..
  24843. jassert (getNodeForId (nodeId) == 0);
  24844. removeNode (nodeId);
  24845. }
  24846. lastNodeId = nodeId;
  24847. Node* const n = new Node (nodeId, newProcessor);
  24848. nodes.add (n);
  24849. triggerAsyncUpdate();
  24850. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  24851. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (n->processor);
  24852. if (ioProc != 0)
  24853. ioProc->setParentGraph (this);
  24854. return n;
  24855. }
  24856. bool AudioProcessorGraph::removeNode (const uint32 nodeId)
  24857. {
  24858. disconnectNode (nodeId);
  24859. for (int i = nodes.size(); --i >= 0;)
  24860. {
  24861. if (nodes.getUnchecked(i)->id == nodeId)
  24862. {
  24863. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  24864. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (nodes.getUnchecked(i)->processor);
  24865. if (ioProc != 0)
  24866. ioProc->setParentGraph (0);
  24867. nodes.remove (i);
  24868. triggerAsyncUpdate();
  24869. return true;
  24870. }
  24871. }
  24872. return false;
  24873. }
  24874. const AudioProcessorGraph::Connection* AudioProcessorGraph::getConnectionBetween (const uint32 sourceNodeId,
  24875. const int sourceChannelIndex,
  24876. const uint32 destNodeId,
  24877. const int destChannelIndex) const throw()
  24878. {
  24879. for (int i = connections.size(); --i >= 0;)
  24880. {
  24881. const Connection* const c = connections.getUnchecked(i);
  24882. if (c->sourceNodeId == sourceNodeId
  24883. && c->destNodeId == destNodeId
  24884. && c->sourceChannelIndex == sourceChannelIndex
  24885. && c->destChannelIndex == destChannelIndex)
  24886. {
  24887. return c;
  24888. }
  24889. }
  24890. return 0;
  24891. }
  24892. bool AudioProcessorGraph::isConnected (const uint32 possibleSourceNodeId,
  24893. const uint32 possibleDestNodeId) const throw()
  24894. {
  24895. for (int i = connections.size(); --i >= 0;)
  24896. {
  24897. const Connection* const c = connections.getUnchecked(i);
  24898. if (c->sourceNodeId == possibleSourceNodeId
  24899. && c->destNodeId == possibleDestNodeId)
  24900. {
  24901. return true;
  24902. }
  24903. }
  24904. return false;
  24905. }
  24906. bool AudioProcessorGraph::canConnect (const uint32 sourceNodeId,
  24907. const int sourceChannelIndex,
  24908. const uint32 destNodeId,
  24909. const int destChannelIndex) const throw()
  24910. {
  24911. if (sourceChannelIndex < 0
  24912. || destChannelIndex < 0
  24913. || sourceNodeId == destNodeId
  24914. || (destChannelIndex == midiChannelIndex) != (sourceChannelIndex == midiChannelIndex))
  24915. return false;
  24916. const Node* const source = getNodeForId (sourceNodeId);
  24917. if (source == 0
  24918. || (sourceChannelIndex != midiChannelIndex && sourceChannelIndex >= source->processor->getNumOutputChannels())
  24919. || (sourceChannelIndex == midiChannelIndex && ! source->processor->producesMidi()))
  24920. return false;
  24921. const Node* const dest = getNodeForId (destNodeId);
  24922. if (dest == 0
  24923. || (destChannelIndex != midiChannelIndex && destChannelIndex >= dest->processor->getNumInputChannels())
  24924. || (destChannelIndex == midiChannelIndex && ! dest->processor->acceptsMidi()))
  24925. return false;
  24926. return getConnectionBetween (sourceNodeId, sourceChannelIndex,
  24927. destNodeId, destChannelIndex) == 0;
  24928. }
  24929. bool AudioProcessorGraph::addConnection (const uint32 sourceNodeId,
  24930. const int sourceChannelIndex,
  24931. const uint32 destNodeId,
  24932. const int destChannelIndex)
  24933. {
  24934. if (! canConnect (sourceNodeId, sourceChannelIndex, destNodeId, destChannelIndex))
  24935. return false;
  24936. Connection* const c = new Connection();
  24937. c->sourceNodeId = sourceNodeId;
  24938. c->sourceChannelIndex = sourceChannelIndex;
  24939. c->destNodeId = destNodeId;
  24940. c->destChannelIndex = destChannelIndex;
  24941. connections.add (c);
  24942. triggerAsyncUpdate();
  24943. return true;
  24944. }
  24945. void AudioProcessorGraph::removeConnection (const int index)
  24946. {
  24947. connections.remove (index);
  24948. triggerAsyncUpdate();
  24949. }
  24950. bool AudioProcessorGraph::removeConnection (const uint32 sourceNodeId, const int sourceChannelIndex,
  24951. const uint32 destNodeId, const int destChannelIndex)
  24952. {
  24953. bool doneAnything = false;
  24954. for (int i = connections.size(); --i >= 0;)
  24955. {
  24956. const Connection* const c = connections.getUnchecked(i);
  24957. if (c->sourceNodeId == sourceNodeId
  24958. && c->destNodeId == destNodeId
  24959. && c->sourceChannelIndex == sourceChannelIndex
  24960. && c->destChannelIndex == destChannelIndex)
  24961. {
  24962. removeConnection (i);
  24963. doneAnything = true;
  24964. triggerAsyncUpdate();
  24965. }
  24966. }
  24967. return doneAnything;
  24968. }
  24969. bool AudioProcessorGraph::disconnectNode (const uint32 nodeId)
  24970. {
  24971. bool doneAnything = false;
  24972. for (int i = connections.size(); --i >= 0;)
  24973. {
  24974. const Connection* const c = connections.getUnchecked(i);
  24975. if (c->sourceNodeId == nodeId || c->destNodeId == nodeId)
  24976. {
  24977. removeConnection (i);
  24978. doneAnything = true;
  24979. triggerAsyncUpdate();
  24980. }
  24981. }
  24982. return doneAnything;
  24983. }
  24984. bool AudioProcessorGraph::removeIllegalConnections()
  24985. {
  24986. bool doneAnything = false;
  24987. for (int i = connections.size(); --i >= 0;)
  24988. {
  24989. const Connection* const c = connections.getUnchecked(i);
  24990. const Node* const source = getNodeForId (c->sourceNodeId);
  24991. const Node* const dest = getNodeForId (c->destNodeId);
  24992. if (source == 0 || dest == 0
  24993. || (c->sourceChannelIndex != midiChannelIndex
  24994. && (((unsigned int) c->sourceChannelIndex) >= (unsigned int) source->processor->getNumOutputChannels()))
  24995. || (c->sourceChannelIndex == midiChannelIndex
  24996. && ! source->processor->producesMidi())
  24997. || (c->destChannelIndex != midiChannelIndex
  24998. && (((unsigned int) c->destChannelIndex) >= (unsigned int) dest->processor->getNumInputChannels()))
  24999. || (c->destChannelIndex == midiChannelIndex
  25000. && ! dest->processor->acceptsMidi()))
  25001. {
  25002. removeConnection (i);
  25003. doneAnything = true;
  25004. triggerAsyncUpdate();
  25005. }
  25006. }
  25007. return doneAnything;
  25008. }
  25009. namespace GraphRenderingOps
  25010. {
  25011. class AudioGraphRenderingOp
  25012. {
  25013. public:
  25014. AudioGraphRenderingOp() throw() {}
  25015. virtual ~AudioGraphRenderingOp() throw() {}
  25016. virtual void perform (AudioSampleBuffer& sharedBufferChans,
  25017. const OwnedArray <MidiBuffer>& sharedMidiBuffers,
  25018. const int numSamples) throw() = 0;
  25019. juce_UseDebuggingNewOperator
  25020. };
  25021. class ClearChannelOp : public AudioGraphRenderingOp
  25022. {
  25023. public:
  25024. ClearChannelOp (const int channelNum_) throw()
  25025. : channelNum (channelNum_)
  25026. {}
  25027. ~ClearChannelOp() throw() {}
  25028. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples) throw()
  25029. {
  25030. sharedBufferChans.clear (channelNum, 0, numSamples);
  25031. }
  25032. private:
  25033. const int channelNum;
  25034. ClearChannelOp (const ClearChannelOp&);
  25035. const ClearChannelOp& operator= (const ClearChannelOp&);
  25036. };
  25037. class CopyChannelOp : public AudioGraphRenderingOp
  25038. {
  25039. public:
  25040. CopyChannelOp (const int srcChannelNum_, const int dstChannelNum_) throw()
  25041. : srcChannelNum (srcChannelNum_),
  25042. dstChannelNum (dstChannelNum_)
  25043. {}
  25044. ~CopyChannelOp() throw() {}
  25045. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples) throw()
  25046. {
  25047. sharedBufferChans.copyFrom (dstChannelNum, 0, sharedBufferChans, srcChannelNum, 0, numSamples);
  25048. }
  25049. private:
  25050. const int srcChannelNum, dstChannelNum;
  25051. CopyChannelOp (const CopyChannelOp&);
  25052. const CopyChannelOp& operator= (const CopyChannelOp&);
  25053. };
  25054. class AddChannelOp : public AudioGraphRenderingOp
  25055. {
  25056. public:
  25057. AddChannelOp (const int srcChannelNum_, const int dstChannelNum_) throw()
  25058. : srcChannelNum (srcChannelNum_),
  25059. dstChannelNum (dstChannelNum_)
  25060. {}
  25061. ~AddChannelOp() throw() {}
  25062. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples) throw()
  25063. {
  25064. sharedBufferChans.addFrom (dstChannelNum, 0, sharedBufferChans, srcChannelNum, 0, numSamples);
  25065. }
  25066. private:
  25067. const int srcChannelNum, dstChannelNum;
  25068. AddChannelOp (const AddChannelOp&);
  25069. const AddChannelOp& operator= (const AddChannelOp&);
  25070. };
  25071. class ClearMidiBufferOp : public AudioGraphRenderingOp
  25072. {
  25073. public:
  25074. ClearMidiBufferOp (const int bufferNum_) throw()
  25075. : bufferNum (bufferNum_)
  25076. {}
  25077. ~ClearMidiBufferOp() throw() {}
  25078. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int) throw()
  25079. {
  25080. sharedMidiBuffers.getUnchecked (bufferNum)->clear();
  25081. }
  25082. private:
  25083. const int bufferNum;
  25084. ClearMidiBufferOp (const ClearMidiBufferOp&);
  25085. const ClearMidiBufferOp& operator= (const ClearMidiBufferOp&);
  25086. };
  25087. class CopyMidiBufferOp : public AudioGraphRenderingOp
  25088. {
  25089. public:
  25090. CopyMidiBufferOp (const int srcBufferNum_, const int dstBufferNum_) throw()
  25091. : srcBufferNum (srcBufferNum_),
  25092. dstBufferNum (dstBufferNum_)
  25093. {}
  25094. ~CopyMidiBufferOp() throw() {}
  25095. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int) throw()
  25096. {
  25097. *sharedMidiBuffers.getUnchecked (dstBufferNum) = *sharedMidiBuffers.getUnchecked (srcBufferNum);
  25098. }
  25099. private:
  25100. const int srcBufferNum, dstBufferNum;
  25101. CopyMidiBufferOp (const CopyMidiBufferOp&);
  25102. const CopyMidiBufferOp& operator= (const CopyMidiBufferOp&);
  25103. };
  25104. class AddMidiBufferOp : public AudioGraphRenderingOp
  25105. {
  25106. public:
  25107. AddMidiBufferOp (const int srcBufferNum_, const int dstBufferNum_) throw()
  25108. : srcBufferNum (srcBufferNum_),
  25109. dstBufferNum (dstBufferNum_)
  25110. {}
  25111. ~AddMidiBufferOp() throw() {}
  25112. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int numSamples) throw()
  25113. {
  25114. sharedMidiBuffers.getUnchecked (dstBufferNum)
  25115. ->addEvents (*sharedMidiBuffers.getUnchecked (srcBufferNum), 0, numSamples, 0);
  25116. }
  25117. private:
  25118. const int srcBufferNum, dstBufferNum;
  25119. AddMidiBufferOp (const AddMidiBufferOp&);
  25120. const AddMidiBufferOp& operator= (const AddMidiBufferOp&);
  25121. };
  25122. class ProcessBufferOp : public AudioGraphRenderingOp
  25123. {
  25124. public:
  25125. ProcessBufferOp (const AudioProcessorGraph::Node::Ptr& node_,
  25126. const Array <int>& audioChannelsToUse_,
  25127. const int totalChans_,
  25128. const int midiBufferToUse_) throw()
  25129. : node (node_),
  25130. processor (node_->processor),
  25131. audioChannelsToUse (audioChannelsToUse_),
  25132. totalChans (totalChans_),
  25133. midiBufferToUse (midiBufferToUse_)
  25134. {
  25135. channels = (float**) juce_calloc (sizeof (float*) * totalChans_);
  25136. }
  25137. ~ProcessBufferOp() throw()
  25138. {
  25139. juce_free (channels);
  25140. }
  25141. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int numSamples) throw()
  25142. {
  25143. for (int i = totalChans; --i >= 0;)
  25144. channels[i] = sharedBufferChans.getSampleData (audioChannelsToUse.getUnchecked (i), 0);
  25145. AudioSampleBuffer buffer (channels, totalChans, numSamples);
  25146. processor->processBlock (buffer, *sharedMidiBuffers.getUnchecked (midiBufferToUse));
  25147. }
  25148. const AudioProcessorGraph::Node::Ptr node;
  25149. AudioProcessor* const processor;
  25150. private:
  25151. Array <int> audioChannelsToUse;
  25152. float** channels;
  25153. int totalChans;
  25154. int midiBufferToUse;
  25155. ProcessBufferOp (const ProcessBufferOp&);
  25156. const ProcessBufferOp& operator= (const ProcessBufferOp&);
  25157. };
  25158. /** Used to calculate the correct sequence of rendering ops needed, based on
  25159. the best re-use of shared buffers at each stage.
  25160. */
  25161. class RenderingOpSequenceCalculator
  25162. {
  25163. public:
  25164. RenderingOpSequenceCalculator (AudioProcessorGraph& graph_,
  25165. const VoidArray& orderedNodes_,
  25166. VoidArray& renderingOps)
  25167. : graph (graph_),
  25168. orderedNodes (orderedNodes_)
  25169. {
  25170. nodeIds.add (-2); // first buffer is read-only zeros
  25171. channels.add (0);
  25172. midiNodeIds.add (-2);
  25173. for (int i = 0; i < orderedNodes.size(); ++i)
  25174. {
  25175. createRenderingOpsForNode ((AudioProcessorGraph::Node*) orderedNodes.getUnchecked(i),
  25176. renderingOps, i);
  25177. markAnyUnusedBuffersAsFree (i);
  25178. }
  25179. }
  25180. int getNumBuffersNeeded() const throw() { return nodeIds.size(); }
  25181. int getNumMidiBuffersNeeded() const throw() { return midiNodeIds.size(); }
  25182. juce_UseDebuggingNewOperator
  25183. private:
  25184. AudioProcessorGraph& graph;
  25185. const VoidArray& orderedNodes;
  25186. Array <int> nodeIds, channels, midiNodeIds;
  25187. void createRenderingOpsForNode (AudioProcessorGraph::Node* const node,
  25188. VoidArray& renderingOps,
  25189. const int ourRenderingIndex)
  25190. {
  25191. const int numIns = node->processor->getNumInputChannels();
  25192. const int numOuts = node->processor->getNumOutputChannels();
  25193. const int totalChans = jmax (numIns, numOuts);
  25194. Array <int> audioChannelsToUse;
  25195. int midiBufferToUse = -1;
  25196. for (int inputChan = 0; inputChan < numIns; ++inputChan)
  25197. {
  25198. // get a list of all the inputs to this node
  25199. Array <int> sourceNodes, sourceOutputChans;
  25200. for (int i = graph.getNumConnections(); --i >= 0;)
  25201. {
  25202. const AudioProcessorGraph::Connection* const c = graph.getConnection (i);
  25203. if (c->destNodeId == node->id && c->destChannelIndex == inputChan)
  25204. {
  25205. sourceNodes.add (c->sourceNodeId);
  25206. sourceOutputChans.add (c->sourceChannelIndex);
  25207. }
  25208. }
  25209. int bufIndex = -1;
  25210. if (sourceNodes.size() == 0)
  25211. {
  25212. // unconnected input channel
  25213. if (inputChan >= numOuts)
  25214. {
  25215. bufIndex = getReadOnlyEmptyBuffer();
  25216. jassert (bufIndex >= 0);
  25217. }
  25218. else
  25219. {
  25220. bufIndex = getFreeBuffer (false);
  25221. renderingOps.add (new ClearChannelOp (bufIndex));
  25222. }
  25223. }
  25224. else if (sourceNodes.size() == 1)
  25225. {
  25226. // channel with a straightforward single input..
  25227. const int srcNode = sourceNodes.getUnchecked(0);
  25228. const int srcChan = sourceOutputChans.getUnchecked(0);
  25229. bufIndex = getBufferContaining (srcNode, srcChan);
  25230. if (bufIndex < 0)
  25231. {
  25232. // if not found, this is probably a feedback loop
  25233. bufIndex = getReadOnlyEmptyBuffer();
  25234. jassert (bufIndex >= 0);
  25235. }
  25236. if (inputChan < numOuts
  25237. && isBufferNeededLater (ourRenderingIndex,
  25238. inputChan,
  25239. srcNode, srcChan))
  25240. {
  25241. // can't mess up this channel because it's needed later by another node, so we
  25242. // need to use a copy of it..
  25243. const int newFreeBuffer = getFreeBuffer (false);
  25244. renderingOps.add (new CopyChannelOp (bufIndex, newFreeBuffer));
  25245. bufIndex = newFreeBuffer;
  25246. }
  25247. }
  25248. else
  25249. {
  25250. // channel with a mix of several inputs..
  25251. // try to find a re-usable channel from our inputs..
  25252. int reusableInputIndex = -1;
  25253. for (int i = 0; i < sourceNodes.size(); ++i)
  25254. {
  25255. const int sourceBufIndex = getBufferContaining (sourceNodes.getUnchecked(i),
  25256. sourceOutputChans.getUnchecked(i));
  25257. if (sourceBufIndex >= 0
  25258. && ! isBufferNeededLater (ourRenderingIndex,
  25259. inputChan,
  25260. sourceNodes.getUnchecked(i),
  25261. sourceOutputChans.getUnchecked(i)))
  25262. {
  25263. // we've found one of our input chans that can be re-used..
  25264. reusableInputIndex = i;
  25265. bufIndex = sourceBufIndex;
  25266. break;
  25267. }
  25268. }
  25269. if (reusableInputIndex < 0)
  25270. {
  25271. // can't re-use any of our input chans, so get a new one and copy everything into it..
  25272. bufIndex = getFreeBuffer (false);
  25273. jassert (bufIndex != 0);
  25274. const int srcIndex = getBufferContaining (sourceNodes.getUnchecked (0),
  25275. sourceOutputChans.getUnchecked (0));
  25276. if (srcIndex < 0)
  25277. {
  25278. // if not found, this is probably a feedback loop
  25279. renderingOps.add (new ClearChannelOp (bufIndex));
  25280. }
  25281. else
  25282. {
  25283. renderingOps.add (new CopyChannelOp (srcIndex, bufIndex));
  25284. }
  25285. reusableInputIndex = 0;
  25286. }
  25287. for (int j = 0; j < sourceNodes.size(); ++j)
  25288. {
  25289. if (j != reusableInputIndex)
  25290. {
  25291. const int srcIndex = getBufferContaining (sourceNodes.getUnchecked(j),
  25292. sourceOutputChans.getUnchecked(j));
  25293. if (srcIndex >= 0)
  25294. renderingOps.add (new AddChannelOp (srcIndex, bufIndex));
  25295. }
  25296. }
  25297. }
  25298. jassert (bufIndex >= 0);
  25299. audioChannelsToUse.add (bufIndex);
  25300. if (inputChan < numOuts)
  25301. markBufferAsContaining (bufIndex, node->id, inputChan);
  25302. }
  25303. for (int outputChan = numIns; outputChan < numOuts; ++outputChan)
  25304. {
  25305. const int bufIndex = getFreeBuffer (false);
  25306. jassert (bufIndex != 0);
  25307. audioChannelsToUse.add (bufIndex);
  25308. markBufferAsContaining (bufIndex, node->id, outputChan);
  25309. }
  25310. // Now the same thing for midi..
  25311. Array <int> midiSourceNodes;
  25312. for (int i = graph.getNumConnections(); --i >= 0;)
  25313. {
  25314. const AudioProcessorGraph::Connection* const c = graph.getConnection (i);
  25315. if (c->destNodeId == node->id && c->destChannelIndex == AudioProcessorGraph::midiChannelIndex)
  25316. midiSourceNodes.add (c->sourceNodeId);
  25317. }
  25318. if (midiSourceNodes.size() == 0)
  25319. {
  25320. // No midi inputs..
  25321. midiBufferToUse = getFreeBuffer (true); // need to pick a buffer even if the processor doesn't use midi
  25322. if (node->processor->acceptsMidi() || node->processor->producesMidi())
  25323. renderingOps.add (new ClearMidiBufferOp (midiBufferToUse));
  25324. }
  25325. else if (midiSourceNodes.size() == 1)
  25326. {
  25327. // One midi input..
  25328. midiBufferToUse = getBufferContaining (midiSourceNodes.getUnchecked(0),
  25329. AudioProcessorGraph::midiChannelIndex);
  25330. if (midiBufferToUse >= 0)
  25331. {
  25332. if (isBufferNeededLater (ourRenderingIndex,
  25333. AudioProcessorGraph::midiChannelIndex,
  25334. midiSourceNodes.getUnchecked(0),
  25335. AudioProcessorGraph::midiChannelIndex))
  25336. {
  25337. // can't mess up this channel because it's needed later by another node, so we
  25338. // need to use a copy of it..
  25339. const int newFreeBuffer = getFreeBuffer (true);
  25340. renderingOps.add (new CopyMidiBufferOp (midiBufferToUse, newFreeBuffer));
  25341. midiBufferToUse = newFreeBuffer;
  25342. }
  25343. }
  25344. else
  25345. {
  25346. // probably a feedback loop, so just use an empty one..
  25347. midiBufferToUse = getFreeBuffer (true); // need to pick a buffer even if the processor doesn't use midi
  25348. }
  25349. }
  25350. else
  25351. {
  25352. // More than one midi input being mixed..
  25353. int reusableInputIndex = -1;
  25354. for (int i = 0; i < midiSourceNodes.size(); ++i)
  25355. {
  25356. const int sourceBufIndex = getBufferContaining (midiSourceNodes.getUnchecked(i),
  25357. AudioProcessorGraph::midiChannelIndex);
  25358. if (sourceBufIndex >= 0
  25359. && ! isBufferNeededLater (ourRenderingIndex,
  25360. AudioProcessorGraph::midiChannelIndex,
  25361. midiSourceNodes.getUnchecked(i),
  25362. AudioProcessorGraph::midiChannelIndex))
  25363. {
  25364. // we've found one of our input buffers that can be re-used..
  25365. reusableInputIndex = i;
  25366. midiBufferToUse = sourceBufIndex;
  25367. break;
  25368. }
  25369. }
  25370. if (reusableInputIndex < 0)
  25371. {
  25372. // can't re-use any of our input buffers, so get a new one and copy everything into it..
  25373. midiBufferToUse = getFreeBuffer (true);
  25374. jassert (midiBufferToUse >= 0);
  25375. const int srcIndex = getBufferContaining (midiSourceNodes.getUnchecked(0),
  25376. AudioProcessorGraph::midiChannelIndex);
  25377. if (srcIndex >= 0)
  25378. renderingOps.add (new CopyMidiBufferOp (srcIndex, midiBufferToUse));
  25379. else
  25380. renderingOps.add (new ClearMidiBufferOp (midiBufferToUse));
  25381. reusableInputIndex = 0;
  25382. }
  25383. for (int j = 0; j < midiSourceNodes.size(); ++j)
  25384. {
  25385. if (j != reusableInputIndex)
  25386. {
  25387. const int srcIndex = getBufferContaining (midiSourceNodes.getUnchecked(j),
  25388. AudioProcessorGraph::midiChannelIndex);
  25389. if (srcIndex >= 0)
  25390. renderingOps.add (new AddMidiBufferOp (srcIndex, midiBufferToUse));
  25391. }
  25392. }
  25393. }
  25394. if (node->processor->producesMidi())
  25395. markBufferAsContaining (midiBufferToUse, node->id,
  25396. AudioProcessorGraph::midiChannelIndex);
  25397. renderingOps.add (new ProcessBufferOp (node, audioChannelsToUse,
  25398. totalChans, midiBufferToUse));
  25399. }
  25400. int getFreeBuffer (const bool forMidi)
  25401. {
  25402. if (forMidi)
  25403. {
  25404. for (int i = 1; i < midiNodeIds.size(); ++i)
  25405. if (midiNodeIds.getUnchecked(i) < 0)
  25406. return i;
  25407. midiNodeIds.add (-1);
  25408. return midiNodeIds.size() - 1;
  25409. }
  25410. else
  25411. {
  25412. for (int i = 1; i < nodeIds.size(); ++i)
  25413. if (nodeIds.getUnchecked(i) < 0)
  25414. return i;
  25415. nodeIds.add (-1);
  25416. channels.add (0);
  25417. return nodeIds.size() - 1;
  25418. }
  25419. }
  25420. int getReadOnlyEmptyBuffer() const throw()
  25421. {
  25422. return 0;
  25423. }
  25424. int getBufferContaining (const int nodeId, const int outputChannel) const throw()
  25425. {
  25426. if (outputChannel == AudioProcessorGraph::midiChannelIndex)
  25427. {
  25428. for (int i = midiNodeIds.size(); --i >= 0;)
  25429. if (midiNodeIds.getUnchecked(i) == nodeId)
  25430. return i;
  25431. }
  25432. else
  25433. {
  25434. for (int i = nodeIds.size(); --i >= 0;)
  25435. if (nodeIds.getUnchecked(i) == nodeId
  25436. && channels.getUnchecked(i) == outputChannel)
  25437. return i;
  25438. }
  25439. return -1;
  25440. }
  25441. void markAnyUnusedBuffersAsFree (const int stepIndex)
  25442. {
  25443. int i;
  25444. for (i = 0; i < nodeIds.size(); ++i)
  25445. {
  25446. if (nodeIds.getUnchecked(i) >= 0
  25447. && ! isBufferNeededLater (stepIndex, -1,
  25448. nodeIds.getUnchecked(i),
  25449. channels.getUnchecked(i)))
  25450. {
  25451. nodeIds.set (i, -1);
  25452. }
  25453. }
  25454. for (i = 0; i < midiNodeIds.size(); ++i)
  25455. {
  25456. if (midiNodeIds.getUnchecked(i) >= 0
  25457. && ! isBufferNeededLater (stepIndex, -1,
  25458. midiNodeIds.getUnchecked(i),
  25459. AudioProcessorGraph::midiChannelIndex))
  25460. {
  25461. midiNodeIds.set (i, -1);
  25462. }
  25463. }
  25464. }
  25465. bool isBufferNeededLater (int stepIndexToSearchFrom,
  25466. int inputChannelOfIndexToIgnore,
  25467. const int nodeId,
  25468. const int outputChanIndex) const throw()
  25469. {
  25470. while (stepIndexToSearchFrom < orderedNodes.size())
  25471. {
  25472. const AudioProcessorGraph::Node* const node = (const AudioProcessorGraph::Node*) orderedNodes.getUnchecked (stepIndexToSearchFrom);
  25473. if (outputChanIndex == AudioProcessorGraph::midiChannelIndex)
  25474. {
  25475. if (inputChannelOfIndexToIgnore != AudioProcessorGraph::midiChannelIndex
  25476. && graph.getConnectionBetween (nodeId, AudioProcessorGraph::midiChannelIndex,
  25477. node->id, AudioProcessorGraph::midiChannelIndex) != 0)
  25478. return true;
  25479. }
  25480. else
  25481. {
  25482. for (int i = 0; i < node->processor->getNumInputChannels(); ++i)
  25483. if (i != inputChannelOfIndexToIgnore
  25484. && graph.getConnectionBetween (nodeId, outputChanIndex,
  25485. node->id, i) != 0)
  25486. return true;
  25487. }
  25488. inputChannelOfIndexToIgnore = -1;
  25489. ++stepIndexToSearchFrom;
  25490. }
  25491. return false;
  25492. }
  25493. void markBufferAsContaining (int bufferNum, int nodeId, int outputIndex)
  25494. {
  25495. if (outputIndex == AudioProcessorGraph::midiChannelIndex)
  25496. {
  25497. jassert (bufferNum > 0 && bufferNum < midiNodeIds.size());
  25498. midiNodeIds.set (bufferNum, nodeId);
  25499. }
  25500. else
  25501. {
  25502. jassert (bufferNum > 0 && bufferNum < nodeIds.size());
  25503. nodeIds.set (bufferNum, nodeId);
  25504. channels.set (bufferNum, outputIndex);
  25505. }
  25506. }
  25507. RenderingOpSequenceCalculator (const RenderingOpSequenceCalculator&);
  25508. const RenderingOpSequenceCalculator& operator= (const RenderingOpSequenceCalculator&);
  25509. };
  25510. }
  25511. void AudioProcessorGraph::clearRenderingSequence()
  25512. {
  25513. const ScopedLock sl (renderLock);
  25514. for (int i = renderingOps.size(); --i >= 0;)
  25515. {
  25516. GraphRenderingOps::AudioGraphRenderingOp* const r
  25517. = (GraphRenderingOps::AudioGraphRenderingOp*) renderingOps.getUnchecked(i);
  25518. renderingOps.remove (i);
  25519. delete r;
  25520. }
  25521. }
  25522. bool AudioProcessorGraph::isAnInputTo (const uint32 possibleInputId,
  25523. const uint32 possibleDestinationId,
  25524. const int recursionCheck) const throw()
  25525. {
  25526. if (recursionCheck > 0)
  25527. {
  25528. for (int i = connections.size(); --i >= 0;)
  25529. {
  25530. const AudioProcessorGraph::Connection* const c = connections.getUnchecked (i);
  25531. if (c->destNodeId == possibleDestinationId
  25532. && (c->sourceNodeId == possibleInputId
  25533. || isAnInputTo (possibleInputId, c->sourceNodeId, recursionCheck - 1)))
  25534. return true;
  25535. }
  25536. }
  25537. return false;
  25538. }
  25539. void AudioProcessorGraph::buildRenderingSequence()
  25540. {
  25541. VoidArray newRenderingOps;
  25542. int numRenderingBuffersNeeded = 2;
  25543. int numMidiBuffersNeeded = 1;
  25544. {
  25545. MessageManagerLock mml;
  25546. VoidArray orderedNodes;
  25547. int i;
  25548. for (i = 0; i < nodes.size(); ++i)
  25549. {
  25550. Node* const node = nodes.getUnchecked(i);
  25551. node->prepare (getSampleRate(), getBlockSize(), this);
  25552. int j = 0;
  25553. for (; j < orderedNodes.size(); ++j)
  25554. if (isAnInputTo (node->id,
  25555. ((Node*) orderedNodes.getUnchecked (j))->id,
  25556. nodes.size() + 1))
  25557. break;
  25558. orderedNodes.insert (j, node);
  25559. }
  25560. GraphRenderingOps::RenderingOpSequenceCalculator calculator (*this, orderedNodes, newRenderingOps);
  25561. numRenderingBuffersNeeded = calculator.getNumBuffersNeeded();
  25562. numMidiBuffersNeeded = calculator.getNumMidiBuffersNeeded();
  25563. }
  25564. VoidArray oldRenderingOps (renderingOps);
  25565. {
  25566. // swap over to the new set of rendering sequence..
  25567. const ScopedLock sl (renderLock);
  25568. renderingBuffers.setSize (numRenderingBuffersNeeded, getBlockSize());
  25569. renderingBuffers.clear();
  25570. for (int i = midiBuffers.size(); --i >= 0;)
  25571. midiBuffers.getUnchecked(i)->clear();
  25572. while (midiBuffers.size() < numMidiBuffersNeeded)
  25573. midiBuffers.add (new MidiBuffer());
  25574. renderingOps = newRenderingOps;
  25575. }
  25576. for (int i = oldRenderingOps.size(); --i >= 0;)
  25577. delete (GraphRenderingOps::AudioGraphRenderingOp*) oldRenderingOps.getUnchecked(i);
  25578. }
  25579. void AudioProcessorGraph::handleAsyncUpdate()
  25580. {
  25581. buildRenderingSequence();
  25582. }
  25583. void AudioProcessorGraph::prepareToPlay (double /*sampleRate*/, int estimatedSamplesPerBlock)
  25584. {
  25585. currentAudioInputBuffer = 0;
  25586. currentAudioOutputBuffer.setSize (getNumOutputChannels(), estimatedSamplesPerBlock);
  25587. currentMidiInputBuffer = 0;
  25588. currentMidiOutputBuffer.clear();
  25589. clearRenderingSequence();
  25590. buildRenderingSequence();
  25591. }
  25592. void AudioProcessorGraph::releaseResources()
  25593. {
  25594. for (int i = 0; i < nodes.size(); ++i)
  25595. nodes.getUnchecked(i)->unprepare();
  25596. renderingBuffers.setSize (1, 1);
  25597. midiBuffers.clear();
  25598. currentAudioInputBuffer = 0;
  25599. currentAudioOutputBuffer.setSize (1, 1);
  25600. currentMidiInputBuffer = 0;
  25601. currentMidiOutputBuffer.clear();
  25602. }
  25603. void AudioProcessorGraph::processBlock (AudioSampleBuffer& buffer, MidiBuffer& midiMessages)
  25604. {
  25605. const int numSamples = buffer.getNumSamples();
  25606. const ScopedLock sl (renderLock);
  25607. currentAudioInputBuffer = &buffer;
  25608. currentAudioOutputBuffer.setSize (buffer.getNumChannels(), numSamples);
  25609. currentAudioOutputBuffer.clear();
  25610. currentMidiInputBuffer = &midiMessages;
  25611. currentMidiOutputBuffer.clear();
  25612. for (int i = 0; i < renderingOps.size(); ++i)
  25613. {
  25614. GraphRenderingOps::AudioGraphRenderingOp* const op
  25615. = (GraphRenderingOps::AudioGraphRenderingOp*) renderingOps.getUnchecked(i);
  25616. op->perform (renderingBuffers, midiBuffers, numSamples);
  25617. }
  25618. for (int i = 0; i < buffer.getNumChannels(); ++i)
  25619. buffer.copyFrom (i, 0, currentAudioOutputBuffer, i, 0, numSamples);
  25620. }
  25621. const String AudioProcessorGraph::getInputChannelName (const int channelIndex) const
  25622. {
  25623. return "Input " + String (channelIndex + 1);
  25624. }
  25625. const String AudioProcessorGraph::getOutputChannelName (const int channelIndex) const
  25626. {
  25627. return "Output " + String (channelIndex + 1);
  25628. }
  25629. bool AudioProcessorGraph::isInputChannelStereoPair (int /*index*/) const
  25630. {
  25631. return true;
  25632. }
  25633. bool AudioProcessorGraph::isOutputChannelStereoPair (int /*index*/) const
  25634. {
  25635. return true;
  25636. }
  25637. bool AudioProcessorGraph::acceptsMidi() const
  25638. {
  25639. return true;
  25640. }
  25641. bool AudioProcessorGraph::producesMidi() const
  25642. {
  25643. return true;
  25644. }
  25645. void AudioProcessorGraph::getStateInformation (JUCE_NAMESPACE::MemoryBlock& /*destData*/)
  25646. {
  25647. }
  25648. void AudioProcessorGraph::setStateInformation (const void* /*data*/, int /*sizeInBytes*/)
  25649. {
  25650. }
  25651. AudioProcessorGraph::AudioGraphIOProcessor::AudioGraphIOProcessor (const IODeviceType type_)
  25652. : type (type_),
  25653. graph (0)
  25654. {
  25655. }
  25656. AudioProcessorGraph::AudioGraphIOProcessor::~AudioGraphIOProcessor()
  25657. {
  25658. }
  25659. const String AudioProcessorGraph::AudioGraphIOProcessor::getName() const
  25660. {
  25661. switch (type)
  25662. {
  25663. case audioOutputNode:
  25664. return "Audio Output";
  25665. case audioInputNode:
  25666. return "Audio Input";
  25667. case midiOutputNode:
  25668. return "Midi Output";
  25669. case midiInputNode:
  25670. return "Midi Input";
  25671. default:
  25672. break;
  25673. }
  25674. return String::empty;
  25675. }
  25676. void AudioProcessorGraph::AudioGraphIOProcessor::fillInPluginDescription (PluginDescription& d) const
  25677. {
  25678. d.name = getName();
  25679. d.uid = d.name.hashCode();
  25680. d.category = "I/O devices";
  25681. d.pluginFormatName = "Internal";
  25682. d.manufacturerName = "Raw Material Software";
  25683. d.version = "1.0";
  25684. d.isInstrument = false;
  25685. d.numInputChannels = getNumInputChannels();
  25686. if (type == audioOutputNode && graph != 0)
  25687. d.numInputChannels = graph->getNumInputChannels();
  25688. d.numOutputChannels = getNumOutputChannels();
  25689. if (type == audioInputNode && graph != 0)
  25690. d.numOutputChannels = graph->getNumOutputChannels();
  25691. }
  25692. void AudioProcessorGraph::AudioGraphIOProcessor::prepareToPlay (double, int)
  25693. {
  25694. jassert (graph != 0);
  25695. }
  25696. void AudioProcessorGraph::AudioGraphIOProcessor::releaseResources()
  25697. {
  25698. }
  25699. void AudioProcessorGraph::AudioGraphIOProcessor::processBlock (AudioSampleBuffer& buffer,
  25700. MidiBuffer& midiMessages)
  25701. {
  25702. jassert (graph != 0);
  25703. switch (type)
  25704. {
  25705. case audioOutputNode:
  25706. {
  25707. for (int i = jmin (graph->currentAudioOutputBuffer.getNumChannels(),
  25708. buffer.getNumChannels()); --i >= 0;)
  25709. {
  25710. graph->currentAudioOutputBuffer.addFrom (i, 0, buffer, i, 0, buffer.getNumSamples());
  25711. }
  25712. break;
  25713. }
  25714. case audioInputNode:
  25715. {
  25716. for (int i = jmin (graph->currentAudioInputBuffer->getNumChannels(),
  25717. buffer.getNumChannels()); --i >= 0;)
  25718. {
  25719. buffer.addFrom (i, 0, *graph->currentAudioInputBuffer, i, 0, buffer.getNumSamples());
  25720. }
  25721. break;
  25722. }
  25723. case midiOutputNode:
  25724. graph->currentMidiOutputBuffer.addEvents (midiMessages, 0, buffer.getNumSamples(), 0);
  25725. break;
  25726. case midiInputNode:
  25727. midiMessages.addEvents (*graph->currentMidiInputBuffer, 0, buffer.getNumSamples(), 0);
  25728. break;
  25729. default:
  25730. break;
  25731. }
  25732. }
  25733. bool AudioProcessorGraph::AudioGraphIOProcessor::acceptsMidi() const
  25734. {
  25735. return type == midiOutputNode;
  25736. }
  25737. bool AudioProcessorGraph::AudioGraphIOProcessor::producesMidi() const
  25738. {
  25739. return type == midiInputNode;
  25740. }
  25741. const String AudioProcessorGraph::AudioGraphIOProcessor::getInputChannelName (const int channelIndex) const
  25742. {
  25743. switch (type)
  25744. {
  25745. case audioOutputNode:
  25746. return "Output " + String (channelIndex + 1);
  25747. case midiOutputNode:
  25748. return "Midi Output";
  25749. default:
  25750. break;
  25751. }
  25752. return String::empty;
  25753. }
  25754. const String AudioProcessorGraph::AudioGraphIOProcessor::getOutputChannelName (const int channelIndex) const
  25755. {
  25756. switch (type)
  25757. {
  25758. case audioInputNode:
  25759. return "Input " + String (channelIndex + 1);
  25760. case midiInputNode:
  25761. return "Midi Input";
  25762. default:
  25763. break;
  25764. }
  25765. return String::empty;
  25766. }
  25767. bool AudioProcessorGraph::AudioGraphIOProcessor::isInputChannelStereoPair (int /*index*/) const
  25768. {
  25769. return type == audioInputNode || type == audioOutputNode;
  25770. }
  25771. bool AudioProcessorGraph::AudioGraphIOProcessor::isOutputChannelStereoPair (int index) const
  25772. {
  25773. return isInputChannelStereoPair (index);
  25774. }
  25775. bool AudioProcessorGraph::AudioGraphIOProcessor::isInput() const throw()
  25776. {
  25777. return type == audioInputNode || type == midiInputNode;
  25778. }
  25779. bool AudioProcessorGraph::AudioGraphIOProcessor::isOutput() const throw()
  25780. {
  25781. return type == audioOutputNode || type == midiOutputNode;
  25782. }
  25783. AudioProcessorEditor* AudioProcessorGraph::AudioGraphIOProcessor::createEditor()
  25784. {
  25785. return 0;
  25786. }
  25787. int AudioProcessorGraph::AudioGraphIOProcessor::getNumParameters() { return 0; }
  25788. const String AudioProcessorGraph::AudioGraphIOProcessor::getParameterName (int) { return String::empty; }
  25789. float AudioProcessorGraph::AudioGraphIOProcessor::getParameter (int) { return 0.0f; }
  25790. const String AudioProcessorGraph::AudioGraphIOProcessor::getParameterText (int) { return String::empty; }
  25791. void AudioProcessorGraph::AudioGraphIOProcessor::setParameter (int, float) { }
  25792. int AudioProcessorGraph::AudioGraphIOProcessor::getNumPrograms() { return 0; }
  25793. int AudioProcessorGraph::AudioGraphIOProcessor::getCurrentProgram() { return 0; }
  25794. void AudioProcessorGraph::AudioGraphIOProcessor::setCurrentProgram (int) { }
  25795. const String AudioProcessorGraph::AudioGraphIOProcessor::getProgramName (int) { return String::empty; }
  25796. void AudioProcessorGraph::AudioGraphIOProcessor::changeProgramName (int, const String&) { }
  25797. void AudioProcessorGraph::AudioGraphIOProcessor::getStateInformation (JUCE_NAMESPACE::MemoryBlock&)
  25798. {
  25799. }
  25800. void AudioProcessorGraph::AudioGraphIOProcessor::setStateInformation (const void*, int)
  25801. {
  25802. }
  25803. void AudioProcessorGraph::AudioGraphIOProcessor::setParentGraph (AudioProcessorGraph* const newGraph) throw()
  25804. {
  25805. graph = newGraph;
  25806. if (graph != 0)
  25807. {
  25808. setPlayConfigDetails (type == audioOutputNode ? graph->getNumInputChannels() : 0,
  25809. type == audioInputNode ? graph->getNumOutputChannels() : 0,
  25810. getSampleRate(),
  25811. getBlockSize());
  25812. updateHostDisplay();
  25813. }
  25814. }
  25815. END_JUCE_NAMESPACE
  25816. /********* End of inlined file: juce_AudioProcessorGraph.cpp *********/
  25817. /********* Start of inlined file: juce_AudioProcessorPlayer.cpp *********/
  25818. BEGIN_JUCE_NAMESPACE
  25819. AudioProcessorPlayer::AudioProcessorPlayer()
  25820. : processor (0),
  25821. sampleRate (0),
  25822. blockSize (0),
  25823. isPrepared (false),
  25824. numInputChans (0),
  25825. numOutputChans (0),
  25826. tempBuffer (1, 1)
  25827. {
  25828. }
  25829. AudioProcessorPlayer::~AudioProcessorPlayer()
  25830. {
  25831. setProcessor (0);
  25832. }
  25833. void AudioProcessorPlayer::setProcessor (AudioProcessor* const processorToPlay)
  25834. {
  25835. if (processor != processorToPlay)
  25836. {
  25837. if (processorToPlay != 0 && sampleRate > 0 && blockSize > 0)
  25838. {
  25839. processorToPlay->setPlayConfigDetails (numInputChans, numOutputChans,
  25840. sampleRate, blockSize);
  25841. processorToPlay->prepareToPlay (sampleRate, blockSize);
  25842. }
  25843. lock.enter();
  25844. AudioProcessor* const oldOne = isPrepared ? processor : 0;
  25845. processor = processorToPlay;
  25846. isPrepared = true;
  25847. lock.exit();
  25848. if (oldOne != 0)
  25849. oldOne->releaseResources();
  25850. }
  25851. }
  25852. void AudioProcessorPlayer::audioDeviceIOCallback (const float** inputChannelData,
  25853. int totalNumInputChannels,
  25854. float** outputChannelData,
  25855. int totalNumOutputChannels,
  25856. int numSamples)
  25857. {
  25858. // these should have been prepared by audioDeviceAboutToStart()...
  25859. jassert (sampleRate > 0 && blockSize > 0);
  25860. incomingMidi.clear();
  25861. messageCollector.removeNextBlockOfMessages (incomingMidi, numSamples);
  25862. int i, numActiveChans = 0, numInputs = 0, numOutputs = 0;
  25863. // messy stuff needed to compact the channels down into an array
  25864. // of non-zero pointers..
  25865. for (i = 0; i < totalNumInputChannels; ++i)
  25866. {
  25867. if (inputChannelData[i] != 0)
  25868. {
  25869. inputChans [numInputs++] = inputChannelData[i];
  25870. if (numInputs >= numElementsInArray (inputChans))
  25871. break;
  25872. }
  25873. }
  25874. for (i = 0; i < totalNumOutputChannels; ++i)
  25875. {
  25876. if (outputChannelData[i] != 0)
  25877. {
  25878. outputChans [numOutputs++] = outputChannelData[i];
  25879. if (numOutputs >= numElementsInArray (outputChans))
  25880. break;
  25881. }
  25882. }
  25883. if (numInputs > numOutputs)
  25884. {
  25885. // if there aren't enough output channels for the number of
  25886. // inputs, we need to create some temporary extra ones (can't
  25887. // use the input data in case it gets written to)
  25888. tempBuffer.setSize (numInputs - numOutputs, numSamples,
  25889. false, false, true);
  25890. for (i = 0; i < numOutputs; ++i)
  25891. {
  25892. channels[numActiveChans] = outputChans[i];
  25893. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  25894. ++numActiveChans;
  25895. }
  25896. for (i = numOutputs; i < numInputs; ++i)
  25897. {
  25898. channels[numActiveChans] = tempBuffer.getSampleData (i - numOutputs, 0);
  25899. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  25900. ++numActiveChans;
  25901. }
  25902. }
  25903. else
  25904. {
  25905. for (i = 0; i < numInputs; ++i)
  25906. {
  25907. channels[numActiveChans] = outputChans[i];
  25908. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  25909. ++numActiveChans;
  25910. }
  25911. for (i = numInputs; i < numOutputs; ++i)
  25912. {
  25913. channels[numActiveChans] = outputChans[i];
  25914. zeromem (channels[numActiveChans], sizeof (float) * numSamples);
  25915. ++numActiveChans;
  25916. }
  25917. }
  25918. AudioSampleBuffer buffer (channels, numActiveChans, numSamples);
  25919. const ScopedLock sl (lock);
  25920. if (processor != 0)
  25921. processor->processBlock (buffer, incomingMidi);
  25922. }
  25923. void AudioProcessorPlayer::audioDeviceAboutToStart (AudioIODevice* device)
  25924. {
  25925. const ScopedLock sl (lock);
  25926. sampleRate = device->getCurrentSampleRate();
  25927. blockSize = device->getCurrentBufferSizeSamples();
  25928. numInputChans = device->getActiveInputChannels().countNumberOfSetBits();
  25929. numOutputChans = device->getActiveOutputChannels().countNumberOfSetBits();
  25930. messageCollector.reset (sampleRate);
  25931. zeromem (channels, sizeof (channels));
  25932. if (processor != 0)
  25933. {
  25934. if (isPrepared)
  25935. processor->releaseResources();
  25936. AudioProcessor* const oldProcessor = processor;
  25937. setProcessor (0);
  25938. setProcessor (oldProcessor);
  25939. }
  25940. }
  25941. void AudioProcessorPlayer::audioDeviceStopped()
  25942. {
  25943. const ScopedLock sl (lock);
  25944. if (processor != 0 && isPrepared)
  25945. processor->releaseResources();
  25946. sampleRate = 0.0;
  25947. blockSize = 0;
  25948. isPrepared = false;
  25949. tempBuffer.setSize (1, 1);
  25950. }
  25951. void AudioProcessorPlayer::handleIncomingMidiMessage (MidiInput*, const MidiMessage& message)
  25952. {
  25953. messageCollector.addMessageToQueue (message);
  25954. }
  25955. END_JUCE_NAMESPACE
  25956. /********* End of inlined file: juce_AudioProcessorPlayer.cpp *********/
  25957. /********* Start of inlined file: juce_GenericAudioProcessorEditor.cpp *********/
  25958. BEGIN_JUCE_NAMESPACE
  25959. class ProcessorParameterPropertyComp : public PropertyComponent,
  25960. public AudioProcessorListener,
  25961. public AsyncUpdater
  25962. {
  25963. public:
  25964. ProcessorParameterPropertyComp (const String& name,
  25965. AudioProcessor* const owner_,
  25966. const int index_)
  25967. : PropertyComponent (name),
  25968. owner (owner_),
  25969. index (index_)
  25970. {
  25971. addAndMakeVisible (slider = new ParamSlider (owner_, index_));
  25972. owner_->addListener (this);
  25973. }
  25974. ~ProcessorParameterPropertyComp()
  25975. {
  25976. owner->removeListener (this);
  25977. deleteAllChildren();
  25978. }
  25979. void refresh()
  25980. {
  25981. slider->setValue (owner->getParameter (index), false);
  25982. }
  25983. void audioProcessorChanged (AudioProcessor*) {}
  25984. void audioProcessorParameterChanged (AudioProcessor*, int parameterIndex, float)
  25985. {
  25986. if (parameterIndex == index)
  25987. triggerAsyncUpdate();
  25988. }
  25989. void handleAsyncUpdate()
  25990. {
  25991. refresh();
  25992. }
  25993. juce_UseDebuggingNewOperator
  25994. private:
  25995. AudioProcessor* const owner;
  25996. const int index;
  25997. Slider* slider;
  25998. class ParamSlider : public Slider
  25999. {
  26000. public:
  26001. ParamSlider (AudioProcessor* const owner_, const int index_)
  26002. : Slider (String::empty),
  26003. owner (owner_),
  26004. index (index_)
  26005. {
  26006. setRange (0.0, 1.0, 0.0);
  26007. setSliderStyle (Slider::LinearBar);
  26008. setTextBoxIsEditable (false);
  26009. setScrollWheelEnabled (false);
  26010. }
  26011. ~ParamSlider()
  26012. {
  26013. }
  26014. void valueChanged()
  26015. {
  26016. const float newVal = (float) getValue();
  26017. if (owner->getParameter (index) != newVal)
  26018. owner->setParameter (index, newVal);
  26019. }
  26020. const String getTextFromValue (double /*value*/)
  26021. {
  26022. return owner->getParameterText (index);
  26023. }
  26024. juce_UseDebuggingNewOperator
  26025. private:
  26026. AudioProcessor* const owner;
  26027. const int index;
  26028. };
  26029. };
  26030. GenericAudioProcessorEditor::GenericAudioProcessorEditor (AudioProcessor* const owner)
  26031. : AudioProcessorEditor (owner)
  26032. {
  26033. setOpaque (true);
  26034. addAndMakeVisible (panel = new PropertyPanel());
  26035. Array <PropertyComponent*> params;
  26036. const int numParams = owner->getNumParameters();
  26037. int totalHeight = 0;
  26038. for (int i = 0; i < numParams; ++i)
  26039. {
  26040. String name (owner->getParameterName (i));
  26041. if (name.trim().isEmpty())
  26042. name = "Unnamed";
  26043. ProcessorParameterPropertyComp* const pc = new ProcessorParameterPropertyComp (name, owner, i);
  26044. params.add (pc);
  26045. totalHeight += pc->getPreferredHeight();
  26046. }
  26047. panel->addProperties (params);
  26048. setSize (400, jlimit (25, 400, totalHeight));
  26049. }
  26050. GenericAudioProcessorEditor::~GenericAudioProcessorEditor()
  26051. {
  26052. deleteAllChildren();
  26053. }
  26054. void GenericAudioProcessorEditor::paint (Graphics& g)
  26055. {
  26056. g.fillAll (Colours::white);
  26057. }
  26058. void GenericAudioProcessorEditor::resized()
  26059. {
  26060. panel->setSize (getWidth(), getHeight());
  26061. }
  26062. END_JUCE_NAMESPACE
  26063. /********* End of inlined file: juce_GenericAudioProcessorEditor.cpp *********/
  26064. /********* Start of inlined file: juce_Sampler.cpp *********/
  26065. BEGIN_JUCE_NAMESPACE
  26066. SamplerSound::SamplerSound (const String& name_,
  26067. AudioFormatReader& source,
  26068. const BitArray& midiNotes_,
  26069. const int midiNoteForNormalPitch,
  26070. const double attackTimeSecs,
  26071. const double releaseTimeSecs,
  26072. const double maxSampleLengthSeconds)
  26073. : name (name_),
  26074. midiNotes (midiNotes_),
  26075. midiRootNote (midiNoteForNormalPitch)
  26076. {
  26077. sourceSampleRate = source.sampleRate;
  26078. if (sourceSampleRate <= 0 || source.lengthInSamples <= 0)
  26079. {
  26080. data = 0;
  26081. length = 0;
  26082. attackSamples = 0;
  26083. releaseSamples = 0;
  26084. }
  26085. else
  26086. {
  26087. length = jmin ((int) source.lengthInSamples,
  26088. (int) (maxSampleLengthSeconds * sourceSampleRate));
  26089. data = new AudioSampleBuffer (jmin (2, source.numChannels), length + 4);
  26090. data->readFromAudioReader (&source, 0, length + 4, 0, true, true);
  26091. attackSamples = roundDoubleToInt (attackTimeSecs * sourceSampleRate);
  26092. releaseSamples = roundDoubleToInt (releaseTimeSecs * sourceSampleRate);
  26093. }
  26094. }
  26095. SamplerSound::~SamplerSound()
  26096. {
  26097. delete data;
  26098. data = 0;
  26099. }
  26100. bool SamplerSound::appliesToNote (const int midiNoteNumber)
  26101. {
  26102. return midiNotes [midiNoteNumber];
  26103. }
  26104. bool SamplerSound::appliesToChannel (const int /*midiChannel*/)
  26105. {
  26106. return true;
  26107. }
  26108. SamplerVoice::SamplerVoice()
  26109. : pitchRatio (0.0),
  26110. sourceSamplePosition (0.0),
  26111. lgain (0.0f),
  26112. rgain (0.0f),
  26113. isInAttack (false),
  26114. isInRelease (false)
  26115. {
  26116. }
  26117. SamplerVoice::~SamplerVoice()
  26118. {
  26119. }
  26120. bool SamplerVoice::canPlaySound (SynthesiserSound* sound)
  26121. {
  26122. return dynamic_cast <const SamplerSound*> (sound) != 0;
  26123. }
  26124. void SamplerVoice::startNote (const int midiNoteNumber,
  26125. const float velocity,
  26126. SynthesiserSound* s,
  26127. const int /*currentPitchWheelPosition*/)
  26128. {
  26129. const SamplerSound* const sound = dynamic_cast <const SamplerSound*> (s);
  26130. jassert (sound != 0); // this object can only play SamplerSounds!
  26131. if (sound != 0)
  26132. {
  26133. const double targetFreq = MidiMessage::getMidiNoteInHertz (midiNoteNumber);
  26134. const double naturalFreq = MidiMessage::getMidiNoteInHertz (sound->midiRootNote);
  26135. pitchRatio = (targetFreq * sound->sourceSampleRate) / (naturalFreq * getSampleRate());
  26136. sourceSamplePosition = 0.0;
  26137. lgain = velocity;
  26138. rgain = velocity;
  26139. isInAttack = (sound->attackSamples > 0);
  26140. isInRelease = false;
  26141. if (isInAttack)
  26142. {
  26143. attackReleaseLevel = 0.0f;
  26144. attackDelta = (float) (pitchRatio / sound->attackSamples);
  26145. }
  26146. else
  26147. {
  26148. attackReleaseLevel = 1.0f;
  26149. attackDelta = 0.0f;
  26150. }
  26151. if (sound->releaseSamples > 0)
  26152. {
  26153. releaseDelta = (float) (-pitchRatio / sound->releaseSamples);
  26154. }
  26155. else
  26156. {
  26157. releaseDelta = 0.0f;
  26158. }
  26159. }
  26160. }
  26161. void SamplerVoice::stopNote (const bool allowTailOff)
  26162. {
  26163. if (allowTailOff)
  26164. {
  26165. isInAttack = false;
  26166. isInRelease = true;
  26167. }
  26168. else
  26169. {
  26170. clearCurrentNote();
  26171. }
  26172. }
  26173. void SamplerVoice::pitchWheelMoved (const int /*newValue*/)
  26174. {
  26175. }
  26176. void SamplerVoice::controllerMoved (const int /*controllerNumber*/,
  26177. const int /*newValue*/)
  26178. {
  26179. }
  26180. void SamplerVoice::renderNextBlock (AudioSampleBuffer& outputBuffer, int startSample, int numSamples)
  26181. {
  26182. const SamplerSound* const playingSound = (SamplerSound*) (SynthesiserSound*) getCurrentlyPlayingSound();
  26183. if (playingSound != 0)
  26184. {
  26185. const float* const inL = playingSound->data->getSampleData (0, 0);
  26186. const float* const inR = playingSound->data->getNumChannels() > 1
  26187. ? playingSound->data->getSampleData (1, 0) : 0;
  26188. float* outL = outputBuffer.getSampleData (0, startSample);
  26189. float* outR = outputBuffer.getNumChannels() > 1 ? outputBuffer.getSampleData (1, startSample) : 0;
  26190. while (--numSamples >= 0)
  26191. {
  26192. const int pos = (int) sourceSamplePosition;
  26193. const float alpha = (float) (sourceSamplePosition - pos);
  26194. const float invAlpha = 1.0f - alpha;
  26195. // just using a very simple linear interpolation here..
  26196. float l = (inL [pos] * invAlpha + inL [pos + 1] * alpha);
  26197. float r = (inR != 0) ? (inR [pos] * invAlpha + inR [pos + 1] * alpha)
  26198. : l;
  26199. l *= lgain;
  26200. r *= rgain;
  26201. if (isInAttack)
  26202. {
  26203. l *= attackReleaseLevel;
  26204. r *= attackReleaseLevel;
  26205. attackReleaseLevel += attackDelta;
  26206. if (attackReleaseLevel >= 1.0f)
  26207. {
  26208. attackReleaseLevel = 1.0f;
  26209. isInAttack = false;
  26210. }
  26211. }
  26212. else if (isInRelease)
  26213. {
  26214. l *= attackReleaseLevel;
  26215. r *= attackReleaseLevel;
  26216. attackReleaseLevel += releaseDelta;
  26217. if (attackReleaseLevel <= 0.0f)
  26218. {
  26219. stopNote (false);
  26220. break;
  26221. }
  26222. }
  26223. if (outR != 0)
  26224. {
  26225. *outL++ += l;
  26226. *outR++ += r;
  26227. }
  26228. else
  26229. {
  26230. *outL++ += (l + r) * 0.5f;
  26231. }
  26232. sourceSamplePosition += pitchRatio;
  26233. if (sourceSamplePosition > playingSound->length)
  26234. {
  26235. stopNote (false);
  26236. break;
  26237. }
  26238. }
  26239. }
  26240. }
  26241. END_JUCE_NAMESPACE
  26242. /********* End of inlined file: juce_Sampler.cpp *********/
  26243. /********* Start of inlined file: juce_Synthesiser.cpp *********/
  26244. BEGIN_JUCE_NAMESPACE
  26245. SynthesiserSound::SynthesiserSound()
  26246. {
  26247. }
  26248. SynthesiserSound::~SynthesiserSound()
  26249. {
  26250. }
  26251. SynthesiserVoice::SynthesiserVoice()
  26252. : currentSampleRate (44100.0),
  26253. currentlyPlayingNote (-1),
  26254. noteOnTime (0),
  26255. currentlyPlayingSound (0)
  26256. {
  26257. }
  26258. SynthesiserVoice::~SynthesiserVoice()
  26259. {
  26260. }
  26261. bool SynthesiserVoice::isPlayingChannel (const int midiChannel) const
  26262. {
  26263. return currentlyPlayingSound != 0
  26264. && currentlyPlayingSound->appliesToChannel (midiChannel);
  26265. }
  26266. void SynthesiserVoice::setCurrentPlaybackSampleRate (const double newRate)
  26267. {
  26268. currentSampleRate = newRate;
  26269. }
  26270. void SynthesiserVoice::clearCurrentNote()
  26271. {
  26272. currentlyPlayingNote = -1;
  26273. currentlyPlayingSound = 0;
  26274. }
  26275. Synthesiser::Synthesiser()
  26276. : voices (2),
  26277. sounds (2),
  26278. sampleRate (0),
  26279. lastNoteOnCounter (0),
  26280. shouldStealNotes (true)
  26281. {
  26282. zeromem (lastPitchWheelValues, sizeof (lastPitchWheelValues));
  26283. }
  26284. Synthesiser::~Synthesiser()
  26285. {
  26286. }
  26287. SynthesiserVoice* Synthesiser::getVoice (const int index) const throw()
  26288. {
  26289. const ScopedLock sl (lock);
  26290. return voices [index];
  26291. }
  26292. void Synthesiser::clearVoices()
  26293. {
  26294. const ScopedLock sl (lock);
  26295. voices.clear();
  26296. }
  26297. void Synthesiser::addVoice (SynthesiserVoice* const newVoice)
  26298. {
  26299. const ScopedLock sl (lock);
  26300. voices.add (newVoice);
  26301. }
  26302. void Synthesiser::removeVoice (const int index)
  26303. {
  26304. const ScopedLock sl (lock);
  26305. voices.remove (index);
  26306. }
  26307. void Synthesiser::clearSounds()
  26308. {
  26309. const ScopedLock sl (lock);
  26310. sounds.clear();
  26311. }
  26312. void Synthesiser::addSound (const SynthesiserSound::Ptr& newSound)
  26313. {
  26314. const ScopedLock sl (lock);
  26315. sounds.add (newSound);
  26316. }
  26317. void Synthesiser::removeSound (const int index)
  26318. {
  26319. const ScopedLock sl (lock);
  26320. sounds.remove (index);
  26321. }
  26322. void Synthesiser::setNoteStealingEnabled (const bool shouldStealNotes_)
  26323. {
  26324. shouldStealNotes = shouldStealNotes_;
  26325. }
  26326. void Synthesiser::setCurrentPlaybackSampleRate (const double newRate)
  26327. {
  26328. if (sampleRate != newRate)
  26329. {
  26330. const ScopedLock sl (lock);
  26331. allNotesOff (0, false);
  26332. sampleRate = newRate;
  26333. for (int i = voices.size(); --i >= 0;)
  26334. voices.getUnchecked (i)->setCurrentPlaybackSampleRate (newRate);
  26335. }
  26336. }
  26337. void Synthesiser::renderNextBlock (AudioSampleBuffer& outputBuffer,
  26338. const MidiBuffer& midiData,
  26339. int startSample,
  26340. int numSamples)
  26341. {
  26342. // must set the sample rate before using this!
  26343. jassert (sampleRate != 0);
  26344. const ScopedLock sl (lock);
  26345. MidiBuffer::Iterator midiIterator (midiData);
  26346. midiIterator.setNextSamplePosition (startSample);
  26347. MidiMessage m (0xf4, 0.0);
  26348. while (numSamples > 0)
  26349. {
  26350. int midiEventPos;
  26351. const bool useEvent = midiIterator.getNextEvent (m, midiEventPos)
  26352. && midiEventPos < startSample + numSamples;
  26353. const int numThisTime = useEvent ? midiEventPos - startSample
  26354. : numSamples;
  26355. if (numThisTime > 0)
  26356. {
  26357. for (int i = voices.size(); --i >= 0;)
  26358. voices.getUnchecked (i)->renderNextBlock (outputBuffer, startSample, numThisTime);
  26359. }
  26360. if (useEvent)
  26361. {
  26362. if (m.isNoteOn())
  26363. {
  26364. const int channel = m.getChannel();
  26365. noteOn (channel,
  26366. m.getNoteNumber(),
  26367. m.getFloatVelocity());
  26368. }
  26369. else if (m.isNoteOff())
  26370. {
  26371. noteOff (m.getChannel(),
  26372. m.getNoteNumber(),
  26373. true);
  26374. }
  26375. else if (m.isAllNotesOff() || m.isAllSoundOff())
  26376. {
  26377. allNotesOff (m.getChannel(), true);
  26378. }
  26379. else if (m.isPitchWheel())
  26380. {
  26381. const int channel = m.getChannel();
  26382. const int wheelPos = m.getPitchWheelValue();
  26383. lastPitchWheelValues [channel - 1] = wheelPos;
  26384. handlePitchWheel (channel, wheelPos);
  26385. }
  26386. else if (m.isController())
  26387. {
  26388. handleController (m.getChannel(),
  26389. m.getControllerNumber(),
  26390. m.getControllerValue());
  26391. }
  26392. }
  26393. startSample += numThisTime;
  26394. numSamples -= numThisTime;
  26395. }
  26396. }
  26397. void Synthesiser::noteOn (const int midiChannel,
  26398. const int midiNoteNumber,
  26399. const float velocity)
  26400. {
  26401. const ScopedLock sl (lock);
  26402. for (int i = sounds.size(); --i >= 0;)
  26403. {
  26404. SynthesiserSound* const sound = sounds.getUnchecked(i);
  26405. if (sound->appliesToNote (midiNoteNumber)
  26406. && sound->appliesToChannel (midiChannel))
  26407. {
  26408. startVoice (findFreeVoice (sound, shouldStealNotes),
  26409. sound, midiChannel, midiNoteNumber, velocity);
  26410. }
  26411. }
  26412. }
  26413. void Synthesiser::startVoice (SynthesiserVoice* const voice,
  26414. SynthesiserSound* const sound,
  26415. const int midiChannel,
  26416. const int midiNoteNumber,
  26417. const float velocity)
  26418. {
  26419. if (voice != 0 && sound != 0)
  26420. {
  26421. if (voice->currentlyPlayingSound != 0)
  26422. voice->stopNote (false);
  26423. voice->startNote (midiNoteNumber,
  26424. velocity,
  26425. sound,
  26426. lastPitchWheelValues [midiChannel - 1]);
  26427. voice->currentlyPlayingNote = midiNoteNumber;
  26428. voice->noteOnTime = ++lastNoteOnCounter;
  26429. voice->currentlyPlayingSound = sound;
  26430. }
  26431. }
  26432. void Synthesiser::noteOff (const int midiChannel,
  26433. const int midiNoteNumber,
  26434. const bool allowTailOff)
  26435. {
  26436. const ScopedLock sl (lock);
  26437. for (int i = voices.size(); --i >= 0;)
  26438. {
  26439. SynthesiserVoice* const voice = voices.getUnchecked (i);
  26440. if (voice->getCurrentlyPlayingNote() == midiNoteNumber)
  26441. {
  26442. SynthesiserSound* const sound = voice->getCurrentlyPlayingSound();
  26443. if (sound != 0
  26444. && sound->appliesToNote (midiNoteNumber)
  26445. && sound->appliesToChannel (midiChannel))
  26446. {
  26447. voice->stopNote (allowTailOff);
  26448. // the subclass MUST call clearCurrentNote() if it's not tailing off! RTFM for stopNote()!
  26449. jassert (allowTailOff || (voice->getCurrentlyPlayingNote() < 0 && voice->getCurrentlyPlayingSound() == 0));
  26450. }
  26451. }
  26452. }
  26453. }
  26454. void Synthesiser::allNotesOff (const int midiChannel,
  26455. const bool allowTailOff)
  26456. {
  26457. const ScopedLock sl (lock);
  26458. for (int i = voices.size(); --i >= 0;)
  26459. {
  26460. SynthesiserVoice* const voice = voices.getUnchecked (i);
  26461. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  26462. voice->stopNote (allowTailOff);
  26463. }
  26464. }
  26465. void Synthesiser::handlePitchWheel (const int midiChannel,
  26466. const int wheelValue)
  26467. {
  26468. const ScopedLock sl (lock);
  26469. for (int i = voices.size(); --i >= 0;)
  26470. {
  26471. SynthesiserVoice* const voice = voices.getUnchecked (i);
  26472. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  26473. {
  26474. voice->pitchWheelMoved (wheelValue);
  26475. }
  26476. }
  26477. }
  26478. void Synthesiser::handleController (const int midiChannel,
  26479. const int controllerNumber,
  26480. const int controllerValue)
  26481. {
  26482. const ScopedLock sl (lock);
  26483. for (int i = voices.size(); --i >= 0;)
  26484. {
  26485. SynthesiserVoice* const voice = voices.getUnchecked (i);
  26486. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  26487. voice->controllerMoved (controllerNumber, controllerValue);
  26488. }
  26489. }
  26490. SynthesiserVoice* Synthesiser::findFreeVoice (SynthesiserSound* soundToPlay,
  26491. const bool stealIfNoneAvailable) const
  26492. {
  26493. const ScopedLock sl (lock);
  26494. for (int i = voices.size(); --i >= 0;)
  26495. if (voices.getUnchecked (i)->getCurrentlyPlayingNote() < 0
  26496. && voices.getUnchecked (i)->canPlaySound (soundToPlay))
  26497. return voices.getUnchecked (i);
  26498. if (stealIfNoneAvailable)
  26499. {
  26500. // currently this just steals the one that's been playing the longest, but could be made a bit smarter..
  26501. SynthesiserVoice* oldest = 0;
  26502. for (int i = voices.size(); --i >= 0;)
  26503. {
  26504. SynthesiserVoice* const voice = voices.getUnchecked (i);
  26505. if (voice->canPlaySound (soundToPlay)
  26506. && (oldest == 0 || oldest->noteOnTime > voice->noteOnTime))
  26507. oldest = voice;
  26508. }
  26509. jassert (oldest != 0);
  26510. return oldest;
  26511. }
  26512. return 0;
  26513. }
  26514. END_JUCE_NAMESPACE
  26515. /********* End of inlined file: juce_Synthesiser.cpp *********/
  26516. /********* Start of inlined file: juce_FileBasedDocument.cpp *********/
  26517. BEGIN_JUCE_NAMESPACE
  26518. FileBasedDocument::FileBasedDocument (const String& fileExtension_,
  26519. const String& fileWildcard_,
  26520. const String& openFileDialogTitle_,
  26521. const String& saveFileDialogTitle_)
  26522. : changedSinceSave (false),
  26523. fileExtension (fileExtension_),
  26524. fileWildcard (fileWildcard_),
  26525. openFileDialogTitle (openFileDialogTitle_),
  26526. saveFileDialogTitle (saveFileDialogTitle_)
  26527. {
  26528. }
  26529. FileBasedDocument::~FileBasedDocument()
  26530. {
  26531. }
  26532. void FileBasedDocument::setChangedFlag (const bool hasChanged)
  26533. {
  26534. changedSinceSave = hasChanged;
  26535. }
  26536. void FileBasedDocument::changed()
  26537. {
  26538. changedSinceSave = true;
  26539. sendChangeMessage (this);
  26540. }
  26541. void FileBasedDocument::setFile (const File& newFile)
  26542. {
  26543. if (documentFile != newFile)
  26544. {
  26545. documentFile = newFile;
  26546. changedSinceSave = true;
  26547. }
  26548. }
  26549. bool FileBasedDocument::loadFrom (const File& newFile,
  26550. const bool showMessageOnFailure)
  26551. {
  26552. MouseCursor::showWaitCursor();
  26553. const File oldFile (documentFile);
  26554. documentFile = newFile;
  26555. String error;
  26556. if (newFile.existsAsFile())
  26557. {
  26558. error = loadDocument (newFile);
  26559. if (error.isEmpty())
  26560. {
  26561. setChangedFlag (false);
  26562. MouseCursor::hideWaitCursor();
  26563. setLastDocumentOpened (newFile);
  26564. return true;
  26565. }
  26566. }
  26567. else
  26568. {
  26569. error = "The file doesn't exist";
  26570. }
  26571. documentFile = oldFile;
  26572. MouseCursor::hideWaitCursor();
  26573. if (showMessageOnFailure)
  26574. {
  26575. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  26576. TRANS("Failed to open file..."),
  26577. TRANS("There was an error while trying to load the file:\n\n")
  26578. + newFile.getFullPathName()
  26579. + T("\n\n")
  26580. + error);
  26581. }
  26582. return false;
  26583. }
  26584. bool FileBasedDocument::loadFromUserSpecifiedFile (const bool showMessageOnFailure)
  26585. {
  26586. FileChooser fc (openFileDialogTitle,
  26587. getLastDocumentOpened(),
  26588. fileWildcard);
  26589. if (fc.browseForFileToOpen())
  26590. return loadFrom (fc.getResult(), showMessageOnFailure);
  26591. return false;
  26592. }
  26593. FileBasedDocument::SaveResult FileBasedDocument::save (const bool askUserForFileIfNotSpecified,
  26594. const bool showMessageOnFailure)
  26595. {
  26596. return saveAs (documentFile,
  26597. false,
  26598. askUserForFileIfNotSpecified,
  26599. showMessageOnFailure);
  26600. }
  26601. FileBasedDocument::SaveResult FileBasedDocument::saveAs (const File& newFile,
  26602. const bool warnAboutOverwritingExistingFiles,
  26603. const bool askUserForFileIfNotSpecified,
  26604. const bool showMessageOnFailure)
  26605. {
  26606. if (newFile == File::nonexistent)
  26607. {
  26608. if (askUserForFileIfNotSpecified)
  26609. {
  26610. return saveAsInteractive (true);
  26611. }
  26612. else
  26613. {
  26614. // can't save to an unspecified file
  26615. jassertfalse
  26616. return failedToWriteToFile;
  26617. }
  26618. }
  26619. if (warnAboutOverwritingExistingFiles && newFile.exists())
  26620. {
  26621. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  26622. TRANS("File already exists"),
  26623. TRANS("There's already a file called:\n\n")
  26624. + newFile.getFullPathName()
  26625. + TRANS("\n\nAre you sure you want to overwrite it?"),
  26626. TRANS("overwrite"),
  26627. TRANS("cancel")))
  26628. {
  26629. return userCancelledSave;
  26630. }
  26631. }
  26632. MouseCursor::showWaitCursor();
  26633. const File oldFile (documentFile);
  26634. documentFile = newFile;
  26635. String error (saveDocument (newFile));
  26636. if (error.isEmpty())
  26637. {
  26638. setChangedFlag (false);
  26639. MouseCursor::hideWaitCursor();
  26640. return savedOk;
  26641. }
  26642. documentFile = oldFile;
  26643. MouseCursor::hideWaitCursor();
  26644. if (showMessageOnFailure)
  26645. {
  26646. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  26647. TRANS("Error writing to file..."),
  26648. TRANS("An error occurred while trying to save \"")
  26649. + getDocumentTitle()
  26650. + TRANS("\" to the file:\n\n")
  26651. + newFile.getFullPathName()
  26652. + T("\n\n")
  26653. + error);
  26654. }
  26655. return failedToWriteToFile;
  26656. }
  26657. FileBasedDocument::SaveResult FileBasedDocument::saveIfNeededAndUserAgrees()
  26658. {
  26659. if (! hasChangedSinceSaved())
  26660. return savedOk;
  26661. const int r = AlertWindow::showYesNoCancelBox (AlertWindow::QuestionIcon,
  26662. TRANS("Closing document..."),
  26663. TRANS("Do you want to save the changes to \"")
  26664. + getDocumentTitle() + T("\"?"),
  26665. TRANS("save"),
  26666. TRANS("discard changes"),
  26667. TRANS("cancel"));
  26668. if (r == 1)
  26669. {
  26670. // save changes
  26671. return save (true, true);
  26672. }
  26673. else if (r == 2)
  26674. {
  26675. // discard changes
  26676. return savedOk;
  26677. }
  26678. return userCancelledSave;
  26679. }
  26680. FileBasedDocument::SaveResult FileBasedDocument::saveAsInteractive (const bool warnAboutOverwritingExistingFiles)
  26681. {
  26682. File f;
  26683. if (documentFile.existsAsFile())
  26684. f = documentFile;
  26685. else
  26686. f = getLastDocumentOpened();
  26687. String legalFilename (File::createLegalFileName (getDocumentTitle()));
  26688. if (legalFilename.isEmpty())
  26689. legalFilename = "unnamed";
  26690. if (f.existsAsFile() || f.getParentDirectory().isDirectory())
  26691. f = f.getSiblingFile (legalFilename);
  26692. else
  26693. f = File::getSpecialLocation (File::userDocumentsDirectory).getChildFile (legalFilename);
  26694. f = f.withFileExtension (fileExtension)
  26695. .getNonexistentSibling (true);
  26696. FileChooser fc (saveFileDialogTitle, f, fileWildcard);
  26697. if (fc.browseForFileToSave (warnAboutOverwritingExistingFiles))
  26698. {
  26699. setLastDocumentOpened (fc.getResult());
  26700. File chosen (fc.getResult());
  26701. if (chosen.getFileExtension().isEmpty())
  26702. chosen = chosen.withFileExtension (fileExtension);
  26703. return saveAs (chosen, false, false, true);
  26704. }
  26705. return userCancelledSave;
  26706. }
  26707. END_JUCE_NAMESPACE
  26708. /********* End of inlined file: juce_FileBasedDocument.cpp *********/
  26709. /********* Start of inlined file: juce_RecentlyOpenedFilesList.cpp *********/
  26710. BEGIN_JUCE_NAMESPACE
  26711. RecentlyOpenedFilesList::RecentlyOpenedFilesList()
  26712. : maxNumberOfItems (10)
  26713. {
  26714. }
  26715. RecentlyOpenedFilesList::~RecentlyOpenedFilesList()
  26716. {
  26717. }
  26718. void RecentlyOpenedFilesList::setMaxNumberOfItems (const int newMaxNumber)
  26719. {
  26720. maxNumberOfItems = jmax (1, newMaxNumber);
  26721. while (getNumFiles() > maxNumberOfItems)
  26722. files.remove (getNumFiles() - 1);
  26723. }
  26724. int RecentlyOpenedFilesList::getNumFiles() const
  26725. {
  26726. return files.size();
  26727. }
  26728. const File RecentlyOpenedFilesList::getFile (const int index) const
  26729. {
  26730. return File (files [index]);
  26731. }
  26732. void RecentlyOpenedFilesList::clear()
  26733. {
  26734. files.clear();
  26735. }
  26736. void RecentlyOpenedFilesList::addFile (const File& file)
  26737. {
  26738. const String path (file.getFullPathName());
  26739. files.removeString (path, true);
  26740. files.insert (0, path);
  26741. setMaxNumberOfItems (maxNumberOfItems);
  26742. }
  26743. void RecentlyOpenedFilesList::removeNonExistentFiles()
  26744. {
  26745. for (int i = getNumFiles(); --i >= 0;)
  26746. if (! getFile(i).exists())
  26747. files.remove (i);
  26748. }
  26749. int RecentlyOpenedFilesList::createPopupMenuItems (PopupMenu& menuToAddTo,
  26750. const int baseItemId,
  26751. const bool showFullPaths,
  26752. const bool dontAddNonExistentFiles,
  26753. const File** filesToAvoid)
  26754. {
  26755. int num = 0;
  26756. for (int i = 0; i < getNumFiles(); ++i)
  26757. {
  26758. const File f (getFile(i));
  26759. if ((! dontAddNonExistentFiles) || f.exists())
  26760. {
  26761. bool needsAvoiding = false;
  26762. if (filesToAvoid != 0)
  26763. {
  26764. const File** files = filesToAvoid;
  26765. while (*files != 0)
  26766. {
  26767. if (f == **files)
  26768. {
  26769. needsAvoiding = true;
  26770. break;
  26771. }
  26772. ++files;
  26773. }
  26774. }
  26775. if (! needsAvoiding)
  26776. {
  26777. menuToAddTo.addItem (baseItemId + i,
  26778. showFullPaths ? f.getFullPathName()
  26779. : f.getFileName());
  26780. ++num;
  26781. }
  26782. }
  26783. }
  26784. return num;
  26785. }
  26786. const String RecentlyOpenedFilesList::toString() const
  26787. {
  26788. return files.joinIntoString (T("\n"));
  26789. }
  26790. void RecentlyOpenedFilesList::restoreFromString (const String& stringifiedVersion)
  26791. {
  26792. clear();
  26793. files.addLines (stringifiedVersion);
  26794. setMaxNumberOfItems (maxNumberOfItems);
  26795. }
  26796. END_JUCE_NAMESPACE
  26797. /********* End of inlined file: juce_RecentlyOpenedFilesList.cpp *********/
  26798. /********* Start of inlined file: juce_UndoManager.cpp *********/
  26799. BEGIN_JUCE_NAMESPACE
  26800. UndoManager::UndoManager (const int maxNumberOfUnitsToKeep,
  26801. const int minimumTransactions)
  26802. : totalUnitsStored (0),
  26803. nextIndex (0),
  26804. newTransaction (true),
  26805. reentrancyCheck (false)
  26806. {
  26807. setMaxNumberOfStoredUnits (maxNumberOfUnitsToKeep,
  26808. minimumTransactions);
  26809. }
  26810. UndoManager::~UndoManager()
  26811. {
  26812. clearUndoHistory();
  26813. }
  26814. void UndoManager::clearUndoHistory()
  26815. {
  26816. transactions.clear();
  26817. transactionNames.clear();
  26818. totalUnitsStored = 0;
  26819. nextIndex = 0;
  26820. sendChangeMessage (this);
  26821. }
  26822. int UndoManager::getNumberOfUnitsTakenUpByStoredCommands() const
  26823. {
  26824. return totalUnitsStored;
  26825. }
  26826. void UndoManager::setMaxNumberOfStoredUnits (const int maxNumberOfUnitsToKeep,
  26827. const int minimumTransactions)
  26828. {
  26829. maxNumUnitsToKeep = jmax (1, maxNumberOfUnitsToKeep);
  26830. minimumTransactionsToKeep = jmax (1, minimumTransactions);
  26831. }
  26832. bool UndoManager::perform (UndoableAction* const command, const String& actionName)
  26833. {
  26834. if (command != 0)
  26835. {
  26836. if (actionName.isNotEmpty())
  26837. currentTransactionName = actionName;
  26838. if (reentrancyCheck)
  26839. {
  26840. jassertfalse // don't call perform() recursively from the UndoableAction::perform() or
  26841. // undo() methods, or else these actions won't actually get done.
  26842. return false;
  26843. }
  26844. else
  26845. {
  26846. bool success = false;
  26847. JUCE_TRY
  26848. {
  26849. success = command->perform();
  26850. }
  26851. JUCE_CATCH_EXCEPTION
  26852. jassert (success);
  26853. if (success)
  26854. {
  26855. if (nextIndex > 0 && ! newTransaction)
  26856. {
  26857. OwnedArray<UndoableAction>* commandSet = transactions [nextIndex - 1];
  26858. jassert (commandSet != 0);
  26859. if (commandSet == 0)
  26860. return false;
  26861. commandSet->add (command);
  26862. }
  26863. else
  26864. {
  26865. OwnedArray<UndoableAction>* commandSet = new OwnedArray<UndoableAction>();
  26866. commandSet->add (command);
  26867. transactions.insert (nextIndex, commandSet);
  26868. transactionNames.insert (nextIndex, currentTransactionName);
  26869. ++nextIndex;
  26870. }
  26871. totalUnitsStored += command->getSizeInUnits();
  26872. newTransaction = false;
  26873. }
  26874. while (nextIndex < transactions.size())
  26875. {
  26876. const OwnedArray <UndoableAction>* const lastSet = transactions.getLast();
  26877. for (int i = lastSet->size(); --i >= 0;)
  26878. totalUnitsStored -= lastSet->getUnchecked (i)->getSizeInUnits();
  26879. transactions.removeLast();
  26880. transactionNames.remove (transactionNames.size() - 1);
  26881. }
  26882. while (nextIndex > 0
  26883. && totalUnitsStored > maxNumUnitsToKeep
  26884. && transactions.size() > minimumTransactionsToKeep)
  26885. {
  26886. const OwnedArray <UndoableAction>* const firstSet = transactions.getFirst();
  26887. for (int i = firstSet->size(); --i >= 0;)
  26888. totalUnitsStored -= firstSet->getUnchecked (i)->getSizeInUnits();
  26889. jassert (totalUnitsStored >= 0); // something fishy going on if this fails!
  26890. transactions.remove (0);
  26891. transactionNames.remove (0);
  26892. --nextIndex;
  26893. }
  26894. sendChangeMessage (this);
  26895. return success;
  26896. }
  26897. }
  26898. return false;
  26899. }
  26900. void UndoManager::beginNewTransaction (const String& actionName)
  26901. {
  26902. newTransaction = true;
  26903. currentTransactionName = actionName;
  26904. }
  26905. void UndoManager::setCurrentTransactionName (const String& newName)
  26906. {
  26907. currentTransactionName = newName;
  26908. }
  26909. bool UndoManager::canUndo() const
  26910. {
  26911. return nextIndex > 0;
  26912. }
  26913. bool UndoManager::canRedo() const
  26914. {
  26915. return nextIndex < transactions.size();
  26916. }
  26917. const String UndoManager::getUndoDescription() const
  26918. {
  26919. return transactionNames [nextIndex - 1];
  26920. }
  26921. const String UndoManager::getRedoDescription() const
  26922. {
  26923. return transactionNames [nextIndex];
  26924. }
  26925. bool UndoManager::undo()
  26926. {
  26927. const OwnedArray<UndoableAction>* const commandSet = transactions [nextIndex - 1];
  26928. if (commandSet == 0)
  26929. return false;
  26930. reentrancyCheck = true;
  26931. bool failed = false;
  26932. for (int i = commandSet->size(); --i >= 0;)
  26933. {
  26934. if (! commandSet->getUnchecked(i)->undo())
  26935. {
  26936. jassertfalse
  26937. failed = true;
  26938. break;
  26939. }
  26940. }
  26941. reentrancyCheck = false;
  26942. if (failed)
  26943. {
  26944. clearUndoHistory();
  26945. }
  26946. else
  26947. {
  26948. --nextIndex;
  26949. }
  26950. beginNewTransaction();
  26951. sendChangeMessage (this);
  26952. return true;
  26953. }
  26954. bool UndoManager::redo()
  26955. {
  26956. const OwnedArray<UndoableAction>* const commandSet = transactions [nextIndex];
  26957. if (commandSet == 0)
  26958. return false;
  26959. reentrancyCheck = true;
  26960. bool failed = false;
  26961. for (int i = 0; i < commandSet->size(); ++i)
  26962. {
  26963. if (! commandSet->getUnchecked(i)->perform())
  26964. {
  26965. jassertfalse
  26966. failed = true;
  26967. break;
  26968. }
  26969. }
  26970. reentrancyCheck = false;
  26971. if (failed)
  26972. {
  26973. clearUndoHistory();
  26974. }
  26975. else
  26976. {
  26977. ++nextIndex;
  26978. }
  26979. beginNewTransaction();
  26980. sendChangeMessage (this);
  26981. return true;
  26982. }
  26983. bool UndoManager::undoCurrentTransactionOnly()
  26984. {
  26985. return newTransaction ? false
  26986. : undo();
  26987. }
  26988. void UndoManager::getActionsInCurrentTransaction (Array <const UndoableAction*>& actionsFound) const
  26989. {
  26990. const OwnedArray <UndoableAction>* const commandSet = transactions [nextIndex - 1];
  26991. if (commandSet != 0 && ! newTransaction)
  26992. {
  26993. for (int i = 0; i < commandSet->size(); ++i)
  26994. actionsFound.add (commandSet->getUnchecked(i));
  26995. }
  26996. }
  26997. END_JUCE_NAMESPACE
  26998. /********* End of inlined file: juce_UndoManager.cpp *********/
  26999. /********* Start of inlined file: juce_ActionBroadcaster.cpp *********/
  27000. BEGIN_JUCE_NAMESPACE
  27001. ActionBroadcaster::ActionBroadcaster() throw()
  27002. {
  27003. // are you trying to create this object before or after juce has been intialised??
  27004. jassert (MessageManager::instance != 0);
  27005. }
  27006. ActionBroadcaster::~ActionBroadcaster()
  27007. {
  27008. // all event-based objects must be deleted BEFORE juce is shut down!
  27009. jassert (MessageManager::instance != 0);
  27010. }
  27011. void ActionBroadcaster::addActionListener (ActionListener* const listener)
  27012. {
  27013. actionListenerList.addActionListener (listener);
  27014. }
  27015. void ActionBroadcaster::removeActionListener (ActionListener* const listener)
  27016. {
  27017. jassert (actionListenerList.isValidMessageListener());
  27018. if (actionListenerList.isValidMessageListener())
  27019. actionListenerList.removeActionListener (listener);
  27020. }
  27021. void ActionBroadcaster::removeAllActionListeners()
  27022. {
  27023. actionListenerList.removeAllActionListeners();
  27024. }
  27025. void ActionBroadcaster::sendActionMessage (const String& message) const
  27026. {
  27027. actionListenerList.sendActionMessage (message);
  27028. }
  27029. END_JUCE_NAMESPACE
  27030. /********* End of inlined file: juce_ActionBroadcaster.cpp *********/
  27031. /********* Start of inlined file: juce_ActionListenerList.cpp *********/
  27032. BEGIN_JUCE_NAMESPACE
  27033. // special message of our own with a string in it
  27034. class ActionMessage : public Message
  27035. {
  27036. public:
  27037. const String message;
  27038. ActionMessage (const String& messageText,
  27039. void* const listener_) throw()
  27040. : message (messageText)
  27041. {
  27042. pointerParameter = listener_;
  27043. }
  27044. ~ActionMessage() throw()
  27045. {
  27046. }
  27047. private:
  27048. ActionMessage (const ActionMessage&);
  27049. const ActionMessage& operator= (const ActionMessage&);
  27050. };
  27051. ActionListenerList::ActionListenerList() throw()
  27052. {
  27053. }
  27054. ActionListenerList::~ActionListenerList() throw()
  27055. {
  27056. }
  27057. void ActionListenerList::addActionListener (ActionListener* const listener) throw()
  27058. {
  27059. const ScopedLock sl (actionListenerLock_);
  27060. jassert (listener != 0);
  27061. jassert (! actionListeners_.contains (listener)); // trying to add a listener to the list twice!
  27062. if (listener != 0)
  27063. actionListeners_.add (listener);
  27064. }
  27065. void ActionListenerList::removeActionListener (ActionListener* const listener) throw()
  27066. {
  27067. const ScopedLock sl (actionListenerLock_);
  27068. jassert (actionListeners_.contains (listener)); // trying to remove a listener that isn't on the list!
  27069. actionListeners_.removeValue (listener);
  27070. }
  27071. void ActionListenerList::removeAllActionListeners() throw()
  27072. {
  27073. const ScopedLock sl (actionListenerLock_);
  27074. actionListeners_.clear();
  27075. }
  27076. void ActionListenerList::sendActionMessage (const String& message) const
  27077. {
  27078. const ScopedLock sl (actionListenerLock_);
  27079. for (int i = actionListeners_.size(); --i >= 0;)
  27080. {
  27081. postMessage (new ActionMessage (message,
  27082. (ActionListener*) actionListeners_.getUnchecked(i)));
  27083. }
  27084. }
  27085. void ActionListenerList::handleMessage (const Message& message)
  27086. {
  27087. const ActionMessage& am = (const ActionMessage&) message;
  27088. if (actionListeners_.contains (am.pointerParameter))
  27089. ((ActionListener*) am.pointerParameter)->actionListenerCallback (am.message);
  27090. }
  27091. END_JUCE_NAMESPACE
  27092. /********* End of inlined file: juce_ActionListenerList.cpp *********/
  27093. /********* Start of inlined file: juce_AsyncUpdater.cpp *********/
  27094. BEGIN_JUCE_NAMESPACE
  27095. AsyncUpdater::AsyncUpdater() throw()
  27096. : asyncMessagePending (false)
  27097. {
  27098. internalAsyncHandler.owner = this;
  27099. }
  27100. AsyncUpdater::~AsyncUpdater()
  27101. {
  27102. }
  27103. void AsyncUpdater::triggerAsyncUpdate() throw()
  27104. {
  27105. if (! asyncMessagePending)
  27106. {
  27107. asyncMessagePending = true;
  27108. internalAsyncHandler.postMessage (new Message());
  27109. }
  27110. }
  27111. void AsyncUpdater::cancelPendingUpdate() throw()
  27112. {
  27113. asyncMessagePending = false;
  27114. }
  27115. void AsyncUpdater::handleUpdateNowIfNeeded()
  27116. {
  27117. if (asyncMessagePending)
  27118. {
  27119. asyncMessagePending = false;
  27120. handleAsyncUpdate();
  27121. }
  27122. }
  27123. void AsyncUpdater::AsyncUpdaterInternal::handleMessage (const Message&)
  27124. {
  27125. owner->handleUpdateNowIfNeeded();
  27126. }
  27127. END_JUCE_NAMESPACE
  27128. /********* End of inlined file: juce_AsyncUpdater.cpp *********/
  27129. /********* Start of inlined file: juce_ChangeBroadcaster.cpp *********/
  27130. BEGIN_JUCE_NAMESPACE
  27131. ChangeBroadcaster::ChangeBroadcaster() throw()
  27132. {
  27133. // are you trying to create this object before or after juce has been intialised??
  27134. jassert (MessageManager::instance != 0);
  27135. }
  27136. ChangeBroadcaster::~ChangeBroadcaster()
  27137. {
  27138. // all event-based objects must be deleted BEFORE juce is shut down!
  27139. jassert (MessageManager::instance != 0);
  27140. }
  27141. void ChangeBroadcaster::addChangeListener (ChangeListener* const listener) throw()
  27142. {
  27143. changeListenerList.addChangeListener (listener);
  27144. }
  27145. void ChangeBroadcaster::removeChangeListener (ChangeListener* const listener) throw()
  27146. {
  27147. jassert (changeListenerList.isValidMessageListener());
  27148. if (changeListenerList.isValidMessageListener())
  27149. changeListenerList.removeChangeListener (listener);
  27150. }
  27151. void ChangeBroadcaster::removeAllChangeListeners() throw()
  27152. {
  27153. changeListenerList.removeAllChangeListeners();
  27154. }
  27155. void ChangeBroadcaster::sendChangeMessage (void* objectThatHasChanged) throw()
  27156. {
  27157. changeListenerList.sendChangeMessage (objectThatHasChanged);
  27158. }
  27159. void ChangeBroadcaster::sendSynchronousChangeMessage (void* objectThatHasChanged)
  27160. {
  27161. changeListenerList.sendSynchronousChangeMessage (objectThatHasChanged);
  27162. }
  27163. void ChangeBroadcaster::dispatchPendingMessages()
  27164. {
  27165. changeListenerList.dispatchPendingMessages();
  27166. }
  27167. END_JUCE_NAMESPACE
  27168. /********* End of inlined file: juce_ChangeBroadcaster.cpp *********/
  27169. /********* Start of inlined file: juce_ChangeListenerList.cpp *********/
  27170. BEGIN_JUCE_NAMESPACE
  27171. ChangeListenerList::ChangeListenerList() throw()
  27172. : lastChangedObject (0),
  27173. messagePending (false)
  27174. {
  27175. }
  27176. ChangeListenerList::~ChangeListenerList() throw()
  27177. {
  27178. }
  27179. void ChangeListenerList::addChangeListener (ChangeListener* const listener) throw()
  27180. {
  27181. const ScopedLock sl (lock);
  27182. jassert (listener != 0);
  27183. if (listener != 0)
  27184. listeners.add (listener);
  27185. }
  27186. void ChangeListenerList::removeChangeListener (ChangeListener* const listener) throw()
  27187. {
  27188. const ScopedLock sl (lock);
  27189. listeners.removeValue (listener);
  27190. }
  27191. void ChangeListenerList::removeAllChangeListeners() throw()
  27192. {
  27193. const ScopedLock sl (lock);
  27194. listeners.clear();
  27195. }
  27196. void ChangeListenerList::sendChangeMessage (void* const objectThatHasChanged) throw()
  27197. {
  27198. const ScopedLock sl (lock);
  27199. if ((! messagePending) && (listeners.size() > 0))
  27200. {
  27201. lastChangedObject = objectThatHasChanged;
  27202. postMessage (new Message (0, 0, 0, objectThatHasChanged));
  27203. messagePending = true;
  27204. }
  27205. }
  27206. void ChangeListenerList::handleMessage (const Message& message)
  27207. {
  27208. sendSynchronousChangeMessage (message.pointerParameter);
  27209. }
  27210. void ChangeListenerList::sendSynchronousChangeMessage (void* const objectThatHasChanged)
  27211. {
  27212. const ScopedLock sl (lock);
  27213. messagePending = false;
  27214. for (int i = listeners.size(); --i >= 0;)
  27215. {
  27216. ChangeListener* const l = (ChangeListener*) listeners.getUnchecked (i);
  27217. {
  27218. const ScopedUnlock tempUnlocker (lock);
  27219. l->changeListenerCallback (objectThatHasChanged);
  27220. }
  27221. i = jmin (i, listeners.size());
  27222. }
  27223. }
  27224. void ChangeListenerList::dispatchPendingMessages()
  27225. {
  27226. if (messagePending)
  27227. sendSynchronousChangeMessage (lastChangedObject);
  27228. }
  27229. END_JUCE_NAMESPACE
  27230. /********* End of inlined file: juce_ChangeListenerList.cpp *********/
  27231. /********* Start of inlined file: juce_InterprocessConnection.cpp *********/
  27232. BEGIN_JUCE_NAMESPACE
  27233. InterprocessConnection::InterprocessConnection (const bool callbacksOnMessageThread,
  27234. const uint32 magicMessageHeaderNumber)
  27235. : Thread ("Juce IPC connection"),
  27236. socket (0),
  27237. pipe (0),
  27238. callbackConnectionState (false),
  27239. useMessageThread (callbacksOnMessageThread),
  27240. magicMessageHeader (magicMessageHeaderNumber),
  27241. pipeReceiveMessageTimeout (-1)
  27242. {
  27243. }
  27244. InterprocessConnection::~InterprocessConnection()
  27245. {
  27246. callbackConnectionState = false;
  27247. disconnect();
  27248. }
  27249. bool InterprocessConnection::connectToSocket (const String& hostName,
  27250. const int portNumber,
  27251. const int timeOutMillisecs)
  27252. {
  27253. disconnect();
  27254. const ScopedLock sl (pipeAndSocketLock);
  27255. socket = new StreamingSocket();
  27256. if (socket->connect (hostName, portNumber, timeOutMillisecs))
  27257. {
  27258. connectionMadeInt();
  27259. startThread();
  27260. return true;
  27261. }
  27262. else
  27263. {
  27264. deleteAndZero (socket);
  27265. return false;
  27266. }
  27267. }
  27268. bool InterprocessConnection::connectToPipe (const String& pipeName,
  27269. const int pipeReceiveMessageTimeoutMs)
  27270. {
  27271. disconnect();
  27272. NamedPipe* const newPipe = new NamedPipe();
  27273. if (newPipe->openExisting (pipeName))
  27274. {
  27275. const ScopedLock sl (pipeAndSocketLock);
  27276. pipeReceiveMessageTimeout = pipeReceiveMessageTimeoutMs;
  27277. initialiseWithPipe (newPipe);
  27278. return true;
  27279. }
  27280. else
  27281. {
  27282. delete newPipe;
  27283. return false;
  27284. }
  27285. }
  27286. bool InterprocessConnection::createPipe (const String& pipeName,
  27287. const int pipeReceiveMessageTimeoutMs)
  27288. {
  27289. disconnect();
  27290. NamedPipe* const newPipe = new NamedPipe();
  27291. if (newPipe->createNewPipe (pipeName))
  27292. {
  27293. const ScopedLock sl (pipeAndSocketLock);
  27294. pipeReceiveMessageTimeout = pipeReceiveMessageTimeoutMs;
  27295. initialiseWithPipe (newPipe);
  27296. return true;
  27297. }
  27298. else
  27299. {
  27300. delete newPipe;
  27301. return false;
  27302. }
  27303. }
  27304. void InterprocessConnection::disconnect()
  27305. {
  27306. if (socket != 0)
  27307. socket->close();
  27308. if (pipe != 0)
  27309. {
  27310. pipe->cancelPendingReads();
  27311. pipe->close();
  27312. }
  27313. stopThread (4000);
  27314. {
  27315. const ScopedLock sl (pipeAndSocketLock);
  27316. deleteAndZero (socket);
  27317. deleteAndZero (pipe);
  27318. }
  27319. connectionLostInt();
  27320. }
  27321. bool InterprocessConnection::isConnected() const
  27322. {
  27323. const ScopedLock sl (pipeAndSocketLock);
  27324. return ((socket != 0 && socket->isConnected())
  27325. || (pipe != 0 && pipe->isOpen()))
  27326. && isThreadRunning();
  27327. }
  27328. const String InterprocessConnection::getConnectedHostName() const
  27329. {
  27330. if (pipe != 0)
  27331. {
  27332. return "localhost";
  27333. }
  27334. else if (socket != 0)
  27335. {
  27336. if (! socket->isLocal())
  27337. return socket->getHostName();
  27338. return "localhost";
  27339. }
  27340. return String::empty;
  27341. }
  27342. bool InterprocessConnection::sendMessage (const MemoryBlock& message)
  27343. {
  27344. uint32 messageHeader[2];
  27345. messageHeader [0] = swapIfBigEndian (magicMessageHeader);
  27346. messageHeader [1] = swapIfBigEndian ((uint32) message.getSize());
  27347. MemoryBlock messageData (sizeof (messageHeader) + message.getSize());
  27348. messageData.copyFrom (messageHeader, 0, sizeof (messageHeader));
  27349. messageData.copyFrom (message.getData(), sizeof (messageHeader), message.getSize());
  27350. int bytesWritten = 0;
  27351. const ScopedLock sl (pipeAndSocketLock);
  27352. if (socket != 0)
  27353. {
  27354. bytesWritten = socket->write (messageData.getData(), messageData.getSize());
  27355. }
  27356. else if (pipe != 0)
  27357. {
  27358. bytesWritten = pipe->write (messageData.getData(), messageData.getSize());
  27359. }
  27360. if (bytesWritten < 0)
  27361. {
  27362. // error..
  27363. return false;
  27364. }
  27365. return (bytesWritten == messageData.getSize());
  27366. }
  27367. void InterprocessConnection::initialiseWithSocket (StreamingSocket* const socket_)
  27368. {
  27369. jassert (socket == 0);
  27370. socket = socket_;
  27371. connectionMadeInt();
  27372. startThread();
  27373. }
  27374. void InterprocessConnection::initialiseWithPipe (NamedPipe* const pipe_)
  27375. {
  27376. jassert (pipe == 0);
  27377. pipe = pipe_;
  27378. connectionMadeInt();
  27379. startThread();
  27380. }
  27381. const int messageMagicNumber = 0xb734128b;
  27382. void InterprocessConnection::handleMessage (const Message& message)
  27383. {
  27384. if (message.intParameter1 == messageMagicNumber)
  27385. {
  27386. switch (message.intParameter2)
  27387. {
  27388. case 0:
  27389. {
  27390. MemoryBlock* const data = (MemoryBlock*) message.pointerParameter;
  27391. messageReceived (*data);
  27392. delete data;
  27393. break;
  27394. }
  27395. case 1:
  27396. connectionMade();
  27397. break;
  27398. case 2:
  27399. connectionLost();
  27400. break;
  27401. }
  27402. }
  27403. }
  27404. void InterprocessConnection::connectionMadeInt()
  27405. {
  27406. if (! callbackConnectionState)
  27407. {
  27408. callbackConnectionState = true;
  27409. if (useMessageThread)
  27410. postMessage (new Message (messageMagicNumber, 1, 0, 0));
  27411. else
  27412. connectionMade();
  27413. }
  27414. }
  27415. void InterprocessConnection::connectionLostInt()
  27416. {
  27417. if (callbackConnectionState)
  27418. {
  27419. callbackConnectionState = false;
  27420. if (useMessageThread)
  27421. postMessage (new Message (messageMagicNumber, 2, 0, 0));
  27422. else
  27423. connectionLost();
  27424. }
  27425. }
  27426. void InterprocessConnection::deliverDataInt (const MemoryBlock& data)
  27427. {
  27428. jassert (callbackConnectionState);
  27429. if (useMessageThread)
  27430. postMessage (new Message (messageMagicNumber, 0, 0, new MemoryBlock (data)));
  27431. else
  27432. messageReceived (data);
  27433. }
  27434. bool InterprocessConnection::readNextMessageInt()
  27435. {
  27436. const int maximumMessageSize = 1024 * 1024 * 10; // sanity check
  27437. uint32 messageHeader[2];
  27438. const int bytes = (socket != 0) ? socket->read (messageHeader, sizeof (messageHeader))
  27439. : pipe->read (messageHeader, sizeof (messageHeader), pipeReceiveMessageTimeout);
  27440. if (bytes == sizeof (messageHeader)
  27441. && swapIfBigEndian (messageHeader[0]) == magicMessageHeader)
  27442. {
  27443. const int bytesInMessage = (int) swapIfBigEndian (messageHeader[1]);
  27444. if (bytesInMessage > 0 && bytesInMessage < maximumMessageSize)
  27445. {
  27446. MemoryBlock messageData (bytesInMessage, true);
  27447. int bytesRead = 0;
  27448. while (bytesRead < bytesInMessage)
  27449. {
  27450. if (threadShouldExit())
  27451. return false;
  27452. const int numThisTime = jmin (bytesInMessage, 65536);
  27453. const int bytesIn = (socket != 0) ? socket->read (((char*) messageData.getData()) + bytesRead, numThisTime)
  27454. : pipe->read (((char*) messageData.getData()) + bytesRead, numThisTime,
  27455. pipeReceiveMessageTimeout);
  27456. if (bytesIn <= 0)
  27457. break;
  27458. bytesRead += bytesIn;
  27459. }
  27460. if (bytesRead >= 0)
  27461. deliverDataInt (messageData);
  27462. }
  27463. }
  27464. else if (bytes < 0)
  27465. {
  27466. {
  27467. const ScopedLock sl (pipeAndSocketLock);
  27468. deleteAndZero (socket);
  27469. }
  27470. connectionLostInt();
  27471. return false;
  27472. }
  27473. return true;
  27474. }
  27475. void InterprocessConnection::run()
  27476. {
  27477. while (! threadShouldExit())
  27478. {
  27479. if (socket != 0)
  27480. {
  27481. const int ready = socket->waitUntilReady (true, 0);
  27482. if (ready < 0)
  27483. {
  27484. {
  27485. const ScopedLock sl (pipeAndSocketLock);
  27486. deleteAndZero (socket);
  27487. }
  27488. connectionLostInt();
  27489. break;
  27490. }
  27491. else if (ready > 0)
  27492. {
  27493. if (! readNextMessageInt())
  27494. break;
  27495. }
  27496. else
  27497. {
  27498. Thread::sleep (2);
  27499. }
  27500. }
  27501. else if (pipe != 0)
  27502. {
  27503. if (! pipe->isOpen())
  27504. {
  27505. {
  27506. const ScopedLock sl (pipeAndSocketLock);
  27507. deleteAndZero (pipe);
  27508. }
  27509. connectionLostInt();
  27510. break;
  27511. }
  27512. else
  27513. {
  27514. if (! readNextMessageInt())
  27515. break;
  27516. }
  27517. }
  27518. else
  27519. {
  27520. break;
  27521. }
  27522. }
  27523. }
  27524. END_JUCE_NAMESPACE
  27525. /********* End of inlined file: juce_InterprocessConnection.cpp *********/
  27526. /********* Start of inlined file: juce_InterprocessConnectionServer.cpp *********/
  27527. BEGIN_JUCE_NAMESPACE
  27528. InterprocessConnectionServer::InterprocessConnectionServer()
  27529. : Thread ("Juce IPC server"),
  27530. socket (0)
  27531. {
  27532. }
  27533. InterprocessConnectionServer::~InterprocessConnectionServer()
  27534. {
  27535. stop();
  27536. }
  27537. bool InterprocessConnectionServer::beginWaitingForSocket (const int portNumber)
  27538. {
  27539. stop();
  27540. socket = new StreamingSocket();
  27541. if (socket->createListener (portNumber))
  27542. {
  27543. startThread();
  27544. return true;
  27545. }
  27546. deleteAndZero (socket);
  27547. return false;
  27548. }
  27549. void InterprocessConnectionServer::stop()
  27550. {
  27551. signalThreadShouldExit();
  27552. if (socket != 0)
  27553. socket->close();
  27554. stopThread (4000);
  27555. deleteAndZero (socket);
  27556. }
  27557. void InterprocessConnectionServer::run()
  27558. {
  27559. while ((! threadShouldExit()) && socket != 0)
  27560. {
  27561. StreamingSocket* const clientSocket = socket->waitForNextConnection();
  27562. if (clientSocket != 0)
  27563. {
  27564. InterprocessConnection* newConnection = createConnectionObject();
  27565. if (newConnection != 0)
  27566. {
  27567. newConnection->initialiseWithSocket (clientSocket);
  27568. }
  27569. else
  27570. {
  27571. delete clientSocket;
  27572. }
  27573. }
  27574. }
  27575. }
  27576. END_JUCE_NAMESPACE
  27577. /********* End of inlined file: juce_InterprocessConnectionServer.cpp *********/
  27578. /********* Start of inlined file: juce_Message.cpp *********/
  27579. BEGIN_JUCE_NAMESPACE
  27580. Message::Message() throw()
  27581. {
  27582. }
  27583. Message::~Message() throw()
  27584. {
  27585. }
  27586. Message::Message (const int intParameter1_,
  27587. const int intParameter2_,
  27588. const int intParameter3_,
  27589. void* const pointerParameter_) throw()
  27590. : intParameter1 (intParameter1_),
  27591. intParameter2 (intParameter2_),
  27592. intParameter3 (intParameter3_),
  27593. pointerParameter (pointerParameter_)
  27594. {
  27595. }
  27596. END_JUCE_NAMESPACE
  27597. /********* End of inlined file: juce_Message.cpp *********/
  27598. /********* Start of inlined file: juce_MessageListener.cpp *********/
  27599. BEGIN_JUCE_NAMESPACE
  27600. MessageListener::MessageListener() throw()
  27601. {
  27602. // are you trying to create a messagelistener before or after juce has been intialised??
  27603. jassert (MessageManager::instance != 0);
  27604. if (MessageManager::instance != 0)
  27605. MessageManager::instance->messageListeners.add (this);
  27606. }
  27607. MessageListener::~MessageListener()
  27608. {
  27609. if (MessageManager::instance != 0)
  27610. MessageManager::instance->messageListeners.removeValue (this);
  27611. }
  27612. void MessageListener::postMessage (Message* const message) const throw()
  27613. {
  27614. message->messageRecipient = const_cast <MessageListener*> (this);
  27615. if (MessageManager::instance == 0)
  27616. MessageManager::getInstance();
  27617. MessageManager::instance->postMessageToQueue (message);
  27618. }
  27619. bool MessageListener::isValidMessageListener() const throw()
  27620. {
  27621. return (MessageManager::instance != 0)
  27622. && MessageManager::instance->messageListeners.contains (this);
  27623. }
  27624. END_JUCE_NAMESPACE
  27625. /********* End of inlined file: juce_MessageListener.cpp *********/
  27626. /********* Start of inlined file: juce_MessageManager.cpp *********/
  27627. BEGIN_JUCE_NAMESPACE
  27628. // platform-specific functions..
  27629. bool juce_dispatchNextMessageOnSystemQueue (bool returnIfNoPendingMessages);
  27630. bool juce_postMessageToSystemQueue (void* message);
  27631. MessageManager* MessageManager::instance = 0;
  27632. static const int quitMessageId = 0xfffff321;
  27633. MessageManager::MessageManager() throw()
  27634. : broadcastListeners (0),
  27635. quitMessagePosted (false),
  27636. quitMessageReceived (false),
  27637. useMaximumForceWhenQuitting (true),
  27638. messageCounter (0),
  27639. lastMessageCounter (-1),
  27640. isInMessageDispatcher (0),
  27641. needToGetRidOfWaitCursor (false),
  27642. timeBeforeWaitCursor (0),
  27643. lastActivityCheckOkTime (0)
  27644. {
  27645. currentLockingThreadId = messageThreadId = Thread::getCurrentThreadId();
  27646. }
  27647. MessageManager::~MessageManager() throw()
  27648. {
  27649. jassert (instance == this);
  27650. instance = 0;
  27651. deleteAndZero (broadcastListeners);
  27652. doPlatformSpecificShutdown();
  27653. }
  27654. MessageManager* MessageManager::getInstance() throw()
  27655. {
  27656. if (instance == 0)
  27657. {
  27658. instance = new MessageManager();
  27659. doPlatformSpecificInitialisation();
  27660. instance->setTimeBeforeShowingWaitCursor (500);
  27661. }
  27662. return instance;
  27663. }
  27664. void MessageManager::postMessageToQueue (Message* const message)
  27665. {
  27666. if (quitMessagePosted || ! juce_postMessageToSystemQueue (message))
  27667. delete message;
  27668. }
  27669. // not for public use..
  27670. void MessageManager::deliverMessage (void* message)
  27671. {
  27672. const MessageManagerLock lock;
  27673. Message* const m = (Message*) message;
  27674. MessageListener* const recipient = m->messageRecipient;
  27675. if (messageListeners.contains (recipient))
  27676. {
  27677. JUCE_TRY
  27678. {
  27679. recipient->handleMessage (*m);
  27680. }
  27681. JUCE_CATCH_EXCEPTION
  27682. if (needToGetRidOfWaitCursor)
  27683. {
  27684. needToGetRidOfWaitCursor = false;
  27685. MouseCursor::hideWaitCursor();
  27686. }
  27687. ++messageCounter;
  27688. }
  27689. else if (recipient == 0 && m->intParameter1 == quitMessageId)
  27690. {
  27691. quitMessageReceived = true;
  27692. useMaximumForceWhenQuitting = (m->intParameter2 != 0);
  27693. }
  27694. delete m;
  27695. }
  27696. bool MessageManager::dispatchNextMessage (const bool returnImmediatelyIfNoMessages,
  27697. bool* const wasAMessageDispatched)
  27698. {
  27699. if (quitMessageReceived)
  27700. {
  27701. if (wasAMessageDispatched != 0)
  27702. *wasAMessageDispatched = false;
  27703. return false;
  27704. }
  27705. ++isInMessageDispatcher;
  27706. bool result = false;
  27707. JUCE_TRY
  27708. {
  27709. result = juce_dispatchNextMessageOnSystemQueue (returnImmediatelyIfNoMessages);
  27710. if (wasAMessageDispatched != 0)
  27711. *wasAMessageDispatched = result;
  27712. if (instance == 0)
  27713. return false;
  27714. }
  27715. JUCE_CATCH_EXCEPTION
  27716. --isInMessageDispatcher;
  27717. ++messageCounter;
  27718. return result || ! returnImmediatelyIfNoMessages;
  27719. }
  27720. void MessageManager::dispatchPendingMessages (int maxNumberOfMessagesToDispatch)
  27721. {
  27722. jassert (isThisTheMessageThread()); // must only be called by the message thread
  27723. while (--maxNumberOfMessagesToDispatch >= 0 && ! quitMessageReceived)
  27724. {
  27725. ++isInMessageDispatcher;
  27726. bool carryOn = false;
  27727. JUCE_TRY
  27728. {
  27729. carryOn = juce_dispatchNextMessageOnSystemQueue (true);
  27730. }
  27731. JUCE_CATCH_EXCEPTION
  27732. --isInMessageDispatcher;
  27733. ++messageCounter;
  27734. if (! carryOn)
  27735. break;
  27736. }
  27737. }
  27738. bool MessageManager::runDispatchLoop()
  27739. {
  27740. jassert (isThisTheMessageThread()); // must only be called by the message thread
  27741. while (dispatchNextMessage())
  27742. {
  27743. }
  27744. return useMaximumForceWhenQuitting;
  27745. }
  27746. void MessageManager::postQuitMessage (const bool useMaximumForce)
  27747. {
  27748. Message* const m = new Message (quitMessageId, (useMaximumForce) ? 1 : 0, 0, 0);
  27749. m->messageRecipient = 0;
  27750. postMessageToQueue (m);
  27751. quitMessagePosted = true;
  27752. }
  27753. bool MessageManager::hasQuitMessageBeenPosted() const throw()
  27754. {
  27755. return quitMessagePosted;
  27756. }
  27757. void MessageManager::deliverBroadcastMessage (const String& value)
  27758. {
  27759. if (broadcastListeners != 0)
  27760. broadcastListeners->sendActionMessage (value);
  27761. }
  27762. void MessageManager::registerBroadcastListener (ActionListener* const listener) throw()
  27763. {
  27764. if (broadcastListeners == 0)
  27765. broadcastListeners = new ActionListenerList();
  27766. broadcastListeners->addActionListener (listener);
  27767. }
  27768. void MessageManager::deregisterBroadcastListener (ActionListener* const listener) throw()
  27769. {
  27770. if (broadcastListeners != 0)
  27771. broadcastListeners->removeActionListener (listener);
  27772. }
  27773. // This gets called occasionally by the timer thread (to save using an extra thread
  27774. // for it).
  27775. void MessageManager::inactivityCheckCallback() throw()
  27776. {
  27777. if (instance != 0)
  27778. instance->inactivityCheckCallbackInt();
  27779. }
  27780. void MessageManager::inactivityCheckCallbackInt() throw()
  27781. {
  27782. const unsigned int now = Time::getApproximateMillisecondCounter();
  27783. if (isInMessageDispatcher > 0
  27784. && lastMessageCounter == messageCounter
  27785. && timeBeforeWaitCursor > 0
  27786. && lastActivityCheckOkTime > 0
  27787. && ! ModifierKeys::getCurrentModifiersRealtime().isAnyMouseButtonDown())
  27788. {
  27789. if (now >= lastActivityCheckOkTime + timeBeforeWaitCursor
  27790. && ! needToGetRidOfWaitCursor)
  27791. {
  27792. // been in the same message call too long..
  27793. MouseCursor::showWaitCursor();
  27794. needToGetRidOfWaitCursor = true;
  27795. }
  27796. }
  27797. else
  27798. {
  27799. lastActivityCheckOkTime = now;
  27800. lastMessageCounter = messageCounter;
  27801. }
  27802. }
  27803. void MessageManager::delayWaitCursor() throw()
  27804. {
  27805. if (instance != 0)
  27806. {
  27807. instance->messageCounter++;
  27808. if (instance->needToGetRidOfWaitCursor)
  27809. {
  27810. instance->needToGetRidOfWaitCursor = false;
  27811. MouseCursor::hideWaitCursor();
  27812. }
  27813. }
  27814. }
  27815. void MessageManager::setTimeBeforeShowingWaitCursor (const int millisecs) throw()
  27816. {
  27817. // if this is a bit too small you'll get a lot of unwanted hourglass cursors..
  27818. jassert (millisecs <= 0 || millisecs > 200);
  27819. timeBeforeWaitCursor = millisecs;
  27820. if (millisecs > 0)
  27821. startTimer (millisecs / 2); // (see timerCallback() for explanation of this)
  27822. else
  27823. stopTimer();
  27824. }
  27825. void MessageManager::timerCallback()
  27826. {
  27827. // dummy callback - the message manager is just a Timer to ensure that there are always
  27828. // some events coming in - otherwise it'll show the egg-timer/beachball-of-death.
  27829. ++messageCounter;
  27830. }
  27831. int MessageManager::getTimeBeforeShowingWaitCursor() const throw()
  27832. {
  27833. return timeBeforeWaitCursor;
  27834. }
  27835. bool MessageManager::isThisTheMessageThread() const throw()
  27836. {
  27837. return Thread::getCurrentThreadId() == messageThreadId;
  27838. }
  27839. void MessageManager::setCurrentMessageThread (const int threadId) throw()
  27840. {
  27841. messageThreadId = threadId;
  27842. }
  27843. bool MessageManager::currentThreadHasLockedMessageManager() const throw()
  27844. {
  27845. return Thread::getCurrentThreadId() == currentLockingThreadId;
  27846. }
  27847. MessageManagerLock::MessageManagerLock() throw()
  27848. : locked (false)
  27849. {
  27850. if (MessageManager::instance != 0)
  27851. {
  27852. MessageManager::instance->messageDispatchLock.enter();
  27853. lastLockingThreadId = MessageManager::instance->currentLockingThreadId;
  27854. MessageManager::instance->currentLockingThreadId = Thread::getCurrentThreadId();
  27855. locked = true;
  27856. }
  27857. }
  27858. MessageManagerLock::MessageManagerLock (Thread* const thread) throw()
  27859. : locked (false)
  27860. {
  27861. jassert (thread != 0); // This will only work if you give it a valid thread!
  27862. if (MessageManager::instance != 0)
  27863. {
  27864. for (;;)
  27865. {
  27866. if (MessageManager::instance->messageDispatchLock.tryEnter())
  27867. {
  27868. locked = true;
  27869. lastLockingThreadId = MessageManager::instance->currentLockingThreadId;
  27870. MessageManager::instance->currentLockingThreadId = Thread::getCurrentThreadId();
  27871. break;
  27872. }
  27873. if (thread != 0 && thread->threadShouldExit())
  27874. break;
  27875. Thread::sleep (1);
  27876. }
  27877. }
  27878. }
  27879. MessageManagerLock::~MessageManagerLock() throw()
  27880. {
  27881. if (locked && MessageManager::instance != 0)
  27882. {
  27883. MessageManager::instance->currentLockingThreadId = lastLockingThreadId;
  27884. MessageManager::instance->messageDispatchLock.exit();
  27885. }
  27886. }
  27887. END_JUCE_NAMESPACE
  27888. /********* End of inlined file: juce_MessageManager.cpp *********/
  27889. /********* Start of inlined file: juce_MultiTimer.cpp *********/
  27890. BEGIN_JUCE_NAMESPACE
  27891. class InternalMultiTimerCallback : public Timer
  27892. {
  27893. public:
  27894. InternalMultiTimerCallback (const int timerId_, MultiTimer& owner_)
  27895. : timerId (timerId_),
  27896. owner (owner_)
  27897. {
  27898. }
  27899. ~InternalMultiTimerCallback()
  27900. {
  27901. }
  27902. void timerCallback()
  27903. {
  27904. owner.timerCallback (timerId);
  27905. }
  27906. const int timerId;
  27907. private:
  27908. MultiTimer& owner;
  27909. };
  27910. MultiTimer::MultiTimer() throw()
  27911. {
  27912. }
  27913. MultiTimer::MultiTimer (const MultiTimer&) throw()
  27914. {
  27915. }
  27916. MultiTimer::~MultiTimer()
  27917. {
  27918. const ScopedLock sl (timerListLock);
  27919. for (int i = timers.size(); --i >= 0;)
  27920. delete (InternalMultiTimerCallback*) timers.getUnchecked(i);
  27921. timers.clear();
  27922. }
  27923. void MultiTimer::startTimer (const int timerId, const int intervalInMilliseconds) throw()
  27924. {
  27925. const ScopedLock sl (timerListLock);
  27926. for (int i = timers.size(); --i >= 0;)
  27927. {
  27928. InternalMultiTimerCallback* const t = (InternalMultiTimerCallback*) timers.getUnchecked(i);
  27929. if (t->timerId == timerId)
  27930. {
  27931. t->startTimer (intervalInMilliseconds);
  27932. return;
  27933. }
  27934. }
  27935. InternalMultiTimerCallback* const newTimer = new InternalMultiTimerCallback (timerId, *this);
  27936. timers.add (newTimer);
  27937. newTimer->startTimer (intervalInMilliseconds);
  27938. }
  27939. void MultiTimer::stopTimer (const int timerId) throw()
  27940. {
  27941. const ScopedLock sl (timerListLock);
  27942. for (int i = timers.size(); --i >= 0;)
  27943. {
  27944. InternalMultiTimerCallback* const t = (InternalMultiTimerCallback*) timers.getUnchecked(i);
  27945. if (t->timerId == timerId)
  27946. t->stopTimer();
  27947. }
  27948. }
  27949. bool MultiTimer::isTimerRunning (const int timerId) const throw()
  27950. {
  27951. const ScopedLock sl (timerListLock);
  27952. for (int i = timers.size(); --i >= 0;)
  27953. {
  27954. const InternalMultiTimerCallback* const t = (InternalMultiTimerCallback*) timers.getUnchecked(i);
  27955. if (t->timerId == timerId)
  27956. return t->isTimerRunning();
  27957. }
  27958. return false;
  27959. }
  27960. int MultiTimer::getTimerInterval (const int timerId) const throw()
  27961. {
  27962. const ScopedLock sl (timerListLock);
  27963. for (int i = timers.size(); --i >= 0;)
  27964. {
  27965. const InternalMultiTimerCallback* const t = (InternalMultiTimerCallback*) timers.getUnchecked(i);
  27966. if (t->timerId == timerId)
  27967. return t->getTimerInterval();
  27968. }
  27969. return 0;
  27970. }
  27971. END_JUCE_NAMESPACE
  27972. /********* End of inlined file: juce_MultiTimer.cpp *********/
  27973. /********* Start of inlined file: juce_Timer.cpp *********/
  27974. BEGIN_JUCE_NAMESPACE
  27975. class InternalTimerThread : private Thread,
  27976. private MessageListener,
  27977. private DeletedAtShutdown,
  27978. private AsyncUpdater
  27979. {
  27980. private:
  27981. friend class Timer;
  27982. static InternalTimerThread* instance;
  27983. static CriticalSection lock;
  27984. Timer* volatile firstTimer;
  27985. bool volatile callbackNeeded;
  27986. InternalTimerThread (const InternalTimerThread&);
  27987. const InternalTimerThread& operator= (const InternalTimerThread&);
  27988. void addTimer (Timer* const t) throw()
  27989. {
  27990. #ifdef JUCE_DEBUG
  27991. Timer* tt = firstTimer;
  27992. while (tt != 0)
  27993. {
  27994. // trying to add a timer that's already here - shouldn't get to this point,
  27995. // so if you get this assertion, let me know!
  27996. jassert (tt != t);
  27997. tt = tt->next;
  27998. }
  27999. jassert (t->previous == 0 && t->next == 0);
  28000. #endif
  28001. Timer* i = firstTimer;
  28002. if (i == 0 || i->countdownMs > t->countdownMs)
  28003. {
  28004. t->next = firstTimer;
  28005. firstTimer = t;
  28006. }
  28007. else
  28008. {
  28009. while (i->next != 0 && i->next->countdownMs <= t->countdownMs)
  28010. i = i->next;
  28011. jassert (i != 0);
  28012. t->next = i->next;
  28013. t->previous = i;
  28014. i->next = t;
  28015. }
  28016. if (t->next != 0)
  28017. t->next->previous = t;
  28018. jassert ((t->next == 0 || t->next->countdownMs >= t->countdownMs)
  28019. && (t->previous == 0 || t->previous->countdownMs <= t->countdownMs));
  28020. notify();
  28021. }
  28022. void removeTimer (Timer* const t) throw()
  28023. {
  28024. #ifdef JUCE_DEBUG
  28025. Timer* tt = firstTimer;
  28026. bool found = false;
  28027. while (tt != 0)
  28028. {
  28029. if (tt == t)
  28030. {
  28031. found = true;
  28032. break;
  28033. }
  28034. tt = tt->next;
  28035. }
  28036. // trying to remove a timer that's not here - shouldn't get to this point,
  28037. // so if you get this assertion, let me know!
  28038. jassert (found);
  28039. #endif
  28040. if (t->previous != 0)
  28041. {
  28042. jassert (firstTimer != t);
  28043. t->previous->next = t->next;
  28044. }
  28045. else
  28046. {
  28047. jassert (firstTimer == t);
  28048. firstTimer = t->next;
  28049. }
  28050. if (t->next != 0)
  28051. t->next->previous = t->previous;
  28052. t->next = 0;
  28053. t->previous = 0;
  28054. }
  28055. void decrementAllCounters (const int numMillisecs) const
  28056. {
  28057. Timer* t = firstTimer;
  28058. while (t != 0)
  28059. {
  28060. t->countdownMs -= numMillisecs;
  28061. t = t->next;
  28062. }
  28063. }
  28064. void handleAsyncUpdate()
  28065. {
  28066. startThread (7);
  28067. }
  28068. public:
  28069. InternalTimerThread()
  28070. : Thread ("Juce Timer"),
  28071. firstTimer (0),
  28072. callbackNeeded (false)
  28073. {
  28074. triggerAsyncUpdate();
  28075. }
  28076. ~InternalTimerThread() throw()
  28077. {
  28078. stopThread (4000);
  28079. jassert (instance == this || instance == 0);
  28080. if (instance == this)
  28081. instance = 0;
  28082. }
  28083. void run()
  28084. {
  28085. uint32 lastTime = Time::getMillisecondCounter();
  28086. uint32 lastMessageManagerCallback = lastTime;
  28087. while (! threadShouldExit())
  28088. {
  28089. uint32 now = Time::getMillisecondCounter();
  28090. if (now <= lastTime)
  28091. {
  28092. wait (2);
  28093. continue;
  28094. }
  28095. const int elapsed = now - lastTime;
  28096. lastTime = now;
  28097. lock.enter();
  28098. decrementAllCounters (elapsed);
  28099. const int timeUntilFirstTimer = (firstTimer != 0) ? firstTimer->countdownMs
  28100. : 1000;
  28101. lock.exit();
  28102. if (timeUntilFirstTimer <= 0)
  28103. {
  28104. callbackNeeded = true;
  28105. postMessage (new Message());
  28106. // sometimes, our message could get discarded by the OS (particularly when running as an RTAS when the app has a modal loop),
  28107. // so this is how long to wait before assuming the message has been lost and trying again.
  28108. const uint32 messageDeliveryTimeout = now + 2000;
  28109. while (callbackNeeded)
  28110. {
  28111. wait (4);
  28112. if (threadShouldExit())
  28113. return;
  28114. now = Time::getMillisecondCounter();
  28115. if (now > lastMessageManagerCallback + 200)
  28116. {
  28117. lastMessageManagerCallback = now;
  28118. MessageManager::inactivityCheckCallback();
  28119. }
  28120. if (now > messageDeliveryTimeout)
  28121. break;
  28122. }
  28123. }
  28124. else
  28125. {
  28126. // don't wait for too long because running this loop also helps keep the
  28127. // Time::getApproximateMillisecondTimer value stay up-to-date
  28128. wait (jlimit (1, 50, timeUntilFirstTimer));
  28129. }
  28130. if (now > lastMessageManagerCallback + 200)
  28131. {
  28132. lastMessageManagerCallback = now;
  28133. MessageManager::inactivityCheckCallback();
  28134. }
  28135. }
  28136. }
  28137. void handleMessage (const Message&)
  28138. {
  28139. const ScopedLock sl (lock);
  28140. while (firstTimer != 0 && firstTimer->countdownMs <= 0)
  28141. {
  28142. Timer* const t = firstTimer;
  28143. t->countdownMs = t->periodMs;
  28144. removeTimer (t);
  28145. addTimer (t);
  28146. const ScopedUnlock ul (lock);
  28147. callbackNeeded = false;
  28148. JUCE_TRY
  28149. {
  28150. t->timerCallback();
  28151. }
  28152. JUCE_CATCH_EXCEPTION
  28153. }
  28154. callbackNeeded = false;
  28155. }
  28156. static void callAnyTimersSynchronously()
  28157. {
  28158. if (InternalTimerThread::instance != 0)
  28159. {
  28160. const Message m;
  28161. InternalTimerThread::instance->handleMessage (m);
  28162. }
  28163. }
  28164. static inline void add (Timer* const tim) throw()
  28165. {
  28166. if (instance == 0)
  28167. instance = new InternalTimerThread();
  28168. instance->addTimer (tim);
  28169. }
  28170. static inline void remove (Timer* const tim) throw()
  28171. {
  28172. if (instance != 0)
  28173. instance->removeTimer (tim);
  28174. }
  28175. static inline void resetCounter (Timer* const tim,
  28176. const int newCounter) throw()
  28177. {
  28178. if (instance != 0)
  28179. {
  28180. tim->countdownMs = newCounter;
  28181. tim->periodMs = newCounter;
  28182. if ((tim->next != 0 && tim->next->countdownMs < tim->countdownMs)
  28183. || (tim->previous != 0 && tim->previous->countdownMs > tim->countdownMs))
  28184. {
  28185. instance->removeTimer (tim);
  28186. instance->addTimer (tim);
  28187. }
  28188. }
  28189. }
  28190. };
  28191. InternalTimerThread* InternalTimerThread::instance = 0;
  28192. CriticalSection InternalTimerThread::lock;
  28193. void juce_callAnyTimersSynchronously()
  28194. {
  28195. InternalTimerThread::callAnyTimersSynchronously();
  28196. }
  28197. #ifdef JUCE_DEBUG
  28198. static SortedSet <Timer*> activeTimers;
  28199. #endif
  28200. Timer::Timer() throw()
  28201. : countdownMs (0),
  28202. periodMs (0),
  28203. previous (0),
  28204. next (0)
  28205. {
  28206. #ifdef JUCE_DEBUG
  28207. activeTimers.add (this);
  28208. #endif
  28209. }
  28210. Timer::Timer (const Timer&) throw()
  28211. : countdownMs (0),
  28212. periodMs (0),
  28213. previous (0),
  28214. next (0)
  28215. {
  28216. #ifdef JUCE_DEBUG
  28217. activeTimers.add (this);
  28218. #endif
  28219. }
  28220. Timer::~Timer()
  28221. {
  28222. stopTimer();
  28223. #ifdef JUCE_DEBUG
  28224. activeTimers.removeValue (this);
  28225. #endif
  28226. }
  28227. void Timer::startTimer (const int interval) throw()
  28228. {
  28229. const ScopedLock sl (InternalTimerThread::lock);
  28230. #ifdef JUCE_DEBUG
  28231. // this isn't a valid object! Your timer might be a dangling pointer or something..
  28232. jassert (activeTimers.contains (this));
  28233. #endif
  28234. if (periodMs == 0)
  28235. {
  28236. countdownMs = interval;
  28237. periodMs = jmax (1, interval);
  28238. InternalTimerThread::add (this);
  28239. }
  28240. else
  28241. {
  28242. InternalTimerThread::resetCounter (this, interval);
  28243. }
  28244. }
  28245. void Timer::stopTimer() throw()
  28246. {
  28247. const ScopedLock sl (InternalTimerThread::lock);
  28248. #ifdef JUCE_DEBUG
  28249. // this isn't a valid object! Your timer might be a dangling pointer or something..
  28250. jassert (activeTimers.contains (this));
  28251. #endif
  28252. if (periodMs > 0)
  28253. {
  28254. InternalTimerThread::remove (this);
  28255. periodMs = 0;
  28256. }
  28257. }
  28258. END_JUCE_NAMESPACE
  28259. /********* End of inlined file: juce_Timer.cpp *********/
  28260. /********* Start of inlined file: juce_Component.cpp *********/
  28261. BEGIN_JUCE_NAMESPACE
  28262. Component* Component::componentUnderMouse = 0;
  28263. Component* Component::currentlyFocusedComponent = 0;
  28264. static Array <Component*> modalComponentStack (4), modalComponentReturnValueKeys (4);
  28265. static Array <int> modalReturnValues (4);
  28266. static const int customCommandMessage = 0x7fff0001;
  28267. static const int exitModalStateMessage = 0x7fff0002;
  28268. // these are also used by ComponentPeer
  28269. int64 juce_recentMouseDownTimes [4] = { 0, 0, 0, 0 };
  28270. int juce_recentMouseDownX [4] = { 0, 0, 0, 0 };
  28271. int juce_recentMouseDownY [4] = { 0, 0, 0, 0 };
  28272. Component* juce_recentMouseDownComponent [4] = { 0, 0, 0, 0 };
  28273. int juce_LastMousePosX = 0;
  28274. int juce_LastMousePosY = 0;
  28275. int juce_MouseClickCounter = 0;
  28276. bool juce_MouseHasMovedSignificantlySincePressed = false;
  28277. static int countMouseClicks() throw()
  28278. {
  28279. int numClicks = 0;
  28280. if (juce_recentMouseDownTimes[0] != 0)
  28281. {
  28282. if (! juce_MouseHasMovedSignificantlySincePressed)
  28283. ++numClicks;
  28284. for (int i = 1; i < numElementsInArray (juce_recentMouseDownTimes); ++i)
  28285. {
  28286. if (juce_recentMouseDownTimes[0] - juce_recentMouseDownTimes [i]
  28287. < (int) (MouseEvent::getDoubleClickTimeout() * (1.0 + 0.25 * (i - 1)))
  28288. && abs (juce_recentMouseDownX[0] - juce_recentMouseDownX[i]) < 8
  28289. && abs (juce_recentMouseDownY[0] - juce_recentMouseDownY[i]) < 8
  28290. && juce_recentMouseDownComponent[0] == juce_recentMouseDownComponent [i])
  28291. {
  28292. ++numClicks;
  28293. }
  28294. else
  28295. {
  28296. break;
  28297. }
  28298. }
  28299. }
  28300. return numClicks;
  28301. }
  28302. static int unboundedMouseOffsetX = 0;
  28303. static int unboundedMouseOffsetY = 0;
  28304. static bool isUnboundedMouseModeOn = false;
  28305. static bool isCursorVisibleUntilOffscreen;
  28306. #define checkMessageManagerIsLocked jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  28307. static uint32 nextComponentUID = 0;
  28308. Component::Component() throw()
  28309. : parentComponent_ (0),
  28310. componentUID (++nextComponentUID),
  28311. numDeepMouseListeners (0),
  28312. childComponentList_ (16),
  28313. lookAndFeel_ (0),
  28314. effect_ (0),
  28315. bufferedImage_ (0),
  28316. mouseListeners_ (0),
  28317. keyListeners_ (0),
  28318. componentListeners_ (0),
  28319. propertySet_ (0),
  28320. componentFlags_ (0)
  28321. {
  28322. }
  28323. Component::Component (const String& name) throw()
  28324. : componentName_ (name),
  28325. parentComponent_ (0),
  28326. componentUID (++nextComponentUID),
  28327. numDeepMouseListeners (0),
  28328. childComponentList_ (16),
  28329. lookAndFeel_ (0),
  28330. effect_ (0),
  28331. bufferedImage_ (0),
  28332. mouseListeners_ (0),
  28333. keyListeners_ (0),
  28334. componentListeners_ (0),
  28335. propertySet_ (0),
  28336. componentFlags_ (0)
  28337. {
  28338. }
  28339. Component::~Component()
  28340. {
  28341. if (parentComponent_ != 0)
  28342. {
  28343. parentComponent_->removeChildComponent (this);
  28344. }
  28345. else if ((currentlyFocusedComponent == this)
  28346. || isParentOf (currentlyFocusedComponent))
  28347. {
  28348. giveAwayFocus();
  28349. }
  28350. if (componentUnderMouse == this)
  28351. componentUnderMouse = 0;
  28352. if (flags.hasHeavyweightPeerFlag)
  28353. removeFromDesktop();
  28354. modalComponentStack.removeValue (this);
  28355. for (int i = childComponentList_.size(); --i >= 0;)
  28356. childComponentList_.getUnchecked(i)->parentComponent_ = 0;
  28357. delete bufferedImage_;
  28358. delete mouseListeners_;
  28359. delete keyListeners_;
  28360. delete componentListeners_;
  28361. delete propertySet_;
  28362. }
  28363. void Component::setName (const String& name)
  28364. {
  28365. // if component methods are being called from threads other than the message
  28366. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  28367. checkMessageManagerIsLocked
  28368. if (componentName_ != name)
  28369. {
  28370. componentName_ = name;
  28371. if (flags.hasHeavyweightPeerFlag)
  28372. {
  28373. ComponentPeer* const peer = getPeer();
  28374. jassert (peer != 0);
  28375. if (peer != 0)
  28376. peer->setTitle (name);
  28377. }
  28378. if (componentListeners_ != 0)
  28379. {
  28380. const ComponentDeletionWatcher deletionChecker (this);
  28381. for (int i = componentListeners_->size(); --i >= 0;)
  28382. {
  28383. ((ComponentListener*) componentListeners_->getUnchecked (i))
  28384. ->componentNameChanged (*this);
  28385. if (deletionChecker.hasBeenDeleted())
  28386. return;
  28387. i = jmin (i, componentListeners_->size());
  28388. }
  28389. }
  28390. }
  28391. }
  28392. void Component::setVisible (bool shouldBeVisible)
  28393. {
  28394. if (flags.visibleFlag != shouldBeVisible)
  28395. {
  28396. // if component methods are being called from threads other than the message
  28397. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  28398. checkMessageManagerIsLocked
  28399. const ComponentDeletionWatcher deletionChecker (this);
  28400. flags.visibleFlag = shouldBeVisible;
  28401. internalRepaint (0, 0, getWidth(), getHeight());
  28402. sendFakeMouseMove();
  28403. if (! shouldBeVisible)
  28404. {
  28405. if (currentlyFocusedComponent == this
  28406. || isParentOf (currentlyFocusedComponent))
  28407. {
  28408. if (parentComponent_ != 0)
  28409. parentComponent_->grabKeyboardFocus();
  28410. else
  28411. giveAwayFocus();
  28412. }
  28413. }
  28414. sendVisibilityChangeMessage();
  28415. if ((! deletionChecker.hasBeenDeleted()) && flags.hasHeavyweightPeerFlag)
  28416. {
  28417. ComponentPeer* const peer = getPeer();
  28418. jassert (peer != 0);
  28419. if (peer != 0)
  28420. {
  28421. peer->setVisible (shouldBeVisible);
  28422. internalHierarchyChanged();
  28423. }
  28424. }
  28425. }
  28426. }
  28427. void Component::visibilityChanged()
  28428. {
  28429. }
  28430. void Component::sendVisibilityChangeMessage()
  28431. {
  28432. const ComponentDeletionWatcher deletionChecker (this);
  28433. visibilityChanged();
  28434. if ((! deletionChecker.hasBeenDeleted()) && componentListeners_ != 0)
  28435. {
  28436. for (int i = componentListeners_->size(); --i >= 0;)
  28437. {
  28438. ((ComponentListener*) componentListeners_->getUnchecked (i))
  28439. ->componentVisibilityChanged (*this);
  28440. if (deletionChecker.hasBeenDeleted())
  28441. return;
  28442. i = jmin (i, componentListeners_->size());
  28443. }
  28444. }
  28445. }
  28446. bool Component::isShowing() const throw()
  28447. {
  28448. if (flags.visibleFlag)
  28449. {
  28450. if (parentComponent_ != 0)
  28451. {
  28452. return parentComponent_->isShowing();
  28453. }
  28454. else
  28455. {
  28456. const ComponentPeer* const peer = getPeer();
  28457. return peer != 0 && ! peer->isMinimised();
  28458. }
  28459. }
  28460. return false;
  28461. }
  28462. class FadeOutProxyComponent : public Component,
  28463. public Timer
  28464. {
  28465. public:
  28466. FadeOutProxyComponent (Component* comp,
  28467. const int fadeLengthMs,
  28468. const int deltaXToMove,
  28469. const int deltaYToMove,
  28470. const float scaleFactorAtEnd)
  28471. : lastTime (0),
  28472. alpha (1.0f),
  28473. scale (1.0f)
  28474. {
  28475. image = comp->createComponentSnapshot (Rectangle (0, 0, comp->getWidth(), comp->getHeight()));
  28476. setBounds (comp->getBounds());
  28477. comp->getParentComponent()->addAndMakeVisible (this);
  28478. toBehind (comp);
  28479. alphaChangePerMs = -1.0f / (float)fadeLengthMs;
  28480. centreX = comp->getX() + comp->getWidth() * 0.5f;
  28481. xChangePerMs = deltaXToMove / (float)fadeLengthMs;
  28482. centreY = comp->getY() + comp->getHeight() * 0.5f;
  28483. yChangePerMs = deltaYToMove / (float)fadeLengthMs;
  28484. scaleChangePerMs = (scaleFactorAtEnd - 1.0f) / (float)fadeLengthMs;
  28485. setInterceptsMouseClicks (false, false);
  28486. // 30 fps is enough for a fade, but we need a higher rate if it's moving as well..
  28487. startTimer (1000 / ((deltaXToMove == 0 && deltaYToMove == 0) ? 30 : 50));
  28488. }
  28489. ~FadeOutProxyComponent()
  28490. {
  28491. delete image;
  28492. }
  28493. void paint (Graphics& g)
  28494. {
  28495. g.setOpacity (alpha);
  28496. g.drawImage (image,
  28497. 0, 0, getWidth(), getHeight(),
  28498. 0, 0, image->getWidth(), image->getHeight());
  28499. }
  28500. void timerCallback()
  28501. {
  28502. const uint32 now = Time::getMillisecondCounter();
  28503. if (lastTime == 0)
  28504. lastTime = now;
  28505. const int msPassed = (now > lastTime) ? now - lastTime : 0;
  28506. lastTime = now;
  28507. alpha += alphaChangePerMs * msPassed;
  28508. if (alpha > 0)
  28509. {
  28510. if (xChangePerMs != 0.0f || yChangePerMs != 0.0f || scaleChangePerMs != 0.0f)
  28511. {
  28512. centreX += xChangePerMs * msPassed;
  28513. centreY += yChangePerMs * msPassed;
  28514. scale += scaleChangePerMs * msPassed;
  28515. const int w = roundFloatToInt (image->getWidth() * scale);
  28516. const int h = roundFloatToInt (image->getHeight() * scale);
  28517. setBounds (roundFloatToInt (centreX) - w / 2,
  28518. roundFloatToInt (centreY) - h / 2,
  28519. w, h);
  28520. }
  28521. repaint();
  28522. }
  28523. else
  28524. {
  28525. delete this;
  28526. }
  28527. }
  28528. juce_UseDebuggingNewOperator
  28529. private:
  28530. Image* image;
  28531. uint32 lastTime;
  28532. float alpha, alphaChangePerMs;
  28533. float centreX, xChangePerMs;
  28534. float centreY, yChangePerMs;
  28535. float scale, scaleChangePerMs;
  28536. FadeOutProxyComponent (const FadeOutProxyComponent&);
  28537. const FadeOutProxyComponent& operator= (const FadeOutProxyComponent&);
  28538. };
  28539. void Component::fadeOutComponent (const int millisecondsToFade,
  28540. const int deltaXToMove,
  28541. const int deltaYToMove,
  28542. const float scaleFactorAtEnd)
  28543. {
  28544. //xxx won't work for comps without parents
  28545. if (isShowing() && millisecondsToFade > 0)
  28546. new FadeOutProxyComponent (this, millisecondsToFade,
  28547. deltaXToMove, deltaYToMove, scaleFactorAtEnd);
  28548. setVisible (false);
  28549. }
  28550. bool Component::isValidComponent() const throw()
  28551. {
  28552. return (this != 0) && isValidMessageListener();
  28553. }
  28554. void* Component::getWindowHandle() const throw()
  28555. {
  28556. const ComponentPeer* const peer = getPeer();
  28557. if (peer != 0)
  28558. return peer->getNativeHandle();
  28559. return 0;
  28560. }
  28561. void Component::addToDesktop (int styleWanted, void* nativeWindowToAttachTo)
  28562. {
  28563. // if component methods are being called from threads other than the message
  28564. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  28565. checkMessageManagerIsLocked
  28566. if (! isOpaque())
  28567. styleWanted |= ComponentPeer::windowIsSemiTransparent;
  28568. int currentStyleFlags = 0;
  28569. // don't use getPeer(), so that we only get the peer that's specifically
  28570. // for this comp, and not for one of its parents.
  28571. ComponentPeer* peer = ComponentPeer::getPeerFor (this);
  28572. if (peer != 0)
  28573. currentStyleFlags = peer->getStyleFlags();
  28574. if (styleWanted != currentStyleFlags || ! flags.hasHeavyweightPeerFlag)
  28575. {
  28576. const ComponentDeletionWatcher deletionChecker (this);
  28577. #if JUCE_LINUX
  28578. // it's wise to give the component a non-zero size before
  28579. // putting it on the desktop, as X windows get confused by this, and
  28580. // a (1, 1) minimum size is enforced here.
  28581. setSize (jmax (1, getWidth()),
  28582. jmax (1, getHeight()));
  28583. #endif
  28584. int x = 0, y = 0;
  28585. relativePositionToGlobal (x, y);
  28586. bool wasFullscreen = false;
  28587. bool wasMinimised = false;
  28588. ComponentBoundsConstrainer* currentConstainer = 0;
  28589. Rectangle oldNonFullScreenBounds;
  28590. if (peer != 0)
  28591. {
  28592. wasFullscreen = peer->isFullScreen();
  28593. wasMinimised = peer->isMinimised();
  28594. currentConstainer = peer->getConstrainer();
  28595. oldNonFullScreenBounds = peer->getNonFullScreenBounds();
  28596. removeFromDesktop();
  28597. }
  28598. if (parentComponent_ != 0)
  28599. parentComponent_->removeChildComponent (this);
  28600. if (! deletionChecker.hasBeenDeleted())
  28601. {
  28602. flags.hasHeavyweightPeerFlag = true;
  28603. peer = createNewPeer (styleWanted, nativeWindowToAttachTo);
  28604. Desktop::getInstance().addDesktopComponent (this);
  28605. bounds_.setPosition (x, y);
  28606. peer->setBounds (x, y, getWidth(), getHeight(), false);
  28607. peer->setVisible (isVisible());
  28608. if (wasFullscreen)
  28609. {
  28610. peer->setFullScreen (true);
  28611. peer->setNonFullScreenBounds (oldNonFullScreenBounds);
  28612. }
  28613. if (wasMinimised)
  28614. peer->setMinimised (true);
  28615. if (isAlwaysOnTop())
  28616. peer->setAlwaysOnTop (true);
  28617. peer->setConstrainer (currentConstainer);
  28618. repaint();
  28619. }
  28620. internalHierarchyChanged();
  28621. }
  28622. }
  28623. void Component::removeFromDesktop()
  28624. {
  28625. // if component methods are being called from threads other than the message
  28626. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  28627. checkMessageManagerIsLocked
  28628. if (flags.hasHeavyweightPeerFlag)
  28629. {
  28630. ComponentPeer* const peer = ComponentPeer::getPeerFor (this);
  28631. flags.hasHeavyweightPeerFlag = false;
  28632. jassert (peer != 0);
  28633. delete peer;
  28634. Desktop::getInstance().removeDesktopComponent (this);
  28635. }
  28636. }
  28637. bool Component::isOnDesktop() const throw()
  28638. {
  28639. return flags.hasHeavyweightPeerFlag;
  28640. }
  28641. void Component::userTriedToCloseWindow()
  28642. {
  28643. /* This means that the user's trying to get rid of your window with the 'close window' system
  28644. menu option (on windows) or possibly the task manager - you should really handle this
  28645. and delete or hide your component in an appropriate way.
  28646. If you want to ignore the event and don't want to trigger this assertion, just override
  28647. this method and do nothing.
  28648. */
  28649. jassertfalse
  28650. }
  28651. void Component::minimisationStateChanged (bool)
  28652. {
  28653. }
  28654. void Component::setOpaque (const bool shouldBeOpaque) throw()
  28655. {
  28656. if (shouldBeOpaque != flags.opaqueFlag)
  28657. {
  28658. flags.opaqueFlag = shouldBeOpaque;
  28659. if (flags.hasHeavyweightPeerFlag)
  28660. {
  28661. const ComponentPeer* const peer = ComponentPeer::getPeerFor (this);
  28662. if (peer != 0)
  28663. {
  28664. // to make it recreate the heavyweight window
  28665. addToDesktop (peer->getStyleFlags());
  28666. }
  28667. }
  28668. repaint();
  28669. }
  28670. }
  28671. bool Component::isOpaque() const throw()
  28672. {
  28673. return flags.opaqueFlag;
  28674. }
  28675. void Component::setBufferedToImage (const bool shouldBeBuffered) throw()
  28676. {
  28677. if (shouldBeBuffered != flags.bufferToImageFlag)
  28678. {
  28679. deleteAndZero (bufferedImage_);
  28680. flags.bufferToImageFlag = shouldBeBuffered;
  28681. }
  28682. }
  28683. void Component::toFront (const bool setAsForeground)
  28684. {
  28685. // if component methods are being called from threads other than the message
  28686. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  28687. checkMessageManagerIsLocked
  28688. if (flags.hasHeavyweightPeerFlag)
  28689. {
  28690. ComponentPeer* const peer = getPeer();
  28691. if (peer != 0)
  28692. {
  28693. peer->toFront (setAsForeground);
  28694. if (setAsForeground && ! hasKeyboardFocus (true))
  28695. grabKeyboardFocus();
  28696. }
  28697. }
  28698. else if (parentComponent_ != 0)
  28699. {
  28700. if (parentComponent_->childComponentList_.getLast() != this)
  28701. {
  28702. const int index = parentComponent_->childComponentList_.indexOf (this);
  28703. if (index >= 0)
  28704. {
  28705. int insertIndex = -1;
  28706. if (! flags.alwaysOnTopFlag)
  28707. {
  28708. insertIndex = parentComponent_->childComponentList_.size() - 1;
  28709. while (insertIndex > 0
  28710. && parentComponent_->childComponentList_.getUnchecked (insertIndex)->isAlwaysOnTop())
  28711. {
  28712. --insertIndex;
  28713. }
  28714. }
  28715. if (index != insertIndex)
  28716. {
  28717. parentComponent_->childComponentList_.move (index, insertIndex);
  28718. sendFakeMouseMove();
  28719. repaintParent();
  28720. }
  28721. }
  28722. }
  28723. if (setAsForeground)
  28724. {
  28725. internalBroughtToFront();
  28726. grabKeyboardFocus();
  28727. }
  28728. }
  28729. }
  28730. void Component::toBehind (Component* const other)
  28731. {
  28732. if (other != 0)
  28733. {
  28734. // the two components must belong to the same parent..
  28735. jassert (parentComponent_ == other->parentComponent_);
  28736. if (parentComponent_ != 0)
  28737. {
  28738. const int index = parentComponent_->childComponentList_.indexOf (this);
  28739. int otherIndex = parentComponent_->childComponentList_.indexOf (other);
  28740. if (index >= 0
  28741. && otherIndex >= 0
  28742. && index != otherIndex - 1
  28743. && other != this)
  28744. {
  28745. if (index < otherIndex)
  28746. --otherIndex;
  28747. parentComponent_->childComponentList_.move (index, otherIndex);
  28748. sendFakeMouseMove();
  28749. repaintParent();
  28750. }
  28751. }
  28752. else if (isOnDesktop())
  28753. {
  28754. jassert (other->isOnDesktop());
  28755. if (other->isOnDesktop())
  28756. {
  28757. ComponentPeer* const us = getPeer();
  28758. ComponentPeer* const them = other->getPeer();
  28759. jassert (us != 0 && them != 0);
  28760. if (us != 0 && them != 0)
  28761. us->toBehind (them);
  28762. }
  28763. }
  28764. }
  28765. }
  28766. void Component::toBack()
  28767. {
  28768. if (isOnDesktop())
  28769. {
  28770. jassertfalse //xxx need to add this to native window
  28771. }
  28772. else if (parentComponent_ != 0
  28773. && parentComponent_->childComponentList_.getFirst() != this)
  28774. {
  28775. const int index = parentComponent_->childComponentList_.indexOf (this);
  28776. if (index > 0)
  28777. {
  28778. int insertIndex = 0;
  28779. if (flags.alwaysOnTopFlag)
  28780. {
  28781. while (insertIndex < parentComponent_->childComponentList_.size()
  28782. && ! parentComponent_->childComponentList_.getUnchecked (insertIndex)->isAlwaysOnTop())
  28783. {
  28784. ++insertIndex;
  28785. }
  28786. }
  28787. if (index != insertIndex)
  28788. {
  28789. parentComponent_->childComponentList_.move (index, insertIndex);
  28790. sendFakeMouseMove();
  28791. repaintParent();
  28792. }
  28793. }
  28794. }
  28795. }
  28796. void Component::setAlwaysOnTop (const bool shouldStayOnTop)
  28797. {
  28798. if (shouldStayOnTop != flags.alwaysOnTopFlag)
  28799. {
  28800. flags.alwaysOnTopFlag = shouldStayOnTop;
  28801. if (isOnDesktop())
  28802. {
  28803. ComponentPeer* const peer = getPeer();
  28804. jassert (peer != 0);
  28805. if (peer != 0)
  28806. {
  28807. if (! peer->setAlwaysOnTop (shouldStayOnTop))
  28808. {
  28809. // some kinds of peer can't change their always-on-top status, so
  28810. // for these, we'll need to create a new window
  28811. const int oldFlags = peer->getStyleFlags();
  28812. removeFromDesktop();
  28813. addToDesktop (oldFlags);
  28814. }
  28815. }
  28816. }
  28817. if (shouldStayOnTop)
  28818. toFront (false);
  28819. internalHierarchyChanged();
  28820. }
  28821. }
  28822. bool Component::isAlwaysOnTop() const throw()
  28823. {
  28824. return flags.alwaysOnTopFlag;
  28825. }
  28826. int Component::proportionOfWidth (const float proportion) const throw()
  28827. {
  28828. return roundDoubleToInt (proportion * bounds_.getWidth());
  28829. }
  28830. int Component::proportionOfHeight (const float proportion) const throw()
  28831. {
  28832. return roundDoubleToInt (proportion * bounds_.getHeight());
  28833. }
  28834. int Component::getParentWidth() const throw()
  28835. {
  28836. return (parentComponent_ != 0) ? parentComponent_->getWidth()
  28837. : getParentMonitorArea().getWidth();
  28838. }
  28839. int Component::getParentHeight() const throw()
  28840. {
  28841. return (parentComponent_ != 0) ? parentComponent_->getHeight()
  28842. : getParentMonitorArea().getHeight();
  28843. }
  28844. int Component::getScreenX() const throw()
  28845. {
  28846. return (parentComponent_ != 0) ? parentComponent_->getScreenX() + getX()
  28847. : (flags.hasHeavyweightPeerFlag ? getPeer()->getScreenX()
  28848. : getX());
  28849. }
  28850. int Component::getScreenY() const throw()
  28851. {
  28852. return (parentComponent_ != 0) ? parentComponent_->getScreenY() + getY()
  28853. : (flags.hasHeavyweightPeerFlag ? getPeer()->getScreenY()
  28854. : getY());
  28855. }
  28856. void Component::relativePositionToGlobal (int& x, int& y) const throw()
  28857. {
  28858. const Component* c = this;
  28859. do
  28860. {
  28861. if (c->flags.hasHeavyweightPeerFlag)
  28862. {
  28863. c->getPeer()->relativePositionToGlobal (x, y);
  28864. break;
  28865. }
  28866. x += c->getX();
  28867. y += c->getY();
  28868. c = c->parentComponent_;
  28869. }
  28870. while (c != 0);
  28871. }
  28872. void Component::globalPositionToRelative (int& x, int& y) const throw()
  28873. {
  28874. if (flags.hasHeavyweightPeerFlag)
  28875. {
  28876. getPeer()->globalPositionToRelative (x, y);
  28877. }
  28878. else
  28879. {
  28880. if (parentComponent_ != 0)
  28881. parentComponent_->globalPositionToRelative (x, y);
  28882. x -= getX();
  28883. y -= getY();
  28884. }
  28885. }
  28886. void Component::relativePositionToOtherComponent (const Component* const targetComponent, int& x, int& y) const throw()
  28887. {
  28888. if (targetComponent != 0)
  28889. {
  28890. const Component* c = this;
  28891. do
  28892. {
  28893. if (c == targetComponent)
  28894. return;
  28895. if (c->flags.hasHeavyweightPeerFlag)
  28896. {
  28897. c->getPeer()->relativePositionToGlobal (x, y);
  28898. break;
  28899. }
  28900. x += c->getX();
  28901. y += c->getY();
  28902. c = c->parentComponent_;
  28903. }
  28904. while (c != 0);
  28905. targetComponent->globalPositionToRelative (x, y);
  28906. }
  28907. }
  28908. void Component::setBounds (int x, int y, int w, int h)
  28909. {
  28910. // if component methods are being called from threads other than the message
  28911. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  28912. checkMessageManagerIsLocked
  28913. if (w < 0) w = 0;
  28914. if (h < 0) h = 0;
  28915. const bool wasResized = (getWidth() != w || getHeight() != h);
  28916. const bool wasMoved = (getX() != x || getY() != y);
  28917. #ifdef JUCE_DEBUG
  28918. // It's a very bad idea to try to resize a window during its paint() method!
  28919. jassert (! (flags.isInsidePaintCall && wasResized && isOnDesktop()));
  28920. #endif
  28921. if (wasMoved || wasResized)
  28922. {
  28923. if (flags.visibleFlag)
  28924. {
  28925. // send a fake mouse move to trigger enter/exit messages if needed..
  28926. sendFakeMouseMove();
  28927. if (! flags.hasHeavyweightPeerFlag)
  28928. repaintParent();
  28929. }
  28930. bounds_.setBounds (x, y, w, h);
  28931. if (wasResized)
  28932. repaint();
  28933. else if (! flags.hasHeavyweightPeerFlag)
  28934. repaintParent();
  28935. if (flags.hasHeavyweightPeerFlag)
  28936. {
  28937. ComponentPeer* const peer = getPeer();
  28938. if (peer != 0)
  28939. {
  28940. if (wasMoved && wasResized)
  28941. peer->setBounds (getX(), getY(), getWidth(), getHeight(), false);
  28942. else if (wasMoved)
  28943. peer->setPosition (getX(), getY());
  28944. else if (wasResized)
  28945. peer->setSize (getWidth(), getHeight());
  28946. }
  28947. }
  28948. sendMovedResizedMessages (wasMoved, wasResized);
  28949. }
  28950. }
  28951. void Component::sendMovedResizedMessages (const bool wasMoved, const bool wasResized)
  28952. {
  28953. JUCE_TRY
  28954. {
  28955. if (wasMoved)
  28956. moved();
  28957. if (wasResized)
  28958. {
  28959. resized();
  28960. for (int i = childComponentList_.size(); --i >= 0;)
  28961. {
  28962. childComponentList_.getUnchecked(i)->parentSizeChanged();
  28963. i = jmin (i, childComponentList_.size());
  28964. }
  28965. }
  28966. if (parentComponent_ != 0)
  28967. parentComponent_->childBoundsChanged (this);
  28968. if (componentListeners_ != 0)
  28969. {
  28970. const ComponentDeletionWatcher deletionChecker (this);
  28971. for (int i = componentListeners_->size(); --i >= 0;)
  28972. {
  28973. ((ComponentListener*) componentListeners_->getUnchecked (i))
  28974. ->componentMovedOrResized (*this, wasMoved, wasResized);
  28975. if (deletionChecker.hasBeenDeleted())
  28976. return;
  28977. i = jmin (i, componentListeners_->size());
  28978. }
  28979. }
  28980. }
  28981. JUCE_CATCH_EXCEPTION
  28982. }
  28983. void Component::setSize (const int w, const int h)
  28984. {
  28985. setBounds (getX(), getY(), w, h);
  28986. }
  28987. void Component::setTopLeftPosition (const int x, const int y)
  28988. {
  28989. setBounds (x, y, getWidth(), getHeight());
  28990. }
  28991. void Component::setTopRightPosition (const int x, const int y)
  28992. {
  28993. setTopLeftPosition (x - getWidth(), y);
  28994. }
  28995. void Component::setBounds (const Rectangle& r)
  28996. {
  28997. setBounds (r.getX(),
  28998. r.getY(),
  28999. r.getWidth(),
  29000. r.getHeight());
  29001. }
  29002. void Component::setBoundsRelative (const float x, const float y,
  29003. const float w, const float h)
  29004. {
  29005. const int pw = getParentWidth();
  29006. const int ph = getParentHeight();
  29007. setBounds (roundFloatToInt (x * pw),
  29008. roundFloatToInt (y * ph),
  29009. roundFloatToInt (w * pw),
  29010. roundFloatToInt (h * ph));
  29011. }
  29012. void Component::setCentrePosition (const int x, const int y)
  29013. {
  29014. setTopLeftPosition (x - getWidth() / 2,
  29015. y - getHeight() / 2);
  29016. }
  29017. void Component::setCentreRelative (const float x, const float y)
  29018. {
  29019. setCentrePosition (roundFloatToInt (getParentWidth() * x),
  29020. roundFloatToInt (getParentHeight() * y));
  29021. }
  29022. void Component::centreWithSize (const int width, const int height)
  29023. {
  29024. setBounds ((getParentWidth() - width) / 2,
  29025. (getParentHeight() - height) / 2,
  29026. width,
  29027. height);
  29028. }
  29029. void Component::setBoundsInset (const BorderSize& borders)
  29030. {
  29031. setBounds (borders.getLeft(),
  29032. borders.getTop(),
  29033. getParentWidth() - (borders.getLeftAndRight()),
  29034. getParentHeight() - (borders.getTopAndBottom()));
  29035. }
  29036. void Component::setBoundsToFit (int x, int y, int width, int height,
  29037. const Justification& justification,
  29038. const bool onlyReduceInSize)
  29039. {
  29040. // it's no good calling this method unless both the component and
  29041. // target rectangle have a finite size.
  29042. jassert (getWidth() > 0 && getHeight() > 0 && width > 0 && height > 0);
  29043. if (getWidth() > 0 && getHeight() > 0
  29044. && width > 0 && height > 0)
  29045. {
  29046. int newW, newH;
  29047. if (onlyReduceInSize && getWidth() <= width && getHeight() <= height)
  29048. {
  29049. newW = getWidth();
  29050. newH = getHeight();
  29051. }
  29052. else
  29053. {
  29054. const double imageRatio = getHeight() / (double) getWidth();
  29055. const double targetRatio = height / (double) width;
  29056. if (imageRatio <= targetRatio)
  29057. {
  29058. newW = width;
  29059. newH = jmin (height, roundDoubleToInt (newW * imageRatio));
  29060. }
  29061. else
  29062. {
  29063. newH = height;
  29064. newW = jmin (width, roundDoubleToInt (newH / imageRatio));
  29065. }
  29066. }
  29067. if (newW > 0 && newH > 0)
  29068. {
  29069. int newX, newY;
  29070. justification.applyToRectangle (newX, newY, newW, newH,
  29071. x, y, width, height);
  29072. setBounds (newX, newY, newW, newH);
  29073. }
  29074. }
  29075. }
  29076. bool Component::hitTest (int x, int y)
  29077. {
  29078. if (! flags.ignoresMouseClicksFlag)
  29079. return true;
  29080. if (flags.allowChildMouseClicksFlag)
  29081. {
  29082. for (int i = getNumChildComponents(); --i >= 0;)
  29083. {
  29084. Component* const c = getChildComponent (i);
  29085. if (c->isVisible()
  29086. && c->bounds_.contains (x, y)
  29087. && c->hitTest (x - c->getX(),
  29088. y - c->getY()))
  29089. {
  29090. return true;
  29091. }
  29092. }
  29093. }
  29094. return false;
  29095. }
  29096. void Component::setInterceptsMouseClicks (const bool allowClicks,
  29097. const bool allowClicksOnChildComponents) throw()
  29098. {
  29099. flags.ignoresMouseClicksFlag = ! allowClicks;
  29100. flags.allowChildMouseClicksFlag = allowClicksOnChildComponents;
  29101. }
  29102. void Component::getInterceptsMouseClicks (bool& allowsClicksOnThisComponent,
  29103. bool& allowsClicksOnChildComponents) const throw()
  29104. {
  29105. allowsClicksOnThisComponent = ! flags.ignoresMouseClicksFlag;
  29106. allowsClicksOnChildComponents = flags.allowChildMouseClicksFlag;
  29107. }
  29108. bool Component::contains (const int x, const int y)
  29109. {
  29110. if (((unsigned int) x) < (unsigned int) getWidth()
  29111. && ((unsigned int) y) < (unsigned int) getHeight()
  29112. && hitTest (x, y))
  29113. {
  29114. if (parentComponent_ != 0)
  29115. {
  29116. return parentComponent_->contains (x + getX(),
  29117. y + getY());
  29118. }
  29119. else if (flags.hasHeavyweightPeerFlag)
  29120. {
  29121. const ComponentPeer* const peer = getPeer();
  29122. if (peer != 0)
  29123. return peer->contains (x, y, true);
  29124. }
  29125. }
  29126. return false;
  29127. }
  29128. bool Component::reallyContains (int x, int y, const bool returnTrueIfWithinAChild)
  29129. {
  29130. if (! contains (x, y))
  29131. return false;
  29132. Component* p = this;
  29133. while (p->parentComponent_ != 0)
  29134. {
  29135. x += p->getX();
  29136. y += p->getY();
  29137. p = p->parentComponent_;
  29138. }
  29139. const Component* const c = p->getComponentAt (x, y);
  29140. return (c == this) || (returnTrueIfWithinAChild && isParentOf (c));
  29141. }
  29142. Component* Component::getComponentAt (const int x, const int y)
  29143. {
  29144. if (flags.visibleFlag
  29145. && ((unsigned int) x) < (unsigned int) getWidth()
  29146. && ((unsigned int) y) < (unsigned int) getHeight()
  29147. && hitTest (x, y))
  29148. {
  29149. for (int i = childComponentList_.size(); --i >= 0;)
  29150. {
  29151. Component* const child = childComponentList_.getUnchecked(i);
  29152. Component* const c = child->getComponentAt (x - child->getX(),
  29153. y - child->getY());
  29154. if (c != 0)
  29155. return c;
  29156. }
  29157. return this;
  29158. }
  29159. return 0;
  29160. }
  29161. void Component::addChildComponent (Component* const child, int zOrder)
  29162. {
  29163. // if component methods are being called from threads other than the message
  29164. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  29165. checkMessageManagerIsLocked
  29166. if (child != 0 && child->parentComponent_ != this)
  29167. {
  29168. if (child->parentComponent_ != 0)
  29169. child->parentComponent_->removeChildComponent (child);
  29170. else
  29171. child->removeFromDesktop();
  29172. child->parentComponent_ = this;
  29173. if (child->isVisible())
  29174. child->repaintParent();
  29175. if (! child->isAlwaysOnTop())
  29176. {
  29177. if (zOrder < 0)
  29178. zOrder = childComponentList_.size();
  29179. while (zOrder > 0)
  29180. {
  29181. if (! childComponentList_.getUnchecked (zOrder - 1)->isAlwaysOnTop())
  29182. break;
  29183. --zOrder;
  29184. }
  29185. }
  29186. childComponentList_.insert (zOrder, child);
  29187. child->internalHierarchyChanged();
  29188. internalChildrenChanged();
  29189. }
  29190. }
  29191. void Component::addAndMakeVisible (Component* const child, int zOrder)
  29192. {
  29193. if (child != 0)
  29194. {
  29195. child->setVisible (true);
  29196. addChildComponent (child, zOrder);
  29197. }
  29198. }
  29199. void Component::removeChildComponent (Component* const child)
  29200. {
  29201. removeChildComponent (childComponentList_.indexOf (child));
  29202. }
  29203. Component* Component::removeChildComponent (const int index)
  29204. {
  29205. // if component methods are being called from threads other than the message
  29206. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  29207. checkMessageManagerIsLocked
  29208. Component* const child = childComponentList_ [index];
  29209. if (child != 0)
  29210. {
  29211. sendFakeMouseMove();
  29212. child->repaintParent();
  29213. childComponentList_.remove (index);
  29214. child->parentComponent_ = 0;
  29215. JUCE_TRY
  29216. {
  29217. if ((currentlyFocusedComponent == child)
  29218. || child->isParentOf (currentlyFocusedComponent))
  29219. {
  29220. // get rid first to force the grabKeyboardFocus to change to us.
  29221. giveAwayFocus();
  29222. grabKeyboardFocus();
  29223. }
  29224. }
  29225. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  29226. catch (const std::exception& e)
  29227. {
  29228. currentlyFocusedComponent = 0;
  29229. Desktop::getInstance().triggerFocusCallback();
  29230. JUCEApplication::sendUnhandledException (&e, __FILE__, __LINE__);
  29231. }
  29232. catch (...)
  29233. {
  29234. currentlyFocusedComponent = 0;
  29235. Desktop::getInstance().triggerFocusCallback();
  29236. JUCEApplication::sendUnhandledException (0, __FILE__, __LINE__);
  29237. }
  29238. #endif
  29239. child->internalHierarchyChanged();
  29240. internalChildrenChanged();
  29241. }
  29242. return child;
  29243. }
  29244. void Component::removeAllChildren()
  29245. {
  29246. for (int i = childComponentList_.size(); --i >= 0;)
  29247. removeChildComponent (i);
  29248. }
  29249. void Component::deleteAllChildren()
  29250. {
  29251. for (int i = childComponentList_.size(); --i >= 0;)
  29252. delete (removeChildComponent (i));
  29253. }
  29254. int Component::getNumChildComponents() const throw()
  29255. {
  29256. return childComponentList_.size();
  29257. }
  29258. Component* Component::getChildComponent (const int index) const throw()
  29259. {
  29260. return childComponentList_ [index];
  29261. }
  29262. int Component::getIndexOfChildComponent (const Component* const child) const throw()
  29263. {
  29264. return childComponentList_.indexOf (const_cast <Component*> (child));
  29265. }
  29266. Component* Component::getTopLevelComponent() const throw()
  29267. {
  29268. const Component* comp = this;
  29269. while (comp->parentComponent_ != 0)
  29270. comp = comp->parentComponent_;
  29271. return (Component*) comp;
  29272. }
  29273. bool Component::isParentOf (const Component* possibleChild) const throw()
  29274. {
  29275. while (possibleChild->isValidComponent())
  29276. {
  29277. possibleChild = possibleChild->parentComponent_;
  29278. if (possibleChild == this)
  29279. return true;
  29280. }
  29281. return false;
  29282. }
  29283. void Component::parentHierarchyChanged()
  29284. {
  29285. }
  29286. void Component::childrenChanged()
  29287. {
  29288. }
  29289. void Component::internalChildrenChanged()
  29290. {
  29291. const ComponentDeletionWatcher deletionChecker (this);
  29292. const bool hasListeners = componentListeners_ != 0;
  29293. childrenChanged();
  29294. if (hasListeners)
  29295. {
  29296. if (deletionChecker.hasBeenDeleted())
  29297. return;
  29298. for (int i = componentListeners_->size(); --i >= 0;)
  29299. {
  29300. ((ComponentListener*) componentListeners_->getUnchecked (i))
  29301. ->componentChildrenChanged (*this);
  29302. if (deletionChecker.hasBeenDeleted())
  29303. return;
  29304. i = jmin (i, componentListeners_->size());
  29305. }
  29306. }
  29307. }
  29308. void Component::internalHierarchyChanged()
  29309. {
  29310. parentHierarchyChanged();
  29311. const ComponentDeletionWatcher deletionChecker (this);
  29312. if (componentListeners_ != 0)
  29313. {
  29314. for (int i = componentListeners_->size(); --i >= 0;)
  29315. {
  29316. ((ComponentListener*) componentListeners_->getUnchecked (i))
  29317. ->componentParentHierarchyChanged (*this);
  29318. if (deletionChecker.hasBeenDeleted())
  29319. return;
  29320. i = jmin (i, componentListeners_->size());
  29321. }
  29322. }
  29323. for (int i = childComponentList_.size(); --i >= 0;)
  29324. {
  29325. childComponentList_.getUnchecked (i)->internalHierarchyChanged();
  29326. // you really shouldn't delete the parent component during a callback telling you
  29327. // that it's changed..
  29328. jassert (! deletionChecker.hasBeenDeleted());
  29329. if (deletionChecker.hasBeenDeleted())
  29330. return;
  29331. i = jmin (i, childComponentList_.size());
  29332. }
  29333. }
  29334. void* Component::runModalLoopCallback (void* userData)
  29335. {
  29336. return (void*) (pointer_sized_int) ((Component*) userData)->runModalLoop();
  29337. }
  29338. int Component::runModalLoop()
  29339. {
  29340. if (! MessageManager::getInstance()->isThisTheMessageThread())
  29341. {
  29342. // use a callback so this can be called from non-gui threads
  29343. return (int) (pointer_sized_int)
  29344. MessageManager::getInstance()
  29345. ->callFunctionOnMessageThread (&runModalLoopCallback, (void*) this);
  29346. }
  29347. Component* const prevFocused = getCurrentlyFocusedComponent();
  29348. ComponentDeletionWatcher* deletionChecker = 0;
  29349. if (prevFocused != 0)
  29350. deletionChecker = new ComponentDeletionWatcher (prevFocused);
  29351. if (! isCurrentlyModal())
  29352. enterModalState();
  29353. JUCE_TRY
  29354. {
  29355. while (flags.currentlyModalFlag && flags.visibleFlag)
  29356. {
  29357. if (! MessageManager::getInstance()->dispatchNextMessage())
  29358. break;
  29359. // check whether this component was deleted during the last message
  29360. if (! isValidMessageListener())
  29361. break;
  29362. }
  29363. }
  29364. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  29365. catch (const std::exception& e)
  29366. {
  29367. JUCEApplication::sendUnhandledException (&e, __FILE__, __LINE__);
  29368. return 0;
  29369. }
  29370. catch (...)
  29371. {
  29372. JUCEApplication::sendUnhandledException (0, __FILE__, __LINE__);
  29373. return 0;
  29374. }
  29375. #endif
  29376. const int modalIndex = modalComponentReturnValueKeys.indexOf (this);
  29377. int returnValue = 0;
  29378. if (modalIndex >= 0)
  29379. {
  29380. modalComponentReturnValueKeys.remove (modalIndex);
  29381. returnValue = modalReturnValues.remove (modalIndex);
  29382. }
  29383. modalComponentStack.removeValue (this);
  29384. if (deletionChecker != 0)
  29385. {
  29386. if (! deletionChecker->hasBeenDeleted())
  29387. prevFocused->grabKeyboardFocus();
  29388. delete deletionChecker;
  29389. }
  29390. return returnValue;
  29391. }
  29392. void Component::enterModalState (const bool takeKeyboardFocus)
  29393. {
  29394. // if component methods are being called from threads other than the message
  29395. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  29396. checkMessageManagerIsLocked
  29397. // Check for an attempt to make a component modal when it already is!
  29398. // This can cause nasty problems..
  29399. jassert (! flags.currentlyModalFlag);
  29400. if (! isCurrentlyModal())
  29401. {
  29402. modalComponentStack.add (this);
  29403. modalComponentReturnValueKeys.add (this);
  29404. modalReturnValues.add (0);
  29405. flags.currentlyModalFlag = true;
  29406. setVisible (true);
  29407. if (takeKeyboardFocus)
  29408. grabKeyboardFocus();
  29409. }
  29410. }
  29411. void Component::exitModalState (const int returnValue)
  29412. {
  29413. if (isCurrentlyModal())
  29414. {
  29415. if (MessageManager::getInstance()->isThisTheMessageThread())
  29416. {
  29417. const int modalIndex = modalComponentReturnValueKeys.indexOf (this);
  29418. if (modalIndex >= 0)
  29419. {
  29420. modalReturnValues.set (modalIndex, returnValue);
  29421. }
  29422. else
  29423. {
  29424. modalComponentReturnValueKeys.add (this);
  29425. modalReturnValues.add (returnValue);
  29426. }
  29427. modalComponentStack.removeValue (this);
  29428. flags.currentlyModalFlag = false;
  29429. }
  29430. else
  29431. {
  29432. postMessage (new Message (exitModalStateMessage, returnValue, 0, 0));
  29433. }
  29434. }
  29435. }
  29436. bool Component::isCurrentlyModal() const throw()
  29437. {
  29438. return flags.currentlyModalFlag
  29439. && getCurrentlyModalComponent() == this;
  29440. }
  29441. bool Component::isCurrentlyBlockedByAnotherModalComponent() const throw()
  29442. {
  29443. Component* const mc = getCurrentlyModalComponent();
  29444. return mc != 0
  29445. && mc != this
  29446. && (! mc->isParentOf (this))
  29447. && ! mc->canModalEventBeSentToComponent (this);
  29448. }
  29449. Component* JUCE_CALLTYPE Component::getCurrentlyModalComponent() throw()
  29450. {
  29451. Component* const c = (Component*) modalComponentStack.getLast();
  29452. return c->isValidComponent() ? c : 0;
  29453. }
  29454. void Component::setBroughtToFrontOnMouseClick (const bool shouldBeBroughtToFront) throw()
  29455. {
  29456. flags.bringToFrontOnClickFlag = shouldBeBroughtToFront;
  29457. }
  29458. bool Component::isBroughtToFrontOnMouseClick() const throw()
  29459. {
  29460. return flags.bringToFrontOnClickFlag;
  29461. }
  29462. void Component::setMouseCursor (const MouseCursor& cursor) throw()
  29463. {
  29464. cursor_ = cursor;
  29465. if (flags.visibleFlag)
  29466. {
  29467. int mx, my;
  29468. getMouseXYRelative (mx, my);
  29469. if (flags.draggingFlag || reallyContains (mx, my, false))
  29470. {
  29471. internalUpdateMouseCursor (false);
  29472. }
  29473. }
  29474. }
  29475. const MouseCursor Component::getMouseCursor()
  29476. {
  29477. return cursor_;
  29478. }
  29479. void Component::updateMouseCursor() const throw()
  29480. {
  29481. sendFakeMouseMove();
  29482. }
  29483. void Component::internalUpdateMouseCursor (const bool forcedUpdate) throw()
  29484. {
  29485. ComponentPeer* const peer = getPeer();
  29486. if (peer != 0)
  29487. {
  29488. MouseCursor mc (getMouseCursor());
  29489. if (isUnboundedMouseModeOn && (unboundedMouseOffsetX != 0
  29490. || unboundedMouseOffsetY != 0
  29491. || ! isCursorVisibleUntilOffscreen))
  29492. {
  29493. mc = MouseCursor::NoCursor;
  29494. }
  29495. static void* currentCursorHandle = 0;
  29496. if (forcedUpdate || mc.getHandle() != currentCursorHandle)
  29497. {
  29498. currentCursorHandle = mc.getHandle();
  29499. mc.showInWindow (peer);
  29500. }
  29501. }
  29502. }
  29503. void Component::setRepaintsOnMouseActivity (const bool shouldRepaint) throw()
  29504. {
  29505. flags.repaintOnMouseActivityFlag = shouldRepaint;
  29506. }
  29507. void Component::repaintParent() throw()
  29508. {
  29509. if (flags.visibleFlag)
  29510. internalRepaint (0, 0, getWidth(), getHeight());
  29511. }
  29512. void Component::repaint() throw()
  29513. {
  29514. repaint (0, 0, getWidth(), getHeight());
  29515. }
  29516. void Component::repaint (const int x, const int y,
  29517. const int w, const int h) throw()
  29518. {
  29519. deleteAndZero (bufferedImage_);
  29520. if (flags.visibleFlag)
  29521. internalRepaint (x, y, w, h);
  29522. }
  29523. void Component::internalRepaint (int x, int y, int w, int h)
  29524. {
  29525. // if component methods are being called from threads other than the message
  29526. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  29527. checkMessageManagerIsLocked
  29528. if (x < 0)
  29529. {
  29530. w += x;
  29531. x = 0;
  29532. }
  29533. if (x + w > getWidth())
  29534. w = getWidth() - x;
  29535. if (w > 0)
  29536. {
  29537. if (y < 0)
  29538. {
  29539. h += y;
  29540. y = 0;
  29541. }
  29542. if (y + h > getHeight())
  29543. h = getHeight() - y;
  29544. if (h > 0)
  29545. {
  29546. if (parentComponent_ != 0)
  29547. {
  29548. x += getX();
  29549. y += getY();
  29550. if (parentComponent_->flags.visibleFlag)
  29551. parentComponent_->internalRepaint (x, y, w, h);
  29552. }
  29553. else if (flags.hasHeavyweightPeerFlag)
  29554. {
  29555. ComponentPeer* const peer = getPeer();
  29556. if (peer != 0)
  29557. peer->repaint (x, y, w, h);
  29558. }
  29559. }
  29560. }
  29561. }
  29562. void Component::paintEntireComponent (Graphics& originalContext)
  29563. {
  29564. jassert (! originalContext.isClipEmpty());
  29565. #ifdef JUCE_DEBUG
  29566. flags.isInsidePaintCall = true;
  29567. #endif
  29568. Graphics* g = &originalContext;
  29569. Image* effectImage = 0;
  29570. if (effect_ != 0)
  29571. {
  29572. effectImage = new Image (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  29573. getWidth(), getHeight(),
  29574. ! flags.opaqueFlag);
  29575. g = new Graphics (*effectImage);
  29576. }
  29577. g->saveState();
  29578. clipObscuredRegions (*g, g->getClipBounds(), 0, 0);
  29579. if (! g->isClipEmpty())
  29580. {
  29581. if (bufferedImage_ != 0)
  29582. {
  29583. g->setColour (Colours::black);
  29584. g->drawImageAt (bufferedImage_, 0, 0);
  29585. }
  29586. else
  29587. {
  29588. if (flags.bufferToImageFlag)
  29589. {
  29590. if (bufferedImage_ == 0)
  29591. {
  29592. bufferedImage_ = new Image (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  29593. getWidth(), getHeight(), ! flags.opaqueFlag);
  29594. Graphics imG (*bufferedImage_);
  29595. paint (imG);
  29596. }
  29597. g->setColour (Colours::black);
  29598. g->drawImageAt (bufferedImage_, 0, 0);
  29599. }
  29600. else
  29601. {
  29602. paint (*g);
  29603. g->resetToDefaultState();
  29604. }
  29605. }
  29606. }
  29607. g->restoreState();
  29608. for (int i = 0; i < childComponentList_.size(); ++i)
  29609. {
  29610. Component* const child = childComponentList_.getUnchecked (i);
  29611. if (child->isVisible())
  29612. {
  29613. g->saveState();
  29614. if (g->reduceClipRegion (child->getX(), child->getY(),
  29615. child->getWidth(), child->getHeight()))
  29616. {
  29617. for (int j = i + 1; j < childComponentList_.size(); ++j)
  29618. {
  29619. const Component* const sibling = childComponentList_.getUnchecked (j);
  29620. if (sibling->flags.opaqueFlag && sibling->isVisible())
  29621. g->excludeClipRegion (sibling->getX(), sibling->getY(),
  29622. sibling->getWidth(), sibling->getHeight());
  29623. }
  29624. if (! g->isClipEmpty())
  29625. {
  29626. g->setOrigin (child->getX(), child->getY());
  29627. child->paintEntireComponent (*g);
  29628. }
  29629. }
  29630. g->restoreState();
  29631. }
  29632. }
  29633. JUCE_TRY
  29634. {
  29635. g->saveState();
  29636. paintOverChildren (*g);
  29637. g->restoreState();
  29638. }
  29639. JUCE_CATCH_EXCEPTION
  29640. if (effect_ != 0)
  29641. {
  29642. delete g;
  29643. effect_->applyEffect (*effectImage, originalContext);
  29644. delete effectImage;
  29645. }
  29646. #ifdef JUCE_DEBUG
  29647. flags.isInsidePaintCall = false;
  29648. #endif
  29649. }
  29650. Image* Component::createComponentSnapshot (const Rectangle& areaToGrab,
  29651. const bool clipImageToComponentBounds)
  29652. {
  29653. Rectangle r (areaToGrab);
  29654. if (clipImageToComponentBounds)
  29655. r = r.getIntersection (Rectangle (0, 0, getWidth(), getHeight()));
  29656. Image* const componentImage = new Image (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  29657. jmax (1, r.getWidth()),
  29658. jmax (1, r.getHeight()),
  29659. true);
  29660. Graphics imageContext (*componentImage);
  29661. imageContext.setOrigin (-r.getX(),
  29662. -r.getY());
  29663. paintEntireComponent (imageContext);
  29664. return componentImage;
  29665. }
  29666. void Component::setComponentEffect (ImageEffectFilter* const effect)
  29667. {
  29668. if (effect_ != effect)
  29669. {
  29670. effect_ = effect;
  29671. repaint();
  29672. }
  29673. }
  29674. LookAndFeel& Component::getLookAndFeel() const throw()
  29675. {
  29676. const Component* c = this;
  29677. do
  29678. {
  29679. if (c->lookAndFeel_ != 0)
  29680. return *(c->lookAndFeel_);
  29681. c = c->parentComponent_;
  29682. }
  29683. while (c != 0);
  29684. return LookAndFeel::getDefaultLookAndFeel();
  29685. }
  29686. void Component::setLookAndFeel (LookAndFeel* const newLookAndFeel)
  29687. {
  29688. if (lookAndFeel_ != newLookAndFeel)
  29689. {
  29690. lookAndFeel_ = newLookAndFeel;
  29691. sendLookAndFeelChange();
  29692. }
  29693. }
  29694. void Component::lookAndFeelChanged()
  29695. {
  29696. }
  29697. void Component::sendLookAndFeelChange()
  29698. {
  29699. repaint();
  29700. lookAndFeelChanged();
  29701. // (it's not a great idea to do anything that would delete this component
  29702. // during the lookAndFeelChanged() callback)
  29703. jassert (isValidComponent());
  29704. const ComponentDeletionWatcher deletionChecker (this);
  29705. for (int i = childComponentList_.size(); --i >= 0;)
  29706. {
  29707. childComponentList_.getUnchecked (i)->sendLookAndFeelChange();
  29708. if (deletionChecker.hasBeenDeleted())
  29709. return;
  29710. i = jmin (i, childComponentList_.size());
  29711. }
  29712. }
  29713. static const String getColourPropertyName (const int colourId) throw()
  29714. {
  29715. String s;
  29716. s.preallocateStorage (18);
  29717. s << T("jcclr_") << colourId;
  29718. return s;
  29719. }
  29720. const Colour Component::findColour (const int colourId, const bool inheritFromParent) const throw()
  29721. {
  29722. const String customColour (getComponentProperty (getColourPropertyName (colourId),
  29723. inheritFromParent,
  29724. String::empty));
  29725. if (customColour.isNotEmpty())
  29726. return Colour (customColour.getIntValue());
  29727. return getLookAndFeel().findColour (colourId);
  29728. }
  29729. bool Component::isColourSpecified (const int colourId) const throw()
  29730. {
  29731. return getComponentProperty (getColourPropertyName (colourId),
  29732. false,
  29733. String::empty).isNotEmpty();
  29734. }
  29735. void Component::removeColour (const int colourId)
  29736. {
  29737. if (isColourSpecified (colourId))
  29738. {
  29739. removeComponentProperty (getColourPropertyName (colourId));
  29740. colourChanged();
  29741. }
  29742. }
  29743. void Component::setColour (const int colourId, const Colour& colour)
  29744. {
  29745. const String colourName (getColourPropertyName (colourId));
  29746. const String customColour (getComponentProperty (colourName, false, String::empty));
  29747. if (customColour.isEmpty() || Colour (customColour.getIntValue()) != colour)
  29748. {
  29749. setComponentProperty (colourName, colour);
  29750. colourChanged();
  29751. }
  29752. }
  29753. void Component::copyAllExplicitColoursTo (Component& target) const throw()
  29754. {
  29755. if (propertySet_ != 0)
  29756. {
  29757. const StringPairArray& props = propertySet_->getAllProperties();
  29758. const StringArray& keys = props.getAllKeys();
  29759. for (int i = 0; i < keys.size(); ++i)
  29760. {
  29761. if (keys[i].startsWith (T("jcclr_")))
  29762. {
  29763. target.setComponentProperty (keys[i],
  29764. props.getAllValues() [i]);
  29765. }
  29766. }
  29767. target.colourChanged();
  29768. }
  29769. }
  29770. void Component::colourChanged()
  29771. {
  29772. }
  29773. const Rectangle Component::getUnclippedArea() const
  29774. {
  29775. int x = 0, y = 0, w = getWidth(), h = getHeight();
  29776. Component* p = parentComponent_;
  29777. int px = getX();
  29778. int py = getY();
  29779. while (p != 0)
  29780. {
  29781. if (! Rectangle::intersectRectangles (x, y, w, h, -px, -py, p->getWidth(), p->getHeight()))
  29782. return Rectangle();
  29783. px += p->getX();
  29784. py += p->getY();
  29785. p = p->parentComponent_;
  29786. }
  29787. return Rectangle (x, y, w, h);
  29788. }
  29789. void Component::clipObscuredRegions (Graphics& g, const Rectangle& clipRect,
  29790. const int deltaX, const int deltaY) const throw()
  29791. {
  29792. for (int i = childComponentList_.size(); --i >= 0;)
  29793. {
  29794. const Component* const c = childComponentList_.getUnchecked(i);
  29795. if (c->isVisible())
  29796. {
  29797. Rectangle newClip (clipRect.getIntersection (c->bounds_));
  29798. if (! newClip.isEmpty())
  29799. {
  29800. if (c->isOpaque())
  29801. {
  29802. g.excludeClipRegion (deltaX + newClip.getX(),
  29803. deltaY + newClip.getY(),
  29804. newClip.getWidth(),
  29805. newClip.getHeight());
  29806. }
  29807. else
  29808. {
  29809. newClip.translate (-c->getX(), -c->getY());
  29810. c->clipObscuredRegions (g, newClip,
  29811. c->getX() + deltaX,
  29812. c->getY() + deltaY);
  29813. }
  29814. }
  29815. }
  29816. }
  29817. }
  29818. void Component::getVisibleArea (RectangleList& result,
  29819. const bool includeSiblings) const
  29820. {
  29821. result.clear();
  29822. const Rectangle unclipped (getUnclippedArea());
  29823. if (! unclipped.isEmpty())
  29824. {
  29825. result.add (unclipped);
  29826. if (includeSiblings)
  29827. {
  29828. const Component* const c = getTopLevelComponent();
  29829. int x = 0, y = 0;
  29830. c->relativePositionToOtherComponent (this, x, y);
  29831. c->subtractObscuredRegions (result, x, y,
  29832. Rectangle (0, 0, c->getWidth(), c->getHeight()),
  29833. this);
  29834. }
  29835. subtractObscuredRegions (result, 0, 0, unclipped, 0);
  29836. result.consolidate();
  29837. }
  29838. }
  29839. void Component::subtractObscuredRegions (RectangleList& result,
  29840. const int deltaX,
  29841. const int deltaY,
  29842. const Rectangle& clipRect,
  29843. const Component* const compToAvoid) const throw()
  29844. {
  29845. for (int i = childComponentList_.size(); --i >= 0;)
  29846. {
  29847. const Component* const c = childComponentList_.getUnchecked(i);
  29848. if (c != compToAvoid && c->isVisible())
  29849. {
  29850. if (c->isOpaque())
  29851. {
  29852. Rectangle childBounds (c->bounds_.getIntersection (clipRect));
  29853. childBounds.translate (deltaX, deltaY);
  29854. result.subtract (childBounds);
  29855. }
  29856. else
  29857. {
  29858. Rectangle newClip (clipRect.getIntersection (c->bounds_));
  29859. newClip.translate (-c->getX(), -c->getY());
  29860. c->subtractObscuredRegions (result,
  29861. c->getX() + deltaX,
  29862. c->getY() + deltaY,
  29863. newClip,
  29864. compToAvoid);
  29865. }
  29866. }
  29867. }
  29868. }
  29869. void Component::mouseEnter (const MouseEvent&)
  29870. {
  29871. // base class does nothing
  29872. }
  29873. void Component::mouseExit (const MouseEvent&)
  29874. {
  29875. // base class does nothing
  29876. }
  29877. void Component::mouseDown (const MouseEvent&)
  29878. {
  29879. // base class does nothing
  29880. }
  29881. void Component::mouseUp (const MouseEvent&)
  29882. {
  29883. // base class does nothing
  29884. }
  29885. void Component::mouseDrag (const MouseEvent&)
  29886. {
  29887. // base class does nothing
  29888. }
  29889. void Component::mouseMove (const MouseEvent&)
  29890. {
  29891. // base class does nothing
  29892. }
  29893. void Component::mouseDoubleClick (const MouseEvent&)
  29894. {
  29895. // base class does nothing
  29896. }
  29897. void Component::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  29898. {
  29899. // the base class just passes this event up to its parent..
  29900. if (parentComponent_ != 0)
  29901. parentComponent_->mouseWheelMove (e.getEventRelativeTo (parentComponent_),
  29902. wheelIncrementX, wheelIncrementY);
  29903. }
  29904. void Component::resized()
  29905. {
  29906. // base class does nothing
  29907. }
  29908. void Component::moved()
  29909. {
  29910. // base class does nothing
  29911. }
  29912. void Component::childBoundsChanged (Component*)
  29913. {
  29914. // base class does nothing
  29915. }
  29916. void Component::parentSizeChanged()
  29917. {
  29918. // base class does nothing
  29919. }
  29920. void Component::addComponentListener (ComponentListener* const newListener) throw()
  29921. {
  29922. if (componentListeners_ == 0)
  29923. componentListeners_ = new VoidArray (4);
  29924. componentListeners_->addIfNotAlreadyThere (newListener);
  29925. }
  29926. void Component::removeComponentListener (ComponentListener* const listenerToRemove) throw()
  29927. {
  29928. jassert (isValidComponent());
  29929. if (componentListeners_ != 0)
  29930. componentListeners_->removeValue (listenerToRemove);
  29931. }
  29932. void Component::inputAttemptWhenModal()
  29933. {
  29934. getTopLevelComponent()->toFront (true);
  29935. getLookAndFeel().playAlertSound();
  29936. }
  29937. bool Component::canModalEventBeSentToComponent (const Component*)
  29938. {
  29939. return false;
  29940. }
  29941. void Component::internalModalInputAttempt()
  29942. {
  29943. Component* const current = getCurrentlyModalComponent();
  29944. if (current != 0)
  29945. current->inputAttemptWhenModal();
  29946. }
  29947. void Component::paint (Graphics&)
  29948. {
  29949. // all painting is done in the subclasses
  29950. jassert (! isOpaque()); // if your component's opaque, you've gotta paint it!
  29951. }
  29952. void Component::paintOverChildren (Graphics&)
  29953. {
  29954. // all painting is done in the subclasses
  29955. }
  29956. void Component::handleMessage (const Message& message)
  29957. {
  29958. if (message.intParameter1 == exitModalStateMessage)
  29959. {
  29960. exitModalState (message.intParameter2);
  29961. }
  29962. else if (message.intParameter1 == customCommandMessage)
  29963. {
  29964. handleCommandMessage (message.intParameter2);
  29965. }
  29966. }
  29967. void Component::postCommandMessage (const int commandId) throw()
  29968. {
  29969. postMessage (new Message (customCommandMessage, commandId, 0, 0));
  29970. }
  29971. void Component::handleCommandMessage (int)
  29972. {
  29973. // used by subclasses
  29974. }
  29975. void Component::addMouseListener (MouseListener* const newListener,
  29976. const bool wantsEventsForAllNestedChildComponents) throw()
  29977. {
  29978. // if component methods are being called from threads other than the message
  29979. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  29980. checkMessageManagerIsLocked
  29981. if (mouseListeners_ == 0)
  29982. mouseListeners_ = new VoidArray (4);
  29983. if (! mouseListeners_->contains (newListener))
  29984. {
  29985. if (wantsEventsForAllNestedChildComponents)
  29986. {
  29987. mouseListeners_->insert (0, newListener);
  29988. ++numDeepMouseListeners;
  29989. }
  29990. else
  29991. {
  29992. mouseListeners_->add (newListener);
  29993. }
  29994. }
  29995. }
  29996. void Component::removeMouseListener (MouseListener* const listenerToRemove) throw()
  29997. {
  29998. // if component methods are being called from threads other than the message
  29999. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  30000. checkMessageManagerIsLocked
  30001. if (mouseListeners_ != 0)
  30002. {
  30003. const int index = mouseListeners_->indexOf (listenerToRemove);
  30004. if (index >= 0)
  30005. {
  30006. if (index < numDeepMouseListeners)
  30007. --numDeepMouseListeners;
  30008. mouseListeners_->remove (index);
  30009. }
  30010. }
  30011. }
  30012. void Component::internalMouseEnter (int x, int y, int64 time)
  30013. {
  30014. if (isCurrentlyBlockedByAnotherModalComponent())
  30015. {
  30016. // if something else is modal, always just show a normal mouse cursor
  30017. if (componentUnderMouse == this)
  30018. {
  30019. ComponentPeer* const peer = getPeer();
  30020. if (peer != 0)
  30021. {
  30022. MouseCursor mc (MouseCursor::NormalCursor);
  30023. mc.showInWindow (peer);
  30024. }
  30025. }
  30026. return;
  30027. }
  30028. if (! flags.mouseInsideFlag)
  30029. {
  30030. flags.mouseInsideFlag = true;
  30031. flags.mouseOverFlag = true;
  30032. flags.draggingFlag = false;
  30033. if (isValidComponent())
  30034. {
  30035. const ComponentDeletionWatcher deletionChecker (this);
  30036. if (flags.repaintOnMouseActivityFlag)
  30037. repaint();
  30038. const MouseEvent me (x, y,
  30039. ModifierKeys::getCurrentModifiers(),
  30040. this,
  30041. Time (time),
  30042. x, y,
  30043. Time (time),
  30044. 0, false);
  30045. mouseEnter (me);
  30046. if (deletionChecker.hasBeenDeleted())
  30047. return;
  30048. Desktop::getInstance().resetTimer();
  30049. for (int i = Desktop::getInstance().mouseListeners.size(); --i >= 0;)
  30050. {
  30051. ((MouseListener*) Desktop::getInstance().mouseListeners[i])->mouseEnter (me);
  30052. if (deletionChecker.hasBeenDeleted())
  30053. return;
  30054. i = jmin (i, Desktop::getInstance().mouseListeners.size());
  30055. }
  30056. if (mouseListeners_ != 0)
  30057. {
  30058. for (int i = mouseListeners_->size(); --i >= 0;)
  30059. {
  30060. ((MouseListener*) mouseListeners_->getUnchecked(i))->mouseEnter (me);
  30061. if (deletionChecker.hasBeenDeleted())
  30062. return;
  30063. i = jmin (i, mouseListeners_->size());
  30064. }
  30065. }
  30066. const Component* p = parentComponent_;
  30067. while (p != 0)
  30068. {
  30069. const ComponentDeletionWatcher parentDeletionChecker (p);
  30070. for (int i = p->numDeepMouseListeners; --i >= 0;)
  30071. {
  30072. ((MouseListener*) (p->mouseListeners_->getUnchecked(i)))->mouseEnter (me);
  30073. if (deletionChecker.hasBeenDeleted() || parentDeletionChecker.hasBeenDeleted())
  30074. return;
  30075. i = jmin (i, p->numDeepMouseListeners);
  30076. }
  30077. p = p->parentComponent_;
  30078. }
  30079. }
  30080. }
  30081. if (componentUnderMouse == this)
  30082. internalUpdateMouseCursor (true);
  30083. }
  30084. void Component::internalMouseExit (int x, int y, int64 time)
  30085. {
  30086. const ComponentDeletionWatcher deletionChecker (this);
  30087. if (flags.draggingFlag)
  30088. {
  30089. internalMouseUp (ModifierKeys::getCurrentModifiers().getRawFlags(), x, y, time);
  30090. if (deletionChecker.hasBeenDeleted())
  30091. return;
  30092. }
  30093. enableUnboundedMouseMovement (false);
  30094. if (flags.mouseInsideFlag || flags.mouseOverFlag)
  30095. {
  30096. flags.mouseInsideFlag = false;
  30097. flags.mouseOverFlag = false;
  30098. flags.draggingFlag = false;
  30099. if (flags.repaintOnMouseActivityFlag)
  30100. repaint();
  30101. const MouseEvent me (x, y,
  30102. ModifierKeys::getCurrentModifiers(),
  30103. this,
  30104. Time (time),
  30105. x, y,
  30106. Time (time),
  30107. 0, false);
  30108. mouseExit (me);
  30109. if (deletionChecker.hasBeenDeleted())
  30110. return;
  30111. Desktop::getInstance().resetTimer();
  30112. for (int i = Desktop::getInstance().mouseListeners.size(); --i >= 0;)
  30113. {
  30114. ((MouseListener*) Desktop::getInstance().mouseListeners[i])->mouseExit (me);
  30115. if (deletionChecker.hasBeenDeleted())
  30116. return;
  30117. i = jmin (i, Desktop::getInstance().mouseListeners.size());
  30118. }
  30119. if (mouseListeners_ != 0)
  30120. {
  30121. for (int i = mouseListeners_->size(); --i >= 0;)
  30122. {
  30123. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseExit (me);
  30124. if (deletionChecker.hasBeenDeleted())
  30125. return;
  30126. i = jmin (i, mouseListeners_->size());
  30127. }
  30128. }
  30129. const Component* p = parentComponent_;
  30130. while (p != 0)
  30131. {
  30132. const ComponentDeletionWatcher parentDeletionChecker (p);
  30133. for (int i = p->numDeepMouseListeners; --i >= 0;)
  30134. {
  30135. ((MouseListener*) (p->mouseListeners_->getUnchecked (i)))->mouseExit (me);
  30136. if (deletionChecker.hasBeenDeleted() || parentDeletionChecker.hasBeenDeleted())
  30137. return;
  30138. i = jmin (i, p->numDeepMouseListeners);
  30139. }
  30140. p = p->parentComponent_;
  30141. }
  30142. }
  30143. }
  30144. class InternalDragRepeater : public Timer
  30145. {
  30146. public:
  30147. InternalDragRepeater()
  30148. {}
  30149. ~InternalDragRepeater()
  30150. {}
  30151. void timerCallback()
  30152. {
  30153. Component* const c = Component::getComponentUnderMouse();
  30154. if (c != 0 && c->isMouseButtonDown())
  30155. {
  30156. int x, y;
  30157. c->getMouseXYRelative (x, y);
  30158. // the offsets have been added on, so must be taken off before calling the
  30159. // drag.. otherwise they'll be added twice
  30160. x -= unboundedMouseOffsetX;
  30161. y -= unboundedMouseOffsetY;
  30162. c->internalMouseDrag (x, y, Time::currentTimeMillis());
  30163. }
  30164. }
  30165. juce_UseDebuggingNewOperator
  30166. };
  30167. static InternalDragRepeater* dragRepeater = 0;
  30168. void Component::beginDragAutoRepeat (const int interval)
  30169. {
  30170. if (interval > 0)
  30171. {
  30172. if (dragRepeater == 0)
  30173. dragRepeater = new InternalDragRepeater();
  30174. if (dragRepeater->getTimerInterval() != interval)
  30175. dragRepeater->startTimer (interval);
  30176. }
  30177. else
  30178. {
  30179. deleteAndZero (dragRepeater);
  30180. }
  30181. }
  30182. void Component::internalMouseDown (const int x, const int y)
  30183. {
  30184. const ComponentDeletionWatcher deletionChecker (this);
  30185. if (isCurrentlyBlockedByAnotherModalComponent())
  30186. {
  30187. internalModalInputAttempt();
  30188. if (deletionChecker.hasBeenDeleted())
  30189. return;
  30190. // If processing the input attempt has exited the modal loop, we'll allow the event
  30191. // to be delivered..
  30192. if (isCurrentlyBlockedByAnotherModalComponent())
  30193. {
  30194. // allow blocked mouse-events to go to global listeners..
  30195. const MouseEvent me (x, y,
  30196. ModifierKeys::getCurrentModifiers(),
  30197. this,
  30198. Time (juce_recentMouseDownTimes[0]),
  30199. x, y,
  30200. Time (juce_recentMouseDownTimes[0]),
  30201. countMouseClicks(),
  30202. false);
  30203. Desktop::getInstance().resetTimer();
  30204. for (int i = Desktop::getInstance().mouseListeners.size(); --i >= 0;)
  30205. {
  30206. ((MouseListener*) Desktop::getInstance().mouseListeners[i])->mouseDown (me);
  30207. if (deletionChecker.hasBeenDeleted())
  30208. return;
  30209. i = jmin (i, Desktop::getInstance().mouseListeners.size());
  30210. }
  30211. return;
  30212. }
  30213. }
  30214. {
  30215. Component* c = this;
  30216. while (c != 0)
  30217. {
  30218. if (c->isBroughtToFrontOnMouseClick())
  30219. {
  30220. c->toFront (true);
  30221. if (deletionChecker.hasBeenDeleted())
  30222. return;
  30223. }
  30224. c = c->parentComponent_;
  30225. }
  30226. }
  30227. if (! flags.dontFocusOnMouseClickFlag)
  30228. grabFocusInternal (focusChangedByMouseClick);
  30229. if (! deletionChecker.hasBeenDeleted())
  30230. {
  30231. flags.draggingFlag = true;
  30232. flags.mouseOverFlag = true;
  30233. if (flags.repaintOnMouseActivityFlag)
  30234. repaint();
  30235. const MouseEvent me (x, y,
  30236. ModifierKeys::getCurrentModifiers(),
  30237. this,
  30238. Time (juce_recentMouseDownTimes[0]),
  30239. x, y,
  30240. Time (juce_recentMouseDownTimes[0]),
  30241. countMouseClicks(),
  30242. false);
  30243. mouseDown (me);
  30244. if (deletionChecker.hasBeenDeleted())
  30245. return;
  30246. Desktop::getInstance().resetTimer();
  30247. for (int i = Desktop::getInstance().mouseListeners.size(); --i >= 0;)
  30248. {
  30249. ((MouseListener*) Desktop::getInstance().mouseListeners[i])->mouseDown (me);
  30250. if (deletionChecker.hasBeenDeleted())
  30251. return;
  30252. i = jmin (i, Desktop::getInstance().mouseListeners.size());
  30253. }
  30254. if (mouseListeners_ != 0)
  30255. {
  30256. for (int i = mouseListeners_->size(); --i >= 0;)
  30257. {
  30258. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseDown (me);
  30259. if (deletionChecker.hasBeenDeleted())
  30260. return;
  30261. i = jmin (i, mouseListeners_->size());
  30262. }
  30263. }
  30264. const Component* p = parentComponent_;
  30265. while (p != 0)
  30266. {
  30267. const ComponentDeletionWatcher parentDeletionChecker (p);
  30268. for (int i = p->numDeepMouseListeners; --i >= 0;)
  30269. {
  30270. ((MouseListener*) (p->mouseListeners_->getUnchecked (i)))->mouseDown (me);
  30271. if (deletionChecker.hasBeenDeleted() || parentDeletionChecker.hasBeenDeleted())
  30272. return;
  30273. i = jmin (i, p->numDeepMouseListeners);
  30274. }
  30275. p = p->parentComponent_;
  30276. }
  30277. }
  30278. }
  30279. void Component::internalMouseUp (const int oldModifiers, int x, int y, const int64 time)
  30280. {
  30281. if (isValidComponent() && flags.draggingFlag)
  30282. {
  30283. flags.draggingFlag = false;
  30284. deleteAndZero (dragRepeater);
  30285. x += unboundedMouseOffsetX;
  30286. y += unboundedMouseOffsetY;
  30287. juce_LastMousePosX = x;
  30288. juce_LastMousePosY = y;
  30289. relativePositionToGlobal (juce_LastMousePosX, juce_LastMousePosY);
  30290. const ComponentDeletionWatcher deletionChecker (this);
  30291. if (flags.repaintOnMouseActivityFlag)
  30292. repaint();
  30293. int mdx = juce_recentMouseDownX[0];
  30294. int mdy = juce_recentMouseDownY[0];
  30295. globalPositionToRelative (mdx, mdy);
  30296. const MouseEvent me (x, y,
  30297. oldModifiers,
  30298. this,
  30299. Time (time),
  30300. mdx, mdy,
  30301. Time (juce_recentMouseDownTimes [0]),
  30302. countMouseClicks(),
  30303. juce_MouseHasMovedSignificantlySincePressed
  30304. || juce_recentMouseDownTimes[0] + 300 < time);
  30305. mouseUp (me);
  30306. if (deletionChecker.hasBeenDeleted())
  30307. return;
  30308. Desktop::getInstance().resetTimer();
  30309. for (int i = Desktop::getInstance().mouseListeners.size(); --i >= 0;)
  30310. {
  30311. ((MouseListener*) Desktop::getInstance().mouseListeners[i])->mouseUp (me);
  30312. if (deletionChecker.hasBeenDeleted())
  30313. return;
  30314. i = jmin (i, Desktop::getInstance().mouseListeners.size());
  30315. }
  30316. if (mouseListeners_ != 0)
  30317. {
  30318. for (int i = mouseListeners_->size(); --i >= 0;)
  30319. {
  30320. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseUp (me);
  30321. if (deletionChecker.hasBeenDeleted())
  30322. return;
  30323. i = jmin (i, mouseListeners_->size());
  30324. }
  30325. }
  30326. {
  30327. const Component* p = parentComponent_;
  30328. while (p != 0)
  30329. {
  30330. const ComponentDeletionWatcher parentDeletionChecker (p);
  30331. for (int i = p->numDeepMouseListeners; --i >= 0;)
  30332. {
  30333. ((MouseListener*) (p->mouseListeners_->getUnchecked (i)))->mouseUp (me);
  30334. if (deletionChecker.hasBeenDeleted() || parentDeletionChecker.hasBeenDeleted())
  30335. return;
  30336. i = jmin (i, p->numDeepMouseListeners);
  30337. }
  30338. p = p->parentComponent_;
  30339. }
  30340. }
  30341. // check for double-click
  30342. if (me.getNumberOfClicks() >= 2)
  30343. {
  30344. const int numListeners = (mouseListeners_ != 0) ? mouseListeners_->size() : 0;
  30345. mouseDoubleClick (me);
  30346. int i;
  30347. for (i = Desktop::getInstance().mouseListeners.size(); --i >= 0;)
  30348. {
  30349. ((MouseListener*) Desktop::getInstance().mouseListeners[i])->mouseDoubleClick (me);
  30350. if (deletionChecker.hasBeenDeleted())
  30351. return;
  30352. i = jmin (i, Desktop::getInstance().mouseListeners.size());
  30353. }
  30354. for (i = numListeners; --i >= 0;)
  30355. {
  30356. if (deletionChecker.hasBeenDeleted() || mouseListeners_ == 0)
  30357. return;
  30358. MouseListener* const ml = (MouseListener*)((*mouseListeners_)[i]);
  30359. if (ml != 0)
  30360. ml->mouseDoubleClick (me);
  30361. }
  30362. if (deletionChecker.hasBeenDeleted())
  30363. return;
  30364. const Component* p = parentComponent_;
  30365. while (p != 0)
  30366. {
  30367. const ComponentDeletionWatcher parentDeletionChecker (p);
  30368. for (i = p->numDeepMouseListeners; --i >= 0;)
  30369. {
  30370. ((MouseListener*) (p->mouseListeners_->getUnchecked (i)))->mouseDoubleClick (me);
  30371. if (deletionChecker.hasBeenDeleted() || parentDeletionChecker.hasBeenDeleted())
  30372. return;
  30373. i = jmin (i, p->numDeepMouseListeners);
  30374. }
  30375. p = p->parentComponent_;
  30376. }
  30377. }
  30378. }
  30379. enableUnboundedMouseMovement (false);
  30380. }
  30381. void Component::internalMouseDrag (int x, int y, const int64 time)
  30382. {
  30383. if (isValidComponent() && flags.draggingFlag)
  30384. {
  30385. flags.mouseOverFlag = reallyContains (x, y, false);
  30386. x += unboundedMouseOffsetX;
  30387. y += unboundedMouseOffsetY;
  30388. juce_LastMousePosX = x;
  30389. juce_LastMousePosY = y;
  30390. relativePositionToGlobal (juce_LastMousePosX, juce_LastMousePosY);
  30391. juce_MouseHasMovedSignificantlySincePressed
  30392. = juce_MouseHasMovedSignificantlySincePressed
  30393. || abs (juce_recentMouseDownX[0] - juce_LastMousePosX) >= 4
  30394. || abs (juce_recentMouseDownY[0] - juce_LastMousePosY) >= 4;
  30395. const ComponentDeletionWatcher deletionChecker (this);
  30396. int mdx = juce_recentMouseDownX[0];
  30397. int mdy = juce_recentMouseDownY[0];
  30398. globalPositionToRelative (mdx, mdy);
  30399. const MouseEvent me (x, y,
  30400. ModifierKeys::getCurrentModifiers(),
  30401. this,
  30402. Time (time),
  30403. mdx, mdy,
  30404. Time (juce_recentMouseDownTimes[0]),
  30405. countMouseClicks(),
  30406. juce_MouseHasMovedSignificantlySincePressed
  30407. || juce_recentMouseDownTimes[0] + 300 < time);
  30408. mouseDrag (me);
  30409. if (deletionChecker.hasBeenDeleted())
  30410. return;
  30411. Desktop::getInstance().resetTimer();
  30412. for (int i = Desktop::getInstance().mouseListeners.size(); --i >= 0;)
  30413. {
  30414. ((MouseListener*) Desktop::getInstance().mouseListeners[i])->mouseDrag (me);
  30415. if (deletionChecker.hasBeenDeleted())
  30416. return;
  30417. i = jmin (i, Desktop::getInstance().mouseListeners.size());
  30418. }
  30419. if (mouseListeners_ != 0)
  30420. {
  30421. for (int i = mouseListeners_->size(); --i >= 0;)
  30422. {
  30423. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseDrag (me);
  30424. if (deletionChecker.hasBeenDeleted())
  30425. return;
  30426. i = jmin (i, mouseListeners_->size());
  30427. }
  30428. }
  30429. const Component* p = parentComponent_;
  30430. while (p != 0)
  30431. {
  30432. const ComponentDeletionWatcher parentDeletionChecker (p);
  30433. for (int i = p->numDeepMouseListeners; --i >= 0;)
  30434. {
  30435. ((MouseListener*) (p->mouseListeners_->getUnchecked (i)))->mouseDrag (me);
  30436. if (deletionChecker.hasBeenDeleted() || parentDeletionChecker.hasBeenDeleted())
  30437. return;
  30438. i = jmin (i, p->numDeepMouseListeners);
  30439. }
  30440. p = p->parentComponent_;
  30441. }
  30442. if (this == componentUnderMouse)
  30443. {
  30444. if (isUnboundedMouseModeOn)
  30445. {
  30446. Rectangle screenArea (getParentMonitorArea().expanded (-2, -2));
  30447. int mx, my;
  30448. Desktop::getMousePosition (mx, my);
  30449. if (! screenArea.contains (mx, my))
  30450. {
  30451. int deltaX = 0, deltaY = 0;
  30452. if (mx <= screenArea.getX() || mx >= screenArea.getRight())
  30453. deltaX = getScreenX() + getWidth() / 2 - mx;
  30454. if (my <= screenArea.getY() || my >= screenArea.getBottom())
  30455. deltaY = getScreenY() + getHeight() / 2 - my;
  30456. unboundedMouseOffsetX -= deltaX;
  30457. unboundedMouseOffsetY -= deltaY;
  30458. Desktop::setMousePosition (mx + deltaX,
  30459. my + deltaY);
  30460. }
  30461. else if (isCursorVisibleUntilOffscreen
  30462. && (unboundedMouseOffsetX != 0 || unboundedMouseOffsetY != 0)
  30463. && screenArea.contains (mx + unboundedMouseOffsetX,
  30464. my + unboundedMouseOffsetY))
  30465. {
  30466. mx += unboundedMouseOffsetX;
  30467. my += unboundedMouseOffsetY;
  30468. unboundedMouseOffsetX = 0;
  30469. unboundedMouseOffsetY = 0;
  30470. Desktop::setMousePosition (mx, my);
  30471. }
  30472. }
  30473. internalUpdateMouseCursor (false);
  30474. }
  30475. }
  30476. }
  30477. void Component::internalMouseMove (const int x, const int y, const int64 time)
  30478. {
  30479. const ComponentDeletionWatcher deletionChecker (this);
  30480. if (isValidComponent())
  30481. {
  30482. const MouseEvent me (x, y,
  30483. ModifierKeys::getCurrentModifiers(),
  30484. this,
  30485. Time (time),
  30486. x, y,
  30487. Time (time),
  30488. 0, false);
  30489. if (isCurrentlyBlockedByAnotherModalComponent())
  30490. {
  30491. // allow blocked mouse-events to go to global listeners..
  30492. Desktop::getInstance().sendMouseMove();
  30493. }
  30494. else
  30495. {
  30496. if (this == componentUnderMouse)
  30497. internalUpdateMouseCursor (false);
  30498. flags.mouseOverFlag = true;
  30499. mouseMove (me);
  30500. if (deletionChecker.hasBeenDeleted())
  30501. return;
  30502. Desktop::getInstance().resetTimer();
  30503. for (int i = Desktop::getInstance().mouseListeners.size(); --i >= 0;)
  30504. {
  30505. ((MouseListener*) Desktop::getInstance().mouseListeners[i])->mouseMove (me);
  30506. if (deletionChecker.hasBeenDeleted())
  30507. return;
  30508. i = jmin (i, Desktop::getInstance().mouseListeners.size());
  30509. }
  30510. if (mouseListeners_ != 0)
  30511. {
  30512. for (int i = mouseListeners_->size(); --i >= 0;)
  30513. {
  30514. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseMove (me);
  30515. if (deletionChecker.hasBeenDeleted())
  30516. return;
  30517. i = jmin (i, mouseListeners_->size());
  30518. }
  30519. }
  30520. const Component* p = parentComponent_;
  30521. while (p != 0)
  30522. {
  30523. const ComponentDeletionWatcher parentDeletionChecker (p);
  30524. for (int i = p->numDeepMouseListeners; --i >= 0;)
  30525. {
  30526. ((MouseListener*) (p->mouseListeners_->getUnchecked (i)))->mouseMove (me);
  30527. if (deletionChecker.hasBeenDeleted() || parentDeletionChecker.hasBeenDeleted())
  30528. return;
  30529. i = jmin (i, p->numDeepMouseListeners);
  30530. }
  30531. p = p->parentComponent_;
  30532. }
  30533. }
  30534. }
  30535. }
  30536. void Component::internalMouseWheel (const int intAmountX, const int intAmountY, const int64 time)
  30537. {
  30538. const ComponentDeletionWatcher deletionChecker (this);
  30539. const float wheelIncrementX = intAmountX * (1.0f / 256.0f);
  30540. const float wheelIncrementY = intAmountY * (1.0f / 256.0f);
  30541. int mx, my;
  30542. getMouseXYRelative (mx, my);
  30543. const MouseEvent me (mx, my,
  30544. ModifierKeys::getCurrentModifiers(),
  30545. this,
  30546. Time (time),
  30547. mx, my,
  30548. Time (time),
  30549. 0, false);
  30550. if (isCurrentlyBlockedByAnotherModalComponent())
  30551. {
  30552. // allow blocked mouse-events to go to global listeners..
  30553. for (int i = Desktop::getInstance().mouseListeners.size(); --i >= 0;)
  30554. {
  30555. ((MouseListener*) Desktop::getInstance().mouseListeners[i])->mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  30556. if (deletionChecker.hasBeenDeleted())
  30557. return;
  30558. i = jmin (i, Desktop::getInstance().mouseListeners.size());
  30559. }
  30560. }
  30561. else
  30562. {
  30563. mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  30564. if (deletionChecker.hasBeenDeleted())
  30565. return;
  30566. for (int i = Desktop::getInstance().mouseListeners.size(); --i >= 0;)
  30567. {
  30568. ((MouseListener*) Desktop::getInstance().mouseListeners[i])->mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  30569. if (deletionChecker.hasBeenDeleted())
  30570. return;
  30571. i = jmin (i, Desktop::getInstance().mouseListeners.size());
  30572. }
  30573. if (mouseListeners_ != 0)
  30574. {
  30575. for (int i = mouseListeners_->size(); --i >= 0;)
  30576. {
  30577. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  30578. if (deletionChecker.hasBeenDeleted())
  30579. return;
  30580. i = jmin (i, mouseListeners_->size());
  30581. }
  30582. }
  30583. const Component* p = parentComponent_;
  30584. while (p != 0)
  30585. {
  30586. const ComponentDeletionWatcher parentDeletionChecker (p);
  30587. for (int i = p->numDeepMouseListeners; --i >= 0;)
  30588. {
  30589. ((MouseListener*) (p->mouseListeners_->getUnchecked (i)))->mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  30590. if (deletionChecker.hasBeenDeleted() || parentDeletionChecker.hasBeenDeleted())
  30591. return;
  30592. i = jmin (i, p->numDeepMouseListeners);
  30593. }
  30594. p = p->parentComponent_;
  30595. }
  30596. sendFakeMouseMove();
  30597. }
  30598. }
  30599. void Component::sendFakeMouseMove() const
  30600. {
  30601. ComponentPeer* const peer = getPeer();
  30602. if (peer != 0)
  30603. peer->sendFakeMouseMove();
  30604. }
  30605. void Component::broughtToFront()
  30606. {
  30607. }
  30608. void Component::internalBroughtToFront()
  30609. {
  30610. if (isValidComponent())
  30611. {
  30612. if (flags.hasHeavyweightPeerFlag)
  30613. Desktop::getInstance().componentBroughtToFront (this);
  30614. const ComponentDeletionWatcher deletionChecker (this);
  30615. broughtToFront();
  30616. if (deletionChecker.hasBeenDeleted())
  30617. return;
  30618. if (componentListeners_ != 0)
  30619. {
  30620. for (int i = componentListeners_->size(); --i >= 0;)
  30621. {
  30622. ((ComponentListener*) componentListeners_->getUnchecked (i))
  30623. ->componentBroughtToFront (*this);
  30624. if (deletionChecker.hasBeenDeleted())
  30625. return;
  30626. i = jmin (i, componentListeners_->size());
  30627. }
  30628. }
  30629. // when brought to the front and there's a modal component blocking this one,
  30630. // we need to bring the modal one to the front instead..
  30631. Component* const cm = getCurrentlyModalComponent();
  30632. if (cm != 0 && cm->getTopLevelComponent() != getTopLevelComponent())
  30633. {
  30634. cm->getTopLevelComponent()->toFront (false);
  30635. }
  30636. }
  30637. }
  30638. void Component::focusGained (FocusChangeType)
  30639. {
  30640. // base class does nothing
  30641. }
  30642. void Component::internalFocusGain (const FocusChangeType cause)
  30643. {
  30644. const ComponentDeletionWatcher deletionChecker (this);
  30645. focusGained (cause);
  30646. if (! deletionChecker.hasBeenDeleted())
  30647. internalChildFocusChange (cause);
  30648. }
  30649. void Component::focusLost (FocusChangeType)
  30650. {
  30651. // base class does nothing
  30652. }
  30653. void Component::internalFocusLoss (const FocusChangeType cause)
  30654. {
  30655. const ComponentDeletionWatcher deletionChecker (this);
  30656. focusLost (focusChangedDirectly);
  30657. if (! deletionChecker.hasBeenDeleted())
  30658. internalChildFocusChange (cause);
  30659. }
  30660. void Component::focusOfChildComponentChanged (FocusChangeType /*cause*/)
  30661. {
  30662. // base class does nothing
  30663. }
  30664. void Component::internalChildFocusChange (FocusChangeType cause)
  30665. {
  30666. const bool childIsNowFocused = hasKeyboardFocus (true);
  30667. if (flags.childCompFocusedFlag != childIsNowFocused)
  30668. {
  30669. flags.childCompFocusedFlag = childIsNowFocused;
  30670. const ComponentDeletionWatcher deletionChecker (this);
  30671. focusOfChildComponentChanged (cause);
  30672. if (deletionChecker.hasBeenDeleted())
  30673. return;
  30674. }
  30675. if (parentComponent_ != 0)
  30676. parentComponent_->internalChildFocusChange (cause);
  30677. }
  30678. bool Component::isEnabled() const throw()
  30679. {
  30680. return (! flags.isDisabledFlag)
  30681. && (parentComponent_ == 0 || parentComponent_->isEnabled());
  30682. }
  30683. void Component::setEnabled (const bool shouldBeEnabled)
  30684. {
  30685. if (flags.isDisabledFlag == shouldBeEnabled)
  30686. {
  30687. flags.isDisabledFlag = ! shouldBeEnabled;
  30688. // if any parent components are disabled, setting our flag won't make a difference,
  30689. // so no need to send a change message
  30690. if (parentComponent_ == 0 || parentComponent_->isEnabled())
  30691. sendEnablementChangeMessage();
  30692. }
  30693. }
  30694. void Component::sendEnablementChangeMessage()
  30695. {
  30696. const ComponentDeletionWatcher deletionChecker (this);
  30697. enablementChanged();
  30698. if (deletionChecker.hasBeenDeleted())
  30699. return;
  30700. for (int i = getNumChildComponents(); --i >= 0;)
  30701. {
  30702. Component* const c = getChildComponent (i);
  30703. if (c != 0)
  30704. {
  30705. c->sendEnablementChangeMessage();
  30706. if (deletionChecker.hasBeenDeleted())
  30707. return;
  30708. }
  30709. }
  30710. }
  30711. void Component::enablementChanged()
  30712. {
  30713. }
  30714. void Component::setWantsKeyboardFocus (const bool wantsFocus) throw()
  30715. {
  30716. flags.wantsFocusFlag = wantsFocus;
  30717. }
  30718. void Component::setMouseClickGrabsKeyboardFocus (const bool shouldGrabFocus)
  30719. {
  30720. flags.dontFocusOnMouseClickFlag = ! shouldGrabFocus;
  30721. }
  30722. bool Component::getMouseClickGrabsKeyboardFocus() const throw()
  30723. {
  30724. return ! flags.dontFocusOnMouseClickFlag;
  30725. }
  30726. bool Component::getWantsKeyboardFocus() const throw()
  30727. {
  30728. return flags.wantsFocusFlag && ! flags.isDisabledFlag;
  30729. }
  30730. void Component::setFocusContainer (const bool isFocusContainer) throw()
  30731. {
  30732. flags.isFocusContainerFlag = isFocusContainer;
  30733. }
  30734. bool Component::isFocusContainer() const throw()
  30735. {
  30736. return flags.isFocusContainerFlag;
  30737. }
  30738. int Component::getExplicitFocusOrder() const throw()
  30739. {
  30740. return getComponentPropertyInt (T("_jexfo"), false, 0);
  30741. }
  30742. void Component::setExplicitFocusOrder (const int newFocusOrderIndex) throw()
  30743. {
  30744. setComponentProperty (T("_jexfo"), newFocusOrderIndex);
  30745. }
  30746. KeyboardFocusTraverser* Component::createFocusTraverser()
  30747. {
  30748. if (flags.isFocusContainerFlag || parentComponent_ == 0)
  30749. return new KeyboardFocusTraverser();
  30750. return parentComponent_->createFocusTraverser();
  30751. }
  30752. void Component::takeKeyboardFocus (const FocusChangeType cause)
  30753. {
  30754. // give the focus to this component
  30755. if (currentlyFocusedComponent != this)
  30756. {
  30757. JUCE_TRY
  30758. {
  30759. // get the focus onto our desktop window
  30760. ComponentPeer* const peer = getPeer();
  30761. if (peer != 0)
  30762. {
  30763. const ComponentDeletionWatcher deletionChecker (this);
  30764. peer->grabFocus();
  30765. if (peer->isFocused() && currentlyFocusedComponent != this)
  30766. {
  30767. Component* const componentLosingFocus = currentlyFocusedComponent;
  30768. currentlyFocusedComponent = this;
  30769. Desktop::getInstance().triggerFocusCallback();
  30770. // call this after setting currentlyFocusedComponent so that the one that's
  30771. // losing it has a chance to see where focus is going
  30772. if (componentLosingFocus->isValidComponent())
  30773. componentLosingFocus->internalFocusLoss (cause);
  30774. if (currentlyFocusedComponent == this)
  30775. {
  30776. focusGained (cause);
  30777. if (! deletionChecker.hasBeenDeleted())
  30778. internalChildFocusChange (cause);
  30779. }
  30780. }
  30781. }
  30782. }
  30783. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  30784. catch (const std::exception& e)
  30785. {
  30786. currentlyFocusedComponent = 0;
  30787. Desktop::getInstance().triggerFocusCallback();
  30788. JUCEApplication::sendUnhandledException (&e, __FILE__, __LINE__);
  30789. }
  30790. catch (...)
  30791. {
  30792. currentlyFocusedComponent = 0;
  30793. Desktop::getInstance().triggerFocusCallback();
  30794. JUCEApplication::sendUnhandledException (0, __FILE__, __LINE__);
  30795. }
  30796. #endif
  30797. }
  30798. }
  30799. void Component::grabFocusInternal (const FocusChangeType cause, const bool canTryParent)
  30800. {
  30801. if (isShowing())
  30802. {
  30803. if (flags.wantsFocusFlag && (isEnabled() || parentComponent_ == 0))
  30804. {
  30805. takeKeyboardFocus (cause);
  30806. }
  30807. else
  30808. {
  30809. if (isParentOf (currentlyFocusedComponent)
  30810. && currentlyFocusedComponent->isShowing())
  30811. {
  30812. // do nothing if the focused component is actually a child of ours..
  30813. }
  30814. else
  30815. {
  30816. // find the default child component..
  30817. KeyboardFocusTraverser* const traverser = createFocusTraverser();
  30818. if (traverser != 0)
  30819. {
  30820. Component* const defaultComp = traverser->getDefaultComponent (this);
  30821. delete traverser;
  30822. if (defaultComp != 0)
  30823. {
  30824. defaultComp->grabFocusInternal (cause, false);
  30825. return;
  30826. }
  30827. }
  30828. if (canTryParent && parentComponent_ != 0)
  30829. {
  30830. // if no children want it and we're allowed to try our parent comp,
  30831. // then pass up to parent, which will try our siblings.
  30832. parentComponent_->grabFocusInternal (cause, true);
  30833. }
  30834. }
  30835. }
  30836. }
  30837. }
  30838. void Component::grabKeyboardFocus()
  30839. {
  30840. // if component methods are being called from threads other than the message
  30841. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  30842. checkMessageManagerIsLocked
  30843. grabFocusInternal (focusChangedDirectly);
  30844. }
  30845. void Component::moveKeyboardFocusToSibling (const bool moveToNext)
  30846. {
  30847. // if component methods are being called from threads other than the message
  30848. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  30849. checkMessageManagerIsLocked
  30850. if (parentComponent_ != 0)
  30851. {
  30852. KeyboardFocusTraverser* const traverser = createFocusTraverser();
  30853. if (traverser != 0)
  30854. {
  30855. Component* const nextComp = moveToNext ? traverser->getNextComponent (this)
  30856. : traverser->getPreviousComponent (this);
  30857. delete traverser;
  30858. if (nextComp != 0)
  30859. {
  30860. if (nextComp->isCurrentlyBlockedByAnotherModalComponent())
  30861. {
  30862. const ComponentDeletionWatcher deletionChecker (nextComp);
  30863. internalModalInputAttempt();
  30864. if (deletionChecker.hasBeenDeleted()
  30865. || nextComp->isCurrentlyBlockedByAnotherModalComponent())
  30866. return;
  30867. }
  30868. nextComp->grabFocusInternal (focusChangedByTabKey);
  30869. return;
  30870. }
  30871. }
  30872. parentComponent_->moveKeyboardFocusToSibling (moveToNext);
  30873. }
  30874. }
  30875. bool Component::hasKeyboardFocus (const bool trueIfChildIsFocused) const throw()
  30876. {
  30877. return (currentlyFocusedComponent == this)
  30878. || (trueIfChildIsFocused && isParentOf (currentlyFocusedComponent));
  30879. }
  30880. Component* JUCE_CALLTYPE Component::getCurrentlyFocusedComponent() throw()
  30881. {
  30882. return currentlyFocusedComponent;
  30883. }
  30884. void Component::giveAwayFocus()
  30885. {
  30886. // use a copy so we can clear the value before the call
  30887. Component* const componentLosingFocus = currentlyFocusedComponent;
  30888. currentlyFocusedComponent = 0;
  30889. Desktop::getInstance().triggerFocusCallback();
  30890. if (componentLosingFocus->isValidComponent())
  30891. componentLosingFocus->internalFocusLoss (focusChangedDirectly);
  30892. }
  30893. bool Component::isMouseOver() const throw()
  30894. {
  30895. return flags.mouseOverFlag;
  30896. }
  30897. bool Component::isMouseButtonDown() const throw()
  30898. {
  30899. return flags.draggingFlag;
  30900. }
  30901. bool Component::isMouseOverOrDragging() const throw()
  30902. {
  30903. return flags.mouseOverFlag || flags.draggingFlag;
  30904. }
  30905. bool JUCE_CALLTYPE Component::isMouseButtonDownAnywhere() throw()
  30906. {
  30907. return ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown();
  30908. }
  30909. void Component::getMouseXYRelative (int& mx, int& my) const throw()
  30910. {
  30911. Desktop::getMousePosition (mx, my);
  30912. globalPositionToRelative (mx, my);
  30913. mx += unboundedMouseOffsetX;
  30914. my += unboundedMouseOffsetY;
  30915. }
  30916. void Component::enableUnboundedMouseMovement (bool enable,
  30917. bool keepCursorVisibleUntilOffscreen) throw()
  30918. {
  30919. enable = enable && isMouseButtonDown();
  30920. isCursorVisibleUntilOffscreen = keepCursorVisibleUntilOffscreen;
  30921. if (enable != isUnboundedMouseModeOn)
  30922. {
  30923. if ((! enable) && ((! isCursorVisibleUntilOffscreen)
  30924. || unboundedMouseOffsetX != 0
  30925. || unboundedMouseOffsetY != 0))
  30926. {
  30927. // when released, return the mouse to within the component's bounds
  30928. int mx, my;
  30929. getMouseXYRelative (mx, my);
  30930. mx = jlimit (0, getWidth(), mx);
  30931. my = jlimit (0, getHeight(), my);
  30932. relativePositionToGlobal (mx, my);
  30933. Desktop::setMousePosition (mx, my);
  30934. }
  30935. isUnboundedMouseModeOn = enable;
  30936. unboundedMouseOffsetX = 0;
  30937. unboundedMouseOffsetY = 0;
  30938. internalUpdateMouseCursor (true);
  30939. }
  30940. }
  30941. Component* JUCE_CALLTYPE Component::getComponentUnderMouse() throw()
  30942. {
  30943. return componentUnderMouse;
  30944. }
  30945. const Rectangle Component::getParentMonitorArea() const throw()
  30946. {
  30947. int centreX = getWidth() / 2;
  30948. int centreY = getHeight() / 2;
  30949. relativePositionToGlobal (centreX, centreY);
  30950. return Desktop::getInstance().getMonitorAreaContaining (centreX, centreY);
  30951. }
  30952. void Component::addKeyListener (KeyListener* const newListener) throw()
  30953. {
  30954. if (keyListeners_ == 0)
  30955. keyListeners_ = new VoidArray (4);
  30956. keyListeners_->addIfNotAlreadyThere (newListener);
  30957. }
  30958. void Component::removeKeyListener (KeyListener* const listenerToRemove) throw()
  30959. {
  30960. if (keyListeners_ != 0)
  30961. keyListeners_->removeValue (listenerToRemove);
  30962. }
  30963. bool Component::keyPressed (const KeyPress&)
  30964. {
  30965. return false;
  30966. }
  30967. bool Component::keyStateChanged()
  30968. {
  30969. return false;
  30970. }
  30971. void Component::modifierKeysChanged (const ModifierKeys& modifiers)
  30972. {
  30973. if (parentComponent_ != 0)
  30974. parentComponent_->modifierKeysChanged (modifiers);
  30975. }
  30976. void Component::internalModifierKeysChanged()
  30977. {
  30978. sendFakeMouseMove();
  30979. modifierKeysChanged (ModifierKeys::getCurrentModifiers());
  30980. }
  30981. ComponentPeer* Component::getPeer() const throw()
  30982. {
  30983. if (flags.hasHeavyweightPeerFlag)
  30984. return ComponentPeer::getPeerFor (this);
  30985. else if (parentComponent_ != 0)
  30986. return parentComponent_->getPeer();
  30987. else
  30988. return 0;
  30989. }
  30990. const String Component::getComponentProperty (const String& keyName,
  30991. const bool useParentComponentIfNotFound,
  30992. const String& defaultReturnValue) const throw()
  30993. {
  30994. if (propertySet_ != 0 && ((! useParentComponentIfNotFound) || propertySet_->containsKey (keyName)))
  30995. return propertySet_->getValue (keyName, defaultReturnValue);
  30996. if (useParentComponentIfNotFound && (parentComponent_ != 0))
  30997. return parentComponent_->getComponentProperty (keyName, true, defaultReturnValue);
  30998. return defaultReturnValue;
  30999. }
  31000. int Component::getComponentPropertyInt (const String& keyName,
  31001. const bool useParentComponentIfNotFound,
  31002. const int defaultReturnValue) const throw()
  31003. {
  31004. if (propertySet_ != 0 && ((! useParentComponentIfNotFound) || propertySet_->containsKey (keyName)))
  31005. return propertySet_->getIntValue (keyName, defaultReturnValue);
  31006. if (useParentComponentIfNotFound && (parentComponent_ != 0))
  31007. return parentComponent_->getComponentPropertyInt (keyName, true, defaultReturnValue);
  31008. return defaultReturnValue;
  31009. }
  31010. double Component::getComponentPropertyDouble (const String& keyName,
  31011. const bool useParentComponentIfNotFound,
  31012. const double defaultReturnValue) const throw()
  31013. {
  31014. if (propertySet_ != 0 && ((! useParentComponentIfNotFound) || propertySet_->containsKey (keyName)))
  31015. return propertySet_->getDoubleValue (keyName, defaultReturnValue);
  31016. if (useParentComponentIfNotFound && (parentComponent_ != 0))
  31017. return parentComponent_->getComponentPropertyDouble (keyName, true, defaultReturnValue);
  31018. return defaultReturnValue;
  31019. }
  31020. bool Component::getComponentPropertyBool (const String& keyName,
  31021. const bool useParentComponentIfNotFound,
  31022. const bool defaultReturnValue) const throw()
  31023. {
  31024. if (propertySet_ != 0 && ((! useParentComponentIfNotFound) || propertySet_->containsKey (keyName)))
  31025. return propertySet_->getBoolValue (keyName, defaultReturnValue);
  31026. if (useParentComponentIfNotFound && (parentComponent_ != 0))
  31027. return parentComponent_->getComponentPropertyBool (keyName, true, defaultReturnValue);
  31028. return defaultReturnValue;
  31029. }
  31030. const Colour Component::getComponentPropertyColour (const String& keyName,
  31031. const bool useParentComponentIfNotFound,
  31032. const Colour& defaultReturnValue) const throw()
  31033. {
  31034. return Colour ((uint32) getComponentPropertyInt (keyName,
  31035. useParentComponentIfNotFound,
  31036. defaultReturnValue.getARGB()));
  31037. }
  31038. void Component::setComponentProperty (const String& keyName, const String& value) throw()
  31039. {
  31040. if (propertySet_ == 0)
  31041. propertySet_ = new PropertySet();
  31042. propertySet_->setValue (keyName, value);
  31043. }
  31044. void Component::setComponentProperty (const String& keyName, const int value) throw()
  31045. {
  31046. if (propertySet_ == 0)
  31047. propertySet_ = new PropertySet();
  31048. propertySet_->setValue (keyName, value);
  31049. }
  31050. void Component::setComponentProperty (const String& keyName, const double value) throw()
  31051. {
  31052. if (propertySet_ == 0)
  31053. propertySet_ = new PropertySet();
  31054. propertySet_->setValue (keyName, value);
  31055. }
  31056. void Component::setComponentProperty (const String& keyName, const bool value) throw()
  31057. {
  31058. if (propertySet_ == 0)
  31059. propertySet_ = new PropertySet();
  31060. propertySet_->setValue (keyName, value);
  31061. }
  31062. void Component::setComponentProperty (const String& keyName, const Colour& colour) throw()
  31063. {
  31064. setComponentProperty (keyName, (int) colour.getARGB());
  31065. }
  31066. void Component::removeComponentProperty (const String& keyName) throw()
  31067. {
  31068. if (propertySet_ != 0)
  31069. propertySet_->removeValue (keyName);
  31070. }
  31071. ComponentDeletionWatcher::ComponentDeletionWatcher (const Component* const componentToWatch_) throw()
  31072. : componentToWatch (componentToWatch_),
  31073. componentUID (componentToWatch_->getComponentUID())
  31074. {
  31075. // not possible to check on an already-deleted object..
  31076. jassert (componentToWatch_->isValidComponent());
  31077. }
  31078. ComponentDeletionWatcher::~ComponentDeletionWatcher() throw() {}
  31079. bool ComponentDeletionWatcher::hasBeenDeleted() const throw()
  31080. {
  31081. return ! (componentToWatch->isValidComponent()
  31082. && componentToWatch->getComponentUID() == componentUID);
  31083. }
  31084. const Component* ComponentDeletionWatcher::getComponent() const throw()
  31085. {
  31086. return hasBeenDeleted() ? 0 : componentToWatch;
  31087. }
  31088. END_JUCE_NAMESPACE
  31089. /********* End of inlined file: juce_Component.cpp *********/
  31090. /********* Start of inlined file: juce_ComponentListener.cpp *********/
  31091. BEGIN_JUCE_NAMESPACE
  31092. void ComponentListener::componentMovedOrResized (Component&, bool, bool)
  31093. {
  31094. }
  31095. void ComponentListener::componentBroughtToFront (Component&)
  31096. {
  31097. }
  31098. void ComponentListener::componentVisibilityChanged (Component&)
  31099. {
  31100. }
  31101. void ComponentListener::componentChildrenChanged (Component&)
  31102. {
  31103. }
  31104. void ComponentListener::componentParentHierarchyChanged (Component&)
  31105. {
  31106. }
  31107. void ComponentListener::componentNameChanged (Component&)
  31108. {
  31109. }
  31110. END_JUCE_NAMESPACE
  31111. /********* End of inlined file: juce_ComponentListener.cpp *********/
  31112. /********* Start of inlined file: juce_Desktop.cpp *********/
  31113. BEGIN_JUCE_NAMESPACE
  31114. extern void juce_updateMultiMonitorInfo (Array <Rectangle>& monitorCoords,
  31115. const bool clipToWorkArea) throw();
  31116. static Desktop* juce_desktopInstance = 0;
  31117. Desktop::Desktop() throw()
  31118. : mouseListeners (2),
  31119. desktopComponents (4),
  31120. monitorCoordsClipped (2),
  31121. monitorCoordsUnclipped (2),
  31122. lastMouseX (0),
  31123. lastMouseY (0)
  31124. {
  31125. refreshMonitorSizes();
  31126. }
  31127. Desktop::~Desktop() throw()
  31128. {
  31129. jassert (juce_desktopInstance == this);
  31130. juce_desktopInstance = 0;
  31131. // doh! If you don't delete all your windows before exiting, you're going to
  31132. // be leaking memory!
  31133. jassert (desktopComponents.size() == 0);
  31134. }
  31135. Desktop& JUCE_CALLTYPE Desktop::getInstance() throw()
  31136. {
  31137. if (juce_desktopInstance == 0)
  31138. juce_desktopInstance = new Desktop();
  31139. return *juce_desktopInstance;
  31140. }
  31141. void Desktop::refreshMonitorSizes() throw()
  31142. {
  31143. const Array <Rectangle> oldClipped (monitorCoordsClipped);
  31144. const Array <Rectangle> oldUnclipped (monitorCoordsUnclipped);
  31145. monitorCoordsClipped.clear();
  31146. monitorCoordsUnclipped.clear();
  31147. juce_updateMultiMonitorInfo (monitorCoordsClipped, true);
  31148. juce_updateMultiMonitorInfo (monitorCoordsUnclipped, false);
  31149. jassert (monitorCoordsClipped.size() > 0
  31150. && monitorCoordsClipped.size() == monitorCoordsUnclipped.size());
  31151. if (oldClipped != monitorCoordsClipped
  31152. || oldUnclipped != monitorCoordsUnclipped)
  31153. {
  31154. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  31155. {
  31156. ComponentPeer* const p = ComponentPeer::getPeer (i);
  31157. if (p != 0)
  31158. p->handleScreenSizeChange();
  31159. }
  31160. }
  31161. }
  31162. int Desktop::getNumDisplayMonitors() const throw()
  31163. {
  31164. return monitorCoordsClipped.size();
  31165. }
  31166. const Rectangle Desktop::getDisplayMonitorCoordinates (const int index, const bool clippedToWorkArea) const throw()
  31167. {
  31168. return clippedToWorkArea ? monitorCoordsClipped [index]
  31169. : monitorCoordsUnclipped [index];
  31170. }
  31171. const RectangleList Desktop::getAllMonitorDisplayAreas (const bool clippedToWorkArea) const throw()
  31172. {
  31173. RectangleList rl;
  31174. for (int i = 0; i < getNumDisplayMonitors(); ++i)
  31175. rl.addWithoutMerging (getDisplayMonitorCoordinates (i, clippedToWorkArea));
  31176. return rl;
  31177. }
  31178. const Rectangle Desktop::getMainMonitorArea (const bool clippedToWorkArea) const throw()
  31179. {
  31180. return getDisplayMonitorCoordinates (0, clippedToWorkArea);
  31181. }
  31182. const Rectangle Desktop::getMonitorAreaContaining (int cx, int cy, const bool clippedToWorkArea) const throw()
  31183. {
  31184. Rectangle best (getMainMonitorArea (clippedToWorkArea));
  31185. double bestDistance = 1.0e10;
  31186. for (int i = getNumDisplayMonitors(); --i >= 0;)
  31187. {
  31188. const Rectangle rect (getDisplayMonitorCoordinates (i, clippedToWorkArea));
  31189. if (rect.contains (cx, cy))
  31190. return rect;
  31191. const double distance = juce_hypot ((double) (rect.getCentreX() - cx),
  31192. (double) (rect.getCentreY() - cy));
  31193. if (distance < bestDistance)
  31194. {
  31195. bestDistance = distance;
  31196. best = rect;
  31197. }
  31198. }
  31199. return best;
  31200. }
  31201. int Desktop::getNumComponents() const throw()
  31202. {
  31203. return desktopComponents.size();
  31204. }
  31205. Component* Desktop::getComponent (const int index) const throw()
  31206. {
  31207. return (Component*) desktopComponents [index];
  31208. }
  31209. Component* Desktop::findComponentAt (const int screenX,
  31210. const int screenY) const
  31211. {
  31212. for (int i = desktopComponents.size(); --i >= 0;)
  31213. {
  31214. Component* const c = (Component*) desktopComponents.getUnchecked(i);
  31215. int x = screenX, y = screenY;
  31216. c->globalPositionToRelative (x, y);
  31217. if (c->contains (x, y))
  31218. return c->getComponentAt (x, y);
  31219. }
  31220. return 0;
  31221. }
  31222. void Desktop::addDesktopComponent (Component* const c) throw()
  31223. {
  31224. jassert (c != 0);
  31225. jassert (! desktopComponents.contains (c));
  31226. desktopComponents.addIfNotAlreadyThere (c);
  31227. }
  31228. void Desktop::removeDesktopComponent (Component* const c) throw()
  31229. {
  31230. desktopComponents.removeValue (c);
  31231. }
  31232. void Desktop::componentBroughtToFront (Component* const c) throw()
  31233. {
  31234. const int index = desktopComponents.indexOf (c);
  31235. jassert (index >= 0);
  31236. if (index >= 0)
  31237. desktopComponents.move (index, -1);
  31238. }
  31239. // from Component.cpp
  31240. extern int juce_recentMouseDownX [4];
  31241. extern int juce_recentMouseDownY [4];
  31242. extern int juce_MouseClickCounter;
  31243. void Desktop::getLastMouseDownPosition (int& x, int& y) throw()
  31244. {
  31245. x = juce_recentMouseDownX [0];
  31246. y = juce_recentMouseDownY [0];
  31247. }
  31248. int Desktop::getMouseButtonClickCounter() throw()
  31249. {
  31250. return juce_MouseClickCounter;
  31251. }
  31252. void Desktop::addGlobalMouseListener (MouseListener* const listener) throw()
  31253. {
  31254. jassert (listener != 0);
  31255. if (listener != 0)
  31256. {
  31257. mouseListeners.add (listener);
  31258. resetTimer();
  31259. }
  31260. }
  31261. void Desktop::removeGlobalMouseListener (MouseListener* const listener) throw()
  31262. {
  31263. mouseListeners.removeValue (listener);
  31264. resetTimer();
  31265. }
  31266. void Desktop::addFocusChangeListener (FocusChangeListener* const listener) throw()
  31267. {
  31268. jassert (listener != 0);
  31269. if (listener != 0)
  31270. focusListeners.add (listener);
  31271. }
  31272. void Desktop::removeFocusChangeListener (FocusChangeListener* const listener) throw()
  31273. {
  31274. focusListeners.removeValue (listener);
  31275. }
  31276. void Desktop::triggerFocusCallback() throw()
  31277. {
  31278. triggerAsyncUpdate();
  31279. }
  31280. void Desktop::handleAsyncUpdate()
  31281. {
  31282. for (int i = focusListeners.size(); --i >= 0;)
  31283. {
  31284. ((FocusChangeListener*) focusListeners.getUnchecked (i))->globalFocusChanged (Component::getCurrentlyFocusedComponent());
  31285. i = jmin (i, focusListeners.size());
  31286. }
  31287. }
  31288. void Desktop::timerCallback()
  31289. {
  31290. int x, y;
  31291. getMousePosition (x, y);
  31292. if (lastMouseX != x || lastMouseY != y)
  31293. sendMouseMove();
  31294. }
  31295. void Desktop::sendMouseMove()
  31296. {
  31297. if (mouseListeners.size() > 0)
  31298. {
  31299. startTimer (20);
  31300. int x, y;
  31301. getMousePosition (x, y);
  31302. lastMouseX = x;
  31303. lastMouseY = y;
  31304. Component* const target = findComponentAt (x, y);
  31305. if (target != 0)
  31306. {
  31307. target->globalPositionToRelative (x, y);
  31308. ComponentDeletionWatcher deletionChecker (target);
  31309. const MouseEvent me (x, y,
  31310. ModifierKeys::getCurrentModifiers(),
  31311. target,
  31312. Time::getCurrentTime(),
  31313. x, y,
  31314. Time::getCurrentTime(),
  31315. 0, false);
  31316. for (int i = mouseListeners.size(); --i >= 0;)
  31317. {
  31318. if (ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown())
  31319. ((MouseListener*) mouseListeners[i])->mouseDrag (me);
  31320. else
  31321. ((MouseListener*) mouseListeners[i])->mouseMove (me);
  31322. if (deletionChecker.hasBeenDeleted())
  31323. return;
  31324. i = jmin (i, mouseListeners.size());
  31325. }
  31326. }
  31327. }
  31328. }
  31329. void Desktop::resetTimer() throw()
  31330. {
  31331. if (mouseListeners.size() == 0)
  31332. stopTimer();
  31333. else
  31334. startTimer (100);
  31335. getMousePosition (lastMouseX, lastMouseY);
  31336. }
  31337. END_JUCE_NAMESPACE
  31338. /********* End of inlined file: juce_Desktop.cpp *********/
  31339. /********* Start of inlined file: juce_ArrowButton.cpp *********/
  31340. BEGIN_JUCE_NAMESPACE
  31341. ArrowButton::ArrowButton (const String& name,
  31342. float arrowDirectionInRadians,
  31343. const Colour& arrowColour)
  31344. : Button (name),
  31345. colour (arrowColour)
  31346. {
  31347. path.lineTo (0.0f, 1.0f);
  31348. path.lineTo (1.0f, 0.5f);
  31349. path.closeSubPath();
  31350. path.applyTransform (AffineTransform::rotation (float_Pi * 2.0f * arrowDirectionInRadians,
  31351. 0.5f, 0.5f));
  31352. setComponentEffect (&shadow);
  31353. buttonStateChanged();
  31354. }
  31355. ArrowButton::~ArrowButton()
  31356. {
  31357. }
  31358. void ArrowButton::paintButton (Graphics& g,
  31359. bool /*isMouseOverButton*/,
  31360. bool /*isButtonDown*/)
  31361. {
  31362. g.setColour (colour);
  31363. g.fillPath (path, path.getTransformToScaleToFit ((float) offset,
  31364. (float) offset,
  31365. (float) (getWidth() - 3),
  31366. (float) (getHeight() - 3),
  31367. false));
  31368. }
  31369. void ArrowButton::buttonStateChanged()
  31370. {
  31371. offset = (isDown()) ? 1 : 0;
  31372. shadow.setShadowProperties ((isDown()) ? 1.2f : 3.0f,
  31373. 0.3f, -1, 0);
  31374. }
  31375. END_JUCE_NAMESPACE
  31376. /********* End of inlined file: juce_ArrowButton.cpp *********/
  31377. /********* Start of inlined file: juce_Button.cpp *********/
  31378. BEGIN_JUCE_NAMESPACE
  31379. Button::Button (const String& name)
  31380. : Component (name),
  31381. shortcuts (2),
  31382. keySource (0),
  31383. text (name),
  31384. buttonListeners (2),
  31385. repeatTimer (0),
  31386. buttonPressTime (0),
  31387. lastTimeCallbackTime (0),
  31388. commandManagerToUse (0),
  31389. autoRepeatDelay (-1),
  31390. autoRepeatSpeed (0),
  31391. autoRepeatMinimumDelay (-1),
  31392. radioGroupId (0),
  31393. commandID (0),
  31394. connectedEdgeFlags (0),
  31395. buttonState (buttonNormal),
  31396. isOn (false),
  31397. clickTogglesState (false),
  31398. needsToRelease (false),
  31399. needsRepainting (false),
  31400. isKeyDown (false),
  31401. triggerOnMouseDown (false),
  31402. generateTooltip (false)
  31403. {
  31404. setWantsKeyboardFocus (true);
  31405. }
  31406. Button::~Button()
  31407. {
  31408. if (commandManagerToUse != 0)
  31409. commandManagerToUse->removeListener (this);
  31410. delete repeatTimer;
  31411. clearShortcuts();
  31412. }
  31413. void Button::setButtonText (const String& newText) throw()
  31414. {
  31415. if (text != newText)
  31416. {
  31417. text = newText;
  31418. repaint();
  31419. }
  31420. }
  31421. void Button::setTooltip (const String& newTooltip)
  31422. {
  31423. SettableTooltipClient::setTooltip (newTooltip);
  31424. generateTooltip = false;
  31425. }
  31426. const String Button::getTooltip()
  31427. {
  31428. if (generateTooltip && commandManagerToUse != 0 && commandID != 0)
  31429. {
  31430. String tt (commandManagerToUse->getDescriptionOfCommand (commandID));
  31431. Array <KeyPress> keyPresses (commandManagerToUse->getKeyMappings()->getKeyPressesAssignedToCommand (commandID));
  31432. for (int i = 0; i < keyPresses.size(); ++i)
  31433. {
  31434. const String key (keyPresses.getReference(i).getTextDescription());
  31435. if (key.length() == 1)
  31436. tt << " [shortcut: '" << key << "']";
  31437. else
  31438. tt << " [" << key << ']';
  31439. }
  31440. return tt;
  31441. }
  31442. return SettableTooltipClient::getTooltip();
  31443. }
  31444. void Button::setConnectedEdges (const int connectedEdgeFlags_) throw()
  31445. {
  31446. if (connectedEdgeFlags != connectedEdgeFlags_)
  31447. {
  31448. connectedEdgeFlags = connectedEdgeFlags_;
  31449. repaint();
  31450. }
  31451. }
  31452. void Button::setToggleState (const bool shouldBeOn,
  31453. const bool sendChangeNotification)
  31454. {
  31455. if (shouldBeOn != isOn)
  31456. {
  31457. const ComponentDeletionWatcher deletionWatcher (this);
  31458. isOn = shouldBeOn;
  31459. repaint();
  31460. if (sendChangeNotification)
  31461. sendClickMessage (ModifierKeys());
  31462. if ((! deletionWatcher.hasBeenDeleted()) && isOn)
  31463. turnOffOtherButtonsInGroup (sendChangeNotification);
  31464. }
  31465. }
  31466. void Button::setClickingTogglesState (const bool shouldToggle) throw()
  31467. {
  31468. clickTogglesState = shouldToggle;
  31469. // if you've got clickTogglesState turned on, you shouldn't also connect the button
  31470. // up to be a command invoker. Instead, your command handler must flip the state of whatever
  31471. // it is that this button represents, and the button will update its state to reflect this
  31472. // in the applicationCommandListChanged() method.
  31473. jassert (commandManagerToUse == 0 || ! clickTogglesState);
  31474. }
  31475. bool Button::getClickingTogglesState() const throw()
  31476. {
  31477. return clickTogglesState;
  31478. }
  31479. void Button::setRadioGroupId (const int newGroupId)
  31480. {
  31481. if (radioGroupId != newGroupId)
  31482. {
  31483. radioGroupId = newGroupId;
  31484. if (isOn)
  31485. turnOffOtherButtonsInGroup (true);
  31486. }
  31487. }
  31488. void Button::turnOffOtherButtonsInGroup (const bool sendChangeNotification)
  31489. {
  31490. Component* const p = getParentComponent();
  31491. if (p != 0 && radioGroupId != 0)
  31492. {
  31493. const ComponentDeletionWatcher deletionWatcher (this);
  31494. for (int i = p->getNumChildComponents(); --i >= 0;)
  31495. {
  31496. Component* const c = p->getChildComponent (i);
  31497. if (c != this)
  31498. {
  31499. Button* const b = dynamic_cast <Button*> (c);
  31500. if (b != 0 && b->getRadioGroupId() == radioGroupId)
  31501. {
  31502. b->setToggleState (false, sendChangeNotification);
  31503. if (deletionWatcher.hasBeenDeleted())
  31504. return;
  31505. }
  31506. }
  31507. }
  31508. }
  31509. }
  31510. void Button::enablementChanged()
  31511. {
  31512. updateState (0);
  31513. repaint();
  31514. }
  31515. Button::ButtonState Button::updateState (const MouseEvent* const e) throw()
  31516. {
  31517. ButtonState state = buttonNormal;
  31518. if (isEnabled() && isVisible() && ! isCurrentlyBlockedByAnotherModalComponent())
  31519. {
  31520. int mx, my;
  31521. if (e == 0)
  31522. {
  31523. getMouseXYRelative (mx, my);
  31524. }
  31525. else
  31526. {
  31527. const MouseEvent e2 (e->getEventRelativeTo (this));
  31528. mx = e2.x;
  31529. my = e2.y;
  31530. }
  31531. const bool over = reallyContains (mx, my, true);
  31532. const bool down = isMouseButtonDown();
  31533. if ((down && (over || (triggerOnMouseDown && buttonState == buttonDown))) || isKeyDown)
  31534. state = buttonDown;
  31535. else if (over)
  31536. state = buttonOver;
  31537. }
  31538. setState (state);
  31539. return state;
  31540. }
  31541. void Button::setState (const ButtonState newState)
  31542. {
  31543. if (buttonState != newState)
  31544. {
  31545. buttonState = newState;
  31546. repaint();
  31547. if (buttonState == buttonDown)
  31548. {
  31549. buttonPressTime = Time::getApproximateMillisecondCounter();
  31550. lastTimeCallbackTime = buttonPressTime;
  31551. }
  31552. sendStateMessage();
  31553. }
  31554. }
  31555. bool Button::isDown() const throw()
  31556. {
  31557. return buttonState == buttonDown;
  31558. }
  31559. bool Button::isOver() const throw()
  31560. {
  31561. return buttonState != buttonNormal;
  31562. }
  31563. void Button::buttonStateChanged()
  31564. {
  31565. }
  31566. uint32 Button::getMillisecondsSinceButtonDown() const throw()
  31567. {
  31568. const uint32 now = Time::getApproximateMillisecondCounter();
  31569. return now > buttonPressTime ? now - buttonPressTime : 0;
  31570. }
  31571. void Button::setTriggeredOnMouseDown (const bool isTriggeredOnMouseDown) throw()
  31572. {
  31573. triggerOnMouseDown = isTriggeredOnMouseDown;
  31574. }
  31575. void Button::clicked()
  31576. {
  31577. }
  31578. void Button::clicked (const ModifierKeys& /*modifiers*/)
  31579. {
  31580. clicked();
  31581. }
  31582. static const int clickMessageId = 0x2f3f4f99;
  31583. void Button::triggerClick()
  31584. {
  31585. postCommandMessage (clickMessageId);
  31586. }
  31587. void Button::internalClickCallback (const ModifierKeys& modifiers)
  31588. {
  31589. if (clickTogglesState)
  31590. setToggleState ((radioGroupId != 0) || ! isOn, false);
  31591. sendClickMessage (modifiers);
  31592. }
  31593. void Button::flashButtonState() throw()
  31594. {
  31595. if (isEnabled())
  31596. {
  31597. needsToRelease = true;
  31598. setState (buttonDown);
  31599. getRepeatTimer().startTimer (100);
  31600. }
  31601. }
  31602. void Button::handleCommandMessage (int commandId)
  31603. {
  31604. if (commandId == clickMessageId)
  31605. {
  31606. if (isEnabled())
  31607. {
  31608. flashButtonState();
  31609. internalClickCallback (ModifierKeys::getCurrentModifiers());
  31610. }
  31611. }
  31612. else
  31613. {
  31614. Component::handleCommandMessage (commandId);
  31615. }
  31616. }
  31617. void Button::addButtonListener (ButtonListener* const newListener) throw()
  31618. {
  31619. jassert (newListener != 0);
  31620. jassert (! buttonListeners.contains (newListener)); // trying to add a listener to the list twice!
  31621. if (newListener != 0)
  31622. buttonListeners.add (newListener);
  31623. }
  31624. void Button::removeButtonListener (ButtonListener* const listener) throw()
  31625. {
  31626. jassert (buttonListeners.contains (listener)); // trying to remove a listener that isn't on the list!
  31627. buttonListeners.removeValue (listener);
  31628. }
  31629. void Button::sendClickMessage (const ModifierKeys& modifiers)
  31630. {
  31631. const ComponentDeletionWatcher cdw (this);
  31632. if (commandManagerToUse != 0 && commandID != 0)
  31633. {
  31634. ApplicationCommandTarget::InvocationInfo info (commandID);
  31635. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromButton;
  31636. info.originatingComponent = this;
  31637. commandManagerToUse->invoke (info, true);
  31638. }
  31639. clicked (modifiers);
  31640. if (! cdw.hasBeenDeleted())
  31641. {
  31642. for (int i = buttonListeners.size(); --i >= 0;)
  31643. {
  31644. ButtonListener* const bl = (ButtonListener*) buttonListeners[i];
  31645. if (bl != 0)
  31646. {
  31647. bl->buttonClicked (this);
  31648. if (cdw.hasBeenDeleted())
  31649. return;
  31650. }
  31651. }
  31652. }
  31653. }
  31654. void Button::sendStateMessage()
  31655. {
  31656. const ComponentDeletionWatcher cdw (this);
  31657. buttonStateChanged();
  31658. if (cdw.hasBeenDeleted())
  31659. return;
  31660. for (int i = buttonListeners.size(); --i >= 0;)
  31661. {
  31662. ButtonListener* const bl = (ButtonListener*) buttonListeners[i];
  31663. if (bl != 0)
  31664. {
  31665. bl->buttonStateChanged (this);
  31666. if (cdw.hasBeenDeleted())
  31667. return;
  31668. }
  31669. }
  31670. }
  31671. void Button::paint (Graphics& g)
  31672. {
  31673. if (needsToRelease && isEnabled())
  31674. {
  31675. needsToRelease = false;
  31676. needsRepainting = true;
  31677. }
  31678. paintButton (g, isOver(), isDown());
  31679. }
  31680. void Button::mouseEnter (const MouseEvent& e)
  31681. {
  31682. updateState (&e);
  31683. }
  31684. void Button::mouseExit (const MouseEvent& e)
  31685. {
  31686. updateState (&e);
  31687. }
  31688. void Button::mouseDown (const MouseEvent& e)
  31689. {
  31690. updateState (&e);
  31691. if (isDown())
  31692. {
  31693. if (autoRepeatDelay >= 0)
  31694. getRepeatTimer().startTimer (autoRepeatDelay);
  31695. if (triggerOnMouseDown)
  31696. internalClickCallback (e.mods);
  31697. }
  31698. }
  31699. void Button::mouseUp (const MouseEvent& e)
  31700. {
  31701. const bool wasDown = isDown();
  31702. updateState (&e);
  31703. if (wasDown && isOver() && ! triggerOnMouseDown)
  31704. internalClickCallback (e.mods);
  31705. }
  31706. void Button::mouseDrag (const MouseEvent& e)
  31707. {
  31708. const ButtonState oldState = buttonState;
  31709. updateState (&e);
  31710. if (autoRepeatDelay >= 0 && buttonState != oldState && isDown())
  31711. getRepeatTimer().startTimer (autoRepeatSpeed);
  31712. }
  31713. void Button::focusGained (FocusChangeType)
  31714. {
  31715. updateState (0);
  31716. repaint();
  31717. }
  31718. void Button::focusLost (FocusChangeType)
  31719. {
  31720. updateState (0);
  31721. repaint();
  31722. }
  31723. void Button::setVisible (bool shouldBeVisible)
  31724. {
  31725. if (shouldBeVisible != isVisible())
  31726. {
  31727. Component::setVisible (shouldBeVisible);
  31728. if (! shouldBeVisible)
  31729. needsToRelease = false;
  31730. updateState (0);
  31731. }
  31732. else
  31733. {
  31734. Component::setVisible (shouldBeVisible);
  31735. }
  31736. }
  31737. void Button::parentHierarchyChanged()
  31738. {
  31739. Component* const newKeySource = (shortcuts.size() == 0) ? 0 : getTopLevelComponent();
  31740. if (newKeySource != keySource)
  31741. {
  31742. if (keySource->isValidComponent())
  31743. keySource->removeKeyListener (this);
  31744. keySource = newKeySource;
  31745. if (keySource->isValidComponent())
  31746. keySource->addKeyListener (this);
  31747. }
  31748. }
  31749. void Button::setCommandToTrigger (ApplicationCommandManager* const commandManagerToUse_,
  31750. const int commandID_,
  31751. const bool generateTooltip_)
  31752. {
  31753. commandID = commandID_;
  31754. generateTooltip = generateTooltip_;
  31755. if (commandManagerToUse != commandManagerToUse_)
  31756. {
  31757. if (commandManagerToUse != 0)
  31758. commandManagerToUse->removeListener (this);
  31759. commandManagerToUse = commandManagerToUse_;
  31760. if (commandManagerToUse != 0)
  31761. commandManagerToUse->addListener (this);
  31762. // if you've got clickTogglesState turned on, you shouldn't also connect the button
  31763. // up to be a command invoker. Instead, your command handler must flip the state of whatever
  31764. // it is that this button represents, and the button will update its state to reflect this
  31765. // in the applicationCommandListChanged() method.
  31766. jassert (commandManagerToUse == 0 || ! clickTogglesState);
  31767. }
  31768. if (commandManagerToUse != 0)
  31769. applicationCommandListChanged();
  31770. else
  31771. setEnabled (true);
  31772. }
  31773. void Button::applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info)
  31774. {
  31775. if (info.commandID == commandID
  31776. && (info.commandFlags & ApplicationCommandInfo::dontTriggerVisualFeedback) == 0)
  31777. {
  31778. flashButtonState();
  31779. }
  31780. }
  31781. void Button::applicationCommandListChanged()
  31782. {
  31783. if (commandManagerToUse != 0)
  31784. {
  31785. ApplicationCommandInfo info (0);
  31786. ApplicationCommandTarget* const target = commandManagerToUse->getTargetForCommand (commandID, info);
  31787. setEnabled (target != 0 && (info.flags & ApplicationCommandInfo::isDisabled) == 0);
  31788. if (target != 0)
  31789. setToggleState ((info.flags & ApplicationCommandInfo::isTicked) != 0, false);
  31790. }
  31791. }
  31792. void Button::addShortcut (const KeyPress& key)
  31793. {
  31794. if (key.isValid())
  31795. {
  31796. jassert (! isRegisteredForShortcut (key)); // already registered!
  31797. shortcuts.add (key);
  31798. parentHierarchyChanged();
  31799. }
  31800. }
  31801. void Button::clearShortcuts()
  31802. {
  31803. shortcuts.clear();
  31804. parentHierarchyChanged();
  31805. }
  31806. bool Button::isShortcutPressed() const throw()
  31807. {
  31808. if (! isCurrentlyBlockedByAnotherModalComponent())
  31809. {
  31810. for (int i = shortcuts.size(); --i >= 0;)
  31811. if (shortcuts.getReference(i).isCurrentlyDown())
  31812. return true;
  31813. }
  31814. return false;
  31815. }
  31816. bool Button::isRegisteredForShortcut (const KeyPress& key) const throw()
  31817. {
  31818. for (int i = shortcuts.size(); --i >= 0;)
  31819. if (key == shortcuts.getReference(i))
  31820. return true;
  31821. return false;
  31822. }
  31823. bool Button::keyStateChanged (Component*)
  31824. {
  31825. if (! isEnabled())
  31826. return false;
  31827. const bool wasDown = isKeyDown;
  31828. isKeyDown = isShortcutPressed();
  31829. if (autoRepeatDelay >= 0 && (isKeyDown && ! wasDown))
  31830. getRepeatTimer().startTimer (autoRepeatDelay);
  31831. updateState (0);
  31832. if (isEnabled() && wasDown && ! isKeyDown)
  31833. internalClickCallback (ModifierKeys::getCurrentModifiers());
  31834. return isKeyDown || wasDown;
  31835. }
  31836. bool Button::keyPressed (const KeyPress&, Component*)
  31837. {
  31838. // returning true will avoid forwarding events for keys that we're using as shortcuts
  31839. return isShortcutPressed();
  31840. }
  31841. bool Button::keyPressed (const KeyPress& key)
  31842. {
  31843. if (isEnabled() && key.isKeyCode (KeyPress::returnKey))
  31844. {
  31845. triggerClick();
  31846. return true;
  31847. }
  31848. return false;
  31849. }
  31850. void Button::setRepeatSpeed (const int initialDelayMillisecs,
  31851. const int repeatMillisecs,
  31852. const int minimumDelayInMillisecs) throw()
  31853. {
  31854. autoRepeatDelay = initialDelayMillisecs;
  31855. autoRepeatSpeed = repeatMillisecs;
  31856. autoRepeatMinimumDelay = jmin (autoRepeatSpeed, minimumDelayInMillisecs);
  31857. }
  31858. void Button::repeatTimerCallback() throw()
  31859. {
  31860. if (needsRepainting)
  31861. {
  31862. getRepeatTimer().stopTimer();
  31863. updateState (0);
  31864. needsRepainting = false;
  31865. }
  31866. else if (autoRepeatSpeed > 0 && (isKeyDown || (updateState (0) == buttonDown)))
  31867. {
  31868. int repeatSpeed = autoRepeatSpeed;
  31869. if (autoRepeatMinimumDelay >= 0)
  31870. {
  31871. double timeHeldDown = jmin (1.0, getMillisecondsSinceButtonDown() / 4000.0);
  31872. timeHeldDown *= timeHeldDown;
  31873. repeatSpeed = repeatSpeed + (int) (timeHeldDown * (autoRepeatMinimumDelay - repeatSpeed));
  31874. }
  31875. repeatSpeed = jmax (1, repeatSpeed);
  31876. getRepeatTimer().startTimer (repeatSpeed);
  31877. const uint32 now = Time::getApproximateMillisecondCounter();
  31878. const int numTimesToCallback
  31879. = (now > lastTimeCallbackTime) ? jmax (1, (now - lastTimeCallbackTime) / repeatSpeed) : 1;
  31880. lastTimeCallbackTime = now;
  31881. const ComponentDeletionWatcher cdw (this);
  31882. for (int i = numTimesToCallback; --i >= 0;)
  31883. {
  31884. internalClickCallback (ModifierKeys::getCurrentModifiers());
  31885. if (cdw.hasBeenDeleted() || ! isDown())
  31886. return;
  31887. }
  31888. }
  31889. else if (! needsToRelease)
  31890. {
  31891. getRepeatTimer().stopTimer();
  31892. }
  31893. }
  31894. class InternalButtonRepeatTimer : public Timer
  31895. {
  31896. public:
  31897. InternalButtonRepeatTimer (Button& owner_) throw()
  31898. : owner (owner_)
  31899. {
  31900. }
  31901. ~InternalButtonRepeatTimer()
  31902. {
  31903. }
  31904. void timerCallback()
  31905. {
  31906. owner.repeatTimerCallback();
  31907. }
  31908. private:
  31909. Button& owner;
  31910. InternalButtonRepeatTimer (const InternalButtonRepeatTimer&);
  31911. const InternalButtonRepeatTimer& operator= (const InternalButtonRepeatTimer&);
  31912. };
  31913. Timer& Button::getRepeatTimer() throw()
  31914. {
  31915. if (repeatTimer == 0)
  31916. repeatTimer = new InternalButtonRepeatTimer (*this);
  31917. return *repeatTimer;
  31918. }
  31919. END_JUCE_NAMESPACE
  31920. /********* End of inlined file: juce_Button.cpp *********/
  31921. /********* Start of inlined file: juce_DrawableButton.cpp *********/
  31922. BEGIN_JUCE_NAMESPACE
  31923. DrawableButton::DrawableButton (const String& name,
  31924. const DrawableButton::ButtonStyle buttonStyle)
  31925. : Button (name),
  31926. style (buttonStyle),
  31927. normalImage (0),
  31928. overImage (0),
  31929. downImage (0),
  31930. disabledImage (0),
  31931. normalImageOn (0),
  31932. overImageOn (0),
  31933. downImageOn (0),
  31934. disabledImageOn (0),
  31935. edgeIndent (3)
  31936. {
  31937. if (buttonStyle == ImageOnButtonBackground)
  31938. {
  31939. backgroundOff = Colour (0xffbbbbff);
  31940. backgroundOn = Colour (0xff3333ff);
  31941. }
  31942. else
  31943. {
  31944. backgroundOff = Colours::transparentBlack;
  31945. backgroundOn = Colour (0xaabbbbff);
  31946. }
  31947. }
  31948. DrawableButton::~DrawableButton()
  31949. {
  31950. deleteImages();
  31951. }
  31952. void DrawableButton::deleteImages()
  31953. {
  31954. deleteAndZero (normalImage);
  31955. deleteAndZero (overImage);
  31956. deleteAndZero (downImage);
  31957. deleteAndZero (disabledImage);
  31958. deleteAndZero (normalImageOn);
  31959. deleteAndZero (overImageOn);
  31960. deleteAndZero (downImageOn);
  31961. deleteAndZero (disabledImageOn);
  31962. }
  31963. void DrawableButton::setImages (const Drawable* normal,
  31964. const Drawable* over,
  31965. const Drawable* down,
  31966. const Drawable* disabled,
  31967. const Drawable* normalOn,
  31968. const Drawable* overOn,
  31969. const Drawable* downOn,
  31970. const Drawable* disabledOn)
  31971. {
  31972. deleteImages();
  31973. jassert (normal != 0); // you really need to give it at least a normal image..
  31974. if (normal != 0)
  31975. normalImage = normal->createCopy();
  31976. if (over != 0)
  31977. overImage = over->createCopy();
  31978. if (down != 0)
  31979. downImage = down->createCopy();
  31980. if (disabled != 0)
  31981. disabledImage = disabled->createCopy();
  31982. if (normalOn != 0)
  31983. normalImageOn = normalOn->createCopy();
  31984. if (overOn != 0)
  31985. overImageOn = overOn->createCopy();
  31986. if (downOn != 0)
  31987. downImageOn = downOn->createCopy();
  31988. if (disabledOn != 0)
  31989. disabledImageOn = disabledOn->createCopy();
  31990. repaint();
  31991. }
  31992. void DrawableButton::setButtonStyle (const DrawableButton::ButtonStyle newStyle)
  31993. {
  31994. if (style != newStyle)
  31995. {
  31996. style = newStyle;
  31997. repaint();
  31998. }
  31999. }
  32000. void DrawableButton::setBackgroundColours (const Colour& toggledOffColour,
  32001. const Colour& toggledOnColour)
  32002. {
  32003. if (backgroundOff != toggledOffColour
  32004. || backgroundOn != toggledOnColour)
  32005. {
  32006. backgroundOff = toggledOffColour;
  32007. backgroundOn = toggledOnColour;
  32008. repaint();
  32009. }
  32010. }
  32011. const Colour& DrawableButton::getBackgroundColour() const throw()
  32012. {
  32013. return getToggleState() ? backgroundOn
  32014. : backgroundOff;
  32015. }
  32016. void DrawableButton::setEdgeIndent (const int numPixelsIndent)
  32017. {
  32018. edgeIndent = numPixelsIndent;
  32019. repaint();
  32020. }
  32021. void DrawableButton::paintButton (Graphics& g,
  32022. bool isMouseOverButton,
  32023. bool isButtonDown)
  32024. {
  32025. Rectangle imageSpace;
  32026. if (style == ImageOnButtonBackground)
  32027. {
  32028. const int insetX = getWidth() / 4;
  32029. const int insetY = getHeight() / 4;
  32030. imageSpace.setBounds (insetX, insetY, getWidth() - insetX * 2, getHeight() - insetY * 2);
  32031. getLookAndFeel().drawButtonBackground (g, *this,
  32032. getBackgroundColour(),
  32033. isMouseOverButton,
  32034. isButtonDown);
  32035. }
  32036. else
  32037. {
  32038. g.fillAll (getBackgroundColour());
  32039. const int textH = (style == ImageAboveTextLabel)
  32040. ? jmin (16, proportionOfHeight (0.25f))
  32041. : 0;
  32042. const int indentX = jmin (edgeIndent, proportionOfWidth (0.3f));
  32043. const int indentY = jmin (edgeIndent, proportionOfHeight (0.3f));
  32044. imageSpace.setBounds (indentX, indentY,
  32045. getWidth() - indentX * 2,
  32046. getHeight() - indentY * 2 - textH);
  32047. if (textH > 0)
  32048. {
  32049. g.setFont ((float) textH);
  32050. g.setColour (Colours::black.withAlpha (isEnabled() ? 1.0f : 0.4f));
  32051. g.drawFittedText (getName(),
  32052. 2, getHeight() - textH - 1,
  32053. getWidth() - 4, textH,
  32054. Justification::centred, 1);
  32055. }
  32056. }
  32057. g.setImageResamplingQuality (Graphics::mediumResamplingQuality);
  32058. g.setOpacity (1.0f);
  32059. const Drawable* imageToDraw = 0;
  32060. if (isEnabled())
  32061. {
  32062. imageToDraw = getCurrentImage();
  32063. }
  32064. else
  32065. {
  32066. imageToDraw = getToggleState() ? disabledImageOn
  32067. : disabledImage;
  32068. if (imageToDraw == 0)
  32069. {
  32070. g.setOpacity (0.4f);
  32071. imageToDraw = getNormalImage();
  32072. }
  32073. }
  32074. if (imageToDraw != 0)
  32075. {
  32076. if (style == ImageRaw)
  32077. {
  32078. imageToDraw->draw (g);
  32079. }
  32080. else
  32081. {
  32082. imageToDraw->drawWithin (g,
  32083. imageSpace.getX(),
  32084. imageSpace.getY(),
  32085. imageSpace.getWidth(),
  32086. imageSpace.getHeight(),
  32087. RectanglePlacement::centred);
  32088. }
  32089. }
  32090. }
  32091. const Drawable* DrawableButton::getCurrentImage() const throw()
  32092. {
  32093. if (isDown())
  32094. return getDownImage();
  32095. if (isOver())
  32096. return getOverImage();
  32097. return getNormalImage();
  32098. }
  32099. const Drawable* DrawableButton::getNormalImage() const throw()
  32100. {
  32101. return (getToggleState() && normalImageOn != 0) ? normalImageOn
  32102. : normalImage;
  32103. }
  32104. const Drawable* DrawableButton::getOverImage() const throw()
  32105. {
  32106. const Drawable* d = normalImage;
  32107. if (getToggleState())
  32108. {
  32109. if (overImageOn != 0)
  32110. d = overImageOn;
  32111. else if (normalImageOn != 0)
  32112. d = normalImageOn;
  32113. else if (overImage != 0)
  32114. d = overImage;
  32115. }
  32116. else
  32117. {
  32118. if (overImage != 0)
  32119. d = overImage;
  32120. }
  32121. return d;
  32122. }
  32123. const Drawable* DrawableButton::getDownImage() const throw()
  32124. {
  32125. const Drawable* d = normalImage;
  32126. if (getToggleState())
  32127. {
  32128. if (downImageOn != 0)
  32129. d = downImageOn;
  32130. else if (overImageOn != 0)
  32131. d = overImageOn;
  32132. else if (normalImageOn != 0)
  32133. d = normalImageOn;
  32134. else if (downImage != 0)
  32135. d = downImage;
  32136. else
  32137. d = getOverImage();
  32138. }
  32139. else
  32140. {
  32141. if (downImage != 0)
  32142. d = downImage;
  32143. else
  32144. d = getOverImage();
  32145. }
  32146. return d;
  32147. }
  32148. END_JUCE_NAMESPACE
  32149. /********* End of inlined file: juce_DrawableButton.cpp *********/
  32150. /********* Start of inlined file: juce_HyperlinkButton.cpp *********/
  32151. BEGIN_JUCE_NAMESPACE
  32152. HyperlinkButton::HyperlinkButton (const String& linkText,
  32153. const URL& linkURL)
  32154. : Button (linkText),
  32155. url (linkURL),
  32156. font (14.0f, Font::underlined),
  32157. resizeFont (true),
  32158. justification (Justification::centred)
  32159. {
  32160. setMouseCursor (MouseCursor::PointingHandCursor);
  32161. setTooltip (linkURL.toString (false));
  32162. }
  32163. HyperlinkButton::~HyperlinkButton()
  32164. {
  32165. }
  32166. void HyperlinkButton::setFont (const Font& newFont,
  32167. const bool resizeToMatchComponentHeight,
  32168. const Justification& justificationType)
  32169. {
  32170. font = newFont;
  32171. resizeFont = resizeToMatchComponentHeight;
  32172. justification = justificationType;
  32173. repaint();
  32174. }
  32175. void HyperlinkButton::setURL (const URL& newURL) throw()
  32176. {
  32177. url = newURL;
  32178. setTooltip (newURL.toString (false));
  32179. }
  32180. const Font HyperlinkButton::getFontToUse() const
  32181. {
  32182. Font f (font);
  32183. if (resizeFont)
  32184. f.setHeight (getHeight() * 0.7f);
  32185. return f;
  32186. }
  32187. void HyperlinkButton::changeWidthToFitText()
  32188. {
  32189. setSize (getFontToUse().getStringWidth (getName()) + 6, getHeight());
  32190. }
  32191. void HyperlinkButton::colourChanged()
  32192. {
  32193. repaint();
  32194. }
  32195. void HyperlinkButton::clicked()
  32196. {
  32197. if (url.isWellFormed())
  32198. url.launchInDefaultBrowser();
  32199. }
  32200. void HyperlinkButton::paintButton (Graphics& g,
  32201. bool isMouseOverButton,
  32202. bool isButtonDown)
  32203. {
  32204. const Colour textColour (findColour (textColourId));
  32205. if (isEnabled())
  32206. g.setColour ((isMouseOverButton) ? textColour.darker ((isButtonDown) ? 1.3f : 0.4f)
  32207. : textColour);
  32208. else
  32209. g.setColour (textColour.withMultipliedAlpha (0.4f));
  32210. g.setFont (getFontToUse());
  32211. g.drawText (getButtonText(),
  32212. 2, 0, getWidth() - 2, getHeight(),
  32213. justification.getOnlyHorizontalFlags() | Justification::verticallyCentred,
  32214. true);
  32215. }
  32216. END_JUCE_NAMESPACE
  32217. /********* End of inlined file: juce_HyperlinkButton.cpp *********/
  32218. /********* Start of inlined file: juce_ImageButton.cpp *********/
  32219. BEGIN_JUCE_NAMESPACE
  32220. ImageButton::ImageButton (const String& text)
  32221. : Button (text),
  32222. scaleImageToFit (true),
  32223. preserveProportions (true),
  32224. alphaThreshold (0),
  32225. imageX (0),
  32226. imageY (0),
  32227. imageW (0),
  32228. imageH (0),
  32229. normalImage (0),
  32230. overImage (0),
  32231. downImage (0)
  32232. {
  32233. }
  32234. ImageButton::~ImageButton()
  32235. {
  32236. deleteImages();
  32237. }
  32238. void ImageButton::deleteImages()
  32239. {
  32240. if (normalImage != 0)
  32241. {
  32242. if (ImageCache::isImageInCache (normalImage))
  32243. ImageCache::release (normalImage);
  32244. else
  32245. delete normalImage;
  32246. }
  32247. if (overImage != 0)
  32248. {
  32249. if (ImageCache::isImageInCache (overImage))
  32250. ImageCache::release (overImage);
  32251. else
  32252. delete overImage;
  32253. }
  32254. if (downImage != 0)
  32255. {
  32256. if (ImageCache::isImageInCache (downImage))
  32257. ImageCache::release (downImage);
  32258. else
  32259. delete downImage;
  32260. }
  32261. }
  32262. void ImageButton::setImages (const bool resizeButtonNowToFitThisImage,
  32263. const bool rescaleImagesWhenButtonSizeChanges,
  32264. const bool preserveImageProportions,
  32265. Image* const normalImage_,
  32266. const float imageOpacityWhenNormal,
  32267. const Colour& overlayColourWhenNormal,
  32268. Image* const overImage_,
  32269. const float imageOpacityWhenOver,
  32270. const Colour& overlayColourWhenOver,
  32271. Image* const downImage_,
  32272. const float imageOpacityWhenDown,
  32273. const Colour& overlayColourWhenDown,
  32274. const float hitTestAlphaThreshold)
  32275. {
  32276. deleteImages();
  32277. normalImage = normalImage_;
  32278. overImage = overImage_;
  32279. downImage = downImage_;
  32280. if (resizeButtonNowToFitThisImage && normalImage != 0)
  32281. {
  32282. imageW = normalImage->getWidth();
  32283. imageH = normalImage->getHeight();
  32284. setSize (imageW, imageH);
  32285. }
  32286. scaleImageToFit = rescaleImagesWhenButtonSizeChanges;
  32287. preserveProportions = preserveImageProportions;
  32288. normalOpacity = imageOpacityWhenNormal;
  32289. normalOverlay = overlayColourWhenNormal;
  32290. overOpacity = imageOpacityWhenOver;
  32291. overOverlay = overlayColourWhenOver;
  32292. downOpacity = imageOpacityWhenDown;
  32293. downOverlay = overlayColourWhenDown;
  32294. alphaThreshold = (unsigned char) jlimit (0, 0xff, roundFloatToInt (255.0f * hitTestAlphaThreshold));
  32295. repaint();
  32296. }
  32297. Image* ImageButton::getCurrentImage() const
  32298. {
  32299. if (isDown())
  32300. return getDownImage();
  32301. if (isOver())
  32302. return getOverImage();
  32303. return getNormalImage();
  32304. }
  32305. Image* ImageButton::getNormalImage() const throw()
  32306. {
  32307. return normalImage;
  32308. }
  32309. Image* ImageButton::getOverImage() const throw()
  32310. {
  32311. return (overImage != 0) ? overImage
  32312. : normalImage;
  32313. }
  32314. Image* ImageButton::getDownImage() const throw()
  32315. {
  32316. return (downImage != 0) ? downImage
  32317. : getOverImage();
  32318. }
  32319. void ImageButton::paintButton (Graphics& g,
  32320. bool isMouseOverButton,
  32321. bool isButtonDown)
  32322. {
  32323. if (! isEnabled())
  32324. {
  32325. isMouseOverButton = false;
  32326. isButtonDown = false;
  32327. }
  32328. Image* const im = getCurrentImage();
  32329. if (im != 0)
  32330. {
  32331. const int iw = im->getWidth();
  32332. const int ih = im->getHeight();
  32333. imageW = getWidth();
  32334. imageH = getHeight();
  32335. imageX = (imageW - iw) >> 1;
  32336. imageY = (imageH - ih) >> 1;
  32337. if (scaleImageToFit)
  32338. {
  32339. if (preserveProportions)
  32340. {
  32341. int newW, newH;
  32342. const float imRatio = ih / (float)iw;
  32343. const float destRatio = imageH / (float)imageW;
  32344. if (imRatio > destRatio)
  32345. {
  32346. newW = roundFloatToInt (imageH / imRatio);
  32347. newH = imageH;
  32348. }
  32349. else
  32350. {
  32351. newW = imageW;
  32352. newH = roundFloatToInt (imageW * imRatio);
  32353. }
  32354. imageX = (imageW - newW) / 2;
  32355. imageY = (imageH - newH) / 2;
  32356. imageW = newW;
  32357. imageH = newH;
  32358. }
  32359. else
  32360. {
  32361. imageX = 0;
  32362. imageY = 0;
  32363. }
  32364. }
  32365. const Colour& overlayColour = (isButtonDown) ? downOverlay
  32366. : ((isMouseOverButton) ? overOverlay
  32367. : normalOverlay);
  32368. if (! overlayColour.isOpaque())
  32369. {
  32370. g.setOpacity ((isButtonDown) ? downOpacity
  32371. : ((isMouseOverButton) ? overOpacity
  32372. : normalOpacity));
  32373. if (scaleImageToFit)
  32374. g.drawImage (im, imageX, imageY, imageW, imageH, 0, 0, iw, ih, false);
  32375. else
  32376. g.drawImageAt (im, imageX, imageY, false);
  32377. }
  32378. if (! overlayColour.isTransparent())
  32379. {
  32380. g.setColour (overlayColour);
  32381. if (scaleImageToFit)
  32382. g.drawImage (im, imageX, imageY, imageW, imageH, 0, 0, iw, ih, true);
  32383. else
  32384. g.drawImageAt (im, imageX, imageY, true);
  32385. }
  32386. }
  32387. }
  32388. bool ImageButton::hitTest (int x, int y)
  32389. {
  32390. if (alphaThreshold == 0)
  32391. return true;
  32392. Image* const im = getCurrentImage();
  32393. return im == 0
  32394. || (imageW > 0 && imageH > 0
  32395. && alphaThreshold < im->getPixelAt (((x - imageX) * im->getWidth()) / imageW,
  32396. ((y - imageY) * im->getHeight()) / imageH).getAlpha());
  32397. }
  32398. END_JUCE_NAMESPACE
  32399. /********* End of inlined file: juce_ImageButton.cpp *********/
  32400. /********* Start of inlined file: juce_ShapeButton.cpp *********/
  32401. BEGIN_JUCE_NAMESPACE
  32402. ShapeButton::ShapeButton (const String& text,
  32403. const Colour& normalColour_,
  32404. const Colour& overColour_,
  32405. const Colour& downColour_)
  32406. : Button (text),
  32407. normalColour (normalColour_),
  32408. overColour (overColour_),
  32409. downColour (downColour_),
  32410. maintainShapeProportions (false),
  32411. outlineWidth (0.0f)
  32412. {
  32413. }
  32414. ShapeButton::~ShapeButton()
  32415. {
  32416. }
  32417. void ShapeButton::setColours (const Colour& newNormalColour,
  32418. const Colour& newOverColour,
  32419. const Colour& newDownColour)
  32420. {
  32421. normalColour = newNormalColour;
  32422. overColour = newOverColour;
  32423. downColour = newDownColour;
  32424. }
  32425. void ShapeButton::setOutline (const Colour& newOutlineColour,
  32426. const float newOutlineWidth)
  32427. {
  32428. outlineColour = newOutlineColour;
  32429. outlineWidth = newOutlineWidth;
  32430. }
  32431. void ShapeButton::setShape (const Path& newShape,
  32432. const bool resizeNowToFitThisShape,
  32433. const bool maintainShapeProportions_,
  32434. const bool hasShadow)
  32435. {
  32436. shape = newShape;
  32437. maintainShapeProportions = maintainShapeProportions_;
  32438. shadow.setShadowProperties (3.0f, 0.5f, 0, 0);
  32439. setComponentEffect ((hasShadow) ? &shadow : 0);
  32440. if (resizeNowToFitThisShape)
  32441. {
  32442. float x, y, w, h;
  32443. shape.getBounds (x, y, w, h);
  32444. shape.applyTransform (AffineTransform::translation (-x, -y));
  32445. if (hasShadow)
  32446. {
  32447. w += 4.0f;
  32448. h += 4.0f;
  32449. shape.applyTransform (AffineTransform::translation (2.0f, 2.0f));
  32450. }
  32451. setSize (1 + (int) (w + outlineWidth),
  32452. 1 + (int) (h + outlineWidth));
  32453. }
  32454. }
  32455. void ShapeButton::paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown)
  32456. {
  32457. if (! isEnabled())
  32458. {
  32459. isMouseOverButton = false;
  32460. isButtonDown = false;
  32461. }
  32462. g.setColour ((isButtonDown) ? downColour
  32463. : (isMouseOverButton) ? overColour
  32464. : normalColour);
  32465. int w = getWidth();
  32466. int h = getHeight();
  32467. if (getComponentEffect() != 0)
  32468. {
  32469. w -= 4;
  32470. h -= 4;
  32471. }
  32472. const float offset = (outlineWidth * 0.5f) + (isButtonDown ? 1.5f : 0.0f);
  32473. const AffineTransform trans (shape.getTransformToScaleToFit (offset, offset,
  32474. w - offset - outlineWidth,
  32475. h - offset - outlineWidth,
  32476. maintainShapeProportions));
  32477. g.fillPath (shape, trans);
  32478. if (outlineWidth > 0.0f)
  32479. {
  32480. g.setColour (outlineColour);
  32481. g.strokePath (shape, PathStrokeType (outlineWidth), trans);
  32482. }
  32483. }
  32484. END_JUCE_NAMESPACE
  32485. /********* End of inlined file: juce_ShapeButton.cpp *********/
  32486. /********* Start of inlined file: juce_TextButton.cpp *********/
  32487. BEGIN_JUCE_NAMESPACE
  32488. TextButton::TextButton (const String& name,
  32489. const String& toolTip)
  32490. : Button (name)
  32491. {
  32492. setTooltip (toolTip);
  32493. }
  32494. TextButton::~TextButton()
  32495. {
  32496. }
  32497. void TextButton::paintButton (Graphics& g,
  32498. bool isMouseOverButton,
  32499. bool isButtonDown)
  32500. {
  32501. getLookAndFeel().drawButtonBackground (g, *this,
  32502. findColour (getToggleState() ? buttonOnColourId
  32503. : buttonColourId),
  32504. isMouseOverButton,
  32505. isButtonDown);
  32506. getLookAndFeel().drawButtonText (g, *this,
  32507. isMouseOverButton,
  32508. isButtonDown);
  32509. }
  32510. void TextButton::colourChanged()
  32511. {
  32512. repaint();
  32513. }
  32514. const Font TextButton::getFont()
  32515. {
  32516. return Font (jmin (15.0f, getHeight() * 0.6f));
  32517. }
  32518. void TextButton::changeWidthToFitText (const int newHeight)
  32519. {
  32520. if (newHeight >= 0)
  32521. setSize (jmax (1, getWidth()), newHeight);
  32522. setSize (getFont().getStringWidth (getButtonText()) + getHeight(),
  32523. getHeight());
  32524. }
  32525. END_JUCE_NAMESPACE
  32526. /********* End of inlined file: juce_TextButton.cpp *********/
  32527. /********* Start of inlined file: juce_ToggleButton.cpp *********/
  32528. BEGIN_JUCE_NAMESPACE
  32529. ToggleButton::ToggleButton (const String& buttonText)
  32530. : Button (buttonText)
  32531. {
  32532. setClickingTogglesState (true);
  32533. }
  32534. ToggleButton::~ToggleButton()
  32535. {
  32536. }
  32537. void ToggleButton::paintButton (Graphics& g,
  32538. bool isMouseOverButton,
  32539. bool isButtonDown)
  32540. {
  32541. getLookAndFeel().drawToggleButton (g, *this,
  32542. isMouseOverButton,
  32543. isButtonDown);
  32544. }
  32545. void ToggleButton::changeWidthToFitText()
  32546. {
  32547. getLookAndFeel().changeToggleButtonWidthToFitText (*this);
  32548. }
  32549. void ToggleButton::colourChanged()
  32550. {
  32551. repaint();
  32552. }
  32553. END_JUCE_NAMESPACE
  32554. /********* End of inlined file: juce_ToggleButton.cpp *********/
  32555. /********* Start of inlined file: juce_ToolbarButton.cpp *********/
  32556. BEGIN_JUCE_NAMESPACE
  32557. ToolbarButton::ToolbarButton (const int itemId,
  32558. const String& buttonText,
  32559. Drawable* const normalImage_,
  32560. Drawable* const toggledOnImage_)
  32561. : ToolbarItemComponent (itemId, buttonText, true),
  32562. normalImage (normalImage_),
  32563. toggledOnImage (toggledOnImage_)
  32564. {
  32565. }
  32566. ToolbarButton::~ToolbarButton()
  32567. {
  32568. delete normalImage;
  32569. delete toggledOnImage;
  32570. }
  32571. bool ToolbarButton::getToolbarItemSizes (int toolbarDepth,
  32572. bool /*isToolbarVertical*/,
  32573. int& preferredSize,
  32574. int& minSize, int& maxSize)
  32575. {
  32576. preferredSize = minSize = maxSize = toolbarDepth;
  32577. return true;
  32578. }
  32579. void ToolbarButton::paintButtonArea (Graphics& g,
  32580. int width, int height,
  32581. bool /*isMouseOver*/,
  32582. bool /*isMouseDown*/)
  32583. {
  32584. Drawable* d = normalImage;
  32585. if (getToggleState() && toggledOnImage != 0)
  32586. d = toggledOnImage;
  32587. if (! isEnabled())
  32588. {
  32589. Image im (Image::ARGB, width, height, true);
  32590. Graphics g2 (im);
  32591. d->drawWithin (g2, 0, 0, width, height, RectanglePlacement::centred);
  32592. im.desaturate();
  32593. g.drawImageAt (&im, 0, 0);
  32594. }
  32595. else
  32596. {
  32597. d->drawWithin (g, 0, 0, width, height, RectanglePlacement::centred);
  32598. }
  32599. }
  32600. void ToolbarButton::contentAreaChanged (const Rectangle&)
  32601. {
  32602. }
  32603. END_JUCE_NAMESPACE
  32604. /********* End of inlined file: juce_ToolbarButton.cpp *********/
  32605. /********* Start of inlined file: juce_ComboBox.cpp *********/
  32606. BEGIN_JUCE_NAMESPACE
  32607. ComboBox::ComboBox (const String& name)
  32608. : Component (name),
  32609. items (4),
  32610. currentIndex (-1),
  32611. isButtonDown (false),
  32612. separatorPending (false),
  32613. menuActive (false),
  32614. listeners (2),
  32615. label (0)
  32616. {
  32617. noChoicesMessage = TRANS("(no choices)");
  32618. setRepaintsOnMouseActivity (true);
  32619. lookAndFeelChanged();
  32620. }
  32621. ComboBox::~ComboBox()
  32622. {
  32623. if (menuActive)
  32624. PopupMenu::dismissAllActiveMenus();
  32625. deleteAllChildren();
  32626. }
  32627. void ComboBox::setEditableText (const bool isEditable)
  32628. {
  32629. label->setEditable (isEditable, isEditable, false);
  32630. setWantsKeyboardFocus (! isEditable);
  32631. resized();
  32632. }
  32633. bool ComboBox::isTextEditable() const throw()
  32634. {
  32635. return label->isEditable();
  32636. }
  32637. void ComboBox::setJustificationType (const Justification& justification) throw()
  32638. {
  32639. label->setJustificationType (justification);
  32640. }
  32641. const Justification ComboBox::getJustificationType() const throw()
  32642. {
  32643. return label->getJustificationType();
  32644. }
  32645. void ComboBox::setTooltip (const String& newTooltip)
  32646. {
  32647. SettableTooltipClient::setTooltip (newTooltip);
  32648. label->setTooltip (newTooltip);
  32649. }
  32650. void ComboBox::addItem (const String& newItemText,
  32651. const int newItemId) throw()
  32652. {
  32653. // you can't add empty strings to the list..
  32654. jassert (newItemText.isNotEmpty());
  32655. // IDs must be non-zero, as zero is used to indicate a lack of selecion.
  32656. jassert (newItemId != 0);
  32657. // you shouldn't use duplicate item IDs!
  32658. jassert (getItemForId (newItemId) == 0);
  32659. if (newItemText.isNotEmpty() && newItemId != 0)
  32660. {
  32661. if (separatorPending)
  32662. {
  32663. separatorPending = false;
  32664. ItemInfo* const item = new ItemInfo();
  32665. item->itemId = 0;
  32666. item->isEnabled = false;
  32667. item->isHeading = false;
  32668. items.add (item);
  32669. }
  32670. ItemInfo* const item = new ItemInfo();
  32671. item->name = newItemText;
  32672. item->itemId = newItemId;
  32673. item->isEnabled = true;
  32674. item->isHeading = false;
  32675. items.add (item);
  32676. }
  32677. }
  32678. void ComboBox::addSeparator() throw()
  32679. {
  32680. separatorPending = (items.size() > 0);
  32681. }
  32682. void ComboBox::addSectionHeading (const String& headingName) throw()
  32683. {
  32684. // you can't add empty strings to the list..
  32685. jassert (headingName.isNotEmpty());
  32686. if (headingName.isNotEmpty())
  32687. {
  32688. if (separatorPending)
  32689. {
  32690. separatorPending = false;
  32691. ItemInfo* const item = new ItemInfo();
  32692. item->itemId = 0;
  32693. item->isEnabled = false;
  32694. item->isHeading = false;
  32695. items.add (item);
  32696. }
  32697. ItemInfo* const item = new ItemInfo();
  32698. item->name = headingName;
  32699. item->itemId = 0;
  32700. item->isEnabled = true;
  32701. item->isHeading = true;
  32702. items.add (item);
  32703. }
  32704. }
  32705. void ComboBox::setItemEnabled (const int itemId,
  32706. const bool isEnabled) throw()
  32707. {
  32708. ItemInfo* const item = getItemForId (itemId);
  32709. if (item != 0)
  32710. item->isEnabled = isEnabled;
  32711. }
  32712. void ComboBox::changeItemText (const int itemId,
  32713. const String& newText) throw()
  32714. {
  32715. ItemInfo* const item = getItemForId (itemId);
  32716. jassert (item != 0);
  32717. if (item != 0)
  32718. item->name = newText;
  32719. }
  32720. void ComboBox::clear (const bool dontSendChangeMessage)
  32721. {
  32722. items.clear();
  32723. separatorPending = false;
  32724. if (! label->isEditable())
  32725. setSelectedItemIndex (-1, dontSendChangeMessage);
  32726. }
  32727. ComboBox::ItemInfo* ComboBox::getItemForId (const int itemId) const throw()
  32728. {
  32729. jassert (itemId != 0);
  32730. if (itemId != 0)
  32731. {
  32732. for (int i = items.size(); --i >= 0;)
  32733. if (items.getUnchecked(i)->itemId == itemId)
  32734. return items.getUnchecked(i);
  32735. }
  32736. return 0;
  32737. }
  32738. ComboBox::ItemInfo* ComboBox::getItemForIndex (const int index) const throw()
  32739. {
  32740. int n = 0;
  32741. for (int i = 0; i < items.size(); ++i)
  32742. {
  32743. ItemInfo* const item = items.getUnchecked(i);
  32744. if (item->isRealItem())
  32745. {
  32746. if (n++ == index)
  32747. return item;
  32748. }
  32749. }
  32750. return 0;
  32751. }
  32752. int ComboBox::getNumItems() const throw()
  32753. {
  32754. int n = 0;
  32755. for (int i = items.size(); --i >= 0;)
  32756. {
  32757. ItemInfo* const item = items.getUnchecked(i);
  32758. if (item->isRealItem())
  32759. ++n;
  32760. }
  32761. return n;
  32762. }
  32763. const String ComboBox::getItemText (const int index) const throw()
  32764. {
  32765. ItemInfo* const item = getItemForIndex (index);
  32766. if (item != 0)
  32767. return item->name;
  32768. return String::empty;
  32769. }
  32770. int ComboBox::getItemId (const int index) const throw()
  32771. {
  32772. ItemInfo* const item = getItemForIndex (index);
  32773. return (item != 0) ? item->itemId : 0;
  32774. }
  32775. bool ComboBox::ItemInfo::isSeparator() const throw()
  32776. {
  32777. return name.isEmpty();
  32778. }
  32779. bool ComboBox::ItemInfo::isRealItem() const throw()
  32780. {
  32781. return ! (isHeading || name.isEmpty());
  32782. }
  32783. int ComboBox::getSelectedItemIndex() const throw()
  32784. {
  32785. return (currentIndex >= 0 && getText() == getItemText (currentIndex))
  32786. ? currentIndex
  32787. : -1;
  32788. }
  32789. void ComboBox::setSelectedItemIndex (const int index,
  32790. const bool dontSendChangeMessage) throw()
  32791. {
  32792. if (currentIndex != index || label->getText() != getItemText (currentIndex))
  32793. {
  32794. if (((unsigned int) index) < (unsigned int) getNumItems())
  32795. currentIndex = index;
  32796. else
  32797. currentIndex = -1;
  32798. label->setText (getItemText (currentIndex), false);
  32799. if (! dontSendChangeMessage)
  32800. triggerAsyncUpdate();
  32801. }
  32802. }
  32803. void ComboBox::setSelectedId (const int newItemId,
  32804. const bool dontSendChangeMessage) throw()
  32805. {
  32806. for (int i = getNumItems(); --i >= 0;)
  32807. {
  32808. if (getItemId(i) == newItemId)
  32809. {
  32810. setSelectedItemIndex (i, dontSendChangeMessage);
  32811. break;
  32812. }
  32813. }
  32814. }
  32815. int ComboBox::getSelectedId() const throw()
  32816. {
  32817. const ItemInfo* const item = getItemForIndex (currentIndex);
  32818. return (item != 0 && getText() == item->name)
  32819. ? item->itemId
  32820. : 0;
  32821. }
  32822. void ComboBox::addListener (ComboBoxListener* const listener) throw()
  32823. {
  32824. jassert (listener != 0);
  32825. if (listener != 0)
  32826. listeners.add (listener);
  32827. }
  32828. void ComboBox::removeListener (ComboBoxListener* const listener) throw()
  32829. {
  32830. listeners.removeValue (listener);
  32831. }
  32832. void ComboBox::handleAsyncUpdate()
  32833. {
  32834. for (int i = listeners.size(); --i >= 0;)
  32835. {
  32836. ((ComboBoxListener*) listeners.getUnchecked (i))->comboBoxChanged (this);
  32837. i = jmin (i, listeners.size());
  32838. }
  32839. }
  32840. const String ComboBox::getText() const throw()
  32841. {
  32842. return label->getText();
  32843. }
  32844. void ComboBox::setText (const String& newText,
  32845. const bool dontSendChangeMessage) throw()
  32846. {
  32847. for (int i = items.size(); --i >= 0;)
  32848. {
  32849. ItemInfo* const item = items.getUnchecked(i);
  32850. if (item->isRealItem()
  32851. && item->name == newText)
  32852. {
  32853. setSelectedId (item->itemId, dontSendChangeMessage);
  32854. return;
  32855. }
  32856. }
  32857. currentIndex = -1;
  32858. if (label->getText() != newText)
  32859. {
  32860. label->setText (newText, false);
  32861. if (! dontSendChangeMessage)
  32862. triggerAsyncUpdate();
  32863. }
  32864. repaint();
  32865. }
  32866. void ComboBox::showEditor()
  32867. {
  32868. jassert (isTextEditable()); // you probably shouldn't do this to a non-editable combo box?
  32869. label->showEditor();
  32870. }
  32871. void ComboBox::setTextWhenNothingSelected (const String& newMessage) throw()
  32872. {
  32873. textWhenNothingSelected = newMessage;
  32874. repaint();
  32875. }
  32876. const String ComboBox::getTextWhenNothingSelected() const throw()
  32877. {
  32878. return textWhenNothingSelected;
  32879. }
  32880. void ComboBox::setTextWhenNoChoicesAvailable (const String& newMessage) throw()
  32881. {
  32882. noChoicesMessage = newMessage;
  32883. }
  32884. const String ComboBox::getTextWhenNoChoicesAvailable() const throw()
  32885. {
  32886. return noChoicesMessage;
  32887. }
  32888. void ComboBox::paint (Graphics& g)
  32889. {
  32890. getLookAndFeel().drawComboBox (g,
  32891. getWidth(),
  32892. getHeight(),
  32893. isButtonDown,
  32894. label->getRight(),
  32895. 0,
  32896. getWidth() - label->getRight(),
  32897. getHeight(),
  32898. *this);
  32899. if (textWhenNothingSelected.isNotEmpty()
  32900. && label->getText().isEmpty()
  32901. && ! label->isBeingEdited())
  32902. {
  32903. g.setColour (findColour (textColourId).withMultipliedAlpha (0.5f));
  32904. g.setFont (label->getFont());
  32905. g.drawFittedText (textWhenNothingSelected,
  32906. label->getX() + 2, label->getY() + 1,
  32907. label->getWidth() - 4, label->getHeight() - 2,
  32908. label->getJustificationType(),
  32909. jmax (1, (int) (label->getHeight() / label->getFont().getHeight())));
  32910. }
  32911. }
  32912. void ComboBox::resized()
  32913. {
  32914. if (getHeight() > 0 && getWidth() > 0)
  32915. getLookAndFeel().positionComboBoxText (*this, *label);
  32916. }
  32917. void ComboBox::enablementChanged()
  32918. {
  32919. repaint();
  32920. }
  32921. void ComboBox::lookAndFeelChanged()
  32922. {
  32923. repaint();
  32924. Label* const newLabel = getLookAndFeel().createComboBoxTextBox (*this);
  32925. if (label != 0)
  32926. {
  32927. newLabel->setEditable (label->isEditable());
  32928. newLabel->setJustificationType (label->getJustificationType());
  32929. newLabel->setTooltip (label->getTooltip());
  32930. newLabel->setText (label->getText(), false);
  32931. }
  32932. delete label;
  32933. label = newLabel;
  32934. addAndMakeVisible (newLabel);
  32935. newLabel->addListener (this);
  32936. newLabel->addMouseListener (this, false);
  32937. newLabel->setColour (Label::backgroundColourId, Colours::transparentBlack);
  32938. newLabel->setColour (Label::textColourId, findColour (ComboBox::textColourId));
  32939. newLabel->setColour (TextEditor::textColourId, findColour (ComboBox::textColourId));
  32940. newLabel->setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  32941. newLabel->setColour (TextEditor::highlightColourId, findColour (TextEditor::highlightColourId));
  32942. newLabel->setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  32943. resized();
  32944. }
  32945. void ComboBox::colourChanged()
  32946. {
  32947. lookAndFeelChanged();
  32948. }
  32949. bool ComboBox::keyPressed (const KeyPress& key)
  32950. {
  32951. bool used = false;
  32952. if (key.isKeyCode (KeyPress::upKey)
  32953. || key.isKeyCode (KeyPress::leftKey))
  32954. {
  32955. setSelectedItemIndex (jmax (0, currentIndex - 1));
  32956. used = true;
  32957. }
  32958. else if (key.isKeyCode (KeyPress::downKey)
  32959. || key.isKeyCode (KeyPress::rightKey))
  32960. {
  32961. setSelectedItemIndex (jmin (currentIndex + 1, getNumItems() - 1));
  32962. used = true;
  32963. }
  32964. else if (key.isKeyCode (KeyPress::returnKey))
  32965. {
  32966. showPopup();
  32967. used = true;
  32968. }
  32969. return used;
  32970. }
  32971. bool ComboBox::keyStateChanged()
  32972. {
  32973. // only forward key events that aren't used by this component
  32974. return KeyPress::isKeyCurrentlyDown (KeyPress::upKey)
  32975. || KeyPress::isKeyCurrentlyDown (KeyPress::leftKey)
  32976. || KeyPress::isKeyCurrentlyDown (KeyPress::downKey)
  32977. || KeyPress::isKeyCurrentlyDown (KeyPress::rightKey);
  32978. }
  32979. void ComboBox::focusGained (FocusChangeType)
  32980. {
  32981. repaint();
  32982. }
  32983. void ComboBox::focusLost (FocusChangeType)
  32984. {
  32985. repaint();
  32986. }
  32987. void ComboBox::labelTextChanged (Label*)
  32988. {
  32989. triggerAsyncUpdate();
  32990. }
  32991. void ComboBox::showPopup()
  32992. {
  32993. if (! menuActive)
  32994. {
  32995. const int currentId = getSelectedId();
  32996. ComponentDeletionWatcher deletionWatcher (this);
  32997. PopupMenu menu;
  32998. menu.setLookAndFeel (&getLookAndFeel());
  32999. for (int i = 0; i < items.size(); ++i)
  33000. {
  33001. const ItemInfo* const item = items.getUnchecked(i);
  33002. if (item->isSeparator())
  33003. menu.addSeparator();
  33004. else if (item->isHeading)
  33005. menu.addSectionHeader (item->name);
  33006. else
  33007. menu.addItem (item->itemId, item->name,
  33008. item->isEnabled, item->itemId == currentId);
  33009. }
  33010. if (items.size() == 0)
  33011. menu.addItem (1, noChoicesMessage, false);
  33012. const int itemHeight = jlimit (12, 24, getHeight());
  33013. menuActive = true;
  33014. const int resultId = menu.showAt (this, currentId,
  33015. getWidth(), 1, itemHeight);
  33016. if (deletionWatcher.hasBeenDeleted())
  33017. return;
  33018. menuActive = false;
  33019. if (resultId != 0)
  33020. setSelectedId (resultId);
  33021. }
  33022. }
  33023. void ComboBox::mouseDown (const MouseEvent& e)
  33024. {
  33025. beginDragAutoRepeat (300);
  33026. isButtonDown = isEnabled();
  33027. if (isButtonDown
  33028. && (e.eventComponent == this || ! label->isEditable()))
  33029. {
  33030. showPopup();
  33031. }
  33032. }
  33033. void ComboBox::mouseDrag (const MouseEvent& e)
  33034. {
  33035. beginDragAutoRepeat (50);
  33036. if (isButtonDown && ! e.mouseWasClicked())
  33037. showPopup();
  33038. }
  33039. void ComboBox::mouseUp (const MouseEvent& e2)
  33040. {
  33041. if (isButtonDown)
  33042. {
  33043. isButtonDown = false;
  33044. repaint();
  33045. const MouseEvent e (e2.getEventRelativeTo (this));
  33046. if (reallyContains (e.x, e.y, true)
  33047. && (e2.eventComponent == this || ! label->isEditable()))
  33048. {
  33049. showPopup();
  33050. }
  33051. }
  33052. }
  33053. END_JUCE_NAMESPACE
  33054. /********* End of inlined file: juce_ComboBox.cpp *********/
  33055. /********* Start of inlined file: juce_Label.cpp *********/
  33056. BEGIN_JUCE_NAMESPACE
  33057. Label::Label (const String& componentName,
  33058. const String& labelText)
  33059. : Component (componentName),
  33060. text (labelText),
  33061. font (15.0f),
  33062. justification (Justification::centredLeft),
  33063. editor (0),
  33064. listeners (2),
  33065. ownerComponent (0),
  33066. deletionWatcher (0),
  33067. editSingleClick (false),
  33068. editDoubleClick (false),
  33069. lossOfFocusDiscardsChanges (false)
  33070. {
  33071. setColour (TextEditor::textColourId, Colours::black);
  33072. setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  33073. setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  33074. }
  33075. Label::~Label()
  33076. {
  33077. if (ownerComponent != 0 && ! deletionWatcher->hasBeenDeleted())
  33078. ownerComponent->removeComponentListener (this);
  33079. deleteAndZero (deletionWatcher);
  33080. if (editor != 0)
  33081. delete editor;
  33082. }
  33083. void Label::setText (const String& newText,
  33084. const bool broadcastChangeMessage)
  33085. {
  33086. hideEditor (true);
  33087. if (text != newText)
  33088. {
  33089. text = newText;
  33090. if (broadcastChangeMessage)
  33091. triggerAsyncUpdate();
  33092. repaint();
  33093. if (ownerComponent != 0 && ! deletionWatcher->hasBeenDeleted())
  33094. componentMovedOrResized (*ownerComponent, true, true);
  33095. }
  33096. }
  33097. const String Label::getText (const bool returnActiveEditorContents) const throw()
  33098. {
  33099. return (returnActiveEditorContents && isBeingEdited())
  33100. ? editor->getText()
  33101. : text;
  33102. }
  33103. void Label::setFont (const Font& newFont) throw()
  33104. {
  33105. font = newFont;
  33106. repaint();
  33107. }
  33108. const Font& Label::getFont() const throw()
  33109. {
  33110. return font;
  33111. }
  33112. void Label::setEditable (const bool editOnSingleClick,
  33113. const bool editOnDoubleClick,
  33114. const bool lossOfFocusDiscardsChanges_) throw()
  33115. {
  33116. editSingleClick = editOnSingleClick;
  33117. editDoubleClick = editOnDoubleClick;
  33118. lossOfFocusDiscardsChanges = lossOfFocusDiscardsChanges_;
  33119. setWantsKeyboardFocus (editOnSingleClick || editOnDoubleClick);
  33120. setFocusContainer (editOnSingleClick || editOnDoubleClick);
  33121. }
  33122. void Label::setJustificationType (const Justification& justification_) throw()
  33123. {
  33124. justification = justification_;
  33125. repaint();
  33126. }
  33127. void Label::attachToComponent (Component* owner,
  33128. const bool onLeft)
  33129. {
  33130. if (ownerComponent != 0 && ! deletionWatcher->hasBeenDeleted())
  33131. ownerComponent->removeComponentListener (this);
  33132. deleteAndZero (deletionWatcher);
  33133. ownerComponent = owner;
  33134. leftOfOwnerComp = onLeft;
  33135. if (ownerComponent != 0)
  33136. {
  33137. deletionWatcher = new ComponentDeletionWatcher (owner);
  33138. setVisible (owner->isVisible());
  33139. ownerComponent->addComponentListener (this);
  33140. componentParentHierarchyChanged (*ownerComponent);
  33141. componentMovedOrResized (*ownerComponent, true, true);
  33142. }
  33143. }
  33144. void Label::componentMovedOrResized (Component& component,
  33145. bool /*wasMoved*/,
  33146. bool /*wasResized*/)
  33147. {
  33148. if (leftOfOwnerComp)
  33149. {
  33150. setSize (jmin (getFont().getStringWidth (text) + 8, component.getX()),
  33151. component.getHeight());
  33152. setTopRightPosition (component.getX(), component.getY());
  33153. }
  33154. else
  33155. {
  33156. setSize (component.getWidth(),
  33157. 8 + roundFloatToInt (getFont().getHeight()));
  33158. setTopLeftPosition (component.getX(), component.getY() - getHeight());
  33159. }
  33160. }
  33161. void Label::componentParentHierarchyChanged (Component& component)
  33162. {
  33163. if (component.getParentComponent() != 0)
  33164. component.getParentComponent()->addChildComponent (this);
  33165. }
  33166. void Label::componentVisibilityChanged (Component& component)
  33167. {
  33168. setVisible (component.isVisible());
  33169. }
  33170. void Label::textWasEdited()
  33171. {
  33172. }
  33173. void Label::showEditor()
  33174. {
  33175. if (editor == 0)
  33176. {
  33177. addAndMakeVisible (editor = createEditorComponent());
  33178. editor->setText (getText());
  33179. editor->addListener (this);
  33180. editor->grabKeyboardFocus();
  33181. editor->setHighlightedRegion (0, text.length());
  33182. editor->addListener (this);
  33183. resized();
  33184. repaint();
  33185. enterModalState();
  33186. editor->grabKeyboardFocus();
  33187. }
  33188. }
  33189. bool Label::updateFromTextEditorContents()
  33190. {
  33191. jassert (editor != 0);
  33192. const String newText (editor->getText());
  33193. if (text != newText)
  33194. {
  33195. text = newText;
  33196. triggerAsyncUpdate();
  33197. repaint();
  33198. if (ownerComponent != 0 && ! deletionWatcher->hasBeenDeleted())
  33199. componentMovedOrResized (*ownerComponent, true, true);
  33200. return true;
  33201. }
  33202. return false;
  33203. }
  33204. void Label::hideEditor (const bool discardCurrentEditorContents)
  33205. {
  33206. if (editor != 0)
  33207. {
  33208. const bool changed = (! discardCurrentEditorContents)
  33209. && updateFromTextEditorContents();
  33210. deleteAndZero (editor);
  33211. repaint();
  33212. if (changed)
  33213. textWasEdited();
  33214. exitModalState (0);
  33215. }
  33216. }
  33217. void Label::inputAttemptWhenModal()
  33218. {
  33219. if (editor != 0)
  33220. {
  33221. if (lossOfFocusDiscardsChanges)
  33222. textEditorEscapeKeyPressed (*editor);
  33223. else
  33224. textEditorReturnKeyPressed (*editor);
  33225. }
  33226. }
  33227. bool Label::isBeingEdited() const throw()
  33228. {
  33229. return editor != 0;
  33230. }
  33231. TextEditor* Label::createEditorComponent()
  33232. {
  33233. TextEditor* const ed = new TextEditor (getName());
  33234. ed->setFont (font);
  33235. // copy these colours from our own settings..
  33236. const int cols[] = { TextEditor::backgroundColourId,
  33237. TextEditor::textColourId,
  33238. TextEditor::highlightColourId,
  33239. TextEditor::highlightedTextColourId,
  33240. TextEditor::caretColourId,
  33241. TextEditor::outlineColourId,
  33242. TextEditor::focusedOutlineColourId,
  33243. TextEditor::shadowColourId };
  33244. for (int i = 0; i < numElementsInArray (cols); ++i)
  33245. ed->setColour (cols[i], findColour (cols[i]));
  33246. return ed;
  33247. }
  33248. void Label::paint (Graphics& g)
  33249. {
  33250. g.fillAll (findColour (backgroundColourId));
  33251. if (editor == 0)
  33252. {
  33253. const float alpha = isEnabled() ? 1.0f : 0.5f;
  33254. g.setColour (findColour (textColourId).withMultipliedAlpha (alpha));
  33255. g.setFont (font);
  33256. g.drawFittedText (text,
  33257. 3, 1, getWidth() - 6, getHeight() - 2,
  33258. justification,
  33259. jmax (1, (int) (getHeight() / font.getHeight())));
  33260. g.setColour (findColour (outlineColourId).withMultipliedAlpha (alpha));
  33261. g.drawRect (0, 0, getWidth(), getHeight());
  33262. }
  33263. else if (isEnabled())
  33264. {
  33265. g.setColour (editor->findColour (TextEditor::backgroundColourId)
  33266. .overlaidWith (findColour (outlineColourId)));
  33267. g.drawRect (0, 0, getWidth(), getHeight());
  33268. }
  33269. }
  33270. void Label::mouseUp (const MouseEvent& e)
  33271. {
  33272. if (editSingleClick
  33273. && e.mouseWasClicked()
  33274. && contains (e.x, e.y)
  33275. && ! e.mods.isPopupMenu())
  33276. {
  33277. showEditor();
  33278. }
  33279. }
  33280. void Label::mouseDoubleClick (const MouseEvent& e)
  33281. {
  33282. if (editDoubleClick && ! e.mods.isPopupMenu())
  33283. showEditor();
  33284. }
  33285. void Label::resized()
  33286. {
  33287. if (editor != 0)
  33288. editor->setBoundsInset (BorderSize (0));
  33289. }
  33290. void Label::focusGained (FocusChangeType cause)
  33291. {
  33292. if (editSingleClick && cause == focusChangedByTabKey)
  33293. showEditor();
  33294. }
  33295. void Label::enablementChanged()
  33296. {
  33297. repaint();
  33298. }
  33299. void Label::colourChanged()
  33300. {
  33301. repaint();
  33302. }
  33303. // We'll use a custom focus traverser here to make sure focus goes from the
  33304. // text editor to another component rather than back to the label itself.
  33305. class LabelKeyboardFocusTraverser : public KeyboardFocusTraverser
  33306. {
  33307. public:
  33308. LabelKeyboardFocusTraverser() {}
  33309. Component* getNextComponent (Component* current)
  33310. {
  33311. return KeyboardFocusTraverser::getNextComponent (dynamic_cast <TextEditor*> (current) != 0
  33312. ? current->getParentComponent() : current);
  33313. }
  33314. Component* getPreviousComponent (Component* current)
  33315. {
  33316. return KeyboardFocusTraverser::getPreviousComponent (dynamic_cast <TextEditor*> (current) != 0
  33317. ? current->getParentComponent() : current);
  33318. }
  33319. };
  33320. KeyboardFocusTraverser* Label::createFocusTraverser()
  33321. {
  33322. return new LabelKeyboardFocusTraverser();
  33323. }
  33324. void Label::addListener (LabelListener* const listener) throw()
  33325. {
  33326. jassert (listener != 0);
  33327. if (listener != 0)
  33328. listeners.add (listener);
  33329. }
  33330. void Label::removeListener (LabelListener* const listener) throw()
  33331. {
  33332. listeners.removeValue (listener);
  33333. }
  33334. void Label::handleAsyncUpdate()
  33335. {
  33336. for (int i = listeners.size(); --i >= 0;)
  33337. {
  33338. ((LabelListener*) listeners.getUnchecked (i))->labelTextChanged (this);
  33339. i = jmin (i, listeners.size());
  33340. }
  33341. }
  33342. void Label::textEditorTextChanged (TextEditor& ed)
  33343. {
  33344. if (editor != 0)
  33345. {
  33346. jassert (&ed == editor);
  33347. if (! (hasKeyboardFocus (true) || isCurrentlyBlockedByAnotherModalComponent()))
  33348. {
  33349. if (lossOfFocusDiscardsChanges)
  33350. textEditorEscapeKeyPressed (ed);
  33351. else
  33352. textEditorReturnKeyPressed (ed);
  33353. }
  33354. }
  33355. }
  33356. void Label::textEditorReturnKeyPressed (TextEditor& ed)
  33357. {
  33358. if (editor != 0)
  33359. {
  33360. jassert (&ed == editor);
  33361. (void) ed;
  33362. const bool changed = updateFromTextEditorContents();
  33363. hideEditor (true);
  33364. if (changed)
  33365. textWasEdited();
  33366. }
  33367. }
  33368. void Label::textEditorEscapeKeyPressed (TextEditor& ed)
  33369. {
  33370. if (editor != 0)
  33371. {
  33372. jassert (&ed == editor);
  33373. (void) ed;
  33374. editor->setText (text, false);
  33375. hideEditor (true);
  33376. }
  33377. }
  33378. void Label::textEditorFocusLost (TextEditor& ed)
  33379. {
  33380. textEditorTextChanged (ed);
  33381. }
  33382. END_JUCE_NAMESPACE
  33383. /********* End of inlined file: juce_Label.cpp *********/
  33384. /********* Start of inlined file: juce_ListBox.cpp *********/
  33385. BEGIN_JUCE_NAMESPACE
  33386. class ListBoxRowComponent : public Component
  33387. {
  33388. public:
  33389. ListBoxRowComponent (ListBox& owner_)
  33390. : owner (owner_),
  33391. row (-1),
  33392. selected (false),
  33393. isDragging (false)
  33394. {
  33395. }
  33396. ~ListBoxRowComponent()
  33397. {
  33398. deleteAllChildren();
  33399. }
  33400. void paint (Graphics& g)
  33401. {
  33402. if (owner.getModel() != 0)
  33403. owner.getModel()->paintListBoxItem (row, g, getWidth(), getHeight(), selected);
  33404. }
  33405. void update (const int row_, const bool selected_)
  33406. {
  33407. if (row != row_ || selected != selected_)
  33408. {
  33409. repaint();
  33410. row = row_;
  33411. selected = selected_;
  33412. }
  33413. if (owner.getModel() != 0)
  33414. {
  33415. Component* const customComp = owner.getModel()->refreshComponentForRow (row_, selected_, getChildComponent (0));
  33416. if (customComp != 0)
  33417. {
  33418. addAndMakeVisible (customComp);
  33419. customComp->setBounds (0, 0, getWidth(), getHeight());
  33420. for (int i = getNumChildComponents(); --i >= 0;)
  33421. if (getChildComponent (i) != customComp)
  33422. delete getChildComponent (i);
  33423. }
  33424. else
  33425. {
  33426. deleteAllChildren();
  33427. }
  33428. }
  33429. }
  33430. void mouseDown (const MouseEvent& e)
  33431. {
  33432. isDragging = false;
  33433. selectRowOnMouseUp = false;
  33434. if (isEnabled())
  33435. {
  33436. if (! selected)
  33437. {
  33438. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  33439. if (owner.getModel() != 0)
  33440. owner.getModel()->listBoxItemClicked (row, e);
  33441. }
  33442. else
  33443. {
  33444. selectRowOnMouseUp = true;
  33445. }
  33446. }
  33447. }
  33448. void mouseUp (const MouseEvent& e)
  33449. {
  33450. if (isEnabled() && selectRowOnMouseUp && ! isDragging)
  33451. {
  33452. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  33453. if (owner.getModel() != 0)
  33454. owner.getModel()->listBoxItemClicked (row, e);
  33455. }
  33456. }
  33457. void mouseDoubleClick (const MouseEvent& e)
  33458. {
  33459. if (owner.getModel() != 0 && isEnabled())
  33460. owner.getModel()->listBoxItemDoubleClicked (row, e);
  33461. }
  33462. void mouseDrag (const MouseEvent& e)
  33463. {
  33464. if (isEnabled() && owner.getModel() != 0 && ! (e.mouseWasClicked() || isDragging))
  33465. {
  33466. const SparseSet <int> selectedRows (owner.getSelectedRows());
  33467. if (selectedRows.size() > 0)
  33468. {
  33469. const String dragDescription (owner.getModel()->getDragSourceDescription (selectedRows));
  33470. if (dragDescription.isNotEmpty())
  33471. {
  33472. isDragging = true;
  33473. DragAndDropContainer* const dragContainer
  33474. = DragAndDropContainer::findParentDragContainerFor (this);
  33475. if (dragContainer != 0)
  33476. {
  33477. Image* dragImage = owner.createSnapshotOfSelectedRows();
  33478. dragImage->multiplyAllAlphas (0.6f);
  33479. dragContainer->startDragging (dragDescription, &owner, dragImage, true);
  33480. }
  33481. else
  33482. {
  33483. // to be able to do a drag-and-drop operation, the listbox needs to
  33484. // be inside a component which is also a DragAndDropContainer.
  33485. jassertfalse
  33486. }
  33487. }
  33488. }
  33489. }
  33490. }
  33491. void resized()
  33492. {
  33493. if (getNumChildComponents() > 0)
  33494. getChildComponent(0)->setBounds (0, 0, getWidth(), getHeight());
  33495. }
  33496. juce_UseDebuggingNewOperator
  33497. bool neededFlag;
  33498. private:
  33499. ListBox& owner;
  33500. int row;
  33501. bool selected, isDragging, selectRowOnMouseUp;
  33502. ListBoxRowComponent (const ListBoxRowComponent&);
  33503. const ListBoxRowComponent& operator= (const ListBoxRowComponent&);
  33504. };
  33505. class ListViewport : public Viewport
  33506. {
  33507. public:
  33508. int firstIndex, firstWholeIndex, lastWholeIndex;
  33509. bool hasUpdated;
  33510. ListViewport (ListBox& owner_)
  33511. : owner (owner_)
  33512. {
  33513. setWantsKeyboardFocus (false);
  33514. setViewedComponent (new Component());
  33515. getViewedComponent()->addMouseListener (this, false);
  33516. getViewedComponent()->setWantsKeyboardFocus (false);
  33517. }
  33518. ~ListViewport()
  33519. {
  33520. getViewedComponent()->removeMouseListener (this);
  33521. getViewedComponent()->deleteAllChildren();
  33522. }
  33523. ListBoxRowComponent* getComponentForRow (const int row) const throw()
  33524. {
  33525. return (ListBoxRowComponent*) getViewedComponent()
  33526. ->getChildComponent (row % jmax (1, getViewedComponent()->getNumChildComponents()));
  33527. }
  33528. int getRowNumberOfComponent (Component* const rowComponent) const throw()
  33529. {
  33530. const int index = getIndexOfChildComponent (rowComponent);
  33531. const int num = getViewedComponent()->getNumChildComponents();
  33532. for (int i = num; --i >= 0;)
  33533. if (((firstIndex + i) % jmax (1, num)) == index)
  33534. return firstIndex + i;
  33535. return -1;
  33536. }
  33537. Component* getComponentForRowIfOnscreen (const int row) const throw()
  33538. {
  33539. return (row >= firstIndex && row < firstIndex + getViewedComponent()->getNumChildComponents())
  33540. ? getComponentForRow (row) : 0;
  33541. }
  33542. void visibleAreaChanged (int, int, int, int)
  33543. {
  33544. updateVisibleArea (true);
  33545. if (owner.getModel() != 0)
  33546. owner.getModel()->listWasScrolled();
  33547. }
  33548. void updateVisibleArea (const bool makeSureItUpdatesContent)
  33549. {
  33550. hasUpdated = false;
  33551. const int newX = getViewedComponent()->getX();
  33552. int newY = getViewedComponent()->getY();
  33553. const int newW = jmax (owner.minimumRowWidth, getMaximumVisibleWidth());
  33554. const int newH = owner.totalItems * owner.getRowHeight();
  33555. if (newY + newH < getMaximumVisibleHeight() && newH > getMaximumVisibleHeight())
  33556. newY = getMaximumVisibleHeight() - newH;
  33557. getViewedComponent()->setBounds (newX, newY, newW, newH);
  33558. if (makeSureItUpdatesContent && ! hasUpdated)
  33559. updateContents();
  33560. }
  33561. void updateContents()
  33562. {
  33563. hasUpdated = true;
  33564. const int rowHeight = owner.getRowHeight();
  33565. if (rowHeight > 0)
  33566. {
  33567. const int y = getViewPositionY();
  33568. const int w = getViewedComponent()->getWidth();
  33569. const int numNeeded = 2 + getMaximumVisibleHeight() / rowHeight;
  33570. while (numNeeded > getViewedComponent()->getNumChildComponents())
  33571. getViewedComponent()->addAndMakeVisible (new ListBoxRowComponent (owner));
  33572. jassert (numNeeded >= 0);
  33573. while (numNeeded < getViewedComponent()->getNumChildComponents())
  33574. {
  33575. Component* const rowToRemove
  33576. = getViewedComponent()->getChildComponent (getViewedComponent()->getNumChildComponents() - 1);
  33577. delete rowToRemove;
  33578. }
  33579. firstIndex = y / rowHeight;
  33580. firstWholeIndex = (y + rowHeight - 1) / rowHeight;
  33581. lastWholeIndex = (y + getMaximumVisibleHeight() - 1) / rowHeight;
  33582. for (int i = 0; i < numNeeded; ++i)
  33583. {
  33584. const int row = i + firstIndex;
  33585. ListBoxRowComponent* const rowComp = getComponentForRow (row);
  33586. if (rowComp != 0)
  33587. {
  33588. rowComp->setBounds (0, row * rowHeight, w, rowHeight);
  33589. rowComp->update (row, owner.isRowSelected (row));
  33590. }
  33591. }
  33592. }
  33593. if (owner.headerComponent != 0)
  33594. owner.headerComponent->setBounds (owner.outlineThickness + getViewedComponent()->getX(),
  33595. owner.outlineThickness,
  33596. jmax (owner.getWidth() - owner.outlineThickness * 2,
  33597. getViewedComponent()->getWidth()),
  33598. owner.headerComponent->getHeight());
  33599. }
  33600. void paint (Graphics& g)
  33601. {
  33602. if (isOpaque())
  33603. g.fillAll (owner.findColour (ListBox::backgroundColourId));
  33604. }
  33605. bool keyPressed (const KeyPress& key)
  33606. {
  33607. if (key.isKeyCode (KeyPress::upKey)
  33608. || key.isKeyCode (KeyPress::downKey)
  33609. || key.isKeyCode (KeyPress::pageUpKey)
  33610. || key.isKeyCode (KeyPress::pageDownKey)
  33611. || key.isKeyCode (KeyPress::homeKey)
  33612. || key.isKeyCode (KeyPress::endKey))
  33613. {
  33614. // we want to avoid these keypresses going to the viewport, and instead allow
  33615. // them to pass up to our listbox..
  33616. return false;
  33617. }
  33618. return Viewport::keyPressed (key);
  33619. }
  33620. juce_UseDebuggingNewOperator
  33621. private:
  33622. ListBox& owner;
  33623. ListViewport (const ListViewport&);
  33624. const ListViewport& operator= (const ListViewport&);
  33625. };
  33626. ListBox::ListBox (const String& name, ListBoxModel* const model_)
  33627. : Component (name),
  33628. model (model_),
  33629. headerComponent (0),
  33630. totalItems (0),
  33631. rowHeight (22),
  33632. minimumRowWidth (0),
  33633. outlineThickness (0),
  33634. lastRowSelected (-1),
  33635. mouseMoveSelects (false),
  33636. multipleSelection (false),
  33637. hasDoneInitialUpdate (false)
  33638. {
  33639. addAndMakeVisible (viewport = new ListViewport (*this));
  33640. setWantsKeyboardFocus (true);
  33641. }
  33642. ListBox::~ListBox()
  33643. {
  33644. deleteAllChildren();
  33645. }
  33646. void ListBox::setModel (ListBoxModel* const newModel)
  33647. {
  33648. if (model != newModel)
  33649. {
  33650. model = newModel;
  33651. updateContent();
  33652. }
  33653. }
  33654. void ListBox::setMultipleSelectionEnabled (bool b)
  33655. {
  33656. multipleSelection = b;
  33657. }
  33658. void ListBox::setMouseMoveSelectsRows (bool b)
  33659. {
  33660. mouseMoveSelects = b;
  33661. if (b)
  33662. addMouseListener (this, true);
  33663. }
  33664. void ListBox::paint (Graphics& g)
  33665. {
  33666. if (! hasDoneInitialUpdate)
  33667. updateContent();
  33668. g.fillAll (findColour (backgroundColourId));
  33669. }
  33670. void ListBox::paintOverChildren (Graphics& g)
  33671. {
  33672. if (outlineThickness > 0)
  33673. {
  33674. g.setColour (findColour (outlineColourId));
  33675. g.drawRect (0, 0, getWidth(), getHeight(), outlineThickness);
  33676. }
  33677. }
  33678. void ListBox::resized()
  33679. {
  33680. viewport->setBoundsInset (BorderSize (outlineThickness + ((headerComponent != 0) ? headerComponent->getHeight() : 0),
  33681. outlineThickness,
  33682. outlineThickness,
  33683. outlineThickness));
  33684. viewport->setSingleStepSizes (20, getRowHeight());
  33685. viewport->updateVisibleArea (false);
  33686. }
  33687. void ListBox::visibilityChanged()
  33688. {
  33689. viewport->updateVisibleArea (true);
  33690. }
  33691. Viewport* ListBox::getViewport() const throw()
  33692. {
  33693. return viewport;
  33694. }
  33695. void ListBox::updateContent()
  33696. {
  33697. hasDoneInitialUpdate = true;
  33698. totalItems = (model != 0) ? model->getNumRows() : 0;
  33699. bool selectionChanged = false;
  33700. if (selected [selected.size() - 1] >= totalItems)
  33701. {
  33702. selected.removeRange (totalItems, INT_MAX - totalItems);
  33703. lastRowSelected = getSelectedRow (0);
  33704. selectionChanged = true;
  33705. }
  33706. viewport->updateVisibleArea (isVisible());
  33707. viewport->resized();
  33708. if (selectionChanged && model != 0)
  33709. model->selectedRowsChanged (lastRowSelected);
  33710. }
  33711. void ListBox::selectRow (const int row,
  33712. bool dontScroll,
  33713. bool deselectOthersFirst)
  33714. {
  33715. selectRowInternal (row, dontScroll, deselectOthersFirst, false);
  33716. }
  33717. void ListBox::selectRowInternal (const int row,
  33718. bool dontScroll,
  33719. bool deselectOthersFirst,
  33720. bool isMouseClick)
  33721. {
  33722. if (! multipleSelection)
  33723. deselectOthersFirst = true;
  33724. if ((! isRowSelected (row))
  33725. || (deselectOthersFirst && getNumSelectedRows() > 1))
  33726. {
  33727. if (((unsigned int) row) < (unsigned int) totalItems)
  33728. {
  33729. if (deselectOthersFirst)
  33730. selected.clear();
  33731. selected.addRange (row, 1);
  33732. if (getHeight() == 0 || getWidth() == 0)
  33733. dontScroll = true;
  33734. viewport->hasUpdated = false;
  33735. if (row < viewport->firstWholeIndex && ! dontScroll)
  33736. {
  33737. viewport->setViewPosition (viewport->getViewPositionX(),
  33738. row * getRowHeight());
  33739. }
  33740. else if (row >= viewport->lastWholeIndex && ! dontScroll)
  33741. {
  33742. const int rowsOnScreen = viewport->lastWholeIndex - viewport->firstWholeIndex;
  33743. if (row >= lastRowSelected + rowsOnScreen
  33744. && rowsOnScreen < totalItems - 1
  33745. && ! isMouseClick)
  33746. {
  33747. viewport->setViewPosition (viewport->getViewPositionX(),
  33748. jlimit (0, jmax (0, totalItems - rowsOnScreen), row)
  33749. * getRowHeight());
  33750. }
  33751. else
  33752. {
  33753. viewport->setViewPosition (viewport->getViewPositionX(),
  33754. jmax (0, (row + 1) * getRowHeight() - viewport->getMaximumVisibleHeight()));
  33755. }
  33756. }
  33757. if (! viewport->hasUpdated)
  33758. viewport->updateContents();
  33759. lastRowSelected = row;
  33760. model->selectedRowsChanged (row);
  33761. }
  33762. else
  33763. {
  33764. if (deselectOthersFirst)
  33765. deselectAllRows();
  33766. }
  33767. }
  33768. }
  33769. void ListBox::deselectRow (const int row)
  33770. {
  33771. if (selected.contains (row))
  33772. {
  33773. selected.removeRange (row, 1);
  33774. if (row == lastRowSelected)
  33775. lastRowSelected = getSelectedRow (0);
  33776. viewport->updateContents();
  33777. model->selectedRowsChanged (lastRowSelected);
  33778. }
  33779. }
  33780. void ListBox::setSelectedRows (const SparseSet<int>& setOfRowsToBeSelected,
  33781. const bool sendNotificationEventToModel)
  33782. {
  33783. selected = setOfRowsToBeSelected;
  33784. selected.removeRange (totalItems, INT_MAX - totalItems);
  33785. if (! isRowSelected (lastRowSelected))
  33786. lastRowSelected = getSelectedRow (0);
  33787. viewport->updateContents();
  33788. if ((model != 0) && sendNotificationEventToModel)
  33789. model->selectedRowsChanged (lastRowSelected);
  33790. }
  33791. const SparseSet<int> ListBox::getSelectedRows() const
  33792. {
  33793. return selected;
  33794. }
  33795. void ListBox::selectRangeOfRows (int firstRow, int lastRow)
  33796. {
  33797. if (multipleSelection && (firstRow != lastRow))
  33798. {
  33799. const int numRows = totalItems - 1;
  33800. firstRow = jlimit (0, jmax (0, numRows), firstRow);
  33801. lastRow = jlimit (0, jmax (0, numRows), lastRow);
  33802. selected.addRange (jmin (firstRow, lastRow),
  33803. abs (firstRow - lastRow) + 1);
  33804. selected.removeRange (lastRow, 1);
  33805. }
  33806. selectRowInternal (lastRow, false, false, true);
  33807. }
  33808. void ListBox::flipRowSelection (const int row)
  33809. {
  33810. if (isRowSelected (row))
  33811. deselectRow (row);
  33812. else
  33813. selectRowInternal (row, false, false, true);
  33814. }
  33815. void ListBox::deselectAllRows()
  33816. {
  33817. if (! selected.isEmpty())
  33818. {
  33819. selected.clear();
  33820. lastRowSelected = -1;
  33821. viewport->updateContents();
  33822. if (model != 0)
  33823. model->selectedRowsChanged (lastRowSelected);
  33824. }
  33825. }
  33826. void ListBox::selectRowsBasedOnModifierKeys (const int row,
  33827. const ModifierKeys& mods)
  33828. {
  33829. if (multipleSelection && mods.isCommandDown())
  33830. {
  33831. flipRowSelection (row);
  33832. }
  33833. else if (multipleSelection && mods.isShiftDown() && lastRowSelected >= 0)
  33834. {
  33835. selectRangeOfRows (lastRowSelected, row);
  33836. }
  33837. else if ((! mods.isPopupMenu()) || ! isRowSelected (row))
  33838. {
  33839. selectRowInternal (row, false, true, true);
  33840. }
  33841. }
  33842. int ListBox::getNumSelectedRows() const
  33843. {
  33844. return selected.size();
  33845. }
  33846. int ListBox::getSelectedRow (const int index) const
  33847. {
  33848. return (((unsigned int) index) < (unsigned int) selected.size())
  33849. ? selected [index] : -1;
  33850. }
  33851. bool ListBox::isRowSelected (const int row) const
  33852. {
  33853. return selected.contains (row);
  33854. }
  33855. int ListBox::getLastRowSelected() const
  33856. {
  33857. return (isRowSelected (lastRowSelected)) ? lastRowSelected : -1;
  33858. }
  33859. int ListBox::getRowContainingPosition (const int x, const int y) const throw()
  33860. {
  33861. if (((unsigned int) x) < (unsigned int) getWidth())
  33862. {
  33863. const int row = (viewport->getViewPositionY() + y - viewport->getY()) / rowHeight;
  33864. if (((unsigned int) row) < (unsigned int) totalItems)
  33865. return row;
  33866. }
  33867. return -1;
  33868. }
  33869. int ListBox::getInsertionIndexForPosition (const int x, const int y) const throw()
  33870. {
  33871. if (((unsigned int) x) < (unsigned int) getWidth())
  33872. {
  33873. const int row = (viewport->getViewPositionY() + y + rowHeight / 2 - viewport->getY()) / rowHeight;
  33874. return jlimit (0, totalItems, row);
  33875. }
  33876. return -1;
  33877. }
  33878. Component* ListBox::getComponentForRowNumber (const int row) const throw()
  33879. {
  33880. Component* const listRowComp = viewport->getComponentForRowIfOnscreen (row);
  33881. return listRowComp != 0 ? listRowComp->getChildComponent (0) : 0;
  33882. }
  33883. int ListBox::getRowNumberOfComponent (Component* const rowComponent) const throw()
  33884. {
  33885. return viewport->getRowNumberOfComponent (rowComponent);
  33886. }
  33887. const Rectangle ListBox::getRowPosition (const int rowNumber,
  33888. const bool relativeToComponentTopLeft) const throw()
  33889. {
  33890. const int rowHeight = getRowHeight();
  33891. int y = viewport->getY() + rowHeight * rowNumber;
  33892. if (relativeToComponentTopLeft)
  33893. y -= viewport->getViewPositionY();
  33894. return Rectangle (viewport->getX(), y,
  33895. viewport->getViewedComponent()->getWidth(), rowHeight);
  33896. }
  33897. void ListBox::setVerticalPosition (const double proportion)
  33898. {
  33899. const int offscreen = viewport->getViewedComponent()->getHeight() - viewport->getHeight();
  33900. viewport->setViewPosition (viewport->getViewPositionX(),
  33901. jmax (0, roundDoubleToInt (proportion * offscreen)));
  33902. }
  33903. double ListBox::getVerticalPosition() const
  33904. {
  33905. const int offscreen = viewport->getViewedComponent()->getHeight() - viewport->getHeight();
  33906. return (offscreen > 0) ? viewport->getViewPositionY() / (double) offscreen
  33907. : 0;
  33908. }
  33909. int ListBox::getVisibleRowWidth() const throw()
  33910. {
  33911. return viewport->getViewWidth();
  33912. }
  33913. void ListBox::scrollToEnsureRowIsOnscreen (const int row)
  33914. {
  33915. if (row < viewport->firstWholeIndex)
  33916. {
  33917. viewport->setViewPosition (viewport->getViewPositionX(),
  33918. row * getRowHeight());
  33919. }
  33920. else if (row >= viewport->lastWholeIndex)
  33921. {
  33922. viewport->setViewPosition (viewport->getViewPositionX(),
  33923. jmax (0, (row + 1) * getRowHeight() - viewport->getMaximumVisibleHeight()));
  33924. }
  33925. }
  33926. bool ListBox::keyPressed (const KeyPress& key)
  33927. {
  33928. const int numVisibleRows = viewport->getHeight() / getRowHeight();
  33929. const bool multiple = multipleSelection
  33930. && (lastRowSelected >= 0)
  33931. && (key.getModifiers().isShiftDown()
  33932. || key.getModifiers().isCtrlDown()
  33933. || key.getModifiers().isCommandDown());
  33934. if (key.isKeyCode (KeyPress::upKey))
  33935. {
  33936. if (multiple)
  33937. selectRangeOfRows (lastRowSelected, lastRowSelected - 1);
  33938. else
  33939. selectRow (jmax (0, lastRowSelected - 1));
  33940. }
  33941. else if (key.isKeyCode (KeyPress::returnKey)
  33942. && isRowSelected (lastRowSelected))
  33943. {
  33944. if (model != 0)
  33945. model->returnKeyPressed (lastRowSelected);
  33946. }
  33947. else if (key.isKeyCode (KeyPress::pageUpKey))
  33948. {
  33949. if (multiple)
  33950. selectRangeOfRows (lastRowSelected, lastRowSelected - numVisibleRows);
  33951. else
  33952. selectRow (jmax (0, jmax (0, lastRowSelected) - numVisibleRows));
  33953. }
  33954. else if (key.isKeyCode (KeyPress::pageDownKey))
  33955. {
  33956. if (multiple)
  33957. selectRangeOfRows (lastRowSelected, lastRowSelected + numVisibleRows);
  33958. else
  33959. selectRow (jmin (totalItems - 1, jmax (0, lastRowSelected) + numVisibleRows));
  33960. }
  33961. else if (key.isKeyCode (KeyPress::homeKey))
  33962. {
  33963. if (multiple && key.getModifiers().isShiftDown())
  33964. selectRangeOfRows (lastRowSelected, 0);
  33965. else
  33966. selectRow (0);
  33967. }
  33968. else if (key.isKeyCode (KeyPress::endKey))
  33969. {
  33970. if (multiple && key.getModifiers().isShiftDown())
  33971. selectRangeOfRows (lastRowSelected, totalItems - 1);
  33972. else
  33973. selectRow (totalItems - 1);
  33974. }
  33975. else if (key.isKeyCode (KeyPress::downKey))
  33976. {
  33977. if (multiple)
  33978. selectRangeOfRows (lastRowSelected, lastRowSelected + 1);
  33979. else
  33980. selectRow (jmin (totalItems - 1, jmax (0, lastRowSelected) + 1));
  33981. }
  33982. else if ((key.isKeyCode (KeyPress::deleteKey) || key.isKeyCode (KeyPress::backspaceKey))
  33983. && isRowSelected (lastRowSelected))
  33984. {
  33985. if (model != 0)
  33986. model->deleteKeyPressed (lastRowSelected);
  33987. }
  33988. else if (multiple && key == KeyPress (T('a'), ModifierKeys::commandModifier, 0))
  33989. {
  33990. selectRangeOfRows (0, INT_MAX);
  33991. }
  33992. else
  33993. {
  33994. return false;
  33995. }
  33996. return true;
  33997. }
  33998. bool ListBox::keyStateChanged()
  33999. {
  34000. return KeyPress::isKeyCurrentlyDown (KeyPress::upKey)
  34001. || KeyPress::isKeyCurrentlyDown (KeyPress::pageUpKey)
  34002. || KeyPress::isKeyCurrentlyDown (KeyPress::downKey)
  34003. || KeyPress::isKeyCurrentlyDown (KeyPress::pageDownKey)
  34004. || KeyPress::isKeyCurrentlyDown (KeyPress::homeKey)
  34005. || KeyPress::isKeyCurrentlyDown (KeyPress::endKey)
  34006. || KeyPress::isKeyCurrentlyDown (KeyPress::returnKey);
  34007. }
  34008. void ListBox::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  34009. {
  34010. getHorizontalScrollBar()->mouseWheelMove (e, wheelIncrementX, 0);
  34011. getVerticalScrollBar()->mouseWheelMove (e, 0, wheelIncrementY);
  34012. }
  34013. void ListBox::mouseMove (const MouseEvent& e)
  34014. {
  34015. if (mouseMoveSelects)
  34016. {
  34017. const MouseEvent e2 (e.getEventRelativeTo (this));
  34018. selectRow (getRowContainingPosition (e2.x, e2.y), true);
  34019. lastMouseX = e2.x;
  34020. lastMouseY = e2.y;
  34021. }
  34022. }
  34023. void ListBox::mouseExit (const MouseEvent& e)
  34024. {
  34025. mouseMove (e);
  34026. }
  34027. void ListBox::mouseUp (const MouseEvent& e)
  34028. {
  34029. if (e.mouseWasClicked() && model != 0)
  34030. model->backgroundClicked();
  34031. }
  34032. void ListBox::setRowHeight (const int newHeight)
  34033. {
  34034. rowHeight = jmax (1, newHeight);
  34035. viewport->setSingleStepSizes (20, rowHeight);
  34036. updateContent();
  34037. }
  34038. int ListBox::getNumRowsOnScreen() const throw()
  34039. {
  34040. return viewport->getMaximumVisibleHeight() / rowHeight;
  34041. }
  34042. void ListBox::setMinimumContentWidth (const int newMinimumWidth)
  34043. {
  34044. minimumRowWidth = newMinimumWidth;
  34045. updateContent();
  34046. }
  34047. int ListBox::getVisibleContentWidth() const throw()
  34048. {
  34049. return viewport->getMaximumVisibleWidth();
  34050. }
  34051. ScrollBar* ListBox::getVerticalScrollBar() const throw()
  34052. {
  34053. return viewport->getVerticalScrollBar();
  34054. }
  34055. ScrollBar* ListBox::getHorizontalScrollBar() const throw()
  34056. {
  34057. return viewport->getHorizontalScrollBar();
  34058. }
  34059. void ListBox::colourChanged()
  34060. {
  34061. setOpaque (findColour (backgroundColourId).isOpaque());
  34062. viewport->setOpaque (isOpaque());
  34063. repaint();
  34064. }
  34065. void ListBox::setOutlineThickness (const int outlineThickness_)
  34066. {
  34067. outlineThickness = outlineThickness_;
  34068. resized();
  34069. }
  34070. void ListBox::setHeaderComponent (Component* const newHeaderComponent)
  34071. {
  34072. if (headerComponent != newHeaderComponent)
  34073. {
  34074. if (headerComponent != 0)
  34075. delete headerComponent;
  34076. headerComponent = newHeaderComponent;
  34077. addAndMakeVisible (newHeaderComponent);
  34078. ListBox::resized();
  34079. }
  34080. }
  34081. void ListBox::repaintRow (const int rowNumber) throw()
  34082. {
  34083. const Rectangle r (getRowPosition (rowNumber, true));
  34084. repaint (r.getX(), r.getY(), r.getWidth(), r.getHeight());
  34085. }
  34086. Image* ListBox::createSnapshotOfSelectedRows()
  34087. {
  34088. Image* snapshot = new Image (Image::ARGB, getWidth(), getHeight(), true);
  34089. Graphics g (*snapshot);
  34090. const int firstRow = getRowContainingPosition (0, 0);
  34091. for (int i = getNumRowsOnScreen() + 2; --i >= 0;)
  34092. {
  34093. Component* rowComp = viewport->getComponentForRowIfOnscreen (firstRow + i);
  34094. if (rowComp != 0 && isRowSelected (firstRow + i))
  34095. {
  34096. g.saveState();
  34097. int x = 0, y = 0;
  34098. rowComp->relativePositionToOtherComponent (this, x, y);
  34099. g.setOrigin (x, y);
  34100. g.reduceClipRegion (0, 0, rowComp->getWidth(), rowComp->getHeight());
  34101. rowComp->paintEntireComponent (g);
  34102. g.restoreState();
  34103. }
  34104. }
  34105. return snapshot;
  34106. }
  34107. Component* ListBoxModel::refreshComponentForRow (int, bool, Component* existingComponentToUpdate)
  34108. {
  34109. (void) existingComponentToUpdate;
  34110. jassert (existingComponentToUpdate == 0); // indicates a failure in the code the recycles the components
  34111. return 0;
  34112. }
  34113. void ListBoxModel::listBoxItemClicked (int, const MouseEvent&)
  34114. {
  34115. }
  34116. void ListBoxModel::listBoxItemDoubleClicked (int, const MouseEvent&)
  34117. {
  34118. }
  34119. void ListBoxModel::backgroundClicked()
  34120. {
  34121. }
  34122. void ListBoxModel::selectedRowsChanged (int)
  34123. {
  34124. }
  34125. void ListBoxModel::deleteKeyPressed (int)
  34126. {
  34127. }
  34128. void ListBoxModel::returnKeyPressed (int)
  34129. {
  34130. }
  34131. void ListBoxModel::listWasScrolled()
  34132. {
  34133. }
  34134. const String ListBoxModel::getDragSourceDescription (const SparseSet<int>&)
  34135. {
  34136. return String::empty;
  34137. }
  34138. END_JUCE_NAMESPACE
  34139. /********* End of inlined file: juce_ListBox.cpp *********/
  34140. /********* Start of inlined file: juce_ProgressBar.cpp *********/
  34141. BEGIN_JUCE_NAMESPACE
  34142. ProgressBar::ProgressBar (double& progress_)
  34143. : progress (progress_),
  34144. displayPercentage (true)
  34145. {
  34146. currentValue = jlimit (0.0, 1.0, progress);
  34147. }
  34148. ProgressBar::~ProgressBar()
  34149. {
  34150. }
  34151. void ProgressBar::setPercentageDisplay (const bool shouldDisplayPercentage)
  34152. {
  34153. displayPercentage = shouldDisplayPercentage;
  34154. repaint();
  34155. }
  34156. void ProgressBar::setTextToDisplay (const String& text)
  34157. {
  34158. displayPercentage = false;
  34159. displayedMessage = text;
  34160. }
  34161. void ProgressBar::lookAndFeelChanged()
  34162. {
  34163. setOpaque (findColour (backgroundColourId).isOpaque());
  34164. }
  34165. void ProgressBar::colourChanged()
  34166. {
  34167. lookAndFeelChanged();
  34168. }
  34169. void ProgressBar::paint (Graphics& g)
  34170. {
  34171. String text;
  34172. if (displayPercentage)
  34173. {
  34174. if (currentValue >= 0 && currentValue <= 1.0)
  34175. text << roundDoubleToInt (currentValue * 100.0) << T("%");
  34176. }
  34177. else
  34178. {
  34179. text = displayedMessage;
  34180. }
  34181. getLookAndFeel().drawProgressBar (g, *this,
  34182. getWidth(), getHeight(),
  34183. currentValue, text);
  34184. }
  34185. void ProgressBar::visibilityChanged()
  34186. {
  34187. if (isVisible())
  34188. startTimer (30);
  34189. else
  34190. stopTimer();
  34191. }
  34192. void ProgressBar::timerCallback()
  34193. {
  34194. double newProgress = progress;
  34195. if (currentValue != newProgress
  34196. || newProgress < 0 || newProgress >= 1.0
  34197. || currentMessage != displayedMessage)
  34198. {
  34199. if (currentValue < newProgress
  34200. && newProgress >= 0 && newProgress < 1.0
  34201. && currentValue >= 0 && newProgress < 1.0)
  34202. {
  34203. newProgress = jmin (currentValue + 0.02, newProgress);
  34204. }
  34205. currentValue = newProgress;
  34206. currentMessage = displayedMessage;
  34207. repaint();
  34208. }
  34209. }
  34210. END_JUCE_NAMESPACE
  34211. /********* End of inlined file: juce_ProgressBar.cpp *********/
  34212. /********* Start of inlined file: juce_Slider.cpp *********/
  34213. BEGIN_JUCE_NAMESPACE
  34214. class SliderPopupDisplayComponent : public BubbleComponent
  34215. {
  34216. public:
  34217. SliderPopupDisplayComponent (Slider* const owner_)
  34218. : owner (owner_),
  34219. font (15.0f, Font::bold)
  34220. {
  34221. setAlwaysOnTop (true);
  34222. }
  34223. ~SliderPopupDisplayComponent()
  34224. {
  34225. }
  34226. void paintContent (Graphics& g, int w, int h)
  34227. {
  34228. g.setFont (font);
  34229. g.setColour (Colours::black);
  34230. g.drawFittedText (text, 0, 0, w, h, Justification::centred, 1);
  34231. }
  34232. void getContentSize (int& w, int& h)
  34233. {
  34234. w = font.getStringWidth (text) + 18;
  34235. h = (int) (font.getHeight() * 1.6f);
  34236. }
  34237. void updatePosition (const String& newText)
  34238. {
  34239. if (text != newText)
  34240. {
  34241. text = newText;
  34242. repaint();
  34243. }
  34244. BubbleComponent::setPosition (owner);
  34245. }
  34246. juce_UseDebuggingNewOperator
  34247. private:
  34248. Slider* owner;
  34249. Font font;
  34250. String text;
  34251. SliderPopupDisplayComponent (const SliderPopupDisplayComponent&);
  34252. const SliderPopupDisplayComponent& operator= (const SliderPopupDisplayComponent&);
  34253. };
  34254. Slider::Slider (const String& name)
  34255. : Component (name),
  34256. listeners (2),
  34257. currentValue (0.0),
  34258. valueMin (0.0),
  34259. valueMax (0.0),
  34260. minimum (0),
  34261. maximum (10),
  34262. interval (0),
  34263. skewFactor (1.0),
  34264. velocityModeSensitivity (1.0),
  34265. velocityModeOffset (0.0),
  34266. velocityModeThreshold (1),
  34267. rotaryStart (float_Pi * 1.2f),
  34268. rotaryEnd (float_Pi * 2.8f),
  34269. numDecimalPlaces (7),
  34270. sliderRegionStart (0),
  34271. sliderRegionSize (1),
  34272. pixelsForFullDragExtent (250),
  34273. style (LinearHorizontal),
  34274. textBoxPos (TextBoxLeft),
  34275. textBoxWidth (80),
  34276. textBoxHeight (20),
  34277. incDecButtonMode (incDecButtonsNotDraggable),
  34278. editableText (true),
  34279. doubleClickToValue (false),
  34280. isVelocityBased (false),
  34281. userKeyOverridesVelocity (true),
  34282. rotaryStop (true),
  34283. incDecButtonsSideBySide (false),
  34284. sendChangeOnlyOnRelease (false),
  34285. popupDisplayEnabled (false),
  34286. menuEnabled (false),
  34287. menuShown (false),
  34288. scrollWheelEnabled (true),
  34289. snapsToMousePos (true),
  34290. valueBox (0),
  34291. incButton (0),
  34292. decButton (0),
  34293. popupDisplay (0),
  34294. parentForPopupDisplay (0)
  34295. {
  34296. setWantsKeyboardFocus (false);
  34297. setRepaintsOnMouseActivity (true);
  34298. lookAndFeelChanged();
  34299. updateText();
  34300. }
  34301. Slider::~Slider()
  34302. {
  34303. deleteAndZero (popupDisplay);
  34304. deleteAllChildren();
  34305. }
  34306. void Slider::handleAsyncUpdate()
  34307. {
  34308. cancelPendingUpdate();
  34309. for (int i = listeners.size(); --i >= 0;)
  34310. {
  34311. ((SliderListener*) listeners.getUnchecked (i))->sliderValueChanged (this);
  34312. i = jmin (i, listeners.size());
  34313. }
  34314. }
  34315. void Slider::sendDragStart()
  34316. {
  34317. startedDragging();
  34318. for (int i = listeners.size(); --i >= 0;)
  34319. {
  34320. ((SliderListener*) listeners.getUnchecked (i))->sliderDragStarted (this);
  34321. i = jmin (i, listeners.size());
  34322. }
  34323. }
  34324. void Slider::sendDragEnd()
  34325. {
  34326. stoppedDragging();
  34327. for (int i = listeners.size(); --i >= 0;)
  34328. {
  34329. ((SliderListener*) listeners.getUnchecked (i))->sliderDragEnded (this);
  34330. i = jmin (i, listeners.size());
  34331. }
  34332. }
  34333. void Slider::addListener (SliderListener* const listener) throw()
  34334. {
  34335. jassert (listener != 0);
  34336. if (listener != 0)
  34337. listeners.add (listener);
  34338. }
  34339. void Slider::removeListener (SliderListener* const listener) throw()
  34340. {
  34341. listeners.removeValue (listener);
  34342. }
  34343. void Slider::setSliderStyle (const SliderStyle newStyle)
  34344. {
  34345. if (style != newStyle)
  34346. {
  34347. style = newStyle;
  34348. repaint();
  34349. lookAndFeelChanged();
  34350. }
  34351. }
  34352. void Slider::setRotaryParameters (const float startAngleRadians,
  34353. const float endAngleRadians,
  34354. const bool stopAtEnd)
  34355. {
  34356. // make sure the values are sensible..
  34357. jassert (rotaryStart >= 0 && rotaryEnd >= 0);
  34358. jassert (rotaryStart < float_Pi * 4.0f && rotaryEnd < float_Pi * 4.0f);
  34359. jassert (rotaryStart < rotaryEnd);
  34360. rotaryStart = startAngleRadians;
  34361. rotaryEnd = endAngleRadians;
  34362. rotaryStop = stopAtEnd;
  34363. }
  34364. void Slider::setVelocityBasedMode (const bool velBased) throw()
  34365. {
  34366. isVelocityBased = velBased;
  34367. }
  34368. void Slider::setVelocityModeParameters (const double sensitivity,
  34369. const int threshold,
  34370. const double offset,
  34371. const bool userCanPressKeyToSwapMode) throw()
  34372. {
  34373. jassert (threshold >= 0);
  34374. jassert (sensitivity > 0);
  34375. jassert (offset >= 0);
  34376. velocityModeSensitivity = sensitivity;
  34377. velocityModeOffset = offset;
  34378. velocityModeThreshold = threshold;
  34379. userKeyOverridesVelocity = userCanPressKeyToSwapMode;
  34380. }
  34381. void Slider::setSkewFactor (const double factor) throw()
  34382. {
  34383. skewFactor = factor;
  34384. }
  34385. void Slider::setSkewFactorFromMidPoint (const double sliderValueToShowAtMidPoint) throw()
  34386. {
  34387. if (maximum > minimum)
  34388. skewFactor = log (0.5) / log ((sliderValueToShowAtMidPoint - minimum)
  34389. / (maximum - minimum));
  34390. }
  34391. void Slider::setMouseDragSensitivity (const int distanceForFullScaleDrag)
  34392. {
  34393. jassert (distanceForFullScaleDrag > 0);
  34394. pixelsForFullDragExtent = distanceForFullScaleDrag;
  34395. }
  34396. void Slider::setIncDecButtonsMode (const IncDecButtonMode mode)
  34397. {
  34398. if (incDecButtonMode != mode)
  34399. {
  34400. incDecButtonMode = mode;
  34401. lookAndFeelChanged();
  34402. }
  34403. }
  34404. void Slider::setTextBoxStyle (const TextEntryBoxPosition newPosition,
  34405. const bool isReadOnly,
  34406. const int textEntryBoxWidth,
  34407. const int textEntryBoxHeight)
  34408. {
  34409. textBoxPos = newPosition;
  34410. editableText = ! isReadOnly;
  34411. textBoxWidth = textEntryBoxWidth;
  34412. textBoxHeight = textEntryBoxHeight;
  34413. repaint();
  34414. lookAndFeelChanged();
  34415. }
  34416. void Slider::setTextBoxIsEditable (const bool shouldBeEditable) throw()
  34417. {
  34418. editableText = shouldBeEditable;
  34419. if (valueBox != 0)
  34420. valueBox->setEditable (shouldBeEditable && isEnabled());
  34421. }
  34422. void Slider::showTextBox()
  34423. {
  34424. jassert (editableText); // this should probably be avoided in read-only sliders.
  34425. if (valueBox != 0)
  34426. valueBox->showEditor();
  34427. }
  34428. void Slider::hideTextBox (const bool discardCurrentEditorContents)
  34429. {
  34430. if (valueBox != 0)
  34431. {
  34432. valueBox->hideEditor (discardCurrentEditorContents);
  34433. if (discardCurrentEditorContents)
  34434. updateText();
  34435. }
  34436. }
  34437. void Slider::setChangeNotificationOnlyOnRelease (const bool onlyNotifyOnRelease) throw()
  34438. {
  34439. sendChangeOnlyOnRelease = onlyNotifyOnRelease;
  34440. }
  34441. void Slider::setSliderSnapsToMousePosition (const bool shouldSnapToMouse) throw()
  34442. {
  34443. snapsToMousePos = shouldSnapToMouse;
  34444. }
  34445. void Slider::setPopupDisplayEnabled (const bool enabled,
  34446. Component* const parentComponentToUse) throw()
  34447. {
  34448. popupDisplayEnabled = enabled;
  34449. parentForPopupDisplay = parentComponentToUse;
  34450. }
  34451. void Slider::colourChanged()
  34452. {
  34453. lookAndFeelChanged();
  34454. }
  34455. void Slider::lookAndFeelChanged()
  34456. {
  34457. const String previousTextBoxContent (valueBox != 0 ? valueBox->getText()
  34458. : getTextFromValue (currentValue));
  34459. deleteAllChildren();
  34460. valueBox = 0;
  34461. LookAndFeel& lf = getLookAndFeel();
  34462. if (textBoxPos != NoTextBox)
  34463. {
  34464. addAndMakeVisible (valueBox = getLookAndFeel().createSliderTextBox (*this));
  34465. valueBox->setWantsKeyboardFocus (false);
  34466. valueBox->setText (previousTextBoxContent, false);
  34467. valueBox->setEditable (editableText && isEnabled());
  34468. valueBox->addListener (this);
  34469. if (style == LinearBar)
  34470. valueBox->addMouseListener (this, false);
  34471. }
  34472. if (style == IncDecButtons)
  34473. {
  34474. addAndMakeVisible (incButton = lf.createSliderButton (true));
  34475. incButton->addButtonListener (this);
  34476. addAndMakeVisible (decButton = lf.createSliderButton (false));
  34477. decButton->addButtonListener (this);
  34478. if (incDecButtonMode != incDecButtonsNotDraggable)
  34479. {
  34480. incButton->addMouseListener (this, false);
  34481. decButton->addMouseListener (this, false);
  34482. }
  34483. else
  34484. {
  34485. incButton->setRepeatSpeed (300, 100, 20);
  34486. incButton->addMouseListener (decButton, false);
  34487. decButton->setRepeatSpeed (300, 100, 20);
  34488. decButton->addMouseListener (incButton, false);
  34489. }
  34490. }
  34491. setComponentEffect (lf.getSliderEffect());
  34492. resized();
  34493. repaint();
  34494. }
  34495. void Slider::setRange (const double newMin,
  34496. const double newMax,
  34497. const double newInt)
  34498. {
  34499. if (minimum != newMin
  34500. || maximum != newMax
  34501. || interval != newInt)
  34502. {
  34503. minimum = newMin;
  34504. maximum = newMax;
  34505. interval = newInt;
  34506. // figure out the number of DPs needed to display all values at this
  34507. // interval setting.
  34508. numDecimalPlaces = 7;
  34509. if (newInt != 0)
  34510. {
  34511. int v = abs ((int) (newInt * 10000000));
  34512. while ((v % 10) == 0)
  34513. {
  34514. --numDecimalPlaces;
  34515. v /= 10;
  34516. }
  34517. }
  34518. // keep the current values inside the new range..
  34519. if (style != TwoValueHorizontal && style != TwoValueVertical)
  34520. {
  34521. setValue (currentValue, false, false);
  34522. }
  34523. else
  34524. {
  34525. setMinValue (getMinValue(), false, false);
  34526. setMaxValue (getMaxValue(), false, false);
  34527. }
  34528. updateText();
  34529. }
  34530. }
  34531. void Slider::triggerChangeMessage (const bool synchronous)
  34532. {
  34533. if (synchronous)
  34534. handleAsyncUpdate();
  34535. else
  34536. triggerAsyncUpdate();
  34537. valueChanged();
  34538. }
  34539. double Slider::getValue() const throw()
  34540. {
  34541. // for a two-value style slider, you should use the getMinValue() and getMaxValue()
  34542. // methods to get the two values.
  34543. jassert (style != TwoValueHorizontal && style != TwoValueVertical);
  34544. return currentValue;
  34545. }
  34546. void Slider::setValue (double newValue,
  34547. const bool sendUpdateMessage,
  34548. const bool sendMessageSynchronously)
  34549. {
  34550. // for a two-value style slider, you should use the setMinValue() and setMaxValue()
  34551. // methods to set the two values.
  34552. jassert (style != TwoValueHorizontal && style != TwoValueVertical);
  34553. newValue = constrainedValue (newValue);
  34554. if (style == ThreeValueHorizontal || style == ThreeValueVertical)
  34555. {
  34556. jassert (valueMin <= valueMax);
  34557. newValue = jlimit (valueMin, valueMax, newValue);
  34558. }
  34559. if (currentValue != newValue)
  34560. {
  34561. if (valueBox != 0)
  34562. valueBox->hideEditor (true);
  34563. currentValue = newValue;
  34564. updateText();
  34565. repaint();
  34566. if (popupDisplay != 0)
  34567. {
  34568. ((SliderPopupDisplayComponent*) popupDisplay)->updatePosition (getTextFromValue (currentValue));
  34569. popupDisplay->repaint();
  34570. }
  34571. if (sendUpdateMessage)
  34572. triggerChangeMessage (sendMessageSynchronously);
  34573. }
  34574. }
  34575. double Slider::getMinValue() const throw()
  34576. {
  34577. // The minimum value only applies to sliders that are in two- or three-value mode.
  34578. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  34579. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  34580. return valueMin;
  34581. }
  34582. double Slider::getMaxValue() const throw()
  34583. {
  34584. // The maximum value only applies to sliders that are in two- or three-value mode.
  34585. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  34586. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  34587. return valueMax;
  34588. }
  34589. void Slider::setMinValue (double newValue, const bool sendUpdateMessage, const bool sendMessageSynchronously)
  34590. {
  34591. // The minimum value only applies to sliders that are in two- or three-value mode.
  34592. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  34593. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  34594. newValue = constrainedValue (newValue);
  34595. if (style == TwoValueHorizontal || style == TwoValueVertical)
  34596. newValue = jmin (valueMax, newValue);
  34597. else
  34598. newValue = jmin (currentValue, newValue);
  34599. if (valueMin != newValue)
  34600. {
  34601. valueMin = newValue;
  34602. repaint();
  34603. if (popupDisplay != 0)
  34604. {
  34605. ((SliderPopupDisplayComponent*) popupDisplay)->updatePosition (getTextFromValue (valueMin));
  34606. popupDisplay->repaint();
  34607. }
  34608. if (sendUpdateMessage)
  34609. triggerChangeMessage (sendMessageSynchronously);
  34610. }
  34611. }
  34612. void Slider::setMaxValue (double newValue, const bool sendUpdateMessage, const bool sendMessageSynchronously)
  34613. {
  34614. // The maximum value only applies to sliders that are in two- or three-value mode.
  34615. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  34616. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  34617. newValue = constrainedValue (newValue);
  34618. if (style == TwoValueHorizontal || style == TwoValueVertical)
  34619. newValue = jmax (valueMin, newValue);
  34620. else
  34621. newValue = jmax (currentValue, newValue);
  34622. if (valueMax != newValue)
  34623. {
  34624. valueMax = newValue;
  34625. repaint();
  34626. if (popupDisplay != 0)
  34627. {
  34628. ((SliderPopupDisplayComponent*) popupDisplay)->updatePosition (getTextFromValue (valueMax));
  34629. popupDisplay->repaint();
  34630. }
  34631. if (sendUpdateMessage)
  34632. triggerChangeMessage (sendMessageSynchronously);
  34633. }
  34634. }
  34635. void Slider::setDoubleClickReturnValue (const bool isDoubleClickEnabled,
  34636. const double valueToSetOnDoubleClick) throw()
  34637. {
  34638. doubleClickToValue = isDoubleClickEnabled;
  34639. doubleClickReturnValue = valueToSetOnDoubleClick;
  34640. }
  34641. double Slider::getDoubleClickReturnValue (bool& isEnabled_) const throw()
  34642. {
  34643. isEnabled_ = doubleClickToValue;
  34644. return doubleClickReturnValue;
  34645. }
  34646. void Slider::updateText()
  34647. {
  34648. if (valueBox != 0)
  34649. valueBox->setText (getTextFromValue (currentValue), false);
  34650. }
  34651. void Slider::setTextValueSuffix (const String& suffix)
  34652. {
  34653. if (textSuffix != suffix)
  34654. {
  34655. textSuffix = suffix;
  34656. updateText();
  34657. }
  34658. }
  34659. const String Slider::getTextFromValue (double v)
  34660. {
  34661. if (numDecimalPlaces > 0)
  34662. return String (v, numDecimalPlaces) + textSuffix;
  34663. else
  34664. return String (roundDoubleToInt (v)) + textSuffix;
  34665. }
  34666. double Slider::getValueFromText (const String& text)
  34667. {
  34668. String t (text.trimStart());
  34669. if (t.endsWith (textSuffix))
  34670. t = t.substring (0, t.length() - textSuffix.length());
  34671. while (t.startsWithChar (T('+')))
  34672. t = t.substring (1).trimStart();
  34673. return t.initialSectionContainingOnly (T("0123456789.,-"))
  34674. .getDoubleValue();
  34675. }
  34676. double Slider::proportionOfLengthToValue (double proportion)
  34677. {
  34678. if (skewFactor != 1.0 && proportion > 0.0)
  34679. proportion = exp (log (proportion) / skewFactor);
  34680. return minimum + (maximum - minimum) * proportion;
  34681. }
  34682. double Slider::valueToProportionOfLength (double value)
  34683. {
  34684. const double n = (value - minimum) / (maximum - minimum);
  34685. return skewFactor == 1.0 ? n : pow (n, skewFactor);
  34686. }
  34687. double Slider::snapValue (double attemptedValue, const bool)
  34688. {
  34689. return attemptedValue;
  34690. }
  34691. void Slider::startedDragging()
  34692. {
  34693. }
  34694. void Slider::stoppedDragging()
  34695. {
  34696. }
  34697. void Slider::valueChanged()
  34698. {
  34699. }
  34700. void Slider::enablementChanged()
  34701. {
  34702. repaint();
  34703. }
  34704. void Slider::setPopupMenuEnabled (const bool menuEnabled_) throw()
  34705. {
  34706. menuEnabled = menuEnabled_;
  34707. }
  34708. void Slider::setScrollWheelEnabled (const bool enabled) throw()
  34709. {
  34710. scrollWheelEnabled = enabled;
  34711. }
  34712. void Slider::labelTextChanged (Label* label)
  34713. {
  34714. const double newValue = snapValue (getValueFromText (label->getText()), false);
  34715. if (getValue() != newValue)
  34716. {
  34717. sendDragStart();
  34718. setValue (newValue, true, true);
  34719. sendDragEnd();
  34720. }
  34721. updateText(); // force a clean-up of the text, needed in case setValue() hasn't done this.
  34722. }
  34723. void Slider::buttonClicked (Button* button)
  34724. {
  34725. if (style == IncDecButtons)
  34726. {
  34727. sendDragStart();
  34728. if (button == incButton)
  34729. setValue (snapValue (getValue() + interval, false), true, true);
  34730. else if (button == decButton)
  34731. setValue (snapValue (getValue() - interval, false), true, true);
  34732. sendDragEnd();
  34733. }
  34734. }
  34735. double Slider::constrainedValue (double value) const throw()
  34736. {
  34737. if (interval > 0)
  34738. value = minimum + interval * floor ((value - minimum) / interval + 0.5);
  34739. if (value <= minimum || maximum <= minimum)
  34740. value = minimum;
  34741. else if (value >= maximum)
  34742. value = maximum;
  34743. return value;
  34744. }
  34745. float Slider::getLinearSliderPos (const double value)
  34746. {
  34747. double sliderPosProportional;
  34748. if (maximum > minimum)
  34749. {
  34750. if (value < minimum)
  34751. {
  34752. sliderPosProportional = 0.0;
  34753. }
  34754. else if (value > maximum)
  34755. {
  34756. sliderPosProportional = 1.0;
  34757. }
  34758. else
  34759. {
  34760. sliderPosProportional = valueToProportionOfLength (value);
  34761. jassert (sliderPosProportional >= 0 && sliderPosProportional <= 1.0);
  34762. }
  34763. }
  34764. else
  34765. {
  34766. sliderPosProportional = 0.5;
  34767. }
  34768. if (style == LinearVertical || style == IncDecButtons)
  34769. sliderPosProportional = 1.0 - sliderPosProportional;
  34770. return (float) (sliderRegionStart + sliderPosProportional * sliderRegionSize);
  34771. }
  34772. bool Slider::isHorizontal() const throw()
  34773. {
  34774. return style == LinearHorizontal
  34775. || style == LinearBar
  34776. || style == TwoValueHorizontal
  34777. || style == ThreeValueHorizontal;
  34778. }
  34779. bool Slider::isVertical() const throw()
  34780. {
  34781. return style == LinearVertical
  34782. || style == TwoValueVertical
  34783. || style == ThreeValueVertical;
  34784. }
  34785. bool Slider::incDecDragDirectionIsHorizontal() const throw()
  34786. {
  34787. return incDecButtonMode == incDecButtonsDraggable_Horizontal
  34788. || (incDecButtonMode == incDecButtonsDraggable_AutoDirection && incDecButtonsSideBySide);
  34789. }
  34790. float Slider::getPositionOfValue (const double value)
  34791. {
  34792. if (isHorizontal() || isVertical())
  34793. {
  34794. return getLinearSliderPos (value);
  34795. }
  34796. else
  34797. {
  34798. jassertfalse // not a valid call on a slider that doesn't work linearly!
  34799. return 0.0f;
  34800. }
  34801. }
  34802. void Slider::paint (Graphics& g)
  34803. {
  34804. if (style != IncDecButtons)
  34805. {
  34806. if (style == Rotary || style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  34807. {
  34808. const float sliderPos = (float) valueToProportionOfLength (currentValue);
  34809. jassert (sliderPos >= 0 && sliderPos <= 1.0f);
  34810. getLookAndFeel().drawRotarySlider (g,
  34811. sliderRect.getX(),
  34812. sliderRect.getY(),
  34813. sliderRect.getWidth(),
  34814. sliderRect.getHeight(),
  34815. sliderPos,
  34816. rotaryStart, rotaryEnd,
  34817. *this);
  34818. }
  34819. else
  34820. {
  34821. getLookAndFeel().drawLinearSlider (g,
  34822. sliderRect.getX(),
  34823. sliderRect.getY(),
  34824. sliderRect.getWidth(),
  34825. sliderRect.getHeight(),
  34826. getLinearSliderPos (currentValue),
  34827. getLinearSliderPos (valueMin),
  34828. getLinearSliderPos (valueMax),
  34829. style,
  34830. *this);
  34831. }
  34832. if (style == LinearBar && valueBox == 0)
  34833. {
  34834. g.setColour (findColour (Slider::textBoxOutlineColourId));
  34835. g.drawRect (0, 0, getWidth(), getHeight(), 1);
  34836. }
  34837. }
  34838. }
  34839. void Slider::resized()
  34840. {
  34841. int minXSpace = 0;
  34842. int minYSpace = 0;
  34843. if (textBoxPos == TextBoxLeft || textBoxPos == TextBoxRight)
  34844. minXSpace = 30;
  34845. else
  34846. minYSpace = 15;
  34847. const int tbw = jmax (0, jmin (textBoxWidth, getWidth() - minXSpace));
  34848. const int tbh = jmax (0, jmin (textBoxHeight, getHeight() - minYSpace));
  34849. if (style == LinearBar)
  34850. {
  34851. if (valueBox != 0)
  34852. valueBox->setBounds (0, 0, getWidth(), getHeight());
  34853. }
  34854. else
  34855. {
  34856. if (textBoxPos == NoTextBox)
  34857. {
  34858. sliderRect.setBounds (0, 0, getWidth(), getHeight());
  34859. }
  34860. else if (textBoxPos == TextBoxLeft)
  34861. {
  34862. valueBox->setBounds (0, (getHeight() - tbh) / 2, tbw, tbh);
  34863. sliderRect.setBounds (tbw, 0, getWidth() - tbw, getHeight());
  34864. }
  34865. else if (textBoxPos == TextBoxRight)
  34866. {
  34867. valueBox->setBounds (getWidth() - tbw, (getHeight() - tbh) / 2, tbw, tbh);
  34868. sliderRect.setBounds (0, 0, getWidth() - tbw, getHeight());
  34869. }
  34870. else if (textBoxPos == TextBoxAbove)
  34871. {
  34872. valueBox->setBounds ((getWidth() - tbw) / 2, 0, tbw, tbh);
  34873. sliderRect.setBounds (0, tbh, getWidth(), getHeight() - tbh);
  34874. }
  34875. else if (textBoxPos == TextBoxBelow)
  34876. {
  34877. valueBox->setBounds ((getWidth() - tbw) / 2, getHeight() - tbh, tbw, tbh);
  34878. sliderRect.setBounds (0, 0, getWidth(), getHeight() - tbh);
  34879. }
  34880. }
  34881. const int indent = getLookAndFeel().getSliderThumbRadius (*this);
  34882. if (style == LinearBar)
  34883. {
  34884. const int barIndent = 1;
  34885. sliderRegionStart = barIndent;
  34886. sliderRegionSize = getWidth() - barIndent * 2;
  34887. sliderRect.setBounds (sliderRegionStart, barIndent,
  34888. sliderRegionSize, getHeight() - barIndent * 2);
  34889. }
  34890. else if (isHorizontal())
  34891. {
  34892. sliderRegionStart = sliderRect.getX() + indent;
  34893. sliderRegionSize = jmax (1, sliderRect.getWidth() - indent * 2);
  34894. sliderRect.setBounds (sliderRegionStart, sliderRect.getY(),
  34895. sliderRegionSize, sliderRect.getHeight());
  34896. }
  34897. else if (isVertical())
  34898. {
  34899. sliderRegionStart = sliderRect.getY() + indent;
  34900. sliderRegionSize = jmax (1, sliderRect.getHeight() - indent * 2);
  34901. sliderRect.setBounds (sliderRect.getX(), sliderRegionStart,
  34902. sliderRect.getWidth(), sliderRegionSize);
  34903. }
  34904. else
  34905. {
  34906. sliderRegionStart = 0;
  34907. sliderRegionSize = 100;
  34908. }
  34909. if (style == IncDecButtons)
  34910. {
  34911. Rectangle buttonRect (sliderRect);
  34912. if (textBoxPos == TextBoxLeft || textBoxPos == TextBoxRight)
  34913. buttonRect.expand (-2, 0);
  34914. else
  34915. buttonRect.expand (0, -2);
  34916. incDecButtonsSideBySide = buttonRect.getWidth() > buttonRect.getHeight();
  34917. if (incDecButtonsSideBySide)
  34918. {
  34919. decButton->setBounds (buttonRect.getX(),
  34920. buttonRect.getY(),
  34921. buttonRect.getWidth() / 2,
  34922. buttonRect.getHeight());
  34923. decButton->setConnectedEdges (Button::ConnectedOnRight);
  34924. incButton->setBounds (buttonRect.getCentreX(),
  34925. buttonRect.getY(),
  34926. buttonRect.getWidth() / 2,
  34927. buttonRect.getHeight());
  34928. incButton->setConnectedEdges (Button::ConnectedOnLeft);
  34929. }
  34930. else
  34931. {
  34932. incButton->setBounds (buttonRect.getX(),
  34933. buttonRect.getY(),
  34934. buttonRect.getWidth(),
  34935. buttonRect.getHeight() / 2);
  34936. incButton->setConnectedEdges (Button::ConnectedOnBottom);
  34937. decButton->setBounds (buttonRect.getX(),
  34938. buttonRect.getCentreY(),
  34939. buttonRect.getWidth(),
  34940. buttonRect.getHeight() / 2);
  34941. decButton->setConnectedEdges (Button::ConnectedOnTop);
  34942. }
  34943. }
  34944. }
  34945. void Slider::focusOfChildComponentChanged (FocusChangeType)
  34946. {
  34947. repaint();
  34948. }
  34949. void Slider::mouseDown (const MouseEvent& e)
  34950. {
  34951. mouseWasHidden = false;
  34952. incDecDragged = false;
  34953. if (isEnabled())
  34954. {
  34955. if (e.mods.isPopupMenu() && menuEnabled)
  34956. {
  34957. menuShown = true;
  34958. PopupMenu m;
  34959. m.addItem (1, TRANS ("velocity-sensitive mode"), true, isVelocityBased);
  34960. m.addSeparator();
  34961. if (style == Rotary || style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  34962. {
  34963. PopupMenu rotaryMenu;
  34964. rotaryMenu.addItem (2, TRANS ("use circular dragging"), true, style == Rotary);
  34965. rotaryMenu.addItem (3, TRANS ("use left-right dragging"), true, style == RotaryHorizontalDrag);
  34966. rotaryMenu.addItem (4, TRANS ("use up-down dragging"), true, style == RotaryVerticalDrag);
  34967. m.addSubMenu (TRANS ("rotary mode"), rotaryMenu);
  34968. }
  34969. const int r = m.show();
  34970. if (r == 1)
  34971. {
  34972. setVelocityBasedMode (! isVelocityBased);
  34973. }
  34974. else if (r == 2)
  34975. {
  34976. setSliderStyle (Rotary);
  34977. }
  34978. else if (r == 3)
  34979. {
  34980. setSliderStyle (RotaryHorizontalDrag);
  34981. }
  34982. else if (r == 4)
  34983. {
  34984. setSliderStyle (RotaryVerticalDrag);
  34985. }
  34986. }
  34987. else if (maximum > minimum)
  34988. {
  34989. menuShown = false;
  34990. if (valueBox != 0)
  34991. valueBox->hideEditor (true);
  34992. sliderBeingDragged = 0;
  34993. if (style == TwoValueHorizontal
  34994. || style == TwoValueVertical
  34995. || style == ThreeValueHorizontal
  34996. || style == ThreeValueVertical)
  34997. {
  34998. const float mousePos = (float) (isVertical() ? e.y : e.x);
  34999. const float normalPosDistance = fabsf (getLinearSliderPos (currentValue) - mousePos);
  35000. const float minPosDistance = fabsf (getLinearSliderPos (valueMin) - 0.1f - mousePos);
  35001. const float maxPosDistance = fabsf (getLinearSliderPos (valueMax) + 0.1f - mousePos);
  35002. if (style == TwoValueHorizontal || style == TwoValueVertical)
  35003. {
  35004. if (maxPosDistance <= minPosDistance)
  35005. sliderBeingDragged = 2;
  35006. else
  35007. sliderBeingDragged = 1;
  35008. }
  35009. else if (style == ThreeValueHorizontal || style == ThreeValueVertical)
  35010. {
  35011. if (normalPosDistance >= minPosDistance && maxPosDistance >= minPosDistance)
  35012. sliderBeingDragged = 1;
  35013. else if (normalPosDistance >= maxPosDistance)
  35014. sliderBeingDragged = 2;
  35015. }
  35016. }
  35017. minMaxDiff = valueMax - valueMin;
  35018. mouseXWhenLastDragged = e.x;
  35019. mouseYWhenLastDragged = e.y;
  35020. lastAngle = rotaryStart + (rotaryEnd - rotaryStart)
  35021. * valueToProportionOfLength (currentValue);
  35022. if (sliderBeingDragged == 2)
  35023. valueWhenLastDragged = valueMax;
  35024. else if (sliderBeingDragged == 1)
  35025. valueWhenLastDragged = valueMin;
  35026. else
  35027. valueWhenLastDragged = currentValue;
  35028. valueOnMouseDown = valueWhenLastDragged;
  35029. if (popupDisplayEnabled)
  35030. {
  35031. SliderPopupDisplayComponent* const popup = new SliderPopupDisplayComponent (this);
  35032. popupDisplay = popup;
  35033. if (parentForPopupDisplay != 0)
  35034. {
  35035. parentForPopupDisplay->addChildComponent (popup);
  35036. }
  35037. else
  35038. {
  35039. popup->addToDesktop (0);
  35040. }
  35041. popup->setVisible (true);
  35042. }
  35043. sendDragStart();
  35044. mouseDrag (e);
  35045. }
  35046. }
  35047. }
  35048. void Slider::mouseUp (const MouseEvent&)
  35049. {
  35050. if (isEnabled()
  35051. && (! menuShown)
  35052. && (maximum > minimum)
  35053. && (style != IncDecButtons || incDecDragged))
  35054. {
  35055. restoreMouseIfHidden();
  35056. if (sendChangeOnlyOnRelease && valueOnMouseDown != currentValue)
  35057. triggerChangeMessage (false);
  35058. sendDragEnd();
  35059. deleteAndZero (popupDisplay);
  35060. if (style == IncDecButtons)
  35061. {
  35062. incButton->setState (Button::buttonNormal);
  35063. decButton->setState (Button::buttonNormal);
  35064. }
  35065. }
  35066. }
  35067. void Slider::restoreMouseIfHidden()
  35068. {
  35069. if (mouseWasHidden)
  35070. {
  35071. mouseWasHidden = false;
  35072. Component* c = Component::getComponentUnderMouse();
  35073. if (c == 0)
  35074. c = this;
  35075. c->enableUnboundedMouseMovement (false);
  35076. const double pos = (sliderBeingDragged == 2) ? getMaxValue()
  35077. : ((sliderBeingDragged == 1) ? getMinValue()
  35078. : currentValue);
  35079. const int pixelPos = (int) getLinearSliderPos (pos);
  35080. int x = isHorizontal() ? pixelPos : (getWidth() / 2);
  35081. int y = isVertical() ? pixelPos : (getHeight() / 2);
  35082. relativePositionToGlobal (x, y);
  35083. Desktop::setMousePosition (x, y);
  35084. }
  35085. }
  35086. void Slider::modifierKeysChanged (const ModifierKeys& modifiers)
  35087. {
  35088. if (isEnabled()
  35089. && style != IncDecButtons
  35090. && style != Rotary
  35091. && isVelocityBased == modifiers.isAnyModifierKeyDown())
  35092. {
  35093. restoreMouseIfHidden();
  35094. }
  35095. }
  35096. static double smallestAngleBetween (double a1, double a2)
  35097. {
  35098. return jmin (fabs (a1 - a2),
  35099. fabs (a1 + double_Pi * 2.0 - a2),
  35100. fabs (a2 + double_Pi * 2.0 - a1));
  35101. }
  35102. void Slider::mouseDrag (const MouseEvent& e)
  35103. {
  35104. if (isEnabled()
  35105. && (! menuShown)
  35106. && (maximum > minimum))
  35107. {
  35108. if (style == Rotary)
  35109. {
  35110. int dx = e.x - sliderRect.getCentreX();
  35111. int dy = e.y - sliderRect.getCentreY();
  35112. if (dx * dx + dy * dy > 25)
  35113. {
  35114. double angle = atan2 ((double) dx, (double) -dy);
  35115. while (angle < 0.0)
  35116. angle += double_Pi * 2.0;
  35117. if (rotaryStop && ! e.mouseWasClicked())
  35118. {
  35119. if (fabs (angle - lastAngle) > double_Pi)
  35120. {
  35121. if (angle >= lastAngle)
  35122. angle -= double_Pi * 2.0;
  35123. else
  35124. angle += double_Pi * 2.0;
  35125. }
  35126. if (angle >= lastAngle)
  35127. angle = jmin (angle, (double) jmax (rotaryStart, rotaryEnd));
  35128. else
  35129. angle = jmax (angle, (double) jmin (rotaryStart, rotaryEnd));
  35130. }
  35131. else
  35132. {
  35133. while (angle < rotaryStart)
  35134. angle += double_Pi * 2.0;
  35135. if (angle > rotaryEnd)
  35136. {
  35137. if (smallestAngleBetween (angle, rotaryStart) <= smallestAngleBetween (angle, rotaryEnd))
  35138. angle = rotaryStart;
  35139. else
  35140. angle = rotaryEnd;
  35141. }
  35142. }
  35143. const double proportion = (angle - rotaryStart) / (rotaryEnd - rotaryStart);
  35144. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, proportion));
  35145. lastAngle = angle;
  35146. }
  35147. }
  35148. else
  35149. {
  35150. if (style == LinearBar && e.mouseWasClicked()
  35151. && valueBox != 0 && valueBox->isEditable())
  35152. return;
  35153. if (style == IncDecButtons)
  35154. {
  35155. if (! incDecDragged)
  35156. incDecDragged = e.getDistanceFromDragStart() > 10 && ! e.mouseWasClicked();
  35157. if (! incDecDragged)
  35158. return;
  35159. }
  35160. if ((isVelocityBased == (userKeyOverridesVelocity ? e.mods.testFlags (ModifierKeys::ctrlModifier | ModifierKeys::commandModifier | ModifierKeys::altModifier)
  35161. : false))
  35162. || ((maximum - minimum) / sliderRegionSize < interval))
  35163. {
  35164. const int mousePos = (isHorizontal() || style == RotaryHorizontalDrag) ? e.x : e.y;
  35165. double scaledMousePos = (mousePos - sliderRegionStart) / (double) sliderRegionSize;
  35166. if (style == RotaryHorizontalDrag
  35167. || style == RotaryVerticalDrag
  35168. || style == IncDecButtons
  35169. || ((style == LinearHorizontal || style == LinearVertical || style == LinearBar)
  35170. && ! snapsToMousePos))
  35171. {
  35172. const int mouseDiff = (style == RotaryHorizontalDrag
  35173. || style == LinearHorizontal
  35174. || style == LinearBar
  35175. || (style == IncDecButtons && incDecDragDirectionIsHorizontal()))
  35176. ? e.getDistanceFromDragStartX()
  35177. : -e.getDistanceFromDragStartY();
  35178. double newPos = valueToProportionOfLength (valueOnMouseDown)
  35179. + mouseDiff * (1.0 / pixelsForFullDragExtent);
  35180. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, newPos));
  35181. if (style == IncDecButtons)
  35182. {
  35183. incButton->setState (mouseDiff < 0 ? Button::buttonNormal : Button::buttonDown);
  35184. decButton->setState (mouseDiff > 0 ? Button::buttonNormal : Button::buttonDown);
  35185. }
  35186. }
  35187. else
  35188. {
  35189. if (style == LinearVertical)
  35190. scaledMousePos = 1.0 - scaledMousePos;
  35191. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, scaledMousePos));
  35192. }
  35193. }
  35194. else
  35195. {
  35196. const int mouseDiff = (isHorizontal() || style == RotaryHorizontalDrag
  35197. || (style == IncDecButtons && incDecDragDirectionIsHorizontal()))
  35198. ? e.x - mouseXWhenLastDragged
  35199. : e.y - mouseYWhenLastDragged;
  35200. const double maxSpeed = jmax (200, sliderRegionSize);
  35201. double speed = jlimit (0.0, maxSpeed, (double) abs (mouseDiff));
  35202. if (speed != 0)
  35203. {
  35204. speed = 0.2 * velocityModeSensitivity
  35205. * (1.0 + sin (double_Pi * (1.5 + jmin (0.5, velocityModeOffset
  35206. + jmax (0.0, (double) (speed - velocityModeThreshold))
  35207. / maxSpeed))));
  35208. if (mouseDiff < 0)
  35209. speed = -speed;
  35210. if (style == LinearVertical || style == RotaryVerticalDrag
  35211. || (style == IncDecButtons && ! incDecDragDirectionIsHorizontal()))
  35212. speed = -speed;
  35213. const double currentPos = valueToProportionOfLength (valueWhenLastDragged);
  35214. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, currentPos + speed));
  35215. e.originalComponent->enableUnboundedMouseMovement (true, false);
  35216. mouseWasHidden = true;
  35217. }
  35218. }
  35219. }
  35220. valueWhenLastDragged = jlimit (minimum, maximum, valueWhenLastDragged);
  35221. if (sliderBeingDragged == 0)
  35222. {
  35223. setValue (snapValue (valueWhenLastDragged, true),
  35224. ! sendChangeOnlyOnRelease, true);
  35225. }
  35226. else if (sliderBeingDragged == 1)
  35227. {
  35228. setMinValue (snapValue (valueWhenLastDragged, true),
  35229. ! sendChangeOnlyOnRelease, false);
  35230. if (e.mods.isShiftDown())
  35231. setMaxValue (getMinValue() + minMaxDiff, false);
  35232. else
  35233. minMaxDiff = valueMax - valueMin;
  35234. }
  35235. else
  35236. {
  35237. jassert (sliderBeingDragged == 2);
  35238. setMaxValue (snapValue (valueWhenLastDragged, true),
  35239. ! sendChangeOnlyOnRelease, false);
  35240. if (e.mods.isShiftDown())
  35241. setMinValue (getMaxValue() - minMaxDiff, false);
  35242. else
  35243. minMaxDiff = valueMax - valueMin;
  35244. }
  35245. mouseXWhenLastDragged = e.x;
  35246. mouseYWhenLastDragged = e.y;
  35247. }
  35248. }
  35249. void Slider::mouseDoubleClick (const MouseEvent&)
  35250. {
  35251. if (doubleClickToValue
  35252. && isEnabled()
  35253. && style != IncDecButtons
  35254. && minimum <= doubleClickReturnValue
  35255. && maximum >= doubleClickReturnValue)
  35256. {
  35257. sendDragStart();
  35258. setValue (doubleClickReturnValue, true, true);
  35259. sendDragEnd();
  35260. }
  35261. }
  35262. void Slider::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  35263. {
  35264. if (scrollWheelEnabled && isEnabled())
  35265. {
  35266. if (maximum > minimum && ! isMouseButtonDownAnywhere())
  35267. {
  35268. if (valueBox != 0)
  35269. valueBox->hideEditor (false);
  35270. const double proportionDelta = (wheelIncrementX != 0 ? -wheelIncrementX : wheelIncrementY) * 0.15f;
  35271. const double currentPos = valueToProportionOfLength (currentValue);
  35272. const double newValue = proportionOfLengthToValue (jlimit (0.0, 1.0, currentPos + proportionDelta));
  35273. double delta = (newValue != currentValue)
  35274. ? jmax (fabs (newValue - currentValue), interval) : 0;
  35275. if (currentValue > newValue)
  35276. delta = -delta;
  35277. sendDragStart();
  35278. setValue (snapValue (currentValue + delta, false), true, true);
  35279. sendDragEnd();
  35280. }
  35281. }
  35282. else
  35283. {
  35284. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  35285. }
  35286. }
  35287. void SliderListener::sliderDragStarted (Slider*)
  35288. {
  35289. }
  35290. void SliderListener::sliderDragEnded (Slider*)
  35291. {
  35292. }
  35293. END_JUCE_NAMESPACE
  35294. /********* End of inlined file: juce_Slider.cpp *********/
  35295. /********* Start of inlined file: juce_TableHeaderComponent.cpp *********/
  35296. BEGIN_JUCE_NAMESPACE
  35297. class DragOverlayComp : public Component
  35298. {
  35299. public:
  35300. DragOverlayComp (Image* const image_)
  35301. : image (image_)
  35302. {
  35303. image->multiplyAllAlphas (0.8f);
  35304. setAlwaysOnTop (true);
  35305. }
  35306. ~DragOverlayComp()
  35307. {
  35308. delete image;
  35309. }
  35310. void paint (Graphics& g)
  35311. {
  35312. g.drawImageAt (image, 0, 0);
  35313. }
  35314. private:
  35315. Image* image;
  35316. DragOverlayComp (const DragOverlayComp&);
  35317. const DragOverlayComp& operator= (const DragOverlayComp&);
  35318. };
  35319. TableHeaderComponent::TableHeaderComponent()
  35320. : listeners (2),
  35321. dragOverlayComp (0),
  35322. columnsChanged (false),
  35323. columnsResized (false),
  35324. sortChanged (false),
  35325. menuActive (true),
  35326. stretchToFit (false),
  35327. columnIdBeingResized (0),
  35328. columnIdBeingDragged (0),
  35329. columnIdUnderMouse (0),
  35330. lastDeliberateWidth (0)
  35331. {
  35332. }
  35333. TableHeaderComponent::~TableHeaderComponent()
  35334. {
  35335. delete dragOverlayComp;
  35336. }
  35337. void TableHeaderComponent::setPopupMenuActive (const bool hasMenu)
  35338. {
  35339. menuActive = hasMenu;
  35340. }
  35341. bool TableHeaderComponent::isPopupMenuActive() const throw() { return menuActive; }
  35342. int TableHeaderComponent::getNumColumns (const bool onlyCountVisibleColumns) const throw()
  35343. {
  35344. if (onlyCountVisibleColumns)
  35345. {
  35346. int num = 0;
  35347. for (int i = columns.size(); --i >= 0;)
  35348. if (columns.getUnchecked(i)->isVisible())
  35349. ++num;
  35350. return num;
  35351. }
  35352. else
  35353. {
  35354. return columns.size();
  35355. }
  35356. }
  35357. const String TableHeaderComponent::getColumnName (const int columnId) const throw()
  35358. {
  35359. const ColumnInfo* const ci = getInfoForId (columnId);
  35360. return ci != 0 ? ci->name : String::empty;
  35361. }
  35362. void TableHeaderComponent::setColumnName (const int columnId, const String& newName)
  35363. {
  35364. ColumnInfo* const ci = getInfoForId (columnId);
  35365. if (ci != 0 && ci->name != newName)
  35366. {
  35367. ci->name = newName;
  35368. sendColumnsChanged();
  35369. }
  35370. }
  35371. void TableHeaderComponent::addColumn (const String& columnName,
  35372. const int columnId,
  35373. const int width,
  35374. const int minimumWidth,
  35375. const int maximumWidth,
  35376. const int propertyFlags,
  35377. const int insertIndex)
  35378. {
  35379. // can't have a duplicate or null ID!
  35380. jassert (columnId != 0 && getIndexOfColumnId (columnId, false) < 0);
  35381. jassert (width > 0);
  35382. ColumnInfo* const ci = new ColumnInfo();
  35383. ci->name = columnName;
  35384. ci->id = columnId;
  35385. ci->width = width;
  35386. ci->lastDeliberateWidth = width;
  35387. ci->minimumWidth = minimumWidth;
  35388. ci->maximumWidth = maximumWidth;
  35389. if (ci->maximumWidth < 0)
  35390. ci->maximumWidth = INT_MAX;
  35391. jassert (ci->maximumWidth >= ci->minimumWidth);
  35392. ci->propertyFlags = propertyFlags;
  35393. columns.insert (insertIndex, ci);
  35394. sendColumnsChanged();
  35395. }
  35396. void TableHeaderComponent::removeColumn (const int columnIdToRemove)
  35397. {
  35398. const int index = getIndexOfColumnId (columnIdToRemove, false);
  35399. if (index >= 0)
  35400. {
  35401. columns.remove (index);
  35402. sortChanged = true;
  35403. sendColumnsChanged();
  35404. }
  35405. }
  35406. void TableHeaderComponent::removeAllColumns()
  35407. {
  35408. if (columns.size() > 0)
  35409. {
  35410. columns.clear();
  35411. sendColumnsChanged();
  35412. }
  35413. }
  35414. void TableHeaderComponent::moveColumn (const int columnId, int newIndex)
  35415. {
  35416. const int currentIndex = getIndexOfColumnId (columnId, false);
  35417. newIndex = visibleIndexToTotalIndex (newIndex);
  35418. if (columns [currentIndex] != 0 && currentIndex != newIndex)
  35419. {
  35420. columns.move (currentIndex, newIndex);
  35421. sendColumnsChanged();
  35422. }
  35423. }
  35424. void TableHeaderComponent::setColumnWidth (const int columnId, const int newWidth)
  35425. {
  35426. ColumnInfo* const ci = getInfoForId (columnId);
  35427. if (ci != 0 && ci->width != newWidth)
  35428. {
  35429. const int numColumns = getNumColumns (true);
  35430. ci->lastDeliberateWidth = ci->width
  35431. = jlimit (ci->minimumWidth, ci->maximumWidth, newWidth);
  35432. if (stretchToFit)
  35433. {
  35434. const int index = getIndexOfColumnId (columnId, true) + 1;
  35435. if (((unsigned int) index) < (unsigned int) numColumns)
  35436. {
  35437. const int x = getColumnPosition (index).getX();
  35438. if (lastDeliberateWidth == 0)
  35439. lastDeliberateWidth = getTotalWidth();
  35440. resizeColumnsToFit (visibleIndexToTotalIndex (index), lastDeliberateWidth - x);
  35441. }
  35442. }
  35443. repaint();
  35444. columnsResized = true;
  35445. triggerAsyncUpdate();
  35446. }
  35447. }
  35448. int TableHeaderComponent::getIndexOfColumnId (const int columnId, const bool onlyCountVisibleColumns) const throw()
  35449. {
  35450. int n = 0;
  35451. for (int i = 0; i < columns.size(); ++i)
  35452. {
  35453. if ((! onlyCountVisibleColumns) || columns.getUnchecked(i)->isVisible())
  35454. {
  35455. if (columns.getUnchecked(i)->id == columnId)
  35456. return n;
  35457. ++n;
  35458. }
  35459. }
  35460. return -1;
  35461. }
  35462. int TableHeaderComponent::getColumnIdOfIndex (int index, const bool onlyCountVisibleColumns) const throw()
  35463. {
  35464. if (onlyCountVisibleColumns)
  35465. index = visibleIndexToTotalIndex (index);
  35466. const ColumnInfo* const ci = columns [index];
  35467. return (ci != 0) ? ci->id : 0;
  35468. }
  35469. const Rectangle TableHeaderComponent::getColumnPosition (const int index) const throw()
  35470. {
  35471. int x = 0, width = 0, n = 0;
  35472. for (int i = 0; i < columns.size(); ++i)
  35473. {
  35474. x += width;
  35475. if (columns.getUnchecked(i)->isVisible())
  35476. {
  35477. width = columns.getUnchecked(i)->width;
  35478. if (n++ == index)
  35479. break;
  35480. }
  35481. else
  35482. {
  35483. width = 0;
  35484. }
  35485. }
  35486. return Rectangle (x, 0, width, getHeight());
  35487. }
  35488. int TableHeaderComponent::getColumnIdAtX (const int xToFind) const throw()
  35489. {
  35490. if (xToFind >= 0)
  35491. {
  35492. int x = 0;
  35493. for (int i = 0; i < columns.size(); ++i)
  35494. {
  35495. const ColumnInfo* const ci = columns.getUnchecked(i);
  35496. if (ci->isVisible())
  35497. {
  35498. x += ci->width;
  35499. if (xToFind < x)
  35500. return ci->id;
  35501. }
  35502. }
  35503. }
  35504. return 0;
  35505. }
  35506. int TableHeaderComponent::getTotalWidth() const throw()
  35507. {
  35508. int w = 0;
  35509. for (int i = columns.size(); --i >= 0;)
  35510. if (columns.getUnchecked(i)->isVisible())
  35511. w += columns.getUnchecked(i)->width;
  35512. return w;
  35513. }
  35514. void TableHeaderComponent::setStretchToFitActive (const bool shouldStretchToFit)
  35515. {
  35516. stretchToFit = shouldStretchToFit;
  35517. lastDeliberateWidth = getTotalWidth();
  35518. resized();
  35519. }
  35520. bool TableHeaderComponent::isStretchToFitActive() const throw()
  35521. {
  35522. return stretchToFit;
  35523. }
  35524. void TableHeaderComponent::resizeAllColumnsToFit (int targetTotalWidth)
  35525. {
  35526. if (stretchToFit && getWidth() > 0
  35527. && columnIdBeingResized == 0 && columnIdBeingDragged == 0)
  35528. {
  35529. lastDeliberateWidth = targetTotalWidth;
  35530. resizeColumnsToFit (0, targetTotalWidth);
  35531. }
  35532. }
  35533. void TableHeaderComponent::resizeColumnsToFit (int firstColumnIndex, int targetTotalWidth)
  35534. {
  35535. targetTotalWidth = jmax (targetTotalWidth, 0);
  35536. StretchableObjectResizer sor;
  35537. int i;
  35538. for (i = firstColumnIndex; i < columns.size(); ++i)
  35539. {
  35540. ColumnInfo* const ci = columns.getUnchecked(i);
  35541. if (ci->isVisible())
  35542. sor.addItem (ci->lastDeliberateWidth, ci->minimumWidth, ci->maximumWidth);
  35543. }
  35544. sor.resizeToFit (targetTotalWidth);
  35545. int visIndex = 0;
  35546. for (i = firstColumnIndex; i < columns.size(); ++i)
  35547. {
  35548. ColumnInfo* const ci = columns.getUnchecked(i);
  35549. if (ci->isVisible())
  35550. {
  35551. const int newWidth = jlimit (ci->minimumWidth, ci->maximumWidth,
  35552. (int) floor (sor.getItemSize (visIndex++)));
  35553. if (newWidth != ci->width)
  35554. {
  35555. ci->width = newWidth;
  35556. repaint();
  35557. columnsResized = true;
  35558. triggerAsyncUpdate();
  35559. }
  35560. }
  35561. }
  35562. }
  35563. void TableHeaderComponent::setColumnVisible (const int columnId, const bool shouldBeVisible)
  35564. {
  35565. ColumnInfo* const ci = getInfoForId (columnId);
  35566. if (ci != 0 && shouldBeVisible != ci->isVisible())
  35567. {
  35568. if (shouldBeVisible)
  35569. ci->propertyFlags |= visible;
  35570. else
  35571. ci->propertyFlags &= ~visible;
  35572. sendColumnsChanged();
  35573. resized();
  35574. }
  35575. }
  35576. bool TableHeaderComponent::isColumnVisible (const int columnId) const
  35577. {
  35578. const ColumnInfo* const ci = getInfoForId (columnId);
  35579. return ci != 0 && ci->isVisible();
  35580. }
  35581. void TableHeaderComponent::setSortColumnId (const int columnId, const bool sortForwards)
  35582. {
  35583. if (getSortColumnId() != columnId || isSortedForwards() != sortForwards)
  35584. {
  35585. for (int i = columns.size(); --i >= 0;)
  35586. columns.getUnchecked(i)->propertyFlags &= ~(sortedForwards | sortedBackwards);
  35587. ColumnInfo* const ci = getInfoForId (columnId);
  35588. if (ci != 0)
  35589. ci->propertyFlags |= (sortForwards ? sortedForwards : sortedBackwards);
  35590. reSortTable();
  35591. }
  35592. }
  35593. int TableHeaderComponent::getSortColumnId() const throw()
  35594. {
  35595. for (int i = columns.size(); --i >= 0;)
  35596. if ((columns.getUnchecked(i)->propertyFlags & (sortedForwards | sortedBackwards)) != 0)
  35597. return columns.getUnchecked(i)->id;
  35598. return 0;
  35599. }
  35600. bool TableHeaderComponent::isSortedForwards() const throw()
  35601. {
  35602. for (int i = columns.size(); --i >= 0;)
  35603. if ((columns.getUnchecked(i)->propertyFlags & (sortedForwards | sortedBackwards)) != 0)
  35604. return (columns.getUnchecked(i)->propertyFlags & sortedForwards) != 0;
  35605. return true;
  35606. }
  35607. void TableHeaderComponent::reSortTable()
  35608. {
  35609. sortChanged = true;
  35610. repaint();
  35611. triggerAsyncUpdate();
  35612. }
  35613. const String TableHeaderComponent::toString() const
  35614. {
  35615. String s;
  35616. XmlElement doc (T("TABLELAYOUT"));
  35617. doc.setAttribute (T("sortedCol"), getSortColumnId());
  35618. doc.setAttribute (T("sortForwards"), isSortedForwards());
  35619. for (int i = 0; i < columns.size(); ++i)
  35620. {
  35621. const ColumnInfo* const ci = columns.getUnchecked (i);
  35622. XmlElement* const e = new XmlElement (T("COLUMN"));
  35623. doc.addChildElement (e);
  35624. e->setAttribute (T("id"), ci->id);
  35625. e->setAttribute (T("visible"), ci->isVisible());
  35626. e->setAttribute (T("width"), ci->width);
  35627. }
  35628. return doc.createDocument (String::empty, true, false);
  35629. }
  35630. void TableHeaderComponent::restoreFromString (const String& storedVersion)
  35631. {
  35632. XmlDocument doc (storedVersion);
  35633. XmlElement* const storedXml = doc.getDocumentElement();
  35634. int index = 0;
  35635. if (storedXml != 0 && storedXml->hasTagName (T("TABLELAYOUT")))
  35636. {
  35637. forEachXmlChildElement (*storedXml, col)
  35638. {
  35639. const int tabId = col->getIntAttribute (T("id"));
  35640. ColumnInfo* const ci = getInfoForId (tabId);
  35641. if (ci != 0)
  35642. {
  35643. columns.move (columns.indexOf (ci), index);
  35644. ci->width = col->getIntAttribute (T("width"));
  35645. setColumnVisible (tabId, col->getBoolAttribute (T("visible")));
  35646. }
  35647. ++index;
  35648. }
  35649. columnsResized = true;
  35650. sendColumnsChanged();
  35651. setSortColumnId (storedXml->getIntAttribute (T("sortedCol")),
  35652. storedXml->getBoolAttribute (T("sortForwards"), true));
  35653. }
  35654. delete storedXml;
  35655. }
  35656. void TableHeaderComponent::addListener (TableHeaderListener* const newListener) throw()
  35657. {
  35658. listeners.addIfNotAlreadyThere (newListener);
  35659. }
  35660. void TableHeaderComponent::removeListener (TableHeaderListener* const listenerToRemove) throw()
  35661. {
  35662. listeners.removeValue (listenerToRemove);
  35663. }
  35664. void TableHeaderComponent::columnClicked (int columnId, const ModifierKeys& mods)
  35665. {
  35666. const ColumnInfo* const ci = getInfoForId (columnId);
  35667. if (ci != 0 && (ci->propertyFlags & sortable) != 0 && ! mods.isPopupMenu())
  35668. setSortColumnId (columnId, (ci->propertyFlags & sortedForwards) == 0);
  35669. }
  35670. void TableHeaderComponent::addMenuItems (PopupMenu& menu, const int /*columnIdClicked*/)
  35671. {
  35672. for (int i = 0; i < columns.size(); ++i)
  35673. {
  35674. const ColumnInfo* const ci = columns.getUnchecked(i);
  35675. if ((ci->propertyFlags & appearsOnColumnMenu) != 0)
  35676. menu.addItem (ci->id, ci->name,
  35677. (ci->propertyFlags & (sortedForwards | sortedBackwards)) == 0,
  35678. isColumnVisible (ci->id));
  35679. }
  35680. }
  35681. void TableHeaderComponent::reactToMenuItem (const int menuReturnId, const int /*columnIdClicked*/)
  35682. {
  35683. if (getIndexOfColumnId (menuReturnId, false) >= 0)
  35684. setColumnVisible (menuReturnId, ! isColumnVisible (menuReturnId));
  35685. }
  35686. void TableHeaderComponent::paint (Graphics& g)
  35687. {
  35688. LookAndFeel& lf = getLookAndFeel();
  35689. lf.drawTableHeaderBackground (g, *this);
  35690. const Rectangle clip (g.getClipBounds());
  35691. int x = 0;
  35692. for (int i = 0; i < columns.size(); ++i)
  35693. {
  35694. const ColumnInfo* const ci = columns.getUnchecked(i);
  35695. if (ci->isVisible())
  35696. {
  35697. if (x + ci->width > clip.getX()
  35698. && (ci->id != columnIdBeingDragged
  35699. || dragOverlayComp == 0
  35700. || ! dragOverlayComp->isVisible()))
  35701. {
  35702. g.saveState();
  35703. g.setOrigin (x, 0);
  35704. g.reduceClipRegion (0, 0, ci->width, getHeight());
  35705. lf.drawTableHeaderColumn (g, ci->name, ci->id, ci->width, getHeight(),
  35706. ci->id == columnIdUnderMouse,
  35707. ci->id == columnIdUnderMouse && isMouseButtonDown(),
  35708. ci->propertyFlags);
  35709. g.restoreState();
  35710. }
  35711. x += ci->width;
  35712. if (x >= clip.getRight())
  35713. break;
  35714. }
  35715. }
  35716. }
  35717. void TableHeaderComponent::resized()
  35718. {
  35719. }
  35720. void TableHeaderComponent::mouseMove (const MouseEvent& e)
  35721. {
  35722. updateColumnUnderMouse (e.x, e.y);
  35723. }
  35724. void TableHeaderComponent::mouseEnter (const MouseEvent& e)
  35725. {
  35726. updateColumnUnderMouse (e.x, e.y);
  35727. }
  35728. void TableHeaderComponent::mouseExit (const MouseEvent& e)
  35729. {
  35730. updateColumnUnderMouse (e.x, e.y);
  35731. }
  35732. void TableHeaderComponent::mouseDown (const MouseEvent& e)
  35733. {
  35734. repaint();
  35735. columnIdBeingResized = 0;
  35736. columnIdBeingDragged = 0;
  35737. if (columnIdUnderMouse != 0)
  35738. {
  35739. draggingColumnOffset = e.x - getColumnPosition (getIndexOfColumnId (columnIdUnderMouse, true)).getX();
  35740. if (e.mods.isPopupMenu())
  35741. columnClicked (columnIdUnderMouse, e.mods);
  35742. }
  35743. if (menuActive && e.mods.isPopupMenu())
  35744. showColumnChooserMenu (columnIdUnderMouse);
  35745. }
  35746. void TableHeaderComponent::mouseDrag (const MouseEvent& e)
  35747. {
  35748. if (columnIdBeingResized == 0
  35749. && columnIdBeingDragged == 0
  35750. && ! (e.mouseWasClicked() || e.mods.isPopupMenu()))
  35751. {
  35752. deleteAndZero (dragOverlayComp);
  35753. columnIdBeingResized = getResizeDraggerAt (e.getMouseDownX());
  35754. if (columnIdBeingResized != 0)
  35755. {
  35756. const ColumnInfo* const ci = getInfoForId (columnIdBeingResized);
  35757. initialColumnWidth = ci->width;
  35758. }
  35759. else
  35760. {
  35761. beginDrag (e);
  35762. }
  35763. }
  35764. if (columnIdBeingResized != 0)
  35765. {
  35766. const ColumnInfo* const ci = getInfoForId (columnIdBeingResized);
  35767. if (ci != 0)
  35768. {
  35769. int w = jlimit (ci->minimumWidth, ci->maximumWidth,
  35770. initialColumnWidth + e.getDistanceFromDragStartX());
  35771. if (stretchToFit)
  35772. {
  35773. // prevent us dragging a column too far right if we're in stretch-to-fit mode
  35774. int minWidthOnRight = 0;
  35775. for (int i = getIndexOfColumnId (columnIdBeingResized, false) + 1; i < columns.size(); ++i)
  35776. if (columns.getUnchecked (i)->isVisible())
  35777. minWidthOnRight += columns.getUnchecked (i)->minimumWidth;
  35778. const Rectangle currentPos (getColumnPosition (getIndexOfColumnId (columnIdBeingResized, true)));
  35779. w = jmax (ci->minimumWidth, jmin (w, getWidth() - minWidthOnRight - currentPos.getX()));
  35780. }
  35781. setColumnWidth (columnIdBeingResized, w);
  35782. }
  35783. }
  35784. else if (columnIdBeingDragged != 0)
  35785. {
  35786. if (e.y >= -50 && e.y < getHeight() + 50)
  35787. {
  35788. beginDrag (e);
  35789. if (dragOverlayComp != 0)
  35790. {
  35791. dragOverlayComp->setVisible (true);
  35792. dragOverlayComp->setBounds (jlimit (0,
  35793. jmax (0, getTotalWidth() - dragOverlayComp->getWidth()),
  35794. e.x - draggingColumnOffset),
  35795. 0,
  35796. dragOverlayComp->getWidth(),
  35797. getHeight());
  35798. for (int i = columns.size(); --i >= 0;)
  35799. {
  35800. const int currentIndex = getIndexOfColumnId (columnIdBeingDragged, true);
  35801. int newIndex = currentIndex;
  35802. if (newIndex > 0)
  35803. {
  35804. // if the previous column isn't draggable, we can't move our column
  35805. // past it, because that'd change the undraggable column's position..
  35806. const ColumnInfo* const previous = columns.getUnchecked (newIndex - 1);
  35807. if ((previous->propertyFlags & draggable) != 0)
  35808. {
  35809. const int leftOfPrevious = getColumnPosition (newIndex - 1).getX();
  35810. const int rightOfCurrent = getColumnPosition (newIndex).getRight();
  35811. if (abs (dragOverlayComp->getX() - leftOfPrevious)
  35812. < abs (dragOverlayComp->getRight() - rightOfCurrent))
  35813. {
  35814. --newIndex;
  35815. }
  35816. }
  35817. }
  35818. if (newIndex < columns.size() - 1)
  35819. {
  35820. // if the next column isn't draggable, we can't move our column
  35821. // past it, because that'd change the undraggable column's position..
  35822. const ColumnInfo* const nextCol = columns.getUnchecked (newIndex + 1);
  35823. if ((nextCol->propertyFlags & draggable) != 0)
  35824. {
  35825. const int leftOfCurrent = getColumnPosition (newIndex).getX();
  35826. const int rightOfNext = getColumnPosition (newIndex + 1).getRight();
  35827. if (abs (dragOverlayComp->getX() - leftOfCurrent)
  35828. > abs (dragOverlayComp->getRight() - rightOfNext))
  35829. {
  35830. ++newIndex;
  35831. }
  35832. }
  35833. }
  35834. if (newIndex != currentIndex)
  35835. moveColumn (columnIdBeingDragged, newIndex);
  35836. else
  35837. break;
  35838. }
  35839. }
  35840. }
  35841. else
  35842. {
  35843. endDrag (draggingColumnOriginalIndex);
  35844. }
  35845. }
  35846. }
  35847. void TableHeaderComponent::beginDrag (const MouseEvent& e)
  35848. {
  35849. if (columnIdBeingDragged == 0)
  35850. {
  35851. columnIdBeingDragged = getColumnIdAtX (e.getMouseDownX());
  35852. const ColumnInfo* const ci = getInfoForId (columnIdBeingDragged);
  35853. if (ci == 0 || (ci->propertyFlags & draggable) == 0)
  35854. {
  35855. columnIdBeingDragged = 0;
  35856. }
  35857. else
  35858. {
  35859. draggingColumnOriginalIndex = getIndexOfColumnId (columnIdBeingDragged, true);
  35860. const Rectangle columnRect (getColumnPosition (draggingColumnOriginalIndex));
  35861. const int temp = columnIdBeingDragged;
  35862. columnIdBeingDragged = 0;
  35863. addAndMakeVisible (dragOverlayComp = new DragOverlayComp (createComponentSnapshot (columnRect, false)));
  35864. columnIdBeingDragged = temp;
  35865. dragOverlayComp->setBounds (columnRect);
  35866. for (int i = listeners.size(); --i >= 0;)
  35867. {
  35868. listeners.getUnchecked(i)->tableColumnDraggingChanged (this, columnIdBeingDragged);
  35869. i = jmin (i, listeners.size() - 1);
  35870. }
  35871. }
  35872. }
  35873. }
  35874. void TableHeaderComponent::endDrag (const int finalIndex)
  35875. {
  35876. if (columnIdBeingDragged != 0)
  35877. {
  35878. moveColumn (columnIdBeingDragged, finalIndex);
  35879. columnIdBeingDragged = 0;
  35880. repaint();
  35881. for (int i = listeners.size(); --i >= 0;)
  35882. {
  35883. listeners.getUnchecked(i)->tableColumnDraggingChanged (this, 0);
  35884. i = jmin (i, listeners.size() - 1);
  35885. }
  35886. }
  35887. }
  35888. void TableHeaderComponent::mouseUp (const MouseEvent& e)
  35889. {
  35890. mouseDrag (e);
  35891. for (int i = columns.size(); --i >= 0;)
  35892. if (columns.getUnchecked (i)->isVisible())
  35893. columns.getUnchecked (i)->lastDeliberateWidth = columns.getUnchecked (i)->width;
  35894. columnIdBeingResized = 0;
  35895. repaint();
  35896. endDrag (getIndexOfColumnId (columnIdBeingDragged, true));
  35897. updateColumnUnderMouse (e.x, e.y);
  35898. if (columnIdUnderMouse != 0 && e.mouseWasClicked() && ! e.mods.isPopupMenu())
  35899. columnClicked (columnIdUnderMouse, e.mods);
  35900. deleteAndZero (dragOverlayComp);
  35901. }
  35902. const MouseCursor TableHeaderComponent::getMouseCursor()
  35903. {
  35904. int x, y;
  35905. getMouseXYRelative (x, y);
  35906. if (columnIdBeingResized != 0 || (getResizeDraggerAt (x) != 0 && ! isMouseButtonDown()))
  35907. return MouseCursor (MouseCursor::LeftRightResizeCursor);
  35908. return Component::getMouseCursor();
  35909. }
  35910. bool TableHeaderComponent::ColumnInfo::isVisible() const throw()
  35911. {
  35912. return (propertyFlags & TableHeaderComponent::visible) != 0;
  35913. }
  35914. TableHeaderComponent::ColumnInfo* TableHeaderComponent::getInfoForId (const int id) const throw()
  35915. {
  35916. for (int i = columns.size(); --i >= 0;)
  35917. if (columns.getUnchecked(i)->id == id)
  35918. return columns.getUnchecked(i);
  35919. return 0;
  35920. }
  35921. int TableHeaderComponent::visibleIndexToTotalIndex (const int visibleIndex) const throw()
  35922. {
  35923. int n = 0;
  35924. for (int i = 0; i < columns.size(); ++i)
  35925. {
  35926. if (columns.getUnchecked(i)->isVisible())
  35927. {
  35928. if (n == visibleIndex)
  35929. return i;
  35930. ++n;
  35931. }
  35932. }
  35933. return -1;
  35934. }
  35935. void TableHeaderComponent::sendColumnsChanged()
  35936. {
  35937. if (stretchToFit && lastDeliberateWidth > 0)
  35938. resizeAllColumnsToFit (lastDeliberateWidth);
  35939. repaint();
  35940. columnsChanged = true;
  35941. triggerAsyncUpdate();
  35942. }
  35943. void TableHeaderComponent::handleAsyncUpdate()
  35944. {
  35945. const bool changed = columnsChanged || sortChanged;
  35946. const bool sized = columnsResized || changed;
  35947. const bool sorted = sortChanged;
  35948. columnsChanged = false;
  35949. columnsResized = false;
  35950. sortChanged = false;
  35951. if (sorted)
  35952. {
  35953. for (int i = listeners.size(); --i >= 0;)
  35954. {
  35955. listeners.getUnchecked(i)->tableSortOrderChanged (this);
  35956. i = jmin (i, listeners.size() - 1);
  35957. }
  35958. }
  35959. if (changed)
  35960. {
  35961. for (int i = listeners.size(); --i >= 0;)
  35962. {
  35963. listeners.getUnchecked(i)->tableColumnsChanged (this);
  35964. i = jmin (i, listeners.size() - 1);
  35965. }
  35966. }
  35967. if (sized)
  35968. {
  35969. for (int i = listeners.size(); --i >= 0;)
  35970. {
  35971. listeners.getUnchecked(i)->tableColumnsResized (this);
  35972. i = jmin (i, listeners.size() - 1);
  35973. }
  35974. }
  35975. }
  35976. int TableHeaderComponent::getResizeDraggerAt (const int mouseX) const throw()
  35977. {
  35978. if (((unsigned int) mouseX) < (unsigned int) getWidth())
  35979. {
  35980. const int draggableDistance = 3;
  35981. int x = 0;
  35982. for (int i = 0; i < columns.size(); ++i)
  35983. {
  35984. const ColumnInfo* const ci = columns.getUnchecked(i);
  35985. if (ci->isVisible())
  35986. {
  35987. if (abs (mouseX - (x + ci->width)) <= draggableDistance
  35988. && (ci->propertyFlags & resizable) != 0)
  35989. return ci->id;
  35990. x += ci->width;
  35991. }
  35992. }
  35993. }
  35994. return 0;
  35995. }
  35996. void TableHeaderComponent::updateColumnUnderMouse (int x, int y)
  35997. {
  35998. const int newCol = (reallyContains (x, y, true) && getResizeDraggerAt (x) == 0)
  35999. ? getColumnIdAtX (x) : 0;
  36000. if (newCol != columnIdUnderMouse)
  36001. {
  36002. columnIdUnderMouse = newCol;
  36003. repaint();
  36004. }
  36005. }
  36006. void TableHeaderComponent::showColumnChooserMenu (const int columnIdClicked)
  36007. {
  36008. PopupMenu m;
  36009. addMenuItems (m, columnIdClicked);
  36010. if (m.getNumItems() > 0)
  36011. {
  36012. const int result = m.show();
  36013. if (result != 0)
  36014. reactToMenuItem (result, columnIdClicked);
  36015. }
  36016. }
  36017. void TableHeaderListener::tableColumnDraggingChanged (TableHeaderComponent*, int)
  36018. {
  36019. }
  36020. END_JUCE_NAMESPACE
  36021. /********* End of inlined file: juce_TableHeaderComponent.cpp *********/
  36022. /********* Start of inlined file: juce_TableListBox.cpp *********/
  36023. BEGIN_JUCE_NAMESPACE
  36024. static const tchar* const tableColumnPropertyTag = T("_tableColumnID");
  36025. class TableListRowComp : public Component
  36026. {
  36027. public:
  36028. TableListRowComp (TableListBox& owner_)
  36029. : owner (owner_),
  36030. row (-1),
  36031. isSelected (false)
  36032. {
  36033. }
  36034. ~TableListRowComp()
  36035. {
  36036. deleteAllChildren();
  36037. }
  36038. void paint (Graphics& g)
  36039. {
  36040. TableListBoxModel* const model = owner.getModel();
  36041. if (model != 0)
  36042. {
  36043. const TableHeaderComponent* const header = owner.getHeader();
  36044. model->paintRowBackground (g, row, getWidth(), getHeight(), isSelected);
  36045. const int numColumns = header->getNumColumns (true);
  36046. for (int i = 0; i < numColumns; ++i)
  36047. {
  36048. if (! columnsWithComponents [i])
  36049. {
  36050. const int columnId = header->getColumnIdOfIndex (i, true);
  36051. Rectangle columnRect (header->getColumnPosition (i));
  36052. columnRect.setSize (columnRect.getWidth(), getHeight());
  36053. g.saveState();
  36054. g.reduceClipRegion (columnRect);
  36055. g.setOrigin (columnRect.getX(), 0);
  36056. model->paintCell (g, row, columnId, columnRect.getWidth(), columnRect.getHeight(), isSelected);
  36057. g.restoreState();
  36058. }
  36059. }
  36060. }
  36061. }
  36062. void update (const int newRow, const bool isNowSelected)
  36063. {
  36064. if (newRow != row || isNowSelected != isSelected)
  36065. {
  36066. row = newRow;
  36067. isSelected = isNowSelected;
  36068. repaint();
  36069. }
  36070. if (row < owner.getNumRows())
  36071. {
  36072. jassert (row >= 0);
  36073. const tchar* const tagPropertyName = T("_tableLastUseNum");
  36074. const int newTag = Random::getSystemRandom().nextInt();
  36075. const TableHeaderComponent* const header = owner.getHeader();
  36076. const int numColumns = header->getNumColumns (true);
  36077. int i;
  36078. columnsWithComponents.clear();
  36079. if (owner.getModel() != 0)
  36080. {
  36081. for (i = 0; i < numColumns; ++i)
  36082. {
  36083. const int columnId = header->getColumnIdOfIndex (i, true);
  36084. Component* const newComp
  36085. = owner.getModel()->refreshComponentForCell (row, columnId, isSelected,
  36086. findChildComponentForColumn (columnId));
  36087. if (newComp != 0)
  36088. {
  36089. addAndMakeVisible (newComp);
  36090. newComp->setComponentProperty (tagPropertyName, newTag);
  36091. newComp->setComponentProperty (tableColumnPropertyTag, columnId);
  36092. const Rectangle columnRect (header->getColumnPosition (i));
  36093. newComp->setBounds (columnRect.getX(), 0, columnRect.getWidth(), getHeight());
  36094. columnsWithComponents.setBit (i);
  36095. }
  36096. }
  36097. }
  36098. for (i = getNumChildComponents(); --i >= 0;)
  36099. {
  36100. Component* const c = getChildComponent (i);
  36101. if (c->getComponentPropertyInt (tagPropertyName, false, 0) != newTag)
  36102. delete c;
  36103. }
  36104. }
  36105. else
  36106. {
  36107. columnsWithComponents.clear();
  36108. deleteAllChildren();
  36109. }
  36110. }
  36111. void resized()
  36112. {
  36113. for (int i = getNumChildComponents(); --i >= 0;)
  36114. {
  36115. Component* const c = getChildComponent (i);
  36116. const int columnId = c->getComponentPropertyInt (tableColumnPropertyTag, false, 0);
  36117. if (columnId != 0)
  36118. {
  36119. const Rectangle columnRect (owner.getHeader()->getColumnPosition (owner.getHeader()->getIndexOfColumnId (columnId, true)));
  36120. c->setBounds (columnRect.getX(), 0, columnRect.getWidth(), getHeight());
  36121. }
  36122. }
  36123. }
  36124. void mouseDown (const MouseEvent& e)
  36125. {
  36126. isDragging = false;
  36127. selectRowOnMouseUp = false;
  36128. if (isEnabled())
  36129. {
  36130. if (! isSelected)
  36131. {
  36132. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  36133. const int columnId = owner.getHeader()->getColumnIdAtX (e.x);
  36134. if (columnId != 0 && owner.getModel() != 0)
  36135. owner.getModel()->cellClicked (row, columnId, e);
  36136. }
  36137. else
  36138. {
  36139. selectRowOnMouseUp = true;
  36140. }
  36141. }
  36142. }
  36143. void mouseDrag (const MouseEvent& e)
  36144. {
  36145. if (isEnabled() && owner.getModel() != 0 && ! (e.mouseWasClicked() || isDragging))
  36146. {
  36147. const SparseSet <int> selectedRows (owner.getSelectedRows());
  36148. if (selectedRows.size() > 0)
  36149. {
  36150. const String dragDescription (owner.getModel()->getDragSourceDescription (selectedRows));
  36151. if (dragDescription.isNotEmpty())
  36152. {
  36153. isDragging = true;
  36154. DragAndDropContainer* const dragContainer
  36155. = DragAndDropContainer::findParentDragContainerFor (this);
  36156. if (dragContainer != 0)
  36157. {
  36158. Image* dragImage = owner.createSnapshotOfSelectedRows();
  36159. dragImage->multiplyAllAlphas (0.6f);
  36160. dragContainer->startDragging (dragDescription, &owner, dragImage, true);
  36161. }
  36162. else
  36163. {
  36164. // to be able to do a drag-and-drop operation, the listbox needs to
  36165. // be inside a component which is also a DragAndDropContainer.
  36166. jassertfalse
  36167. }
  36168. }
  36169. }
  36170. }
  36171. }
  36172. void mouseUp (const MouseEvent& e)
  36173. {
  36174. if (selectRowOnMouseUp && e.mouseWasClicked() && isEnabled())
  36175. {
  36176. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  36177. const int columnId = owner.getHeader()->getColumnIdAtX (e.x);
  36178. if (columnId != 0 && owner.getModel() != 0)
  36179. owner.getModel()->cellClicked (row, columnId, e);
  36180. }
  36181. }
  36182. void mouseDoubleClick (const MouseEvent& e)
  36183. {
  36184. const int columnId = owner.getHeader()->getColumnIdAtX (e.x);
  36185. if (columnId != 0 && owner.getModel() != 0)
  36186. owner.getModel()->cellDoubleClicked (row, columnId, e);
  36187. }
  36188. juce_UseDebuggingNewOperator
  36189. private:
  36190. TableListBox& owner;
  36191. int row;
  36192. bool isSelected, isDragging, selectRowOnMouseUp;
  36193. BitArray columnsWithComponents;
  36194. Component* findChildComponentForColumn (const int columnId) const
  36195. {
  36196. for (int i = getNumChildComponents(); --i >= 0;)
  36197. {
  36198. Component* const c = getChildComponent (i);
  36199. if (c->getComponentPropertyInt (tableColumnPropertyTag, false, 0) == columnId)
  36200. return c;
  36201. }
  36202. return 0;
  36203. }
  36204. TableListRowComp (const TableListRowComp&);
  36205. const TableListRowComp& operator= (const TableListRowComp&);
  36206. };
  36207. class TableListBoxHeader : public TableHeaderComponent
  36208. {
  36209. public:
  36210. TableListBoxHeader (TableListBox& owner_)
  36211. : owner (owner_)
  36212. {
  36213. }
  36214. ~TableListBoxHeader()
  36215. {
  36216. }
  36217. void addMenuItems (PopupMenu& menu, const int columnIdClicked)
  36218. {
  36219. if (owner.isAutoSizeMenuOptionShown())
  36220. {
  36221. menu.addItem (0xf836743, TRANS("Auto-size this column"), columnIdClicked != 0);
  36222. menu.addItem (0xf836744, TRANS("Auto-size all columns"), owner.getHeader()->getNumColumns (true) > 0);
  36223. menu.addSeparator();
  36224. }
  36225. TableHeaderComponent::addMenuItems (menu, columnIdClicked);
  36226. }
  36227. void reactToMenuItem (const int menuReturnId, const int columnIdClicked)
  36228. {
  36229. if (menuReturnId == 0xf836743)
  36230. {
  36231. owner.autoSizeColumn (columnIdClicked);
  36232. }
  36233. else if (menuReturnId == 0xf836744)
  36234. {
  36235. owner.autoSizeAllColumns();
  36236. }
  36237. else
  36238. {
  36239. TableHeaderComponent::reactToMenuItem (menuReturnId, columnIdClicked);
  36240. }
  36241. }
  36242. juce_UseDebuggingNewOperator
  36243. private:
  36244. TableListBox& owner;
  36245. TableListBoxHeader (const TableListBoxHeader&);
  36246. const TableListBoxHeader& operator= (const TableListBoxHeader&);
  36247. };
  36248. TableListBox::TableListBox (const String& name, TableListBoxModel* const model_)
  36249. : ListBox (name, 0),
  36250. model (model_),
  36251. autoSizeOptionsShown (true)
  36252. {
  36253. ListBox::model = this;
  36254. header = new TableListBoxHeader (*this);
  36255. header->setSize (100, 28);
  36256. header->addListener (this);
  36257. setHeaderComponent (header);
  36258. }
  36259. TableListBox::~TableListBox()
  36260. {
  36261. deleteAllChildren();
  36262. }
  36263. void TableListBox::setModel (TableListBoxModel* const newModel)
  36264. {
  36265. if (model != newModel)
  36266. {
  36267. model = newModel;
  36268. updateContent();
  36269. }
  36270. }
  36271. int TableListBox::getHeaderHeight() const throw()
  36272. {
  36273. return header->getHeight();
  36274. }
  36275. void TableListBox::setHeaderHeight (const int newHeight)
  36276. {
  36277. header->setSize (header->getWidth(), newHeight);
  36278. resized();
  36279. }
  36280. void TableListBox::autoSizeColumn (const int columnId)
  36281. {
  36282. const int width = model != 0 ? model->getColumnAutoSizeWidth (columnId) : 0;
  36283. if (width > 0)
  36284. header->setColumnWidth (columnId, width);
  36285. }
  36286. void TableListBox::autoSizeAllColumns()
  36287. {
  36288. for (int i = 0; i < header->getNumColumns (true); ++i)
  36289. autoSizeColumn (header->getColumnIdOfIndex (i, true));
  36290. }
  36291. void TableListBox::setAutoSizeMenuOptionShown (const bool shouldBeShown)
  36292. {
  36293. autoSizeOptionsShown = shouldBeShown;
  36294. }
  36295. bool TableListBox::isAutoSizeMenuOptionShown() const throw()
  36296. {
  36297. return autoSizeOptionsShown;
  36298. }
  36299. const Rectangle TableListBox::getCellPosition (const int columnId,
  36300. const int rowNumber,
  36301. const bool relativeToComponentTopLeft) const
  36302. {
  36303. Rectangle headerCell (header->getColumnPosition (header->getIndexOfColumnId (columnId, true)));
  36304. if (relativeToComponentTopLeft)
  36305. headerCell.translate (header->getX(), 0);
  36306. const Rectangle row (getRowPosition (rowNumber, relativeToComponentTopLeft));
  36307. return Rectangle (headerCell.getX(), row.getY(),
  36308. headerCell.getWidth(), row.getHeight());
  36309. }
  36310. void TableListBox::scrollToEnsureColumnIsOnscreen (const int columnId)
  36311. {
  36312. ScrollBar* const scrollbar = getHorizontalScrollBar();
  36313. if (scrollbar != 0)
  36314. {
  36315. const Rectangle pos (header->getColumnPosition (header->getIndexOfColumnId (columnId, true)));
  36316. double x = scrollbar->getCurrentRangeStart();
  36317. const double w = scrollbar->getCurrentRangeSize();
  36318. if (pos.getX() < x)
  36319. x = pos.getX();
  36320. else if (pos.getRight() > x + w)
  36321. x += jmax (0.0, pos.getRight() - (x + w));
  36322. scrollbar->setCurrentRangeStart (x);
  36323. }
  36324. }
  36325. int TableListBox::getNumRows()
  36326. {
  36327. return model != 0 ? model->getNumRows() : 0;
  36328. }
  36329. void TableListBox::paintListBoxItem (int, Graphics&, int, int, bool)
  36330. {
  36331. }
  36332. Component* TableListBox::refreshComponentForRow (int rowNumber, bool isRowSelected, Component* existingComponentToUpdate)
  36333. {
  36334. if (existingComponentToUpdate == 0)
  36335. existingComponentToUpdate = new TableListRowComp (*this);
  36336. ((TableListRowComp*) existingComponentToUpdate)->update (rowNumber, isRowSelected);
  36337. return existingComponentToUpdate;
  36338. }
  36339. void TableListBox::selectedRowsChanged (int row)
  36340. {
  36341. if (model != 0)
  36342. model->selectedRowsChanged (row);
  36343. }
  36344. void TableListBox::deleteKeyPressed (int row)
  36345. {
  36346. if (model != 0)
  36347. model->deleteKeyPressed (row);
  36348. }
  36349. void TableListBox::returnKeyPressed (int row)
  36350. {
  36351. if (model != 0)
  36352. model->returnKeyPressed (row);
  36353. }
  36354. void TableListBox::backgroundClicked()
  36355. {
  36356. if (model != 0)
  36357. model->backgroundClicked();
  36358. }
  36359. void TableListBox::listWasScrolled()
  36360. {
  36361. if (model != 0)
  36362. model->listWasScrolled();
  36363. }
  36364. void TableListBox::tableColumnsChanged (TableHeaderComponent*)
  36365. {
  36366. setMinimumContentWidth (header->getTotalWidth());
  36367. repaint();
  36368. updateColumnComponents();
  36369. }
  36370. void TableListBox::tableColumnsResized (TableHeaderComponent*)
  36371. {
  36372. setMinimumContentWidth (header->getTotalWidth());
  36373. repaint();
  36374. updateColumnComponents();
  36375. }
  36376. void TableListBox::tableSortOrderChanged (TableHeaderComponent*)
  36377. {
  36378. if (model != 0)
  36379. model->sortOrderChanged (header->getSortColumnId(),
  36380. header->isSortedForwards());
  36381. }
  36382. void TableListBox::tableColumnDraggingChanged (TableHeaderComponent*, int columnIdNowBeingDragged_)
  36383. {
  36384. columnIdNowBeingDragged = columnIdNowBeingDragged_;
  36385. repaint();
  36386. }
  36387. void TableListBox::resized()
  36388. {
  36389. ListBox::resized();
  36390. header->resizeAllColumnsToFit (getVisibleContentWidth());
  36391. setMinimumContentWidth (header->getTotalWidth());
  36392. }
  36393. void TableListBox::updateColumnComponents() const
  36394. {
  36395. const int firstRow = getRowContainingPosition (0, 0);
  36396. for (int i = firstRow + getNumRowsOnScreen() + 2; --i >= firstRow;)
  36397. {
  36398. TableListRowComp* const rowComp = dynamic_cast <TableListRowComp*> (getComponentForRowNumber (i));
  36399. if (rowComp != 0)
  36400. rowComp->resized();
  36401. }
  36402. }
  36403. void TableListBoxModel::cellClicked (int, int, const MouseEvent&)
  36404. {
  36405. }
  36406. void TableListBoxModel::cellDoubleClicked (int, int, const MouseEvent&)
  36407. {
  36408. }
  36409. void TableListBoxModel::backgroundClicked()
  36410. {
  36411. }
  36412. void TableListBoxModel::sortOrderChanged (int, const bool)
  36413. {
  36414. }
  36415. int TableListBoxModel::getColumnAutoSizeWidth (int)
  36416. {
  36417. return 0;
  36418. }
  36419. void TableListBoxModel::selectedRowsChanged (int)
  36420. {
  36421. }
  36422. void TableListBoxModel::deleteKeyPressed (int)
  36423. {
  36424. }
  36425. void TableListBoxModel::returnKeyPressed (int)
  36426. {
  36427. }
  36428. void TableListBoxModel::listWasScrolled()
  36429. {
  36430. }
  36431. const String TableListBoxModel::getDragSourceDescription (const SparseSet<int>&)
  36432. {
  36433. return String::empty;
  36434. }
  36435. Component* TableListBoxModel::refreshComponentForCell (int, int, bool, Component* existingComponentToUpdate)
  36436. {
  36437. (void) existingComponentToUpdate;
  36438. jassert (existingComponentToUpdate == 0); // indicates a failure in the code the recycles the components
  36439. return 0;
  36440. }
  36441. END_JUCE_NAMESPACE
  36442. /********* End of inlined file: juce_TableListBox.cpp *********/
  36443. /********* Start of inlined file: juce_TextEditor.cpp *********/
  36444. BEGIN_JUCE_NAMESPACE
  36445. #define SHOULD_WRAP(x, wrapwidth) (((x) - 0.0001f) >= (wrapwidth))
  36446. // a word or space that can't be broken down any further
  36447. struct TextAtom
  36448. {
  36449. String atomText;
  36450. float width;
  36451. uint16 numChars;
  36452. bool isWhitespace() const throw() { return CharacterFunctions::isWhitespace (atomText[0]); }
  36453. bool isNewLine() const throw() { return atomText[0] == T('\r') || atomText[0] == T('\n'); }
  36454. const String getText (const tchar passwordCharacter) const throw()
  36455. {
  36456. if (passwordCharacter == 0)
  36457. return atomText;
  36458. else
  36459. return String::repeatedString (String::charToString (passwordCharacter),
  36460. atomText.length());
  36461. }
  36462. const String getTrimmedText (const tchar passwordCharacter) const throw()
  36463. {
  36464. if (passwordCharacter == 0)
  36465. return atomText.substring (0, numChars);
  36466. else if (isNewLine())
  36467. return String::empty;
  36468. else
  36469. return String::repeatedString (String::charToString (passwordCharacter), numChars);
  36470. }
  36471. };
  36472. // a run of text with a single font and colour
  36473. class UniformTextSection
  36474. {
  36475. public:
  36476. UniformTextSection (const String& text,
  36477. const Font& font_,
  36478. const Colour& colour_,
  36479. const tchar passwordCharacter) throw()
  36480. : font (font_),
  36481. colour (colour_),
  36482. atoms (64)
  36483. {
  36484. initialiseAtoms (text, passwordCharacter);
  36485. }
  36486. UniformTextSection (const UniformTextSection& other) throw()
  36487. : font (other.font),
  36488. colour (other.colour),
  36489. atoms (64)
  36490. {
  36491. for (int i = 0; i < other.atoms.size(); ++i)
  36492. atoms.add (new TextAtom (*(const TextAtom*) other.atoms.getUnchecked(i)));
  36493. }
  36494. ~UniformTextSection() throw()
  36495. {
  36496. // (no need to delete the atoms, as they're explicitly deleted by the caller)
  36497. }
  36498. void clear() throw()
  36499. {
  36500. for (int i = atoms.size(); --i >= 0;)
  36501. {
  36502. TextAtom* const atom = getAtom(i);
  36503. delete atom;
  36504. }
  36505. atoms.clear();
  36506. }
  36507. int getNumAtoms() const throw()
  36508. {
  36509. return atoms.size();
  36510. }
  36511. TextAtom* getAtom (const int index) const throw()
  36512. {
  36513. return (TextAtom*) atoms.getUnchecked (index);
  36514. }
  36515. void append (const UniformTextSection& other, const tchar passwordCharacter) throw()
  36516. {
  36517. if (other.atoms.size() > 0)
  36518. {
  36519. TextAtom* const lastAtom = (TextAtom*) atoms.getLast();
  36520. int i = 0;
  36521. if (lastAtom != 0)
  36522. {
  36523. if (! CharacterFunctions::isWhitespace (lastAtom->atomText.getLastCharacter()))
  36524. {
  36525. TextAtom* const first = other.getAtom(0);
  36526. if (! CharacterFunctions::isWhitespace (first->atomText[0]))
  36527. {
  36528. lastAtom->atomText += first->atomText;
  36529. lastAtom->numChars = (uint16) (lastAtom->numChars + first->numChars);
  36530. lastAtom->width = font.getStringWidthFloat (lastAtom->getText (passwordCharacter));
  36531. delete first;
  36532. ++i;
  36533. }
  36534. }
  36535. }
  36536. while (i < other.atoms.size())
  36537. {
  36538. atoms.add (other.getAtom(i));
  36539. ++i;
  36540. }
  36541. }
  36542. }
  36543. UniformTextSection* split (const int indexToBreakAt,
  36544. const tchar passwordCharacter) throw()
  36545. {
  36546. UniformTextSection* const section2 = new UniformTextSection (String::empty,
  36547. font, colour,
  36548. passwordCharacter);
  36549. int index = 0;
  36550. for (int i = 0; i < atoms.size(); ++i)
  36551. {
  36552. TextAtom* const atom = getAtom(i);
  36553. const int nextIndex = index + atom->numChars;
  36554. if (index == indexToBreakAt)
  36555. {
  36556. int j;
  36557. for (j = i; 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. else if (indexToBreakAt >= index && indexToBreakAt < nextIndex)
  36564. {
  36565. TextAtom* const secondAtom = new TextAtom();
  36566. secondAtom->atomText = atom->atomText.substring (indexToBreakAt - index);
  36567. secondAtom->width = font.getStringWidthFloat (secondAtom->getText (passwordCharacter));
  36568. secondAtom->numChars = (uint16) secondAtom->atomText.length();
  36569. section2->atoms.add (secondAtom);
  36570. atom->atomText = atom->atomText.substring (0, indexToBreakAt - index);
  36571. atom->width = font.getStringWidthFloat (atom->getText (passwordCharacter));
  36572. atom->numChars = (uint16) (indexToBreakAt - index);
  36573. int j;
  36574. for (j = i + 1; j < atoms.size(); ++j)
  36575. section2->atoms.add (getAtom (j));
  36576. for (j = atoms.size(); --j > i;)
  36577. atoms.remove (j);
  36578. break;
  36579. }
  36580. index = nextIndex;
  36581. }
  36582. return section2;
  36583. }
  36584. const String getAllText() const throw()
  36585. {
  36586. String s;
  36587. s.preallocateStorage (getTotalLength());
  36588. tchar* endOfString = (tchar*) &(s[0]);
  36589. for (int i = 0; i < atoms.size(); ++i)
  36590. {
  36591. const TextAtom* const atom = getAtom(i);
  36592. memcpy (endOfString, &(atom->atomText[0]), atom->numChars * sizeof (tchar));
  36593. endOfString += atom->numChars;
  36594. }
  36595. *endOfString = 0;
  36596. jassert ((endOfString - (tchar*) &(s[0])) <= getTotalLength());
  36597. return s;
  36598. }
  36599. const String getTextSubstring (const int startCharacter,
  36600. const int endCharacter) const throw()
  36601. {
  36602. int index = 0;
  36603. int totalLen = 0;
  36604. int i;
  36605. for (i = 0; i < atoms.size(); ++i)
  36606. {
  36607. const TextAtom* const atom = getAtom (i);
  36608. const int nextIndex = index + atom->numChars;
  36609. if (startCharacter < nextIndex)
  36610. {
  36611. if (endCharacter <= index)
  36612. break;
  36613. const int start = jmax (0, startCharacter - index);
  36614. const int end = jmin (endCharacter - index, atom->numChars);
  36615. jassert (end >= start);
  36616. totalLen += end - start;
  36617. }
  36618. index = nextIndex;
  36619. }
  36620. String s;
  36621. s.preallocateStorage (totalLen + 1);
  36622. tchar* psz = (tchar*) (const tchar*) s;
  36623. index = 0;
  36624. for (i = 0; i < atoms.size(); ++i)
  36625. {
  36626. const TextAtom* const atom = getAtom (i);
  36627. const int nextIndex = index + atom->numChars;
  36628. if (startCharacter < nextIndex)
  36629. {
  36630. if (endCharacter <= index)
  36631. break;
  36632. const int start = jmax (0, startCharacter - index);
  36633. const int len = jmin (endCharacter - index, atom->numChars) - start;
  36634. memcpy (psz, ((const tchar*) atom->atomText) + start, len * sizeof (tchar));
  36635. psz += len;
  36636. *psz = 0;
  36637. }
  36638. index = nextIndex;
  36639. }
  36640. return s;
  36641. }
  36642. int getTotalLength() const throw()
  36643. {
  36644. int c = 0;
  36645. for (int i = atoms.size(); --i >= 0;)
  36646. c += getAtom(i)->numChars;
  36647. return c;
  36648. }
  36649. void setFont (const Font& newFont,
  36650. const tchar passwordCharacter) throw()
  36651. {
  36652. if (font != newFont)
  36653. {
  36654. font = newFont;
  36655. for (int i = atoms.size(); --i >= 0;)
  36656. {
  36657. TextAtom* const atom = (TextAtom*) atoms.getUnchecked(i);
  36658. atom->width = newFont.getStringWidthFloat (atom->getText (passwordCharacter));
  36659. }
  36660. }
  36661. }
  36662. juce_UseDebuggingNewOperator
  36663. Font font;
  36664. Colour colour;
  36665. private:
  36666. VoidArray atoms;
  36667. void initialiseAtoms (const String& textToParse,
  36668. const tchar passwordCharacter) throw()
  36669. {
  36670. int i = 0;
  36671. const int len = textToParse.length();
  36672. const tchar* const text = (const tchar*) textToParse;
  36673. while (i < len)
  36674. {
  36675. int start = i;
  36676. // create a whitespace atom unless it starts with non-ws
  36677. if (CharacterFunctions::isWhitespace (text[i])
  36678. && text[i] != T('\r')
  36679. && text[i] != T('\n'))
  36680. {
  36681. while (i < len
  36682. && CharacterFunctions::isWhitespace (text[i])
  36683. && text[i] != T('\r')
  36684. && text[i] != T('\n'))
  36685. {
  36686. ++i;
  36687. }
  36688. }
  36689. else
  36690. {
  36691. if (text[i] == T('\r'))
  36692. {
  36693. ++i;
  36694. if ((i < len) && (text[i] == T('\n')))
  36695. {
  36696. ++start;
  36697. ++i;
  36698. }
  36699. }
  36700. else if (text[i] == T('\n'))
  36701. {
  36702. ++i;
  36703. }
  36704. else
  36705. {
  36706. while ((i < len) && ! CharacterFunctions::isWhitespace (text[i]))
  36707. ++i;
  36708. }
  36709. }
  36710. TextAtom* const atom = new TextAtom();
  36711. atom->atomText = String (text + start, i - start);
  36712. atom->width = font.getStringWidthFloat (atom->getText (passwordCharacter));
  36713. atom->numChars = (uint16) (i - start);
  36714. atoms.add (atom);
  36715. }
  36716. }
  36717. const UniformTextSection& operator= (const UniformTextSection& other);
  36718. };
  36719. class TextEditorIterator
  36720. {
  36721. public:
  36722. TextEditorIterator (const VoidArray& sections_,
  36723. const float wordWrapWidth_,
  36724. const tchar passwordCharacter_) throw()
  36725. : indexInText (0),
  36726. lineY (0),
  36727. lineHeight (0),
  36728. maxDescent (0),
  36729. atomX (0),
  36730. atomRight (0),
  36731. atom (0),
  36732. currentSection (0),
  36733. sections (sections_),
  36734. sectionIndex (0),
  36735. atomIndex (0),
  36736. wordWrapWidth (wordWrapWidth_),
  36737. passwordCharacter (passwordCharacter_)
  36738. {
  36739. jassert (wordWrapWidth_ > 0);
  36740. if (sections.size() > 0)
  36741. currentSection = (const UniformTextSection*) sections.getUnchecked (sectionIndex);
  36742. if (currentSection != 0)
  36743. {
  36744. lineHeight = currentSection->font.getHeight();
  36745. maxDescent = currentSection->font.getDescent();
  36746. }
  36747. }
  36748. TextEditorIterator (const TextEditorIterator& other) throw()
  36749. : indexInText (other.indexInText),
  36750. lineY (other.lineY),
  36751. lineHeight (other.lineHeight),
  36752. maxDescent (other.maxDescent),
  36753. atomX (other.atomX),
  36754. atomRight (other.atomRight),
  36755. atom (other.atom),
  36756. currentSection (other.currentSection),
  36757. sections (other.sections),
  36758. sectionIndex (other.sectionIndex),
  36759. atomIndex (other.atomIndex),
  36760. wordWrapWidth (other.wordWrapWidth),
  36761. passwordCharacter (other.passwordCharacter),
  36762. tempAtom (other.tempAtom)
  36763. {
  36764. }
  36765. ~TextEditorIterator() throw()
  36766. {
  36767. }
  36768. bool next() throw()
  36769. {
  36770. if (atom == &tempAtom)
  36771. {
  36772. const int numRemaining = tempAtom.atomText.length() - tempAtom.numChars;
  36773. if (numRemaining > 0)
  36774. {
  36775. tempAtom.atomText = tempAtom.atomText.substring (tempAtom.numChars);
  36776. atomX = 0;
  36777. if (tempAtom.numChars > 0)
  36778. lineY += lineHeight;
  36779. indexInText += tempAtom.numChars;
  36780. GlyphArrangement g;
  36781. g.addLineOfText (currentSection->font, atom->getText (passwordCharacter), 0.0f, 0.0f);
  36782. int split;
  36783. for (split = 0; split < g.getNumGlyphs(); ++split)
  36784. if (SHOULD_WRAP (g.getGlyph (split).getRight(), wordWrapWidth))
  36785. break;
  36786. if (split > 0 && split <= numRemaining)
  36787. {
  36788. tempAtom.numChars = (uint16) split;
  36789. tempAtom.width = g.getGlyph (split - 1).getRight();
  36790. atomRight = atomX + tempAtom.width;
  36791. return true;
  36792. }
  36793. }
  36794. }
  36795. bool forceNewLine = false;
  36796. if (sectionIndex >= sections.size())
  36797. {
  36798. moveToEndOfLastAtom();
  36799. return false;
  36800. }
  36801. else if (atomIndex >= currentSection->getNumAtoms() - 1)
  36802. {
  36803. if (atomIndex >= currentSection->getNumAtoms())
  36804. {
  36805. if (++sectionIndex >= sections.size())
  36806. {
  36807. moveToEndOfLastAtom();
  36808. return false;
  36809. }
  36810. atomIndex = 0;
  36811. currentSection = (const UniformTextSection*) sections.getUnchecked (sectionIndex);
  36812. lineHeight = jmax (lineHeight, currentSection->font.getHeight());
  36813. maxDescent = jmax (maxDescent, currentSection->font.getDescent());
  36814. }
  36815. else
  36816. {
  36817. const TextAtom* const lastAtom = currentSection->getAtom (atomIndex);
  36818. if (! lastAtom->isWhitespace())
  36819. {
  36820. // handle the case where the last atom in a section is actually part of the same
  36821. // word as the first atom of the next section...
  36822. float right = atomRight + lastAtom->width;
  36823. float lineHeight2 = lineHeight;
  36824. float maxDescent2 = maxDescent;
  36825. for (int section = sectionIndex + 1; section < sections.size(); ++section)
  36826. {
  36827. const UniformTextSection* const s = (const UniformTextSection*) sections.getUnchecked (section);
  36828. if (s->getNumAtoms() == 0)
  36829. break;
  36830. const TextAtom* const nextAtom = s->getAtom (0);
  36831. if (nextAtom->isWhitespace())
  36832. break;
  36833. right += nextAtom->width;
  36834. lineHeight2 = jmax (lineHeight2, s->font.getHeight());
  36835. maxDescent2 = jmax (maxDescent2, s->font.getDescent());
  36836. if (SHOULD_WRAP (right, wordWrapWidth))
  36837. {
  36838. lineHeight = lineHeight2;
  36839. maxDescent = maxDescent2;
  36840. forceNewLine = true;
  36841. break;
  36842. }
  36843. if (s->getNumAtoms() > 1)
  36844. break;
  36845. }
  36846. }
  36847. }
  36848. }
  36849. if (atom != 0)
  36850. {
  36851. atomX = atomRight;
  36852. indexInText += atom->numChars;
  36853. if (atom->isNewLine())
  36854. {
  36855. atomX = 0;
  36856. lineY += lineHeight;
  36857. }
  36858. }
  36859. atom = currentSection->getAtom (atomIndex);
  36860. atomRight = atomX + atom->width;
  36861. ++atomIndex;
  36862. if (SHOULD_WRAP (atomRight, wordWrapWidth) || forceNewLine)
  36863. {
  36864. if (atom->isWhitespace())
  36865. {
  36866. // leave whitespace at the end of a line, but truncate it to avoid scrolling
  36867. atomRight = jmin (atomRight, wordWrapWidth);
  36868. }
  36869. else
  36870. {
  36871. return wrapCurrentAtom();
  36872. }
  36873. }
  36874. return true;
  36875. }
  36876. bool wrapCurrentAtom() throw()
  36877. {
  36878. atomRight = atom->width;
  36879. if (SHOULD_WRAP (atomRight, wordWrapWidth)) // atom too big to fit on a line, so break it up..
  36880. {
  36881. tempAtom = *atom;
  36882. tempAtom.width = 0;
  36883. tempAtom.numChars = 0;
  36884. atom = &tempAtom;
  36885. if (atomX > 0)
  36886. {
  36887. atomX = 0;
  36888. lineY += lineHeight;
  36889. }
  36890. return next();
  36891. }
  36892. atomX = 0;
  36893. lineY += lineHeight;
  36894. return true;
  36895. }
  36896. void draw (Graphics& g, const UniformTextSection*& lastSection) const throw()
  36897. {
  36898. if (passwordCharacter != 0 || ! atom->isWhitespace())
  36899. {
  36900. if (lastSection != currentSection)
  36901. {
  36902. lastSection = currentSection;
  36903. g.setColour (currentSection->colour);
  36904. g.setFont (currentSection->font);
  36905. }
  36906. jassert (atom->getTrimmedText (passwordCharacter).isNotEmpty());
  36907. GlyphArrangement ga;
  36908. ga.addLineOfText (currentSection->font,
  36909. atom->getTrimmedText (passwordCharacter),
  36910. atomX,
  36911. (float) roundFloatToInt (lineY + lineHeight - maxDescent));
  36912. ga.draw (g);
  36913. }
  36914. }
  36915. void drawSelection (Graphics& g,
  36916. const int selectionStart,
  36917. const int selectionEnd) const throw()
  36918. {
  36919. const int startX = roundFloatToInt (indexToX (selectionStart));
  36920. const int endX = roundFloatToInt (indexToX (selectionEnd));
  36921. const int y = roundFloatToInt (lineY);
  36922. const int nextY = roundFloatToInt (lineY + lineHeight);
  36923. g.fillRect (startX, y, endX - startX, nextY - y);
  36924. }
  36925. void drawSelectedText (Graphics& g,
  36926. const int selectionStart,
  36927. const int selectionEnd,
  36928. const Colour& selectedTextColour) const throw()
  36929. {
  36930. if (passwordCharacter != 0 || ! atom->isWhitespace())
  36931. {
  36932. GlyphArrangement ga;
  36933. ga.addLineOfText (currentSection->font,
  36934. atom->getTrimmedText (passwordCharacter),
  36935. atomX,
  36936. (float) roundFloatToInt (lineY + lineHeight - maxDescent));
  36937. if (selectionEnd < indexInText + atom->numChars)
  36938. {
  36939. GlyphArrangement ga2 (ga);
  36940. ga2.removeRangeOfGlyphs (0, selectionEnd - indexInText);
  36941. ga.removeRangeOfGlyphs (selectionEnd - indexInText, -1);
  36942. g.setColour (currentSection->colour);
  36943. ga2.draw (g);
  36944. }
  36945. if (selectionStart > indexInText)
  36946. {
  36947. GlyphArrangement ga2 (ga);
  36948. ga2.removeRangeOfGlyphs (selectionStart - indexInText, -1);
  36949. ga.removeRangeOfGlyphs (0, selectionStart - indexInText);
  36950. g.setColour (currentSection->colour);
  36951. ga2.draw (g);
  36952. }
  36953. g.setColour (selectedTextColour);
  36954. ga.draw (g);
  36955. }
  36956. }
  36957. float indexToX (const int indexToFind) const throw()
  36958. {
  36959. if (indexToFind <= indexInText)
  36960. return atomX;
  36961. if (indexToFind >= indexInText + atom->numChars)
  36962. return atomRight;
  36963. GlyphArrangement g;
  36964. g.addLineOfText (currentSection->font,
  36965. atom->getText (passwordCharacter),
  36966. atomX, 0.0f);
  36967. return jmin (atomRight, g.getGlyph (indexToFind - indexInText).getLeft());
  36968. }
  36969. int xToIndex (const float xToFind) const throw()
  36970. {
  36971. if (xToFind <= atomX || atom->isNewLine())
  36972. return indexInText;
  36973. if (xToFind >= atomRight)
  36974. return indexInText + atom->numChars;
  36975. GlyphArrangement g;
  36976. g.addLineOfText (currentSection->font,
  36977. atom->getText (passwordCharacter),
  36978. atomX, 0.0f);
  36979. int j;
  36980. for (j = 0; j < atom->numChars; ++j)
  36981. if ((g.getGlyph(j).getLeft() + g.getGlyph(j).getRight()) / 2 > xToFind)
  36982. break;
  36983. return indexInText + j;
  36984. }
  36985. void updateLineHeight() throw()
  36986. {
  36987. float x = atomRight;
  36988. int tempSectionIndex = sectionIndex;
  36989. int tempAtomIndex = atomIndex;
  36990. const UniformTextSection* currentSection = (const UniformTextSection*) sections.getUnchecked (tempSectionIndex);
  36991. while (! SHOULD_WRAP (x, wordWrapWidth))
  36992. {
  36993. if (tempSectionIndex >= sections.size())
  36994. break;
  36995. bool checkSize = false;
  36996. if (tempAtomIndex >= currentSection->getNumAtoms())
  36997. {
  36998. if (++tempSectionIndex >= sections.size())
  36999. break;
  37000. tempAtomIndex = 0;
  37001. currentSection = (const UniformTextSection*) sections.getUnchecked (tempSectionIndex);
  37002. checkSize = true;
  37003. }
  37004. const TextAtom* const atom = currentSection->getAtom (tempAtomIndex);
  37005. if (atom == 0)
  37006. break;
  37007. x += atom->width;
  37008. if (SHOULD_WRAP (x, wordWrapWidth) || atom->isNewLine())
  37009. break;
  37010. if (checkSize)
  37011. {
  37012. lineHeight = jmax (lineHeight, currentSection->font.getHeight());
  37013. maxDescent = jmax (maxDescent, currentSection->font.getDescent());
  37014. }
  37015. ++tempAtomIndex;
  37016. }
  37017. }
  37018. bool getCharPosition (const int index, float& cx, float& cy, float& lineHeight_) throw()
  37019. {
  37020. while (next())
  37021. {
  37022. if (indexInText + atom->numChars >= index)
  37023. {
  37024. updateLineHeight();
  37025. if (indexInText + atom->numChars > index)
  37026. {
  37027. cx = indexToX (index);
  37028. cy = lineY;
  37029. lineHeight_ = lineHeight;
  37030. return true;
  37031. }
  37032. }
  37033. }
  37034. cx = atomX;
  37035. cy = lineY;
  37036. lineHeight_ = lineHeight;
  37037. return false;
  37038. }
  37039. juce_UseDebuggingNewOperator
  37040. int indexInText;
  37041. float lineY, lineHeight, maxDescent;
  37042. float atomX, atomRight;
  37043. const TextAtom* atom;
  37044. const UniformTextSection* currentSection;
  37045. private:
  37046. const VoidArray& sections;
  37047. int sectionIndex, atomIndex;
  37048. const float wordWrapWidth;
  37049. const tchar passwordCharacter;
  37050. TextAtom tempAtom;
  37051. const TextEditorIterator& operator= (const TextEditorIterator&);
  37052. void moveToEndOfLastAtom() throw()
  37053. {
  37054. if (atom != 0)
  37055. {
  37056. atomX = atomRight;
  37057. if (atom->isNewLine())
  37058. {
  37059. atomX = 0.0f;
  37060. lineY += lineHeight;
  37061. }
  37062. }
  37063. }
  37064. };
  37065. class TextEditorInsertAction : public UndoableAction
  37066. {
  37067. TextEditor& owner;
  37068. const String text;
  37069. const int insertIndex, oldCaretPos, newCaretPos;
  37070. const Font font;
  37071. const Colour colour;
  37072. TextEditorInsertAction (const TextEditorInsertAction&);
  37073. const TextEditorInsertAction& operator= (const TextEditorInsertAction&);
  37074. public:
  37075. TextEditorInsertAction (TextEditor& owner_,
  37076. const String& text_,
  37077. const int insertIndex_,
  37078. const Font& font_,
  37079. const Colour& colour_,
  37080. const int oldCaretPos_,
  37081. const int newCaretPos_) throw()
  37082. : owner (owner_),
  37083. text (text_),
  37084. insertIndex (insertIndex_),
  37085. oldCaretPos (oldCaretPos_),
  37086. newCaretPos (newCaretPos_),
  37087. font (font_),
  37088. colour (colour_)
  37089. {
  37090. }
  37091. ~TextEditorInsertAction()
  37092. {
  37093. }
  37094. bool perform()
  37095. {
  37096. owner.insert (text, insertIndex, font, colour, 0, newCaretPos);
  37097. return true;
  37098. }
  37099. bool undo()
  37100. {
  37101. owner.remove (insertIndex, insertIndex + text.length(), 0, oldCaretPos);
  37102. return true;
  37103. }
  37104. int getSizeInUnits()
  37105. {
  37106. return text.length() + 16;
  37107. }
  37108. };
  37109. class TextEditorRemoveAction : public UndoableAction
  37110. {
  37111. TextEditor& owner;
  37112. const int startIndex, endIndex, oldCaretPos, newCaretPos;
  37113. VoidArray removedSections;
  37114. TextEditorRemoveAction (const TextEditorRemoveAction&);
  37115. const TextEditorRemoveAction& operator= (const TextEditorRemoveAction&);
  37116. public:
  37117. TextEditorRemoveAction (TextEditor& owner_,
  37118. const int startIndex_,
  37119. const int endIndex_,
  37120. const int oldCaretPos_,
  37121. const int newCaretPos_,
  37122. const VoidArray& removedSections_) throw()
  37123. : owner (owner_),
  37124. startIndex (startIndex_),
  37125. endIndex (endIndex_),
  37126. oldCaretPos (oldCaretPos_),
  37127. newCaretPos (newCaretPos_),
  37128. removedSections (removedSections_)
  37129. {
  37130. }
  37131. ~TextEditorRemoveAction()
  37132. {
  37133. for (int i = removedSections.size(); --i >= 0;)
  37134. {
  37135. UniformTextSection* const section = (UniformTextSection*) removedSections.getUnchecked (i);
  37136. section->clear();
  37137. delete section;
  37138. }
  37139. }
  37140. bool perform()
  37141. {
  37142. owner.remove (startIndex, endIndex, 0, newCaretPos);
  37143. return true;
  37144. }
  37145. bool undo()
  37146. {
  37147. owner.reinsert (startIndex, removedSections);
  37148. owner.moveCursorTo (oldCaretPos, false);
  37149. return true;
  37150. }
  37151. int getSizeInUnits()
  37152. {
  37153. int n = 0;
  37154. for (int i = removedSections.size(); --i >= 0;)
  37155. {
  37156. UniformTextSection* const section = (UniformTextSection*) removedSections.getUnchecked (i);
  37157. n += section->getTotalLength();
  37158. }
  37159. return n + 16;
  37160. }
  37161. };
  37162. class TextHolderComponent : public Component,
  37163. public Timer
  37164. {
  37165. TextEditor* const owner;
  37166. TextHolderComponent (const TextHolderComponent&);
  37167. const TextHolderComponent& operator= (const TextHolderComponent&);
  37168. public:
  37169. TextHolderComponent (TextEditor* const owner_)
  37170. : owner (owner_)
  37171. {
  37172. setWantsKeyboardFocus (false);
  37173. setInterceptsMouseClicks (false, true);
  37174. }
  37175. ~TextHolderComponent()
  37176. {
  37177. }
  37178. void paint (Graphics& g)
  37179. {
  37180. owner->drawContent (g);
  37181. }
  37182. void timerCallback()
  37183. {
  37184. owner->timerCallbackInt();
  37185. }
  37186. const MouseCursor getMouseCursor()
  37187. {
  37188. return owner->getMouseCursor();
  37189. }
  37190. };
  37191. class TextEditorViewport : public Viewport
  37192. {
  37193. TextEditor* const owner;
  37194. float lastWordWrapWidth;
  37195. TextEditorViewport (const TextEditorViewport&);
  37196. const TextEditorViewport& operator= (const TextEditorViewport&);
  37197. public:
  37198. TextEditorViewport (TextEditor* const owner_)
  37199. : owner (owner_),
  37200. lastWordWrapWidth (0)
  37201. {
  37202. }
  37203. ~TextEditorViewport()
  37204. {
  37205. }
  37206. void visibleAreaChanged (int, int, int, int)
  37207. {
  37208. const float wordWrapWidth = owner->getWordWrapWidth();
  37209. if (wordWrapWidth != lastWordWrapWidth)
  37210. {
  37211. lastWordWrapWidth = wordWrapWidth;
  37212. owner->updateTextHolderSize();
  37213. }
  37214. }
  37215. };
  37216. const int flashSpeedIntervalMs = 380;
  37217. const int textChangeMessageId = 0x10003001;
  37218. const int returnKeyMessageId = 0x10003002;
  37219. const int escapeKeyMessageId = 0x10003003;
  37220. const int focusLossMessageId = 0x10003004;
  37221. TextEditor::TextEditor (const String& name,
  37222. const tchar passwordCharacter_)
  37223. : Component (name),
  37224. borderSize (1, 1, 1, 3),
  37225. readOnly (false),
  37226. multiline (false),
  37227. wordWrap (false),
  37228. returnKeyStartsNewLine (false),
  37229. caretVisible (true),
  37230. popupMenuEnabled (true),
  37231. selectAllTextWhenFocused (false),
  37232. scrollbarVisible (true),
  37233. wasFocused (false),
  37234. caretFlashState (true),
  37235. keepCursorOnScreen (true),
  37236. tabKeyUsed (false),
  37237. menuActive (false),
  37238. cursorX (0),
  37239. cursorY (0),
  37240. cursorHeight (0),
  37241. maxTextLength (0),
  37242. selectionStart (0),
  37243. selectionEnd (0),
  37244. leftIndent (4),
  37245. topIndent (4),
  37246. lastTransactionTime (0),
  37247. currentFont (14.0f),
  37248. totalNumChars (0),
  37249. caretPosition (0),
  37250. sections (8),
  37251. passwordCharacter (passwordCharacter_),
  37252. dragType (notDragging),
  37253. listeners (2)
  37254. {
  37255. setOpaque (true);
  37256. addAndMakeVisible (viewport = new TextEditorViewport (this));
  37257. viewport->setViewedComponent (textHolder = new TextHolderComponent (this));
  37258. viewport->setWantsKeyboardFocus (false);
  37259. viewport->setScrollBarsShown (false, false);
  37260. setMouseCursor (MouseCursor::IBeamCursor);
  37261. setWantsKeyboardFocus (true);
  37262. }
  37263. TextEditor::~TextEditor()
  37264. {
  37265. clearInternal (0);
  37266. delete viewport;
  37267. }
  37268. void TextEditor::newTransaction() throw()
  37269. {
  37270. lastTransactionTime = Time::getApproximateMillisecondCounter();
  37271. undoManager.beginNewTransaction();
  37272. }
  37273. void TextEditor::doUndoRedo (const bool isRedo)
  37274. {
  37275. if (! isReadOnly())
  37276. {
  37277. if ((isRedo) ? undoManager.redo()
  37278. : undoManager.undo())
  37279. {
  37280. scrollToMakeSureCursorIsVisible();
  37281. repaint();
  37282. textChanged();
  37283. }
  37284. }
  37285. }
  37286. void TextEditor::setMultiLine (const bool shouldBeMultiLine,
  37287. const bool shouldWordWrap)
  37288. {
  37289. multiline = shouldBeMultiLine;
  37290. wordWrap = shouldWordWrap && shouldBeMultiLine;
  37291. setScrollbarsShown (scrollbarVisible);
  37292. viewport->setViewPosition (0, 0);
  37293. resized();
  37294. scrollToMakeSureCursorIsVisible();
  37295. }
  37296. bool TextEditor::isMultiLine() const throw()
  37297. {
  37298. return multiline;
  37299. }
  37300. void TextEditor::setScrollbarsShown (bool enabled) throw()
  37301. {
  37302. scrollbarVisible = enabled;
  37303. enabled = enabled && isMultiLine();
  37304. viewport->setScrollBarsShown (enabled, enabled);
  37305. }
  37306. void TextEditor::setReadOnly (const bool shouldBeReadOnly)
  37307. {
  37308. readOnly = shouldBeReadOnly;
  37309. enablementChanged();
  37310. }
  37311. bool TextEditor::isReadOnly() const throw()
  37312. {
  37313. return readOnly || ! isEnabled();
  37314. }
  37315. void TextEditor::setReturnKeyStartsNewLine (const bool shouldStartNewLine)
  37316. {
  37317. returnKeyStartsNewLine = shouldStartNewLine;
  37318. }
  37319. void TextEditor::setTabKeyUsedAsCharacter (const bool shouldTabKeyBeUsed) throw()
  37320. {
  37321. tabKeyUsed = shouldTabKeyBeUsed;
  37322. }
  37323. void TextEditor::setPopupMenuEnabled (const bool b) throw()
  37324. {
  37325. popupMenuEnabled = b;
  37326. }
  37327. void TextEditor::setSelectAllWhenFocused (const bool b) throw()
  37328. {
  37329. selectAllTextWhenFocused = b;
  37330. }
  37331. const Font TextEditor::getFont() const throw()
  37332. {
  37333. return currentFont;
  37334. }
  37335. void TextEditor::setFont (const Font& newFont) throw()
  37336. {
  37337. currentFont = newFont;
  37338. scrollToMakeSureCursorIsVisible();
  37339. }
  37340. void TextEditor::applyFontToAllText (const Font& newFont)
  37341. {
  37342. currentFont = newFont;
  37343. const Colour overallColour (findColour (textColourId));
  37344. for (int i = sections.size(); --i >= 0;)
  37345. {
  37346. UniformTextSection* const uts = (UniformTextSection*) sections.getUnchecked(i);
  37347. uts->setFont (newFont, passwordCharacter);
  37348. uts->colour = overallColour;
  37349. }
  37350. coalesceSimilarSections();
  37351. updateTextHolderSize();
  37352. scrollToMakeSureCursorIsVisible();
  37353. repaint();
  37354. }
  37355. void TextEditor::colourChanged()
  37356. {
  37357. setOpaque (findColour (backgroundColourId).isOpaque());
  37358. repaint();
  37359. }
  37360. void TextEditor::setCaretVisible (const bool shouldCaretBeVisible) throw()
  37361. {
  37362. caretVisible = shouldCaretBeVisible;
  37363. if (shouldCaretBeVisible)
  37364. textHolder->startTimer (flashSpeedIntervalMs);
  37365. setMouseCursor (shouldCaretBeVisible ? MouseCursor::IBeamCursor
  37366. : MouseCursor::NormalCursor);
  37367. }
  37368. void TextEditor::setInputRestrictions (const int maxLen,
  37369. const String& chars) throw()
  37370. {
  37371. maxTextLength = jmax (0, maxLen);
  37372. allowedCharacters = chars;
  37373. }
  37374. void TextEditor::setTextToShowWhenEmpty (const String& text, const Colour& colourToUse) throw()
  37375. {
  37376. textToShowWhenEmpty = text;
  37377. colourForTextWhenEmpty = colourToUse;
  37378. }
  37379. void TextEditor::setPasswordCharacter (const tchar newPasswordCharacter) throw()
  37380. {
  37381. if (passwordCharacter != newPasswordCharacter)
  37382. {
  37383. passwordCharacter = newPasswordCharacter;
  37384. resized();
  37385. repaint();
  37386. }
  37387. }
  37388. void TextEditor::setScrollBarThickness (const int newThicknessPixels)
  37389. {
  37390. viewport->setScrollBarThickness (newThicknessPixels);
  37391. }
  37392. void TextEditor::setScrollBarButtonVisibility (const bool buttonsVisible)
  37393. {
  37394. viewport->setScrollBarButtonVisibility (buttonsVisible);
  37395. }
  37396. void TextEditor::clear()
  37397. {
  37398. clearInternal (0);
  37399. updateTextHolderSize();
  37400. undoManager.clearUndoHistory();
  37401. }
  37402. void TextEditor::setText (const String& newText,
  37403. const bool sendTextChangeMessage)
  37404. {
  37405. const int newLength = newText.length();
  37406. if (newLength != getTotalNumChars() || getText() != newText)
  37407. {
  37408. const int oldCursorPos = caretPosition;
  37409. const bool cursorWasAtEnd = oldCursorPos >= getTotalNumChars();
  37410. clearInternal (0);
  37411. insert (newText, 0, currentFont, findColour (textColourId), 0, caretPosition);
  37412. // if you're adding text with line-feeds to a single-line text editor, it
  37413. // ain't gonna look right!
  37414. jassert (multiline || ! newText.containsAnyOf (T("\r\n")));
  37415. if (cursorWasAtEnd && ! isMultiLine())
  37416. moveCursorTo (getTotalNumChars(), false);
  37417. else
  37418. moveCursorTo (oldCursorPos, false);
  37419. if (sendTextChangeMessage)
  37420. textChanged();
  37421. repaint();
  37422. }
  37423. updateTextHolderSize();
  37424. scrollToMakeSureCursorIsVisible();
  37425. undoManager.clearUndoHistory();
  37426. }
  37427. void TextEditor::textChanged() throw()
  37428. {
  37429. updateTextHolderSize();
  37430. postCommandMessage (textChangeMessageId);
  37431. }
  37432. void TextEditor::returnPressed()
  37433. {
  37434. postCommandMessage (returnKeyMessageId);
  37435. }
  37436. void TextEditor::escapePressed()
  37437. {
  37438. postCommandMessage (escapeKeyMessageId);
  37439. }
  37440. void TextEditor::addListener (TextEditorListener* const newListener) throw()
  37441. {
  37442. jassert (newListener != 0)
  37443. if (newListener != 0)
  37444. listeners.add (newListener);
  37445. }
  37446. void TextEditor::removeListener (TextEditorListener* const listenerToRemove) throw()
  37447. {
  37448. listeners.removeValue (listenerToRemove);
  37449. }
  37450. void TextEditor::timerCallbackInt()
  37451. {
  37452. const bool newState = (! caretFlashState) && ! isCurrentlyBlockedByAnotherModalComponent();
  37453. if (caretFlashState != newState)
  37454. {
  37455. caretFlashState = newState;
  37456. if (caretFlashState)
  37457. wasFocused = true;
  37458. if (caretVisible
  37459. && hasKeyboardFocus (false)
  37460. && ! isReadOnly())
  37461. {
  37462. repaintCaret();
  37463. }
  37464. }
  37465. const unsigned int now = Time::getApproximateMillisecondCounter();
  37466. if (now > lastTransactionTime + 200)
  37467. newTransaction();
  37468. }
  37469. void TextEditor::repaintCaret()
  37470. {
  37471. if (! findColour (caretColourId).isTransparent())
  37472. repaint (borderSize.getLeft() + textHolder->getX() + leftIndent + roundFloatToInt (cursorX) - 1,
  37473. borderSize.getTop() + textHolder->getY() + topIndent + roundFloatToInt (cursorY) - 1,
  37474. 4,
  37475. roundFloatToInt (cursorHeight) + 2);
  37476. }
  37477. void TextEditor::repaintText (int textStartIndex, int textEndIndex)
  37478. {
  37479. if (textStartIndex > textEndIndex && textEndIndex > 0)
  37480. swapVariables (textStartIndex, textEndIndex);
  37481. float x = 0, y = 0, lh = currentFont.getHeight();
  37482. const float wordWrapWidth = getWordWrapWidth();
  37483. if (wordWrapWidth > 0)
  37484. {
  37485. TextEditorIterator i (sections, wordWrapWidth, passwordCharacter);
  37486. i.getCharPosition (textStartIndex, x, y, lh);
  37487. const int y1 = (int) y;
  37488. int y2;
  37489. if (textEndIndex >= 0)
  37490. {
  37491. i.getCharPosition (textEndIndex, x, y, lh);
  37492. y2 = (int) (y + lh * 2.0f);
  37493. }
  37494. else
  37495. {
  37496. y2 = textHolder->getHeight();
  37497. }
  37498. textHolder->repaint (0, y1, textHolder->getWidth(), y2 - y1);
  37499. }
  37500. }
  37501. void TextEditor::moveCaret (int newCaretPos) throw()
  37502. {
  37503. if (newCaretPos < 0)
  37504. newCaretPos = 0;
  37505. else if (newCaretPos > getTotalNumChars())
  37506. newCaretPos = getTotalNumChars();
  37507. if (newCaretPos != getCaretPosition())
  37508. {
  37509. repaintCaret();
  37510. caretFlashState = true;
  37511. caretPosition = newCaretPos;
  37512. textHolder->startTimer (flashSpeedIntervalMs);
  37513. scrollToMakeSureCursorIsVisible();
  37514. repaintCaret();
  37515. }
  37516. }
  37517. void TextEditor::setCaretPosition (const int newIndex) throw()
  37518. {
  37519. moveCursorTo (newIndex, false);
  37520. }
  37521. int TextEditor::getCaretPosition() const throw()
  37522. {
  37523. return caretPosition;
  37524. }
  37525. float TextEditor::getWordWrapWidth() const throw()
  37526. {
  37527. return (wordWrap) ? (float) (viewport->getMaximumVisibleWidth() - leftIndent - leftIndent / 2)
  37528. : 1.0e10f;
  37529. }
  37530. void TextEditor::updateTextHolderSize() throw()
  37531. {
  37532. const float wordWrapWidth = getWordWrapWidth();
  37533. if (wordWrapWidth > 0)
  37534. {
  37535. float maxWidth = 0.0f;
  37536. TextEditorIterator i (sections, wordWrapWidth, passwordCharacter);
  37537. while (i.next())
  37538. maxWidth = jmax (maxWidth, i.atomRight);
  37539. const int w = leftIndent + roundFloatToInt (maxWidth);
  37540. const int h = topIndent + roundFloatToInt (jmax (i.lineY + i.lineHeight,
  37541. currentFont.getHeight()));
  37542. textHolder->setSize (w + 1, h + 1);
  37543. }
  37544. }
  37545. int TextEditor::getTextWidth() const throw()
  37546. {
  37547. return textHolder->getWidth();
  37548. }
  37549. int TextEditor::getTextHeight() const throw()
  37550. {
  37551. return textHolder->getHeight();
  37552. }
  37553. void TextEditor::setIndents (const int newLeftIndent,
  37554. const int newTopIndent) throw()
  37555. {
  37556. leftIndent = newLeftIndent;
  37557. topIndent = newTopIndent;
  37558. }
  37559. void TextEditor::setBorder (const BorderSize& border) throw()
  37560. {
  37561. borderSize = border;
  37562. resized();
  37563. }
  37564. const BorderSize TextEditor::getBorder() const throw()
  37565. {
  37566. return borderSize;
  37567. }
  37568. void TextEditor::setScrollToShowCursor (const bool shouldScrollToShowCursor) throw()
  37569. {
  37570. keepCursorOnScreen = shouldScrollToShowCursor;
  37571. }
  37572. void TextEditor::scrollToMakeSureCursorIsVisible() throw()
  37573. {
  37574. cursorHeight = currentFont.getHeight(); // (in case the text is empty and the call below doesn't set this value)
  37575. getCharPosition (caretPosition,
  37576. cursorX, cursorY,
  37577. cursorHeight);
  37578. if (keepCursorOnScreen)
  37579. {
  37580. int x = viewport->getViewPositionX();
  37581. int y = viewport->getViewPositionY();
  37582. const int relativeCursorX = roundFloatToInt (cursorX) - x;
  37583. const int relativeCursorY = roundFloatToInt (cursorY) - y;
  37584. if (relativeCursorX < jmax (1, proportionOfWidth (0.05f)))
  37585. {
  37586. x += relativeCursorX - proportionOfWidth (0.2f);
  37587. }
  37588. else if (relativeCursorX > jmax (0, viewport->getMaximumVisibleWidth() - (wordWrap ? 2 : 10)))
  37589. {
  37590. x += relativeCursorX + (isMultiLine() ? proportionOfWidth (0.2f) : 10) - viewport->getMaximumVisibleWidth();
  37591. }
  37592. x = jlimit (0, jmax (0, textHolder->getWidth() + 8 - viewport->getMaximumVisibleWidth()), x);
  37593. if (! isMultiLine())
  37594. {
  37595. y = (getHeight() - textHolder->getHeight() - topIndent) / -2;
  37596. }
  37597. else
  37598. {
  37599. const int curH = roundFloatToInt (cursorHeight);
  37600. if (relativeCursorY < 0)
  37601. {
  37602. y = jmax (0, relativeCursorY + y);
  37603. }
  37604. else if (relativeCursorY > jmax (0, viewport->getMaximumVisibleHeight() - topIndent - curH))
  37605. {
  37606. y += relativeCursorY + 2 + curH + topIndent - viewport->getMaximumVisibleHeight();
  37607. }
  37608. }
  37609. viewport->setViewPosition (x, y);
  37610. }
  37611. }
  37612. void TextEditor::moveCursorTo (const int newPosition,
  37613. const bool isSelecting) throw()
  37614. {
  37615. if (isSelecting)
  37616. {
  37617. moveCaret (newPosition);
  37618. const int oldSelStart = selectionStart;
  37619. const int oldSelEnd = selectionEnd;
  37620. if (dragType == notDragging)
  37621. {
  37622. if (abs (getCaretPosition() - selectionStart) < abs (getCaretPosition() - selectionEnd))
  37623. dragType = draggingSelectionStart;
  37624. else
  37625. dragType = draggingSelectionEnd;
  37626. }
  37627. if (dragType == draggingSelectionStart)
  37628. {
  37629. selectionStart = getCaretPosition();
  37630. if (selectionEnd < selectionStart)
  37631. {
  37632. swapVariables (selectionStart, selectionEnd);
  37633. dragType = draggingSelectionEnd;
  37634. }
  37635. }
  37636. else
  37637. {
  37638. selectionEnd = getCaretPosition();
  37639. if (selectionEnd < selectionStart)
  37640. {
  37641. swapVariables (selectionStart, selectionEnd);
  37642. dragType = draggingSelectionStart;
  37643. }
  37644. }
  37645. jassert (selectionStart <= selectionEnd);
  37646. jassert (oldSelStart <= oldSelEnd);
  37647. repaintText (jmin (oldSelStart, selectionStart),
  37648. jmax (oldSelEnd, selectionEnd));
  37649. }
  37650. else
  37651. {
  37652. dragType = notDragging;
  37653. if (selectionEnd > selectionStart)
  37654. repaintText (selectionStart, selectionEnd);
  37655. moveCaret (newPosition);
  37656. selectionStart = getCaretPosition();
  37657. selectionEnd = getCaretPosition();
  37658. }
  37659. }
  37660. int TextEditor::getTextIndexAt (const int x,
  37661. const int y) throw()
  37662. {
  37663. return indexAtPosition ((float) (x + viewport->getViewPositionX() - leftIndent),
  37664. (float) (y + viewport->getViewPositionY() - topIndent));
  37665. }
  37666. void TextEditor::insertTextAtCursor (String newText)
  37667. {
  37668. if (allowedCharacters.isNotEmpty())
  37669. newText = newText.retainCharacters (allowedCharacters);
  37670. if (! isMultiLine())
  37671. newText = newText.replaceCharacters (T("\r\n"), T(" "));
  37672. else
  37673. newText = newText.replace (T("\r\n"), T("\n"));
  37674. const int newCaretPos = selectionStart + newText.length();
  37675. const int insertIndex = selectionStart;
  37676. remove (selectionStart, selectionEnd,
  37677. &undoManager,
  37678. newCaretPos);
  37679. if (maxTextLength > 0)
  37680. newText = newText.substring (0, maxTextLength - getTotalNumChars());
  37681. if (newText.isNotEmpty())
  37682. insert (newText,
  37683. insertIndex,
  37684. currentFont,
  37685. findColour (textColourId),
  37686. &undoManager,
  37687. newCaretPos);
  37688. textChanged();
  37689. }
  37690. void TextEditor::setHighlightedRegion (int startPos, int numChars) throw()
  37691. {
  37692. moveCursorTo (startPos, false);
  37693. moveCursorTo (startPos + numChars, true);
  37694. }
  37695. void TextEditor::copy()
  37696. {
  37697. const String selection (getTextSubstring (selectionStart, selectionEnd));
  37698. if (selection.isNotEmpty())
  37699. SystemClipboard::copyTextToClipboard (selection);
  37700. }
  37701. void TextEditor::paste()
  37702. {
  37703. if (! isReadOnly())
  37704. {
  37705. const String clip (SystemClipboard::getTextFromClipboard());
  37706. if (clip.isNotEmpty())
  37707. insertTextAtCursor (clip);
  37708. }
  37709. }
  37710. void TextEditor::cut()
  37711. {
  37712. if (! isReadOnly())
  37713. {
  37714. moveCaret (selectionEnd);
  37715. insertTextAtCursor (String::empty);
  37716. }
  37717. }
  37718. void TextEditor::drawContent (Graphics& g)
  37719. {
  37720. const float wordWrapWidth = getWordWrapWidth();
  37721. if (wordWrapWidth > 0)
  37722. {
  37723. g.setOrigin (leftIndent, topIndent);
  37724. const Rectangle clip (g.getClipBounds());
  37725. Colour selectedTextColour;
  37726. TextEditorIterator i (sections, wordWrapWidth, passwordCharacter);
  37727. while (i.lineY + 200.0 < clip.getY() && i.next())
  37728. {}
  37729. if (selectionStart < selectionEnd)
  37730. {
  37731. g.setColour (findColour (highlightColourId)
  37732. .withMultipliedAlpha (hasKeyboardFocus (true) ? 1.0f : 0.5f));
  37733. selectedTextColour = findColour (highlightedTextColourId);
  37734. TextEditorIterator i2 (i);
  37735. while (i2.next() && i2.lineY < clip.getBottom())
  37736. {
  37737. i2.updateLineHeight();
  37738. if (i2.lineY + i2.lineHeight >= clip.getY()
  37739. && selectionEnd >= i2.indexInText
  37740. && selectionStart <= i2.indexInText + i2.atom->numChars)
  37741. {
  37742. i2.drawSelection (g, selectionStart, selectionEnd);
  37743. }
  37744. }
  37745. }
  37746. const UniformTextSection* lastSection = 0;
  37747. while (i.next() && i.lineY < clip.getBottom())
  37748. {
  37749. i.updateLineHeight();
  37750. if (i.lineY + i.lineHeight >= clip.getY())
  37751. {
  37752. if (selectionEnd >= i.indexInText
  37753. && selectionStart <= i.indexInText + i.atom->numChars)
  37754. {
  37755. i.drawSelectedText (g, selectionStart, selectionEnd, selectedTextColour);
  37756. lastSection = 0;
  37757. }
  37758. else
  37759. {
  37760. i.draw (g, lastSection);
  37761. }
  37762. }
  37763. }
  37764. }
  37765. }
  37766. void TextEditor::paint (Graphics& g)
  37767. {
  37768. getLookAndFeel().fillTextEditorBackground (g, getWidth(), getHeight(), *this);
  37769. }
  37770. void TextEditor::paintOverChildren (Graphics& g)
  37771. {
  37772. if (caretFlashState
  37773. && hasKeyboardFocus (false)
  37774. && caretVisible
  37775. && ! isReadOnly())
  37776. {
  37777. g.setColour (findColour (caretColourId));
  37778. g.fillRect (borderSize.getLeft() + textHolder->getX() + leftIndent + cursorX,
  37779. borderSize.getTop() + textHolder->getY() + topIndent + cursorY,
  37780. 2.0f, cursorHeight);
  37781. }
  37782. if (textToShowWhenEmpty.isNotEmpty()
  37783. && (! hasKeyboardFocus (false))
  37784. && getTotalNumChars() == 0)
  37785. {
  37786. g.setColour (colourForTextWhenEmpty);
  37787. g.setFont (getFont());
  37788. if (isMultiLine())
  37789. {
  37790. g.drawText (textToShowWhenEmpty,
  37791. 0, 0, getWidth(), getHeight(),
  37792. Justification::centred, true);
  37793. }
  37794. else
  37795. {
  37796. g.drawText (textToShowWhenEmpty,
  37797. leftIndent, topIndent,
  37798. viewport->getWidth() - leftIndent,
  37799. viewport->getHeight() - topIndent,
  37800. Justification::centredLeft, true);
  37801. }
  37802. }
  37803. getLookAndFeel().drawTextEditorOutline (g, getWidth(), getHeight(), *this);
  37804. }
  37805. void TextEditor::mouseDown (const MouseEvent& e)
  37806. {
  37807. beginDragAutoRepeat (100);
  37808. newTransaction();
  37809. if (wasFocused || ! selectAllTextWhenFocused)
  37810. {
  37811. if (! (popupMenuEnabled && e.mods.isPopupMenu()))
  37812. {
  37813. moveCursorTo (getTextIndexAt (e.x, e.y),
  37814. e.mods.isShiftDown());
  37815. }
  37816. else
  37817. {
  37818. PopupMenu m;
  37819. addPopupMenuItems (m, &e);
  37820. menuActive = true;
  37821. const int result = m.show();
  37822. menuActive = false;
  37823. if (result != 0)
  37824. performPopupMenuAction (result);
  37825. }
  37826. }
  37827. }
  37828. void TextEditor::mouseDrag (const MouseEvent& e)
  37829. {
  37830. if (wasFocused || ! selectAllTextWhenFocused)
  37831. {
  37832. if (! (popupMenuEnabled && e.mods.isPopupMenu()))
  37833. {
  37834. moveCursorTo (getTextIndexAt (e.x, e.y), true);
  37835. }
  37836. }
  37837. }
  37838. void TextEditor::mouseUp (const MouseEvent& e)
  37839. {
  37840. newTransaction();
  37841. textHolder->startTimer (flashSpeedIntervalMs);
  37842. if (wasFocused || ! selectAllTextWhenFocused)
  37843. {
  37844. if (! (popupMenuEnabled && e.mods.isPopupMenu()))
  37845. {
  37846. moveCaret (getTextIndexAt (e.x, e.y));
  37847. }
  37848. }
  37849. wasFocused = true;
  37850. }
  37851. void TextEditor::mouseDoubleClick (const MouseEvent& e)
  37852. {
  37853. int tokenEnd = getTextIndexAt (e.x, e.y);
  37854. int tokenStart = tokenEnd;
  37855. if (e.getNumberOfClicks() > 3)
  37856. {
  37857. tokenStart = 0;
  37858. tokenEnd = getTotalNumChars();
  37859. }
  37860. else
  37861. {
  37862. const String t (getText());
  37863. const int totalLength = getTotalNumChars();
  37864. while (tokenEnd < totalLength)
  37865. {
  37866. if (CharacterFunctions::isLetterOrDigit (t [tokenEnd]))
  37867. ++tokenEnd;
  37868. else
  37869. break;
  37870. }
  37871. tokenStart = tokenEnd;
  37872. while (tokenStart > 0)
  37873. {
  37874. if (CharacterFunctions::isLetterOrDigit (t [tokenStart - 1]))
  37875. --tokenStart;
  37876. else
  37877. break;
  37878. }
  37879. if (e.getNumberOfClicks() > 2)
  37880. {
  37881. while (tokenEnd < totalLength)
  37882. {
  37883. if (t [tokenEnd] != T('\r') && t [tokenEnd] != T('\n'))
  37884. ++tokenEnd;
  37885. else
  37886. break;
  37887. }
  37888. while (tokenStart > 0)
  37889. {
  37890. if (t [tokenStart - 1] != T('\r') && t [tokenStart - 1] != T('\n'))
  37891. --tokenStart;
  37892. else
  37893. break;
  37894. }
  37895. }
  37896. }
  37897. moveCursorTo (tokenEnd, false);
  37898. moveCursorTo (tokenStart, true);
  37899. }
  37900. void TextEditor::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  37901. {
  37902. if (! viewport->useMouseWheelMoveIfNeeded (e, wheelIncrementX, wheelIncrementY))
  37903. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  37904. }
  37905. bool TextEditor::keyPressed (const KeyPress& key)
  37906. {
  37907. if (isReadOnly() && key != KeyPress (T('c'), ModifierKeys::commandModifier, 0))
  37908. return false;
  37909. const bool moveInWholeWordSteps = key.getModifiers().isCtrlDown() || key.getModifiers().isAltDown();
  37910. if (key.isKeyCode (KeyPress::leftKey)
  37911. || key.isKeyCode (KeyPress::upKey))
  37912. {
  37913. newTransaction();
  37914. int newPos;
  37915. if (isMultiLine() && key.isKeyCode (KeyPress::upKey))
  37916. newPos = indexAtPosition (cursorX, cursorY - 1);
  37917. else if (moveInWholeWordSteps)
  37918. newPos = findWordBreakBefore (getCaretPosition());
  37919. else
  37920. newPos = getCaretPosition() - 1;
  37921. moveCursorTo (newPos, key.getModifiers().isShiftDown());
  37922. }
  37923. else if (key.isKeyCode (KeyPress::rightKey)
  37924. || key.isKeyCode (KeyPress::downKey))
  37925. {
  37926. newTransaction();
  37927. int newPos;
  37928. if (isMultiLine() && key.isKeyCode (KeyPress::downKey))
  37929. newPos = indexAtPosition (cursorX, cursorY + cursorHeight + 1);
  37930. else if (moveInWholeWordSteps)
  37931. newPos = findWordBreakAfter (getCaretPosition());
  37932. else
  37933. newPos = getCaretPosition() + 1;
  37934. moveCursorTo (newPos, key.getModifiers().isShiftDown());
  37935. }
  37936. else if (key.isKeyCode (KeyPress::pageDownKey) && isMultiLine())
  37937. {
  37938. newTransaction();
  37939. moveCursorTo (indexAtPosition (cursorX, cursorY + cursorHeight + viewport->getViewHeight()),
  37940. key.getModifiers().isShiftDown());
  37941. }
  37942. else if (key.isKeyCode (KeyPress::pageUpKey) && isMultiLine())
  37943. {
  37944. newTransaction();
  37945. moveCursorTo (indexAtPosition (cursorX, cursorY - viewport->getViewHeight()),
  37946. key.getModifiers().isShiftDown());
  37947. }
  37948. else if (key.isKeyCode (KeyPress::homeKey))
  37949. {
  37950. newTransaction();
  37951. if (isMultiLine() && ! moveInWholeWordSteps)
  37952. moveCursorTo (indexAtPosition (0.0f, cursorY),
  37953. key.getModifiers().isShiftDown());
  37954. else
  37955. moveCursorTo (0, key.getModifiers().isShiftDown());
  37956. }
  37957. else if (key.isKeyCode (KeyPress::endKey))
  37958. {
  37959. newTransaction();
  37960. if (isMultiLine() && ! moveInWholeWordSteps)
  37961. moveCursorTo (indexAtPosition ((float) textHolder->getWidth(), cursorY),
  37962. key.getModifiers().isShiftDown());
  37963. else
  37964. moveCursorTo (getTotalNumChars(), key.getModifiers().isShiftDown());
  37965. }
  37966. else if (key.isKeyCode (KeyPress::backspaceKey))
  37967. {
  37968. if (moveInWholeWordSteps)
  37969. {
  37970. moveCursorTo (findWordBreakBefore (getCaretPosition()), true);
  37971. }
  37972. else
  37973. {
  37974. if (selectionStart == selectionEnd && selectionStart > 0)
  37975. --selectionStart;
  37976. }
  37977. cut();
  37978. }
  37979. else if (key.isKeyCode (KeyPress::deleteKey))
  37980. {
  37981. if (key.getModifiers().isShiftDown())
  37982. copy();
  37983. if (selectionStart == selectionEnd
  37984. && selectionEnd < getTotalNumChars())
  37985. {
  37986. ++selectionEnd;
  37987. }
  37988. cut();
  37989. }
  37990. else if (key == KeyPress (T('c'), ModifierKeys::commandModifier, 0)
  37991. || key == KeyPress (KeyPress::insertKey, ModifierKeys::ctrlModifier, 0))
  37992. {
  37993. newTransaction();
  37994. copy();
  37995. }
  37996. else if (key == KeyPress (T('x'), ModifierKeys::commandModifier, 0))
  37997. {
  37998. newTransaction();
  37999. copy();
  38000. cut();
  38001. }
  38002. else if (key == KeyPress (T('v'), ModifierKeys::commandModifier, 0)
  38003. || key == KeyPress (KeyPress::insertKey, ModifierKeys::shiftModifier, 0))
  38004. {
  38005. newTransaction();
  38006. paste();
  38007. }
  38008. else if (key == KeyPress (T('z'), ModifierKeys::commandModifier, 0))
  38009. {
  38010. newTransaction();
  38011. doUndoRedo (false);
  38012. }
  38013. else if (key == KeyPress (T('y'), ModifierKeys::commandModifier, 0))
  38014. {
  38015. newTransaction();
  38016. doUndoRedo (true);
  38017. }
  38018. else if (key == KeyPress (T('a'), ModifierKeys::commandModifier, 0))
  38019. {
  38020. newTransaction();
  38021. moveCursorTo (getTotalNumChars(), false);
  38022. moveCursorTo (0, true);
  38023. }
  38024. else if (key == KeyPress::returnKey)
  38025. {
  38026. newTransaction();
  38027. if (returnKeyStartsNewLine)
  38028. insertTextAtCursor (T("\n"));
  38029. else
  38030. returnPressed();
  38031. }
  38032. else if (key.isKeyCode (KeyPress::escapeKey))
  38033. {
  38034. newTransaction();
  38035. moveCursorTo (getCaretPosition(), false);
  38036. escapePressed();
  38037. }
  38038. else if (key.getTextCharacter() >= ' '
  38039. || (tabKeyUsed && (key.getTextCharacter() == '\t')))
  38040. {
  38041. insertTextAtCursor (String::charToString (key.getTextCharacter()));
  38042. lastTransactionTime = Time::getApproximateMillisecondCounter();
  38043. }
  38044. else
  38045. {
  38046. return false;
  38047. }
  38048. return true;
  38049. }
  38050. bool TextEditor::keyStateChanged()
  38051. {
  38052. // (overridden to avoid forwarding key events to the parent)
  38053. return true;
  38054. }
  38055. const int baseMenuItemID = 0x7fff0000;
  38056. void TextEditor::addPopupMenuItems (PopupMenu& m, const MouseEvent*)
  38057. {
  38058. const bool writable = ! isReadOnly();
  38059. m.addItem (baseMenuItemID + 1, TRANS("cut"), writable);
  38060. m.addItem (baseMenuItemID + 2, TRANS("copy"), selectionStart < selectionEnd);
  38061. m.addItem (baseMenuItemID + 3, TRANS("paste"), writable);
  38062. m.addItem (baseMenuItemID + 4, TRANS("delete"), writable);
  38063. m.addSeparator();
  38064. m.addItem (baseMenuItemID + 5, TRANS("select all"));
  38065. m.addSeparator();
  38066. m.addItem (baseMenuItemID + 6, TRANS("undo"), undoManager.canUndo());
  38067. m.addItem (baseMenuItemID + 7, TRANS("redo"), undoManager.canRedo());
  38068. }
  38069. void TextEditor::performPopupMenuAction (const int menuItemID)
  38070. {
  38071. switch (menuItemID)
  38072. {
  38073. case baseMenuItemID + 1:
  38074. copy();
  38075. cut();
  38076. break;
  38077. case baseMenuItemID + 2:
  38078. copy();
  38079. break;
  38080. case baseMenuItemID + 3:
  38081. paste();
  38082. break;
  38083. case baseMenuItemID + 4:
  38084. cut();
  38085. break;
  38086. case baseMenuItemID + 5:
  38087. moveCursorTo (getTotalNumChars(), false);
  38088. moveCursorTo (0, true);
  38089. break;
  38090. case baseMenuItemID + 6:
  38091. doUndoRedo (false);
  38092. break;
  38093. case baseMenuItemID + 7:
  38094. doUndoRedo (true);
  38095. break;
  38096. default:
  38097. break;
  38098. }
  38099. }
  38100. void TextEditor::focusGained (FocusChangeType)
  38101. {
  38102. newTransaction();
  38103. caretFlashState = true;
  38104. if (selectAllTextWhenFocused)
  38105. {
  38106. moveCursorTo (0, false);
  38107. moveCursorTo (getTotalNumChars(), true);
  38108. }
  38109. repaint();
  38110. if (caretVisible)
  38111. textHolder->startTimer (flashSpeedIntervalMs);
  38112. }
  38113. void TextEditor::focusLost (FocusChangeType)
  38114. {
  38115. newTransaction();
  38116. wasFocused = false;
  38117. textHolder->stopTimer();
  38118. caretFlashState = false;
  38119. postCommandMessage (focusLossMessageId);
  38120. repaint();
  38121. }
  38122. void TextEditor::resized()
  38123. {
  38124. viewport->setBoundsInset (borderSize);
  38125. viewport->setSingleStepSizes (16, roundFloatToInt (currentFont.getHeight()));
  38126. updateTextHolderSize();
  38127. if (! isMultiLine())
  38128. {
  38129. scrollToMakeSureCursorIsVisible();
  38130. }
  38131. else
  38132. {
  38133. cursorHeight = currentFont.getHeight(); // (in case the text is empty and the call below doesn't set this value)
  38134. getCharPosition (caretPosition,
  38135. cursorX, cursorY,
  38136. cursorHeight);
  38137. }
  38138. }
  38139. void TextEditor::handleCommandMessage (const int commandId)
  38140. {
  38141. const ComponentDeletionWatcher deletionChecker (this);
  38142. for (int i = listeners.size(); --i >= 0;)
  38143. {
  38144. TextEditorListener* const tl = (TextEditorListener*) listeners [i];
  38145. if (tl != 0)
  38146. {
  38147. switch (commandId)
  38148. {
  38149. case textChangeMessageId:
  38150. tl->textEditorTextChanged (*this);
  38151. break;
  38152. case returnKeyMessageId:
  38153. tl->textEditorReturnKeyPressed (*this);
  38154. break;
  38155. case escapeKeyMessageId:
  38156. tl->textEditorEscapeKeyPressed (*this);
  38157. break;
  38158. case focusLossMessageId:
  38159. tl->textEditorFocusLost (*this);
  38160. break;
  38161. default:
  38162. jassertfalse
  38163. break;
  38164. }
  38165. if (i > 0 && deletionChecker.hasBeenDeleted())
  38166. return;
  38167. }
  38168. }
  38169. }
  38170. void TextEditor::enablementChanged()
  38171. {
  38172. setMouseCursor (MouseCursor (isReadOnly() ? MouseCursor::NormalCursor
  38173. : MouseCursor::IBeamCursor));
  38174. repaint();
  38175. }
  38176. void TextEditor::clearInternal (UndoManager* const um) throw()
  38177. {
  38178. remove (0, getTotalNumChars(), um, caretPosition);
  38179. }
  38180. void TextEditor::insert (const String& text,
  38181. const int insertIndex,
  38182. const Font& font,
  38183. const Colour& colour,
  38184. UndoManager* const um,
  38185. const int caretPositionToMoveTo) throw()
  38186. {
  38187. if (text.isNotEmpty())
  38188. {
  38189. if (um != 0)
  38190. {
  38191. um->perform (new TextEditorInsertAction (*this,
  38192. text,
  38193. insertIndex,
  38194. font,
  38195. colour,
  38196. caretPosition,
  38197. caretPositionToMoveTo));
  38198. }
  38199. else
  38200. {
  38201. repaintText (insertIndex, -1); // must do this before and after changing the data, in case
  38202. // a line gets moved due to word wrap
  38203. int index = 0;
  38204. int nextIndex = 0;
  38205. for (int i = 0; i < sections.size(); ++i)
  38206. {
  38207. nextIndex = index + ((UniformTextSection*) sections.getUnchecked(i))->getTotalLength();
  38208. if (insertIndex == index)
  38209. {
  38210. sections.insert (i, new UniformTextSection (text,
  38211. font, colour,
  38212. passwordCharacter));
  38213. break;
  38214. }
  38215. else if (insertIndex > index && insertIndex < nextIndex)
  38216. {
  38217. splitSection (i, insertIndex - index);
  38218. sections.insert (i + 1, new UniformTextSection (text,
  38219. font, colour,
  38220. passwordCharacter));
  38221. break;
  38222. }
  38223. index = nextIndex;
  38224. }
  38225. if (nextIndex == insertIndex)
  38226. sections.add (new UniformTextSection (text,
  38227. font, colour,
  38228. passwordCharacter));
  38229. coalesceSimilarSections();
  38230. totalNumChars = -1;
  38231. moveCursorTo (caretPositionToMoveTo, false);
  38232. repaintText (insertIndex, -1);
  38233. }
  38234. }
  38235. }
  38236. void TextEditor::reinsert (const int insertIndex,
  38237. const VoidArray& sectionsToInsert) throw()
  38238. {
  38239. int index = 0;
  38240. int nextIndex = 0;
  38241. for (int i = 0; i < sections.size(); ++i)
  38242. {
  38243. nextIndex = index + ((UniformTextSection*) sections.getUnchecked(i))->getTotalLength();
  38244. if (insertIndex == index)
  38245. {
  38246. for (int j = sectionsToInsert.size(); --j >= 0;)
  38247. sections.insert (i, new UniformTextSection (*(UniformTextSection*) sectionsToInsert.getUnchecked(j)));
  38248. break;
  38249. }
  38250. else if (insertIndex > index && insertIndex < nextIndex)
  38251. {
  38252. splitSection (i, insertIndex - index);
  38253. for (int j = sectionsToInsert.size(); --j >= 0;)
  38254. sections.insert (i + 1, new UniformTextSection (*(UniformTextSection*) sectionsToInsert.getUnchecked(j)));
  38255. break;
  38256. }
  38257. index = nextIndex;
  38258. }
  38259. if (nextIndex == insertIndex)
  38260. {
  38261. for (int j = 0; j < sectionsToInsert.size(); ++j)
  38262. sections.add (new UniformTextSection (*(UniformTextSection*) sectionsToInsert.getUnchecked(j)));
  38263. }
  38264. coalesceSimilarSections();
  38265. totalNumChars = -1;
  38266. }
  38267. void TextEditor::remove (const int startIndex,
  38268. int endIndex,
  38269. UndoManager* const um,
  38270. const int caretPositionToMoveTo) throw()
  38271. {
  38272. if (endIndex > startIndex)
  38273. {
  38274. int index = 0;
  38275. for (int i = 0; i < sections.size(); ++i)
  38276. {
  38277. const int nextIndex = index + ((UniformTextSection*) sections[i])->getTotalLength();
  38278. if (startIndex > index && startIndex < nextIndex)
  38279. {
  38280. splitSection (i, startIndex - index);
  38281. --i;
  38282. }
  38283. else if (endIndex > index && endIndex < nextIndex)
  38284. {
  38285. splitSection (i, endIndex - index);
  38286. --i;
  38287. }
  38288. else
  38289. {
  38290. index = nextIndex;
  38291. if (index > endIndex)
  38292. break;
  38293. }
  38294. }
  38295. index = 0;
  38296. if (um != 0)
  38297. {
  38298. VoidArray removedSections;
  38299. for (int i = 0; i < sections.size(); ++i)
  38300. {
  38301. if (endIndex <= startIndex)
  38302. break;
  38303. UniformTextSection* const section = (UniformTextSection*) sections.getUnchecked (i);
  38304. const int nextIndex = index + section->getTotalLength();
  38305. if (startIndex <= index && endIndex >= nextIndex)
  38306. removedSections.add (new UniformTextSection (*section));
  38307. index = nextIndex;
  38308. }
  38309. um->perform (new TextEditorRemoveAction (*this,
  38310. startIndex,
  38311. endIndex,
  38312. caretPosition,
  38313. caretPositionToMoveTo,
  38314. removedSections));
  38315. }
  38316. else
  38317. {
  38318. for (int i = 0; i < sections.size(); ++i)
  38319. {
  38320. if (endIndex <= startIndex)
  38321. break;
  38322. UniformTextSection* const section = (UniformTextSection*) sections.getUnchecked (i);
  38323. const int nextIndex = index + section->getTotalLength();
  38324. if (startIndex <= index && endIndex >= nextIndex)
  38325. {
  38326. sections.remove(i);
  38327. endIndex -= (nextIndex - index);
  38328. section->clear();
  38329. delete section;
  38330. --i;
  38331. }
  38332. else
  38333. {
  38334. index = nextIndex;
  38335. }
  38336. }
  38337. coalesceSimilarSections();
  38338. totalNumChars = -1;
  38339. moveCursorTo (caretPositionToMoveTo, false);
  38340. repaintText (startIndex, -1);
  38341. }
  38342. }
  38343. }
  38344. const String TextEditor::getText() const throw()
  38345. {
  38346. String t;
  38347. for (int i = 0; i < sections.size(); ++i)
  38348. t += ((const UniformTextSection*) sections.getUnchecked(i))->getAllText();
  38349. return t;
  38350. }
  38351. const String TextEditor::getTextSubstring (const int startCharacter, const int endCharacter) const throw()
  38352. {
  38353. String t;
  38354. int index = 0;
  38355. for (int i = 0; i < sections.size(); ++i)
  38356. {
  38357. const UniformTextSection* const s = (const UniformTextSection*) sections.getUnchecked(i);
  38358. const int nextIndex = index + s->getTotalLength();
  38359. if (startCharacter < nextIndex)
  38360. {
  38361. if (endCharacter <= index)
  38362. break;
  38363. const int start = jmax (index, startCharacter);
  38364. t += s->getTextSubstring (start - index, endCharacter - index);
  38365. }
  38366. index = nextIndex;
  38367. }
  38368. return t;
  38369. }
  38370. const String TextEditor::getHighlightedText() const throw()
  38371. {
  38372. return getTextSubstring (getHighlightedRegionStart(),
  38373. getHighlightedRegionStart() + getHighlightedRegionLength());
  38374. }
  38375. int TextEditor::getTotalNumChars() throw()
  38376. {
  38377. if (totalNumChars < 0)
  38378. {
  38379. totalNumChars = 0;
  38380. for (int i = sections.size(); --i >= 0;)
  38381. totalNumChars += ((const UniformTextSection*) sections.getUnchecked(i))->getTotalLength();
  38382. }
  38383. return totalNumChars;
  38384. }
  38385. bool TextEditor::isEmpty() const throw()
  38386. {
  38387. if (totalNumChars != 0)
  38388. {
  38389. for (int i = sections.size(); --i >= 0;)
  38390. if (((const UniformTextSection*) sections.getUnchecked(i))->getTotalLength() > 0)
  38391. return false;
  38392. }
  38393. return true;
  38394. }
  38395. void TextEditor::getCharPosition (const int index, float& cx, float& cy, float& lineHeight) const throw()
  38396. {
  38397. const float wordWrapWidth = getWordWrapWidth();
  38398. if (wordWrapWidth > 0 && sections.size() > 0)
  38399. {
  38400. TextEditorIterator i (sections, wordWrapWidth, passwordCharacter);
  38401. i.getCharPosition (index, cx, cy, lineHeight);
  38402. }
  38403. else
  38404. {
  38405. cx = cy = 0;
  38406. lineHeight = currentFont.getHeight();
  38407. }
  38408. }
  38409. int TextEditor::indexAtPosition (const float x, const float y) throw()
  38410. {
  38411. const float wordWrapWidth = getWordWrapWidth();
  38412. if (wordWrapWidth > 0)
  38413. {
  38414. TextEditorIterator i (sections, wordWrapWidth, passwordCharacter);
  38415. while (i.next())
  38416. {
  38417. if (i.lineY + getHeight() > y)
  38418. i.updateLineHeight();
  38419. if (i.lineY + i.lineHeight > y)
  38420. {
  38421. if (i.lineY > y)
  38422. return jmax (0, i.indexInText - 1);
  38423. if (i.atomX >= x)
  38424. return i.indexInText;
  38425. if (x < i.atomRight)
  38426. return i.xToIndex (x);
  38427. }
  38428. }
  38429. }
  38430. return getTotalNumChars();
  38431. }
  38432. static int getCharacterCategory (const tchar character) throw()
  38433. {
  38434. return CharacterFunctions::isLetterOrDigit (character)
  38435. ? 2 : (CharacterFunctions::isWhitespace (character) ? 0 : 1);
  38436. }
  38437. int TextEditor::findWordBreakAfter (const int position) const throw()
  38438. {
  38439. const String t (getTextSubstring (position, position + 512));
  38440. const int totalLength = t.length();
  38441. int i = 0;
  38442. while (i < totalLength && CharacterFunctions::isWhitespace (t[i]))
  38443. ++i;
  38444. const int type = getCharacterCategory (t[i]);
  38445. while (i < totalLength && type == getCharacterCategory (t[i]))
  38446. ++i;
  38447. while (i < totalLength && CharacterFunctions::isWhitespace (t[i]))
  38448. ++i;
  38449. return position + i;
  38450. }
  38451. int TextEditor::findWordBreakBefore (const int position) const throw()
  38452. {
  38453. if (position <= 0)
  38454. return 0;
  38455. const int startOfBuffer = jmax (0, position - 512);
  38456. const String t (getTextSubstring (startOfBuffer, position));
  38457. int i = position - startOfBuffer;
  38458. while (i > 0 && CharacterFunctions::isWhitespace (t [i - 1]))
  38459. --i;
  38460. if (i > 0)
  38461. {
  38462. const int type = getCharacterCategory (t [i - 1]);
  38463. while (i > 0 && type == getCharacterCategory (t [i - 1]))
  38464. --i;
  38465. }
  38466. jassert (startOfBuffer + i >= 0);
  38467. return startOfBuffer + i;
  38468. }
  38469. void TextEditor::splitSection (const int sectionIndex,
  38470. const int charToSplitAt) throw()
  38471. {
  38472. jassert (sections[sectionIndex] != 0);
  38473. sections.insert (sectionIndex + 1,
  38474. ((UniformTextSection*) sections.getUnchecked (sectionIndex))
  38475. ->split (charToSplitAt, passwordCharacter));
  38476. }
  38477. void TextEditor::coalesceSimilarSections() throw()
  38478. {
  38479. for (int i = 0; i < sections.size() - 1; ++i)
  38480. {
  38481. UniformTextSection* const s1 = (UniformTextSection*) (sections.getUnchecked (i));
  38482. UniformTextSection* const s2 = (UniformTextSection*) (sections.getUnchecked (i + 1));
  38483. if (s1->font == s2->font
  38484. && s1->colour == s2->colour)
  38485. {
  38486. s1->append (*s2, passwordCharacter);
  38487. sections.remove (i + 1);
  38488. delete s2;
  38489. --i;
  38490. }
  38491. }
  38492. }
  38493. END_JUCE_NAMESPACE
  38494. /********* End of inlined file: juce_TextEditor.cpp *********/
  38495. /********* Start of inlined file: juce_Toolbar.cpp *********/
  38496. BEGIN_JUCE_NAMESPACE
  38497. const tchar* const Toolbar::toolbarDragDescriptor = T("_toolbarItem_");
  38498. class ToolbarSpacerComp : public ToolbarItemComponent
  38499. {
  38500. public:
  38501. ToolbarSpacerComp (const int itemId, const float fixedSize_, const bool drawBar_)
  38502. : ToolbarItemComponent (itemId, String::empty, false),
  38503. fixedSize (fixedSize_),
  38504. drawBar (drawBar_)
  38505. {
  38506. }
  38507. ~ToolbarSpacerComp()
  38508. {
  38509. }
  38510. bool getToolbarItemSizes (int toolbarThickness, bool /*isToolbarVertical*/,
  38511. int& preferredSize, int& minSize, int& maxSize)
  38512. {
  38513. if (fixedSize <= 0)
  38514. {
  38515. preferredSize = toolbarThickness * 2;
  38516. minSize = 4;
  38517. maxSize = 32768;
  38518. }
  38519. else
  38520. {
  38521. maxSize = roundFloatToInt (toolbarThickness * fixedSize);
  38522. minSize = drawBar ? maxSize : jmin (4, maxSize);
  38523. preferredSize = maxSize;
  38524. if (getEditingMode() == editableOnPalette)
  38525. preferredSize = maxSize = toolbarThickness / (drawBar ? 3 : 2);
  38526. }
  38527. return true;
  38528. }
  38529. void paintButtonArea (Graphics&, int, int, bool, bool)
  38530. {
  38531. }
  38532. void contentAreaChanged (const Rectangle&)
  38533. {
  38534. }
  38535. int getResizeOrder() const throw()
  38536. {
  38537. return fixedSize <= 0 ? 0 : 1;
  38538. }
  38539. void paint (Graphics& g)
  38540. {
  38541. const int w = getWidth();
  38542. const int h = getHeight();
  38543. if (drawBar)
  38544. {
  38545. g.setColour (findColour (Toolbar::separatorColourId, true));
  38546. const float thickness = 0.2f;
  38547. if (isToolbarVertical())
  38548. g.fillRect (w * 0.1f, h * (0.5f - thickness * 0.5f), w * 0.8f, h * thickness);
  38549. else
  38550. g.fillRect (w * (0.5f - thickness * 0.5f), h * 0.1f, w * thickness, h * 0.8f);
  38551. }
  38552. if (getEditingMode() != normalMode && ! drawBar)
  38553. {
  38554. g.setColour (findColour (Toolbar::separatorColourId, true));
  38555. const int indentX = jmin (2, (w - 3) / 2);
  38556. const int indentY = jmin (2, (h - 3) / 2);
  38557. g.drawRect (indentX, indentY, w - indentX * 2, h - indentY * 2, 1);
  38558. if (fixedSize <= 0)
  38559. {
  38560. float x1, y1, x2, y2, x3, y3, x4, y4, hw, hl;
  38561. if (isToolbarVertical())
  38562. {
  38563. x1 = w * 0.5f;
  38564. y1 = h * 0.4f;
  38565. x2 = x1;
  38566. y2 = indentX * 2.0f;
  38567. x3 = x1;
  38568. y3 = h * 0.6f;
  38569. x4 = x1;
  38570. y4 = h - y2;
  38571. hw = w * 0.15f;
  38572. hl = w * 0.2f;
  38573. }
  38574. else
  38575. {
  38576. x1 = w * 0.4f;
  38577. y1 = h * 0.5f;
  38578. x2 = indentX * 2.0f;
  38579. y2 = y1;
  38580. x3 = w * 0.6f;
  38581. y3 = y1;
  38582. x4 = w - x2;
  38583. y4 = y1;
  38584. hw = h * 0.15f;
  38585. hl = h * 0.2f;
  38586. }
  38587. Path p;
  38588. p.addArrow (x1, y1, x2, y2, 1.5f, hw, hl);
  38589. p.addArrow (x3, y3, x4, y4, 1.5f, hw, hl);
  38590. g.fillPath (p);
  38591. }
  38592. }
  38593. }
  38594. juce_UseDebuggingNewOperator
  38595. private:
  38596. const float fixedSize;
  38597. const bool drawBar;
  38598. ToolbarSpacerComp (const ToolbarSpacerComp&);
  38599. const ToolbarSpacerComp& operator= (const ToolbarSpacerComp&);
  38600. };
  38601. class MissingItemsComponent : public PopupMenuCustomComponent
  38602. {
  38603. public:
  38604. MissingItemsComponent (Toolbar& owner_, const int height_)
  38605. : PopupMenuCustomComponent (true),
  38606. owner (owner_),
  38607. height (height_)
  38608. {
  38609. for (int i = owner_.getNumChildComponents(); --i >= 0;)
  38610. {
  38611. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (owner_.getChildComponent (i));
  38612. if (tc != 0 && dynamic_cast <ToolbarSpacerComp*> (tc) == 0 && ! tc->isVisible())
  38613. {
  38614. oldIndexes.insert (0, i);
  38615. addAndMakeVisible (tc, 0);
  38616. }
  38617. }
  38618. layout (400);
  38619. }
  38620. ~MissingItemsComponent()
  38621. {
  38622. // deleting the toolbar while its menu it open??
  38623. jassert (owner.isValidComponent());
  38624. for (int i = 0; i < getNumChildComponents(); ++i)
  38625. {
  38626. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getChildComponent (i));
  38627. if (tc != 0)
  38628. {
  38629. tc->setVisible (false);
  38630. owner.addChildComponent (tc, oldIndexes.remove (i));
  38631. --i;
  38632. }
  38633. }
  38634. owner.resized();
  38635. }
  38636. void layout (const int preferredWidth)
  38637. {
  38638. const int indent = 8;
  38639. int x = indent;
  38640. int y = indent;
  38641. int maxX = 0;
  38642. for (int i = 0; i < getNumChildComponents(); ++i)
  38643. {
  38644. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getChildComponent (i));
  38645. if (tc != 0)
  38646. {
  38647. int preferredSize = 1, minSize = 1, maxSize = 1;
  38648. if (tc->getToolbarItemSizes (height, false, preferredSize, minSize, maxSize))
  38649. {
  38650. if (x + preferredSize > preferredWidth && x > indent)
  38651. {
  38652. x = indent;
  38653. y += height;
  38654. }
  38655. tc->setBounds (x, y, preferredSize, height);
  38656. x += preferredSize;
  38657. maxX = jmax (maxX, x);
  38658. }
  38659. }
  38660. }
  38661. setSize (maxX + 8, y + height + 8);
  38662. }
  38663. void getIdealSize (int& idealWidth, int& idealHeight)
  38664. {
  38665. idealWidth = getWidth();
  38666. idealHeight = getHeight();
  38667. }
  38668. juce_UseDebuggingNewOperator
  38669. private:
  38670. Toolbar& owner;
  38671. const int height;
  38672. Array <int> oldIndexes;
  38673. MissingItemsComponent (const MissingItemsComponent&);
  38674. const MissingItemsComponent& operator= (const MissingItemsComponent&);
  38675. };
  38676. Toolbar::Toolbar()
  38677. : vertical (false),
  38678. isEditingActive (false),
  38679. toolbarStyle (Toolbar::iconsOnly)
  38680. {
  38681. addChildComponent (missingItemsButton = getLookAndFeel().createToolbarMissingItemsButton (*this));
  38682. missingItemsButton->setAlwaysOnTop (true);
  38683. missingItemsButton->addButtonListener (this);
  38684. }
  38685. Toolbar::~Toolbar()
  38686. {
  38687. animator.cancelAllAnimations (true);
  38688. deleteAllChildren();
  38689. }
  38690. void Toolbar::setVertical (const bool shouldBeVertical)
  38691. {
  38692. if (vertical != shouldBeVertical)
  38693. {
  38694. vertical = shouldBeVertical;
  38695. resized();
  38696. }
  38697. }
  38698. void Toolbar::clear()
  38699. {
  38700. for (int i = getNumChildComponents(); --i >= 0;)
  38701. {
  38702. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getChildComponent (i));
  38703. if (tc != 0)
  38704. delete tc;
  38705. }
  38706. resized();
  38707. }
  38708. ToolbarItemComponent* Toolbar::createItem (ToolbarItemFactory& factory, const int itemId)
  38709. {
  38710. if (itemId == ToolbarItemFactory::separatorBarId)
  38711. return new ToolbarSpacerComp (itemId, 0.1f, true);
  38712. else if (itemId == ToolbarItemFactory::spacerId)
  38713. return new ToolbarSpacerComp (itemId, 0.5f, false);
  38714. else if (itemId == ToolbarItemFactory::flexibleSpacerId)
  38715. return new ToolbarSpacerComp (itemId, 0, false);
  38716. return factory.createItem (itemId);
  38717. }
  38718. void Toolbar::addItemInternal (ToolbarItemFactory& factory,
  38719. const int itemId,
  38720. const int insertIndex)
  38721. {
  38722. // An ID can't be zero - this might indicate a mistake somewhere?
  38723. jassert (itemId != 0);
  38724. ToolbarItemComponent* const tc = createItem (factory, itemId);
  38725. if (tc != 0)
  38726. {
  38727. #ifdef JUCE_DEBUG
  38728. Array <int> allowedIds;
  38729. factory.getAllToolbarItemIds (allowedIds);
  38730. // If your factory can create an item for a given ID, it must also return
  38731. // that ID from its getAllToolbarItemIds() method!
  38732. jassert (allowedIds.contains (itemId));
  38733. #endif
  38734. addAndMakeVisible (tc, insertIndex);
  38735. }
  38736. }
  38737. void Toolbar::addItem (ToolbarItemFactory& factory,
  38738. const int itemId,
  38739. const int insertIndex)
  38740. {
  38741. addItemInternal (factory, itemId, insertIndex);
  38742. resized();
  38743. }
  38744. void Toolbar::addDefaultItems (ToolbarItemFactory& factoryToUse)
  38745. {
  38746. Array <int> ids;
  38747. factoryToUse.getDefaultItemSet (ids);
  38748. clear();
  38749. for (int i = 0; i < ids.size(); ++i)
  38750. addItemInternal (factoryToUse, ids.getUnchecked (i), -1);
  38751. resized();
  38752. }
  38753. void Toolbar::removeToolbarItem (const int itemIndex)
  38754. {
  38755. ToolbarItemComponent* const tc = getItemComponent (itemIndex);
  38756. if (tc != 0)
  38757. {
  38758. delete tc;
  38759. resized();
  38760. }
  38761. }
  38762. int Toolbar::getNumItems() const throw()
  38763. {
  38764. return getNumChildComponents() - 1;
  38765. }
  38766. int Toolbar::getItemId (const int itemIndex) const throw()
  38767. {
  38768. ToolbarItemComponent* const tc = getItemComponent (itemIndex);
  38769. return tc != 0 ? tc->getItemId() : 0;
  38770. }
  38771. ToolbarItemComponent* Toolbar::getItemComponent (const int itemIndex) const throw()
  38772. {
  38773. if (itemIndex < getNumItems())
  38774. return dynamic_cast <ToolbarItemComponent*> (getChildComponent (itemIndex));
  38775. return 0;
  38776. }
  38777. ToolbarItemComponent* Toolbar::getNextActiveComponent (int index, const int delta) const
  38778. {
  38779. for (;;)
  38780. {
  38781. index += delta;
  38782. ToolbarItemComponent* const tc = getItemComponent (index);
  38783. if (tc == 0)
  38784. break;
  38785. if (tc->isActive)
  38786. return tc;
  38787. }
  38788. return 0;
  38789. }
  38790. void Toolbar::setStyle (const ToolbarItemStyle& newStyle)
  38791. {
  38792. if (toolbarStyle != newStyle)
  38793. {
  38794. toolbarStyle = newStyle;
  38795. updateAllItemPositions (false);
  38796. }
  38797. }
  38798. const String Toolbar::toString() const
  38799. {
  38800. String s (T("TB:"));
  38801. for (int i = 0; i < getNumItems(); ++i)
  38802. s << getItemId(i) << T(' ');
  38803. return s.trimEnd();
  38804. }
  38805. bool Toolbar::restoreFromString (ToolbarItemFactory& factoryToUse,
  38806. const String& savedVersion)
  38807. {
  38808. if (! savedVersion.startsWith (T("TB:")))
  38809. return false;
  38810. StringArray tokens;
  38811. tokens.addTokens (savedVersion.substring (3), false);
  38812. clear();
  38813. for (int i = 0; i < tokens.size(); ++i)
  38814. addItemInternal (factoryToUse, tokens[i].getIntValue(), -1);
  38815. resized();
  38816. return true;
  38817. }
  38818. void Toolbar::paint (Graphics& g)
  38819. {
  38820. getLookAndFeel().paintToolbarBackground (g, getWidth(), getHeight(), *this);
  38821. }
  38822. int Toolbar::getThickness() const throw()
  38823. {
  38824. return vertical ? getWidth() : getHeight();
  38825. }
  38826. int Toolbar::getLength() const throw()
  38827. {
  38828. return vertical ? getHeight() : getWidth();
  38829. }
  38830. void Toolbar::setEditingActive (const bool active)
  38831. {
  38832. if (isEditingActive != active)
  38833. {
  38834. isEditingActive = active;
  38835. updateAllItemPositions (false);
  38836. }
  38837. }
  38838. void Toolbar::resized()
  38839. {
  38840. updateAllItemPositions (false);
  38841. }
  38842. void Toolbar::updateAllItemPositions (const bool animate)
  38843. {
  38844. if (getWidth() > 0 && getHeight() > 0)
  38845. {
  38846. StretchableObjectResizer resizer;
  38847. const int numComponents = getNumChildComponents();
  38848. Array <ToolbarItemComponent*> activeComps;
  38849. int i;
  38850. for (i = 0; i < numComponents; ++i)
  38851. {
  38852. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getChildComponent (i));
  38853. // have you added a component directly to the toolbar? That's not advisable! Only use addCustomToolbarItem()!
  38854. jassert (tc != 0 || getChildComponent(i) == missingItemsButton);
  38855. if (tc != 0)
  38856. {
  38857. tc->setEditingMode (isEditingActive ? ToolbarItemComponent::editableOnToolbar
  38858. : ToolbarItemComponent::normalMode);
  38859. tc->setStyle (toolbarStyle);
  38860. ToolbarSpacerComp* const spacer = dynamic_cast <ToolbarSpacerComp*> (tc);
  38861. int preferredSize = 1, minSize = 1, maxSize = 1;
  38862. if (tc->getToolbarItemSizes (getThickness(), isVertical(),
  38863. preferredSize, minSize, maxSize))
  38864. {
  38865. tc->isActive = true;
  38866. resizer.addItem (preferredSize, minSize, maxSize,
  38867. spacer != 0 ? spacer->getResizeOrder() : 2);
  38868. }
  38869. else
  38870. {
  38871. tc->isActive = false;
  38872. tc->setVisible (false);
  38873. }
  38874. }
  38875. }
  38876. resizer.resizeToFit (getLength());
  38877. int totalLength = 0;
  38878. for (i = 0; i < resizer.getNumItems(); ++i)
  38879. totalLength += (int) resizer.getItemSize (i);
  38880. const bool itemsOffTheEnd = totalLength > getLength();
  38881. const int extrasButtonSize = getThickness() / 2;
  38882. missingItemsButton->setSize (extrasButtonSize, extrasButtonSize);
  38883. missingItemsButton->setVisible (itemsOffTheEnd);
  38884. missingItemsButton->setEnabled (! isEditingActive);
  38885. if (vertical)
  38886. missingItemsButton->setCentrePosition (getWidth() / 2,
  38887. getHeight() - 4 - extrasButtonSize / 2);
  38888. else
  38889. missingItemsButton->setCentrePosition (getWidth() - 4 - extrasButtonSize / 2,
  38890. getHeight() / 2);
  38891. const int maxLength = itemsOffTheEnd ? (vertical ? missingItemsButton->getY()
  38892. : missingItemsButton->getX()) - 4
  38893. : getLength();
  38894. int pos = 0, activeIndex = 0;
  38895. for (i = 0; i < getNumChildComponents(); ++i)
  38896. {
  38897. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getChildComponent (i));
  38898. if (tc != 0 && tc->isActive)
  38899. {
  38900. const int size = (int) resizer.getItemSize (activeIndex++);
  38901. Rectangle newBounds;
  38902. if (vertical)
  38903. newBounds.setBounds (0, pos, getWidth(), size);
  38904. else
  38905. newBounds.setBounds (pos, 0, size, getHeight());
  38906. if (animate)
  38907. {
  38908. animator.animateComponent (tc, newBounds, 200, 3.0, 0.0);
  38909. }
  38910. else
  38911. {
  38912. animator.cancelAnimation (tc, false);
  38913. tc->setBounds (newBounds);
  38914. }
  38915. pos += size;
  38916. tc->setVisible (pos <= maxLength
  38917. && ((! tc->isBeingDragged)
  38918. || tc->getEditingMode() == ToolbarItemComponent::editableOnPalette));
  38919. }
  38920. }
  38921. }
  38922. }
  38923. void Toolbar::buttonClicked (Button*)
  38924. {
  38925. jassert (missingItemsButton->isShowing());
  38926. if (missingItemsButton->isShowing())
  38927. {
  38928. PopupMenu m;
  38929. m.addCustomItem (1, new MissingItemsComponent (*this, getThickness()));
  38930. m.showAt (missingItemsButton);
  38931. }
  38932. }
  38933. bool Toolbar::isInterestedInDragSource (const String& sourceDescription,
  38934. Component* /*sourceComponent*/)
  38935. {
  38936. return sourceDescription == toolbarDragDescriptor && isEditingActive;
  38937. }
  38938. void Toolbar::itemDragMove (const String&, Component* sourceComponent, int x, int y)
  38939. {
  38940. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (sourceComponent);
  38941. if (tc != 0)
  38942. {
  38943. if (getNumItems() == 0)
  38944. {
  38945. if (tc->getEditingMode() == ToolbarItemComponent::editableOnPalette)
  38946. {
  38947. ToolbarItemPalette* const palette = tc->findParentComponentOfClass ((ToolbarItemPalette*) 0);
  38948. if (palette != 0)
  38949. palette->replaceComponent (tc);
  38950. }
  38951. else
  38952. {
  38953. jassert (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar);
  38954. }
  38955. addChildComponent (tc);
  38956. updateAllItemPositions (false);
  38957. }
  38958. else
  38959. {
  38960. for (int i = getNumItems(); --i >= 0;)
  38961. {
  38962. int currentIndex = getIndexOfChildComponent (tc);
  38963. if (currentIndex < 0)
  38964. {
  38965. if (tc->getEditingMode() == ToolbarItemComponent::editableOnPalette)
  38966. {
  38967. ToolbarItemPalette* const palette = tc->findParentComponentOfClass ((ToolbarItemPalette*) 0);
  38968. if (palette != 0)
  38969. palette->replaceComponent (tc);
  38970. }
  38971. else
  38972. {
  38973. jassert (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar);
  38974. }
  38975. addChildComponent (tc);
  38976. currentIndex = getIndexOfChildComponent (tc);
  38977. updateAllItemPositions (true);
  38978. }
  38979. int newIndex = currentIndex;
  38980. const int dragObjectLeft = vertical ? (y - tc->dragOffsetY) : (x - tc->dragOffsetX);
  38981. const int dragObjectRight = dragObjectLeft + (vertical ? tc->getHeight() : tc->getWidth());
  38982. const Rectangle current (animator.getComponentDestination (getChildComponent (newIndex)));
  38983. ToolbarItemComponent* const prev = getNextActiveComponent (newIndex, -1);
  38984. if (prev != 0)
  38985. {
  38986. const Rectangle previousPos (animator.getComponentDestination (prev));
  38987. if (abs (dragObjectLeft - (vertical ? previousPos.getY() : previousPos.getX())
  38988. < abs (dragObjectRight - (vertical ? current.getBottom() : current.getRight()))))
  38989. {
  38990. newIndex = getIndexOfChildComponent (prev);
  38991. }
  38992. }
  38993. ToolbarItemComponent* const next = getNextActiveComponent (newIndex, 1);
  38994. if (next != 0)
  38995. {
  38996. const Rectangle nextPos (animator.getComponentDestination (next));
  38997. if (abs (dragObjectLeft - (vertical ? current.getY() : current.getX())
  38998. > abs (dragObjectRight - (vertical ? nextPos.getBottom() : nextPos.getRight()))))
  38999. {
  39000. newIndex = getIndexOfChildComponent (next) + 1;
  39001. }
  39002. }
  39003. if (newIndex != currentIndex)
  39004. {
  39005. removeChildComponent (tc);
  39006. addChildComponent (tc, newIndex);
  39007. updateAllItemPositions (true);
  39008. }
  39009. else
  39010. {
  39011. break;
  39012. }
  39013. }
  39014. }
  39015. }
  39016. }
  39017. void Toolbar::itemDragExit (const String&, Component* sourceComponent)
  39018. {
  39019. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (sourceComponent);
  39020. if (tc != 0)
  39021. {
  39022. if (isParentOf (tc))
  39023. {
  39024. removeChildComponent (tc);
  39025. updateAllItemPositions (true);
  39026. }
  39027. }
  39028. }
  39029. void Toolbar::itemDropped (const String&, Component*, int, int)
  39030. {
  39031. }
  39032. void Toolbar::mouseDown (const MouseEvent& e)
  39033. {
  39034. if (e.mods.isPopupMenu())
  39035. {
  39036. }
  39037. }
  39038. class ToolbarCustomisationDialog : public DialogWindow
  39039. {
  39040. public:
  39041. ToolbarCustomisationDialog (ToolbarItemFactory& factory,
  39042. Toolbar* const toolbar_,
  39043. const int optionFlags)
  39044. : DialogWindow (TRANS("Add/remove items from toolbar"), Colours::white, true, true),
  39045. toolbar (toolbar_)
  39046. {
  39047. setContentComponent (new CustomiserPanel (factory, toolbar, optionFlags), true, true);
  39048. setResizable (true, true);
  39049. setResizeLimits (400, 300, 1500, 1000);
  39050. positionNearBar();
  39051. }
  39052. ~ToolbarCustomisationDialog()
  39053. {
  39054. setContentComponent (0, true);
  39055. }
  39056. void closeButtonPressed()
  39057. {
  39058. setVisible (false);
  39059. }
  39060. bool canModalEventBeSentToComponent (const Component* comp)
  39061. {
  39062. return toolbar->isParentOf (comp);
  39063. }
  39064. void positionNearBar()
  39065. {
  39066. const Rectangle screenSize (toolbar->getParentMonitorArea());
  39067. const int tbx = toolbar->getScreenX();
  39068. const int tby = toolbar->getScreenY();
  39069. const int gap = 8;
  39070. int x, y;
  39071. if (toolbar->isVertical())
  39072. {
  39073. y = tby;
  39074. if (tbx > screenSize.getCentreX())
  39075. x = tbx - getWidth() - gap;
  39076. else
  39077. x = tbx + toolbar->getWidth() + gap;
  39078. }
  39079. else
  39080. {
  39081. x = tbx + (toolbar->getWidth() - getWidth()) / 2;
  39082. if (tby > screenSize.getCentreY())
  39083. y = tby - getHeight() - gap;
  39084. else
  39085. y = tby + toolbar->getHeight() + gap;
  39086. }
  39087. setTopLeftPosition (x, y);
  39088. }
  39089. private:
  39090. Toolbar* const toolbar;
  39091. class CustomiserPanel : public Component,
  39092. private ComboBoxListener,
  39093. private ButtonListener
  39094. {
  39095. public:
  39096. CustomiserPanel (ToolbarItemFactory& factory_,
  39097. Toolbar* const toolbar_,
  39098. const int optionFlags)
  39099. : factory (factory_),
  39100. toolbar (toolbar_),
  39101. styleBox (0),
  39102. defaultButton (0)
  39103. {
  39104. addAndMakeVisible (palette = new ToolbarItemPalette (factory, toolbar));
  39105. if ((optionFlags & (Toolbar::allowIconsOnlyChoice
  39106. | Toolbar::allowIconsWithTextChoice
  39107. | Toolbar::allowTextOnlyChoice)) != 0)
  39108. {
  39109. addAndMakeVisible (styleBox = new ComboBox (String::empty));
  39110. styleBox->setEditableText (false);
  39111. if ((optionFlags & Toolbar::allowIconsOnlyChoice) != 0)
  39112. styleBox->addItem (TRANS("Show icons only"), 1);
  39113. if ((optionFlags & Toolbar::allowIconsWithTextChoice) != 0)
  39114. styleBox->addItem (TRANS("Show icons and descriptions"), 2);
  39115. if ((optionFlags & Toolbar::allowTextOnlyChoice) != 0)
  39116. styleBox->addItem (TRANS("Show descriptions only"), 3);
  39117. if (toolbar_->getStyle() == Toolbar::iconsOnly)
  39118. styleBox->setSelectedId (1);
  39119. else if (toolbar_->getStyle() == Toolbar::iconsWithText)
  39120. styleBox->setSelectedId (2);
  39121. else if (toolbar_->getStyle() == Toolbar::textOnly)
  39122. styleBox->setSelectedId (3);
  39123. styleBox->addListener (this);
  39124. }
  39125. if ((optionFlags & Toolbar::showResetToDefaultsButton) != 0)
  39126. {
  39127. addAndMakeVisible (defaultButton = new TextButton (TRANS ("Restore to default set of items")));
  39128. defaultButton->addButtonListener (this);
  39129. }
  39130. addAndMakeVisible (instructions = new Label (String::empty,
  39131. 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.")));
  39132. instructions->setFont (Font (13.0f));
  39133. setSize (500, 300);
  39134. }
  39135. ~CustomiserPanel()
  39136. {
  39137. deleteAllChildren();
  39138. }
  39139. void comboBoxChanged (ComboBox*)
  39140. {
  39141. if (styleBox->getSelectedId() == 1)
  39142. toolbar->setStyle (Toolbar::iconsOnly);
  39143. else if (styleBox->getSelectedId() == 2)
  39144. toolbar->setStyle (Toolbar::iconsWithText);
  39145. else if (styleBox->getSelectedId() == 3)
  39146. toolbar->setStyle (Toolbar::textOnly);
  39147. palette->resized(); // to make it update the styles
  39148. }
  39149. void buttonClicked (Button*)
  39150. {
  39151. toolbar->addDefaultItems (factory);
  39152. }
  39153. void paint (Graphics& g)
  39154. {
  39155. Colour background;
  39156. DialogWindow* const dw = findParentComponentOfClass ((DialogWindow*) 0);
  39157. if (dw != 0)
  39158. background = dw->getBackgroundColour();
  39159. g.setColour (background.contrasting().withAlpha (0.3f));
  39160. g.fillRect (palette->getX(), palette->getBottom() - 1, palette->getWidth(), 1);
  39161. }
  39162. void resized()
  39163. {
  39164. palette->setBounds (0, 0, getWidth(), getHeight() - 120);
  39165. if (styleBox != 0)
  39166. styleBox->setBounds (10, getHeight() - 110, 200, 22);
  39167. if (defaultButton != 0)
  39168. {
  39169. defaultButton->changeWidthToFitText (22);
  39170. defaultButton->setTopLeftPosition (240, getHeight() - 110);
  39171. }
  39172. instructions->setBounds (10, getHeight() - 80, getWidth() - 20, 80);
  39173. }
  39174. private:
  39175. ToolbarItemFactory& factory;
  39176. Toolbar* const toolbar;
  39177. Label* instructions;
  39178. ToolbarItemPalette* palette;
  39179. ComboBox* styleBox;
  39180. TextButton* defaultButton;
  39181. };
  39182. };
  39183. void Toolbar::showCustomisationDialog (ToolbarItemFactory& factory, const int optionFlags)
  39184. {
  39185. setEditingActive (true);
  39186. ToolbarCustomisationDialog dw (factory, this, optionFlags);
  39187. dw.runModalLoop();
  39188. jassert (isValidComponent()); // ? deleting the toolbar while it's being edited?
  39189. setEditingActive (false);
  39190. }
  39191. END_JUCE_NAMESPACE
  39192. /********* End of inlined file: juce_Toolbar.cpp *********/
  39193. /********* Start of inlined file: juce_ToolbarItemComponent.cpp *********/
  39194. BEGIN_JUCE_NAMESPACE
  39195. ToolbarItemFactory::ToolbarItemFactory()
  39196. {
  39197. }
  39198. ToolbarItemFactory::~ToolbarItemFactory()
  39199. {
  39200. }
  39201. class ItemDragAndDropOverlayComponent : public Component
  39202. {
  39203. public:
  39204. ItemDragAndDropOverlayComponent()
  39205. : isDragging (false)
  39206. {
  39207. setAlwaysOnTop (true);
  39208. setRepaintsOnMouseActivity (true);
  39209. setMouseCursor (MouseCursor::DraggingHandCursor);
  39210. }
  39211. ~ItemDragAndDropOverlayComponent()
  39212. {
  39213. }
  39214. void paint (Graphics& g)
  39215. {
  39216. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  39217. if (isMouseOverOrDragging()
  39218. && tc != 0
  39219. && tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  39220. {
  39221. g.setColour (findColour (Toolbar::editingModeOutlineColourId, true));
  39222. g.drawRect (0, 0, getWidth(), getHeight(),
  39223. jmin (2, (getWidth() - 1) / 2, (getHeight() - 1) / 2));
  39224. }
  39225. }
  39226. void mouseDown (const MouseEvent& e)
  39227. {
  39228. isDragging = false;
  39229. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  39230. if (tc != 0)
  39231. {
  39232. tc->dragOffsetX = e.x;
  39233. tc->dragOffsetY = e.y;
  39234. }
  39235. }
  39236. void mouseDrag (const MouseEvent& e)
  39237. {
  39238. if (! (isDragging || e.mouseWasClicked()))
  39239. {
  39240. isDragging = true;
  39241. DragAndDropContainer* const dnd = DragAndDropContainer::findParentDragContainerFor (this);
  39242. if (dnd != 0)
  39243. {
  39244. dnd->startDragging (Toolbar::toolbarDragDescriptor, getParentComponent(), 0, true);
  39245. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  39246. if (tc != 0)
  39247. {
  39248. tc->isBeingDragged = true;
  39249. if (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  39250. tc->setVisible (false);
  39251. }
  39252. }
  39253. }
  39254. }
  39255. void mouseUp (const MouseEvent&)
  39256. {
  39257. isDragging = false;
  39258. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  39259. if (tc != 0)
  39260. {
  39261. tc->isBeingDragged = false;
  39262. Toolbar* const tb = tc->getToolbar();
  39263. if (tb != 0)
  39264. tb->updateAllItemPositions (true);
  39265. else if (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  39266. delete tc;
  39267. }
  39268. }
  39269. void parentSizeChanged()
  39270. {
  39271. setBounds (0, 0, getParentWidth(), getParentHeight());
  39272. }
  39273. juce_UseDebuggingNewOperator
  39274. private:
  39275. bool isDragging;
  39276. ItemDragAndDropOverlayComponent (const ItemDragAndDropOverlayComponent&);
  39277. const ItemDragAndDropOverlayComponent& operator= (const ItemDragAndDropOverlayComponent&);
  39278. };
  39279. ToolbarItemComponent::ToolbarItemComponent (const int itemId_,
  39280. const String& labelText,
  39281. const bool isBeingUsedAsAButton_)
  39282. : Button (labelText),
  39283. itemId (itemId_),
  39284. mode (normalMode),
  39285. toolbarStyle (Toolbar::iconsOnly),
  39286. overlayComp (0),
  39287. dragOffsetX (0),
  39288. dragOffsetY (0),
  39289. isActive (true),
  39290. isBeingDragged (false),
  39291. isBeingUsedAsAButton (isBeingUsedAsAButton_)
  39292. {
  39293. // Your item ID can't be 0!
  39294. jassert (itemId_ != 0);
  39295. }
  39296. ToolbarItemComponent::~ToolbarItemComponent()
  39297. {
  39298. jassert (overlayComp == 0 || overlayComp->isValidComponent());
  39299. delete overlayComp;
  39300. }
  39301. Toolbar* ToolbarItemComponent::getToolbar() const
  39302. {
  39303. return dynamic_cast <Toolbar*> (getParentComponent());
  39304. }
  39305. bool ToolbarItemComponent::isToolbarVertical() const
  39306. {
  39307. const Toolbar* const t = getToolbar();
  39308. return t != 0 && t->isVertical();
  39309. }
  39310. void ToolbarItemComponent::setStyle (const Toolbar::ToolbarItemStyle& newStyle)
  39311. {
  39312. if (toolbarStyle != newStyle)
  39313. {
  39314. toolbarStyle = newStyle;
  39315. repaint();
  39316. resized();
  39317. }
  39318. }
  39319. void ToolbarItemComponent::paintButton (Graphics& g, bool isMouseOver, bool isMouseDown)
  39320. {
  39321. if (isBeingUsedAsAButton)
  39322. getLookAndFeel().paintToolbarButtonBackground (g, getWidth(), getHeight(),
  39323. isMouseOver, isMouseDown, *this);
  39324. if (toolbarStyle != Toolbar::iconsOnly)
  39325. {
  39326. const int indent = contentArea.getX();
  39327. int y = indent;
  39328. int h = getHeight() - indent * 2;
  39329. if (toolbarStyle == Toolbar::iconsWithText)
  39330. {
  39331. y = contentArea.getBottom() + indent / 2;
  39332. h -= contentArea.getHeight();
  39333. }
  39334. getLookAndFeel().paintToolbarButtonLabel (g, indent, y, getWidth() - indent * 2, h,
  39335. getButtonText(), *this);
  39336. }
  39337. if (! contentArea.isEmpty())
  39338. {
  39339. g.saveState();
  39340. g.setOrigin (contentArea.getX(), contentArea.getY());
  39341. g.reduceClipRegion (0, 0, contentArea.getWidth(), contentArea.getHeight());
  39342. paintButtonArea (g, contentArea.getWidth(), contentArea.getHeight(), isMouseOver, isMouseDown);
  39343. g.restoreState();
  39344. }
  39345. }
  39346. void ToolbarItemComponent::resized()
  39347. {
  39348. if (toolbarStyle != Toolbar::textOnly)
  39349. {
  39350. const int indent = jmin (proportionOfWidth (0.08f),
  39351. proportionOfHeight (0.08f));
  39352. contentArea = Rectangle (indent, indent,
  39353. getWidth() - indent * 2,
  39354. toolbarStyle == Toolbar::iconsWithText ? proportionOfHeight (0.55f)
  39355. : (getHeight() - indent * 2));
  39356. }
  39357. else
  39358. {
  39359. contentArea = Rectangle();
  39360. }
  39361. contentAreaChanged (contentArea);
  39362. }
  39363. void ToolbarItemComponent::setEditingMode (const ToolbarEditingMode newMode)
  39364. {
  39365. if (mode != newMode)
  39366. {
  39367. mode = newMode;
  39368. repaint();
  39369. if (mode == normalMode)
  39370. {
  39371. jassert (overlayComp == 0 || overlayComp->isValidComponent());
  39372. delete overlayComp;
  39373. overlayComp = 0;
  39374. }
  39375. else if (overlayComp == 0)
  39376. {
  39377. addAndMakeVisible (overlayComp = new ItemDragAndDropOverlayComponent());
  39378. overlayComp->parentSizeChanged();
  39379. }
  39380. resized();
  39381. }
  39382. }
  39383. END_JUCE_NAMESPACE
  39384. /********* End of inlined file: juce_ToolbarItemComponent.cpp *********/
  39385. /********* Start of inlined file: juce_ToolbarItemPalette.cpp *********/
  39386. BEGIN_JUCE_NAMESPACE
  39387. ToolbarItemPalette::ToolbarItemPalette (ToolbarItemFactory& factory_,
  39388. Toolbar* const toolbar_)
  39389. : factory (factory_),
  39390. toolbar (toolbar_)
  39391. {
  39392. Component* const itemHolder = new Component();
  39393. Array <int> allIds;
  39394. factory_.getAllToolbarItemIds (allIds);
  39395. for (int i = 0; i < allIds.size(); ++i)
  39396. {
  39397. ToolbarItemComponent* const tc = Toolbar::createItem (factory_, allIds.getUnchecked (i));
  39398. jassert (tc != 0);
  39399. if (tc != 0)
  39400. {
  39401. itemHolder->addAndMakeVisible (tc);
  39402. tc->setEditingMode (ToolbarItemComponent::editableOnPalette);
  39403. }
  39404. }
  39405. viewport = new Viewport();
  39406. viewport->setViewedComponent (itemHolder);
  39407. addAndMakeVisible (viewport);
  39408. }
  39409. ToolbarItemPalette::~ToolbarItemPalette()
  39410. {
  39411. viewport->getViewedComponent()->deleteAllChildren();
  39412. deleteAllChildren();
  39413. }
  39414. void ToolbarItemPalette::resized()
  39415. {
  39416. viewport->setBoundsInset (BorderSize (1));
  39417. Component* const itemHolder = viewport->getViewedComponent();
  39418. const int indent = 8;
  39419. const int preferredWidth = viewport->getWidth() - viewport->getScrollBarThickness() - indent;
  39420. const int height = toolbar->getThickness();
  39421. int x = indent;
  39422. int y = indent;
  39423. int maxX = 0;
  39424. for (int i = 0; i < itemHolder->getNumChildComponents(); ++i)
  39425. {
  39426. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (itemHolder->getChildComponent (i));
  39427. if (tc != 0)
  39428. {
  39429. tc->setStyle (toolbar->getStyle());
  39430. int preferredSize = 1, minSize = 1, maxSize = 1;
  39431. if (tc->getToolbarItemSizes (height, false, preferredSize, minSize, maxSize))
  39432. {
  39433. if (x + preferredSize > preferredWidth && x > indent)
  39434. {
  39435. x = indent;
  39436. y += height;
  39437. }
  39438. tc->setBounds (x, y, preferredSize, height);
  39439. x += preferredSize + 8;
  39440. maxX = jmax (maxX, x);
  39441. }
  39442. }
  39443. }
  39444. itemHolder->setSize (maxX, y + height + 8);
  39445. }
  39446. void ToolbarItemPalette::replaceComponent (ToolbarItemComponent* const comp)
  39447. {
  39448. ToolbarItemComponent* const tc = Toolbar::createItem (factory, comp->getItemId());
  39449. jassert (tc != 0);
  39450. if (tc != 0)
  39451. {
  39452. tc->setBounds (comp->getBounds());
  39453. tc->setStyle (toolbar->getStyle());
  39454. tc->setEditingMode (comp->getEditingMode());
  39455. viewport->getViewedComponent()->addAndMakeVisible (tc, getIndexOfChildComponent (comp));
  39456. }
  39457. }
  39458. END_JUCE_NAMESPACE
  39459. /********* End of inlined file: juce_ToolbarItemPalette.cpp *********/
  39460. /********* Start of inlined file: juce_TreeView.cpp *********/
  39461. BEGIN_JUCE_NAMESPACE
  39462. class TreeViewContentComponent : public Component
  39463. {
  39464. public:
  39465. TreeViewContentComponent (TreeView* const owner_)
  39466. : owner (owner_),
  39467. isDragging (false)
  39468. {
  39469. }
  39470. ~TreeViewContentComponent()
  39471. {
  39472. deleteAllChildren();
  39473. }
  39474. void mouseDown (const MouseEvent& e)
  39475. {
  39476. isDragging = false;
  39477. needSelectionOnMouseUp = false;
  39478. Rectangle pos;
  39479. TreeViewItem* const item = findItemAt (e.y, pos);
  39480. if (item != 0 && e.x >= pos.getX())
  39481. {
  39482. if (! owner->isMultiSelectEnabled())
  39483. item->setSelected (true, true);
  39484. else if (item->isSelected())
  39485. needSelectionOnMouseUp = ! e.mods.isPopupMenu();
  39486. else
  39487. selectBasedOnModifiers (item, e.mods);
  39488. MouseEvent e2 (e);
  39489. e2.x -= pos.getX();
  39490. e2.y -= pos.getY();
  39491. item->itemClicked (e2);
  39492. }
  39493. }
  39494. void mouseUp (const MouseEvent& e)
  39495. {
  39496. Rectangle pos;
  39497. TreeViewItem* const item = findItemAt (e.y, pos);
  39498. if (item != 0 && e.mouseWasClicked())
  39499. {
  39500. if (needSelectionOnMouseUp)
  39501. {
  39502. selectBasedOnModifiers (item, e.mods);
  39503. }
  39504. else if (e.mouseWasClicked())
  39505. {
  39506. if (e.x >= pos.getX() - owner->getIndentSize()
  39507. && e.x < pos.getX())
  39508. {
  39509. item->setOpen (! item->isOpen());
  39510. }
  39511. }
  39512. }
  39513. }
  39514. void mouseDoubleClick (const MouseEvent& e)
  39515. {
  39516. if (e.getNumberOfClicks() != 3) // ignore triple clicks
  39517. {
  39518. Rectangle pos;
  39519. TreeViewItem* const item = findItemAt (e.y, pos);
  39520. if (item != 0 && e.x >= pos.getX())
  39521. {
  39522. MouseEvent e2 (e);
  39523. e2.x -= pos.getX();
  39524. e2.y -= pos.getY();
  39525. item->itemDoubleClicked (e2);
  39526. }
  39527. }
  39528. }
  39529. void mouseDrag (const MouseEvent& e)
  39530. {
  39531. if (isEnabled() && ! (e.mouseWasClicked() || isDragging))
  39532. {
  39533. isDragging = true;
  39534. Rectangle pos;
  39535. TreeViewItem* const item = findItemAt (e.getMouseDownY(), pos);
  39536. if (item != 0 && e.getMouseDownX() >= pos.getX())
  39537. {
  39538. const String dragDescription (item->getDragSourceDescription());
  39539. if (dragDescription.isNotEmpty())
  39540. {
  39541. DragAndDropContainer* const dragContainer
  39542. = DragAndDropContainer::findParentDragContainerFor (this);
  39543. if (dragContainer != 0)
  39544. {
  39545. pos.setSize (pos.getWidth(), item->itemHeight);
  39546. Image* dragImage = Component::createComponentSnapshot (pos, true);
  39547. dragImage->multiplyAllAlphas (0.6f);
  39548. dragContainer->startDragging (dragDescription, owner, dragImage, true);
  39549. }
  39550. else
  39551. {
  39552. // to be able to do a drag-and-drop operation, the treeview needs to
  39553. // be inside a component which is also a DragAndDropContainer.
  39554. jassertfalse
  39555. }
  39556. }
  39557. }
  39558. }
  39559. }
  39560. void paint (Graphics& g);
  39561. TreeViewItem* findItemAt (int y, Rectangle& itemPosition) const;
  39562. void updateComponents()
  39563. {
  39564. int xAdjust = 0, yAdjust = 0;
  39565. if ((! owner->rootItemVisible) && owner->rootItem != 0)
  39566. {
  39567. yAdjust = owner->rootItem->itemHeight;
  39568. xAdjust = owner->getIndentSize();
  39569. }
  39570. const int visibleTop = -getY();
  39571. const int visibleBottom = visibleTop + getParentHeight();
  39572. BitArray itemsToKeep;
  39573. TreeViewItem* item = owner->rootItem;
  39574. int y = -yAdjust;
  39575. while (item != 0 && y < visibleBottom)
  39576. {
  39577. y += item->itemHeight;
  39578. if (y >= visibleTop)
  39579. {
  39580. const int index = rowComponentIds.indexOf (item->uid);
  39581. if (index < 0)
  39582. {
  39583. Component* const comp = item->createItemComponent();
  39584. if (comp != 0)
  39585. {
  39586. addAndMakeVisible (comp);
  39587. itemsToKeep.setBit (rowComponentItems.size());
  39588. rowComponentItems.add (item);
  39589. rowComponentIds.add (item->uid);
  39590. rowComponents.add (comp);
  39591. }
  39592. }
  39593. else
  39594. {
  39595. itemsToKeep.setBit (index);
  39596. }
  39597. }
  39598. item = item->getNextVisibleItem (true);
  39599. }
  39600. for (int i = rowComponentItems.size(); --i >= 0;)
  39601. {
  39602. Component* const comp = (Component*) (rowComponents.getUnchecked(i));
  39603. bool keep = false;
  39604. if ((itemsToKeep[i] || (comp == Component::getComponentUnderMouse() && comp->isMouseButtonDown()))
  39605. && isParentOf (comp))
  39606. {
  39607. if (itemsToKeep[i])
  39608. {
  39609. const TreeViewItem* const item = (TreeViewItem*) rowComponentItems.getUnchecked(i);
  39610. Rectangle pos (item->getItemPosition (false));
  39611. pos.translate (-xAdjust, -yAdjust);
  39612. pos.setSize (pos.getWidth() + xAdjust, item->itemHeight);
  39613. if (pos.getBottom() >= visibleTop && pos.getY() < visibleBottom)
  39614. {
  39615. keep = true;
  39616. comp->setBounds (pos);
  39617. }
  39618. }
  39619. else
  39620. {
  39621. comp->setSize (0, 0);
  39622. }
  39623. }
  39624. if (! keep)
  39625. {
  39626. delete comp;
  39627. rowComponents.remove (i);
  39628. rowComponentIds.remove (i);
  39629. rowComponentItems.remove (i);
  39630. }
  39631. }
  39632. }
  39633. void resized()
  39634. {
  39635. owner->itemsChanged();
  39636. }
  39637. juce_UseDebuggingNewOperator
  39638. private:
  39639. TreeView* const owner;
  39640. VoidArray rowComponentItems;
  39641. Array <int> rowComponentIds;
  39642. VoidArray rowComponents;
  39643. bool isDragging, needSelectionOnMouseUp;
  39644. TreeViewContentComponent (const TreeViewContentComponent&);
  39645. const TreeViewContentComponent& operator= (const TreeViewContentComponent&);
  39646. void selectBasedOnModifiers (TreeViewItem* const item, const ModifierKeys& modifiers)
  39647. {
  39648. TreeViewItem* firstSelected = 0;
  39649. if (modifiers.isShiftDown() && ((firstSelected = owner->getSelectedItem (0)) != 0))
  39650. {
  39651. TreeViewItem* const lastSelected = owner->getSelectedItem (owner->getNumSelectedItems() - 1);
  39652. jassert (lastSelected != 0);
  39653. int rowStart = firstSelected->getRowNumberInTree();
  39654. int rowEnd = lastSelected->getRowNumberInTree();
  39655. if (rowStart > rowEnd)
  39656. swapVariables (rowStart, rowEnd);
  39657. int ourRow = item->getRowNumberInTree();
  39658. int otherEnd = ourRow < rowEnd ? rowStart : rowEnd;
  39659. if (ourRow > otherEnd)
  39660. swapVariables (ourRow, otherEnd);
  39661. for (int i = ourRow; i <= otherEnd; ++i)
  39662. owner->getItemOnRow (i)->setSelected (true, false);
  39663. }
  39664. else
  39665. {
  39666. const bool cmd = modifiers.isCommandDown();
  39667. item->setSelected ((! cmd) || (! item->isSelected()), ! cmd);
  39668. }
  39669. }
  39670. };
  39671. class TreeViewport : public Viewport
  39672. {
  39673. public:
  39674. TreeViewport() throw() {}
  39675. ~TreeViewport() throw() {}
  39676. void updateComponents()
  39677. {
  39678. if (getViewedComponent() != 0)
  39679. ((TreeViewContentComponent*) getViewedComponent())->updateComponents();
  39680. repaint();
  39681. }
  39682. void visibleAreaChanged (int, int, int, int)
  39683. {
  39684. updateComponents();
  39685. }
  39686. juce_UseDebuggingNewOperator
  39687. private:
  39688. TreeViewport (const TreeViewport&);
  39689. const TreeViewport& operator= (const TreeViewport&);
  39690. };
  39691. TreeView::TreeView (const String& componentName)
  39692. : Component (componentName),
  39693. rootItem (0),
  39694. indentSize (24),
  39695. defaultOpenness (false),
  39696. needsRecalculating (true),
  39697. rootItemVisible (true),
  39698. multiSelectEnabled (false)
  39699. {
  39700. addAndMakeVisible (viewport = new TreeViewport());
  39701. viewport->setViewedComponent (new TreeViewContentComponent (this));
  39702. viewport->setWantsKeyboardFocus (false);
  39703. setWantsKeyboardFocus (true);
  39704. }
  39705. TreeView::~TreeView()
  39706. {
  39707. if (rootItem != 0)
  39708. rootItem->setOwnerView (0);
  39709. deleteAllChildren();
  39710. }
  39711. void TreeView::setRootItem (TreeViewItem* const newRootItem)
  39712. {
  39713. if (rootItem != newRootItem)
  39714. {
  39715. if (newRootItem != 0)
  39716. {
  39717. jassert (newRootItem->ownerView == 0); // can't use a tree item in more than one tree at once..
  39718. if (newRootItem->ownerView != 0)
  39719. newRootItem->ownerView->setRootItem (0);
  39720. }
  39721. if (rootItem != 0)
  39722. rootItem->setOwnerView (0);
  39723. rootItem = newRootItem;
  39724. if (newRootItem != 0)
  39725. newRootItem->setOwnerView (this);
  39726. needsRecalculating = true;
  39727. handleAsyncUpdate();
  39728. if (rootItem != 0 && (defaultOpenness || ! rootItemVisible))
  39729. {
  39730. rootItem->setOpen (false); // force a re-open
  39731. rootItem->setOpen (true);
  39732. }
  39733. }
  39734. }
  39735. void TreeView::setRootItemVisible (const bool shouldBeVisible)
  39736. {
  39737. rootItemVisible = shouldBeVisible;
  39738. if (rootItem != 0 && (defaultOpenness || ! rootItemVisible))
  39739. {
  39740. rootItem->setOpen (false); // force a re-open
  39741. rootItem->setOpen (true);
  39742. }
  39743. itemsChanged();
  39744. }
  39745. void TreeView::colourChanged()
  39746. {
  39747. setOpaque (findColour (backgroundColourId).isOpaque());
  39748. repaint();
  39749. }
  39750. void TreeView::setIndentSize (const int newIndentSize)
  39751. {
  39752. if (indentSize != newIndentSize)
  39753. {
  39754. indentSize = newIndentSize;
  39755. resized();
  39756. }
  39757. }
  39758. void TreeView::setDefaultOpenness (const bool isOpenByDefault)
  39759. {
  39760. if (defaultOpenness != isOpenByDefault)
  39761. {
  39762. defaultOpenness = isOpenByDefault;
  39763. itemsChanged();
  39764. }
  39765. }
  39766. void TreeView::setMultiSelectEnabled (const bool canMultiSelect)
  39767. {
  39768. multiSelectEnabled = canMultiSelect;
  39769. }
  39770. void TreeView::clearSelectedItems()
  39771. {
  39772. if (rootItem != 0)
  39773. rootItem->deselectAllRecursively();
  39774. }
  39775. int TreeView::getNumSelectedItems() const throw()
  39776. {
  39777. return (rootItem != 0) ? rootItem->countSelectedItemsRecursively() : 0;
  39778. }
  39779. TreeViewItem* TreeView::getSelectedItem (const int index) const throw()
  39780. {
  39781. return (rootItem != 0) ? rootItem->getSelectedItemWithIndex (index) : 0;
  39782. }
  39783. int TreeView::getNumRowsInTree() const
  39784. {
  39785. if (rootItem != 0)
  39786. return rootItem->getNumRows() - (rootItemVisible ? 0 : 1);
  39787. return 0;
  39788. }
  39789. TreeViewItem* TreeView::getItemOnRow (int index) const
  39790. {
  39791. if (! rootItemVisible)
  39792. ++index;
  39793. if (rootItem != 0 && index >= 0)
  39794. return rootItem->getItemOnRow (index);
  39795. return 0;
  39796. }
  39797. XmlElement* TreeView::getOpennessState (const bool alsoIncludeScrollPosition) const
  39798. {
  39799. XmlElement* e = 0;
  39800. if (rootItem != 0)
  39801. {
  39802. e = rootItem->createXmlOpenness();
  39803. if (e != 0 && alsoIncludeScrollPosition)
  39804. e->setAttribute (T("scrollPos"), viewport->getViewPositionY());
  39805. }
  39806. return e;
  39807. }
  39808. void TreeView::restoreOpennessState (const XmlElement& newState)
  39809. {
  39810. if (rootItem != 0)
  39811. {
  39812. rootItem->restoreFromXml (newState);
  39813. if (newState.hasAttribute (T("scrollPos")))
  39814. viewport->setViewPosition (viewport->getViewPositionX(),
  39815. newState.getIntAttribute (T("scrollPos")));
  39816. }
  39817. }
  39818. void TreeView::paint (Graphics& g)
  39819. {
  39820. g.fillAll (findColour (backgroundColourId));
  39821. }
  39822. void TreeView::resized()
  39823. {
  39824. viewport->setBounds (0, 0, getWidth(), getHeight());
  39825. itemsChanged();
  39826. }
  39827. void TreeView::moveSelectedRow (int delta)
  39828. {
  39829. int rowSelected = 0;
  39830. TreeViewItem* const firstSelected = getSelectedItem (0);
  39831. if (firstSelected != 0)
  39832. rowSelected = firstSelected->getRowNumberInTree();
  39833. rowSelected = jlimit (0, getNumRowsInTree() - 1, rowSelected + delta);
  39834. TreeViewItem* item = getItemOnRow (rowSelected);
  39835. if (item != 0)
  39836. {
  39837. item->setSelected (true, true);
  39838. scrollToKeepItemVisible (item);
  39839. }
  39840. }
  39841. void TreeView::scrollToKeepItemVisible (TreeViewItem* item)
  39842. {
  39843. if (item != 0 && item->ownerView == this)
  39844. {
  39845. handleAsyncUpdate();
  39846. item = item->getDeepestOpenParentItem();
  39847. int y = item->y;
  39848. if (! rootItemVisible)
  39849. y -= rootItem->itemHeight;
  39850. int viewTop = viewport->getViewPositionY();
  39851. if (y < viewTop)
  39852. {
  39853. viewport->setViewPosition (viewport->getViewPositionX(), y);
  39854. }
  39855. else if (y + item->itemHeight > viewTop + viewport->getViewHeight())
  39856. {
  39857. viewport->setViewPosition (viewport->getViewPositionX(),
  39858. (y + item->itemHeight) - viewport->getViewHeight());
  39859. }
  39860. }
  39861. }
  39862. bool TreeView::keyPressed (const KeyPress& key)
  39863. {
  39864. if (key.isKeyCode (KeyPress::upKey))
  39865. {
  39866. moveSelectedRow (-1);
  39867. }
  39868. else if (key.isKeyCode (KeyPress::downKey))
  39869. {
  39870. moveSelectedRow (1);
  39871. }
  39872. else if (key.isKeyCode (KeyPress::pageDownKey) || key.isKeyCode (KeyPress::pageUpKey))
  39873. {
  39874. if (rootItem != 0)
  39875. {
  39876. int rowsOnScreen = getHeight() / jmax (1, rootItem->itemHeight);
  39877. if (key.isKeyCode (KeyPress::pageUpKey))
  39878. rowsOnScreen = -rowsOnScreen;
  39879. moveSelectedRow (rowsOnScreen);
  39880. }
  39881. }
  39882. else if (key.isKeyCode (KeyPress::homeKey))
  39883. {
  39884. moveSelectedRow (-0x3fffffff);
  39885. }
  39886. else if (key.isKeyCode (KeyPress::endKey))
  39887. {
  39888. moveSelectedRow (0x3fffffff);
  39889. }
  39890. else if (key.isKeyCode (KeyPress::returnKey))
  39891. {
  39892. TreeViewItem* const firstSelected = getSelectedItem (0);
  39893. if (firstSelected != 0)
  39894. firstSelected->setOpen (! firstSelected->isOpen());
  39895. }
  39896. else if (key.isKeyCode (KeyPress::leftKey))
  39897. {
  39898. TreeViewItem* const firstSelected = getSelectedItem (0);
  39899. if (firstSelected != 0)
  39900. {
  39901. if (firstSelected->isOpen())
  39902. {
  39903. firstSelected->setOpen (false);
  39904. }
  39905. else
  39906. {
  39907. TreeViewItem* parent = firstSelected->parentItem;
  39908. if ((! rootItemVisible) && parent == rootItem)
  39909. parent = 0;
  39910. if (parent != 0)
  39911. {
  39912. parent->setSelected (true, true);
  39913. scrollToKeepItemVisible (parent);
  39914. }
  39915. }
  39916. }
  39917. }
  39918. else if (key.isKeyCode (KeyPress::rightKey))
  39919. {
  39920. TreeViewItem* const firstSelected = getSelectedItem (0);
  39921. if (firstSelected != 0)
  39922. {
  39923. if (firstSelected->isOpen() || ! firstSelected->mightContainSubItems())
  39924. moveSelectedRow (1);
  39925. else
  39926. firstSelected->setOpen (true);
  39927. }
  39928. }
  39929. else
  39930. {
  39931. return false;
  39932. }
  39933. return true;
  39934. }
  39935. void TreeView::itemsChanged() throw()
  39936. {
  39937. needsRecalculating = true;
  39938. repaint();
  39939. triggerAsyncUpdate();
  39940. }
  39941. void TreeView::handleAsyncUpdate()
  39942. {
  39943. if (needsRecalculating)
  39944. {
  39945. needsRecalculating = false;
  39946. const ScopedLock sl (nodeAlterationLock);
  39947. if (rootItem != 0)
  39948. rootItem->updatePositions (0);
  39949. ((TreeViewport*) viewport)->updateComponents();
  39950. if (rootItem != 0)
  39951. {
  39952. viewport->getViewedComponent()
  39953. ->setSize (jmax (viewport->getMaximumVisibleWidth(), rootItem->totalWidth),
  39954. rootItem->totalHeight - (rootItemVisible ? 0 : rootItem->itemHeight));
  39955. }
  39956. else
  39957. {
  39958. viewport->getViewedComponent()->setSize (0, 0);
  39959. }
  39960. }
  39961. }
  39962. void TreeViewContentComponent::paint (Graphics& g)
  39963. {
  39964. if (owner->rootItem != 0)
  39965. {
  39966. owner->handleAsyncUpdate();
  39967. int w = getWidth();
  39968. if (! owner->rootItemVisible)
  39969. {
  39970. const int indentWidth = owner->getIndentSize();
  39971. g.setOrigin (-indentWidth, -owner->rootItem->itemHeight);
  39972. w += indentWidth;
  39973. }
  39974. owner->rootItem->paintRecursively (g, w);
  39975. }
  39976. }
  39977. TreeViewItem* TreeViewContentComponent::findItemAt (int y, Rectangle& itemPosition) const
  39978. {
  39979. if (owner->rootItem != 0)
  39980. {
  39981. owner->handleAsyncUpdate();
  39982. if (! owner->rootItemVisible)
  39983. y += owner->rootItem->itemHeight;
  39984. TreeViewItem* const ti = owner->rootItem->findItemRecursively (y);
  39985. if (ti != 0)
  39986. {
  39987. itemPosition = ti->getItemPosition (false);
  39988. if (! owner->rootItemVisible)
  39989. itemPosition.translate (-owner->getIndentSize(),
  39990. -owner->rootItem->itemHeight);
  39991. }
  39992. return ti;
  39993. }
  39994. return 0;
  39995. }
  39996. #define opennessDefault 0
  39997. #define opennessClosed 1
  39998. #define opennessOpen 2
  39999. TreeViewItem::TreeViewItem()
  40000. : ownerView (0),
  40001. parentItem (0),
  40002. subItems (8),
  40003. y (0),
  40004. itemHeight (0),
  40005. totalHeight (0),
  40006. selected (false),
  40007. redrawNeeded (true),
  40008. drawLinesInside (true),
  40009. openness (opennessDefault)
  40010. {
  40011. static int nextUID = 0;
  40012. uid = nextUID++;
  40013. }
  40014. TreeViewItem::~TreeViewItem()
  40015. {
  40016. }
  40017. const String TreeViewItem::getUniqueName() const
  40018. {
  40019. return String::empty;
  40020. }
  40021. void TreeViewItem::itemOpennessChanged (bool)
  40022. {
  40023. }
  40024. int TreeViewItem::getNumSubItems() const throw()
  40025. {
  40026. return subItems.size();
  40027. }
  40028. TreeViewItem* TreeViewItem::getSubItem (const int index) const throw()
  40029. {
  40030. return subItems [index];
  40031. }
  40032. void TreeViewItem::clearSubItems()
  40033. {
  40034. if (subItems.size() > 0)
  40035. {
  40036. if (ownerView != 0)
  40037. {
  40038. const ScopedLock sl (ownerView->nodeAlterationLock);
  40039. subItems.clear();
  40040. treeHasChanged();
  40041. }
  40042. else
  40043. {
  40044. subItems.clear();
  40045. }
  40046. }
  40047. }
  40048. void TreeViewItem::addSubItem (TreeViewItem* const newItem, const int insertPosition)
  40049. {
  40050. if (newItem != 0)
  40051. {
  40052. newItem->parentItem = this;
  40053. newItem->setOwnerView (ownerView);
  40054. newItem->y = 0;
  40055. newItem->itemHeight = newItem->getItemHeight();
  40056. newItem->totalHeight = 0;
  40057. newItem->itemWidth = newItem->getItemWidth();
  40058. newItem->totalWidth = 0;
  40059. if (ownerView != 0)
  40060. {
  40061. const ScopedLock sl (ownerView->nodeAlterationLock);
  40062. subItems.insert (insertPosition, newItem);
  40063. treeHasChanged();
  40064. if (newItem->isOpen())
  40065. newItem->itemOpennessChanged (true);
  40066. }
  40067. else
  40068. {
  40069. subItems.insert (insertPosition, newItem);
  40070. if (newItem->isOpen())
  40071. newItem->itemOpennessChanged (true);
  40072. }
  40073. }
  40074. }
  40075. void TreeViewItem::removeSubItem (const int index, const bool deleteItem)
  40076. {
  40077. if (ownerView != 0)
  40078. ownerView->nodeAlterationLock.enter();
  40079. if (((unsigned int) index) < (unsigned int) subItems.size())
  40080. {
  40081. subItems.remove (index, deleteItem);
  40082. treeHasChanged();
  40083. }
  40084. if (ownerView != 0)
  40085. ownerView->nodeAlterationLock.exit();
  40086. }
  40087. bool TreeViewItem::isOpen() const throw()
  40088. {
  40089. if (openness == opennessDefault)
  40090. return ownerView != 0 && ownerView->defaultOpenness;
  40091. else
  40092. return openness == opennessOpen;
  40093. }
  40094. void TreeViewItem::setOpen (const bool shouldBeOpen)
  40095. {
  40096. if (isOpen() != shouldBeOpen)
  40097. {
  40098. openness = shouldBeOpen ? opennessOpen
  40099. : opennessClosed;
  40100. treeHasChanged();
  40101. itemOpennessChanged (isOpen());
  40102. }
  40103. }
  40104. bool TreeViewItem::isSelected() const throw()
  40105. {
  40106. return selected;
  40107. }
  40108. void TreeViewItem::deselectAllRecursively()
  40109. {
  40110. setSelected (false, false);
  40111. for (int i = 0; i < subItems.size(); ++i)
  40112. subItems.getUnchecked(i)->deselectAllRecursively();
  40113. }
  40114. void TreeViewItem::setSelected (const bool shouldBeSelected,
  40115. const bool deselectOtherItemsFirst)
  40116. {
  40117. if (deselectOtherItemsFirst)
  40118. getTopLevelItem()->deselectAllRecursively();
  40119. if (shouldBeSelected != selected)
  40120. {
  40121. selected = shouldBeSelected;
  40122. if (ownerView != 0)
  40123. ownerView->repaint();
  40124. itemSelectionChanged (shouldBeSelected);
  40125. }
  40126. }
  40127. void TreeViewItem::paintItem (Graphics&, int, int)
  40128. {
  40129. }
  40130. void TreeViewItem::itemClicked (const MouseEvent&)
  40131. {
  40132. }
  40133. void TreeViewItem::itemDoubleClicked (const MouseEvent&)
  40134. {
  40135. if (mightContainSubItems())
  40136. setOpen (! isOpen());
  40137. }
  40138. void TreeViewItem::itemSelectionChanged (bool)
  40139. {
  40140. }
  40141. const String TreeViewItem::getDragSourceDescription()
  40142. {
  40143. return String::empty;
  40144. }
  40145. const Rectangle TreeViewItem::getItemPosition (const bool relativeToTreeViewTopLeft) const throw()
  40146. {
  40147. const int indentX = getIndentX();
  40148. int width = itemWidth;
  40149. if (ownerView != 0 && width < 0)
  40150. width = ownerView->viewport->getViewWidth() - indentX;
  40151. Rectangle r (indentX, y, jmax (0, width), totalHeight);
  40152. if (relativeToTreeViewTopLeft)
  40153. r.setPosition (r.getX() - ownerView->viewport->getViewPositionX(),
  40154. r.getY() - ownerView->viewport->getViewPositionY());
  40155. return r;
  40156. }
  40157. void TreeViewItem::treeHasChanged() const throw()
  40158. {
  40159. if (ownerView != 0)
  40160. ownerView->itemsChanged();
  40161. }
  40162. void TreeViewItem::updatePositions (int newY)
  40163. {
  40164. y = newY;
  40165. itemHeight = getItemHeight();
  40166. totalHeight = itemHeight;
  40167. itemWidth = getItemWidth();
  40168. totalWidth = jmax (itemWidth, 0);
  40169. if (isOpen())
  40170. {
  40171. const int ourIndent = getIndentX();
  40172. newY += totalHeight;
  40173. for (int i = 0; i < subItems.size(); ++i)
  40174. {
  40175. TreeViewItem* const ti = subItems.getUnchecked(i);
  40176. ti->updatePositions (newY);
  40177. newY += ti->totalHeight;
  40178. totalHeight += ti->totalHeight;
  40179. totalWidth = jmax (totalWidth, ti->totalWidth + ourIndent);
  40180. }
  40181. }
  40182. }
  40183. TreeViewItem* TreeViewItem::getDeepestOpenParentItem() throw()
  40184. {
  40185. TreeViewItem* result = this;
  40186. TreeViewItem* item = this;
  40187. while (item->parentItem != 0)
  40188. {
  40189. item = item->parentItem;
  40190. if (! item->isOpen())
  40191. result = item;
  40192. }
  40193. return result;
  40194. }
  40195. void TreeViewItem::setOwnerView (TreeView* const newOwner) throw()
  40196. {
  40197. ownerView = newOwner;
  40198. for (int i = subItems.size(); --i >= 0;)
  40199. subItems.getUnchecked(i)->setOwnerView (newOwner);
  40200. }
  40201. int TreeViewItem::getIndentX() const throw()
  40202. {
  40203. const int indentWidth = ownerView->getIndentSize();
  40204. int x = indentWidth;
  40205. TreeViewItem* p = parentItem;
  40206. while (p != 0)
  40207. {
  40208. x += indentWidth;
  40209. p = p->parentItem;
  40210. }
  40211. return x;
  40212. }
  40213. void TreeViewItem::paintRecursively (Graphics& g, int width)
  40214. {
  40215. jassert (ownerView != 0);
  40216. if (ownerView == 0)
  40217. return;
  40218. const int indent = getIndentX();
  40219. const int itemW = itemWidth < 0 ? width - indent : itemWidth;
  40220. g.setColour (ownerView->findColour (TreeView::linesColourId));
  40221. const float halfH = itemHeight * 0.5f;
  40222. int depth = 0;
  40223. TreeViewItem* p = parentItem;
  40224. while (p != 0)
  40225. {
  40226. ++depth;
  40227. p = p->parentItem;
  40228. }
  40229. const int indentWidth = ownerView->getIndentSize();
  40230. float x = (depth + 0.5f) * indentWidth;
  40231. if (x > 0)
  40232. {
  40233. if (depth >= 0)
  40234. {
  40235. if (parentItem != 0 && parentItem->drawLinesInside)
  40236. g.drawLine (x, 0, x, isLastOfSiblings() ? halfH : (float) itemHeight);
  40237. if ((parentItem != 0 && parentItem->drawLinesInside)
  40238. || (parentItem == 0 && drawLinesInside))
  40239. g.drawLine (x, halfH, x + indentWidth / 2, halfH);
  40240. }
  40241. p = parentItem;
  40242. int d = depth;
  40243. while (p != 0 && --d >= 0)
  40244. {
  40245. x -= (float) indentWidth;
  40246. if ((p->parentItem == 0 || p->parentItem->drawLinesInside)
  40247. && ! p->isLastOfSiblings())
  40248. {
  40249. g.drawLine (x, 0, x, (float) itemHeight);
  40250. }
  40251. p = p->parentItem;
  40252. }
  40253. if (mightContainSubItems())
  40254. {
  40255. ownerView->getLookAndFeel()
  40256. .drawTreeviewPlusMinusBox (g,
  40257. depth * indentWidth, 0,
  40258. indentWidth, itemHeight,
  40259. ! isOpen());
  40260. }
  40261. }
  40262. {
  40263. g.saveState();
  40264. g.setOrigin (indent, 0);
  40265. if (g.reduceClipRegion (0, 0, itemW, itemHeight))
  40266. paintItem (g, itemW, itemHeight);
  40267. g.restoreState();
  40268. }
  40269. if (isOpen())
  40270. {
  40271. const Rectangle clip (g.getClipBounds());
  40272. for (int i = 0; i < subItems.size(); ++i)
  40273. {
  40274. TreeViewItem* const ti = subItems.getUnchecked(i);
  40275. const int relY = ti->y - y;
  40276. if (relY >= clip.getBottom())
  40277. break;
  40278. if (relY + ti->totalHeight >= clip.getY())
  40279. {
  40280. g.saveState();
  40281. g.setOrigin (0, relY);
  40282. if (g.reduceClipRegion (0, 0, width, ti->totalHeight))
  40283. ti->paintRecursively (g, width);
  40284. g.restoreState();
  40285. }
  40286. }
  40287. }
  40288. }
  40289. bool TreeViewItem::isLastOfSiblings() const throw()
  40290. {
  40291. return parentItem == 0
  40292. || parentItem->subItems.getLast() == this;
  40293. }
  40294. TreeViewItem* TreeViewItem::getTopLevelItem() throw()
  40295. {
  40296. return (parentItem == 0) ? this
  40297. : parentItem->getTopLevelItem();
  40298. }
  40299. int TreeViewItem::getNumRows() const throw()
  40300. {
  40301. int num = 1;
  40302. if (isOpen())
  40303. {
  40304. for (int i = subItems.size(); --i >= 0;)
  40305. num += subItems.getUnchecked(i)->getNumRows();
  40306. }
  40307. return num;
  40308. }
  40309. TreeViewItem* TreeViewItem::getItemOnRow (int index) throw()
  40310. {
  40311. if (index == 0)
  40312. return this;
  40313. if (index > 0 && isOpen())
  40314. {
  40315. --index;
  40316. for (int i = 0; i < subItems.size(); ++i)
  40317. {
  40318. TreeViewItem* const item = subItems.getUnchecked(i);
  40319. if (index == 0)
  40320. return item;
  40321. const int numRows = item->getNumRows();
  40322. if (numRows > index)
  40323. return item->getItemOnRow (index);
  40324. index -= numRows;
  40325. }
  40326. }
  40327. return 0;
  40328. }
  40329. TreeViewItem* TreeViewItem::findItemRecursively (int y) throw()
  40330. {
  40331. if (((unsigned int) y) < (unsigned int) totalHeight)
  40332. {
  40333. const int h = itemHeight;
  40334. if (y < h)
  40335. return this;
  40336. if (isOpen())
  40337. {
  40338. y -= h;
  40339. for (int i = 0; i < subItems.size(); ++i)
  40340. {
  40341. TreeViewItem* const ti = subItems.getUnchecked(i);
  40342. if (ti->totalHeight >= y)
  40343. return ti->findItemRecursively (y);
  40344. y -= ti->totalHeight;
  40345. }
  40346. }
  40347. }
  40348. return 0;
  40349. }
  40350. int TreeViewItem::countSelectedItemsRecursively() const throw()
  40351. {
  40352. int total = 0;
  40353. if (isSelected())
  40354. ++total;
  40355. for (int i = subItems.size(); --i >= 0;)
  40356. total += subItems.getUnchecked(i)->countSelectedItemsRecursively();
  40357. return total;
  40358. }
  40359. TreeViewItem* TreeViewItem::getSelectedItemWithIndex (int index) throw()
  40360. {
  40361. if (isSelected())
  40362. {
  40363. if (index == 0)
  40364. return this;
  40365. --index;
  40366. }
  40367. if (index >= 0)
  40368. {
  40369. for (int i = 0; i < subItems.size(); ++i)
  40370. {
  40371. TreeViewItem* const item = subItems.getUnchecked(i);
  40372. TreeViewItem* const found = item->getSelectedItemWithIndex (index);
  40373. if (found != 0)
  40374. return found;
  40375. index -= item->countSelectedItemsRecursively();
  40376. }
  40377. }
  40378. return 0;
  40379. }
  40380. int TreeViewItem::getRowNumberInTree() const throw()
  40381. {
  40382. if (parentItem != 0 && ownerView != 0)
  40383. {
  40384. int n = 1 + parentItem->getRowNumberInTree();
  40385. int ourIndex = parentItem->subItems.indexOf (this);
  40386. jassert (ourIndex >= 0);
  40387. while (--ourIndex >= 0)
  40388. n += parentItem->subItems [ourIndex]->getNumRows();
  40389. if (parentItem->parentItem == 0
  40390. && ! ownerView->rootItemVisible)
  40391. --n;
  40392. return n;
  40393. }
  40394. else
  40395. {
  40396. return 0;
  40397. }
  40398. }
  40399. void TreeViewItem::setLinesDrawnForSubItems (const bool drawLines) throw()
  40400. {
  40401. drawLinesInside = drawLines;
  40402. }
  40403. TreeViewItem* TreeViewItem::getNextVisibleItem (const bool recurse) const throw()
  40404. {
  40405. if (recurse && isOpen() && subItems.size() > 0)
  40406. return subItems [0];
  40407. if (parentItem != 0)
  40408. {
  40409. const int nextIndex = parentItem->subItems.indexOf (this) + 1;
  40410. if (nextIndex >= parentItem->subItems.size())
  40411. return parentItem->getNextVisibleItem (false);
  40412. return parentItem->subItems [nextIndex];
  40413. }
  40414. return 0;
  40415. }
  40416. void TreeViewItem::restoreFromXml (const XmlElement& e)
  40417. {
  40418. if (e.hasTagName (T("CLOSED")))
  40419. {
  40420. setOpen (false);
  40421. }
  40422. else if (e.hasTagName (T("OPEN")))
  40423. {
  40424. setOpen (true);
  40425. forEachXmlChildElement (e, n)
  40426. {
  40427. const String id (n->getStringAttribute (T("id")));
  40428. for (int i = 0; i < subItems.size(); ++i)
  40429. {
  40430. TreeViewItem* const ti = subItems.getUnchecked(i);
  40431. if (ti->getUniqueName() == id)
  40432. {
  40433. ti->restoreFromXml (*n);
  40434. break;
  40435. }
  40436. }
  40437. }
  40438. }
  40439. }
  40440. XmlElement* TreeViewItem::createXmlOpenness() const
  40441. {
  40442. if (openness != opennessDefault)
  40443. {
  40444. const String name (getUniqueName());
  40445. if (name.isNotEmpty())
  40446. {
  40447. XmlElement* e;
  40448. if (isOpen())
  40449. {
  40450. e = new XmlElement (T("OPEN"));
  40451. for (int i = 0; i < subItems.size(); ++i)
  40452. e->addChildElement (subItems.getUnchecked(i)->createXmlOpenness());
  40453. }
  40454. else
  40455. {
  40456. e = new XmlElement (T("CLOSED"));
  40457. }
  40458. e->setAttribute (T("id"), name);
  40459. return e;
  40460. }
  40461. else
  40462. {
  40463. // trying to save the openness for an element that has no name - this won't
  40464. // work because it needs the names to identify what to open.
  40465. jassertfalse
  40466. }
  40467. }
  40468. return 0;
  40469. }
  40470. END_JUCE_NAMESPACE
  40471. /********* End of inlined file: juce_TreeView.cpp *********/
  40472. /********* Start of inlined file: juce_DirectoryContentsDisplayComponent.cpp *********/
  40473. BEGIN_JUCE_NAMESPACE
  40474. DirectoryContentsDisplayComponent::DirectoryContentsDisplayComponent (DirectoryContentsList& listToShow)
  40475. : fileList (listToShow),
  40476. listeners (2)
  40477. {
  40478. }
  40479. DirectoryContentsDisplayComponent::~DirectoryContentsDisplayComponent()
  40480. {
  40481. }
  40482. FileBrowserListener::~FileBrowserListener()
  40483. {
  40484. }
  40485. void DirectoryContentsDisplayComponent::addListener (FileBrowserListener* const listener) throw()
  40486. {
  40487. jassert (listener != 0);
  40488. if (listener != 0)
  40489. listeners.add (listener);
  40490. }
  40491. void DirectoryContentsDisplayComponent::removeListener (FileBrowserListener* const listener) throw()
  40492. {
  40493. listeners.removeValue (listener);
  40494. }
  40495. void DirectoryContentsDisplayComponent::sendSelectionChangeMessage()
  40496. {
  40497. const ComponentDeletionWatcher deletionWatcher (dynamic_cast <Component*> (this));
  40498. for (int i = listeners.size(); --i >= 0;)
  40499. {
  40500. ((FileBrowserListener*) listeners.getUnchecked (i))->selectionChanged();
  40501. if (deletionWatcher.hasBeenDeleted())
  40502. return;
  40503. i = jmin (i, listeners.size() - 1);
  40504. }
  40505. }
  40506. void DirectoryContentsDisplayComponent::sendMouseClickMessage (const File& file, const MouseEvent& e)
  40507. {
  40508. if (fileList.getDirectory().exists())
  40509. {
  40510. const ComponentDeletionWatcher deletionWatcher (dynamic_cast <Component*> (this));
  40511. for (int i = listeners.size(); --i >= 0;)
  40512. {
  40513. ((FileBrowserListener*) listeners.getUnchecked (i))->fileClicked (file, e);
  40514. if (deletionWatcher.hasBeenDeleted())
  40515. return;
  40516. i = jmin (i, listeners.size() - 1);
  40517. }
  40518. }
  40519. }
  40520. void DirectoryContentsDisplayComponent::sendDoubleClickMessage (const File& file)
  40521. {
  40522. if (fileList.getDirectory().exists())
  40523. {
  40524. const ComponentDeletionWatcher deletionWatcher (dynamic_cast <Component*> (this));
  40525. for (int i = listeners.size(); --i >= 0;)
  40526. {
  40527. ((FileBrowserListener*) listeners.getUnchecked (i))->fileDoubleClicked (file);
  40528. if (deletionWatcher.hasBeenDeleted())
  40529. return;
  40530. i = jmin (i, listeners.size() - 1);
  40531. }
  40532. }
  40533. }
  40534. END_JUCE_NAMESPACE
  40535. /********* End of inlined file: juce_DirectoryContentsDisplayComponent.cpp *********/
  40536. /********* Start of inlined file: juce_DirectoryContentsList.cpp *********/
  40537. BEGIN_JUCE_NAMESPACE
  40538. void* juce_findFileStart (const String& directory, const String& wildCard, String& firstResultFile,
  40539. bool* isDirectory, bool* isHidden, int64* fileSize, Time* modTime,
  40540. Time* creationTime, bool* isReadOnly) throw();
  40541. bool juce_findFileNext (void* handle, String& resultFile,
  40542. bool* isDirectory, bool* isHidden, int64* fileSize,
  40543. Time* modTime, Time* creationTime, bool* isReadOnly) throw();
  40544. void juce_findFileClose (void* handle) throw();
  40545. DirectoryContentsList::DirectoryContentsList (const FileFilter* const fileFilter_,
  40546. TimeSliceThread& thread_)
  40547. : fileFilter (fileFilter_),
  40548. thread (thread_),
  40549. includeDirectories (false),
  40550. includeFiles (false),
  40551. ignoreHiddenFiles (true),
  40552. fileFindHandle (0),
  40553. shouldStop (true)
  40554. {
  40555. }
  40556. DirectoryContentsList::~DirectoryContentsList()
  40557. {
  40558. clear();
  40559. }
  40560. void DirectoryContentsList::setIgnoresHiddenFiles (const bool shouldIgnoreHiddenFiles)
  40561. {
  40562. ignoreHiddenFiles = shouldIgnoreHiddenFiles;
  40563. }
  40564. const File& DirectoryContentsList::getDirectory() const throw()
  40565. {
  40566. return root;
  40567. }
  40568. void DirectoryContentsList::setDirectory (const File& directory,
  40569. const bool includeDirectories_,
  40570. const bool includeFiles_)
  40571. {
  40572. if (directory != root
  40573. || includeDirectories != includeDirectories_
  40574. || includeFiles != includeFiles_)
  40575. {
  40576. clear();
  40577. root = directory;
  40578. includeDirectories = includeDirectories_;
  40579. includeFiles = includeFiles_;
  40580. refresh();
  40581. }
  40582. }
  40583. void DirectoryContentsList::clear()
  40584. {
  40585. shouldStop = true;
  40586. thread.removeTimeSliceClient (this);
  40587. if (fileFindHandle != 0)
  40588. {
  40589. juce_findFileClose (fileFindHandle);
  40590. fileFindHandle = 0;
  40591. }
  40592. if (files.size() > 0)
  40593. {
  40594. files.clear();
  40595. changed();
  40596. }
  40597. }
  40598. void DirectoryContentsList::refresh()
  40599. {
  40600. clear();
  40601. if (root.isDirectory())
  40602. {
  40603. String fileFound;
  40604. bool fileFoundIsDir, isHidden, isReadOnly;
  40605. int64 fileSize;
  40606. Time modTime, creationTime;
  40607. String path (root.getFullPathName());
  40608. if (! path.endsWithChar (File::separator))
  40609. path += File::separator;
  40610. jassert (fileFindHandle == 0);
  40611. fileFindHandle = juce_findFileStart (path, T("*"), fileFound,
  40612. &fileFoundIsDir,
  40613. &isHidden,
  40614. &fileSize,
  40615. &modTime,
  40616. &creationTime,
  40617. &isReadOnly);
  40618. if (fileFindHandle != 0 && fileFound.isNotEmpty())
  40619. {
  40620. if (addFile (fileFound, fileFoundIsDir, isHidden,
  40621. fileSize, modTime, creationTime, isReadOnly))
  40622. {
  40623. changed();
  40624. }
  40625. }
  40626. shouldStop = false;
  40627. thread.addTimeSliceClient (this);
  40628. }
  40629. }
  40630. int DirectoryContentsList::getNumFiles() const
  40631. {
  40632. return files.size();
  40633. }
  40634. bool DirectoryContentsList::getFileInfo (const int index,
  40635. FileInfo& result) const
  40636. {
  40637. const ScopedLock sl (fileListLock);
  40638. const FileInfo* const info = files [index];
  40639. if (info != 0)
  40640. {
  40641. result = *info;
  40642. return true;
  40643. }
  40644. return false;
  40645. }
  40646. const File DirectoryContentsList::getFile (const int index) const
  40647. {
  40648. const ScopedLock sl (fileListLock);
  40649. const FileInfo* const info = files [index];
  40650. if (info != 0)
  40651. return root.getChildFile (info->filename);
  40652. return File::nonexistent;
  40653. }
  40654. bool DirectoryContentsList::isStillLoading() const
  40655. {
  40656. return fileFindHandle != 0;
  40657. }
  40658. void DirectoryContentsList::changed()
  40659. {
  40660. sendChangeMessage (this);
  40661. }
  40662. bool DirectoryContentsList::useTimeSlice()
  40663. {
  40664. const uint32 startTime = Time::getApproximateMillisecondCounter();
  40665. bool hasChanged = false;
  40666. for (int i = 100; --i >= 0;)
  40667. {
  40668. if (! checkNextFile (hasChanged))
  40669. {
  40670. if (hasChanged)
  40671. changed();
  40672. return false;
  40673. }
  40674. if (shouldStop || (Time::getApproximateMillisecondCounter() > startTime + 150))
  40675. break;
  40676. }
  40677. if (hasChanged)
  40678. changed();
  40679. return true;
  40680. }
  40681. bool DirectoryContentsList::checkNextFile (bool& hasChanged)
  40682. {
  40683. if (fileFindHandle != 0)
  40684. {
  40685. String fileFound;
  40686. bool fileFoundIsDir, isHidden, isReadOnly;
  40687. int64 fileSize;
  40688. Time modTime, creationTime;
  40689. if (juce_findFileNext (fileFindHandle, fileFound,
  40690. &fileFoundIsDir, &isHidden,
  40691. &fileSize,
  40692. &modTime,
  40693. &creationTime,
  40694. &isReadOnly))
  40695. {
  40696. if (addFile (fileFound, fileFoundIsDir, isHidden, fileSize,
  40697. modTime, creationTime, isReadOnly))
  40698. {
  40699. hasChanged = true;
  40700. }
  40701. return true;
  40702. }
  40703. else
  40704. {
  40705. juce_findFileClose (fileFindHandle);
  40706. fileFindHandle = 0;
  40707. }
  40708. }
  40709. return false;
  40710. }
  40711. int DirectoryContentsList::compareElements (const DirectoryContentsList::FileInfo* const first,
  40712. const DirectoryContentsList::FileInfo* const second) throw()
  40713. {
  40714. #if JUCE_WIN32
  40715. if (first->isDirectory != second->isDirectory)
  40716. return first->isDirectory ? -1 : 1;
  40717. #endif
  40718. return first->filename.compareIgnoreCase (second->filename);
  40719. }
  40720. bool DirectoryContentsList::addFile (const String& filename,
  40721. const bool isDir,
  40722. const bool isHidden,
  40723. const int64 fileSize,
  40724. const Time& modTime,
  40725. const Time& creationTime,
  40726. const bool isReadOnly)
  40727. {
  40728. if (filename == T("..")
  40729. || filename == T(".")
  40730. || (ignoreHiddenFiles && isHidden))
  40731. return false;
  40732. const File file (root.getChildFile (filename));
  40733. if (((isDir && includeDirectories) || ((! isDir) && includeFiles))
  40734. && (fileFilter == 0
  40735. || ((! isDir) && fileFilter->isFileSuitable (file))
  40736. || (isDir && fileFilter->isDirectorySuitable (file))))
  40737. {
  40738. FileInfo* const info = new FileInfo();
  40739. info->filename = filename;
  40740. info->fileSize = fileSize;
  40741. info->modificationTime = modTime;
  40742. info->creationTime = creationTime;
  40743. info->isDirectory = isDir;
  40744. info->isReadOnly = isReadOnly;
  40745. const ScopedLock sl (fileListLock);
  40746. for (int i = files.size(); --i >= 0;)
  40747. {
  40748. if (files.getUnchecked(i)->filename == info->filename)
  40749. {
  40750. delete info;
  40751. return false;
  40752. }
  40753. }
  40754. files.addSorted (*this, info);
  40755. return true;
  40756. }
  40757. return false;
  40758. }
  40759. END_JUCE_NAMESPACE
  40760. /********* End of inlined file: juce_DirectoryContentsList.cpp *********/
  40761. /********* Start of inlined file: juce_FileBrowserComponent.cpp *********/
  40762. BEGIN_JUCE_NAMESPACE
  40763. class DirectoriesOnlyFilter : public FileFilter
  40764. {
  40765. public:
  40766. DirectoriesOnlyFilter() : FileFilter (String::empty) {}
  40767. bool isFileSuitable (const File&) const { return false; }
  40768. bool isDirectorySuitable (const File&) const { return true; }
  40769. };
  40770. FileBrowserComponent::FileBrowserComponent (FileChooserMode mode_,
  40771. const File& initialFileOrDirectory,
  40772. const FileFilter* fileFilter,
  40773. FilePreviewComponent* previewComp_,
  40774. const bool useTreeView,
  40775. const bool filenameTextBoxIsReadOnly)
  40776. : directoriesOnlyFilter (0),
  40777. mode (mode_),
  40778. listeners (2),
  40779. previewComp (previewComp_),
  40780. thread ("Juce FileBrowser")
  40781. {
  40782. String filename;
  40783. if (initialFileOrDirectory == File::nonexistent)
  40784. {
  40785. currentRoot = File::getCurrentWorkingDirectory();
  40786. }
  40787. else if (initialFileOrDirectory.isDirectory())
  40788. {
  40789. currentRoot = initialFileOrDirectory;
  40790. }
  40791. else
  40792. {
  40793. currentRoot = initialFileOrDirectory.getParentDirectory();
  40794. filename = initialFileOrDirectory.getFileName();
  40795. }
  40796. if (mode_ == chooseDirectoryMode)
  40797. fileFilter = directoriesOnlyFilter = new DirectoriesOnlyFilter();
  40798. fileList = new DirectoryContentsList (fileFilter, thread);
  40799. if (useTreeView)
  40800. {
  40801. FileTreeComponent* const tree = new FileTreeComponent (*fileList);
  40802. addAndMakeVisible (tree);
  40803. fileListComponent = tree;
  40804. }
  40805. else
  40806. {
  40807. FileListComponent* const list = new FileListComponent (*fileList);
  40808. list->setOutlineThickness (1);
  40809. addAndMakeVisible (list);
  40810. fileListComponent = list;
  40811. }
  40812. fileListComponent->addListener (this);
  40813. addAndMakeVisible (currentPathBox = new ComboBox ("path"));
  40814. currentPathBox->setEditableText (true);
  40815. StringArray rootNames, rootPaths;
  40816. const BitArray separators (getRoots (rootNames, rootPaths));
  40817. for (int i = 0; i < rootNames.size(); ++i)
  40818. {
  40819. if (separators [i])
  40820. currentPathBox->addSeparator();
  40821. currentPathBox->addItem (rootNames[i], i + 1);
  40822. }
  40823. currentPathBox->addSeparator();
  40824. currentPathBox->addListener (this);
  40825. addAndMakeVisible (filenameBox = new TextEditor());
  40826. filenameBox->setMultiLine (false);
  40827. filenameBox->setSelectAllWhenFocused (true);
  40828. filenameBox->setText (filename, false);
  40829. filenameBox->addListener (this);
  40830. filenameBox->setReadOnly (filenameTextBoxIsReadOnly);
  40831. Label* label = new Label ("f", (mode == chooseDirectoryMode) ? TRANS("folder:")
  40832. : TRANS("file:"));
  40833. addAndMakeVisible (label);
  40834. label->attachToComponent (filenameBox, true);
  40835. addAndMakeVisible (goUpButton = getLookAndFeel().createFileBrowserGoUpButton());
  40836. goUpButton->addButtonListener (this);
  40837. goUpButton->setTooltip (TRANS ("go up to parent directory"));
  40838. if (previewComp != 0)
  40839. addAndMakeVisible (previewComp);
  40840. setRoot (currentRoot);
  40841. thread.startThread (4);
  40842. }
  40843. FileBrowserComponent::~FileBrowserComponent()
  40844. {
  40845. if (previewComp != 0)
  40846. removeChildComponent (previewComp);
  40847. deleteAllChildren();
  40848. deleteAndZero (fileList);
  40849. delete directoriesOnlyFilter;
  40850. thread.stopThread (10000);
  40851. }
  40852. void FileBrowserComponent::addListener (FileBrowserListener* const newListener) throw()
  40853. {
  40854. jassert (newListener != 0)
  40855. if (newListener != 0)
  40856. listeners.add (newListener);
  40857. }
  40858. void FileBrowserComponent::removeListener (FileBrowserListener* const listener) throw()
  40859. {
  40860. listeners.removeValue (listener);
  40861. }
  40862. const File FileBrowserComponent::getCurrentFile() const throw()
  40863. {
  40864. return currentRoot.getChildFile (filenameBox->getText());
  40865. }
  40866. bool FileBrowserComponent::currentFileIsValid() const
  40867. {
  40868. if (mode == saveFileMode)
  40869. return ! getCurrentFile().isDirectory();
  40870. else if (mode == loadFileMode)
  40871. return getCurrentFile().existsAsFile();
  40872. else if (mode == chooseDirectoryMode)
  40873. return getCurrentFile().isDirectory();
  40874. jassertfalse
  40875. return false;
  40876. }
  40877. const File FileBrowserComponent::getRoot() const
  40878. {
  40879. return currentRoot;
  40880. }
  40881. void FileBrowserComponent::setRoot (const File& newRootDirectory)
  40882. {
  40883. if (currentRoot != newRootDirectory)
  40884. {
  40885. fileListComponent->scrollToTop();
  40886. if (mode == chooseDirectoryMode)
  40887. filenameBox->setText (String::empty, false);
  40888. String path (newRootDirectory.getFullPathName());
  40889. if (path.isEmpty())
  40890. path += File::separator;
  40891. StringArray rootNames, rootPaths;
  40892. getRoots (rootNames, rootPaths);
  40893. if (! rootPaths.contains (path, true))
  40894. {
  40895. bool alreadyListed = false;
  40896. for (int i = currentPathBox->getNumItems(); --i >= 0;)
  40897. {
  40898. if (currentPathBox->getItemText (i).equalsIgnoreCase (path))
  40899. {
  40900. alreadyListed = true;
  40901. break;
  40902. }
  40903. }
  40904. if (! alreadyListed)
  40905. currentPathBox->addItem (path, currentPathBox->getNumItems() + 2);
  40906. }
  40907. }
  40908. currentRoot = newRootDirectory;
  40909. fileList->setDirectory (currentRoot, true, true);
  40910. String currentRootName (currentRoot.getFullPathName());
  40911. if (currentRootName.isEmpty())
  40912. currentRootName += File::separator;
  40913. currentPathBox->setText (currentRootName, true);
  40914. goUpButton->setEnabled (currentRoot.getParentDirectory().isDirectory()
  40915. && currentRoot.getParentDirectory() != currentRoot);
  40916. }
  40917. void FileBrowserComponent::goUp()
  40918. {
  40919. setRoot (getRoot().getParentDirectory());
  40920. }
  40921. void FileBrowserComponent::refresh()
  40922. {
  40923. fileList->refresh();
  40924. }
  40925. const String FileBrowserComponent::getActionVerb() const
  40926. {
  40927. return (mode == chooseDirectoryMode) ? TRANS("Choose")
  40928. : ((mode == saveFileMode) ? TRANS("Save") : TRANS("Open"));
  40929. }
  40930. FilePreviewComponent* FileBrowserComponent::getPreviewComponent() const throw()
  40931. {
  40932. return previewComp;
  40933. }
  40934. void FileBrowserComponent::resized()
  40935. {
  40936. getLookAndFeel()
  40937. .layoutFileBrowserComponent (*this, fileListComponent,
  40938. previewComp, currentPathBox,
  40939. filenameBox, goUpButton);
  40940. }
  40941. void FileBrowserComponent::sendListenerChangeMessage()
  40942. {
  40943. ComponentDeletionWatcher deletionWatcher (this);
  40944. if (previewComp != 0)
  40945. previewComp->selectedFileChanged (getCurrentFile());
  40946. jassert (! deletionWatcher.hasBeenDeleted());
  40947. for (int i = listeners.size(); --i >= 0;)
  40948. {
  40949. ((FileBrowserListener*) listeners.getUnchecked (i))->selectionChanged();
  40950. if (deletionWatcher.hasBeenDeleted())
  40951. return;
  40952. i = jmin (i, listeners.size() - 1);
  40953. }
  40954. }
  40955. void FileBrowserComponent::selectionChanged()
  40956. {
  40957. const File selected (fileListComponent->getSelectedFile());
  40958. if ((mode == chooseDirectoryMode && selected.isDirectory())
  40959. || selected.existsAsFile())
  40960. {
  40961. filenameBox->setText (selected.getRelativePathFrom (getRoot()), false);
  40962. }
  40963. sendListenerChangeMessage();
  40964. }
  40965. void FileBrowserComponent::fileClicked (const File& f, const MouseEvent& e)
  40966. {
  40967. ComponentDeletionWatcher deletionWatcher (this);
  40968. for (int i = listeners.size(); --i >= 0;)
  40969. {
  40970. ((FileBrowserListener*) listeners.getUnchecked (i))->fileClicked (f, e);
  40971. if (deletionWatcher.hasBeenDeleted())
  40972. return;
  40973. i = jmin (i, listeners.size() - 1);
  40974. }
  40975. }
  40976. void FileBrowserComponent::fileDoubleClicked (const File& f)
  40977. {
  40978. if (f.isDirectory())
  40979. {
  40980. setRoot (f);
  40981. }
  40982. else
  40983. {
  40984. ComponentDeletionWatcher deletionWatcher (this);
  40985. for (int i = listeners.size(); --i >= 0;)
  40986. {
  40987. ((FileBrowserListener*) listeners.getUnchecked (i))->fileDoubleClicked (f);
  40988. if (deletionWatcher.hasBeenDeleted())
  40989. return;
  40990. i = jmin (i, listeners.size() - 1);
  40991. }
  40992. }
  40993. }
  40994. void FileBrowserComponent::textEditorTextChanged (TextEditor&)
  40995. {
  40996. sendListenerChangeMessage();
  40997. }
  40998. void FileBrowserComponent::textEditorReturnKeyPressed (TextEditor&)
  40999. {
  41000. if (filenameBox->getText().containsChar (File::separator))
  41001. {
  41002. const File f (currentRoot.getChildFile (filenameBox->getText()));
  41003. if (f.isDirectory())
  41004. {
  41005. setRoot (f);
  41006. filenameBox->setText (String::empty);
  41007. }
  41008. else
  41009. {
  41010. setRoot (f.getParentDirectory());
  41011. filenameBox->setText (f.getFileName());
  41012. }
  41013. }
  41014. else
  41015. {
  41016. fileDoubleClicked (getCurrentFile());
  41017. }
  41018. }
  41019. void FileBrowserComponent::textEditorEscapeKeyPressed (TextEditor&)
  41020. {
  41021. }
  41022. void FileBrowserComponent::textEditorFocusLost (TextEditor&)
  41023. {
  41024. if (mode != saveFileMode)
  41025. selectionChanged();
  41026. }
  41027. void FileBrowserComponent::buttonClicked (Button*)
  41028. {
  41029. goUp();
  41030. }
  41031. void FileBrowserComponent::comboBoxChanged (ComboBox*)
  41032. {
  41033. const String newText (currentPathBox->getText().trim().unquoted());
  41034. if (newText.isNotEmpty())
  41035. {
  41036. const int index = currentPathBox->getSelectedId() - 1;
  41037. StringArray rootNames, rootPaths;
  41038. getRoots (rootNames, rootPaths);
  41039. if (rootPaths [index].isNotEmpty())
  41040. {
  41041. setRoot (File (rootPaths [index]));
  41042. }
  41043. else
  41044. {
  41045. File f (newText);
  41046. for (;;)
  41047. {
  41048. if (f.isDirectory())
  41049. {
  41050. setRoot (f);
  41051. break;
  41052. }
  41053. if (f.getParentDirectory() == f)
  41054. break;
  41055. f = f.getParentDirectory();
  41056. }
  41057. }
  41058. }
  41059. }
  41060. const BitArray FileBrowserComponent::getRoots (StringArray& rootNames, StringArray& rootPaths)
  41061. {
  41062. BitArray separators;
  41063. #if JUCE_WIN32
  41064. OwnedArray<File> roots;
  41065. File::findFileSystemRoots (roots);
  41066. rootPaths.clear();
  41067. for (int i = 0; i < roots.size(); ++i)
  41068. {
  41069. const File* const drive = roots.getUnchecked(i);
  41070. String name (drive->getFullPathName());
  41071. rootPaths.add (name);
  41072. if (drive->isOnHardDisk())
  41073. {
  41074. String volume (drive->getVolumeLabel());
  41075. if (volume.isEmpty())
  41076. volume = TRANS("Hard Drive");
  41077. name << " [" << drive->getVolumeLabel() << ']';
  41078. }
  41079. else if (drive->isOnCDRomDrive())
  41080. {
  41081. name << TRANS(" [CD/DVD drive]");
  41082. }
  41083. rootNames.add (name);
  41084. }
  41085. separators.setBit (rootPaths.size());
  41086. rootPaths.add (File::getSpecialLocation (File::userDocumentsDirectory).getFullPathName());
  41087. rootNames.add ("Documents");
  41088. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  41089. rootNames.add ("Desktop");
  41090. #endif
  41091. #if JUCE_MAC
  41092. rootPaths.add (File::getSpecialLocation (File::userHomeDirectory).getFullPathName());
  41093. rootNames.add ("Home folder");
  41094. rootPaths.add (File::getSpecialLocation (File::userDocumentsDirectory).getFullPathName());
  41095. rootNames.add ("Documents");
  41096. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  41097. rootNames.add ("Desktop");
  41098. separators.setBit (rootPaths.size());
  41099. OwnedArray <File> volumes;
  41100. File vol ("/Volumes");
  41101. vol.findChildFiles (volumes, File::findDirectories, false);
  41102. for (int i = 0; i < volumes.size(); ++i)
  41103. {
  41104. const File* const volume = volumes.getUnchecked(i);
  41105. if (volume->isDirectory() && ! volume->getFileName().startsWithChar (T('.')))
  41106. {
  41107. rootPaths.add (volume->getFullPathName());
  41108. rootNames.add (volume->getFileName());
  41109. }
  41110. }
  41111. #endif
  41112. #if JUCE_LINUX
  41113. rootPaths.add ("/");
  41114. rootNames.add ("/");
  41115. rootPaths.add (File::getSpecialLocation (File::userHomeDirectory).getFullPathName());
  41116. rootNames.add ("Home folder");
  41117. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  41118. rootNames.add ("Desktop");
  41119. #endif
  41120. return separators;
  41121. }
  41122. END_JUCE_NAMESPACE
  41123. /********* End of inlined file: juce_FileBrowserComponent.cpp *********/
  41124. /********* Start of inlined file: juce_FileChooser.cpp *********/
  41125. BEGIN_JUCE_NAMESPACE
  41126. FileChooser::FileChooser (const String& chooserBoxTitle,
  41127. const File& currentFileOrDirectory,
  41128. const String& fileFilters,
  41129. const bool useNativeDialogBox_)
  41130. : title (chooserBoxTitle),
  41131. filters (fileFilters),
  41132. startingFile (currentFileOrDirectory),
  41133. useNativeDialogBox (useNativeDialogBox_)
  41134. {
  41135. #if JUCE_LINUX
  41136. useNativeDialogBox = false;
  41137. #endif
  41138. if (fileFilters.trim().isEmpty())
  41139. filters = T("*");
  41140. }
  41141. FileChooser::~FileChooser()
  41142. {
  41143. }
  41144. bool FileChooser::browseForFileToOpen (FilePreviewComponent* previewComponent)
  41145. {
  41146. return showDialog (false, false, false, false, previewComponent);
  41147. }
  41148. bool FileChooser::browseForMultipleFilesToOpen (FilePreviewComponent* previewComponent)
  41149. {
  41150. return showDialog (false, false, false, true, previewComponent);
  41151. }
  41152. bool FileChooser::browseForFileToSave (const bool warnAboutOverwritingExistingFiles)
  41153. {
  41154. return showDialog (false, true, warnAboutOverwritingExistingFiles, false, 0);
  41155. }
  41156. bool FileChooser::browseForDirectory()
  41157. {
  41158. return showDialog (true, false, false, false, 0);
  41159. }
  41160. const File FileChooser::getResult() const
  41161. {
  41162. // if you've used a multiple-file select, you should use the getResults() method
  41163. // to retrieve all the files that were chosen.
  41164. jassert (results.size() <= 1);
  41165. const File* const f = results.getFirst();
  41166. if (f != 0)
  41167. return *f;
  41168. return File::nonexistent;
  41169. }
  41170. const OwnedArray <File>& FileChooser::getResults() const
  41171. {
  41172. return results;
  41173. }
  41174. bool FileChooser::showDialog (const bool isDirectory,
  41175. const bool isSave,
  41176. const bool warnAboutOverwritingExistingFiles,
  41177. const bool selectMultipleFiles,
  41178. FilePreviewComponent* const previewComponent)
  41179. {
  41180. ComponentDeletionWatcher* currentlyFocusedChecker = 0;
  41181. Component* const currentlyFocused = Component::getCurrentlyFocusedComponent();
  41182. if (currentlyFocused != 0)
  41183. currentlyFocusedChecker = new ComponentDeletionWatcher (currentlyFocused);
  41184. results.clear();
  41185. // the preview component needs to be the right size before you pass it in here..
  41186. jassert (previewComponent == 0 || (previewComponent->getWidth() > 10
  41187. && previewComponent->getHeight() > 10));
  41188. #if JUCE_WIN32
  41189. if (useNativeDialogBox)
  41190. #else
  41191. if (useNativeDialogBox && (previewComponent == 0))
  41192. #endif
  41193. {
  41194. showPlatformDialog (results, title, startingFile, filters,
  41195. isDirectory, isSave,
  41196. warnAboutOverwritingExistingFiles,
  41197. selectMultipleFiles,
  41198. previewComponent);
  41199. }
  41200. else
  41201. {
  41202. jassert (! selectMultipleFiles); // not yet implemented for juce dialogs!
  41203. WildcardFileFilter wildcard (filters, String::empty);
  41204. FileBrowserComponent browserComponent (isDirectory ? FileBrowserComponent::chooseDirectoryMode
  41205. : (isSave ? FileBrowserComponent::saveFileMode
  41206. : FileBrowserComponent::loadFileMode),
  41207. startingFile, &wildcard, previewComponent);
  41208. FileChooserDialogBox box (title, String::empty,
  41209. browserComponent,
  41210. warnAboutOverwritingExistingFiles,
  41211. browserComponent.findColour (AlertWindow::backgroundColourId));
  41212. if (box.show())
  41213. results.add (new File (browserComponent.getCurrentFile()));
  41214. }
  41215. if (currentlyFocused != 0 && ! currentlyFocusedChecker->hasBeenDeleted())
  41216. currentlyFocused->grabKeyboardFocus();
  41217. delete currentlyFocusedChecker;
  41218. return results.size() > 0;
  41219. }
  41220. FilePreviewComponent::FilePreviewComponent()
  41221. {
  41222. }
  41223. FilePreviewComponent::~FilePreviewComponent()
  41224. {
  41225. }
  41226. END_JUCE_NAMESPACE
  41227. /********* End of inlined file: juce_FileChooser.cpp *********/
  41228. /********* Start of inlined file: juce_FileChooserDialogBox.cpp *********/
  41229. BEGIN_JUCE_NAMESPACE
  41230. FileChooserDialogBox::FileChooserDialogBox (const String& name,
  41231. const String& instructions,
  41232. FileBrowserComponent& chooserComponent,
  41233. const bool warnAboutOverwritingExistingFiles_,
  41234. const Colour& backgroundColour)
  41235. : ResizableWindow (name, backgroundColour, true),
  41236. warnAboutOverwritingExistingFiles (warnAboutOverwritingExistingFiles_)
  41237. {
  41238. content = new ContentComponent();
  41239. content->setName (name);
  41240. content->instructions = instructions;
  41241. content->chooserComponent = &chooserComponent;
  41242. content->addAndMakeVisible (&chooserComponent);
  41243. content->okButton = new TextButton (chooserComponent.getActionVerb());
  41244. content->addAndMakeVisible (content->okButton);
  41245. content->okButton->addButtonListener (this);
  41246. content->okButton->setEnabled (chooserComponent.currentFileIsValid());
  41247. content->okButton->addShortcut (KeyPress (KeyPress::returnKey, 0, 0));
  41248. content->cancelButton = new TextButton (TRANS("Cancel"));
  41249. content->addAndMakeVisible (content->cancelButton);
  41250. content->cancelButton->addButtonListener (this);
  41251. content->cancelButton->addShortcut (KeyPress (KeyPress::escapeKey, 0, 0));
  41252. setContentComponent (content);
  41253. setResizable (true, true);
  41254. setResizeLimits (300, 300, 1200, 1000);
  41255. content->chooserComponent->addListener (this);
  41256. }
  41257. FileChooserDialogBox::~FileChooserDialogBox()
  41258. {
  41259. content->chooserComponent->removeListener (this);
  41260. }
  41261. bool FileChooserDialogBox::show (int w, int h)
  41262. {
  41263. if (w <= 0)
  41264. {
  41265. Component* const previewComp = content->chooserComponent->getPreviewComponent();
  41266. if (previewComp != 0)
  41267. w = 400 + previewComp->getWidth();
  41268. else
  41269. w = 600;
  41270. }
  41271. if (h <= 0)
  41272. h = 500;
  41273. centreWithSize (w, h);
  41274. const bool ok = (runModalLoop() != 0);
  41275. setVisible (false);
  41276. return ok;
  41277. }
  41278. void FileChooserDialogBox::buttonClicked (Button* button)
  41279. {
  41280. if (button == content->okButton)
  41281. {
  41282. if (warnAboutOverwritingExistingFiles
  41283. && content->chooserComponent->getMode() == FileBrowserComponent::saveFileMode
  41284. && content->chooserComponent->getCurrentFile().exists())
  41285. {
  41286. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  41287. TRANS("File already exists"),
  41288. TRANS("There's already a file called:\n\n")
  41289. + content->chooserComponent->getCurrentFile().getFullPathName()
  41290. + T("\n\nAre you sure you want to overwrite it?"),
  41291. TRANS("overwrite"),
  41292. TRANS("cancel")))
  41293. {
  41294. return;
  41295. }
  41296. }
  41297. exitModalState (1);
  41298. }
  41299. else if (button == content->cancelButton)
  41300. closeButtonPressed();
  41301. }
  41302. void FileChooserDialogBox::closeButtonPressed()
  41303. {
  41304. setVisible (false);
  41305. }
  41306. void FileChooserDialogBox::selectionChanged()
  41307. {
  41308. content->okButton->setEnabled (content->chooserComponent->currentFileIsValid());
  41309. }
  41310. void FileChooserDialogBox::fileClicked (const File&, const MouseEvent&)
  41311. {
  41312. }
  41313. void FileChooserDialogBox::fileDoubleClicked (const File&)
  41314. {
  41315. selectionChanged();
  41316. content->okButton->triggerClick();
  41317. }
  41318. FileChooserDialogBox::ContentComponent::ContentComponent()
  41319. {
  41320. setInterceptsMouseClicks (false, true);
  41321. }
  41322. FileChooserDialogBox::ContentComponent::~ContentComponent()
  41323. {
  41324. delete okButton;
  41325. delete cancelButton;
  41326. }
  41327. void FileChooserDialogBox::ContentComponent::paint (Graphics& g)
  41328. {
  41329. g.setColour (Colours::black);
  41330. text.draw (g);
  41331. }
  41332. void FileChooserDialogBox::ContentComponent::resized()
  41333. {
  41334. getLookAndFeel().createFileChooserHeaderText (getName(), instructions, text, getWidth());
  41335. float left, top, right, bottom;
  41336. text.getBoundingBox (0, text.getNumGlyphs(), left, top, right, bottom, false);
  41337. const int y = roundFloatToInt (bottom) + 10;
  41338. const int buttonHeight = 26;
  41339. const int buttonY = getHeight() - buttonHeight - 8;
  41340. chooserComponent->setBounds (0, y, getWidth(), buttonY - y - 20);
  41341. okButton->setBounds (proportionOfWidth (0.25f), buttonY,
  41342. proportionOfWidth (0.2f), buttonHeight);
  41343. cancelButton->setBounds (proportionOfWidth (0.55f), buttonY,
  41344. proportionOfWidth (0.2f), buttonHeight);
  41345. }
  41346. END_JUCE_NAMESPACE
  41347. /********* End of inlined file: juce_FileChooserDialogBox.cpp *********/
  41348. /********* Start of inlined file: juce_FileFilter.cpp *********/
  41349. BEGIN_JUCE_NAMESPACE
  41350. FileFilter::FileFilter (const String& filterDescription)
  41351. : description (filterDescription)
  41352. {
  41353. }
  41354. FileFilter::~FileFilter()
  41355. {
  41356. }
  41357. const String& FileFilter::getDescription() const throw()
  41358. {
  41359. return description;
  41360. }
  41361. END_JUCE_NAMESPACE
  41362. /********* End of inlined file: juce_FileFilter.cpp *********/
  41363. /********* Start of inlined file: juce_FileListComponent.cpp *********/
  41364. BEGIN_JUCE_NAMESPACE
  41365. Image* juce_createIconForFile (const File& file);
  41366. FileListComponent::FileListComponent (DirectoryContentsList& listToShow)
  41367. : DirectoryContentsDisplayComponent (listToShow),
  41368. ListBox (String::empty, 0)
  41369. {
  41370. setModel (this);
  41371. fileList.addChangeListener (this);
  41372. }
  41373. FileListComponent::~FileListComponent()
  41374. {
  41375. fileList.removeChangeListener (this);
  41376. deleteAllChildren();
  41377. }
  41378. const File FileListComponent::getSelectedFile() const
  41379. {
  41380. return fileList.getFile (getSelectedRow());
  41381. }
  41382. void FileListComponent::scrollToTop()
  41383. {
  41384. getVerticalScrollBar()->setCurrentRangeStart (0);
  41385. }
  41386. void FileListComponent::changeListenerCallback (void*)
  41387. {
  41388. updateContent();
  41389. }
  41390. class FileListItemComponent : public Component,
  41391. public TimeSliceClient,
  41392. public AsyncUpdater
  41393. {
  41394. public:
  41395. FileListItemComponent (FileListComponent& owner_,
  41396. TimeSliceThread& thread_) throw()
  41397. : owner (owner_),
  41398. thread (thread_),
  41399. icon (0)
  41400. {
  41401. }
  41402. ~FileListItemComponent() throw()
  41403. {
  41404. thread.removeTimeSliceClient (this);
  41405. clearIcon();
  41406. }
  41407. void paint (Graphics& g)
  41408. {
  41409. getLookAndFeel().drawFileBrowserRow (g, getWidth(), getHeight(),
  41410. file.getFileName(),
  41411. icon,
  41412. fileSize, modTime,
  41413. isDirectory, highlighted,
  41414. index);
  41415. }
  41416. void mouseDown (const MouseEvent& e)
  41417. {
  41418. owner.selectRowsBasedOnModifierKeys (index, e.mods);
  41419. owner.sendMouseClickMessage (file, e);
  41420. }
  41421. void mouseDoubleClick (const MouseEvent&)
  41422. {
  41423. owner.sendDoubleClickMessage (file);
  41424. }
  41425. void update (const File& root,
  41426. const DirectoryContentsList::FileInfo* const fileInfo,
  41427. const int index_,
  41428. const bool highlighted_) throw()
  41429. {
  41430. thread.removeTimeSliceClient (this);
  41431. if (highlighted_ != highlighted
  41432. || index_ != index)
  41433. {
  41434. index = index_;
  41435. highlighted = highlighted_;
  41436. repaint();
  41437. }
  41438. File newFile;
  41439. String newFileSize;
  41440. String newModTime;
  41441. if (fileInfo != 0)
  41442. {
  41443. newFile = root.getChildFile (fileInfo->filename);
  41444. newFileSize = File::descriptionOfSizeInBytes (fileInfo->fileSize);
  41445. newModTime = fileInfo->modificationTime.formatted (T("%d %b '%y %H:%M"));
  41446. }
  41447. if (newFile != file
  41448. || fileSize != newFileSize
  41449. || modTime != newModTime)
  41450. {
  41451. file = newFile;
  41452. fileSize = newFileSize;
  41453. modTime = newModTime;
  41454. isDirectory = fileInfo != 0 && fileInfo->isDirectory;
  41455. repaint();
  41456. clearIcon();
  41457. }
  41458. if (file != File::nonexistent
  41459. && icon == 0 && ! isDirectory)
  41460. {
  41461. updateIcon (true);
  41462. if (icon == 0)
  41463. thread.addTimeSliceClient (this);
  41464. }
  41465. }
  41466. bool useTimeSlice()
  41467. {
  41468. updateIcon (false);
  41469. return false;
  41470. }
  41471. void handleAsyncUpdate()
  41472. {
  41473. repaint();
  41474. }
  41475. juce_UseDebuggingNewOperator
  41476. private:
  41477. FileListComponent& owner;
  41478. TimeSliceThread& thread;
  41479. bool highlighted;
  41480. int index;
  41481. File file;
  41482. String fileSize;
  41483. String modTime;
  41484. Image* icon;
  41485. bool isDirectory;
  41486. void clearIcon() throw()
  41487. {
  41488. ImageCache::release (icon);
  41489. icon = 0;
  41490. }
  41491. void updateIcon (const bool onlyUpdateIfCached) throw()
  41492. {
  41493. if (icon == 0)
  41494. {
  41495. const int hashCode = (file.getFullPathName() + T("_iconCacheSalt")).hashCode();
  41496. Image* im = ImageCache::getFromHashCode (hashCode);
  41497. if (im == 0 && ! onlyUpdateIfCached)
  41498. {
  41499. im = juce_createIconForFile (file);
  41500. if (im != 0)
  41501. ImageCache::addImageToCache (im, hashCode);
  41502. }
  41503. if (im != 0)
  41504. {
  41505. icon = im;
  41506. triggerAsyncUpdate();
  41507. }
  41508. }
  41509. }
  41510. };
  41511. int FileListComponent::getNumRows()
  41512. {
  41513. return fileList.getNumFiles();
  41514. }
  41515. void FileListComponent::paintListBoxItem (int, Graphics&, int, int, bool)
  41516. {
  41517. }
  41518. Component* FileListComponent::refreshComponentForRow (int row, bool isSelected, Component* existingComponentToUpdate)
  41519. {
  41520. FileListItemComponent* comp = dynamic_cast <FileListItemComponent*> (existingComponentToUpdate);
  41521. if (comp == 0)
  41522. {
  41523. delete existingComponentToUpdate;
  41524. existingComponentToUpdate = comp = new FileListItemComponent (*this, fileList.getTimeSliceThread());
  41525. }
  41526. DirectoryContentsList::FileInfo fileInfo;
  41527. if (fileList.getFileInfo (row, fileInfo))
  41528. comp->update (fileList.getDirectory(), &fileInfo, row, isSelected);
  41529. else
  41530. comp->update (fileList.getDirectory(), 0, row, isSelected);
  41531. return comp;
  41532. }
  41533. void FileListComponent::selectedRowsChanged (int /*lastRowSelected*/)
  41534. {
  41535. sendSelectionChangeMessage();
  41536. }
  41537. void FileListComponent::deleteKeyPressed (int /*currentSelectedRow*/)
  41538. {
  41539. }
  41540. void FileListComponent::returnKeyPressed (int currentSelectedRow)
  41541. {
  41542. sendDoubleClickMessage (fileList.getFile (currentSelectedRow));
  41543. }
  41544. END_JUCE_NAMESPACE
  41545. /********* End of inlined file: juce_FileListComponent.cpp *********/
  41546. /********* Start of inlined file: juce_FilenameComponent.cpp *********/
  41547. BEGIN_JUCE_NAMESPACE
  41548. FilenameComponent::FilenameComponent (const String& name,
  41549. const File& currentFile,
  41550. const bool canEditFilename,
  41551. const bool isDirectory,
  41552. const bool isForSaving,
  41553. const String& fileBrowserWildcard,
  41554. const String& enforcedSuffix_,
  41555. const String& textWhenNothingSelected)
  41556. : Component (name),
  41557. maxRecentFiles (30),
  41558. isDir (isDirectory),
  41559. isSaving (isForSaving),
  41560. isFileDragOver (false),
  41561. wildcard (fileBrowserWildcard),
  41562. enforcedSuffix (enforcedSuffix_)
  41563. {
  41564. addAndMakeVisible (filenameBox = new ComboBox (T("fn")));
  41565. filenameBox->setEditableText (canEditFilename);
  41566. filenameBox->addListener (this);
  41567. filenameBox->setTextWhenNothingSelected (textWhenNothingSelected);
  41568. filenameBox->setTextWhenNoChoicesAvailable (TRANS("(no recently seleced files)"));
  41569. browseButton = 0;
  41570. setBrowseButtonText (T("..."));
  41571. setCurrentFile (currentFile, true);
  41572. }
  41573. FilenameComponent::~FilenameComponent()
  41574. {
  41575. deleteAllChildren();
  41576. }
  41577. void FilenameComponent::paintOverChildren (Graphics& g)
  41578. {
  41579. if (isFileDragOver)
  41580. {
  41581. g.setColour (Colours::red.withAlpha (0.2f));
  41582. g.drawRect (0, 0, getWidth(), getHeight(), 3);
  41583. }
  41584. }
  41585. void FilenameComponent::resized()
  41586. {
  41587. getLookAndFeel().layoutFilenameComponent (*this, filenameBox, browseButton);
  41588. }
  41589. void FilenameComponent::setBrowseButtonText (const String& newBrowseButtonText)
  41590. {
  41591. browseButtonText = newBrowseButtonText;
  41592. lookAndFeelChanged();
  41593. }
  41594. void FilenameComponent::lookAndFeelChanged()
  41595. {
  41596. deleteAndZero (browseButton);
  41597. addAndMakeVisible (browseButton = getLookAndFeel().createFilenameComponentBrowseButton (browseButtonText));
  41598. browseButton->setConnectedEdges (Button::ConnectedOnLeft);
  41599. resized();
  41600. browseButton->addButtonListener (this);
  41601. }
  41602. void FilenameComponent::setTooltip (const String& newTooltip)
  41603. {
  41604. SettableTooltipClient::setTooltip (newTooltip);
  41605. filenameBox->setTooltip (newTooltip);
  41606. }
  41607. void FilenameComponent::setDefaultBrowseTarget (const File& newDefaultDirectory) throw()
  41608. {
  41609. defaultBrowseFile = newDefaultDirectory;
  41610. }
  41611. void FilenameComponent::buttonClicked (Button*)
  41612. {
  41613. FileChooser fc (TRANS("Choose a new file"),
  41614. getCurrentFile() == File::nonexistent ? defaultBrowseFile
  41615. : getCurrentFile(),
  41616. wildcard);
  41617. if (isDir ? fc.browseForDirectory()
  41618. : (isSaving ? fc.browseForFileToSave (false)
  41619. : fc.browseForFileToOpen()))
  41620. {
  41621. setCurrentFile (fc.getResult(), true);
  41622. }
  41623. }
  41624. void FilenameComponent::comboBoxChanged (ComboBox*)
  41625. {
  41626. setCurrentFile (getCurrentFile(), true);
  41627. }
  41628. bool FilenameComponent::isInterestedInFileDrag (const StringArray&)
  41629. {
  41630. return true;
  41631. }
  41632. void FilenameComponent::filesDropped (const StringArray& filenames, int, int)
  41633. {
  41634. isFileDragOver = false;
  41635. repaint();
  41636. const File f (filenames[0]);
  41637. if (f.exists() && (f.isDirectory() == isDir))
  41638. setCurrentFile (f, true);
  41639. }
  41640. void FilenameComponent::fileDragEnter (const StringArray&, int, int)
  41641. {
  41642. isFileDragOver = true;
  41643. repaint();
  41644. }
  41645. void FilenameComponent::fileDragExit (const StringArray&)
  41646. {
  41647. isFileDragOver = false;
  41648. repaint();
  41649. }
  41650. const File FilenameComponent::getCurrentFile() const
  41651. {
  41652. File f (filenameBox->getText());
  41653. if (enforcedSuffix.isNotEmpty())
  41654. f = f.withFileExtension (enforcedSuffix);
  41655. return f;
  41656. }
  41657. void FilenameComponent::setCurrentFile (File newFile,
  41658. const bool addToRecentlyUsedList,
  41659. const bool sendChangeNotification)
  41660. {
  41661. if (enforcedSuffix.isNotEmpty())
  41662. newFile = newFile.withFileExtension (enforcedSuffix);
  41663. if (newFile.getFullPathName() != lastFilename)
  41664. {
  41665. lastFilename = newFile.getFullPathName();
  41666. if (addToRecentlyUsedList)
  41667. addRecentlyUsedFile (newFile);
  41668. filenameBox->setText (lastFilename, true);
  41669. if (sendChangeNotification)
  41670. triggerAsyncUpdate();
  41671. }
  41672. }
  41673. void FilenameComponent::setFilenameIsEditable (const bool shouldBeEditable)
  41674. {
  41675. filenameBox->setEditableText (shouldBeEditable);
  41676. }
  41677. const StringArray FilenameComponent::getRecentlyUsedFilenames() const
  41678. {
  41679. StringArray names;
  41680. for (int i = 0; i < filenameBox->getNumItems(); ++i)
  41681. names.add (filenameBox->getItemText (i));
  41682. return names;
  41683. }
  41684. void FilenameComponent::setRecentlyUsedFilenames (const StringArray& filenames)
  41685. {
  41686. if (filenames != getRecentlyUsedFilenames())
  41687. {
  41688. filenameBox->clear();
  41689. for (int i = 0; i < jmin (filenames.size(), maxRecentFiles); ++i)
  41690. filenameBox->addItem (filenames[i], i + 1);
  41691. }
  41692. }
  41693. void FilenameComponent::setMaxNumberOfRecentFiles (const int newMaximum)
  41694. {
  41695. maxRecentFiles = jmax (1, newMaximum);
  41696. setRecentlyUsedFilenames (getRecentlyUsedFilenames());
  41697. }
  41698. void FilenameComponent::addRecentlyUsedFile (const File& file)
  41699. {
  41700. StringArray files (getRecentlyUsedFilenames());
  41701. if (file.getFullPathName().isNotEmpty())
  41702. {
  41703. files.removeString (file.getFullPathName(), true);
  41704. files.insert (0, file.getFullPathName());
  41705. setRecentlyUsedFilenames (files);
  41706. }
  41707. }
  41708. void FilenameComponent::addListener (FilenameComponentListener* const listener) throw()
  41709. {
  41710. jassert (listener != 0);
  41711. if (listener != 0)
  41712. listeners.add (listener);
  41713. }
  41714. void FilenameComponent::removeListener (FilenameComponentListener* const listener) throw()
  41715. {
  41716. listeners.removeValue (listener);
  41717. }
  41718. void FilenameComponent::handleAsyncUpdate()
  41719. {
  41720. for (int i = listeners.size(); --i >= 0;)
  41721. {
  41722. ((FilenameComponentListener*) listeners.getUnchecked (i))->filenameComponentChanged (this);
  41723. i = jmin (i, listeners.size());
  41724. }
  41725. }
  41726. END_JUCE_NAMESPACE
  41727. /********* End of inlined file: juce_FilenameComponent.cpp *********/
  41728. /********* Start of inlined file: juce_FileSearchPathListComponent.cpp *********/
  41729. BEGIN_JUCE_NAMESPACE
  41730. FileSearchPathListComponent::FileSearchPathListComponent()
  41731. {
  41732. addAndMakeVisible (listBox = new ListBox (String::empty, this));
  41733. listBox->setColour (ListBox::backgroundColourId, Colours::black.withAlpha (0.02f));
  41734. listBox->setColour (ListBox::outlineColourId, Colours::black.withAlpha (0.1f));
  41735. listBox->setOutlineThickness (1);
  41736. addAndMakeVisible (addButton = new TextButton ("+"));
  41737. addButton->addButtonListener (this);
  41738. addButton->setConnectedEdges (Button::ConnectedOnLeft | Button::ConnectedOnRight | Button::ConnectedOnBottom | Button::ConnectedOnTop);
  41739. addAndMakeVisible (removeButton = new TextButton ("-"));
  41740. removeButton->addButtonListener (this);
  41741. removeButton->setConnectedEdges (Button::ConnectedOnLeft | Button::ConnectedOnRight | Button::ConnectedOnBottom | Button::ConnectedOnTop);
  41742. addAndMakeVisible (changeButton = new TextButton (TRANS("change...")));
  41743. changeButton->addButtonListener (this);
  41744. addAndMakeVisible (upButton = new DrawableButton (String::empty, DrawableButton::ImageOnButtonBackground));
  41745. upButton->addButtonListener (this);
  41746. {
  41747. Path arrowPath;
  41748. arrowPath.addArrow (50.0f, 100.0f, 50.0f, 0.0, 40.0f, 100.0f, 50.0f);
  41749. DrawablePath arrowImage;
  41750. arrowImage.setSolidFill (Colours::black.withAlpha (0.4f));
  41751. arrowImage.setPath (arrowPath);
  41752. ((DrawableButton*) upButton)->setImages (&arrowImage);
  41753. }
  41754. addAndMakeVisible (downButton = new DrawableButton (String::empty, DrawableButton::ImageOnButtonBackground));
  41755. downButton->addButtonListener (this);
  41756. {
  41757. Path arrowPath;
  41758. arrowPath.addArrow (50.0f, 0.0f, 50.0f, 100.0f, 40.0f, 100.0f, 50.0f);
  41759. DrawablePath arrowImage;
  41760. arrowImage.setSolidFill (Colours::black.withAlpha (0.4f));
  41761. arrowImage.setPath (arrowPath);
  41762. ((DrawableButton*) downButton)->setImages (&arrowImage);
  41763. }
  41764. updateButtons();
  41765. }
  41766. FileSearchPathListComponent::~FileSearchPathListComponent()
  41767. {
  41768. deleteAllChildren();
  41769. }
  41770. void FileSearchPathListComponent::updateButtons() throw()
  41771. {
  41772. const bool anythingSelected = listBox->getNumSelectedRows() > 0;
  41773. removeButton->setEnabled (anythingSelected);
  41774. changeButton->setEnabled (anythingSelected);
  41775. upButton->setEnabled (anythingSelected);
  41776. downButton->setEnabled (anythingSelected);
  41777. }
  41778. void FileSearchPathListComponent::changed() throw()
  41779. {
  41780. listBox->updateContent();
  41781. listBox->repaint();
  41782. updateButtons();
  41783. }
  41784. void FileSearchPathListComponent::setPath (const FileSearchPath& newPath)
  41785. {
  41786. if (newPath.toString() != path.toString())
  41787. {
  41788. path = newPath;
  41789. changed();
  41790. }
  41791. }
  41792. void FileSearchPathListComponent::setDefaultBrowseTarget (const File& newDefaultDirectory) throw()
  41793. {
  41794. defaultBrowseTarget = newDefaultDirectory;
  41795. }
  41796. int FileSearchPathListComponent::getNumRows()
  41797. {
  41798. return path.getNumPaths();
  41799. }
  41800. void FileSearchPathListComponent::paintListBoxItem (int rowNumber, Graphics& g, int width, int height, bool rowIsSelected)
  41801. {
  41802. if (rowIsSelected)
  41803. g.fillAll (findColour (TextEditor::highlightColourId));
  41804. g.setColour (findColour (ListBox::textColourId));
  41805. Font f (height * 0.7f);
  41806. f.setHorizontalScale (0.9f);
  41807. g.setFont (f);
  41808. g.drawText (path [rowNumber].getFullPathName(),
  41809. 4, 0, width - 6, height,
  41810. Justification::centredLeft, true);
  41811. }
  41812. void FileSearchPathListComponent::deleteKeyPressed (int row)
  41813. {
  41814. if (((unsigned int) row) < (unsigned int) path.getNumPaths())
  41815. {
  41816. path.remove (row);
  41817. changed();
  41818. }
  41819. }
  41820. void FileSearchPathListComponent::returnKeyPressed (int row)
  41821. {
  41822. FileChooser chooser (TRANS("Change folder..."), path [row], T("*"));
  41823. if (chooser.browseForDirectory())
  41824. {
  41825. path.remove (row);
  41826. path.add (chooser.getResult(), row);
  41827. changed();
  41828. }
  41829. }
  41830. void FileSearchPathListComponent::listBoxItemDoubleClicked (int row, const MouseEvent&)
  41831. {
  41832. returnKeyPressed (row);
  41833. }
  41834. void FileSearchPathListComponent::selectedRowsChanged (int)
  41835. {
  41836. updateButtons();
  41837. }
  41838. void FileSearchPathListComponent::paint (Graphics& g)
  41839. {
  41840. g.fillAll (findColour (backgroundColourId));
  41841. }
  41842. void FileSearchPathListComponent::resized()
  41843. {
  41844. const int buttonH = 22;
  41845. const int buttonY = getHeight() - buttonH - 4;
  41846. listBox->setBounds (2, 2, getWidth() - 4, buttonY - 5);
  41847. addButton->setBounds (2, buttonY, buttonH, buttonH);
  41848. removeButton->setBounds (addButton->getRight(), buttonY, buttonH, buttonH);
  41849. ((TextButton*) changeButton)->changeWidthToFitText (buttonH);
  41850. downButton->setSize (buttonH * 2, buttonH);
  41851. upButton->setSize (buttonH * 2, buttonH);
  41852. downButton->setTopRightPosition (getWidth() - 2, buttonY);
  41853. upButton->setTopRightPosition (downButton->getX() - 4, buttonY);
  41854. changeButton->setTopRightPosition (upButton->getX() - 8, buttonY);
  41855. }
  41856. bool FileSearchPathListComponent::isInterestedInFileDrag (const StringArray&)
  41857. {
  41858. return true;
  41859. }
  41860. void FileSearchPathListComponent::filesDropped (const StringArray& filenames, int, int mouseY)
  41861. {
  41862. for (int i = filenames.size(); --i >= 0;)
  41863. {
  41864. const File f (filenames[i]);
  41865. if (f.isDirectory())
  41866. {
  41867. const int row = listBox->getRowContainingPosition (0, mouseY - listBox->getY());
  41868. path.add (f, row);
  41869. changed();
  41870. }
  41871. }
  41872. }
  41873. void FileSearchPathListComponent::buttonClicked (Button* button)
  41874. {
  41875. const int currentRow = listBox->getSelectedRow();
  41876. if (button == removeButton)
  41877. {
  41878. deleteKeyPressed (currentRow);
  41879. }
  41880. else if (button == addButton)
  41881. {
  41882. File start (defaultBrowseTarget);
  41883. if (start == File::nonexistent)
  41884. start = path [0];
  41885. if (start == File::nonexistent)
  41886. start = File::getCurrentWorkingDirectory();
  41887. FileChooser chooser (TRANS("Add a folder..."), start, T("*"));
  41888. if (chooser.browseForDirectory())
  41889. {
  41890. path.add (chooser.getResult(), currentRow);
  41891. }
  41892. }
  41893. else if (button == changeButton)
  41894. {
  41895. returnKeyPressed (currentRow);
  41896. }
  41897. else if (button == upButton)
  41898. {
  41899. if (currentRow > 0 && currentRow < path.getNumPaths())
  41900. {
  41901. const File f (path[currentRow]);
  41902. path.remove (currentRow);
  41903. path.add (f, currentRow - 1);
  41904. listBox->selectRow (currentRow - 1);
  41905. }
  41906. }
  41907. else if (button == downButton)
  41908. {
  41909. if (currentRow >= 0 && currentRow < path.getNumPaths() - 1)
  41910. {
  41911. const File f (path[currentRow]);
  41912. path.remove (currentRow);
  41913. path.add (f, currentRow + 1);
  41914. listBox->selectRow (currentRow + 1);
  41915. }
  41916. }
  41917. changed();
  41918. }
  41919. END_JUCE_NAMESPACE
  41920. /********* End of inlined file: juce_FileSearchPathListComponent.cpp *********/
  41921. /********* Start of inlined file: juce_FileTreeComponent.cpp *********/
  41922. BEGIN_JUCE_NAMESPACE
  41923. Image* juce_createIconForFile (const File& file);
  41924. class FileListTreeItem : public TreeViewItem,
  41925. public TimeSliceClient,
  41926. public AsyncUpdater,
  41927. public ChangeListener
  41928. {
  41929. public:
  41930. FileListTreeItem (FileTreeComponent& owner_,
  41931. DirectoryContentsList* const parentContentsList_,
  41932. const int indexInContentsList_,
  41933. const File& file_,
  41934. TimeSliceThread& thread_) throw()
  41935. : file (file_),
  41936. owner (owner_),
  41937. parentContentsList (parentContentsList_),
  41938. indexInContentsList (indexInContentsList_),
  41939. subContentsList (0),
  41940. canDeleteSubContentsList (false),
  41941. thread (thread_),
  41942. icon (0)
  41943. {
  41944. DirectoryContentsList::FileInfo fileInfo;
  41945. if (parentContentsList_ != 0
  41946. && parentContentsList_->getFileInfo (indexInContentsList_, fileInfo))
  41947. {
  41948. fileSize = File::descriptionOfSizeInBytes (fileInfo.fileSize);
  41949. modTime = fileInfo.modificationTime.formatted (T("%d %b '%y %H:%M"));
  41950. isDirectory = fileInfo.isDirectory;
  41951. }
  41952. else
  41953. {
  41954. isDirectory = true;
  41955. }
  41956. }
  41957. ~FileListTreeItem() throw()
  41958. {
  41959. thread.removeTimeSliceClient (this);
  41960. clearSubItems();
  41961. ImageCache::release (icon);
  41962. if (canDeleteSubContentsList)
  41963. delete subContentsList;
  41964. }
  41965. bool mightContainSubItems() { return isDirectory; }
  41966. const String getUniqueName() const { return file.getFullPathName(); }
  41967. int getItemHeight() const { return 22; }
  41968. const String getDragSourceDescription() { return owner.getDragAndDropDescription(); }
  41969. void itemOpennessChanged (bool isNowOpen)
  41970. {
  41971. if (isNowOpen)
  41972. {
  41973. clearSubItems();
  41974. isDirectory = file.isDirectory();
  41975. if (isDirectory)
  41976. {
  41977. if (subContentsList == 0)
  41978. {
  41979. jassert (parentContentsList != 0);
  41980. DirectoryContentsList* const l = new DirectoryContentsList (parentContentsList->getFilter(), thread);
  41981. l->setDirectory (file, true, true);
  41982. setSubContentsList (l);
  41983. canDeleteSubContentsList = true;
  41984. }
  41985. changeListenerCallback (0);
  41986. }
  41987. }
  41988. }
  41989. void setSubContentsList (DirectoryContentsList* newList) throw()
  41990. {
  41991. jassert (subContentsList == 0);
  41992. subContentsList = newList;
  41993. newList->addChangeListener (this);
  41994. }
  41995. void changeListenerCallback (void*)
  41996. {
  41997. clearSubItems();
  41998. if (isOpen() && subContentsList != 0)
  41999. {
  42000. for (int i = 0; i < subContentsList->getNumFiles(); ++i)
  42001. {
  42002. FileListTreeItem* const item
  42003. = new FileListTreeItem (owner, subContentsList, i, subContentsList->getFile(i), thread);
  42004. addSubItem (item);
  42005. }
  42006. }
  42007. }
  42008. void paintItem (Graphics& g, int width, int height)
  42009. {
  42010. if (file != File::nonexistent && ! isDirectory)
  42011. {
  42012. updateIcon (true);
  42013. if (icon == 0)
  42014. thread.addTimeSliceClient (this);
  42015. }
  42016. owner.getLookAndFeel()
  42017. .drawFileBrowserRow (g, width, height,
  42018. file.getFileName(),
  42019. icon,
  42020. fileSize, modTime,
  42021. isDirectory, isSelected(),
  42022. indexInContentsList);
  42023. }
  42024. void itemClicked (const MouseEvent& e)
  42025. {
  42026. owner.sendMouseClickMessage (file, e);
  42027. }
  42028. void itemDoubleClicked (const MouseEvent& e)
  42029. {
  42030. TreeViewItem::itemDoubleClicked (e);
  42031. owner.sendDoubleClickMessage (file);
  42032. }
  42033. void itemSelectionChanged (bool)
  42034. {
  42035. owner.sendSelectionChangeMessage();
  42036. }
  42037. bool useTimeSlice()
  42038. {
  42039. updateIcon (false);
  42040. thread.removeTimeSliceClient (this);
  42041. return false;
  42042. }
  42043. void handleAsyncUpdate()
  42044. {
  42045. owner.repaint();
  42046. }
  42047. const File file;
  42048. juce_UseDebuggingNewOperator
  42049. private:
  42050. FileTreeComponent& owner;
  42051. DirectoryContentsList* parentContentsList;
  42052. int indexInContentsList;
  42053. DirectoryContentsList* subContentsList;
  42054. bool isDirectory, canDeleteSubContentsList;
  42055. TimeSliceThread& thread;
  42056. Image* icon;
  42057. String fileSize;
  42058. String modTime;
  42059. void updateIcon (const bool onlyUpdateIfCached) throw()
  42060. {
  42061. if (icon == 0)
  42062. {
  42063. const int hashCode = (file.getFullPathName() + T("_iconCacheSalt")).hashCode();
  42064. Image* im = ImageCache::getFromHashCode (hashCode);
  42065. if (im == 0 && ! onlyUpdateIfCached)
  42066. {
  42067. im = juce_createIconForFile (file);
  42068. if (im != 0)
  42069. ImageCache::addImageToCache (im, hashCode);
  42070. }
  42071. if (im != 0)
  42072. {
  42073. icon = im;
  42074. triggerAsyncUpdate();
  42075. }
  42076. }
  42077. }
  42078. };
  42079. FileTreeComponent::FileTreeComponent (DirectoryContentsList& listToShow)
  42080. : DirectoryContentsDisplayComponent (listToShow)
  42081. {
  42082. FileListTreeItem* const root
  42083. = new FileListTreeItem (*this, 0, 0, listToShow.getDirectory(),
  42084. listToShow.getTimeSliceThread());
  42085. root->setSubContentsList (&listToShow);
  42086. setRootItemVisible (false);
  42087. setRootItem (root);
  42088. }
  42089. FileTreeComponent::~FileTreeComponent()
  42090. {
  42091. TreeViewItem* const root = getRootItem();
  42092. setRootItem (0);
  42093. delete root;
  42094. }
  42095. const File FileTreeComponent::getSelectedFile() const
  42096. {
  42097. return getSelectedFile (0);
  42098. }
  42099. const File FileTreeComponent::getSelectedFile (const int index) const throw()
  42100. {
  42101. const FileListTreeItem* const item = dynamic_cast <const FileListTreeItem*> (getSelectedItem (index));
  42102. if (item != 0)
  42103. return item->file;
  42104. return File::nonexistent;
  42105. }
  42106. void FileTreeComponent::scrollToTop()
  42107. {
  42108. getViewport()->getVerticalScrollBar()->setCurrentRangeStart (0);
  42109. }
  42110. void FileTreeComponent::setDragAndDropDescription (const String& description) throw()
  42111. {
  42112. dragAndDropDescription = description;
  42113. }
  42114. END_JUCE_NAMESPACE
  42115. /********* End of inlined file: juce_FileTreeComponent.cpp *********/
  42116. /********* Start of inlined file: juce_ImagePreviewComponent.cpp *********/
  42117. BEGIN_JUCE_NAMESPACE
  42118. ImagePreviewComponent::ImagePreviewComponent()
  42119. : currentThumbnail (0)
  42120. {
  42121. }
  42122. ImagePreviewComponent::~ImagePreviewComponent()
  42123. {
  42124. delete currentThumbnail;
  42125. }
  42126. void ImagePreviewComponent::getThumbSize (int& w, int& h) const
  42127. {
  42128. const int availableW = proportionOfWidth (0.97f);
  42129. const int availableH = getHeight() - 13 * 4;
  42130. const double scale = jmin (1.0,
  42131. availableW / (double) w,
  42132. availableH / (double) h);
  42133. w = roundDoubleToInt (scale * w);
  42134. h = roundDoubleToInt (scale * h);
  42135. }
  42136. void ImagePreviewComponent::selectedFileChanged (const File& file)
  42137. {
  42138. if (fileToLoad != file)
  42139. {
  42140. fileToLoad = file;
  42141. startTimer (100);
  42142. }
  42143. }
  42144. void ImagePreviewComponent::timerCallback()
  42145. {
  42146. stopTimer();
  42147. deleteAndZero (currentThumbnail);
  42148. currentDetails = String::empty;
  42149. repaint();
  42150. FileInputStream* const in = fileToLoad.createInputStream();
  42151. if (in != 0)
  42152. {
  42153. ImageFileFormat* const format = ImageFileFormat::findImageFormatForStream (*in);
  42154. if (format != 0)
  42155. {
  42156. currentThumbnail = format->decodeImage (*in);
  42157. if (currentThumbnail != 0)
  42158. {
  42159. int w = currentThumbnail->getWidth();
  42160. int h = currentThumbnail->getHeight();
  42161. currentDetails
  42162. << fileToLoad.getFileName() << "\n"
  42163. << format->getFormatName() << "\n"
  42164. << w << " x " << h << " pixels\n"
  42165. << File::descriptionOfSizeInBytes (fileToLoad.getSize());
  42166. getThumbSize (w, h);
  42167. Image* const reduced = currentThumbnail->createCopy (w, h);
  42168. delete currentThumbnail;
  42169. currentThumbnail = reduced;
  42170. }
  42171. }
  42172. delete in;
  42173. }
  42174. }
  42175. void ImagePreviewComponent::paint (Graphics& g)
  42176. {
  42177. if (currentThumbnail != 0)
  42178. {
  42179. g.setFont (13.0f);
  42180. int w = currentThumbnail->getWidth();
  42181. int h = currentThumbnail->getHeight();
  42182. getThumbSize (w, h);
  42183. const int numLines = 4;
  42184. const int totalH = 13 * numLines + h + 4;
  42185. const int y = (getHeight() - totalH) / 2;
  42186. g.drawImageWithin (currentThumbnail,
  42187. (getWidth() - w) / 2, y, w, h,
  42188. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize,
  42189. false);
  42190. g.drawFittedText (currentDetails,
  42191. 0, y + h + 4, getWidth(), 100,
  42192. Justification::centredTop, numLines);
  42193. }
  42194. }
  42195. END_JUCE_NAMESPACE
  42196. /********* End of inlined file: juce_ImagePreviewComponent.cpp *********/
  42197. /********* Start of inlined file: juce_WildcardFileFilter.cpp *********/
  42198. BEGIN_JUCE_NAMESPACE
  42199. WildcardFileFilter::WildcardFileFilter (const String& wildcardPatterns,
  42200. const String& description)
  42201. : FileFilter (description.isEmpty() ? wildcardPatterns
  42202. : (description + T(" (") + wildcardPatterns + T(")")))
  42203. {
  42204. wildcards.addTokens (wildcardPatterns.toLowerCase(), T(";,"), T("\"'"));
  42205. wildcards.trim();
  42206. wildcards.removeEmptyStrings();
  42207. // special case for *.*, because people use it to mean "any file", but it
  42208. // would actually ignore files with no extension.
  42209. for (int i = wildcards.size(); --i >= 0;)
  42210. if (wildcards[i] == T("*.*"))
  42211. wildcards.set (i, T("*"));
  42212. }
  42213. WildcardFileFilter::~WildcardFileFilter()
  42214. {
  42215. }
  42216. bool WildcardFileFilter::isFileSuitable (const File& file) const
  42217. {
  42218. const String filename (file.getFileName());
  42219. for (int i = wildcards.size(); --i >= 0;)
  42220. if (filename.matchesWildcard (wildcards[i], true))
  42221. return true;
  42222. return false;
  42223. }
  42224. bool WildcardFileFilter::isDirectorySuitable (const File&) const
  42225. {
  42226. return true;
  42227. }
  42228. END_JUCE_NAMESPACE
  42229. /********* End of inlined file: juce_WildcardFileFilter.cpp *********/
  42230. /********* Start of inlined file: juce_KeyboardFocusTraverser.cpp *********/
  42231. BEGIN_JUCE_NAMESPACE
  42232. KeyboardFocusTraverser::KeyboardFocusTraverser()
  42233. {
  42234. }
  42235. KeyboardFocusTraverser::~KeyboardFocusTraverser()
  42236. {
  42237. }
  42238. // This will sort a set of components, so that they are ordered in terms of
  42239. // left-to-right and then top-to-bottom.
  42240. class ScreenPositionComparator
  42241. {
  42242. public:
  42243. ScreenPositionComparator() {}
  42244. static int compareElements (const Component* const first, const Component* const second) throw()
  42245. {
  42246. int explicitOrder1 = first->getExplicitFocusOrder();
  42247. if (explicitOrder1 <= 0)
  42248. explicitOrder1 = INT_MAX / 2;
  42249. int explicitOrder2 = second->getExplicitFocusOrder();
  42250. if (explicitOrder2 <= 0)
  42251. explicitOrder2 = INT_MAX / 2;
  42252. if (explicitOrder1 != explicitOrder2)
  42253. return explicitOrder1 - explicitOrder2;
  42254. const int diff = first->getY() - second->getY();
  42255. return (diff == 0) ? first->getX() - second->getX()
  42256. : diff;
  42257. }
  42258. };
  42259. static void findAllFocusableComponents (Component* const parent, Array <Component*>& comps)
  42260. {
  42261. if (parent->getNumChildComponents() > 0)
  42262. {
  42263. Array <Component*> localComps;
  42264. ScreenPositionComparator comparator;
  42265. int i;
  42266. for (i = parent->getNumChildComponents(); --i >= 0;)
  42267. {
  42268. Component* const c = parent->getChildComponent (i);
  42269. if (c->isVisible() && c->isEnabled())
  42270. localComps.addSorted (comparator, c);
  42271. }
  42272. for (i = 0; i < localComps.size(); ++i)
  42273. {
  42274. Component* const c = localComps.getUnchecked (i);
  42275. if (c->getWantsKeyboardFocus())
  42276. comps.add (c);
  42277. if (! c->isFocusContainer())
  42278. findAllFocusableComponents (c, comps);
  42279. }
  42280. }
  42281. }
  42282. static Component* getIncrementedComponent (Component* const current, const int delta) throw()
  42283. {
  42284. Component* focusContainer = current->getParentComponent();
  42285. if (focusContainer != 0)
  42286. {
  42287. while (focusContainer->getParentComponent() != 0 && ! focusContainer->isFocusContainer())
  42288. focusContainer = focusContainer->getParentComponent();
  42289. if (focusContainer != 0)
  42290. {
  42291. Array <Component*> comps;
  42292. findAllFocusableComponents (focusContainer, comps);
  42293. if (comps.size() > 0)
  42294. {
  42295. const int index = comps.indexOf (current);
  42296. return comps [(index + comps.size() + delta) % comps.size()];
  42297. }
  42298. }
  42299. }
  42300. return 0;
  42301. }
  42302. Component* KeyboardFocusTraverser::getNextComponent (Component* current)
  42303. {
  42304. return getIncrementedComponent (current, 1);
  42305. }
  42306. Component* KeyboardFocusTraverser::getPreviousComponent (Component* current)
  42307. {
  42308. return getIncrementedComponent (current, -1);
  42309. }
  42310. Component* KeyboardFocusTraverser::getDefaultComponent (Component* parentComponent)
  42311. {
  42312. Array <Component*> comps;
  42313. if (parentComponent != 0)
  42314. findAllFocusableComponents (parentComponent, comps);
  42315. return comps.getFirst();
  42316. }
  42317. END_JUCE_NAMESPACE
  42318. /********* End of inlined file: juce_KeyboardFocusTraverser.cpp *********/
  42319. /********* Start of inlined file: juce_KeyListener.cpp *********/
  42320. BEGIN_JUCE_NAMESPACE
  42321. bool KeyListener::keyStateChanged (Component*)
  42322. {
  42323. return false;
  42324. }
  42325. END_JUCE_NAMESPACE
  42326. /********* End of inlined file: juce_KeyListener.cpp *********/
  42327. /********* Start of inlined file: juce_KeyMappingEditorComponent.cpp *********/
  42328. BEGIN_JUCE_NAMESPACE
  42329. // N.B. these two includes are put here deliberately to avoid problems with
  42330. // old GCCs failing on long include paths
  42331. const int maxKeys = 3;
  42332. class KeyMappingChangeButton : public Button
  42333. {
  42334. public:
  42335. KeyMappingChangeButton (KeyMappingEditorComponent* const owner_,
  42336. const CommandID commandID_,
  42337. const String& keyName,
  42338. const int keyNum_)
  42339. : Button (keyName),
  42340. owner (owner_),
  42341. commandID (commandID_),
  42342. keyNum (keyNum_)
  42343. {
  42344. setWantsKeyboardFocus (false);
  42345. setTriggeredOnMouseDown (keyNum >= 0);
  42346. if (keyNum_ < 0)
  42347. setTooltip (TRANS("adds a new key-mapping"));
  42348. else
  42349. setTooltip (TRANS("click to change this key-mapping"));
  42350. }
  42351. ~KeyMappingChangeButton()
  42352. {
  42353. }
  42354. void paintButton (Graphics& g, bool isOver, bool isDown)
  42355. {
  42356. if (keyNum >= 0)
  42357. {
  42358. if (isEnabled())
  42359. {
  42360. const float alpha = isDown ? 0.3f : (isOver ? 0.15f : 0.08f);
  42361. g.fillAll (owner->textColour.withAlpha (alpha));
  42362. g.setOpacity (0.3f);
  42363. g.drawBevel (0, 0, getWidth(), getHeight(), 2);
  42364. }
  42365. g.setColour (owner->textColour);
  42366. g.setFont (getHeight() * 0.6f);
  42367. g.drawFittedText (getName(),
  42368. 3, 0, getWidth() - 6, getHeight(),
  42369. Justification::centred, 1);
  42370. }
  42371. else
  42372. {
  42373. const float thickness = 7.0f;
  42374. const float indent = 22.0f;
  42375. Path p;
  42376. p.addEllipse (0.0f, 0.0f, 100.0f, 100.0f);
  42377. p.addRectangle (indent, 50.0f - thickness, 100.0f - indent * 2.0f, thickness * 2.0f);
  42378. p.addRectangle (50.0f - thickness, indent, thickness * 2.0f, 50.0f - indent - thickness);
  42379. p.addRectangle (50.0f - thickness, 50.0f + thickness, thickness * 2.0f, 50.0f - indent - thickness);
  42380. p.setUsingNonZeroWinding (false);
  42381. g.setColour (owner->textColour.withAlpha (isDown ? 0.7f : (isOver ? 0.5f : 0.3f)));
  42382. g.fillPath (p, p.getTransformToScaleToFit (2.0f, 2.0f, getWidth() - 4.0f, getHeight() - 4.0f, true));
  42383. }
  42384. if (hasKeyboardFocus (false))
  42385. {
  42386. g.setColour (owner->textColour.withAlpha (0.4f));
  42387. g.drawRect (0, 0, getWidth(), getHeight());
  42388. }
  42389. }
  42390. void clicked()
  42391. {
  42392. if (keyNum >= 0)
  42393. {
  42394. // existing key clicked..
  42395. PopupMenu m;
  42396. m.addItem (1, TRANS("change this key-mapping"));
  42397. m.addSeparator();
  42398. m.addItem (2, TRANS("remove this key-mapping"));
  42399. const int res = m.show();
  42400. if (res == 1)
  42401. {
  42402. owner->assignNewKey (commandID, keyNum);
  42403. }
  42404. else if (res == 2)
  42405. {
  42406. owner->getMappings()->removeKeyPress (commandID, keyNum);
  42407. }
  42408. }
  42409. else
  42410. {
  42411. // + button pressed..
  42412. owner->assignNewKey (commandID, -1);
  42413. }
  42414. }
  42415. void fitToContent (const int h) throw()
  42416. {
  42417. if (keyNum < 0)
  42418. {
  42419. setSize (h, h);
  42420. }
  42421. else
  42422. {
  42423. Font f (h * 0.6f);
  42424. setSize (jlimit (h * 4, h * 8, 6 + f.getStringWidth (getName())), h);
  42425. }
  42426. }
  42427. juce_UseDebuggingNewOperator
  42428. private:
  42429. KeyMappingEditorComponent* const owner;
  42430. const CommandID commandID;
  42431. const int keyNum;
  42432. KeyMappingChangeButton (const KeyMappingChangeButton&);
  42433. const KeyMappingChangeButton& operator= (const KeyMappingChangeButton&);
  42434. };
  42435. class KeyMappingItemComponent : public Component
  42436. {
  42437. public:
  42438. KeyMappingItemComponent (KeyMappingEditorComponent* const owner_,
  42439. const CommandID commandID_)
  42440. : owner (owner_),
  42441. commandID (commandID_)
  42442. {
  42443. setInterceptsMouseClicks (false, true);
  42444. const bool isReadOnly = owner_->isCommandReadOnly (commandID);
  42445. const Array <KeyPress> keyPresses (owner_->getMappings()->getKeyPressesAssignedToCommand (commandID));
  42446. for (int i = 0; i < jmin (maxKeys, keyPresses.size()); ++i)
  42447. {
  42448. KeyMappingChangeButton* const kb
  42449. = new KeyMappingChangeButton (owner_, commandID,
  42450. owner_->getDescriptionForKeyPress (keyPresses.getReference (i)), i);
  42451. kb->setEnabled (! isReadOnly);
  42452. addAndMakeVisible (kb);
  42453. }
  42454. KeyMappingChangeButton* const kb
  42455. = new KeyMappingChangeButton (owner_, commandID, String::empty, -1);
  42456. addChildComponent (kb);
  42457. kb->setVisible (keyPresses.size() < maxKeys && ! isReadOnly);
  42458. }
  42459. ~KeyMappingItemComponent()
  42460. {
  42461. deleteAllChildren();
  42462. }
  42463. void paint (Graphics& g)
  42464. {
  42465. g.setFont (getHeight() * 0.7f);
  42466. g.setColour (owner->textColour);
  42467. g.drawFittedText (owner->getMappings()->getCommandManager()->getNameOfCommand (commandID),
  42468. 4, 0, jmax (40, getChildComponent (0)->getX() - 5), getHeight(),
  42469. Justification::centredLeft, true);
  42470. }
  42471. void resized()
  42472. {
  42473. int x = getWidth() - 4;
  42474. for (int i = getNumChildComponents(); --i >= 0;)
  42475. {
  42476. KeyMappingChangeButton* const kb = dynamic_cast <KeyMappingChangeButton*> (getChildComponent (i));
  42477. kb->fitToContent (getHeight() - 2);
  42478. kb->setTopRightPosition (x, 1);
  42479. x -= kb->getWidth() + 5;
  42480. }
  42481. }
  42482. juce_UseDebuggingNewOperator
  42483. private:
  42484. KeyMappingEditorComponent* const owner;
  42485. const CommandID commandID;
  42486. KeyMappingItemComponent (const KeyMappingItemComponent&);
  42487. const KeyMappingItemComponent& operator= (const KeyMappingItemComponent&);
  42488. };
  42489. class KeyMappingTreeViewItem : public TreeViewItem
  42490. {
  42491. public:
  42492. KeyMappingTreeViewItem (KeyMappingEditorComponent* const owner_,
  42493. const CommandID commandID_)
  42494. : owner (owner_),
  42495. commandID (commandID_)
  42496. {
  42497. }
  42498. ~KeyMappingTreeViewItem()
  42499. {
  42500. }
  42501. const String getUniqueName() const { return String ((int) commandID) + "_id"; }
  42502. bool mightContainSubItems() { return false; }
  42503. int getItemHeight() const { return 20; }
  42504. Component* createItemComponent()
  42505. {
  42506. return new KeyMappingItemComponent (owner, commandID);
  42507. }
  42508. juce_UseDebuggingNewOperator
  42509. private:
  42510. KeyMappingEditorComponent* const owner;
  42511. const CommandID commandID;
  42512. KeyMappingTreeViewItem (const KeyMappingTreeViewItem&);
  42513. const KeyMappingTreeViewItem& operator= (const KeyMappingTreeViewItem&);
  42514. };
  42515. class KeyCategoryTreeViewItem : public TreeViewItem
  42516. {
  42517. public:
  42518. KeyCategoryTreeViewItem (KeyMappingEditorComponent* const owner_,
  42519. const String& name)
  42520. : owner (owner_),
  42521. categoryName (name)
  42522. {
  42523. }
  42524. ~KeyCategoryTreeViewItem()
  42525. {
  42526. }
  42527. const String getUniqueName() const { return categoryName + "_cat"; }
  42528. bool mightContainSubItems() { return true; }
  42529. int getItemHeight() const { return 28; }
  42530. void paintItem (Graphics& g, int width, int height)
  42531. {
  42532. g.setFont (height * 0.6f, Font::bold);
  42533. g.setColour (owner->textColour);
  42534. g.drawText (categoryName,
  42535. 2, 0, width - 2, height,
  42536. Justification::centredLeft, true);
  42537. }
  42538. void itemOpennessChanged (bool isNowOpen)
  42539. {
  42540. if (isNowOpen)
  42541. {
  42542. if (getNumSubItems() == 0)
  42543. {
  42544. Array <CommandID> commands (owner->getMappings()->getCommandManager()->getCommandsInCategory (categoryName));
  42545. for (int i = 0; i < commands.size(); ++i)
  42546. {
  42547. if (owner->shouldCommandBeIncluded (commands[i]))
  42548. addSubItem (new KeyMappingTreeViewItem (owner, commands[i]));
  42549. }
  42550. }
  42551. }
  42552. else
  42553. {
  42554. clearSubItems();
  42555. }
  42556. }
  42557. juce_UseDebuggingNewOperator
  42558. private:
  42559. KeyMappingEditorComponent* owner;
  42560. String categoryName;
  42561. KeyCategoryTreeViewItem (const KeyCategoryTreeViewItem&);
  42562. const KeyCategoryTreeViewItem& operator= (const KeyCategoryTreeViewItem&);
  42563. };
  42564. KeyMappingEditorComponent::KeyMappingEditorComponent (KeyPressMappingSet* const mappingManager,
  42565. const bool showResetToDefaultButton)
  42566. : mappings (mappingManager),
  42567. textColour (Colours::black)
  42568. {
  42569. jassert (mappingManager != 0); // can't be null!
  42570. mappingManager->addChangeListener (this);
  42571. setLinesDrawnForSubItems (false);
  42572. resetButton = 0;
  42573. if (showResetToDefaultButton)
  42574. {
  42575. addAndMakeVisible (resetButton = new TextButton (TRANS("reset to defaults")));
  42576. resetButton->addButtonListener (this);
  42577. }
  42578. addAndMakeVisible (tree = new TreeView());
  42579. tree->setColour (TreeView::backgroundColourId, backgroundColour);
  42580. tree->setRootItemVisible (false);
  42581. tree->setDefaultOpenness (true);
  42582. tree->setRootItem (this);
  42583. }
  42584. KeyMappingEditorComponent::~KeyMappingEditorComponent()
  42585. {
  42586. mappings->removeChangeListener (this);
  42587. deleteAllChildren();
  42588. }
  42589. bool KeyMappingEditorComponent::mightContainSubItems()
  42590. {
  42591. return true;
  42592. }
  42593. const String KeyMappingEditorComponent::getUniqueName() const
  42594. {
  42595. return T("keys");
  42596. }
  42597. void KeyMappingEditorComponent::setColours (const Colour& mainBackground,
  42598. const Colour& textColour_)
  42599. {
  42600. backgroundColour = mainBackground;
  42601. textColour = textColour_;
  42602. tree->setColour (TreeView::backgroundColourId, backgroundColour);
  42603. }
  42604. void KeyMappingEditorComponent::parentHierarchyChanged()
  42605. {
  42606. changeListenerCallback (0);
  42607. }
  42608. void KeyMappingEditorComponent::resized()
  42609. {
  42610. int h = getHeight();
  42611. if (resetButton != 0)
  42612. {
  42613. const int buttonHeight = 20;
  42614. h -= buttonHeight + 8;
  42615. int x = getWidth() - 8;
  42616. const int y = h + 6;
  42617. resetButton->changeWidthToFitText (buttonHeight);
  42618. resetButton->setTopRightPosition (x, y);
  42619. }
  42620. tree->setBounds (0, 0, getWidth(), h);
  42621. }
  42622. void KeyMappingEditorComponent::buttonClicked (Button* button)
  42623. {
  42624. if (button == resetButton)
  42625. {
  42626. if (AlertWindow::showOkCancelBox (AlertWindow::QuestionIcon,
  42627. TRANS("Reset to defaults"),
  42628. TRANS("Are you sure you want to reset all the key-mappings to their default state?"),
  42629. TRANS("Reset")))
  42630. {
  42631. mappings->resetToDefaultMappings();
  42632. }
  42633. }
  42634. }
  42635. void KeyMappingEditorComponent::changeListenerCallback (void*)
  42636. {
  42637. XmlElement* openness = tree->getOpennessState (true);
  42638. clearSubItems();
  42639. const StringArray categories (mappings->getCommandManager()->getCommandCategories());
  42640. for (int i = 0; i < categories.size(); ++i)
  42641. {
  42642. const Array <CommandID> commands (mappings->getCommandManager()->getCommandsInCategory (categories[i]));
  42643. int count = 0;
  42644. for (int j = 0; j < commands.size(); ++j)
  42645. if (shouldCommandBeIncluded (commands[j]))
  42646. ++count;
  42647. if (count > 0)
  42648. addSubItem (new KeyCategoryTreeViewItem (this, categories[i]));
  42649. }
  42650. if (openness != 0)
  42651. {
  42652. tree->restoreOpennessState (*openness);
  42653. delete openness;
  42654. }
  42655. }
  42656. class KeyEntryWindow : public AlertWindow
  42657. {
  42658. public:
  42659. KeyEntryWindow (KeyMappingEditorComponent* const owner_)
  42660. : AlertWindow (TRANS("New key-mapping"),
  42661. TRANS("Please press a key combination now..."),
  42662. AlertWindow::NoIcon),
  42663. owner (owner_)
  42664. {
  42665. addButton (TRANS("ok"), 1);
  42666. addButton (TRANS("cancel"), 0);
  42667. // (avoid return + escape keys getting processed by the buttons..)
  42668. for (int i = getNumChildComponents(); --i >= 0;)
  42669. getChildComponent (i)->setWantsKeyboardFocus (false);
  42670. setWantsKeyboardFocus (true);
  42671. grabKeyboardFocus();
  42672. }
  42673. ~KeyEntryWindow()
  42674. {
  42675. }
  42676. bool keyPressed (const KeyPress& key)
  42677. {
  42678. lastPress = key;
  42679. String message (TRANS("Key: ") + owner->getDescriptionForKeyPress (key));
  42680. const CommandID previousCommand = owner->getMappings()->findCommandForKeyPress (key);
  42681. if (previousCommand != 0)
  42682. {
  42683. message << "\n\n"
  42684. << TRANS("(Currently assigned to \"")
  42685. << owner->getMappings()->getCommandManager()->getNameOfCommand (previousCommand)
  42686. << "\")";
  42687. }
  42688. setMessage (message);
  42689. return true;
  42690. }
  42691. bool keyStateChanged()
  42692. {
  42693. return true;
  42694. }
  42695. KeyPress lastPress;
  42696. juce_UseDebuggingNewOperator
  42697. private:
  42698. KeyMappingEditorComponent* owner;
  42699. KeyEntryWindow (const KeyEntryWindow&);
  42700. const KeyEntryWindow& operator= (const KeyEntryWindow&);
  42701. };
  42702. void KeyMappingEditorComponent::assignNewKey (const CommandID commandID, const int index)
  42703. {
  42704. KeyEntryWindow entryWindow (this);
  42705. if (entryWindow.runModalLoop() != 0)
  42706. {
  42707. entryWindow.setVisible (false);
  42708. if (entryWindow.lastPress.isValid())
  42709. {
  42710. const CommandID previousCommand = mappings->findCommandForKeyPress (entryWindow.lastPress);
  42711. if (previousCommand != 0)
  42712. {
  42713. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  42714. TRANS("Change key-mapping"),
  42715. TRANS("This key is already assigned to the command \"")
  42716. + mappings->getCommandManager()->getNameOfCommand (previousCommand)
  42717. + TRANS("\"\n\nDo you want to re-assign it to this new command instead?"),
  42718. TRANS("re-assign"),
  42719. TRANS("cancel")))
  42720. {
  42721. return;
  42722. }
  42723. }
  42724. mappings->removeKeyPress (entryWindow.lastPress);
  42725. if (index >= 0)
  42726. mappings->removeKeyPress (commandID, index);
  42727. mappings->addKeyPress (commandID, entryWindow.lastPress, index);
  42728. }
  42729. }
  42730. }
  42731. bool KeyMappingEditorComponent::shouldCommandBeIncluded (const CommandID commandID)
  42732. {
  42733. const ApplicationCommandInfo* const ci = mappings->getCommandManager()->getCommandForID (commandID);
  42734. return (ci != 0) && ((ci->flags & ApplicationCommandInfo::hiddenFromKeyEditor) == 0);
  42735. }
  42736. bool KeyMappingEditorComponent::isCommandReadOnly (const CommandID commandID)
  42737. {
  42738. const ApplicationCommandInfo* const ci = mappings->getCommandManager()->getCommandForID (commandID);
  42739. return (ci != 0) && ((ci->flags & ApplicationCommandInfo::readOnlyInKeyEditor) != 0);
  42740. }
  42741. const String KeyMappingEditorComponent::getDescriptionForKeyPress (const KeyPress& key)
  42742. {
  42743. return key.getTextDescription();
  42744. }
  42745. END_JUCE_NAMESPACE
  42746. /********* End of inlined file: juce_KeyMappingEditorComponent.cpp *********/
  42747. /********* Start of inlined file: juce_KeyPress.cpp *********/
  42748. BEGIN_JUCE_NAMESPACE
  42749. KeyPress::KeyPress() throw()
  42750. : keyCode (0),
  42751. mods (0),
  42752. textCharacter (0)
  42753. {
  42754. }
  42755. KeyPress::KeyPress (const int keyCode_,
  42756. const ModifierKeys& mods_,
  42757. const juce_wchar textCharacter_) throw()
  42758. : keyCode (keyCode_),
  42759. mods (mods_),
  42760. textCharacter (textCharacter_)
  42761. {
  42762. }
  42763. KeyPress::KeyPress (const int keyCode_) throw()
  42764. : keyCode (keyCode_),
  42765. textCharacter (0)
  42766. {
  42767. }
  42768. KeyPress::KeyPress (const KeyPress& other) throw()
  42769. : keyCode (other.keyCode),
  42770. mods (other.mods),
  42771. textCharacter (other.textCharacter)
  42772. {
  42773. }
  42774. const KeyPress& KeyPress::operator= (const KeyPress& other) throw()
  42775. {
  42776. keyCode = other.keyCode;
  42777. mods = other.mods;
  42778. textCharacter = other.textCharacter;
  42779. return *this;
  42780. }
  42781. bool KeyPress::operator== (const KeyPress& other) const throw()
  42782. {
  42783. return mods.getRawFlags() == other.mods.getRawFlags()
  42784. && (textCharacter == other.textCharacter
  42785. || textCharacter == 0
  42786. || other.textCharacter == 0)
  42787. && (keyCode == other.keyCode
  42788. || (keyCode < 256
  42789. && other.keyCode < 256
  42790. && CharacterFunctions::toLowerCase ((tchar) keyCode)
  42791. == CharacterFunctions::toLowerCase ((tchar) other.keyCode)));
  42792. }
  42793. bool KeyPress::operator!= (const KeyPress& other) const throw()
  42794. {
  42795. return ! operator== (other);
  42796. }
  42797. bool KeyPress::isCurrentlyDown() const throw()
  42798. {
  42799. return isKeyCurrentlyDown (keyCode)
  42800. && (ModifierKeys::getCurrentModifiers().getRawFlags() & ModifierKeys::allKeyboardModifiers)
  42801. == (mods.getRawFlags() & ModifierKeys::allKeyboardModifiers);
  42802. }
  42803. struct KeyNameAndCode
  42804. {
  42805. const char* name;
  42806. int code;
  42807. };
  42808. static const KeyNameAndCode keyNameTranslations[] =
  42809. {
  42810. { "spacebar", KeyPress::spaceKey },
  42811. { "return", KeyPress::returnKey },
  42812. { "escape", KeyPress::escapeKey },
  42813. { "backspace", KeyPress::backspaceKey },
  42814. { "cursor left", KeyPress::leftKey },
  42815. { "cursor right", KeyPress::rightKey },
  42816. { "cursor up", KeyPress::upKey },
  42817. { "cursor down", KeyPress::downKey },
  42818. { "page up", KeyPress::pageUpKey },
  42819. { "page down", KeyPress::pageDownKey },
  42820. { "home", KeyPress::homeKey },
  42821. { "end", KeyPress::endKey },
  42822. { "delete", KeyPress::deleteKey },
  42823. { "insert", KeyPress::insertKey },
  42824. { "tab", KeyPress::tabKey },
  42825. { "play", KeyPress::playKey },
  42826. { "stop", KeyPress::stopKey },
  42827. { "fast forward", KeyPress::fastForwardKey },
  42828. { "rewind", KeyPress::rewindKey }
  42829. };
  42830. static const tchar* const numberPadPrefix = T("numpad ");
  42831. const KeyPress KeyPress::createFromDescription (const String& desc) throw()
  42832. {
  42833. int modifiers = 0;
  42834. if (desc.containsWholeWordIgnoreCase (T("ctrl"))
  42835. || desc.containsWholeWordIgnoreCase (T("control"))
  42836. || desc.containsWholeWordIgnoreCase (T("ctl")))
  42837. modifiers |= ModifierKeys::ctrlModifier;
  42838. if (desc.containsWholeWordIgnoreCase (T("shift"))
  42839. || desc.containsWholeWordIgnoreCase (T("shft")))
  42840. modifiers |= ModifierKeys::shiftModifier;
  42841. if (desc.containsWholeWordIgnoreCase (T("alt"))
  42842. || desc.containsWholeWordIgnoreCase (T("option")))
  42843. modifiers |= ModifierKeys::altModifier;
  42844. if (desc.containsWholeWordIgnoreCase (T("command"))
  42845. || desc.containsWholeWordIgnoreCase (T("cmd")))
  42846. modifiers |= ModifierKeys::commandModifier;
  42847. int key = 0;
  42848. for (int i = 0; i < numElementsInArray (keyNameTranslations); ++i)
  42849. {
  42850. if (desc.containsWholeWordIgnoreCase (String (keyNameTranslations[i].name)))
  42851. {
  42852. key = keyNameTranslations[i].code;
  42853. break;
  42854. }
  42855. }
  42856. if (key == 0)
  42857. {
  42858. // see if it's a numpad key..
  42859. if (desc.containsIgnoreCase (numberPadPrefix))
  42860. {
  42861. const tchar lastChar = desc.trimEnd().getLastCharacter();
  42862. if (lastChar >= T('0') && lastChar <= T('9'))
  42863. key = numberPad0 + lastChar - T('0');
  42864. else if (lastChar == T('+'))
  42865. key = numberPadAdd;
  42866. else if (lastChar == T('-'))
  42867. key = numberPadSubtract;
  42868. else if (lastChar == T('*'))
  42869. key = numberPadMultiply;
  42870. else if (lastChar == T('/'))
  42871. key = numberPadDivide;
  42872. else if (lastChar == T('.'))
  42873. key = numberPadDecimalPoint;
  42874. else if (lastChar == T('='))
  42875. key = numberPadEquals;
  42876. else if (desc.endsWith (T("separator")))
  42877. key = numberPadSeparator;
  42878. else if (desc.endsWith (T("delete")))
  42879. key = numberPadDelete;
  42880. }
  42881. if (key == 0)
  42882. {
  42883. // see if it's a function key..
  42884. for (int i = 1; i <= 12; ++i)
  42885. if (desc.containsWholeWordIgnoreCase (T("f") + String (i)))
  42886. key = F1Key + i - 1;
  42887. if (key == 0)
  42888. {
  42889. // give up and use the hex code..
  42890. const int hexCode = desc.fromFirstOccurrenceOf (T("#"), false, false)
  42891. .toLowerCase()
  42892. .retainCharacters (T("0123456789abcdef"))
  42893. .getHexValue32();
  42894. if (hexCode > 0)
  42895. key = hexCode;
  42896. else
  42897. key = CharacterFunctions::toUpperCase (desc.getLastCharacter());
  42898. }
  42899. }
  42900. }
  42901. return KeyPress (key, ModifierKeys (modifiers), 0);
  42902. }
  42903. const String KeyPress::getTextDescription() const throw()
  42904. {
  42905. String desc;
  42906. if (keyCode > 0)
  42907. {
  42908. // some keyboard layouts use a shift-key to get the slash, but in those cases, we
  42909. // want to store it as being a slash, not shift+whatever.
  42910. if (textCharacter == T('/'))
  42911. return "/";
  42912. if (mods.isCtrlDown())
  42913. desc << "ctrl + ";
  42914. if (mods.isShiftDown())
  42915. desc << "shift + ";
  42916. #if JUCE_MAC
  42917. // only do this on the mac, because on Windows ctrl and command are the same,
  42918. // and this would get confusing
  42919. if (mods.isCommandDown())
  42920. desc << "command + ";
  42921. if (mods.isAltDown())
  42922. desc << "option + ";
  42923. #else
  42924. if (mods.isAltDown())
  42925. desc << "alt + ";
  42926. #endif
  42927. for (int i = 0; i < numElementsInArray (keyNameTranslations); ++i)
  42928. if (keyCode == keyNameTranslations[i].code)
  42929. return desc + keyNameTranslations[i].name;
  42930. if (keyCode >= F1Key && keyCode <= F16Key)
  42931. desc << 'F' << (1 + keyCode - F1Key);
  42932. else if (keyCode >= numberPad0 && keyCode <= numberPad9)
  42933. desc << numberPadPrefix << (keyCode - numberPad0);
  42934. else if (keyCode >= 33 && keyCode < 176)
  42935. desc += CharacterFunctions::toUpperCase ((tchar) keyCode);
  42936. else if (keyCode == numberPadAdd)
  42937. desc << numberPadPrefix << '+';
  42938. else if (keyCode == numberPadSubtract)
  42939. desc << numberPadPrefix << '-';
  42940. else if (keyCode == numberPadMultiply)
  42941. desc << numberPadPrefix << '*';
  42942. else if (keyCode == numberPadDivide)
  42943. desc << numberPadPrefix << '/';
  42944. else if (keyCode == numberPadSeparator)
  42945. desc << numberPadPrefix << "separator";
  42946. else if (keyCode == numberPadDecimalPoint)
  42947. desc << numberPadPrefix << '.';
  42948. else if (keyCode == numberPadDelete)
  42949. desc << numberPadPrefix << "delete";
  42950. else
  42951. desc << '#' << String::toHexString (keyCode);
  42952. }
  42953. return desc;
  42954. }
  42955. END_JUCE_NAMESPACE
  42956. /********* End of inlined file: juce_KeyPress.cpp *********/
  42957. /********* Start of inlined file: juce_KeyPressMappingSet.cpp *********/
  42958. BEGIN_JUCE_NAMESPACE
  42959. KeyPressMappingSet::KeyPressMappingSet (ApplicationCommandManager* const commandManager_) throw()
  42960. : commandManager (commandManager_)
  42961. {
  42962. // A manager is needed to get the descriptions of commands, and will be called when
  42963. // a command is invoked. So you can't leave this null..
  42964. jassert (commandManager_ != 0);
  42965. Desktop::getInstance().addFocusChangeListener (this);
  42966. }
  42967. KeyPressMappingSet::KeyPressMappingSet (const KeyPressMappingSet& other) throw()
  42968. : commandManager (other.commandManager)
  42969. {
  42970. Desktop::getInstance().addFocusChangeListener (this);
  42971. }
  42972. KeyPressMappingSet::~KeyPressMappingSet()
  42973. {
  42974. Desktop::getInstance().removeFocusChangeListener (this);
  42975. }
  42976. const Array <KeyPress> KeyPressMappingSet::getKeyPressesAssignedToCommand (const CommandID commandID) const throw()
  42977. {
  42978. for (int i = 0; i < mappings.size(); ++i)
  42979. if (mappings.getUnchecked(i)->commandID == commandID)
  42980. return mappings.getUnchecked (i)->keypresses;
  42981. return Array <KeyPress> ();
  42982. }
  42983. void KeyPressMappingSet::addKeyPress (const CommandID commandID,
  42984. const KeyPress& newKeyPress,
  42985. int insertIndex) throw()
  42986. {
  42987. if (findCommandForKeyPress (newKeyPress) != commandID)
  42988. {
  42989. removeKeyPress (newKeyPress);
  42990. if (newKeyPress.isValid())
  42991. {
  42992. for (int i = mappings.size(); --i >= 0;)
  42993. {
  42994. if (mappings.getUnchecked(i)->commandID == commandID)
  42995. {
  42996. mappings.getUnchecked(i)->keypresses.insert (insertIndex, newKeyPress);
  42997. sendChangeMessage (this);
  42998. return;
  42999. }
  43000. }
  43001. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  43002. if (ci != 0)
  43003. {
  43004. CommandMapping* const cm = new CommandMapping();
  43005. cm->commandID = commandID;
  43006. cm->keypresses.add (newKeyPress);
  43007. cm->wantsKeyUpDownCallbacks = (ci->flags & ApplicationCommandInfo::wantsKeyUpDownCallbacks) != 0;
  43008. mappings.add (cm);
  43009. sendChangeMessage (this);
  43010. }
  43011. }
  43012. }
  43013. }
  43014. void KeyPressMappingSet::resetToDefaultMappings() throw()
  43015. {
  43016. mappings.clear();
  43017. for (int i = 0; i < commandManager->getNumCommands(); ++i)
  43018. {
  43019. const ApplicationCommandInfo* const ci = commandManager->getCommandForIndex (i);
  43020. for (int j = 0; j < ci->defaultKeypresses.size(); ++j)
  43021. {
  43022. addKeyPress (ci->commandID,
  43023. ci->defaultKeypresses.getReference (j));
  43024. }
  43025. }
  43026. sendChangeMessage (this);
  43027. }
  43028. void KeyPressMappingSet::resetToDefaultMapping (const CommandID commandID) throw()
  43029. {
  43030. clearAllKeyPresses (commandID);
  43031. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  43032. for (int j = 0; j < ci->defaultKeypresses.size(); ++j)
  43033. {
  43034. addKeyPress (ci->commandID,
  43035. ci->defaultKeypresses.getReference (j));
  43036. }
  43037. }
  43038. void KeyPressMappingSet::clearAllKeyPresses() throw()
  43039. {
  43040. if (mappings.size() > 0)
  43041. {
  43042. sendChangeMessage (this);
  43043. mappings.clear();
  43044. }
  43045. }
  43046. void KeyPressMappingSet::clearAllKeyPresses (const CommandID commandID) throw()
  43047. {
  43048. for (int i = mappings.size(); --i >= 0;)
  43049. {
  43050. if (mappings.getUnchecked(i)->commandID == commandID)
  43051. {
  43052. mappings.remove (i);
  43053. sendChangeMessage (this);
  43054. }
  43055. }
  43056. }
  43057. void KeyPressMappingSet::removeKeyPress (const KeyPress& keypress) throw()
  43058. {
  43059. if (keypress.isValid())
  43060. {
  43061. for (int i = mappings.size(); --i >= 0;)
  43062. {
  43063. CommandMapping* const cm = mappings.getUnchecked(i);
  43064. for (int j = cm->keypresses.size(); --j >= 0;)
  43065. {
  43066. if (keypress == cm->keypresses [j])
  43067. {
  43068. cm->keypresses.remove (j);
  43069. sendChangeMessage (this);
  43070. }
  43071. }
  43072. }
  43073. }
  43074. }
  43075. void KeyPressMappingSet::removeKeyPress (const CommandID commandID,
  43076. const int keyPressIndex) throw()
  43077. {
  43078. for (int i = mappings.size(); --i >= 0;)
  43079. {
  43080. if (mappings.getUnchecked(i)->commandID == commandID)
  43081. {
  43082. mappings.getUnchecked(i)->keypresses.remove (keyPressIndex);
  43083. sendChangeMessage (this);
  43084. break;
  43085. }
  43086. }
  43087. }
  43088. CommandID KeyPressMappingSet::findCommandForKeyPress (const KeyPress& keyPress) const throw()
  43089. {
  43090. for (int i = 0; i < mappings.size(); ++i)
  43091. if (mappings.getUnchecked(i)->keypresses.contains (keyPress))
  43092. return mappings.getUnchecked(i)->commandID;
  43093. return 0;
  43094. }
  43095. bool KeyPressMappingSet::containsMapping (const CommandID commandID,
  43096. const KeyPress& keyPress) const throw()
  43097. {
  43098. for (int i = mappings.size(); --i >= 0;)
  43099. if (mappings.getUnchecked(i)->commandID == commandID)
  43100. return mappings.getUnchecked(i)->keypresses.contains (keyPress);
  43101. return false;
  43102. }
  43103. void KeyPressMappingSet::invokeCommand (const CommandID commandID,
  43104. const KeyPress& key,
  43105. const bool isKeyDown,
  43106. const int millisecsSinceKeyPressed,
  43107. Component* const originatingComponent) const
  43108. {
  43109. ApplicationCommandTarget::InvocationInfo info (commandID);
  43110. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromKeyPress;
  43111. info.isKeyDown = isKeyDown;
  43112. info.keyPress = key;
  43113. info.millisecsSinceKeyPressed = millisecsSinceKeyPressed;
  43114. info.originatingComponent = originatingComponent;
  43115. commandManager->invoke (info, false);
  43116. }
  43117. bool KeyPressMappingSet::restoreFromXml (const XmlElement& xmlVersion)
  43118. {
  43119. if (xmlVersion.hasTagName (T("KEYMAPPINGS")))
  43120. {
  43121. if (xmlVersion.getBoolAttribute (T("basedOnDefaults"), true))
  43122. {
  43123. // if the XML was created as a set of differences from the default mappings,
  43124. // (i.e. by calling createXml (true)), then we need to first restore the defaults.
  43125. resetToDefaultMappings();
  43126. }
  43127. else
  43128. {
  43129. // if the XML was created calling createXml (false), then we need to clear all
  43130. // the keys and treat the xml as describing the entire set of mappings.
  43131. clearAllKeyPresses();
  43132. }
  43133. forEachXmlChildElement (xmlVersion, map)
  43134. {
  43135. const CommandID commandId = map->getStringAttribute (T("commandId")).getHexValue32();
  43136. if (commandId != 0)
  43137. {
  43138. const KeyPress key (KeyPress::createFromDescription (map->getStringAttribute (T("key"))));
  43139. if (map->hasTagName (T("MAPPING")))
  43140. {
  43141. addKeyPress (commandId, key);
  43142. }
  43143. else if (map->hasTagName (T("UNMAPPING")))
  43144. {
  43145. if (containsMapping (commandId, key))
  43146. removeKeyPress (key);
  43147. }
  43148. }
  43149. }
  43150. return true;
  43151. }
  43152. return false;
  43153. }
  43154. XmlElement* KeyPressMappingSet::createXml (const bool saveDifferencesFromDefaultSet) const
  43155. {
  43156. KeyPressMappingSet* defaultSet = 0;
  43157. if (saveDifferencesFromDefaultSet)
  43158. {
  43159. defaultSet = new KeyPressMappingSet (commandManager);
  43160. defaultSet->resetToDefaultMappings();
  43161. }
  43162. XmlElement* const doc = new XmlElement (T("KEYMAPPINGS"));
  43163. doc->setAttribute (T("basedOnDefaults"), saveDifferencesFromDefaultSet);
  43164. int i;
  43165. for (i = 0; i < mappings.size(); ++i)
  43166. {
  43167. const CommandMapping* const cm = mappings.getUnchecked(i);
  43168. for (int j = 0; j < cm->keypresses.size(); ++j)
  43169. {
  43170. if (defaultSet == 0
  43171. || ! defaultSet->containsMapping (cm->commandID, cm->keypresses.getReference (j)))
  43172. {
  43173. XmlElement* const map = new XmlElement (T("MAPPING"));
  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. if (defaultSet != 0)
  43182. {
  43183. for (i = 0; i < defaultSet->mappings.size(); ++i)
  43184. {
  43185. const CommandMapping* const cm = defaultSet->mappings.getUnchecked(i);
  43186. for (int j = 0; j < cm->keypresses.size(); ++j)
  43187. {
  43188. if (! containsMapping (cm->commandID, cm->keypresses.getReference (j)))
  43189. {
  43190. XmlElement* const map = new XmlElement (T("UNMAPPING"));
  43191. map->setAttribute (T("commandId"), String::toHexString ((int) cm->commandID));
  43192. map->setAttribute (T("description"), commandManager->getDescriptionOfCommand (cm->commandID));
  43193. map->setAttribute (T("key"), cm->keypresses.getReference (j).getTextDescription());
  43194. doc->addChildElement (map);
  43195. }
  43196. }
  43197. }
  43198. delete defaultSet;
  43199. }
  43200. return doc;
  43201. }
  43202. bool KeyPressMappingSet::keyPressed (const KeyPress& key,
  43203. Component* originatingComponent)
  43204. {
  43205. bool used = false;
  43206. const CommandID commandID = findCommandForKeyPress (key);
  43207. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  43208. if (ci != 0
  43209. && (ci->flags & ApplicationCommandInfo::wantsKeyUpDownCallbacks) == 0)
  43210. {
  43211. ApplicationCommandInfo info (0);
  43212. if (commandManager->getTargetForCommand (commandID, info) != 0
  43213. && (info.flags & ApplicationCommandInfo::isDisabled) == 0)
  43214. {
  43215. invokeCommand (commandID, key, true, 0, originatingComponent);
  43216. used = true;
  43217. }
  43218. else
  43219. {
  43220. if (originatingComponent != 0)
  43221. originatingComponent->getLookAndFeel().playAlertSound();
  43222. }
  43223. }
  43224. return used;
  43225. }
  43226. bool KeyPressMappingSet::keyStateChanged (Component* originatingComponent)
  43227. {
  43228. bool used = false;
  43229. const uint32 now = Time::getMillisecondCounter();
  43230. for (int i = mappings.size(); --i >= 0;)
  43231. {
  43232. CommandMapping* const cm = mappings.getUnchecked(i);
  43233. if (cm->wantsKeyUpDownCallbacks)
  43234. {
  43235. for (int j = cm->keypresses.size(); --j >= 0;)
  43236. {
  43237. const KeyPress key (cm->keypresses.getReference (j));
  43238. const bool isDown = key.isCurrentlyDown();
  43239. int keyPressEntryIndex = 0;
  43240. bool wasDown = false;
  43241. for (int k = keysDown.size(); --k >= 0;)
  43242. {
  43243. if (key == keysDown.getUnchecked(k)->key)
  43244. {
  43245. keyPressEntryIndex = k;
  43246. wasDown = true;
  43247. break;
  43248. }
  43249. }
  43250. if (isDown != wasDown)
  43251. {
  43252. int millisecs = 0;
  43253. if (isDown)
  43254. {
  43255. KeyPressTime* const k = new KeyPressTime();
  43256. k->key = key;
  43257. k->timeWhenPressed = now;
  43258. keysDown.add (k);
  43259. }
  43260. else
  43261. {
  43262. const uint32 pressTime = keysDown.getUnchecked (keyPressEntryIndex)->timeWhenPressed;
  43263. if (now > pressTime)
  43264. millisecs = now - pressTime;
  43265. keysDown.remove (keyPressEntryIndex);
  43266. }
  43267. invokeCommand (cm->commandID, key, isDown, millisecs, originatingComponent);
  43268. used = true;
  43269. }
  43270. }
  43271. }
  43272. }
  43273. return used;
  43274. }
  43275. void KeyPressMappingSet::globalFocusChanged (Component* focusedComponent)
  43276. {
  43277. if (focusedComponent != 0)
  43278. focusedComponent->keyStateChanged();
  43279. }
  43280. END_JUCE_NAMESPACE
  43281. /********* End of inlined file: juce_KeyPressMappingSet.cpp *********/
  43282. /********* Start of inlined file: juce_ModifierKeys.cpp *********/
  43283. BEGIN_JUCE_NAMESPACE
  43284. ModifierKeys::ModifierKeys (const int flags_) throw()
  43285. : flags (flags_)
  43286. {
  43287. }
  43288. ModifierKeys::ModifierKeys (const ModifierKeys& other) throw()
  43289. : flags (other.flags)
  43290. {
  43291. }
  43292. const ModifierKeys& ModifierKeys::operator= (const ModifierKeys& other) throw()
  43293. {
  43294. flags = other.flags;
  43295. return *this;
  43296. }
  43297. int ModifierKeys::currentModifierFlags = 0;
  43298. const ModifierKeys ModifierKeys::getCurrentModifiers() throw()
  43299. {
  43300. return ModifierKeys (currentModifierFlags);
  43301. }
  43302. END_JUCE_NAMESPACE
  43303. /********* End of inlined file: juce_ModifierKeys.cpp *********/
  43304. /********* Start of inlined file: juce_ComponentAnimator.cpp *********/
  43305. BEGIN_JUCE_NAMESPACE
  43306. struct AnimationTask
  43307. {
  43308. AnimationTask (Component* const comp)
  43309. : component (comp),
  43310. watcher (comp)
  43311. {
  43312. }
  43313. Component* component;
  43314. ComponentDeletionWatcher watcher;
  43315. Rectangle destination;
  43316. int msElapsed, msTotal;
  43317. double startSpeed, midSpeed, endSpeed, lastProgress;
  43318. double left, top, right, bottom;
  43319. bool useTimeslice (const int elapsed)
  43320. {
  43321. if (watcher.hasBeenDeleted())
  43322. return false;
  43323. msElapsed += elapsed;
  43324. double newProgress = msElapsed / (double) msTotal;
  43325. if (newProgress >= 0 && newProgress < 1.0)
  43326. {
  43327. newProgress = timeToDistance (newProgress);
  43328. const double delta = (newProgress - lastProgress) / (1.0 - lastProgress);
  43329. jassert (newProgress >= lastProgress);
  43330. lastProgress = newProgress;
  43331. left += (destination.getX() - left) * delta;
  43332. top += (destination.getY() - top) * delta;
  43333. right += (destination.getRight() - right) * delta;
  43334. bottom += (destination.getBottom() - bottom) * delta;
  43335. if (delta < 1.0)
  43336. {
  43337. const Rectangle newBounds (roundDoubleToInt (left),
  43338. roundDoubleToInt (top),
  43339. roundDoubleToInt (right - left),
  43340. roundDoubleToInt (bottom - top));
  43341. if (newBounds != destination)
  43342. {
  43343. component->setBounds (newBounds);
  43344. return true;
  43345. }
  43346. }
  43347. }
  43348. component->setBounds (destination);
  43349. return false;
  43350. }
  43351. void moveToFinalDestination()
  43352. {
  43353. if (! watcher.hasBeenDeleted())
  43354. component->setBounds (destination);
  43355. }
  43356. private:
  43357. inline double timeToDistance (const double time) const
  43358. {
  43359. return (time < 0.5) ? time * (startSpeed + time * (midSpeed - startSpeed))
  43360. : 0.5 * (startSpeed + 0.5 * (midSpeed - startSpeed))
  43361. + (time - 0.5) * (midSpeed + (time - 0.5) * (endSpeed - midSpeed));
  43362. }
  43363. };
  43364. ComponentAnimator::ComponentAnimator()
  43365. : lastTime (0)
  43366. {
  43367. }
  43368. ComponentAnimator::~ComponentAnimator()
  43369. {
  43370. cancelAllAnimations (false);
  43371. jassert (tasks.size() == 0);
  43372. }
  43373. void* ComponentAnimator::findTaskFor (Component* const component) const
  43374. {
  43375. for (int i = tasks.size(); --i >= 0;)
  43376. if (component == ((AnimationTask*) tasks.getUnchecked(i))->component)
  43377. return tasks.getUnchecked(i);
  43378. return 0;
  43379. }
  43380. void ComponentAnimator::animateComponent (Component* const component,
  43381. const Rectangle& finalPosition,
  43382. const int millisecondsToSpendMoving,
  43383. const double startSpeed,
  43384. const double endSpeed)
  43385. {
  43386. if (component != 0)
  43387. {
  43388. AnimationTask* at = (AnimationTask*) findTaskFor (component);
  43389. if (at == 0)
  43390. {
  43391. at = new AnimationTask (component);
  43392. tasks.add (at);
  43393. }
  43394. at->msElapsed = 0;
  43395. at->lastProgress = 0;
  43396. at->msTotal = jmax (1, millisecondsToSpendMoving);
  43397. at->destination = finalPosition;
  43398. // the speeds must be 0 or greater!
  43399. jassert (startSpeed >= 0 && endSpeed >= 0)
  43400. const double invTotalDistance = 4.0 / (startSpeed + endSpeed + 2.0);
  43401. at->startSpeed = jmax (0.0, startSpeed * invTotalDistance);
  43402. at->midSpeed = invTotalDistance;
  43403. at->endSpeed = jmax (0.0, endSpeed * invTotalDistance);
  43404. at->left = component->getX();
  43405. at->top = component->getY();
  43406. at->right = component->getRight();
  43407. at->bottom = component->getBottom();
  43408. if (! isTimerRunning())
  43409. {
  43410. lastTime = Time::getMillisecondCounter();
  43411. startTimer (1000 / 50);
  43412. }
  43413. }
  43414. }
  43415. void ComponentAnimator::cancelAllAnimations (const bool moveComponentsToTheirFinalPositions)
  43416. {
  43417. for (int i = tasks.size(); --i >= 0;)
  43418. {
  43419. AnimationTask* const at = (AnimationTask*) tasks.getUnchecked(i);
  43420. if (moveComponentsToTheirFinalPositions)
  43421. at->moveToFinalDestination();
  43422. delete at;
  43423. tasks.remove (i);
  43424. }
  43425. }
  43426. void ComponentAnimator::cancelAnimation (Component* const component,
  43427. const bool moveComponentToItsFinalPosition)
  43428. {
  43429. AnimationTask* const at = (AnimationTask*) findTaskFor (component);
  43430. if (at != 0)
  43431. {
  43432. if (moveComponentToItsFinalPosition)
  43433. at->moveToFinalDestination();
  43434. tasks.removeValue (at);
  43435. delete at;
  43436. }
  43437. }
  43438. const Rectangle ComponentAnimator::getComponentDestination (Component* const component)
  43439. {
  43440. AnimationTask* const at = (AnimationTask*) findTaskFor (component);
  43441. if (at != 0)
  43442. return at->destination;
  43443. else if (component != 0)
  43444. return component->getBounds();
  43445. return Rectangle();
  43446. }
  43447. void ComponentAnimator::timerCallback()
  43448. {
  43449. const uint32 timeNow = Time::getMillisecondCounter();
  43450. if (lastTime == 0 || lastTime == timeNow)
  43451. lastTime = timeNow;
  43452. const int elapsed = timeNow - lastTime;
  43453. for (int i = tasks.size(); --i >= 0;)
  43454. {
  43455. AnimationTask* const at = (AnimationTask*) tasks.getUnchecked(i);
  43456. if (! at->useTimeslice (elapsed))
  43457. {
  43458. tasks.remove (i);
  43459. delete at;
  43460. }
  43461. }
  43462. lastTime = timeNow;
  43463. if (tasks.size() == 0)
  43464. stopTimer();
  43465. }
  43466. END_JUCE_NAMESPACE
  43467. /********* End of inlined file: juce_ComponentAnimator.cpp *********/
  43468. /********* Start of inlined file: juce_ComponentBoundsConstrainer.cpp *********/
  43469. BEGIN_JUCE_NAMESPACE
  43470. ComponentBoundsConstrainer::ComponentBoundsConstrainer() throw()
  43471. : minW (0),
  43472. maxW (0x3fffffff),
  43473. minH (0),
  43474. maxH (0x3fffffff),
  43475. minOffTop (0),
  43476. minOffLeft (0),
  43477. minOffBottom (0),
  43478. minOffRight (0),
  43479. aspectRatio (0.0)
  43480. {
  43481. }
  43482. ComponentBoundsConstrainer::~ComponentBoundsConstrainer()
  43483. {
  43484. }
  43485. void ComponentBoundsConstrainer::setMinimumWidth (const int minimumWidth) throw()
  43486. {
  43487. minW = minimumWidth;
  43488. }
  43489. void ComponentBoundsConstrainer::setMaximumWidth (const int maximumWidth) throw()
  43490. {
  43491. maxW = maximumWidth;
  43492. }
  43493. void ComponentBoundsConstrainer::setMinimumHeight (const int minimumHeight) throw()
  43494. {
  43495. minH = minimumHeight;
  43496. }
  43497. void ComponentBoundsConstrainer::setMaximumHeight (const int maximumHeight) throw()
  43498. {
  43499. maxH = maximumHeight;
  43500. }
  43501. void ComponentBoundsConstrainer::setMinimumSize (const int minimumWidth, const int minimumHeight) throw()
  43502. {
  43503. jassert (maxW >= minimumWidth);
  43504. jassert (maxH >= minimumHeight);
  43505. jassert (minimumWidth > 0 && minimumHeight > 0);
  43506. minW = minimumWidth;
  43507. minH = minimumHeight;
  43508. if (minW > maxW)
  43509. maxW = minW;
  43510. if (minH > maxH)
  43511. maxH = minH;
  43512. }
  43513. void ComponentBoundsConstrainer::setMaximumSize (const int maximumWidth, const int maximumHeight) throw()
  43514. {
  43515. jassert (maximumWidth >= minW);
  43516. jassert (maximumHeight >= minH);
  43517. jassert (maximumWidth > 0 && maximumHeight > 0);
  43518. maxW = jmax (minW, maximumWidth);
  43519. maxH = jmax (minH, maximumHeight);
  43520. }
  43521. void ComponentBoundsConstrainer::setSizeLimits (const int minimumWidth,
  43522. const int minimumHeight,
  43523. const int maximumWidth,
  43524. const int maximumHeight) throw()
  43525. {
  43526. jassert (maximumWidth >= minimumWidth);
  43527. jassert (maximumHeight >= minimumHeight);
  43528. jassert (maximumWidth > 0 && maximumHeight > 0);
  43529. jassert (minimumWidth > 0 && minimumHeight > 0);
  43530. minW = jmax (0, minimumWidth);
  43531. minH = jmax (0, minimumHeight);
  43532. maxW = jmax (minW, maximumWidth);
  43533. maxH = jmax (minH, maximumHeight);
  43534. }
  43535. void ComponentBoundsConstrainer::setMinimumOnscreenAmounts (const int minimumWhenOffTheTop,
  43536. const int minimumWhenOffTheLeft,
  43537. const int minimumWhenOffTheBottom,
  43538. const int minimumWhenOffTheRight) throw()
  43539. {
  43540. minOffTop = minimumWhenOffTheTop;
  43541. minOffLeft = minimumWhenOffTheLeft;
  43542. minOffBottom = minimumWhenOffTheBottom;
  43543. minOffRight = minimumWhenOffTheRight;
  43544. }
  43545. void ComponentBoundsConstrainer::setFixedAspectRatio (const double widthOverHeight) throw()
  43546. {
  43547. aspectRatio = jmax (0.0, widthOverHeight);
  43548. }
  43549. double ComponentBoundsConstrainer::getFixedAspectRatio() const throw()
  43550. {
  43551. return aspectRatio;
  43552. }
  43553. void ComponentBoundsConstrainer::setBoundsForComponent (Component* const component,
  43554. int x, int y, int w, int h,
  43555. const bool isStretchingTop,
  43556. const bool isStretchingLeft,
  43557. const bool isStretchingBottom,
  43558. const bool isStretchingRight)
  43559. {
  43560. jassert (component != 0);
  43561. Rectangle limits;
  43562. Component* const p = component->getParentComponent();
  43563. if (p == 0)
  43564. limits = Desktop::getInstance().getAllMonitorDisplayAreas().getBounds();
  43565. else
  43566. limits.setSize (p->getWidth(), p->getHeight());
  43567. if (component->isOnDesktop())
  43568. {
  43569. ComponentPeer* const peer = component->getPeer();
  43570. const BorderSize border (peer->getFrameSize());
  43571. x -= border.getLeft();
  43572. y -= border.getTop();
  43573. w += border.getLeftAndRight();
  43574. h += border.getTopAndBottom();
  43575. checkBounds (x, y, w, h,
  43576. border.addedTo (component->getBounds()), limits,
  43577. isStretchingTop, isStretchingLeft,
  43578. isStretchingBottom, isStretchingRight);
  43579. x += border.getLeft();
  43580. y += border.getTop();
  43581. w -= border.getLeftAndRight();
  43582. h -= border.getTopAndBottom();
  43583. }
  43584. else
  43585. {
  43586. checkBounds (x, y, w, h,
  43587. component->getBounds(), limits,
  43588. isStretchingTop, isStretchingLeft,
  43589. isStretchingBottom, isStretchingRight);
  43590. }
  43591. applyBoundsToComponent (component, x, y, w, h);
  43592. }
  43593. void ComponentBoundsConstrainer::applyBoundsToComponent (Component* component,
  43594. int x, int y, int w, int h)
  43595. {
  43596. component->setBounds (x, y, w, h);
  43597. }
  43598. void ComponentBoundsConstrainer::resizeStart()
  43599. {
  43600. }
  43601. void ComponentBoundsConstrainer::resizeEnd()
  43602. {
  43603. }
  43604. void ComponentBoundsConstrainer::checkBounds (int& x, int& y, int& w, int& h,
  43605. const Rectangle& old,
  43606. const Rectangle& limits,
  43607. const bool isStretchingTop,
  43608. const bool isStretchingLeft,
  43609. const bool isStretchingBottom,
  43610. const bool isStretchingRight)
  43611. {
  43612. // constrain the size if it's being stretched..
  43613. if (isStretchingLeft)
  43614. {
  43615. x = jlimit (old.getRight() - maxW, old.getRight() - minW, x);
  43616. w = old.getRight() - x;
  43617. }
  43618. if (isStretchingRight)
  43619. {
  43620. w = jlimit (minW, maxW, w);
  43621. }
  43622. if (isStretchingTop)
  43623. {
  43624. y = jlimit (old.getBottom() - maxH, old.getBottom() - minH, y);
  43625. h = old.getBottom() - y;
  43626. }
  43627. if (isStretchingBottom)
  43628. {
  43629. h = jlimit (minH, maxH, h);
  43630. }
  43631. // constrain the aspect ratio if one has been specified..
  43632. if (aspectRatio > 0.0 && w > 0 && h > 0)
  43633. {
  43634. bool adjustWidth;
  43635. if ((isStretchingTop || isStretchingBottom) && ! (isStretchingLeft || isStretchingRight))
  43636. {
  43637. adjustWidth = true;
  43638. }
  43639. else if ((isStretchingLeft || isStretchingRight) && ! (isStretchingTop || isStretchingBottom))
  43640. {
  43641. adjustWidth = false;
  43642. }
  43643. else
  43644. {
  43645. const double oldRatio = (old.getHeight() > 0) ? fabs (old.getWidth() / (double) old.getHeight()) : 0.0;
  43646. const double newRatio = fabs (w / (double) h);
  43647. adjustWidth = (oldRatio > newRatio);
  43648. }
  43649. if (adjustWidth)
  43650. {
  43651. w = roundDoubleToInt (h * aspectRatio);
  43652. if (w > maxW || w < minW)
  43653. {
  43654. w = jlimit (minW, maxW, w);
  43655. h = roundDoubleToInt (w / aspectRatio);
  43656. }
  43657. }
  43658. else
  43659. {
  43660. h = roundDoubleToInt (w / aspectRatio);
  43661. if (h > maxH || h < minH)
  43662. {
  43663. h = jlimit (minH, maxH, h);
  43664. w = roundDoubleToInt (h * aspectRatio);
  43665. }
  43666. }
  43667. if ((isStretchingTop || isStretchingBottom) && ! (isStretchingLeft || isStretchingRight))
  43668. {
  43669. x = old.getX() + (old.getWidth() - w) / 2;
  43670. }
  43671. else if ((isStretchingLeft || isStretchingRight) && ! (isStretchingTop || isStretchingBottom))
  43672. {
  43673. y = old.getY() + (old.getHeight() - h) / 2;
  43674. }
  43675. else
  43676. {
  43677. if (isStretchingLeft)
  43678. x = old.getRight() - w;
  43679. if (isStretchingTop)
  43680. y = old.getBottom() - h;
  43681. }
  43682. }
  43683. // ...and constrain the position if limits have been set for that.
  43684. if (minOffTop > 0 || minOffLeft > 0 || minOffBottom > 0 || minOffRight > 0)
  43685. {
  43686. if (minOffTop > 0)
  43687. {
  43688. const int limit = limits.getY() + jmin (minOffTop - h, 0);
  43689. if (y < limit)
  43690. {
  43691. if (isStretchingTop)
  43692. h -= (limit - y);
  43693. y = limit;
  43694. }
  43695. }
  43696. if (minOffLeft > 0)
  43697. {
  43698. const int limit = limits.getX() + jmin (minOffLeft - w, 0);
  43699. if (x < limit)
  43700. {
  43701. if (isStretchingLeft)
  43702. w -= (limit - x);
  43703. x = limit;
  43704. }
  43705. }
  43706. if (minOffBottom > 0)
  43707. {
  43708. const int limit = limits.getBottom() - jmin (minOffBottom, h);
  43709. if (y > limit)
  43710. {
  43711. if (isStretchingBottom)
  43712. h += (limit - y);
  43713. else
  43714. y = limit;
  43715. }
  43716. }
  43717. if (minOffRight > 0)
  43718. {
  43719. const int limit = limits.getRight() - jmin (minOffRight, w);
  43720. if (x > limit)
  43721. {
  43722. if (isStretchingRight)
  43723. w += (limit - x);
  43724. else
  43725. x = limit;
  43726. }
  43727. }
  43728. }
  43729. jassert (w >= 0 && h >= 0);
  43730. }
  43731. END_JUCE_NAMESPACE
  43732. /********* End of inlined file: juce_ComponentBoundsConstrainer.cpp *********/
  43733. /********* Start of inlined file: juce_ComponentMovementWatcher.cpp *********/
  43734. BEGIN_JUCE_NAMESPACE
  43735. ComponentMovementWatcher::ComponentMovementWatcher (Component* const component_)
  43736. : component (component_),
  43737. lastPeer (0),
  43738. registeredParentComps (4),
  43739. reentrant (false)
  43740. {
  43741. jassert (component != 0); // can't use this with a null pointer..
  43742. #ifdef JUCE_DEBUG
  43743. deletionWatcher = new ComponentDeletionWatcher (component_);
  43744. #endif
  43745. component->addComponentListener (this);
  43746. registerWithParentComps();
  43747. }
  43748. ComponentMovementWatcher::~ComponentMovementWatcher()
  43749. {
  43750. component->removeComponentListener (this);
  43751. unregister();
  43752. #ifdef JUCE_DEBUG
  43753. delete deletionWatcher;
  43754. #endif
  43755. }
  43756. void ComponentMovementWatcher::componentParentHierarchyChanged (Component&)
  43757. {
  43758. #ifdef JUCE_DEBUG
  43759. // agh! don't delete the target component without deleting this object first!
  43760. jassert (! deletionWatcher->hasBeenDeleted());
  43761. #endif
  43762. if (! reentrant)
  43763. {
  43764. reentrant = true;
  43765. ComponentPeer* const peer = component->getPeer();
  43766. if (peer != lastPeer)
  43767. {
  43768. ComponentDeletionWatcher watcher (component);
  43769. componentPeerChanged();
  43770. if (watcher.hasBeenDeleted())
  43771. return;
  43772. lastPeer = peer;
  43773. }
  43774. unregister();
  43775. registerWithParentComps();
  43776. reentrant = false;
  43777. componentMovedOrResized (*component, true, true);
  43778. }
  43779. }
  43780. void ComponentMovementWatcher::componentMovedOrResized (Component&, bool wasMoved, bool wasResized)
  43781. {
  43782. #ifdef JUCE_DEBUG
  43783. // agh! don't delete the target component without deleting this object first!
  43784. jassert (! deletionWatcher->hasBeenDeleted());
  43785. #endif
  43786. if (wasMoved)
  43787. {
  43788. int x = 0, y = 0;
  43789. component->relativePositionToOtherComponent (component->getTopLevelComponent(), x, y);
  43790. wasMoved = (lastX != x || lastY != y);
  43791. lastX = x;
  43792. lastY = y;
  43793. }
  43794. wasResized = (lastWidth != component->getWidth() || lastHeight != component->getHeight());
  43795. lastWidth = component->getWidth();
  43796. lastHeight = component->getHeight();
  43797. if (wasMoved || wasResized)
  43798. componentMovedOrResized (wasMoved, wasResized);
  43799. }
  43800. void ComponentMovementWatcher::registerWithParentComps() throw()
  43801. {
  43802. Component* p = component->getParentComponent();
  43803. while (p != 0)
  43804. {
  43805. p->addComponentListener (this);
  43806. registeredParentComps.add (p);
  43807. p = p->getParentComponent();
  43808. }
  43809. }
  43810. void ComponentMovementWatcher::unregister() throw()
  43811. {
  43812. for (int i = registeredParentComps.size(); --i >= 0;)
  43813. ((Component*) registeredParentComps.getUnchecked(i))->removeComponentListener (this);
  43814. registeredParentComps.clear();
  43815. }
  43816. END_JUCE_NAMESPACE
  43817. /********* End of inlined file: juce_ComponentMovementWatcher.cpp *********/
  43818. /********* Start of inlined file: juce_GroupComponent.cpp *********/
  43819. BEGIN_JUCE_NAMESPACE
  43820. GroupComponent::GroupComponent (const String& componentName,
  43821. const String& labelText)
  43822. : Component (componentName),
  43823. text (labelText),
  43824. justification (Justification::left)
  43825. {
  43826. setInterceptsMouseClicks (false, true);
  43827. }
  43828. GroupComponent::~GroupComponent()
  43829. {
  43830. }
  43831. void GroupComponent::setText (const String& newText) throw()
  43832. {
  43833. if (text != newText)
  43834. {
  43835. text = newText;
  43836. repaint();
  43837. }
  43838. }
  43839. const String GroupComponent::getText() const throw()
  43840. {
  43841. return text;
  43842. }
  43843. void GroupComponent::setTextLabelPosition (const Justification& newJustification)
  43844. {
  43845. if (justification.getFlags() != newJustification.getFlags())
  43846. {
  43847. justification = newJustification;
  43848. repaint();
  43849. }
  43850. }
  43851. void GroupComponent::paint (Graphics& g)
  43852. {
  43853. getLookAndFeel()
  43854. .drawGroupComponentOutline (g, getWidth(), getHeight(),
  43855. text, justification,
  43856. *this);
  43857. }
  43858. void GroupComponent::enablementChanged()
  43859. {
  43860. repaint();
  43861. }
  43862. void GroupComponent::colourChanged()
  43863. {
  43864. repaint();
  43865. }
  43866. END_JUCE_NAMESPACE
  43867. /********* End of inlined file: juce_GroupComponent.cpp *********/
  43868. /********* Start of inlined file: juce_MultiDocumentPanel.cpp *********/
  43869. BEGIN_JUCE_NAMESPACE
  43870. MultiDocumentPanelWindow::MultiDocumentPanelWindow (const Colour& backgroundColour)
  43871. : DocumentWindow (String::empty, backgroundColour,
  43872. DocumentWindow::maximiseButton | DocumentWindow::closeButton, false)
  43873. {
  43874. }
  43875. MultiDocumentPanelWindow::~MultiDocumentPanelWindow()
  43876. {
  43877. }
  43878. void MultiDocumentPanelWindow::maximiseButtonPressed()
  43879. {
  43880. MultiDocumentPanel* const owner = getOwner();
  43881. jassert (owner != 0); // these windows are only designed to be used inside a MultiDocumentPanel!
  43882. if (owner != 0)
  43883. owner->setLayoutMode (MultiDocumentPanel::MaximisedWindowsWithTabs);
  43884. }
  43885. void MultiDocumentPanelWindow::closeButtonPressed()
  43886. {
  43887. MultiDocumentPanel* const owner = getOwner();
  43888. jassert (owner != 0); // these windows are only designed to be used inside a MultiDocumentPanel!
  43889. if (owner != 0)
  43890. owner->closeDocument (getContentComponent(), true);
  43891. }
  43892. void MultiDocumentPanelWindow::activeWindowStatusChanged()
  43893. {
  43894. DocumentWindow::activeWindowStatusChanged();
  43895. updateOrder();
  43896. }
  43897. void MultiDocumentPanelWindow::broughtToFront()
  43898. {
  43899. DocumentWindow::broughtToFront();
  43900. updateOrder();
  43901. }
  43902. void MultiDocumentPanelWindow::updateOrder()
  43903. {
  43904. MultiDocumentPanel* const owner = getOwner();
  43905. if (owner != 0)
  43906. owner->updateOrder();
  43907. }
  43908. MultiDocumentPanel* MultiDocumentPanelWindow::getOwner() const throw()
  43909. {
  43910. // (unable to use the syntax findParentComponentOfClass <MultiDocumentPanel> () because of a VC6 compiler bug)
  43911. return findParentComponentOfClass ((MultiDocumentPanel*) 0);
  43912. }
  43913. class MDITabbedComponentInternal : public TabbedComponent
  43914. {
  43915. public:
  43916. MDITabbedComponentInternal()
  43917. : TabbedComponent (TabbedButtonBar::TabsAtTop)
  43918. {
  43919. }
  43920. ~MDITabbedComponentInternal()
  43921. {
  43922. }
  43923. void currentTabChanged (const int, const String&)
  43924. {
  43925. // (unable to use the syntax findParentComponentOfClass <MultiDocumentPanel> () because of a VC6 compiler bug)
  43926. MultiDocumentPanel* const owner = findParentComponentOfClass ((MultiDocumentPanel*) 0);
  43927. if (owner != 0)
  43928. owner->updateOrder();
  43929. }
  43930. };
  43931. MultiDocumentPanel::MultiDocumentPanel()
  43932. : mode (MaximisedWindowsWithTabs),
  43933. tabComponent (0),
  43934. backgroundColour (Colours::lightblue),
  43935. maximumNumDocuments (0),
  43936. numDocsBeforeTabsUsed (0)
  43937. {
  43938. setOpaque (true);
  43939. }
  43940. MultiDocumentPanel::~MultiDocumentPanel()
  43941. {
  43942. closeAllDocuments (false);
  43943. }
  43944. static bool shouldDeleteComp (Component* const c)
  43945. {
  43946. return c->getComponentPropertyBool (T("mdiDocumentDelete_"), false);
  43947. }
  43948. bool MultiDocumentPanel::closeAllDocuments (const bool checkItsOkToCloseFirst)
  43949. {
  43950. while (components.size() > 0)
  43951. if (! closeDocument (components.getLast(), checkItsOkToCloseFirst))
  43952. return false;
  43953. return true;
  43954. }
  43955. MultiDocumentPanelWindow* MultiDocumentPanel::createNewDocumentWindow()
  43956. {
  43957. return new MultiDocumentPanelWindow (backgroundColour);
  43958. }
  43959. void MultiDocumentPanel::addWindow (Component* component)
  43960. {
  43961. MultiDocumentPanelWindow* const dw = createNewDocumentWindow();
  43962. dw->setResizable (true, false);
  43963. dw->setContentComponent (component, false, true);
  43964. dw->setName (component->getName());
  43965. dw->setBackgroundColour (component->getComponentPropertyColour (T("mdiDocumentBkg_"), false, backgroundColour));
  43966. int x = 4;
  43967. Component* const topComp = getChildComponent (getNumChildComponents() - 1);
  43968. if (topComp != 0 && topComp->getX() == x && topComp->getY() == x)
  43969. x += 16;
  43970. dw->setTopLeftPosition (x, x);
  43971. if (component->getComponentProperty (T("mdiDocumentPos_"), false, String::empty).isNotEmpty())
  43972. dw->restoreWindowStateFromString (component->getComponentProperty (T("mdiDocumentPos_"), false, String::empty));
  43973. addAndMakeVisible (dw);
  43974. dw->toFront (true);
  43975. }
  43976. bool MultiDocumentPanel::addDocument (Component* const component,
  43977. const Colour& backgroundColour,
  43978. const bool deleteWhenRemoved)
  43979. {
  43980. // If you try passing a full DocumentWindow or ResizableWindow in here, you'll end up
  43981. // with a frame-within-a-frame! Just pass in the bare content component.
  43982. jassert (dynamic_cast <ResizableWindow*> (component) == 0);
  43983. if (component == 0 || (maximumNumDocuments > 0 && components.size() >= maximumNumDocuments))
  43984. return false;
  43985. components.add (component);
  43986. component->setComponentProperty (T("mdiDocumentDelete_"), deleteWhenRemoved);
  43987. component->setComponentProperty (T("mdiDocumentBkg_"), backgroundColour);
  43988. component->addComponentListener (this);
  43989. if (mode == FloatingWindows)
  43990. {
  43991. if (isFullscreenWhenOneDocument())
  43992. {
  43993. if (components.size() == 1)
  43994. {
  43995. addAndMakeVisible (component);
  43996. }
  43997. else
  43998. {
  43999. if (components.size() == 2)
  44000. addWindow (components.getFirst());
  44001. addWindow (component);
  44002. }
  44003. }
  44004. else
  44005. {
  44006. addWindow (component);
  44007. }
  44008. }
  44009. else
  44010. {
  44011. if (tabComponent == 0 && components.size() > numDocsBeforeTabsUsed)
  44012. {
  44013. addAndMakeVisible (tabComponent = new MDITabbedComponentInternal());
  44014. Array <Component*> temp (components);
  44015. for (int i = 0; i < temp.size(); ++i)
  44016. tabComponent->addTab (temp[i]->getName(), backgroundColour, temp[i], false);
  44017. resized();
  44018. }
  44019. else
  44020. {
  44021. if (tabComponent != 0)
  44022. tabComponent->addTab (component->getName(), backgroundColour, component, false);
  44023. else
  44024. addAndMakeVisible (component);
  44025. }
  44026. setActiveDocument (component);
  44027. }
  44028. resized();
  44029. activeDocumentChanged();
  44030. return true;
  44031. }
  44032. bool MultiDocumentPanel::closeDocument (Component* component,
  44033. const bool checkItsOkToCloseFirst)
  44034. {
  44035. if (components.contains (component))
  44036. {
  44037. if (checkItsOkToCloseFirst && ! tryToCloseDocument (component))
  44038. return false;
  44039. component->removeComponentListener (this);
  44040. const bool shouldDelete = shouldDeleteComp (component);
  44041. component->removeComponentProperty (T("mdiDocumentDelete_"));
  44042. component->removeComponentProperty (T("mdiDocumentBkg_"));
  44043. if (mode == FloatingWindows)
  44044. {
  44045. for (int i = getNumChildComponents(); --i >= 0;)
  44046. {
  44047. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  44048. if (dw != 0 && dw->getContentComponent() == component)
  44049. {
  44050. dw->setContentComponent (0, false);
  44051. delete dw;
  44052. break;
  44053. }
  44054. }
  44055. if (shouldDelete)
  44056. delete component;
  44057. components.removeValue (component);
  44058. if (isFullscreenWhenOneDocument() && components.size() == 1)
  44059. {
  44060. for (int i = getNumChildComponents(); --i >= 0;)
  44061. {
  44062. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  44063. if (dw != 0)
  44064. {
  44065. dw->setContentComponent (0, false);
  44066. delete dw;
  44067. }
  44068. }
  44069. addAndMakeVisible (components.getFirst());
  44070. }
  44071. }
  44072. else
  44073. {
  44074. jassert (components.indexOf (component) >= 0);
  44075. if (tabComponent != 0)
  44076. {
  44077. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  44078. if (tabComponent->getTabContentComponent (i) == component)
  44079. tabComponent->removeTab (i);
  44080. }
  44081. else
  44082. {
  44083. removeChildComponent (component);
  44084. }
  44085. if (shouldDelete)
  44086. delete component;
  44087. if (tabComponent != 0 && tabComponent->getNumTabs() <= numDocsBeforeTabsUsed)
  44088. deleteAndZero (tabComponent);
  44089. components.removeValue (component);
  44090. if (components.size() > 0 && tabComponent == 0)
  44091. addAndMakeVisible (components.getFirst());
  44092. }
  44093. resized();
  44094. activeDocumentChanged();
  44095. }
  44096. else
  44097. {
  44098. jassertfalse
  44099. }
  44100. return true;
  44101. }
  44102. int MultiDocumentPanel::getNumDocuments() const throw()
  44103. {
  44104. return components.size();
  44105. }
  44106. Component* MultiDocumentPanel::getDocument (const int index) const throw()
  44107. {
  44108. return components [index];
  44109. }
  44110. Component* MultiDocumentPanel::getActiveDocument() const throw()
  44111. {
  44112. if (mode == FloatingWindows)
  44113. {
  44114. for (int i = getNumChildComponents(); --i >= 0;)
  44115. {
  44116. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  44117. if (dw != 0 && dw->isActiveWindow())
  44118. return dw->getContentComponent();
  44119. }
  44120. }
  44121. return components.getLast();
  44122. }
  44123. void MultiDocumentPanel::setActiveDocument (Component* component)
  44124. {
  44125. if (mode == FloatingWindows)
  44126. {
  44127. component = getContainerComp (component);
  44128. if (component != 0)
  44129. component->toFront (true);
  44130. }
  44131. else if (tabComponent != 0)
  44132. {
  44133. jassert (components.indexOf (component) >= 0);
  44134. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  44135. {
  44136. if (tabComponent->getTabContentComponent (i) == component)
  44137. {
  44138. tabComponent->setCurrentTabIndex (i);
  44139. break;
  44140. }
  44141. }
  44142. }
  44143. else
  44144. {
  44145. component->grabKeyboardFocus();
  44146. }
  44147. }
  44148. void MultiDocumentPanel::activeDocumentChanged()
  44149. {
  44150. }
  44151. void MultiDocumentPanel::setMaximumNumDocuments (const int newNumber)
  44152. {
  44153. maximumNumDocuments = newNumber;
  44154. }
  44155. void MultiDocumentPanel::useFullscreenWhenOneDocument (const bool shouldUseTabs)
  44156. {
  44157. numDocsBeforeTabsUsed = shouldUseTabs ? 1 : 0;
  44158. }
  44159. bool MultiDocumentPanel::isFullscreenWhenOneDocument() const throw()
  44160. {
  44161. return numDocsBeforeTabsUsed != 0;
  44162. }
  44163. void MultiDocumentPanel::setLayoutMode (const LayoutMode newLayoutMode)
  44164. {
  44165. if (mode != newLayoutMode)
  44166. {
  44167. mode = newLayoutMode;
  44168. if (mode == FloatingWindows)
  44169. {
  44170. deleteAndZero (tabComponent);
  44171. }
  44172. else
  44173. {
  44174. for (int i = getNumChildComponents(); --i >= 0;)
  44175. {
  44176. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  44177. if (dw != 0)
  44178. {
  44179. dw->getContentComponent()->setComponentProperty (T("mdiDocumentPos_"), dw->getWindowStateAsString());
  44180. dw->setContentComponent (0, false);
  44181. delete dw;
  44182. }
  44183. }
  44184. }
  44185. resized();
  44186. const Array <Component*> tempComps (components);
  44187. components.clear();
  44188. for (int i = 0; i < tempComps.size(); ++i)
  44189. {
  44190. Component* const c = tempComps.getUnchecked(i);
  44191. addDocument (c,
  44192. c->getComponentPropertyColour (T("mdiDocumentBkg_"), false, Colours::white),
  44193. shouldDeleteComp (c));
  44194. }
  44195. }
  44196. }
  44197. void MultiDocumentPanel::setBackgroundColour (const Colour& newBackgroundColour)
  44198. {
  44199. if (backgroundColour != newBackgroundColour)
  44200. {
  44201. backgroundColour = newBackgroundColour;
  44202. setOpaque (newBackgroundColour.isOpaque());
  44203. repaint();
  44204. }
  44205. }
  44206. void MultiDocumentPanel::paint (Graphics& g)
  44207. {
  44208. g.fillAll (backgroundColour);
  44209. }
  44210. void MultiDocumentPanel::resized()
  44211. {
  44212. if (mode == MaximisedWindowsWithTabs || components.size() == numDocsBeforeTabsUsed)
  44213. {
  44214. for (int i = getNumChildComponents(); --i >= 0;)
  44215. getChildComponent (i)->setBounds (0, 0, getWidth(), getHeight());
  44216. }
  44217. setWantsKeyboardFocus (components.size() == 0);
  44218. }
  44219. Component* MultiDocumentPanel::getContainerComp (Component* c) const
  44220. {
  44221. if (mode == FloatingWindows)
  44222. {
  44223. for (int i = 0; i < getNumChildComponents(); ++i)
  44224. {
  44225. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  44226. if (dw != 0 && dw->getContentComponent() == c)
  44227. {
  44228. c = dw;
  44229. break;
  44230. }
  44231. }
  44232. }
  44233. return c;
  44234. }
  44235. void MultiDocumentPanel::componentNameChanged (Component&)
  44236. {
  44237. if (mode == FloatingWindows)
  44238. {
  44239. for (int i = 0; i < getNumChildComponents(); ++i)
  44240. {
  44241. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  44242. if (dw != 0)
  44243. dw->setName (dw->getContentComponent()->getName());
  44244. }
  44245. }
  44246. else if (tabComponent != 0)
  44247. {
  44248. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  44249. tabComponent->setTabName (i, tabComponent->getTabContentComponent (i)->getName());
  44250. }
  44251. }
  44252. void MultiDocumentPanel::updateOrder()
  44253. {
  44254. const Array <Component*> oldList (components);
  44255. if (mode == FloatingWindows)
  44256. {
  44257. components.clear();
  44258. for (int i = 0; i < getNumChildComponents(); ++i)
  44259. {
  44260. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  44261. if (dw != 0)
  44262. components.add (dw->getContentComponent());
  44263. }
  44264. }
  44265. else
  44266. {
  44267. if (tabComponent != 0)
  44268. {
  44269. Component* const current = tabComponent->getCurrentContentComponent();
  44270. if (current != 0)
  44271. {
  44272. components.removeValue (current);
  44273. components.add (current);
  44274. }
  44275. }
  44276. }
  44277. if (components != oldList)
  44278. activeDocumentChanged();
  44279. }
  44280. END_JUCE_NAMESPACE
  44281. /********* End of inlined file: juce_MultiDocumentPanel.cpp *********/
  44282. /********* Start of inlined file: juce_ResizableBorderComponent.cpp *********/
  44283. BEGIN_JUCE_NAMESPACE
  44284. const int zoneL = 1;
  44285. const int zoneR = 2;
  44286. const int zoneT = 4;
  44287. const int zoneB = 8;
  44288. ResizableBorderComponent::ResizableBorderComponent (Component* const componentToResize,
  44289. ComponentBoundsConstrainer* const constrainer_)
  44290. : component (componentToResize),
  44291. constrainer (constrainer_),
  44292. borderSize (5),
  44293. mouseZone (0)
  44294. {
  44295. }
  44296. ResizableBorderComponent::~ResizableBorderComponent()
  44297. {
  44298. }
  44299. void ResizableBorderComponent::paint (Graphics& g)
  44300. {
  44301. getLookAndFeel().drawResizableFrame (g, getWidth(), getHeight(), borderSize);
  44302. }
  44303. void ResizableBorderComponent::mouseEnter (const MouseEvent& e)
  44304. {
  44305. updateMouseZone (e);
  44306. }
  44307. void ResizableBorderComponent::mouseMove (const MouseEvent& e)
  44308. {
  44309. updateMouseZone (e);
  44310. }
  44311. void ResizableBorderComponent::mouseDown (const MouseEvent& e)
  44312. {
  44313. if (component->isValidComponent())
  44314. {
  44315. updateMouseZone (e);
  44316. originalX = component->getX();
  44317. originalY = component->getY();
  44318. originalW = component->getWidth();
  44319. originalH = component->getHeight();
  44320. if (constrainer != 0)
  44321. constrainer->resizeStart();
  44322. }
  44323. else
  44324. {
  44325. jassertfalse
  44326. }
  44327. }
  44328. void ResizableBorderComponent::mouseDrag (const MouseEvent& e)
  44329. {
  44330. if (! component->isValidComponent())
  44331. {
  44332. jassertfalse
  44333. return;
  44334. }
  44335. int x = originalX;
  44336. int y = originalY;
  44337. int w = originalW;
  44338. int h = originalH;
  44339. const int dx = e.getDistanceFromDragStartX();
  44340. const int dy = e.getDistanceFromDragStartY();
  44341. if ((mouseZone & zoneL) != 0)
  44342. {
  44343. x += dx;
  44344. w -= dx;
  44345. }
  44346. if ((mouseZone & zoneT) != 0)
  44347. {
  44348. y += dy;
  44349. h -= dy;
  44350. }
  44351. if ((mouseZone & zoneR) != 0)
  44352. w += dx;
  44353. if ((mouseZone & zoneB) != 0)
  44354. h += dy;
  44355. if (constrainer != 0)
  44356. constrainer->setBoundsForComponent (component,
  44357. x, y, w, h,
  44358. (mouseZone & zoneT) != 0,
  44359. (mouseZone & zoneL) != 0,
  44360. (mouseZone & zoneB) != 0,
  44361. (mouseZone & zoneR) != 0);
  44362. else
  44363. component->setBounds (x, y, w, h);
  44364. }
  44365. void ResizableBorderComponent::mouseUp (const MouseEvent&)
  44366. {
  44367. if (constrainer != 0)
  44368. constrainer->resizeEnd();
  44369. }
  44370. bool ResizableBorderComponent::hitTest (int x, int y)
  44371. {
  44372. return x < borderSize.getLeft()
  44373. || x >= getWidth() - borderSize.getRight()
  44374. || y < borderSize.getTop()
  44375. || y >= getHeight() - borderSize.getBottom();
  44376. }
  44377. void ResizableBorderComponent::setBorderThickness (const BorderSize& newBorderSize) throw()
  44378. {
  44379. if (borderSize != newBorderSize)
  44380. {
  44381. borderSize = newBorderSize;
  44382. repaint();
  44383. }
  44384. }
  44385. const BorderSize ResizableBorderComponent::getBorderThickness() const throw()
  44386. {
  44387. return borderSize;
  44388. }
  44389. void ResizableBorderComponent::updateMouseZone (const MouseEvent& e) throw()
  44390. {
  44391. int newZone = 0;
  44392. if (ResizableBorderComponent::hitTest (e.x, e.y))
  44393. {
  44394. if (e.x < jmax (borderSize.getLeft(), proportionOfWidth (0.1f)))
  44395. newZone |= zoneL;
  44396. else if (e.x >= jmin (getWidth() - borderSize.getRight(), proportionOfWidth (0.9f)))
  44397. newZone |= zoneR;
  44398. if (e.y < jmax (borderSize.getTop(), proportionOfHeight (0.1f)))
  44399. newZone |= zoneT;
  44400. else if (e.y >= jmin (getHeight() - borderSize.getBottom(), proportionOfHeight (0.9f)))
  44401. newZone |= zoneB;
  44402. }
  44403. if (mouseZone != newZone)
  44404. {
  44405. mouseZone = newZone;
  44406. MouseCursor::StandardCursorType mc = MouseCursor::NormalCursor;
  44407. switch (newZone)
  44408. {
  44409. case (zoneL | zoneT):
  44410. mc = MouseCursor::TopLeftCornerResizeCursor;
  44411. break;
  44412. case zoneT:
  44413. mc = MouseCursor::TopEdgeResizeCursor;
  44414. break;
  44415. case (zoneR | zoneT):
  44416. mc = MouseCursor::TopRightCornerResizeCursor;
  44417. break;
  44418. case zoneL:
  44419. mc = MouseCursor::LeftEdgeResizeCursor;
  44420. break;
  44421. case zoneR:
  44422. mc = MouseCursor::RightEdgeResizeCursor;
  44423. break;
  44424. case (zoneL | zoneB):
  44425. mc = MouseCursor::BottomLeftCornerResizeCursor;
  44426. break;
  44427. case zoneB:
  44428. mc = MouseCursor::BottomEdgeResizeCursor;
  44429. break;
  44430. case (zoneR | zoneB):
  44431. mc = MouseCursor::BottomRightCornerResizeCursor;
  44432. break;
  44433. default:
  44434. break;
  44435. }
  44436. setMouseCursor (mc);
  44437. }
  44438. }
  44439. END_JUCE_NAMESPACE
  44440. /********* End of inlined file: juce_ResizableBorderComponent.cpp *********/
  44441. /********* Start of inlined file: juce_ResizableCornerComponent.cpp *********/
  44442. BEGIN_JUCE_NAMESPACE
  44443. ResizableCornerComponent::ResizableCornerComponent (Component* const componentToResize,
  44444. ComponentBoundsConstrainer* const constrainer_)
  44445. : component (componentToResize),
  44446. constrainer (constrainer_)
  44447. {
  44448. setRepaintsOnMouseActivity (true);
  44449. setMouseCursor (MouseCursor::BottomRightCornerResizeCursor);
  44450. }
  44451. ResizableCornerComponent::~ResizableCornerComponent()
  44452. {
  44453. }
  44454. void ResizableCornerComponent::paint (Graphics& g)
  44455. {
  44456. getLookAndFeel()
  44457. .drawCornerResizer (g, getWidth(), getHeight(),
  44458. isMouseOverOrDragging(),
  44459. isMouseButtonDown());
  44460. }
  44461. void ResizableCornerComponent::mouseDown (const MouseEvent&)
  44462. {
  44463. if (component->isValidComponent())
  44464. {
  44465. originalX = component->getX();
  44466. originalY = component->getY();
  44467. originalW = component->getWidth();
  44468. originalH = component->getHeight();
  44469. if (constrainer != 0)
  44470. constrainer->resizeStart();
  44471. }
  44472. else
  44473. {
  44474. jassertfalse
  44475. }
  44476. }
  44477. void ResizableCornerComponent::mouseDrag (const MouseEvent& e)
  44478. {
  44479. if (! component->isValidComponent())
  44480. {
  44481. jassertfalse
  44482. return;
  44483. }
  44484. int x = originalX;
  44485. int y = originalY;
  44486. int w = originalW + e.getDistanceFromDragStartX();
  44487. int h = originalH + e.getDistanceFromDragStartY();
  44488. if (constrainer != 0)
  44489. constrainer->setBoundsForComponent (component, x, y, w, h,
  44490. false, false, true, true);
  44491. else
  44492. component->setBounds (x, y, w, h);
  44493. }
  44494. void ResizableCornerComponent::mouseUp (const MouseEvent&)
  44495. {
  44496. if (constrainer != 0)
  44497. constrainer->resizeStart();
  44498. }
  44499. bool ResizableCornerComponent::hitTest (int x, int y)
  44500. {
  44501. if (getWidth() <= 0)
  44502. return false;
  44503. const int yAtX = getHeight() - (getHeight() * x / getWidth());
  44504. return y >= yAtX - getHeight() / 4;
  44505. }
  44506. END_JUCE_NAMESPACE
  44507. /********* End of inlined file: juce_ResizableCornerComponent.cpp *********/
  44508. /********* Start of inlined file: juce_ScrollBar.cpp *********/
  44509. BEGIN_JUCE_NAMESPACE
  44510. class ScrollbarButton : public Button
  44511. {
  44512. public:
  44513. int direction;
  44514. ScrollbarButton (const int direction_,
  44515. ScrollBar& owner_) throw()
  44516. : Button (String::empty),
  44517. direction (direction_),
  44518. owner (owner_)
  44519. {
  44520. setWantsKeyboardFocus (false);
  44521. }
  44522. ~ScrollbarButton()
  44523. {
  44524. }
  44525. void paintButton (Graphics& g,
  44526. bool isMouseOver,
  44527. bool isMouseDown)
  44528. {
  44529. getLookAndFeel()
  44530. .drawScrollbarButton (g, owner,
  44531. getWidth(), getHeight(),
  44532. direction,
  44533. owner.isVertical(),
  44534. isMouseOver, isMouseDown);
  44535. }
  44536. void clicked()
  44537. {
  44538. owner.moveScrollbarInSteps ((direction == 1 || direction == 2) ? 1 : -1);
  44539. }
  44540. juce_UseDebuggingNewOperator
  44541. private:
  44542. ScrollBar& owner;
  44543. ScrollbarButton (const ScrollbarButton&);
  44544. const ScrollbarButton& operator= (const ScrollbarButton&);
  44545. };
  44546. ScrollBar::ScrollBar (const bool vertical_,
  44547. const bool buttonsAreVisible)
  44548. : minimum (0.0),
  44549. maximum (1.0),
  44550. rangeStart (0.0),
  44551. rangeSize (0.1),
  44552. singleStepSize (0.1),
  44553. thumbAreaStart (0),
  44554. thumbAreaSize (0),
  44555. thumbStart (0),
  44556. thumbSize (0),
  44557. initialDelayInMillisecs (100),
  44558. repeatDelayInMillisecs (50),
  44559. minimumDelayInMillisecs (10),
  44560. vertical (vertical_),
  44561. isDraggingThumb (false),
  44562. alwaysVisible (false),
  44563. upButton (0),
  44564. downButton (0),
  44565. listeners (2)
  44566. {
  44567. setButtonVisibility (buttonsAreVisible);
  44568. setRepaintsOnMouseActivity (true);
  44569. setFocusContainer (true);
  44570. }
  44571. ScrollBar::~ScrollBar()
  44572. {
  44573. deleteAllChildren();
  44574. }
  44575. void ScrollBar::setRangeLimits (const double newMinimum,
  44576. const double newMaximum) throw()
  44577. {
  44578. minimum = newMinimum;
  44579. maximum = newMaximum;
  44580. jassert (maximum >= minimum); // these can't be the wrong way round!
  44581. setCurrentRangeStart (rangeStart);
  44582. updateThumbPosition();
  44583. }
  44584. void ScrollBar::setCurrentRange (double newStart,
  44585. double newSize) throw()
  44586. {
  44587. newSize = jlimit (0.0, maximum - minimum, newSize);
  44588. newStart = jlimit (minimum, maximum - newSize, newStart);
  44589. if (rangeStart != newStart
  44590. || rangeSize != newSize)
  44591. {
  44592. rangeStart = newStart;
  44593. rangeSize = newSize;
  44594. updateThumbPosition();
  44595. triggerAsyncUpdate();
  44596. }
  44597. }
  44598. void ScrollBar::setCurrentRangeStart (double newStart) throw()
  44599. {
  44600. setCurrentRange (newStart, rangeSize);
  44601. }
  44602. void ScrollBar::setSingleStepSize (const double newSingleStepSize) throw()
  44603. {
  44604. singleStepSize = newSingleStepSize;
  44605. }
  44606. void ScrollBar::moveScrollbarInSteps (const int howManySteps) throw()
  44607. {
  44608. setCurrentRangeStart (rangeStart + howManySteps * singleStepSize);
  44609. }
  44610. void ScrollBar::moveScrollbarInPages (const int howManyPages) throw()
  44611. {
  44612. setCurrentRangeStart (rangeStart + howManyPages * rangeSize);
  44613. }
  44614. void ScrollBar::scrollToTop() throw()
  44615. {
  44616. setCurrentRangeStart (minimum);
  44617. }
  44618. void ScrollBar::scrollToBottom() throw()
  44619. {
  44620. setCurrentRangeStart (maximum - rangeSize);
  44621. }
  44622. void ScrollBar::setButtonRepeatSpeed (const int initialDelayInMillisecs_,
  44623. const int repeatDelayInMillisecs_,
  44624. const int minimumDelayInMillisecs_) throw()
  44625. {
  44626. initialDelayInMillisecs = initialDelayInMillisecs_;
  44627. repeatDelayInMillisecs = repeatDelayInMillisecs_;
  44628. minimumDelayInMillisecs = minimumDelayInMillisecs_;
  44629. if (upButton != 0)
  44630. {
  44631. upButton->setRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  44632. downButton->setRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  44633. }
  44634. }
  44635. void ScrollBar::addListener (ScrollBarListener* const listener) throw()
  44636. {
  44637. jassert (listener != 0);
  44638. if (listener != 0)
  44639. listeners.add (listener);
  44640. }
  44641. void ScrollBar::removeListener (ScrollBarListener* const listener) throw()
  44642. {
  44643. listeners.removeValue (listener);
  44644. }
  44645. void ScrollBar::handleAsyncUpdate()
  44646. {
  44647. const double value = getCurrentRangeStart();
  44648. for (int i = listeners.size(); --i >= 0;)
  44649. {
  44650. ((ScrollBarListener*) listeners.getUnchecked (i))->scrollBarMoved (this, value);
  44651. i = jmin (i, listeners.size());
  44652. }
  44653. }
  44654. void ScrollBar::updateThumbPosition() throw()
  44655. {
  44656. int newThumbSize = roundDoubleToInt ((maximum > minimum) ? (rangeSize * thumbAreaSize) / (maximum - minimum)
  44657. : thumbAreaSize);
  44658. if (newThumbSize < getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  44659. newThumbSize = jmin (getLookAndFeel().getMinimumScrollbarThumbSize (*this), thumbAreaSize - 1);
  44660. if (newThumbSize > thumbAreaSize)
  44661. newThumbSize = thumbAreaSize;
  44662. int newThumbStart = thumbAreaStart;
  44663. if (maximum - minimum > rangeSize)
  44664. newThumbStart += roundDoubleToInt (((rangeStart - minimum) * (thumbAreaSize - newThumbSize))
  44665. / ((maximum - minimum) - rangeSize));
  44666. setVisible (alwaysVisible || (maximum - minimum > rangeSize && rangeSize > 0.0));
  44667. if (thumbStart != newThumbStart || thumbSize != newThumbSize)
  44668. {
  44669. const int repaintStart = jmin (thumbStart, newThumbStart) - 4;
  44670. const int repaintSize = jmax (thumbStart + thumbSize, newThumbStart + newThumbSize) + 8 - repaintStart;
  44671. if (vertical)
  44672. repaint (0, repaintStart, getWidth(), repaintSize);
  44673. else
  44674. repaint (repaintStart, 0, repaintSize, getHeight());
  44675. thumbStart = newThumbStart;
  44676. thumbSize = newThumbSize;
  44677. }
  44678. }
  44679. void ScrollBar::setOrientation (const bool shouldBeVertical) throw()
  44680. {
  44681. if (vertical != shouldBeVertical)
  44682. {
  44683. vertical = shouldBeVertical;
  44684. if (upButton != 0)
  44685. {
  44686. ((ScrollbarButton*) upButton)->direction = (vertical) ? 0 : 3;
  44687. ((ScrollbarButton*) downButton)->direction = (vertical) ? 2 : 1;
  44688. }
  44689. updateThumbPosition();
  44690. }
  44691. }
  44692. void ScrollBar::setButtonVisibility (const bool buttonsAreVisible)
  44693. {
  44694. deleteAndZero (upButton);
  44695. deleteAndZero (downButton);
  44696. if (buttonsAreVisible)
  44697. {
  44698. addAndMakeVisible (upButton = new ScrollbarButton ((vertical) ? 0 : 3, *this));
  44699. addAndMakeVisible (downButton = new ScrollbarButton ((vertical) ? 2 : 1, *this));
  44700. setButtonRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  44701. }
  44702. updateThumbPosition();
  44703. }
  44704. void ScrollBar::setAutoHide (const bool shouldHideWhenFullRange)
  44705. {
  44706. alwaysVisible = ! shouldHideWhenFullRange;
  44707. updateThumbPosition();
  44708. }
  44709. void ScrollBar::paint (Graphics& g)
  44710. {
  44711. if (thumbAreaSize > 0)
  44712. {
  44713. LookAndFeel& lf = getLookAndFeel();
  44714. const int thumb = (thumbAreaSize > lf.getMinimumScrollbarThumbSize (*this))
  44715. ? thumbSize : 0;
  44716. if (vertical)
  44717. {
  44718. lf.drawScrollbar (g, *this,
  44719. 0, thumbAreaStart,
  44720. getWidth(), thumbAreaSize,
  44721. vertical,
  44722. thumbStart, thumb,
  44723. isMouseOver(), isMouseButtonDown());
  44724. }
  44725. else
  44726. {
  44727. lf.drawScrollbar (g, *this,
  44728. thumbAreaStart, 0,
  44729. thumbAreaSize, getHeight(),
  44730. vertical,
  44731. thumbStart, thumb,
  44732. isMouseOver(), isMouseButtonDown());
  44733. }
  44734. }
  44735. }
  44736. void ScrollBar::lookAndFeelChanged()
  44737. {
  44738. setComponentEffect (getLookAndFeel().getScrollbarEffect());
  44739. }
  44740. void ScrollBar::resized()
  44741. {
  44742. const int length = ((vertical) ? getHeight() : getWidth());
  44743. const int buttonSize = (upButton != 0) ? jmin (getLookAndFeel().getScrollbarButtonSize (*this), (length >> 1))
  44744. : 0;
  44745. if (length < 32 + getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  44746. {
  44747. thumbAreaStart = length >> 1;
  44748. thumbAreaSize = 0;
  44749. }
  44750. else
  44751. {
  44752. thumbAreaStart = buttonSize;
  44753. thumbAreaSize = length - (buttonSize << 1);
  44754. }
  44755. if (upButton != 0)
  44756. {
  44757. if (vertical)
  44758. {
  44759. upButton->setBounds (0, 0, getWidth(), buttonSize);
  44760. downButton->setBounds (0, thumbAreaStart + thumbAreaSize, getWidth(), buttonSize);
  44761. }
  44762. else
  44763. {
  44764. upButton->setBounds (0, 0, buttonSize, getHeight());
  44765. downButton->setBounds (thumbAreaStart + thumbAreaSize, 0, buttonSize, getHeight());
  44766. }
  44767. }
  44768. updateThumbPosition();
  44769. }
  44770. void ScrollBar::mouseDown (const MouseEvent& e)
  44771. {
  44772. isDraggingThumb = false;
  44773. lastMousePos = vertical ? e.y : e.x;
  44774. dragStartMousePos = lastMousePos;
  44775. dragStartRange = rangeStart;
  44776. if (dragStartMousePos < thumbStart)
  44777. {
  44778. moveScrollbarInPages (-1);
  44779. startTimer (400);
  44780. }
  44781. else if (dragStartMousePos >= thumbStart + thumbSize)
  44782. {
  44783. moveScrollbarInPages (1);
  44784. startTimer (400);
  44785. }
  44786. else
  44787. {
  44788. isDraggingThumb = (thumbAreaSize > getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  44789. && (thumbAreaSize > thumbSize);
  44790. }
  44791. }
  44792. void ScrollBar::mouseDrag (const MouseEvent& e)
  44793. {
  44794. if (isDraggingThumb)
  44795. {
  44796. const int deltaPixels = ((vertical) ? e.y : e.x) - dragStartMousePos;
  44797. setCurrentRangeStart (dragStartRange
  44798. + deltaPixels * ((maximum - minimum) - rangeSize)
  44799. / (thumbAreaSize - thumbSize));
  44800. }
  44801. else
  44802. {
  44803. lastMousePos = (vertical) ? e.y : e.x;
  44804. }
  44805. }
  44806. void ScrollBar::mouseUp (const MouseEvent&)
  44807. {
  44808. isDraggingThumb = false;
  44809. stopTimer();
  44810. repaint();
  44811. }
  44812. void ScrollBar::mouseWheelMove (const MouseEvent&,
  44813. float wheelIncrementX,
  44814. float wheelIncrementY)
  44815. {
  44816. float increment = vertical ? wheelIncrementY : wheelIncrementX;
  44817. if (increment < 0)
  44818. increment = jmin (increment * 10.0f, -1.0f);
  44819. else if (increment > 0)
  44820. increment = jmax (increment * 10.0f, 1.0f);
  44821. setCurrentRangeStart (rangeStart - singleStepSize * increment);
  44822. }
  44823. void ScrollBar::timerCallback()
  44824. {
  44825. if (isMouseButtonDown())
  44826. {
  44827. startTimer (40);
  44828. if (lastMousePos < thumbStart)
  44829. setCurrentRangeStart (rangeStart - rangeSize);
  44830. else if (lastMousePos > thumbStart + thumbSize)
  44831. setCurrentRangeStart (rangeStart + rangeSize);
  44832. }
  44833. else
  44834. {
  44835. stopTimer();
  44836. }
  44837. }
  44838. bool ScrollBar::keyPressed (const KeyPress& key)
  44839. {
  44840. if (! isVisible())
  44841. return false;
  44842. if (key.isKeyCode (KeyPress::upKey) || key.isKeyCode (KeyPress::leftKey))
  44843. moveScrollbarInSteps (-1);
  44844. else if (key.isKeyCode (KeyPress::downKey) || key.isKeyCode (KeyPress::rightKey))
  44845. moveScrollbarInSteps (1);
  44846. else if (key.isKeyCode (KeyPress::pageUpKey))
  44847. moveScrollbarInPages (-1);
  44848. else if (key.isKeyCode (KeyPress::pageDownKey))
  44849. moveScrollbarInPages (1);
  44850. else if (key.isKeyCode (KeyPress::homeKey))
  44851. scrollToTop();
  44852. else if (key.isKeyCode (KeyPress::endKey))
  44853. scrollToBottom();
  44854. else
  44855. return false;
  44856. return true;
  44857. }
  44858. END_JUCE_NAMESPACE
  44859. /********* End of inlined file: juce_ScrollBar.cpp *********/
  44860. /********* Start of inlined file: juce_StretchableLayoutManager.cpp *********/
  44861. BEGIN_JUCE_NAMESPACE
  44862. StretchableLayoutManager::StretchableLayoutManager()
  44863. : totalSize (0)
  44864. {
  44865. }
  44866. StretchableLayoutManager::~StretchableLayoutManager()
  44867. {
  44868. }
  44869. void StretchableLayoutManager::clearAllItems()
  44870. {
  44871. items.clear();
  44872. totalSize = 0;
  44873. }
  44874. void StretchableLayoutManager::setItemLayout (const int itemIndex,
  44875. const double minimumSize,
  44876. const double maximumSize,
  44877. const double preferredSize)
  44878. {
  44879. ItemLayoutProperties* layout = getInfoFor (itemIndex);
  44880. if (layout == 0)
  44881. {
  44882. layout = new ItemLayoutProperties();
  44883. layout->itemIndex = itemIndex;
  44884. int i;
  44885. for (i = 0; i < items.size(); ++i)
  44886. if (items.getUnchecked (i)->itemIndex > itemIndex)
  44887. break;
  44888. items.insert (i, layout);
  44889. }
  44890. layout->minSize = minimumSize;
  44891. layout->maxSize = maximumSize;
  44892. layout->preferredSize = preferredSize;
  44893. layout->currentSize = 0;
  44894. }
  44895. bool StretchableLayoutManager::getItemLayout (const int itemIndex,
  44896. double& minimumSize,
  44897. double& maximumSize,
  44898. double& preferredSize) const
  44899. {
  44900. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  44901. if (layout != 0)
  44902. {
  44903. minimumSize = layout->minSize;
  44904. maximumSize = layout->maxSize;
  44905. preferredSize = layout->preferredSize;
  44906. return true;
  44907. }
  44908. return false;
  44909. }
  44910. void StretchableLayoutManager::setTotalSize (const int newTotalSize)
  44911. {
  44912. totalSize = newTotalSize;
  44913. fitComponentsIntoSpace (0, items.size(), totalSize, 0);
  44914. }
  44915. int StretchableLayoutManager::getItemCurrentPosition (const int itemIndex) const
  44916. {
  44917. int pos = 0;
  44918. for (int i = 0; i < itemIndex; ++i)
  44919. {
  44920. const ItemLayoutProperties* const layout = getInfoFor (i);
  44921. if (layout != 0)
  44922. pos += layout->currentSize;
  44923. }
  44924. return pos;
  44925. }
  44926. int StretchableLayoutManager::getItemCurrentAbsoluteSize (const int itemIndex) const
  44927. {
  44928. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  44929. if (layout != 0)
  44930. return layout->currentSize;
  44931. return 0;
  44932. }
  44933. double StretchableLayoutManager::getItemCurrentRelativeSize (const int itemIndex) const
  44934. {
  44935. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  44936. if (layout != 0)
  44937. return -layout->currentSize / (double) totalSize;
  44938. return 0;
  44939. }
  44940. void StretchableLayoutManager::setItemPosition (const int itemIndex,
  44941. int newPosition)
  44942. {
  44943. for (int i = items.size(); --i >= 0;)
  44944. {
  44945. const ItemLayoutProperties* const layout = items.getUnchecked(i);
  44946. if (layout->itemIndex == itemIndex)
  44947. {
  44948. int realTotalSize = jmax (totalSize, getMinimumSizeOfItems (0, items.size()));
  44949. const int minSizeAfterThisComp = getMinimumSizeOfItems (i, items.size());
  44950. const int maxSizeAfterThisComp = getMaximumSizeOfItems (i + 1, items.size());
  44951. newPosition = jmax (newPosition, totalSize - maxSizeAfterThisComp - layout->currentSize);
  44952. newPosition = jmin (newPosition, realTotalSize - minSizeAfterThisComp);
  44953. int endPos = fitComponentsIntoSpace (0, i, newPosition, 0);
  44954. endPos += layout->currentSize;
  44955. fitComponentsIntoSpace (i + 1, items.size(), totalSize - endPos, endPos);
  44956. updatePrefSizesToMatchCurrentPositions();
  44957. break;
  44958. }
  44959. }
  44960. }
  44961. void StretchableLayoutManager::layOutComponents (Component** const components,
  44962. int numComponents,
  44963. int x, int y, int w, int h,
  44964. const bool vertically,
  44965. const bool resizeOtherDimension)
  44966. {
  44967. setTotalSize (vertically ? h : w);
  44968. int pos = vertically ? y : x;
  44969. for (int i = 0; i < numComponents; ++i)
  44970. {
  44971. const ItemLayoutProperties* const layout = getInfoFor (i);
  44972. if (layout != 0)
  44973. {
  44974. Component* const c = components[i];
  44975. if (c != 0)
  44976. {
  44977. if (i == numComponents - 1)
  44978. {
  44979. // if it's the last item, crop it to exactly fit the available space..
  44980. if (resizeOtherDimension)
  44981. {
  44982. if (vertically)
  44983. c->setBounds (x, pos, w, jmax (layout->currentSize, h - pos));
  44984. else
  44985. c->setBounds (pos, y, jmax (layout->currentSize, w - pos), h);
  44986. }
  44987. else
  44988. {
  44989. if (vertically)
  44990. c->setBounds (c->getX(), pos, c->getWidth(), jmax (layout->currentSize, h - pos));
  44991. else
  44992. c->setBounds (pos, c->getY(), jmax (layout->currentSize, w - pos), c->getHeight());
  44993. }
  44994. }
  44995. else
  44996. {
  44997. if (resizeOtherDimension)
  44998. {
  44999. if (vertically)
  45000. c->setBounds (x, pos, w, layout->currentSize);
  45001. else
  45002. c->setBounds (pos, y, layout->currentSize, h);
  45003. }
  45004. else
  45005. {
  45006. if (vertically)
  45007. c->setBounds (c->getX(), pos, c->getWidth(), layout->currentSize);
  45008. else
  45009. c->setBounds (pos, c->getY(), layout->currentSize, c->getHeight());
  45010. }
  45011. }
  45012. }
  45013. pos += layout->currentSize;
  45014. }
  45015. }
  45016. }
  45017. StretchableLayoutManager::ItemLayoutProperties* StretchableLayoutManager::getInfoFor (const int itemIndex) const
  45018. {
  45019. for (int i = items.size(); --i >= 0;)
  45020. if (items.getUnchecked(i)->itemIndex == itemIndex)
  45021. return items.getUnchecked(i);
  45022. return 0;
  45023. }
  45024. int StretchableLayoutManager::fitComponentsIntoSpace (const int startIndex,
  45025. const int endIndex,
  45026. const int availableSpace,
  45027. int startPos)
  45028. {
  45029. // calculate the total sizes
  45030. int i;
  45031. double totalIdealSize = 0.0;
  45032. int totalMinimums = 0;
  45033. for (i = startIndex; i < endIndex; ++i)
  45034. {
  45035. ItemLayoutProperties* const layout = items.getUnchecked (i);
  45036. layout->currentSize = sizeToRealSize (layout->minSize, totalSize);
  45037. totalMinimums += layout->currentSize;
  45038. totalIdealSize += sizeToRealSize (layout->preferredSize, availableSpace);
  45039. }
  45040. if (totalIdealSize <= 0)
  45041. totalIdealSize = 1.0;
  45042. // now calc the best sizes..
  45043. int extraSpace = availableSpace - totalMinimums;
  45044. while (extraSpace > 0)
  45045. {
  45046. int numWantingMoreSpace = 0;
  45047. int numHavingTakenExtraSpace = 0;
  45048. // first figure out how many comps want a slice of the extra space..
  45049. for (i = startIndex; i < endIndex; ++i)
  45050. {
  45051. ItemLayoutProperties* const layout = items.getUnchecked (i);
  45052. double sizeWanted = sizeToRealSize (layout->preferredSize, availableSpace);
  45053. const int bestSize = jlimit (layout->currentSize,
  45054. jmax (layout->currentSize,
  45055. sizeToRealSize (layout->maxSize, totalSize)),
  45056. roundDoubleToInt (sizeWanted * availableSpace / totalIdealSize));
  45057. if (bestSize > layout->currentSize)
  45058. ++numWantingMoreSpace;
  45059. }
  45060. // ..share out the extra space..
  45061. for (i = startIndex; i < endIndex; ++i)
  45062. {
  45063. ItemLayoutProperties* const layout = items.getUnchecked (i);
  45064. double sizeWanted = sizeToRealSize (layout->preferredSize, availableSpace);
  45065. int bestSize = jlimit (layout->currentSize,
  45066. jmax (layout->currentSize, sizeToRealSize (layout->maxSize, totalSize)),
  45067. roundDoubleToInt (sizeWanted * availableSpace / totalIdealSize));
  45068. const int extraWanted = bestSize - layout->currentSize;
  45069. if (extraWanted > 0)
  45070. {
  45071. const int extraAllowed = jmin (extraWanted,
  45072. extraSpace / jmax (1, numWantingMoreSpace));
  45073. if (extraAllowed > 0)
  45074. {
  45075. ++numHavingTakenExtraSpace;
  45076. --numWantingMoreSpace;
  45077. layout->currentSize += extraAllowed;
  45078. extraSpace -= extraAllowed;
  45079. }
  45080. }
  45081. }
  45082. if (numHavingTakenExtraSpace <= 0)
  45083. break;
  45084. }
  45085. // ..and calculate the end position
  45086. for (i = startIndex; i < endIndex; ++i)
  45087. {
  45088. ItemLayoutProperties* const layout = items.getUnchecked(i);
  45089. startPos += layout->currentSize;
  45090. }
  45091. return startPos;
  45092. }
  45093. int StretchableLayoutManager::getMinimumSizeOfItems (const int startIndex,
  45094. const int endIndex) const
  45095. {
  45096. int totalMinimums = 0;
  45097. for (int i = startIndex; i < endIndex; ++i)
  45098. totalMinimums += sizeToRealSize (items.getUnchecked (i)->minSize, totalSize);
  45099. return totalMinimums;
  45100. }
  45101. int StretchableLayoutManager::getMaximumSizeOfItems (const int startIndex, const int endIndex) const
  45102. {
  45103. int totalMaximums = 0;
  45104. for (int i = startIndex; i < endIndex; ++i)
  45105. totalMaximums += sizeToRealSize (items.getUnchecked (i)->maxSize, totalSize);
  45106. return totalMaximums;
  45107. }
  45108. void StretchableLayoutManager::updatePrefSizesToMatchCurrentPositions()
  45109. {
  45110. for (int i = 0; i < items.size(); ++i)
  45111. {
  45112. ItemLayoutProperties* const layout = items.getUnchecked (i);
  45113. layout->preferredSize
  45114. = (layout->preferredSize < 0) ? getItemCurrentRelativeSize (i)
  45115. : getItemCurrentAbsoluteSize (i);
  45116. }
  45117. }
  45118. int StretchableLayoutManager::sizeToRealSize (double size, int totalSpace)
  45119. {
  45120. if (size < 0)
  45121. size *= -totalSpace;
  45122. return roundDoubleToInt (size);
  45123. }
  45124. END_JUCE_NAMESPACE
  45125. /********* End of inlined file: juce_StretchableLayoutManager.cpp *********/
  45126. /********* Start of inlined file: juce_StretchableLayoutResizerBar.cpp *********/
  45127. BEGIN_JUCE_NAMESPACE
  45128. StretchableLayoutResizerBar::StretchableLayoutResizerBar (StretchableLayoutManager* layout_,
  45129. const int itemIndex_,
  45130. const bool isVertical_)
  45131. : layout (layout_),
  45132. itemIndex (itemIndex_),
  45133. isVertical (isVertical_)
  45134. {
  45135. setRepaintsOnMouseActivity (true);
  45136. setMouseCursor (MouseCursor (isVertical_ ? MouseCursor::LeftRightResizeCursor
  45137. : MouseCursor::UpDownResizeCursor));
  45138. }
  45139. StretchableLayoutResizerBar::~StretchableLayoutResizerBar()
  45140. {
  45141. }
  45142. void StretchableLayoutResizerBar::paint (Graphics& g)
  45143. {
  45144. getLookAndFeel().drawStretchableLayoutResizerBar (g,
  45145. getWidth(), getHeight(),
  45146. isVertical,
  45147. isMouseOver(),
  45148. isMouseButtonDown());
  45149. }
  45150. void StretchableLayoutResizerBar::mouseDown (const MouseEvent&)
  45151. {
  45152. mouseDownPos = layout->getItemCurrentPosition (itemIndex);
  45153. }
  45154. void StretchableLayoutResizerBar::mouseDrag (const MouseEvent& e)
  45155. {
  45156. const int desiredPos = mouseDownPos + (isVertical ? e.getDistanceFromDragStartX()
  45157. : e.getDistanceFromDragStartY());
  45158. layout->setItemPosition (itemIndex, desiredPos);
  45159. hasBeenMoved();
  45160. }
  45161. void StretchableLayoutResizerBar::hasBeenMoved()
  45162. {
  45163. if (getParentComponent() != 0)
  45164. getParentComponent()->resized();
  45165. }
  45166. END_JUCE_NAMESPACE
  45167. /********* End of inlined file: juce_StretchableLayoutResizerBar.cpp *********/
  45168. /********* Start of inlined file: juce_StretchableObjectResizer.cpp *********/
  45169. BEGIN_JUCE_NAMESPACE
  45170. StretchableObjectResizer::StretchableObjectResizer()
  45171. {
  45172. }
  45173. StretchableObjectResizer::~StretchableObjectResizer()
  45174. {
  45175. }
  45176. void StretchableObjectResizer::addItem (const double size,
  45177. const double minSize, const double maxSize,
  45178. const int order)
  45179. {
  45180. jassert (order >= 0 && order < INT_MAX); // the order must be >= 0 and less than INT_MAX
  45181. Item* const item = new Item();
  45182. item->size = size;
  45183. item->minSize = minSize;
  45184. item->maxSize = maxSize;
  45185. item->order = order;
  45186. items.add (item);
  45187. }
  45188. double StretchableObjectResizer::getItemSize (const int index) const throw()
  45189. {
  45190. const Item* const it = items [index];
  45191. return it != 0 ? it->size : 0;
  45192. }
  45193. void StretchableObjectResizer::resizeToFit (const double targetSize)
  45194. {
  45195. int order = 0;
  45196. for (;;)
  45197. {
  45198. double currentSize = 0;
  45199. double minSize = 0;
  45200. double maxSize = 0;
  45201. int nextHighestOrder = INT_MAX;
  45202. for (int i = 0; i < items.size(); ++i)
  45203. {
  45204. const Item* const it = items.getUnchecked(i);
  45205. currentSize += it->size;
  45206. if (it->order <= order)
  45207. {
  45208. minSize += it->minSize;
  45209. maxSize += it->maxSize;
  45210. }
  45211. else
  45212. {
  45213. minSize += it->size;
  45214. maxSize += it->size;
  45215. nextHighestOrder = jmin (nextHighestOrder, it->order);
  45216. }
  45217. }
  45218. const double thisIterationTarget = jlimit (minSize, maxSize, targetSize);
  45219. if (thisIterationTarget >= currentSize)
  45220. {
  45221. const double availableExtraSpace = maxSize - currentSize;
  45222. const double targetAmountOfExtraSpace = thisIterationTarget - currentSize;
  45223. const double scale = targetAmountOfExtraSpace / availableExtraSpace;
  45224. for (int i = 0; i < items.size(); ++i)
  45225. {
  45226. Item* const it = items.getUnchecked(i);
  45227. if (it->order <= order)
  45228. it->size = jmin (it->maxSize, it->size + (it->maxSize - it->size) * scale);
  45229. }
  45230. }
  45231. else
  45232. {
  45233. const double amountOfSlack = currentSize - minSize;
  45234. const double targetAmountOfSlack = thisIterationTarget - minSize;
  45235. const double scale = targetAmountOfSlack / amountOfSlack;
  45236. for (int i = 0; i < items.size(); ++i)
  45237. {
  45238. Item* const it = items.getUnchecked(i);
  45239. if (it->order <= order)
  45240. it->size = jmax (it->minSize, it->minSize + (it->size - it->minSize) * scale);
  45241. }
  45242. }
  45243. if (nextHighestOrder < INT_MAX)
  45244. order = nextHighestOrder;
  45245. else
  45246. break;
  45247. }
  45248. }
  45249. END_JUCE_NAMESPACE
  45250. /********* End of inlined file: juce_StretchableObjectResizer.cpp *********/
  45251. /********* Start of inlined file: juce_TabbedButtonBar.cpp *********/
  45252. BEGIN_JUCE_NAMESPACE
  45253. TabBarButton::TabBarButton (const String& name,
  45254. TabbedButtonBar* const owner_,
  45255. const int index)
  45256. : Button (name),
  45257. owner (owner_),
  45258. tabIndex (index),
  45259. overlapPixels (0)
  45260. {
  45261. shadow.setShadowProperties (2.2f, 0.7f, 0, 0);
  45262. setComponentEffect (&shadow);
  45263. setWantsKeyboardFocus (false);
  45264. }
  45265. TabBarButton::~TabBarButton()
  45266. {
  45267. }
  45268. void TabBarButton::paintButton (Graphics& g,
  45269. bool isMouseOverButton,
  45270. bool isButtonDown)
  45271. {
  45272. int x, y, w, h;
  45273. getActiveArea (x, y, w, h);
  45274. g.setOrigin (x, y);
  45275. getLookAndFeel()
  45276. .drawTabButton (g, w, h,
  45277. owner->getTabBackgroundColour (tabIndex),
  45278. tabIndex, getButtonText(), *this,
  45279. owner->getOrientation(),
  45280. isMouseOverButton, isButtonDown,
  45281. getToggleState());
  45282. }
  45283. void TabBarButton::clicked (const ModifierKeys& mods)
  45284. {
  45285. if (mods.isPopupMenu())
  45286. owner->popupMenuClickOnTab (tabIndex, getButtonText());
  45287. else
  45288. owner->setCurrentTabIndex (tabIndex);
  45289. }
  45290. bool TabBarButton::hitTest (int mx, int my)
  45291. {
  45292. int x, y, w, h;
  45293. getActiveArea (x, y, w, h);
  45294. if (owner->getOrientation() == TabbedButtonBar::TabsAtLeft
  45295. || owner->getOrientation() == TabbedButtonBar::TabsAtRight)
  45296. {
  45297. if (((unsigned int) mx) < (unsigned int) getWidth()
  45298. && my >= y + overlapPixels
  45299. && my < y + h - overlapPixels)
  45300. return true;
  45301. }
  45302. else
  45303. {
  45304. if (mx >= x + overlapPixels && mx < x + w - overlapPixels
  45305. && ((unsigned int) my) < (unsigned int) getHeight())
  45306. return true;
  45307. }
  45308. Path p;
  45309. getLookAndFeel()
  45310. .createTabButtonShape (p, w, h, tabIndex, getButtonText(), *this,
  45311. owner->getOrientation(),
  45312. false, false, getToggleState());
  45313. return p.contains ((float) (mx - x),
  45314. (float) (my - y));
  45315. }
  45316. int TabBarButton::getBestTabLength (const int depth)
  45317. {
  45318. return jlimit (depth * 2,
  45319. depth * 7,
  45320. getLookAndFeel().getTabButtonBestWidth (tabIndex, getButtonText(), depth, *this));
  45321. }
  45322. void TabBarButton::getActiveArea (int& x, int& y, int& w, int& h)
  45323. {
  45324. x = 0;
  45325. y = 0;
  45326. int r = getWidth();
  45327. int b = getHeight();
  45328. const int spaceAroundImage = getLookAndFeel().getTabButtonSpaceAroundImage();
  45329. if (owner->getOrientation() != TabbedButtonBar::TabsAtLeft)
  45330. r -= spaceAroundImage;
  45331. if (owner->getOrientation() != TabbedButtonBar::TabsAtRight)
  45332. x += spaceAroundImage;
  45333. if (owner->getOrientation() != TabbedButtonBar::TabsAtBottom)
  45334. y += spaceAroundImage;
  45335. if (owner->getOrientation() != TabbedButtonBar::TabsAtTop)
  45336. b -= spaceAroundImage;
  45337. w = r - x;
  45338. h = b - y;
  45339. }
  45340. class TabAreaBehindFrontButtonComponent : public Component
  45341. {
  45342. public:
  45343. TabAreaBehindFrontButtonComponent (TabbedButtonBar* const owner_)
  45344. : owner (owner_)
  45345. {
  45346. setInterceptsMouseClicks (false, false);
  45347. }
  45348. ~TabAreaBehindFrontButtonComponent()
  45349. {
  45350. }
  45351. void paint (Graphics& g)
  45352. {
  45353. getLookAndFeel()
  45354. .drawTabAreaBehindFrontButton (g, getWidth(), getHeight(),
  45355. *owner, owner->getOrientation());
  45356. }
  45357. void enablementChanged()
  45358. {
  45359. repaint();
  45360. }
  45361. private:
  45362. TabbedButtonBar* const owner;
  45363. TabAreaBehindFrontButtonComponent (const TabAreaBehindFrontButtonComponent&);
  45364. const TabAreaBehindFrontButtonComponent& operator= (const TabAreaBehindFrontButtonComponent&);
  45365. };
  45366. TabbedButtonBar::TabbedButtonBar (const Orientation orientation_)
  45367. : orientation (orientation_),
  45368. currentTabIndex (-1),
  45369. extraTabsButton (0)
  45370. {
  45371. setInterceptsMouseClicks (false, true);
  45372. addAndMakeVisible (behindFrontTab = new TabAreaBehindFrontButtonComponent (this));
  45373. setFocusContainer (true);
  45374. }
  45375. TabbedButtonBar::~TabbedButtonBar()
  45376. {
  45377. deleteAllChildren();
  45378. }
  45379. void TabbedButtonBar::setOrientation (const Orientation newOrientation)
  45380. {
  45381. orientation = newOrientation;
  45382. for (int i = getNumChildComponents(); --i >= 0;)
  45383. getChildComponent (i)->resized();
  45384. resized();
  45385. }
  45386. TabBarButton* TabbedButtonBar::createTabButton (const String& name, const int index)
  45387. {
  45388. return new TabBarButton (name, this, index);
  45389. }
  45390. void TabbedButtonBar::clearTabs()
  45391. {
  45392. tabs.clear();
  45393. tabColours.clear();
  45394. currentTabIndex = -1;
  45395. deleteAndZero (extraTabsButton);
  45396. removeChildComponent (behindFrontTab);
  45397. deleteAllChildren();
  45398. addChildComponent (behindFrontTab);
  45399. setCurrentTabIndex (-1);
  45400. }
  45401. void TabbedButtonBar::addTab (const String& tabName,
  45402. const Colour& tabBackgroundColour,
  45403. int insertIndex)
  45404. {
  45405. jassert (tabName.isNotEmpty()); // you have to give them all a name..
  45406. if (tabName.isNotEmpty())
  45407. {
  45408. if (((unsigned int) insertIndex) > (unsigned int) tabs.size())
  45409. insertIndex = tabs.size();
  45410. for (int i = tabs.size(); --i >= insertIndex;)
  45411. {
  45412. TabBarButton* const tb = getTabButton (i);
  45413. if (tb != 0)
  45414. tb->tabIndex++;
  45415. }
  45416. tabs.insert (insertIndex, tabName);
  45417. tabColours.insert (insertIndex, tabBackgroundColour);
  45418. TabBarButton* const tb = createTabButton (tabName, insertIndex);
  45419. jassert (tb != 0); // your createTabButton() mustn't return zero!
  45420. addAndMakeVisible (tb, insertIndex);
  45421. resized();
  45422. if (currentTabIndex < 0)
  45423. setCurrentTabIndex (0);
  45424. }
  45425. }
  45426. void TabbedButtonBar::setTabName (const int tabIndex,
  45427. const String& newName)
  45428. {
  45429. if (((unsigned int) tabIndex) < (unsigned int) tabs.size()
  45430. && tabs[tabIndex] != newName)
  45431. {
  45432. tabs.set (tabIndex, newName);
  45433. TabBarButton* const tb = getTabButton (tabIndex);
  45434. if (tb != 0)
  45435. tb->setButtonText (newName);
  45436. resized();
  45437. }
  45438. }
  45439. void TabbedButtonBar::removeTab (const int tabIndex)
  45440. {
  45441. if (((unsigned int) tabIndex) < (unsigned int) tabs.size())
  45442. {
  45443. const int oldTabIndex = currentTabIndex;
  45444. if (currentTabIndex == tabIndex)
  45445. currentTabIndex = -1;
  45446. tabs.remove (tabIndex);
  45447. tabColours.remove (tabIndex);
  45448. TabBarButton* const tb = getTabButton (tabIndex);
  45449. if (tb != 0)
  45450. delete tb;
  45451. for (int i = tabIndex + 1; i <= tabs.size(); ++i)
  45452. {
  45453. TabBarButton* const tb = getTabButton (i);
  45454. if (tb != 0)
  45455. tb->tabIndex--;
  45456. }
  45457. resized();
  45458. setCurrentTabIndex (jlimit (0, jmax (0, tabs.size() - 1), oldTabIndex));
  45459. }
  45460. }
  45461. void TabbedButtonBar::moveTab (const int currentIndex,
  45462. const int newIndex)
  45463. {
  45464. tabs.move (currentIndex, newIndex);
  45465. tabColours.move (currentIndex, newIndex);
  45466. resized();
  45467. }
  45468. int TabbedButtonBar::getNumTabs() const
  45469. {
  45470. return tabs.size();
  45471. }
  45472. const StringArray TabbedButtonBar::getTabNames() const
  45473. {
  45474. return tabs;
  45475. }
  45476. void TabbedButtonBar::setCurrentTabIndex (int newIndex)
  45477. {
  45478. if (currentTabIndex != newIndex)
  45479. {
  45480. if (((unsigned int) newIndex) >= (unsigned int) tabs.size())
  45481. newIndex = -1;
  45482. currentTabIndex = newIndex;
  45483. for (int i = 0; i < getNumChildComponents(); ++i)
  45484. {
  45485. TabBarButton* const tb = dynamic_cast <TabBarButton*> (getChildComponent (i));
  45486. if (tb != 0)
  45487. tb->setToggleState (tb->tabIndex == newIndex, false);
  45488. }
  45489. resized();
  45490. sendChangeMessage (this);
  45491. currentTabChanged (newIndex, newIndex >= 0 ? tabs [newIndex] : String::empty);
  45492. }
  45493. }
  45494. TabBarButton* TabbedButtonBar::getTabButton (const int index) const
  45495. {
  45496. for (int i = getNumChildComponents(); --i >= 0;)
  45497. {
  45498. TabBarButton* const tb = dynamic_cast <TabBarButton*> (getChildComponent (i));
  45499. if (tb != 0 && tb->tabIndex == index)
  45500. return tb;
  45501. }
  45502. return 0;
  45503. }
  45504. void TabbedButtonBar::lookAndFeelChanged()
  45505. {
  45506. deleteAndZero (extraTabsButton);
  45507. resized();
  45508. }
  45509. void TabbedButtonBar::resized()
  45510. {
  45511. const double minimumScale = 0.7;
  45512. int depth = getWidth();
  45513. int length = getHeight();
  45514. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  45515. swapVariables (depth, length);
  45516. const int overlap = getLookAndFeel().getTabButtonOverlap (depth)
  45517. + getLookAndFeel().getTabButtonSpaceAroundImage() * 2;
  45518. int i, totalLength = overlap;
  45519. int numVisibleButtons = tabs.size();
  45520. for (i = 0; i < getNumChildComponents(); ++i)
  45521. {
  45522. TabBarButton* const tb = dynamic_cast <TabBarButton*> (getChildComponent (i));
  45523. if (tb != 0)
  45524. {
  45525. totalLength += tb->getBestTabLength (depth) - overlap;
  45526. tb->overlapPixels = overlap / 2;
  45527. }
  45528. }
  45529. double scale = 1.0;
  45530. if (totalLength > length)
  45531. scale = jmax (minimumScale, length / (double) totalLength);
  45532. const bool isTooBig = totalLength * scale > length;
  45533. int tabsButtonPos = 0;
  45534. if (isTooBig)
  45535. {
  45536. if (extraTabsButton == 0)
  45537. {
  45538. addAndMakeVisible (extraTabsButton = getLookAndFeel().createTabBarExtrasButton());
  45539. extraTabsButton->addButtonListener (this);
  45540. extraTabsButton->setAlwaysOnTop (true);
  45541. extraTabsButton->setTriggeredOnMouseDown (true);
  45542. }
  45543. const int buttonSize = jmin (proportionOfWidth (0.7f), proportionOfHeight (0.7f));
  45544. extraTabsButton->setSize (buttonSize, buttonSize);
  45545. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  45546. {
  45547. tabsButtonPos = getWidth() - buttonSize / 2 - 1;
  45548. extraTabsButton->setCentrePosition (tabsButtonPos, getHeight() / 2);
  45549. }
  45550. else
  45551. {
  45552. tabsButtonPos = getHeight() - buttonSize / 2 - 1;
  45553. extraTabsButton->setCentrePosition (getWidth() / 2, tabsButtonPos);
  45554. }
  45555. totalLength = 0;
  45556. for (i = 0; i < tabs.size(); ++i)
  45557. {
  45558. TabBarButton* const tb = getTabButton (i);
  45559. if (tb != 0)
  45560. {
  45561. const int newLength = totalLength + tb->getBestTabLength (depth);
  45562. if (i > 0 && newLength * minimumScale > tabsButtonPos)
  45563. {
  45564. totalLength += overlap;
  45565. break;
  45566. }
  45567. numVisibleButtons = i + 1;
  45568. totalLength = newLength - overlap;
  45569. }
  45570. }
  45571. scale = jmax (minimumScale, tabsButtonPos / (double) totalLength);
  45572. }
  45573. else
  45574. {
  45575. deleteAndZero (extraTabsButton);
  45576. }
  45577. int pos = 0;
  45578. TabBarButton* frontTab = 0;
  45579. for (i = 0; i < tabs.size(); ++i)
  45580. {
  45581. TabBarButton* const tb = getTabButton (i);
  45582. if (tb != 0)
  45583. {
  45584. const int bestLength = roundDoubleToInt (scale * tb->getBestTabLength (depth));
  45585. if (i < numVisibleButtons)
  45586. {
  45587. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  45588. tb->setBounds (pos, 0, bestLength, getHeight());
  45589. else
  45590. tb->setBounds (0, pos, getWidth(), bestLength);
  45591. tb->toBack();
  45592. if (tb->tabIndex == currentTabIndex)
  45593. frontTab = tb;
  45594. tb->setVisible (true);
  45595. }
  45596. else
  45597. {
  45598. tb->setVisible (false);
  45599. }
  45600. pos += bestLength - overlap;
  45601. }
  45602. }
  45603. behindFrontTab->setBounds (0, 0, getWidth(), getHeight());
  45604. if (frontTab != 0)
  45605. {
  45606. frontTab->toFront (false);
  45607. behindFrontTab->toBehind (frontTab);
  45608. }
  45609. }
  45610. const Colour TabbedButtonBar::getTabBackgroundColour (const int tabIndex)
  45611. {
  45612. return tabColours [tabIndex];
  45613. }
  45614. void TabbedButtonBar::setTabBackgroundColour (const int tabIndex, const Colour& newColour)
  45615. {
  45616. if (((unsigned int) tabIndex) < (unsigned int) tabColours.size()
  45617. && tabColours [tabIndex] != newColour)
  45618. {
  45619. tabColours.set (tabIndex, newColour);
  45620. repaint();
  45621. }
  45622. }
  45623. void TabbedButtonBar::buttonClicked (Button* button)
  45624. {
  45625. if (extraTabsButton == button)
  45626. {
  45627. PopupMenu m;
  45628. for (int i = 0; i < tabs.size(); ++i)
  45629. {
  45630. TabBarButton* const tb = getTabButton (i);
  45631. if (tb != 0 && ! tb->isVisible())
  45632. m.addItem (tb->tabIndex + 1, tabs[i], true, i == currentTabIndex);
  45633. }
  45634. const int res = m.showAt (extraTabsButton);
  45635. if (res != 0)
  45636. setCurrentTabIndex (res - 1);
  45637. }
  45638. }
  45639. void TabbedButtonBar::currentTabChanged (const int, const String&)
  45640. {
  45641. }
  45642. void TabbedButtonBar::popupMenuClickOnTab (const int, const String&)
  45643. {
  45644. }
  45645. END_JUCE_NAMESPACE
  45646. /********* End of inlined file: juce_TabbedButtonBar.cpp *********/
  45647. /********* Start of inlined file: juce_TabbedComponent.cpp *********/
  45648. BEGIN_JUCE_NAMESPACE
  45649. class TabCompButtonBar : public TabbedButtonBar
  45650. {
  45651. public:
  45652. TabCompButtonBar (TabbedComponent* const owner_,
  45653. const TabbedButtonBar::Orientation orientation)
  45654. : TabbedButtonBar (orientation),
  45655. owner (owner_)
  45656. {
  45657. }
  45658. ~TabCompButtonBar()
  45659. {
  45660. }
  45661. void currentTabChanged (const int newCurrentTabIndex,
  45662. const String& newTabName)
  45663. {
  45664. owner->changeCallback (newCurrentTabIndex, newTabName);
  45665. }
  45666. void popupMenuClickOnTab (const int tabIndex,
  45667. const String& tabName)
  45668. {
  45669. owner->popupMenuClickOnTab (tabIndex, tabName);
  45670. }
  45671. const Colour getTabBackgroundColour (const int tabIndex)
  45672. {
  45673. return owner->tabs->getTabBackgroundColour (tabIndex);
  45674. }
  45675. TabBarButton* createTabButton (const String& tabName, const int tabIndex)
  45676. {
  45677. return owner->createTabButton (tabName, tabIndex);
  45678. }
  45679. juce_UseDebuggingNewOperator
  45680. private:
  45681. TabbedComponent* const owner;
  45682. TabCompButtonBar (const TabCompButtonBar&);
  45683. const TabCompButtonBar& operator= (const TabCompButtonBar&);
  45684. };
  45685. TabbedComponent::TabbedComponent (const TabbedButtonBar::Orientation orientation)
  45686. : panelComponent (0),
  45687. tabDepth (30),
  45688. outlineColour (Colours::grey),
  45689. outlineThickness (1),
  45690. edgeIndent (0)
  45691. {
  45692. addAndMakeVisible (tabs = new TabCompButtonBar (this, orientation));
  45693. }
  45694. TabbedComponent::~TabbedComponent()
  45695. {
  45696. clearTabs();
  45697. delete tabs;
  45698. }
  45699. void TabbedComponent::setOrientation (const TabbedButtonBar::Orientation orientation)
  45700. {
  45701. tabs->setOrientation (orientation);
  45702. resized();
  45703. }
  45704. TabbedButtonBar::Orientation TabbedComponent::getOrientation() const throw()
  45705. {
  45706. return tabs->getOrientation();
  45707. }
  45708. void TabbedComponent::setTabBarDepth (const int newDepth)
  45709. {
  45710. if (tabDepth != newDepth)
  45711. {
  45712. tabDepth = newDepth;
  45713. resized();
  45714. }
  45715. }
  45716. TabBarButton* TabbedComponent::createTabButton (const String& tabName, const int tabIndex)
  45717. {
  45718. return new TabBarButton (tabName, tabs, tabIndex);
  45719. }
  45720. void TabbedComponent::clearTabs()
  45721. {
  45722. if (panelComponent != 0)
  45723. {
  45724. panelComponent->setVisible (false);
  45725. removeChildComponent (panelComponent);
  45726. panelComponent = 0;
  45727. }
  45728. tabs->clearTabs();
  45729. for (int i = contentComponents.size(); --i >= 0;)
  45730. {
  45731. Component* const c = contentComponents.getUnchecked(i);
  45732. // be careful not to delete these components until they've been removed from the tab component
  45733. jassert (c == 0 || c->isValidComponent());
  45734. if (c != 0 && c->getComponentPropertyBool (T("deleteByTabComp_"), false, false))
  45735. delete c;
  45736. }
  45737. contentComponents.clear();
  45738. }
  45739. void TabbedComponent::addTab (const String& tabName,
  45740. const Colour& tabBackgroundColour,
  45741. Component* const contentComponent,
  45742. const bool deleteComponentWhenNotNeeded,
  45743. const int insertIndex)
  45744. {
  45745. contentComponents.insert (insertIndex, contentComponent);
  45746. if (contentComponent != 0)
  45747. contentComponent->setComponentProperty (T("deleteByTabComp_"), deleteComponentWhenNotNeeded);
  45748. tabs->addTab (tabName, tabBackgroundColour, insertIndex);
  45749. }
  45750. void TabbedComponent::setTabName (const int tabIndex,
  45751. const String& newName)
  45752. {
  45753. tabs->setTabName (tabIndex, newName);
  45754. }
  45755. void TabbedComponent::removeTab (const int tabIndex)
  45756. {
  45757. Component* const c = contentComponents [tabIndex];
  45758. if (c != 0 && c->getComponentPropertyBool (T("deleteByTabComp_"), false, false))
  45759. {
  45760. if (c == panelComponent)
  45761. panelComponent = 0;
  45762. delete c;
  45763. }
  45764. contentComponents.remove (tabIndex);
  45765. tabs->removeTab (tabIndex);
  45766. }
  45767. int TabbedComponent::getNumTabs() const
  45768. {
  45769. return tabs->getNumTabs();
  45770. }
  45771. const StringArray TabbedComponent::getTabNames() const
  45772. {
  45773. return tabs->getTabNames();
  45774. }
  45775. Component* TabbedComponent::getTabContentComponent (const int tabIndex) const throw()
  45776. {
  45777. return contentComponents [tabIndex];
  45778. }
  45779. const Colour TabbedComponent::getTabBackgroundColour (const int tabIndex) const throw()
  45780. {
  45781. return tabs->getTabBackgroundColour (tabIndex);
  45782. }
  45783. void TabbedComponent::setTabBackgroundColour (const int tabIndex, const Colour& newColour)
  45784. {
  45785. tabs->setTabBackgroundColour (tabIndex, newColour);
  45786. if (getCurrentTabIndex() == tabIndex)
  45787. repaint();
  45788. }
  45789. void TabbedComponent::setCurrentTabIndex (const int newTabIndex)
  45790. {
  45791. tabs->setCurrentTabIndex (newTabIndex);
  45792. }
  45793. int TabbedComponent::getCurrentTabIndex() const
  45794. {
  45795. return tabs->getCurrentTabIndex();
  45796. }
  45797. const String& TabbedComponent::getCurrentTabName() const
  45798. {
  45799. return tabs->getCurrentTabName();
  45800. }
  45801. void TabbedComponent::setOutline (const Colour& colour, int thickness)
  45802. {
  45803. outlineColour = colour;
  45804. outlineThickness = thickness;
  45805. repaint();
  45806. }
  45807. void TabbedComponent::setIndent (const int indentThickness)
  45808. {
  45809. edgeIndent = indentThickness;
  45810. }
  45811. void TabbedComponent::paint (Graphics& g)
  45812. {
  45813. const TabbedButtonBar::Orientation o = getOrientation();
  45814. int x = 0;
  45815. int y = 0;
  45816. int r = getWidth();
  45817. int b = getHeight();
  45818. if (o == TabbedButtonBar::TabsAtTop)
  45819. y += tabDepth;
  45820. else if (o == TabbedButtonBar::TabsAtBottom)
  45821. b -= tabDepth;
  45822. else if (o == TabbedButtonBar::TabsAtLeft)
  45823. x += tabDepth;
  45824. else if (o == TabbedButtonBar::TabsAtRight)
  45825. r -= tabDepth;
  45826. g.reduceClipRegion (x, y, r - x, b - y);
  45827. g.fillAll (tabs->getTabBackgroundColour (getCurrentTabIndex()));
  45828. if (outlineThickness > 0)
  45829. {
  45830. if (o == TabbedButtonBar::TabsAtTop)
  45831. --y;
  45832. else if (o == TabbedButtonBar::TabsAtBottom)
  45833. ++b;
  45834. else if (o == TabbedButtonBar::TabsAtLeft)
  45835. --x;
  45836. else if (o == TabbedButtonBar::TabsAtRight)
  45837. ++r;
  45838. g.setColour (outlineColour);
  45839. g.drawRect (x, y, r - x, b - y, outlineThickness);
  45840. }
  45841. }
  45842. void TabbedComponent::resized()
  45843. {
  45844. const TabbedButtonBar::Orientation o = getOrientation();
  45845. const int indent = edgeIndent + outlineThickness;
  45846. BorderSize indents (indent);
  45847. if (o == TabbedButtonBar::TabsAtTop)
  45848. {
  45849. tabs->setBounds (0, 0, getWidth(), tabDepth);
  45850. indents.setTop (tabDepth + edgeIndent);
  45851. }
  45852. else if (o == TabbedButtonBar::TabsAtBottom)
  45853. {
  45854. tabs->setBounds (0, getHeight() - tabDepth, getWidth(), tabDepth);
  45855. indents.setBottom (tabDepth + edgeIndent);
  45856. }
  45857. else if (o == TabbedButtonBar::TabsAtLeft)
  45858. {
  45859. tabs->setBounds (0, 0, tabDepth, getHeight());
  45860. indents.setLeft (tabDepth + edgeIndent);
  45861. }
  45862. else if (o == TabbedButtonBar::TabsAtRight)
  45863. {
  45864. tabs->setBounds (getWidth() - tabDepth, 0, tabDepth, getHeight());
  45865. indents.setRight (tabDepth + edgeIndent);
  45866. }
  45867. const Rectangle bounds (indents.subtractedFrom (Rectangle (0, 0, getWidth(), getHeight())));
  45868. for (int i = contentComponents.size(); --i >= 0;)
  45869. if (contentComponents.getUnchecked (i) != 0)
  45870. contentComponents.getUnchecked (i)->setBounds (bounds);
  45871. }
  45872. void TabbedComponent::changeCallback (const int newCurrentTabIndex,
  45873. const String& newTabName)
  45874. {
  45875. if (panelComponent != 0)
  45876. {
  45877. panelComponent->setVisible (false);
  45878. removeChildComponent (panelComponent);
  45879. panelComponent = 0;
  45880. }
  45881. if (getCurrentTabIndex() >= 0)
  45882. {
  45883. panelComponent = contentComponents [getCurrentTabIndex()];
  45884. if (panelComponent != 0)
  45885. {
  45886. // do these ops as two stages instead of addAndMakeVisible() so that the
  45887. // component has always got a parent when it gets the visibilityChanged() callback
  45888. addChildComponent (panelComponent);
  45889. panelComponent->setVisible (true);
  45890. panelComponent->toFront (true);
  45891. }
  45892. repaint();
  45893. }
  45894. resized();
  45895. currentTabChanged (newCurrentTabIndex, newTabName);
  45896. }
  45897. void TabbedComponent::currentTabChanged (const int, const String&)
  45898. {
  45899. }
  45900. void TabbedComponent::popupMenuClickOnTab (const int, const String&)
  45901. {
  45902. }
  45903. END_JUCE_NAMESPACE
  45904. /********* End of inlined file: juce_TabbedComponent.cpp *********/
  45905. /********* Start of inlined file: juce_Viewport.cpp *********/
  45906. BEGIN_JUCE_NAMESPACE
  45907. Viewport::Viewport (const String& componentName)
  45908. : Component (componentName),
  45909. contentComp (0),
  45910. lastVX (0),
  45911. lastVY (0),
  45912. lastVW (0),
  45913. lastVH (0),
  45914. scrollBarThickness (0),
  45915. singleStepX (16),
  45916. singleStepY (16),
  45917. showHScrollbar (true),
  45918. showVScrollbar (true)
  45919. {
  45920. // content holder is used to clip the contents so they don't overlap the scrollbars
  45921. addAndMakeVisible (contentHolder = new Component());
  45922. contentHolder->setInterceptsMouseClicks (false, true);
  45923. verticalScrollBar = new ScrollBar (true);
  45924. horizontalScrollBar = new ScrollBar (false);
  45925. addChildComponent (verticalScrollBar);
  45926. addChildComponent (horizontalScrollBar);
  45927. verticalScrollBar->addListener (this);
  45928. horizontalScrollBar->addListener (this);
  45929. setInterceptsMouseClicks (false, true);
  45930. setWantsKeyboardFocus (true);
  45931. }
  45932. Viewport::~Viewport()
  45933. {
  45934. contentHolder->deleteAllChildren();
  45935. deleteAllChildren();
  45936. }
  45937. void Viewport::visibleAreaChanged (int, int, int, int)
  45938. {
  45939. }
  45940. void Viewport::setViewedComponent (Component* const newViewedComponent)
  45941. {
  45942. if (contentComp != newViewedComponent)
  45943. {
  45944. if (contentComp->isValidComponent())
  45945. {
  45946. Component* const oldComp = contentComp;
  45947. contentComp = 0;
  45948. delete oldComp;
  45949. }
  45950. contentComp = newViewedComponent;
  45951. if (contentComp != 0)
  45952. {
  45953. contentComp->setTopLeftPosition (0, 0);
  45954. contentHolder->addAndMakeVisible (contentComp);
  45955. contentComp->addComponentListener (this);
  45956. }
  45957. updateVisibleRegion();
  45958. }
  45959. }
  45960. int Viewport::getMaximumVisibleWidth() const throw()
  45961. {
  45962. return jmax (0, getWidth() - (verticalScrollBar->isVisible() ? getScrollBarThickness() : 0));
  45963. }
  45964. int Viewport::getMaximumVisibleHeight() const throw()
  45965. {
  45966. return jmax (0, getHeight() - (horizontalScrollBar->isVisible() ? getScrollBarThickness() : 0));
  45967. }
  45968. void Viewport::setViewPosition (const int xPixelsOffset,
  45969. const int yPixelsOffset)
  45970. {
  45971. if (contentComp != 0)
  45972. contentComp->setTopLeftPosition (-xPixelsOffset,
  45973. -yPixelsOffset);
  45974. }
  45975. void Viewport::setViewPositionProportionately (const double x,
  45976. const double y)
  45977. {
  45978. if (contentComp != 0)
  45979. setViewPosition (jmax (0, roundDoubleToInt (x * (contentComp->getWidth() - getWidth()))),
  45980. jmax (0, roundDoubleToInt (y * (contentComp->getHeight() - getHeight()))));
  45981. }
  45982. void Viewport::componentMovedOrResized (Component&, bool, bool)
  45983. {
  45984. updateVisibleRegion();
  45985. }
  45986. void Viewport::resized()
  45987. {
  45988. updateVisibleRegion();
  45989. }
  45990. void Viewport::updateVisibleRegion()
  45991. {
  45992. if (contentComp != 0)
  45993. {
  45994. const int newVX = -contentComp->getX();
  45995. const int newVY = -contentComp->getY();
  45996. if (newVX == 0 && newVY == 0
  45997. && contentComp->getWidth() <= getWidth()
  45998. && contentComp->getHeight() <= getHeight())
  45999. {
  46000. horizontalScrollBar->setVisible (false);
  46001. verticalScrollBar->setVisible (false);
  46002. }
  46003. if ((contentComp->getWidth() > 0) && showHScrollbar
  46004. && getHeight() > getScrollBarThickness())
  46005. {
  46006. horizontalScrollBar->setRangeLimits (0.0, contentComp->getWidth());
  46007. horizontalScrollBar->setCurrentRange (newVX, getMaximumVisibleWidth());
  46008. horizontalScrollBar->setSingleStepSize (singleStepX);
  46009. }
  46010. else
  46011. {
  46012. horizontalScrollBar->setVisible (false);
  46013. }
  46014. if ((contentComp->getHeight() > 0) && showVScrollbar
  46015. && getWidth() > getScrollBarThickness())
  46016. {
  46017. verticalScrollBar->setRangeLimits (0.0, contentComp->getHeight());
  46018. verticalScrollBar->setCurrentRange (newVY, getMaximumVisibleHeight());
  46019. verticalScrollBar->setSingleStepSize (singleStepY);
  46020. }
  46021. else
  46022. {
  46023. verticalScrollBar->setVisible (false);
  46024. }
  46025. if (verticalScrollBar->isVisible())
  46026. {
  46027. horizontalScrollBar->setCurrentRange (newVX, getMaximumVisibleWidth());
  46028. verticalScrollBar->setCurrentRange (newVY, getMaximumVisibleHeight());
  46029. verticalScrollBar
  46030. ->setBounds (getMaximumVisibleWidth(), 0,
  46031. getScrollBarThickness(), getMaximumVisibleHeight());
  46032. }
  46033. if (horizontalScrollBar->isVisible())
  46034. {
  46035. horizontalScrollBar->setCurrentRange (newVX, getMaximumVisibleWidth());
  46036. horizontalScrollBar
  46037. ->setBounds (0, getMaximumVisibleHeight(),
  46038. getMaximumVisibleWidth(), getScrollBarThickness());
  46039. }
  46040. contentHolder->setSize (getMaximumVisibleWidth(),
  46041. getMaximumVisibleHeight());
  46042. const int newVW = jmin (contentComp->getRight(), getMaximumVisibleWidth());
  46043. const int newVH = jmin (contentComp->getBottom(), getMaximumVisibleHeight());
  46044. if (newVX != lastVX
  46045. || newVY != lastVY
  46046. || newVW != lastVW
  46047. || newVH != lastVH)
  46048. {
  46049. lastVX = newVX;
  46050. lastVY = newVY;
  46051. lastVW = newVW;
  46052. lastVH = newVH;
  46053. visibleAreaChanged (newVX, newVY, newVW, newVH);
  46054. }
  46055. horizontalScrollBar->handleUpdateNowIfNeeded();
  46056. verticalScrollBar->handleUpdateNowIfNeeded();
  46057. }
  46058. else
  46059. {
  46060. horizontalScrollBar->setVisible (false);
  46061. verticalScrollBar->setVisible (false);
  46062. }
  46063. }
  46064. void Viewport::setSingleStepSizes (const int stepX,
  46065. const int stepY)
  46066. {
  46067. singleStepX = stepX;
  46068. singleStepY = stepY;
  46069. updateVisibleRegion();
  46070. }
  46071. void Viewport::setScrollBarsShown (const bool showVerticalScrollbarIfNeeded,
  46072. const bool showHorizontalScrollbarIfNeeded)
  46073. {
  46074. showVScrollbar = showVerticalScrollbarIfNeeded;
  46075. showHScrollbar = showHorizontalScrollbarIfNeeded;
  46076. updateVisibleRegion();
  46077. }
  46078. void Viewport::setScrollBarThickness (const int thickness)
  46079. {
  46080. scrollBarThickness = thickness;
  46081. updateVisibleRegion();
  46082. }
  46083. int Viewport::getScrollBarThickness() const throw()
  46084. {
  46085. return (scrollBarThickness > 0) ? scrollBarThickness
  46086. : getLookAndFeel().getDefaultScrollbarWidth();
  46087. }
  46088. void Viewport::setScrollBarButtonVisibility (const bool buttonsVisible)
  46089. {
  46090. verticalScrollBar->setButtonVisibility (buttonsVisible);
  46091. horizontalScrollBar->setButtonVisibility (buttonsVisible);
  46092. }
  46093. void Viewport::scrollBarMoved (ScrollBar* scrollBarThatHasMoved, const double newRangeStart)
  46094. {
  46095. if (scrollBarThatHasMoved == horizontalScrollBar)
  46096. {
  46097. setViewPosition (roundDoubleToInt (newRangeStart), getViewPositionY());
  46098. }
  46099. else if (scrollBarThatHasMoved == verticalScrollBar)
  46100. {
  46101. setViewPosition (getViewPositionX(), roundDoubleToInt (newRangeStart));
  46102. }
  46103. }
  46104. void Viewport::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  46105. {
  46106. if (! useMouseWheelMoveIfNeeded (e, wheelIncrementX, wheelIncrementY))
  46107. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  46108. }
  46109. bool Viewport::useMouseWheelMoveIfNeeded (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  46110. {
  46111. if (! (e.mods.isAltDown() || e.mods.isCtrlDown()))
  46112. {
  46113. const bool hasVertBar = verticalScrollBar->isVisible();
  46114. const bool hasHorzBar = horizontalScrollBar->isVisible();
  46115. if (hasHorzBar && (wheelIncrementX != 0 || e.mods.isShiftDown() || ! hasVertBar))
  46116. {
  46117. horizontalScrollBar->mouseWheelMove (e.getEventRelativeTo (horizontalScrollBar),
  46118. wheelIncrementX, wheelIncrementY);
  46119. return true;
  46120. }
  46121. else if (hasVertBar && wheelIncrementY != 0)
  46122. {
  46123. verticalScrollBar->mouseWheelMove (e.getEventRelativeTo (verticalScrollBar),
  46124. wheelIncrementX, wheelIncrementY);
  46125. return true;
  46126. }
  46127. }
  46128. return false;
  46129. }
  46130. bool Viewport::keyPressed (const KeyPress& key)
  46131. {
  46132. const bool isUpDownKey = key.isKeyCode (KeyPress::upKey)
  46133. || key.isKeyCode (KeyPress::downKey)
  46134. || key.isKeyCode (KeyPress::pageUpKey)
  46135. || key.isKeyCode (KeyPress::pageDownKey)
  46136. || key.isKeyCode (KeyPress::homeKey)
  46137. || key.isKeyCode (KeyPress::endKey);
  46138. if (verticalScrollBar->isVisible() && isUpDownKey)
  46139. return verticalScrollBar->keyPressed (key);
  46140. const bool isLeftRightKey = key.isKeyCode (KeyPress::leftKey)
  46141. || key.isKeyCode (KeyPress::rightKey);
  46142. if (horizontalScrollBar->isVisible() && (isUpDownKey || isLeftRightKey))
  46143. return horizontalScrollBar->keyPressed (key);
  46144. return false;
  46145. }
  46146. END_JUCE_NAMESPACE
  46147. /********* End of inlined file: juce_Viewport.cpp *********/
  46148. /********* Start of inlined file: juce_LookAndFeel.cpp *********/
  46149. BEGIN_JUCE_NAMESPACE
  46150. static const Colour createBaseColour (const Colour& buttonColour,
  46151. const bool hasKeyboardFocus,
  46152. const bool isMouseOverButton,
  46153. const bool isButtonDown) throw()
  46154. {
  46155. const float sat = hasKeyboardFocus ? 1.3f : 0.9f;
  46156. const Colour baseColour (buttonColour.withMultipliedSaturation (sat));
  46157. if (isButtonDown)
  46158. return baseColour.contrasting (0.2f);
  46159. else if (isMouseOverButton)
  46160. return baseColour.contrasting (0.1f);
  46161. return baseColour;
  46162. }
  46163. LookAndFeel::LookAndFeel()
  46164. {
  46165. /* if this fails it means you're trying to create a LookAndFeel object before
  46166. the static Colours have been initialised. That ain't gonna work. It probably
  46167. means that you're using a static LookAndFeel object and that your compiler has
  46168. decided to intialise it before the Colours class.
  46169. */
  46170. jassert (Colours::white == Colour (0xffffffff));
  46171. // set up the standard set of colours..
  46172. #define textButtonColour 0xffbbbbff
  46173. #define textHighlightColour 0x401111ee
  46174. #define standardOutlineColour 0xb2808080
  46175. static const int standardColours[] =
  46176. {
  46177. TextButton::buttonColourId, textButtonColour,
  46178. TextButton::buttonOnColourId, 0xff4444ff,
  46179. TextButton::textColourId, 0xff000000,
  46180. ComboBox::buttonColourId, 0xffbbbbff,
  46181. ComboBox::outlineColourId, standardOutlineColour,
  46182. ToggleButton::textColourId, 0xff000000,
  46183. TextEditor::backgroundColourId, 0xffffffff,
  46184. TextEditor::textColourId, 0xff000000,
  46185. TextEditor::highlightColourId, textHighlightColour,
  46186. TextEditor::highlightedTextColourId, 0xff000000,
  46187. TextEditor::caretColourId, 0xff000000,
  46188. TextEditor::outlineColourId, 0x00000000,
  46189. TextEditor::focusedOutlineColourId, textButtonColour,
  46190. TextEditor::shadowColourId, 0x38000000,
  46191. Label::backgroundColourId, 0x00000000,
  46192. Label::textColourId, 0xff000000,
  46193. Label::outlineColourId, 0x00000000,
  46194. ScrollBar::backgroundColourId, 0x00000000,
  46195. ScrollBar::thumbColourId, 0xffffffff,
  46196. ScrollBar::trackColourId, 0xffffffff,
  46197. TreeView::linesColourId, 0x4c000000,
  46198. TreeView::backgroundColourId, 0x00000000,
  46199. PopupMenu::backgroundColourId, 0xffffffff,
  46200. PopupMenu::textColourId, 0xff000000,
  46201. PopupMenu::headerTextColourId, 0xff000000,
  46202. PopupMenu::highlightedTextColourId, 0xffffffff,
  46203. PopupMenu::highlightedBackgroundColourId, 0x991111aa,
  46204. ComboBox::textColourId, 0xff000000,
  46205. ComboBox::backgroundColourId, 0xffffffff,
  46206. ComboBox::arrowColourId, 0x99000000,
  46207. ListBox::backgroundColourId, 0xffffffff,
  46208. ListBox::outlineColourId, standardOutlineColour,
  46209. ListBox::textColourId, 0xff000000,
  46210. Slider::backgroundColourId, 0x00000000,
  46211. Slider::thumbColourId, textButtonColour,
  46212. Slider::trackColourId, 0x7fffffff,
  46213. Slider::rotarySliderFillColourId, 0x7f0000ff,
  46214. Slider::rotarySliderOutlineColourId, 0x66000000,
  46215. Slider::textBoxTextColourId, 0xff000000,
  46216. Slider::textBoxBackgroundColourId, 0xffffffff,
  46217. Slider::textBoxHighlightColourId, textHighlightColour,
  46218. Slider::textBoxOutlineColourId, standardOutlineColour,
  46219. AlertWindow::backgroundColourId, 0xffededed,
  46220. AlertWindow::textColourId, 0xff000000,
  46221. AlertWindow::outlineColourId, 0xff666666,
  46222. ProgressBar::backgroundColourId, 0xffeeeeee,
  46223. ProgressBar::foregroundColourId, 0xffaaaaee,
  46224. TooltipWindow::backgroundColourId, 0xffeeeebb,
  46225. TooltipWindow::textColourId, 0xff000000,
  46226. TooltipWindow::outlineColourId, 0x4c000000,
  46227. Toolbar::backgroundColourId, 0xfff6f8f9,
  46228. Toolbar::separatorColourId, 0x4c000000,
  46229. Toolbar::buttonMouseOverBackgroundColourId, 0x4c0000ff,
  46230. Toolbar::buttonMouseDownBackgroundColourId, 0x800000ff,
  46231. Toolbar::labelTextColourId, 0xff000000,
  46232. Toolbar::editingModeOutlineColourId, 0xffff0000,
  46233. HyperlinkButton::textColourId, 0xcc1111ee,
  46234. GroupComponent::outlineColourId, 0x66000000,
  46235. GroupComponent::textColourId, 0xff000000,
  46236. DirectoryContentsDisplayComponent::highlightColourId, textHighlightColour,
  46237. DirectoryContentsDisplayComponent::textColourId, 0xff000000,
  46238. 0x1000440, /*LassoComponent::lassoFillColourId*/ 0x66dddddd,
  46239. 0x1000441, /*LassoComponent::lassoOutlineColourId*/ 0x99111111,
  46240. MidiKeyboardComponent::whiteNoteColourId, 0xffffffff,
  46241. MidiKeyboardComponent::blackNoteColourId, 0xff000000,
  46242. MidiKeyboardComponent::keySeparatorLineColourId, 0x66000000,
  46243. MidiKeyboardComponent::mouseOverKeyOverlayColourId, 0x80ffff00,
  46244. MidiKeyboardComponent::keyDownOverlayColourId, 0xffb6b600,
  46245. MidiKeyboardComponent::textLabelColourId, 0xff000000,
  46246. MidiKeyboardComponent::upDownButtonBackgroundColourId, 0xffd3d3d3,
  46247. MidiKeyboardComponent::upDownButtonArrowColourId, 0xff000000,
  46248. ColourSelector::backgroundColourId, 0xffe5e5e5,
  46249. ColourSelector::labelTextColourId, 0xff000000,
  46250. FileSearchPathListComponent::backgroundColourId, 0xffffffff,
  46251. };
  46252. for (int i = 0; i < numElementsInArray (standardColours); i += 2)
  46253. setColour (standardColours [i], Colour (standardColours [i + 1]));
  46254. }
  46255. LookAndFeel::~LookAndFeel()
  46256. {
  46257. }
  46258. const Colour LookAndFeel::findColour (const int colourId) const throw()
  46259. {
  46260. const int index = colourIds.indexOf (colourId);
  46261. if (index >= 0)
  46262. return colours [index];
  46263. jassertfalse
  46264. return Colours::black;
  46265. }
  46266. void LookAndFeel::setColour (const int colourId, const Colour& colour) throw()
  46267. {
  46268. const int index = colourIds.indexOf (colourId);
  46269. if (index >= 0)
  46270. colours.set (index, colour);
  46271. colourIds.add (colourId);
  46272. colours.add (colour);
  46273. }
  46274. static LookAndFeel* defaultLF = 0;
  46275. static LookAndFeel* currentDefaultLF = 0;
  46276. LookAndFeel& LookAndFeel::getDefaultLookAndFeel() throw()
  46277. {
  46278. // if this happens, your app hasn't initialised itself properly.. if you're
  46279. // trying to hack your own main() function, have a look at
  46280. // JUCEApplication::initialiseForGUI()
  46281. jassert (currentDefaultLF != 0);
  46282. return *currentDefaultLF;
  46283. }
  46284. void LookAndFeel::setDefaultLookAndFeel (LookAndFeel* newDefaultLookAndFeel) throw()
  46285. {
  46286. if (newDefaultLookAndFeel == 0)
  46287. {
  46288. if (defaultLF == 0)
  46289. defaultLF = new LookAndFeel();
  46290. newDefaultLookAndFeel = defaultLF;
  46291. }
  46292. currentDefaultLF = newDefaultLookAndFeel;
  46293. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  46294. {
  46295. Component* const c = Desktop::getInstance().getComponent (i);
  46296. if (c != 0)
  46297. c->sendLookAndFeelChange();
  46298. }
  46299. }
  46300. void LookAndFeel::clearDefaultLookAndFeel() throw()
  46301. {
  46302. if (currentDefaultLF == defaultLF)
  46303. currentDefaultLF = 0;
  46304. deleteAndZero (defaultLF);
  46305. }
  46306. void LookAndFeel::drawButtonBackground (Graphics& g,
  46307. Button& button,
  46308. const Colour& backgroundColour,
  46309. bool isMouseOverButton,
  46310. bool isButtonDown)
  46311. {
  46312. const int width = button.getWidth();
  46313. const int height = button.getHeight();
  46314. const float outlineThickness = button.isEnabled() ? ((isButtonDown || isMouseOverButton) ? 1.2f : 0.7f) : 0.4f;
  46315. const float halfThickness = outlineThickness * 0.5f;
  46316. const float indentL = button.isConnectedOnLeft() ? 0.1f : halfThickness;
  46317. const float indentR = button.isConnectedOnRight() ? 0.1f : halfThickness;
  46318. const float indentT = button.isConnectedOnTop() ? 0.1f : halfThickness;
  46319. const float indentB = button.isConnectedOnBottom() ? 0.1f : halfThickness;
  46320. const Colour baseColour (createBaseColour (backgroundColour,
  46321. button.hasKeyboardFocus (true),
  46322. isMouseOverButton, isButtonDown)
  46323. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  46324. drawGlassLozenge (g,
  46325. indentL,
  46326. indentT,
  46327. width - indentL - indentR,
  46328. height - indentT - indentB,
  46329. baseColour, outlineThickness, -1.0f,
  46330. button.isConnectedOnLeft(),
  46331. button.isConnectedOnRight(),
  46332. button.isConnectedOnTop(),
  46333. button.isConnectedOnBottom());
  46334. }
  46335. void LookAndFeel::drawButtonText (Graphics& g, TextButton& button,
  46336. bool /*isMouseOverButton*/, bool /*isButtonDown*/)
  46337. {
  46338. g.setFont (button.getFont());
  46339. g.setColour (button.findColour (TextButton::textColourId)
  46340. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  46341. const int yIndent = jmin (4, button.proportionOfHeight (0.3f));
  46342. const int cornerSize = jmin (button.getHeight(), button.getWidth()) / 2;
  46343. const int fontHeight = roundFloatToInt (g.getCurrentFont().getHeight() * 0.6f);
  46344. const int leftIndent = jmin (fontHeight, 2 + cornerSize / (button.isConnectedOnLeft() ? 4 : 2));
  46345. const int rightIndent = jmin (fontHeight, 2 + cornerSize / (button.isConnectedOnRight() ? 4 : 2));
  46346. g.drawFittedText (button.getButtonText(),
  46347. leftIndent,
  46348. yIndent,
  46349. button.getWidth() - leftIndent - rightIndent,
  46350. button.getHeight() - yIndent * 2,
  46351. Justification::centred, 2);
  46352. }
  46353. void LookAndFeel::drawTickBox (Graphics& g,
  46354. Component& component,
  46355. int x, int y, int w, int h,
  46356. const bool ticked,
  46357. const bool isEnabled,
  46358. const bool isMouseOverButton,
  46359. const bool isButtonDown)
  46360. {
  46361. const float boxSize = w * 0.7f;
  46362. drawGlassSphere (g, (float) x, y + (h - boxSize) * 0.5f, boxSize,
  46363. createBaseColour (component.findColour (TextButton::buttonColourId)
  46364. .withMultipliedAlpha (isEnabled ? 1.0f : 0.5f),
  46365. true,
  46366. isMouseOverButton,
  46367. isButtonDown),
  46368. isEnabled ? ((isButtonDown || isMouseOverButton) ? 1.1f : 0.5f) : 0.3f);
  46369. if (ticked)
  46370. {
  46371. Path tick;
  46372. tick.startNewSubPath (1.5f, 3.0f);
  46373. tick.lineTo (3.0f, 6.0f);
  46374. tick.lineTo (6.0f, 0.0f);
  46375. g.setColour (isEnabled ? Colours::black : Colours::grey);
  46376. const AffineTransform trans (AffineTransform::scale (w / 9.0f, h / 9.0f)
  46377. .translated ((float) x, (float) y));
  46378. g.strokePath (tick, PathStrokeType (2.5f), trans);
  46379. }
  46380. }
  46381. void LookAndFeel::drawToggleButton (Graphics& g,
  46382. ToggleButton& button,
  46383. bool isMouseOverButton,
  46384. bool isButtonDown)
  46385. {
  46386. if (button.hasKeyboardFocus (true))
  46387. {
  46388. g.setColour (button.findColour (TextEditor::focusedOutlineColourId));
  46389. g.drawRect (0, 0, button.getWidth(), button.getHeight());
  46390. }
  46391. const int tickWidth = jmin (20, button.getHeight() - 4);
  46392. drawTickBox (g, button, 4, (button.getHeight() - tickWidth) / 2,
  46393. tickWidth, tickWidth,
  46394. button.getToggleState(),
  46395. button.isEnabled(),
  46396. isMouseOverButton,
  46397. isButtonDown);
  46398. g.setColour (button.findColour (ToggleButton::textColourId));
  46399. g.setFont (jmin (15.0f, button.getHeight() * 0.6f));
  46400. if (! button.isEnabled())
  46401. g.setOpacity (0.5f);
  46402. const int textX = tickWidth + 5;
  46403. g.drawFittedText (button.getButtonText(),
  46404. textX, 4,
  46405. button.getWidth() - textX - 2, button.getHeight() - 8,
  46406. Justification::centredLeft, 10);
  46407. }
  46408. void LookAndFeel::changeToggleButtonWidthToFitText (ToggleButton& button)
  46409. {
  46410. Font font (jmin (15.0f, button.getHeight() * 0.6f));
  46411. const int tickWidth = jmin (24, button.getHeight());
  46412. button.setSize (font.getStringWidth (button.getButtonText()) + tickWidth + 8,
  46413. button.getHeight());
  46414. }
  46415. void LookAndFeel::drawAlertBox (Graphics& g,
  46416. AlertWindow& alert,
  46417. const Rectangle& textArea,
  46418. TextLayout& textLayout)
  46419. {
  46420. const int iconWidth = 80;
  46421. const Colour background (alert.findColour (AlertWindow::backgroundColourId));
  46422. g.fillAll (background);
  46423. int iconSpaceUsed = 0;
  46424. Justification alignment (Justification::horizontallyCentred);
  46425. int iconSize = jmin (iconWidth + 50, alert.getHeight() + 20);
  46426. if (alert.containsAnyExtraComponents() || alert.getNumButtons() > 2)
  46427. iconSize = jmin (iconSize, textArea.getHeight() + 50);
  46428. const Rectangle iconRect (iconSize / -10,
  46429. iconSize / -10,
  46430. iconSize,
  46431. iconSize);
  46432. if (alert.getAlertType() == AlertWindow::QuestionIcon
  46433. || alert.getAlertType() == AlertWindow::InfoIcon)
  46434. {
  46435. if (alert.getAlertType() == AlertWindow::InfoIcon)
  46436. g.setColour (background.overlaidWith (Colour (0x280000ff)));
  46437. else
  46438. g.setColour (background.overlaidWith (Colours::gold.darker().withAlpha (0.25f)));
  46439. g.fillEllipse ((float) iconRect.getX(),
  46440. (float) iconRect.getY(),
  46441. (float) iconRect.getWidth(),
  46442. (float) iconRect.getHeight());
  46443. g.setColour (background);
  46444. g.setFont (iconRect.getHeight() * 0.9f, Font::bold);
  46445. g.drawText ((alert.getAlertType() == AlertWindow::InfoIcon) ? "i"
  46446. : "?",
  46447. iconRect.getX(),
  46448. iconRect.getY(),
  46449. iconRect.getWidth(),
  46450. iconRect.getHeight(),
  46451. Justification::centred, false);
  46452. iconSpaceUsed = iconWidth;
  46453. alignment = Justification::left;
  46454. }
  46455. else if (alert.getAlertType() == AlertWindow::WarningIcon)
  46456. {
  46457. Path p;
  46458. p.addTriangle (iconRect.getX() + iconRect.getWidth() * 0.5f,
  46459. (float) iconRect.getY(),
  46460. (float) iconRect.getRight(),
  46461. (float) iconRect.getBottom(),
  46462. (float) iconRect.getX(),
  46463. (float) iconRect.getBottom());
  46464. g.setColour (background.overlaidWith (Colour (0x33ff0000)));
  46465. g.fillPath (p.createPathWithRoundedCorners (5.0f));
  46466. g.setColour (background);
  46467. g.setFont (iconRect.getHeight() * 0.9f, Font::bold);
  46468. g.drawText (T("!"),
  46469. iconRect.getX(),
  46470. iconRect.getY(),
  46471. iconRect.getWidth(),
  46472. iconRect.getHeight() + iconRect.getHeight() / 8,
  46473. Justification::centred, false);
  46474. iconSpaceUsed = iconWidth;
  46475. alignment = Justification::left;
  46476. }
  46477. g.setColour (alert.findColour (AlertWindow::textColourId));
  46478. textLayout.drawWithin (g,
  46479. textArea.getX() + iconSpaceUsed,
  46480. textArea.getY(),
  46481. textArea.getWidth() - iconSpaceUsed,
  46482. textArea.getHeight(),
  46483. alignment.getFlags() | Justification::top);
  46484. g.setColour (alert.findColour (AlertWindow::outlineColourId));
  46485. g.drawRect (0, 0, alert.getWidth(), alert.getHeight());
  46486. }
  46487. int LookAndFeel::getAlertBoxWindowFlags()
  46488. {
  46489. return ComponentPeer::windowAppearsOnTaskbar
  46490. | ComponentPeer::windowHasDropShadow;
  46491. }
  46492. void LookAndFeel::drawProgressBar (Graphics& g, ProgressBar& progressBar,
  46493. int width, int height,
  46494. double progress, const String& textToShow)
  46495. {
  46496. const Colour background (progressBar.findColour (ProgressBar::backgroundColourId));
  46497. const Colour foreground (progressBar.findColour (ProgressBar::foregroundColourId));
  46498. g.fillAll (background);
  46499. if (progress >= 0.0f && progress < 1.0f)
  46500. {
  46501. drawGlassLozenge (g, 1.0f, 1.0f,
  46502. (float) jlimit (0.0, width - 2.0, progress * (width - 2.0)),
  46503. (float) (height - 2),
  46504. foreground,
  46505. 0.5f, 0.0f,
  46506. true, true, true, true);
  46507. }
  46508. else
  46509. {
  46510. // spinning bar..
  46511. g.setColour (foreground);
  46512. const int stripeWidth = height * 2;
  46513. const int position = (Time::getMillisecondCounter() / 15) % stripeWidth;
  46514. Path p;
  46515. for (float x = (float) (-stripeWidth - position); x < width + stripeWidth; x += stripeWidth)
  46516. p.addQuadrilateral (x, 0.0f,
  46517. x + stripeWidth * 0.5f, 0.0f,
  46518. x, (float) height,
  46519. x - stripeWidth * 0.5f, (float) height);
  46520. Image im (Image::ARGB, width, height, true);
  46521. {
  46522. Graphics g (im);
  46523. drawGlassLozenge (g, 1.0f, 1.0f,
  46524. (float) (width - 2),
  46525. (float) (height - 2),
  46526. foreground,
  46527. 0.5f, 0.0f,
  46528. true, true, true, true);
  46529. }
  46530. ImageBrush ib (&im, 0, 0, 0.85f);
  46531. g.setBrush (&ib);
  46532. g.fillPath (p);
  46533. }
  46534. if (textToShow.isNotEmpty())
  46535. {
  46536. g.setColour (Colour::contrasting (background, foreground));
  46537. g.setFont (height * 0.6f);
  46538. g.drawText (textToShow, 0, 0, width, height, Justification::centred, false);
  46539. }
  46540. }
  46541. void LookAndFeel::drawScrollbarButton (Graphics& g,
  46542. ScrollBar& scrollbar,
  46543. int width, int height,
  46544. int buttonDirection,
  46545. bool /*isScrollbarVertical*/,
  46546. bool /*isMouseOverButton*/,
  46547. bool isButtonDown)
  46548. {
  46549. Path p;
  46550. if (buttonDirection == 0)
  46551. p.addTriangle (width * 0.5f, height * 0.2f,
  46552. width * 0.1f, height * 0.7f,
  46553. width * 0.9f, height * 0.7f);
  46554. else if (buttonDirection == 1)
  46555. p.addTriangle (width * 0.8f, height * 0.5f,
  46556. width * 0.3f, height * 0.1f,
  46557. width * 0.3f, height * 0.9f);
  46558. else if (buttonDirection == 2)
  46559. p.addTriangle (width * 0.5f, height * 0.8f,
  46560. width * 0.1f, height * 0.3f,
  46561. width * 0.9f, height * 0.3f);
  46562. else if (buttonDirection == 3)
  46563. p.addTriangle (width * 0.2f, height * 0.5f,
  46564. width * 0.7f, height * 0.1f,
  46565. width * 0.7f, height * 0.9f);
  46566. if (isButtonDown)
  46567. g.setColour (scrollbar.findColour (ScrollBar::thumbColourId).contrasting (0.2f));
  46568. else
  46569. g.setColour (scrollbar.findColour (ScrollBar::thumbColourId));
  46570. g.fillPath (p);
  46571. g.setColour (Colour (0x80000000));
  46572. g.strokePath (p, PathStrokeType (0.5f));
  46573. }
  46574. void LookAndFeel::drawScrollbar (Graphics& g,
  46575. ScrollBar& scrollbar,
  46576. int x, int y,
  46577. int width, int height,
  46578. bool isScrollbarVertical,
  46579. int thumbStartPosition,
  46580. int thumbSize,
  46581. bool /*isMouseOver*/,
  46582. bool /*isMouseDown*/)
  46583. {
  46584. g.fillAll (scrollbar.findColour (ScrollBar::backgroundColourId));
  46585. Path slotPath, thumbPath;
  46586. const float slotIndent = jmin (width, height) > 15 ? 1.0f : 0.0f;
  46587. const float slotIndentx2 = slotIndent * 2.0f;
  46588. const float thumbIndent = slotIndent + 1.0f;
  46589. const float thumbIndentx2 = thumbIndent * 2.0f;
  46590. float gx1 = 0.0f, gy1 = 0.0f, gx2 = 0.0f, gy2 = 0.0f;
  46591. if (isScrollbarVertical)
  46592. {
  46593. slotPath.addRoundedRectangle (x + slotIndent,
  46594. y + slotIndent,
  46595. width - slotIndentx2,
  46596. height - slotIndentx2,
  46597. (width - slotIndentx2) * 0.5f);
  46598. if (thumbSize > 0)
  46599. thumbPath.addRoundedRectangle (x + thumbIndent,
  46600. thumbStartPosition + thumbIndent,
  46601. width - thumbIndentx2,
  46602. thumbSize - thumbIndentx2,
  46603. (width - thumbIndentx2) * 0.5f);
  46604. gx1 = (float) x;
  46605. gx2 = x + width * 0.7f;
  46606. }
  46607. else
  46608. {
  46609. slotPath.addRoundedRectangle (x + slotIndent,
  46610. y + slotIndent,
  46611. width - slotIndentx2,
  46612. height - slotIndentx2,
  46613. (height - slotIndentx2) * 0.5f);
  46614. if (thumbSize > 0)
  46615. thumbPath.addRoundedRectangle (thumbStartPosition + thumbIndent,
  46616. y + thumbIndent,
  46617. thumbSize - thumbIndentx2,
  46618. height - thumbIndentx2,
  46619. (height - thumbIndentx2) * 0.5f);
  46620. gy1 = (float) y;
  46621. gy2 = y + height * 0.7f;
  46622. }
  46623. const Colour thumbColour (scrollbar.findColour (ScrollBar::trackColourId));
  46624. GradientBrush gb (thumbColour.overlaidWith (Colour (0x44000000)),
  46625. gx1, gy1,
  46626. thumbColour.overlaidWith (Colour (0x19000000)),
  46627. gx2, gy2, false);
  46628. g.setBrush (&gb);
  46629. g.fillPath (slotPath);
  46630. if (isScrollbarVertical)
  46631. {
  46632. gx1 = x + width * 0.6f;
  46633. gx2 = (float) x + width;
  46634. }
  46635. else
  46636. {
  46637. gy1 = y + height * 0.6f;
  46638. gy2 = (float) y + height;
  46639. }
  46640. GradientBrush gb2 (Colours::transparentBlack,
  46641. gx1, gy1,
  46642. Colour (0x19000000),
  46643. gx2, gy2, false);
  46644. g.setBrush (&gb2);
  46645. g.fillPath (slotPath);
  46646. g.setColour (thumbColour);
  46647. g.fillPath (thumbPath);
  46648. GradientBrush gb3 (Colour (0x10000000),
  46649. gx1, gy1,
  46650. Colours::transparentBlack,
  46651. gx2, gy2, false);
  46652. g.saveState();
  46653. g.setBrush (&gb3);
  46654. if (isScrollbarVertical)
  46655. g.reduceClipRegion (x + width / 2, y, width, height);
  46656. else
  46657. g.reduceClipRegion (x, y + height / 2, width, height);
  46658. g.fillPath (thumbPath);
  46659. g.restoreState();
  46660. g.setColour (Colour (0x4c000000));
  46661. g.strokePath (thumbPath, PathStrokeType (0.4f));
  46662. }
  46663. ImageEffectFilter* LookAndFeel::getScrollbarEffect()
  46664. {
  46665. return 0;
  46666. }
  46667. int LookAndFeel::getMinimumScrollbarThumbSize (ScrollBar& scrollbar)
  46668. {
  46669. return jmin (scrollbar.getWidth(), scrollbar.getHeight()) * 2;
  46670. }
  46671. int LookAndFeel::getDefaultScrollbarWidth()
  46672. {
  46673. return 18;
  46674. }
  46675. int LookAndFeel::getScrollbarButtonSize (ScrollBar& scrollbar)
  46676. {
  46677. return 2 + (scrollbar.isVertical() ? scrollbar.getWidth()
  46678. : scrollbar.getHeight());
  46679. }
  46680. const Path LookAndFeel::getTickShape (const float height)
  46681. {
  46682. static const unsigned char tickShapeData[] =
  46683. {
  46684. 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,
  46685. 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,
  46686. 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,
  46687. 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,
  46688. 96,140,68,0,128,188,67,0,224,168,68,0,0,119,67,99,101
  46689. };
  46690. Path p;
  46691. p.loadPathFromData (tickShapeData, sizeof (tickShapeData));
  46692. p.scaleToFit (0, 0, height * 2.0f, height, true);
  46693. return p;
  46694. }
  46695. const Path LookAndFeel::getCrossShape (const float height)
  46696. {
  46697. static const unsigned char crossShapeData[] =
  46698. {
  46699. 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,
  46700. 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,
  46701. 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,
  46702. 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,
  46703. 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,
  46704. 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,
  46705. 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
  46706. };
  46707. Path p;
  46708. p.loadPathFromData (crossShapeData, sizeof (crossShapeData));
  46709. p.scaleToFit (0, 0, height * 2.0f, height, true);
  46710. return p;
  46711. }
  46712. void LookAndFeel::drawTreeviewPlusMinusBox (Graphics& g, int x, int y, int w, int h, bool isPlus)
  46713. {
  46714. const int boxSize = ((jmin (16, w, h) << 1) / 3) | 1;
  46715. x += (w - boxSize) >> 1;
  46716. y += (h - boxSize) >> 1;
  46717. w = boxSize;
  46718. h = boxSize;
  46719. g.setColour (Colour (0xe5ffffff));
  46720. g.fillRect (x, y, w, h);
  46721. g.setColour (Colour (0x80000000));
  46722. g.drawRect (x, y, w, h);
  46723. const float size = boxSize / 2 + 1.0f;
  46724. const float centre = (float) (boxSize / 2);
  46725. g.fillRect (x + (w - size) * 0.5f, y + centre, size, 1.0f);
  46726. if (isPlus)
  46727. g.fillRect (x + centre, y + (h - size) * 0.5f, 1.0f, size);
  46728. }
  46729. void LookAndFeel::drawBubble (Graphics& g,
  46730. float tipX, float tipY,
  46731. float boxX, float boxY,
  46732. float boxW, float boxH)
  46733. {
  46734. int side = 0;
  46735. if (tipX < boxX)
  46736. side = 1;
  46737. else if (tipX > boxX + boxW)
  46738. side = 3;
  46739. else if (tipY > boxY + boxH)
  46740. side = 2;
  46741. const float indent = 2.0f;
  46742. Path p;
  46743. p.addBubble (boxX + indent,
  46744. boxY + indent,
  46745. boxW - indent * 2.0f,
  46746. boxH - indent * 2.0f,
  46747. 5.0f,
  46748. tipX, tipY,
  46749. side,
  46750. 0.5f,
  46751. jmin (15.0f, boxW * 0.3f, boxH * 0.3f));
  46752. //xxx need to take comp as param for colour
  46753. g.setColour (findColour (TooltipWindow::backgroundColourId).withAlpha (0.9f));
  46754. g.fillPath (p);
  46755. //xxx as above
  46756. g.setColour (findColour (TooltipWindow::textColourId).withAlpha (0.4f));
  46757. g.strokePath (p, PathStrokeType (1.33f));
  46758. }
  46759. const Font LookAndFeel::getPopupMenuFont()
  46760. {
  46761. return Font (17.0f);
  46762. }
  46763. void LookAndFeel::getIdealPopupMenuItemSize (const String& text,
  46764. const bool isSeparator,
  46765. int standardMenuItemHeight,
  46766. int& idealWidth,
  46767. int& idealHeight)
  46768. {
  46769. if (isSeparator)
  46770. {
  46771. idealWidth = 50;
  46772. idealHeight = standardMenuItemHeight > 0 ? standardMenuItemHeight / 2 : 10;
  46773. }
  46774. else
  46775. {
  46776. Font font (getPopupMenuFont());
  46777. if (standardMenuItemHeight > 0 && font.getHeight() > standardMenuItemHeight / 1.3f)
  46778. font.setHeight (standardMenuItemHeight / 1.3f);
  46779. idealHeight = standardMenuItemHeight > 0 ? standardMenuItemHeight : roundFloatToInt (font.getHeight() * 1.3f);
  46780. idealWidth = font.getStringWidth (text) + idealHeight * 2;
  46781. }
  46782. }
  46783. void LookAndFeel::drawPopupMenuBackground (Graphics& g, int width, int height)
  46784. {
  46785. const Colour background (findColour (PopupMenu::backgroundColourId));
  46786. g.fillAll (background);
  46787. g.setColour (background.overlaidWith (Colour (0x2badd8e6)));
  46788. for (int i = 0; i < height; i += 3)
  46789. g.fillRect (0, i, width, 1);
  46790. g.setColour (findColour (PopupMenu::textColourId).withAlpha (0.6f));
  46791. g.drawRect (0, 0, width, height);
  46792. }
  46793. void LookAndFeel::drawPopupMenuUpDownArrow (Graphics& g,
  46794. int width, int height,
  46795. bool isScrollUpArrow)
  46796. {
  46797. const Colour background (findColour (PopupMenu::backgroundColourId));
  46798. GradientBrush gb (background,
  46799. 0.0f, height * 0.5f,
  46800. background.withAlpha (0.0f),
  46801. 0.0f, isScrollUpArrow ? ((float) height) : 0.0f,
  46802. false);
  46803. g.setBrush (&gb);
  46804. g.fillRect (1, 1, width - 2, height - 2);
  46805. const float hw = width * 0.5f;
  46806. const float arrowW = height * 0.3f;
  46807. const float y1 = height * (isScrollUpArrow ? 0.6f : 0.3f);
  46808. const float y2 = height * (isScrollUpArrow ? 0.3f : 0.6f);
  46809. Path p;
  46810. p.addTriangle (hw - arrowW, y1,
  46811. hw + arrowW, y1,
  46812. hw, y2);
  46813. g.setColour (findColour (PopupMenu::textColourId).withAlpha (0.5f));
  46814. g.fillPath (p);
  46815. }
  46816. void LookAndFeel::drawPopupMenuItem (Graphics& g,
  46817. int width, int height,
  46818. const bool isSeparator,
  46819. const bool isActive,
  46820. const bool isHighlighted,
  46821. const bool isTicked,
  46822. const bool hasSubMenu,
  46823. const String& text,
  46824. const String& shortcutKeyText,
  46825. Image* image,
  46826. const Colour* const textColourToUse)
  46827. {
  46828. const float halfH = height * 0.5f;
  46829. if (isSeparator)
  46830. {
  46831. const float separatorIndent = 5.5f;
  46832. g.setColour (Colour (0x33000000));
  46833. g.drawLine (separatorIndent, halfH, width - separatorIndent, halfH);
  46834. g.setColour (Colour (0x66ffffff));
  46835. g.drawLine (separatorIndent, halfH + 1.0f, width - separatorIndent, halfH + 1.0f);
  46836. }
  46837. else
  46838. {
  46839. Colour textColour (findColour (PopupMenu::textColourId));
  46840. if (textColourToUse != 0)
  46841. textColour = *textColourToUse;
  46842. if (isHighlighted)
  46843. {
  46844. g.setColour (findColour (PopupMenu::highlightedBackgroundColourId));
  46845. g.fillRect (1, 1, width - 2, height - 2);
  46846. g.setColour (findColour (PopupMenu::highlightedTextColourId));
  46847. }
  46848. else
  46849. {
  46850. g.setColour (textColour);
  46851. }
  46852. if (! isActive)
  46853. g.setOpacity (0.3f);
  46854. Font font (getPopupMenuFont());
  46855. if (font.getHeight() > height / 1.3f)
  46856. font.setHeight (height / 1.3f);
  46857. g.setFont (font);
  46858. const int leftBorder = (height * 5) / 4;
  46859. const int rightBorder = 4;
  46860. if (image != 0)
  46861. {
  46862. g.drawImageWithin (image,
  46863. 2, 1, leftBorder - 4, height - 2,
  46864. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize, false);
  46865. }
  46866. else if (isTicked)
  46867. {
  46868. const Path tick (getTickShape (1.0f));
  46869. const float th = font.getAscent();
  46870. const float ty = halfH - th * 0.5f;
  46871. g.fillPath (tick, tick.getTransformToScaleToFit (2.0f, ty, (float) (leftBorder - 4),
  46872. th, true));
  46873. }
  46874. g.drawFittedText (text,
  46875. leftBorder, 0,
  46876. width - (leftBorder + rightBorder), height,
  46877. Justification::centredLeft, 1);
  46878. if (shortcutKeyText.isNotEmpty())
  46879. {
  46880. Font f2 (g.getCurrentFont());
  46881. f2.setHeight (f2.getHeight() * 0.75f);
  46882. f2.setHorizontalScale (0.95f);
  46883. g.setFont (f2);
  46884. g.drawText (shortcutKeyText,
  46885. leftBorder,
  46886. 0,
  46887. width - (leftBorder + rightBorder + 4),
  46888. height,
  46889. Justification::centredRight,
  46890. true);
  46891. }
  46892. if (hasSubMenu)
  46893. {
  46894. const float arrowH = 0.6f * getPopupMenuFont().getAscent();
  46895. const float x = width - height * 0.6f;
  46896. Path p;
  46897. p.addTriangle (x, halfH - arrowH * 0.5f,
  46898. x, halfH + arrowH * 0.5f,
  46899. x + arrowH * 0.6f, halfH);
  46900. g.fillPath (p);
  46901. }
  46902. }
  46903. }
  46904. int LookAndFeel::getMenuWindowFlags()
  46905. {
  46906. return ComponentPeer::windowHasDropShadow;
  46907. }
  46908. void LookAndFeel::drawMenuBarBackground (Graphics& g, int width, int height,
  46909. bool, MenuBarComponent& menuBar)
  46910. {
  46911. const Colour baseColour (createBaseColour (menuBar.findColour (PopupMenu::backgroundColourId), false, false, false));
  46912. if (menuBar.isEnabled())
  46913. {
  46914. drawShinyButtonShape (g,
  46915. -4.0f, 0.0f,
  46916. width + 8.0f, (float) height,
  46917. 0.0f,
  46918. baseColour,
  46919. 0.4f,
  46920. true, true, true, true);
  46921. }
  46922. else
  46923. {
  46924. g.fillAll (baseColour);
  46925. }
  46926. }
  46927. const Font LookAndFeel::getMenuBarFont (MenuBarComponent& menuBar, int /*itemIndex*/, const String& /*itemText*/)
  46928. {
  46929. return Font (menuBar.getHeight() * 0.7f);
  46930. }
  46931. int LookAndFeel::getMenuBarItemWidth (MenuBarComponent& menuBar, int itemIndex, const String& itemText)
  46932. {
  46933. return getMenuBarFont (menuBar, itemIndex, itemText)
  46934. .getStringWidth (itemText) + menuBar.getHeight();
  46935. }
  46936. void LookAndFeel::drawMenuBarItem (Graphics& g,
  46937. int width, int height,
  46938. int itemIndex,
  46939. const String& itemText,
  46940. bool isMouseOverItem,
  46941. bool isMenuOpen,
  46942. bool /*isMouseOverBar*/,
  46943. MenuBarComponent& menuBar)
  46944. {
  46945. if (! menuBar.isEnabled())
  46946. {
  46947. g.setColour (menuBar.findColour (PopupMenu::textColourId)
  46948. .withMultipliedAlpha (0.5f));
  46949. }
  46950. else if (isMenuOpen || isMouseOverItem)
  46951. {
  46952. g.fillAll (menuBar.findColour (PopupMenu::highlightedBackgroundColourId));
  46953. g.setColour (menuBar.findColour (PopupMenu::highlightedTextColourId));
  46954. }
  46955. else
  46956. {
  46957. g.setColour (menuBar.findColour (PopupMenu::textColourId));
  46958. }
  46959. g.setFont (getMenuBarFont (menuBar, itemIndex, itemText));
  46960. g.drawFittedText (itemText, 0, 0, width, height, Justification::centred, 1);
  46961. }
  46962. void LookAndFeel::fillTextEditorBackground (Graphics& g, int /*width*/, int /*height*/,
  46963. TextEditor& textEditor)
  46964. {
  46965. g.fillAll (textEditor.findColour (TextEditor::backgroundColourId));
  46966. }
  46967. void LookAndFeel::drawTextEditorOutline (Graphics& g, int width, int height, TextEditor& textEditor)
  46968. {
  46969. if (textEditor.isEnabled())
  46970. {
  46971. if (textEditor.hasKeyboardFocus (true) && ! textEditor.isReadOnly())
  46972. {
  46973. const int border = 2;
  46974. g.setColour (textEditor.findColour (TextEditor::focusedOutlineColourId));
  46975. g.drawRect (0, 0, width, height, border);
  46976. g.setOpacity (1.0f);
  46977. const Colour shadowColour (textEditor.findColour (TextEditor::shadowColourId).withMultipliedAlpha (0.75f));
  46978. g.drawBevel (0, 0, width, height + 2, border + 2, shadowColour, shadowColour);
  46979. }
  46980. else
  46981. {
  46982. g.setColour (textEditor.findColour (TextEditor::outlineColourId));
  46983. g.drawRect (0, 0, width, height);
  46984. g.setOpacity (1.0f);
  46985. const Colour shadowColour (textEditor.findColour (TextEditor::shadowColourId));
  46986. g.drawBevel (0, 0, width, height + 2, 3, shadowColour, shadowColour);
  46987. }
  46988. }
  46989. }
  46990. void LookAndFeel::drawComboBox (Graphics& g, int width, int height,
  46991. const bool isButtonDown,
  46992. int buttonX, int buttonY,
  46993. int buttonW, int buttonH,
  46994. ComboBox& box)
  46995. {
  46996. g.fillAll (box.findColour (ComboBox::backgroundColourId));
  46997. if (box.isEnabled() && box.hasKeyboardFocus (false))
  46998. {
  46999. g.setColour (box.findColour (TextButton::buttonColourId));
  47000. g.drawRect (0, 0, width, height, 2);
  47001. }
  47002. else
  47003. {
  47004. g.setColour (box.findColour (ComboBox::outlineColourId));
  47005. g.drawRect (0, 0, width, height);
  47006. }
  47007. const float outlineThickness = box.isEnabled() ? (isButtonDown ? 1.2f : 0.5f) : 0.3f;
  47008. const Colour baseColour (createBaseColour (box.findColour (ComboBox::buttonColourId),
  47009. box.hasKeyboardFocus (true),
  47010. false, isButtonDown)
  47011. .withMultipliedAlpha (box.isEnabled() ? 1.0f : 0.5f));
  47012. drawGlassLozenge (g,
  47013. buttonX + outlineThickness, buttonY + outlineThickness,
  47014. buttonW - outlineThickness * 2.0f, buttonH - outlineThickness * 2.0f,
  47015. baseColour, outlineThickness, -1.0f,
  47016. true, true, true, true);
  47017. if (box.isEnabled())
  47018. {
  47019. const float arrowX = 0.3f;
  47020. const float arrowH = 0.2f;
  47021. Path p;
  47022. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.45f - arrowH),
  47023. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.45f,
  47024. buttonX + buttonW * arrowX, buttonY + buttonH * 0.45f);
  47025. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.55f + arrowH),
  47026. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.55f,
  47027. buttonX + buttonW * arrowX, buttonY + buttonH * 0.55f);
  47028. g.setColour (box.findColour (ComboBox::arrowColourId));
  47029. g.fillPath (p);
  47030. }
  47031. }
  47032. const Font LookAndFeel::getComboBoxFont (ComboBox& box)
  47033. {
  47034. return Font (jmin (15.0f, box.getHeight() * 0.85f));
  47035. }
  47036. Label* LookAndFeel::createComboBoxTextBox (ComboBox&)
  47037. {
  47038. return new Label (String::empty, String::empty);
  47039. }
  47040. void LookAndFeel::positionComboBoxText (ComboBox& box, Label& label)
  47041. {
  47042. label.setBounds (1, 1,
  47043. box.getWidth() + 3 - box.getHeight(),
  47044. box.getHeight() - 2);
  47045. label.setFont (getComboBoxFont (box));
  47046. }
  47047. void LookAndFeel::drawLinearSliderBackground (Graphics& g,
  47048. int x, int y,
  47049. int width, int height,
  47050. float /*sliderPos*/,
  47051. float /*minSliderPos*/,
  47052. float /*maxSliderPos*/,
  47053. const Slider::SliderStyle /*style*/,
  47054. Slider& slider)
  47055. {
  47056. const float sliderRadius = (float) (getSliderThumbRadius (slider) - 2);
  47057. const Colour trackColour (slider.findColour (Slider::trackColourId));
  47058. const Colour gradCol1 (trackColour.overlaidWith (Colours::black.withAlpha (slider.isEnabled() ? 0.25f : 0.13f)));
  47059. const Colour gradCol2 (trackColour.overlaidWith (Colour (0x14000000)));
  47060. Path indent;
  47061. if (slider.isHorizontal())
  47062. {
  47063. const float iy = y + height * 0.5f - sliderRadius * 0.5f;
  47064. const float ih = sliderRadius;
  47065. GradientBrush gb (gradCol1, 0.0f, iy,
  47066. gradCol2, 0.0f, iy + ih, false);
  47067. g.setBrush (&gb);
  47068. indent.addRoundedRectangle (x - sliderRadius * 0.5f, iy,
  47069. width + sliderRadius, ih,
  47070. 5.0f);
  47071. g.fillPath (indent);
  47072. }
  47073. else
  47074. {
  47075. const float ix = x + width * 0.5f - sliderRadius * 0.5f;
  47076. const float iw = sliderRadius;
  47077. GradientBrush gb (gradCol1, ix, 0.0f,
  47078. gradCol2, ix + iw, 0.0f, false);
  47079. g.setBrush (&gb);
  47080. indent.addRoundedRectangle (ix, y - sliderRadius * 0.5f,
  47081. iw, height + sliderRadius,
  47082. 5.0f);
  47083. g.fillPath (indent);
  47084. }
  47085. g.setColour (Colour (0x4c000000));
  47086. g.strokePath (indent, PathStrokeType (0.5f));
  47087. }
  47088. void LookAndFeel::drawLinearSliderThumb (Graphics& g,
  47089. int x, int y,
  47090. int width, int height,
  47091. float sliderPos,
  47092. float minSliderPos,
  47093. float maxSliderPos,
  47094. const Slider::SliderStyle style,
  47095. Slider& slider)
  47096. {
  47097. const float sliderRadius = (float) (getSliderThumbRadius (slider) - 2);
  47098. Colour knobColour (createBaseColour (slider.findColour (Slider::thumbColourId),
  47099. slider.hasKeyboardFocus (false) && slider.isEnabled(),
  47100. slider.isMouseOverOrDragging() && slider.isEnabled(),
  47101. slider.isMouseButtonDown() && slider.isEnabled()));
  47102. const float outlineThickness = slider.isEnabled() ? 0.8f : 0.3f;
  47103. if (style == Slider::LinearHorizontal || style == Slider::LinearVertical)
  47104. {
  47105. float kx, ky;
  47106. if (style == Slider::LinearVertical)
  47107. {
  47108. kx = x + width * 0.5f;
  47109. ky = sliderPos;
  47110. }
  47111. else
  47112. {
  47113. kx = sliderPos;
  47114. ky = y + height * 0.5f;
  47115. }
  47116. drawGlassSphere (g,
  47117. kx - sliderRadius,
  47118. ky - sliderRadius,
  47119. sliderRadius * 2.0f,
  47120. knobColour, outlineThickness);
  47121. }
  47122. else
  47123. {
  47124. if (style == Slider::ThreeValueVertical)
  47125. {
  47126. drawGlassSphere (g, x + width * 0.5f - sliderRadius,
  47127. sliderPos - sliderRadius,
  47128. sliderRadius * 2.0f,
  47129. knobColour, outlineThickness);
  47130. }
  47131. else if (style == Slider::ThreeValueHorizontal)
  47132. {
  47133. drawGlassSphere (g,sliderPos - sliderRadius,
  47134. y + height * 0.5f - sliderRadius,
  47135. sliderRadius * 2.0f,
  47136. knobColour, outlineThickness);
  47137. }
  47138. if (style == Slider::TwoValueVertical || style == Slider::ThreeValueVertical)
  47139. {
  47140. const float sr = jmin (sliderRadius, width * 0.4f);
  47141. drawGlassPointer (g, jmax (0.0f, x + width * 0.5f - sliderRadius * 2.0f),
  47142. minSliderPos - sliderRadius,
  47143. sliderRadius * 2.0f, knobColour, outlineThickness, 1);
  47144. drawGlassPointer (g, jmin (x + width - sliderRadius * 2.0f, x + width * 0.5f), maxSliderPos - sr,
  47145. sliderRadius * 2.0f, knobColour, outlineThickness, 3);
  47146. }
  47147. else if (style == Slider::TwoValueHorizontal || style == Slider::ThreeValueHorizontal)
  47148. {
  47149. const float sr = jmin (sliderRadius, height * 0.4f);
  47150. drawGlassPointer (g, minSliderPos - sr,
  47151. jmax (0.0f, y + height * 0.5f - sliderRadius * 2.0f),
  47152. sliderRadius * 2.0f, knobColour, outlineThickness, 2);
  47153. drawGlassPointer (g, maxSliderPos - sliderRadius,
  47154. jmin (y + height - sliderRadius * 2.0f, y + height * 0.5f),
  47155. sliderRadius * 2.0f, knobColour, outlineThickness, 4);
  47156. }
  47157. }
  47158. }
  47159. void LookAndFeel::drawLinearSlider (Graphics& g,
  47160. int x, int y,
  47161. int width, int height,
  47162. float sliderPos,
  47163. float minSliderPos,
  47164. float maxSliderPos,
  47165. const Slider::SliderStyle style,
  47166. Slider& slider)
  47167. {
  47168. g.fillAll (slider.findColour (Slider::backgroundColourId));
  47169. if (style == Slider::LinearBar)
  47170. {
  47171. const bool isMouseOver = slider.isMouseOverOrDragging() && slider.isEnabled();
  47172. Colour baseColour (createBaseColour (slider.findColour (Slider::thumbColourId)
  47173. .withMultipliedSaturation (slider.isEnabled() ? 1.0f : 0.5f),
  47174. false,
  47175. isMouseOver,
  47176. isMouseOver || slider.isMouseButtonDown()));
  47177. drawShinyButtonShape (g,
  47178. (float) x, (float) y, sliderPos - (float) x, (float) height, 0.0f,
  47179. baseColour,
  47180. slider.isEnabled() ? 0.9f : 0.3f,
  47181. true, true, true, true);
  47182. }
  47183. else
  47184. {
  47185. drawLinearSliderBackground (g, x, y, width, height, sliderPos, minSliderPos, maxSliderPos, style, slider);
  47186. drawLinearSliderThumb (g, x, y, width, height, sliderPos, minSliderPos, maxSliderPos, style, slider);
  47187. }
  47188. }
  47189. int LookAndFeel::getSliderThumbRadius (Slider& slider)
  47190. {
  47191. return jmin (7,
  47192. slider.getHeight() / 2,
  47193. slider.getWidth() / 2) + 2;
  47194. }
  47195. void LookAndFeel::drawRotarySlider (Graphics& g,
  47196. int x, int y,
  47197. int width, int height,
  47198. float sliderPos,
  47199. const float rotaryStartAngle,
  47200. const float rotaryEndAngle,
  47201. Slider& slider)
  47202. {
  47203. const float radius = jmin (width / 2, height / 2) - 2.0f;
  47204. const float centreX = x + width * 0.5f;
  47205. const float centreY = y + height * 0.5f;
  47206. const float rx = centreX - radius;
  47207. const float ry = centreY - radius;
  47208. const float rw = radius * 2.0f;
  47209. const float angle = rotaryStartAngle + sliderPos * (rotaryEndAngle - rotaryStartAngle);
  47210. const bool isMouseOver = slider.isMouseOverOrDragging() && slider.isEnabled();
  47211. if (radius > 12.0f)
  47212. {
  47213. if (slider.isEnabled())
  47214. g.setColour (slider.findColour (Slider::rotarySliderFillColourId).withAlpha (isMouseOver ? 1.0f : 0.7f));
  47215. else
  47216. g.setColour (Colour (0x80808080));
  47217. const float thickness = 0.7f;
  47218. {
  47219. Path filledArc;
  47220. filledArc.addPieSegment (rx, ry, rw, rw,
  47221. rotaryStartAngle,
  47222. angle,
  47223. thickness);
  47224. g.fillPath (filledArc);
  47225. }
  47226. if (thickness > 0)
  47227. {
  47228. const float innerRadius = radius * 0.2f;
  47229. Path p;
  47230. p.addTriangle (-innerRadius, 0.0f,
  47231. 0.0f, -radius * thickness * 1.1f,
  47232. innerRadius, 0.0f);
  47233. p.addEllipse (-innerRadius, -innerRadius, innerRadius * 2.0f, innerRadius * 2.0f);
  47234. g.fillPath (p, AffineTransform::rotation (angle).translated (centreX, centreY));
  47235. }
  47236. if (slider.isEnabled())
  47237. {
  47238. g.setColour (slider.findColour (Slider::rotarySliderOutlineColourId));
  47239. Path outlineArc;
  47240. outlineArc.addPieSegment (rx, ry, rw, rw, rotaryStartAngle, rotaryEndAngle, thickness);
  47241. outlineArc.closeSubPath();
  47242. g.strokePath (outlineArc, PathStrokeType (slider.isEnabled() ? (isMouseOver ? 2.0f : 1.2f) : 0.3f));
  47243. }
  47244. }
  47245. else
  47246. {
  47247. if (slider.isEnabled())
  47248. g.setColour (slider.findColour (Slider::rotarySliderFillColourId).withAlpha (isMouseOver ? 1.0f : 0.7f));
  47249. else
  47250. g.setColour (Colour (0x80808080));
  47251. Path p;
  47252. p.addEllipse (-0.4f * rw, -0.4f * rw, rw * 0.8f, rw * 0.8f);
  47253. PathStrokeType (rw * 0.1f).createStrokedPath (p, p);
  47254. p.addLineSegment (0.0f, 0.0f, 0.0f, -radius, rw * 0.2f);
  47255. g.fillPath (p, AffineTransform::rotation (angle).translated (centreX, centreY));
  47256. }
  47257. }
  47258. Button* LookAndFeel::createSliderButton (const bool isIncrement)
  47259. {
  47260. return new TextButton (isIncrement ? "+" : "-", String::empty);
  47261. }
  47262. Label* LookAndFeel::createSliderTextBox (Slider& slider)
  47263. {
  47264. Label* const l = new Label (T("n"), String::empty);
  47265. l->setJustificationType (Justification::centred);
  47266. l->setColour (Label::textColourId, slider.findColour (Slider::textBoxTextColourId));
  47267. l->setColour (Label::backgroundColourId,
  47268. (slider.getSliderStyle() == Slider::LinearBar) ? Colours::transparentBlack
  47269. : slider.findColour (Slider::textBoxBackgroundColourId));
  47270. l->setColour (Label::outlineColourId, slider.findColour (Slider::textBoxOutlineColourId));
  47271. l->setColour (TextEditor::textColourId, slider.findColour (Slider::textBoxTextColourId));
  47272. l->setColour (TextEditor::backgroundColourId,
  47273. slider.findColour (Slider::textBoxBackgroundColourId)
  47274. .withAlpha (slider.getSliderStyle() == Slider::LinearBar ? 0.7f : 1.0f));
  47275. l->setColour (TextEditor::outlineColourId, slider.findColour (Slider::textBoxOutlineColourId));
  47276. return l;
  47277. }
  47278. ImageEffectFilter* LookAndFeel::getSliderEffect()
  47279. {
  47280. return 0;
  47281. }
  47282. static const TextLayout layoutTooltipText (const String& text) throw()
  47283. {
  47284. const float tooltipFontSize = 15.0f;
  47285. const int maxToolTipWidth = 400;
  47286. const Font f (tooltipFontSize, Font::bold);
  47287. TextLayout tl (text, f);
  47288. tl.layout (maxToolTipWidth, Justification::left, true);
  47289. return tl;
  47290. }
  47291. void LookAndFeel::getTooltipSize (const String& tipText, int& width, int& height)
  47292. {
  47293. const TextLayout tl (layoutTooltipText (tipText));
  47294. width = tl.getWidth() + 14;
  47295. height = tl.getHeight() + 10;
  47296. }
  47297. void LookAndFeel::drawTooltip (Graphics& g, const String& text, int width, int height)
  47298. {
  47299. g.fillAll (findColour (TooltipWindow::backgroundColourId));
  47300. const Colour textCol (findColour (TooltipWindow::textColourId));
  47301. g.setColour (findColour (TooltipWindow::outlineColourId));
  47302. g.drawRect (0, 0, width, height);
  47303. const TextLayout tl (layoutTooltipText (text));
  47304. g.setColour (findColour (TooltipWindow::textColourId));
  47305. tl.drawWithin (g, 0, 0, width, height, Justification::centred);
  47306. }
  47307. Button* LookAndFeel::createFilenameComponentBrowseButton (const String& text)
  47308. {
  47309. return new TextButton (text, TRANS("click to browse for a different file"));
  47310. }
  47311. void LookAndFeel::layoutFilenameComponent (FilenameComponent& filenameComp,
  47312. ComboBox* filenameBox,
  47313. Button* browseButton)
  47314. {
  47315. browseButton->setSize (80, filenameComp.getHeight());
  47316. TextButton* const tb = dynamic_cast <TextButton*> (browseButton);
  47317. if (tb != 0)
  47318. tb->changeWidthToFitText();
  47319. browseButton->setTopRightPosition (filenameComp.getWidth(), 0);
  47320. filenameBox->setBounds (0, 0, browseButton->getX(), filenameComp.getHeight());
  47321. }
  47322. void LookAndFeel::drawCornerResizer (Graphics& g,
  47323. int w, int h,
  47324. bool /*isMouseOver*/,
  47325. bool /*isMouseDragging*/)
  47326. {
  47327. const float lineThickness = jmin (w, h) * 0.075f;
  47328. for (float i = 0.0f; i < 1.0f; i += 0.3f)
  47329. {
  47330. g.setColour (Colours::lightgrey);
  47331. g.drawLine (w * i,
  47332. h + 1.0f,
  47333. w + 1.0f,
  47334. h * i,
  47335. lineThickness);
  47336. g.setColour (Colours::darkgrey);
  47337. g.drawLine (w * i + lineThickness,
  47338. h + 1.0f,
  47339. w + 1.0f,
  47340. h * i + lineThickness,
  47341. lineThickness);
  47342. }
  47343. }
  47344. void LookAndFeel::drawResizableFrame (Graphics&, int /*w*/, int /*h*/,
  47345. const BorderSize& /*borders*/)
  47346. {
  47347. }
  47348. void LookAndFeel::drawResizableWindowBorder (Graphics& g, int w, int h,
  47349. const BorderSize& border, ResizableWindow&)
  47350. {
  47351. g.setColour (Colour (0x80000000));
  47352. g.drawRect (0, 0, w, h);
  47353. g.setColour (Colour (0x19000000));
  47354. g.drawRect (border.getLeft() - 1,
  47355. border.getTop() - 1,
  47356. w + 2 - border.getLeftAndRight(),
  47357. h + 2 - border.getTopAndBottom());
  47358. }
  47359. void LookAndFeel::drawDocumentWindowTitleBar (DocumentWindow& window,
  47360. Graphics& g, int w, int h,
  47361. int titleSpaceX, int titleSpaceW,
  47362. const Image* icon,
  47363. bool drawTitleTextOnLeft)
  47364. {
  47365. const bool isActive = window.isActiveWindow();
  47366. GradientBrush gb (window.getBackgroundColour(),
  47367. 0.0f, 0.0f,
  47368. window.getBackgroundColour().contrasting (isActive ? 0.15f : 0.05f),
  47369. 0.0f, (float) h, false);
  47370. g.setBrush (&gb);
  47371. g.fillAll();
  47372. g.setFont (h * 0.65f, Font::bold);
  47373. int textW = g.getCurrentFont().getStringWidth (window.getName());
  47374. int iconW = 0;
  47375. int iconH = 0;
  47376. if (icon != 0)
  47377. {
  47378. iconH = (int) g.getCurrentFont().getHeight();
  47379. iconW = icon->getWidth() * iconH / icon->getHeight() + 4;
  47380. }
  47381. textW = jmin (titleSpaceW, textW + iconW);
  47382. int textX = drawTitleTextOnLeft ? titleSpaceX
  47383. : jmax (titleSpaceX, (w - textW) / 2);
  47384. if (textX + textW > titleSpaceX + titleSpaceW)
  47385. textX = titleSpaceX + titleSpaceW - textW;
  47386. if (icon != 0)
  47387. {
  47388. g.setOpacity (isActive ? 1.0f : 0.6f);
  47389. g.drawImageWithin (icon, textX, (h - iconH) / 2, iconW, iconH,
  47390. RectanglePlacement::centred, false);
  47391. textX += iconW;
  47392. textW -= iconW;
  47393. }
  47394. g.setColour (window.getBackgroundColour().contrasting (isActive ? 0.7f : 0.4f));
  47395. g.drawText (window.getName(), textX, 0, textW, h, Justification::centredLeft, true);
  47396. }
  47397. class GlassWindowButton : public Button
  47398. {
  47399. public:
  47400. GlassWindowButton (const String& name, const Colour& col,
  47401. const Path& normalShape_,
  47402. const Path& toggledShape_) throw()
  47403. : Button (name),
  47404. colour (col),
  47405. normalShape (normalShape_),
  47406. toggledShape (toggledShape_)
  47407. {
  47408. }
  47409. ~GlassWindowButton()
  47410. {
  47411. }
  47412. void paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown)
  47413. {
  47414. float alpha = isMouseOverButton ? (isButtonDown ? 1.0f : 0.8f) : 0.55f;
  47415. if (! isEnabled())
  47416. alpha *= 0.5f;
  47417. float x = 0, y = 0, diam;
  47418. if (getWidth() < getHeight())
  47419. {
  47420. diam = (float) getWidth();
  47421. y = (getHeight() - getWidth()) * 0.5f;
  47422. }
  47423. else
  47424. {
  47425. diam = (float) getHeight();
  47426. y = (getWidth() - getHeight()) * 0.5f;
  47427. }
  47428. x += diam * 0.05f;
  47429. y += diam * 0.05f;
  47430. diam *= 0.9f;
  47431. GradientBrush gb1 (Colour::greyLevel (0.9f).withAlpha (alpha), 0, y + diam,
  47432. Colour::greyLevel (0.6f).withAlpha (alpha), 0, y, false);
  47433. g.setBrush (&gb1);
  47434. g.fillEllipse (x, y, diam, diam);
  47435. x += 2.0f;
  47436. y += 2.0f;
  47437. diam -= 4.0f;
  47438. LookAndFeel::drawGlassSphere (g, x, y, diam, colour.withAlpha (alpha), 1.0f);
  47439. Path& p = getToggleState() ? toggledShape : normalShape;
  47440. const AffineTransform t (p.getTransformToScaleToFit (x + diam * 0.3f, y + diam * 0.3f,
  47441. diam * 0.4f, diam * 0.4f, true));
  47442. g.setColour (Colours::black.withAlpha (alpha * 0.6f));
  47443. g.fillPath (p, t);
  47444. }
  47445. juce_UseDebuggingNewOperator
  47446. private:
  47447. Colour colour;
  47448. Path normalShape, toggledShape;
  47449. GlassWindowButton (const GlassWindowButton&);
  47450. const GlassWindowButton& operator= (const GlassWindowButton&);
  47451. };
  47452. Button* LookAndFeel::createDocumentWindowButton (int buttonType)
  47453. {
  47454. Path shape;
  47455. const float crossThickness = 0.25f;
  47456. if (buttonType == DocumentWindow::closeButton)
  47457. {
  47458. shape.addLineSegment (0.0f, 0.0f, 1.0f, 1.0f, crossThickness * 1.4f);
  47459. shape.addLineSegment (1.0f, 0.0f, 0.0f, 1.0f, crossThickness * 1.4f);
  47460. return new GlassWindowButton ("close", Colour (0xffdd1100), shape, shape);
  47461. }
  47462. else if (buttonType == DocumentWindow::minimiseButton)
  47463. {
  47464. shape.addLineSegment (0.0f, 0.5f, 1.0f, 0.5f, crossThickness);
  47465. return new GlassWindowButton ("minimise", Colour (0xffaa8811), shape, shape);
  47466. }
  47467. else if (buttonType == DocumentWindow::maximiseButton)
  47468. {
  47469. shape.addLineSegment (0.5f, 0.0f, 0.5f, 1.0f, crossThickness);
  47470. shape.addLineSegment (0.0f, 0.5f, 1.0f, 0.5f, crossThickness);
  47471. Path fullscreenShape;
  47472. fullscreenShape.startNewSubPath (45.0f, 100.0f);
  47473. fullscreenShape.lineTo (0.0f, 100.0f);
  47474. fullscreenShape.lineTo (0.0f, 0.0f);
  47475. fullscreenShape.lineTo (100.0f, 0.0f);
  47476. fullscreenShape.lineTo (100.0f, 45.0f);
  47477. fullscreenShape.addRectangle (45.0f, 45.0f, 100.0f, 100.0f);
  47478. PathStrokeType (30.0f).createStrokedPath (fullscreenShape, fullscreenShape);
  47479. return new GlassWindowButton ("maximise", Colour (0xff119911), shape, fullscreenShape);
  47480. }
  47481. jassertfalse
  47482. return 0;
  47483. }
  47484. void LookAndFeel::positionDocumentWindowButtons (DocumentWindow&,
  47485. int titleBarX,
  47486. int titleBarY,
  47487. int titleBarW,
  47488. int titleBarH,
  47489. Button* minimiseButton,
  47490. Button* maximiseButton,
  47491. Button* closeButton,
  47492. bool positionTitleBarButtonsOnLeft)
  47493. {
  47494. const int buttonW = titleBarH - titleBarH / 8;
  47495. int x = positionTitleBarButtonsOnLeft ? titleBarX + 4
  47496. : titleBarX + titleBarW - buttonW - buttonW / 4;
  47497. if (closeButton != 0)
  47498. {
  47499. closeButton->setBounds (x, titleBarY, buttonW, titleBarH);
  47500. x += positionTitleBarButtonsOnLeft ? buttonW : -(buttonW + buttonW / 4);
  47501. }
  47502. if (positionTitleBarButtonsOnLeft)
  47503. swapVariables (minimiseButton, maximiseButton);
  47504. if (maximiseButton != 0)
  47505. {
  47506. maximiseButton->setBounds (x, titleBarY, buttonW, titleBarH);
  47507. x += positionTitleBarButtonsOnLeft ? buttonW : -buttonW;
  47508. }
  47509. if (minimiseButton != 0)
  47510. minimiseButton->setBounds (x, titleBarY, buttonW, titleBarH);
  47511. }
  47512. int LookAndFeel::getDefaultMenuBarHeight()
  47513. {
  47514. return 24;
  47515. }
  47516. DropShadower* LookAndFeel::createDropShadowerForComponent (Component*)
  47517. {
  47518. return new DropShadower (0.4f, 1, 5, 10);
  47519. }
  47520. void LookAndFeel::drawStretchableLayoutResizerBar (Graphics& g,
  47521. int w, int h,
  47522. bool /*isVerticalBar*/,
  47523. bool isMouseOver,
  47524. bool isMouseDragging)
  47525. {
  47526. float alpha = 0.5f;
  47527. if (isMouseOver || isMouseDragging)
  47528. {
  47529. g.fillAll (Colour (0x190000ff));
  47530. alpha = 1.0f;
  47531. }
  47532. const float cx = w * 0.5f;
  47533. const float cy = h * 0.5f;
  47534. const float cr = jmin (w, h) * 0.4f;
  47535. GradientBrush gb (Colours::white.withAlpha (alpha), cx + cr * 0.1f, cy + cr,
  47536. Colours::black.withAlpha (alpha), cx, cy - cr * 4.0f,
  47537. true);
  47538. g.setBrush (&gb);
  47539. g.fillEllipse (cx - cr, cy - cr, cr * 2.0f, cr * 2.0f);
  47540. }
  47541. void LookAndFeel::drawGroupComponentOutline (Graphics& g, int width, int height,
  47542. const String& text,
  47543. const Justification& position,
  47544. GroupComponent& group)
  47545. {
  47546. const float textH = 15.0f;
  47547. const float indent = 3.0f;
  47548. const float textEdgeGap = 4.0f;
  47549. float cs = 5.0f;
  47550. Font f (textH);
  47551. Path p;
  47552. float x = indent;
  47553. float y = f.getAscent() - 3.0f;
  47554. float w = jmax (0.0f, width - x * 2.0f);
  47555. float h = jmax (0.0f, height - y - indent);
  47556. cs = jmin (cs, w * 0.5f, h * 0.5f);
  47557. const float cs2 = 2.0f * cs;
  47558. float textW = text.isEmpty() ? 0 : jlimit (0.0f, jmax (0.0f, w - cs2 - textEdgeGap * 2), f.getStringWidth (text) + textEdgeGap * 2.0f);
  47559. float textX = cs + textEdgeGap;
  47560. if (position.testFlags (Justification::horizontallyCentred))
  47561. textX = cs + (w - cs2 - textW) * 0.5f;
  47562. else if (position.testFlags (Justification::right))
  47563. textX = w - cs - textW - textEdgeGap;
  47564. p.startNewSubPath (x + textX + textW, y);
  47565. p.lineTo (x + w - cs, y);
  47566. p.addArc (x + w - cs2, y, cs2, cs2, 0, float_Pi * 0.5f);
  47567. p.lineTo (x + w, y + h - cs);
  47568. p.addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  47569. p.lineTo (x + cs, y + h);
  47570. p.addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  47571. p.lineTo (x, y + cs);
  47572. p.addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f);
  47573. p.lineTo (x + textX, y);
  47574. const float alpha = group.isEnabled() ? 1.0f : 0.5f;
  47575. g.setColour (group.findColour (GroupComponent::outlineColourId)
  47576. .withMultipliedAlpha (alpha));
  47577. g.strokePath (p, PathStrokeType (2.0f));
  47578. g.setColour (group.findColour (GroupComponent::textColourId)
  47579. .withMultipliedAlpha (alpha));
  47580. g.setFont (f);
  47581. g.drawText (text,
  47582. roundFloatToInt (x + textX), 0,
  47583. roundFloatToInt (textW),
  47584. roundFloatToInt (textH),
  47585. Justification::centred, true);
  47586. }
  47587. int LookAndFeel::getTabButtonOverlap (int tabDepth)
  47588. {
  47589. return 1 + tabDepth / 3;
  47590. }
  47591. int LookAndFeel::getTabButtonSpaceAroundImage()
  47592. {
  47593. return 4;
  47594. }
  47595. void LookAndFeel::createTabButtonShape (Path& p,
  47596. int width, int height,
  47597. int /*tabIndex*/,
  47598. const String& /*text*/,
  47599. Button& /*button*/,
  47600. TabbedButtonBar::Orientation orientation,
  47601. const bool /*isMouseOver*/,
  47602. const bool /*isMouseDown*/,
  47603. const bool /*isFrontTab*/)
  47604. {
  47605. const float w = (float) width;
  47606. const float h = (float) height;
  47607. float length = w;
  47608. float depth = h;
  47609. if (orientation == TabbedButtonBar::TabsAtLeft
  47610. || orientation == TabbedButtonBar::TabsAtRight)
  47611. {
  47612. swapVariables (length, depth);
  47613. }
  47614. const float indent = (float) getTabButtonOverlap ((int) depth);
  47615. const float overhang = 4.0f;
  47616. if (orientation == TabbedButtonBar::TabsAtLeft)
  47617. {
  47618. p.startNewSubPath (w, 0.0f);
  47619. p.lineTo (0.0f, indent);
  47620. p.lineTo (0.0f, h - indent);
  47621. p.lineTo (w, h);
  47622. p.lineTo (w + overhang, h + overhang);
  47623. p.lineTo (w + overhang, -overhang);
  47624. }
  47625. else if (orientation == TabbedButtonBar::TabsAtRight)
  47626. {
  47627. p.startNewSubPath (0.0f, 0.0f);
  47628. p.lineTo (w, indent);
  47629. p.lineTo (w, h - indent);
  47630. p.lineTo (0.0f, h);
  47631. p.lineTo (-overhang, h + overhang);
  47632. p.lineTo (-overhang, -overhang);
  47633. }
  47634. else if (orientation == TabbedButtonBar::TabsAtBottom)
  47635. {
  47636. p.startNewSubPath (0.0f, 0.0f);
  47637. p.lineTo (indent, h);
  47638. p.lineTo (w - indent, h);
  47639. p.lineTo (w, 0.0f);
  47640. p.lineTo (w + overhang, -overhang);
  47641. p.lineTo (-overhang, -overhang);
  47642. }
  47643. else
  47644. {
  47645. p.startNewSubPath (0.0f, h);
  47646. p.lineTo (indent, 0.0f);
  47647. p.lineTo (w - indent, 0.0f);
  47648. p.lineTo (w, h);
  47649. p.lineTo (w + overhang, h + overhang);
  47650. p.lineTo (-overhang, h + overhang);
  47651. }
  47652. p.closeSubPath();
  47653. p = p.createPathWithRoundedCorners (3.0f);
  47654. }
  47655. void LookAndFeel::fillTabButtonShape (Graphics& g,
  47656. const Path& path,
  47657. const Colour& preferredColour,
  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. g.setColour (isFrontTab ? preferredColour
  47667. : preferredColour.withMultipliedAlpha (0.9f));
  47668. g.fillPath (path);
  47669. g.setColour (Colours::black.withAlpha (button.isEnabled() ? 0.5f : 0.25f));
  47670. g.strokePath (path, PathStrokeType (isFrontTab ? 1.0f : 0.5f));
  47671. }
  47672. void LookAndFeel::drawTabButtonText (Graphics& g,
  47673. int x, int y, int w, int h,
  47674. const Colour& preferredBackgroundColour,
  47675. int /*tabIndex*/,
  47676. const String& text,
  47677. Button& button,
  47678. TabbedButtonBar::Orientation orientation,
  47679. const bool isMouseOver,
  47680. const bool isMouseDown,
  47681. const bool /*isFrontTab*/)
  47682. {
  47683. int length = w;
  47684. int depth = h;
  47685. if (orientation == TabbedButtonBar::TabsAtLeft
  47686. || orientation == TabbedButtonBar::TabsAtRight)
  47687. {
  47688. swapVariables (length, depth);
  47689. }
  47690. Font font (depth * 0.6f);
  47691. font.setUnderline (button.hasKeyboardFocus (false));
  47692. GlyphArrangement textLayout;
  47693. textLayout.addFittedText (font, text.trim(),
  47694. 0.0f, 0.0f, (float) length, (float) depth,
  47695. Justification::centred,
  47696. jmax (1, depth / 12));
  47697. AffineTransform transform;
  47698. if (orientation == TabbedButtonBar::TabsAtLeft)
  47699. {
  47700. transform = transform.rotated (float_Pi * -0.5f)
  47701. .translated ((float) x, (float) (y + h));
  47702. }
  47703. else if (orientation == TabbedButtonBar::TabsAtRight)
  47704. {
  47705. transform = transform.rotated (float_Pi * 0.5f)
  47706. .translated ((float) (x + w), (float) y);
  47707. }
  47708. else
  47709. {
  47710. transform = transform.translated ((float) x, (float) y);
  47711. }
  47712. g.setColour (preferredBackgroundColour.contrasting());
  47713. if (! (isMouseOver || isMouseDown))
  47714. g.setOpacity (0.8f);
  47715. if (! button.isEnabled())
  47716. g.setOpacity (0.3f);
  47717. textLayout.draw (g, transform);
  47718. }
  47719. int LookAndFeel::getTabButtonBestWidth (int /*tabIndex*/,
  47720. const String& text,
  47721. int tabDepth,
  47722. Button&)
  47723. {
  47724. Font f (tabDepth * 0.6f);
  47725. return f.getStringWidth (text.trim()) + getTabButtonOverlap (tabDepth) * 2;
  47726. }
  47727. void LookAndFeel::drawTabButton (Graphics& g,
  47728. int w, int h,
  47729. const Colour& preferredColour,
  47730. int tabIndex,
  47731. const String& text,
  47732. Button& button,
  47733. TabbedButtonBar::Orientation orientation,
  47734. const bool isMouseOver,
  47735. const bool isMouseDown,
  47736. const bool isFrontTab)
  47737. {
  47738. int length = w;
  47739. int depth = h;
  47740. if (orientation == TabbedButtonBar::TabsAtLeft
  47741. || orientation == TabbedButtonBar::TabsAtRight)
  47742. {
  47743. swapVariables (length, depth);
  47744. }
  47745. Path tabShape;
  47746. createTabButtonShape (tabShape, w, h,
  47747. tabIndex, text, button, orientation,
  47748. isMouseOver, isMouseDown, isFrontTab);
  47749. fillTabButtonShape (g, tabShape, preferredColour,
  47750. tabIndex, text, button, orientation,
  47751. isMouseOver, isMouseDown, isFrontTab);
  47752. const int indent = getTabButtonOverlap (depth);
  47753. int x = 0, y = 0;
  47754. if (orientation == TabbedButtonBar::TabsAtLeft
  47755. || orientation == TabbedButtonBar::TabsAtRight)
  47756. {
  47757. y += indent;
  47758. h -= indent * 2;
  47759. }
  47760. else
  47761. {
  47762. x += indent;
  47763. w -= indent * 2;
  47764. }
  47765. drawTabButtonText (g, x, y, w, h, preferredColour,
  47766. tabIndex, text, button, orientation,
  47767. isMouseOver, isMouseDown, isFrontTab);
  47768. }
  47769. void LookAndFeel::drawTabAreaBehindFrontButton (Graphics& g,
  47770. int w, int h,
  47771. TabbedButtonBar& tabBar,
  47772. TabbedButtonBar::Orientation orientation)
  47773. {
  47774. const float shadowSize = 0.2f;
  47775. float x1 = 0.0f, y1 = 0.0f, x2 = 0.0f, y2 = 0.0f;
  47776. Rectangle shadowRect;
  47777. if (orientation == TabbedButtonBar::TabsAtLeft)
  47778. {
  47779. x1 = (float) w;
  47780. x2 = w * (1.0f - shadowSize);
  47781. shadowRect.setBounds ((int) x2, 0, w - (int) x2, h);
  47782. }
  47783. else if (orientation == TabbedButtonBar::TabsAtRight)
  47784. {
  47785. x2 = w * shadowSize;
  47786. shadowRect.setBounds (0, 0, (int) x2, h);
  47787. }
  47788. else if (orientation == TabbedButtonBar::TabsAtBottom)
  47789. {
  47790. y2 = h * shadowSize;
  47791. shadowRect.setBounds (0, 0, w, (int) y2);
  47792. }
  47793. else
  47794. {
  47795. y1 = (float) h;
  47796. y2 = h * (1.0f - shadowSize);
  47797. shadowRect.setBounds (0, (int) y2, w, h - (int) y2);
  47798. }
  47799. GradientBrush gb (Colours::black.withAlpha (tabBar.isEnabled() ? 0.3f : 0.15f), x1, y1,
  47800. Colours::transparentBlack, x2, y2,
  47801. false);
  47802. g.setBrush (&gb);
  47803. shadowRect.expand (2, 2);
  47804. g.fillRect (shadowRect);
  47805. g.setColour (Colour (0x80000000));
  47806. if (orientation == TabbedButtonBar::TabsAtLeft)
  47807. {
  47808. g.fillRect (w - 1, 0, 1, h);
  47809. }
  47810. else if (orientation == TabbedButtonBar::TabsAtRight)
  47811. {
  47812. g.fillRect (0, 0, 1, h);
  47813. }
  47814. else if (orientation == TabbedButtonBar::TabsAtBottom)
  47815. {
  47816. g.fillRect (0, 0, w, 1);
  47817. }
  47818. else
  47819. {
  47820. g.fillRect (0, h - 1, w, 1);
  47821. }
  47822. }
  47823. Button* LookAndFeel::createTabBarExtrasButton()
  47824. {
  47825. const float thickness = 7.0f;
  47826. const float indent = 22.0f;
  47827. Path p;
  47828. p.addEllipse (-10.0f, -10.0f, 120.0f, 120.0f);
  47829. DrawablePath ellipse;
  47830. ellipse.setPath (p);
  47831. ellipse.setSolidFill (Colour (0x99ffffff));
  47832. p.clear();
  47833. p.addEllipse (0.0f, 0.0f, 100.0f, 100.0f);
  47834. p.addRectangle (indent, 50.0f - thickness, 100.0f - indent * 2.0f, thickness * 2.0f);
  47835. p.addRectangle (50.0f - thickness, indent, thickness * 2.0f, 50.0f - indent - thickness);
  47836. p.addRectangle (50.0f - thickness, 50.0f + thickness, thickness * 2.0f, 50.0f - indent - thickness);
  47837. p.setUsingNonZeroWinding (false);
  47838. DrawablePath dp;
  47839. dp.setPath (p);
  47840. dp.setSolidFill (Colour (0x59000000));
  47841. DrawableComposite normalImage;
  47842. normalImage.insertDrawable (ellipse);
  47843. normalImage.insertDrawable (dp);
  47844. dp.setSolidFill (Colour (0xcc000000));
  47845. DrawableComposite overImage;
  47846. overImage.insertDrawable (ellipse);
  47847. overImage.insertDrawable (dp);
  47848. DrawableButton* db = new DrawableButton (T("tabs"), DrawableButton::ImageFitted);
  47849. db->setImages (&normalImage, &overImage, 0);
  47850. return db;
  47851. }
  47852. void LookAndFeel::drawTableHeaderBackground (Graphics& g, TableHeaderComponent& header)
  47853. {
  47854. g.fillAll (Colours::white);
  47855. const int w = header.getWidth();
  47856. const int h = header.getHeight();
  47857. GradientBrush gb (Colour (0xffe8ebf9), 0.0f, h * 0.5f,
  47858. Colour (0xfff6f8f9), 0.0f, h - 1.0f,
  47859. false);
  47860. g.setBrush (&gb);
  47861. g.fillRect (0, h / 2, w, h);
  47862. g.setColour (Colour (0x33000000));
  47863. g.fillRect (0, h - 1, w, 1);
  47864. for (int i = header.getNumColumns (true); --i >= 0;)
  47865. g.fillRect (header.getColumnPosition (i).getRight() - 1, 0, 1, h - 1);
  47866. }
  47867. void LookAndFeel::drawTableHeaderColumn (Graphics& g, const String& columnName, int /*columnId*/,
  47868. int width, int height,
  47869. bool isMouseOver, bool isMouseDown,
  47870. int columnFlags)
  47871. {
  47872. if (isMouseDown)
  47873. g.fillAll (Colour (0x8899aadd));
  47874. else if (isMouseOver)
  47875. g.fillAll (Colour (0x5599aadd));
  47876. int rightOfText = width - 4;
  47877. if ((columnFlags & (TableHeaderComponent::sortedForwards | TableHeaderComponent::sortedBackwards)) != 0)
  47878. {
  47879. const float top = height * ((columnFlags & TableHeaderComponent::sortedForwards) != 0 ? 0.35f : (1.0f - 0.35f));
  47880. const float bottom = height - top;
  47881. const float w = height * 0.5f;
  47882. const float x = rightOfText - (w * 1.25f);
  47883. rightOfText = (int) x;
  47884. Path sortArrow;
  47885. sortArrow.addTriangle (x, bottom, x + w * 0.5f, top, x + w, bottom);
  47886. g.setColour (Colour (0x99000000));
  47887. g.fillPath (sortArrow);
  47888. }
  47889. g.setColour (Colours::black);
  47890. g.setFont (height * 0.5f, Font::bold);
  47891. const int textX = 4;
  47892. g.drawFittedText (columnName, textX, 0, rightOfText - textX, height, Justification::centredLeft, 1);
  47893. }
  47894. void LookAndFeel::paintToolbarBackground (Graphics& g, int w, int h, Toolbar& toolbar)
  47895. {
  47896. const Colour background (toolbar.findColour (Toolbar::backgroundColourId));
  47897. GradientBrush gb (background, 0.0f, 0.0f,
  47898. background.darker (0.1f),
  47899. toolbar.isVertical() ? w - 1.0f : 0.0f,
  47900. toolbar.isVertical() ? 0.0f : h - 1.0f,
  47901. false);
  47902. g.setBrush (&gb);
  47903. g.fillAll();
  47904. }
  47905. Button* LookAndFeel::createToolbarMissingItemsButton (Toolbar& /*toolbar*/)
  47906. {
  47907. return createTabBarExtrasButton();
  47908. }
  47909. void LookAndFeel::paintToolbarButtonBackground (Graphics& g, int /*width*/, int /*height*/,
  47910. bool isMouseOver, bool isMouseDown,
  47911. ToolbarItemComponent& component)
  47912. {
  47913. if (isMouseDown)
  47914. g.fillAll (component.findColour (Toolbar::buttonMouseDownBackgroundColourId, true));
  47915. else if (isMouseOver)
  47916. g.fillAll (component.findColour (Toolbar::buttonMouseOverBackgroundColourId, true));
  47917. }
  47918. void LookAndFeel::paintToolbarButtonLabel (Graphics& g, int x, int y, int width, int height,
  47919. const String& text, ToolbarItemComponent& component)
  47920. {
  47921. g.setColour (component.findColour (Toolbar::labelTextColourId, true)
  47922. .withAlpha (component.isEnabled() ? 1.0f : 0.25f));
  47923. const float fontHeight = jmin (14.0f, height * 0.85f);
  47924. g.setFont (fontHeight);
  47925. g.drawFittedText (text,
  47926. x, y, width, height,
  47927. Justification::centred,
  47928. jmax (1, height / (int) fontHeight));
  47929. }
  47930. void LookAndFeel::drawPropertyPanelSectionHeader (Graphics& g, const String& name,
  47931. bool isOpen, int width, int height)
  47932. {
  47933. const int buttonSize = (height * 3) / 4;
  47934. const int buttonIndent = (height - buttonSize) / 2;
  47935. drawTreeviewPlusMinusBox (g, buttonIndent, buttonIndent, buttonSize, buttonSize, ! isOpen);
  47936. const int textX = buttonIndent * 2 + buttonSize + 2;
  47937. g.setColour (Colours::black);
  47938. g.setFont (height * 0.7f, Font::bold);
  47939. g.drawText (name, textX, 0, width - textX - 4, height, Justification::centredLeft, true);
  47940. }
  47941. void LookAndFeel::drawPropertyComponentBackground (Graphics& g, int width, int height,
  47942. PropertyComponent&)
  47943. {
  47944. g.setColour (Colour (0x66ffffff));
  47945. g.fillRect (0, 0, width, height - 1);
  47946. }
  47947. void LookAndFeel::drawPropertyComponentLabel (Graphics& g, int, int height,
  47948. PropertyComponent& component)
  47949. {
  47950. g.setColour (Colours::black);
  47951. if (! component.isEnabled())
  47952. g.setOpacity (g.getCurrentColour().getAlpha() * 0.6f);
  47953. g.setFont (jmin (height, 24) * 0.65f);
  47954. const Rectangle r (getPropertyComponentContentPosition (component));
  47955. g.drawFittedText (component.getName(),
  47956. 3, r.getY(), r.getX() - 5, r.getHeight(),
  47957. Justification::centredLeft, 2);
  47958. }
  47959. const Rectangle LookAndFeel::getPropertyComponentContentPosition (PropertyComponent& component)
  47960. {
  47961. return Rectangle (component.getWidth() / 3, 1,
  47962. component.getWidth() - component.getWidth() / 3 - 1, component.getHeight() - 3);
  47963. }
  47964. void LookAndFeel::createFileChooserHeaderText (const String& title,
  47965. const String& instructions,
  47966. GlyphArrangement& text,
  47967. int width)
  47968. {
  47969. text.clear();
  47970. text.addJustifiedText (Font (17.0f, Font::bold), title,
  47971. 8.0f, 22.0f, width - 16.0f,
  47972. Justification::centred);
  47973. text.addJustifiedText (Font (14.0f), instructions,
  47974. 8.0f, 24.0f + 16.0f, width - 16.0f,
  47975. Justification::centred);
  47976. }
  47977. void LookAndFeel::drawFileBrowserRow (Graphics& g, int width, int height,
  47978. const String& filename, Image* icon,
  47979. const String& fileSizeDescription,
  47980. const String& fileTimeDescription,
  47981. const bool isDirectory,
  47982. const bool isItemSelected,
  47983. const int /*itemIndex*/)
  47984. {
  47985. if (isItemSelected)
  47986. g.fillAll (findColour (DirectoryContentsDisplayComponent::highlightColourId));
  47987. g.setColour (findColour (DirectoryContentsDisplayComponent::textColourId));
  47988. g.setFont (height * 0.7f);
  47989. Image* im = icon;
  47990. Image* toRelease = 0;
  47991. if (im == 0)
  47992. {
  47993. toRelease = im = (isDirectory ? getDefaultFolderImage()
  47994. : getDefaultDocumentFileImage());
  47995. }
  47996. const int x = 32;
  47997. if (im != 0)
  47998. {
  47999. g.drawImageWithin (im, 2, 2, x - 4, height - 4,
  48000. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize,
  48001. false);
  48002. ImageCache::release (toRelease);
  48003. }
  48004. if (width > 450 && ! isDirectory)
  48005. {
  48006. const int sizeX = roundFloatToInt (width * 0.7f);
  48007. const int dateX = roundFloatToInt (width * 0.8f);
  48008. g.drawFittedText (filename,
  48009. x, 0, sizeX - x, height,
  48010. Justification::centredLeft, 1);
  48011. g.setFont (height * 0.5f);
  48012. g.setColour (Colours::darkgrey);
  48013. if (! isDirectory)
  48014. {
  48015. g.drawFittedText (fileSizeDescription,
  48016. sizeX, 0, dateX - sizeX - 8, height,
  48017. Justification::centredRight, 1);
  48018. g.drawFittedText (fileTimeDescription,
  48019. dateX, 0, width - 8 - dateX, height,
  48020. Justification::centredRight, 1);
  48021. }
  48022. }
  48023. else
  48024. {
  48025. g.drawFittedText (filename,
  48026. x, 0, width - x, height,
  48027. Justification::centredLeft, 1);
  48028. }
  48029. }
  48030. Button* LookAndFeel::createFileBrowserGoUpButton()
  48031. {
  48032. DrawableButton* goUpButton = new DrawableButton ("up", DrawableButton::ImageOnButtonBackground);
  48033. Path arrowPath;
  48034. arrowPath.addArrow (50.0f, 100.0f, 50.0f, 0.0, 40.0f, 100.0f, 50.0f);
  48035. DrawablePath arrowImage;
  48036. arrowImage.setSolidFill (Colours::black.withAlpha (0.4f));
  48037. arrowImage.setPath (arrowPath);
  48038. goUpButton->setImages (&arrowImage);
  48039. return goUpButton;
  48040. }
  48041. void LookAndFeel::layoutFileBrowserComponent (FileBrowserComponent& browserComp,
  48042. DirectoryContentsDisplayComponent* fileListComponent,
  48043. FilePreviewComponent* previewComp,
  48044. ComboBox* currentPathBox,
  48045. TextEditor* filenameBox,
  48046. Button* goUpButton)
  48047. {
  48048. const int x = 8;
  48049. int w = browserComp.getWidth() - x - x;
  48050. if (previewComp != 0)
  48051. {
  48052. const int previewWidth = w / 3;
  48053. previewComp->setBounds (x + w - previewWidth, 0, previewWidth, browserComp.getHeight());
  48054. w -= previewWidth + 4;
  48055. }
  48056. int y = 4;
  48057. const int controlsHeight = 22;
  48058. const int bottomSectionHeight = controlsHeight + 8;
  48059. const int upButtonWidth = 50;
  48060. currentPathBox->setBounds (x, y, w - upButtonWidth - 6, controlsHeight);
  48061. goUpButton->setBounds (x + w - upButtonWidth, y, upButtonWidth, controlsHeight);
  48062. y += controlsHeight + 4;
  48063. Component* const listAsComp = dynamic_cast <Component*> (fileListComponent);
  48064. listAsComp->setBounds (x, y, w, browserComp.getHeight() - y - bottomSectionHeight);
  48065. y = listAsComp->getBottom() + 4;
  48066. filenameBox->setBounds (x + 50, y, w - 50, controlsHeight);
  48067. }
  48068. Image* LookAndFeel::getDefaultFolderImage()
  48069. {
  48070. 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,
  48071. 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,
  48072. 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,
  48073. 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,
  48074. 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,
  48075. 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,
  48076. 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,
  48077. 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,
  48078. 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,
  48079. 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,
  48080. 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,
  48081. 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,
  48082. 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,
  48083. 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,
  48084. 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,
  48085. 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,
  48086. 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,
  48087. 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,
  48088. 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,
  48089. 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,
  48090. 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,
  48091. 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,
  48092. 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,
  48093. 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,
  48094. 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,
  48095. 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,
  48096. 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,
  48097. 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,
  48098. 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,
  48099. 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,
  48100. 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,
  48101. 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,
  48102. 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,
  48103. 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,
  48104. 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,
  48105. 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,
  48106. 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,
  48107. 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,
  48108. 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,
  48109. 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,
  48110. 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,
  48111. 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,
  48112. 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,
  48113. 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};
  48114. return ImageCache::getFromMemory (foldericon_png, sizeof (foldericon_png));
  48115. }
  48116. Image* LookAndFeel::getDefaultDocumentFileImage()
  48117. {
  48118. 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,
  48119. 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,
  48120. 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,
  48121. 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,
  48122. 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,
  48123. 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,
  48124. 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,
  48125. 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,
  48126. 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,
  48127. 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,
  48128. 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,
  48129. 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,
  48130. 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,
  48131. 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,
  48132. 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,
  48133. 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,
  48134. 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,
  48135. 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,
  48136. 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,
  48137. 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,
  48138. 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,
  48139. 174,66,96,130,0,0};
  48140. return ImageCache::getFromMemory (fileicon_png, sizeof (fileicon_png));
  48141. }
  48142. void LookAndFeel::playAlertSound()
  48143. {
  48144. PlatformUtilities::beep();
  48145. }
  48146. static void createRoundedPath (Path& p,
  48147. const float x, const float y,
  48148. const float w, const float h,
  48149. const float cs,
  48150. const bool curveTopLeft, const bool curveTopRight,
  48151. const bool curveBottomLeft, const bool curveBottomRight) throw()
  48152. {
  48153. const float cs2 = 2.0f * cs;
  48154. if (curveTopLeft)
  48155. {
  48156. p.startNewSubPath (x, y + cs);
  48157. p.addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f);
  48158. }
  48159. else
  48160. {
  48161. p.startNewSubPath (x, y);
  48162. }
  48163. if (curveTopRight)
  48164. {
  48165. p.lineTo (x + w - cs, y);
  48166. p.addArc (x + w - cs2, y, cs2, cs2, 0.0f, float_Pi * 0.5f);
  48167. }
  48168. else
  48169. {
  48170. p.lineTo (x + w, y);
  48171. }
  48172. if (curveBottomRight)
  48173. {
  48174. p.lineTo (x + w, y + h - cs);
  48175. p.addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  48176. }
  48177. else
  48178. {
  48179. p.lineTo (x + w, y + h);
  48180. }
  48181. if (curveBottomLeft)
  48182. {
  48183. p.lineTo (x + cs, y + h);
  48184. p.addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  48185. }
  48186. else
  48187. {
  48188. p.lineTo (x, y + h);
  48189. }
  48190. p.closeSubPath();
  48191. }
  48192. void LookAndFeel::drawShinyButtonShape (Graphics& g,
  48193. float x, float y, float w, float h,
  48194. float maxCornerSize,
  48195. const Colour& baseColour,
  48196. const float strokeWidth,
  48197. const bool flatOnLeft,
  48198. const bool flatOnRight,
  48199. const bool flatOnTop,
  48200. const bool flatOnBottom) throw()
  48201. {
  48202. if (w <= strokeWidth * 1.1f || h <= strokeWidth * 1.1f)
  48203. return;
  48204. const float cs = jmin (maxCornerSize, w * 0.5f, h * 0.5f);
  48205. Path outline;
  48206. createRoundedPath (outline, x, y, w, h, cs,
  48207. ! (flatOnLeft || flatOnTop),
  48208. ! (flatOnRight || flatOnTop),
  48209. ! (flatOnLeft || flatOnBottom),
  48210. ! (flatOnRight || flatOnBottom));
  48211. ColourGradient cg (baseColour, 0.0f, y,
  48212. baseColour.overlaidWith (Colour (0x070000ff)), 0.0f, y + h,
  48213. false);
  48214. cg.addColour (0.5, baseColour.overlaidWith (Colour (0x33ffffff)));
  48215. cg.addColour (0.51, baseColour.overlaidWith (Colour (0x110000ff)));
  48216. GradientBrush gb (cg);
  48217. g.setBrush (&gb);
  48218. g.fillPath (outline);
  48219. g.setColour (Colour (0x80000000));
  48220. g.strokePath (outline, PathStrokeType (strokeWidth));
  48221. }
  48222. void LookAndFeel::drawGlassSphere (Graphics& g,
  48223. const float x, const float y,
  48224. const float diameter,
  48225. const Colour& colour,
  48226. const float outlineThickness) throw()
  48227. {
  48228. if (diameter <= outlineThickness)
  48229. return;
  48230. Path p;
  48231. p.addEllipse (x, y, diameter, diameter);
  48232. {
  48233. ColourGradient cg (Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y,
  48234. Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y + diameter, false);
  48235. cg.addColour (0.4, Colours::white.overlaidWith (colour));
  48236. GradientBrush gb (cg);
  48237. g.setBrush (&gb);
  48238. g.fillPath (p);
  48239. }
  48240. {
  48241. GradientBrush gb (Colours::white, 0, y + diameter * 0.06f,
  48242. Colours::transparentWhite, 0, y + diameter * 0.3f, false);
  48243. g.setBrush (&gb);
  48244. g.fillEllipse (x + diameter * 0.2f, y + diameter * 0.05f, diameter * 0.6f, diameter * 0.4f);
  48245. }
  48246. {
  48247. ColourGradient cg (Colours::transparentBlack,
  48248. x + diameter * 0.5f, y + diameter * 0.5f,
  48249. Colours::black.withAlpha (0.5f * outlineThickness * colour.getFloatAlpha()),
  48250. x, y + diameter * 0.5f, true);
  48251. cg.addColour (0.7, Colours::transparentBlack);
  48252. cg.addColour (0.8, Colours::black.withAlpha (0.1f * outlineThickness));
  48253. GradientBrush gb (cg);
  48254. g.setBrush (&gb);
  48255. g.fillPath (p);
  48256. }
  48257. g.setColour (Colours::black.withAlpha (0.5f * colour.getFloatAlpha()));
  48258. g.drawEllipse (x, y, diameter, diameter, outlineThickness);
  48259. }
  48260. void LookAndFeel::drawGlassPointer (Graphics& g,
  48261. const float x, const float y,
  48262. const float diameter,
  48263. const Colour& colour, const float outlineThickness,
  48264. const int direction) throw()
  48265. {
  48266. if (diameter <= outlineThickness)
  48267. return;
  48268. Path p;
  48269. p.startNewSubPath (x + diameter * 0.5f, y);
  48270. p.lineTo (x + diameter, y + diameter * 0.6f);
  48271. p.lineTo (x + diameter, y + diameter);
  48272. p.lineTo (x, y + diameter);
  48273. p.lineTo (x, y + diameter * 0.6f);
  48274. p.closeSubPath();
  48275. p.applyTransform (AffineTransform::rotation (direction * (float_Pi * 0.5f), x + diameter * 0.5f, y + diameter * 0.5f));
  48276. {
  48277. ColourGradient cg (Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y,
  48278. Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y + diameter, false);
  48279. cg.addColour (0.4, Colours::white.overlaidWith (colour));
  48280. GradientBrush gb (cg);
  48281. g.setBrush (&gb);
  48282. g.fillPath (p);
  48283. }
  48284. {
  48285. ColourGradient cg (Colours::transparentBlack,
  48286. x + diameter * 0.5f, y + diameter * 0.5f,
  48287. Colours::black.withAlpha (0.5f * outlineThickness * colour.getFloatAlpha()),
  48288. x - diameter * 0.2f, y + diameter * 0.5f, true);
  48289. cg.addColour (0.5, Colours::transparentBlack);
  48290. cg.addColour (0.7, Colours::black.withAlpha (0.07f * outlineThickness));
  48291. GradientBrush gb (cg);
  48292. g.setBrush (&gb);
  48293. g.fillPath (p);
  48294. }
  48295. g.setColour (Colours::black.withAlpha (0.5f * colour.getFloatAlpha()));
  48296. g.strokePath (p, PathStrokeType (outlineThickness));
  48297. }
  48298. void LookAndFeel::drawGlassLozenge (Graphics& g,
  48299. const float x, const float y,
  48300. const float width, const float height,
  48301. const Colour& colour,
  48302. const float outlineThickness,
  48303. const float cornerSize,
  48304. const bool flatOnLeft,
  48305. const bool flatOnRight,
  48306. const bool flatOnTop,
  48307. const bool flatOnBottom) throw()
  48308. {
  48309. if (width <= outlineThickness || height <= outlineThickness)
  48310. return;
  48311. const int intX = (int) x;
  48312. const int intY = (int) y;
  48313. const int intW = (int) width;
  48314. const int intH = (int) height;
  48315. const float cs = cornerSize < 0 ? jmin (width * 0.5f, height * 0.5f) : cornerSize;
  48316. const float edgeBlurRadius = height * 0.75f + (height - cs * 2.0f);
  48317. const int intEdge = (int) edgeBlurRadius;
  48318. Path outline;
  48319. createRoundedPath (outline, x, y, width, height, cs,
  48320. ! (flatOnLeft || flatOnTop),
  48321. ! (flatOnRight || flatOnTop),
  48322. ! (flatOnLeft || flatOnBottom),
  48323. ! (flatOnRight || flatOnBottom));
  48324. {
  48325. ColourGradient cg (colour.darker (0.2f), 0, y,
  48326. colour.darker (0.2f), 0, y + height, false);
  48327. cg.addColour (0.03, colour.withMultipliedAlpha (0.3f));
  48328. cg.addColour (0.4, colour);
  48329. cg.addColour (0.97, colour.withMultipliedAlpha (0.3f));
  48330. GradientBrush gb (cg);
  48331. g.setBrush (&gb);
  48332. g.fillPath (outline);
  48333. }
  48334. ColourGradient cg (Colours::transparentBlack, x + edgeBlurRadius, y + height * 0.5f,
  48335. colour.darker (0.2f), x, y + height * 0.5f, true);
  48336. cg.addColour (jlimit (0.0, 1.0, 1.0 - (cs * 0.5f) / edgeBlurRadius), Colours::transparentBlack);
  48337. cg.addColour (jlimit (0.0, 1.0, 1.0 - (cs * 0.25f) / edgeBlurRadius), colour.darker (0.2f).withMultipliedAlpha (0.3f));
  48338. if (! (flatOnLeft || flatOnTop || flatOnBottom))
  48339. {
  48340. GradientBrush gb (cg);
  48341. g.saveState();
  48342. g.setBrush (&gb);
  48343. g.reduceClipRegion (intX, intY, intEdge, intH);
  48344. g.fillPath (outline);
  48345. g.restoreState();
  48346. }
  48347. if (! (flatOnRight || flatOnTop || flatOnBottom))
  48348. {
  48349. cg.x1 = x + width - edgeBlurRadius;
  48350. cg.x2 = x + width;
  48351. GradientBrush gb (cg);
  48352. g.saveState();
  48353. g.setBrush (&gb);
  48354. g.reduceClipRegion (intX + intW - intEdge, intY, 2 + intEdge, intH);
  48355. g.fillPath (outline);
  48356. g.restoreState();
  48357. }
  48358. {
  48359. const float leftIndent = flatOnLeft ? 0.0f : cs * 0.4f;
  48360. const float rightIndent = flatOnRight ? 0.0f : cs * 0.4f;
  48361. Path highlight;
  48362. createRoundedPath (highlight,
  48363. x + leftIndent,
  48364. y + cs * 0.1f,
  48365. width - (leftIndent + rightIndent),
  48366. height * 0.4f, cs * 0.4f,
  48367. ! (flatOnLeft || flatOnTop),
  48368. ! (flatOnRight || flatOnTop),
  48369. ! (flatOnLeft || flatOnBottom),
  48370. ! (flatOnRight || flatOnBottom));
  48371. GradientBrush gb (colour.brighter (10.0f), 0, y + height * 0.06f,
  48372. Colours::transparentWhite, 0, y + height * 0.4f, false);
  48373. g.setBrush (&gb);
  48374. g.fillPath (highlight);
  48375. }
  48376. g.setColour (colour.darker().withMultipliedAlpha (1.5f));
  48377. g.strokePath (outline, PathStrokeType (outlineThickness));
  48378. }
  48379. END_JUCE_NAMESPACE
  48380. /********* End of inlined file: juce_LookAndFeel.cpp *********/
  48381. /********* Start of inlined file: juce_OldSchoolLookAndFeel.cpp *********/
  48382. BEGIN_JUCE_NAMESPACE
  48383. OldSchoolLookAndFeel::OldSchoolLookAndFeel()
  48384. {
  48385. setColour (TextButton::buttonColourId, Colour (0xffbbbbff));
  48386. setColour (ListBox::outlineColourId, findColour (ComboBox::outlineColourId));
  48387. setColour (ScrollBar::thumbColourId, Colour (0xffbbbbdd));
  48388. setColour (ScrollBar::backgroundColourId, Colours::transparentBlack);
  48389. setColour (Slider::thumbColourId, Colours::white);
  48390. setColour (Slider::trackColourId, Colour (0x7f000000));
  48391. setColour (Slider::textBoxOutlineColourId, Colours::grey);
  48392. setColour (ProgressBar::backgroundColourId, Colours::white.withAlpha (0.6f));
  48393. setColour (ProgressBar::foregroundColourId, Colours::green.withAlpha (0.7f));
  48394. setColour (PopupMenu::backgroundColourId, Colour (0xffeef5f8));
  48395. setColour (PopupMenu::highlightedBackgroundColourId, Colour (0xbfa4c2ce));
  48396. setColour (PopupMenu::highlightedTextColourId, Colours::black);
  48397. setColour (TextEditor::focusedOutlineColourId, findColour (TextButton::buttonColourId));
  48398. scrollbarShadow.setShadowProperties (2.2f, 0.5f, 0, 0);
  48399. }
  48400. OldSchoolLookAndFeel::~OldSchoolLookAndFeel()
  48401. {
  48402. }
  48403. void OldSchoolLookAndFeel::drawButtonBackground (Graphics& g,
  48404. Button& button,
  48405. const Colour& backgroundColour,
  48406. bool isMouseOverButton,
  48407. bool isButtonDown)
  48408. {
  48409. const int width = button.getWidth();
  48410. const int height = button.getHeight();
  48411. const float indent = 2.0f;
  48412. const int cornerSize = jmin (roundFloatToInt (width * 0.4f),
  48413. roundFloatToInt (height * 0.4f));
  48414. Path p;
  48415. p.addRoundedRectangle (indent, indent,
  48416. width - indent * 2.0f,
  48417. height - indent * 2.0f,
  48418. (float) cornerSize);
  48419. Colour bc (backgroundColour.withMultipliedSaturation (0.3f));
  48420. if (isMouseOverButton)
  48421. {
  48422. if (isButtonDown)
  48423. bc = bc.brighter();
  48424. else if (bc.getBrightness() > 0.5f)
  48425. bc = bc.darker (0.1f);
  48426. else
  48427. bc = bc.brighter (0.1f);
  48428. }
  48429. g.setColour (bc);
  48430. g.fillPath (p);
  48431. g.setColour (bc.contrasting().withAlpha ((isMouseOverButton) ? 0.6f : 0.4f));
  48432. g.strokePath (p, PathStrokeType ((isMouseOverButton) ? 2.0f : 1.4f));
  48433. }
  48434. void OldSchoolLookAndFeel::drawTickBox (Graphics& g,
  48435. Component& /*component*/,
  48436. int x, int y, int w, int h,
  48437. const bool ticked,
  48438. const bool isEnabled,
  48439. const bool /*isMouseOverButton*/,
  48440. const bool isButtonDown)
  48441. {
  48442. Path box;
  48443. box.addRoundedRectangle (0.0f, 2.0f, 6.0f, 6.0f, 1.0f);
  48444. g.setColour (isEnabled ? Colours::blue.withAlpha (isButtonDown ? 0.3f : 0.1f)
  48445. : Colours::lightgrey.withAlpha (0.1f));
  48446. AffineTransform trans (AffineTransform::scale (w / 9.0f, h / 9.0f)
  48447. .translated ((float) x, (float) y));
  48448. g.fillPath (box, trans);
  48449. g.setColour (Colours::black.withAlpha (0.6f));
  48450. g.strokePath (box, PathStrokeType (0.9f), trans);
  48451. if (ticked)
  48452. {
  48453. Path tick;
  48454. tick.startNewSubPath (1.5f, 3.0f);
  48455. tick.lineTo (3.0f, 6.0f);
  48456. tick.lineTo (6.0f, 0.0f);
  48457. g.setColour (isEnabled ? Colours::black : Colours::grey);
  48458. g.strokePath (tick, PathStrokeType (2.5f), trans);
  48459. }
  48460. }
  48461. void OldSchoolLookAndFeel::drawToggleButton (Graphics& g,
  48462. ToggleButton& button,
  48463. bool isMouseOverButton,
  48464. bool isButtonDown)
  48465. {
  48466. if (button.hasKeyboardFocus (true))
  48467. {
  48468. g.setColour (button.findColour (TextEditor::focusedOutlineColourId));
  48469. g.drawRect (0, 0, button.getWidth(), button.getHeight());
  48470. }
  48471. const int tickWidth = jmin (20, button.getHeight() - 4);
  48472. drawTickBox (g, button, 4, (button.getHeight() - tickWidth) / 2,
  48473. tickWidth, tickWidth,
  48474. button.getToggleState(),
  48475. button.isEnabled(),
  48476. isMouseOverButton,
  48477. isButtonDown);
  48478. g.setColour (button.findColour (ToggleButton::textColourId));
  48479. g.setFont (jmin (15.0f, button.getHeight() * 0.6f));
  48480. if (! button.isEnabled())
  48481. g.setOpacity (0.5f);
  48482. const int textX = tickWidth + 5;
  48483. g.drawFittedText (button.getButtonText(),
  48484. textX, 4,
  48485. button.getWidth() - textX - 2, button.getHeight() - 8,
  48486. Justification::centredLeft, 10);
  48487. }
  48488. void OldSchoolLookAndFeel::drawProgressBar (Graphics& g, ProgressBar& progressBar,
  48489. int width, int height,
  48490. double progress, const String& textToShow)
  48491. {
  48492. if (progress < 0 || progress >= 1.0)
  48493. {
  48494. LookAndFeel::drawProgressBar (g, progressBar, width, height, progress, textToShow);
  48495. }
  48496. else
  48497. {
  48498. const Colour background (progressBar.findColour (ProgressBar::backgroundColourId));
  48499. const Colour foreground (progressBar.findColour (ProgressBar::foregroundColourId));
  48500. g.fillAll (background);
  48501. g.setColour (foreground);
  48502. g.fillRect (1, 1,
  48503. jlimit (0, width - 2, roundDoubleToInt (progress * (width - 2))),
  48504. height - 2);
  48505. if (textToShow.isNotEmpty())
  48506. {
  48507. g.setColour (Colour::contrasting (background, foreground));
  48508. g.setFont (height * 0.6f);
  48509. g.drawText (textToShow, 0, 0, width, height, Justification::centred, false);
  48510. }
  48511. }
  48512. }
  48513. void OldSchoolLookAndFeel::drawScrollbarButton (Graphics& g,
  48514. ScrollBar& bar,
  48515. int width, int height,
  48516. int buttonDirection,
  48517. bool isScrollbarVertical,
  48518. bool isMouseOverButton,
  48519. bool isButtonDown)
  48520. {
  48521. if (isScrollbarVertical)
  48522. width -= 2;
  48523. else
  48524. height -= 2;
  48525. Path p;
  48526. if (buttonDirection == 0)
  48527. p.addTriangle (width * 0.5f, height * 0.2f,
  48528. width * 0.1f, height * 0.7f,
  48529. width * 0.9f, height * 0.7f);
  48530. else if (buttonDirection == 1)
  48531. p.addTriangle (width * 0.8f, height * 0.5f,
  48532. width * 0.3f, height * 0.1f,
  48533. width * 0.3f, height * 0.9f);
  48534. else if (buttonDirection == 2)
  48535. p.addTriangle (width * 0.5f, height * 0.8f,
  48536. width * 0.1f, height * 0.3f,
  48537. width * 0.9f, height * 0.3f);
  48538. else if (buttonDirection == 3)
  48539. p.addTriangle (width * 0.2f, height * 0.5f,
  48540. width * 0.7f, height * 0.1f,
  48541. width * 0.7f, height * 0.9f);
  48542. if (isButtonDown)
  48543. g.setColour (Colours::white);
  48544. else if (isMouseOverButton)
  48545. g.setColour (Colours::white.withAlpha (0.7f));
  48546. else
  48547. g.setColour (bar.findColour (ScrollBar::thumbColourId).withAlpha (0.5f));
  48548. g.fillPath (p);
  48549. g.setColour (Colours::black.withAlpha (0.5f));
  48550. g.strokePath (p, PathStrokeType (0.5f));
  48551. }
  48552. void OldSchoolLookAndFeel::drawScrollbar (Graphics& g,
  48553. ScrollBar& bar,
  48554. int x, int y,
  48555. int width, int height,
  48556. bool isScrollbarVertical,
  48557. int thumbStartPosition,
  48558. int thumbSize,
  48559. bool isMouseOver,
  48560. bool isMouseDown)
  48561. {
  48562. g.fillAll (bar.findColour (ScrollBar::backgroundColourId));
  48563. g.setColour (bar.findColour (ScrollBar::thumbColourId)
  48564. .withAlpha ((isMouseOver || isMouseDown) ? 0.4f : 0.15f));
  48565. if (thumbSize > 0.0f)
  48566. {
  48567. Rectangle thumb;
  48568. if (isScrollbarVertical)
  48569. {
  48570. width -= 2;
  48571. g.fillRect (x + roundFloatToInt (width * 0.35f), y,
  48572. roundFloatToInt (width * 0.3f), height);
  48573. thumb.setBounds (x + 1, thumbStartPosition,
  48574. width - 2, thumbSize);
  48575. }
  48576. else
  48577. {
  48578. height -= 2;
  48579. g.fillRect (x, y + roundFloatToInt (height * 0.35f),
  48580. width, roundFloatToInt (height * 0.3f));
  48581. thumb.setBounds (thumbStartPosition, y + 1,
  48582. thumbSize, height - 2);
  48583. }
  48584. g.setColour (bar.findColour (ScrollBar::thumbColourId)
  48585. .withAlpha ((isMouseOver || isMouseDown) ? 0.95f : 0.7f));
  48586. g.fillRect (thumb);
  48587. g.setColour (Colours::black.withAlpha ((isMouseOver || isMouseDown) ? 0.4f : 0.25f));
  48588. g.drawRect (thumb.getX(), thumb.getY(), thumb.getWidth(), thumb.getHeight());
  48589. if (thumbSize > 16)
  48590. {
  48591. for (int i = 3; --i >= 0;)
  48592. {
  48593. const float linePos = thumbStartPosition + thumbSize / 2 + (i - 1) * 4.0f;
  48594. g.setColour (Colours::black.withAlpha (0.15f));
  48595. if (isScrollbarVertical)
  48596. {
  48597. g.drawLine (x + width * 0.2f, linePos, width * 0.8f, linePos);
  48598. g.setColour (Colours::white.withAlpha (0.15f));
  48599. g.drawLine (width * 0.2f, linePos - 1, width * 0.8f, linePos - 1);
  48600. }
  48601. else
  48602. {
  48603. g.drawLine (linePos, height * 0.2f, linePos, height * 0.8f);
  48604. g.setColour (Colours::white.withAlpha (0.15f));
  48605. g.drawLine (linePos - 1, height * 0.2f, linePos - 1, height * 0.8f);
  48606. }
  48607. }
  48608. }
  48609. }
  48610. }
  48611. ImageEffectFilter* OldSchoolLookAndFeel::getScrollbarEffect()
  48612. {
  48613. return &scrollbarShadow;
  48614. }
  48615. void OldSchoolLookAndFeel::drawPopupMenuBackground (Graphics& g, int width, int height)
  48616. {
  48617. g.fillAll (findColour (PopupMenu::backgroundColourId));
  48618. g.setColour (Colours::black.withAlpha (0.6f));
  48619. g.drawRect (0, 0, width, height);
  48620. }
  48621. void OldSchoolLookAndFeel::drawMenuBarBackground (Graphics& g, int /*width*/, int /*height*/,
  48622. bool, MenuBarComponent& menuBar)
  48623. {
  48624. g.fillAll (menuBar.findColour (PopupMenu::backgroundColourId));
  48625. }
  48626. void OldSchoolLookAndFeel::drawTextEditorOutline (Graphics& g, int width, int height, TextEditor& textEditor)
  48627. {
  48628. if (textEditor.isEnabled())
  48629. {
  48630. g.setColour (textEditor.findColour (TextEditor::outlineColourId));
  48631. g.drawRect (0, 0, width, height);
  48632. }
  48633. }
  48634. void OldSchoolLookAndFeel::drawComboBox (Graphics& g, int width, int height,
  48635. const bool isButtonDown,
  48636. int buttonX, int buttonY,
  48637. int buttonW, int buttonH,
  48638. ComboBox& box)
  48639. {
  48640. g.fillAll (box.findColour (ComboBox::backgroundColourId));
  48641. g.setColour (box.findColour ((isButtonDown) ? ComboBox::buttonColourId
  48642. : ComboBox::backgroundColourId));
  48643. g.fillRect (buttonX, buttonY, buttonW, buttonH);
  48644. g.setColour (box.findColour (ComboBox::outlineColourId));
  48645. g.drawRect (0, 0, width, height);
  48646. const float arrowX = 0.2f;
  48647. const float arrowH = 0.3f;
  48648. if (box.isEnabled())
  48649. {
  48650. Path p;
  48651. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.45f - arrowH),
  48652. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.45f,
  48653. buttonX + buttonW * arrowX, buttonY + buttonH * 0.45f);
  48654. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.55f + arrowH),
  48655. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.55f,
  48656. buttonX + buttonW * arrowX, buttonY + buttonH * 0.55f);
  48657. g.setColour (box.findColour ((isButtonDown) ? ComboBox::backgroundColourId
  48658. : ComboBox::buttonColourId));
  48659. g.fillPath (p);
  48660. }
  48661. }
  48662. const Font OldSchoolLookAndFeel::getComboBoxFont (ComboBox& box)
  48663. {
  48664. Font f (jmin (15.0f, box.getHeight() * 0.85f));
  48665. f.setHorizontalScale (0.9f);
  48666. return f;
  48667. }
  48668. static void drawTriangle (Graphics& g, float x1, float y1, float x2, float y2, float x3, float y3, const Colour& fill, const Colour& outline) throw()
  48669. {
  48670. Path p;
  48671. p.addTriangle (x1, y1, x2, y2, x3, y3);
  48672. g.setColour (fill);
  48673. g.fillPath (p);
  48674. g.setColour (outline);
  48675. g.strokePath (p, PathStrokeType (0.3f));
  48676. }
  48677. void OldSchoolLookAndFeel::drawLinearSlider (Graphics& g,
  48678. int x, int y,
  48679. int w, int h,
  48680. float sliderPos,
  48681. float minSliderPos,
  48682. float maxSliderPos,
  48683. const Slider::SliderStyle style,
  48684. Slider& slider)
  48685. {
  48686. g.fillAll (slider.findColour (Slider::backgroundColourId));
  48687. if (style == Slider::LinearBar)
  48688. {
  48689. g.setColour (slider.findColour (Slider::thumbColourId));
  48690. g.fillRect (x, y, (int) sliderPos - x, h);
  48691. g.setColour (slider.findColour (Slider::textBoxTextColourId).withMultipliedAlpha (0.5f));
  48692. g.drawRect (x, y, (int) sliderPos - x, h);
  48693. }
  48694. else
  48695. {
  48696. g.setColour (slider.findColour (Slider::trackColourId)
  48697. .withMultipliedAlpha (slider.isEnabled() ? 1.0f : 0.3f));
  48698. if (slider.isHorizontal())
  48699. {
  48700. g.fillRect (x, y + roundFloatToInt (h * 0.6f),
  48701. w, roundFloatToInt (h * 0.2f));
  48702. }
  48703. else
  48704. {
  48705. g.fillRect (x + roundFloatToInt (w * 0.5f - jmin (3.0f, w * 0.1f)), y,
  48706. jmin (4, roundFloatToInt (w * 0.2f)), h);
  48707. }
  48708. float alpha = 0.35f;
  48709. if (slider.isEnabled())
  48710. alpha = slider.isMouseOverOrDragging() ? 1.0f : 0.7f;
  48711. const Colour fill (slider.findColour (Slider::thumbColourId).withAlpha (alpha));
  48712. const Colour outline (Colours::black.withAlpha (slider.isEnabled() ? 0.7f : 0.35f));
  48713. if (style == Slider::TwoValueVertical || style == Slider::ThreeValueVertical)
  48714. {
  48715. drawTriangle (g, x + w * 0.5f + jmin (4.0f, w * 0.3f), minSliderPos,
  48716. x + w * 0.5f - jmin (8.0f, w * 0.4f), minSliderPos - 7.0f,
  48717. x + w * 0.5f - jmin (8.0f, w * 0.4f), minSliderPos,
  48718. fill, outline);
  48719. drawTriangle (g, x + w * 0.5f + jmin (4.0f, w * 0.3f), maxSliderPos,
  48720. x + w * 0.5f - jmin (8.0f, w * 0.4f), maxSliderPos,
  48721. x + w * 0.5f - jmin (8.0f, w * 0.4f), maxSliderPos + 7.0f,
  48722. fill, outline);
  48723. }
  48724. else if (style == Slider::TwoValueHorizontal || style == Slider::ThreeValueHorizontal)
  48725. {
  48726. drawTriangle (g, minSliderPos, y + h * 0.6f - jmin (4.0f, h * 0.3f),
  48727. minSliderPos - 7.0f, y + h * 0.9f ,
  48728. minSliderPos, y + h * 0.9f,
  48729. fill, outline);
  48730. drawTriangle (g, maxSliderPos, y + h * 0.6f - jmin (4.0f, h * 0.3f),
  48731. maxSliderPos, y + h * 0.9f,
  48732. maxSliderPos + 7.0f, y + h * 0.9f,
  48733. fill, outline);
  48734. }
  48735. if (style == Slider::LinearHorizontal || style == Slider::ThreeValueHorizontal)
  48736. {
  48737. drawTriangle (g, sliderPos, y + h * 0.9f,
  48738. sliderPos - 7.0f, y + h * 0.2f,
  48739. sliderPos + 7.0f, y + h * 0.2f,
  48740. fill, outline);
  48741. }
  48742. else if (style == Slider::LinearVertical || style == Slider::ThreeValueVertical)
  48743. {
  48744. drawTriangle (g, x + w * 0.5f - jmin (4.0f, w * 0.3f), sliderPos,
  48745. x + w * 0.5f + jmin (8.0f, w * 0.4f), sliderPos - 7.0f,
  48746. x + w * 0.5f + jmin (8.0f, w * 0.4f), sliderPos + 7.0f,
  48747. fill, outline);
  48748. }
  48749. }
  48750. }
  48751. Button* OldSchoolLookAndFeel::createSliderButton (const bool isIncrement)
  48752. {
  48753. if (isIncrement)
  48754. return new ArrowButton ("u", 0.75f, Colours::white.withAlpha (0.8f));
  48755. else
  48756. return new ArrowButton ("d", 0.25f, Colours::white.withAlpha (0.8f));
  48757. }
  48758. ImageEffectFilter* OldSchoolLookAndFeel::getSliderEffect()
  48759. {
  48760. return &scrollbarShadow;
  48761. }
  48762. int OldSchoolLookAndFeel::getSliderThumbRadius (Slider&)
  48763. {
  48764. return 8;
  48765. }
  48766. void OldSchoolLookAndFeel::drawCornerResizer (Graphics& g,
  48767. int w, int h,
  48768. bool isMouseOver,
  48769. bool isMouseDragging)
  48770. {
  48771. g.setColour ((isMouseOver || isMouseDragging) ? Colours::lightgrey
  48772. : Colours::darkgrey);
  48773. const float lineThickness = jmin (w, h) * 0.1f;
  48774. for (float i = 0.0f; i < 1.0f; i += 0.3f)
  48775. {
  48776. g.drawLine (w * i,
  48777. h + 1.0f,
  48778. w + 1.0f,
  48779. h * i,
  48780. lineThickness);
  48781. }
  48782. }
  48783. Button* OldSchoolLookAndFeel::createDocumentWindowButton (int buttonType)
  48784. {
  48785. Path shape;
  48786. if (buttonType == DocumentWindow::closeButton)
  48787. {
  48788. shape.addLineSegment (0.0f, 0.0f, 1.0f, 1.0f, 0.35f);
  48789. shape.addLineSegment (1.0f, 0.0f, 0.0f, 1.0f, 0.35f);
  48790. ShapeButton* const b = new ShapeButton ("close",
  48791. Colour (0x7fff3333),
  48792. Colour (0xd7ff3333),
  48793. Colour (0xf7ff3333));
  48794. b->setShape (shape, true, true, true);
  48795. return b;
  48796. }
  48797. else if (buttonType == DocumentWindow::minimiseButton)
  48798. {
  48799. shape.addLineSegment (0.0f, 0.5f, 1.0f, 0.5f, 0.25f);
  48800. DrawableButton* b = new DrawableButton ("minimise", DrawableButton::ImageFitted);
  48801. DrawablePath dp;
  48802. dp.setPath (shape);
  48803. dp.setSolidFill (Colours::black.withAlpha (0.3f));
  48804. b->setImages (&dp);
  48805. return b;
  48806. }
  48807. else if (buttonType == DocumentWindow::maximiseButton)
  48808. {
  48809. shape.addLineSegment (0.5f, 0.0f, 0.5f, 1.0f, 0.25f);
  48810. shape.addLineSegment (0.0f, 0.5f, 1.0f, 0.5f, 0.25f);
  48811. DrawableButton* b = new DrawableButton ("maximise", DrawableButton::ImageFitted);
  48812. DrawablePath dp;
  48813. dp.setPath (shape);
  48814. dp.setSolidFill (Colours::black.withAlpha (0.3f));
  48815. b->setImages (&dp);
  48816. return b;
  48817. }
  48818. jassertfalse
  48819. return 0;
  48820. }
  48821. void OldSchoolLookAndFeel::positionDocumentWindowButtons (DocumentWindow&,
  48822. int titleBarX,
  48823. int titleBarY,
  48824. int titleBarW,
  48825. int titleBarH,
  48826. Button* minimiseButton,
  48827. Button* maximiseButton,
  48828. Button* closeButton,
  48829. bool positionTitleBarButtonsOnLeft)
  48830. {
  48831. titleBarY += titleBarH / 8;
  48832. titleBarH -= titleBarH / 4;
  48833. const int buttonW = titleBarH;
  48834. int x = positionTitleBarButtonsOnLeft ? titleBarX + 4
  48835. : titleBarX + titleBarW - buttonW - 4;
  48836. if (closeButton != 0)
  48837. {
  48838. closeButton->setBounds (x, titleBarY, buttonW, titleBarH);
  48839. x += positionTitleBarButtonsOnLeft ? buttonW + buttonW / 5
  48840. : -(buttonW + buttonW / 5);
  48841. }
  48842. if (positionTitleBarButtonsOnLeft)
  48843. swapVariables (minimiseButton, maximiseButton);
  48844. if (maximiseButton != 0)
  48845. {
  48846. maximiseButton->setBounds (x, titleBarY - 2, buttonW, titleBarH);
  48847. x += positionTitleBarButtonsOnLeft ? buttonW : -buttonW;
  48848. }
  48849. if (minimiseButton != 0)
  48850. minimiseButton->setBounds (x, titleBarY - 2, buttonW, titleBarH);
  48851. }
  48852. END_JUCE_NAMESPACE
  48853. /********* End of inlined file: juce_OldSchoolLookAndFeel.cpp *********/
  48854. /********* Start of inlined file: juce_MenuBarComponent.cpp *********/
  48855. BEGIN_JUCE_NAMESPACE
  48856. class DummyMenuComponent : public Component
  48857. {
  48858. DummyMenuComponent (const DummyMenuComponent&);
  48859. const DummyMenuComponent& operator= (const DummyMenuComponent&);
  48860. public:
  48861. DummyMenuComponent() {}
  48862. ~DummyMenuComponent() {}
  48863. void inputAttemptWhenModal()
  48864. {
  48865. exitModalState (0);
  48866. }
  48867. };
  48868. MenuBarComponent::MenuBarComponent (MenuBarModel* model_)
  48869. : model (0),
  48870. itemUnderMouse (-1),
  48871. currentPopupIndex (-1),
  48872. indexToShowAgain (-1),
  48873. lastMouseX (0),
  48874. lastMouseY (0),
  48875. inModalState (false),
  48876. currentPopup (0)
  48877. {
  48878. setRepaintsOnMouseActivity (true);
  48879. setWantsKeyboardFocus (false);
  48880. setMouseClickGrabsKeyboardFocus (false);
  48881. setModel (model_);
  48882. }
  48883. MenuBarComponent::~MenuBarComponent()
  48884. {
  48885. setModel (0);
  48886. Desktop::getInstance().removeGlobalMouseListener (this);
  48887. deleteAndZero (currentPopup);
  48888. }
  48889. void MenuBarComponent::setModel (MenuBarModel* const newModel)
  48890. {
  48891. if (model != newModel)
  48892. {
  48893. if (model != 0)
  48894. model->removeListener (this);
  48895. model = newModel;
  48896. if (model != 0)
  48897. model->addListener (this);
  48898. repaint();
  48899. menuBarItemsChanged (0);
  48900. }
  48901. }
  48902. void MenuBarComponent::paint (Graphics& g)
  48903. {
  48904. const bool isMouseOverBar = currentPopupIndex >= 0 || itemUnderMouse >= 0 || isMouseOver();
  48905. getLookAndFeel().drawMenuBarBackground (g,
  48906. getWidth(),
  48907. getHeight(),
  48908. isMouseOverBar,
  48909. *this);
  48910. if (model != 0)
  48911. {
  48912. for (int i = 0; i < menuNames.size(); ++i)
  48913. {
  48914. g.saveState();
  48915. g.setOrigin (xPositions [i], 0);
  48916. g.reduceClipRegion (0, 0, xPositions[i + 1] - xPositions[i], getHeight());
  48917. getLookAndFeel().drawMenuBarItem (g,
  48918. xPositions[i + 1] - xPositions[i],
  48919. getHeight(),
  48920. i,
  48921. menuNames[i],
  48922. i == itemUnderMouse,
  48923. i == currentPopupIndex,
  48924. isMouseOverBar,
  48925. *this);
  48926. g.restoreState();
  48927. }
  48928. }
  48929. }
  48930. void MenuBarComponent::resized()
  48931. {
  48932. xPositions.clear();
  48933. int x = 2;
  48934. xPositions.add (x);
  48935. for (int i = 0; i < menuNames.size(); ++i)
  48936. {
  48937. x += getLookAndFeel().getMenuBarItemWidth (*this, i, menuNames[i]);
  48938. xPositions.add (x);
  48939. }
  48940. }
  48941. int MenuBarComponent::getItemAt (const int x, const int y)
  48942. {
  48943. for (int i = 0; i < xPositions.size(); ++i)
  48944. if (x >= xPositions[i] && x < xPositions[i + 1])
  48945. return reallyContains (x, y, true) ? i : -1;
  48946. return -1;
  48947. }
  48948. void MenuBarComponent::repaintMenuItem (int index)
  48949. {
  48950. if (((unsigned int) index) < (unsigned int) xPositions.size())
  48951. {
  48952. const int x1 = xPositions [index];
  48953. const int x2 = xPositions [index + 1];
  48954. repaint (x1 - 2, 0, x2 - x1 + 4, getHeight());
  48955. }
  48956. }
  48957. void MenuBarComponent::updateItemUnderMouse (int x, int y)
  48958. {
  48959. const int newItem = getItemAt (x, y);
  48960. if (itemUnderMouse != newItem)
  48961. {
  48962. repaintMenuItem (itemUnderMouse);
  48963. itemUnderMouse = newItem;
  48964. repaintMenuItem (itemUnderMouse);
  48965. }
  48966. }
  48967. void MenuBarComponent::hideCurrentMenu()
  48968. {
  48969. deleteAndZero (currentPopup);
  48970. repaint();
  48971. }
  48972. void MenuBarComponent::showMenu (int index)
  48973. {
  48974. if (index != currentPopupIndex)
  48975. {
  48976. if (inModalState)
  48977. {
  48978. hideCurrentMenu();
  48979. indexToShowAgain = index;
  48980. return;
  48981. }
  48982. indexToShowAgain = -1;
  48983. currentPopupIndex = -1;
  48984. deleteAndZero (currentPopup);
  48985. menuBarItemsChanged (0);
  48986. Component* const prevFocused = getCurrentlyFocusedComponent();
  48987. ComponentDeletionWatcher* prevCompDeletionChecker = 0;
  48988. if (prevFocused != 0)
  48989. prevCompDeletionChecker = new ComponentDeletionWatcher (prevFocused);
  48990. ComponentDeletionWatcher deletionChecker (this);
  48991. enterModalState (false);
  48992. inModalState = true;
  48993. int result = 0;
  48994. ApplicationCommandManager* managerOfChosenCommand = 0;
  48995. Desktop::getInstance().addGlobalMouseListener (this);
  48996. for (;;)
  48997. {
  48998. const int x = getScreenX() + xPositions [itemUnderMouse];
  48999. const int w = xPositions [itemUnderMouse + 1] - xPositions [itemUnderMouse];
  49000. currentPopupIndex = itemUnderMouse;
  49001. indexToShowAgain = -1;
  49002. repaint();
  49003. if (((unsigned int) itemUnderMouse) < (unsigned int) menuNames.size())
  49004. {
  49005. PopupMenu m (model->getMenuForIndex (itemUnderMouse,
  49006. menuNames [itemUnderMouse]));
  49007. currentPopup = m.createMenuComponent (x, getScreenY(),
  49008. w, getHeight(),
  49009. 0, w, 0, 0,
  49010. true, this,
  49011. &managerOfChosenCommand,
  49012. this);
  49013. }
  49014. if (currentPopup == 0)
  49015. {
  49016. currentPopup = new DummyMenuComponent();
  49017. addAndMakeVisible (currentPopup);
  49018. }
  49019. currentPopup->enterModalState (false);
  49020. currentPopup->toFront (false); // need to do this after making it modal, or it could
  49021. // be stuck behind other comps that are already modal..
  49022. result = currentPopup->runModalLoop();
  49023. if (deletionChecker.hasBeenDeleted())
  49024. {
  49025. delete prevCompDeletionChecker;
  49026. return;
  49027. }
  49028. const int lastPopupIndex = currentPopupIndex;
  49029. deleteAndZero (currentPopup);
  49030. currentPopupIndex = -1;
  49031. if (result != 0)
  49032. {
  49033. topLevelIndexClicked = lastPopupIndex;
  49034. break;
  49035. }
  49036. else if (indexToShowAgain >= 0)
  49037. {
  49038. menuBarItemsChanged (0);
  49039. repaint();
  49040. itemUnderMouse = indexToShowAgain;
  49041. if (((unsigned int) itemUnderMouse) >= (unsigned int) menuNames.size())
  49042. break;
  49043. }
  49044. else
  49045. {
  49046. break;
  49047. }
  49048. }
  49049. Desktop::getInstance().removeGlobalMouseListener (this);
  49050. inModalState = false;
  49051. exitModalState (0);
  49052. if (prevCompDeletionChecker != 0)
  49053. {
  49054. if (! prevCompDeletionChecker->hasBeenDeleted())
  49055. prevFocused->grabKeyboardFocus();
  49056. delete prevCompDeletionChecker;
  49057. }
  49058. int mx, my;
  49059. getMouseXYRelative (mx, my);
  49060. updateItemUnderMouse (mx, my);
  49061. repaint();
  49062. if (result != 0)
  49063. {
  49064. if (managerOfChosenCommand != 0)
  49065. {
  49066. ApplicationCommandTarget::InvocationInfo info (result);
  49067. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromMenu;
  49068. managerOfChosenCommand->invoke (info, true);
  49069. }
  49070. postCommandMessage (result);
  49071. }
  49072. }
  49073. }
  49074. void MenuBarComponent::handleCommandMessage (int commandId)
  49075. {
  49076. if (model != 0)
  49077. model->menuItemSelected (commandId, topLevelIndexClicked);
  49078. }
  49079. void MenuBarComponent::mouseEnter (const MouseEvent& e)
  49080. {
  49081. if (e.eventComponent == this)
  49082. updateItemUnderMouse (e.x, e.y);
  49083. }
  49084. void MenuBarComponent::mouseExit (const MouseEvent& e)
  49085. {
  49086. if (e.eventComponent == this)
  49087. updateItemUnderMouse (e.x, e.y);
  49088. }
  49089. void MenuBarComponent::mouseDown (const MouseEvent& e)
  49090. {
  49091. const MouseEvent e2 (e.getEventRelativeTo (this));
  49092. if (currentPopupIndex < 0)
  49093. {
  49094. updateItemUnderMouse (e2.x, e2.y);
  49095. currentPopupIndex = -2;
  49096. showMenu (itemUnderMouse);
  49097. }
  49098. }
  49099. void MenuBarComponent::mouseDrag (const MouseEvent& e)
  49100. {
  49101. const MouseEvent e2 (e.getEventRelativeTo (this));
  49102. const int item = getItemAt (e2.x, e2.y);
  49103. if (item >= 0)
  49104. showMenu (item);
  49105. }
  49106. void MenuBarComponent::mouseUp (const MouseEvent& e)
  49107. {
  49108. const MouseEvent e2 (e.getEventRelativeTo (this));
  49109. updateItemUnderMouse (e2.x, e2.y);
  49110. if (itemUnderMouse < 0 && dynamic_cast <DummyMenuComponent*> (currentPopup) != 0)
  49111. hideCurrentMenu();
  49112. }
  49113. void MenuBarComponent::mouseMove (const MouseEvent& e)
  49114. {
  49115. const MouseEvent e2 (e.getEventRelativeTo (this));
  49116. if (lastMouseX != e2.x || lastMouseY != e2.y)
  49117. {
  49118. if (currentPopupIndex >= 0)
  49119. {
  49120. const int item = getItemAt (e2.x, e2.y);
  49121. if (item >= 0)
  49122. showMenu (item);
  49123. }
  49124. else
  49125. {
  49126. updateItemUnderMouse (e2.x, e2.y);
  49127. }
  49128. lastMouseX = e2.x;
  49129. lastMouseY = e2.y;
  49130. }
  49131. }
  49132. bool MenuBarComponent::keyPressed (const KeyPress& key)
  49133. {
  49134. bool used = false;
  49135. const int numMenus = menuNames.size();
  49136. const int currentIndex = jlimit (0, menuNames.size() - 1, currentPopupIndex);
  49137. if (key.isKeyCode (KeyPress::leftKey))
  49138. {
  49139. showMenu ((currentIndex + numMenus - 1) % numMenus);
  49140. used = true;
  49141. }
  49142. else if (key.isKeyCode (KeyPress::rightKey))
  49143. {
  49144. showMenu ((currentIndex + 1) % numMenus);
  49145. used = true;
  49146. }
  49147. return used;
  49148. }
  49149. void MenuBarComponent::inputAttemptWhenModal()
  49150. {
  49151. hideCurrentMenu();
  49152. }
  49153. void MenuBarComponent::menuBarItemsChanged (MenuBarModel* /*menuBarModel*/)
  49154. {
  49155. StringArray newNames;
  49156. if (model != 0)
  49157. newNames = model->getMenuBarNames();
  49158. if (newNames != menuNames)
  49159. {
  49160. menuNames = newNames;
  49161. repaint();
  49162. resized();
  49163. }
  49164. }
  49165. void MenuBarComponent::menuCommandInvoked (MenuBarModel* /*menuBarModel*/,
  49166. const ApplicationCommandTarget::InvocationInfo& info)
  49167. {
  49168. if (model == 0
  49169. || (info.commandFlags & ApplicationCommandInfo::dontTriggerVisualFeedback) != 0)
  49170. return;
  49171. for (int i = 0; i < menuNames.size(); ++i)
  49172. {
  49173. const PopupMenu menu (model->getMenuForIndex (i, menuNames [i]));
  49174. if (menu.containsCommandItem (info.commandID))
  49175. {
  49176. itemUnderMouse = i;
  49177. repaintMenuItem (i);
  49178. startTimer (200);
  49179. break;
  49180. }
  49181. }
  49182. }
  49183. void MenuBarComponent::timerCallback()
  49184. {
  49185. stopTimer();
  49186. int mx, my;
  49187. getMouseXYRelative (mx, my);
  49188. updateItemUnderMouse (mx, my);
  49189. }
  49190. END_JUCE_NAMESPACE
  49191. /********* End of inlined file: juce_MenuBarComponent.cpp *********/
  49192. /********* Start of inlined file: juce_MenuBarModel.cpp *********/
  49193. BEGIN_JUCE_NAMESPACE
  49194. MenuBarModel::MenuBarModel() throw()
  49195. : manager (0)
  49196. {
  49197. }
  49198. MenuBarModel::~MenuBarModel()
  49199. {
  49200. setApplicationCommandManagerToWatch (0);
  49201. }
  49202. void MenuBarModel::menuItemsChanged()
  49203. {
  49204. triggerAsyncUpdate();
  49205. }
  49206. void MenuBarModel::setApplicationCommandManagerToWatch (ApplicationCommandManager* const newManager) throw()
  49207. {
  49208. if (manager != newManager)
  49209. {
  49210. if (manager != 0)
  49211. manager->removeListener (this);
  49212. manager = newManager;
  49213. if (manager != 0)
  49214. manager->addListener (this);
  49215. }
  49216. }
  49217. void MenuBarModel::addListener (MenuBarModelListener* const newListener) throw()
  49218. {
  49219. jassert (newListener != 0);
  49220. jassert (! listeners.contains (newListener)); // trying to add a listener to the list twice!
  49221. if (newListener != 0)
  49222. listeners.add (newListener);
  49223. }
  49224. void MenuBarModel::removeListener (MenuBarModelListener* const listenerToRemove) throw()
  49225. {
  49226. // Trying to remove a listener that isn't on the list!
  49227. // If this assertion happens because this object is a dangling pointer, make sure you've not
  49228. // deleted this menu model while it's still being used by something (e.g. by a MenuBarComponent)
  49229. jassert (listeners.contains (listenerToRemove));
  49230. listeners.removeValue (listenerToRemove);
  49231. }
  49232. void MenuBarModel::handleAsyncUpdate()
  49233. {
  49234. for (int i = listeners.size(); --i >= 0;)
  49235. {
  49236. ((MenuBarModelListener*) listeners.getUnchecked (i))->menuBarItemsChanged (this);
  49237. i = jmin (i, listeners.size());
  49238. }
  49239. }
  49240. void MenuBarModel::applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info)
  49241. {
  49242. for (int i = listeners.size(); --i >= 0;)
  49243. {
  49244. ((MenuBarModelListener*) listeners.getUnchecked (i))->menuCommandInvoked (this, info);
  49245. i = jmin (i, listeners.size());
  49246. }
  49247. }
  49248. void MenuBarModel::applicationCommandListChanged()
  49249. {
  49250. menuItemsChanged();
  49251. }
  49252. END_JUCE_NAMESPACE
  49253. /********* End of inlined file: juce_MenuBarModel.cpp *********/
  49254. /********* Start of inlined file: juce_PopupMenu.cpp *********/
  49255. BEGIN_JUCE_NAMESPACE
  49256. static VoidArray activeMenuWindows;
  49257. class MenuItemInfo
  49258. {
  49259. public:
  49260. const int itemId;
  49261. String text;
  49262. const Colour textColour;
  49263. const bool active, isSeparator, isTicked, usesColour;
  49264. Image* image;
  49265. PopupMenuCustomComponent* const customComp;
  49266. PopupMenu* subMenu;
  49267. ApplicationCommandManager* const commandManager;
  49268. MenuItemInfo() throw()
  49269. : itemId (0),
  49270. active (true),
  49271. isSeparator (true),
  49272. isTicked (false),
  49273. usesColour (false),
  49274. image (0),
  49275. customComp (0),
  49276. subMenu (0),
  49277. commandManager (0)
  49278. {
  49279. }
  49280. MenuItemInfo (const int itemId_,
  49281. const String& text_,
  49282. const bool active_,
  49283. const bool isTicked_,
  49284. const Image* im,
  49285. const Colour& textColour_,
  49286. const bool usesColour_,
  49287. PopupMenuCustomComponent* const customComp_,
  49288. const PopupMenu* const subMenu_,
  49289. ApplicationCommandManager* const commandManager_) throw()
  49290. : itemId (itemId_),
  49291. text (text_),
  49292. textColour (textColour_),
  49293. active (active_),
  49294. isSeparator (false),
  49295. isTicked (isTicked_),
  49296. usesColour (usesColour_),
  49297. image (0),
  49298. customComp (customComp_),
  49299. commandManager (commandManager_)
  49300. {
  49301. subMenu = (subMenu_ != 0) ? new PopupMenu (*subMenu_) : 0;
  49302. if (customComp != 0)
  49303. customComp->refCount_++;
  49304. if (im != 0)
  49305. image = im->createCopy();
  49306. if (commandManager_ != 0 && itemId_ != 0)
  49307. {
  49308. String shortcutKey;
  49309. Array <KeyPress> keyPresses (commandManager_->getKeyMappings()
  49310. ->getKeyPressesAssignedToCommand (itemId_));
  49311. for (int i = 0; i < keyPresses.size(); ++i)
  49312. {
  49313. const String key (keyPresses.getReference(i).getTextDescription());
  49314. if (shortcutKey.isNotEmpty())
  49315. shortcutKey << ", ";
  49316. if (key.length() == 1)
  49317. shortcutKey << "shortcut: '" << key << '\'';
  49318. else
  49319. shortcutKey << key;
  49320. }
  49321. shortcutKey = shortcutKey.trim();
  49322. if (shortcutKey.isNotEmpty())
  49323. text << "<end>" << shortcutKey;
  49324. }
  49325. }
  49326. MenuItemInfo (const MenuItemInfo& other) throw()
  49327. : itemId (other.itemId),
  49328. text (other.text),
  49329. textColour (other.textColour),
  49330. active (other.active),
  49331. isSeparator (other.isSeparator),
  49332. isTicked (other.isTicked),
  49333. usesColour (other.usesColour),
  49334. customComp (other.customComp),
  49335. commandManager (other.commandManager)
  49336. {
  49337. if (other.subMenu != 0)
  49338. subMenu = new PopupMenu (*(other.subMenu));
  49339. else
  49340. subMenu = 0;
  49341. if (other.image != 0)
  49342. image = other.image->createCopy();
  49343. else
  49344. image = 0;
  49345. if (customComp != 0)
  49346. customComp->refCount_++;
  49347. }
  49348. ~MenuItemInfo() throw()
  49349. {
  49350. delete subMenu;
  49351. delete image;
  49352. if (customComp != 0 && --(customComp->refCount_) == 0)
  49353. delete customComp;
  49354. }
  49355. bool canBeTriggered() const throw()
  49356. {
  49357. return active && ! (isSeparator || (subMenu != 0));
  49358. }
  49359. bool hasActiveSubMenu() const throw()
  49360. {
  49361. return active && (subMenu != 0);
  49362. }
  49363. juce_UseDebuggingNewOperator
  49364. private:
  49365. const MenuItemInfo& operator= (const MenuItemInfo&);
  49366. };
  49367. class MenuItemComponent : public Component
  49368. {
  49369. bool isHighlighted;
  49370. public:
  49371. MenuItemInfo itemInfo;
  49372. MenuItemComponent (const MenuItemInfo& itemInfo_)
  49373. : isHighlighted (false),
  49374. itemInfo (itemInfo_)
  49375. {
  49376. if (itemInfo.customComp != 0)
  49377. addAndMakeVisible (itemInfo.customComp);
  49378. }
  49379. ~MenuItemComponent()
  49380. {
  49381. if (itemInfo.customComp != 0)
  49382. removeChildComponent (itemInfo.customComp);
  49383. }
  49384. void getIdealSize (int& idealWidth,
  49385. int& idealHeight,
  49386. const int standardItemHeight)
  49387. {
  49388. if (itemInfo.customComp != 0)
  49389. {
  49390. itemInfo.customComp->getIdealSize (idealWidth, idealHeight);
  49391. }
  49392. else
  49393. {
  49394. getLookAndFeel().getIdealPopupMenuItemSize (itemInfo.text,
  49395. itemInfo.isSeparator,
  49396. standardItemHeight,
  49397. idealWidth,
  49398. idealHeight);
  49399. }
  49400. }
  49401. void paint (Graphics& g)
  49402. {
  49403. if (itemInfo.customComp == 0)
  49404. {
  49405. String mainText (itemInfo.text);
  49406. String endText;
  49407. const int endIndex = mainText.indexOf (T("<end>"));
  49408. if (endIndex >= 0)
  49409. {
  49410. endText = mainText.substring (endIndex + 5).trim();
  49411. mainText = mainText.substring (0, endIndex);
  49412. }
  49413. getLookAndFeel()
  49414. .drawPopupMenuItem (g, getWidth(), getHeight(),
  49415. itemInfo.isSeparator,
  49416. itemInfo.active,
  49417. isHighlighted,
  49418. itemInfo.isTicked,
  49419. itemInfo.subMenu != 0,
  49420. mainText, endText,
  49421. itemInfo.image,
  49422. itemInfo.usesColour ? &(itemInfo.textColour) : 0);
  49423. }
  49424. }
  49425. void resized()
  49426. {
  49427. if (getNumChildComponents() > 0)
  49428. getChildComponent(0)->setBounds (2, 0, getWidth() - 4, getHeight());
  49429. }
  49430. void setHighlighted (bool shouldBeHighlighted)
  49431. {
  49432. shouldBeHighlighted = shouldBeHighlighted && itemInfo.active;
  49433. if (isHighlighted != shouldBeHighlighted)
  49434. {
  49435. isHighlighted = shouldBeHighlighted;
  49436. if (itemInfo.customComp != 0)
  49437. {
  49438. itemInfo.customComp->isHighlighted = shouldBeHighlighted;
  49439. itemInfo.customComp->repaint();
  49440. }
  49441. repaint();
  49442. }
  49443. }
  49444. private:
  49445. MenuItemComponent (const MenuItemComponent&);
  49446. const MenuItemComponent& operator= (const MenuItemComponent&);
  49447. };
  49448. static const int scrollZone = 24;
  49449. static const int borderSize = 2;
  49450. static const int timerInterval = 50;
  49451. static const int dismissCommandId = 0x6287345f;
  49452. static bool wasHiddenBecauseOfAppChange = false;
  49453. class PopupMenuWindow : public Component,
  49454. private Timer
  49455. {
  49456. public:
  49457. PopupMenuWindow() throw()
  49458. : Component (T("menu")),
  49459. owner (0),
  49460. currentChild (0),
  49461. activeSubMenu (0),
  49462. menuBarComponent (0),
  49463. managerOfChosenCommand (0),
  49464. componentAttachedTo (0),
  49465. attachedCompWatcher (0),
  49466. lastMouseX (0),
  49467. lastMouseY (0),
  49468. minimumWidth (0),
  49469. maximumNumColumns (7),
  49470. standardItemHeight (0),
  49471. isOver (false),
  49472. hasBeenOver (false),
  49473. isDown (false),
  49474. needsToScroll (false),
  49475. hideOnExit (false),
  49476. disableMouseMoves (false),
  49477. hasAnyJuceCompHadFocus (false),
  49478. numColumns (0),
  49479. contentHeight (0),
  49480. childYOffset (0),
  49481. timeEnteredCurrentChildComp (0),
  49482. scrollAcceleration (1.0)
  49483. {
  49484. menuCreationTime = lastFocused = lastScroll = Time::getMillisecondCounter();
  49485. setWantsKeyboardFocus (true);
  49486. setOpaque (true);
  49487. setAlwaysOnTop (true);
  49488. Desktop::getInstance().addGlobalMouseListener (this);
  49489. activeMenuWindows.add (this);
  49490. }
  49491. ~PopupMenuWindow()
  49492. {
  49493. activeMenuWindows.removeValue (this);
  49494. Desktop::getInstance().removeGlobalMouseListener (this);
  49495. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  49496. delete activeSubMenu;
  49497. deleteAllChildren();
  49498. delete attachedCompWatcher;
  49499. }
  49500. static PopupMenuWindow* create (const PopupMenu& menu,
  49501. const bool dismissOnMouseUp,
  49502. PopupMenuWindow* const owner_,
  49503. const int minX, const int maxX,
  49504. const int minY, const int maxY,
  49505. const int minimumWidth,
  49506. const int maximumNumColumns,
  49507. const int standardItemHeight,
  49508. const bool alignToRectangle,
  49509. const int itemIdThatMustBeVisible,
  49510. Component* const menuBarComponent,
  49511. ApplicationCommandManager** managerOfChosenCommand,
  49512. Component* const componentAttachedTo) throw()
  49513. {
  49514. if (menu.items.size() > 0)
  49515. {
  49516. int totalItems = 0;
  49517. PopupMenuWindow* const mw = new PopupMenuWindow();
  49518. mw->setLookAndFeel (menu.lookAndFeel);
  49519. mw->setWantsKeyboardFocus (false);
  49520. mw->minimumWidth = minimumWidth;
  49521. mw->maximumNumColumns = maximumNumColumns;
  49522. mw->standardItemHeight = standardItemHeight;
  49523. mw->dismissOnMouseUp = dismissOnMouseUp;
  49524. for (int i = 0; i < menu.items.size(); ++i)
  49525. {
  49526. MenuItemInfo* const item = (MenuItemInfo*) menu.items.getUnchecked(i);
  49527. mw->addItem (*item);
  49528. ++totalItems;
  49529. }
  49530. if (totalItems == 0)
  49531. {
  49532. delete mw;
  49533. }
  49534. else
  49535. {
  49536. mw->owner = owner_;
  49537. mw->menuBarComponent = menuBarComponent;
  49538. mw->managerOfChosenCommand = managerOfChosenCommand;
  49539. mw->componentAttachedTo = componentAttachedTo;
  49540. delete mw->attachedCompWatcher;
  49541. mw->attachedCompWatcher = componentAttachedTo != 0 ? new ComponentDeletionWatcher (componentAttachedTo) : 0;
  49542. mw->calculateWindowPos (minX, maxX, minY, maxY, alignToRectangle);
  49543. mw->setTopLeftPosition (mw->windowPos.getX(),
  49544. mw->windowPos.getY());
  49545. mw->updateYPositions();
  49546. if (itemIdThatMustBeVisible != 0)
  49547. {
  49548. const int y = minY - mw->windowPos.getY();
  49549. mw->ensureItemIsVisible (itemIdThatMustBeVisible,
  49550. (((unsigned int) y) < (unsigned int) mw->windowPos.getHeight()) ? y : -1);
  49551. }
  49552. mw->resizeToBestWindowPos();
  49553. mw->addToDesktop (ComponentPeer::windowIsTemporary
  49554. | mw->getLookAndFeel().getMenuWindowFlags());
  49555. return mw;
  49556. }
  49557. }
  49558. return 0;
  49559. }
  49560. void paint (Graphics& g)
  49561. {
  49562. getLookAndFeel().drawPopupMenuBackground (g, getWidth(), getHeight());
  49563. }
  49564. void paintOverChildren (Graphics& g)
  49565. {
  49566. if (isScrolling())
  49567. {
  49568. LookAndFeel& lf = getLookAndFeel();
  49569. if (isScrollZoneActive (false))
  49570. lf.drawPopupMenuUpDownArrow (g, getWidth(), scrollZone, true);
  49571. if (isScrollZoneActive (true))
  49572. {
  49573. g.setOrigin (0, getHeight() - scrollZone);
  49574. lf.drawPopupMenuUpDownArrow (g, getWidth(), scrollZone, false);
  49575. }
  49576. }
  49577. }
  49578. bool isScrollZoneActive (bool bottomOne) const
  49579. {
  49580. return isScrolling()
  49581. && (bottomOne
  49582. ? childYOffset < contentHeight - windowPos.getHeight()
  49583. : childYOffset > 0);
  49584. }
  49585. void addItem (const MenuItemInfo& item) throw()
  49586. {
  49587. MenuItemComponent* const mic = new MenuItemComponent (item);
  49588. addAndMakeVisible (mic);
  49589. int itemW = 80;
  49590. int itemH = 16;
  49591. mic->getIdealSize (itemW, itemH, standardItemHeight);
  49592. mic->setSize (itemW, jlimit (10, 600, itemH));
  49593. mic->addMouseListener (this, false);
  49594. }
  49595. // hide this and all sub-comps
  49596. void hide (const MenuItemInfo* const item) throw()
  49597. {
  49598. if (isVisible())
  49599. {
  49600. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  49601. deleteAndZero (activeSubMenu);
  49602. currentChild = 0;
  49603. exitModalState (item != 0 ? item->itemId : 0);
  49604. setVisible (false);
  49605. if (item != 0
  49606. && item->commandManager != 0
  49607. && item->itemId != 0)
  49608. {
  49609. *managerOfChosenCommand = item->commandManager;
  49610. }
  49611. }
  49612. }
  49613. void dismissMenu (const MenuItemInfo* const item) throw()
  49614. {
  49615. if (owner != 0)
  49616. {
  49617. owner->dismissMenu (item);
  49618. }
  49619. else
  49620. {
  49621. if (item != 0)
  49622. {
  49623. // need a copy of this on the stack as the one passed in will get deleted during this call
  49624. const MenuItemInfo mi (*item);
  49625. hide (&mi);
  49626. }
  49627. else
  49628. {
  49629. hide (0);
  49630. }
  49631. }
  49632. }
  49633. void mouseMove (const MouseEvent&)
  49634. {
  49635. timerCallback();
  49636. }
  49637. void mouseDown (const MouseEvent&)
  49638. {
  49639. timerCallback();
  49640. }
  49641. void mouseDrag (const MouseEvent&)
  49642. {
  49643. timerCallback();
  49644. }
  49645. void mouseUp (const MouseEvent&)
  49646. {
  49647. timerCallback();
  49648. }
  49649. void mouseWheelMove (const MouseEvent&, float /*amountX*/, float amountY)
  49650. {
  49651. alterChildYPos (roundFloatToInt (-10.0f * amountY * scrollZone));
  49652. lastMouseX = -1;
  49653. }
  49654. bool keyPressed (const KeyPress& key)
  49655. {
  49656. if (key.isKeyCode (KeyPress::downKey))
  49657. {
  49658. selectNextItem (1);
  49659. }
  49660. else if (key.isKeyCode (KeyPress::upKey))
  49661. {
  49662. selectNextItem (-1);
  49663. }
  49664. else if (key.isKeyCode (KeyPress::leftKey))
  49665. {
  49666. PopupMenuWindow* parentWindow = owner;
  49667. if (parentWindow != 0)
  49668. {
  49669. MenuItemComponent* currentChildOfParent
  49670. = (parentWindow != 0) ? parentWindow->currentChild : 0;
  49671. hide (0);
  49672. if (parentWindow->isValidComponent())
  49673. parentWindow->setCurrentlyHighlightedChild (currentChildOfParent);
  49674. disableTimerUntilMouseMoves();
  49675. }
  49676. else if (menuBarComponent != 0)
  49677. {
  49678. menuBarComponent->keyPressed (key);
  49679. }
  49680. }
  49681. else if (key.isKeyCode (KeyPress::rightKey))
  49682. {
  49683. disableTimerUntilMouseMoves();
  49684. if (showSubMenuFor (currentChild))
  49685. {
  49686. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  49687. if (activeSubMenu != 0 && activeSubMenu->isVisible())
  49688. activeSubMenu->selectNextItem (1);
  49689. }
  49690. else if (menuBarComponent != 0)
  49691. {
  49692. menuBarComponent->keyPressed (key);
  49693. }
  49694. }
  49695. else if (key.isKeyCode (KeyPress::returnKey))
  49696. {
  49697. triggerCurrentlyHighlightedItem();
  49698. }
  49699. else if (key.isKeyCode (KeyPress::escapeKey))
  49700. {
  49701. dismissMenu (0);
  49702. }
  49703. else
  49704. {
  49705. return false;
  49706. }
  49707. return true;
  49708. }
  49709. void inputAttemptWhenModal()
  49710. {
  49711. timerCallback();
  49712. if (! isOverAnyMenu())
  49713. {
  49714. if (componentAttachedTo != 0 && ! attachedCompWatcher->hasBeenDeleted())
  49715. {
  49716. // we want to dismiss the menu, but if we do it synchronously, then
  49717. // the mouse-click will be allowed to pass through. That's good, except
  49718. // when the user clicks on the button that orginally popped the menu up,
  49719. // as they'll expect the menu to go away, and in fact it'll just
  49720. // come back. So only dismiss synchronously if they're not on the original
  49721. // comp that we're attached to.
  49722. int mx, my;
  49723. componentAttachedTo->getMouseXYRelative (mx, my);
  49724. if (componentAttachedTo->reallyContains (mx, my, true))
  49725. {
  49726. postCommandMessage (dismissCommandId); // dismiss asynchrounously
  49727. return;
  49728. }
  49729. }
  49730. dismissMenu (0);
  49731. }
  49732. }
  49733. void handleCommandMessage (int commandId)
  49734. {
  49735. Component::handleCommandMessage (commandId);
  49736. if (commandId == dismissCommandId)
  49737. dismissMenu (0);
  49738. }
  49739. void timerCallback()
  49740. {
  49741. if (! isVisible())
  49742. return;
  49743. if (attachedCompWatcher != 0 && attachedCompWatcher->hasBeenDeleted())
  49744. {
  49745. dismissMenu (0);
  49746. return;
  49747. }
  49748. PopupMenuWindow* currentlyModalWindow = dynamic_cast <PopupMenuWindow*> (Component::getCurrentlyModalComponent());
  49749. if (currentlyModalWindow != 0 && ! treeContains (currentlyModalWindow))
  49750. return;
  49751. startTimer (timerInterval); // do this in case it was called from a mouse
  49752. // move rather than a real timer callback
  49753. int mx, my;
  49754. Desktop::getMousePosition (mx, my);
  49755. int x = mx, y = my;
  49756. globalPositionToRelative (x, y);
  49757. const uint32 now = Time::getMillisecondCounter();
  49758. if (now > timeEnteredCurrentChildComp + 100
  49759. && reallyContains (x, y, true)
  49760. && currentChild->isValidComponent()
  49761. && (! disableMouseMoves)
  49762. && ! (activeSubMenu != 0 && activeSubMenu->isVisible()))
  49763. {
  49764. showSubMenuFor (currentChild);
  49765. }
  49766. if (mx != lastMouseX || my != lastMouseY || now > lastMouseMoveTime + 350)
  49767. {
  49768. highlightItemUnderMouse (mx, my, x, y);
  49769. }
  49770. bool overScrollArea = false;
  49771. if (isScrolling()
  49772. && (isOver || (isDown && ((unsigned int) x) < (unsigned int) getWidth()))
  49773. && ((isScrollZoneActive (false) && y < scrollZone)
  49774. || (isScrollZoneActive (true) && y > getHeight() - scrollZone)))
  49775. {
  49776. if (now > lastScroll + 20)
  49777. {
  49778. scrollAcceleration = jmin (4.0, scrollAcceleration * 1.04);
  49779. int amount = 0;
  49780. for (int i = 0; i < getNumChildComponents() && amount == 0; ++i)
  49781. amount = ((int) scrollAcceleration) * getChildComponent (i)->getHeight();
  49782. alterChildYPos (y < scrollZone ? -amount : amount);
  49783. lastScroll = now;
  49784. }
  49785. overScrollArea = true;
  49786. lastMouseX = -1; // trigger a mouse-move
  49787. }
  49788. else
  49789. {
  49790. scrollAcceleration = 1.0;
  49791. }
  49792. const bool wasDown = isDown;
  49793. bool isOverAny = isOverAnyMenu();
  49794. if (hideOnExit && hasBeenOver && (! isOverAny) && activeSubMenu != 0)
  49795. {
  49796. activeSubMenu->updateMouseOverStatus (mx, my);
  49797. isOverAny = isOverAnyMenu();
  49798. }
  49799. if (hideOnExit && hasBeenOver && ! isOverAny)
  49800. {
  49801. hide (0);
  49802. }
  49803. else
  49804. {
  49805. isDown = hasBeenOver
  49806. && (ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown()
  49807. || ModifierKeys::getCurrentModifiersRealtime().isAnyMouseButtonDown());
  49808. bool anyFocused = Process::isForegroundProcess();
  49809. if (anyFocused && Component::getCurrentlyFocusedComponent() == 0)
  49810. {
  49811. // because no component at all may have focus, our test here will
  49812. // only be triggered when something has focus and then loses it.
  49813. anyFocused = ! hasAnyJuceCompHadFocus;
  49814. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  49815. {
  49816. if (ComponentPeer::getPeer (i)->isFocused())
  49817. {
  49818. anyFocused = true;
  49819. hasAnyJuceCompHadFocus = true;
  49820. break;
  49821. }
  49822. }
  49823. }
  49824. if (! anyFocused)
  49825. {
  49826. if (now > lastFocused + 10)
  49827. {
  49828. wasHiddenBecauseOfAppChange = true;
  49829. dismissMenu (0);
  49830. return; // may have been deleted by the previous call..
  49831. }
  49832. }
  49833. else if (wasDown && now > menuCreationTime + 250
  49834. && ! (isDown || overScrollArea))
  49835. {
  49836. isOver = reallyContains (x, y, true);
  49837. if (isOver)
  49838. {
  49839. triggerCurrentlyHighlightedItem();
  49840. }
  49841. else if ((hasBeenOver || ! dismissOnMouseUp) && ! isOverAny)
  49842. {
  49843. dismissMenu (0);
  49844. }
  49845. return; // may have been deleted by the previous calls..
  49846. }
  49847. else
  49848. {
  49849. lastFocused = now;
  49850. }
  49851. }
  49852. }
  49853. juce_UseDebuggingNewOperator
  49854. private:
  49855. PopupMenuWindow* owner;
  49856. MenuItemComponent* currentChild;
  49857. PopupMenuWindow* activeSubMenu;
  49858. Component* menuBarComponent;
  49859. ApplicationCommandManager** managerOfChosenCommand;
  49860. Component* componentAttachedTo;
  49861. ComponentDeletionWatcher* attachedCompWatcher;
  49862. Rectangle windowPos;
  49863. int lastMouseX, lastMouseY;
  49864. int minimumWidth, maximumNumColumns, standardItemHeight;
  49865. bool isOver, hasBeenOver, isDown, needsToScroll;
  49866. bool dismissOnMouseUp, hideOnExit, disableMouseMoves, hasAnyJuceCompHadFocus;
  49867. int numColumns, contentHeight, childYOffset;
  49868. Array <int> columnWidths;
  49869. uint32 menuCreationTime, lastFocused, lastScroll, lastMouseMoveTime, timeEnteredCurrentChildComp;
  49870. double scrollAcceleration;
  49871. bool overlaps (const Rectangle& r) const throw()
  49872. {
  49873. return r.intersects (getBounds())
  49874. || (owner != 0 && owner->overlaps (r));
  49875. }
  49876. bool isOverAnyMenu() const throw()
  49877. {
  49878. return (owner != 0) ? owner->isOverAnyMenu()
  49879. : isOverChildren();
  49880. }
  49881. bool isOverChildren() const throw()
  49882. {
  49883. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  49884. return isVisible()
  49885. && (isOver || (activeSubMenu != 0 && activeSubMenu->isOverChildren()));
  49886. }
  49887. void updateMouseOverStatus (const int mx, const int my) throw()
  49888. {
  49889. int rx = mx, ry = my;
  49890. globalPositionToRelative (rx, ry);
  49891. isOver = reallyContains (rx, ry, true);
  49892. if (activeSubMenu != 0)
  49893. activeSubMenu->updateMouseOverStatus (mx, my);
  49894. }
  49895. bool treeContains (const PopupMenuWindow* const window) const throw()
  49896. {
  49897. const PopupMenuWindow* mw = this;
  49898. while (mw->owner != 0)
  49899. mw = mw->owner;
  49900. while (mw != 0)
  49901. {
  49902. if (mw == window)
  49903. return true;
  49904. mw = mw->activeSubMenu;
  49905. }
  49906. return false;
  49907. }
  49908. void calculateWindowPos (const int minX, const int maxX,
  49909. const int minY, const int maxY,
  49910. const bool alignToRectangle)
  49911. {
  49912. const Rectangle mon (Desktop::getInstance()
  49913. .getMonitorAreaContaining ((minX + maxX) / 2,
  49914. (minY + maxY) / 2,
  49915. true));
  49916. int x, y, widthToUse, heightToUse;
  49917. layoutMenuItems (mon.getWidth() - 24, widthToUse, heightToUse);
  49918. if (alignToRectangle)
  49919. {
  49920. x = minX;
  49921. const int spaceUnder = mon.getHeight() - (maxY - mon.getY());
  49922. const int spaceOver = minY - mon.getY();
  49923. if (heightToUse < spaceUnder - 30 || spaceUnder >= spaceOver)
  49924. y = maxY;
  49925. else
  49926. y = minY - heightToUse;
  49927. }
  49928. else
  49929. {
  49930. bool tendTowardsRight = (minX + maxX) / 2 < mon.getCentreX();
  49931. if (owner != 0)
  49932. {
  49933. if (owner->owner != 0)
  49934. {
  49935. const bool ownerGoingRight = (owner->getX() + owner->getWidth() / 2
  49936. > owner->owner->getX() + owner->owner->getWidth() / 2);
  49937. if (ownerGoingRight && maxX + widthToUse < mon.getRight() - 4)
  49938. tendTowardsRight = true;
  49939. else if ((! ownerGoingRight) && minX > widthToUse + 4)
  49940. tendTowardsRight = false;
  49941. }
  49942. else if (maxX + widthToUse < mon.getRight() - 32)
  49943. {
  49944. tendTowardsRight = true;
  49945. }
  49946. }
  49947. const int biggestSpace = jmax (mon.getRight() - maxX,
  49948. minX - mon.getX()) - 32;
  49949. if (biggestSpace < widthToUse)
  49950. {
  49951. layoutMenuItems (biggestSpace + (maxX - minX) / 3, widthToUse, heightToUse);
  49952. if (numColumns > 1)
  49953. layoutMenuItems (biggestSpace - 4, widthToUse, heightToUse);
  49954. tendTowardsRight = (mon.getRight() - maxX) >= (minX - mon.getX());
  49955. }
  49956. if (tendTowardsRight)
  49957. x = jmin (mon.getRight() - widthToUse - 4, maxX);
  49958. else
  49959. x = jmax (mon.getX() + 4, minX - widthToUse);
  49960. y = minY;
  49961. if ((minY + maxY) / 2 > mon.getCentreY())
  49962. y = jmax (mon.getY(), maxY - heightToUse);
  49963. }
  49964. x = jlimit (mon.getX() + 1, mon.getRight() - (widthToUse + 6), x);
  49965. y = jlimit (mon.getY() + 1, mon.getBottom() - (heightToUse + 6), y);
  49966. windowPos.setBounds (x, y, widthToUse, heightToUse);
  49967. // sets this flag if it's big enough to obscure any of its parent menus
  49968. hideOnExit = (owner != 0)
  49969. && owner->windowPos.intersects (windowPos.expanded (-4, -4));
  49970. }
  49971. void layoutMenuItems (const int maxMenuW, int& width, int& height)
  49972. {
  49973. numColumns = 0;
  49974. contentHeight = 0;
  49975. const int maxMenuH = getParentHeight() - 24;
  49976. int totalW;
  49977. do
  49978. {
  49979. ++numColumns;
  49980. totalW = workOutBestSize (numColumns, maxMenuW);
  49981. if (totalW > maxMenuW)
  49982. {
  49983. numColumns = jmax (1, numColumns - 1);
  49984. totalW = workOutBestSize (numColumns, maxMenuW); // to update col widths
  49985. break;
  49986. }
  49987. else if (totalW > maxMenuW / 2 || contentHeight < maxMenuH)
  49988. {
  49989. break;
  49990. }
  49991. } while (numColumns < maximumNumColumns);
  49992. const int actualH = jmin (contentHeight, maxMenuH);
  49993. needsToScroll = contentHeight > actualH;
  49994. width = updateYPositions();
  49995. height = actualH + borderSize * 2;
  49996. }
  49997. int workOutBestSize (const int numColumns, const int maxMenuW)
  49998. {
  49999. int totalW = 0;
  50000. contentHeight = 0;
  50001. int childNum = 0;
  50002. for (int col = 0; col < numColumns; ++col)
  50003. {
  50004. int i, colW = 50, colH = 0;
  50005. const int numChildren = jmin (getNumChildComponents() - childNum,
  50006. (getNumChildComponents() + numColumns - 1) / numColumns);
  50007. for (i = numChildren; --i >= 0;)
  50008. {
  50009. colW = jmax (colW, getChildComponent (childNum + i)->getWidth());
  50010. colH += getChildComponent (childNum + i)->getHeight();
  50011. }
  50012. colW = jmin (maxMenuW / jmax (1, numColumns - 2), colW + borderSize * 2);
  50013. columnWidths.set (col, colW);
  50014. totalW += colW;
  50015. contentHeight = jmax (contentHeight, colH);
  50016. childNum += numChildren;
  50017. }
  50018. if (totalW < minimumWidth)
  50019. {
  50020. totalW = minimumWidth;
  50021. for (int col = 0; col < numColumns; ++col)
  50022. columnWidths.set (0, totalW / numColumns);
  50023. }
  50024. return totalW;
  50025. }
  50026. void ensureItemIsVisible (const int itemId, int wantedY)
  50027. {
  50028. jassert (itemId != 0)
  50029. for (int i = getNumChildComponents(); --i >= 0;)
  50030. {
  50031. MenuItemComponent* const m = (MenuItemComponent*) getChildComponent (i);
  50032. if (m != 0
  50033. && m->itemInfo.itemId == itemId
  50034. && windowPos.getHeight() > scrollZone * 4)
  50035. {
  50036. const int currentY = m->getY();
  50037. if (wantedY > 0 || currentY < 0 || m->getBottom() > windowPos.getHeight())
  50038. {
  50039. if (wantedY < 0)
  50040. wantedY = jlimit (scrollZone,
  50041. jmax (scrollZone, windowPos.getHeight() - (scrollZone + m->getHeight())),
  50042. currentY);
  50043. const Rectangle mon (Desktop::getInstance()
  50044. .getMonitorAreaContaining (windowPos.getX(),
  50045. windowPos.getY(),
  50046. true));
  50047. int deltaY = wantedY - currentY;
  50048. const int newY = jlimit (mon.getY(),
  50049. mon.getBottom() - windowPos.getHeight(),
  50050. windowPos.getY() + deltaY);
  50051. deltaY -= newY - windowPos.getY();
  50052. childYOffset -= deltaY;
  50053. windowPos.setPosition (windowPos.getX(), newY);
  50054. updateYPositions();
  50055. }
  50056. break;
  50057. }
  50058. }
  50059. }
  50060. void resizeToBestWindowPos()
  50061. {
  50062. Rectangle r (windowPos);
  50063. if (childYOffset < 0)
  50064. {
  50065. r.setBounds (r.getX(), r.getY() - childYOffset,
  50066. r.getWidth(), r.getHeight() + childYOffset);
  50067. }
  50068. else if (childYOffset > 0)
  50069. {
  50070. const int spaceAtBottom = r.getHeight() - (contentHeight - childYOffset);
  50071. if (spaceAtBottom > 0)
  50072. r.setSize (r.getWidth(), r.getHeight() - spaceAtBottom);
  50073. }
  50074. setBounds (r);
  50075. updateYPositions();
  50076. }
  50077. void alterChildYPos (const int delta)
  50078. {
  50079. if (isScrolling())
  50080. {
  50081. childYOffset += delta;
  50082. if (delta < 0)
  50083. {
  50084. childYOffset = jmax (childYOffset, 0);
  50085. }
  50086. else if (delta > 0)
  50087. {
  50088. childYOffset = jmin (childYOffset,
  50089. contentHeight - windowPos.getHeight() + borderSize);
  50090. }
  50091. updateYPositions();
  50092. }
  50093. else
  50094. {
  50095. childYOffset = 0;
  50096. }
  50097. resizeToBestWindowPos();
  50098. repaint();
  50099. }
  50100. int updateYPositions()
  50101. {
  50102. int x = 0;
  50103. int childNum = 0;
  50104. for (int col = 0; col < numColumns; ++col)
  50105. {
  50106. const int numChildren = jmin (getNumChildComponents() - childNum,
  50107. (getNumChildComponents() + numColumns - 1) / numColumns);
  50108. const int colW = columnWidths [col];
  50109. int y = borderSize - (childYOffset + (getY() - windowPos.getY()));
  50110. for (int i = 0; i < numChildren; ++i)
  50111. {
  50112. Component* const c = getChildComponent (childNum + i);
  50113. c->setBounds (x, y, colW, c->getHeight());
  50114. y += c->getHeight();
  50115. }
  50116. x += colW;
  50117. childNum += numChildren;
  50118. }
  50119. return x;
  50120. }
  50121. bool isScrolling() const throw()
  50122. {
  50123. return childYOffset != 0 || needsToScroll;
  50124. }
  50125. void setCurrentlyHighlightedChild (MenuItemComponent* const child) throw()
  50126. {
  50127. if (currentChild->isValidComponent())
  50128. currentChild->setHighlighted (false);
  50129. currentChild = child;
  50130. if (currentChild != 0)
  50131. {
  50132. currentChild->setHighlighted (true);
  50133. timeEnteredCurrentChildComp = Time::getApproximateMillisecondCounter();
  50134. }
  50135. }
  50136. bool showSubMenuFor (MenuItemComponent* const childComp)
  50137. {
  50138. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  50139. deleteAndZero (activeSubMenu);
  50140. if (childComp->isValidComponent() && childComp->itemInfo.hasActiveSubMenu())
  50141. {
  50142. int left = 0, top = 0;
  50143. childComp->relativePositionToGlobal (left, top);
  50144. int right = childComp->getWidth(), bottom = childComp->getHeight();
  50145. childComp->relativePositionToGlobal (right, bottom);
  50146. activeSubMenu = PopupMenuWindow::create (*(childComp->itemInfo.subMenu),
  50147. dismissOnMouseUp,
  50148. this,
  50149. left, right, top, bottom,
  50150. 0, maximumNumColumns,
  50151. standardItemHeight,
  50152. false, 0, menuBarComponent,
  50153. managerOfChosenCommand,
  50154. componentAttachedTo);
  50155. if (activeSubMenu != 0)
  50156. {
  50157. activeSubMenu->setVisible (true);
  50158. activeSubMenu->enterModalState (false);
  50159. activeSubMenu->toFront (false);
  50160. return true;
  50161. }
  50162. }
  50163. return false;
  50164. }
  50165. void highlightItemUnderMouse (const int mx, const int my, const int x, const int y)
  50166. {
  50167. isOver = reallyContains (x, y, true);
  50168. if (isOver)
  50169. hasBeenOver = true;
  50170. if (abs (lastMouseX - mx) > 2 || abs (lastMouseY - my) > 2)
  50171. {
  50172. lastMouseMoveTime = Time::getApproximateMillisecondCounter();
  50173. if (disableMouseMoves && isOver)
  50174. disableMouseMoves = false;
  50175. }
  50176. if (disableMouseMoves)
  50177. return;
  50178. bool isMovingTowardsMenu = false;
  50179. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent())
  50180. if (isOver && (activeSubMenu != 0) && (mx != lastMouseX || my != lastMouseY))
  50181. {
  50182. // try to intelligently guess whether the user is moving the mouse towards a currently-open
  50183. // submenu. To do this, look at whether the mouse stays inside a triangular region that
  50184. // extends from the last mouse pos to the submenu's rectangle..
  50185. float subX = (float) activeSubMenu->getScreenX();
  50186. if (activeSubMenu->getX() > getX())
  50187. {
  50188. lastMouseX -= 2; // to enlarge the triangle a bit, in case the mouse only moves a couple of pixels
  50189. }
  50190. else
  50191. {
  50192. lastMouseX += 2;
  50193. subX += activeSubMenu->getWidth();
  50194. }
  50195. Path areaTowardsSubMenu;
  50196. areaTowardsSubMenu.addTriangle ((float) lastMouseX,
  50197. (float) lastMouseY,
  50198. subX,
  50199. (float) activeSubMenu->getScreenY(),
  50200. subX,
  50201. (float) (activeSubMenu->getScreenY() + activeSubMenu->getHeight()));
  50202. isMovingTowardsMenu = areaTowardsSubMenu.contains ((float) mx, (float) my);
  50203. }
  50204. lastMouseX = mx;
  50205. lastMouseY = my;
  50206. if (! isMovingTowardsMenu)
  50207. {
  50208. Component* c = getComponentAt (x, y);
  50209. if (c == this)
  50210. c = 0;
  50211. MenuItemComponent* mic = dynamic_cast <MenuItemComponent*> (c);
  50212. if (mic == 0 && c != 0)
  50213. mic = c->findParentComponentOfClass ((MenuItemComponent*) 0);
  50214. if (mic != currentChild
  50215. && (isOver || (activeSubMenu == 0) || ! activeSubMenu->isVisible()))
  50216. {
  50217. if (isOver && (c != 0) && (activeSubMenu != 0))
  50218. {
  50219. activeSubMenu->hide (0);
  50220. }
  50221. if (! isOver)
  50222. mic = 0;
  50223. setCurrentlyHighlightedChild (mic);
  50224. }
  50225. }
  50226. }
  50227. void triggerCurrentlyHighlightedItem()
  50228. {
  50229. if (currentChild->isValidComponent()
  50230. && currentChild->itemInfo.canBeTriggered()
  50231. && (currentChild->itemInfo.customComp == 0
  50232. || currentChild->itemInfo.customComp->isTriggeredAutomatically))
  50233. {
  50234. dismissMenu (&currentChild->itemInfo);
  50235. }
  50236. }
  50237. void selectNextItem (const int delta)
  50238. {
  50239. disableTimerUntilMouseMoves();
  50240. MenuItemComponent* mic = 0;
  50241. bool wasLastOne = (currentChild == 0);
  50242. const int numItems = getNumChildComponents();
  50243. for (int i = 0; i < numItems + 1; ++i)
  50244. {
  50245. int index = (delta > 0) ? i : (numItems - 1 - i);
  50246. index = (index + numItems) % numItems;
  50247. mic = dynamic_cast <MenuItemComponent*> (getChildComponent (index));
  50248. if (mic != 0 && (mic->itemInfo.canBeTriggered() || mic->itemInfo.hasActiveSubMenu())
  50249. && wasLastOne)
  50250. break;
  50251. if (mic == currentChild)
  50252. wasLastOne = true;
  50253. }
  50254. setCurrentlyHighlightedChild (mic);
  50255. }
  50256. void disableTimerUntilMouseMoves() throw()
  50257. {
  50258. disableMouseMoves = true;
  50259. if (owner != 0)
  50260. owner->disableTimerUntilMouseMoves();
  50261. }
  50262. PopupMenuWindow (const PopupMenuWindow&);
  50263. const PopupMenuWindow& operator= (const PopupMenuWindow&);
  50264. };
  50265. PopupMenu::PopupMenu() throw()
  50266. : items (8),
  50267. lookAndFeel (0),
  50268. separatorPending (false)
  50269. {
  50270. }
  50271. PopupMenu::PopupMenu (const PopupMenu& other) throw()
  50272. : items (8),
  50273. lookAndFeel (other.lookAndFeel),
  50274. separatorPending (false)
  50275. {
  50276. items.ensureStorageAllocated (other.items.size());
  50277. for (int i = 0; i < other.items.size(); ++i)
  50278. items.add (new MenuItemInfo (*(const MenuItemInfo*) other.items.getUnchecked(i)));
  50279. }
  50280. const PopupMenu& PopupMenu::operator= (const PopupMenu& other) throw()
  50281. {
  50282. if (this != &other)
  50283. {
  50284. lookAndFeel = other.lookAndFeel;
  50285. clear();
  50286. items.ensureStorageAllocated (other.items.size());
  50287. for (int i = 0; i < other.items.size(); ++i)
  50288. items.add (new MenuItemInfo (*(const MenuItemInfo*) other.items.getUnchecked(i)));
  50289. }
  50290. return *this;
  50291. }
  50292. PopupMenu::~PopupMenu() throw()
  50293. {
  50294. clear();
  50295. }
  50296. void PopupMenu::clear() throw()
  50297. {
  50298. for (int i = items.size(); --i >= 0;)
  50299. {
  50300. MenuItemInfo* const mi = (MenuItemInfo*) items.getUnchecked(i);
  50301. delete mi;
  50302. }
  50303. items.clear();
  50304. separatorPending = false;
  50305. }
  50306. void PopupMenu::addSeparatorIfPending()
  50307. {
  50308. if (separatorPending)
  50309. {
  50310. separatorPending = false;
  50311. if (items.size() > 0)
  50312. items.add (new MenuItemInfo());
  50313. }
  50314. }
  50315. void PopupMenu::addItem (const int itemResultId,
  50316. const String& itemText,
  50317. const bool isActive,
  50318. const bool isTicked,
  50319. const Image* const iconToUse) throw()
  50320. {
  50321. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  50322. // didn't pick anything, so you shouldn't use it as the id
  50323. // for an item..
  50324. addSeparatorIfPending();
  50325. items.add (new MenuItemInfo (itemResultId,
  50326. itemText,
  50327. isActive,
  50328. isTicked,
  50329. iconToUse,
  50330. Colours::black,
  50331. false,
  50332. 0, 0, 0));
  50333. }
  50334. void PopupMenu::addCommandItem (ApplicationCommandManager* commandManager,
  50335. const int commandID,
  50336. const String& displayName) throw()
  50337. {
  50338. jassert (commandManager != 0 && commandID != 0);
  50339. const ApplicationCommandInfo* const registeredInfo = commandManager->getCommandForID (commandID);
  50340. if (registeredInfo != 0)
  50341. {
  50342. ApplicationCommandInfo info (*registeredInfo);
  50343. ApplicationCommandTarget* const target = commandManager->getTargetForCommand (commandID, info);
  50344. addSeparatorIfPending();
  50345. items.add (new MenuItemInfo (commandID,
  50346. displayName.isNotEmpty() ? displayName
  50347. : info.shortName,
  50348. target != 0 && (info.flags & ApplicationCommandInfo::isDisabled) == 0,
  50349. (info.flags & ApplicationCommandInfo::isTicked) != 0,
  50350. 0,
  50351. Colours::black,
  50352. false,
  50353. 0, 0,
  50354. commandManager));
  50355. }
  50356. }
  50357. void PopupMenu::addColouredItem (const int itemResultId,
  50358. const String& itemText,
  50359. const Colour& itemTextColour,
  50360. const bool isActive,
  50361. const bool isTicked,
  50362. const Image* const iconToUse) throw()
  50363. {
  50364. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  50365. // didn't pick anything, so you shouldn't use it as the id
  50366. // for an item..
  50367. addSeparatorIfPending();
  50368. items.add (new MenuItemInfo (itemResultId,
  50369. itemText,
  50370. isActive,
  50371. isTicked,
  50372. iconToUse,
  50373. itemTextColour,
  50374. true,
  50375. 0, 0, 0));
  50376. }
  50377. void PopupMenu::addCustomItem (const int itemResultId,
  50378. PopupMenuCustomComponent* const customComponent) throw()
  50379. {
  50380. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  50381. // didn't pick anything, so you shouldn't use it as the id
  50382. // for an item..
  50383. addSeparatorIfPending();
  50384. items.add (new MenuItemInfo (itemResultId,
  50385. String::empty,
  50386. true,
  50387. false,
  50388. 0,
  50389. Colours::black,
  50390. false,
  50391. customComponent,
  50392. 0, 0));
  50393. }
  50394. class NormalComponentWrapper : public PopupMenuCustomComponent
  50395. {
  50396. public:
  50397. NormalComponentWrapper (Component* const comp,
  50398. const int w, const int h,
  50399. const bool triggerMenuItemAutomaticallyWhenClicked)
  50400. : PopupMenuCustomComponent (triggerMenuItemAutomaticallyWhenClicked),
  50401. width (w),
  50402. height (h)
  50403. {
  50404. addAndMakeVisible (comp);
  50405. }
  50406. ~NormalComponentWrapper() {}
  50407. void getIdealSize (int& idealWidth, int& idealHeight)
  50408. {
  50409. idealWidth = width;
  50410. idealHeight = height;
  50411. }
  50412. void resized()
  50413. {
  50414. if (getChildComponent(0) != 0)
  50415. getChildComponent(0)->setBounds (0, 0, getWidth(), getHeight());
  50416. }
  50417. juce_UseDebuggingNewOperator
  50418. private:
  50419. const int width, height;
  50420. NormalComponentWrapper (const NormalComponentWrapper&);
  50421. const NormalComponentWrapper& operator= (const NormalComponentWrapper&);
  50422. };
  50423. void PopupMenu::addCustomItem (const int itemResultId,
  50424. Component* customComponent,
  50425. int idealWidth, int idealHeight,
  50426. const bool triggerMenuItemAutomaticallyWhenClicked) throw()
  50427. {
  50428. addCustomItem (itemResultId,
  50429. new NormalComponentWrapper (customComponent,
  50430. idealWidth, idealHeight,
  50431. triggerMenuItemAutomaticallyWhenClicked));
  50432. }
  50433. void PopupMenu::addSubMenu (const String& subMenuName,
  50434. const PopupMenu& subMenu,
  50435. const bool isActive,
  50436. Image* const iconToUse) throw()
  50437. {
  50438. addSeparatorIfPending();
  50439. items.add (new MenuItemInfo (0,
  50440. subMenuName,
  50441. isActive && (subMenu.getNumItems() > 0),
  50442. false,
  50443. iconToUse,
  50444. Colours::black,
  50445. false,
  50446. 0,
  50447. &subMenu,
  50448. 0));
  50449. }
  50450. void PopupMenu::addSeparator() throw()
  50451. {
  50452. separatorPending = true;
  50453. }
  50454. class HeaderItemComponent : public PopupMenuCustomComponent
  50455. {
  50456. public:
  50457. HeaderItemComponent (const String& name)
  50458. : PopupMenuCustomComponent (false)
  50459. {
  50460. setName (name);
  50461. }
  50462. ~HeaderItemComponent()
  50463. {
  50464. }
  50465. void paint (Graphics& g)
  50466. {
  50467. Font f (getLookAndFeel().getPopupMenuFont());
  50468. f.setBold (true);
  50469. g.setFont (f);
  50470. g.setColour (findColour (PopupMenu::headerTextColourId));
  50471. g.drawFittedText (getName(),
  50472. 12, 0, getWidth() - 16, proportionOfHeight (0.8f),
  50473. Justification::bottomLeft, 1);
  50474. }
  50475. void getIdealSize (int& idealWidth,
  50476. int& idealHeight)
  50477. {
  50478. getLookAndFeel().getIdealPopupMenuItemSize (getName(), false, -1, idealWidth, idealHeight);
  50479. idealHeight += idealHeight / 2;
  50480. idealWidth += idealWidth / 4;
  50481. }
  50482. juce_UseDebuggingNewOperator
  50483. };
  50484. void PopupMenu::addSectionHeader (const String& title) throw()
  50485. {
  50486. addCustomItem (0X4734a34f, new HeaderItemComponent (title));
  50487. }
  50488. Component* PopupMenu::createMenuComponent (const int x, const int y, const int w, const int h,
  50489. const int itemIdThatMustBeVisible,
  50490. const int minimumWidth,
  50491. const int maximumNumColumns,
  50492. const int standardItemHeight,
  50493. const bool alignToRectangle,
  50494. Component* menuBarComponent,
  50495. ApplicationCommandManager** managerOfChosenCommand,
  50496. Component* const componentAttachedTo) throw()
  50497. {
  50498. PopupMenuWindow* const pw
  50499. = PopupMenuWindow::create (*this,
  50500. ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown(),
  50501. 0,
  50502. x, x + w,
  50503. y, y + h,
  50504. minimumWidth,
  50505. maximumNumColumns,
  50506. standardItemHeight,
  50507. alignToRectangle,
  50508. itemIdThatMustBeVisible,
  50509. menuBarComponent,
  50510. managerOfChosenCommand,
  50511. componentAttachedTo);
  50512. if (pw != 0)
  50513. pw->setVisible (true);
  50514. return pw;
  50515. }
  50516. int PopupMenu::showMenu (const int x, const int y, const int w, const int h,
  50517. const int itemIdThatMustBeVisible,
  50518. const int minimumWidth,
  50519. const int maximumNumColumns,
  50520. const int standardItemHeight,
  50521. const bool alignToRectangle,
  50522. Component* const componentAttachedTo) throw()
  50523. {
  50524. Component* const prevFocused = Component::getCurrentlyFocusedComponent();
  50525. ComponentDeletionWatcher* deletionChecker1 = 0;
  50526. if (prevFocused != 0)
  50527. deletionChecker1 = new ComponentDeletionWatcher (prevFocused);
  50528. Component* const prevTopLevel = (prevFocused != 0) ? prevFocused->getTopLevelComponent() : 0;
  50529. ComponentDeletionWatcher* deletionChecker2 = 0;
  50530. if (prevTopLevel != 0)
  50531. deletionChecker2 = new ComponentDeletionWatcher (prevTopLevel);
  50532. wasHiddenBecauseOfAppChange = false;
  50533. int result = 0;
  50534. ApplicationCommandManager* managerOfChosenCommand = 0;
  50535. Component* const popupComp = createMenuComponent (x, y, w, h,
  50536. itemIdThatMustBeVisible,
  50537. minimumWidth,
  50538. maximumNumColumns > 0 ? maximumNumColumns : 7,
  50539. standardItemHeight,
  50540. alignToRectangle, 0,
  50541. &managerOfChosenCommand,
  50542. componentAttachedTo);
  50543. if (popupComp != 0)
  50544. {
  50545. popupComp->enterModalState (false);
  50546. popupComp->toFront (false); // need to do this after making it modal, or it could
  50547. // be stuck behind other comps that are already modal..
  50548. result = popupComp->runModalLoop();
  50549. delete popupComp;
  50550. if (! wasHiddenBecauseOfAppChange)
  50551. {
  50552. if (deletionChecker2 != 0 && ! deletionChecker2->hasBeenDeleted())
  50553. prevTopLevel->toFront (true);
  50554. if (deletionChecker1 != 0 && ! deletionChecker1->hasBeenDeleted())
  50555. prevFocused->grabKeyboardFocus();
  50556. }
  50557. }
  50558. delete deletionChecker1;
  50559. delete deletionChecker2;
  50560. if (managerOfChosenCommand != 0 && result != 0)
  50561. {
  50562. ApplicationCommandTarget::InvocationInfo info (result);
  50563. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromMenu;
  50564. managerOfChosenCommand->invoke (info, true);
  50565. }
  50566. return result;
  50567. }
  50568. int PopupMenu::show (const int itemIdThatMustBeVisible,
  50569. const int minimumWidth,
  50570. const int maximumNumColumns,
  50571. const int standardItemHeight)
  50572. {
  50573. int x, y;
  50574. Desktop::getMousePosition (x, y);
  50575. return showAt (x, y,
  50576. itemIdThatMustBeVisible,
  50577. minimumWidth,
  50578. maximumNumColumns,
  50579. standardItemHeight);
  50580. }
  50581. int PopupMenu::showAt (const int screenX,
  50582. const int screenY,
  50583. const int itemIdThatMustBeVisible,
  50584. const int minimumWidth,
  50585. const int maximumNumColumns,
  50586. const int standardItemHeight)
  50587. {
  50588. return showMenu (screenX, screenY, 1, 1,
  50589. itemIdThatMustBeVisible,
  50590. minimumWidth, maximumNumColumns,
  50591. standardItemHeight,
  50592. false, 0);
  50593. }
  50594. int PopupMenu::showAt (Component* componentToAttachTo,
  50595. const int itemIdThatMustBeVisible,
  50596. const int minimumWidth,
  50597. const int maximumNumColumns,
  50598. const int standardItemHeight)
  50599. {
  50600. if (componentToAttachTo != 0)
  50601. {
  50602. return showMenu (componentToAttachTo->getScreenX(),
  50603. componentToAttachTo->getScreenY(),
  50604. componentToAttachTo->getWidth(),
  50605. componentToAttachTo->getHeight(),
  50606. itemIdThatMustBeVisible,
  50607. minimumWidth,
  50608. maximumNumColumns,
  50609. standardItemHeight,
  50610. true, componentToAttachTo);
  50611. }
  50612. else
  50613. {
  50614. return show (itemIdThatMustBeVisible,
  50615. minimumWidth,
  50616. maximumNumColumns,
  50617. standardItemHeight);
  50618. }
  50619. }
  50620. void JUCE_CALLTYPE PopupMenu::dismissAllActiveMenus() throw()
  50621. {
  50622. for (int i = activeMenuWindows.size(); --i >= 0;)
  50623. {
  50624. PopupMenuWindow* const pmw = (PopupMenuWindow*) activeMenuWindows[i];
  50625. if (pmw != 0)
  50626. pmw->dismissMenu (0);
  50627. }
  50628. }
  50629. int PopupMenu::getNumItems() const throw()
  50630. {
  50631. int num = 0;
  50632. for (int i = items.size(); --i >= 0;)
  50633. if (! ((MenuItemInfo*) items.getUnchecked(i))->isSeparator)
  50634. ++num;
  50635. return num;
  50636. }
  50637. bool PopupMenu::containsCommandItem (const int commandID) const throw()
  50638. {
  50639. for (int i = items.size(); --i >= 0;)
  50640. {
  50641. const MenuItemInfo* mi = (const MenuItemInfo*) items.getUnchecked (i);
  50642. if ((mi->itemId == commandID && mi->commandManager != 0)
  50643. || (mi->subMenu != 0 && mi->subMenu->containsCommandItem (commandID)))
  50644. {
  50645. return true;
  50646. }
  50647. }
  50648. return false;
  50649. }
  50650. bool PopupMenu::containsAnyActiveItems() const throw()
  50651. {
  50652. for (int i = items.size(); --i >= 0;)
  50653. {
  50654. const MenuItemInfo* const mi = (const MenuItemInfo*) items.getUnchecked (i);
  50655. if (mi->subMenu != 0)
  50656. {
  50657. if (mi->subMenu->containsAnyActiveItems())
  50658. return true;
  50659. }
  50660. else if (mi->active)
  50661. {
  50662. return true;
  50663. }
  50664. }
  50665. return false;
  50666. }
  50667. void PopupMenu::setLookAndFeel (LookAndFeel* const newLookAndFeel) throw()
  50668. {
  50669. lookAndFeel = newLookAndFeel;
  50670. }
  50671. PopupMenuCustomComponent::PopupMenuCustomComponent (const bool isTriggeredAutomatically_)
  50672. : refCount_ (0),
  50673. isHighlighted (false),
  50674. isTriggeredAutomatically (isTriggeredAutomatically_)
  50675. {
  50676. }
  50677. PopupMenuCustomComponent::~PopupMenuCustomComponent()
  50678. {
  50679. jassert (refCount_ == 0); // should be deleted only by the menu component, as they keep a ref-count.
  50680. }
  50681. void PopupMenuCustomComponent::triggerMenuItem()
  50682. {
  50683. MenuItemComponent* const mic = dynamic_cast<MenuItemComponent*> (getParentComponent());
  50684. if (mic != 0)
  50685. {
  50686. PopupMenuWindow* const pmw = dynamic_cast<PopupMenuWindow*> (mic->getParentComponent());
  50687. if (pmw != 0)
  50688. {
  50689. pmw->dismissMenu (&mic->itemInfo);
  50690. }
  50691. else
  50692. {
  50693. // something must have gone wrong with the component hierarchy if this happens..
  50694. jassertfalse
  50695. }
  50696. }
  50697. else
  50698. {
  50699. // why isn't this component inside a menu? Not much point triggering the item if
  50700. // there's no menu.
  50701. jassertfalse
  50702. }
  50703. }
  50704. PopupMenu::MenuItemIterator::MenuItemIterator (const PopupMenu& menu_) throw()
  50705. : subMenu (0),
  50706. itemId (0),
  50707. isSeparator (false),
  50708. isTicked (false),
  50709. isEnabled (false),
  50710. isCustomComponent (false),
  50711. isSectionHeader (false),
  50712. customColour (0),
  50713. customImage (0),
  50714. menu (menu_),
  50715. index (0)
  50716. {
  50717. }
  50718. PopupMenu::MenuItemIterator::~MenuItemIterator() throw()
  50719. {
  50720. }
  50721. bool PopupMenu::MenuItemIterator::next() throw()
  50722. {
  50723. if (index >= menu.items.size())
  50724. return false;
  50725. const MenuItemInfo* const item = (const MenuItemInfo*) menu.items.getUnchecked (index);
  50726. ++index;
  50727. itemName = item->customComp != 0 ? item->customComp->getName() : item->text;
  50728. subMenu = item->subMenu;
  50729. itemId = item->itemId;
  50730. isSeparator = item->isSeparator;
  50731. isTicked = item->isTicked;
  50732. isEnabled = item->active;
  50733. isSectionHeader = dynamic_cast <HeaderItemComponent*> (item->customComp) != 0;
  50734. isCustomComponent = (! isSectionHeader) && item->customComp != 0;
  50735. customColour = item->usesColour ? &(item->textColour) : 0;
  50736. customImage = item->image;
  50737. commandManager = item->commandManager;
  50738. return true;
  50739. }
  50740. END_JUCE_NAMESPACE
  50741. /********* End of inlined file: juce_PopupMenu.cpp *********/
  50742. /********* Start of inlined file: juce_ComponentDragger.cpp *********/
  50743. BEGIN_JUCE_NAMESPACE
  50744. ComponentDragger::ComponentDragger()
  50745. : constrainer (0),
  50746. originalX (0),
  50747. originalY (0)
  50748. {
  50749. }
  50750. ComponentDragger::~ComponentDragger()
  50751. {
  50752. }
  50753. void ComponentDragger::startDraggingComponent (Component* const componentToDrag,
  50754. ComponentBoundsConstrainer* const constrainer_)
  50755. {
  50756. jassert (componentToDrag->isValidComponent());
  50757. if (componentToDrag->isValidComponent())
  50758. {
  50759. constrainer = constrainer_;
  50760. originalX = 0;
  50761. originalY = 0;
  50762. componentToDrag->relativePositionToGlobal (originalX, originalY);
  50763. }
  50764. }
  50765. void ComponentDragger::dragComponent (Component* const componentToDrag, const MouseEvent& e)
  50766. {
  50767. jassert (componentToDrag->isValidComponent());
  50768. jassert (e.mods.isAnyMouseButtonDown()); // (the event has to be a drag event..)
  50769. if (componentToDrag->isValidComponent())
  50770. {
  50771. int x = originalX + e.getDistanceFromDragStartX();
  50772. int y = originalY + e.getDistanceFromDragStartY();
  50773. int w = componentToDrag->getWidth();
  50774. int h = componentToDrag->getHeight();
  50775. const Component* const parentComp = componentToDrag->getParentComponent();
  50776. if (parentComp != 0)
  50777. parentComp->globalPositionToRelative (x, y);
  50778. if (constrainer != 0)
  50779. constrainer->setBoundsForComponent (componentToDrag, x, y, w, h,
  50780. false, false, false, false);
  50781. else
  50782. componentToDrag->setBounds (x, y, w, h);
  50783. }
  50784. }
  50785. END_JUCE_NAMESPACE
  50786. /********* End of inlined file: juce_ComponentDragger.cpp *********/
  50787. /********* Start of inlined file: juce_DragAndDropContainer.cpp *********/
  50788. BEGIN_JUCE_NAMESPACE
  50789. bool juce_performDragDropFiles (const StringArray& files, const bool copyFiles, bool& shouldStop);
  50790. bool juce_performDragDropText (const String& text, bool& shouldStop);
  50791. class DragImageComponent : public Component,
  50792. public Timer
  50793. {
  50794. private:
  50795. Image* image;
  50796. Component* const source;
  50797. DragAndDropContainer* const owner;
  50798. ComponentDeletionWatcher* sourceWatcher;
  50799. Component* mouseDragSource;
  50800. ComponentDeletionWatcher* mouseDragSourceWatcher;
  50801. DragAndDropTarget* currentlyOver;
  50802. String dragDesc;
  50803. int xOff, yOff;
  50804. bool hasCheckedForExternalDrag, drawImage;
  50805. DragImageComponent (const DragImageComponent&);
  50806. const DragImageComponent& operator= (const DragImageComponent&);
  50807. public:
  50808. DragImageComponent (Image* const im,
  50809. const String& desc,
  50810. Component* const s,
  50811. DragAndDropContainer* const o)
  50812. : image (im),
  50813. source (s),
  50814. owner (o),
  50815. currentlyOver (0),
  50816. dragDesc (desc),
  50817. hasCheckedForExternalDrag (false),
  50818. drawImage (true)
  50819. {
  50820. setSize (im->getWidth(), im->getHeight());
  50821. sourceWatcher = new ComponentDeletionWatcher (source);
  50822. mouseDragSource = Component::getComponentUnderMouse();
  50823. if (mouseDragSource == 0)
  50824. mouseDragSource = source;
  50825. mouseDragSourceWatcher = new ComponentDeletionWatcher (mouseDragSource);
  50826. mouseDragSource->addMouseListener (this, false);
  50827. int mx, my;
  50828. Desktop::getLastMouseDownPosition (mx, my);
  50829. source->globalPositionToRelative (mx, my);
  50830. xOff = jlimit (0, im->getWidth(), mx);
  50831. yOff = jlimit (0, im->getHeight(), my);
  50832. startTimer (200);
  50833. setInterceptsMouseClicks (false, false);
  50834. setAlwaysOnTop (true);
  50835. }
  50836. ~DragImageComponent()
  50837. {
  50838. if (owner->dragImageComponent == this)
  50839. owner->dragImageComponent = 0;
  50840. if (((Component*) currentlyOver)->isValidComponent())
  50841. {
  50842. Component* const over = dynamic_cast <Component*> (currentlyOver);
  50843. if (over != 0
  50844. && over->isValidComponent()
  50845. && source->isValidComponent()
  50846. && currentlyOver->isInterestedInDragSource (dragDesc, source))
  50847. {
  50848. currentlyOver->itemDragExit (dragDesc, source);
  50849. }
  50850. }
  50851. if (! mouseDragSourceWatcher->hasBeenDeleted())
  50852. mouseDragSource->removeMouseListener (this);
  50853. delete mouseDragSourceWatcher;
  50854. delete sourceWatcher;
  50855. delete image;
  50856. }
  50857. void paint (Graphics& g)
  50858. {
  50859. if (isOpaque())
  50860. g.fillAll (Colours::white);
  50861. if (drawImage)
  50862. {
  50863. g.setOpacity (1.0f);
  50864. g.drawImageAt (image, 0, 0);
  50865. }
  50866. }
  50867. DragAndDropTarget* findTarget (const int screenX, const int screenY,
  50868. int& relX, int& relY) const throw()
  50869. {
  50870. Component* hit = getParentComponent();
  50871. if (hit == 0)
  50872. {
  50873. hit = Desktop::getInstance().findComponentAt (screenX, screenY);
  50874. }
  50875. else
  50876. {
  50877. int rx = screenX, ry = screenY;
  50878. hit->globalPositionToRelative (rx, ry);
  50879. hit = hit->getComponentAt (rx, ry);
  50880. }
  50881. while (hit != 0)
  50882. {
  50883. DragAndDropTarget* const ddt = dynamic_cast <DragAndDropTarget*> (hit);
  50884. if (ddt != 0 && ddt->isInterestedInDragSource (dragDesc, source))
  50885. {
  50886. relX = screenX;
  50887. relY = screenY;
  50888. hit->globalPositionToRelative (relX, relY);
  50889. return ddt;
  50890. }
  50891. hit = hit->getParentComponent();
  50892. }
  50893. return 0;
  50894. }
  50895. void mouseUp (const MouseEvent& e)
  50896. {
  50897. if (e.originalComponent != this)
  50898. {
  50899. if (! mouseDragSourceWatcher->hasBeenDeleted())
  50900. mouseDragSource->removeMouseListener (this);
  50901. bool dropAccepted = false;
  50902. DragAndDropTarget* ddt = 0;
  50903. int relX = 0, relY = 0;
  50904. if (isVisible())
  50905. {
  50906. setVisible (false);
  50907. ddt = findTarget (e.getScreenX(),
  50908. e.getScreenY(),
  50909. relX, relY);
  50910. // fade this component and remove it - it'll be deleted later by the timer callback
  50911. dropAccepted = ddt != 0;
  50912. setVisible (true);
  50913. if (dropAccepted || sourceWatcher->hasBeenDeleted())
  50914. {
  50915. fadeOutComponent (120);
  50916. }
  50917. else
  50918. {
  50919. int targetX = source->getWidth() / 2;
  50920. int targetY = source->getHeight() / 2;
  50921. source->relativePositionToGlobal (targetX, targetY);
  50922. int ourCentreX = getWidth() / 2;
  50923. int ourCentreY = getHeight() / 2;
  50924. relativePositionToGlobal (ourCentreX, ourCentreY);
  50925. fadeOutComponent (120,
  50926. targetX - ourCentreX,
  50927. targetY - ourCentreY);
  50928. }
  50929. }
  50930. if (getParentComponent() != 0)
  50931. getParentComponent()->removeChildComponent (this);
  50932. if (dropAccepted && ddt != 0)
  50933. ddt->itemDropped (dragDesc, source, relX, relY);
  50934. // careful - this object could now be deleted..
  50935. }
  50936. }
  50937. void updateLocation (const bool canDoExternalDrag, int x, int y)
  50938. {
  50939. int newX = x - xOff;
  50940. int newY = y - yOff;
  50941. if (getParentComponent() != 0)
  50942. getParentComponent()->globalPositionToRelative (newX, newY);
  50943. if (newX != getX() || newY != getY())
  50944. {
  50945. setTopLeftPosition (newX, newY);
  50946. int relX = 0, relY = 0;
  50947. DragAndDropTarget* const ddt = findTarget (x, y, relX, relY);
  50948. drawImage = (ddt == 0) || ddt->shouldDrawDragImageWhenOver();
  50949. if (ddt != currentlyOver)
  50950. {
  50951. Component* const over = dynamic_cast <Component*> (currentlyOver);
  50952. if (over != 0
  50953. && over->isValidComponent()
  50954. && ! (sourceWatcher->hasBeenDeleted())
  50955. && currentlyOver->isInterestedInDragSource (dragDesc, source))
  50956. {
  50957. currentlyOver->itemDragExit (dragDesc, source);
  50958. }
  50959. currentlyOver = ddt;
  50960. if (currentlyOver != 0
  50961. && currentlyOver->isInterestedInDragSource (dragDesc, source))
  50962. currentlyOver->itemDragEnter (dragDesc, source, relX, relY);
  50963. }
  50964. if (currentlyOver != 0
  50965. && currentlyOver->isInterestedInDragSource (dragDesc, source))
  50966. currentlyOver->itemDragMove (dragDesc, source, relX, relY);
  50967. if (currentlyOver == 0
  50968. && canDoExternalDrag
  50969. && ! hasCheckedForExternalDrag)
  50970. {
  50971. if (Desktop::getInstance().findComponentAt (x, y) == 0)
  50972. {
  50973. hasCheckedForExternalDrag = true;
  50974. StringArray files;
  50975. bool canMoveFiles = false;
  50976. if (owner->shouldDropFilesWhenDraggedExternally (dragDesc, source, files, canMoveFiles)
  50977. && files.size() > 0)
  50978. {
  50979. ComponentDeletionWatcher cdw (this);
  50980. setVisible (false);
  50981. if (ModifierKeys::getCurrentModifiersRealtime().isAnyMouseButtonDown())
  50982. DragAndDropContainer::performExternalDragDropOfFiles (files, canMoveFiles);
  50983. if (! cdw.hasBeenDeleted())
  50984. delete this;
  50985. return;
  50986. }
  50987. }
  50988. }
  50989. }
  50990. }
  50991. void mouseDrag (const MouseEvent& e)
  50992. {
  50993. if (e.originalComponent != this)
  50994. updateLocation (true, e.getScreenX(), e.getScreenY());
  50995. }
  50996. void timerCallback()
  50997. {
  50998. if (sourceWatcher->hasBeenDeleted())
  50999. {
  51000. delete this;
  51001. }
  51002. else if (! isMouseButtonDownAnywhere())
  51003. {
  51004. if (! mouseDragSourceWatcher->hasBeenDeleted())
  51005. mouseDragSource->removeMouseListener (this);
  51006. delete this;
  51007. }
  51008. }
  51009. };
  51010. DragAndDropContainer::DragAndDropContainer()
  51011. : dragImageComponent (0)
  51012. {
  51013. }
  51014. DragAndDropContainer::~DragAndDropContainer()
  51015. {
  51016. if (dragImageComponent != 0)
  51017. delete dragImageComponent;
  51018. }
  51019. void DragAndDropContainer::startDragging (const String& sourceDescription,
  51020. Component* sourceComponent,
  51021. Image* im,
  51022. const bool allowDraggingToExternalWindows)
  51023. {
  51024. if (dragImageComponent != 0)
  51025. {
  51026. if (im != 0)
  51027. delete im;
  51028. }
  51029. else
  51030. {
  51031. Component* const thisComp = dynamic_cast <Component*> (this);
  51032. if (thisComp != 0)
  51033. {
  51034. int mx, my;
  51035. Desktop::getLastMouseDownPosition (mx, my);
  51036. if (im == 0)
  51037. {
  51038. im = sourceComponent->createComponentSnapshot (Rectangle (0, 0, sourceComponent->getWidth(), sourceComponent->getHeight()));
  51039. if (im->getFormat() != Image::ARGB)
  51040. {
  51041. Image* newIm = new Image (Image::ARGB, im->getWidth(), im->getHeight(), true);
  51042. Graphics g2 (*newIm);
  51043. g2.drawImageAt (im, 0, 0);
  51044. delete im;
  51045. im = newIm;
  51046. }
  51047. im->multiplyAllAlphas (0.6f);
  51048. const int lo = 150;
  51049. const int hi = 400;
  51050. int rx = mx, ry = my;
  51051. sourceComponent->globalPositionToRelative (rx, ry);
  51052. const int cx = jlimit (0, im->getWidth(), rx);
  51053. const int cy = jlimit (0, im->getHeight(), ry);
  51054. for (int y = im->getHeight(); --y >= 0;)
  51055. {
  51056. const double dy = (y - cy) * (y - cy);
  51057. for (int x = im->getWidth(); --x >= 0;)
  51058. {
  51059. const int dx = x - cx;
  51060. const int distance = roundDoubleToInt (sqrt (dx * dx + dy));
  51061. if (distance > lo)
  51062. {
  51063. const float alpha = (distance > hi) ? 0
  51064. : (hi - distance) / (float) (hi - lo)
  51065. + Random::getSystemRandom().nextFloat() * 0.008f;
  51066. im->multiplyAlphaAt (x, y, alpha);
  51067. }
  51068. }
  51069. }
  51070. }
  51071. DragImageComponent* const dic
  51072. = new DragImageComponent (im,
  51073. sourceDescription,
  51074. sourceComponent,
  51075. this);
  51076. dragImageComponent = dic;
  51077. currentDragDesc = sourceDescription;
  51078. if (allowDraggingToExternalWindows)
  51079. {
  51080. if (! Desktop::canUseSemiTransparentWindows())
  51081. dic->setOpaque (true);
  51082. dic->addToDesktop (ComponentPeer::windowIgnoresMouseClicks
  51083. | ComponentPeer::windowIsTemporary);
  51084. }
  51085. else
  51086. thisComp->addChildComponent (dic);
  51087. dic->updateLocation (false, mx, my);
  51088. dic->setVisible (true);
  51089. }
  51090. else
  51091. {
  51092. // this class must only be implemented by an object that
  51093. // is also a Component.
  51094. jassertfalse
  51095. if (im != 0)
  51096. delete im;
  51097. }
  51098. }
  51099. }
  51100. bool DragAndDropContainer::isDragAndDropActive() const
  51101. {
  51102. return dragImageComponent != 0;
  51103. }
  51104. const String DragAndDropContainer::getCurrentDragDescription() const
  51105. {
  51106. return (dragImageComponent != 0) ? currentDragDesc
  51107. : String::empty;
  51108. }
  51109. DragAndDropContainer* DragAndDropContainer::findParentDragContainerFor (Component* c)
  51110. {
  51111. if (c == 0)
  51112. return 0;
  51113. // (unable to use the syntax findParentComponentOfClass <DragAndDropContainer> () because of a VC6 compiler bug)
  51114. return c->findParentComponentOfClass ((DragAndDropContainer*) 0);
  51115. }
  51116. bool DragAndDropContainer::shouldDropFilesWhenDraggedExternally (const String&, Component*, StringArray&, bool&)
  51117. {
  51118. return false;
  51119. }
  51120. void DragAndDropTarget::itemDragEnter (const String&, Component*, int, int)
  51121. {
  51122. }
  51123. void DragAndDropTarget::itemDragMove (const String&, Component*, int, int)
  51124. {
  51125. }
  51126. void DragAndDropTarget::itemDragExit (const String&, Component*)
  51127. {
  51128. }
  51129. bool DragAndDropTarget::shouldDrawDragImageWhenOver()
  51130. {
  51131. return true;
  51132. }
  51133. void FileDragAndDropTarget::fileDragEnter (const StringArray&, int, int)
  51134. {
  51135. }
  51136. void FileDragAndDropTarget::fileDragMove (const StringArray&, int, int)
  51137. {
  51138. }
  51139. void FileDragAndDropTarget::fileDragExit (const StringArray&)
  51140. {
  51141. }
  51142. END_JUCE_NAMESPACE
  51143. /********* End of inlined file: juce_DragAndDropContainer.cpp *********/
  51144. /********* Start of inlined file: juce_MouseCursor.cpp *********/
  51145. BEGIN_JUCE_NAMESPACE
  51146. void* juce_createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) throw();
  51147. void* juce_createStandardMouseCursor (MouseCursor::StandardCursorType type) throw();
  51148. // isStandard set depending on which interface was used to create the cursor
  51149. void juce_deleteMouseCursor (void* const cursorHandle, const bool isStandard) throw();
  51150. static CriticalSection mouseCursorLock;
  51151. static VoidArray standardCursors (2);
  51152. class RefCountedMouseCursor
  51153. {
  51154. public:
  51155. RefCountedMouseCursor (const MouseCursor::StandardCursorType t) throw()
  51156. : refCount (1),
  51157. standardType (t),
  51158. isStandard (true)
  51159. {
  51160. handle = juce_createStandardMouseCursor (standardType);
  51161. standardCursors.add (this);
  51162. }
  51163. RefCountedMouseCursor (Image& image,
  51164. const int hotSpotX,
  51165. const int hotSpotY) throw()
  51166. : refCount (1),
  51167. standardType (MouseCursor::NormalCursor),
  51168. isStandard (false)
  51169. {
  51170. handle = juce_createMouseCursorFromImage (image, hotSpotX, hotSpotY);
  51171. }
  51172. ~RefCountedMouseCursor() throw()
  51173. {
  51174. juce_deleteMouseCursor (handle, isStandard);
  51175. standardCursors.removeValue (this);
  51176. }
  51177. void decRef() throw()
  51178. {
  51179. if (--refCount == 0)
  51180. delete this;
  51181. }
  51182. void incRef() throw()
  51183. {
  51184. ++refCount;
  51185. }
  51186. void* getHandle() const throw()
  51187. {
  51188. return handle;
  51189. }
  51190. static RefCountedMouseCursor* findInstance (MouseCursor::StandardCursorType type) throw()
  51191. {
  51192. const ScopedLock sl (mouseCursorLock);
  51193. for (int i = 0; i < standardCursors.size(); i++)
  51194. {
  51195. RefCountedMouseCursor* const r = (RefCountedMouseCursor*) standardCursors.getUnchecked(i);
  51196. if (r->standardType == type)
  51197. {
  51198. r->incRef();
  51199. return r;
  51200. }
  51201. }
  51202. return new RefCountedMouseCursor (type);
  51203. }
  51204. juce_UseDebuggingNewOperator
  51205. private:
  51206. void* handle;
  51207. int refCount;
  51208. const MouseCursor::StandardCursorType standardType;
  51209. const bool isStandard;
  51210. const RefCountedMouseCursor& operator= (const RefCountedMouseCursor&);
  51211. };
  51212. MouseCursor::MouseCursor() throw()
  51213. {
  51214. cursorHandle = RefCountedMouseCursor::findInstance (NormalCursor);
  51215. }
  51216. MouseCursor::MouseCursor (const StandardCursorType type) throw()
  51217. {
  51218. cursorHandle = RefCountedMouseCursor::findInstance (type);
  51219. }
  51220. MouseCursor::MouseCursor (Image& image,
  51221. const int hotSpotX,
  51222. const int hotSpotY) throw()
  51223. {
  51224. cursorHandle = new RefCountedMouseCursor (image, hotSpotX, hotSpotY);
  51225. }
  51226. MouseCursor::MouseCursor (const MouseCursor& other) throw()
  51227. : cursorHandle (other.cursorHandle)
  51228. {
  51229. const ScopedLock sl (mouseCursorLock);
  51230. cursorHandle->incRef();
  51231. }
  51232. MouseCursor::~MouseCursor() throw()
  51233. {
  51234. const ScopedLock sl (mouseCursorLock);
  51235. cursorHandle->decRef();
  51236. }
  51237. const MouseCursor& MouseCursor::operator= (const MouseCursor& other) throw()
  51238. {
  51239. if (this != &other)
  51240. {
  51241. const ScopedLock sl (mouseCursorLock);
  51242. cursorHandle->decRef();
  51243. cursorHandle = other.cursorHandle;
  51244. cursorHandle->incRef();
  51245. }
  51246. return *this;
  51247. }
  51248. bool MouseCursor::operator== (const MouseCursor& other) const throw()
  51249. {
  51250. return cursorHandle == other.cursorHandle;
  51251. }
  51252. bool MouseCursor::operator!= (const MouseCursor& other) const throw()
  51253. {
  51254. return cursorHandle != other.cursorHandle;
  51255. }
  51256. void* MouseCursor::getHandle() const throw()
  51257. {
  51258. return cursorHandle->getHandle();
  51259. }
  51260. void MouseCursor::showWaitCursor() throw()
  51261. {
  51262. const MouseCursor mc (MouseCursor::WaitCursor);
  51263. mc.showInAllWindows();
  51264. }
  51265. void MouseCursor::hideWaitCursor() throw()
  51266. {
  51267. if (Component::getComponentUnderMouse()->isValidComponent())
  51268. {
  51269. Component::getComponentUnderMouse()->getMouseCursor().showInAllWindows();
  51270. }
  51271. else
  51272. {
  51273. const MouseCursor mc (MouseCursor::NormalCursor);
  51274. mc.showInAllWindows();
  51275. }
  51276. }
  51277. END_JUCE_NAMESPACE
  51278. /********* End of inlined file: juce_MouseCursor.cpp *********/
  51279. /********* Start of inlined file: juce_MouseEvent.cpp *********/
  51280. BEGIN_JUCE_NAMESPACE
  51281. MouseEvent::MouseEvent (const int x_,
  51282. const int y_,
  51283. const ModifierKeys& mods_,
  51284. Component* const originator,
  51285. const Time& eventTime_,
  51286. const int mouseDownX_,
  51287. const int mouseDownY_,
  51288. const Time& mouseDownTime_,
  51289. const int numberOfClicks_,
  51290. const bool mouseWasDragged) throw()
  51291. : x (x_),
  51292. y (y_),
  51293. mods (mods_),
  51294. eventComponent (originator),
  51295. originalComponent (originator),
  51296. eventTime (eventTime_),
  51297. mouseDownX (mouseDownX_),
  51298. mouseDownY (mouseDownY_),
  51299. mouseDownTime (mouseDownTime_),
  51300. numberOfClicks (numberOfClicks_),
  51301. wasMovedSinceMouseDown (mouseWasDragged)
  51302. {
  51303. }
  51304. MouseEvent::~MouseEvent() throw()
  51305. {
  51306. }
  51307. bool MouseEvent::mouseWasClicked() const throw()
  51308. {
  51309. return ! wasMovedSinceMouseDown;
  51310. }
  51311. int MouseEvent::getMouseDownX() const throw()
  51312. {
  51313. return mouseDownX;
  51314. }
  51315. int MouseEvent::getMouseDownY() const throw()
  51316. {
  51317. return mouseDownY;
  51318. }
  51319. int MouseEvent::getDistanceFromDragStartX() const throw()
  51320. {
  51321. return x - mouseDownX;
  51322. }
  51323. int MouseEvent::getDistanceFromDragStartY() const throw()
  51324. {
  51325. return y - mouseDownY;
  51326. }
  51327. int MouseEvent::getDistanceFromDragStart() const throw()
  51328. {
  51329. return roundDoubleToInt (juce_hypot (getDistanceFromDragStartX(),
  51330. getDistanceFromDragStartY()));
  51331. }
  51332. int MouseEvent::getLengthOfMousePress() const throw()
  51333. {
  51334. if (mouseDownTime.toMilliseconds() > 0)
  51335. return jmax (0, (int) (eventTime - mouseDownTime).inMilliseconds());
  51336. return 0;
  51337. }
  51338. int MouseEvent::getScreenX() const throw()
  51339. {
  51340. int sx = x, sy = y;
  51341. eventComponent->relativePositionToGlobal (sx, sy);
  51342. return sx;
  51343. }
  51344. int MouseEvent::getScreenY() const throw()
  51345. {
  51346. int sx = x, sy = y;
  51347. eventComponent->relativePositionToGlobal (sx, sy);
  51348. return sy;
  51349. }
  51350. int MouseEvent::getMouseDownScreenX() const throw()
  51351. {
  51352. int sx = mouseDownX, sy = mouseDownY;
  51353. eventComponent->relativePositionToGlobal (sx, sy);
  51354. return sx;
  51355. }
  51356. int MouseEvent::getMouseDownScreenY() const throw()
  51357. {
  51358. int sx = mouseDownX, sy = mouseDownY;
  51359. eventComponent->relativePositionToGlobal (sx, sy);
  51360. return sy;
  51361. }
  51362. const MouseEvent MouseEvent::getEventRelativeTo (Component* const otherComponent) const throw()
  51363. {
  51364. if (otherComponent == 0)
  51365. {
  51366. jassertfalse
  51367. return *this;
  51368. }
  51369. MouseEvent me (*this);
  51370. eventComponent->relativePositionToOtherComponent (otherComponent, me.x, me.y);
  51371. eventComponent->relativePositionToOtherComponent (otherComponent, me.mouseDownX, me.mouseDownY);
  51372. me.eventComponent = otherComponent;
  51373. return me;
  51374. }
  51375. static int doubleClickTimeOutMs = 400;
  51376. void MouseEvent::setDoubleClickTimeout (const int newTime) throw()
  51377. {
  51378. doubleClickTimeOutMs = newTime;
  51379. }
  51380. int MouseEvent::getDoubleClickTimeout() throw()
  51381. {
  51382. return doubleClickTimeOutMs;
  51383. }
  51384. END_JUCE_NAMESPACE
  51385. /********* End of inlined file: juce_MouseEvent.cpp *********/
  51386. /********* Start of inlined file: juce_MouseHoverDetector.cpp *********/
  51387. BEGIN_JUCE_NAMESPACE
  51388. MouseHoverDetector::MouseHoverDetector (const int hoverTimeMillisecs_)
  51389. : source (0),
  51390. hoverTimeMillisecs (hoverTimeMillisecs_),
  51391. hasJustHovered (false)
  51392. {
  51393. internalTimer.owner = this;
  51394. }
  51395. MouseHoverDetector::~MouseHoverDetector()
  51396. {
  51397. setHoverComponent (0);
  51398. }
  51399. void MouseHoverDetector::setHoverTimeMillisecs (const int newTimeInMillisecs)
  51400. {
  51401. hoverTimeMillisecs = newTimeInMillisecs;
  51402. }
  51403. void MouseHoverDetector::setHoverComponent (Component* const newSourceComponent)
  51404. {
  51405. if (source != newSourceComponent)
  51406. {
  51407. internalTimer.stopTimer();
  51408. hasJustHovered = false;
  51409. if (source != 0)
  51410. {
  51411. // ! you need to delete the hover detector before deleting its component
  51412. jassert (source->isValidComponent());
  51413. source->removeMouseListener (&internalTimer);
  51414. }
  51415. source = newSourceComponent;
  51416. if (newSourceComponent != 0)
  51417. newSourceComponent->addMouseListener (&internalTimer, false);
  51418. }
  51419. }
  51420. void MouseHoverDetector::hoverTimerCallback()
  51421. {
  51422. internalTimer.stopTimer();
  51423. if (source != 0)
  51424. {
  51425. int mx, my;
  51426. source->getMouseXYRelative (mx, my);
  51427. if (source->reallyContains (mx, my, false))
  51428. {
  51429. hasJustHovered = true;
  51430. mouseHovered (mx, my);
  51431. }
  51432. }
  51433. }
  51434. void MouseHoverDetector::checkJustHoveredCallback()
  51435. {
  51436. if (hasJustHovered)
  51437. {
  51438. hasJustHovered = false;
  51439. mouseMovedAfterHover();
  51440. }
  51441. }
  51442. void MouseHoverDetector::HoverDetectorInternal::timerCallback()
  51443. {
  51444. owner->hoverTimerCallback();
  51445. }
  51446. void MouseHoverDetector::HoverDetectorInternal::mouseEnter (const MouseEvent&)
  51447. {
  51448. stopTimer();
  51449. owner->checkJustHoveredCallback();
  51450. }
  51451. void MouseHoverDetector::HoverDetectorInternal::mouseExit (const MouseEvent&)
  51452. {
  51453. stopTimer();
  51454. owner->checkJustHoveredCallback();
  51455. }
  51456. void MouseHoverDetector::HoverDetectorInternal::mouseDown (const MouseEvent&)
  51457. {
  51458. stopTimer();
  51459. owner->checkJustHoveredCallback();
  51460. }
  51461. void MouseHoverDetector::HoverDetectorInternal::mouseUp (const MouseEvent&)
  51462. {
  51463. stopTimer();
  51464. owner->checkJustHoveredCallback();
  51465. }
  51466. void MouseHoverDetector::HoverDetectorInternal::mouseMove (const MouseEvent& e)
  51467. {
  51468. if (lastX != e.x || lastY != e.y) // to avoid fake mouse-moves setting it off
  51469. {
  51470. lastX = e.x;
  51471. lastY = e.y;
  51472. if (owner->source != 0)
  51473. startTimer (owner->hoverTimeMillisecs);
  51474. owner->checkJustHoveredCallback();
  51475. }
  51476. }
  51477. void MouseHoverDetector::HoverDetectorInternal::mouseWheelMove (const MouseEvent&, float, float)
  51478. {
  51479. stopTimer();
  51480. owner->checkJustHoveredCallback();
  51481. }
  51482. END_JUCE_NAMESPACE
  51483. /********* End of inlined file: juce_MouseHoverDetector.cpp *********/
  51484. /********* Start of inlined file: juce_MouseListener.cpp *********/
  51485. BEGIN_JUCE_NAMESPACE
  51486. void MouseListener::mouseEnter (const MouseEvent&)
  51487. {
  51488. }
  51489. void MouseListener::mouseExit (const MouseEvent&)
  51490. {
  51491. }
  51492. void MouseListener::mouseDown (const MouseEvent&)
  51493. {
  51494. }
  51495. void MouseListener::mouseUp (const MouseEvent&)
  51496. {
  51497. }
  51498. void MouseListener::mouseDrag (const MouseEvent&)
  51499. {
  51500. }
  51501. void MouseListener::mouseMove (const MouseEvent&)
  51502. {
  51503. }
  51504. void MouseListener::mouseDoubleClick (const MouseEvent&)
  51505. {
  51506. }
  51507. void MouseListener::mouseWheelMove (const MouseEvent&, float, float)
  51508. {
  51509. }
  51510. END_JUCE_NAMESPACE
  51511. /********* End of inlined file: juce_MouseListener.cpp *********/
  51512. /********* Start of inlined file: juce_BooleanPropertyComponent.cpp *********/
  51513. BEGIN_JUCE_NAMESPACE
  51514. BooleanPropertyComponent::BooleanPropertyComponent (const String& name,
  51515. const String& buttonTextWhenTrue,
  51516. const String& buttonTextWhenFalse)
  51517. : PropertyComponent (name),
  51518. onText (buttonTextWhenTrue),
  51519. offText (buttonTextWhenFalse)
  51520. {
  51521. addAndMakeVisible (button = new ToggleButton (String::empty));
  51522. button->setClickingTogglesState (false);
  51523. button->addButtonListener (this);
  51524. }
  51525. BooleanPropertyComponent::~BooleanPropertyComponent()
  51526. {
  51527. deleteAllChildren();
  51528. }
  51529. void BooleanPropertyComponent::paint (Graphics& g)
  51530. {
  51531. PropertyComponent::paint (g);
  51532. const Rectangle r (button->getBounds());
  51533. g.setColour (Colours::white);
  51534. g.fillRect (r);
  51535. g.setColour (findColour (ComboBox::outlineColourId));
  51536. g.drawRect (r.getX(), r.getY(), r.getWidth(), r.getHeight());
  51537. }
  51538. void BooleanPropertyComponent::refresh()
  51539. {
  51540. button->setToggleState (getState(), false);
  51541. button->setButtonText (button->getToggleState() ? onText : offText);
  51542. }
  51543. void BooleanPropertyComponent::buttonClicked (Button*)
  51544. {
  51545. setState (! getState());
  51546. }
  51547. END_JUCE_NAMESPACE
  51548. /********* End of inlined file: juce_BooleanPropertyComponent.cpp *********/
  51549. /********* Start of inlined file: juce_ButtonPropertyComponent.cpp *********/
  51550. BEGIN_JUCE_NAMESPACE
  51551. ButtonPropertyComponent::ButtonPropertyComponent (const String& name,
  51552. const bool triggerOnMouseDown)
  51553. : PropertyComponent (name)
  51554. {
  51555. addAndMakeVisible (button = new TextButton (String::empty));
  51556. button->setTriggeredOnMouseDown (triggerOnMouseDown);
  51557. button->addButtonListener (this);
  51558. }
  51559. ButtonPropertyComponent::~ButtonPropertyComponent()
  51560. {
  51561. deleteAllChildren();
  51562. }
  51563. void ButtonPropertyComponent::refresh()
  51564. {
  51565. button->setButtonText (getButtonText());
  51566. }
  51567. void ButtonPropertyComponent::buttonClicked (Button*)
  51568. {
  51569. buttonClicked();
  51570. }
  51571. END_JUCE_NAMESPACE
  51572. /********* End of inlined file: juce_ButtonPropertyComponent.cpp *********/
  51573. /********* Start of inlined file: juce_ChoicePropertyComponent.cpp *********/
  51574. BEGIN_JUCE_NAMESPACE
  51575. ChoicePropertyComponent::ChoicePropertyComponent (const String& name)
  51576. : PropertyComponent (name),
  51577. comboBox (0)
  51578. {
  51579. }
  51580. ChoicePropertyComponent::~ChoicePropertyComponent()
  51581. {
  51582. deleteAllChildren();
  51583. }
  51584. const StringArray& ChoicePropertyComponent::getChoices() const throw()
  51585. {
  51586. return choices;
  51587. }
  51588. void ChoicePropertyComponent::refresh()
  51589. {
  51590. if (comboBox == 0)
  51591. {
  51592. addAndMakeVisible (comboBox = new ComboBox (String::empty));
  51593. for (int i = 0; i < choices.size(); ++i)
  51594. {
  51595. if (choices[i].isNotEmpty())
  51596. comboBox->addItem (choices[i], i + 1);
  51597. else
  51598. comboBox->addSeparator();
  51599. }
  51600. comboBox->setEditableText (false);
  51601. comboBox->addListener (this);
  51602. }
  51603. comboBox->setSelectedId (getIndex() + 1, true);
  51604. }
  51605. void ChoicePropertyComponent::comboBoxChanged (ComboBox*)
  51606. {
  51607. const int newIndex = comboBox->getSelectedId() - 1;
  51608. if (newIndex != getIndex())
  51609. setIndex (newIndex);
  51610. }
  51611. END_JUCE_NAMESPACE
  51612. /********* End of inlined file: juce_ChoicePropertyComponent.cpp *********/
  51613. /********* Start of inlined file: juce_PropertyComponent.cpp *********/
  51614. BEGIN_JUCE_NAMESPACE
  51615. PropertyComponent::PropertyComponent (const String& name,
  51616. const int preferredHeight_)
  51617. : Component (name),
  51618. preferredHeight (preferredHeight_)
  51619. {
  51620. jassert (name.isNotEmpty());
  51621. }
  51622. PropertyComponent::~PropertyComponent()
  51623. {
  51624. }
  51625. void PropertyComponent::paint (Graphics& g)
  51626. {
  51627. getLookAndFeel().drawPropertyComponentBackground (g, getWidth(), getHeight(), *this);
  51628. getLookAndFeel().drawPropertyComponentLabel (g, getWidth(), getHeight(), *this);
  51629. }
  51630. void PropertyComponent::resized()
  51631. {
  51632. if (getNumChildComponents() > 0)
  51633. getChildComponent (0)->setBounds (getLookAndFeel().getPropertyComponentContentPosition (*this));
  51634. }
  51635. void PropertyComponent::enablementChanged()
  51636. {
  51637. repaint();
  51638. }
  51639. END_JUCE_NAMESPACE
  51640. /********* End of inlined file: juce_PropertyComponent.cpp *********/
  51641. /********* Start of inlined file: juce_PropertyPanel.cpp *********/
  51642. BEGIN_JUCE_NAMESPACE
  51643. class PropertyHolderComponent : public Component
  51644. {
  51645. public:
  51646. PropertyHolderComponent()
  51647. {
  51648. }
  51649. ~PropertyHolderComponent()
  51650. {
  51651. deleteAllChildren();
  51652. }
  51653. void paint (Graphics&)
  51654. {
  51655. }
  51656. void updateLayout (const int width);
  51657. void refreshAll() const;
  51658. };
  51659. class PropertySectionComponent : public Component
  51660. {
  51661. public:
  51662. PropertySectionComponent (const String& sectionTitle,
  51663. const Array <PropertyComponent*>& newProperties,
  51664. const bool open)
  51665. : Component (sectionTitle),
  51666. titleHeight (sectionTitle.isNotEmpty() ? 22 : 0),
  51667. isOpen_ (open)
  51668. {
  51669. for (int i = newProperties.size(); --i >= 0;)
  51670. {
  51671. addAndMakeVisible (newProperties.getUnchecked(i));
  51672. newProperties.getUnchecked(i)->refresh();
  51673. }
  51674. }
  51675. ~PropertySectionComponent()
  51676. {
  51677. deleteAllChildren();
  51678. }
  51679. void paint (Graphics& g)
  51680. {
  51681. if (titleHeight > 0)
  51682. getLookAndFeel().drawPropertyPanelSectionHeader (g, getName(), isOpen(), getWidth(), titleHeight);
  51683. }
  51684. void resized()
  51685. {
  51686. int y = titleHeight;
  51687. for (int i = getNumChildComponents(); --i >= 0;)
  51688. {
  51689. PropertyComponent* const pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  51690. if (pec != 0)
  51691. {
  51692. const int prefH = pec->getPreferredHeight();
  51693. pec->setBounds (1, y, getWidth() - 2, prefH);
  51694. y += prefH;
  51695. }
  51696. }
  51697. }
  51698. int getPreferredHeight() const
  51699. {
  51700. int y = titleHeight;
  51701. if (isOpen())
  51702. {
  51703. for (int i = 0; i < getNumChildComponents(); ++i)
  51704. {
  51705. PropertyComponent* pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  51706. if (pec != 0)
  51707. y += pec->getPreferredHeight();
  51708. }
  51709. }
  51710. return y;
  51711. }
  51712. void setOpen (const bool open)
  51713. {
  51714. if (isOpen_ != open)
  51715. {
  51716. isOpen_ = open;
  51717. for (int i = 0; i < getNumChildComponents(); ++i)
  51718. {
  51719. PropertyComponent* pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  51720. if (pec != 0)
  51721. pec->setVisible (open);
  51722. }
  51723. // (unable to use the syntax findParentComponentOfClass <DragAndDropContainer> () because of a VC6 compiler bug)
  51724. PropertyPanel* const pp = findParentComponentOfClass ((PropertyPanel*) 0);
  51725. if (pp != 0)
  51726. pp->resized();
  51727. }
  51728. }
  51729. bool isOpen() const throw()
  51730. {
  51731. return isOpen_;
  51732. }
  51733. void refreshAll() const
  51734. {
  51735. for (int i = 0; i < getNumChildComponents(); ++i)
  51736. {
  51737. PropertyComponent* pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  51738. if (pec != 0)
  51739. pec->refresh();
  51740. }
  51741. }
  51742. void mouseDown (const MouseEvent&)
  51743. {
  51744. }
  51745. void mouseUp (const MouseEvent& e)
  51746. {
  51747. if (e.getMouseDownX() < titleHeight
  51748. && e.x < titleHeight
  51749. && e.y < titleHeight
  51750. && e.getNumberOfClicks() != 2)
  51751. {
  51752. setOpen (! isOpen());
  51753. }
  51754. }
  51755. void mouseDoubleClick (const MouseEvent& e)
  51756. {
  51757. if (e.y < titleHeight)
  51758. setOpen (! isOpen());
  51759. }
  51760. private:
  51761. int titleHeight;
  51762. bool isOpen_;
  51763. };
  51764. void PropertyHolderComponent::updateLayout (const int width)
  51765. {
  51766. int y = 0;
  51767. for (int i = getNumChildComponents(); --i >= 0;)
  51768. {
  51769. PropertySectionComponent* const section
  51770. = dynamic_cast <PropertySectionComponent*> (getChildComponent (i));
  51771. if (section != 0)
  51772. {
  51773. const int prefH = section->getPreferredHeight();
  51774. section->setBounds (0, y, width, prefH);
  51775. y += prefH;
  51776. }
  51777. }
  51778. setSize (width, y);
  51779. repaint();
  51780. }
  51781. void PropertyHolderComponent::refreshAll() const
  51782. {
  51783. for (int i = getNumChildComponents(); --i >= 0;)
  51784. {
  51785. PropertySectionComponent* const section
  51786. = dynamic_cast <PropertySectionComponent*> (getChildComponent (i));
  51787. if (section != 0)
  51788. section->refreshAll();
  51789. }
  51790. }
  51791. PropertyPanel::PropertyPanel()
  51792. {
  51793. messageWhenEmpty = TRANS("(nothing selected)");
  51794. addAndMakeVisible (viewport = new Viewport());
  51795. viewport->setViewedComponent (propertyHolderComponent = new PropertyHolderComponent());
  51796. viewport->setFocusContainer (true);
  51797. }
  51798. PropertyPanel::~PropertyPanel()
  51799. {
  51800. clear();
  51801. deleteAllChildren();
  51802. }
  51803. void PropertyPanel::paint (Graphics& g)
  51804. {
  51805. if (propertyHolderComponent->getNumChildComponents() == 0)
  51806. {
  51807. g.setColour (Colours::black.withAlpha (0.5f));
  51808. g.setFont (14.0f);
  51809. g.drawText (messageWhenEmpty, 0, 0, getWidth(), 30,
  51810. Justification::centred, true);
  51811. }
  51812. }
  51813. void PropertyPanel::resized()
  51814. {
  51815. viewport->setBounds (0, 0, getWidth(), getHeight());
  51816. updatePropHolderLayout();
  51817. }
  51818. void PropertyPanel::clear()
  51819. {
  51820. if (propertyHolderComponent->getNumChildComponents() > 0)
  51821. {
  51822. propertyHolderComponent->deleteAllChildren();
  51823. repaint();
  51824. }
  51825. }
  51826. void PropertyPanel::addProperties (const Array <PropertyComponent*>& newProperties)
  51827. {
  51828. if (propertyHolderComponent->getNumChildComponents() == 0)
  51829. repaint();
  51830. propertyHolderComponent->addAndMakeVisible (new PropertySectionComponent (String::empty,
  51831. newProperties,
  51832. true), 0);
  51833. updatePropHolderLayout();
  51834. }
  51835. void PropertyPanel::addSection (const String& sectionTitle,
  51836. const Array <PropertyComponent*>& newProperties,
  51837. const bool shouldBeOpen)
  51838. {
  51839. jassert (sectionTitle.isNotEmpty());
  51840. if (propertyHolderComponent->getNumChildComponents() == 0)
  51841. repaint();
  51842. propertyHolderComponent->addAndMakeVisible (new PropertySectionComponent (sectionTitle,
  51843. newProperties,
  51844. shouldBeOpen), 0);
  51845. updatePropHolderLayout();
  51846. }
  51847. void PropertyPanel::updatePropHolderLayout() const
  51848. {
  51849. const int maxWidth = viewport->getMaximumVisibleWidth();
  51850. ((PropertyHolderComponent*) propertyHolderComponent)->updateLayout (maxWidth);
  51851. const int newMaxWidth = viewport->getMaximumVisibleWidth();
  51852. if (maxWidth != newMaxWidth)
  51853. {
  51854. // need to do this twice because of scrollbars changing the size, etc.
  51855. ((PropertyHolderComponent*) propertyHolderComponent)->updateLayout (newMaxWidth);
  51856. }
  51857. }
  51858. void PropertyPanel::refreshAll() const
  51859. {
  51860. ((PropertyHolderComponent*) propertyHolderComponent)->refreshAll();
  51861. }
  51862. const StringArray PropertyPanel::getSectionNames() const
  51863. {
  51864. StringArray s;
  51865. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  51866. {
  51867. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  51868. if (section != 0 && section->getName().isNotEmpty())
  51869. s.add (section->getName());
  51870. }
  51871. return s;
  51872. }
  51873. bool PropertyPanel::isSectionOpen (const int sectionIndex) const
  51874. {
  51875. int index = 0;
  51876. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  51877. {
  51878. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  51879. if (section != 0 && section->getName().isNotEmpty())
  51880. {
  51881. if (index == sectionIndex)
  51882. return section->isOpen();
  51883. ++index;
  51884. }
  51885. }
  51886. return false;
  51887. }
  51888. void PropertyPanel::setSectionOpen (const int sectionIndex, const bool shouldBeOpen)
  51889. {
  51890. int index = 0;
  51891. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  51892. {
  51893. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  51894. if (section != 0 && section->getName().isNotEmpty())
  51895. {
  51896. if (index == sectionIndex)
  51897. {
  51898. section->setOpen (shouldBeOpen);
  51899. break;
  51900. }
  51901. ++index;
  51902. }
  51903. }
  51904. }
  51905. XmlElement* PropertyPanel::getOpennessState() const
  51906. {
  51907. XmlElement* const xml = new XmlElement (T("PROPERTYPANELSTATE"));
  51908. const StringArray sections (getSectionNames());
  51909. for (int i = 0; i < sections.size(); ++i)
  51910. {
  51911. if (sections[i].isNotEmpty())
  51912. {
  51913. XmlElement* const e = new XmlElement (T("SECTION"));
  51914. e->setAttribute (T("name"), sections[i]);
  51915. e->setAttribute (T("open"), isSectionOpen (i) ? 1 : 0);
  51916. xml->addChildElement (e);
  51917. }
  51918. }
  51919. return xml;
  51920. }
  51921. void PropertyPanel::restoreOpennessState (const XmlElement& xml)
  51922. {
  51923. if (xml.hasTagName (T("PROPERTYPANELSTATE")))
  51924. {
  51925. const StringArray sections (getSectionNames());
  51926. forEachXmlChildElementWithTagName (xml, e, T("SECTION"))
  51927. {
  51928. setSectionOpen (sections.indexOf (e->getStringAttribute (T("name"))),
  51929. e->getBoolAttribute (T("open")));
  51930. }
  51931. }
  51932. }
  51933. void PropertyPanel::setMessageWhenEmpty (const String& newMessage)
  51934. {
  51935. if (messageWhenEmpty != newMessage)
  51936. {
  51937. messageWhenEmpty = newMessage;
  51938. repaint();
  51939. }
  51940. }
  51941. const String& PropertyPanel::getMessageWhenEmpty() const throw()
  51942. {
  51943. return messageWhenEmpty;
  51944. }
  51945. END_JUCE_NAMESPACE
  51946. /********* End of inlined file: juce_PropertyPanel.cpp *********/
  51947. /********* Start of inlined file: juce_SliderPropertyComponent.cpp *********/
  51948. BEGIN_JUCE_NAMESPACE
  51949. SliderPropertyComponent::SliderPropertyComponent (const String& name,
  51950. const double rangeMin,
  51951. const double rangeMax,
  51952. const double interval,
  51953. const double skewFactor)
  51954. : PropertyComponent (name)
  51955. {
  51956. addAndMakeVisible (slider = new Slider (name));
  51957. slider->setRange (rangeMin, rangeMax, interval);
  51958. slider->setSkewFactor (skewFactor);
  51959. slider->setSliderStyle (Slider::LinearBar);
  51960. slider->addListener (this);
  51961. }
  51962. SliderPropertyComponent::~SliderPropertyComponent()
  51963. {
  51964. deleteAllChildren();
  51965. }
  51966. void SliderPropertyComponent::refresh()
  51967. {
  51968. slider->setValue (getValue(), false);
  51969. }
  51970. void SliderPropertyComponent::sliderValueChanged (Slider*)
  51971. {
  51972. if (getValue() != slider->getValue())
  51973. setValue (slider->getValue());
  51974. }
  51975. END_JUCE_NAMESPACE
  51976. /********* End of inlined file: juce_SliderPropertyComponent.cpp *********/
  51977. /********* Start of inlined file: juce_TextPropertyComponent.cpp *********/
  51978. BEGIN_JUCE_NAMESPACE
  51979. class TextPropLabel : public Label
  51980. {
  51981. TextPropertyComponent& owner;
  51982. int maxChars;
  51983. bool isMultiline;
  51984. public:
  51985. TextPropLabel (TextPropertyComponent& owner_,
  51986. const int maxChars_, const bool isMultiline_)
  51987. : Label (String::empty, String::empty),
  51988. owner (owner_),
  51989. maxChars (maxChars_),
  51990. isMultiline (isMultiline_)
  51991. {
  51992. setEditable (true, true, false);
  51993. setColour (backgroundColourId, Colours::white);
  51994. setColour (outlineColourId, findColour (ComboBox::outlineColourId));
  51995. }
  51996. ~TextPropLabel()
  51997. {
  51998. }
  51999. TextEditor* createEditorComponent()
  52000. {
  52001. TextEditor* const textEditor = Label::createEditorComponent();
  52002. textEditor->setInputRestrictions (maxChars);
  52003. if (isMultiline)
  52004. {
  52005. textEditor->setMultiLine (true, true);
  52006. textEditor->setReturnKeyStartsNewLine (true);
  52007. }
  52008. return textEditor;
  52009. }
  52010. void textWasEdited()
  52011. {
  52012. owner.textWasEdited();
  52013. }
  52014. };
  52015. TextPropertyComponent::TextPropertyComponent (const String& name,
  52016. const int maxNumChars,
  52017. const bool isMultiLine)
  52018. : PropertyComponent (name)
  52019. {
  52020. addAndMakeVisible (textEditor = new TextPropLabel (*this, maxNumChars, isMultiLine));
  52021. if (isMultiLine)
  52022. {
  52023. textEditor->setJustificationType (Justification::topLeft);
  52024. preferredHeight = 120;
  52025. }
  52026. }
  52027. TextPropertyComponent::~TextPropertyComponent()
  52028. {
  52029. deleteAllChildren();
  52030. }
  52031. void TextPropertyComponent::refresh()
  52032. {
  52033. textEditor->setText (getText(), false);
  52034. }
  52035. void TextPropertyComponent::textWasEdited()
  52036. {
  52037. const String newText (textEditor->getText());
  52038. if (getText() != newText)
  52039. setText (newText);
  52040. }
  52041. END_JUCE_NAMESPACE
  52042. /********* End of inlined file: juce_TextPropertyComponent.cpp *********/
  52043. /********* Start of inlined file: juce_AudioDeviceSelectorComponent.cpp *********/
  52044. BEGIN_JUCE_NAMESPACE
  52045. class AudioDeviceSelectorComponentListBox : public ListBox,
  52046. public ListBoxModel
  52047. {
  52048. public:
  52049. enum BoxType
  52050. {
  52051. midiInputType,
  52052. audioInputType,
  52053. audioOutputType
  52054. };
  52055. AudioDeviceSelectorComponentListBox (AudioDeviceManager& deviceManager_,
  52056. const BoxType type_,
  52057. const String& noItemsMessage_,
  52058. const int minNumber_,
  52059. const int maxNumber_)
  52060. : ListBox (String::empty, 0),
  52061. deviceManager (deviceManager_),
  52062. type (type_),
  52063. noItemsMessage (noItemsMessage_),
  52064. minNumber (minNumber_),
  52065. maxNumber (maxNumber_)
  52066. {
  52067. AudioIODevice* const currentDevice = deviceManager.getCurrentAudioDevice();
  52068. if (type_ == midiInputType)
  52069. {
  52070. items = MidiInput::getDevices();
  52071. }
  52072. else if (type_ == audioInputType)
  52073. {
  52074. items = currentDevice->getInputChannelNames();
  52075. }
  52076. else if (type_ == audioOutputType)
  52077. {
  52078. items = currentDevice->getOutputChannelNames();
  52079. }
  52080. else
  52081. {
  52082. jassertfalse
  52083. }
  52084. setModel (this);
  52085. setOutlineThickness (1);
  52086. }
  52087. ~AudioDeviceSelectorComponentListBox()
  52088. {
  52089. }
  52090. int getNumRows()
  52091. {
  52092. return items.size();
  52093. }
  52094. void paintListBoxItem (int row,
  52095. Graphics& g,
  52096. int width, int height,
  52097. bool rowIsSelected)
  52098. {
  52099. if (((unsigned int) row) < (unsigned int) items.size())
  52100. {
  52101. if (rowIsSelected)
  52102. g.fillAll (findColour (TextEditor::highlightColourId)
  52103. .withMultipliedAlpha (0.3f));
  52104. const String item (items [row]);
  52105. bool enabled = false;
  52106. if (type == midiInputType)
  52107. {
  52108. enabled = deviceManager.isMidiInputEnabled (item);
  52109. }
  52110. else if (type == audioInputType)
  52111. {
  52112. enabled = deviceManager.getInputChannels() [row];
  52113. }
  52114. else if (type == audioOutputType)
  52115. {
  52116. enabled = deviceManager.getOutputChannels() [row];
  52117. }
  52118. const int x = getTickX();
  52119. const int tickW = height - height / 4;
  52120. getLookAndFeel().drawTickBox (g, *this, x - tickW, (height - tickW) / 2, tickW, tickW,
  52121. enabled, true, true, false);
  52122. g.setFont (height * 0.6f);
  52123. g.setColour (findColour (ListBox::textColourId, true).withMultipliedAlpha (enabled ? 1.0f : 0.6f));
  52124. g.drawText (item, x, 0, width - x - 2, height, Justification::centredLeft, true);
  52125. }
  52126. }
  52127. void listBoxItemClicked (int row, const MouseEvent& e)
  52128. {
  52129. selectRow (row);
  52130. if (e.x < getTickX())
  52131. flipEnablement (row);
  52132. }
  52133. void listBoxItemDoubleClicked (int row, const MouseEvent&)
  52134. {
  52135. flipEnablement (row);
  52136. }
  52137. void returnKeyPressed (int row)
  52138. {
  52139. flipEnablement (row);
  52140. }
  52141. void paint (Graphics& g)
  52142. {
  52143. ListBox::paint (g);
  52144. if (items.size() == 0)
  52145. {
  52146. g.setColour (Colours::grey);
  52147. g.setFont (13.0f);
  52148. g.drawText (noItemsMessage,
  52149. 0, 0, getWidth(), getHeight() / 2,
  52150. Justification::centred, true);
  52151. }
  52152. }
  52153. int getBestHeight (const int preferredHeight)
  52154. {
  52155. const int extra = getOutlineThickness() * 2;
  52156. return jmax (getRowHeight() * 2 + extra,
  52157. jmin (getRowHeight() * getNumRows() + extra,
  52158. preferredHeight));
  52159. }
  52160. juce_UseDebuggingNewOperator
  52161. private:
  52162. AudioDeviceManager& deviceManager;
  52163. const BoxType type;
  52164. const String noItemsMessage;
  52165. StringArray items;
  52166. int minNumber, maxNumber;
  52167. void flipEnablement (const int row)
  52168. {
  52169. if (((unsigned int) row) < (unsigned int) items.size())
  52170. {
  52171. AudioIODevice* const audioDevice = deviceManager.getCurrentAudioDevice();
  52172. const String item (items [row]);
  52173. if (type == midiInputType)
  52174. {
  52175. deviceManager.setMidiInputEnabled (item, ! deviceManager.isMidiInputEnabled (item));
  52176. }
  52177. else
  52178. {
  52179. jassert (type == audioInputType || type == audioOutputType);
  52180. if (audioDevice != 0)
  52181. {
  52182. BitArray chans (type == audioInputType ? deviceManager.getInputChannels()
  52183. : deviceManager.getOutputChannels());
  52184. const BitArray oldChans (chans);
  52185. const bool newVal = ! chans[row];
  52186. const int numActive = chans.countNumberOfSetBits();
  52187. if (! newVal)
  52188. {
  52189. if (numActive > minNumber)
  52190. chans.setBit (row, false);
  52191. }
  52192. else
  52193. {
  52194. if (numActive >= maxNumber)
  52195. {
  52196. const int firstActiveChan = chans.findNextSetBit();
  52197. chans.setBit (row > firstActiveChan
  52198. ? firstActiveChan : chans.getHighestBit(),
  52199. false);
  52200. }
  52201. chans.setBit (row, true);
  52202. }
  52203. if (type == audioInputType)
  52204. deviceManager.setInputChannels (chans, true);
  52205. else
  52206. deviceManager.setOutputChannels (chans, true);
  52207. }
  52208. }
  52209. }
  52210. }
  52211. int getTickX() const throw()
  52212. {
  52213. return getRowHeight() + 5;
  52214. }
  52215. AudioDeviceSelectorComponentListBox (const AudioDeviceSelectorComponentListBox&);
  52216. const AudioDeviceSelectorComponentListBox& operator= (const AudioDeviceSelectorComponentListBox&);
  52217. };
  52218. AudioDeviceSelectorComponent::AudioDeviceSelectorComponent (AudioDeviceManager& deviceManager_,
  52219. const int minInputChannels_,
  52220. const int maxInputChannels_,
  52221. const int minOutputChannels_,
  52222. const int maxOutputChannels_,
  52223. const bool showMidiInputOptions,
  52224. const bool showMidiOutputSelector)
  52225. : deviceManager (deviceManager_),
  52226. minOutputChannels (minOutputChannels_),
  52227. maxOutputChannels (maxOutputChannels_),
  52228. minInputChannels (minInputChannels_),
  52229. maxInputChannels (maxInputChannels_),
  52230. sampleRateDropDown (0),
  52231. inputChansBox (0),
  52232. inputsLabel (0),
  52233. outputChansBox (0),
  52234. outputsLabel (0),
  52235. sampleRateLabel (0),
  52236. bufferSizeDropDown (0),
  52237. bufferSizeLabel (0),
  52238. launchUIButton (0)
  52239. {
  52240. jassert (minOutputChannels >= 0 && minOutputChannels <= maxOutputChannels);
  52241. jassert (minInputChannels >= 0 && minInputChannels <= maxInputChannels);
  52242. audioDeviceDropDown = new ComboBox ("device");
  52243. deviceManager_.addDeviceNamesToComboBox (*audioDeviceDropDown);
  52244. audioDeviceDropDown->setSelectedId (-1, true);
  52245. if (deviceManager_.getCurrentAudioDeviceName().isNotEmpty())
  52246. audioDeviceDropDown->setText (deviceManager_.getCurrentAudioDeviceName(), true);
  52247. audioDeviceDropDown->addListener (this);
  52248. addAndMakeVisible (audioDeviceDropDown);
  52249. Label* label = new Label ("l1", TRANS ("audio device:"));
  52250. label->attachToComponent (audioDeviceDropDown, true);
  52251. if (showMidiInputOptions)
  52252. {
  52253. addAndMakeVisible (midiInputsList
  52254. = new AudioDeviceSelectorComponentListBox (deviceManager,
  52255. AudioDeviceSelectorComponentListBox::midiInputType,
  52256. TRANS("(no midi inputs available)"),
  52257. 0, 0));
  52258. midiInputsLabel = new Label ("lm", TRANS ("active midi inputs:"));
  52259. midiInputsLabel->setJustificationType (Justification::topRight);
  52260. midiInputsLabel->attachToComponent (midiInputsList, true);
  52261. }
  52262. else
  52263. {
  52264. midiInputsList = 0;
  52265. midiInputsLabel = 0;
  52266. }
  52267. if (showMidiOutputSelector)
  52268. {
  52269. addAndMakeVisible (midiOutputSelector = new ComboBox (String::empty));
  52270. midiOutputSelector->addListener (this);
  52271. midiOutputLabel = new Label ("lm", TRANS("Midi Output:"));
  52272. midiOutputLabel->attachToComponent (midiOutputSelector, true);
  52273. }
  52274. else
  52275. {
  52276. midiOutputSelector = 0;
  52277. midiOutputLabel = 0;
  52278. }
  52279. deviceManager_.addChangeListener (this);
  52280. changeListenerCallback (0);
  52281. }
  52282. AudioDeviceSelectorComponent::~AudioDeviceSelectorComponent()
  52283. {
  52284. deviceManager.removeChangeListener (this);
  52285. deleteAllChildren();
  52286. }
  52287. void AudioDeviceSelectorComponent::resized()
  52288. {
  52289. const int lx = proportionOfWidth (0.35f);
  52290. const int w = proportionOfWidth (0.55f);
  52291. const int h = 24;
  52292. const int space = 6;
  52293. const int dh = h + space;
  52294. int y = 15;
  52295. audioDeviceDropDown->setBounds (lx, y, w, h);
  52296. y += dh;
  52297. if (sampleRateDropDown != 0)
  52298. {
  52299. sampleRateDropDown->setBounds (lx, y, w, h);
  52300. y += dh;
  52301. }
  52302. if (bufferSizeDropDown != 0)
  52303. {
  52304. bufferSizeDropDown->setBounds (lx, y, w, h);
  52305. y += dh;
  52306. }
  52307. if (launchUIButton != 0)
  52308. {
  52309. launchUIButton->setBounds (lx, y, 150, h);
  52310. ((TextButton*) launchUIButton)->changeWidthToFitText();
  52311. y += dh;
  52312. }
  52313. VoidArray boxes;
  52314. if (outputChansBox != 0)
  52315. boxes.add (outputChansBox);
  52316. if (inputChansBox != 0)
  52317. boxes.add (inputChansBox);
  52318. if (midiInputsList != 0)
  52319. boxes.add (midiInputsList);
  52320. const int boxSpace = getHeight() - y;
  52321. for (int i = 0; i < boxes.size(); ++i)
  52322. {
  52323. AudioDeviceSelectorComponentListBox* const box = (AudioDeviceSelectorComponentListBox*) boxes.getUnchecked (i);
  52324. const int bh = box->getBestHeight (jmin (h * 8, boxSpace / boxes.size()) - space);
  52325. box->setBounds (lx, y, w, bh);
  52326. y += bh + space;
  52327. }
  52328. if (midiOutputSelector != 0)
  52329. midiOutputSelector->setBounds (lx, y, w, h);
  52330. }
  52331. void AudioDeviceSelectorComponent::buttonClicked (Button*)
  52332. {
  52333. AudioIODevice* const device = deviceManager.getCurrentAudioDevice();
  52334. if (device != 0 && device->hasControlPanel())
  52335. {
  52336. const String lastDevice (device->getName());
  52337. if (device->showControlPanel())
  52338. {
  52339. deviceManager.setAudioDevice (String::empty, 0, 0, 0, 0, false);
  52340. deviceManager.setAudioDevice (lastDevice, 0, 0, 0, 0, false);
  52341. }
  52342. getTopLevelComponent()->toFront (true);
  52343. }
  52344. }
  52345. void AudioDeviceSelectorComponent::comboBoxChanged (ComboBox* comboBoxThatHasChanged)
  52346. {
  52347. AudioIODevice* const audioDevice = deviceManager.getCurrentAudioDevice();
  52348. if (comboBoxThatHasChanged == audioDeviceDropDown)
  52349. {
  52350. if (audioDeviceDropDown->getSelectedId() < 0)
  52351. {
  52352. deviceManager.setAudioDevice (String::empty, 0, 0, 0, 0, true);
  52353. }
  52354. else
  52355. {
  52356. String error (deviceManager.setAudioDevice (audioDeviceDropDown->getText(),
  52357. 0, 0, 0, 0, true));
  52358. if (error.isNotEmpty())
  52359. {
  52360. #if JUCE_WIN32
  52361. if (deviceManager.getInputChannels().countNumberOfSetBits() > 0
  52362. && deviceManager.getOutputChannels().countNumberOfSetBits() > 0)
  52363. {
  52364. // in DSound, some machines lose their primary input device when a mic
  52365. // is removed, and this also buggers up our attempt at opening an output
  52366. // device, so this is a workaround that doesn't fail in that case.
  52367. BitArray noInputs;
  52368. error = deviceManager.setAudioDevice (audioDeviceDropDown->getText(),
  52369. 0, 0, &noInputs, 0, false);
  52370. }
  52371. #endif
  52372. if (error.isNotEmpty())
  52373. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  52374. T("Error while opening \"")
  52375. + audioDeviceDropDown->getText()
  52376. + T("\""),
  52377. error);
  52378. }
  52379. }
  52380. if (deviceManager.getCurrentAudioDeviceName().isNotEmpty())
  52381. audioDeviceDropDown->setText (deviceManager.getCurrentAudioDeviceName(), true);
  52382. else
  52383. audioDeviceDropDown->setSelectedId (-1, true);
  52384. }
  52385. else if (comboBoxThatHasChanged == midiOutputSelector)
  52386. {
  52387. deviceManager.setDefaultMidiOutput (midiOutputSelector->getText());
  52388. }
  52389. else if (audioDevice != 0)
  52390. {
  52391. if (bufferSizeDropDown != 0 && comboBoxThatHasChanged == bufferSizeDropDown)
  52392. {
  52393. if (bufferSizeDropDown->getSelectedId() > 0)
  52394. deviceManager.setAudioDevice (audioDevice->getName(),
  52395. bufferSizeDropDown->getSelectedId(),
  52396. audioDevice->getCurrentSampleRate(),
  52397. 0, 0, true);
  52398. }
  52399. else if (sampleRateDropDown != 0 && comboBoxThatHasChanged == sampleRateDropDown)
  52400. {
  52401. if (sampleRateDropDown->getSelectedId() > 0)
  52402. deviceManager.setAudioDevice (audioDevice->getName(),
  52403. audioDevice->getCurrentBufferSizeSamples(),
  52404. sampleRateDropDown->getSelectedId(),
  52405. 0, 0, true);
  52406. }
  52407. }
  52408. }
  52409. void AudioDeviceSelectorComponent::changeListenerCallback (void*)
  52410. {
  52411. deleteAndZero (sampleRateDropDown);
  52412. deleteAndZero (inputChansBox);
  52413. deleteAndZero (inputsLabel);
  52414. deleteAndZero (outputChansBox);
  52415. deleteAndZero (outputsLabel);
  52416. deleteAndZero (sampleRateLabel);
  52417. deleteAndZero (bufferSizeDropDown);
  52418. deleteAndZero (bufferSizeLabel);
  52419. deleteAndZero (launchUIButton);
  52420. AudioIODevice* const currentDevice = deviceManager.getCurrentAudioDevice();
  52421. if (currentDevice != 0)
  52422. {
  52423. audioDeviceDropDown->setText (currentDevice->getName(), true);
  52424. // sample rate
  52425. addAndMakeVisible (sampleRateDropDown = new ComboBox ("samplerate"));
  52426. sampleRateLabel = new Label ("l2", TRANS ("sample rate:"));
  52427. sampleRateLabel->attachToComponent (sampleRateDropDown, true);
  52428. const int numRates = currentDevice->getNumSampleRates();
  52429. int i;
  52430. for (i = 0; i < numRates; ++i)
  52431. {
  52432. const int rate = roundDoubleToInt (currentDevice->getSampleRate (i));
  52433. sampleRateDropDown->addItem (String (rate) + T(" Hz"), rate);
  52434. }
  52435. const double currentRate = currentDevice->getCurrentSampleRate();
  52436. sampleRateDropDown->setSelectedId (roundDoubleToInt (currentRate), true);
  52437. sampleRateDropDown->addListener (this);
  52438. // buffer size
  52439. addAndMakeVisible (bufferSizeDropDown = new ComboBox ("buffersize"));
  52440. bufferSizeLabel = new Label ("l2", TRANS ("audio buffer size:"));
  52441. bufferSizeLabel->attachToComponent (bufferSizeDropDown, true);
  52442. const int numBufferSizes = currentDevice->getNumBufferSizesAvailable();
  52443. for (i = 0; i < numBufferSizes; ++i)
  52444. {
  52445. const int bs = currentDevice->getBufferSizeSamples (i);
  52446. bufferSizeDropDown->addItem (String (bs)
  52447. + T(" samples (")
  52448. + String (bs * 1000.0 / currentRate, 1)
  52449. + T(" ms)"),
  52450. bs);
  52451. }
  52452. bufferSizeDropDown->setSelectedId (currentDevice->getCurrentBufferSizeSamples(), true);
  52453. bufferSizeDropDown->addListener (this);
  52454. if (currentDevice->hasControlPanel())
  52455. {
  52456. addAndMakeVisible (launchUIButton = new TextButton (TRANS ("show this device's control panel"),
  52457. TRANS ("opens the device's own control panel")));
  52458. launchUIButton->addButtonListener (this);
  52459. }
  52460. // output chans
  52461. if (maxOutputChannels > 0 && minOutputChannels < currentDevice->getOutputChannelNames().size())
  52462. {
  52463. addAndMakeVisible (outputChansBox
  52464. = new AudioDeviceSelectorComponentListBox (deviceManager,
  52465. AudioDeviceSelectorComponentListBox::audioOutputType,
  52466. TRANS ("(no audio output channels found)"),
  52467. minOutputChannels, maxOutputChannels));
  52468. outputsLabel = new Label ("l3", TRANS ("active output channels:"));
  52469. outputsLabel->attachToComponent (outputChansBox, true);
  52470. }
  52471. // input chans
  52472. if (maxInputChannels > 0 && minInputChannels < currentDevice->getInputChannelNames().size())
  52473. {
  52474. addAndMakeVisible (inputChansBox
  52475. = new AudioDeviceSelectorComponentListBox (deviceManager,
  52476. AudioDeviceSelectorComponentListBox::audioInputType,
  52477. TRANS ("(no audio input channels found)"),
  52478. minInputChannels, maxInputChannels));
  52479. inputsLabel = new Label ("l4", TRANS ("active input channels:"));
  52480. inputsLabel->attachToComponent (inputChansBox, true);
  52481. }
  52482. }
  52483. else
  52484. {
  52485. audioDeviceDropDown->setSelectedId (-1, true);
  52486. }
  52487. if (midiInputsList != 0)
  52488. {
  52489. midiInputsList->updateContent();
  52490. midiInputsList->repaint();
  52491. }
  52492. if (midiOutputSelector != 0)
  52493. {
  52494. midiOutputSelector->clear();
  52495. const StringArray midiOuts (MidiOutput::getDevices());
  52496. midiOutputSelector->addItem (TRANS("<< no audio device >>"), -1);
  52497. midiOutputSelector->addSeparator();
  52498. for (int i = 0; i < midiOuts.size(); ++i)
  52499. midiOutputSelector->addItem (midiOuts[i], i + 1);
  52500. int current = -1;
  52501. if (deviceManager.getDefaultMidiOutput() != 0)
  52502. current = 1 + midiOuts.indexOf (deviceManager.getDefaultMidiOutputName());
  52503. midiOutputSelector->setSelectedId (current, true);
  52504. }
  52505. resized();
  52506. }
  52507. END_JUCE_NAMESPACE
  52508. /********* End of inlined file: juce_AudioDeviceSelectorComponent.cpp *********/
  52509. /********* Start of inlined file: juce_BubbleComponent.cpp *********/
  52510. BEGIN_JUCE_NAMESPACE
  52511. BubbleComponent::BubbleComponent()
  52512. : side (0),
  52513. allowablePlacements (above | below | left | right),
  52514. arrowTipX (0.0f),
  52515. arrowTipY (0.0f)
  52516. {
  52517. setInterceptsMouseClicks (false, false);
  52518. shadow.setShadowProperties (5.0f, 0.35f, 0, 0);
  52519. setComponentEffect (&shadow);
  52520. }
  52521. BubbleComponent::~BubbleComponent()
  52522. {
  52523. }
  52524. void BubbleComponent::paint (Graphics& g)
  52525. {
  52526. int x = content.getX();
  52527. int y = content.getY();
  52528. int w = content.getWidth();
  52529. int h = content.getHeight();
  52530. int cw, ch;
  52531. getContentSize (cw, ch);
  52532. if (side == 3)
  52533. x += w - cw;
  52534. else if (side != 1)
  52535. x += (w - cw) / 2;
  52536. w = cw;
  52537. if (side == 2)
  52538. y += h - ch;
  52539. else if (side != 0)
  52540. y += (h - ch) / 2;
  52541. h = ch;
  52542. getLookAndFeel().drawBubble (g, arrowTipX, arrowTipY,
  52543. (float) x, (float) y,
  52544. (float) w, (float) h);
  52545. const int cx = x + (w - cw) / 2;
  52546. const int cy = y + (h - ch) / 2;
  52547. const int indent = 3;
  52548. g.setOrigin (cx + indent, cy + indent);
  52549. g.reduceClipRegion (0, 0, cw - indent * 2, ch - indent * 2);
  52550. paintContent (g, cw - indent * 2, ch - indent * 2);
  52551. }
  52552. void BubbleComponent::setAllowedPlacement (const int newPlacement)
  52553. {
  52554. allowablePlacements = newPlacement;
  52555. }
  52556. void BubbleComponent::setPosition (Component* componentToPointTo)
  52557. {
  52558. jassert (componentToPointTo->isValidComponent());
  52559. int tx = 0;
  52560. int ty = 0;
  52561. if (getParentComponent() != 0)
  52562. componentToPointTo->relativePositionToOtherComponent (getParentComponent(), tx, ty);
  52563. else
  52564. componentToPointTo->relativePositionToGlobal (tx, ty);
  52565. setPosition (Rectangle (tx, ty, componentToPointTo->getWidth(), componentToPointTo->getHeight()));
  52566. }
  52567. void BubbleComponent::setPosition (const int arrowTipX,
  52568. const int arrowTipY)
  52569. {
  52570. setPosition (Rectangle (arrowTipX, arrowTipY, 1, 1));
  52571. }
  52572. void BubbleComponent::setPosition (const Rectangle& rectangleToPointTo)
  52573. {
  52574. Rectangle availableSpace;
  52575. if (getParentComponent() != 0)
  52576. {
  52577. availableSpace.setSize (getParentComponent()->getWidth(),
  52578. getParentComponent()->getHeight());
  52579. }
  52580. else
  52581. {
  52582. availableSpace = getParentMonitorArea();
  52583. }
  52584. int x = 0;
  52585. int y = 0;
  52586. int w = 150;
  52587. int h = 30;
  52588. getContentSize (w, h);
  52589. w += 30;
  52590. h += 30;
  52591. const float edgeIndent = 2.0f;
  52592. const int arrowLength = jmin (10, h / 3, w / 3);
  52593. int spaceAbove = ((allowablePlacements & above) != 0) ? jmax (0, rectangleToPointTo.getY() - availableSpace.getY()) : -1;
  52594. int spaceBelow = ((allowablePlacements & below) != 0) ? jmax (0, availableSpace.getBottom() - rectangleToPointTo.getBottom()) : -1;
  52595. int spaceLeft = ((allowablePlacements & left) != 0) ? jmax (0, rectangleToPointTo.getX() - availableSpace.getX()) : -1;
  52596. int spaceRight = ((allowablePlacements & right) != 0) ? jmax (0, availableSpace.getRight() - rectangleToPointTo.getRight()) : -1;
  52597. // look at whether the component is elongated, and if so, try to position next to its longer dimension.
  52598. if (rectangleToPointTo.getWidth() > rectangleToPointTo.getHeight() * 2
  52599. && (spaceAbove > h + 20 || spaceBelow > h + 20))
  52600. {
  52601. spaceLeft = spaceRight = 0;
  52602. }
  52603. else if (rectangleToPointTo.getWidth() < rectangleToPointTo.getHeight() / 2
  52604. && (spaceLeft > w + 20 || spaceRight > w + 20))
  52605. {
  52606. spaceAbove = spaceBelow = 0;
  52607. }
  52608. if (jmax (spaceAbove, spaceBelow) >= jmax (spaceLeft, spaceRight))
  52609. {
  52610. x = rectangleToPointTo.getX() + (rectangleToPointTo.getWidth() - w) / 2;
  52611. arrowTipX = w * 0.5f;
  52612. content.setSize (w, h - arrowLength);
  52613. if (spaceAbove >= spaceBelow)
  52614. {
  52615. // above
  52616. y = rectangleToPointTo.getY() - h;
  52617. content.setPosition (0, 0);
  52618. arrowTipY = h - edgeIndent;
  52619. side = 2;
  52620. }
  52621. else
  52622. {
  52623. // below
  52624. y = rectangleToPointTo.getBottom();
  52625. content.setPosition (0, arrowLength);
  52626. arrowTipY = edgeIndent;
  52627. side = 0;
  52628. }
  52629. }
  52630. else
  52631. {
  52632. y = rectangleToPointTo.getY() + (rectangleToPointTo.getHeight() - h) / 2;
  52633. arrowTipY = h * 0.5f;
  52634. content.setSize (w - arrowLength, h);
  52635. if (spaceLeft > spaceRight)
  52636. {
  52637. // on the left
  52638. x = rectangleToPointTo.getX() - w;
  52639. content.setPosition (0, 0);
  52640. arrowTipX = w - edgeIndent;
  52641. side = 3;
  52642. }
  52643. else
  52644. {
  52645. // on the right
  52646. x = rectangleToPointTo.getRight();
  52647. content.setPosition (arrowLength, 0);
  52648. arrowTipX = edgeIndent;
  52649. side = 1;
  52650. }
  52651. }
  52652. setBounds (x, y, w, h);
  52653. }
  52654. END_JUCE_NAMESPACE
  52655. /********* End of inlined file: juce_BubbleComponent.cpp *********/
  52656. /********* Start of inlined file: juce_BubbleMessageComponent.cpp *********/
  52657. BEGIN_JUCE_NAMESPACE
  52658. BubbleMessageComponent::BubbleMessageComponent (int fadeOutLengthMs)
  52659. : fadeOutLength (fadeOutLengthMs),
  52660. deleteAfterUse (false)
  52661. {
  52662. }
  52663. BubbleMessageComponent::~BubbleMessageComponent()
  52664. {
  52665. fadeOutComponent (fadeOutLength);
  52666. }
  52667. void BubbleMessageComponent::showAt (int x, int y,
  52668. const String& text,
  52669. const int numMillisecondsBeforeRemoving,
  52670. const bool removeWhenMouseClicked,
  52671. const bool deleteSelfAfterUse)
  52672. {
  52673. textLayout.clear();
  52674. textLayout.setText (text, Font (14.0f));
  52675. textLayout.layout (256, Justification::centredLeft, true);
  52676. setPosition (x, y);
  52677. init (numMillisecondsBeforeRemoving, removeWhenMouseClicked, deleteSelfAfterUse);
  52678. }
  52679. void BubbleMessageComponent::showAt (Component* const component,
  52680. const String& text,
  52681. const int numMillisecondsBeforeRemoving,
  52682. const bool removeWhenMouseClicked,
  52683. const bool deleteSelfAfterUse)
  52684. {
  52685. textLayout.clear();
  52686. textLayout.setText (text, Font (14.0f));
  52687. textLayout.layout (256, Justification::centredLeft, true);
  52688. setPosition (component);
  52689. init (numMillisecondsBeforeRemoving, removeWhenMouseClicked, deleteSelfAfterUse);
  52690. }
  52691. void BubbleMessageComponent::init (const int numMillisecondsBeforeRemoving,
  52692. const bool removeWhenMouseClicked,
  52693. const bool deleteSelfAfterUse)
  52694. {
  52695. setVisible (true);
  52696. deleteAfterUse = deleteSelfAfterUse;
  52697. if (numMillisecondsBeforeRemoving > 0)
  52698. expiryTime = Time::getMillisecondCounter() + numMillisecondsBeforeRemoving;
  52699. else
  52700. expiryTime = 0;
  52701. startTimer (77);
  52702. mouseClickCounter = Desktop::getInstance().getMouseButtonClickCounter();
  52703. if (! (removeWhenMouseClicked && isShowing()))
  52704. mouseClickCounter += 0xfffff;
  52705. repaint();
  52706. }
  52707. void BubbleMessageComponent::getContentSize (int& w, int& h)
  52708. {
  52709. w = textLayout.getWidth() + 16;
  52710. h = textLayout.getHeight() + 16;
  52711. }
  52712. void BubbleMessageComponent::paintContent (Graphics& g, int w, int h)
  52713. {
  52714. g.setColour (findColour (TooltipWindow::textColourId));
  52715. textLayout.drawWithin (g, 0, 0, w, h, Justification::centred);
  52716. }
  52717. void BubbleMessageComponent::timerCallback()
  52718. {
  52719. if (Desktop::getInstance().getMouseButtonClickCounter() > mouseClickCounter)
  52720. {
  52721. stopTimer();
  52722. setVisible (false);
  52723. if (deleteAfterUse)
  52724. delete this;
  52725. }
  52726. else if (expiryTime != 0 && Time::getMillisecondCounter() > expiryTime)
  52727. {
  52728. stopTimer();
  52729. fadeOutComponent (fadeOutLength);
  52730. if (deleteAfterUse)
  52731. delete this;
  52732. }
  52733. }
  52734. END_JUCE_NAMESPACE
  52735. /********* End of inlined file: juce_BubbleMessageComponent.cpp *********/
  52736. /********* Start of inlined file: juce_ColourSelector.cpp *********/
  52737. BEGIN_JUCE_NAMESPACE
  52738. static const int swatchesPerRow = 8;
  52739. static const int swatchHeight = 22;
  52740. class ColourComponentSlider : public Slider
  52741. {
  52742. public:
  52743. ColourComponentSlider (const String& name)
  52744. : Slider (name)
  52745. {
  52746. setRange (0.0, 255.0, 1.0);
  52747. }
  52748. ~ColourComponentSlider()
  52749. {
  52750. }
  52751. const String getTextFromValue (double currentValue)
  52752. {
  52753. return String::formatted (T("%02X"), (int)currentValue);
  52754. }
  52755. double getValueFromText (const String& text)
  52756. {
  52757. return (double) text.getHexValue32();
  52758. }
  52759. private:
  52760. ColourComponentSlider (const ColourComponentSlider&);
  52761. const ColourComponentSlider& operator= (const ColourComponentSlider&);
  52762. };
  52763. class ColourSpaceMarker : public Component
  52764. {
  52765. public:
  52766. ColourSpaceMarker()
  52767. {
  52768. setInterceptsMouseClicks (false, false);
  52769. }
  52770. ~ColourSpaceMarker()
  52771. {
  52772. }
  52773. void paint (Graphics& g)
  52774. {
  52775. g.setColour (Colour::greyLevel (0.1f));
  52776. g.drawEllipse (1.0f, 1.0f, getWidth() - 2.0f, getHeight() - 2.0f, 1.0f);
  52777. g.setColour (Colour::greyLevel (0.9f));
  52778. g.drawEllipse (2.0f, 2.0f, getWidth() - 4.0f, getHeight() - 4.0f, 1.0f);
  52779. }
  52780. private:
  52781. ColourSpaceMarker (const ColourSpaceMarker&);
  52782. const ColourSpaceMarker& operator= (const ColourSpaceMarker&);
  52783. };
  52784. class ColourSpaceView : public Component
  52785. {
  52786. ColourSelector* const owner;
  52787. float& h;
  52788. float& s;
  52789. float& v;
  52790. float lastHue;
  52791. ColourSpaceMarker* marker;
  52792. const int edge;
  52793. public:
  52794. ColourSpaceView (ColourSelector* owner_,
  52795. float& h_, float& s_, float& v_,
  52796. const int edgeSize)
  52797. : owner (owner_),
  52798. h (h_), s (s_), v (v_),
  52799. lastHue (0.0f),
  52800. edge (edgeSize)
  52801. {
  52802. addAndMakeVisible (marker = new ColourSpaceMarker());
  52803. setMouseCursor (MouseCursor::CrosshairCursor);
  52804. }
  52805. ~ColourSpaceView()
  52806. {
  52807. deleteAllChildren();
  52808. }
  52809. void paint (Graphics& g)
  52810. {
  52811. const float hue = h;
  52812. const float xScale = 1.0f / (getWidth() - edge * 2);
  52813. const float yScale = 1.0f / (getHeight() - edge * 2);
  52814. const Rectangle clip (g.getClipBounds());
  52815. const int x1 = jmax (clip.getX(), edge) & ~1;
  52816. const int x2 = jmin (clip.getRight(), getWidth() - edge) | 1;
  52817. const int y1 = jmax (clip.getY(), edge) & ~1;
  52818. const int y2 = jmin (clip.getBottom(), getHeight() - edge) | 1;
  52819. for (int y = y1; y < y2; y += 2)
  52820. {
  52821. const float v = jlimit (0.0f, 1.0f, 1.0f - (y - edge) * yScale);
  52822. for (int x = x1; x < x2; x += 2)
  52823. {
  52824. const float s = jlimit (0.0f, 1.0f, (x - edge) * xScale);
  52825. g.setColour (Colour (hue, s, v, 1.0f));
  52826. g.fillRect (x, y, 2, 2);
  52827. }
  52828. }
  52829. }
  52830. void mouseDown (const MouseEvent& e)
  52831. {
  52832. mouseDrag (e);
  52833. }
  52834. void mouseDrag (const MouseEvent& e)
  52835. {
  52836. const float s = (e.x - edge) / (float) (getWidth() - edge * 2);
  52837. const float v = 1.0f - (e.y - edge) / (float) (getHeight() - edge * 2);
  52838. owner->setSV (s, v);
  52839. }
  52840. void updateIfNeeded()
  52841. {
  52842. if (lastHue != h)
  52843. {
  52844. lastHue = h;
  52845. repaint();
  52846. }
  52847. resized();
  52848. }
  52849. void resized()
  52850. {
  52851. marker->setBounds (roundFloatToInt ((getWidth() - edge * 2) * s),
  52852. roundFloatToInt ((getHeight() - edge * 2) * (1.0f - v)),
  52853. edge * 2, edge * 2);
  52854. }
  52855. private:
  52856. ColourSpaceView (const ColourSpaceView&);
  52857. const ColourSpaceView& operator= (const ColourSpaceView&);
  52858. };
  52859. class HueSelectorMarker : public Component
  52860. {
  52861. public:
  52862. HueSelectorMarker()
  52863. {
  52864. setInterceptsMouseClicks (false, false);
  52865. }
  52866. ~HueSelectorMarker()
  52867. {
  52868. }
  52869. void paint (Graphics& g)
  52870. {
  52871. Path p;
  52872. p.addTriangle (1.0f, 1.0f,
  52873. getWidth() * 0.3f, getHeight() * 0.5f,
  52874. 1.0f, getHeight() - 1.0f);
  52875. p.addTriangle (getWidth() - 1.0f, 1.0f,
  52876. getWidth() * 0.7f, getHeight() * 0.5f,
  52877. getWidth() - 1.0f, getHeight() - 1.0f);
  52878. g.setColour (Colours::white.withAlpha (0.75f));
  52879. g.fillPath (p);
  52880. g.setColour (Colours::black.withAlpha (0.75f));
  52881. g.strokePath (p, PathStrokeType (1.2f));
  52882. }
  52883. private:
  52884. HueSelectorMarker (const HueSelectorMarker&);
  52885. const HueSelectorMarker& operator= (const HueSelectorMarker&);
  52886. };
  52887. class HueSelectorComp : public Component
  52888. {
  52889. public:
  52890. HueSelectorComp (ColourSelector* owner_,
  52891. float& h_, float& s_, float& v_,
  52892. const int edgeSize)
  52893. : owner (owner_),
  52894. h (h_), s (s_), v (v_),
  52895. lastHue (0.0f),
  52896. edge (edgeSize)
  52897. {
  52898. addAndMakeVisible (marker = new HueSelectorMarker());
  52899. }
  52900. ~HueSelectorComp()
  52901. {
  52902. deleteAllChildren();
  52903. }
  52904. void paint (Graphics& g)
  52905. {
  52906. const float yScale = 1.0f / (getHeight() - edge * 2);
  52907. const Rectangle clip (g.getClipBounds());
  52908. for (int y = jmin (clip.getBottom(), getHeight() - edge); --y >= jmax (edge, clip.getY());)
  52909. {
  52910. g.setColour (Colour ((y - edge) * yScale, 1.0f, 1.0f, 1.0f));
  52911. g.fillRect (edge, y, getWidth() - edge * 2, 1);
  52912. }
  52913. }
  52914. void resized()
  52915. {
  52916. marker->setBounds (0, roundFloatToInt ((getHeight() - edge * 2) * h),
  52917. getWidth(), edge * 2);
  52918. }
  52919. void mouseDown (const MouseEvent& e)
  52920. {
  52921. mouseDrag (e);
  52922. }
  52923. void mouseDrag (const MouseEvent& e)
  52924. {
  52925. const float hue = (e.y - edge) / (float) (getHeight() - edge * 2);
  52926. owner->setHue (hue);
  52927. }
  52928. void updateIfNeeded()
  52929. {
  52930. resized();
  52931. }
  52932. private:
  52933. ColourSelector* const owner;
  52934. float& h;
  52935. float& s;
  52936. float& v;
  52937. float lastHue;
  52938. HueSelectorMarker* marker;
  52939. const int edge;
  52940. HueSelectorComp (const HueSelectorComp&);
  52941. const HueSelectorComp& operator= (const HueSelectorComp&);
  52942. };
  52943. class SwatchComponent : public Component
  52944. {
  52945. public:
  52946. SwatchComponent (ColourSelector* owner_, int index_)
  52947. : owner (owner_),
  52948. index (index_)
  52949. {
  52950. }
  52951. ~SwatchComponent()
  52952. {
  52953. }
  52954. void paint (Graphics& g)
  52955. {
  52956. const Colour colour (owner->getSwatchColour (index));
  52957. g.fillCheckerBoard (0, 0, getWidth(), getHeight(),
  52958. 6, 6,
  52959. Colour (0xffdddddd).overlaidWith (colour),
  52960. Colour (0xffffffff).overlaidWith (colour));
  52961. }
  52962. void mouseDown (const MouseEvent&)
  52963. {
  52964. PopupMenu m;
  52965. m.addItem (1, TRANS("Use this swatch as the current colour"));
  52966. m.addSeparator();
  52967. m.addItem (2, TRANS("Set this swatch to the current colour"));
  52968. const int r = m.showAt (this);
  52969. if (r == 1)
  52970. {
  52971. owner->setCurrentColour (owner->getSwatchColour (index));
  52972. }
  52973. else if (r == 2)
  52974. {
  52975. if (owner->getSwatchColour (index) != owner->getCurrentColour())
  52976. {
  52977. owner->setSwatchColour (index, owner->getCurrentColour());
  52978. repaint();
  52979. }
  52980. }
  52981. }
  52982. private:
  52983. ColourSelector* const owner;
  52984. const int index;
  52985. SwatchComponent (const SwatchComponent&);
  52986. const SwatchComponent& operator= (const SwatchComponent&);
  52987. };
  52988. ColourSelector::ColourSelector (const int flags_,
  52989. const int edgeGap_,
  52990. const int gapAroundColourSpaceComponent)
  52991. : colour (Colours::white),
  52992. flags (flags_),
  52993. topSpace (0),
  52994. edgeGap (edgeGap_)
  52995. {
  52996. // not much point having a selector with no components in it!
  52997. jassert ((flags_ & (showColourAtTop | showSliders | showColourspace)) != 0);
  52998. updateHSV();
  52999. if ((flags & showSliders) != 0)
  53000. {
  53001. addAndMakeVisible (sliders[0] = new ColourComponentSlider (TRANS ("red")));
  53002. addAndMakeVisible (sliders[1] = new ColourComponentSlider (TRANS ("green")));
  53003. addAndMakeVisible (sliders[2] = new ColourComponentSlider (TRANS ("blue")));
  53004. addChildComponent (sliders[3] = new ColourComponentSlider (TRANS ("alpha")));
  53005. sliders[3]->setVisible ((flags & showAlphaChannel) != 0);
  53006. for (int i = 4; --i >= 0;)
  53007. sliders[i]->addListener (this);
  53008. }
  53009. else
  53010. {
  53011. zeromem (sliders, sizeof (sliders));
  53012. }
  53013. if ((flags & showColourspace) != 0)
  53014. {
  53015. addAndMakeVisible (colourSpace = new ColourSpaceView (this, h, s, v, gapAroundColourSpaceComponent));
  53016. addAndMakeVisible (hueSelector = new HueSelectorComp (this, h, s, v, gapAroundColourSpaceComponent));
  53017. }
  53018. else
  53019. {
  53020. colourSpace = 0;
  53021. hueSelector = 0;
  53022. }
  53023. update();
  53024. }
  53025. ColourSelector::~ColourSelector()
  53026. {
  53027. dispatchPendingMessages();
  53028. deleteAllChildren();
  53029. }
  53030. const Colour ColourSelector::getCurrentColour() const
  53031. {
  53032. return ((flags & showAlphaChannel) != 0) ? colour
  53033. : colour.withAlpha ((uint8) 0xff);
  53034. }
  53035. void ColourSelector::setCurrentColour (const Colour& c)
  53036. {
  53037. if (c != colour)
  53038. {
  53039. colour = ((flags & showAlphaChannel) != 0) ? c : c.withAlpha ((uint8) 0xff);
  53040. updateHSV();
  53041. update();
  53042. }
  53043. }
  53044. void ColourSelector::setHue (float newH)
  53045. {
  53046. newH = jlimit (0.0f, 1.0f, newH);
  53047. if (h != newH)
  53048. {
  53049. h = newH;
  53050. colour = Colour (h, s, v, colour.getFloatAlpha());
  53051. update();
  53052. }
  53053. }
  53054. void ColourSelector::setSV (float newS, float newV)
  53055. {
  53056. newS = jlimit (0.0f, 1.0f, newS);
  53057. newV = jlimit (0.0f, 1.0f, newV);
  53058. if (s != newS || v != newV)
  53059. {
  53060. s = newS;
  53061. v = newV;
  53062. colour = Colour (h, s, v, colour.getFloatAlpha());
  53063. update();
  53064. }
  53065. }
  53066. void ColourSelector::updateHSV()
  53067. {
  53068. colour.getHSB (h, s, v);
  53069. }
  53070. void ColourSelector::update()
  53071. {
  53072. if (sliders[0] != 0)
  53073. {
  53074. sliders[0]->setValue ((int) colour.getRed());
  53075. sliders[1]->setValue ((int) colour.getGreen());
  53076. sliders[2]->setValue ((int) colour.getBlue());
  53077. sliders[3]->setValue ((int) colour.getAlpha());
  53078. }
  53079. if (colourSpace != 0)
  53080. {
  53081. ((ColourSpaceView*) colourSpace)->updateIfNeeded();
  53082. ((HueSelectorComp*) hueSelector)->updateIfNeeded();
  53083. }
  53084. if ((flags & showColourAtTop) != 0)
  53085. repaint (0, edgeGap, getWidth(), topSpace - edgeGap);
  53086. sendChangeMessage (this);
  53087. }
  53088. void ColourSelector::paint (Graphics& g)
  53089. {
  53090. g.fillAll (findColour (backgroundColourId));
  53091. if ((flags & showColourAtTop) != 0)
  53092. {
  53093. const Colour colour (getCurrentColour());
  53094. g.fillCheckerBoard (edgeGap, edgeGap, getWidth() - edgeGap - edgeGap, topSpace - edgeGap - edgeGap,
  53095. 10, 10,
  53096. Colour (0xffdddddd).overlaidWith (colour),
  53097. Colour (0xffffffff).overlaidWith (colour));
  53098. g.setColour (Colours::white.overlaidWith (colour).contrasting());
  53099. g.setFont (14.0f, true);
  53100. g.drawText (((flags & showAlphaChannel) != 0)
  53101. ? String::formatted (T("#%02X%02X%02X%02X"),
  53102. (int) colour.getAlpha(),
  53103. (int) colour.getRed(),
  53104. (int) colour.getGreen(),
  53105. (int) colour.getBlue())
  53106. : String::formatted (T("#%02X%02X%02X"),
  53107. (int) colour.getRed(),
  53108. (int) colour.getGreen(),
  53109. (int) colour.getBlue()),
  53110. 0, edgeGap, getWidth(), topSpace - edgeGap * 2,
  53111. Justification::centred, false);
  53112. }
  53113. if ((flags & showSliders) != 0)
  53114. {
  53115. g.setColour (findColour (labelTextColourId));
  53116. g.setFont (11.0f);
  53117. for (int i = 4; --i >= 0;)
  53118. {
  53119. if (sliders[i]->isVisible())
  53120. g.drawText (sliders[i]->getName() + T(":"),
  53121. 0, sliders[i]->getY(),
  53122. sliders[i]->getX() - 8, sliders[i]->getHeight(),
  53123. Justification::centredRight, false);
  53124. }
  53125. }
  53126. }
  53127. void ColourSelector::resized()
  53128. {
  53129. const int numSliders = ((flags & showAlphaChannel) != 0) ? 4 : 3;
  53130. const int numSwatches = getNumSwatches();
  53131. const int swatchSpace = numSwatches > 0 ? edgeGap + swatchHeight * ((numSwatches + 7) / swatchesPerRow) : 0;
  53132. const int sliderSpace = ((flags & showSliders) != 0) ? jmin (22 * numSliders + edgeGap, proportionOfHeight (0.3f)) : 0;
  53133. topSpace = ((flags & showColourAtTop) != 0) ? jmin (30 + edgeGap * 2, proportionOfHeight (0.2f)) : edgeGap;
  53134. int y = topSpace;
  53135. if ((flags & showColourspace) != 0)
  53136. {
  53137. const int hueWidth = jmin (50, proportionOfWidth (0.15f));
  53138. colourSpace->setBounds (edgeGap, y,
  53139. getWidth() - hueWidth - edgeGap - 4,
  53140. getHeight() - topSpace - sliderSpace - swatchSpace - edgeGap);
  53141. hueSelector->setBounds (colourSpace->getRight() + 4, y,
  53142. getWidth() - edgeGap - (colourSpace->getRight() + 4),
  53143. colourSpace->getHeight());
  53144. y = getHeight() - sliderSpace - swatchSpace - edgeGap;
  53145. }
  53146. if ((flags & showSliders) != 0)
  53147. {
  53148. const int sliderHeight = jmax (4, sliderSpace / numSliders);
  53149. for (int i = 0; i < numSliders; ++i)
  53150. {
  53151. sliders[i]->setBounds (proportionOfWidth (0.2f), y,
  53152. proportionOfWidth (0.72f), sliderHeight - 2);
  53153. y += sliderHeight;
  53154. }
  53155. }
  53156. if (numSwatches > 0)
  53157. {
  53158. const int startX = 8;
  53159. const int xGap = 4;
  53160. const int yGap = 4;
  53161. const int swatchWidth = (getWidth() - startX * 2) / swatchesPerRow;
  53162. y += edgeGap;
  53163. if (swatchComponents.size() != numSwatches)
  53164. {
  53165. int i;
  53166. for (i = swatchComponents.size(); --i >= 0;)
  53167. {
  53168. SwatchComponent* const sc = (SwatchComponent*) swatchComponents.getUnchecked(i);
  53169. delete sc;
  53170. }
  53171. for (i = 0; i < numSwatches; ++i)
  53172. {
  53173. SwatchComponent* const sc = new SwatchComponent (this, i);
  53174. swatchComponents.add (sc);
  53175. addAndMakeVisible (sc);
  53176. }
  53177. }
  53178. int x = startX;
  53179. for (int i = 0; i < swatchComponents.size(); ++i)
  53180. {
  53181. SwatchComponent* const sc = (SwatchComponent*) swatchComponents.getUnchecked(i);
  53182. sc->setBounds (x + xGap / 2,
  53183. y + yGap / 2,
  53184. swatchWidth - xGap,
  53185. swatchHeight - yGap);
  53186. if (((i + 1) % swatchesPerRow) == 0)
  53187. {
  53188. x = startX;
  53189. y += swatchHeight;
  53190. }
  53191. else
  53192. {
  53193. x += swatchWidth;
  53194. }
  53195. }
  53196. }
  53197. }
  53198. void ColourSelector::sliderValueChanged (Slider*)
  53199. {
  53200. if (sliders[0] != 0)
  53201. setCurrentColour (Colour ((uint8) sliders[0]->getValue(),
  53202. (uint8) sliders[1]->getValue(),
  53203. (uint8) sliders[2]->getValue(),
  53204. (uint8) sliders[3]->getValue()));
  53205. }
  53206. int ColourSelector::getNumSwatches() const
  53207. {
  53208. return 0;
  53209. }
  53210. const Colour ColourSelector::getSwatchColour (const int) const
  53211. {
  53212. jassertfalse // if you've overridden getNumSwatches(), you also need to implement this method
  53213. return Colours::black;
  53214. }
  53215. void ColourSelector::setSwatchColour (const int, const Colour&) const
  53216. {
  53217. jassertfalse // if you've overridden getNumSwatches(), you also need to implement this method
  53218. }
  53219. END_JUCE_NAMESPACE
  53220. /********* End of inlined file: juce_ColourSelector.cpp *********/
  53221. /********* Start of inlined file: juce_DropShadower.cpp *********/
  53222. BEGIN_JUCE_NAMESPACE
  53223. class ShadowWindow : public Component
  53224. {
  53225. Component* owner;
  53226. Image** shadowImageSections;
  53227. const int type; // 0 = left, 1 = right, 2 = top, 3 = bottom. left + right are full-height
  53228. public:
  53229. ShadowWindow (Component* const owner_,
  53230. const int type_,
  53231. Image** const shadowImageSections_)
  53232. : owner (owner_),
  53233. shadowImageSections (shadowImageSections_),
  53234. type (type_)
  53235. {
  53236. setInterceptsMouseClicks (false, false);
  53237. if (owner_->isOnDesktop())
  53238. {
  53239. setSize (1, 1); // to keep the OS happy by not having zero-size windows
  53240. addToDesktop (ComponentPeer::windowIgnoresMouseClicks
  53241. | ComponentPeer::windowIsTemporary);
  53242. }
  53243. else if (owner_->getParentComponent() != 0)
  53244. {
  53245. owner_->getParentComponent()->addChildComponent (this);
  53246. }
  53247. }
  53248. ~ShadowWindow()
  53249. {
  53250. }
  53251. void paint (Graphics& g)
  53252. {
  53253. Image* const topLeft = shadowImageSections [type * 3];
  53254. Image* const bottomRight = shadowImageSections [type * 3 + 1];
  53255. Image* const filler = shadowImageSections [type * 3 + 2];
  53256. ImageBrush fillBrush (filler, 0, 0, 1.0f);
  53257. g.setOpacity (1.0f);
  53258. if (type < 2)
  53259. {
  53260. int imH = jmin (topLeft->getHeight(), getHeight() / 2);
  53261. g.drawImage (topLeft,
  53262. 0, 0, topLeft->getWidth(), imH,
  53263. 0, 0, topLeft->getWidth(), imH);
  53264. imH = jmin (bottomRight->getHeight(), getHeight() - getHeight() / 2);
  53265. g.drawImage (bottomRight,
  53266. 0, getHeight() - imH, bottomRight->getWidth(), imH,
  53267. 0, bottomRight->getHeight() - imH, bottomRight->getWidth(), imH);
  53268. g.setBrush (&fillBrush);
  53269. g.fillRect (0, topLeft->getHeight(), getWidth(), getHeight() - (topLeft->getHeight() + bottomRight->getHeight()));
  53270. }
  53271. else
  53272. {
  53273. int imW = jmin (topLeft->getWidth(), getWidth() / 2);
  53274. g.drawImage (topLeft,
  53275. 0, 0, imW, topLeft->getHeight(),
  53276. 0, 0, imW, topLeft->getHeight());
  53277. imW = jmin (bottomRight->getWidth(), getWidth() - getWidth() / 2);
  53278. g.drawImage (bottomRight,
  53279. getWidth() - imW, 0, imW, bottomRight->getHeight(),
  53280. bottomRight->getWidth() - imW, 0, imW, bottomRight->getHeight());
  53281. g.setBrush (&fillBrush);
  53282. g.fillRect (topLeft->getWidth(), 0, getWidth() - (topLeft->getWidth() + bottomRight->getWidth()), getHeight());
  53283. }
  53284. }
  53285. void resized()
  53286. {
  53287. repaint(); // (needed for correct repainting)
  53288. }
  53289. private:
  53290. ShadowWindow (const ShadowWindow&);
  53291. const ShadowWindow& operator= (const ShadowWindow&);
  53292. };
  53293. DropShadower::DropShadower (const float alpha_,
  53294. const int xOffset_,
  53295. const int yOffset_,
  53296. const float blurRadius_)
  53297. : owner (0),
  53298. numShadows (0),
  53299. shadowEdge (jmax (xOffset_, yOffset_) + (int) blurRadius_),
  53300. xOffset (xOffset_),
  53301. yOffset (yOffset_),
  53302. alpha (alpha_),
  53303. blurRadius (blurRadius_),
  53304. inDestructor (false),
  53305. reentrant (false)
  53306. {
  53307. }
  53308. DropShadower::~DropShadower()
  53309. {
  53310. if (owner != 0)
  53311. owner->removeComponentListener (this);
  53312. inDestructor = true;
  53313. deleteShadowWindows();
  53314. }
  53315. void DropShadower::deleteShadowWindows()
  53316. {
  53317. if (numShadows > 0)
  53318. {
  53319. int i;
  53320. for (i = numShadows; --i >= 0;)
  53321. delete shadowWindows[i];
  53322. for (i = 12; --i >= 0;)
  53323. delete shadowImageSections[i];
  53324. numShadows = 0;
  53325. }
  53326. }
  53327. void DropShadower::setOwner (Component* componentToFollow)
  53328. {
  53329. if (componentToFollow != owner)
  53330. {
  53331. if (owner != 0)
  53332. owner->removeComponentListener (this);
  53333. // (the component can't be null)
  53334. jassert (componentToFollow != 0);
  53335. owner = componentToFollow;
  53336. jassert (owner != 0);
  53337. jassert (owner->isOpaque()); // doesn't work properly for semi-transparent comps!
  53338. owner->addComponentListener (this);
  53339. updateShadows();
  53340. }
  53341. }
  53342. void DropShadower::componentMovedOrResized (Component&, bool /*wasMoved*/, bool /*wasResized*/)
  53343. {
  53344. updateShadows();
  53345. }
  53346. void DropShadower::componentBroughtToFront (Component&)
  53347. {
  53348. bringShadowWindowsToFront();
  53349. }
  53350. void DropShadower::componentChildrenChanged (Component&)
  53351. {
  53352. }
  53353. void DropShadower::componentParentHierarchyChanged (Component&)
  53354. {
  53355. deleteShadowWindows();
  53356. updateShadows();
  53357. }
  53358. void DropShadower::componentVisibilityChanged (Component&)
  53359. {
  53360. updateShadows();
  53361. }
  53362. void DropShadower::updateShadows()
  53363. {
  53364. if (reentrant || inDestructor || (owner == 0))
  53365. return;
  53366. reentrant = true;
  53367. ComponentPeer* const nw = owner->getPeer();
  53368. const bool isOwnerVisible = owner->isVisible()
  53369. && (nw == 0 || ! nw->isMinimised());
  53370. const bool createShadowWindows = numShadows == 0
  53371. && owner->getWidth() > 0
  53372. && owner->getHeight() > 0
  53373. && isOwnerVisible
  53374. && (Desktop::canUseSemiTransparentWindows()
  53375. || owner->getParentComponent() != 0);
  53376. if (createShadowWindows)
  53377. {
  53378. // keep a cached version of the image to save doing the gaussian too often
  53379. String imageId;
  53380. imageId << shadowEdge << T(',')
  53381. << xOffset << T(',')
  53382. << yOffset << T(',')
  53383. << alpha;
  53384. const int hash = imageId.hashCode();
  53385. Image* bigIm = ImageCache::getFromHashCode (hash);
  53386. if (bigIm == 0)
  53387. {
  53388. bigIm = new Image (Image::ARGB, shadowEdge * 5, shadowEdge * 5, true);
  53389. Graphics bigG (*bigIm);
  53390. bigG.setColour (Colours::black.withAlpha (alpha));
  53391. bigG.fillRect (shadowEdge + xOffset,
  53392. shadowEdge + yOffset,
  53393. bigIm->getWidth() - (shadowEdge * 2),
  53394. bigIm->getHeight() - (shadowEdge * 2));
  53395. ImageConvolutionKernel blurKernel (roundFloatToInt (blurRadius * 2.0f));
  53396. blurKernel.createGaussianBlur (blurRadius);
  53397. blurKernel.applyToImage (*bigIm, 0,
  53398. xOffset,
  53399. yOffset,
  53400. bigIm->getWidth(),
  53401. bigIm->getHeight());
  53402. ImageCache::addImageToCache (bigIm, hash);
  53403. }
  53404. const int iw = bigIm->getWidth();
  53405. const int ih = bigIm->getHeight();
  53406. const int shadowEdge2 = shadowEdge * 2;
  53407. setShadowImage (bigIm, 0, shadowEdge, shadowEdge2, 0, 0);
  53408. setShadowImage (bigIm, 1, shadowEdge, shadowEdge2, 0, ih - shadowEdge2);
  53409. setShadowImage (bigIm, 2, shadowEdge, shadowEdge, 0, shadowEdge2);
  53410. setShadowImage (bigIm, 3, shadowEdge, shadowEdge2, iw - shadowEdge, 0);
  53411. setShadowImage (bigIm, 4, shadowEdge, shadowEdge2, iw - shadowEdge, ih - shadowEdge2);
  53412. setShadowImage (bigIm, 5, shadowEdge, shadowEdge, iw - shadowEdge, shadowEdge2);
  53413. setShadowImage (bigIm, 6, shadowEdge, shadowEdge, shadowEdge, 0);
  53414. setShadowImage (bigIm, 7, shadowEdge, shadowEdge, iw - shadowEdge2, 0);
  53415. setShadowImage (bigIm, 8, shadowEdge, shadowEdge, shadowEdge2, 0);
  53416. setShadowImage (bigIm, 9, shadowEdge, shadowEdge, shadowEdge, ih - shadowEdge);
  53417. setShadowImage (bigIm, 10, shadowEdge, shadowEdge, iw - shadowEdge2, ih - shadowEdge);
  53418. setShadowImage (bigIm, 11, shadowEdge, shadowEdge, shadowEdge2, ih - shadowEdge);
  53419. ImageCache::release (bigIm);
  53420. for (int i = 0; i < 4; ++i)
  53421. {
  53422. shadowWindows[numShadows] = new ShadowWindow (owner, i, shadowImageSections);
  53423. ++numShadows;
  53424. }
  53425. }
  53426. if (numShadows > 0)
  53427. {
  53428. for (int i = numShadows; --i >= 0;)
  53429. {
  53430. shadowWindows[i]->setAlwaysOnTop (owner->isAlwaysOnTop());
  53431. shadowWindows[i]->setVisible (isOwnerVisible);
  53432. }
  53433. const int x = owner->getX();
  53434. const int y = owner->getY() - shadowEdge;
  53435. const int w = owner->getWidth();
  53436. const int h = owner->getHeight() + shadowEdge + shadowEdge;
  53437. shadowWindows[0]->setBounds (x - shadowEdge,
  53438. y,
  53439. shadowEdge,
  53440. h);
  53441. shadowWindows[1]->setBounds (x + w,
  53442. y,
  53443. shadowEdge,
  53444. h);
  53445. shadowWindows[2]->setBounds (x,
  53446. y,
  53447. w,
  53448. shadowEdge);
  53449. shadowWindows[3]->setBounds (x,
  53450. owner->getBottom(),
  53451. w,
  53452. shadowEdge);
  53453. }
  53454. reentrant = false;
  53455. if (createShadowWindows)
  53456. bringShadowWindowsToFront();
  53457. }
  53458. void DropShadower::setShadowImage (Image* const src,
  53459. const int num,
  53460. const int w,
  53461. const int h,
  53462. const int sx,
  53463. const int sy) throw()
  53464. {
  53465. shadowImageSections[num] = new Image (Image::ARGB, w, h, true);
  53466. Graphics g (*shadowImageSections[num]);
  53467. g.drawImage (src, 0, 0, w, h, sx, sy, w, h);
  53468. }
  53469. void DropShadower::bringShadowWindowsToFront()
  53470. {
  53471. if (! (inDestructor || reentrant))
  53472. {
  53473. updateShadows();
  53474. reentrant = true;
  53475. for (int i = numShadows; --i >= 0;)
  53476. shadowWindows[i]->toBehind (owner);
  53477. reentrant = false;
  53478. }
  53479. }
  53480. END_JUCE_NAMESPACE
  53481. /********* End of inlined file: juce_DropShadower.cpp *********/
  53482. /********* Start of inlined file: juce_MagnifierComponent.cpp *********/
  53483. BEGIN_JUCE_NAMESPACE
  53484. class MagnifyingPeer : public ComponentPeer
  53485. {
  53486. public:
  53487. MagnifyingPeer (Component* const component,
  53488. MagnifierComponent* const magnifierComp_)
  53489. : ComponentPeer (component, 0),
  53490. magnifierComp (magnifierComp_)
  53491. {
  53492. }
  53493. ~MagnifyingPeer()
  53494. {
  53495. }
  53496. void* getNativeHandle() const { return 0; }
  53497. void setVisible (bool) {}
  53498. void setTitle (const String&) {}
  53499. void setPosition (int, int) {}
  53500. void setSize (int, int) {}
  53501. void setBounds (int, int, int, int, const bool) {}
  53502. void setMinimised (bool) {}
  53503. bool isMinimised() const { return false; }
  53504. void setFullScreen (bool) {}
  53505. bool isFullScreen() const { return false; }
  53506. const BorderSize getFrameSize() const { return BorderSize (0); }
  53507. bool setAlwaysOnTop (bool) { return true; }
  53508. void toFront (bool) {}
  53509. void toBehind (ComponentPeer*) {}
  53510. void setIcon (const Image&) {}
  53511. bool isFocused() const
  53512. {
  53513. return magnifierComp->hasKeyboardFocus (true);
  53514. }
  53515. void grabFocus()
  53516. {
  53517. ComponentPeer* peer = magnifierComp->getPeer();
  53518. if (peer != 0)
  53519. peer->grabFocus();
  53520. }
  53521. void getBounds (int& x, int& y, int& w, int& h) const
  53522. {
  53523. x = magnifierComp->getScreenX();
  53524. y = magnifierComp->getScreenY();
  53525. w = component->getWidth();
  53526. h = component->getHeight();
  53527. }
  53528. int getScreenX() const { return magnifierComp->getScreenX(); }
  53529. int getScreenY() const { return magnifierComp->getScreenY(); }
  53530. void relativePositionToGlobal (int& x, int& y)
  53531. {
  53532. const double zoom = magnifierComp->getScaleFactor();
  53533. x = roundDoubleToInt (x * zoom);
  53534. y = roundDoubleToInt (y * zoom);
  53535. magnifierComp->relativePositionToGlobal (x, y);
  53536. }
  53537. void globalPositionToRelative (int& x, int& y)
  53538. {
  53539. magnifierComp->globalPositionToRelative (x, y);
  53540. const double zoom = magnifierComp->getScaleFactor();
  53541. x = roundDoubleToInt (x / zoom);
  53542. y = roundDoubleToInt (y / zoom);
  53543. }
  53544. bool contains (int x, int y, bool) const
  53545. {
  53546. return ((unsigned int) x) < (unsigned int) magnifierComp->getWidth()
  53547. && ((unsigned int) y) < (unsigned int) magnifierComp->getHeight();
  53548. }
  53549. void repaint (int x, int y, int w, int h)
  53550. {
  53551. const double zoom = magnifierComp->getScaleFactor();
  53552. magnifierComp->repaint ((int) (x * zoom),
  53553. (int) (y * zoom),
  53554. roundDoubleToInt (w * zoom) + 1,
  53555. roundDoubleToInt (h * zoom) + 1);
  53556. }
  53557. void performAnyPendingRepaintsNow()
  53558. {
  53559. }
  53560. juce_UseDebuggingNewOperator
  53561. private:
  53562. MagnifierComponent* const magnifierComp;
  53563. MagnifyingPeer (const MagnifyingPeer&);
  53564. const MagnifyingPeer& operator= (const MagnifyingPeer&);
  53565. };
  53566. class PeerHolderComp : public Component
  53567. {
  53568. public:
  53569. PeerHolderComp (MagnifierComponent* const magnifierComp_)
  53570. : magnifierComp (magnifierComp_)
  53571. {
  53572. setVisible (true);
  53573. }
  53574. ~PeerHolderComp()
  53575. {
  53576. }
  53577. ComponentPeer* createNewPeer (int, void*)
  53578. {
  53579. return new MagnifyingPeer (this, magnifierComp);
  53580. }
  53581. void childBoundsChanged (Component* c)
  53582. {
  53583. if (c != 0)
  53584. {
  53585. setSize (c->getWidth(), c->getHeight());
  53586. magnifierComp->childBoundsChanged (this);
  53587. }
  53588. }
  53589. void mouseWheelMove (const MouseEvent& e, float ix, float iy)
  53590. {
  53591. // unhandled mouse wheel moves can be referred upwards to the parent comp..
  53592. Component* const p = magnifierComp->getParentComponent();
  53593. if (p != 0)
  53594. p->mouseWheelMove (e.getEventRelativeTo (p), ix, iy);
  53595. }
  53596. private:
  53597. MagnifierComponent* const magnifierComp;
  53598. PeerHolderComp (const PeerHolderComp&);
  53599. const PeerHolderComp& operator= (const PeerHolderComp&);
  53600. };
  53601. MagnifierComponent::MagnifierComponent (Component* const content_,
  53602. const bool deleteContentCompWhenNoLongerNeeded)
  53603. : content (content_),
  53604. scaleFactor (0.0),
  53605. peer (0),
  53606. deleteContent (deleteContentCompWhenNoLongerNeeded)
  53607. {
  53608. holderComp = new PeerHolderComp (this);
  53609. setScaleFactor (1.0);
  53610. }
  53611. MagnifierComponent::~MagnifierComponent()
  53612. {
  53613. delete holderComp;
  53614. if (deleteContent)
  53615. delete content;
  53616. }
  53617. void MagnifierComponent::setScaleFactor (double newScaleFactor)
  53618. {
  53619. jassert (newScaleFactor > 0.0); // hmm - unlikely to work well with a negative scale factor
  53620. newScaleFactor = jlimit (1.0 / 8.0, 1000.0, newScaleFactor);
  53621. if (scaleFactor != newScaleFactor)
  53622. {
  53623. scaleFactor = newScaleFactor;
  53624. if (scaleFactor == 1.0)
  53625. {
  53626. holderComp->removeFromDesktop();
  53627. peer = 0;
  53628. addChildComponent (content);
  53629. childBoundsChanged (content);
  53630. }
  53631. else
  53632. {
  53633. holderComp->addAndMakeVisible (content);
  53634. holderComp->childBoundsChanged (content);
  53635. childBoundsChanged (holderComp);
  53636. holderComp->addToDesktop (0);
  53637. peer = holderComp->getPeer();
  53638. }
  53639. repaint();
  53640. }
  53641. }
  53642. void MagnifierComponent::paint (Graphics& g)
  53643. {
  53644. const int w = holderComp->getWidth();
  53645. const int h = holderComp->getHeight();
  53646. if (w == 0 || h == 0)
  53647. return;
  53648. const Rectangle r (g.getClipBounds());
  53649. const int srcX = (int) (r.getX() / scaleFactor);
  53650. const int srcY = (int) (r.getY() / scaleFactor);
  53651. int srcW = roundDoubleToInt (r.getRight() / scaleFactor) - srcX;
  53652. int srcH = roundDoubleToInt (r.getBottom() / scaleFactor) - srcY;
  53653. if (scaleFactor >= 1.0)
  53654. {
  53655. ++srcW;
  53656. ++srcH;
  53657. }
  53658. Image temp (Image::ARGB, jmax (w, srcX + srcW), jmax (h, srcY + srcH), false);
  53659. temp.clear (srcX, srcY, srcW, srcH);
  53660. Graphics g2 (temp);
  53661. g2.reduceClipRegion (srcX, srcY, srcW, srcH);
  53662. holderComp->paintEntireComponent (g2);
  53663. g.setImageResamplingQuality (Graphics::lowResamplingQuality);
  53664. g.drawImage (&temp,
  53665. 0, 0, (int) (w * scaleFactor), (int) (h * scaleFactor),
  53666. 0, 0, w, h,
  53667. false);
  53668. }
  53669. void MagnifierComponent::childBoundsChanged (Component* c)
  53670. {
  53671. if (c != 0)
  53672. setSize (roundDoubleToInt (c->getWidth() * scaleFactor),
  53673. roundDoubleToInt (c->getHeight() * scaleFactor));
  53674. }
  53675. void MagnifierComponent::mouseDown (const MouseEvent& e)
  53676. {
  53677. if (peer != 0)
  53678. peer->handleMouseDown (scaleInt (e.x), scaleInt (e.y), e.eventTime.toMilliseconds());
  53679. }
  53680. void MagnifierComponent::mouseUp (const MouseEvent& e)
  53681. {
  53682. if (peer != 0)
  53683. peer->handleMouseUp (e.mods.getRawFlags(), scaleInt (e.x), scaleInt (e.y), e.eventTime.toMilliseconds());
  53684. }
  53685. void MagnifierComponent::mouseDrag (const MouseEvent& e)
  53686. {
  53687. if (peer != 0)
  53688. peer->handleMouseDrag (scaleInt (e.x), scaleInt (e.y), e.eventTime.toMilliseconds());
  53689. }
  53690. void MagnifierComponent::mouseMove (const MouseEvent& e)
  53691. {
  53692. if (peer != 0)
  53693. peer->handleMouseMove (scaleInt (e.x), scaleInt (e.y), e.eventTime.toMilliseconds());
  53694. }
  53695. void MagnifierComponent::mouseEnter (const MouseEvent& e)
  53696. {
  53697. if (peer != 0)
  53698. peer->handleMouseEnter (scaleInt (e.x), scaleInt (e.y), e.eventTime.toMilliseconds());
  53699. }
  53700. void MagnifierComponent::mouseExit (const MouseEvent& e)
  53701. {
  53702. if (peer != 0)
  53703. peer->handleMouseExit (scaleInt (e.x), scaleInt (e.y), e.eventTime.toMilliseconds());
  53704. }
  53705. void MagnifierComponent::mouseWheelMove (const MouseEvent& e, float ix, float iy)
  53706. {
  53707. if (peer != 0)
  53708. peer->handleMouseWheel (roundFloatToInt (ix * 256.0f),
  53709. roundFloatToInt (iy * 256.0f),
  53710. e.eventTime.toMilliseconds());
  53711. else
  53712. Component::mouseWheelMove (e, ix, iy);
  53713. }
  53714. int MagnifierComponent::scaleInt (const int n) const throw()
  53715. {
  53716. return roundDoubleToInt (n / scaleFactor);
  53717. }
  53718. END_JUCE_NAMESPACE
  53719. /********* End of inlined file: juce_MagnifierComponent.cpp *********/
  53720. /********* Start of inlined file: juce_MidiKeyboardComponent.cpp *********/
  53721. BEGIN_JUCE_NAMESPACE
  53722. class MidiKeyboardUpDownButton : public Button
  53723. {
  53724. public:
  53725. MidiKeyboardUpDownButton (MidiKeyboardComponent* const owner_,
  53726. const int delta_)
  53727. : Button (String::empty),
  53728. owner (owner_),
  53729. delta (delta_)
  53730. {
  53731. setOpaque (true);
  53732. }
  53733. ~MidiKeyboardUpDownButton()
  53734. {
  53735. }
  53736. void clicked()
  53737. {
  53738. int note = owner->getLowestVisibleKey();
  53739. if (delta < 0)
  53740. note = (note - 1) / 12;
  53741. else
  53742. note = note / 12 + 1;
  53743. owner->setLowestVisibleKey (note * 12);
  53744. }
  53745. void paintButton (Graphics& g,
  53746. bool isMouseOverButton,
  53747. bool isButtonDown)
  53748. {
  53749. owner->drawUpDownButton (g, getWidth(), getHeight(),
  53750. isMouseOverButton, isButtonDown,
  53751. delta > 0);
  53752. }
  53753. private:
  53754. MidiKeyboardComponent* const owner;
  53755. const int delta;
  53756. MidiKeyboardUpDownButton (const MidiKeyboardUpDownButton&);
  53757. const MidiKeyboardUpDownButton& operator= (const MidiKeyboardUpDownButton&);
  53758. };
  53759. MidiKeyboardComponent::MidiKeyboardComponent (MidiKeyboardState& state_,
  53760. const Orientation orientation_)
  53761. : state (state_),
  53762. xOffset (0),
  53763. blackNoteLength (1),
  53764. keyWidth (16.0f),
  53765. orientation (orientation_),
  53766. midiChannel (1),
  53767. midiInChannelMask (0xffff),
  53768. velocity (1.0f),
  53769. noteUnderMouse (-1),
  53770. mouseDownNote (-1),
  53771. rangeStart (0),
  53772. rangeEnd (127),
  53773. firstKey (12 * 4),
  53774. canScroll (true),
  53775. mouseDragging (false),
  53776. keyPresses (4),
  53777. keyPressNotes (16),
  53778. keyMappingOctave (6),
  53779. octaveNumForMiddleC (3)
  53780. {
  53781. addChildComponent (scrollDown = new MidiKeyboardUpDownButton (this, -1));
  53782. addChildComponent (scrollUp = new MidiKeyboardUpDownButton (this, 1));
  53783. // initialise with a default set of querty key-mappings..
  53784. const char* const keymap = "awsedftgyhujkolp;";
  53785. for (int i = String (keymap).length(); --i >= 0;)
  53786. setKeyPressForNote (KeyPress (keymap[i], 0, 0), i);
  53787. setOpaque (true);
  53788. setWantsKeyboardFocus (true);
  53789. state.addListener (this);
  53790. }
  53791. MidiKeyboardComponent::~MidiKeyboardComponent()
  53792. {
  53793. state.removeListener (this);
  53794. jassert (mouseDownNote < 0 && keysPressed.countNumberOfSetBits() == 0); // leaving stuck notes!
  53795. deleteAllChildren();
  53796. }
  53797. void MidiKeyboardComponent::setKeyWidth (const float widthInPixels)
  53798. {
  53799. keyWidth = widthInPixels;
  53800. resized();
  53801. }
  53802. void MidiKeyboardComponent::setOrientation (const Orientation newOrientation)
  53803. {
  53804. if (orientation != newOrientation)
  53805. {
  53806. orientation = newOrientation;
  53807. resized();
  53808. }
  53809. }
  53810. void MidiKeyboardComponent::setAvailableRange (const int lowestNote,
  53811. const int highestNote)
  53812. {
  53813. jassert (lowestNote >= 0 && lowestNote <= 127);
  53814. jassert (highestNote >= 0 && highestNote <= 127);
  53815. jassert (lowestNote <= highestNote);
  53816. if (rangeStart != lowestNote || rangeEnd != highestNote)
  53817. {
  53818. rangeStart = jlimit (0, 127, lowestNote);
  53819. rangeEnd = jlimit (0, 127, highestNote);
  53820. firstKey = jlimit (rangeStart, rangeEnd, firstKey);
  53821. resized();
  53822. }
  53823. }
  53824. void MidiKeyboardComponent::setLowestVisibleKey (int noteNumber)
  53825. {
  53826. noteNumber = jlimit (rangeStart, rangeEnd, noteNumber);
  53827. if (noteNumber != firstKey)
  53828. {
  53829. firstKey = noteNumber;
  53830. sendChangeMessage (this);
  53831. resized();
  53832. }
  53833. }
  53834. void MidiKeyboardComponent::setScrollButtonsVisible (const bool canScroll_)
  53835. {
  53836. if (canScroll != canScroll_)
  53837. {
  53838. canScroll = canScroll_;
  53839. resized();
  53840. }
  53841. }
  53842. void MidiKeyboardComponent::colourChanged()
  53843. {
  53844. repaint();
  53845. }
  53846. void MidiKeyboardComponent::setMidiChannel (const int midiChannelNumber)
  53847. {
  53848. jassert (midiChannelNumber > 0 && midiChannelNumber <= 16);
  53849. if (midiChannel != midiChannelNumber)
  53850. {
  53851. resetAnyKeysInUse();
  53852. midiChannel = jlimit (1, 16, midiChannelNumber);
  53853. }
  53854. }
  53855. void MidiKeyboardComponent::setMidiChannelsToDisplay (const int midiChannelMask)
  53856. {
  53857. midiInChannelMask = midiChannelMask;
  53858. triggerAsyncUpdate();
  53859. }
  53860. void MidiKeyboardComponent::setVelocity (const float velocity_)
  53861. {
  53862. jassert (velocity > 0 && velocity <= 1.0f);
  53863. velocity = jlimit (0.0f, 1.0f, velocity_);
  53864. }
  53865. void MidiKeyboardComponent::getKeyPosition (int midiNoteNumber, const float keyWidth, int& x, int& w) const
  53866. {
  53867. jassert (midiNoteNumber >= 0 && midiNoteNumber < 128);
  53868. static const float blackNoteWidth = 0.7f;
  53869. static const float notePos[] = { 0.0f, 1 - blackNoteWidth * 0.6f,
  53870. 1.0f, 2 - blackNoteWidth * 0.4f,
  53871. 2.0f, 3.0f, 4 - blackNoteWidth * 0.7f,
  53872. 4.0f, 5 - blackNoteWidth * 0.5f,
  53873. 5.0f, 6 - blackNoteWidth * 0.3f,
  53874. 6.0f };
  53875. static const float widths[] = { 1.0f, blackNoteWidth,
  53876. 1.0f, blackNoteWidth,
  53877. 1.0f, 1.0f, blackNoteWidth,
  53878. 1.0f, blackNoteWidth,
  53879. 1.0f, blackNoteWidth,
  53880. 1.0f };
  53881. const int octave = midiNoteNumber / 12;
  53882. const int note = midiNoteNumber % 12;
  53883. x = roundFloatToInt (octave * 7.0f * keyWidth + notePos [note] * keyWidth);
  53884. w = roundFloatToInt (widths [note] * keyWidth);
  53885. }
  53886. void MidiKeyboardComponent::getKeyPos (int midiNoteNumber, int& x, int& w) const
  53887. {
  53888. getKeyPosition (midiNoteNumber, keyWidth, x, w);
  53889. int rx, rw;
  53890. getKeyPosition (rangeStart, keyWidth, rx, rw);
  53891. x -= xOffset + rx;
  53892. }
  53893. int MidiKeyboardComponent::getKeyStartPosition (const int midiNoteNumber) const
  53894. {
  53895. int x, y;
  53896. getKeyPos (midiNoteNumber, x, y);
  53897. return x;
  53898. }
  53899. static const uint8 whiteNotes[] = { 0, 2, 4, 5, 7, 9, 11 };
  53900. static const uint8 blackNotes[] = { 1, 3, 6, 8, 10 };
  53901. int MidiKeyboardComponent::xyToNote (int x, int y)
  53902. {
  53903. if (! reallyContains (x, y, false))
  53904. return -1;
  53905. if (orientation != horizontalKeyboard)
  53906. {
  53907. swapVariables (x, y);
  53908. if (orientation == verticalKeyboardFacingLeft)
  53909. y = getWidth() - y;
  53910. else
  53911. x = getHeight() - x;
  53912. }
  53913. return remappedXYToNote (x + xOffset, y);
  53914. }
  53915. int MidiKeyboardComponent::remappedXYToNote (int x, int y) const
  53916. {
  53917. if (y < blackNoteLength)
  53918. {
  53919. for (int octaveStart = 12 * (rangeStart / 12); octaveStart < rangeEnd; octaveStart += 12)
  53920. {
  53921. for (int i = 0; i < 5; ++i)
  53922. {
  53923. const int note = octaveStart + blackNotes [i];
  53924. if (note >= rangeStart && note <= rangeEnd)
  53925. {
  53926. int kx, kw;
  53927. getKeyPos (note, kx, kw);
  53928. kx += xOffset;
  53929. if (x >= kx && x < kx + kw)
  53930. return note;
  53931. }
  53932. }
  53933. }
  53934. }
  53935. for (int octaveStart = 12 * (rangeStart / 12); octaveStart < rangeEnd; octaveStart += 12)
  53936. {
  53937. for (int i = 0; i < 7; ++i)
  53938. {
  53939. const int note = octaveStart + whiteNotes [i];
  53940. if (note >= rangeStart && note <= rangeEnd)
  53941. {
  53942. int kx, kw;
  53943. getKeyPos (note, kx, kw);
  53944. kx += xOffset;
  53945. if (x >= kx && x < kx + kw)
  53946. return note;
  53947. }
  53948. }
  53949. }
  53950. return -1;
  53951. }
  53952. void MidiKeyboardComponent::repaintNote (const int noteNum)
  53953. {
  53954. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  53955. {
  53956. int x, w;
  53957. getKeyPos (noteNum, x, w);
  53958. if (orientation == horizontalKeyboard)
  53959. repaint (x, 0, w, getHeight());
  53960. else if (orientation == verticalKeyboardFacingLeft)
  53961. repaint (0, x, getWidth(), w);
  53962. else if (orientation == verticalKeyboardFacingRight)
  53963. repaint (0, getHeight() - x - w, getWidth(), w);
  53964. }
  53965. }
  53966. void MidiKeyboardComponent::paint (Graphics& g)
  53967. {
  53968. g.fillAll (Colours::white.overlaidWith (findColour (whiteNoteColourId)));
  53969. const Colour lineColour (findColour (keySeparatorLineColourId));
  53970. const Colour textColour (findColour (textLabelColourId));
  53971. int x, w, octave;
  53972. for (octave = 0; octave < 128; octave += 12)
  53973. {
  53974. for (int white = 0; white < 7; ++white)
  53975. {
  53976. const int noteNum = octave + whiteNotes [white];
  53977. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  53978. {
  53979. getKeyPos (noteNum, x, w);
  53980. if (orientation == horizontalKeyboard)
  53981. drawWhiteNote (noteNum, g, x, 0, w, getHeight(),
  53982. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  53983. noteUnderMouse == noteNum,
  53984. lineColour, textColour);
  53985. else if (orientation == verticalKeyboardFacingLeft)
  53986. drawWhiteNote (noteNum, g, 0, x, getWidth(), w,
  53987. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  53988. noteUnderMouse == noteNum,
  53989. lineColour, textColour);
  53990. else if (orientation == verticalKeyboardFacingRight)
  53991. drawWhiteNote (noteNum, g, 0, getHeight() - x - w, getWidth(), w,
  53992. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  53993. noteUnderMouse == noteNum,
  53994. lineColour, textColour);
  53995. }
  53996. }
  53997. }
  53998. float x1 = 0.0f, y1 = 0.0f, x2 = 0.0f, y2 = 0.0f;
  53999. if (orientation == verticalKeyboardFacingLeft)
  54000. {
  54001. x1 = getWidth() - 1.0f;
  54002. x2 = getWidth() - 5.0f;
  54003. }
  54004. else if (orientation == verticalKeyboardFacingRight)
  54005. x2 = 5.0f;
  54006. else
  54007. y2 = 5.0f;
  54008. GradientBrush gb (Colours::black.withAlpha (0.3f), x1, y1,
  54009. Colours::transparentBlack, x2, y2, false);
  54010. g.setBrush (&gb);
  54011. getKeyPos (rangeEnd, x, w);
  54012. x += w;
  54013. if (orientation == verticalKeyboardFacingLeft)
  54014. g.fillRect (getWidth() - 5, 0, 5, x);
  54015. else if (orientation == verticalKeyboardFacingRight)
  54016. g.fillRect (0, 0, 5, x);
  54017. else
  54018. g.fillRect (0, 0, x, 5);
  54019. g.setColour (lineColour);
  54020. if (orientation == verticalKeyboardFacingLeft)
  54021. g.fillRect (0, 0, 1, x);
  54022. else if (orientation == verticalKeyboardFacingRight)
  54023. g.fillRect (getWidth() - 1, 0, 1, x);
  54024. else
  54025. g.fillRect (0, getHeight() - 1, x, 1);
  54026. const Colour blackNoteColour (findColour (blackNoteColourId));
  54027. for (octave = 0; octave < 128; octave += 12)
  54028. {
  54029. for (int black = 0; black < 5; ++black)
  54030. {
  54031. const int noteNum = octave + blackNotes [black];
  54032. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  54033. {
  54034. getKeyPos (noteNum, x, w);
  54035. if (orientation == horizontalKeyboard)
  54036. drawBlackNote (noteNum, g, x, 0, w, blackNoteLength,
  54037. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  54038. noteUnderMouse == noteNum,
  54039. blackNoteColour);
  54040. else if (orientation == verticalKeyboardFacingLeft)
  54041. drawBlackNote (noteNum, g, getWidth() - blackNoteLength, x, blackNoteLength, w,
  54042. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  54043. noteUnderMouse == noteNum,
  54044. blackNoteColour);
  54045. else if (orientation == verticalKeyboardFacingRight)
  54046. drawBlackNote (noteNum, g, 0, getHeight() - x - w, blackNoteLength, w,
  54047. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  54048. noteUnderMouse == noteNum,
  54049. blackNoteColour);
  54050. }
  54051. }
  54052. }
  54053. }
  54054. void MidiKeyboardComponent::drawWhiteNote (int midiNoteNumber,
  54055. Graphics& g, int x, int y, int w, int h,
  54056. bool isDown, bool isOver,
  54057. const Colour& lineColour,
  54058. const Colour& textColour)
  54059. {
  54060. Colour c (Colours::transparentWhite);
  54061. if (isDown)
  54062. c = findColour (keyDownOverlayColourId);
  54063. if (isOver)
  54064. c = c.overlaidWith (findColour (mouseOverKeyOverlayColourId));
  54065. g.setColour (c);
  54066. g.fillRect (x, y, w, h);
  54067. const String text (getWhiteNoteText (midiNoteNumber));
  54068. if (! text.isEmpty())
  54069. {
  54070. g.setColour (textColour);
  54071. Font f (jmin (12.0f, keyWidth * 0.9f));
  54072. f.setHorizontalScale (0.8f);
  54073. g.setFont (f);
  54074. Justification justification (Justification::centredBottom);
  54075. if (orientation == verticalKeyboardFacingLeft)
  54076. justification = Justification::centredLeft;
  54077. else if (orientation == verticalKeyboardFacingRight)
  54078. justification = Justification::centredRight;
  54079. g.drawFittedText (text, x + 2, y + 2, w - 4, h - 4, justification, 1);
  54080. }
  54081. g.setColour (lineColour);
  54082. if (orientation == horizontalKeyboard)
  54083. g.fillRect (x, y, 1, h);
  54084. else if (orientation == verticalKeyboardFacingLeft)
  54085. g.fillRect (x, y, w, 1);
  54086. else if (orientation == verticalKeyboardFacingRight)
  54087. g.fillRect (x, y + h - 1, w, 1);
  54088. if (midiNoteNumber == rangeEnd)
  54089. {
  54090. if (orientation == horizontalKeyboard)
  54091. g.fillRect (x + w, y, 1, h);
  54092. else if (orientation == verticalKeyboardFacingLeft)
  54093. g.fillRect (x, y + h, w, 1);
  54094. else if (orientation == verticalKeyboardFacingRight)
  54095. g.fillRect (x, y - 1, w, 1);
  54096. }
  54097. }
  54098. void MidiKeyboardComponent::drawBlackNote (int /*midiNoteNumber*/,
  54099. Graphics& g, int x, int y, int w, int h,
  54100. bool isDown, bool isOver,
  54101. const Colour& noteFillColour)
  54102. {
  54103. Colour c (noteFillColour);
  54104. if (isDown)
  54105. c = c.overlaidWith (findColour (keyDownOverlayColourId));
  54106. if (isOver)
  54107. c = c.overlaidWith (findColour (mouseOverKeyOverlayColourId));
  54108. g.setColour (c);
  54109. g.fillRect (x, y, w, h);
  54110. if (isDown)
  54111. {
  54112. g.setColour (noteFillColour);
  54113. g.drawRect (x, y, w, h);
  54114. }
  54115. else
  54116. {
  54117. const int xIndent = jmax (1, jmin (w, h) / 8);
  54118. g.setColour (c.brighter());
  54119. if (orientation == horizontalKeyboard)
  54120. g.fillRect (x + xIndent, y, w - xIndent * 2, 7 * h / 8);
  54121. else if (orientation == verticalKeyboardFacingLeft)
  54122. g.fillRect (x + w / 8, y + xIndent, w - w / 8, h - xIndent * 2);
  54123. else if (orientation == verticalKeyboardFacingRight)
  54124. g.fillRect (x, y + xIndent, 7 * w / 8, h - xIndent * 2);
  54125. }
  54126. }
  54127. void MidiKeyboardComponent::setOctaveForMiddleC (const int octaveNumForMiddleC_) throw()
  54128. {
  54129. octaveNumForMiddleC = octaveNumForMiddleC_;
  54130. repaint();
  54131. }
  54132. const String MidiKeyboardComponent::getWhiteNoteText (const int midiNoteNumber)
  54133. {
  54134. if (keyWidth > 14.0f && midiNoteNumber % 12 == 0)
  54135. return MidiMessage::getMidiNoteName (midiNoteNumber, true, true, octaveNumForMiddleC);
  54136. return String::empty;
  54137. }
  54138. void MidiKeyboardComponent::drawUpDownButton (Graphics& g, int w, int h,
  54139. const bool isMouseOver,
  54140. const bool isButtonDown,
  54141. const bool movesOctavesUp)
  54142. {
  54143. g.fillAll (findColour (upDownButtonBackgroundColourId));
  54144. float angle;
  54145. if (orientation == MidiKeyboardComponent::horizontalKeyboard)
  54146. angle = movesOctavesUp ? 0.0f : 0.5f;
  54147. else if (orientation == MidiKeyboardComponent::verticalKeyboardFacingLeft)
  54148. angle = movesOctavesUp ? 0.25f : 0.75f;
  54149. else
  54150. angle = movesOctavesUp ? 0.75f : 0.25f;
  54151. Path path;
  54152. path.lineTo (0.0f, 1.0f);
  54153. path.lineTo (1.0f, 0.5f);
  54154. path.closeSubPath();
  54155. path.applyTransform (AffineTransform::rotation (float_Pi * 2.0f * angle, 0.5f, 0.5f));
  54156. g.setColour (findColour (upDownButtonArrowColourId)
  54157. .withAlpha (isButtonDown ? 1.0f : (isMouseOver ? 0.6f : 0.4f)));
  54158. g.fillPath (path, path.getTransformToScaleToFit (1.0f, 1.0f,
  54159. w - 2.0f,
  54160. h - 2.0f,
  54161. true));
  54162. }
  54163. void MidiKeyboardComponent::resized()
  54164. {
  54165. int w = getWidth();
  54166. int h = getHeight();
  54167. if (w > 0 && h > 0)
  54168. {
  54169. if (orientation != horizontalKeyboard)
  54170. swapVariables (w, h);
  54171. blackNoteLength = roundFloatToInt (h * 0.7f);
  54172. int kx2, kw2;
  54173. getKeyPos (rangeEnd, kx2, kw2);
  54174. kx2 += kw2;
  54175. if (firstKey != rangeStart)
  54176. {
  54177. int kx1, kw1;
  54178. getKeyPos (rangeStart, kx1, kw1);
  54179. if (kx2 - kx1 <= w)
  54180. {
  54181. firstKey = rangeStart;
  54182. sendChangeMessage (this);
  54183. repaint();
  54184. }
  54185. }
  54186. const bool showScrollButtons = canScroll && (firstKey > rangeStart || kx2 > w + xOffset * 2);
  54187. scrollDown->setVisible (showScrollButtons);
  54188. scrollUp->setVisible (showScrollButtons);
  54189. xOffset = 0;
  54190. if (showScrollButtons)
  54191. {
  54192. const int scrollButtonW = jmin (12, w / 2);
  54193. if (orientation == horizontalKeyboard)
  54194. {
  54195. scrollDown->setBounds (0, 0, scrollButtonW, getHeight());
  54196. scrollUp->setBounds (getWidth() - scrollButtonW, 0, scrollButtonW, getHeight());
  54197. }
  54198. else if (orientation == verticalKeyboardFacingLeft)
  54199. {
  54200. scrollDown->setBounds (0, 0, getWidth(), scrollButtonW);
  54201. scrollUp->setBounds (0, getHeight() - scrollButtonW, getWidth(), scrollButtonW);
  54202. }
  54203. else if (orientation == verticalKeyboardFacingRight)
  54204. {
  54205. scrollDown->setBounds (0, getHeight() - scrollButtonW, getWidth(), scrollButtonW);
  54206. scrollUp->setBounds (0, 0, getWidth(), scrollButtonW);
  54207. }
  54208. int endOfLastKey, kw;
  54209. getKeyPos (rangeEnd, endOfLastKey, kw);
  54210. endOfLastKey += kw;
  54211. const int spaceAvailable = w - scrollButtonW * 2;
  54212. const int lastStartKey = remappedXYToNote (endOfLastKey - spaceAvailable, 0) + 1;
  54213. if (lastStartKey >= 0 && firstKey > lastStartKey)
  54214. {
  54215. firstKey = jlimit (rangeStart, rangeEnd, lastStartKey);
  54216. sendChangeMessage (this);
  54217. }
  54218. int newOffset = 0;
  54219. getKeyPos (firstKey, newOffset, kw);
  54220. xOffset = newOffset - scrollButtonW;
  54221. }
  54222. else
  54223. {
  54224. firstKey = rangeStart;
  54225. }
  54226. timerCallback();
  54227. repaint();
  54228. }
  54229. }
  54230. void MidiKeyboardComponent::handleNoteOn (MidiKeyboardState*, int /*midiChannel*/, int /*midiNoteNumber*/, float /*velocity*/)
  54231. {
  54232. triggerAsyncUpdate();
  54233. }
  54234. void MidiKeyboardComponent::handleNoteOff (MidiKeyboardState*, int /*midiChannel*/, int /*midiNoteNumber*/)
  54235. {
  54236. triggerAsyncUpdate();
  54237. }
  54238. void MidiKeyboardComponent::handleAsyncUpdate()
  54239. {
  54240. for (int i = rangeStart; i <= rangeEnd; ++i)
  54241. {
  54242. if (keysCurrentlyDrawnDown[i] != state.isNoteOnForChannels (midiInChannelMask, i))
  54243. {
  54244. keysCurrentlyDrawnDown.setBit (i, state.isNoteOnForChannels (midiInChannelMask, i));
  54245. repaintNote (i);
  54246. }
  54247. }
  54248. }
  54249. void MidiKeyboardComponent::resetAnyKeysInUse()
  54250. {
  54251. if (keysPressed.countNumberOfSetBits() > 0 || mouseDownNote > 0)
  54252. {
  54253. state.allNotesOff (midiChannel);
  54254. keysPressed.clear();
  54255. mouseDownNote = -1;
  54256. }
  54257. }
  54258. void MidiKeyboardComponent::updateNoteUnderMouse (int x, int y)
  54259. {
  54260. const int newNote = (mouseDragging || isMouseOver())
  54261. ? xyToNote (x, y) : -1;
  54262. if (noteUnderMouse != newNote)
  54263. {
  54264. if (mouseDownNote >= 0)
  54265. {
  54266. state.noteOff (midiChannel, mouseDownNote);
  54267. mouseDownNote = -1;
  54268. }
  54269. if (mouseDragging && newNote >= 0)
  54270. {
  54271. state.noteOn (midiChannel, newNote, velocity);
  54272. mouseDownNote = newNote;
  54273. }
  54274. repaintNote (noteUnderMouse);
  54275. noteUnderMouse = newNote;
  54276. repaintNote (noteUnderMouse);
  54277. }
  54278. else if (mouseDownNote >= 0 && ! mouseDragging)
  54279. {
  54280. state.noteOff (midiChannel, mouseDownNote);
  54281. mouseDownNote = -1;
  54282. }
  54283. }
  54284. void MidiKeyboardComponent::mouseMove (const MouseEvent& e)
  54285. {
  54286. updateNoteUnderMouse (e.x, e.y);
  54287. stopTimer();
  54288. }
  54289. void MidiKeyboardComponent::mouseDrag (const MouseEvent& e)
  54290. {
  54291. const int newNote = xyToNote (e.x, e.y);
  54292. if (newNote >= 0)
  54293. mouseDraggedToKey (newNote, e);
  54294. updateNoteUnderMouse (e.x, e.y);
  54295. }
  54296. bool MidiKeyboardComponent::mouseDownOnKey (int /*midiNoteNumber*/, const MouseEvent&)
  54297. {
  54298. return true;
  54299. }
  54300. void MidiKeyboardComponent::mouseDraggedToKey (int /*midiNoteNumber*/, const MouseEvent&)
  54301. {
  54302. }
  54303. void MidiKeyboardComponent::mouseDown (const MouseEvent& e)
  54304. {
  54305. const int newNote = xyToNote (e.x, e.y);
  54306. mouseDragging = false;
  54307. if (newNote >= 0 && mouseDownOnKey (newNote, e))
  54308. {
  54309. repaintNote (noteUnderMouse);
  54310. noteUnderMouse = -1;
  54311. mouseDragging = true;
  54312. updateNoteUnderMouse (e.x, e.y);
  54313. startTimer (500);
  54314. }
  54315. }
  54316. void MidiKeyboardComponent::mouseUp (const MouseEvent& e)
  54317. {
  54318. mouseDragging = false;
  54319. updateNoteUnderMouse (e.x, e.y);
  54320. stopTimer();
  54321. }
  54322. void MidiKeyboardComponent::mouseEnter (const MouseEvent& e)
  54323. {
  54324. updateNoteUnderMouse (e.x, e.y);
  54325. }
  54326. void MidiKeyboardComponent::mouseExit (const MouseEvent& e)
  54327. {
  54328. updateNoteUnderMouse (e.x, e.y);
  54329. }
  54330. void MidiKeyboardComponent::mouseWheelMove (const MouseEvent&, float ix, float iy)
  54331. {
  54332. setLowestVisibleKey (getLowestVisibleKey() + roundFloatToInt ((ix != 0 ? ix : iy) * 5.0f));
  54333. }
  54334. void MidiKeyboardComponent::timerCallback()
  54335. {
  54336. int mx, my;
  54337. getMouseXYRelative (mx, my);
  54338. updateNoteUnderMouse (mx, my);
  54339. }
  54340. void MidiKeyboardComponent::clearKeyMappings()
  54341. {
  54342. resetAnyKeysInUse();
  54343. keyPressNotes.clear();
  54344. keyPresses.clear();
  54345. }
  54346. void MidiKeyboardComponent::setKeyPressForNote (const KeyPress& key,
  54347. const int midiNoteOffsetFromC)
  54348. {
  54349. removeKeyPressForNote (midiNoteOffsetFromC);
  54350. keyPressNotes.add (midiNoteOffsetFromC);
  54351. keyPresses.add (key);
  54352. }
  54353. void MidiKeyboardComponent::removeKeyPressForNote (const int midiNoteOffsetFromC)
  54354. {
  54355. for (int i = keyPressNotes.size(); --i >= 0;)
  54356. {
  54357. if (keyPressNotes.getUnchecked (i) == midiNoteOffsetFromC)
  54358. {
  54359. keyPressNotes.remove (i);
  54360. keyPresses.remove (i);
  54361. }
  54362. }
  54363. }
  54364. void MidiKeyboardComponent::setKeyPressBaseOctave (const int newOctaveNumber)
  54365. {
  54366. jassert (newOctaveNumber >= 0 && newOctaveNumber <= 10);
  54367. keyMappingOctave = newOctaveNumber;
  54368. }
  54369. bool MidiKeyboardComponent::keyStateChanged()
  54370. {
  54371. bool keyPressUsed = false;
  54372. for (int i = keyPresses.size(); --i >= 0;)
  54373. {
  54374. const int note = 12 * keyMappingOctave + keyPressNotes.getUnchecked (i);
  54375. if (keyPresses.getReference(i).isCurrentlyDown())
  54376. {
  54377. if (! keysPressed [note])
  54378. {
  54379. keysPressed.setBit (note);
  54380. state.noteOn (midiChannel, note, velocity);
  54381. keyPressUsed = true;
  54382. }
  54383. }
  54384. else
  54385. {
  54386. if (keysPressed [note])
  54387. {
  54388. keysPressed.clearBit (note);
  54389. state.noteOff (midiChannel, note);
  54390. keyPressUsed = true;
  54391. }
  54392. }
  54393. }
  54394. return keyPressUsed;
  54395. }
  54396. void MidiKeyboardComponent::focusLost (FocusChangeType)
  54397. {
  54398. resetAnyKeysInUse();
  54399. }
  54400. END_JUCE_NAMESPACE
  54401. /********* End of inlined file: juce_MidiKeyboardComponent.cpp *********/
  54402. /********* Start of inlined file: juce_OpenGLComponent.cpp *********/
  54403. #if JUCE_OPENGL
  54404. BEGIN_JUCE_NAMESPACE
  54405. extern void juce_glViewport (const int w, const int h);
  54406. OpenGLPixelFormat::OpenGLPixelFormat (const int bitsPerRGBComponent,
  54407. const int alphaBits_,
  54408. const int depthBufferBits_,
  54409. const int stencilBufferBits_) throw()
  54410. : redBits (bitsPerRGBComponent),
  54411. greenBits (bitsPerRGBComponent),
  54412. blueBits (bitsPerRGBComponent),
  54413. alphaBits (alphaBits_),
  54414. depthBufferBits (depthBufferBits_),
  54415. stencilBufferBits (stencilBufferBits_),
  54416. accumulationBufferRedBits (0),
  54417. accumulationBufferGreenBits (0),
  54418. accumulationBufferBlueBits (0),
  54419. accumulationBufferAlphaBits (0),
  54420. fullSceneAntiAliasingNumSamples (0)
  54421. {
  54422. }
  54423. bool OpenGLPixelFormat::operator== (const OpenGLPixelFormat& other) const throw()
  54424. {
  54425. return memcmp (this, &other, sizeof (other)) == 0;
  54426. }
  54427. static VoidArray knownContexts;
  54428. OpenGLContext::OpenGLContext() throw()
  54429. {
  54430. knownContexts.add (this);
  54431. }
  54432. OpenGLContext::~OpenGLContext()
  54433. {
  54434. knownContexts.removeValue (this);
  54435. }
  54436. OpenGLContext* OpenGLContext::getCurrentContext()
  54437. {
  54438. for (int i = knownContexts.size(); --i >= 0;)
  54439. {
  54440. OpenGLContext* const oglc = (OpenGLContext*) knownContexts.getUnchecked(i);
  54441. if (oglc->isActive())
  54442. return oglc;
  54443. }
  54444. return 0;
  54445. }
  54446. class OpenGLComponentWatcher : public ComponentMovementWatcher
  54447. {
  54448. public:
  54449. OpenGLComponentWatcher (OpenGLComponent* const owner_)
  54450. : ComponentMovementWatcher (owner_),
  54451. owner (owner_),
  54452. wasShowing (false)
  54453. {
  54454. }
  54455. ~OpenGLComponentWatcher() {}
  54456. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  54457. {
  54458. owner->updateContextPosition();
  54459. }
  54460. void componentPeerChanged()
  54461. {
  54462. const ScopedLock sl (owner->getContextLock());
  54463. owner->deleteContext();
  54464. }
  54465. void componentVisibilityChanged (Component&)
  54466. {
  54467. const bool isShowingNow = owner->isShowing();
  54468. if (wasShowing != isShowingNow)
  54469. {
  54470. wasShowing = isShowingNow;
  54471. owner->updateContextPosition();
  54472. }
  54473. }
  54474. juce_UseDebuggingNewOperator
  54475. private:
  54476. OpenGLComponent* const owner;
  54477. bool wasShowing;
  54478. };
  54479. OpenGLComponent::OpenGLComponent()
  54480. : context (0),
  54481. contextToShareListsWith (0),
  54482. needToUpdateViewport (true)
  54483. {
  54484. setOpaque (true);
  54485. componentWatcher = new OpenGLComponentWatcher (this);
  54486. }
  54487. OpenGLComponent::~OpenGLComponent()
  54488. {
  54489. deleteContext();
  54490. delete componentWatcher;
  54491. }
  54492. void OpenGLComponent::deleteContext()
  54493. {
  54494. const ScopedLock sl (contextLock);
  54495. deleteAndZero (context);
  54496. }
  54497. void OpenGLComponent::updateContextPosition()
  54498. {
  54499. needToUpdateViewport = true;
  54500. if (getWidth() > 0 && getHeight() > 0)
  54501. {
  54502. Component* const topComp = getTopLevelComponent();
  54503. if (topComp->getPeer() != 0)
  54504. {
  54505. const ScopedLock sl (contextLock);
  54506. if (context != 0)
  54507. context->updateWindowPosition (getScreenX() - topComp->getScreenX(),
  54508. getScreenY() - topComp->getScreenY(),
  54509. getWidth(),
  54510. getHeight(),
  54511. topComp->getHeight());
  54512. }
  54513. }
  54514. }
  54515. const OpenGLPixelFormat OpenGLComponent::getPixelFormat() const
  54516. {
  54517. OpenGLPixelFormat pf;
  54518. const ScopedLock sl (contextLock);
  54519. if (context != 0)
  54520. pf = context->getPixelFormat();
  54521. return pf;
  54522. }
  54523. void OpenGLComponent::setPixelFormat (const OpenGLPixelFormat& formatToUse)
  54524. {
  54525. if (! (preferredPixelFormat == formatToUse))
  54526. {
  54527. const ScopedLock sl (contextLock);
  54528. deleteContext();
  54529. preferredPixelFormat = formatToUse;
  54530. }
  54531. }
  54532. void OpenGLComponent::shareWith (OpenGLContext* context)
  54533. {
  54534. if (contextToShareListsWith != context)
  54535. {
  54536. const ScopedLock sl (contextLock);
  54537. deleteContext();
  54538. contextToShareListsWith = context;
  54539. }
  54540. }
  54541. bool OpenGLComponent::makeCurrentContextActive()
  54542. {
  54543. if (context == 0)
  54544. {
  54545. const ScopedLock sl (contextLock);
  54546. if (isShowing() && getTopLevelComponent()->getPeer() != 0)
  54547. {
  54548. context = OpenGLContext::createContextForWindow (this,
  54549. preferredPixelFormat,
  54550. contextToShareListsWith);
  54551. if (context != 0)
  54552. {
  54553. updateContextPosition();
  54554. if (context->makeActive())
  54555. newOpenGLContextCreated();
  54556. }
  54557. }
  54558. }
  54559. return context != 0 && context->makeActive();
  54560. }
  54561. void OpenGLComponent::makeCurrentContextInactive()
  54562. {
  54563. if (context != 0)
  54564. context->makeInactive();
  54565. }
  54566. bool OpenGLComponent::isActiveContext() const throw()
  54567. {
  54568. return context != 0 && context->isActive();
  54569. }
  54570. void OpenGLComponent::swapBuffers()
  54571. {
  54572. if (context != 0)
  54573. context->swapBuffers();
  54574. }
  54575. void OpenGLComponent::paint (Graphics&)
  54576. {
  54577. if (renderAndSwapBuffers())
  54578. {
  54579. ComponentPeer* const peer = getPeer();
  54580. if (peer != 0)
  54581. {
  54582. peer->addMaskedRegion (getScreenX() - peer->getScreenX(),
  54583. getScreenY() - peer->getScreenY(),
  54584. getWidth(), getHeight());
  54585. }
  54586. }
  54587. }
  54588. bool OpenGLComponent::renderAndSwapBuffers()
  54589. {
  54590. const ScopedLock sl (contextLock);
  54591. if (! makeCurrentContextActive())
  54592. return false;
  54593. if (needToUpdateViewport)
  54594. {
  54595. needToUpdateViewport = false;
  54596. juce_glViewport (getWidth(), getHeight());
  54597. }
  54598. renderOpenGL();
  54599. swapBuffers();
  54600. return true;
  54601. }
  54602. void OpenGLComponent::internalRepaint (int x, int y, int w, int h)
  54603. {
  54604. Component::internalRepaint (x, y, w, h);
  54605. if (context != 0)
  54606. context->repaint();
  54607. }
  54608. END_JUCE_NAMESPACE
  54609. #endif
  54610. /********* End of inlined file: juce_OpenGLComponent.cpp *********/
  54611. /********* Start of inlined file: juce_PreferencesPanel.cpp *********/
  54612. BEGIN_JUCE_NAMESPACE
  54613. PreferencesPanel::PreferencesPanel()
  54614. : currentPage (0),
  54615. buttonSize (70)
  54616. {
  54617. }
  54618. PreferencesPanel::~PreferencesPanel()
  54619. {
  54620. deleteAllChildren();
  54621. }
  54622. void PreferencesPanel::addSettingsPage (const String& title,
  54623. const Drawable* icon,
  54624. const Drawable* overIcon,
  54625. const Drawable* downIcon)
  54626. {
  54627. DrawableButton* button = new DrawableButton (title, DrawableButton::ImageAboveTextLabel);
  54628. button->setImages (icon, overIcon, downIcon);
  54629. button->setRadioGroupId (1);
  54630. button->addButtonListener (this);
  54631. button->setClickingTogglesState (true);
  54632. button->setWantsKeyboardFocus (false);
  54633. addAndMakeVisible (button);
  54634. resized();
  54635. }
  54636. void PreferencesPanel::addSettingsPage (const String& title,
  54637. const char* imageData,
  54638. const int imageDataSize)
  54639. {
  54640. DrawableImage icon, iconOver, iconDown;
  54641. icon.setImage (ImageCache::getFromMemory (imageData, imageDataSize), true);
  54642. iconOver.setImage (ImageCache::getFromMemory (imageData, imageDataSize), true);
  54643. iconOver.setOverlayColour (Colours::black.withAlpha (0.12f));
  54644. iconDown.setImage (ImageCache::getFromMemory (imageData, imageDataSize), true);
  54645. iconDown.setOverlayColour (Colours::black.withAlpha (0.25f));
  54646. addSettingsPage (title, &icon, &iconOver, &iconDown);
  54647. if (currentPage == 0)
  54648. setCurrentPage (title);
  54649. }
  54650. class PrefsDialogWindow : public DialogWindow
  54651. {
  54652. public:
  54653. PrefsDialogWindow (const String& dialogtitle,
  54654. const Colour& backgroundColour)
  54655. : DialogWindow (dialogtitle, backgroundColour, true)
  54656. {
  54657. }
  54658. ~PrefsDialogWindow()
  54659. {
  54660. }
  54661. void closeButtonPressed()
  54662. {
  54663. exitModalState (0);
  54664. }
  54665. private:
  54666. PrefsDialogWindow (const PrefsDialogWindow&);
  54667. const PrefsDialogWindow& operator= (const PrefsDialogWindow&);
  54668. };
  54669. void PreferencesPanel::showInDialogBox (const String& dialogtitle,
  54670. int dialogWidth,
  54671. int dialogHeight,
  54672. const Colour& backgroundColour)
  54673. {
  54674. setSize (dialogWidth, dialogHeight);
  54675. PrefsDialogWindow dw (dialogtitle, backgroundColour);
  54676. dw.setContentComponent (this, true, true);
  54677. dw.centreAroundComponent (0, dw.getWidth(), dw.getHeight());
  54678. dw.runModalLoop();
  54679. }
  54680. void PreferencesPanel::resized()
  54681. {
  54682. int x = 0;
  54683. for (int i = 0; i < getNumChildComponents(); ++i)
  54684. {
  54685. Component* c = getChildComponent (i);
  54686. if (dynamic_cast <DrawableButton*> (c) == 0)
  54687. {
  54688. c->setBounds (0, buttonSize + 5, getWidth(), getHeight() - buttonSize - 5);
  54689. }
  54690. else
  54691. {
  54692. c->setBounds (x, 0, buttonSize, buttonSize);
  54693. x += buttonSize;
  54694. }
  54695. }
  54696. }
  54697. void PreferencesPanel::paint (Graphics& g)
  54698. {
  54699. g.setColour (Colours::grey);
  54700. g.fillRect (0, buttonSize + 2, getWidth(), 1);
  54701. }
  54702. void PreferencesPanel::setCurrentPage (const String& pageName)
  54703. {
  54704. if (currentPageName != pageName)
  54705. {
  54706. currentPageName = pageName;
  54707. deleteAndZero (currentPage);
  54708. currentPage = createComponentForPage (pageName);
  54709. if (currentPage != 0)
  54710. {
  54711. addAndMakeVisible (currentPage);
  54712. currentPage->toBack();
  54713. resized();
  54714. }
  54715. for (int i = 0; i < getNumChildComponents(); ++i)
  54716. {
  54717. DrawableButton* db = dynamic_cast <DrawableButton*> (getChildComponent (i));
  54718. if (db != 0 && db->getName() == pageName)
  54719. {
  54720. db->setToggleState (true, false);
  54721. break;
  54722. }
  54723. }
  54724. }
  54725. }
  54726. void PreferencesPanel::buttonClicked (Button*)
  54727. {
  54728. for (int i = 0; i < getNumChildComponents(); ++i)
  54729. {
  54730. DrawableButton* db = dynamic_cast <DrawableButton*> (getChildComponent (i));
  54731. if (db != 0 && db->getToggleState())
  54732. {
  54733. setCurrentPage (db->getName());
  54734. break;
  54735. }
  54736. }
  54737. }
  54738. END_JUCE_NAMESPACE
  54739. /********* End of inlined file: juce_PreferencesPanel.cpp *********/
  54740. /********* Start of inlined file: juce_QuickTimeMovieComponent.cpp *********/
  54741. #if JUCE_QUICKTIME
  54742. #ifdef _MSC_VER
  54743. #pragma warning (disable: 4514)
  54744. #endif
  54745. #ifdef _WIN32
  54746. #include <windows.h>
  54747. #ifdef _MSC_VER
  54748. #pragma warning (push)
  54749. #pragma warning (disable : 4100)
  54750. #endif
  54751. /* If you've got an include error here, you probably need to install the QuickTime SDK and
  54752. add its header directory to your include path.
  54753. Alternatively, if you don't need any QuickTime services, just turn off the JUC_QUICKTIME
  54754. flag in juce_Config.h
  54755. */
  54756. #include <Movies.h>
  54757. #include <QTML.h>
  54758. #include <QuickTimeComponents.h>
  54759. #include <MediaHandlers.h>
  54760. #include <ImageCodec.h>
  54761. #ifdef _MSC_VER
  54762. #pragma warning (pop)
  54763. #endif
  54764. // If you've got QuickTime 7 installed, then these COM objects should be found in
  54765. // the "\Program Files\Quicktime" directory. You'll need to add this directory to
  54766. // your include search path to make these import statements work.
  54767. #import <QTOLibrary.dll>
  54768. #import <QTOControl.dll>
  54769. using namespace QTOLibrary;
  54770. using namespace QTOControlLib;
  54771. #else
  54772. #include <Carbon/Carbon.h>
  54773. #include <QuickTime/Movies.h>
  54774. #include <QuickTime/QuickTimeComponents.h>
  54775. #include <QuickTime/MediaHandlers.h>
  54776. #endif
  54777. BEGIN_JUCE_NAMESPACE
  54778. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle);
  54779. static bool hasLoadedQT = false;
  54780. static bool isQTAvailable = false;
  54781. struct QTMovieCompInternal
  54782. {
  54783. QTMovieCompInternal()
  54784. : dataHandle (0)
  54785. {
  54786. #if JUCE_MAC
  54787. movie = 0;
  54788. controller = 0;
  54789. #endif
  54790. }
  54791. ~QTMovieCompInternal()
  54792. {
  54793. clearHandle();
  54794. }
  54795. #if JUCE_MAC
  54796. Movie movie;
  54797. MovieController controller;
  54798. #else
  54799. IQTControlPtr qtControlInternal;
  54800. IQTMoviePtr qtMovieInternal;
  54801. #endif
  54802. Handle dataHandle;
  54803. void clearHandle()
  54804. {
  54805. if (dataHandle != 0)
  54806. {
  54807. DisposeHandle (dataHandle);
  54808. dataHandle = 0;
  54809. }
  54810. }
  54811. };
  54812. #if JUCE_WIN32
  54813. #define qtControl (((QTMovieCompInternal*) internal)->qtControlInternal)
  54814. #define qtMovie (((QTMovieCompInternal*) internal)->qtMovieInternal)
  54815. QuickTimeMovieComponent::QuickTimeMovieComponent()
  54816. : movieLoaded (false),
  54817. controllerVisible (true)
  54818. {
  54819. internal = new QTMovieCompInternal();
  54820. setMouseEventsAllowed (false);
  54821. }
  54822. QuickTimeMovieComponent::~QuickTimeMovieComponent()
  54823. {
  54824. closeMovie();
  54825. qtControl = 0;
  54826. deleteControl();
  54827. delete internal;
  54828. internal = 0;
  54829. }
  54830. bool QuickTimeMovieComponent::isQuickTimeAvailable() throw()
  54831. {
  54832. if (! hasLoadedQT)
  54833. {
  54834. hasLoadedQT = true;
  54835. isQTAvailable = (InitializeQTML (0) == noErr)
  54836. && (EnterMovies() == noErr);
  54837. }
  54838. return isQTAvailable;
  54839. }
  54840. void QuickTimeMovieComponent::createControlIfNeeded()
  54841. {
  54842. if (isShowing() && ! isControlCreated())
  54843. {
  54844. const IID qtIID = __uuidof (QTControl);
  54845. if (createControl (&qtIID))
  54846. {
  54847. const IID qtInterfaceIID = __uuidof (IQTControl);
  54848. qtControl = (IQTControl*) queryInterface (&qtInterfaceIID);
  54849. if (qtControl != 0)
  54850. {
  54851. qtControl->Release(); // it has one ref too many at this point
  54852. qtControl->QuickTimeInitialize();
  54853. qtControl->PutSizing (qtMovieFitsControl);
  54854. if (movieFile != File::nonexistent)
  54855. loadMovie (movieFile, controllerVisible);
  54856. }
  54857. }
  54858. }
  54859. }
  54860. bool QuickTimeMovieComponent::isControlCreated() const
  54861. {
  54862. return isControlOpen();
  54863. }
  54864. bool QuickTimeMovieComponent::loadMovie (InputStream* movieStream,
  54865. const bool isControllerVisible)
  54866. {
  54867. movieFile = File::nonexistent;
  54868. movieLoaded = false;
  54869. qtMovie = 0;
  54870. controllerVisible = isControllerVisible;
  54871. createControlIfNeeded();
  54872. if (isControlCreated())
  54873. {
  54874. if (qtControl != 0)
  54875. {
  54876. qtControl->Put_MovieHandle (0);
  54877. ((QTMovieCompInternal*) internal)->clearHandle();
  54878. Movie movie;
  54879. if (juce_OpenQuickTimeMovieFromStream (movieStream, movie, ((QTMovieCompInternal*) internal)->dataHandle))
  54880. {
  54881. qtControl->Put_MovieHandle ((long) (pointer_sized_int) movie);
  54882. qtMovie = qtControl->GetMovie();
  54883. if (qtMovie != 0)
  54884. qtMovie->PutMovieControllerType (isControllerVisible ? qtMovieControllerTypeStandard
  54885. : qtMovieControllerTypeNone);
  54886. }
  54887. if (movie == 0)
  54888. ((QTMovieCompInternal*) internal)->clearHandle();
  54889. }
  54890. movieLoaded = (qtMovie != 0);
  54891. }
  54892. else
  54893. {
  54894. // You're trying to open a movie when the control hasn't yet been created, probably because
  54895. // you've not yet added this component to a Window and made the whole component hierarchy visible.
  54896. jassertfalse
  54897. }
  54898. delete movieStream;
  54899. return movieLoaded;
  54900. }
  54901. void QuickTimeMovieComponent::closeMovie()
  54902. {
  54903. stop();
  54904. movieFile = File::nonexistent;
  54905. movieLoaded = false;
  54906. qtMovie = 0;
  54907. if (qtControl != 0)
  54908. qtControl->Put_MovieHandle (0);
  54909. ((QTMovieCompInternal*) internal)->clearHandle();
  54910. }
  54911. const File QuickTimeMovieComponent::getCurrentMovieFile() const
  54912. {
  54913. return movieFile;
  54914. }
  54915. bool QuickTimeMovieComponent::isMovieOpen() const
  54916. {
  54917. return movieLoaded;
  54918. }
  54919. double QuickTimeMovieComponent::getMovieDuration() const
  54920. {
  54921. if (qtMovie != 0)
  54922. return qtMovie->GetDuration() / (double) qtMovie->GetTimeScale();
  54923. return 0.0;
  54924. }
  54925. void QuickTimeMovieComponent::getMovieNormalSize (int& width, int& height) const
  54926. {
  54927. if (qtMovie != 0)
  54928. {
  54929. struct QTRECT r = qtMovie->GetNaturalRect();
  54930. width = r.right - r.left;
  54931. height = r.bottom - r.top;
  54932. }
  54933. else
  54934. {
  54935. width = height = 0;
  54936. }
  54937. }
  54938. void QuickTimeMovieComponent::play()
  54939. {
  54940. if (qtMovie != 0)
  54941. qtMovie->Play();
  54942. }
  54943. void QuickTimeMovieComponent::stop()
  54944. {
  54945. if (qtMovie != 0)
  54946. qtMovie->Stop();
  54947. }
  54948. bool QuickTimeMovieComponent::isPlaying() const
  54949. {
  54950. return qtMovie != 0 && qtMovie->GetRate() != 0.0f;
  54951. }
  54952. void QuickTimeMovieComponent::setPosition (const double seconds)
  54953. {
  54954. if (qtMovie != 0)
  54955. qtMovie->PutTime ((long) (seconds * qtMovie->GetTimeScale()));
  54956. }
  54957. double QuickTimeMovieComponent::getPosition() const
  54958. {
  54959. if (qtMovie != 0)
  54960. return qtMovie->GetTime() / (double) qtMovie->GetTimeScale();
  54961. return 0.0;
  54962. }
  54963. void QuickTimeMovieComponent::setSpeed (const float newSpeed)
  54964. {
  54965. if (qtMovie != 0)
  54966. qtMovie->PutRate (newSpeed);
  54967. }
  54968. void QuickTimeMovieComponent::setMovieVolume (const float newVolume)
  54969. {
  54970. if (qtMovie != 0)
  54971. qtMovie->PutAudioVolume (newVolume);
  54972. }
  54973. float QuickTimeMovieComponent::getMovieVolume() const
  54974. {
  54975. if (qtMovie != 0)
  54976. return qtMovie->GetAudioVolume();
  54977. return 0.0f;
  54978. }
  54979. void QuickTimeMovieComponent::setLooping (const bool shouldLoop)
  54980. {
  54981. if (qtMovie != 0)
  54982. qtMovie->PutLoop (shouldLoop);
  54983. }
  54984. bool QuickTimeMovieComponent::isLooping() const
  54985. {
  54986. return qtMovie != 0 && qtMovie->GetLoop();
  54987. }
  54988. bool QuickTimeMovieComponent::isControllerVisible() const
  54989. {
  54990. return controllerVisible;
  54991. }
  54992. void QuickTimeMovieComponent::parentHierarchyChanged()
  54993. {
  54994. createControlIfNeeded();
  54995. QTWinBaseClass::parentHierarchyChanged();
  54996. }
  54997. void QuickTimeMovieComponent::visibilityChanged()
  54998. {
  54999. createControlIfNeeded();
  55000. QTWinBaseClass::visibilityChanged();
  55001. }
  55002. void QuickTimeMovieComponent::paint (Graphics& g)
  55003. {
  55004. if (! isControlCreated())
  55005. g.fillAll (Colours::black);
  55006. }
  55007. #endif
  55008. #if JUCE_MAC
  55009. static VoidArray activeQTWindows (2);
  55010. struct MacClickEventData
  55011. {
  55012. ::Point where;
  55013. long when;
  55014. long modifiers;
  55015. };
  55016. void OfferMouseClickToQuickTime (WindowRef window,
  55017. ::Point where, long when, long modifiers,
  55018. Component* topLevelComp)
  55019. {
  55020. if (hasLoadedQT)
  55021. {
  55022. for (int i = activeQTWindows.size(); --i >= 0;)
  55023. {
  55024. QuickTimeMovieComponent* const qtw = (QuickTimeMovieComponent*) activeQTWindows[i];
  55025. if (qtw->isVisible() && topLevelComp->isParentOf (qtw))
  55026. {
  55027. MacClickEventData data;
  55028. data.where = where;
  55029. data.when = when;
  55030. data.modifiers = modifiers;
  55031. qtw->handleMCEvent (&data);
  55032. }
  55033. }
  55034. }
  55035. }
  55036. QuickTimeMovieComponent::QuickTimeMovieComponent()
  55037. : internal (new QTMovieCompInternal()),
  55038. associatedWindow (0),
  55039. controllerVisible (false),
  55040. controllerAssignedToWindow (false),
  55041. reentrant (false)
  55042. {
  55043. if (! hasLoadedQT)
  55044. {
  55045. hasLoadedQT = true;
  55046. isQTAvailable = EnterMovies() == noErr;
  55047. }
  55048. setOpaque (true);
  55049. setVisible (true);
  55050. activeQTWindows.add (this);
  55051. }
  55052. QuickTimeMovieComponent::~QuickTimeMovieComponent()
  55053. {
  55054. closeMovie();
  55055. activeQTWindows.removeValue ((void*) this);
  55056. QTMovieCompInternal* const i = (QTMovieCompInternal*) internal;
  55057. delete i;
  55058. if (activeQTWindows.size() == 0 && isQTAvailable)
  55059. {
  55060. isQTAvailable = false;
  55061. hasLoadedQT = false;
  55062. ExitMovies();
  55063. }
  55064. }
  55065. bool QuickTimeMovieComponent::isQuickTimeAvailable() throw()
  55066. {
  55067. if (! hasLoadedQT)
  55068. {
  55069. hasLoadedQT = true;
  55070. isQTAvailable = EnterMovies() == noErr;
  55071. }
  55072. return isQTAvailable;
  55073. }
  55074. bool QuickTimeMovieComponent::loadMovie (InputStream* movieStream,
  55075. const bool controllerVisible_)
  55076. {
  55077. if (! isQTAvailable)
  55078. return false;
  55079. closeMovie();
  55080. movieFile = File::nonexistent;
  55081. if (getPeer() == 0)
  55082. {
  55083. // To open a movie, this component must be visible inside a functioning window, so that
  55084. // the QT control can be assigned to the window.
  55085. jassertfalse
  55086. return false;
  55087. }
  55088. controllerVisible = controllerVisible_;
  55089. QTMovieCompInternal* const qmci = (QTMovieCompInternal*) internal;
  55090. GrafPtr savedPort;
  55091. GetPort (&savedPort);
  55092. bool result = false;
  55093. if (juce_OpenQuickTimeMovieFromStream (movieStream, qmci->movie, qmci->dataHandle))
  55094. {
  55095. qmci->controller = 0;
  55096. void* window = getWindowHandle();
  55097. if (window != associatedWindow && window != 0)
  55098. associatedWindow = window;
  55099. assignMovieToWindow();
  55100. SetMovieActive (qmci->movie, true);
  55101. SetMovieProgressProc (qmci->movie, (MovieProgressUPP) -1, 0);
  55102. startTimer (1000 / 50); // this needs to be quite a high frequency for smooth playback
  55103. result = true;
  55104. repaint();
  55105. }
  55106. MacSetPort (savedPort);
  55107. return result;
  55108. }
  55109. void QuickTimeMovieComponent::closeMovie()
  55110. {
  55111. stop();
  55112. QTMovieCompInternal* const qmci = (QTMovieCompInternal*) internal;
  55113. if (qmci->controller != 0)
  55114. {
  55115. DisposeMovieController (qmci->controller);
  55116. qmci->controller = 0;
  55117. }
  55118. if (qmci->movie != 0)
  55119. {
  55120. DisposeMovie (qmci->movie);
  55121. qmci->movie = 0;
  55122. }
  55123. qmci->clearHandle();
  55124. stopTimer();
  55125. movieFile = File::nonexistent;
  55126. }
  55127. bool QuickTimeMovieComponent::isMovieOpen() const
  55128. {
  55129. QTMovieCompInternal* const qmci = (QTMovieCompInternal*) internal;
  55130. return qmci->movie != 0 && qmci->controller != 0;
  55131. }
  55132. const File QuickTimeMovieComponent::getCurrentMovieFile() const
  55133. {
  55134. return movieFile;
  55135. }
  55136. static GrafPtr getPortForWindow (void* window)
  55137. {
  55138. if (window == 0)
  55139. return 0;
  55140. return (GrafPtr) GetWindowPort ((WindowRef) window);
  55141. }
  55142. void QuickTimeMovieComponent::assignMovieToWindow()
  55143. {
  55144. if (reentrant)
  55145. return;
  55146. reentrant = true;
  55147. QTMovieCompInternal* const qmci = (QTMovieCompInternal*) internal;
  55148. if (qmci->controller != 0)
  55149. {
  55150. DisposeMovieController (qmci->controller);
  55151. qmci->controller = 0;
  55152. }
  55153. controllerAssignedToWindow = false;
  55154. void* window = getWindowHandle();
  55155. GrafPtr port = getPortForWindow (window);
  55156. if (port != 0)
  55157. {
  55158. GrafPtr savedPort;
  55159. GetPort (&savedPort);
  55160. SetMovieGWorld (qmci->movie, (CGrafPtr) port, 0);
  55161. MacSetPort (port);
  55162. Rect r;
  55163. r.top = 0;
  55164. r.left = 0;
  55165. r.right = (short) jmax (1, getWidth());
  55166. r.bottom = (short) jmax (1, getHeight());
  55167. SetMovieBox (qmci->movie, &r);
  55168. // create the movie controller
  55169. qmci->controller = NewMovieController (qmci->movie, &r,
  55170. controllerVisible ? mcTopLeftMovie
  55171. : mcNotVisible);
  55172. if (qmci->controller != 0)
  55173. {
  55174. MCEnableEditing (qmci->controller, true);
  55175. MCDoAction (qmci->controller, mcActionSetUseBadge, (void*) false);
  55176. MCDoAction (qmci->controller, mcActionSetLoopIsPalindrome, (void*) false);
  55177. setLooping (looping);
  55178. MCDoAction (qmci->controller, mcActionSetFlags,
  55179. (void*) (pointer_sized_int) (mcFlagSuppressMovieFrame | (controllerVisible ? 0 : (mcFlagSuppressStepButtons | mcFlagSuppressSpeakerButton))));
  55180. MCSetControllerBoundsRect (qmci->controller, &r);
  55181. controllerAssignedToWindow = true;
  55182. resized();
  55183. }
  55184. MacSetPort (savedPort);
  55185. }
  55186. else
  55187. {
  55188. SetMovieGWorld (qmci->movie, 0, 0);
  55189. }
  55190. reentrant = false;
  55191. }
  55192. void QuickTimeMovieComponent::play()
  55193. {
  55194. QTMovieCompInternal* const qmci = (QTMovieCompInternal*) internal;
  55195. if (qmci->movie != 0)
  55196. StartMovie (qmci->movie);
  55197. }
  55198. void QuickTimeMovieComponent::stop()
  55199. {
  55200. QTMovieCompInternal* const qmci = (QTMovieCompInternal*) internal;
  55201. if (qmci->movie != 0)
  55202. StopMovie (qmci->movie);
  55203. }
  55204. bool QuickTimeMovieComponent::isPlaying() const
  55205. {
  55206. QTMovieCompInternal* const qmci = (QTMovieCompInternal*) internal;
  55207. return qmci->movie != 0 && GetMovieRate (qmci->movie) != 0;
  55208. }
  55209. void QuickTimeMovieComponent::setPosition (const double seconds)
  55210. {
  55211. QTMovieCompInternal* const qmci = (QTMovieCompInternal*) internal;
  55212. if (qmci->controller != 0)
  55213. {
  55214. TimeRecord time;
  55215. time.base = GetMovieTimeBase (qmci->movie);
  55216. time.scale = 100000;
  55217. const uint64 t = (uint64) (100000.0 * seconds);
  55218. time.value.lo = (UInt32) (t & 0xffffffff);
  55219. time.value.hi = (UInt32) (t >> 32);
  55220. SetMovieTime (qmci->movie, &time);
  55221. timerCallback(); // to call MCIdle
  55222. }
  55223. else
  55224. {
  55225. jassertfalse // no movie is open, so can't set the position.
  55226. }
  55227. }
  55228. double QuickTimeMovieComponent::getPosition() const
  55229. {
  55230. QTMovieCompInternal* const qmci = (QTMovieCompInternal*) internal;
  55231. if (qmci->movie != 0)
  55232. {
  55233. TimeRecord time;
  55234. GetMovieTime (qmci->movie, &time);
  55235. return ((int64) (((uint64) time.value.hi << 32) | (uint64) time.value.lo))
  55236. / (double) time.scale;
  55237. }
  55238. return 0.0;
  55239. }
  55240. void QuickTimeMovieComponent::setSpeed (const float newSpeed)
  55241. {
  55242. QTMovieCompInternal* const qmci = (QTMovieCompInternal*) internal;
  55243. if (qmci->movie != 0)
  55244. SetMovieRate (qmci->movie, (Fixed) (newSpeed * (Fixed) 0x00010000L));
  55245. }
  55246. double QuickTimeMovieComponent::getMovieDuration() const
  55247. {
  55248. QTMovieCompInternal* const qmci = (QTMovieCompInternal*) internal;
  55249. if (qmci->movie != 0)
  55250. return GetMovieDuration (qmci->movie) / (double) GetMovieTimeScale (qmci->movie);
  55251. return 0.0;
  55252. }
  55253. void QuickTimeMovieComponent::setLooping (const bool shouldLoop)
  55254. {
  55255. QTMovieCompInternal* const qmci = (QTMovieCompInternal*) internal;
  55256. looping = shouldLoop;
  55257. if (qmci->controller != 0)
  55258. MCDoAction (qmci->controller, mcActionSetLooping, (void*) shouldLoop);
  55259. }
  55260. bool QuickTimeMovieComponent::isLooping() const
  55261. {
  55262. return looping;
  55263. }
  55264. void QuickTimeMovieComponent::setMovieVolume (const float newVolume)
  55265. {
  55266. QTMovieCompInternal* const qmci = (QTMovieCompInternal*) internal;
  55267. if (qmci->movie != 0)
  55268. SetMovieVolume (qmci->movie, jlimit ((short) 0, (short) 0x100, (short) (newVolume * 0x0100)));
  55269. }
  55270. float QuickTimeMovieComponent::getMovieVolume() const
  55271. {
  55272. QTMovieCompInternal* const qmci = (QTMovieCompInternal*) internal;
  55273. if (qmci->movie != 0)
  55274. return jmax (0.0f, GetMovieVolume (qmci->movie) / (float) 0x0100);
  55275. return 0.0f;
  55276. }
  55277. void QuickTimeMovieComponent::getMovieNormalSize (int& width, int& height) const
  55278. {
  55279. width = 0;
  55280. height = 0;
  55281. QTMovieCompInternal* const qmci = (QTMovieCompInternal*) internal;
  55282. if (qmci->movie != 0)
  55283. {
  55284. Rect r;
  55285. GetMovieNaturalBoundsRect (qmci->movie, &r);
  55286. width = r.right - r.left;
  55287. height = r.bottom - r.top;
  55288. }
  55289. }
  55290. void QuickTimeMovieComponent::paint (Graphics& g)
  55291. {
  55292. QTMovieCompInternal* const qmci = (QTMovieCompInternal*) internal;
  55293. if (qmci->movie == 0 || qmci->controller == 0)
  55294. {
  55295. g.fillAll (Colours::black);
  55296. return;
  55297. }
  55298. GrafPtr savedPort;
  55299. GetPort (&savedPort);
  55300. MacSetPort (getPortForWindow (getWindowHandle()));
  55301. MCDraw (qmci->controller, (WindowRef) getWindowHandle());
  55302. MacSetPort (savedPort);
  55303. ComponentPeer* const peer = getPeer();
  55304. if (peer != 0)
  55305. {
  55306. peer->addMaskedRegion (getScreenX() - peer->getScreenX(),
  55307. getScreenY() - peer->getScreenY(),
  55308. getWidth(), getHeight());
  55309. }
  55310. timerCallback();
  55311. }
  55312. static const Rectangle getMoviePos (Component* const c)
  55313. {
  55314. return Rectangle (c->getScreenX() - c->getTopLevelComponent()->getScreenX(),
  55315. c->getScreenY() - c->getTopLevelComponent()->getScreenY(),
  55316. jmax (1, c->getWidth()),
  55317. jmax (1, c->getHeight()));
  55318. }
  55319. void QuickTimeMovieComponent::moved()
  55320. {
  55321. resized();
  55322. }
  55323. void QuickTimeMovieComponent::resized()
  55324. {
  55325. QTMovieCompInternal* const qmci = (QTMovieCompInternal*) internal;
  55326. if (qmci->controller != 0 && isShowing())
  55327. {
  55328. checkWindowAssociation();
  55329. GrafPtr port = getPortForWindow (getWindowHandle());
  55330. if (port != 0)
  55331. {
  55332. GrafPtr savedPort;
  55333. GetPort (&savedPort);
  55334. SetMovieGWorld (qmci->movie, (CGrafPtr) port, 0);
  55335. MacSetPort (port);
  55336. lastPositionApplied = getMoviePos (this);
  55337. Rect r;
  55338. r.left = (short) lastPositionApplied.getX();
  55339. r.top = (short) lastPositionApplied.getY();
  55340. r.right = (short) lastPositionApplied.getRight();
  55341. r.bottom = (short) lastPositionApplied.getBottom();
  55342. if (MCGetVisible (qmci->controller))
  55343. MCSetControllerBoundsRect (qmci->controller, &r);
  55344. else
  55345. SetMovieBox (qmci->movie, &r);
  55346. if (! isPlaying())
  55347. timerCallback();
  55348. MacSetPort (savedPort);
  55349. repaint();
  55350. }
  55351. }
  55352. }
  55353. void QuickTimeMovieComponent::visibilityChanged()
  55354. {
  55355. checkWindowAssociation();
  55356. QTWinBaseClass::visibilityChanged();
  55357. }
  55358. void QuickTimeMovieComponent::timerCallback()
  55359. {
  55360. QTMovieCompInternal* const qmci = (QTMovieCompInternal*) internal;
  55361. if (qmci->controller != 0)
  55362. {
  55363. if (isTimerRunning())
  55364. startTimer (getTimerInterval());
  55365. MCIdle (qmci->controller);
  55366. if (lastPositionApplied != getMoviePos (this))
  55367. resized();
  55368. }
  55369. }
  55370. void QuickTimeMovieComponent::checkWindowAssociation()
  55371. {
  55372. void* const window = getWindowHandle();
  55373. if (window != associatedWindow
  55374. || (window != 0 && ! controllerAssignedToWindow))
  55375. {
  55376. associatedWindow = window;
  55377. assignMovieToWindow();
  55378. }
  55379. }
  55380. void QuickTimeMovieComponent::parentHierarchyChanged()
  55381. {
  55382. checkWindowAssociation();
  55383. }
  55384. void QuickTimeMovieComponent::handleMCEvent (void* ev)
  55385. {
  55386. QTMovieCompInternal* const qmci = (QTMovieCompInternal*) internal;
  55387. if (qmci->controller != 0 && isShowing())
  55388. {
  55389. MacClickEventData* data = (MacClickEventData*) ev;
  55390. data->where.h -= getTopLevelComponent()->getScreenX();
  55391. data->where.v -= getTopLevelComponent()->getScreenY();
  55392. Boolean b = false;
  55393. MCPtInController (qmci->controller, data->where, &b);
  55394. if (b)
  55395. {
  55396. const int oldTimeBeforeWaitCursor = MessageManager::getInstance()->getTimeBeforeShowingWaitCursor();
  55397. MessageManager::getInstance()->setTimeBeforeShowingWaitCursor (0);
  55398. MCClick (qmci->controller,
  55399. (WindowRef) getWindowHandle(),
  55400. data->where,
  55401. data->when,
  55402. data->modifiers);
  55403. MessageManager::getInstance()->setTimeBeforeShowingWaitCursor (oldTimeBeforeWaitCursor);
  55404. }
  55405. }
  55406. }
  55407. #endif
  55408. // (methods common to both platforms..)
  55409. static Handle createHandleDataRef (Handle dataHandle, const char* fileName)
  55410. {
  55411. Handle dataRef = 0;
  55412. OSStatus err = PtrToHand (&dataHandle, &dataRef, sizeof (Handle));
  55413. if (err == noErr)
  55414. {
  55415. Str255 suffix;
  55416. CharacterFunctions::copy ((char*) suffix, fileName, 128);
  55417. StringPtr name = suffix;
  55418. err = PtrAndHand (name, dataRef, name[0] + 1);
  55419. if (err == noErr)
  55420. {
  55421. long atoms[3];
  55422. atoms[0] = EndianU32_NtoB (3 * sizeof (long));
  55423. atoms[1] = EndianU32_NtoB (kDataRefExtensionMacOSFileType);
  55424. atoms[2] = EndianU32_NtoB (MovieFileType);
  55425. err = PtrAndHand (atoms, dataRef, 3 * sizeof (long));
  55426. if (err == noErr)
  55427. return dataRef;
  55428. }
  55429. DisposeHandle (dataRef);
  55430. }
  55431. return 0;
  55432. }
  55433. static CFStringRef juceStringToCFString (const String& s)
  55434. {
  55435. const int len = s.length();
  55436. const juce_wchar* const t = (const juce_wchar*) s;
  55437. UniChar* temp = (UniChar*) juce_malloc (sizeof (UniChar) * len + 4);
  55438. for (int i = 0; i <= len; ++i)
  55439. temp[i] = t[i];
  55440. CFStringRef result = CFStringCreateWithCharacters (kCFAllocatorDefault, temp, len);
  55441. juce_free (temp);
  55442. return result;
  55443. }
  55444. static bool openMovie (QTNewMoviePropertyElement* props, int prop, Movie& movie)
  55445. {
  55446. Boolean trueBool = true;
  55447. props[prop].propClass = kQTPropertyClass_MovieInstantiation;
  55448. props[prop].propID = kQTMovieInstantiationPropertyID_DontResolveDataRefs;
  55449. props[prop].propValueSize = sizeof (trueBool);
  55450. props[prop].propValueAddress = &trueBool;
  55451. ++prop;
  55452. props[prop].propClass = kQTPropertyClass_MovieInstantiation;
  55453. props[prop].propID = kQTMovieInstantiationPropertyID_AsyncOK;
  55454. props[prop].propValueSize = sizeof (trueBool);
  55455. props[prop].propValueAddress = &trueBool;
  55456. ++prop;
  55457. Boolean isActive = true;
  55458. props[prop].propClass = kQTPropertyClass_NewMovieProperty;
  55459. props[prop].propID = kQTNewMoviePropertyID_Active;
  55460. props[prop].propValueSize = sizeof (isActive);
  55461. props[prop].propValueAddress = &isActive;
  55462. ++prop;
  55463. #if JUCE_MAC
  55464. SetPort (0);
  55465. #else
  55466. MacSetPort (0);
  55467. #endif
  55468. jassert (prop <= 5);
  55469. OSStatus err = NewMovieFromProperties (prop, props, 0, 0, &movie);
  55470. return err == noErr;
  55471. }
  55472. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle)
  55473. {
  55474. if (input == 0)
  55475. return false;
  55476. dataHandle = 0;
  55477. bool ok = false;
  55478. QTNewMoviePropertyElement props[5];
  55479. zeromem (props, sizeof (props));
  55480. int prop = 0;
  55481. DataReferenceRecord dr;
  55482. props[prop].propClass = kQTPropertyClass_DataLocation;
  55483. props[prop].propID = kQTDataLocationPropertyID_DataReference;
  55484. props[prop].propValueSize = sizeof (dr);
  55485. props[prop].propValueAddress = (void*) &dr;
  55486. ++prop;
  55487. FileInputStream* const fin = dynamic_cast <FileInputStream*> (input);
  55488. if (fin != 0)
  55489. {
  55490. CFStringRef filePath = juceStringToCFString (fin->getFile().getFullPathName());
  55491. QTNewDataReferenceFromFullPathCFString (filePath, (QTPathStyle) kQTNativeDefaultPathStyle, 0,
  55492. &dr.dataRef, &dr.dataRefType);
  55493. ok = openMovie (props, prop, movie);
  55494. DisposeHandle (dr.dataRef);
  55495. CFRelease (filePath);
  55496. }
  55497. else
  55498. {
  55499. // sanity-check because this currently needs to load the whole stream into memory..
  55500. jassert (input->getTotalLength() < 50 * 1024 * 1024);
  55501. dataHandle = NewHandle ((Size) input->getTotalLength());
  55502. HLock (dataHandle);
  55503. // read the entire stream into memory - this is a pain, but can't get it to work
  55504. // properly using a custom callback to supply the data.
  55505. input->read (*dataHandle, (int) input->getTotalLength());
  55506. HUnlock (dataHandle);
  55507. // different types to get QT to try. (We should really be a bit smarter here by
  55508. // working out in advance which one the stream contains, rather than just trying
  55509. // each one)
  55510. const char* const suffixesToTry[] = { "\04.mov", "\04.mp3",
  55511. "\04.avi", "\04.m4a" };
  55512. for (int i = 0; i < numElementsInArray (suffixesToTry) && ! ok; ++i)
  55513. {
  55514. /* // this fails for some bizarre reason - it can be bodged to work with
  55515. // movies, but can't seem to do it for other file types..
  55516. QTNewMovieUserProcRecord procInfo;
  55517. procInfo.getMovieUserProc = NewGetMovieUPP (readMovieStreamProc);
  55518. procInfo.getMovieUserProcRefcon = this;
  55519. procInfo.defaultDataRef.dataRef = dataRef;
  55520. procInfo.defaultDataRef.dataRefType = HandleDataHandlerSubType;
  55521. props[prop].propClass = kQTPropertyClass_DataLocation;
  55522. props[prop].propID = kQTDataLocationPropertyID_MovieUserProc;
  55523. props[prop].propValueSize = sizeof (procInfo);
  55524. props[prop].propValueAddress = (void*) &procInfo;
  55525. ++prop; */
  55526. dr.dataRef = createHandleDataRef (dataHandle, suffixesToTry [i]);
  55527. dr.dataRefType = HandleDataHandlerSubType;
  55528. ok = openMovie (props, prop, movie);
  55529. DisposeHandle (dr.dataRef);
  55530. }
  55531. }
  55532. return ok;
  55533. }
  55534. bool QuickTimeMovieComponent::loadMovie (const File& movieFile_,
  55535. const bool isControllerVisible)
  55536. {
  55537. const bool ok = loadMovie ((InputStream*) movieFile_.createInputStream(), isControllerVisible);
  55538. movieFile = movieFile_;
  55539. return ok;
  55540. }
  55541. void QuickTimeMovieComponent::goToStart()
  55542. {
  55543. setPosition (0.0);
  55544. }
  55545. void QuickTimeMovieComponent::setBoundsWithCorrectAspectRatio (const Rectangle& spaceToFitWithin,
  55546. const RectanglePlacement& placement)
  55547. {
  55548. int normalWidth, normalHeight;
  55549. getMovieNormalSize (normalWidth, normalHeight);
  55550. if (normalWidth > 0 && normalHeight > 0 && ! spaceToFitWithin.isEmpty())
  55551. {
  55552. double x = 0.0, y = 0.0, w = normalWidth, h = normalHeight;
  55553. placement.applyTo (x, y, w, h,
  55554. spaceToFitWithin.getX(), spaceToFitWithin.getY(),
  55555. spaceToFitWithin.getWidth(), spaceToFitWithin.getHeight());
  55556. if (w > 0 && h > 0)
  55557. {
  55558. setBounds (roundDoubleToInt (x), roundDoubleToInt (y),
  55559. roundDoubleToInt (w), roundDoubleToInt (h));
  55560. }
  55561. }
  55562. else
  55563. {
  55564. setBounds (spaceToFitWithin);
  55565. }
  55566. }
  55567. END_JUCE_NAMESPACE
  55568. #endif
  55569. /********* End of inlined file: juce_QuickTimeMovieComponent.cpp *********/
  55570. /********* Start of inlined file: juce_SystemTrayIconComponent.cpp *********/
  55571. #if JUCE_WIN32 || JUCE_LINUX
  55572. BEGIN_JUCE_NAMESPACE
  55573. SystemTrayIconComponent::SystemTrayIconComponent()
  55574. {
  55575. addToDesktop (0);
  55576. }
  55577. SystemTrayIconComponent::~SystemTrayIconComponent()
  55578. {
  55579. }
  55580. END_JUCE_NAMESPACE
  55581. #endif
  55582. /********* End of inlined file: juce_SystemTrayIconComponent.cpp *********/
  55583. /********* Start of inlined file: juce_AlertWindow.cpp *********/
  55584. BEGIN_JUCE_NAMESPACE
  55585. static const int titleH = 24;
  55586. static const int iconWidth = 80;
  55587. class AlertWindowTextEditor : public TextEditor
  55588. {
  55589. public:
  55590. #if JUCE_LINUX
  55591. #define PASSWORD_CHAR 0x2022
  55592. #else
  55593. #define PASSWORD_CHAR 0x25cf
  55594. #endif
  55595. AlertWindowTextEditor (const String& name,
  55596. const bool isPasswordBox)
  55597. : TextEditor (name,
  55598. isPasswordBox ? (const tchar) PASSWORD_CHAR
  55599. : (const tchar) 0)
  55600. {
  55601. setSelectAllWhenFocused (true);
  55602. }
  55603. ~AlertWindowTextEditor()
  55604. {
  55605. }
  55606. void returnPressed()
  55607. {
  55608. // pass these up the component hierarchy to be trigger the buttons
  55609. getParentComponent()->keyPressed (KeyPress (KeyPress::returnKey, 0, T('\n')));
  55610. }
  55611. void escapePressed()
  55612. {
  55613. // pass these up the component hierarchy to be trigger the buttons
  55614. getParentComponent()->keyPressed (KeyPress (KeyPress::escapeKey, 0, 0));
  55615. }
  55616. private:
  55617. AlertWindowTextEditor (const AlertWindowTextEditor&);
  55618. const AlertWindowTextEditor& operator= (const AlertWindowTextEditor&);
  55619. };
  55620. AlertWindow::AlertWindow (const String& title,
  55621. const String& message,
  55622. AlertIconType iconType)
  55623. : TopLevelWindow (title, true),
  55624. alertIconType (iconType)
  55625. {
  55626. if (message.isEmpty())
  55627. text = T(" "); // to force an update if the message is empty
  55628. setMessage (message);
  55629. #if JUCE_MAC
  55630. setAlwaysOnTop (true);
  55631. #else
  55632. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  55633. {
  55634. Component* const c = Desktop::getInstance().getComponent (i);
  55635. if (c != 0 && c->isAlwaysOnTop() && c->isShowing())
  55636. {
  55637. setAlwaysOnTop (true);
  55638. break;
  55639. }
  55640. }
  55641. #endif
  55642. lookAndFeelChanged();
  55643. constrainer.setMinimumOnscreenAmounts (0x10000, 0x10000, 0x10000, 0x10000);
  55644. }
  55645. AlertWindow::~AlertWindow()
  55646. {
  55647. for (int i = customComps.size(); --i >= 0;)
  55648. removeChildComponent ((Component*) customComps[i]);
  55649. deleteAllChildren();
  55650. }
  55651. void AlertWindow::setMessage (const String& message)
  55652. {
  55653. const String newMessage (message.substring (0, 2048));
  55654. if (text != newMessage)
  55655. {
  55656. text = newMessage;
  55657. font.setHeight (15.0f);
  55658. Font titleFont (font.getHeight() * 1.1f, Font::bold);
  55659. textLayout.setText (getName() + T("\n\n"), titleFont);
  55660. textLayout.appendText (text, font);
  55661. updateLayout (true);
  55662. repaint();
  55663. }
  55664. }
  55665. void AlertWindow::buttonClicked (Button* button)
  55666. {
  55667. for (int i = 0; i < buttons.size(); i++)
  55668. {
  55669. TextButton* const c = (TextButton*) buttons[i];
  55670. if (button->getName() == c->getName())
  55671. {
  55672. if (c->getParentComponent() != 0)
  55673. c->getParentComponent()->exitModalState (c->getCommandID());
  55674. break;
  55675. }
  55676. }
  55677. }
  55678. void AlertWindow::addButton (const String& name,
  55679. const int returnValue,
  55680. const KeyPress& shortcutKey1,
  55681. const KeyPress& shortcutKey2)
  55682. {
  55683. TextButton* const b = new TextButton (name, String::empty);
  55684. b->setWantsKeyboardFocus (true);
  55685. b->setMouseClickGrabsKeyboardFocus (false);
  55686. b->setCommandToTrigger (0, returnValue, false);
  55687. b->addShortcut (shortcutKey1);
  55688. b->addShortcut (shortcutKey2);
  55689. b->addButtonListener (this);
  55690. b->changeWidthToFitText (28);
  55691. addAndMakeVisible (b, 0);
  55692. buttons.add (b);
  55693. updateLayout (false);
  55694. }
  55695. int AlertWindow::getNumButtons() const
  55696. {
  55697. return buttons.size();
  55698. }
  55699. void AlertWindow::addTextEditor (const String& name,
  55700. const String& initialContents,
  55701. const String& onScreenLabel,
  55702. const bool isPasswordBox)
  55703. {
  55704. AlertWindowTextEditor* const tc = new AlertWindowTextEditor (name, isPasswordBox);
  55705. tc->setColour (TextEditor::outlineColourId, findColour (ComboBox::outlineColourId));
  55706. tc->setFont (font);
  55707. tc->setText (initialContents);
  55708. tc->setCaretPosition (initialContents.length());
  55709. addAndMakeVisible (tc);
  55710. textBoxes.add (tc);
  55711. allComps.add (tc);
  55712. textboxNames.add (onScreenLabel);
  55713. updateLayout (false);
  55714. }
  55715. const String AlertWindow::getTextEditorContents (const String& nameOfTextEditor) const
  55716. {
  55717. for (int i = textBoxes.size(); --i >= 0;)
  55718. if (((TextEditor*)textBoxes[i])->getName() == nameOfTextEditor)
  55719. return ((TextEditor*)textBoxes[i])->getText();
  55720. return String::empty;
  55721. }
  55722. void AlertWindow::addComboBox (const String& name,
  55723. const StringArray& items,
  55724. const String& onScreenLabel)
  55725. {
  55726. ComboBox* const cb = new ComboBox (name);
  55727. for (int i = 0; i < items.size(); ++i)
  55728. cb->addItem (items[i], i + 1);
  55729. addAndMakeVisible (cb);
  55730. cb->setSelectedItemIndex (0);
  55731. comboBoxes.add (cb);
  55732. allComps.add (cb);
  55733. comboBoxNames.add (onScreenLabel);
  55734. updateLayout (false);
  55735. }
  55736. ComboBox* AlertWindow::getComboBoxComponent (const String& nameOfList) const
  55737. {
  55738. for (int i = comboBoxes.size(); --i >= 0;)
  55739. if (((ComboBox*) comboBoxes[i])->getName() == nameOfList)
  55740. return (ComboBox*) comboBoxes[i];
  55741. return 0;
  55742. }
  55743. class AlertTextComp : public TextEditor
  55744. {
  55745. AlertTextComp (const AlertTextComp&);
  55746. const AlertTextComp& operator= (const AlertTextComp&);
  55747. int bestWidth;
  55748. public:
  55749. AlertTextComp (const String& message,
  55750. const Font& font)
  55751. {
  55752. setReadOnly (true);
  55753. setMultiLine (true, true);
  55754. setCaretVisible (false);
  55755. setScrollbarsShown (true);
  55756. lookAndFeelChanged();
  55757. setWantsKeyboardFocus (false);
  55758. setFont (font);
  55759. setText (message, false);
  55760. bestWidth = 2 * (int) sqrt (font.getHeight() * font.getStringWidth (message));
  55761. setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  55762. setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  55763. setColour (TextEditor::shadowColourId, Colours::transparentBlack);
  55764. }
  55765. ~AlertTextComp()
  55766. {
  55767. }
  55768. int getPreferredWidth() const throw() { return bestWidth; }
  55769. void updateLayout (const int width)
  55770. {
  55771. TextLayout text;
  55772. text.appendText (getText(), getFont());
  55773. text.layout (width - 8, Justification::topLeft, true);
  55774. setSize (width, jmin (width, text.getHeight() + (int) getFont().getHeight()));
  55775. }
  55776. };
  55777. void AlertWindow::addTextBlock (const String& text)
  55778. {
  55779. AlertTextComp* const c = new AlertTextComp (text, font);
  55780. textBlocks.add (c);
  55781. allComps.add (c);
  55782. addAndMakeVisible (c);
  55783. updateLayout (false);
  55784. }
  55785. void AlertWindow::addProgressBarComponent (double& progressValue)
  55786. {
  55787. ProgressBar* const pb = new ProgressBar (progressValue);
  55788. progressBars.add (pb);
  55789. allComps.add (pb);
  55790. addAndMakeVisible (pb);
  55791. updateLayout (false);
  55792. }
  55793. void AlertWindow::addCustomComponent (Component* const component)
  55794. {
  55795. customComps.add (component);
  55796. allComps.add (component);
  55797. addAndMakeVisible (component);
  55798. updateLayout (false);
  55799. }
  55800. int AlertWindow::getNumCustomComponents() const
  55801. {
  55802. return customComps.size();
  55803. }
  55804. Component* AlertWindow::getCustomComponent (const int index) const
  55805. {
  55806. return (Component*) customComps [index];
  55807. }
  55808. Component* AlertWindow::removeCustomComponent (const int index)
  55809. {
  55810. Component* const c = getCustomComponent (index);
  55811. if (c != 0)
  55812. {
  55813. customComps.removeValue (c);
  55814. allComps.removeValue (c);
  55815. removeChildComponent (c);
  55816. updateLayout (false);
  55817. }
  55818. return c;
  55819. }
  55820. void AlertWindow::paint (Graphics& g)
  55821. {
  55822. getLookAndFeel().drawAlertBox (g, *this, textArea, textLayout);
  55823. g.setColour (Colours::black);
  55824. g.setFont (12.0f);
  55825. int i;
  55826. for (i = textBoxes.size(); --i >= 0;)
  55827. {
  55828. if (textboxNames[i].isNotEmpty())
  55829. {
  55830. const TextEditor* const te = (TextEditor*) textBoxes[i];
  55831. g.drawFittedText (textboxNames[i],
  55832. te->getX(), te->getY() - 14,
  55833. te->getWidth(), 14,
  55834. Justification::centredLeft, 1);
  55835. }
  55836. }
  55837. for (i = comboBoxNames.size(); --i >= 0;)
  55838. {
  55839. if (comboBoxNames[i].isNotEmpty())
  55840. {
  55841. const ComboBox* const cb = (ComboBox*) comboBoxes[i];
  55842. g.drawFittedText (comboBoxNames[i],
  55843. cb->getX(), cb->getY() - 14,
  55844. cb->getWidth(), 14,
  55845. Justification::centredLeft, 1);
  55846. }
  55847. }
  55848. }
  55849. void AlertWindow::updateLayout (const bool onlyIncreaseSize)
  55850. {
  55851. const int wid = jmax (font.getStringWidth (text),
  55852. font.getStringWidth (getName()));
  55853. const int sw = (int) sqrt (font.getHeight() * wid);
  55854. int w = jmin (300 + sw * 2, (int) (getParentWidth() * 0.7f));
  55855. const int edgeGap = 10;
  55856. int iconSpace;
  55857. if (alertIconType == NoIcon)
  55858. {
  55859. textLayout.layout (w, Justification::horizontallyCentred, true);
  55860. iconSpace = 0;
  55861. }
  55862. else
  55863. {
  55864. textLayout.layout (w, Justification::left, true);
  55865. iconSpace = iconWidth;
  55866. }
  55867. w = jmax (350, textLayout.getWidth() + iconSpace + edgeGap * 4);
  55868. w = jmin (w, (int) (getParentWidth() * 0.7f));
  55869. const int textLayoutH = textLayout.getHeight();
  55870. const int textBottom = 16 + titleH + textLayoutH;
  55871. int h = textBottom;
  55872. int buttonW = 40;
  55873. int i;
  55874. for (i = 0; i < buttons.size(); ++i)
  55875. buttonW += 16 + ((const TextButton*) buttons[i])->getWidth();
  55876. w = jmax (buttonW, w);
  55877. h += (textBoxes.size() + comboBoxes.size() + progressBars.size()) * 50;
  55878. if (buttons.size() > 0)
  55879. h += 20 + ((TextButton*) buttons[0])->getHeight();
  55880. for (i = customComps.size(); --i >= 0;)
  55881. {
  55882. w = jmax (w, ((Component*) customComps[i])->getWidth() + 40);
  55883. h += 10 + ((Component*) customComps[i])->getHeight();
  55884. }
  55885. for (i = textBlocks.size(); --i >= 0;)
  55886. {
  55887. const AlertTextComp* const ac = (AlertTextComp*) textBlocks[i];
  55888. w = jmax (w, ac->getPreferredWidth());
  55889. }
  55890. w = jmin (w, (int) (getParentWidth() * 0.7f));
  55891. for (i = textBlocks.size(); --i >= 0;)
  55892. {
  55893. AlertTextComp* const ac = (AlertTextComp*) textBlocks[i];
  55894. ac->updateLayout ((int) (w * 0.8f));
  55895. h += ac->getHeight() + 10;
  55896. }
  55897. h = jmin (getParentHeight() - 50, h);
  55898. if (onlyIncreaseSize)
  55899. {
  55900. w = jmax (w, getWidth());
  55901. h = jmax (h, getHeight());
  55902. }
  55903. if (! isVisible())
  55904. {
  55905. centreAroundComponent (0, w, h);
  55906. }
  55907. else
  55908. {
  55909. const int cx = getX() + getWidth() / 2;
  55910. const int cy = getY() + getHeight() / 2;
  55911. setBounds (cx - w / 2,
  55912. cy - h / 2,
  55913. w, h);
  55914. }
  55915. textArea.setBounds (edgeGap, edgeGap, w - (edgeGap * 2), h - edgeGap);
  55916. const int spacer = 16;
  55917. int totalWidth = -spacer;
  55918. for (i = buttons.size(); --i >= 0;)
  55919. totalWidth += ((TextButton*) buttons[i])->getWidth() + spacer;
  55920. int x = (w - totalWidth) / 2;
  55921. int y = (int) (getHeight() * 0.95f);
  55922. for (i = 0; i < buttons.size(); ++i)
  55923. {
  55924. TextButton* const c = (TextButton*) buttons[i];
  55925. int ny = proportionOfHeight (0.95f) - c->getHeight();
  55926. c->setTopLeftPosition (x, ny);
  55927. if (ny < y)
  55928. y = ny;
  55929. x += c->getWidth() + spacer;
  55930. c->toFront (false);
  55931. }
  55932. y = textBottom;
  55933. for (i = 0; i < allComps.size(); ++i)
  55934. {
  55935. Component* const c = (Component*) allComps[i];
  55936. const int h = 22;
  55937. const int comboIndex = comboBoxes.indexOf (c);
  55938. if (comboIndex >= 0 && comboBoxNames [comboIndex].isNotEmpty())
  55939. y += 18;
  55940. const int tbIndex = textBoxes.indexOf (c);
  55941. if (tbIndex >= 0 && textboxNames[tbIndex].isNotEmpty())
  55942. y += 18;
  55943. if (customComps.contains (c) || textBlocks.contains (c))
  55944. {
  55945. c->setTopLeftPosition ((getWidth() - c->getWidth()) / 2, y);
  55946. y += c->getHeight() + 10;
  55947. }
  55948. else
  55949. {
  55950. c->setBounds (proportionOfWidth (0.1f), y, proportionOfWidth (0.8f), h);
  55951. y += h + 10;
  55952. }
  55953. }
  55954. setWantsKeyboardFocus (getNumChildComponents() == 0);
  55955. }
  55956. bool AlertWindow::containsAnyExtraComponents() const
  55957. {
  55958. return textBoxes.size()
  55959. + comboBoxes.size()
  55960. + progressBars.size()
  55961. + customComps.size() > 0;
  55962. }
  55963. void AlertWindow::mouseDown (const MouseEvent&)
  55964. {
  55965. dragger.startDraggingComponent (this, &constrainer);
  55966. }
  55967. void AlertWindow::mouseDrag (const MouseEvent& e)
  55968. {
  55969. dragger.dragComponent (this, e);
  55970. }
  55971. bool AlertWindow::keyPressed (const KeyPress& key)
  55972. {
  55973. for (int i = buttons.size(); --i >= 0;)
  55974. {
  55975. TextButton* const b = (TextButton*) buttons[i];
  55976. if (b->isRegisteredForShortcut (key))
  55977. {
  55978. b->triggerClick();
  55979. return true;
  55980. }
  55981. }
  55982. if (key.isKeyCode (KeyPress::escapeKey) && buttons.size() == 0)
  55983. {
  55984. exitModalState (0);
  55985. return true;
  55986. }
  55987. else if (key.isKeyCode (KeyPress::returnKey) && buttons.size() == 1)
  55988. {
  55989. ((TextButton*) buttons.getFirst())->triggerClick();
  55990. return true;
  55991. }
  55992. return false;
  55993. }
  55994. void AlertWindow::lookAndFeelChanged()
  55995. {
  55996. const int flags = getLookAndFeel().getAlertBoxWindowFlags();
  55997. setUsingNativeTitleBar ((flags & ComponentPeer::windowHasTitleBar) != 0);
  55998. setDropShadowEnabled ((flags & ComponentPeer::windowHasDropShadow) != 0);
  55999. }
  56000. struct AlertWindowInfo
  56001. {
  56002. String title, message, button1, button2, button3;
  56003. AlertWindow::AlertIconType iconType;
  56004. int numButtons;
  56005. int run() const
  56006. {
  56007. return (int) (pointer_sized_int)
  56008. MessageManager::getInstance()->callFunctionOnMessageThread (showCallback, (void*) this);
  56009. }
  56010. private:
  56011. int show() const
  56012. {
  56013. AlertWindow aw (title, message, iconType);
  56014. if (numButtons == 1)
  56015. {
  56016. aw.addButton (button1, 0,
  56017. KeyPress (KeyPress::escapeKey, 0, 0),
  56018. KeyPress (KeyPress::returnKey, 0, 0));
  56019. }
  56020. else
  56021. {
  56022. const KeyPress button1ShortCut (CharacterFunctions::toLowerCase (button1[0]), 0, 0);
  56023. KeyPress button2ShortCut (CharacterFunctions::toLowerCase (button2[0]), 0, 0);
  56024. if (button1ShortCut == button2ShortCut)
  56025. button2ShortCut = KeyPress();
  56026. if (numButtons == 2)
  56027. {
  56028. aw.addButton (button1, 1, KeyPress (KeyPress::returnKey, 0, 0), button1ShortCut);
  56029. aw.addButton (button2, 0, KeyPress (KeyPress::escapeKey, 0, 0), button2ShortCut);
  56030. }
  56031. else
  56032. {
  56033. jassert (numButtons == 3);
  56034. aw.addButton (button1, 1, button1ShortCut);
  56035. aw.addButton (button2, 2, button2ShortCut);
  56036. aw.addButton (button3, 0, KeyPress (KeyPress::escapeKey, 0, 0));
  56037. }
  56038. }
  56039. return aw.runModalLoop();
  56040. }
  56041. static void* showCallback (void* userData)
  56042. {
  56043. return (void*) (pointer_sized_int) ((const AlertWindowInfo*) userData)->show();
  56044. }
  56045. };
  56046. void AlertWindow::showMessageBox (AlertIconType iconType,
  56047. const String& title,
  56048. const String& message,
  56049. const String& buttonText)
  56050. {
  56051. AlertWindowInfo info;
  56052. info.title = title;
  56053. info.message = message;
  56054. info.button1 = buttonText.isEmpty() ? TRANS("ok") : buttonText;
  56055. info.iconType = iconType;
  56056. info.numButtons = 1;
  56057. info.run();
  56058. }
  56059. bool AlertWindow::showOkCancelBox (AlertIconType iconType,
  56060. const String& title,
  56061. const String& message,
  56062. const String& button1Text,
  56063. const String& button2Text)
  56064. {
  56065. AlertWindowInfo info;
  56066. info.title = title;
  56067. info.message = message;
  56068. info.button1 = button1Text.isEmpty() ? TRANS("ok") : button1Text;
  56069. info.button2 = button2Text.isEmpty() ? TRANS("cancel") : button2Text;
  56070. info.iconType = iconType;
  56071. info.numButtons = 2;
  56072. return info.run() != 0;
  56073. }
  56074. int AlertWindow::showYesNoCancelBox (AlertIconType iconType,
  56075. const String& title,
  56076. const String& message,
  56077. const String& button1Text,
  56078. const String& button2Text,
  56079. const String& button3Text)
  56080. {
  56081. AlertWindowInfo info;
  56082. info.title = title;
  56083. info.message = message;
  56084. info.button1 = button1Text.isEmpty() ? TRANS("yes") : button1Text;
  56085. info.button2 = button2Text.isEmpty() ? TRANS("no") : button2Text;
  56086. info.button3 = button3Text.isEmpty() ? TRANS("cancel") : button3Text;
  56087. info.iconType = iconType;
  56088. info.numButtons = 3;
  56089. return info.run();
  56090. }
  56091. END_JUCE_NAMESPACE
  56092. /********* End of inlined file: juce_AlertWindow.cpp *********/
  56093. /********* Start of inlined file: juce_ComponentPeer.cpp *********/
  56094. BEGIN_JUCE_NAMESPACE
  56095. //#define JUCE_ENABLE_REPAINT_DEBUGGING 1
  56096. // these are over in juce_component.cpp
  56097. extern int64 juce_recentMouseDownTimes[4];
  56098. extern int juce_recentMouseDownX [4];
  56099. extern int juce_recentMouseDownY [4];
  56100. extern Component* juce_recentMouseDownComponent [4];
  56101. extern int juce_LastMousePosX;
  56102. extern int juce_LastMousePosY;
  56103. extern int juce_MouseClickCounter;
  56104. extern bool juce_MouseHasMovedSignificantlySincePressed;
  56105. static const int fakeMouseMoveMessage = 0x7fff00ff;
  56106. static VoidArray heavyweightPeers (4);
  56107. ComponentPeer::ComponentPeer (Component* const component_,
  56108. const int styleFlags_) throw()
  56109. : component (component_),
  56110. styleFlags (styleFlags_),
  56111. lastPaintTime (0),
  56112. constrainer (0),
  56113. lastFocusedComponent (0),
  56114. dragAndDropTargetComponent (0),
  56115. lastDragAndDropCompUnderMouse (0),
  56116. fakeMouseMessageSent (false),
  56117. isWindowMinimised (false)
  56118. {
  56119. heavyweightPeers.add (this);
  56120. }
  56121. ComponentPeer::~ComponentPeer()
  56122. {
  56123. heavyweightPeers.removeValue (this);
  56124. delete dragAndDropTargetComponent;
  56125. }
  56126. int ComponentPeer::getNumPeers() throw()
  56127. {
  56128. return heavyweightPeers.size();
  56129. }
  56130. ComponentPeer* ComponentPeer::getPeer (const int index) throw()
  56131. {
  56132. return (ComponentPeer*) heavyweightPeers [index];
  56133. }
  56134. ComponentPeer* ComponentPeer::getPeerFor (const Component* const component) throw()
  56135. {
  56136. for (int i = heavyweightPeers.size(); --i >= 0;)
  56137. {
  56138. ComponentPeer* const peer = (ComponentPeer*) heavyweightPeers.getUnchecked(i);
  56139. if (peer->getComponent() == component)
  56140. return peer;
  56141. }
  56142. return 0;
  56143. }
  56144. bool ComponentPeer::isValidPeer (const ComponentPeer* const peer) throw()
  56145. {
  56146. return heavyweightPeers.contains (const_cast <ComponentPeer*> (peer));
  56147. }
  56148. void ComponentPeer::updateCurrentModifiers() throw()
  56149. {
  56150. ModifierKeys::updateCurrentModifiers();
  56151. }
  56152. void ComponentPeer::handleMouseEnter (int x, int y, const int64 time)
  56153. {
  56154. jassert (component->isValidComponent());
  56155. updateCurrentModifiers();
  56156. Component* c = component->getComponentAt (x, y);
  56157. const ComponentDeletionWatcher deletionChecker (component);
  56158. if (c != Component::componentUnderMouse && Component::componentUnderMouse != 0)
  56159. {
  56160. jassert (Component::componentUnderMouse->isValidComponent());
  56161. const int oldX = x;
  56162. const int oldY = y;
  56163. component->relativePositionToOtherComponent (Component::componentUnderMouse, x, y);
  56164. Component::componentUnderMouse->internalMouseExit (x, y, time);
  56165. Component::componentUnderMouse = 0;
  56166. if (deletionChecker.hasBeenDeleted())
  56167. return;
  56168. c = component->getComponentAt (oldX, oldY);
  56169. }
  56170. Component::componentUnderMouse = c;
  56171. if (Component::componentUnderMouse != 0)
  56172. {
  56173. component->relativePositionToOtherComponent (Component::componentUnderMouse, x, y);
  56174. Component::componentUnderMouse->internalMouseEnter (x, y, time);
  56175. }
  56176. }
  56177. void ComponentPeer::handleMouseMove (int x, int y, const int64 time)
  56178. {
  56179. jassert (component->isValidComponent());
  56180. updateCurrentModifiers();
  56181. fakeMouseMessageSent = false;
  56182. const ComponentDeletionWatcher deletionChecker (component);
  56183. Component* c = component->getComponentAt (x, y);
  56184. if (c != Component::componentUnderMouse)
  56185. {
  56186. const int oldX = x;
  56187. const int oldY = y;
  56188. if (Component::componentUnderMouse != 0)
  56189. {
  56190. component->relativePositionToOtherComponent (Component::componentUnderMouse, x, y);
  56191. Component::componentUnderMouse->internalMouseExit (x, y, time);
  56192. x = oldX;
  56193. y = oldY;
  56194. Component::componentUnderMouse = 0;
  56195. if (deletionChecker.hasBeenDeleted())
  56196. return; // if this window has just been deleted..
  56197. c = component->getComponentAt (x, y);
  56198. }
  56199. Component::componentUnderMouse = c;
  56200. if (c != 0)
  56201. {
  56202. component->relativePositionToOtherComponent (c, x, y);
  56203. c->internalMouseEnter (x, y, time);
  56204. x = oldX;
  56205. y = oldY;
  56206. if (deletionChecker.hasBeenDeleted())
  56207. return; // if this window has just been deleted..
  56208. }
  56209. }
  56210. if (Component::componentUnderMouse != 0)
  56211. {
  56212. component->relativePositionToOtherComponent (Component::componentUnderMouse, x, y);
  56213. Component::componentUnderMouse->internalMouseMove (x, y, time);
  56214. }
  56215. }
  56216. void ComponentPeer::handleMouseDown (int x, int y, const int64 time)
  56217. {
  56218. ++juce_MouseClickCounter;
  56219. updateCurrentModifiers();
  56220. int numMouseButtonsDown = 0;
  56221. if (ModifierKeys::getCurrentModifiers().isLeftButtonDown())
  56222. ++numMouseButtonsDown;
  56223. if (ModifierKeys::getCurrentModifiers().isRightButtonDown())
  56224. ++numMouseButtonsDown;
  56225. if (ModifierKeys::getCurrentModifiers().isMiddleButtonDown())
  56226. ++numMouseButtonsDown;
  56227. if (numMouseButtonsDown == 1)
  56228. {
  56229. Component::componentUnderMouse = component->getComponentAt (x, y);
  56230. if (Component::componentUnderMouse != 0)
  56231. {
  56232. // can't set these in the mouseDownInt() method, because it's re-entrant, so do it here..
  56233. for (int i = numElementsInArray (juce_recentMouseDownTimes); --i > 0;)
  56234. {
  56235. juce_recentMouseDownTimes [i] = juce_recentMouseDownTimes [i - 1];
  56236. juce_recentMouseDownX [i] = juce_recentMouseDownX [i - 1];
  56237. juce_recentMouseDownY [i] = juce_recentMouseDownY [i - 1];
  56238. juce_recentMouseDownComponent [i] = juce_recentMouseDownComponent [i - 1];
  56239. }
  56240. juce_recentMouseDownTimes[0] = time;
  56241. juce_recentMouseDownX[0] = x;
  56242. juce_recentMouseDownY[0] = y;
  56243. juce_recentMouseDownComponent[0] = Component::componentUnderMouse;
  56244. relativePositionToGlobal (juce_recentMouseDownX[0], juce_recentMouseDownY[0]);
  56245. juce_MouseHasMovedSignificantlySincePressed = false;
  56246. component->relativePositionToOtherComponent (Component::componentUnderMouse, x, y);
  56247. Component::componentUnderMouse->internalMouseDown (x, y);
  56248. }
  56249. }
  56250. }
  56251. void ComponentPeer::handleMouseDrag (int x, int y, const int64 time)
  56252. {
  56253. updateCurrentModifiers();
  56254. if (Component::componentUnderMouse != 0)
  56255. {
  56256. component->relativePositionToOtherComponent (Component::componentUnderMouse, x, y);
  56257. Component::componentUnderMouse->internalMouseDrag (x, y, time);
  56258. }
  56259. }
  56260. void ComponentPeer::handleMouseUp (const int oldModifiers, int x, int y, const int64 time)
  56261. {
  56262. updateCurrentModifiers();
  56263. int numMouseButtonsDown = 0;
  56264. if ((oldModifiers & ModifierKeys::leftButtonModifier) != 0)
  56265. ++numMouseButtonsDown;
  56266. if ((oldModifiers & ModifierKeys::rightButtonModifier) != 0)
  56267. ++numMouseButtonsDown;
  56268. if ((oldModifiers & ModifierKeys::middleButtonModifier) != 0)
  56269. ++numMouseButtonsDown;
  56270. if (numMouseButtonsDown == 1)
  56271. {
  56272. const ComponentDeletionWatcher deletionChecker (component);
  56273. Component* c = component->getComponentAt (x, y);
  56274. if (c != Component::componentUnderMouse)
  56275. {
  56276. const int oldX = x;
  56277. const int oldY = y;
  56278. if (Component::componentUnderMouse != 0)
  56279. {
  56280. component->relativePositionToOtherComponent (Component::componentUnderMouse, x, y);
  56281. Component::componentUnderMouse->internalMouseUp (oldModifiers, x, y, time);
  56282. x = oldX;
  56283. y = oldY;
  56284. if (Component::componentUnderMouse != 0)
  56285. Component::componentUnderMouse->internalMouseExit (x, y, time);
  56286. if (deletionChecker.hasBeenDeleted())
  56287. return;
  56288. c = component->getComponentAt (oldX, oldY);
  56289. }
  56290. Component::componentUnderMouse = c;
  56291. if (Component::componentUnderMouse != 0)
  56292. {
  56293. component->relativePositionToOtherComponent (Component::componentUnderMouse, x, y);
  56294. Component::componentUnderMouse->internalMouseEnter (x, y, time);
  56295. }
  56296. }
  56297. else
  56298. {
  56299. if (Component::componentUnderMouse != 0)
  56300. {
  56301. component->relativePositionToOtherComponent (Component::componentUnderMouse, x, y);
  56302. Component::componentUnderMouse->internalMouseUp (oldModifiers, x, y, time);
  56303. }
  56304. }
  56305. }
  56306. }
  56307. void ComponentPeer::handleMouseExit (int x, int y, const int64 time)
  56308. {
  56309. jassert (component->isValidComponent());
  56310. updateCurrentModifiers();
  56311. if (Component::componentUnderMouse != 0)
  56312. {
  56313. component->relativePositionToOtherComponent (Component::componentUnderMouse, x, y);
  56314. Component::componentUnderMouse->internalMouseExit (x, y, time);
  56315. Component::componentUnderMouse = 0;
  56316. }
  56317. }
  56318. void ComponentPeer::handleMouseWheel (const int amountX, const int amountY, const int64 time)
  56319. {
  56320. updateCurrentModifiers();
  56321. if (Component::componentUnderMouse != 0)
  56322. Component::componentUnderMouse->internalMouseWheel (amountX, amountY, time);
  56323. }
  56324. void ComponentPeer::sendFakeMouseMove() throw()
  56325. {
  56326. if ((! fakeMouseMessageSent)
  56327. && component->flags.hasHeavyweightPeerFlag
  56328. && ! ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown())
  56329. {
  56330. if (! isMinimised())
  56331. {
  56332. int realX, realY, realW, realH;
  56333. getBounds (realX, realY, realW, realH);
  56334. component->bounds_.setBounds (realX, realY, realW, realH);
  56335. }
  56336. int x, y;
  56337. component->getMouseXYRelative (x, y);
  56338. if (((unsigned int) x) < (unsigned int) component->getWidth()
  56339. && ((unsigned int) y) < (unsigned int) component->getHeight()
  56340. && contains (x, y, false))
  56341. {
  56342. postMessage (new Message (fakeMouseMoveMessage, x, y, 0));
  56343. }
  56344. fakeMouseMessageSent = true;
  56345. }
  56346. }
  56347. void ComponentPeer::handleMessage (const Message& message)
  56348. {
  56349. if (message.intParameter1 == fakeMouseMoveMessage)
  56350. {
  56351. handleMouseMove (message.intParameter2,
  56352. message.intParameter3,
  56353. Time::currentTimeMillis());
  56354. }
  56355. }
  56356. void ComponentPeer::handlePaint (LowLevelGraphicsContext& contextToPaintTo)
  56357. {
  56358. Graphics g (&contextToPaintTo);
  56359. #if JUCE_ENABLE_REPAINT_DEBUGGING
  56360. g.saveState();
  56361. #endif
  56362. JUCE_TRY
  56363. {
  56364. component->paintEntireComponent (g);
  56365. }
  56366. JUCE_CATCH_EXCEPTION
  56367. #if JUCE_ENABLE_REPAINT_DEBUGGING
  56368. // enabling this code will fill all areas that get repainted with a colour overlay, to show
  56369. // clearly when things are being repainted.
  56370. {
  56371. g.restoreState();
  56372. g.fillAll (Colour ((uint8) Random::getSystemRandom().nextInt (255),
  56373. (uint8) Random::getSystemRandom().nextInt (255),
  56374. (uint8) Random::getSystemRandom().nextInt (255),
  56375. (uint8) 0x50));
  56376. }
  56377. #endif
  56378. }
  56379. bool ComponentPeer::handleKeyPress (const int keyCode,
  56380. const juce_wchar textCharacter)
  56381. {
  56382. updateCurrentModifiers();
  56383. Component* target = Component::currentlyFocusedComponent->isValidComponent()
  56384. ? Component::currentlyFocusedComponent
  56385. : component;
  56386. if (target->isCurrentlyBlockedByAnotherModalComponent())
  56387. {
  56388. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  56389. if (currentModalComp != 0)
  56390. target = currentModalComp;
  56391. }
  56392. const KeyPress keyInfo (keyCode,
  56393. ModifierKeys::getCurrentModifiers().getRawFlags()
  56394. & ModifierKeys::allKeyboardModifiers,
  56395. textCharacter);
  56396. bool keyWasUsed = false;
  56397. while (target != 0)
  56398. {
  56399. const ComponentDeletionWatcher deletionChecker (target);
  56400. if (target->keyListeners_ != 0)
  56401. {
  56402. for (int i = target->keyListeners_->size(); --i >= 0;)
  56403. {
  56404. keyWasUsed = ((KeyListener*) target->keyListeners_->getUnchecked(i))->keyPressed (keyInfo, target);
  56405. if (keyWasUsed || deletionChecker.hasBeenDeleted())
  56406. return keyWasUsed;
  56407. i = jmin (i, target->keyListeners_->size());
  56408. }
  56409. }
  56410. keyWasUsed = target->keyPressed (keyInfo);
  56411. if (keyWasUsed || deletionChecker.hasBeenDeleted())
  56412. break;
  56413. if (keyInfo.isKeyCode (KeyPress::tabKey) && Component::getCurrentlyFocusedComponent() != 0)
  56414. {
  56415. Component::getCurrentlyFocusedComponent()
  56416. ->moveKeyboardFocusToSibling (! keyInfo.getModifiers().isShiftDown());
  56417. keyWasUsed = true;
  56418. break;
  56419. }
  56420. target = target->parentComponent_;
  56421. }
  56422. return keyWasUsed;
  56423. }
  56424. bool ComponentPeer::handleKeyUpOrDown()
  56425. {
  56426. updateCurrentModifiers();
  56427. Component* target = Component::currentlyFocusedComponent->isValidComponent()
  56428. ? Component::currentlyFocusedComponent
  56429. : component;
  56430. if (target->isCurrentlyBlockedByAnotherModalComponent())
  56431. {
  56432. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  56433. if (currentModalComp != 0)
  56434. target = currentModalComp;
  56435. }
  56436. bool keyWasUsed = false;
  56437. while (target != 0)
  56438. {
  56439. const ComponentDeletionWatcher deletionChecker (target);
  56440. keyWasUsed = target->keyStateChanged();
  56441. if (keyWasUsed || deletionChecker.hasBeenDeleted())
  56442. break;
  56443. if (target->keyListeners_ != 0)
  56444. {
  56445. for (int i = target->keyListeners_->size(); --i >= 0;)
  56446. {
  56447. keyWasUsed = ((KeyListener*) target->keyListeners_->getUnchecked(i))->keyStateChanged (target);
  56448. if (keyWasUsed || deletionChecker.hasBeenDeleted())
  56449. return keyWasUsed;
  56450. i = jmin (i, target->keyListeners_->size());
  56451. }
  56452. }
  56453. target = target->parentComponent_;
  56454. }
  56455. return keyWasUsed;
  56456. }
  56457. void ComponentPeer::handleModifierKeysChange()
  56458. {
  56459. updateCurrentModifiers();
  56460. Component* target = Component::getComponentUnderMouse();
  56461. if (target == 0)
  56462. target = Component::getCurrentlyFocusedComponent();
  56463. if (target == 0)
  56464. target = component;
  56465. if (target->isValidComponent())
  56466. target->internalModifierKeysChanged();
  56467. }
  56468. void ComponentPeer::handleBroughtToFront()
  56469. {
  56470. updateCurrentModifiers();
  56471. if (component != 0)
  56472. component->internalBroughtToFront();
  56473. }
  56474. void ComponentPeer::setConstrainer (ComponentBoundsConstrainer* const newConstrainer) throw()
  56475. {
  56476. constrainer = newConstrainer;
  56477. }
  56478. void ComponentPeer::handleMovedOrResized()
  56479. {
  56480. jassert (component->isValidComponent());
  56481. updateCurrentModifiers();
  56482. const bool nowMinimised = isMinimised();
  56483. if (component->flags.hasHeavyweightPeerFlag && ! nowMinimised)
  56484. {
  56485. const ComponentDeletionWatcher deletionChecker (component);
  56486. int realX, realY, realW, realH;
  56487. getBounds (realX, realY, realW, realH);
  56488. const bool wasMoved = (component->getX() != realX || component->getY() != realY);
  56489. const bool wasResized = (component->getWidth() != realW || component->getHeight() != realH);
  56490. if (wasMoved || wasResized)
  56491. {
  56492. component->bounds_.setBounds (realX, realY, realW, realH);
  56493. if (wasResized)
  56494. component->repaint();
  56495. component->sendMovedResizedMessages (wasMoved, wasResized);
  56496. if (deletionChecker.hasBeenDeleted())
  56497. return;
  56498. }
  56499. }
  56500. if (isWindowMinimised != nowMinimised)
  56501. {
  56502. isWindowMinimised = nowMinimised;
  56503. component->minimisationStateChanged (nowMinimised);
  56504. component->sendVisibilityChangeMessage();
  56505. }
  56506. if (! isFullScreen())
  56507. lastNonFullscreenBounds = component->getBounds();
  56508. }
  56509. void ComponentPeer::handleFocusGain()
  56510. {
  56511. updateCurrentModifiers();
  56512. if (component->isParentOf (lastFocusedComponent))
  56513. {
  56514. Component::currentlyFocusedComponent = lastFocusedComponent;
  56515. Desktop::getInstance().triggerFocusCallback();
  56516. lastFocusedComponent->internalFocusGain (Component::focusChangedDirectly);
  56517. }
  56518. else
  56519. {
  56520. if (! component->isCurrentlyBlockedByAnotherModalComponent())
  56521. {
  56522. component->grabKeyboardFocus();
  56523. }
  56524. else
  56525. {
  56526. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  56527. if (currentModalComp != 0)
  56528. currentModalComp->toFront (! currentModalComp->hasKeyboardFocus (true));
  56529. }
  56530. }
  56531. }
  56532. void ComponentPeer::handleFocusLoss()
  56533. {
  56534. updateCurrentModifiers();
  56535. if (component->hasKeyboardFocus (true))
  56536. {
  56537. lastFocusedComponent = Component::currentlyFocusedComponent;
  56538. if (lastFocusedComponent != 0)
  56539. {
  56540. Component::currentlyFocusedComponent = 0;
  56541. Desktop::getInstance().triggerFocusCallback();
  56542. lastFocusedComponent->internalFocusLoss (Component::focusChangedByMouseClick);
  56543. }
  56544. }
  56545. }
  56546. Component* ComponentPeer::getLastFocusedSubcomponent() const throw()
  56547. {
  56548. return (component->isParentOf (lastFocusedComponent) && lastFocusedComponent->isShowing())
  56549. ? lastFocusedComponent
  56550. : component;
  56551. }
  56552. void ComponentPeer::handleScreenSizeChange()
  56553. {
  56554. updateCurrentModifiers();
  56555. component->parentSizeChanged();
  56556. handleMovedOrResized();
  56557. }
  56558. void ComponentPeer::setNonFullScreenBounds (const Rectangle& newBounds) throw()
  56559. {
  56560. lastNonFullscreenBounds = newBounds;
  56561. }
  56562. const Rectangle& ComponentPeer::getNonFullScreenBounds() const throw()
  56563. {
  56564. return lastNonFullscreenBounds;
  56565. }
  56566. static FileDragAndDropTarget* findDragAndDropTarget (Component* c,
  56567. const StringArray& files,
  56568. FileDragAndDropTarget* const lastOne)
  56569. {
  56570. while (c != 0)
  56571. {
  56572. FileDragAndDropTarget* const t = dynamic_cast <FileDragAndDropTarget*> (c);
  56573. if (t != 0 && (t == lastOne || t->isInterestedInFileDrag (files)))
  56574. return t;
  56575. c = c->getParentComponent();
  56576. }
  56577. return 0;
  56578. }
  56579. void ComponentPeer::handleFileDragMove (const StringArray& files, int x, int y)
  56580. {
  56581. updateCurrentModifiers();
  56582. FileDragAndDropTarget* lastTarget = 0;
  56583. if (dragAndDropTargetComponent != 0 && ! dragAndDropTargetComponent->hasBeenDeleted())
  56584. lastTarget = const_cast <FileDragAndDropTarget*> (dynamic_cast <const FileDragAndDropTarget*> (dragAndDropTargetComponent->getComponent()));
  56585. FileDragAndDropTarget* newTarget = 0;
  56586. Component* const compUnderMouse = component->getComponentAt (x, y);
  56587. if (compUnderMouse != lastDragAndDropCompUnderMouse)
  56588. {
  56589. lastDragAndDropCompUnderMouse = compUnderMouse;
  56590. newTarget = findDragAndDropTarget (compUnderMouse, files, lastTarget);
  56591. if (newTarget != lastTarget)
  56592. {
  56593. if (lastTarget != 0)
  56594. lastTarget->fileDragExit (files);
  56595. deleteAndZero (dragAndDropTargetComponent);
  56596. if (newTarget != 0)
  56597. {
  56598. Component* const targetComp = dynamic_cast <Component*> (newTarget);
  56599. int mx = x, my = y;
  56600. component->relativePositionToOtherComponent (targetComp, mx, my);
  56601. dragAndDropTargetComponent = new ComponentDeletionWatcher (dynamic_cast <Component*> (newTarget));
  56602. newTarget->fileDragEnter (files, mx, my);
  56603. }
  56604. }
  56605. }
  56606. else
  56607. {
  56608. newTarget = lastTarget;
  56609. }
  56610. if (newTarget != 0)
  56611. {
  56612. Component* const targetComp = dynamic_cast <Component*> (newTarget);
  56613. component->relativePositionToOtherComponent (targetComp, x, y);
  56614. newTarget->fileDragMove (files, x, y);
  56615. }
  56616. }
  56617. void ComponentPeer::handleFileDragExit (const StringArray& files)
  56618. {
  56619. handleFileDragMove (files, -1, -1);
  56620. jassert (dragAndDropTargetComponent == 0);
  56621. lastDragAndDropCompUnderMouse = 0;
  56622. }
  56623. void ComponentPeer::handleFileDragDrop (const StringArray& files, int x, int y)
  56624. {
  56625. handleFileDragMove (files, x, y);
  56626. if (dragAndDropTargetComponent != 0 && ! dragAndDropTargetComponent->hasBeenDeleted())
  56627. {
  56628. FileDragAndDropTarget* const target = const_cast <FileDragAndDropTarget*> (dynamic_cast <const FileDragAndDropTarget*> (dragAndDropTargetComponent->getComponent()));
  56629. deleteAndZero (dragAndDropTargetComponent);
  56630. lastDragAndDropCompUnderMouse = 0;
  56631. if (target != 0)
  56632. {
  56633. Component* const targetComp = dynamic_cast <Component*> (target);
  56634. if (targetComp->isCurrentlyBlockedByAnotherModalComponent())
  56635. {
  56636. targetComp->internalModalInputAttempt();
  56637. if (targetComp->isCurrentlyBlockedByAnotherModalComponent())
  56638. return;
  56639. }
  56640. component->relativePositionToOtherComponent (targetComp, x, y);
  56641. target->filesDropped (files, x, y);
  56642. }
  56643. }
  56644. }
  56645. void ComponentPeer::handleUserClosingWindow()
  56646. {
  56647. updateCurrentModifiers();
  56648. component->userTriedToCloseWindow();
  56649. }
  56650. void ComponentPeer::clearMaskedRegion() throw()
  56651. {
  56652. maskedRegion.clear();
  56653. }
  56654. void ComponentPeer::addMaskedRegion (int x, int y, int w, int h) throw()
  56655. {
  56656. maskedRegion.add (x, y, w, h);
  56657. }
  56658. END_JUCE_NAMESPACE
  56659. /********* End of inlined file: juce_ComponentPeer.cpp *********/
  56660. /********* Start of inlined file: juce_DialogWindow.cpp *********/
  56661. BEGIN_JUCE_NAMESPACE
  56662. DialogWindow::DialogWindow (const String& name,
  56663. const Colour& backgroundColour_,
  56664. const bool escapeKeyTriggersCloseButton_,
  56665. const bool addToDesktop_)
  56666. : DocumentWindow (name, backgroundColour_, DocumentWindow::closeButton, addToDesktop_),
  56667. escapeKeyTriggersCloseButton (escapeKeyTriggersCloseButton_)
  56668. {
  56669. }
  56670. DialogWindow::~DialogWindow()
  56671. {
  56672. }
  56673. void DialogWindow::resized()
  56674. {
  56675. DocumentWindow::resized();
  56676. const KeyPress esc (KeyPress::escapeKey, 0, 0);
  56677. if (escapeKeyTriggersCloseButton
  56678. && getCloseButton() != 0
  56679. && ! getCloseButton()->isRegisteredForShortcut (esc))
  56680. {
  56681. getCloseButton()->addShortcut (esc);
  56682. }
  56683. }
  56684. class TempDialogWindow : public DialogWindow
  56685. {
  56686. public:
  56687. TempDialogWindow (const String& title, const Colour& colour, const bool escapeCloses)
  56688. : DialogWindow (title, colour, escapeCloses, true)
  56689. {
  56690. }
  56691. ~TempDialogWindow()
  56692. {
  56693. }
  56694. void closeButtonPressed()
  56695. {
  56696. setVisible (false);
  56697. }
  56698. private:
  56699. TempDialogWindow (const TempDialogWindow&);
  56700. const TempDialogWindow& operator= (const TempDialogWindow&);
  56701. };
  56702. int DialogWindow::showModalDialog (const String& dialogTitle,
  56703. Component* contentComponent,
  56704. Component* componentToCentreAround,
  56705. const Colour& colour,
  56706. const bool escapeKeyTriggersCloseButton,
  56707. const bool shouldBeResizable,
  56708. const bool useBottomRightCornerResizer)
  56709. {
  56710. TempDialogWindow dw (dialogTitle, colour, escapeKeyTriggersCloseButton);
  56711. dw.setContentComponent (contentComponent, true, true);
  56712. dw.centreAroundComponent (componentToCentreAround, dw.getWidth(), dw.getHeight());
  56713. dw.setResizable (shouldBeResizable, useBottomRightCornerResizer);
  56714. const int result = dw.runModalLoop();
  56715. dw.setContentComponent (0, false);
  56716. return result;
  56717. }
  56718. END_JUCE_NAMESPACE
  56719. /********* End of inlined file: juce_DialogWindow.cpp *********/
  56720. /********* Start of inlined file: juce_DocumentWindow.cpp *********/
  56721. BEGIN_JUCE_NAMESPACE
  56722. DocumentWindow::DocumentWindow (const String& title,
  56723. const Colour& backgroundColour,
  56724. const int requiredButtons_,
  56725. const bool addToDesktop_)
  56726. : ResizableWindow (title, backgroundColour, addToDesktop_),
  56727. titleBarHeight (26),
  56728. menuBarHeight (24),
  56729. requiredButtons (requiredButtons_),
  56730. #if JUCE_MAC
  56731. positionTitleBarButtonsOnLeft (true),
  56732. #else
  56733. positionTitleBarButtonsOnLeft (false),
  56734. #endif
  56735. drawTitleTextCentred (true),
  56736. titleBarIcon (0),
  56737. menuBar (0),
  56738. menuBarModel (0)
  56739. {
  56740. zeromem (titleBarButtons, sizeof (titleBarButtons));
  56741. setResizeLimits (128, 128, 32768, 32768);
  56742. lookAndFeelChanged();
  56743. }
  56744. DocumentWindow::~DocumentWindow()
  56745. {
  56746. for (int i = 0; i < 3; ++i)
  56747. delete titleBarButtons[i];
  56748. delete titleBarIcon;
  56749. delete menuBar;
  56750. }
  56751. void DocumentWindow::repaintTitleBar()
  56752. {
  56753. const int border = getBorderSize();
  56754. repaint (border, border, getWidth() - border * 2, getTitleBarHeight());
  56755. }
  56756. void DocumentWindow::setName (const String& newName)
  56757. {
  56758. if (newName != getName())
  56759. {
  56760. Component::setName (newName);
  56761. repaintTitleBar();
  56762. }
  56763. }
  56764. void DocumentWindow::setIcon (const Image* imageToUse)
  56765. {
  56766. deleteAndZero (titleBarIcon);
  56767. if (imageToUse != 0)
  56768. titleBarIcon = imageToUse->createCopy();
  56769. repaintTitleBar();
  56770. }
  56771. void DocumentWindow::setTitleBarHeight (const int newHeight)
  56772. {
  56773. titleBarHeight = newHeight;
  56774. resized();
  56775. repaintTitleBar();
  56776. }
  56777. void DocumentWindow::setTitleBarButtonsRequired (const int requiredButtons_,
  56778. const bool positionTitleBarButtonsOnLeft_)
  56779. {
  56780. requiredButtons = requiredButtons_;
  56781. positionTitleBarButtonsOnLeft = positionTitleBarButtonsOnLeft_;
  56782. lookAndFeelChanged();
  56783. }
  56784. void DocumentWindow::setTitleBarTextCentred (const bool textShouldBeCentred)
  56785. {
  56786. drawTitleTextCentred = textShouldBeCentred;
  56787. repaintTitleBar();
  56788. }
  56789. void DocumentWindow::setMenuBar (MenuBarModel* menuBarModel_,
  56790. const int menuBarHeight_)
  56791. {
  56792. if (menuBarModel != menuBarModel_)
  56793. {
  56794. delete menuBar;
  56795. menuBar = 0;
  56796. menuBarModel = menuBarModel_;
  56797. menuBarHeight = (menuBarHeight_ > 0) ? menuBarHeight_
  56798. : getLookAndFeel().getDefaultMenuBarHeight();
  56799. if (menuBarModel != 0)
  56800. {
  56801. // (call the Component method directly to avoid the assertion in ResizableWindow)
  56802. Component::addAndMakeVisible (menuBar = new MenuBarComponent (menuBarModel));
  56803. menuBar->setEnabled (isActiveWindow());
  56804. }
  56805. resized();
  56806. }
  56807. }
  56808. void DocumentWindow::closeButtonPressed()
  56809. {
  56810. /* If you've got a close button, you have to override this method to get
  56811. rid of your window!
  56812. If the window is just a pop-up, you should override this method and make
  56813. it delete the window in whatever way is appropriate for your app. E.g. you
  56814. might just want to call "delete this".
  56815. If your app is centred around this window such that the whole app should quit when
  56816. the window is closed, then you will probably want to use this method as an opportunity
  56817. to call JUCEApplication::quit(), and leave the window to be deleted later by your
  56818. JUCEApplication::shutdown() method. (Doing it this way means that your window will
  56819. still get cleaned-up if the app is quit by some other means (e.g. a cmd-Q on the mac
  56820. or closing it via the taskbar icon on Windows).
  56821. */
  56822. jassertfalse
  56823. }
  56824. void DocumentWindow::minimiseButtonPressed()
  56825. {
  56826. setMinimised (true);
  56827. }
  56828. void DocumentWindow::maximiseButtonPressed()
  56829. {
  56830. setFullScreen (! isFullScreen());
  56831. }
  56832. void DocumentWindow::paint (Graphics& g)
  56833. {
  56834. ResizableWindow::paint (g);
  56835. if (resizableBorder == 0 && getBorderSize() == 1)
  56836. {
  56837. g.setColour (getBackgroundColour().overlaidWith (Colour (0x80000000)));
  56838. g.drawRect (0, 0, getWidth(), getHeight());
  56839. }
  56840. const int border = getBorderSize();
  56841. g.setOrigin (border, border);
  56842. g.reduceClipRegion (0, 0, getWidth() - border * 2, getTitleBarHeight());
  56843. int titleSpaceX1 = 6;
  56844. int titleSpaceX2 = getWidth() - 6;
  56845. for (int i = 0; i < 3; ++i)
  56846. {
  56847. if (titleBarButtons[i] != 0)
  56848. {
  56849. if (positionTitleBarButtonsOnLeft)
  56850. titleSpaceX1 = jmax (titleSpaceX1, titleBarButtons[i]->getRight() + (getWidth() - titleBarButtons[i]->getRight()) / 8);
  56851. else
  56852. titleSpaceX2 = jmin (titleSpaceX2, titleBarButtons[i]->getX() - (titleBarButtons[i]->getX() / 8));
  56853. }
  56854. }
  56855. getLookAndFeel()
  56856. .drawDocumentWindowTitleBar (*this, g,
  56857. getWidth() - border * 2,
  56858. getTitleBarHeight(),
  56859. titleSpaceX1, jmax (1, titleSpaceX2 - titleSpaceX1),
  56860. titleBarIcon, ! drawTitleTextCentred);
  56861. }
  56862. void DocumentWindow::resized()
  56863. {
  56864. ResizableWindow::resized();
  56865. if (titleBarButtons[1] != 0)
  56866. titleBarButtons[1]->setToggleState (isFullScreen(), false);
  56867. const int border = getBorderSize();
  56868. getLookAndFeel()
  56869. .positionDocumentWindowButtons (*this,
  56870. border, border,
  56871. getWidth() - border * 2, getTitleBarHeight(),
  56872. titleBarButtons[0],
  56873. titleBarButtons[1],
  56874. titleBarButtons[2],
  56875. positionTitleBarButtonsOnLeft);
  56876. if (menuBar != 0)
  56877. menuBar->setBounds (border, border + getTitleBarHeight(),
  56878. getWidth() - border * 2, menuBarHeight);
  56879. }
  56880. Button* DocumentWindow::getCloseButton() const throw()
  56881. {
  56882. return titleBarButtons[2];
  56883. }
  56884. Button* DocumentWindow::getMinimiseButton() const throw()
  56885. {
  56886. return titleBarButtons[0];
  56887. }
  56888. Button* DocumentWindow::getMaximiseButton() const throw()
  56889. {
  56890. return titleBarButtons[1];
  56891. }
  56892. int DocumentWindow::getDesktopWindowStyleFlags() const
  56893. {
  56894. int flags = ResizableWindow::getDesktopWindowStyleFlags();
  56895. if ((requiredButtons & minimiseButton) != 0)
  56896. flags |= ComponentPeer::windowHasMinimiseButton;
  56897. if ((requiredButtons & maximiseButton) != 0)
  56898. flags |= ComponentPeer::windowHasMaximiseButton;
  56899. if ((requiredButtons & closeButton) != 0)
  56900. flags |= ComponentPeer::windowHasCloseButton;
  56901. return flags;
  56902. }
  56903. void DocumentWindow::lookAndFeelChanged()
  56904. {
  56905. int i;
  56906. for (i = 0; i < 3; ++i)
  56907. deleteAndZero (titleBarButtons[i]);
  56908. if (! isUsingNativeTitleBar())
  56909. {
  56910. titleBarButtons[0] = ((requiredButtons & minimiseButton) != 0)
  56911. ? getLookAndFeel().createDocumentWindowButton (minimiseButton) : 0;
  56912. titleBarButtons[1] = ((requiredButtons & maximiseButton) != 0)
  56913. ? getLookAndFeel().createDocumentWindowButton (maximiseButton) : 0;
  56914. titleBarButtons[2] = ((requiredButtons & closeButton) != 0)
  56915. ? getLookAndFeel().createDocumentWindowButton (closeButton) : 0;
  56916. for (i = 0; i < 3; ++i)
  56917. {
  56918. if (titleBarButtons[i] != 0)
  56919. {
  56920. buttonListener.owner = this;
  56921. titleBarButtons[i]->addButtonListener (&buttonListener);
  56922. titleBarButtons[i]->setWantsKeyboardFocus (false);
  56923. // (call the Component method directly to avoid the assertion in ResizableWindow)
  56924. Component::addAndMakeVisible (titleBarButtons[i]);
  56925. }
  56926. }
  56927. if (getCloseButton() != 0)
  56928. {
  56929. #if JUCE_MAC
  56930. getCloseButton()->addShortcut (KeyPress (T('w'), ModifierKeys::commandModifier, 0));
  56931. #else
  56932. getCloseButton()->addShortcut (KeyPress (KeyPress::F4Key, ModifierKeys::altModifier, 0));
  56933. #endif
  56934. }
  56935. }
  56936. activeWindowStatusChanged();
  56937. ResizableWindow::lookAndFeelChanged();
  56938. }
  56939. void DocumentWindow::parentHierarchyChanged()
  56940. {
  56941. lookAndFeelChanged();
  56942. }
  56943. void DocumentWindow::activeWindowStatusChanged()
  56944. {
  56945. ResizableWindow::activeWindowStatusChanged();
  56946. for (int i = 0; i < 3; ++i)
  56947. if (titleBarButtons[i] != 0)
  56948. titleBarButtons[i]->setEnabled (isActiveWindow());
  56949. if (menuBar != 0)
  56950. menuBar->setEnabled (isActiveWindow());
  56951. }
  56952. const BorderSize DocumentWindow::getBorderThickness()
  56953. {
  56954. return BorderSize (getBorderSize());
  56955. }
  56956. const BorderSize DocumentWindow::getContentComponentBorder()
  56957. {
  56958. const int size = getBorderSize();
  56959. return BorderSize (size
  56960. + (isUsingNativeTitleBar() ? 0 : titleBarHeight)
  56961. + (menuBar != 0 ? menuBarHeight : 0),
  56962. size, size, size);
  56963. }
  56964. void DocumentWindow::mouseDoubleClick (const MouseEvent& e)
  56965. {
  56966. const int border = getBorderSize();
  56967. if (e.x >= border
  56968. && e.y >= border
  56969. && e.x < getWidth() - border
  56970. && e.y < border + getTitleBarHeight()
  56971. && getMaximiseButton() != 0)
  56972. {
  56973. getMaximiseButton()->triggerClick();
  56974. }
  56975. }
  56976. void DocumentWindow::userTriedToCloseWindow()
  56977. {
  56978. closeButtonPressed();
  56979. }
  56980. int DocumentWindow::getTitleBarHeight() const
  56981. {
  56982. return isUsingNativeTitleBar() ? 0 : jmin (titleBarHeight, getHeight() - 4);
  56983. }
  56984. int DocumentWindow::getBorderSize() const
  56985. {
  56986. return (isFullScreen() || isUsingNativeTitleBar()) ? 0 : (resizableBorder != 0 ? 4 : 1);
  56987. }
  56988. DocumentWindow::ButtonListenerProxy::ButtonListenerProxy()
  56989. {
  56990. }
  56991. void DocumentWindow::ButtonListenerProxy::buttonClicked (Button* button)
  56992. {
  56993. if (button == owner->getMinimiseButton())
  56994. {
  56995. owner->minimiseButtonPressed();
  56996. }
  56997. else if (button == owner->getMaximiseButton())
  56998. {
  56999. owner->maximiseButtonPressed();
  57000. }
  57001. else if (button == owner->getCloseButton())
  57002. {
  57003. owner->closeButtonPressed();
  57004. }
  57005. }
  57006. END_JUCE_NAMESPACE
  57007. /********* End of inlined file: juce_DocumentWindow.cpp *********/
  57008. /********* Start of inlined file: juce_ResizableWindow.cpp *********/
  57009. BEGIN_JUCE_NAMESPACE
  57010. ResizableWindow::ResizableWindow (const String& name,
  57011. const Colour& backgroundColour_,
  57012. const bool addToDesktop_)
  57013. : TopLevelWindow (name, addToDesktop_),
  57014. resizableCorner (0),
  57015. resizableBorder (0),
  57016. contentComponent (0),
  57017. resizeToFitContent (false),
  57018. fullscreen (false),
  57019. constrainer (0)
  57020. #ifdef JUCE_DEBUG
  57021. , hasBeenResized (false)
  57022. #endif
  57023. {
  57024. setBackgroundColour (backgroundColour_);
  57025. defaultConstrainer.setMinimumOnscreenAmounts (0x10000, 16, 24, 16);
  57026. lastNonFullScreenPos.setBounds (50, 50, 256, 256);
  57027. if (addToDesktop_)
  57028. Component::addToDesktop (getDesktopWindowStyleFlags());
  57029. }
  57030. ResizableWindow::~ResizableWindow()
  57031. {
  57032. deleteAndZero (resizableCorner);
  57033. deleteAndZero (resizableBorder);
  57034. deleteAndZero (contentComponent);
  57035. // have you been adding your own components directly to this window..? tut tut tut.
  57036. // Read the instructions for using a ResizableWindow!
  57037. jassert (getNumChildComponents() == 0);
  57038. }
  57039. int ResizableWindow::getDesktopWindowStyleFlags() const
  57040. {
  57041. int flags = TopLevelWindow::getDesktopWindowStyleFlags();
  57042. if (isResizable() && (flags & ComponentPeer::windowHasTitleBar) != 0)
  57043. flags |= ComponentPeer::windowIsResizable;
  57044. return flags;
  57045. }
  57046. void ResizableWindow::setContentComponent (Component* const newContentComponent,
  57047. const bool deleteOldOne,
  57048. const bool resizeToFit)
  57049. {
  57050. resizeToFitContent = resizeToFit;
  57051. if (contentComponent != newContentComponent)
  57052. {
  57053. if (deleteOldOne)
  57054. delete contentComponent;
  57055. else
  57056. removeChildComponent (contentComponent);
  57057. contentComponent = newContentComponent;
  57058. Component::addAndMakeVisible (contentComponent);
  57059. }
  57060. if (resizeToFit)
  57061. childBoundsChanged (contentComponent);
  57062. resized(); // must always be called to position the new content comp
  57063. }
  57064. void ResizableWindow::setContentComponentSize (int width, int height)
  57065. {
  57066. jassert (width > 0 && height > 0); // not a great idea to give it a zero size..
  57067. const BorderSize border (getContentComponentBorder());
  57068. setSize (width + border.getLeftAndRight(),
  57069. height + border.getTopAndBottom());
  57070. }
  57071. const BorderSize ResizableWindow::getBorderThickness()
  57072. {
  57073. return BorderSize (isUsingNativeTitleBar() ? 0 : ((resizableBorder != 0 && ! isFullScreen()) ? 5 : 3));
  57074. }
  57075. const BorderSize ResizableWindow::getContentComponentBorder()
  57076. {
  57077. return getBorderThickness();
  57078. }
  57079. void ResizableWindow::moved()
  57080. {
  57081. updateLastPos();
  57082. }
  57083. void ResizableWindow::visibilityChanged()
  57084. {
  57085. TopLevelWindow::visibilityChanged();
  57086. updateLastPos();
  57087. }
  57088. void ResizableWindow::resized()
  57089. {
  57090. if (resizableBorder != 0)
  57091. {
  57092. resizableBorder->setVisible (! isFullScreen());
  57093. resizableBorder->setBorderThickness (getBorderThickness());
  57094. resizableBorder->setSize (getWidth(), getHeight());
  57095. resizableBorder->toBack();
  57096. }
  57097. if (resizableCorner != 0)
  57098. {
  57099. resizableCorner->setVisible (! isFullScreen());
  57100. const int resizerSize = 18;
  57101. resizableCorner->setBounds (getWidth() - resizerSize,
  57102. getHeight() - resizerSize,
  57103. resizerSize, resizerSize);
  57104. }
  57105. if (contentComponent != 0)
  57106. contentComponent->setBoundsInset (getContentComponentBorder());
  57107. updateLastPos();
  57108. #ifdef JUCE_DEBUG
  57109. hasBeenResized = true;
  57110. #endif
  57111. }
  57112. void ResizableWindow::childBoundsChanged (Component* child)
  57113. {
  57114. if ((child == contentComponent) && (child != 0) && resizeToFitContent)
  57115. {
  57116. // not going to look very good if this component has a zero size..
  57117. jassert (child->getWidth() > 0);
  57118. jassert (child->getHeight() > 0);
  57119. const BorderSize borders (getContentComponentBorder());
  57120. setSize (child->getWidth() + borders.getLeftAndRight(),
  57121. child->getHeight() + borders.getTopAndBottom());
  57122. }
  57123. }
  57124. void ResizableWindow::activeWindowStatusChanged()
  57125. {
  57126. const BorderSize borders (getContentComponentBorder());
  57127. repaint (0, 0, getWidth(), borders.getTop());
  57128. repaint (0, borders.getTop(), borders.getLeft(), getHeight() - borders.getBottom() - borders.getTop());
  57129. repaint (0, getHeight() - borders.getBottom(), getWidth(), borders.getBottom());
  57130. repaint (getWidth() - borders.getRight(), borders.getTop(), borders.getRight(), getHeight() - borders.getBottom() - borders.getTop());
  57131. }
  57132. void ResizableWindow::setResizable (const bool shouldBeResizable,
  57133. const bool useBottomRightCornerResizer)
  57134. {
  57135. if (shouldBeResizable)
  57136. {
  57137. if (useBottomRightCornerResizer)
  57138. {
  57139. deleteAndZero (resizableBorder);
  57140. if (resizableCorner == 0)
  57141. {
  57142. Component::addChildComponent (resizableCorner = new ResizableCornerComponent (this, constrainer));
  57143. resizableCorner->setAlwaysOnTop (true);
  57144. }
  57145. }
  57146. else
  57147. {
  57148. deleteAndZero (resizableCorner);
  57149. if (resizableBorder == 0)
  57150. Component::addChildComponent (resizableBorder = new ResizableBorderComponent (this, constrainer));
  57151. }
  57152. }
  57153. else
  57154. {
  57155. deleteAndZero (resizableCorner);
  57156. deleteAndZero (resizableBorder);
  57157. }
  57158. if (isUsingNativeTitleBar())
  57159. recreateDesktopWindow();
  57160. childBoundsChanged (contentComponent);
  57161. resized();
  57162. }
  57163. bool ResizableWindow::isResizable() const throw()
  57164. {
  57165. return resizableCorner != 0
  57166. || resizableBorder != 0;
  57167. }
  57168. void ResizableWindow::setResizeLimits (const int newMinimumWidth,
  57169. const int newMinimumHeight,
  57170. const int newMaximumWidth,
  57171. const int newMaximumHeight) throw()
  57172. {
  57173. // if you've set up a custom constrainer then these settings won't have any effect..
  57174. jassert (constrainer == &defaultConstrainer || constrainer == 0);
  57175. if (constrainer == 0)
  57176. setConstrainer (&defaultConstrainer);
  57177. defaultConstrainer.setSizeLimits (newMinimumWidth, newMinimumHeight,
  57178. newMaximumWidth, newMaximumHeight);
  57179. setBoundsConstrained (getX(), getY(), getWidth(), getHeight());
  57180. }
  57181. void ResizableWindow::setConstrainer (ComponentBoundsConstrainer* newConstrainer)
  57182. {
  57183. if (constrainer != newConstrainer)
  57184. {
  57185. constrainer = newConstrainer;
  57186. const bool useBottomRightCornerResizer = resizableCorner != 0;
  57187. const bool shouldBeResizable = useBottomRightCornerResizer || resizableBorder != 0;
  57188. deleteAndZero (resizableCorner);
  57189. deleteAndZero (resizableBorder);
  57190. setResizable (shouldBeResizable, useBottomRightCornerResizer);
  57191. ComponentPeer* const peer = getPeer();
  57192. if (peer != 0)
  57193. peer->setConstrainer (newConstrainer);
  57194. }
  57195. }
  57196. void ResizableWindow::setBoundsConstrained (int x, int y, int w, int h)
  57197. {
  57198. if (constrainer != 0)
  57199. constrainer->setBoundsForComponent (this, x, y, w, h, false, false, false, false);
  57200. else
  57201. setBounds (x, y, w, h);
  57202. }
  57203. void ResizableWindow::paint (Graphics& g)
  57204. {
  57205. g.fillAll (backgroundColour);
  57206. if (! isFullScreen())
  57207. {
  57208. getLookAndFeel().drawResizableWindowBorder (g, getWidth(), getHeight(),
  57209. getBorderThickness(), *this);
  57210. }
  57211. #ifdef JUCE_DEBUG
  57212. /* If this fails, then you've probably written a subclass with a resized()
  57213. callback but forgotten to make it call its parent class's resized() method.
  57214. It's important when you override methods like resized(), moved(),
  57215. etc., that you make sure the base class methods also get called.
  57216. Of course you shouldn't really be overriding ResizableWindow::resized() anyway,
  57217. because your content should all be inside the content component - and it's the
  57218. content component's resized() method that you should be using to do your
  57219. layout.
  57220. */
  57221. jassert (hasBeenResized || (getWidth() == 0 && getHeight() == 0));
  57222. #endif
  57223. }
  57224. void ResizableWindow::lookAndFeelChanged()
  57225. {
  57226. resized();
  57227. if (isOnDesktop())
  57228. {
  57229. Component::addToDesktop (getDesktopWindowStyleFlags());
  57230. ComponentPeer* const peer = getPeer();
  57231. if (peer != 0)
  57232. peer->setConstrainer (constrainer);
  57233. }
  57234. }
  57235. void ResizableWindow::setBackgroundColour (const Colour& newColour)
  57236. {
  57237. if (Desktop::canUseSemiTransparentWindows())
  57238. backgroundColour = newColour;
  57239. else
  57240. backgroundColour = newColour.withAlpha (1.0f);
  57241. setOpaque (backgroundColour.isOpaque());
  57242. repaint();
  57243. }
  57244. bool ResizableWindow::isFullScreen() const
  57245. {
  57246. if (isOnDesktop())
  57247. {
  57248. ComponentPeer* const peer = getPeer();
  57249. return peer != 0 && peer->isFullScreen();
  57250. }
  57251. return fullscreen;
  57252. }
  57253. void ResizableWindow::setFullScreen (const bool shouldBeFullScreen)
  57254. {
  57255. if (shouldBeFullScreen != isFullScreen())
  57256. {
  57257. updateLastPos();
  57258. fullscreen = shouldBeFullScreen;
  57259. if (isOnDesktop())
  57260. {
  57261. ComponentPeer* const peer = getPeer();
  57262. if (peer != 0)
  57263. {
  57264. // keep a copy of this intact in case the real one gets messed-up while we're un-maximising
  57265. const Rectangle lastPos (lastNonFullScreenPos);
  57266. peer->setFullScreen (shouldBeFullScreen);
  57267. if (! shouldBeFullScreen)
  57268. setBounds (lastPos);
  57269. }
  57270. else
  57271. {
  57272. jassertfalse
  57273. }
  57274. }
  57275. else
  57276. {
  57277. if (shouldBeFullScreen)
  57278. setBounds (0, 0, getParentWidth(), getParentHeight());
  57279. else
  57280. setBounds (lastNonFullScreenPos);
  57281. }
  57282. resized();
  57283. }
  57284. }
  57285. bool ResizableWindow::isMinimised() const
  57286. {
  57287. ComponentPeer* const peer = getPeer();
  57288. return (peer != 0) && peer->isMinimised();
  57289. }
  57290. void ResizableWindow::setMinimised (const bool shouldMinimise)
  57291. {
  57292. if (shouldMinimise != isMinimised())
  57293. {
  57294. ComponentPeer* const peer = getPeer();
  57295. if (peer != 0)
  57296. {
  57297. updateLastPos();
  57298. peer->setMinimised (shouldMinimise);
  57299. }
  57300. else
  57301. {
  57302. jassertfalse
  57303. }
  57304. }
  57305. }
  57306. void ResizableWindow::updateLastPos()
  57307. {
  57308. if (isShowing() && ! (isFullScreen() || isMinimised()))
  57309. {
  57310. lastNonFullScreenPos = getBounds();
  57311. }
  57312. }
  57313. void ResizableWindow::parentSizeChanged()
  57314. {
  57315. if (isFullScreen() && getParentComponent() != 0)
  57316. {
  57317. setBounds (0, 0, getParentWidth(), getParentHeight());
  57318. }
  57319. }
  57320. const String ResizableWindow::getWindowStateAsString()
  57321. {
  57322. updateLastPos();
  57323. String s;
  57324. if (isFullScreen())
  57325. s << "fs ";
  57326. s << lastNonFullScreenPos.getX() << T(' ')
  57327. << lastNonFullScreenPos.getY() << T(' ')
  57328. << lastNonFullScreenPos.getWidth() << T(' ')
  57329. << lastNonFullScreenPos.getHeight();
  57330. return s;
  57331. }
  57332. bool ResizableWindow::restoreWindowStateFromString (const String& s)
  57333. {
  57334. StringArray tokens;
  57335. tokens.addTokens (s, false);
  57336. tokens.removeEmptyStrings();
  57337. tokens.trim();
  57338. const bool fs = tokens[0].startsWithIgnoreCase (T("fs"));
  57339. const int n = fs ? 1 : 0;
  57340. if (tokens.size() != 4 + n)
  57341. return false;
  57342. Rectangle r (tokens[n].getIntValue(),
  57343. tokens[n + 1].getIntValue(),
  57344. tokens[n + 2].getIntValue(),
  57345. tokens[n + 3].getIntValue());
  57346. if (r.isEmpty())
  57347. return false;
  57348. const Rectangle screen (Desktop::getInstance().getMonitorAreaContaining (r.getX(), r.getY()));
  57349. r = r.getIntersection (screen);
  57350. lastNonFullScreenPos = r;
  57351. if (isOnDesktop())
  57352. {
  57353. ComponentPeer* const peer = getPeer();
  57354. if (peer != 0)
  57355. peer->setNonFullScreenBounds (r);
  57356. }
  57357. setFullScreen (fs);
  57358. if (! fs)
  57359. setBoundsConstrained (r.getX(),
  57360. r.getY(),
  57361. r.getWidth(),
  57362. r.getHeight());
  57363. return true;
  57364. }
  57365. void ResizableWindow::mouseDown (const MouseEvent&)
  57366. {
  57367. if (! isFullScreen())
  57368. dragger.startDraggingComponent (this, constrainer);
  57369. }
  57370. void ResizableWindow::mouseDrag (const MouseEvent& e)
  57371. {
  57372. if (! isFullScreen())
  57373. dragger.dragComponent (this, e);
  57374. }
  57375. #ifdef JUCE_DEBUG
  57376. void ResizableWindow::addChildComponent (Component* const child, int zOrder)
  57377. {
  57378. /* Agh! You shouldn't add components directly to a ResizableWindow - this class
  57379. manages its child components automatically, and if you add your own it'll cause
  57380. trouble. Instead, use setContentComponent() to give it a component which
  57381. will be automatically resized and kept in the right place - then you can add
  57382. subcomponents to the content comp. See the notes for the ResizableWindow class
  57383. for more info.
  57384. If you really know what you're doing and want to avoid this assertion, just call
  57385. Component::addChildComponent directly.
  57386. */
  57387. jassertfalse
  57388. Component::addChildComponent (child, zOrder);
  57389. }
  57390. void ResizableWindow::addAndMakeVisible (Component* const child, int zOrder)
  57391. {
  57392. /* Agh! You shouldn't add components directly to a ResizableWindow - this class
  57393. manages its child components automatically, and if you add your own it'll cause
  57394. trouble. Instead, use setContentComponent() to give it a component which
  57395. will be automatically resized and kept in the right place - then you can add
  57396. subcomponents to the content comp. See the notes for the ResizableWindow class
  57397. for more info.
  57398. If you really know what you're doing and want to avoid this assertion, just call
  57399. Component::addAndMakeVisible directly.
  57400. */
  57401. jassertfalse
  57402. Component::addAndMakeVisible (child, zOrder);
  57403. }
  57404. #endif
  57405. END_JUCE_NAMESPACE
  57406. /********* End of inlined file: juce_ResizableWindow.cpp *********/
  57407. /********* Start of inlined file: juce_SplashScreen.cpp *********/
  57408. BEGIN_JUCE_NAMESPACE
  57409. SplashScreen::SplashScreen()
  57410. : backgroundImage (0),
  57411. isImageInCache (false)
  57412. {
  57413. setOpaque (true);
  57414. }
  57415. SplashScreen::~SplashScreen()
  57416. {
  57417. if (isImageInCache)
  57418. ImageCache::release (backgroundImage);
  57419. else
  57420. delete backgroundImage;
  57421. }
  57422. void SplashScreen::show (const String& title,
  57423. Image* const backgroundImage_,
  57424. const int minimumTimeToDisplayFor,
  57425. const bool useDropShadow,
  57426. const bool removeOnMouseClick)
  57427. {
  57428. backgroundImage = backgroundImage_;
  57429. jassert (backgroundImage_ != 0);
  57430. if (backgroundImage_ != 0)
  57431. {
  57432. isImageInCache = ImageCache::isImageInCache (backgroundImage_);
  57433. setOpaque (! backgroundImage_->hasAlphaChannel());
  57434. show (title,
  57435. backgroundImage_->getWidth(),
  57436. backgroundImage_->getHeight(),
  57437. minimumTimeToDisplayFor,
  57438. useDropShadow,
  57439. removeOnMouseClick);
  57440. }
  57441. }
  57442. void SplashScreen::show (const String& title,
  57443. const int width,
  57444. const int height,
  57445. const int minimumTimeToDisplayFor,
  57446. const bool useDropShadow,
  57447. const bool removeOnMouseClick)
  57448. {
  57449. setName (title);
  57450. setAlwaysOnTop (true);
  57451. setVisible (true);
  57452. centreWithSize (width, height);
  57453. addToDesktop (useDropShadow ? ComponentPeer::windowHasDropShadow : 0);
  57454. toFront (false);
  57455. MessageManager::getInstance()->dispatchPendingMessages();
  57456. repaint();
  57457. originalClickCounter = removeOnMouseClick
  57458. ? Desktop::getMouseButtonClickCounter()
  57459. : INT_MAX;
  57460. earliestTimeToDelete = Time::getCurrentTime() + RelativeTime::milliseconds (minimumTimeToDisplayFor);
  57461. startTimer (50);
  57462. }
  57463. void SplashScreen::paint (Graphics& g)
  57464. {
  57465. if (backgroundImage != 0)
  57466. {
  57467. g.setOpacity (1.0f);
  57468. g.drawImage (backgroundImage,
  57469. 0, 0, getWidth(), getHeight(),
  57470. 0, 0, backgroundImage->getWidth(), backgroundImage->getHeight());
  57471. }
  57472. }
  57473. void SplashScreen::timerCallback()
  57474. {
  57475. if (Time::getCurrentTime() > earliestTimeToDelete
  57476. || Desktop::getMouseButtonClickCounter() > originalClickCounter)
  57477. {
  57478. delete this;
  57479. }
  57480. }
  57481. END_JUCE_NAMESPACE
  57482. /********* End of inlined file: juce_SplashScreen.cpp *********/
  57483. /********* Start of inlined file: juce_ThreadWithProgressWindow.cpp *********/
  57484. BEGIN_JUCE_NAMESPACE
  57485. ThreadWithProgressWindow::ThreadWithProgressWindow (const String& title,
  57486. const bool hasProgressBar,
  57487. const bool hasCancelButton,
  57488. const int timeOutMsWhenCancelling_,
  57489. const String& cancelButtonText)
  57490. : Thread ("Juce Progress Window"),
  57491. progress (0.0),
  57492. alertWindow (title, String::empty, AlertWindow::NoIcon),
  57493. timeOutMsWhenCancelling (timeOutMsWhenCancelling_)
  57494. {
  57495. if (hasProgressBar)
  57496. alertWindow.addProgressBarComponent (progress);
  57497. if (hasCancelButton)
  57498. alertWindow.addButton (cancelButtonText, 1);
  57499. }
  57500. ThreadWithProgressWindow::~ThreadWithProgressWindow()
  57501. {
  57502. stopThread (timeOutMsWhenCancelling);
  57503. }
  57504. bool ThreadWithProgressWindow::runThread (const int priority)
  57505. {
  57506. startThread (priority);
  57507. startTimer (100);
  57508. {
  57509. const ScopedLock sl (messageLock);
  57510. alertWindow.setMessage (message);
  57511. }
  57512. const bool wasCancelled = alertWindow.runModalLoop() != 0;
  57513. stopThread (timeOutMsWhenCancelling);
  57514. alertWindow.setVisible (false);
  57515. return ! wasCancelled;
  57516. }
  57517. void ThreadWithProgressWindow::setProgress (const double newProgress)
  57518. {
  57519. progress = newProgress;
  57520. }
  57521. void ThreadWithProgressWindow::setStatusMessage (const String& newStatusMessage)
  57522. {
  57523. const ScopedLock sl (messageLock);
  57524. message = newStatusMessage;
  57525. }
  57526. void ThreadWithProgressWindow::timerCallback()
  57527. {
  57528. if (! isThreadRunning())
  57529. {
  57530. // thread has finished normally..
  57531. alertWindow.exitModalState (0);
  57532. alertWindow.setVisible (false);
  57533. }
  57534. else
  57535. {
  57536. const ScopedLock sl (messageLock);
  57537. alertWindow.setMessage (message);
  57538. }
  57539. }
  57540. END_JUCE_NAMESPACE
  57541. /********* End of inlined file: juce_ThreadWithProgressWindow.cpp *********/
  57542. /********* Start of inlined file: juce_TooltipWindow.cpp *********/
  57543. BEGIN_JUCE_NAMESPACE
  57544. TooltipWindow::TooltipWindow (Component* const parentComponent,
  57545. const int millisecondsBeforeTipAppears_)
  57546. : Component ("tooltip"),
  57547. millisecondsBeforeTipAppears (millisecondsBeforeTipAppears_),
  57548. mouseX (0),
  57549. mouseY (0),
  57550. lastMouseMoveTime (0),
  57551. lastHideTime (0),
  57552. lastComponentUnderMouse (0),
  57553. changedCompsSinceShown (true)
  57554. {
  57555. startTimer (123);
  57556. setAlwaysOnTop (true);
  57557. setOpaque (true);
  57558. if (parentComponent != 0)
  57559. {
  57560. parentComponent->addChildComponent (this);
  57561. }
  57562. else
  57563. {
  57564. setSize (1, 1); // to keep the OS happy by not having zero-size windows
  57565. addToDesktop (ComponentPeer::windowHasDropShadow
  57566. | ComponentPeer::windowIsTemporary);
  57567. }
  57568. }
  57569. TooltipWindow::~TooltipWindow()
  57570. {
  57571. }
  57572. void TooltipWindow::paint (Graphics& g)
  57573. {
  57574. getLookAndFeel().drawTooltip (g, tip, getWidth(), getHeight());
  57575. }
  57576. void TooltipWindow::mouseEnter (const MouseEvent&)
  57577. {
  57578. setVisible (false);
  57579. }
  57580. void TooltipWindow::showFor (Component* const c)
  57581. {
  57582. TooltipClient* const ttc = dynamic_cast <TooltipClient*> (c);
  57583. if (ttc != 0 && ! c->isCurrentlyBlockedByAnotherModalComponent())
  57584. tip = ttc->getTooltip();
  57585. else
  57586. tip = String::empty;
  57587. if (tip.isEmpty())
  57588. {
  57589. setVisible (false);
  57590. }
  57591. else
  57592. {
  57593. int mx, my;
  57594. Desktop::getMousePosition (mx, my);
  57595. if (getParentComponent() != 0)
  57596. getParentComponent()->globalPositionToRelative (mx, my);
  57597. int x, y, w, h;
  57598. getLookAndFeel().getTooltipSize (tip, w, h);
  57599. if (mx > getParentWidth() / 2)
  57600. x = mx - (w + 12);
  57601. else
  57602. x = mx + 24;
  57603. if (my > getParentHeight() / 2)
  57604. y = my - (h + 6);
  57605. else
  57606. y = my + 6;
  57607. setBounds (x, y, w, h);
  57608. setVisible (true);
  57609. toFront (false);
  57610. }
  57611. }
  57612. void TooltipWindow::timerCallback()
  57613. {
  57614. int mx, my;
  57615. Desktop::getMousePosition (mx, my);
  57616. const unsigned int now = Time::getApproximateMillisecondCounter();
  57617. Component* const underMouse = Component::getComponentUnderMouse();
  57618. const bool changedComp = (underMouse != lastComponentUnderMouse);
  57619. lastComponentUnderMouse = underMouse;
  57620. if (changedComp
  57621. || abs (mx - mouseX) > 4
  57622. || abs (my - mouseY) > 4
  57623. || Desktop::getInstance().getMouseButtonClickCounter() > mouseClicks)
  57624. {
  57625. lastMouseMoveTime = now;
  57626. if (isVisible())
  57627. {
  57628. lastHideTime = now;
  57629. setVisible (false);
  57630. }
  57631. changedCompsSinceShown = changedCompsSinceShown || changedComp;
  57632. tip = String::empty;
  57633. mouseX = mx;
  57634. mouseY = my;
  57635. }
  57636. if (changedCompsSinceShown)
  57637. {
  57638. if ((now > lastMouseMoveTime + millisecondsBeforeTipAppears
  57639. || now < lastHideTime + 500)
  57640. && ! isVisible())
  57641. {
  57642. if (underMouse->isValidComponent())
  57643. showFor (underMouse);
  57644. changedCompsSinceShown = false;
  57645. }
  57646. }
  57647. mouseClicks = Desktop::getInstance().getMouseButtonClickCounter();
  57648. }
  57649. END_JUCE_NAMESPACE
  57650. /********* End of inlined file: juce_TooltipWindow.cpp *********/
  57651. /********* Start of inlined file: juce_TopLevelWindow.cpp *********/
  57652. BEGIN_JUCE_NAMESPACE
  57653. /** Keeps track of the active top level window.
  57654. */
  57655. class TopLevelWindowManager : public Timer,
  57656. public DeletedAtShutdown
  57657. {
  57658. public:
  57659. TopLevelWindowManager()
  57660. : windows (8),
  57661. currentActive (0)
  57662. {
  57663. }
  57664. ~TopLevelWindowManager()
  57665. {
  57666. clearSingletonInstance();
  57667. }
  57668. juce_DeclareSingleton_SingleThreaded_Minimal (TopLevelWindowManager)
  57669. void timerCallback()
  57670. {
  57671. startTimer (1731);
  57672. TopLevelWindow* active = 0;
  57673. if (Process::isForegroundProcess())
  57674. {
  57675. active = currentActive;
  57676. Component* const c = Component::getCurrentlyFocusedComponent();
  57677. TopLevelWindow* tlw = dynamic_cast <TopLevelWindow*> (c);
  57678. if (tlw == 0 && c != 0)
  57679. // (unable to use the syntax findParentComponentOfClass <TopLevelWindow> () because of a VC6 compiler bug)
  57680. tlw = c->findParentComponentOfClass ((TopLevelWindow*) 0);
  57681. if (tlw != 0)
  57682. active = tlw;
  57683. }
  57684. if (active != currentActive)
  57685. {
  57686. currentActive = active;
  57687. for (int i = windows.size(); --i >= 0;)
  57688. {
  57689. TopLevelWindow* const tlw = (TopLevelWindow*) windows.getUnchecked (i);
  57690. tlw->setWindowActive (isWindowActive (tlw));
  57691. i = jmin (i, windows.size() - 1);
  57692. }
  57693. Desktop::getInstance().triggerFocusCallback();
  57694. }
  57695. }
  57696. bool addWindow (TopLevelWindow* const w) throw()
  57697. {
  57698. windows.add (w);
  57699. startTimer (10);
  57700. return isWindowActive (w);
  57701. }
  57702. void removeWindow (TopLevelWindow* const w) throw()
  57703. {
  57704. startTimer (10);
  57705. if (currentActive == w)
  57706. currentActive = 0;
  57707. windows.removeValue (w);
  57708. if (windows.size() == 0)
  57709. deleteInstance();
  57710. }
  57711. VoidArray windows;
  57712. private:
  57713. TopLevelWindow* currentActive;
  57714. bool isWindowActive (TopLevelWindow* const tlw) const throw()
  57715. {
  57716. return (tlw == currentActive
  57717. || tlw->isParentOf (currentActive)
  57718. || tlw->hasKeyboardFocus (true))
  57719. && tlw->isShowing();
  57720. }
  57721. TopLevelWindowManager (const TopLevelWindowManager&);
  57722. const TopLevelWindowManager& operator= (const TopLevelWindowManager&);
  57723. };
  57724. juce_ImplementSingleton_SingleThreaded (TopLevelWindowManager)
  57725. void juce_CheckCurrentlyFocusedTopLevelWindow() throw()
  57726. {
  57727. if (TopLevelWindowManager::getInstanceWithoutCreating() != 0)
  57728. TopLevelWindowManager::getInstanceWithoutCreating()->startTimer (20);
  57729. }
  57730. TopLevelWindow::TopLevelWindow (const String& name,
  57731. const bool addToDesktop_)
  57732. : Component (name),
  57733. useDropShadow (true),
  57734. useNativeTitleBar (false),
  57735. windowIsActive_ (false),
  57736. shadower (0)
  57737. {
  57738. setOpaque (true);
  57739. if (addToDesktop_)
  57740. Component::addToDesktop (getDesktopWindowStyleFlags());
  57741. else
  57742. setDropShadowEnabled (true);
  57743. setWantsKeyboardFocus (true);
  57744. setBroughtToFrontOnMouseClick (true);
  57745. windowIsActive_ = TopLevelWindowManager::getInstance()->addWindow (this);
  57746. }
  57747. TopLevelWindow::~TopLevelWindow()
  57748. {
  57749. deleteAndZero (shadower);
  57750. TopLevelWindowManager::getInstance()->removeWindow (this);
  57751. }
  57752. void TopLevelWindow::focusOfChildComponentChanged (FocusChangeType)
  57753. {
  57754. if (hasKeyboardFocus (true))
  57755. TopLevelWindowManager::getInstance()->timerCallback();
  57756. else
  57757. TopLevelWindowManager::getInstance()->startTimer (10);
  57758. }
  57759. void TopLevelWindow::setWindowActive (const bool isNowActive) throw()
  57760. {
  57761. if (windowIsActive_ != isNowActive)
  57762. {
  57763. windowIsActive_ = isNowActive;
  57764. activeWindowStatusChanged();
  57765. }
  57766. }
  57767. void TopLevelWindow::activeWindowStatusChanged()
  57768. {
  57769. }
  57770. void TopLevelWindow::parentHierarchyChanged()
  57771. {
  57772. setDropShadowEnabled (useDropShadow);
  57773. }
  57774. void TopLevelWindow::visibilityChanged()
  57775. {
  57776. if (isShowing())
  57777. toFront (true);
  57778. }
  57779. int TopLevelWindow::getDesktopWindowStyleFlags() const
  57780. {
  57781. int flags = ComponentPeer::windowAppearsOnTaskbar;
  57782. if (useDropShadow)
  57783. flags |= ComponentPeer::windowHasDropShadow;
  57784. if (useNativeTitleBar)
  57785. flags |= ComponentPeer::windowHasTitleBar;
  57786. return flags;
  57787. }
  57788. void TopLevelWindow::setDropShadowEnabled (const bool useShadow)
  57789. {
  57790. useDropShadow = useShadow;
  57791. if (isOnDesktop())
  57792. {
  57793. deleteAndZero (shadower);
  57794. Component::addToDesktop (getDesktopWindowStyleFlags());
  57795. }
  57796. else
  57797. {
  57798. if (useShadow && isOpaque())
  57799. {
  57800. if (shadower == 0)
  57801. {
  57802. shadower = getLookAndFeel().createDropShadowerForComponent (this);
  57803. if (shadower != 0)
  57804. shadower->setOwner (this);
  57805. }
  57806. }
  57807. else
  57808. {
  57809. deleteAndZero (shadower);
  57810. }
  57811. }
  57812. }
  57813. void TopLevelWindow::setUsingNativeTitleBar (const bool useNativeTitleBar_)
  57814. {
  57815. if (useNativeTitleBar != useNativeTitleBar_)
  57816. {
  57817. useNativeTitleBar = useNativeTitleBar_;
  57818. recreateDesktopWindow();
  57819. sendLookAndFeelChange();
  57820. }
  57821. }
  57822. void TopLevelWindow::recreateDesktopWindow()
  57823. {
  57824. if (isOnDesktop())
  57825. {
  57826. Component::addToDesktop (getDesktopWindowStyleFlags());
  57827. toFront (true);
  57828. }
  57829. }
  57830. void TopLevelWindow::addToDesktop (int windowStyleFlags, void* nativeWindowToAttachTo)
  57831. {
  57832. /* It's not recommended to change the desktop window flags directly for a TopLevelWindow,
  57833. because this class needs to make sure its layout corresponds with settings like whether
  57834. it's got a native title bar or not.
  57835. If you need custom flags for your window, you can override the getDesktopWindowStyleFlags()
  57836. method. If you do this, it's best to call the base class's getDesktopWindowStyleFlags()
  57837. method, then add or remove whatever flags are necessary from this value before returning it.
  57838. */
  57839. jassert ((windowStyleFlags & ~ComponentPeer::windowIsSemiTransparent)
  57840. == (getDesktopWindowStyleFlags() & ~ComponentPeer::windowIsSemiTransparent));
  57841. Component::addToDesktop (windowStyleFlags, nativeWindowToAttachTo);
  57842. if (windowStyleFlags != getDesktopWindowStyleFlags())
  57843. sendLookAndFeelChange();
  57844. }
  57845. void TopLevelWindow::centreAroundComponent (Component* c, const int width, const int height)
  57846. {
  57847. if (c == 0)
  57848. c = TopLevelWindow::getActiveTopLevelWindow();
  57849. if (c == 0)
  57850. {
  57851. centreWithSize (width, height);
  57852. }
  57853. else
  57854. {
  57855. int x = (c->getWidth() - width) / 2;
  57856. int y = (c->getHeight() - height) / 2;
  57857. c->relativePositionToGlobal (x, y);
  57858. Rectangle parentArea (c->getParentMonitorArea());
  57859. if (getParentComponent() != 0)
  57860. {
  57861. getParentComponent()->globalPositionToRelative (x, y);
  57862. parentArea.setBounds (0, 0, getParentWidth(), getParentHeight());
  57863. }
  57864. parentArea.reduce (12, 12);
  57865. setBounds (jlimit (parentArea.getX(), jmax (parentArea.getX(), parentArea.getRight() - width), x),
  57866. jlimit (parentArea.getY(), jmax (parentArea.getY(), parentArea.getBottom() - height), y),
  57867. width, height);
  57868. }
  57869. }
  57870. int TopLevelWindow::getNumTopLevelWindows() throw()
  57871. {
  57872. return TopLevelWindowManager::getInstance()->windows.size();
  57873. }
  57874. TopLevelWindow* TopLevelWindow::getTopLevelWindow (const int index) throw()
  57875. {
  57876. return (TopLevelWindow*) TopLevelWindowManager::getInstance()->windows [index];
  57877. }
  57878. TopLevelWindow* TopLevelWindow::getActiveTopLevelWindow() throw()
  57879. {
  57880. TopLevelWindow* best = 0;
  57881. int bestNumTWLParents = -1;
  57882. for (int i = TopLevelWindow::getNumTopLevelWindows(); --i >= 0;)
  57883. {
  57884. TopLevelWindow* const tlw = TopLevelWindow::getTopLevelWindow (i);
  57885. if (tlw->isActiveWindow())
  57886. {
  57887. int numTWLParents = 0;
  57888. const Component* c = tlw->getParentComponent();
  57889. while (c != 0)
  57890. {
  57891. if (dynamic_cast <const TopLevelWindow*> (c) != 0)
  57892. ++numTWLParents;
  57893. c = c->getParentComponent();
  57894. }
  57895. if (bestNumTWLParents < numTWLParents)
  57896. {
  57897. best = tlw;
  57898. bestNumTWLParents = numTWLParents;
  57899. }
  57900. }
  57901. }
  57902. return best;
  57903. }
  57904. END_JUCE_NAMESPACE
  57905. /********* End of inlined file: juce_TopLevelWindow.cpp *********/
  57906. /********* Start of inlined file: juce_Brush.cpp *********/
  57907. BEGIN_JUCE_NAMESPACE
  57908. Brush::Brush() throw()
  57909. {
  57910. }
  57911. Brush::~Brush() throw()
  57912. {
  57913. }
  57914. void Brush::paintVerticalLine (LowLevelGraphicsContext& context,
  57915. int x, float y1, float y2) throw()
  57916. {
  57917. Path p;
  57918. p.addRectangle ((float) x, y1, 1.0f, y2 - y1);
  57919. paintPath (context, p, AffineTransform::identity);
  57920. }
  57921. void Brush::paintHorizontalLine (LowLevelGraphicsContext& context,
  57922. int y, float x1, float x2) throw()
  57923. {
  57924. Path p;
  57925. p.addRectangle (x1, (float) y, x2 - x1, 1.0f);
  57926. paintPath (context, p, AffineTransform::identity);
  57927. }
  57928. void Brush::paintLine (LowLevelGraphicsContext& context,
  57929. float x1, float y1, float x2, float y2) throw()
  57930. {
  57931. Path p;
  57932. p.addLineSegment (x1, y1, x2, y2, 1.0f);
  57933. paintPath (context, p, AffineTransform::identity);
  57934. }
  57935. END_JUCE_NAMESPACE
  57936. /********* End of inlined file: juce_Brush.cpp *********/
  57937. /********* Start of inlined file: juce_GradientBrush.cpp *********/
  57938. BEGIN_JUCE_NAMESPACE
  57939. GradientBrush::GradientBrush (const Colour& colour1,
  57940. const float x1,
  57941. const float y1,
  57942. const Colour& colour2,
  57943. const float x2,
  57944. const float y2,
  57945. const bool isRadial) throw()
  57946. : gradient (colour1, x1, y1,
  57947. colour2, x2, y2,
  57948. isRadial)
  57949. {
  57950. }
  57951. GradientBrush::GradientBrush (const ColourGradient& gradient_) throw()
  57952. : gradient (gradient_)
  57953. {
  57954. }
  57955. GradientBrush::~GradientBrush() throw()
  57956. {
  57957. }
  57958. Brush* GradientBrush::createCopy() const throw()
  57959. {
  57960. return new GradientBrush (gradient);
  57961. }
  57962. void GradientBrush::applyTransform (const AffineTransform& transform) throw()
  57963. {
  57964. gradient.transform = gradient.transform.followedBy (transform);
  57965. }
  57966. void GradientBrush::multiplyOpacity (const float multiple) throw()
  57967. {
  57968. gradient.multiplyOpacity (multiple);
  57969. }
  57970. bool GradientBrush::isInvisible() const throw()
  57971. {
  57972. return gradient.isInvisible();
  57973. }
  57974. void GradientBrush::paintPath (LowLevelGraphicsContext& context,
  57975. const Path& path, const AffineTransform& transform) throw()
  57976. {
  57977. context.fillPathWithGradient (path, transform, gradient, EdgeTable::Oversampling_4times);
  57978. }
  57979. void GradientBrush::paintRectangle (LowLevelGraphicsContext& context,
  57980. int x, int y, int w, int h) throw()
  57981. {
  57982. context.fillRectWithGradient (x, y, w, h, gradient);
  57983. }
  57984. void GradientBrush::paintAlphaChannel (LowLevelGraphicsContext& context,
  57985. const Image& alphaChannelImage, int imageX, int imageY,
  57986. int x, int y, int w, int h) throw()
  57987. {
  57988. context.saveState();
  57989. if (context.reduceClipRegion (x, y, w, h))
  57990. context.fillAlphaChannelWithGradient (alphaChannelImage, imageX, imageY, gradient);
  57991. context.restoreState();
  57992. }
  57993. END_JUCE_NAMESPACE
  57994. /********* End of inlined file: juce_GradientBrush.cpp *********/
  57995. /********* Start of inlined file: juce_ImageBrush.cpp *********/
  57996. BEGIN_JUCE_NAMESPACE
  57997. ImageBrush::ImageBrush (Image* const image_,
  57998. const int anchorX_,
  57999. const int anchorY_,
  58000. const float opacity_) throw()
  58001. : image (image_),
  58002. anchorX (anchorX_),
  58003. anchorY (anchorY_),
  58004. opacity (opacity_)
  58005. {
  58006. jassert (image != 0); // not much point creating a brush without an image, is there?
  58007. if (image != 0)
  58008. {
  58009. if (image->getWidth() == 0 || image->getHeight() == 0)
  58010. {
  58011. jassertfalse // you've passed in an empty image - not exactly brilliant for tiling.
  58012. image = 0;
  58013. }
  58014. }
  58015. }
  58016. ImageBrush::~ImageBrush() throw()
  58017. {
  58018. }
  58019. Brush* ImageBrush::createCopy() const throw()
  58020. {
  58021. return new ImageBrush (image, anchorX, anchorY, opacity);
  58022. }
  58023. void ImageBrush::multiplyOpacity (const float multiple) throw()
  58024. {
  58025. opacity *= multiple;
  58026. }
  58027. bool ImageBrush::isInvisible() const throw()
  58028. {
  58029. return opacity == 0.0f;
  58030. }
  58031. void ImageBrush::applyTransform (const AffineTransform& /*transform*/) throw()
  58032. {
  58033. //xxx should probably be smarter and warp the image
  58034. }
  58035. void ImageBrush::getStartXY (int& x, int& y) const throw()
  58036. {
  58037. x -= anchorX;
  58038. y -= anchorY;
  58039. const int iw = image->getWidth();
  58040. const int ih = image->getHeight();
  58041. if (x < 0)
  58042. x = ((x / iw) - 1) * iw;
  58043. else
  58044. x = (x / iw) * iw;
  58045. if (y < 0)
  58046. y = ((y / ih) - 1) * ih;
  58047. else
  58048. y = (y / ih) * ih;
  58049. x += anchorX;
  58050. y += anchorY;
  58051. }
  58052. void ImageBrush::paintRectangle (LowLevelGraphicsContext& context,
  58053. int x, int y, int w, int h) throw()
  58054. {
  58055. context.saveState();
  58056. if (image != 0 && context.reduceClipRegion (x, y, w, h))
  58057. {
  58058. const int right = x + w;
  58059. const int bottom = y + h;
  58060. const int iw = image->getWidth();
  58061. const int ih = image->getHeight();
  58062. int startX = x;
  58063. getStartXY (startX, y);
  58064. while (y < bottom)
  58065. {
  58066. x = startX;
  58067. while (x < right)
  58068. {
  58069. context.blendImage (*image, x, y, iw, ih, 0, 0, opacity);
  58070. x += iw;
  58071. }
  58072. y += ih;
  58073. }
  58074. }
  58075. context.restoreState();
  58076. }
  58077. void ImageBrush::paintPath (LowLevelGraphicsContext& context,
  58078. const Path& path, const AffineTransform& transform) throw()
  58079. {
  58080. if (image != 0)
  58081. {
  58082. Rectangle clip (context.getClipBounds());
  58083. {
  58084. float x, y, w, h;
  58085. path.getBoundsTransformed (transform, x, y, w, h);
  58086. clip = clip.getIntersection (Rectangle ((int) floorf (x),
  58087. (int) floorf (y),
  58088. 2 + (int) floorf (w),
  58089. 2 + (int) floorf (h)));
  58090. }
  58091. int x = clip.getX();
  58092. int y = clip.getY();
  58093. const int right = clip.getRight();
  58094. const int bottom = clip.getBottom();
  58095. const int iw = image->getWidth();
  58096. const int ih = image->getHeight();
  58097. int startX = x;
  58098. getStartXY (startX, y);
  58099. while (y < bottom)
  58100. {
  58101. x = startX;
  58102. while (x < right)
  58103. {
  58104. context.fillPathWithImage (path, transform, *image, x, y, opacity, EdgeTable::Oversampling_4times);
  58105. x += iw;
  58106. }
  58107. y += ih;
  58108. }
  58109. }
  58110. }
  58111. void ImageBrush::paintAlphaChannel (LowLevelGraphicsContext& context,
  58112. const Image& alphaChannelImage, int imageX, int imageY,
  58113. int x, int y, int w, int h) throw()
  58114. {
  58115. context.saveState();
  58116. if (image != 0 && context.reduceClipRegion (x, y, w, h))
  58117. {
  58118. const Rectangle clip (context.getClipBounds());
  58119. x = clip.getX();
  58120. y = clip.getY();
  58121. const int right = clip.getRight();
  58122. const int bottom = clip.getBottom();
  58123. const int iw = image->getWidth();
  58124. const int ih = image->getHeight();
  58125. int startX = x;
  58126. getStartXY (startX, y);
  58127. while (y < bottom)
  58128. {
  58129. x = startX;
  58130. while (x < right)
  58131. {
  58132. context.fillAlphaChannelWithImage (alphaChannelImage,
  58133. imageX, imageY, *image,
  58134. x, y, opacity);
  58135. x += iw;
  58136. }
  58137. y += ih;
  58138. }
  58139. }
  58140. context.restoreState();
  58141. }
  58142. END_JUCE_NAMESPACE
  58143. /********* End of inlined file: juce_ImageBrush.cpp *********/
  58144. /********* Start of inlined file: juce_SolidColourBrush.cpp *********/
  58145. BEGIN_JUCE_NAMESPACE
  58146. SolidColourBrush::SolidColourBrush() throw()
  58147. : colour (0xff000000)
  58148. {
  58149. }
  58150. SolidColourBrush::SolidColourBrush (const Colour& colour_) throw()
  58151. : colour (colour_)
  58152. {
  58153. }
  58154. SolidColourBrush::~SolidColourBrush() throw()
  58155. {
  58156. }
  58157. Brush* SolidColourBrush::createCopy() const throw()
  58158. {
  58159. return new SolidColourBrush (colour);
  58160. }
  58161. void SolidColourBrush::applyTransform (const AffineTransform& /*transform*/) throw()
  58162. {
  58163. }
  58164. void SolidColourBrush::multiplyOpacity (const float multiple) throw()
  58165. {
  58166. colour = colour.withMultipliedAlpha (multiple);
  58167. }
  58168. bool SolidColourBrush::isInvisible() const throw()
  58169. {
  58170. return colour.isTransparent();
  58171. }
  58172. void SolidColourBrush::paintPath (LowLevelGraphicsContext& context,
  58173. const Path& path, const AffineTransform& transform) throw()
  58174. {
  58175. if (! colour.isTransparent())
  58176. context.fillPathWithColour (path, transform, colour, EdgeTable::Oversampling_4times);
  58177. }
  58178. void SolidColourBrush::paintRectangle (LowLevelGraphicsContext& context,
  58179. int x, int y, int w, int h) throw()
  58180. {
  58181. if (! colour.isTransparent())
  58182. context.fillRectWithColour (x, y, w, h, colour, false);
  58183. }
  58184. void SolidColourBrush::paintAlphaChannel (LowLevelGraphicsContext& context,
  58185. const Image& alphaChannelImage, int imageX, int imageY,
  58186. int x, int y, int w, int h) throw()
  58187. {
  58188. if (! colour.isTransparent())
  58189. {
  58190. context.saveState();
  58191. if (context.reduceClipRegion (x, y, w, h))
  58192. context.fillAlphaChannelWithColour (alphaChannelImage, imageX, imageY, colour);
  58193. context.restoreState();
  58194. }
  58195. }
  58196. void SolidColourBrush::paintVerticalLine (LowLevelGraphicsContext& context,
  58197. int x, float y1, float y2) throw()
  58198. {
  58199. context.drawVerticalLine (x, y1, y2, colour);
  58200. }
  58201. void SolidColourBrush::paintHorizontalLine (LowLevelGraphicsContext& context,
  58202. int y, float x1, float x2) throw()
  58203. {
  58204. context.drawHorizontalLine (y, x1, x2, colour);
  58205. }
  58206. void SolidColourBrush::paintLine (LowLevelGraphicsContext& context,
  58207. float x1, float y1, float x2, float y2) throw()
  58208. {
  58209. context.drawLine (x1, y1, x2, y2, colour);
  58210. }
  58211. END_JUCE_NAMESPACE
  58212. /********* End of inlined file: juce_SolidColourBrush.cpp *********/
  58213. /********* Start of inlined file: juce_Colour.cpp *********/
  58214. BEGIN_JUCE_NAMESPACE
  58215. static forcedinline uint8 floatAlphaToInt (const float alpha)
  58216. {
  58217. return (uint8) jlimit (0, 0xff, roundFloatToInt (alpha * 255.0f));
  58218. }
  58219. static const float oneOver255 = 1.0f / 255.0f;
  58220. Colour::Colour() throw()
  58221. : argb (0)
  58222. {
  58223. }
  58224. Colour::Colour (const Colour& other) throw()
  58225. : argb (other.argb)
  58226. {
  58227. }
  58228. const Colour& Colour::operator= (const Colour& other) throw()
  58229. {
  58230. argb = other.argb;
  58231. return *this;
  58232. }
  58233. bool Colour::operator== (const Colour& other) const throw()
  58234. {
  58235. return argb.getARGB() == other.argb.getARGB();
  58236. }
  58237. bool Colour::operator!= (const Colour& other) const throw()
  58238. {
  58239. return argb.getARGB() != other.argb.getARGB();
  58240. }
  58241. Colour::Colour (const uint32 argb_) throw()
  58242. : argb (argb_)
  58243. {
  58244. }
  58245. Colour::Colour (const uint8 red,
  58246. const uint8 green,
  58247. const uint8 blue) throw()
  58248. {
  58249. argb.setARGB (0xff, red, green, blue);
  58250. }
  58251. Colour::Colour (const uint8 red,
  58252. const uint8 green,
  58253. const uint8 blue,
  58254. const uint8 alpha) throw()
  58255. {
  58256. argb.setARGB (alpha, red, green, blue);
  58257. }
  58258. Colour::Colour (const uint8 red,
  58259. const uint8 green,
  58260. const uint8 blue,
  58261. const float alpha) throw()
  58262. {
  58263. argb.setARGB (floatAlphaToInt (alpha), red, green, blue);
  58264. }
  58265. static void convertHSBtoRGB (float h, const float s, float v,
  58266. uint8& r, uint8& g, uint8& b) throw()
  58267. {
  58268. v *= 255.0f;
  58269. const uint8 intV = (uint8) roundFloatToInt (v);
  58270. if (s == 0)
  58271. {
  58272. r = intV;
  58273. g = intV;
  58274. b = intV;
  58275. }
  58276. else
  58277. {
  58278. h = (h - floorf (h)) * 6.0f + 0.00001f; // need a small adjustment to compensate for rounding errors
  58279. const float f = h - floorf (h);
  58280. const uint8 x = (uint8) roundFloatToInt (v * (1.0f - s));
  58281. const float y = v * (1.0f - s * f);
  58282. const float z = v * (1.0f - (s * (1.0f - f)));
  58283. if (h < 1.0f)
  58284. {
  58285. r = intV;
  58286. g = (uint8) roundFloatToInt (z);
  58287. b = x;
  58288. }
  58289. else if (h < 2.0f)
  58290. {
  58291. r = (uint8) roundFloatToInt (y);
  58292. g = intV;
  58293. b = x;
  58294. }
  58295. else if (h < 3.0f)
  58296. {
  58297. r = x;
  58298. g = intV;
  58299. b = (uint8) roundFloatToInt (z);
  58300. }
  58301. else if (h < 4.0f)
  58302. {
  58303. r = x;
  58304. g = (uint8) roundFloatToInt (y);
  58305. b = intV;
  58306. }
  58307. else if (h < 5.0f)
  58308. {
  58309. r = (uint8) roundFloatToInt (z);
  58310. g = x;
  58311. b = intV;
  58312. }
  58313. else if (h < 6.0f)
  58314. {
  58315. r = intV;
  58316. g = x;
  58317. b = (uint8) roundFloatToInt (y);
  58318. }
  58319. else
  58320. {
  58321. r = 0;
  58322. g = 0;
  58323. b = 0;
  58324. }
  58325. }
  58326. }
  58327. Colour::Colour (const float hue,
  58328. const float saturation,
  58329. const float brightness,
  58330. const float alpha) throw()
  58331. {
  58332. uint8 r = getRed(), g = getGreen(), b = getBlue();
  58333. convertHSBtoRGB (hue, saturation, brightness, r, g, b);
  58334. argb.setARGB (floatAlphaToInt (alpha), r, g, b);
  58335. }
  58336. Colour::Colour (const float hue,
  58337. const float saturation,
  58338. const float brightness,
  58339. const uint8 alpha) throw()
  58340. {
  58341. uint8 r = getRed(), g = getGreen(), b = getBlue();
  58342. convertHSBtoRGB (hue, saturation, brightness, r, g, b);
  58343. argb.setARGB (alpha, r, g, b);
  58344. }
  58345. Colour::~Colour() throw()
  58346. {
  58347. }
  58348. const PixelARGB Colour::getPixelARGB() const throw()
  58349. {
  58350. PixelARGB p (argb);
  58351. p.premultiply();
  58352. return p;
  58353. }
  58354. uint32 Colour::getARGB() const throw()
  58355. {
  58356. return argb.getARGB();
  58357. }
  58358. bool Colour::isTransparent() const throw()
  58359. {
  58360. return getAlpha() == 0;
  58361. }
  58362. bool Colour::isOpaque() const throw()
  58363. {
  58364. return getAlpha() == 0xff;
  58365. }
  58366. const Colour Colour::withAlpha (const uint8 newAlpha) const throw()
  58367. {
  58368. PixelARGB newCol (argb);
  58369. newCol.setAlpha (newAlpha);
  58370. return Colour (newCol.getARGB());
  58371. }
  58372. const Colour Colour::withAlpha (const float newAlpha) const throw()
  58373. {
  58374. jassert (newAlpha >= 0 && newAlpha <= 1.0f);
  58375. PixelARGB newCol (argb);
  58376. newCol.setAlpha (floatAlphaToInt (newAlpha));
  58377. return Colour (newCol.getARGB());
  58378. }
  58379. const Colour Colour::withMultipliedAlpha (const float alphaMultiplier) const throw()
  58380. {
  58381. jassert (alphaMultiplier >= 0);
  58382. PixelARGB newCol (argb);
  58383. newCol.setAlpha ((uint8) jmin (0xff, roundFloatToInt (alphaMultiplier * newCol.getAlpha())));
  58384. return Colour (newCol.getARGB());
  58385. }
  58386. const Colour Colour::overlaidWith (const Colour& src) const throw()
  58387. {
  58388. const int destAlpha = getAlpha();
  58389. if (destAlpha > 0)
  58390. {
  58391. const int invA = 0xff - (int) src.getAlpha();
  58392. const int resA = 0xff - (((0xff - destAlpha) * invA) >> 8);
  58393. if (resA > 0)
  58394. {
  58395. const int da = (invA * destAlpha) / resA;
  58396. return Colour ((uint8) (src.getRed() + ((((int) getRed() - src.getRed()) * da) >> 8)),
  58397. (uint8) (src.getGreen() + ((((int) getGreen() - src.getGreen()) * da) >> 8)),
  58398. (uint8) (src.getBlue() + ((((int) getBlue() - src.getBlue()) * da) >> 8)),
  58399. (uint8) resA);
  58400. }
  58401. return *this;
  58402. }
  58403. else
  58404. {
  58405. return src;
  58406. }
  58407. }
  58408. float Colour::getFloatRed() const throw()
  58409. {
  58410. return getRed() * oneOver255;
  58411. }
  58412. float Colour::getFloatGreen() const throw()
  58413. {
  58414. return getGreen() * oneOver255;
  58415. }
  58416. float Colour::getFloatBlue() const throw()
  58417. {
  58418. return getBlue() * oneOver255;
  58419. }
  58420. float Colour::getFloatAlpha() const throw()
  58421. {
  58422. return getAlpha() * oneOver255;
  58423. }
  58424. void Colour::getHSB (float& h, float& s, float& v) const throw()
  58425. {
  58426. const int r = getRed();
  58427. const int g = getGreen();
  58428. const int b = getBlue();
  58429. const int hi = jmax (r, g, b);
  58430. const int lo = jmin (r, g, b);
  58431. if (hi != 0)
  58432. {
  58433. s = (hi - lo) / (float) hi;
  58434. if (s != 0)
  58435. {
  58436. const float invDiff = 1.0f / (hi - lo);
  58437. const float red = (hi - r) * invDiff;
  58438. const float green = (hi - g) * invDiff;
  58439. const float blue = (hi - b) * invDiff;
  58440. if (r == hi)
  58441. h = blue - green;
  58442. else if (g == hi)
  58443. h = 2.0f + red - blue;
  58444. else
  58445. h = 4.0f + green - red;
  58446. h *= 1.0f / 6.0f;
  58447. if (h < 0)
  58448. ++h;
  58449. }
  58450. else
  58451. {
  58452. h = 0;
  58453. }
  58454. }
  58455. else
  58456. {
  58457. s = 0;
  58458. h = 0;
  58459. }
  58460. v = hi * oneOver255;
  58461. }
  58462. float Colour::getHue() const throw()
  58463. {
  58464. float h, s, b;
  58465. getHSB (h, s, b);
  58466. return h;
  58467. }
  58468. const Colour Colour::withHue (const float hue) const throw()
  58469. {
  58470. float h, s, b;
  58471. getHSB (h, s, b);
  58472. return Colour (hue, s, b, getAlpha());
  58473. }
  58474. const Colour Colour::withRotatedHue (const float amountToRotate) const throw()
  58475. {
  58476. float h, s, b;
  58477. getHSB (h, s, b);
  58478. h += amountToRotate;
  58479. h -= floorf (h);
  58480. return Colour (h, s, b, getAlpha());
  58481. }
  58482. float Colour::getSaturation() const throw()
  58483. {
  58484. float h, s, b;
  58485. getHSB (h, s, b);
  58486. return s;
  58487. }
  58488. const Colour Colour::withSaturation (const float saturation) const throw()
  58489. {
  58490. float h, s, b;
  58491. getHSB (h, s, b);
  58492. return Colour (h, saturation, b, getAlpha());
  58493. }
  58494. const Colour Colour::withMultipliedSaturation (const float amount) const throw()
  58495. {
  58496. float h, s, b;
  58497. getHSB (h, s, b);
  58498. return Colour (h, jmin (1.0f, s * amount), b, getAlpha());
  58499. }
  58500. float Colour::getBrightness() const throw()
  58501. {
  58502. float h, s, b;
  58503. getHSB (h, s, b);
  58504. return b;
  58505. }
  58506. const Colour Colour::withBrightness (const float brightness) const throw()
  58507. {
  58508. float h, s, b;
  58509. getHSB (h, s, b);
  58510. return Colour (h, s, brightness, getAlpha());
  58511. }
  58512. const Colour Colour::withMultipliedBrightness (const float amount) const throw()
  58513. {
  58514. float h, s, b;
  58515. getHSB (h, s, b);
  58516. b *= amount;
  58517. if (b > 1.0f)
  58518. b = 1.0f;
  58519. return Colour (h, s, b, getAlpha());
  58520. }
  58521. const Colour Colour::brighter (float amount) const throw()
  58522. {
  58523. amount = 1.0f / (1.0f + amount);
  58524. return Colour ((uint8) (255 - (amount * (255 - getRed()))),
  58525. (uint8) (255 - (amount * (255 - getGreen()))),
  58526. (uint8) (255 - (amount * (255 - getBlue()))),
  58527. getAlpha());
  58528. }
  58529. const Colour Colour::darker (float amount) const throw()
  58530. {
  58531. amount = 1.0f / (1.0f + amount);
  58532. return Colour ((uint8) (amount * getRed()),
  58533. (uint8) (amount * getGreen()),
  58534. (uint8) (amount * getBlue()),
  58535. getAlpha());
  58536. }
  58537. const Colour Colour::greyLevel (const float brightness) throw()
  58538. {
  58539. const uint8 level
  58540. = (uint8) jlimit (0x00, 0xff, roundFloatToInt (brightness * 255.0f));
  58541. return Colour (level, level, level);
  58542. }
  58543. const Colour Colour::contrasting (const float amount) const throw()
  58544. {
  58545. return overlaidWith ((((int) getRed() + (int) getGreen() + (int) getBlue() >= 3 * 128)
  58546. ? Colours::black
  58547. : Colours::white).withAlpha (amount));
  58548. }
  58549. const Colour Colour::contrasting (const Colour& colour1,
  58550. const Colour& colour2) throw()
  58551. {
  58552. const float b1 = colour1.getBrightness();
  58553. const float b2 = colour2.getBrightness();
  58554. float best = 0.0f;
  58555. float bestDist = 0.0f;
  58556. for (float i = 0.0f; i < 1.0f; i += 0.02f)
  58557. {
  58558. const float d1 = fabsf (i - b1);
  58559. const float d2 = fabsf (i - b2);
  58560. const float dist = jmin (d1, d2, 1.0f - d1, 1.0f - d2);
  58561. if (dist > bestDist)
  58562. {
  58563. best = i;
  58564. bestDist = dist;
  58565. }
  58566. }
  58567. return colour1.overlaidWith (colour2.withMultipliedAlpha (0.5f))
  58568. .withBrightness (best);
  58569. }
  58570. const String Colour::toString() const throw()
  58571. {
  58572. return String::toHexString ((int) argb.getARGB());
  58573. }
  58574. const Colour Colour::fromString (const String& encodedColourString)
  58575. {
  58576. return Colour ((uint32) encodedColourString.getHexValue32());
  58577. }
  58578. END_JUCE_NAMESPACE
  58579. /********* End of inlined file: juce_Colour.cpp *********/
  58580. /********* Start of inlined file: juce_ColourGradient.cpp *********/
  58581. BEGIN_JUCE_NAMESPACE
  58582. ColourGradient::ColourGradient() throw()
  58583. : colours (4)
  58584. {
  58585. #ifdef JUCE_DEBUG
  58586. x1 = 987654.0f;
  58587. #endif
  58588. }
  58589. ColourGradient::ColourGradient (const Colour& colour1,
  58590. const float x1_,
  58591. const float y1_,
  58592. const Colour& colour2,
  58593. const float x2_,
  58594. const float y2_,
  58595. const bool isRadial_) throw()
  58596. : x1 (x1_),
  58597. y1 (y1_),
  58598. x2 (x2_),
  58599. y2 (y2_),
  58600. isRadial (isRadial_),
  58601. colours (4)
  58602. {
  58603. colours.add (0);
  58604. colours.add (colour1.getPixelARGB().getARGB());
  58605. colours.add (1 << 16);
  58606. colours.add (colour2.getPixelARGB().getARGB());
  58607. }
  58608. ColourGradient::~ColourGradient() throw()
  58609. {
  58610. }
  58611. void ColourGradient::clearColours() throw()
  58612. {
  58613. colours.clear();
  58614. }
  58615. void ColourGradient::addColour (const double proportionAlongGradient,
  58616. const Colour& colour) throw()
  58617. {
  58618. // must be within the two end-points
  58619. jassert (proportionAlongGradient >= 0 && proportionAlongGradient <= 1.0);
  58620. const uint32 pos = jlimit (0, 65535, roundDoubleToInt (proportionAlongGradient * 65536.0));
  58621. int i;
  58622. for (i = 0; i < colours.size(); i += 2)
  58623. if (colours.getUnchecked(i) > pos)
  58624. break;
  58625. colours.insert (i, pos);
  58626. colours.insert (i + 1, colour.getPixelARGB().getARGB());
  58627. }
  58628. void ColourGradient::multiplyOpacity (const float multiplier) throw()
  58629. {
  58630. for (int i = 1; i < colours.size(); i += 2)
  58631. {
  58632. PixelARGB pix (colours.getUnchecked(i));
  58633. pix.multiplyAlpha (multiplier);
  58634. colours.set (i, pix.getARGB());
  58635. }
  58636. }
  58637. int ColourGradient::getNumColours() const throw()
  58638. {
  58639. return colours.size() >> 1;
  58640. }
  58641. double ColourGradient::getColourPosition (const int index) const throw()
  58642. {
  58643. return colours [index << 1];
  58644. }
  58645. const Colour ColourGradient::getColour (const int index) const throw()
  58646. {
  58647. PixelARGB pix (colours [(index << 1) + 1]);
  58648. pix.unpremultiply();
  58649. return Colour (pix.getARGB());
  58650. }
  58651. PixelARGB* ColourGradient::createLookupTable (int& numEntries) const throw()
  58652. {
  58653. #ifdef JUCE_DEBUG
  58654. // trying to use the object without setting its co-ordinates? Have a careful read of
  58655. // the comments for the constructors.
  58656. jassert (x1 != 987654.0f);
  58657. #endif
  58658. const int numColours = colours.size() >> 1;
  58659. float tx1 = x1, ty1 = y1, tx2 = x2, ty2 = y2;
  58660. transform.transformPoint (tx1, ty1);
  58661. transform.transformPoint (tx2, ty2);
  58662. const double distance = juce_hypot (tx1 - tx2, ty1 - ty2);
  58663. numEntries = jlimit (1, (numColours - 1) << 8, 3 * (int) distance);
  58664. PixelARGB* const lookupTable = (PixelARGB*) juce_calloc (numEntries * sizeof (PixelARGB));
  58665. if (numColours >= 2)
  58666. {
  58667. jassert (colours.getUnchecked (0) == 0); // the first colour specified has to go at position 0
  58668. PixelARGB pix1 (colours.getUnchecked (1));
  58669. int index = 0;
  58670. for (int j = 2; j < colours.size(); j += 2)
  58671. {
  58672. const int numToDo = ((colours.getUnchecked (j) * numEntries) >> 16) - index;
  58673. const PixelARGB pix2 (colours.getUnchecked (j + 1));
  58674. for (int i = 0; i < numToDo; ++i)
  58675. {
  58676. jassert (index >= 0 && index < numEntries);
  58677. lookupTable[index] = pix1;
  58678. lookupTable[index].tween (pix2, (i << 8) / numToDo);
  58679. ++index;
  58680. }
  58681. pix1 = pix2;
  58682. }
  58683. while (index < numEntries)
  58684. lookupTable [index++] = pix1;
  58685. }
  58686. else
  58687. {
  58688. jassertfalse // no colours specified!
  58689. }
  58690. return lookupTable;
  58691. }
  58692. bool ColourGradient::isOpaque() const throw()
  58693. {
  58694. for (int i = 1; i < colours.size(); i += 2)
  58695. if (PixelARGB (colours.getUnchecked(i)).getAlpha() < 0xff)
  58696. return false;
  58697. return true;
  58698. }
  58699. bool ColourGradient::isInvisible() const throw()
  58700. {
  58701. for (int i = 1; i < colours.size(); i += 2)
  58702. if (PixelARGB (colours.getUnchecked(i)).getAlpha() > 0)
  58703. return false;
  58704. return true;
  58705. }
  58706. END_JUCE_NAMESPACE
  58707. /********* End of inlined file: juce_ColourGradient.cpp *********/
  58708. /********* Start of inlined file: juce_Colours.cpp *********/
  58709. BEGIN_JUCE_NAMESPACE
  58710. const Colour Colours::transparentBlack (0);
  58711. const Colour Colours::transparentWhite (0x00ffffff);
  58712. const Colour Colours::aliceblue (0xfff0f8ff);
  58713. const Colour Colours::antiquewhite (0xfffaebd7);
  58714. const Colour Colours::aqua (0xff00ffff);
  58715. const Colour Colours::aquamarine (0xff7fffd4);
  58716. const Colour Colours::azure (0xfff0ffff);
  58717. const Colour Colours::beige (0xfff5f5dc);
  58718. const Colour Colours::bisque (0xffffe4c4);
  58719. const Colour Colours::black (0xff000000);
  58720. const Colour Colours::blanchedalmond (0xffffebcd);
  58721. const Colour Colours::blue (0xff0000ff);
  58722. const Colour Colours::blueviolet (0xff8a2be2);
  58723. const Colour Colours::brown (0xffa52a2a);
  58724. const Colour Colours::burlywood (0xffdeb887);
  58725. const Colour Colours::cadetblue (0xff5f9ea0);
  58726. const Colour Colours::chartreuse (0xff7fff00);
  58727. const Colour Colours::chocolate (0xffd2691e);
  58728. const Colour Colours::coral (0xffff7f50);
  58729. const Colour Colours::cornflowerblue (0xff6495ed);
  58730. const Colour Colours::cornsilk (0xfffff8dc);
  58731. const Colour Colours::crimson (0xffdc143c);
  58732. const Colour Colours::cyan (0xff00ffff);
  58733. const Colour Colours::darkblue (0xff00008b);
  58734. const Colour Colours::darkcyan (0xff008b8b);
  58735. const Colour Colours::darkgoldenrod (0xffb8860b);
  58736. const Colour Colours::darkgrey (0xff555555);
  58737. const Colour Colours::darkgreen (0xff006400);
  58738. const Colour Colours::darkkhaki (0xffbdb76b);
  58739. const Colour Colours::darkmagenta (0xff8b008b);
  58740. const Colour Colours::darkolivegreen (0xff556b2f);
  58741. const Colour Colours::darkorange (0xffff8c00);
  58742. const Colour Colours::darkorchid (0xff9932cc);
  58743. const Colour Colours::darkred (0xff8b0000);
  58744. const Colour Colours::darksalmon (0xffe9967a);
  58745. const Colour Colours::darkseagreen (0xff8fbc8f);
  58746. const Colour Colours::darkslateblue (0xff483d8b);
  58747. const Colour Colours::darkslategrey (0xff2f4f4f);
  58748. const Colour Colours::darkturquoise (0xff00ced1);
  58749. const Colour Colours::darkviolet (0xff9400d3);
  58750. const Colour Colours::deeppink (0xffff1493);
  58751. const Colour Colours::deepskyblue (0xff00bfff);
  58752. const Colour Colours::dimgrey (0xff696969);
  58753. const Colour Colours::dodgerblue (0xff1e90ff);
  58754. const Colour Colours::firebrick (0xffb22222);
  58755. const Colour Colours::floralwhite (0xfffffaf0);
  58756. const Colour Colours::forestgreen (0xff228b22);
  58757. const Colour Colours::fuchsia (0xffff00ff);
  58758. const Colour Colours::gainsboro (0xffdcdcdc);
  58759. const Colour Colours::gold (0xffffd700);
  58760. const Colour Colours::goldenrod (0xffdaa520);
  58761. const Colour Colours::grey (0xff808080);
  58762. const Colour Colours::green (0xff008000);
  58763. const Colour Colours::greenyellow (0xffadff2f);
  58764. const Colour Colours::honeydew (0xfff0fff0);
  58765. const Colour Colours::hotpink (0xffff69b4);
  58766. const Colour Colours::indianred (0xffcd5c5c);
  58767. const Colour Colours::indigo (0xff4b0082);
  58768. const Colour Colours::ivory (0xfffffff0);
  58769. const Colour Colours::khaki (0xfff0e68c);
  58770. const Colour Colours::lavender (0xffe6e6fa);
  58771. const Colour Colours::lavenderblush (0xfffff0f5);
  58772. const Colour Colours::lemonchiffon (0xfffffacd);
  58773. const Colour Colours::lightblue (0xffadd8e6);
  58774. const Colour Colours::lightcoral (0xfff08080);
  58775. const Colour Colours::lightcyan (0xffe0ffff);
  58776. const Colour Colours::lightgoldenrodyellow (0xfffafad2);
  58777. const Colour Colours::lightgreen (0xff90ee90);
  58778. const Colour Colours::lightgrey (0xffd3d3d3);
  58779. const Colour Colours::lightpink (0xffffb6c1);
  58780. const Colour Colours::lightsalmon (0xffffa07a);
  58781. const Colour Colours::lightseagreen (0xff20b2aa);
  58782. const Colour Colours::lightskyblue (0xff87cefa);
  58783. const Colour Colours::lightslategrey (0xff778899);
  58784. const Colour Colours::lightsteelblue (0xffb0c4de);
  58785. const Colour Colours::lightyellow (0xffffffe0);
  58786. const Colour Colours::lime (0xff00ff00);
  58787. const Colour Colours::limegreen (0xff32cd32);
  58788. const Colour Colours::linen (0xfffaf0e6);
  58789. const Colour Colours::magenta (0xffff00ff);
  58790. const Colour Colours::maroon (0xff800000);
  58791. const Colour Colours::mediumaquamarine (0xff66cdaa);
  58792. const Colour Colours::mediumblue (0xff0000cd);
  58793. const Colour Colours::mediumorchid (0xffba55d3);
  58794. const Colour Colours::mediumpurple (0xff9370db);
  58795. const Colour Colours::mediumseagreen (0xff3cb371);
  58796. const Colour Colours::mediumslateblue (0xff7b68ee);
  58797. const Colour Colours::mediumspringgreen (0xff00fa9a);
  58798. const Colour Colours::mediumturquoise (0xff48d1cc);
  58799. const Colour Colours::mediumvioletred (0xffc71585);
  58800. const Colour Colours::midnightblue (0xff191970);
  58801. const Colour Colours::mintcream (0xfff5fffa);
  58802. const Colour Colours::mistyrose (0xffffe4e1);
  58803. const Colour Colours::navajowhite (0xffffdead);
  58804. const Colour Colours::navy (0xff000080);
  58805. const Colour Colours::oldlace (0xfffdf5e6);
  58806. const Colour Colours::olive (0xff808000);
  58807. const Colour Colours::olivedrab (0xff6b8e23);
  58808. const Colour Colours::orange (0xffffa500);
  58809. const Colour Colours::orangered (0xffff4500);
  58810. const Colour Colours::orchid (0xffda70d6);
  58811. const Colour Colours::palegoldenrod (0xffeee8aa);
  58812. const Colour Colours::palegreen (0xff98fb98);
  58813. const Colour Colours::paleturquoise (0xffafeeee);
  58814. const Colour Colours::palevioletred (0xffdb7093);
  58815. const Colour Colours::papayawhip (0xffffefd5);
  58816. const Colour Colours::peachpuff (0xffffdab9);
  58817. const Colour Colours::peru (0xffcd853f);
  58818. const Colour Colours::pink (0xffffc0cb);
  58819. const Colour Colours::plum (0xffdda0dd);
  58820. const Colour Colours::powderblue (0xffb0e0e6);
  58821. const Colour Colours::purple (0xff800080);
  58822. const Colour Colours::red (0xffff0000);
  58823. const Colour Colours::rosybrown (0xffbc8f8f);
  58824. const Colour Colours::royalblue (0xff4169e1);
  58825. const Colour Colours::saddlebrown (0xff8b4513);
  58826. const Colour Colours::salmon (0xfffa8072);
  58827. const Colour Colours::sandybrown (0xfff4a460);
  58828. const Colour Colours::seagreen (0xff2e8b57);
  58829. const Colour Colours::seashell (0xfffff5ee);
  58830. const Colour Colours::sienna (0xffa0522d);
  58831. const Colour Colours::silver (0xffc0c0c0);
  58832. const Colour Colours::skyblue (0xff87ceeb);
  58833. const Colour Colours::slateblue (0xff6a5acd);
  58834. const Colour Colours::slategrey (0xff708090);
  58835. const Colour Colours::snow (0xfffffafa);
  58836. const Colour Colours::springgreen (0xff00ff7f);
  58837. const Colour Colours::steelblue (0xff4682b4);
  58838. const Colour Colours::tan (0xffd2b48c);
  58839. const Colour Colours::teal (0xff008080);
  58840. const Colour Colours::thistle (0xffd8bfd8);
  58841. const Colour Colours::tomato (0xffff6347);
  58842. const Colour Colours::turquoise (0xff40e0d0);
  58843. const Colour Colours::violet (0xffee82ee);
  58844. const Colour Colours::wheat (0xfff5deb3);
  58845. const Colour Colours::white (0xffffffff);
  58846. const Colour Colours::whitesmoke (0xfff5f5f5);
  58847. const Colour Colours::yellow (0xffffff00);
  58848. const Colour Colours::yellowgreen (0xff9acd32);
  58849. const Colour Colours::findColourForName (const String& colourName,
  58850. const Colour& defaultColour)
  58851. {
  58852. static const int presets[] =
  58853. {
  58854. // (first value is the string's hashcode, second is ARGB)
  58855. 0x05978fff, 0xff000000, /* black */
  58856. 0x06bdcc29, 0xffffffff, /* white */
  58857. 0x002e305a, 0xff0000ff, /* blue */
  58858. 0x00308adf, 0xff808080, /* grey */
  58859. 0x05e0cf03, 0xff008000, /* green */
  58860. 0x0001b891, 0xffff0000, /* red */
  58861. 0xd43c6474, 0xffffff00, /* yellow */
  58862. 0x620886da, 0xfff0f8ff, /* aliceblue */
  58863. 0x20a2676a, 0xfffaebd7, /* antiquewhite */
  58864. 0x002dcebc, 0xff00ffff, /* aqua */
  58865. 0x46bb5f7e, 0xff7fffd4, /* aquamarine */
  58866. 0x0590228f, 0xfff0ffff, /* azure */
  58867. 0x05947fe4, 0xfff5f5dc, /* beige */
  58868. 0xad388e35, 0xffffe4c4, /* bisque */
  58869. 0x00674f7e, 0xffffebcd, /* blanchedalmond */
  58870. 0x39129959, 0xff8a2be2, /* blueviolet */
  58871. 0x059a8136, 0xffa52a2a, /* brown */
  58872. 0x89cea8f9, 0xffdeb887, /* burlywood */
  58873. 0x0fa260cf, 0xff5f9ea0, /* cadetblue */
  58874. 0x6b748956, 0xff7fff00, /* chartreuse */
  58875. 0x2903623c, 0xffd2691e, /* chocolate */
  58876. 0x05a74431, 0xffff7f50, /* coral */
  58877. 0x618d42dd, 0xff6495ed, /* cornflowerblue */
  58878. 0xe4b479fd, 0xfffff8dc, /* cornsilk */
  58879. 0x3d8c4edf, 0xffdc143c, /* crimson */
  58880. 0x002ed323, 0xff00ffff, /* cyan */
  58881. 0x67cc74d0, 0xff00008b, /* darkblue */
  58882. 0x67cd1799, 0xff008b8b, /* darkcyan */
  58883. 0x31bbd168, 0xffb8860b, /* darkgoldenrod */
  58884. 0x67cecf55, 0xff555555, /* darkgrey */
  58885. 0x920b194d, 0xff006400, /* darkgreen */
  58886. 0x923edd4c, 0xffbdb76b, /* darkkhaki */
  58887. 0x5c293873, 0xff8b008b, /* darkmagenta */
  58888. 0x6b6671fe, 0xff556b2f, /* darkolivegreen */
  58889. 0xbcfd2524, 0xffff8c00, /* darkorange */
  58890. 0xbcfdf799, 0xff9932cc, /* darkorchid */
  58891. 0x55ee0d5b, 0xff8b0000, /* darkred */
  58892. 0xc2e5f564, 0xffe9967a, /* darksalmon */
  58893. 0x61be858a, 0xff8fbc8f, /* darkseagreen */
  58894. 0xc2b0f2bd, 0xff483d8b, /* darkslateblue */
  58895. 0xc2b34d42, 0xff2f4f4f, /* darkslategrey */
  58896. 0x7cf2b06b, 0xff00ced1, /* darkturquoise */
  58897. 0xc8769375, 0xff9400d3, /* darkviolet */
  58898. 0x25832862, 0xffff1493, /* deeppink */
  58899. 0xfcad568f, 0xff00bfff, /* deepskyblue */
  58900. 0x634c8b67, 0xff696969, /* dimgrey */
  58901. 0x45c1ce55, 0xff1e90ff, /* dodgerblue */
  58902. 0xef19e3cb, 0xffb22222, /* firebrick */
  58903. 0xb852b195, 0xfffffaf0, /* floralwhite */
  58904. 0xd086fd06, 0xff228b22, /* forestgreen */
  58905. 0xe106b6d7, 0xffff00ff, /* fuchsia */
  58906. 0x7880d61e, 0xffdcdcdc, /* gainsboro */
  58907. 0x00308060, 0xffffd700, /* gold */
  58908. 0xb3b3bc1e, 0xffdaa520, /* goldenrod */
  58909. 0xbab8a537, 0xffadff2f, /* greenyellow */
  58910. 0xe4cacafb, 0xfff0fff0, /* honeydew */
  58911. 0x41892743, 0xffff69b4, /* hotpink */
  58912. 0xd5796f1a, 0xffcd5c5c, /* indianred */
  58913. 0xb969fed2, 0xff4b0082, /* indigo */
  58914. 0x05fef6a9, 0xfffffff0, /* ivory */
  58915. 0x06149302, 0xfff0e68c, /* khaki */
  58916. 0xad5a05c7, 0xffe6e6fa, /* lavender */
  58917. 0x7c4d5b99, 0xfffff0f5, /* lavenderblush */
  58918. 0x195756f0, 0xfffffacd, /* lemonchiffon */
  58919. 0x28e4ea70, 0xffadd8e6, /* lightblue */
  58920. 0xf3c7ccdb, 0xfff08080, /* lightcoral */
  58921. 0x28e58d39, 0xffe0ffff, /* lightcyan */
  58922. 0x21234e3c, 0xfffafad2, /* lightgoldenrodyellow */
  58923. 0xf40157ad, 0xff90ee90, /* lightgreen */
  58924. 0x28e744f5, 0xffd3d3d3, /* lightgrey */
  58925. 0x28eb3b8c, 0xffffb6c1, /* lightpink */
  58926. 0x9fb78304, 0xffffa07a, /* lightsalmon */
  58927. 0x50632b2a, 0xff20b2aa, /* lightseagreen */
  58928. 0x68fb7b25, 0xff87cefa, /* lightskyblue */
  58929. 0xa8a35ba2, 0xff778899, /* lightslategrey */
  58930. 0xa20d484f, 0xffb0c4de, /* lightsteelblue */
  58931. 0xaa2cf10a, 0xffffffe0, /* lightyellow */
  58932. 0x0032afd5, 0xff00ff00, /* lime */
  58933. 0x607bbc4e, 0xff32cd32, /* limegreen */
  58934. 0x06234efa, 0xfffaf0e6, /* linen */
  58935. 0x316858a9, 0xffff00ff, /* magenta */
  58936. 0xbf8ca470, 0xff800000, /* maroon */
  58937. 0xbd58e0b3, 0xff66cdaa, /* mediumaquamarine */
  58938. 0x967dfd4f, 0xff0000cd, /* mediumblue */
  58939. 0x056f5c58, 0xffba55d3, /* mediumorchid */
  58940. 0x07556b71, 0xff9370db, /* mediumpurple */
  58941. 0x5369b689, 0xff3cb371, /* mediumseagreen */
  58942. 0x066be19e, 0xff7b68ee, /* mediumslateblue */
  58943. 0x3256b281, 0xff00fa9a, /* mediumspringgreen */
  58944. 0xc0ad9f4c, 0xff48d1cc, /* mediumturquoise */
  58945. 0x628e63dd, 0xffc71585, /* mediumvioletred */
  58946. 0x168eb32a, 0xff191970, /* midnightblue */
  58947. 0x4306b960, 0xfff5fffa, /* mintcream */
  58948. 0x4cbc0e6b, 0xffffe4e1, /* mistyrose */
  58949. 0xe97218a6, 0xffffdead, /* navajowhite */
  58950. 0x00337bb6, 0xff000080, /* navy */
  58951. 0xadd2d33e, 0xfffdf5e6, /* oldlace */
  58952. 0x064ee1db, 0xff808000, /* olive */
  58953. 0x9e33a98a, 0xff6b8e23, /* olivedrab */
  58954. 0xc3de262e, 0xffffa500, /* orange */
  58955. 0x58bebba3, 0xffff4500, /* orangered */
  58956. 0xc3def8a3, 0xffda70d6, /* orchid */
  58957. 0x28cb4834, 0xffeee8aa, /* palegoldenrod */
  58958. 0x3d9dd619, 0xff98fb98, /* palegreen */
  58959. 0x74022737, 0xffafeeee, /* paleturquoise */
  58960. 0x15e2ebc8, 0xffdb7093, /* palevioletred */
  58961. 0x5fd898e2, 0xffffefd5, /* papayawhip */
  58962. 0x93e1b776, 0xffffdab9, /* peachpuff */
  58963. 0x003472f8, 0xffcd853f, /* peru */
  58964. 0x00348176, 0xffffc0cb, /* pink */
  58965. 0x00348d94, 0xffdda0dd, /* plum */
  58966. 0xd036be93, 0xffb0e0e6, /* powderblue */
  58967. 0xc5c507bc, 0xff800080, /* purple */
  58968. 0xa89d65b3, 0xffbc8f8f, /* rosybrown */
  58969. 0xbd9413e1, 0xff4169e1, /* royalblue */
  58970. 0xf456044f, 0xff8b4513, /* saddlebrown */
  58971. 0xc9c6f66e, 0xfffa8072, /* salmon */
  58972. 0x0bb131e1, 0xfff4a460, /* sandybrown */
  58973. 0x34636c14, 0xff2e8b57, /* seagreen */
  58974. 0x3507fb41, 0xfffff5ee, /* seashell */
  58975. 0xca348772, 0xffa0522d, /* sienna */
  58976. 0xca37d30d, 0xffc0c0c0, /* silver */
  58977. 0x80da74fb, 0xff87ceeb, /* skyblue */
  58978. 0x44a8dd73, 0xff6a5acd, /* slateblue */
  58979. 0x44ab37f8, 0xff708090, /* slategrey */
  58980. 0x0035f183, 0xfffffafa, /* snow */
  58981. 0xd5440d16, 0xff00ff7f, /* springgreen */
  58982. 0x3e1524a5, 0xff4682b4, /* steelblue */
  58983. 0x0001bfa1, 0xffd2b48c, /* tan */
  58984. 0x0036425c, 0xff008080, /* teal */
  58985. 0xafc8858f, 0xffd8bfd8, /* thistle */
  58986. 0xcc41600a, 0xffff6347, /* tomato */
  58987. 0xfeea9b21, 0xff40e0d0, /* turquoise */
  58988. 0xcf57947f, 0xffee82ee, /* violet */
  58989. 0x06bdbae7, 0xfff5deb3, /* wheat */
  58990. 0x10802ee6, 0xfff5f5f5, /* whitesmoke */
  58991. 0xe1b5130f, 0xff9acd32 /* yellowgreen */
  58992. };
  58993. const int hash = colourName.trim().toLowerCase().hashCode();
  58994. for (int i = 0; i < numElementsInArray (presets); i += 2)
  58995. if (presets [i] == hash)
  58996. return Colour (presets [i + 1]);
  58997. return defaultColour;
  58998. }
  58999. END_JUCE_NAMESPACE
  59000. /********* End of inlined file: juce_Colours.cpp *********/
  59001. /********* Start of inlined file: juce_EdgeTable.cpp *********/
  59002. BEGIN_JUCE_NAMESPACE
  59003. EdgeTable::EdgeTable (const int top_,
  59004. const int height_,
  59005. const OversamplingLevel oversampling_,
  59006. const int expectedEdgesPerLine) throw()
  59007. : top (top_),
  59008. height (height_),
  59009. maxEdgesPerLine (expectedEdgesPerLine),
  59010. lineStrideElements ((expectedEdgesPerLine << 1) + 1),
  59011. oversampling (oversampling_)
  59012. {
  59013. table = (int*) juce_calloc ((height << (int)oversampling_)
  59014. * lineStrideElements * sizeof (int));
  59015. }
  59016. EdgeTable::EdgeTable (const EdgeTable& other) throw()
  59017. : table (0)
  59018. {
  59019. operator= (other);
  59020. }
  59021. const EdgeTable& EdgeTable::operator= (const EdgeTable& other) throw()
  59022. {
  59023. juce_free (table);
  59024. top = other.top;
  59025. height = other.height;
  59026. maxEdgesPerLine = other.maxEdgesPerLine;
  59027. lineStrideElements = other.lineStrideElements;
  59028. oversampling = other.oversampling;
  59029. const int tableSize = (height << (int)oversampling)
  59030. * lineStrideElements * sizeof (int);
  59031. table = (int*) juce_malloc (tableSize);
  59032. memcpy (table, other.table, tableSize);
  59033. return *this;
  59034. }
  59035. EdgeTable::~EdgeTable() throw()
  59036. {
  59037. juce_free (table);
  59038. }
  59039. void EdgeTable::remapTableForNumEdges (const int newNumEdgesPerLine) throw()
  59040. {
  59041. if (newNumEdgesPerLine != maxEdgesPerLine)
  59042. {
  59043. maxEdgesPerLine = newNumEdgesPerLine;
  59044. const int newLineStrideElements = maxEdgesPerLine * 2 + 1;
  59045. int* const newTable = (int*) juce_malloc ((height << (int) oversampling)
  59046. * newLineStrideElements * sizeof (int));
  59047. for (int i = 0; i < (height << (int) oversampling); ++i)
  59048. {
  59049. const int* srcLine = table + lineStrideElements * i;
  59050. int* dstLine = newTable + newLineStrideElements * i;
  59051. int num = *srcLine++;
  59052. *dstLine++ = num;
  59053. num <<= 1;
  59054. while (--num >= 0)
  59055. *dstLine++ = *srcLine++;
  59056. }
  59057. juce_free (table);
  59058. table = newTable;
  59059. lineStrideElements = newLineStrideElements;
  59060. }
  59061. }
  59062. void EdgeTable::optimiseTable() throw()
  59063. {
  59064. int maxLineElements = 0;
  59065. for (int i = height; --i >= 0;)
  59066. maxLineElements = jmax (maxLineElements,
  59067. table [i * lineStrideElements]);
  59068. remapTableForNumEdges (maxLineElements);
  59069. }
  59070. void EdgeTable::addEdgePoint (const int x, const int y, const int winding) throw()
  59071. {
  59072. jassert (y >= 0 && y < (height << oversampling))
  59073. int* lineStart = table + lineStrideElements * y;
  59074. int n = lineStart[0];
  59075. if (n >= maxEdgesPerLine)
  59076. {
  59077. remapTableForNumEdges (maxEdgesPerLine + juce_edgeTableDefaultEdgesPerLine);
  59078. lineStart = table + lineStrideElements * y;
  59079. }
  59080. n <<= 1;
  59081. int* const line = lineStart + 1;
  59082. while (n > 0)
  59083. {
  59084. const int cx = line [n - 2];
  59085. if (cx <= x)
  59086. break;
  59087. line [n] = cx;
  59088. line [n + 1] = line [n - 1];
  59089. n -= 2;
  59090. }
  59091. line [n] = x;
  59092. line [n + 1] = winding;
  59093. lineStart[0]++;
  59094. }
  59095. void EdgeTable::addPath (const Path& path,
  59096. const AffineTransform& transform) throw()
  59097. {
  59098. const int windingAmount = 256 / (1 << (int) oversampling);
  59099. const float timesOversampling = (float) (1 << (int) oversampling);
  59100. const int bottomLimit = (height << (int) oversampling);
  59101. PathFlatteningIterator iter (path, transform);
  59102. while (iter.next())
  59103. {
  59104. int y1 = roundFloatToInt (iter.y1 * timesOversampling) - (top << (int) oversampling);
  59105. int y2 = roundFloatToInt (iter.y2 * timesOversampling) - (top << (int) oversampling);
  59106. if (y1 != y2)
  59107. {
  59108. const double x1 = 256.0 * iter.x1;
  59109. const double x2 = 256.0 * iter.x2;
  59110. const double multiplier = (x2 - x1) / (y2 - y1);
  59111. const int oldY1 = y1;
  59112. int winding;
  59113. if (y1 > y2)
  59114. {
  59115. swapVariables (y1, y2);
  59116. winding = windingAmount;
  59117. }
  59118. else
  59119. {
  59120. winding = -windingAmount;
  59121. }
  59122. jassert (y1 < y2);
  59123. if (y1 < 0)
  59124. y1 = 0;
  59125. if (y2 > bottomLimit)
  59126. y2 = bottomLimit;
  59127. while (y1 < y2)
  59128. {
  59129. addEdgePoint (roundDoubleToInt (x1 + multiplier * (y1 - oldY1)),
  59130. y1,
  59131. winding);
  59132. ++y1;
  59133. }
  59134. }
  59135. }
  59136. if (! path.isUsingNonZeroWinding())
  59137. {
  59138. // if it's an alternate-winding path, we need to go through and
  59139. // make sure all the windings are alternating.
  59140. int* lineStart = table;
  59141. for (int i = height << (int) oversampling; --i >= 0;)
  59142. {
  59143. int* line = lineStart;
  59144. lineStart += lineStrideElements;
  59145. int num = *line;
  59146. while (--num >= 0)
  59147. {
  59148. line += 2;
  59149. *line = abs (*line);
  59150. if (--num >= 0)
  59151. {
  59152. line += 2;
  59153. *line = -abs (*line);
  59154. }
  59155. }
  59156. }
  59157. }
  59158. }
  59159. END_JUCE_NAMESPACE
  59160. /********* End of inlined file: juce_EdgeTable.cpp *********/
  59161. /********* Start of inlined file: juce_Graphics.cpp *********/
  59162. BEGIN_JUCE_NAMESPACE
  59163. static const Graphics::ResamplingQuality defaultQuality = Graphics::mediumResamplingQuality;
  59164. #define MINIMUM_COORD -0x3fffffff
  59165. #define MAXIMUM_COORD 0x3fffffff
  59166. #undef ASSERT_COORDS_ARE_SENSIBLE_NUMBERS
  59167. #define ASSERT_COORDS_ARE_SENSIBLE_NUMBERS(x, y, w, h) \
  59168. jassert ((int) x >= MINIMUM_COORD \
  59169. && (int) x <= MAXIMUM_COORD \
  59170. && (int) y >= MINIMUM_COORD \
  59171. && (int) y <= MAXIMUM_COORD \
  59172. && (int) w >= MINIMUM_COORD \
  59173. && (int) w <= MAXIMUM_COORD \
  59174. && (int) h >= MINIMUM_COORD \
  59175. && (int) h <= MAXIMUM_COORD);
  59176. LowLevelGraphicsContext::LowLevelGraphicsContext()
  59177. {
  59178. }
  59179. LowLevelGraphicsContext::~LowLevelGraphicsContext()
  59180. {
  59181. }
  59182. Graphics::Graphics (Image& imageToDrawOnto) throw()
  59183. : context (imageToDrawOnto.createLowLevelContext()),
  59184. ownsContext (true),
  59185. state (new GraphicsState()),
  59186. saveStatePending (false)
  59187. {
  59188. }
  59189. Graphics::Graphics (LowLevelGraphicsContext* const internalContext) throw()
  59190. : context (internalContext),
  59191. ownsContext (false),
  59192. state (new GraphicsState()),
  59193. saveStatePending (false)
  59194. {
  59195. }
  59196. Graphics::~Graphics() throw()
  59197. {
  59198. delete state;
  59199. if (ownsContext)
  59200. delete context;
  59201. }
  59202. void Graphics::resetToDefaultState() throw()
  59203. {
  59204. setColour (Colours::black);
  59205. state->font.resetToDefaultState();
  59206. state->quality = defaultQuality;
  59207. }
  59208. bool Graphics::isVectorDevice() const throw()
  59209. {
  59210. return context->isVectorDevice();
  59211. }
  59212. bool Graphics::reduceClipRegion (const int x, const int y,
  59213. const int w, const int h) throw()
  59214. {
  59215. saveStateIfPending();
  59216. return context->reduceClipRegion (x, y, w, h);
  59217. }
  59218. bool Graphics::reduceClipRegion (const RectangleList& clipRegion) throw()
  59219. {
  59220. saveStateIfPending();
  59221. return context->reduceClipRegion (clipRegion);
  59222. }
  59223. void Graphics::excludeClipRegion (const int x, const int y,
  59224. const int w, const int h) throw()
  59225. {
  59226. saveStateIfPending();
  59227. context->excludeClipRegion (x, y, w, h);
  59228. }
  59229. bool Graphics::isClipEmpty() const throw()
  59230. {
  59231. return context->isClipEmpty();
  59232. }
  59233. const Rectangle Graphics::getClipBounds() const throw()
  59234. {
  59235. return context->getClipBounds();
  59236. }
  59237. void Graphics::saveState() throw()
  59238. {
  59239. saveStateIfPending();
  59240. saveStatePending = true;
  59241. }
  59242. void Graphics::restoreState() throw()
  59243. {
  59244. if (saveStatePending)
  59245. {
  59246. saveStatePending = false;
  59247. }
  59248. else
  59249. {
  59250. const int stackSize = stateStack.size();
  59251. if (stackSize > 0)
  59252. {
  59253. context->restoreState();
  59254. delete state;
  59255. state = stateStack.getUnchecked (stackSize - 1);
  59256. stateStack.removeLast (1, false);
  59257. }
  59258. else
  59259. {
  59260. // Trying to call restoreState() more times than you've called saveState() !
  59261. // Be careful to correctly match each saveState() with exactly one call to restoreState().
  59262. jassertfalse
  59263. }
  59264. }
  59265. }
  59266. void Graphics::saveStateIfPending() throw()
  59267. {
  59268. if (saveStatePending)
  59269. {
  59270. saveStatePending = false;
  59271. context->saveState();
  59272. stateStack.add (new GraphicsState (*state));
  59273. }
  59274. }
  59275. void Graphics::setOrigin (const int newOriginX,
  59276. const int newOriginY) throw()
  59277. {
  59278. saveStateIfPending();
  59279. context->setOrigin (newOriginX, newOriginY);
  59280. }
  59281. bool Graphics::clipRegionIntersects (const int x, const int y,
  59282. const int w, const int h) const throw()
  59283. {
  59284. return context->clipRegionIntersects (x, y, w, h);
  59285. }
  59286. void Graphics::setColour (const Colour& newColour) throw()
  59287. {
  59288. saveStateIfPending();
  59289. state->colour = newColour;
  59290. deleteAndZero (state->brush);
  59291. }
  59292. const Colour& Graphics::getCurrentColour() const throw()
  59293. {
  59294. return state->colour;
  59295. }
  59296. void Graphics::setOpacity (const float newOpacity) throw()
  59297. {
  59298. saveStateIfPending();
  59299. state->colour = state->colour.withAlpha (newOpacity);
  59300. }
  59301. void Graphics::setBrush (const Brush* const newBrush) throw()
  59302. {
  59303. saveStateIfPending();
  59304. delete state->brush;
  59305. if (newBrush != 0)
  59306. state->brush = newBrush->createCopy();
  59307. else
  59308. state->brush = 0;
  59309. }
  59310. Graphics::GraphicsState::GraphicsState() throw()
  59311. : colour (Colours::black),
  59312. brush (0),
  59313. quality (defaultQuality)
  59314. {
  59315. }
  59316. Graphics::GraphicsState::GraphicsState (const GraphicsState& other) throw()
  59317. : colour (other.colour),
  59318. brush (other.brush != 0 ? other.brush->createCopy() : 0),
  59319. font (other.font),
  59320. quality (other.quality)
  59321. {
  59322. }
  59323. Graphics::GraphicsState::~GraphicsState() throw()
  59324. {
  59325. delete brush;
  59326. }
  59327. void Graphics::setFont (const Font& newFont) throw()
  59328. {
  59329. saveStateIfPending();
  59330. state->font = newFont;
  59331. }
  59332. void Graphics::setFont (const float newFontHeight,
  59333. const int newFontStyleFlags) throw()
  59334. {
  59335. saveStateIfPending();
  59336. state->font.setSizeAndStyle (newFontHeight, newFontStyleFlags, 1.0f, 0.0f);
  59337. }
  59338. const Font& Graphics::getCurrentFont() const throw()
  59339. {
  59340. return state->font;
  59341. }
  59342. void Graphics::drawSingleLineText (const String& text,
  59343. const int startX,
  59344. const int baselineY) const throw()
  59345. {
  59346. if (text.isNotEmpty()
  59347. && startX < context->getClipBounds().getRight())
  59348. {
  59349. GlyphArrangement arr;
  59350. arr.addLineOfText (state->font, text, (float) startX, (float) baselineY);
  59351. arr.draw (*this);
  59352. }
  59353. }
  59354. void Graphics::drawTextAsPath (const String& text,
  59355. const AffineTransform& transform) const throw()
  59356. {
  59357. if (text.isNotEmpty())
  59358. {
  59359. GlyphArrangement arr;
  59360. arr.addLineOfText (state->font, text, 0.0f, 0.0f);
  59361. arr.draw (*this, transform);
  59362. }
  59363. }
  59364. void Graphics::drawMultiLineText (const String& text,
  59365. const int startX,
  59366. const int baselineY,
  59367. const int maximumLineWidth) const throw()
  59368. {
  59369. if (text.isNotEmpty()
  59370. && startX < context->getClipBounds().getRight())
  59371. {
  59372. GlyphArrangement arr;
  59373. arr.addJustifiedText (state->font, text,
  59374. (float) startX, (float) baselineY, (float) maximumLineWidth,
  59375. Justification::left);
  59376. arr.draw (*this);
  59377. }
  59378. }
  59379. void Graphics::drawText (const String& text,
  59380. const int x,
  59381. const int y,
  59382. const int width,
  59383. const int height,
  59384. const Justification& justificationType,
  59385. const bool useEllipsesIfTooBig) const throw()
  59386. {
  59387. if (text.isNotEmpty() && context->clipRegionIntersects (x, y, width, height))
  59388. {
  59389. GlyphArrangement arr;
  59390. arr.addCurtailedLineOfText (state->font, text,
  59391. 0.0f, 0.0f, (float)width,
  59392. useEllipsesIfTooBig);
  59393. arr.justifyGlyphs (0, arr.getNumGlyphs(),
  59394. (float) x, (float) y,
  59395. (float) width, (float) height,
  59396. justificationType);
  59397. arr.draw (*this);
  59398. }
  59399. }
  59400. void Graphics::drawFittedText (const String& text,
  59401. const int x,
  59402. const int y,
  59403. const int width,
  59404. const int height,
  59405. const Justification& justification,
  59406. const int maximumNumberOfLines,
  59407. const float minimumHorizontalScale) const throw()
  59408. {
  59409. if (text.isNotEmpty()
  59410. && width > 0 && height > 0
  59411. && context->clipRegionIntersects (x, y, width, height))
  59412. {
  59413. GlyphArrangement arr;
  59414. arr.addFittedText (state->font, text,
  59415. (float) x, (float) y,
  59416. (float) width, (float) height,
  59417. justification,
  59418. maximumNumberOfLines,
  59419. minimumHorizontalScale);
  59420. arr.draw (*this);
  59421. }
  59422. }
  59423. void Graphics::fillRect (int x,
  59424. int y,
  59425. int width,
  59426. int 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. SolidColourBrush colourBrush (state->colour);
  59431. (state->brush != 0 ? *(state->brush) : (Brush&) colourBrush).paintRectangle (*context, x, y, width, height);
  59432. }
  59433. void Graphics::fillRect (const Rectangle& r) const throw()
  59434. {
  59435. fillRect (r.getX(),
  59436. r.getY(),
  59437. r.getWidth(),
  59438. r.getHeight());
  59439. }
  59440. void Graphics::fillRect (const float x,
  59441. const float y,
  59442. const float width,
  59443. const float height) const throw()
  59444. {
  59445. // passing in a silly number can cause maths problems in rendering!
  59446. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (x, y, width, height);
  59447. Path p;
  59448. p.addRectangle (x, y, width, height);
  59449. fillPath (p);
  59450. }
  59451. void Graphics::setPixel (int x, int y) const throw()
  59452. {
  59453. if (context->clipRegionIntersects (x, y, 1, 1))
  59454. {
  59455. SolidColourBrush colourBrush (state->colour);
  59456. (state->brush != 0 ? *(state->brush) : (Brush&) colourBrush).paintRectangle (*context, x, y, 1, 1);
  59457. }
  59458. }
  59459. void Graphics::fillAll() const throw()
  59460. {
  59461. fillRect (context->getClipBounds());
  59462. }
  59463. void Graphics::fillAll (const Colour& colourToUse) const throw()
  59464. {
  59465. if (! colourToUse.isTransparent())
  59466. {
  59467. const Rectangle clip (context->getClipBounds());
  59468. context->fillRectWithColour (clip.getX(), clip.getY(), clip.getWidth(), clip.getHeight(),
  59469. colourToUse, false);
  59470. }
  59471. }
  59472. void Graphics::fillPath (const Path& path,
  59473. const AffineTransform& transform) const throw()
  59474. {
  59475. if ((! context->isClipEmpty()) && ! path.isEmpty())
  59476. {
  59477. SolidColourBrush colourBrush (state->colour);
  59478. (state->brush != 0 ? *(state->brush) : (Brush&) colourBrush).paintPath (*context, path, transform);
  59479. }
  59480. }
  59481. void Graphics::strokePath (const Path& path,
  59482. const PathStrokeType& strokeType,
  59483. const AffineTransform& transform) const throw()
  59484. {
  59485. if (! state->colour.isTransparent())
  59486. {
  59487. Path stroke;
  59488. strokeType.createStrokedPath (stroke, path, transform);
  59489. fillPath (stroke);
  59490. }
  59491. }
  59492. void Graphics::drawRect (const int x,
  59493. const int y,
  59494. const int width,
  59495. const int height,
  59496. const int lineThickness) const throw()
  59497. {
  59498. // passing in a silly number can cause maths problems in rendering!
  59499. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (x, y, width, height);
  59500. SolidColourBrush colourBrush (state->colour);
  59501. Brush& b = (state->brush != 0 ? *(state->brush) : (Brush&) colourBrush);
  59502. b.paintRectangle (*context, x, y, width, lineThickness);
  59503. b.paintRectangle (*context, x, y + lineThickness, lineThickness, height - lineThickness * 2);
  59504. b.paintRectangle (*context, x + width - lineThickness, y + lineThickness, lineThickness, height - lineThickness * 2);
  59505. b.paintRectangle (*context, x, y + height - lineThickness, width, lineThickness);
  59506. }
  59507. void Graphics::drawRect (const float x,
  59508. const float y,
  59509. const float width,
  59510. const float height,
  59511. const float lineThickness) const throw()
  59512. {
  59513. // passing in a silly number can cause maths problems in rendering!
  59514. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (x, y, width, height);
  59515. Path p;
  59516. p.addRectangle (x, y, width, lineThickness);
  59517. p.addRectangle (x, y + lineThickness, lineThickness, height - lineThickness * 2.0f);
  59518. p.addRectangle (x + width - lineThickness, y + lineThickness, lineThickness, height - lineThickness * 2.0f);
  59519. p.addRectangle (x, y + height - lineThickness, width, lineThickness);
  59520. fillPath (p);
  59521. }
  59522. void Graphics::drawRect (const Rectangle& r,
  59523. const int lineThickness) const throw()
  59524. {
  59525. drawRect (r.getX(), r.getY(),
  59526. r.getWidth(), r.getHeight(),
  59527. lineThickness);
  59528. }
  59529. void Graphics::drawBevel (const int x,
  59530. const int y,
  59531. const int width,
  59532. const int height,
  59533. const int bevelThickness,
  59534. const Colour& topLeftColour,
  59535. const Colour& bottomRightColour,
  59536. const bool useGradient) const throw()
  59537. {
  59538. // passing in a silly number can cause maths problems in rendering!
  59539. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (x, y, width, height);
  59540. if (clipRegionIntersects (x, y, width, height))
  59541. {
  59542. const float oldOpacity = state->colour.getFloatAlpha();
  59543. const float ramp = oldOpacity / bevelThickness;
  59544. for (int i = bevelThickness; --i >= 0;)
  59545. {
  59546. const float op = useGradient ? ramp * (bevelThickness - i)
  59547. : oldOpacity;
  59548. context->fillRectWithColour (x + i, y + i, width - i * 2, 1, topLeftColour.withMultipliedAlpha (op), false);
  59549. context->fillRectWithColour (x + i, y + i + 1, 1, height - i * 2 - 2, topLeftColour.withMultipliedAlpha (op * 0.75f), false);
  59550. context->fillRectWithColour (x + i, y + height - i - 1, width - i * 2, 1, bottomRightColour.withMultipliedAlpha (op), false);
  59551. context->fillRectWithColour (x + width - i - 1, y + i + 1, 1, height - i * 2 - 2, bottomRightColour.withMultipliedAlpha (op * 0.75f), false);
  59552. }
  59553. }
  59554. }
  59555. void Graphics::fillEllipse (const float x,
  59556. const float y,
  59557. const float width,
  59558. const float height) const throw()
  59559. {
  59560. // passing in a silly number can cause maths problems in rendering!
  59561. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (x, y, width, height);
  59562. Path p;
  59563. p.addEllipse (x, y, width, height);
  59564. fillPath (p);
  59565. }
  59566. void Graphics::drawEllipse (const float x,
  59567. const float y,
  59568. const float width,
  59569. const float height,
  59570. const float lineThickness) const throw()
  59571. {
  59572. // passing in a silly number can cause maths problems in rendering!
  59573. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (x, y, width, height);
  59574. Path p;
  59575. p.addEllipse (x, y, width, height);
  59576. strokePath (p, PathStrokeType (lineThickness));
  59577. }
  59578. void Graphics::fillRoundedRectangle (const float x,
  59579. const float y,
  59580. const float width,
  59581. const float height,
  59582. const float cornerSize) const throw()
  59583. {
  59584. // passing in a silly number can cause maths problems in rendering!
  59585. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (x, y, width, height);
  59586. Path p;
  59587. p.addRoundedRectangle (x, y, width, height, cornerSize);
  59588. fillPath (p);
  59589. }
  59590. void Graphics::fillRoundedRectangle (const Rectangle& r,
  59591. const float cornerSize) const throw()
  59592. {
  59593. fillRoundedRectangle ((float) r.getX(),
  59594. (float) r.getY(),
  59595. (float) r.getWidth(),
  59596. (float) r.getHeight(),
  59597. cornerSize);
  59598. }
  59599. void Graphics::drawRoundedRectangle (const float x,
  59600. const float y,
  59601. const float width,
  59602. const float height,
  59603. const float cornerSize,
  59604. const float lineThickness) const throw()
  59605. {
  59606. // passing in a silly number can cause maths problems in rendering!
  59607. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (x, y, width, height);
  59608. Path p;
  59609. p.addRoundedRectangle (x, y, width, height, cornerSize);
  59610. strokePath (p, PathStrokeType (lineThickness));
  59611. }
  59612. void Graphics::drawRoundedRectangle (const Rectangle& r,
  59613. const float cornerSize,
  59614. const float lineThickness) const throw()
  59615. {
  59616. drawRoundedRectangle ((float) r.getX(),
  59617. (float) r.getY(),
  59618. (float) r.getWidth(),
  59619. (float) r.getHeight(),
  59620. cornerSize, lineThickness);
  59621. }
  59622. void Graphics::drawArrow (const float startX,
  59623. const float startY,
  59624. const float endX,
  59625. const float endY,
  59626. const float lineThickness,
  59627. const float arrowheadWidth,
  59628. const float arrowheadLength) const throw()
  59629. {
  59630. Path p;
  59631. p.addArrow (startX, startY, endX, endY,
  59632. lineThickness, arrowheadWidth, arrowheadLength);
  59633. fillPath (p);
  59634. }
  59635. void Graphics::fillCheckerBoard (int x, int y,
  59636. int width, int height,
  59637. const int checkWidth,
  59638. const int checkHeight,
  59639. const Colour& colour1,
  59640. const Colour& colour2) const throw()
  59641. {
  59642. jassert (checkWidth > 0 && checkHeight > 0); // can't be zero or less!
  59643. if (checkWidth > 0 && checkHeight > 0)
  59644. {
  59645. if (colour1 == colour2)
  59646. {
  59647. context->fillRectWithColour (x, y, width, height, colour1, false);
  59648. }
  59649. else
  59650. {
  59651. const Rectangle clip (context->getClipBounds());
  59652. const int right = jmin (x + width, clip.getRight());
  59653. const int bottom = jmin (y + height, clip.getBottom());
  59654. int cy = 0;
  59655. while (y < bottom)
  59656. {
  59657. int cx = cy;
  59658. for (int xx = x; xx < right; xx += checkWidth)
  59659. context->fillRectWithColour (xx, y,
  59660. jmin (checkWidth, right - xx),
  59661. jmin (checkHeight, bottom - y),
  59662. ((cx++ & 1) == 0) ? colour1 : colour2,
  59663. false);
  59664. ++cy;
  59665. y += checkHeight;
  59666. }
  59667. }
  59668. }
  59669. }
  59670. void Graphics::drawVerticalLine (const int x, float top, float bottom) const throw()
  59671. {
  59672. SolidColourBrush colourBrush (state->colour);
  59673. (state->brush != 0 ? *(state->brush) : (Brush&) colourBrush).paintVerticalLine (*context, x, top, bottom);
  59674. }
  59675. void Graphics::drawHorizontalLine (const int y, float left, float right) const throw()
  59676. {
  59677. SolidColourBrush colourBrush (state->colour);
  59678. (state->brush != 0 ? *(state->brush) : (Brush&) colourBrush).paintHorizontalLine (*context, y, left, right);
  59679. }
  59680. void Graphics::drawLine (float x1, float y1,
  59681. float x2, float y2) const throw()
  59682. {
  59683. if (! context->isClipEmpty())
  59684. {
  59685. SolidColourBrush colourBrush (state->colour);
  59686. (state->brush != 0 ? *(state->brush) : (Brush&) colourBrush).paintLine (*context, x1, y1, x2, y2);
  59687. }
  59688. }
  59689. void Graphics::drawLine (const float startX,
  59690. const float startY,
  59691. const float endX,
  59692. const float endY,
  59693. const float lineThickness) const throw()
  59694. {
  59695. Path p;
  59696. p.addLineSegment (startX, startY, endX, endY, lineThickness);
  59697. fillPath (p);
  59698. }
  59699. void Graphics::drawLine (const Line& line) const throw()
  59700. {
  59701. drawLine (line.getStartX(), line.getStartY(), line.getEndX(), line.getEndY());
  59702. }
  59703. void Graphics::drawLine (const Line& line,
  59704. const float lineThickness) const throw()
  59705. {
  59706. drawLine (line.getStartX(), line.getStartY(), line.getEndX(), line.getEndY(), lineThickness);
  59707. }
  59708. void Graphics::drawDashedLine (const float startX,
  59709. const float startY,
  59710. const float endX,
  59711. const float endY,
  59712. const float* const dashLengths,
  59713. const int numDashLengths,
  59714. const float lineThickness) const throw()
  59715. {
  59716. const double dx = endX - startX;
  59717. const double dy = endY - startY;
  59718. const double totalLen = juce_hypot (dx, dy);
  59719. if (totalLen >= 0.5)
  59720. {
  59721. const double onePixAlpha = 1.0 / totalLen;
  59722. double alpha = 0.0;
  59723. float x = startX;
  59724. float y = startY;
  59725. int n = 0;
  59726. while (alpha < 1.0f)
  59727. {
  59728. alpha = jmin (1.0, alpha + dashLengths[n++] * onePixAlpha);
  59729. n = n % numDashLengths;
  59730. const float oldX = x;
  59731. const float oldY = y;
  59732. x = (float) (startX + dx * alpha);
  59733. y = (float) (startY + dy * alpha);
  59734. if ((n & 1) != 0)
  59735. {
  59736. if (lineThickness != 1.0f)
  59737. drawLine (oldX, oldY, x, y, lineThickness);
  59738. else
  59739. drawLine (oldX, oldY, x, y);
  59740. }
  59741. }
  59742. }
  59743. }
  59744. void Graphics::setImageResamplingQuality (const Graphics::ResamplingQuality newQuality) throw()
  59745. {
  59746. saveStateIfPending();
  59747. state->quality = newQuality;
  59748. }
  59749. void Graphics::drawImageAt (const Image* const imageToDraw,
  59750. const int topLeftX,
  59751. const int topLeftY,
  59752. const bool fillAlphaChannelWithCurrentBrush) const throw()
  59753. {
  59754. if (imageToDraw != 0)
  59755. {
  59756. const int imageW = imageToDraw->getWidth();
  59757. const int imageH = imageToDraw->getHeight();
  59758. drawImage (imageToDraw,
  59759. topLeftX, topLeftY, imageW, imageH,
  59760. 0, 0, imageW, imageH,
  59761. fillAlphaChannelWithCurrentBrush);
  59762. }
  59763. }
  59764. void Graphics::drawImageWithin (const Image* const imageToDraw,
  59765. const int destX,
  59766. const int destY,
  59767. const int destW,
  59768. const int destH,
  59769. const RectanglePlacement& placementWithinTarget,
  59770. const bool fillAlphaChannelWithCurrentBrush) const throw()
  59771. {
  59772. // passing in a silly number can cause maths problems in rendering!
  59773. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (destX, destY, destW, destH);
  59774. if (imageToDraw != 0)
  59775. {
  59776. const int imageW = imageToDraw->getWidth();
  59777. const int imageH = imageToDraw->getHeight();
  59778. if (imageW > 0 && imageH > 0)
  59779. {
  59780. double newX = 0.0, newY = 0.0;
  59781. double newW = imageW;
  59782. double newH = imageH;
  59783. placementWithinTarget.applyTo (newX, newY, newW, newH,
  59784. destX, destY, destW, destH);
  59785. if (newW > 0 && newH > 0)
  59786. {
  59787. drawImage (imageToDraw,
  59788. roundDoubleToInt (newX), roundDoubleToInt (newY),
  59789. roundDoubleToInt (newW), roundDoubleToInt (newH),
  59790. 0, 0, imageW, imageH,
  59791. fillAlphaChannelWithCurrentBrush);
  59792. }
  59793. }
  59794. }
  59795. }
  59796. void Graphics::drawImage (const Image* const imageToDraw,
  59797. int dx, int dy, int dw, int dh,
  59798. int sx, int sy, int sw, int sh,
  59799. const bool fillAlphaChannelWithCurrentBrush) const throw()
  59800. {
  59801. // passing in a silly number can cause maths problems in rendering!
  59802. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (dx, dy, dw, dh);
  59803. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (sx, sy, sw, sh);
  59804. if (imageToDraw == 0 || ! context->clipRegionIntersects (dx, dy, dw, dh))
  59805. return;
  59806. if (sw == dw && sh == dh)
  59807. {
  59808. if (sx < 0)
  59809. {
  59810. dx -= sx;
  59811. dw += sx;
  59812. sw += sx;
  59813. sx = 0;
  59814. }
  59815. if (sx + sw > imageToDraw->getWidth())
  59816. {
  59817. const int amount = sx + sw - imageToDraw->getWidth();
  59818. dw -= amount;
  59819. sw -= amount;
  59820. }
  59821. if (sy < 0)
  59822. {
  59823. dy -= sy;
  59824. dh += sy;
  59825. sh += sy;
  59826. sy = 0;
  59827. }
  59828. if (sy + sh > imageToDraw->getHeight())
  59829. {
  59830. const int amount = sy + sh - imageToDraw->getHeight();
  59831. dh -= amount;
  59832. sh -= amount;
  59833. }
  59834. if (dw <= 0 || dh <= 0 || sw <= 0 || sh <= 0)
  59835. return;
  59836. if (fillAlphaChannelWithCurrentBrush)
  59837. {
  59838. SolidColourBrush colourBrush (state->colour);
  59839. (state->brush != 0 ? *(state->brush) : (Brush&) colourBrush)
  59840. .paintAlphaChannel (*context, *imageToDraw,
  59841. dx - sx, dy - sy,
  59842. dx, dy,
  59843. dw, dh);
  59844. }
  59845. else
  59846. {
  59847. context->blendImage (*imageToDraw,
  59848. dx, dy, dw, dh, sx, sy,
  59849. state->colour.getFloatAlpha());
  59850. }
  59851. }
  59852. else
  59853. {
  59854. if (dw <= 0 || dh <= 0 || sw <= 0 || sh <= 0)
  59855. return;
  59856. if (fillAlphaChannelWithCurrentBrush)
  59857. {
  59858. if (imageToDraw->isRGB())
  59859. {
  59860. fillRect (dx, dy, dw, dh);
  59861. }
  59862. else
  59863. {
  59864. int tx = dx;
  59865. int ty = dy;
  59866. int tw = dw;
  59867. int th = dh;
  59868. if (context->getClipBounds().intersectRectangle (tx, ty, tw, th))
  59869. {
  59870. Image temp (imageToDraw->getFormat(), tw, th, true);
  59871. Graphics g (temp);
  59872. g.setImageResamplingQuality (state->quality);
  59873. g.setOrigin (dx - tx, dy - ty);
  59874. g.drawImage (imageToDraw,
  59875. 0, 0, dw, dh,
  59876. sx, sy, sw, sh,
  59877. false);
  59878. SolidColourBrush colourBrush (state->colour);
  59879. (state->brush != 0 ? *(state->brush) : (Brush&) colourBrush)
  59880. .paintAlphaChannel (*context, temp, tx, ty, tx, ty, tw, th);
  59881. }
  59882. }
  59883. }
  59884. else
  59885. {
  59886. context->blendImageRescaling (*imageToDraw,
  59887. dx, dy, dw, dh,
  59888. sx, sy, sw, sh,
  59889. state->colour.getFloatAlpha(),
  59890. state->quality);
  59891. }
  59892. }
  59893. }
  59894. void Graphics::drawImageTransformed (const Image* const imageToDraw,
  59895. int sourceClipX,
  59896. int sourceClipY,
  59897. int sourceClipWidth,
  59898. int sourceClipHeight,
  59899. const AffineTransform& transform,
  59900. const bool fillAlphaChannelWithCurrentBrush) const throw()
  59901. {
  59902. if (imageToDraw != 0
  59903. && (! context->isClipEmpty())
  59904. && ! transform.isSingularity())
  59905. {
  59906. if (fillAlphaChannelWithCurrentBrush)
  59907. {
  59908. Path p;
  59909. p.addRectangle ((float) sourceClipX, (float) sourceClipY,
  59910. (float) sourceClipWidth, (float) sourceClipHeight);
  59911. p.applyTransform (transform);
  59912. float dx, dy, dw, dh;
  59913. p.getBounds (dx, dy, dw, dh);
  59914. int tx = (int) dx;
  59915. int ty = (int) dy;
  59916. int tw = roundFloatToInt (dw) + 2;
  59917. int th = roundFloatToInt (dh) + 2;
  59918. if (context->getClipBounds().intersectRectangle (tx, ty, tw, th))
  59919. {
  59920. Image temp (imageToDraw->getFormat(), tw, th, true);
  59921. Graphics g (temp);
  59922. g.setImageResamplingQuality (state->quality);
  59923. g.drawImageTransformed (imageToDraw,
  59924. sourceClipX,
  59925. sourceClipY,
  59926. sourceClipWidth,
  59927. sourceClipHeight,
  59928. transform.translated ((float) -tx, (float) -ty),
  59929. false);
  59930. SolidColourBrush colourBrush (state->colour);
  59931. (state->brush != 0 ? *(state->brush) : (Brush&) colourBrush).paintAlphaChannel (*context, temp, tx, ty, tx, ty, tw, th);
  59932. }
  59933. }
  59934. else
  59935. {
  59936. context->blendImageWarping (*imageToDraw,
  59937. sourceClipX,
  59938. sourceClipY,
  59939. sourceClipWidth,
  59940. sourceClipHeight,
  59941. transform,
  59942. state->colour.getFloatAlpha(),
  59943. state->quality);
  59944. }
  59945. }
  59946. }
  59947. END_JUCE_NAMESPACE
  59948. /********* End of inlined file: juce_Graphics.cpp *********/
  59949. /********* Start of inlined file: juce_Justification.cpp *********/
  59950. BEGIN_JUCE_NAMESPACE
  59951. Justification::Justification (const Justification& other) throw()
  59952. : flags (other.flags)
  59953. {
  59954. }
  59955. const Justification& Justification::operator= (const Justification& other) throw()
  59956. {
  59957. flags = other.flags;
  59958. return *this;
  59959. }
  59960. int Justification::getOnlyVerticalFlags() const throw()
  59961. {
  59962. return flags & (top | bottom | verticallyCentred);
  59963. }
  59964. int Justification::getOnlyHorizontalFlags() const throw()
  59965. {
  59966. return flags & (left | right | horizontallyCentred | horizontallyJustified);
  59967. }
  59968. void Justification::applyToRectangle (int& x, int& y,
  59969. const int w, const int h,
  59970. const int spaceX, const int spaceY,
  59971. const int spaceW, const int spaceH) const throw()
  59972. {
  59973. if ((flags & horizontallyCentred) != 0)
  59974. {
  59975. x = spaceX + ((spaceW - w) >> 1);
  59976. }
  59977. else if ((flags & right) != 0)
  59978. {
  59979. x = spaceX + spaceW - w;
  59980. }
  59981. else
  59982. {
  59983. x = spaceX;
  59984. }
  59985. if ((flags & verticallyCentred) != 0)
  59986. {
  59987. y = spaceY + ((spaceH - h) >> 1);
  59988. }
  59989. else if ((flags & bottom) != 0)
  59990. {
  59991. y = spaceY + spaceH - h;
  59992. }
  59993. else
  59994. {
  59995. y = spaceY;
  59996. }
  59997. }
  59998. END_JUCE_NAMESPACE
  59999. /********* End of inlined file: juce_Justification.cpp *********/
  60000. /********* Start of inlined file: juce_LowLevelGraphicsPostScriptRenderer.cpp *********/
  60001. BEGIN_JUCE_NAMESPACE
  60002. #if JUCE_MSVC
  60003. #pragma warning (disable: 4996) // deprecated sprintf warning
  60004. #endif
  60005. // this will throw an assertion if you try to draw something that's not
  60006. // possible in postscript
  60007. #define WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS 0
  60008. #if defined (JUCE_DEBUG) && WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS
  60009. #define notPossibleInPostscriptAssert jassertfalse
  60010. #else
  60011. #define notPossibleInPostscriptAssert
  60012. #endif
  60013. LowLevelGraphicsPostScriptRenderer::LowLevelGraphicsPostScriptRenderer (OutputStream& resultingPostScript,
  60014. const String& documentTitle,
  60015. const int totalWidth_,
  60016. const int totalHeight_)
  60017. : out (resultingPostScript),
  60018. totalWidth (totalWidth_),
  60019. totalHeight (totalHeight_),
  60020. xOffset (0),
  60021. yOffset (0),
  60022. needToClip (true)
  60023. {
  60024. clip = new RectangleList (Rectangle (0, 0, totalWidth_, totalHeight_));
  60025. const float scale = jmin ((520.0f / totalWidth_), (750.0f / totalHeight));
  60026. out << "%!PS-Adobe-3.0 EPSF-3.0"
  60027. "\n%%BoundingBox: 0 0 600 824"
  60028. "\n%%Pages: 0"
  60029. "\n%%Creator: Raw Material Software JUCE"
  60030. "\n%%Title: " << documentTitle <<
  60031. "\n%%CreationDate: none"
  60032. "\n%%LanguageLevel: 2"
  60033. "\n%%EndComments"
  60034. "\n%%BeginProlog"
  60035. "\n%%BeginResource: JRes"
  60036. "\n/bd {bind def} bind def"
  60037. "\n/c {setrgbcolor} bd"
  60038. "\n/m {moveto} bd"
  60039. "\n/l {lineto} bd"
  60040. "\n/rl {rlineto} bd"
  60041. "\n/ct {curveto} bd"
  60042. "\n/cp {closepath} bd"
  60043. "\n/pr {3 index 3 index moveto 1 index 0 rlineto 0 1 index rlineto pop neg 0 rlineto pop pop closepath} bd"
  60044. "\n/doclip {initclip newpath} bd"
  60045. "\n/endclip {clip newpath} bd"
  60046. "\n%%EndResource"
  60047. "\n%%EndProlog"
  60048. "\n%%BeginSetup"
  60049. "\n%%EndSetup"
  60050. "\n%%Page: 1 1"
  60051. "\n%%BeginPageSetup"
  60052. "\n%%EndPageSetup\n\n"
  60053. << "40 800 translate\n"
  60054. << scale << ' ' << scale << " scale\n\n";
  60055. }
  60056. LowLevelGraphicsPostScriptRenderer::~LowLevelGraphicsPostScriptRenderer()
  60057. {
  60058. delete clip;
  60059. }
  60060. bool LowLevelGraphicsPostScriptRenderer::isVectorDevice() const
  60061. {
  60062. return true;
  60063. }
  60064. void LowLevelGraphicsPostScriptRenderer::setOrigin (int x, int y)
  60065. {
  60066. if (x != 0 || y != 0)
  60067. {
  60068. xOffset += x;
  60069. yOffset += y;
  60070. needToClip = true;
  60071. }
  60072. }
  60073. bool LowLevelGraphicsPostScriptRenderer::reduceClipRegion (int x, int y, int w, int h)
  60074. {
  60075. needToClip = true;
  60076. return clip->clipTo (Rectangle (x + xOffset, y + yOffset, w, h));
  60077. }
  60078. bool LowLevelGraphicsPostScriptRenderer::reduceClipRegion (const RectangleList& clipRegion)
  60079. {
  60080. needToClip = true;
  60081. return clip->clipTo (clipRegion);
  60082. }
  60083. void LowLevelGraphicsPostScriptRenderer::excludeClipRegion (int x, int y, int w, int h)
  60084. {
  60085. needToClip = true;
  60086. clip->subtract (Rectangle (x + xOffset, y + yOffset, w, h));
  60087. }
  60088. bool LowLevelGraphicsPostScriptRenderer::clipRegionIntersects (int x, int y, int w, int h)
  60089. {
  60090. return clip->intersectsRectangle (Rectangle (x + xOffset, y + yOffset, w, h));
  60091. }
  60092. const Rectangle LowLevelGraphicsPostScriptRenderer::getClipBounds() const
  60093. {
  60094. return clip->getBounds().translated (-xOffset, -yOffset);
  60095. }
  60096. bool LowLevelGraphicsPostScriptRenderer::isClipEmpty() const
  60097. {
  60098. return clip->isEmpty();
  60099. }
  60100. LowLevelGraphicsPostScriptRenderer::SavedState::SavedState (RectangleList* const clip_,
  60101. const int xOffset_, const int yOffset_)
  60102. : clip (clip_),
  60103. xOffset (xOffset_),
  60104. yOffset (yOffset_)
  60105. {
  60106. }
  60107. LowLevelGraphicsPostScriptRenderer::SavedState::~SavedState()
  60108. {
  60109. delete clip;
  60110. }
  60111. void LowLevelGraphicsPostScriptRenderer::saveState()
  60112. {
  60113. stateStack.add (new SavedState (new RectangleList (*clip), xOffset, yOffset));
  60114. }
  60115. void LowLevelGraphicsPostScriptRenderer::restoreState()
  60116. {
  60117. SavedState* const top = stateStack.getLast();
  60118. if (top != 0)
  60119. {
  60120. clip->swapWith (*top->clip);
  60121. xOffset = top->xOffset;
  60122. yOffset = top->yOffset;
  60123. stateStack.removeLast();
  60124. needToClip = true;
  60125. }
  60126. else
  60127. {
  60128. jassertfalse // trying to pop with an empty stack!
  60129. }
  60130. }
  60131. void LowLevelGraphicsPostScriptRenderer::writeClip()
  60132. {
  60133. if (needToClip)
  60134. {
  60135. needToClip = false;
  60136. out << "doclip ";
  60137. int itemsOnLine = 0;
  60138. for (RectangleList::Iterator i (*clip); i.next();)
  60139. {
  60140. if (++itemsOnLine == 6)
  60141. {
  60142. itemsOnLine = 0;
  60143. out << '\n';
  60144. }
  60145. const Rectangle& r = *i.getRectangle();
  60146. out << r.getX() << ' ' << -r.getY() << ' '
  60147. << r.getWidth() << ' ' << -r.getHeight() << " pr ";
  60148. }
  60149. out << "endclip\n";
  60150. }
  60151. }
  60152. void LowLevelGraphicsPostScriptRenderer::writeColour (const Colour& colour)
  60153. {
  60154. Colour c (Colours::white.overlaidWith (colour));
  60155. if (lastColour != c)
  60156. {
  60157. lastColour = c;
  60158. out << String (c.getFloatRed(), 3) << ' '
  60159. << String (c.getFloatGreen(), 3) << ' '
  60160. << String (c.getFloatBlue(), 3) << " c\n";
  60161. }
  60162. }
  60163. void LowLevelGraphicsPostScriptRenderer::writeXY (const float x, const float y) const
  60164. {
  60165. out << String (x, 2) << ' '
  60166. << String (-y, 2) << ' ';
  60167. }
  60168. void LowLevelGraphicsPostScriptRenderer::writePath (const Path& path) const
  60169. {
  60170. out << "newpath ";
  60171. float lastX = 0.0f;
  60172. float lastY = 0.0f;
  60173. int itemsOnLine = 0;
  60174. Path::Iterator i (path);
  60175. while (i.next())
  60176. {
  60177. if (++itemsOnLine == 4)
  60178. {
  60179. itemsOnLine = 0;
  60180. out << '\n';
  60181. }
  60182. switch (i.elementType)
  60183. {
  60184. case Path::Iterator::startNewSubPath:
  60185. writeXY (i.x1, i.y1);
  60186. lastX = i.x1;
  60187. lastY = i.y1;
  60188. out << "m ";
  60189. break;
  60190. case Path::Iterator::lineTo:
  60191. writeXY (i.x1, i.y1);
  60192. lastX = i.x1;
  60193. lastY = i.y1;
  60194. out << "l ";
  60195. break;
  60196. case Path::Iterator::quadraticTo:
  60197. {
  60198. const float cp1x = lastX + (i.x1 - lastX) * 2.0f / 3.0f;
  60199. const float cp1y = lastY + (i.y1 - lastY) * 2.0f / 3.0f;
  60200. const float cp2x = cp1x + (i.x2 - lastX) / 3.0f;
  60201. const float cp2y = cp1y + (i.y2 - lastY) / 3.0f;
  60202. writeXY (cp1x, cp1y);
  60203. writeXY (cp2x, cp2y);
  60204. writeXY (i.x2, i.y2);
  60205. out << "ct ";
  60206. lastX = i.x2;
  60207. lastY = i.y2;
  60208. }
  60209. break;
  60210. case Path::Iterator::cubicTo:
  60211. writeXY (i.x1, i.y1);
  60212. writeXY (i.x2, i.y2);
  60213. writeXY (i.x3, i.y3);
  60214. out << "ct ";
  60215. lastX = i.x3;
  60216. lastY = i.y3;
  60217. break;
  60218. case Path::Iterator::closePath:
  60219. out << "cp ";
  60220. break;
  60221. default:
  60222. jassertfalse
  60223. break;
  60224. }
  60225. }
  60226. out << '\n';
  60227. }
  60228. void LowLevelGraphicsPostScriptRenderer::writeTransform (const AffineTransform& trans) const
  60229. {
  60230. out << "[ "
  60231. << trans.mat00 << ' '
  60232. << trans.mat10 << ' '
  60233. << trans.mat01 << ' '
  60234. << trans.mat11 << ' '
  60235. << trans.mat02 << ' '
  60236. << trans.mat12 << " ] concat ";
  60237. }
  60238. void LowLevelGraphicsPostScriptRenderer::fillRectWithColour (int x, int y, int w, int h, const Colour& colour, const bool /*replaceExistingContents*/)
  60239. {
  60240. writeClip();
  60241. writeColour (colour);
  60242. x += xOffset;
  60243. y += yOffset;
  60244. out << x << ' ' << -(y + h) << ' ' << w << ' ' << h << " rectfill\n";
  60245. }
  60246. void LowLevelGraphicsPostScriptRenderer::fillRectWithGradient (int x, int y, int w, int h, const ColourGradient& gradient)
  60247. {
  60248. Path p;
  60249. p.addRectangle ((float) x, (float) y, (float) w, (float) h);
  60250. fillPathWithGradient (p, AffineTransform::identity, gradient, EdgeTable::Oversampling_256times);
  60251. }
  60252. void LowLevelGraphicsPostScriptRenderer::fillPathWithColour (const Path& path, const AffineTransform& t,
  60253. const Colour& colour, EdgeTable::OversamplingLevel /*quality*/)
  60254. {
  60255. writeClip();
  60256. Path p (path);
  60257. p.applyTransform (t.translated ((float) xOffset, (float) yOffset));
  60258. writePath (p);
  60259. writeColour (colour);
  60260. out << "fill\n";
  60261. }
  60262. void LowLevelGraphicsPostScriptRenderer::fillPathWithGradient (const Path& path, const AffineTransform& t, const ColourGradient& gradient, EdgeTable::OversamplingLevel /*quality*/)
  60263. {
  60264. // this doesn't work correctly yet - it could be improved to handle solid gradients, but
  60265. // postscript can't do semi-transparent ones.
  60266. notPossibleInPostscriptAssert // you can disable this warning by setting the WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS flag at the top of this file
  60267. writeClip();
  60268. out << "gsave ";
  60269. {
  60270. Path p (path);
  60271. p.applyTransform (t.translated ((float) xOffset, (float) yOffset));
  60272. writePath (p);
  60273. out << "clip\n";
  60274. }
  60275. int numColours = 256;
  60276. PixelARGB* const colours = gradient.createLookupTable (numColours);
  60277. for (int i = numColours; --i >= 0;)
  60278. colours[i].unpremultiply();
  60279. const Rectangle bounds (clip->getBounds());
  60280. // ideally this would draw lots of lines or ellipses to approximate the gradient, but for the
  60281. // time-being, this just fills it with the average colour..
  60282. writeColour (Colour (colours [numColours / 2].getARGB()));
  60283. out << bounds.getX() << ' ' << -bounds.getBottom() << ' ' << bounds.getWidth() << ' ' << bounds.getHeight() << " rectfill\n";
  60284. juce_free (colours);
  60285. out << "grestore\n";
  60286. }
  60287. void LowLevelGraphicsPostScriptRenderer::fillPathWithImage (const Path& path, const AffineTransform& transform,
  60288. const Image& sourceImage,
  60289. int imageX, int imageY,
  60290. float opacity, EdgeTable::OversamplingLevel /*quality*/)
  60291. {
  60292. writeClip();
  60293. out << "gsave ";
  60294. Path p (path);
  60295. p.applyTransform (transform.translated ((float) xOffset, (float) yOffset));
  60296. writePath (p);
  60297. out << "clip\n";
  60298. blendImage (sourceImage, imageX, imageY, sourceImage.getWidth(), sourceImage.getHeight(), 0, 0, opacity);
  60299. out << "grestore\n";
  60300. }
  60301. void LowLevelGraphicsPostScriptRenderer::fillAlphaChannelWithColour (const Image& /*clipImage*/, int x, int y, const Colour& colour)
  60302. {
  60303. x += xOffset;
  60304. y += yOffset;
  60305. writeClip();
  60306. writeColour (colour);
  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::fillAlphaChannelWithGradient (const Image& /*alphaChannelImage*/, int imageX, int imageY, const ColourGradient& /*gradient*/)
  60310. {
  60311. imageX += xOffset;
  60312. imageY += yOffset;
  60313. writeClip();
  60314. notPossibleInPostscriptAssert // you can disable this warning by setting the WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS flag at the top of this file
  60315. }
  60316. void LowLevelGraphicsPostScriptRenderer::fillAlphaChannelWithImage (const Image& /*alphaImage*/, int alphaImageX, int alphaImageY,
  60317. const Image& /*fillerImage*/, int fillerImageX, int fillerImageY, float /*opacity*/)
  60318. {
  60319. alphaImageX += xOffset;
  60320. alphaImageY += yOffset;
  60321. fillerImageX += xOffset;
  60322. fillerImageY += yOffset;
  60323. writeClip();
  60324. notPossibleInPostscriptAssert // you can disable this warning by setting the WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS flag at the top of this file
  60325. }
  60326. void LowLevelGraphicsPostScriptRenderer::blendImageRescaling (const Image& sourceImage,
  60327. int dx, int dy, int dw, int dh,
  60328. int sx, int sy, int sw, int sh,
  60329. float alpha,
  60330. const Graphics::ResamplingQuality quality)
  60331. {
  60332. if (sw > 0 && sh > 0)
  60333. {
  60334. jassert (sx >= 0 && sx + sw <= sourceImage.getWidth());
  60335. jassert (sy >= 0 && sy + sh <= sourceImage.getHeight());
  60336. if (sw == dw && sh == dh)
  60337. {
  60338. blendImage (sourceImage,
  60339. dx, dy, dw, dh,
  60340. sx, sy, alpha);
  60341. }
  60342. else
  60343. {
  60344. blendImageWarping (sourceImage,
  60345. sx, sy, sw, sh,
  60346. AffineTransform::scale (dw / (float) sw,
  60347. dh / (float) sh)
  60348. .translated ((float) (dx - sx),
  60349. (float) (dy - sy)),
  60350. alpha,
  60351. quality);
  60352. }
  60353. }
  60354. }
  60355. void LowLevelGraphicsPostScriptRenderer::blendImage (const Image& sourceImage, int dx, int dy, int dw, int dh, int sx, int sy, float opacity)
  60356. {
  60357. blendImageWarping (sourceImage,
  60358. sx, sy, dw, dh,
  60359. AffineTransform::translation ((float) dx, (float) dy),
  60360. opacity, Graphics::highResamplingQuality);
  60361. }
  60362. void LowLevelGraphicsPostScriptRenderer::writeImage (const Image& im,
  60363. const int sx, const int sy,
  60364. const int maxW, const int maxH) const
  60365. {
  60366. out << "{<\n";
  60367. const int w = jmin (maxW, im.getWidth());
  60368. const int h = jmin (maxH, im.getHeight());
  60369. int charsOnLine = 0;
  60370. int lineStride, pixelStride;
  60371. const uint8* data = im.lockPixelDataReadOnly (0, 0, w, h, lineStride, pixelStride);
  60372. Colour pixel;
  60373. for (int y = h; --y >= 0;)
  60374. {
  60375. for (int x = 0; x < w; ++x)
  60376. {
  60377. const uint8* pixelData = data + lineStride * y + pixelStride * x;
  60378. if (x >= sx && y >= sy)
  60379. {
  60380. if (im.isARGB())
  60381. {
  60382. PixelARGB p (*(const PixelARGB*) pixelData);
  60383. p.unpremultiply();
  60384. pixel = Colours::white.overlaidWith (Colour (p.getARGB()));
  60385. }
  60386. else if (im.isRGB())
  60387. {
  60388. pixel = Colour (((const PixelRGB*) pixelData)->getARGB());
  60389. }
  60390. else
  60391. {
  60392. pixel = Colour ((uint8) 0, (uint8) 0, (uint8) 0, *pixelData);
  60393. }
  60394. }
  60395. else
  60396. {
  60397. pixel = Colours::transparentWhite;
  60398. }
  60399. char colourString [16];
  60400. sprintf (colourString, "%x%x%x", pixel.getRed(), pixel.getGreen(), pixel.getBlue());
  60401. out << (const char*) colourString;
  60402. charsOnLine += 3;
  60403. if (charsOnLine > 100)
  60404. {
  60405. out << '\n';
  60406. charsOnLine = 0;
  60407. }
  60408. }
  60409. }
  60410. im.releasePixelDataReadOnly (data);
  60411. out << "\n>}\n";
  60412. }
  60413. void LowLevelGraphicsPostScriptRenderer::blendImageWarping (const Image& sourceImage,
  60414. int srcClipX, int srcClipY,
  60415. int srcClipW, int srcClipH,
  60416. const AffineTransform& t,
  60417. float /*opacity*/,
  60418. const Graphics::ResamplingQuality /*quality*/)
  60419. {
  60420. const int w = jmin (sourceImage.getWidth(), srcClipX + srcClipW);
  60421. const int h = jmin (sourceImage.getHeight(), srcClipY + srcClipH);
  60422. writeClip();
  60423. out << "gsave ";
  60424. writeTransform (t.translated ((float) xOffset, (float) yOffset)
  60425. .scaled (1.0f, -1.0f));
  60426. RectangleList imageClip;
  60427. sourceImage.createSolidAreaMask (imageClip, 0.5f);
  60428. imageClip.clipTo (Rectangle (srcClipX, srcClipY, srcClipW, srcClipH));
  60429. out << "newpath ";
  60430. int itemsOnLine = 0;
  60431. for (RectangleList::Iterator i (imageClip); i.next();)
  60432. {
  60433. if (++itemsOnLine == 6)
  60434. {
  60435. out << '\n';
  60436. itemsOnLine = 0;
  60437. }
  60438. const Rectangle& r = *i.getRectangle();
  60439. out << r.getX() << ' ' << r.getY() << ' ' << r.getWidth() << ' ' << r.getHeight() << " pr ";
  60440. }
  60441. out << " clip newpath\n";
  60442. out << w << ' ' << h << " scale\n";
  60443. out << w << ' ' << h << " 8 [" << w << " 0 0 -" << h << ' ' << (int) 0 << ' ' << h << " ]\n";
  60444. writeImage (sourceImage, srcClipX, srcClipY, srcClipW, srcClipH);
  60445. out << "false 3 colorimage grestore\n";
  60446. needToClip = true;
  60447. }
  60448. void LowLevelGraphicsPostScriptRenderer::drawLine (double x1, double y1, double x2, double y2, const Colour& colour)
  60449. {
  60450. Path p;
  60451. p.addLineSegment ((float) x1, (float) y1, (float) x2, (float) y2, 1.0f);
  60452. fillPathWithColour (p, AffineTransform::identity, colour, EdgeTable::Oversampling_256times);
  60453. }
  60454. void LowLevelGraphicsPostScriptRenderer::drawVerticalLine (const int x, double top, double bottom, const Colour& col)
  60455. {
  60456. drawLine (x, top, x, bottom, col);
  60457. }
  60458. void LowLevelGraphicsPostScriptRenderer::drawHorizontalLine (const int y, double left, double right, const Colour& col)
  60459. {
  60460. drawLine (left, y, right, y, col);
  60461. }
  60462. END_JUCE_NAMESPACE
  60463. /********* End of inlined file: juce_LowLevelGraphicsPostScriptRenderer.cpp *********/
  60464. /********* Start of inlined file: juce_LowLevelGraphicsSoftwareRenderer.cpp *********/
  60465. BEGIN_JUCE_NAMESPACE
  60466. #if ! (defined (JUCE_MAC) || (defined (JUCE_WIN32) && defined (JUCE_64BIT)))
  60467. #define JUCE_USE_SSE_INSTRUCTIONS 1
  60468. #endif
  60469. #if defined (JUCE_DEBUG) && JUCE_MSVC
  60470. #pragma warning (disable: 4714)
  60471. #endif
  60472. #define MINIMUM_COORD -0x3fffffff
  60473. #define MAXIMUM_COORD 0x3fffffff
  60474. #undef ASSERT_COORDS_ARE_SENSIBLE_NUMBERS
  60475. #define ASSERT_COORDS_ARE_SENSIBLE_NUMBERS(x, y, w, h) \
  60476. jassert ((int) x >= MINIMUM_COORD \
  60477. && (int) x <= MAXIMUM_COORD \
  60478. && (int) y >= MINIMUM_COORD \
  60479. && (int) y <= MAXIMUM_COORD \
  60480. && (int) w >= 0 \
  60481. && (int) w < MAXIMUM_COORD \
  60482. && (int) h >= 0 \
  60483. && (int) h < MAXIMUM_COORD);
  60484. static void replaceRectRGB (uint8* pixels, const int w, int h, const int stride, const Colour& colour) throw()
  60485. {
  60486. const PixelARGB blendColour (colour.getPixelARGB());
  60487. if (w < 32)
  60488. {
  60489. while (--h >= 0)
  60490. {
  60491. PixelRGB* dest = (PixelRGB*) pixels;
  60492. for (int i = w; --i >= 0;)
  60493. (dest++)->set (blendColour);
  60494. pixels += stride;
  60495. }
  60496. }
  60497. else
  60498. {
  60499. // for wider fills, it's worth using some optimisations..
  60500. const uint8 r = blendColour.getRed();
  60501. const uint8 g = blendColour.getGreen();
  60502. const uint8 b = blendColour.getBlue();
  60503. if (r == g && r == b) // if all the component values are the same, we can cheat..
  60504. {
  60505. while (--h >= 0)
  60506. {
  60507. memset (pixels, r, w * 3);
  60508. pixels += stride;
  60509. }
  60510. }
  60511. else
  60512. {
  60513. PixelRGB filler [4];
  60514. filler[0].set (blendColour);
  60515. filler[1].set (blendColour);
  60516. filler[2].set (blendColour);
  60517. filler[3].set (blendColour);
  60518. const int* const intFiller = (const int*) filler;
  60519. while (--h >= 0)
  60520. {
  60521. uint8* dest = (uint8*) pixels;
  60522. int i = w;
  60523. while ((i > 8) && (((pointer_sized_int) dest & 7) != 0))
  60524. {
  60525. ((PixelRGB*) dest)->set (blendColour);
  60526. dest += 3;
  60527. --i;
  60528. }
  60529. while (i >= 4)
  60530. {
  60531. ((int*) dest) [0] = intFiller[0];
  60532. ((int*) dest) [1] = intFiller[1];
  60533. ((int*) dest) [2] = intFiller[2];
  60534. dest += 12;
  60535. i -= 4;
  60536. }
  60537. while (--i >= 0)
  60538. {
  60539. ((PixelRGB*) dest)->set (blendColour);
  60540. dest += 3;
  60541. }
  60542. pixels += stride;
  60543. }
  60544. }
  60545. }
  60546. }
  60547. static void replaceRectARGB (uint8* pixels, const int w, int h, const int stride, const Colour& colour) throw()
  60548. {
  60549. const PixelARGB blendColour (colour.getPixelARGB());
  60550. while (--h >= 0)
  60551. {
  60552. PixelARGB* const dest = (PixelARGB*) pixels;
  60553. for (int i = 0; i < w; ++i)
  60554. dest[i] = blendColour;
  60555. pixels += stride;
  60556. }
  60557. }
  60558. static void blendRectRGB (uint8* pixels, const int w, int h, const int stride, const Colour& colour) throw()
  60559. {
  60560. if (colour.isOpaque())
  60561. {
  60562. replaceRectRGB (pixels, w, h, stride, colour);
  60563. }
  60564. else
  60565. {
  60566. const PixelARGB blendColour (colour.getPixelARGB());
  60567. const int alpha = blendColour.getAlpha();
  60568. if (alpha <= 0)
  60569. return;
  60570. #if defined (JUCE_USE_SSE_INSTRUCTIONS) && ! JUCE_64BIT
  60571. if (SystemStats::hasSSE())
  60572. {
  60573. int64 rgb0 = (((int64) blendColour.getRed()) << 32)
  60574. | (int64) ((blendColour.getGreen() << 16)
  60575. | blendColour.getBlue());
  60576. const int invAlpha = 0xff - alpha;
  60577. int64 aaaa = (invAlpha << 16) | invAlpha;
  60578. aaaa = (aaaa << 16) | aaaa;
  60579. #ifndef JUCE_GCC
  60580. __asm
  60581. {
  60582. movq mm1, aaaa
  60583. movq mm2, rgb0
  60584. pxor mm7, mm7
  60585. }
  60586. while (--h >= 0)
  60587. {
  60588. __asm
  60589. {
  60590. mov edx, pixels
  60591. mov ebx, w
  60592. pixloop:
  60593. prefetchnta [edx]
  60594. mov ax, [edx + 1]
  60595. shl eax, 8
  60596. mov al, [edx]
  60597. movd mm0, eax
  60598. punpcklbw mm0, mm7
  60599. pmullw mm0, mm1
  60600. psrlw mm0, 8
  60601. paddw mm0, mm2
  60602. packuswb mm0, mm7
  60603. movd eax, mm0
  60604. mov [edx], al
  60605. inc edx
  60606. shr eax, 8
  60607. mov [edx], ax
  60608. add edx, 2
  60609. dec ebx
  60610. jg pixloop
  60611. }
  60612. pixels += stride;
  60613. }
  60614. __asm emms
  60615. #else
  60616. __asm__ __volatile__ (
  60617. "movq %[aaaa], %%mm1 \n"
  60618. "\tmovq %[rgb0], %%mm2 \n"
  60619. "\tpxor %%mm7, %%mm7 \n"
  60620. ".lineLoop2: \n"
  60621. "\tmovl %%esi,%%edx \n"
  60622. "\tmovl %[w], %%ebx \n"
  60623. ".pixLoop2: \n"
  60624. "\tprefetchnta (%%edx) \n"
  60625. "\tmov (%%edx), %%ax \n"
  60626. "\tshl $8, %%eax \n"
  60627. "\tmov 2(%%edx), %%al \n"
  60628. "\tmovd %%eax, %%mm0 \n"
  60629. "\tpunpcklbw %%mm7, %%mm0 \n"
  60630. "\tpmullw %%mm1, %%mm0 \n"
  60631. "\tpsrlw $8, %%mm0 \n"
  60632. "\tpaddw %%mm2, %%mm0 \n"
  60633. "\tpackuswb %%mm7, %%mm0 \n"
  60634. "\tmovd %%mm0, %%eax \n"
  60635. "\tmovb %%al, (%%edx) \n"
  60636. "\tinc %%edx \n"
  60637. "\tshr $8, %%eax \n"
  60638. "\tmovw %%ax, (%%edx) \n"
  60639. "\tadd $2, %%edx \n"
  60640. "\tdec %%ebx \n"
  60641. "\tjg .pixLoop2 \n"
  60642. "\tadd %%edi, %%esi \n"
  60643. "\tdec %%ecx \n"
  60644. "\tjg .lineLoop2 \n"
  60645. "\temms \n"
  60646. : /* No output registers */
  60647. : [aaaa] "m" (aaaa), /* Input registers */
  60648. [rgb0] "m" (rgb0),
  60649. [w] "m" (w),
  60650. "c" (h),
  60651. [stride] "D" (stride),
  60652. [pixels] "S" (pixels)
  60653. : "cc", "eax", "edx", "memory" /* Clobber list */
  60654. );
  60655. #endif
  60656. }
  60657. else
  60658. #endif
  60659. {
  60660. while (--h >= 0)
  60661. {
  60662. PixelRGB* dest = (PixelRGB*) pixels;
  60663. for (int i = w; --i >= 0;)
  60664. (dest++)->blend (blendColour);
  60665. pixels += stride;
  60666. }
  60667. }
  60668. }
  60669. }
  60670. static void blendRectARGB (uint8* pixels, const int w, int h, const int stride, const Colour& colour) throw()
  60671. {
  60672. if (colour.isOpaque())
  60673. {
  60674. replaceRectARGB (pixels, w, h, stride, colour);
  60675. }
  60676. else
  60677. {
  60678. const PixelARGB blendColour (colour.getPixelARGB());
  60679. const int alpha = blendColour.getAlpha();
  60680. if (alpha <= 0)
  60681. return;
  60682. while (--h >= 0)
  60683. {
  60684. PixelARGB* dest = (PixelARGB*) pixels;
  60685. for (int i = w; --i >= 0;)
  60686. (dest++)->blend (blendColour);
  60687. pixels += stride;
  60688. }
  60689. }
  60690. }
  60691. static void blendAlphaMapARGB (uint8* destPixel, const int imageStride,
  60692. const uint8* alphaValues, const int w, int h,
  60693. const int pixelStride, const int lineStride,
  60694. const Colour& colour) throw()
  60695. {
  60696. const PixelARGB srcPix (colour.getPixelARGB());
  60697. while (--h >= 0)
  60698. {
  60699. PixelARGB* dest = (PixelARGB*) destPixel;
  60700. const uint8* src = alphaValues;
  60701. int i = w;
  60702. while (--i >= 0)
  60703. {
  60704. unsigned int srcAlpha = *src;
  60705. src += pixelStride;
  60706. if (srcAlpha > 0)
  60707. dest->blend (srcPix, srcAlpha);
  60708. ++dest;
  60709. }
  60710. alphaValues += lineStride;
  60711. destPixel += imageStride;
  60712. }
  60713. }
  60714. static void blendAlphaMapRGB (uint8* destPixel, const int imageStride,
  60715. const uint8* alphaValues, int const width, int height,
  60716. const int pixelStride, const int lineStride,
  60717. const Colour& colour) throw()
  60718. {
  60719. const PixelARGB srcPix (colour.getPixelARGB());
  60720. while (--height >= 0)
  60721. {
  60722. PixelRGB* dest = (PixelRGB*) destPixel;
  60723. const uint8* src = alphaValues;
  60724. int i = width;
  60725. while (--i >= 0)
  60726. {
  60727. unsigned int srcAlpha = *src;
  60728. src += pixelStride;
  60729. if (srcAlpha > 0)
  60730. dest->blend (srcPix, srcAlpha);
  60731. ++dest;
  60732. }
  60733. alphaValues += lineStride;
  60734. destPixel += imageStride;
  60735. }
  60736. }
  60737. template <class PixelType>
  60738. class SolidColourEdgeTableRenderer
  60739. {
  60740. uint8* const data;
  60741. const int stride;
  60742. PixelType* linePixels;
  60743. PixelARGB sourceColour;
  60744. SolidColourEdgeTableRenderer (const SolidColourEdgeTableRenderer&);
  60745. const SolidColourEdgeTableRenderer& operator= (const SolidColourEdgeTableRenderer&);
  60746. public:
  60747. SolidColourEdgeTableRenderer (uint8* const data_,
  60748. const int stride_,
  60749. const Colour& colour) throw()
  60750. : data (data_),
  60751. stride (stride_),
  60752. sourceColour (colour.getPixelARGB())
  60753. {
  60754. }
  60755. forcedinline void setEdgeTableYPos (const int y) throw()
  60756. {
  60757. linePixels = (PixelType*) (data + stride * y);
  60758. }
  60759. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) const throw()
  60760. {
  60761. linePixels[x].blend (sourceColour, alphaLevel);
  60762. }
  60763. forcedinline void handleEdgeTableLine (const int x, int width, const int alphaLevel) const throw()
  60764. {
  60765. PixelARGB p (sourceColour);
  60766. p.multiplyAlpha (alphaLevel);
  60767. PixelType* dest = linePixels + x;
  60768. if (p.getAlpha() < 0xff)
  60769. {
  60770. do
  60771. {
  60772. dest->blend (p);
  60773. ++dest;
  60774. } while (--width > 0);
  60775. }
  60776. else
  60777. {
  60778. do
  60779. {
  60780. dest->set (p);
  60781. ++dest;
  60782. } while (--width > 0);
  60783. }
  60784. }
  60785. };
  60786. class AlphaBitmapRenderer
  60787. {
  60788. uint8* data;
  60789. int stride;
  60790. uint8* lineStart;
  60791. AlphaBitmapRenderer (const AlphaBitmapRenderer&);
  60792. const AlphaBitmapRenderer& operator= (const AlphaBitmapRenderer&);
  60793. public:
  60794. AlphaBitmapRenderer (uint8* const data_,
  60795. const int stride_) throw()
  60796. : data (data_),
  60797. stride (stride_)
  60798. {
  60799. }
  60800. forcedinline void setEdgeTableYPos (const int y) throw()
  60801. {
  60802. lineStart = data + (stride * y);
  60803. }
  60804. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) const throw()
  60805. {
  60806. lineStart [x] = (uint8) alphaLevel;
  60807. }
  60808. forcedinline void handleEdgeTableLine (const int x, int width, const int alphaLevel) const throw()
  60809. {
  60810. uint8* d = lineStart + x;
  60811. while (--width >= 0)
  60812. *d++ = (uint8) alphaLevel;
  60813. }
  60814. };
  60815. static const int numScaleBits = 12;
  60816. class LinearGradientPixelGenerator
  60817. {
  60818. const PixelARGB* const lookupTable;
  60819. const int numEntries;
  60820. PixelARGB linePix;
  60821. int start, scale;
  60822. double grad, yTerm;
  60823. bool vertical, horizontal;
  60824. LinearGradientPixelGenerator (const LinearGradientPixelGenerator&);
  60825. const LinearGradientPixelGenerator& operator= (const LinearGradientPixelGenerator&);
  60826. public:
  60827. LinearGradientPixelGenerator (const ColourGradient& gradient,
  60828. const PixelARGB* const lookupTable_, const int numEntries_)
  60829. : lookupTable (lookupTable_),
  60830. numEntries (numEntries_)
  60831. {
  60832. jassert (numEntries_ >= 0);
  60833. float x1 = gradient.x1;
  60834. float y1 = gradient.y1;
  60835. float x2 = gradient.x2;
  60836. float y2 = gradient.y2;
  60837. if (! gradient.transform.isIdentity())
  60838. {
  60839. Line l (x2, y2, x1, y1);
  60840. const Point p3 = l.getPointAlongLine (0.0, 100.0f);
  60841. float x3 = p3.getX();
  60842. float y3 = p3.getY();
  60843. gradient.transform.transformPoint (x1, y1);
  60844. gradient.transform.transformPoint (x2, y2);
  60845. gradient.transform.transformPoint (x3, y3);
  60846. Line l2 (x2, y2, x3, y3);
  60847. float prop = l2.findNearestPointTo (x1, y1);
  60848. const Point newP2 (l2.getPointAlongLineProportionally (prop));
  60849. x2 = newP2.getX();
  60850. y2 = newP2.getY();
  60851. }
  60852. vertical = fabs (x1 - x2) < 0.001f;
  60853. horizontal = fabs (y1 - y2) < 0.001f;
  60854. if (vertical)
  60855. {
  60856. scale = roundDoubleToInt ((numEntries << numScaleBits) / (double) (y2 - y1));
  60857. start = roundDoubleToInt (y1 * scale);
  60858. }
  60859. else if (horizontal)
  60860. {
  60861. scale = roundDoubleToInt ((numEntries << numScaleBits) / (double) (x2 - x1));
  60862. start = roundDoubleToInt (x1 * scale);
  60863. }
  60864. else
  60865. {
  60866. grad = (y2 - y1) / (double) (x1 - x2);
  60867. yTerm = y1 - x1 / grad;
  60868. scale = roundDoubleToInt ((numEntries << numScaleBits) / (yTerm * grad - (y2 * grad - x2)));
  60869. grad *= scale;
  60870. }
  60871. }
  60872. forcedinline void setY (const int y) throw()
  60873. {
  60874. if (vertical)
  60875. linePix = lookupTable [jlimit (0, numEntries, (y * scale - start) >> numScaleBits)];
  60876. else if (! horizontal)
  60877. start = roundDoubleToInt ((y - yTerm) * grad);
  60878. }
  60879. forcedinline const PixelARGB getPixel (const int x) const throw()
  60880. {
  60881. if (vertical)
  60882. return linePix;
  60883. return lookupTable [jlimit (0, numEntries, (x * scale - start) >> numScaleBits)];
  60884. }
  60885. };
  60886. class RadialGradientPixelGenerator
  60887. {
  60888. protected:
  60889. const PixelARGB* const lookupTable;
  60890. const int numEntries;
  60891. const double gx1, gy1;
  60892. double maxDist, invScale;
  60893. double dy;
  60894. RadialGradientPixelGenerator (const RadialGradientPixelGenerator&);
  60895. const RadialGradientPixelGenerator& operator= (const RadialGradientPixelGenerator&);
  60896. public:
  60897. RadialGradientPixelGenerator (const ColourGradient& gradient,
  60898. const PixelARGB* const lookupTable_, const int numEntries_) throw()
  60899. : lookupTable (lookupTable_),
  60900. numEntries (numEntries_),
  60901. gx1 (gradient.x1),
  60902. gy1 (gradient.y1)
  60903. {
  60904. jassert (numEntries_ >= 0);
  60905. const float dx = gradient.x1 - gradient.x2;
  60906. const float dy = gradient.y1 - gradient.y2;
  60907. maxDist = dx * dx + dy * dy;
  60908. invScale = (numEntries + 1) / sqrt (maxDist);
  60909. }
  60910. forcedinline void setY (const int y) throw()
  60911. {
  60912. dy = y - gy1;
  60913. dy *= dy;
  60914. }
  60915. forcedinline const PixelARGB getPixel (const int px) const throw()
  60916. {
  60917. double x = px - gx1;
  60918. x *= x;
  60919. x += dy;
  60920. if (x >= maxDist)
  60921. return lookupTable [numEntries];
  60922. else
  60923. return lookupTable [jmin (numEntries, roundDoubleToInt (sqrt (x) * invScale))];
  60924. }
  60925. };
  60926. class TransformedRadialGradientPixelGenerator : public RadialGradientPixelGenerator
  60927. {
  60928. double tM10, tM00, lineYM01, lineYM11;
  60929. AffineTransform inverseTransform;
  60930. TransformedRadialGradientPixelGenerator (const TransformedRadialGradientPixelGenerator&);
  60931. const TransformedRadialGradientPixelGenerator& operator= (const TransformedRadialGradientPixelGenerator&);
  60932. public:
  60933. TransformedRadialGradientPixelGenerator (const ColourGradient& gradient,
  60934. const PixelARGB* const lookupTable_, const int numEntries_) throw()
  60935. : RadialGradientPixelGenerator (gradient, lookupTable_, numEntries_),
  60936. inverseTransform (gradient.transform.inverted())
  60937. {
  60938. tM10 = inverseTransform.mat10;
  60939. tM00 = inverseTransform.mat00;
  60940. }
  60941. forcedinline void setY (const int y) throw()
  60942. {
  60943. lineYM01 = inverseTransform.mat01 * y + inverseTransform.mat02 - gx1;
  60944. lineYM11 = inverseTransform.mat11 * y + inverseTransform.mat12 - gy1;
  60945. }
  60946. forcedinline const PixelARGB getPixel (const int px) const throw()
  60947. {
  60948. double x = px;
  60949. const double y = tM10 * x + lineYM11;
  60950. x = tM00 * x + lineYM01;
  60951. x *= x;
  60952. x += y * y;
  60953. if (x >= maxDist)
  60954. return lookupTable [numEntries];
  60955. else
  60956. return lookupTable [jmin (numEntries, roundDoubleToInt (sqrt (x) * invScale))];
  60957. }
  60958. };
  60959. template <class PixelType, class GradientType>
  60960. class GradientEdgeTableRenderer : public GradientType
  60961. {
  60962. uint8* const data;
  60963. const int stride;
  60964. PixelType* linePixels;
  60965. GradientEdgeTableRenderer (const GradientEdgeTableRenderer&);
  60966. const GradientEdgeTableRenderer& operator= (const GradientEdgeTableRenderer&);
  60967. public:
  60968. GradientEdgeTableRenderer (uint8* const data_,
  60969. const int stride_,
  60970. const ColourGradient& gradient,
  60971. const PixelARGB* const lookupTable, const int numEntries) throw()
  60972. : GradientType (gradient, lookupTable, numEntries - 1),
  60973. data (data_),
  60974. stride (stride_)
  60975. {
  60976. }
  60977. forcedinline void setEdgeTableYPos (const int y) throw()
  60978. {
  60979. linePixels = (PixelType*) (data + stride * y);
  60980. GradientType::setY (y);
  60981. }
  60982. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) const throw()
  60983. {
  60984. linePixels[x].blend (GradientType::getPixel (x), alphaLevel);
  60985. }
  60986. forcedinline void handleEdgeTableLine (int x, int width, const int alphaLevel) const throw()
  60987. {
  60988. PixelType* dest = linePixels + x;
  60989. if (alphaLevel < 0xff)
  60990. {
  60991. do
  60992. {
  60993. (dest++)->blend (GradientType::getPixel (x++), alphaLevel);
  60994. } while (--width > 0);
  60995. }
  60996. else
  60997. {
  60998. do
  60999. {
  61000. (dest++)->blend (GradientType::getPixel (x++));
  61001. } while (--width > 0);
  61002. }
  61003. }
  61004. };
  61005. template <class DestPixelType, class SrcPixelType>
  61006. class ImageFillEdgeTableRenderer
  61007. {
  61008. uint8* const destImageData;
  61009. const uint8* srcImageData;
  61010. int stride, srcStride, extraAlpha;
  61011. DestPixelType* linePixels;
  61012. SrcPixelType* sourceLineStart;
  61013. ImageFillEdgeTableRenderer (const ImageFillEdgeTableRenderer&);
  61014. const ImageFillEdgeTableRenderer& operator= (const ImageFillEdgeTableRenderer&);
  61015. public:
  61016. ImageFillEdgeTableRenderer (uint8* const destImageData_,
  61017. const int stride_,
  61018. const uint8* srcImageData_,
  61019. const int srcStride_,
  61020. int extraAlpha_,
  61021. SrcPixelType*) throw() // dummy param to avoid compiler error
  61022. : destImageData (destImageData_),
  61023. srcImageData (srcImageData_),
  61024. stride (stride_),
  61025. srcStride (srcStride_),
  61026. extraAlpha (extraAlpha_)
  61027. {
  61028. }
  61029. forcedinline void setEdgeTableYPos (int y) throw()
  61030. {
  61031. linePixels = (DestPixelType*) (destImageData + stride * y);
  61032. sourceLineStart = (SrcPixelType*) (srcImageData + srcStride * y);
  61033. }
  61034. forcedinline void handleEdgeTablePixel (const int x, int alphaLevel) const throw()
  61035. {
  61036. alphaLevel = (alphaLevel * extraAlpha) >> 8;
  61037. linePixels[x].blend (sourceLineStart [x], alphaLevel);
  61038. }
  61039. forcedinline void handleEdgeTableLine (int x, int width, int alphaLevel) const throw()
  61040. {
  61041. DestPixelType* dest = linePixels + x;
  61042. alphaLevel = (alphaLevel * extraAlpha) >> 8;
  61043. if (alphaLevel < 0xfe)
  61044. {
  61045. do
  61046. {
  61047. dest++ ->blend (sourceLineStart [x++], alphaLevel);
  61048. } while (--width > 0);
  61049. }
  61050. else
  61051. {
  61052. do
  61053. {
  61054. dest++ ->blend (sourceLineStart [x++]);
  61055. } while (--width > 0);
  61056. }
  61057. }
  61058. };
  61059. static void blendRowOfPixels (PixelARGB* dst,
  61060. const PixelRGB* src,
  61061. int width) throw()
  61062. {
  61063. while (--width >= 0)
  61064. (dst++)->set (*src++);
  61065. }
  61066. static void blendRowOfPixels (PixelRGB* dst,
  61067. const PixelRGB* src,
  61068. int width) throw()
  61069. {
  61070. memcpy (dst, src, 3 * width);
  61071. }
  61072. static void blendRowOfPixels (PixelRGB* dst,
  61073. const PixelARGB* src,
  61074. int width) throw()
  61075. {
  61076. while (--width >= 0)
  61077. (dst++)->blend (*src++);
  61078. }
  61079. static void blendRowOfPixels (PixelARGB* dst,
  61080. const PixelARGB* src,
  61081. int width) throw()
  61082. {
  61083. while (--width >= 0)
  61084. (dst++)->blend (*src++);
  61085. }
  61086. static void blendRowOfPixels (PixelARGB* dst,
  61087. const PixelRGB* src,
  61088. int width,
  61089. const uint8 alpha) throw()
  61090. {
  61091. while (--width >= 0)
  61092. (dst++)->blend (*src++, alpha);
  61093. }
  61094. static void blendRowOfPixels (PixelRGB* dst,
  61095. const PixelRGB* src,
  61096. int width,
  61097. const uint8 alpha) throw()
  61098. {
  61099. uint8* d = (uint8*) dst;
  61100. const uint8* s = (const uint8*) src;
  61101. const int inverseAlpha = 0xff - alpha;
  61102. while (--width >= 0)
  61103. {
  61104. d[0] = (uint8) (s[0] + (((d[0] - s[0]) * inverseAlpha) >> 8));
  61105. d[1] = (uint8) (s[1] + (((d[1] - s[1]) * inverseAlpha) >> 8));
  61106. d[2] = (uint8) (s[2] + (((d[2] - s[2]) * inverseAlpha) >> 8));
  61107. d += 3;
  61108. s += 3;
  61109. }
  61110. }
  61111. static void blendRowOfPixels (PixelRGB* dst,
  61112. const PixelARGB* src,
  61113. int width,
  61114. const uint8 alpha) throw()
  61115. {
  61116. while (--width >= 0)
  61117. (dst++)->blend (*src++, alpha);
  61118. }
  61119. static void blendRowOfPixels (PixelARGB* dst,
  61120. const PixelARGB* src,
  61121. int width,
  61122. const uint8 alpha) throw()
  61123. {
  61124. while (--width >= 0)
  61125. (dst++)->blend (*src++, alpha);
  61126. }
  61127. template <class DestPixelType, class SrcPixelType>
  61128. static void overlayImage (DestPixelType* dest,
  61129. const int destStride,
  61130. const SrcPixelType* src,
  61131. const int srcStride,
  61132. const int width,
  61133. int height,
  61134. const uint8 alpha) throw()
  61135. {
  61136. if (alpha < 0xff)
  61137. {
  61138. while (--height >= 0)
  61139. {
  61140. blendRowOfPixels (dest, src, width, alpha);
  61141. dest = (DestPixelType*) (((uint8*) dest) + destStride);
  61142. src = (const SrcPixelType*) (((const uint8*) src) + srcStride);
  61143. }
  61144. }
  61145. else
  61146. {
  61147. while (--height >= 0)
  61148. {
  61149. blendRowOfPixels (dest, src, width);
  61150. dest = (DestPixelType*) (((uint8*) dest) + destStride);
  61151. src = (const SrcPixelType*) (((const uint8*) src) + srcStride);
  61152. }
  61153. }
  61154. }
  61155. template <class DestPixelType, class SrcPixelType>
  61156. static void transformedImageRender (Image& destImage,
  61157. const Image& sourceImage,
  61158. const int destClipX, const int destClipY,
  61159. const int destClipW, const int destClipH,
  61160. const int srcClipX, const int srcClipY,
  61161. const int srcClipWidth, const int srcClipHeight,
  61162. double srcX, double srcY,
  61163. const double lineDX, const double lineDY,
  61164. const double pixelDX, const double pixelDY,
  61165. const uint8 alpha,
  61166. const Graphics::ResamplingQuality quality,
  61167. DestPixelType*,
  61168. SrcPixelType*) throw() // forced by a compiler bug to include dummy
  61169. // parameters of the templated classes to
  61170. // make it use the correct instance of this function..
  61171. {
  61172. int destStride, destPixelStride;
  61173. uint8* const destPixels = destImage.lockPixelDataReadWrite (destClipX, destClipY, destClipW, destClipH, destStride, destPixelStride);
  61174. int srcStride, srcPixelStride;
  61175. const uint8* const srcPixels = sourceImage.lockPixelDataReadOnly (srcClipX, srcClipY, srcClipWidth, srcClipHeight, srcStride, srcPixelStride);
  61176. if (quality == Graphics::lowResamplingQuality) // nearest-neighbour..
  61177. {
  61178. for (int y = 0; y < destClipH; ++y)
  61179. {
  61180. double sx = srcX;
  61181. double sy = srcY;
  61182. DestPixelType* dest = (DestPixelType*) (destPixels + destStride * y);
  61183. for (int x = 0; x < destClipW; ++x)
  61184. {
  61185. const int ix = roundDoubleToInt (floor (sx)) - srcClipX;
  61186. if (((unsigned int) ix) < (unsigned int) srcClipWidth)
  61187. {
  61188. const int iy = roundDoubleToInt (floor (sy)) - srcClipY;
  61189. if (((unsigned int) iy) < (unsigned int) srcClipHeight)
  61190. {
  61191. const SrcPixelType* const src = (const SrcPixelType*) (srcPixels + srcStride * iy + srcPixelStride * ix);
  61192. dest->blend (*src, alpha);
  61193. }
  61194. }
  61195. ++dest;
  61196. sx += pixelDX;
  61197. sy += pixelDY;
  61198. }
  61199. srcX += lineDX;
  61200. srcY += lineDY;
  61201. }
  61202. }
  61203. else
  61204. {
  61205. jassert (quality == Graphics::mediumResamplingQuality); // (only bilinear is implemented, so that's what you'll get here..)
  61206. for (int y = 0; y < destClipH; ++y)
  61207. {
  61208. double sx = srcX;
  61209. double sy = srcY;
  61210. DestPixelType* dest = (DestPixelType*) (destPixels + destStride * y);
  61211. for (int x = 0; x < destClipW; ++x)
  61212. {
  61213. const double fx = floor (sx);
  61214. const double fy = floor (sy);
  61215. const int ix = roundDoubleToInt (fx) - srcClipX;
  61216. const int iy = roundDoubleToInt (fy) - srcClipY;
  61217. if (ix < srcClipWidth && iy < srcClipHeight)
  61218. {
  61219. PixelARGB p1 (0), p2 (0), p3 (0), p4 (0);
  61220. const SrcPixelType* src = (const SrcPixelType*) (srcPixels + srcStride * iy + srcPixelStride * ix);
  61221. if (iy >= 0)
  61222. {
  61223. if (ix >= 0)
  61224. p1.set (src[0]);
  61225. if (((unsigned int) (ix + 1)) < (unsigned int) srcClipWidth)
  61226. p2.set (src[1]);
  61227. }
  61228. if (((unsigned int) (iy + 1)) < (unsigned int) srcClipHeight)
  61229. {
  61230. src = (const SrcPixelType*) (((const uint8*) src) + srcStride);
  61231. if (ix >= 0)
  61232. p3.set (src[0]);
  61233. if (((unsigned int) (ix + 1)) < (unsigned int) srcClipWidth)
  61234. p4.set (src[1]);
  61235. }
  61236. const int dx = roundDoubleToInt ((sx - fx) * 255.0);
  61237. p1.tween (p2, dx);
  61238. p3.tween (p4, dx);
  61239. p1.tween (p3, roundDoubleToInt ((sy - fy) * 255.0));
  61240. if (p1.getAlpha() > 0)
  61241. dest->blend (p1, alpha);
  61242. }
  61243. ++dest;
  61244. sx += pixelDX;
  61245. sy += pixelDY;
  61246. }
  61247. srcX += lineDX;
  61248. srcY += lineDY;
  61249. }
  61250. }
  61251. destImage.releasePixelDataReadWrite (destPixels);
  61252. sourceImage.releasePixelDataReadOnly (srcPixels);
  61253. }
  61254. template <class SrcPixelType, class DestPixelType>
  61255. static void renderAlphaMap (DestPixelType* destPixels,
  61256. int destStride,
  61257. SrcPixelType* srcPixels,
  61258. int srcStride,
  61259. const uint8* alphaValues,
  61260. const int lineStride, const int pixelStride,
  61261. int width, int height,
  61262. const int extraAlpha) throw()
  61263. {
  61264. while (--height >= 0)
  61265. {
  61266. SrcPixelType* srcPix = srcPixels;
  61267. srcPixels = (SrcPixelType*) (((const uint8*) srcPixels) + srcStride);
  61268. DestPixelType* destPix = destPixels;
  61269. destPixels = (DestPixelType*) (((uint8*) destPixels) + destStride);
  61270. const uint8* alpha = alphaValues;
  61271. alphaValues += lineStride;
  61272. if (extraAlpha < 0x100)
  61273. {
  61274. for (int i = width; --i >= 0;)
  61275. {
  61276. destPix++ ->blend (*srcPix++, (extraAlpha * *alpha) >> 8);
  61277. alpha += pixelStride;
  61278. }
  61279. }
  61280. else
  61281. {
  61282. for (int i = width; --i >= 0;)
  61283. {
  61284. destPix++ ->blend (*srcPix++, *alpha);
  61285. alpha += pixelStride;
  61286. }
  61287. }
  61288. }
  61289. }
  61290. LowLevelGraphicsSoftwareRenderer::LowLevelGraphicsSoftwareRenderer (Image& image_)
  61291. : image (image_),
  61292. xOffset (0),
  61293. yOffset (0),
  61294. stateStack (20)
  61295. {
  61296. clip = new RectangleList (Rectangle (0, 0, image_.getWidth(), image_.getHeight()));
  61297. }
  61298. LowLevelGraphicsSoftwareRenderer::~LowLevelGraphicsSoftwareRenderer()
  61299. {
  61300. delete clip;
  61301. }
  61302. bool LowLevelGraphicsSoftwareRenderer::isVectorDevice() const
  61303. {
  61304. return false;
  61305. }
  61306. void LowLevelGraphicsSoftwareRenderer::setOrigin (int x, int y)
  61307. {
  61308. xOffset += x;
  61309. yOffset += y;
  61310. }
  61311. bool LowLevelGraphicsSoftwareRenderer::reduceClipRegion (int x, int y, int w, int h)
  61312. {
  61313. return clip->clipTo (Rectangle (x + xOffset, y + yOffset, w, h));
  61314. }
  61315. bool LowLevelGraphicsSoftwareRenderer::reduceClipRegion (const RectangleList& clipRegion)
  61316. {
  61317. RectangleList temp (clipRegion);
  61318. temp.offsetAll (xOffset, yOffset);
  61319. return clip->clipTo (temp);
  61320. }
  61321. void LowLevelGraphicsSoftwareRenderer::excludeClipRegion (int x, int y, int w, int h)
  61322. {
  61323. clip->subtract (Rectangle (x + xOffset, y + yOffset, w, h));
  61324. }
  61325. bool LowLevelGraphicsSoftwareRenderer::clipRegionIntersects (int x, int y, int w, int h)
  61326. {
  61327. return clip->intersectsRectangle (Rectangle (x + xOffset, y + yOffset, w, h));
  61328. }
  61329. const Rectangle LowLevelGraphicsSoftwareRenderer::getClipBounds() const
  61330. {
  61331. return clip->getBounds().translated (-xOffset, -yOffset);
  61332. }
  61333. bool LowLevelGraphicsSoftwareRenderer::isClipEmpty() const
  61334. {
  61335. return clip->isEmpty();
  61336. }
  61337. LowLevelGraphicsSoftwareRenderer::SavedState::SavedState (RectangleList* const clip_,
  61338. const int xOffset_, const int yOffset_)
  61339. : clip (clip_),
  61340. xOffset (xOffset_),
  61341. yOffset (yOffset_)
  61342. {
  61343. }
  61344. LowLevelGraphicsSoftwareRenderer::SavedState::~SavedState()
  61345. {
  61346. delete clip;
  61347. }
  61348. void LowLevelGraphicsSoftwareRenderer::saveState()
  61349. {
  61350. stateStack.add (new SavedState (new RectangleList (*clip), xOffset, yOffset));
  61351. }
  61352. void LowLevelGraphicsSoftwareRenderer::restoreState()
  61353. {
  61354. SavedState* const top = stateStack.getLast();
  61355. if (top != 0)
  61356. {
  61357. clip->swapWith (*top->clip);
  61358. xOffset = top->xOffset;
  61359. yOffset = top->yOffset;
  61360. stateStack.removeLast();
  61361. }
  61362. else
  61363. {
  61364. jassertfalse // trying to pop with an empty stack!
  61365. }
  61366. }
  61367. void LowLevelGraphicsSoftwareRenderer::fillRectWithColour (int x, int y, int w, int h, const Colour& colour, const bool replaceExistingContents)
  61368. {
  61369. x += xOffset;
  61370. y += yOffset;
  61371. for (RectangleList::Iterator i (*clip); i.next();)
  61372. {
  61373. clippedFillRectWithColour (*i.getRectangle(), x, y, w, h, colour, replaceExistingContents);
  61374. }
  61375. }
  61376. void LowLevelGraphicsSoftwareRenderer::clippedFillRectWithColour (const Rectangle& clipRect,
  61377. int x, int y, int w, int h, const Colour& colour, const bool replaceExistingContents)
  61378. {
  61379. if (clipRect.intersectRectangle (x, y, w, h))
  61380. {
  61381. int stride, pixelStride;
  61382. uint8* const pixels = (uint8*) image.lockPixelDataReadWrite (x, y, w, h, stride, pixelStride);
  61383. if (image.getFormat() == Image::RGB)
  61384. {
  61385. if (replaceExistingContents)
  61386. replaceRectRGB (pixels, w, h, stride, colour);
  61387. else
  61388. blendRectRGB (pixels, w, h, stride, colour);
  61389. }
  61390. else if (image.getFormat() == Image::ARGB)
  61391. {
  61392. if (replaceExistingContents)
  61393. replaceRectARGB (pixels, w, h, stride, colour);
  61394. else
  61395. blendRectARGB (pixels, w, h, stride, colour);
  61396. }
  61397. else
  61398. {
  61399. jassertfalse // not done!
  61400. }
  61401. image.releasePixelDataReadWrite (pixels);
  61402. }
  61403. }
  61404. void LowLevelGraphicsSoftwareRenderer::fillRectWithGradient (int x, int y, int w, int h, const ColourGradient& gradient)
  61405. {
  61406. Path p;
  61407. p.addRectangle ((float) x, (float) y, (float) w, (float) h);
  61408. fillPathWithGradient (p, AffineTransform::identity, gradient, EdgeTable::Oversampling_none);
  61409. }
  61410. bool LowLevelGraphicsSoftwareRenderer::getPathBounds (int clipX, int clipY, int clipW, int clipH,
  61411. const Path& path, const AffineTransform& transform,
  61412. int& x, int& y, int& w, int& h) const
  61413. {
  61414. float tx, ty, tw, th;
  61415. path.getBoundsTransformed (transform, tx, ty, tw, th);
  61416. x = roundDoubleToInt (tx) - 1;
  61417. y = roundDoubleToInt (ty) - 1;
  61418. w = roundDoubleToInt (tw) + 2;
  61419. h = roundDoubleToInt (th) + 2;
  61420. // seems like this operation is using some crazy out-of-range numbers..
  61421. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (x, y, w, h);
  61422. return Rectangle::intersectRectangles (x, y, w, h, clipX, clipY, clipW, clipH);
  61423. }
  61424. void LowLevelGraphicsSoftwareRenderer::fillPathWithColour (const Path& path, const AffineTransform& t,
  61425. const Colour& colour, EdgeTable::OversamplingLevel quality)
  61426. {
  61427. for (RectangleList::Iterator i (*clip); i.next();)
  61428. {
  61429. const Rectangle& r = *i.getRectangle();
  61430. clippedFillPathWithColour (r.getX(), r.getY(), r.getWidth(), r.getHeight(), path, t, colour, quality);
  61431. }
  61432. }
  61433. void LowLevelGraphicsSoftwareRenderer::clippedFillPathWithColour (int clipX, int clipY, int clipW, int clipH, const Path& path, const AffineTransform& t,
  61434. const Colour& colour, EdgeTable::OversamplingLevel quality)
  61435. {
  61436. const AffineTransform transform (t.translated ((float) xOffset, (float) yOffset));
  61437. int cx, cy, cw, ch;
  61438. if (getPathBounds (clipX, clipY, clipW, clipH, path, transform, cx, cy, cw, ch))
  61439. {
  61440. EdgeTable edgeTable (0, ch, quality);
  61441. edgeTable.addPath (path, transform.translated ((float) -cx, (float) -cy));
  61442. int stride, pixelStride;
  61443. uint8* const pixels = (uint8*) image.lockPixelDataReadWrite (cx, cy, cw, ch, stride, pixelStride);
  61444. if (image.getFormat() == Image::RGB)
  61445. {
  61446. jassert (pixelStride == 3);
  61447. SolidColourEdgeTableRenderer <PixelRGB> renderer (pixels, stride, colour);
  61448. edgeTable.iterate (renderer, 0, 0, cw, ch, 0);
  61449. }
  61450. else if (image.getFormat() == Image::ARGB)
  61451. {
  61452. jassert (pixelStride == 4);
  61453. SolidColourEdgeTableRenderer <PixelARGB> renderer (pixels, stride, colour);
  61454. edgeTable.iterate (renderer, 0, 0, cw, ch, 0);
  61455. }
  61456. else if (image.getFormat() == Image::SingleChannel)
  61457. {
  61458. jassert (pixelStride == 1);
  61459. AlphaBitmapRenderer renderer (pixels, stride);
  61460. edgeTable.iterate (renderer, 0, 0, cw, ch, 0);
  61461. }
  61462. image.releasePixelDataReadWrite (pixels);
  61463. }
  61464. }
  61465. void LowLevelGraphicsSoftwareRenderer::fillPathWithGradient (const Path& path, const AffineTransform& t, const ColourGradient& gradient, EdgeTable::OversamplingLevel quality)
  61466. {
  61467. for (RectangleList::Iterator i (*clip); i.next();)
  61468. {
  61469. const Rectangle& r = *i.getRectangle();
  61470. clippedFillPathWithGradient (r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  61471. path, t, gradient, quality);
  61472. }
  61473. }
  61474. void LowLevelGraphicsSoftwareRenderer::clippedFillPathWithGradient (int clipX, int clipY, int clipW, int clipH, const Path& path, const AffineTransform& t,
  61475. const ColourGradient& gradient, EdgeTable::OversamplingLevel quality)
  61476. {
  61477. const AffineTransform transform (t.translated ((float) xOffset, (float) yOffset));
  61478. int cx, cy, cw, ch;
  61479. if (getPathBounds (clipX, clipY, clipW, clipH, path, transform, cx, cy, cw, ch))
  61480. {
  61481. int stride, pixelStride;
  61482. uint8* const pixels = (uint8*) image.lockPixelDataReadWrite (cx, cy, cw, ch, stride, pixelStride);
  61483. ColourGradient g2 (gradient);
  61484. const bool isIdentity = g2.transform.isIdentity();
  61485. if (isIdentity)
  61486. {
  61487. g2.x1 += xOffset - cx;
  61488. g2.x2 += xOffset - cx;
  61489. g2.y1 += yOffset - cy;
  61490. g2.y2 += yOffset - cy;
  61491. }
  61492. else
  61493. {
  61494. g2.transform = g2.transform.translated ((float) (xOffset - cx),
  61495. (float) (yOffset - cy));
  61496. }
  61497. int numLookupEntries;
  61498. PixelARGB* const lookupTable = g2.createLookupTable (numLookupEntries);
  61499. jassert (numLookupEntries > 0);
  61500. EdgeTable edgeTable (0, ch, quality);
  61501. edgeTable.addPath (path, transform.translated ((float) -cx, (float) -cy));
  61502. if (image.getFormat() == Image::RGB)
  61503. {
  61504. jassert (pixelStride == 3);
  61505. if (g2.isRadial)
  61506. {
  61507. if (isIdentity)
  61508. {
  61509. GradientEdgeTableRenderer <PixelRGB, RadialGradientPixelGenerator> renderer (pixels, stride, g2, lookupTable, numLookupEntries);
  61510. edgeTable.iterate (renderer, 0, 0, cw, ch, 0);
  61511. }
  61512. else
  61513. {
  61514. GradientEdgeTableRenderer <PixelRGB, TransformedRadialGradientPixelGenerator> renderer (pixels, stride, g2, lookupTable, numLookupEntries);
  61515. edgeTable.iterate (renderer, 0, 0, cw, ch, 0);
  61516. }
  61517. }
  61518. else
  61519. {
  61520. GradientEdgeTableRenderer <PixelRGB, LinearGradientPixelGenerator> renderer (pixels, stride, g2, lookupTable, numLookupEntries);
  61521. edgeTable.iterate (renderer, 0, 0, cw, ch, 0);
  61522. }
  61523. }
  61524. else if (image.getFormat() == Image::ARGB)
  61525. {
  61526. jassert (pixelStride == 4);
  61527. if (g2.isRadial)
  61528. {
  61529. if (isIdentity)
  61530. {
  61531. GradientEdgeTableRenderer <PixelARGB, RadialGradientPixelGenerator> renderer (pixels, stride, g2, lookupTable, numLookupEntries);
  61532. edgeTable.iterate (renderer, 0, 0, cw, ch, 0);
  61533. }
  61534. else
  61535. {
  61536. GradientEdgeTableRenderer <PixelARGB, TransformedRadialGradientPixelGenerator> renderer (pixels, stride, g2, lookupTable, numLookupEntries);
  61537. edgeTable.iterate (renderer, 0, 0, cw, ch, 0);
  61538. }
  61539. }
  61540. else
  61541. {
  61542. GradientEdgeTableRenderer <PixelARGB, LinearGradientPixelGenerator> renderer (pixels, stride, g2, lookupTable, numLookupEntries);
  61543. edgeTable.iterate (renderer, 0, 0, cw, ch, 0);
  61544. }
  61545. }
  61546. else if (image.getFormat() == Image::SingleChannel)
  61547. {
  61548. jassertfalse // not done!
  61549. }
  61550. juce_free (lookupTable);
  61551. image.releasePixelDataReadWrite (pixels);
  61552. }
  61553. }
  61554. void LowLevelGraphicsSoftwareRenderer::fillPathWithImage (const Path& path, const AffineTransform& transform,
  61555. const Image& sourceImage, int imageX, int imageY, float opacity, EdgeTable::OversamplingLevel quality)
  61556. {
  61557. imageX += xOffset;
  61558. imageY += yOffset;
  61559. for (RectangleList::Iterator i (*clip); i.next();)
  61560. {
  61561. const Rectangle& r = *i.getRectangle();
  61562. clippedFillPathWithImage (r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  61563. path, transform, sourceImage, imageX, imageY, opacity, quality);
  61564. }
  61565. }
  61566. void LowLevelGraphicsSoftwareRenderer::clippedFillPathWithImage (int x, int y, int w, int h, const Path& path, const AffineTransform& transform,
  61567. const Image& sourceImage, int imageX, int imageY, float opacity, EdgeTable::OversamplingLevel quality)
  61568. {
  61569. if (Rectangle::intersectRectangles (x, y, w, h, imageX, imageY, sourceImage.getWidth(), sourceImage.getHeight()))
  61570. {
  61571. EdgeTable edgeTable (0, h, quality);
  61572. edgeTable.addPath (path, transform.translated ((float) (xOffset - x), (float) (yOffset - y)));
  61573. int stride, pixelStride;
  61574. uint8* const pixels = (uint8*) image.lockPixelDataReadWrite (x, y, w, h, stride, pixelStride);
  61575. int srcStride, srcPixelStride;
  61576. const uint8* const srcPix = (const uint8*) sourceImage.lockPixelDataReadOnly (x - imageX, y - imageY, w, h, srcStride, srcPixelStride);
  61577. const int alpha = jlimit (0, 255, roundDoubleToInt (opacity * 255.0f));
  61578. if (image.getFormat() == Image::RGB)
  61579. {
  61580. if (sourceImage.getFormat() == Image::RGB)
  61581. {
  61582. ImageFillEdgeTableRenderer <PixelRGB, PixelRGB> renderer (pixels, stride,
  61583. srcPix, srcStride,
  61584. alpha, (PixelRGB*) 0);
  61585. edgeTable.iterate (renderer, 0, 0, w, h, 0);
  61586. }
  61587. else if (sourceImage.getFormat() == Image::ARGB)
  61588. {
  61589. ImageFillEdgeTableRenderer <PixelRGB, PixelARGB> renderer (pixels, stride,
  61590. srcPix, srcStride,
  61591. alpha, (PixelARGB*) 0);
  61592. edgeTable.iterate (renderer, 0, 0, w, h, 0);
  61593. }
  61594. else
  61595. {
  61596. jassertfalse // not done!
  61597. }
  61598. }
  61599. else if (image.getFormat() == Image::ARGB)
  61600. {
  61601. if (sourceImage.getFormat() == Image::RGB)
  61602. {
  61603. ImageFillEdgeTableRenderer <PixelARGB, PixelRGB> renderer (pixels, stride,
  61604. srcPix, srcStride,
  61605. alpha, (PixelRGB*) 0);
  61606. edgeTable.iterate (renderer, 0, 0, w, h, 0);
  61607. }
  61608. else if (sourceImage.getFormat() == Image::ARGB)
  61609. {
  61610. ImageFillEdgeTableRenderer <PixelARGB, PixelARGB> renderer (pixels, stride,
  61611. srcPix, srcStride,
  61612. alpha, (PixelARGB*) 0);
  61613. edgeTable.iterate (renderer, 0, 0, w, h, 0);
  61614. }
  61615. else
  61616. {
  61617. jassertfalse // not done!
  61618. }
  61619. }
  61620. else
  61621. {
  61622. jassertfalse // not done!
  61623. }
  61624. sourceImage.releasePixelDataReadOnly (srcPix);
  61625. image.releasePixelDataReadWrite (pixels);
  61626. }
  61627. }
  61628. void LowLevelGraphicsSoftwareRenderer::fillAlphaChannelWithColour (const Image& clipImage, int x, int y, const Colour& colour)
  61629. {
  61630. x += xOffset;
  61631. y += yOffset;
  61632. for (RectangleList::Iterator i (*clip); i.next();)
  61633. {
  61634. const Rectangle& r = *i.getRectangle();
  61635. clippedFillAlphaChannelWithColour (r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  61636. clipImage, x, y, colour);
  61637. }
  61638. }
  61639. void LowLevelGraphicsSoftwareRenderer::clippedFillAlphaChannelWithColour (int clipX, int clipY, int clipW, int clipH, const Image& clipImage, int x, int y, const Colour& colour)
  61640. {
  61641. int w = clipImage.getWidth();
  61642. int h = clipImage.getHeight();
  61643. int sx = 0;
  61644. int sy = 0;
  61645. if (x < clipX)
  61646. {
  61647. sx = clipX - x;
  61648. w -= clipX - x;
  61649. x = clipX;
  61650. }
  61651. if (y < clipY)
  61652. {
  61653. sy = clipY - y;
  61654. h -= clipY - y;
  61655. y = clipY;
  61656. }
  61657. if (x + w > clipX + clipW)
  61658. w = clipX + clipW - x;
  61659. if (y + h > clipY + clipH)
  61660. h = clipY + clipH - y;
  61661. if (w > 0 && h > 0)
  61662. {
  61663. int stride, alphaStride, pixelStride;
  61664. uint8* const pixels = (uint8*) image.lockPixelDataReadWrite (x, y, w, h, stride, pixelStride);
  61665. const uint8* const alphaValues
  61666. = clipImage.lockPixelDataReadOnly (sx, sy, w, h, alphaStride, pixelStride);
  61667. #if JUCE_MAC
  61668. const uint8* const alphas = alphaValues;
  61669. #else
  61670. const uint8* const alphas = alphaValues + (clipImage.getFormat() == Image::ARGB ? 3 : 0);
  61671. #endif
  61672. if (image.getFormat() == Image::RGB)
  61673. {
  61674. blendAlphaMapRGB (pixels, stride,
  61675. alphas, w, h,
  61676. pixelStride, alphaStride,
  61677. colour);
  61678. }
  61679. else if (image.getFormat() == Image::ARGB)
  61680. {
  61681. blendAlphaMapARGB (pixels, stride,
  61682. alphas, w, h,
  61683. pixelStride, alphaStride,
  61684. colour);
  61685. }
  61686. else
  61687. {
  61688. jassertfalse // not done!
  61689. }
  61690. clipImage.releasePixelDataReadOnly (alphaValues);
  61691. image.releasePixelDataReadWrite (pixels);
  61692. }
  61693. }
  61694. void LowLevelGraphicsSoftwareRenderer::fillAlphaChannelWithGradient (const Image& alphaChannelImage, int imageX, int imageY, const ColourGradient& gradient)
  61695. {
  61696. imageX += xOffset;
  61697. imageY += yOffset;
  61698. for (RectangleList::Iterator i (*clip); i.next();)
  61699. {
  61700. const Rectangle& r = *i.getRectangle();
  61701. clippedFillAlphaChannelWithGradient (r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  61702. alphaChannelImage, imageX, imageY, gradient);
  61703. }
  61704. }
  61705. void LowLevelGraphicsSoftwareRenderer::clippedFillAlphaChannelWithGradient (int x, int y, int w, int h,
  61706. const Image& alphaChannelImage,
  61707. int imageX, int imageY, const ColourGradient& gradient)
  61708. {
  61709. if (Rectangle::intersectRectangles (x, y, w, h, imageX, imageY, alphaChannelImage.getWidth(), alphaChannelImage.getHeight()))
  61710. {
  61711. ColourGradient g2 (gradient);
  61712. g2.x1 += xOffset - x;
  61713. g2.x2 += xOffset - x;
  61714. g2.y1 += yOffset - y;
  61715. g2.y2 += yOffset - y;
  61716. Image temp (g2.isOpaque() ? Image::RGB : Image::ARGB, w, h, true);
  61717. LowLevelGraphicsSoftwareRenderer tempG (temp);
  61718. tempG.fillRectWithGradient (0, 0, w, h, g2);
  61719. clippedFillAlphaChannelWithImage (x, y, w, h,
  61720. alphaChannelImage, imageX, imageY,
  61721. temp, x, y, 1.0f);
  61722. }
  61723. }
  61724. void LowLevelGraphicsSoftwareRenderer::fillAlphaChannelWithImage (const Image& alphaImage, int alphaImageX, int alphaImageY,
  61725. const Image& fillerImage, int fillerImageX, int fillerImageY, float opacity)
  61726. {
  61727. alphaImageX += xOffset;
  61728. alphaImageY += yOffset;
  61729. fillerImageX += xOffset;
  61730. fillerImageY += yOffset;
  61731. for (RectangleList::Iterator i (*clip); i.next();)
  61732. {
  61733. const Rectangle& r = *i.getRectangle();
  61734. clippedFillAlphaChannelWithImage (r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  61735. alphaImage, alphaImageX, alphaImageY,
  61736. fillerImage, fillerImageX, fillerImageY, opacity);
  61737. }
  61738. }
  61739. void LowLevelGraphicsSoftwareRenderer::clippedFillAlphaChannelWithImage (int x, int y, int w, int h, const Image& alphaImage, int alphaImageX, int alphaImageY,
  61740. const Image& fillerImage, int fillerImageX, int fillerImageY, float opacity)
  61741. {
  61742. if (Rectangle::intersectRectangles (x, y, w, h, alphaImageX, alphaImageY, alphaImage.getWidth(), alphaImage.getHeight())
  61743. && Rectangle::intersectRectangles (x, y, w, h, fillerImageX, fillerImageY, fillerImage.getWidth(), fillerImage.getHeight()))
  61744. {
  61745. int dstStride, dstPixStride;
  61746. uint8* const dstPix = image.lockPixelDataReadWrite (x, y, w, h, dstStride, dstPixStride);
  61747. int srcStride, srcPixStride;
  61748. const uint8* const srcPix = fillerImage.lockPixelDataReadOnly (x - fillerImageX, y - fillerImageY, w, h, srcStride, srcPixStride);
  61749. int maskStride, maskPixStride;
  61750. const uint8* const alpha
  61751. = alphaImage.lockPixelDataReadOnly (x - alphaImageX, y - alphaImageY, w, h, maskStride, maskPixStride);
  61752. #if JUCE_MAC
  61753. const uint8* const alphaValues = alpha;
  61754. #else
  61755. const uint8* const alphaValues = alpha + (alphaImage.getFormat() == Image::ARGB ? 3 : 0);
  61756. #endif
  61757. const int extraAlpha = jlimit (0, 0x100, roundDoubleToInt (opacity * 256.0f));
  61758. if (image.getFormat() == Image::RGB)
  61759. {
  61760. if (fillerImage.getFormat() == Image::RGB)
  61761. {
  61762. renderAlphaMap ((PixelRGB*) dstPix, dstStride, (const PixelRGB*) srcPix, srcStride, alphaValues, maskStride, maskPixStride, w, h, extraAlpha);
  61763. }
  61764. else if (fillerImage.getFormat() == Image::ARGB)
  61765. {
  61766. renderAlphaMap ((PixelRGB*) dstPix, dstStride, (const PixelARGB*) srcPix, srcStride, alphaValues, maskStride, maskPixStride, w, h, extraAlpha);
  61767. }
  61768. else
  61769. {
  61770. jassertfalse // not done!
  61771. }
  61772. }
  61773. else if (image.getFormat() == Image::ARGB)
  61774. {
  61775. if (fillerImage.getFormat() == Image::RGB)
  61776. {
  61777. renderAlphaMap ((PixelARGB*) dstPix, dstStride, (const PixelRGB*) srcPix, srcStride, alphaValues, maskStride, maskPixStride, w, h, extraAlpha);
  61778. }
  61779. else if (fillerImage.getFormat() == Image::ARGB)
  61780. {
  61781. renderAlphaMap ((PixelARGB*) dstPix, dstStride, (const PixelARGB*) srcPix, srcStride, alphaValues, maskStride, maskPixStride, w, h, extraAlpha);
  61782. }
  61783. else
  61784. {
  61785. jassertfalse // not done!
  61786. }
  61787. }
  61788. else
  61789. {
  61790. jassertfalse // not done!
  61791. }
  61792. alphaImage.releasePixelDataReadOnly (alphaValues);
  61793. fillerImage.releasePixelDataReadOnly (srcPix);
  61794. image.releasePixelDataReadWrite (dstPix);
  61795. }
  61796. }
  61797. void LowLevelGraphicsSoftwareRenderer::blendImage (const Image& sourceImage, int dx, int dy, int dw, int dh, int sx, int sy, float opacity)
  61798. {
  61799. dx += xOffset;
  61800. dy += yOffset;
  61801. for (RectangleList::Iterator i (*clip); i.next();)
  61802. {
  61803. const Rectangle& r = *i.getRectangle();
  61804. clippedBlendImage (r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  61805. sourceImage, dx, dy, dw, dh, sx, sy, opacity);
  61806. }
  61807. }
  61808. void LowLevelGraphicsSoftwareRenderer::clippedBlendImage (int clipX, int clipY, int clipW, int clipH,
  61809. const Image& sourceImage, int dx, int dy, int dw, int dh, int sx, int sy, float opacity)
  61810. {
  61811. if (dx < clipX)
  61812. {
  61813. sx += clipX - dx;
  61814. dw -= clipX - dx;
  61815. dx = clipX;
  61816. }
  61817. if (dy < clipY)
  61818. {
  61819. sy += clipY - dy;
  61820. dh -= clipY - dy;
  61821. dy = clipY;
  61822. }
  61823. if (dx + dw > clipX + clipW)
  61824. dw = clipX + clipW - dx;
  61825. if (dy + dh > clipY + clipH)
  61826. dh = clipY + clipH - dy;
  61827. if (dw <= 0 || dh <= 0)
  61828. return;
  61829. const uint8 alpha = (uint8) jlimit (0, 0xff, roundDoubleToInt (opacity * 256.0f));
  61830. if (alpha == 0)
  61831. return;
  61832. int dstStride, dstPixelStride;
  61833. uint8* const dstPixels = image.lockPixelDataReadWrite (dx, dy, dw, dh, dstStride, dstPixelStride);
  61834. int srcStride, srcPixelStride;
  61835. const uint8* const srcPixels = sourceImage.lockPixelDataReadOnly (sx, sy, dw, dh, srcStride, srcPixelStride);
  61836. if (image.getFormat() == Image::ARGB)
  61837. {
  61838. if (sourceImage.getFormat() == Image::ARGB)
  61839. {
  61840. overlayImage ((PixelARGB*) dstPixels, dstStride,
  61841. (PixelARGB*) srcPixels, srcStride,
  61842. dw, dh, alpha);
  61843. }
  61844. else if (sourceImage.getFormat() == Image::RGB)
  61845. {
  61846. overlayImage ((PixelARGB*) dstPixels, dstStride,
  61847. (PixelRGB*) srcPixels, srcStride,
  61848. dw, dh, alpha);
  61849. }
  61850. else
  61851. {
  61852. jassertfalse
  61853. }
  61854. }
  61855. else if (image.getFormat() == Image::RGB)
  61856. {
  61857. if (sourceImage.getFormat() == Image::ARGB)
  61858. {
  61859. overlayImage ((PixelRGB*) dstPixels, dstStride,
  61860. (PixelARGB*) srcPixels, srcStride,
  61861. dw, dh, alpha);
  61862. }
  61863. else if (sourceImage.getFormat() == Image::RGB)
  61864. {
  61865. overlayImage ((PixelRGB*) dstPixels, dstStride,
  61866. (PixelRGB*) srcPixels, srcStride,
  61867. dw, dh, alpha);
  61868. }
  61869. else
  61870. {
  61871. jassertfalse
  61872. }
  61873. }
  61874. else
  61875. {
  61876. jassertfalse
  61877. }
  61878. image.releasePixelDataReadWrite (dstPixels);
  61879. sourceImage.releasePixelDataReadOnly (srcPixels);
  61880. }
  61881. void LowLevelGraphicsSoftwareRenderer::blendImageRescaling (const Image& sourceImage,
  61882. int dx, int dy, int dw, int dh,
  61883. int sx, int sy, int sw, int sh,
  61884. float alpha,
  61885. const Graphics::ResamplingQuality quality)
  61886. {
  61887. if (sw > 0 && sh > 0)
  61888. {
  61889. if (sw == dw && sh == dh)
  61890. {
  61891. blendImage (sourceImage,
  61892. dx, dy, dw, dh,
  61893. sx, sy, alpha);
  61894. }
  61895. else
  61896. {
  61897. blendImageWarping (sourceImage,
  61898. sx, sy, sw, sh,
  61899. AffineTransform::translation ((float) -sx,
  61900. (float) -sy)
  61901. .scaled (dw / (float) sw,
  61902. dh / (float) sh)
  61903. .translated ((float) dx,
  61904. (float) dy),
  61905. alpha,
  61906. quality);
  61907. }
  61908. }
  61909. }
  61910. void LowLevelGraphicsSoftwareRenderer::blendImageWarping (const Image& sourceImage,
  61911. int srcClipX, int srcClipY, int srcClipW, int srcClipH,
  61912. const AffineTransform& t,
  61913. float opacity,
  61914. const Graphics::ResamplingQuality quality)
  61915. {
  61916. const AffineTransform transform (t.translated ((float) xOffset, (float) yOffset));
  61917. for (RectangleList::Iterator i (*clip); i.next();)
  61918. {
  61919. const Rectangle& r = *i.getRectangle();
  61920. clippedBlendImageWarping (r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  61921. sourceImage, srcClipX, srcClipY, srcClipW, srcClipH,
  61922. transform, opacity, quality);
  61923. }
  61924. }
  61925. void LowLevelGraphicsSoftwareRenderer::clippedBlendImageWarping (int destClipX, int destClipY, int destClipW, int destClipH,
  61926. const Image& sourceImage,
  61927. int srcClipX, int srcClipY, int srcClipW, int srcClipH,
  61928. const AffineTransform& transform,
  61929. float opacity,
  61930. const Graphics::ResamplingQuality quality)
  61931. {
  61932. if (opacity > 0 && destClipW > 0 && destClipH > 0 && ! transform.isSingularity())
  61933. {
  61934. Rectangle::intersectRectangles (srcClipX, srcClipY, srcClipW, srcClipH,
  61935. 0, 0, sourceImage.getWidth(), sourceImage.getHeight());
  61936. if (srcClipW <= 0 || srcClipH <= 0)
  61937. return;
  61938. jassert (srcClipX >= 0 && srcClipY >= 0);
  61939. Path imageBounds;
  61940. imageBounds.addRectangle ((float) srcClipX, (float) srcClipY, (float) srcClipW, (float) srcClipH);
  61941. imageBounds.applyTransform (transform);
  61942. float imX, imY, imW, imH;
  61943. imageBounds.getBounds (imX, imY, imW, imH);
  61944. if (Rectangle::intersectRectangles (destClipX, destClipY, destClipW, destClipH,
  61945. (int) floorf (imX),
  61946. (int) floorf (imY),
  61947. 1 + roundDoubleToInt (imW),
  61948. 1 + roundDoubleToInt (imH)))
  61949. {
  61950. const uint8 alpha = (uint8) jlimit (0, 0xff, roundDoubleToInt (opacity * 256.0f));
  61951. float srcX1 = (float) destClipX;
  61952. float srcY1 = (float) destClipY;
  61953. float srcX2 = (float) (destClipX + destClipW);
  61954. float srcY2 = srcY1;
  61955. float srcX3 = srcX1;
  61956. float srcY3 = (float) (destClipY + destClipH);
  61957. AffineTransform inverse (transform.inverted());
  61958. inverse.transformPoint (srcX1, srcY1);
  61959. inverse.transformPoint (srcX2, srcY2);
  61960. inverse.transformPoint (srcX3, srcY3);
  61961. const double lineDX = (double) (srcX3 - srcX1) / destClipH;
  61962. const double lineDY = (double) (srcY3 - srcY1) / destClipH;
  61963. const double pixelDX = (double) (srcX2 - srcX1) / destClipW;
  61964. const double pixelDY = (double) (srcY2 - srcY1) / destClipW;
  61965. if (image.getFormat() == Image::ARGB)
  61966. {
  61967. if (sourceImage.getFormat() == Image::ARGB)
  61968. {
  61969. transformedImageRender (image, sourceImage,
  61970. destClipX, destClipY, destClipW, destClipH,
  61971. srcClipX, srcClipY, srcClipW, srcClipH,
  61972. srcX1, srcY1, lineDX, lineDY, pixelDX, pixelDY,
  61973. alpha, quality, (PixelARGB*)0, (PixelARGB*)0);
  61974. }
  61975. else if (sourceImage.getFormat() == Image::RGB)
  61976. {
  61977. transformedImageRender (image, sourceImage,
  61978. destClipX, destClipY, destClipW, destClipH,
  61979. srcClipX, srcClipY, srcClipW, srcClipH,
  61980. srcX1, srcY1, lineDX, lineDY, pixelDX, pixelDY,
  61981. alpha, quality, (PixelARGB*)0, (PixelRGB*)0);
  61982. }
  61983. else
  61984. {
  61985. jassertfalse
  61986. }
  61987. }
  61988. else if (image.getFormat() == Image::RGB)
  61989. {
  61990. if (sourceImage.getFormat() == Image::ARGB)
  61991. {
  61992. transformedImageRender (image, sourceImage,
  61993. destClipX, destClipY, destClipW, destClipH,
  61994. srcClipX, srcClipY, srcClipW, srcClipH,
  61995. srcX1, srcY1, lineDX, lineDY, pixelDX, pixelDY,
  61996. alpha, quality, (PixelRGB*)0, (PixelARGB*)0);
  61997. }
  61998. else if (sourceImage.getFormat() == Image::RGB)
  61999. {
  62000. transformedImageRender (image, sourceImage,
  62001. destClipX, destClipY, destClipW, destClipH,
  62002. srcClipX, srcClipY, srcClipW, srcClipH,
  62003. srcX1, srcY1, lineDX, lineDY, pixelDX, pixelDY,
  62004. alpha, quality, (PixelRGB*)0, (PixelRGB*)0);
  62005. }
  62006. else
  62007. {
  62008. jassertfalse
  62009. }
  62010. }
  62011. else
  62012. {
  62013. jassertfalse
  62014. }
  62015. }
  62016. }
  62017. }
  62018. void LowLevelGraphicsSoftwareRenderer::drawLine (double x1, double y1, double x2, double y2, const Colour& colour)
  62019. {
  62020. x1 += xOffset;
  62021. y1 += yOffset;
  62022. x2 += xOffset;
  62023. y2 += yOffset;
  62024. for (RectangleList::Iterator i (*clip); i.next();)
  62025. {
  62026. const Rectangle& r = *i.getRectangle();
  62027. clippedDrawLine (r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  62028. x1, y1, x2, y2, colour);
  62029. }
  62030. }
  62031. void LowLevelGraphicsSoftwareRenderer::clippedDrawLine (int clipX, int clipY, int clipW, int clipH, double x1, double y1, double x2, double y2, const Colour& colour)
  62032. {
  62033. if (clipW > 0 && clipH > 0)
  62034. {
  62035. if (x1 == x2)
  62036. {
  62037. if (y2 < y1)
  62038. swapVariables (y1, y2);
  62039. clippedDrawVerticalLine (clipX, clipY, clipW, clipH, roundDoubleToInt (x1), y1, y2, colour);
  62040. }
  62041. else if (y1 == y2)
  62042. {
  62043. if (x2 < x1)
  62044. swapVariables (x1, x2);
  62045. clippedDrawHorizontalLine (clipX, clipY, clipW, clipH, roundDoubleToInt (y1), x1, x2, colour);
  62046. }
  62047. else
  62048. {
  62049. double gradient = (y2 - y1) / (x2 - x1);
  62050. if (fabs (gradient) > 1.0)
  62051. {
  62052. gradient = 1.0 / gradient;
  62053. int y = roundDoubleToInt (y1);
  62054. const int startY = y;
  62055. int endY = roundDoubleToInt (y2);
  62056. if (y > endY)
  62057. swapVariables (y, endY);
  62058. while (y < endY)
  62059. {
  62060. const double x = x1 + gradient * (y - startY);
  62061. clippedDrawHorizontalLine (clipX, clipY, clipW, clipH, y, x, x + 1.0, colour);
  62062. ++y;
  62063. }
  62064. }
  62065. else
  62066. {
  62067. int x = roundDoubleToInt (x1);
  62068. const int startX = x;
  62069. int endX = roundDoubleToInt (x2);
  62070. if (x > endX)
  62071. swapVariables (x, endX);
  62072. while (x < endX)
  62073. {
  62074. const double y = y1 + gradient * (x - startX);
  62075. clippedDrawVerticalLine (clipX, clipY, clipW, clipH, x, y, y + 1.0, colour);
  62076. ++x;
  62077. }
  62078. }
  62079. }
  62080. }
  62081. }
  62082. void LowLevelGraphicsSoftwareRenderer::drawVerticalLine (const int x, double top, double bottom, const Colour& col)
  62083. {
  62084. for (RectangleList::Iterator i (*clip); i.next();)
  62085. {
  62086. const Rectangle& r = *i.getRectangle();
  62087. clippedDrawVerticalLine (r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  62088. x + xOffset, top + yOffset, bottom + yOffset, col);
  62089. }
  62090. }
  62091. void LowLevelGraphicsSoftwareRenderer::clippedDrawVerticalLine (int clipX, int clipY, int clipW, int clipH,
  62092. const int x, double top, double bottom, const Colour& col)
  62093. {
  62094. jassert (top <= bottom);
  62095. if (((unsigned int) (x - clipX)) < (unsigned int) clipW
  62096. && top < clipY + clipH
  62097. && bottom > clipY
  62098. && clipW > 0)
  62099. {
  62100. if (top < clipY)
  62101. top = clipY;
  62102. if (bottom > clipY + clipH)
  62103. bottom = clipY + clipH;
  62104. if (bottom > top)
  62105. drawVertical (x, top, bottom, col);
  62106. }
  62107. }
  62108. void LowLevelGraphicsSoftwareRenderer::drawHorizontalLine (const int y, double left, double right, const Colour& col)
  62109. {
  62110. for (RectangleList::Iterator i (*clip); i.next();)
  62111. {
  62112. const Rectangle& r = *i.getRectangle();
  62113. clippedDrawHorizontalLine (r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  62114. y + yOffset, left + xOffset, right + xOffset, col);
  62115. }
  62116. }
  62117. void LowLevelGraphicsSoftwareRenderer::clippedDrawHorizontalLine (int clipX, int clipY, int clipW, int clipH,
  62118. const int y, double left, double right, const Colour& col)
  62119. {
  62120. jassert (left <= right);
  62121. if (((unsigned int) (y - clipY)) < (unsigned int) clipH
  62122. && left < clipX + clipW
  62123. && right > clipX
  62124. && clipW > 0)
  62125. {
  62126. if (left < clipX)
  62127. left = clipX;
  62128. if (right > clipX + clipW)
  62129. right = clipX + clipW;
  62130. if (right > left)
  62131. drawHorizontal (y, left, right, col);
  62132. }
  62133. }
  62134. void LowLevelGraphicsSoftwareRenderer::drawVertical (const int x,
  62135. const double top,
  62136. const double bottom,
  62137. const Colour& col)
  62138. {
  62139. int wholeStart = (int) top;
  62140. const int wholeEnd = (int) bottom;
  62141. const int lastAlpha = roundDoubleToInt (255.0 * (bottom - wholeEnd));
  62142. const int totalPixels = (wholeEnd - wholeStart) + (lastAlpha > 0 ? 1 : 0);
  62143. if (totalPixels <= 0)
  62144. return;
  62145. int lineStride, dstPixelStride;
  62146. uint8* const dstPixels = image.lockPixelDataReadWrite (x, wholeStart, 1, totalPixels, lineStride, dstPixelStride);
  62147. uint8* dest = dstPixels;
  62148. PixelARGB colour (col.getPixelARGB());
  62149. if (wholeEnd == wholeStart)
  62150. {
  62151. if (image.getFormat() == Image::ARGB)
  62152. ((PixelARGB*) dest)->blend (colour, roundDoubleToInt (255.0 * (bottom - top)));
  62153. else if (image.getFormat() == Image::RGB)
  62154. ((PixelRGB*) dest)->blend (colour, roundDoubleToInt (255.0 * (bottom - top)));
  62155. else
  62156. {
  62157. jassertfalse
  62158. }
  62159. }
  62160. else
  62161. {
  62162. if (image.getFormat() == Image::ARGB)
  62163. {
  62164. ((PixelARGB*) dest)->blend (colour, roundDoubleToInt (255.0 * (1.0 - (top - wholeStart))));
  62165. ++wholeStart;
  62166. dest += lineStride;
  62167. if (colour.getAlpha() == 0xff)
  62168. {
  62169. while (wholeEnd > wholeStart)
  62170. {
  62171. ((PixelARGB*) dest)->set (colour);
  62172. ++wholeStart;
  62173. dest += lineStride;
  62174. }
  62175. }
  62176. else
  62177. {
  62178. while (wholeEnd > wholeStart)
  62179. {
  62180. ((PixelARGB*) dest)->blend (colour);
  62181. ++wholeStart;
  62182. dest += lineStride;
  62183. }
  62184. }
  62185. if (lastAlpha > 0)
  62186. {
  62187. ((PixelARGB*) dest)->blend (colour, lastAlpha);
  62188. }
  62189. }
  62190. else if (image.getFormat() == Image::RGB)
  62191. {
  62192. ((PixelRGB*) dest)->blend (colour, roundDoubleToInt (255.0 * (1.0 - (top - wholeStart))));
  62193. ++wholeStart;
  62194. dest += lineStride;
  62195. if (colour.getAlpha() == 0xff)
  62196. {
  62197. while (wholeEnd > wholeStart)
  62198. {
  62199. ((PixelRGB*) dest)->set (colour);
  62200. ++wholeStart;
  62201. dest += lineStride;
  62202. }
  62203. }
  62204. else
  62205. {
  62206. while (wholeEnd > wholeStart)
  62207. {
  62208. ((PixelRGB*) dest)->blend (colour);
  62209. ++wholeStart;
  62210. dest += lineStride;
  62211. }
  62212. }
  62213. if (lastAlpha > 0)
  62214. {
  62215. ((PixelRGB*) dest)->blend (colour, lastAlpha);
  62216. }
  62217. }
  62218. else
  62219. {
  62220. jassertfalse
  62221. }
  62222. }
  62223. image.releasePixelDataReadWrite (dstPixels);
  62224. }
  62225. void LowLevelGraphicsSoftwareRenderer::drawHorizontal (const int y,
  62226. const double top,
  62227. const double bottom,
  62228. const Colour& col)
  62229. {
  62230. int wholeStart = (int) top;
  62231. const int wholeEnd = (int) bottom;
  62232. const int lastAlpha = roundDoubleToInt (255.0 * (bottom - wholeEnd));
  62233. const int totalPixels = (wholeEnd - wholeStart) + (lastAlpha > 0 ? 1 : 0);
  62234. if (totalPixels <= 0)
  62235. return;
  62236. int lineStride, dstPixelStride;
  62237. uint8* const dstPixels = image.lockPixelDataReadWrite (wholeStart, y, totalPixels, 1, lineStride, dstPixelStride);
  62238. uint8* dest = dstPixels;
  62239. PixelARGB colour (col.getPixelARGB());
  62240. if (wholeEnd == wholeStart)
  62241. {
  62242. if (image.getFormat() == Image::ARGB)
  62243. ((PixelARGB*) dest)->blend (colour, roundDoubleToInt (255.0 * (bottom - top)));
  62244. else if (image.getFormat() == Image::RGB)
  62245. ((PixelRGB*) dest)->blend (colour, roundDoubleToInt (255.0 * (bottom - top)));
  62246. else
  62247. {
  62248. jassertfalse
  62249. }
  62250. }
  62251. else
  62252. {
  62253. if (image.getFormat() == Image::ARGB)
  62254. {
  62255. ((PixelARGB*) dest)->blend (colour, roundDoubleToInt (255.0 * (1.0 - (top - wholeStart))));
  62256. dest += dstPixelStride;
  62257. ++wholeStart;
  62258. if (colour.getAlpha() == 0xff)
  62259. {
  62260. while (wholeEnd > wholeStart)
  62261. {
  62262. ((PixelARGB*) dest)->set (colour);
  62263. dest += dstPixelStride;
  62264. ++wholeStart;
  62265. }
  62266. }
  62267. else
  62268. {
  62269. while (wholeEnd > wholeStart)
  62270. {
  62271. ((PixelARGB*) dest)->blend (colour);
  62272. dest += dstPixelStride;
  62273. ++wholeStart;
  62274. }
  62275. }
  62276. if (lastAlpha > 0)
  62277. {
  62278. ((PixelARGB*) dest)->blend (colour, lastAlpha);
  62279. }
  62280. }
  62281. else if (image.getFormat() == Image::RGB)
  62282. {
  62283. ((PixelRGB*) dest)->blend (colour, roundDoubleToInt (255.0 * (1.0 - (top - wholeStart))));
  62284. dest += dstPixelStride;
  62285. ++wholeStart;
  62286. if (colour.getAlpha() == 0xff)
  62287. {
  62288. while (wholeEnd > wholeStart)
  62289. {
  62290. ((PixelRGB*) dest)->set (colour);
  62291. dest += dstPixelStride;
  62292. ++wholeStart;
  62293. }
  62294. }
  62295. else
  62296. {
  62297. while (wholeEnd > wholeStart)
  62298. {
  62299. ((PixelRGB*) dest)->blend (colour);
  62300. dest += dstPixelStride;
  62301. ++wholeStart;
  62302. }
  62303. }
  62304. if (lastAlpha > 0)
  62305. {
  62306. ((PixelRGB*) dest)->blend (colour, lastAlpha);
  62307. }
  62308. }
  62309. else
  62310. {
  62311. jassertfalse
  62312. }
  62313. }
  62314. image.releasePixelDataReadWrite (dstPixels);
  62315. }
  62316. END_JUCE_NAMESPACE
  62317. /********* End of inlined file: juce_LowLevelGraphicsSoftwareRenderer.cpp *********/
  62318. /********* Start of inlined file: juce_RectanglePlacement.cpp *********/
  62319. BEGIN_JUCE_NAMESPACE
  62320. RectanglePlacement::RectanglePlacement (const RectanglePlacement& other) throw()
  62321. : flags (other.flags)
  62322. {
  62323. }
  62324. const RectanglePlacement& RectanglePlacement::operator= (const RectanglePlacement& other) throw()
  62325. {
  62326. flags = other.flags;
  62327. return *this;
  62328. }
  62329. void RectanglePlacement::applyTo (double& x, double& y,
  62330. double& w, double& h,
  62331. const double dx, const double dy,
  62332. const double dw, const double dh) const throw()
  62333. {
  62334. if (w == 0 || h == 0)
  62335. return;
  62336. if ((flags & stretchToFit) != 0)
  62337. {
  62338. x = dx;
  62339. y = dy;
  62340. w = dw;
  62341. h = dh;
  62342. }
  62343. else
  62344. {
  62345. double scale = (flags & fillDestination) != 0 ? jmax (dw / w, dh / h)
  62346. : jmin (dw / w, dh / h);
  62347. if ((flags & onlyReduceInSize) != 0)
  62348. scale = jmin (scale, 1.0);
  62349. if ((flags & onlyIncreaseInSize) != 0)
  62350. scale = jmax (scale, 1.0);
  62351. w *= scale;
  62352. h *= scale;
  62353. if ((flags & xLeft) != 0)
  62354. x = dx;
  62355. else if ((flags & xRight) != 0)
  62356. x = dx + dw - w;
  62357. else
  62358. x = dx + (dw - w) * 0.5;
  62359. if ((flags & yTop) != 0)
  62360. y = dy;
  62361. else if ((flags & yBottom) != 0)
  62362. y = dy + dh - h;
  62363. else
  62364. y = dy + (dh - h) * 0.5;
  62365. }
  62366. }
  62367. const AffineTransform RectanglePlacement::getTransformToFit (float x, float y,
  62368. float w, float h,
  62369. const float dx, const float dy,
  62370. const float dw, const float dh) const throw()
  62371. {
  62372. if (w == 0 || h == 0)
  62373. return AffineTransform::identity;
  62374. const float scaleX = dw / w;
  62375. const float scaleY = dh / h;
  62376. if ((flags & stretchToFit) != 0)
  62377. {
  62378. return AffineTransform::translation (-x, -y)
  62379. .scaled (scaleX, scaleY)
  62380. .translated (dx - x, dy - y);
  62381. }
  62382. float scale = (flags & fillDestination) != 0 ? jmax (scaleX, scaleY)
  62383. : jmin (scaleX, scaleY);
  62384. if ((flags & onlyReduceInSize) != 0)
  62385. scale = jmin (scale, 1.0f);
  62386. if ((flags & onlyIncreaseInSize) != 0)
  62387. scale = jmax (scale, 1.0f);
  62388. w *= scale;
  62389. h *= scale;
  62390. float newX = dx;
  62391. if ((flags & xRight) != 0)
  62392. newX += dw - w; // right
  62393. else if ((flags & xLeft) == 0)
  62394. newX += (dw - w) / 2.0f; // centre
  62395. float newY = dy;
  62396. if ((flags & yBottom) != 0)
  62397. newY += dh - h; // bottom
  62398. else if ((flags & yTop) == 0)
  62399. newY += (dh - h) / 2.0f; // centre
  62400. return AffineTransform::translation (-x, -y)
  62401. .scaled (scale, scale)
  62402. .translated (newX, newY);
  62403. }
  62404. END_JUCE_NAMESPACE
  62405. /********* End of inlined file: juce_RectanglePlacement.cpp *********/
  62406. /********* Start of inlined file: juce_Drawable.cpp *********/
  62407. BEGIN_JUCE_NAMESPACE
  62408. Drawable::Drawable()
  62409. {
  62410. }
  62411. Drawable::~Drawable()
  62412. {
  62413. }
  62414. void Drawable::drawAt (Graphics& g, const float x, const float y) const
  62415. {
  62416. draw (g, AffineTransform::translation (x, y));
  62417. }
  62418. void Drawable::drawWithin (Graphics& g,
  62419. const int destX,
  62420. const int destY,
  62421. const int destW,
  62422. const int destH,
  62423. const RectanglePlacement& placement) const
  62424. {
  62425. if (destW > 0 && destH > 0)
  62426. {
  62427. float x, y, w, h;
  62428. getBounds (x, y, w, h);
  62429. draw (g, placement.getTransformToFit (x, y, w, h,
  62430. (float) destX, (float) destY,
  62431. (float) destW, (float) destH));
  62432. }
  62433. }
  62434. Drawable* Drawable::createFromImageData (const void* data, const int numBytes)
  62435. {
  62436. Drawable* result = 0;
  62437. Image* const image = ImageFileFormat::loadFrom (data, numBytes);
  62438. if (image != 0)
  62439. {
  62440. DrawableImage* const di = new DrawableImage();
  62441. di->setImage (image, true);
  62442. result = di;
  62443. }
  62444. else
  62445. {
  62446. const String asString (String::createStringFromData (data, numBytes));
  62447. XmlDocument doc (asString);
  62448. XmlElement* const outer = doc.getDocumentElement (true);
  62449. if (outer != 0 && outer->hasTagName (T("svg")))
  62450. {
  62451. XmlElement* const svg = doc.getDocumentElement();
  62452. if (svg != 0)
  62453. {
  62454. result = Drawable::createFromSVG (*svg);
  62455. delete svg;
  62456. }
  62457. }
  62458. delete outer;
  62459. }
  62460. return result;
  62461. }
  62462. Drawable* Drawable::createFromImageDataStream (InputStream& dataSource)
  62463. {
  62464. MemoryBlock mb;
  62465. dataSource.readIntoMemoryBlock (mb);
  62466. return createFromImageData (mb.getData(), mb.getSize());
  62467. }
  62468. Drawable* Drawable::createFromImageFile (const File& file)
  62469. {
  62470. FileInputStream* fin = file.createInputStream();
  62471. if (fin == 0)
  62472. return 0;
  62473. Drawable* d = createFromImageDataStream (*fin);
  62474. delete fin;
  62475. return d;
  62476. }
  62477. END_JUCE_NAMESPACE
  62478. /********* End of inlined file: juce_Drawable.cpp *********/
  62479. /********* Start of inlined file: juce_DrawableComposite.cpp *********/
  62480. BEGIN_JUCE_NAMESPACE
  62481. DrawableComposite::DrawableComposite()
  62482. {
  62483. }
  62484. DrawableComposite::~DrawableComposite()
  62485. {
  62486. }
  62487. void DrawableComposite::insertDrawable (Drawable* drawable,
  62488. const AffineTransform& transform,
  62489. const int index)
  62490. {
  62491. if (drawable != 0)
  62492. {
  62493. if (! drawables.contains (drawable))
  62494. {
  62495. drawables.insert (index, drawable);
  62496. if (transform.isIdentity())
  62497. transforms.insert (index, 0);
  62498. else
  62499. transforms.insert (index, new AffineTransform (transform));
  62500. }
  62501. else
  62502. {
  62503. jassertfalse // trying to add a drawable that's already in here!
  62504. }
  62505. }
  62506. }
  62507. void DrawableComposite::insertDrawable (const Drawable& drawable,
  62508. const AffineTransform& transform,
  62509. const int index)
  62510. {
  62511. insertDrawable (drawable.createCopy(), transform, index);
  62512. }
  62513. void DrawableComposite::removeDrawable (const int index)
  62514. {
  62515. drawables.remove (index);
  62516. transforms.remove (index);
  62517. }
  62518. void DrawableComposite::bringToFront (const int index)
  62519. {
  62520. if (index >= 0 && index < drawables.size() - 1)
  62521. {
  62522. drawables.move (index, -1);
  62523. transforms.move (index, -1);
  62524. }
  62525. }
  62526. void DrawableComposite::draw (Graphics& g, const AffineTransform& transform) const
  62527. {
  62528. for (int i = 0; i < drawables.size(); ++i)
  62529. {
  62530. const AffineTransform* const t = transforms.getUnchecked(i);
  62531. drawables.getUnchecked(i)->draw (g, t == 0 ? transform
  62532. : t->followedBy (transform));
  62533. }
  62534. }
  62535. void DrawableComposite::getBounds (float& x, float& y, float& width, float& height) const
  62536. {
  62537. Path totalPath;
  62538. for (int i = 0; i < drawables.size(); ++i)
  62539. {
  62540. drawables.getUnchecked(i)->getBounds (x, y, width, height);
  62541. if (width > 0.0f && height > 0.0f)
  62542. {
  62543. Path outline;
  62544. outline.addRectangle (x, y, width, height);
  62545. const AffineTransform* const t = transforms.getUnchecked(i);
  62546. if (t == 0)
  62547. totalPath.addPath (outline);
  62548. else
  62549. totalPath.addPath (outline, *t);
  62550. }
  62551. }
  62552. totalPath.getBounds (x, y, width, height);
  62553. }
  62554. bool DrawableComposite::hitTest (float x, float y) const
  62555. {
  62556. for (int i = 0; i < drawables.size(); ++i)
  62557. {
  62558. float tx = x;
  62559. float ty = y;
  62560. const AffineTransform* const t = transforms.getUnchecked(i);
  62561. if (t != 0)
  62562. t->inverted().transformPoint (tx, ty);
  62563. if (drawables.getUnchecked(i)->hitTest (tx, ty))
  62564. return true;
  62565. }
  62566. return false;
  62567. }
  62568. Drawable* DrawableComposite::createCopy() const
  62569. {
  62570. DrawableComposite* const dc = new DrawableComposite();
  62571. for (int i = 0; i < drawables.size(); ++i)
  62572. {
  62573. dc->drawables.add (drawables.getUnchecked(i)->createCopy());
  62574. const AffineTransform* const t = transforms.getUnchecked(i);
  62575. dc->transforms.add (t != 0 ? new AffineTransform (*t) : 0);
  62576. }
  62577. return dc;
  62578. }
  62579. END_JUCE_NAMESPACE
  62580. /********* End of inlined file: juce_DrawableComposite.cpp *********/
  62581. /********* Start of inlined file: juce_DrawableImage.cpp *********/
  62582. BEGIN_JUCE_NAMESPACE
  62583. DrawableImage::DrawableImage()
  62584. : image (0),
  62585. canDeleteImage (false),
  62586. opacity (1.0f),
  62587. overlayColour (0x00000000)
  62588. {
  62589. }
  62590. DrawableImage::~DrawableImage()
  62591. {
  62592. clearImage();
  62593. }
  62594. void DrawableImage::clearImage()
  62595. {
  62596. if (canDeleteImage && image != 0)
  62597. {
  62598. if (ImageCache::isImageInCache (image))
  62599. ImageCache::release (image);
  62600. else
  62601. delete image;
  62602. }
  62603. image = 0;
  62604. }
  62605. void DrawableImage::setImage (const Image& imageToCopy)
  62606. {
  62607. clearImage();
  62608. image = new Image (imageToCopy);
  62609. canDeleteImage = true;
  62610. }
  62611. void DrawableImage::setImage (Image* imageToUse,
  62612. const bool releaseWhenNotNeeded)
  62613. {
  62614. clearImage();
  62615. image = imageToUse;
  62616. canDeleteImage = releaseWhenNotNeeded;
  62617. }
  62618. void DrawableImage::setOpacity (const float newOpacity)
  62619. {
  62620. opacity = newOpacity;
  62621. }
  62622. void DrawableImage::setOverlayColour (const Colour& newOverlayColour)
  62623. {
  62624. overlayColour = newOverlayColour;
  62625. }
  62626. void DrawableImage::draw (Graphics& g, const AffineTransform& transform) const
  62627. {
  62628. if (image != 0)
  62629. {
  62630. const Colour oldColour (g.getCurrentColour()); // save this so we can restore it later
  62631. if (opacity > 0.0f && ! overlayColour.isOpaque())
  62632. {
  62633. g.setColour (oldColour.withMultipliedAlpha (opacity));
  62634. g.drawImageTransformed (image,
  62635. 0, 0, image->getWidth(), image->getHeight(),
  62636. transform, false);
  62637. }
  62638. if (! overlayColour.isTransparent())
  62639. {
  62640. g.setColour (overlayColour.withMultipliedAlpha (oldColour.getFloatAlpha()));
  62641. g.drawImageTransformed (image,
  62642. 0, 0, image->getWidth(), image->getHeight(),
  62643. transform, true);
  62644. }
  62645. g.setColour (oldColour);
  62646. }
  62647. }
  62648. void DrawableImage::getBounds (float& x, float& y, float& width, float& height) const
  62649. {
  62650. x = 0.0f;
  62651. y = 0.0f;
  62652. width = 0.0f;
  62653. height = 0.0f;
  62654. if (image != 0)
  62655. {
  62656. width = (float) image->getWidth();
  62657. height = (float) image->getHeight();
  62658. }
  62659. }
  62660. bool DrawableImage::hitTest (float x, float y) const
  62661. {
  62662. return image != 0
  62663. && x >= 0.0f
  62664. && y >= 0.0f
  62665. && x < image->getWidth()
  62666. && y < image->getHeight()
  62667. && image->getPixelAt (roundFloatToInt (x), roundFloatToInt (y)).getAlpha() >= 127;
  62668. }
  62669. Drawable* DrawableImage::createCopy() const
  62670. {
  62671. DrawableImage* const di = new DrawableImage();
  62672. di->opacity = opacity;
  62673. di->overlayColour = overlayColour;
  62674. if (image != 0)
  62675. {
  62676. if ((! canDeleteImage) || ! ImageCache::isImageInCache (image))
  62677. {
  62678. di->setImage (*image);
  62679. }
  62680. else
  62681. {
  62682. ImageCache::incReferenceCount (image);
  62683. di->setImage (image, true);
  62684. }
  62685. }
  62686. return di;
  62687. }
  62688. END_JUCE_NAMESPACE
  62689. /********* End of inlined file: juce_DrawableImage.cpp *********/
  62690. /********* Start of inlined file: juce_DrawablePath.cpp *********/
  62691. BEGIN_JUCE_NAMESPACE
  62692. DrawablePath::DrawablePath()
  62693. : fillBrush (new SolidColourBrush (Colours::black)),
  62694. strokeBrush (0),
  62695. strokeType (0.0f)
  62696. {
  62697. }
  62698. DrawablePath::~DrawablePath()
  62699. {
  62700. delete fillBrush;
  62701. delete strokeBrush;
  62702. }
  62703. void DrawablePath::setPath (const Path& newPath)
  62704. {
  62705. path = newPath;
  62706. updateOutline();
  62707. }
  62708. void DrawablePath::setSolidFill (const Colour& newColour)
  62709. {
  62710. delete fillBrush;
  62711. fillBrush = new SolidColourBrush (newColour);
  62712. }
  62713. void DrawablePath::setFillBrush (const Brush& newBrush)
  62714. {
  62715. delete fillBrush;
  62716. fillBrush = newBrush.createCopy();
  62717. }
  62718. void DrawablePath::setOutline (const float thickness, const Colour& colour)
  62719. {
  62720. strokeType = PathStrokeType (thickness);
  62721. delete strokeBrush;
  62722. strokeBrush = new SolidColourBrush (colour);
  62723. updateOutline();
  62724. }
  62725. void DrawablePath::setOutline (const PathStrokeType& strokeType_, const Brush& newStrokeBrush)
  62726. {
  62727. strokeType = strokeType_;
  62728. delete strokeBrush;
  62729. strokeBrush = newStrokeBrush.createCopy();
  62730. updateOutline();
  62731. }
  62732. void DrawablePath::draw (Graphics& g, const AffineTransform& transform) const
  62733. {
  62734. const Colour oldColour (g.getCurrentColour()); // save this so we can restore it later
  62735. const float currentOpacity = oldColour.getFloatAlpha();
  62736. {
  62737. Brush* const tempBrush = fillBrush->createCopy();
  62738. tempBrush->applyTransform (transform);
  62739. tempBrush->multiplyOpacity (currentOpacity);
  62740. g.setBrush (tempBrush);
  62741. g.fillPath (path, transform);
  62742. delete tempBrush;
  62743. }
  62744. if (strokeBrush != 0 && strokeType.getStrokeThickness() > 0.0f)
  62745. {
  62746. Brush* const tempBrush = strokeBrush->createCopy();
  62747. tempBrush->applyTransform (transform);
  62748. tempBrush->multiplyOpacity (currentOpacity);
  62749. g.setBrush (tempBrush);
  62750. g.fillPath (outline, transform);
  62751. delete tempBrush;
  62752. }
  62753. g.setColour (oldColour);
  62754. }
  62755. void DrawablePath::updateOutline()
  62756. {
  62757. outline.clear();
  62758. strokeType.createStrokedPath (outline, path, AffineTransform::identity, 4.0f);
  62759. }
  62760. void DrawablePath::getBounds (float& x, float& y, float& width, float& height) const
  62761. {
  62762. if (strokeType.getStrokeThickness() > 0.0f)
  62763. outline.getBounds (x, y, width, height);
  62764. else
  62765. path.getBounds (x, y, width, height);
  62766. }
  62767. bool DrawablePath::hitTest (float x, float y) const
  62768. {
  62769. return path.contains (x, y)
  62770. || outline.contains (x, y);
  62771. }
  62772. Drawable* DrawablePath::createCopy() const
  62773. {
  62774. DrawablePath* const dp = new DrawablePath();
  62775. dp->path = path;
  62776. dp->setFillBrush (*fillBrush);
  62777. if (strokeBrush != 0)
  62778. dp->setOutline (strokeType, *strokeBrush);
  62779. return dp;
  62780. }
  62781. END_JUCE_NAMESPACE
  62782. /********* End of inlined file: juce_DrawablePath.cpp *********/
  62783. /********* Start of inlined file: juce_DrawableText.cpp *********/
  62784. BEGIN_JUCE_NAMESPACE
  62785. DrawableText::DrawableText()
  62786. : colour (Colours::white)
  62787. {
  62788. }
  62789. DrawableText::~DrawableText()
  62790. {
  62791. }
  62792. void DrawableText::setText (const GlyphArrangement& newText)
  62793. {
  62794. text = newText;
  62795. }
  62796. void DrawableText::setText (const String& newText, const Font& fontToUse)
  62797. {
  62798. text.clear();
  62799. text.addLineOfText (fontToUse, newText, 0.0f, 0.0f);
  62800. }
  62801. void DrawableText::setColour (const Colour& newColour)
  62802. {
  62803. colour = newColour;
  62804. }
  62805. void DrawableText::draw (Graphics& g, const AffineTransform& transform) const
  62806. {
  62807. const Colour oldColour (g.getCurrentColour()); // save this so we can restore it later
  62808. g.setColour (colour.withMultipliedAlpha (oldColour.getFloatAlpha()));
  62809. text.draw (g, transform);
  62810. g.setColour (oldColour);
  62811. }
  62812. void DrawableText::getBounds (float& x, float& y, float& width, float& height) const
  62813. {
  62814. text.getBoundingBox (0, -1, x, y, width, height, false); // (really returns top, left, bottom, right)
  62815. width -= x;
  62816. height -= y;
  62817. }
  62818. bool DrawableText::hitTest (float x, float y) const
  62819. {
  62820. return text.findGlyphIndexAt (x, y) >= 0;
  62821. }
  62822. Drawable* DrawableText::createCopy() const
  62823. {
  62824. DrawableText* const dt = new DrawableText();
  62825. dt->text = text;
  62826. dt->colour = colour;
  62827. return dt;
  62828. }
  62829. END_JUCE_NAMESPACE
  62830. /********* End of inlined file: juce_DrawableText.cpp *********/
  62831. /********* Start of inlined file: juce_SVGParser.cpp *********/
  62832. BEGIN_JUCE_NAMESPACE
  62833. class SVGState
  62834. {
  62835. public:
  62836. SVGState (const XmlElement* const topLevel)
  62837. : topLevelXml (topLevel),
  62838. x (0), y (0),
  62839. width (512), height (512),
  62840. viewBoxW (0), viewBoxH (0)
  62841. {
  62842. }
  62843. ~SVGState()
  62844. {
  62845. }
  62846. Drawable* parseSVGElement (const XmlElement& xml)
  62847. {
  62848. if (! xml.hasTagName (T("svg")))
  62849. return 0;
  62850. DrawableComposite* const drawable = new DrawableComposite();
  62851. drawable->setName (xml.getStringAttribute (T("id")));
  62852. SVGState newState (*this);
  62853. if (xml.hasAttribute (T("transform")))
  62854. newState.addTransform (xml);
  62855. newState.x = getCoordLength (xml.getStringAttribute (T("x"), String (newState.x)), viewBoxW);
  62856. newState.y = getCoordLength (xml.getStringAttribute (T("y"), String (newState.y)), viewBoxH);
  62857. newState.width = getCoordLength (xml.getStringAttribute (T("width"), String (newState.width)), viewBoxW);
  62858. newState.height = getCoordLength (xml.getStringAttribute (T("height"), String (newState.height)), viewBoxH);
  62859. if (xml.hasAttribute (T("viewBox")))
  62860. {
  62861. const String viewParams (xml.getStringAttribute (T("viewBox")));
  62862. int i = 0;
  62863. float vx, vy, vw, vh;
  62864. if (parseCoords (viewParams, vx, vy, i, true)
  62865. && parseCoords (viewParams, vw, vh, i, true)
  62866. && vw > 0
  62867. && vh > 0)
  62868. {
  62869. newState.viewBoxW = vw;
  62870. newState.viewBoxH = vh;
  62871. int placementFlags = 0;
  62872. const String aspect (xml.getStringAttribute (T("preserveAspectRatio")));
  62873. if (aspect.containsIgnoreCase (T("none")))
  62874. {
  62875. placementFlags = RectanglePlacement::stretchToFit;
  62876. }
  62877. else
  62878. {
  62879. if (aspect.containsIgnoreCase (T("slice")))
  62880. placementFlags |= RectanglePlacement::fillDestination;
  62881. if (aspect.containsIgnoreCase (T("xMin")))
  62882. placementFlags |= RectanglePlacement::xLeft;
  62883. else if (aspect.containsIgnoreCase (T("xMax")))
  62884. placementFlags |= RectanglePlacement::xRight;
  62885. else
  62886. placementFlags |= RectanglePlacement::xMid;
  62887. if (aspect.containsIgnoreCase (T("yMin")))
  62888. placementFlags |= RectanglePlacement::yTop;
  62889. else if (aspect.containsIgnoreCase (T("yMax")))
  62890. placementFlags |= RectanglePlacement::yBottom;
  62891. else
  62892. placementFlags |= RectanglePlacement::yMid;
  62893. }
  62894. const RectanglePlacement placement (placementFlags);
  62895. newState.transform
  62896. = placement.getTransformToFit (vx, vy, vw, vh,
  62897. 0.0f, 0.0f, newState.width, newState.height)
  62898. .followedBy (newState.transform);
  62899. }
  62900. }
  62901. else
  62902. {
  62903. if (viewBoxW == 0)
  62904. newState.viewBoxW = newState.width;
  62905. if (viewBoxH == 0)
  62906. newState.viewBoxH = newState.height;
  62907. }
  62908. newState.parseSubElements (xml, drawable);
  62909. return drawable;
  62910. }
  62911. private:
  62912. const XmlElement* const topLevelXml;
  62913. float x, y, width, height, viewBoxW, viewBoxH;
  62914. AffineTransform transform;
  62915. String cssStyleText;
  62916. void parseSubElements (const XmlElement& xml, DrawableComposite* const parentDrawable)
  62917. {
  62918. forEachXmlChildElement (xml, e)
  62919. {
  62920. Drawable* d = 0;
  62921. if (e->hasTagName (T("g")))
  62922. d = parseGroupElement (*e);
  62923. else if (e->hasTagName (T("svg")))
  62924. d = parseSVGElement (*e);
  62925. else if (e->hasTagName (T("path")))
  62926. d = parsePath (*e);
  62927. else if (e->hasTagName (T("rect")))
  62928. d = parseRect (*e);
  62929. else if (e->hasTagName (T("circle")))
  62930. d = parseCircle (*e);
  62931. else if (e->hasTagName (T("ellipse")))
  62932. d = parseEllipse (*e);
  62933. else if (e->hasTagName (T("line")))
  62934. d = parseLine (*e);
  62935. else if (e->hasTagName (T("polyline")))
  62936. d = parsePolygon (*e, true);
  62937. else if (e->hasTagName (T("polygon")))
  62938. d = parsePolygon (*e, false);
  62939. else if (e->hasTagName (T("text")))
  62940. d = parseText (*e);
  62941. else if (e->hasTagName (T("switch")))
  62942. d = parseSwitch (*e);
  62943. else if (e->hasTagName (T("style")))
  62944. parseCSSStyle (*e);
  62945. parentDrawable->insertDrawable (d);
  62946. }
  62947. }
  62948. DrawableComposite* parseSwitch (const XmlElement& xml)
  62949. {
  62950. const XmlElement* const group = xml.getChildByName (T("g"));
  62951. if (group != 0)
  62952. return parseGroupElement (*group);
  62953. return 0;
  62954. }
  62955. DrawableComposite* parseGroupElement (const XmlElement& xml)
  62956. {
  62957. DrawableComposite* const drawable = new DrawableComposite();
  62958. drawable->setName (xml.getStringAttribute (T("id")));
  62959. if (xml.hasAttribute (T("transform")))
  62960. {
  62961. SVGState newState (*this);
  62962. newState.addTransform (xml);
  62963. newState.parseSubElements (xml, drawable);
  62964. }
  62965. else
  62966. {
  62967. parseSubElements (xml, drawable);
  62968. }
  62969. return drawable;
  62970. }
  62971. Drawable* parsePath (const XmlElement& xml) const
  62972. {
  62973. const String d (xml.getStringAttribute (T("d")).trimStart());
  62974. Path path;
  62975. if (getStyleAttribute (&xml, T("fill-rule")).trim().equalsIgnoreCase (T("evenodd")))
  62976. path.setUsingNonZeroWinding (false);
  62977. int index = 0;
  62978. float lastX = 0, lastY = 0;
  62979. float lastX2 = 0, lastY2 = 0;
  62980. tchar lastCommandChar = 0;
  62981. bool carryOn = true;
  62982. const String validCommandChars (T("MmLlHhVvCcSsQqTtAaZz"));
  62983. for (;;)
  62984. {
  62985. float x, y, x2, y2, x3, y3;
  62986. const bool isRelative = (d[index] >= 'a' && d[index] <= 'z');
  62987. if (validCommandChars.containsChar (d[index]))
  62988. lastCommandChar = d [index++];
  62989. switch (lastCommandChar)
  62990. {
  62991. case T('M'):
  62992. case T('m'):
  62993. case T('L'):
  62994. case T('l'):
  62995. if (parseCoords (d, x, y, index, false))
  62996. {
  62997. if (isRelative)
  62998. {
  62999. x += lastX;
  63000. y += lastY;
  63001. }
  63002. if (lastCommandChar == T('M') || lastCommandChar == T('m'))
  63003. path.startNewSubPath (x, y);
  63004. else
  63005. path.lineTo (x, y);
  63006. lastX2 = lastX;
  63007. lastY2 = lastY;
  63008. lastX = x;
  63009. lastY = y;
  63010. }
  63011. else
  63012. {
  63013. ++index;
  63014. }
  63015. break;
  63016. case T('H'):
  63017. case T('h'):
  63018. if (parseCoord (d, x, index, false, true))
  63019. {
  63020. if (isRelative)
  63021. x += lastX;
  63022. path.lineTo (x, lastY);
  63023. lastX2 = lastX;
  63024. lastX = x;
  63025. }
  63026. else
  63027. {
  63028. ++index;
  63029. }
  63030. break;
  63031. case T('V'):
  63032. case T('v'):
  63033. if (parseCoord (d, y, index, false, false))
  63034. {
  63035. if (isRelative)
  63036. y += lastY;
  63037. path.lineTo (lastX, y);
  63038. lastY2 = lastY;
  63039. lastY = y;
  63040. }
  63041. else
  63042. {
  63043. ++index;
  63044. }
  63045. break;
  63046. case T('C'):
  63047. case T('c'):
  63048. if (parseCoords (d, x, y, index, false)
  63049. && parseCoords (d, x2, y2, index, false)
  63050. && parseCoords (d, x3, y3, index, false))
  63051. {
  63052. if (isRelative)
  63053. {
  63054. x += lastX;
  63055. y += lastY;
  63056. x2 += lastX;
  63057. y2 += lastY;
  63058. x3 += lastX;
  63059. y3 += lastY;
  63060. }
  63061. path.cubicTo (x, y, x2, y2, x3, y3);
  63062. lastX2 = x2;
  63063. lastY2 = y2;
  63064. lastX = x3;
  63065. lastY = y3;
  63066. }
  63067. else
  63068. {
  63069. ++index;
  63070. }
  63071. break;
  63072. case T('S'):
  63073. case T('s'):
  63074. if (parseCoords (d, x, y, index, false)
  63075. && parseCoords (d, x3, y3, index, false))
  63076. {
  63077. if (isRelative)
  63078. {
  63079. x += lastX;
  63080. y += lastY;
  63081. x3 += lastX;
  63082. y3 += lastY;
  63083. }
  63084. x2 = lastX + (lastX - lastX2);
  63085. y2 = lastY + (lastY - lastY2);
  63086. path.cubicTo (x2, y2, x, y, x3, y3);
  63087. lastX2 = x2;
  63088. lastY2 = y2;
  63089. lastX = x3;
  63090. lastY = y3;
  63091. }
  63092. else
  63093. {
  63094. ++index;
  63095. }
  63096. break;
  63097. case T('Q'):
  63098. case T('q'):
  63099. if (parseCoords (d, x, y, index, false)
  63100. && parseCoords (d, x2, y2, index, false))
  63101. {
  63102. if (isRelative)
  63103. {
  63104. x += lastX;
  63105. y += lastY;
  63106. x2 += lastX;
  63107. y2 += lastY;
  63108. }
  63109. path.quadraticTo (x, y, x2, y2);
  63110. lastX2 = x;
  63111. lastY2 = y;
  63112. lastX = x2;
  63113. lastY = y2;
  63114. }
  63115. else
  63116. {
  63117. ++index;
  63118. }
  63119. break;
  63120. case T('T'):
  63121. case T('t'):
  63122. if (parseCoords (d, x, y, index, false))
  63123. {
  63124. if (isRelative)
  63125. {
  63126. x += lastX;
  63127. y += lastY;
  63128. }
  63129. x2 = lastX + (lastX - lastX2);
  63130. y2 = lastY + (lastY - lastY2);
  63131. path.quadraticTo (x2, y2, x, y);
  63132. lastX2 = x2;
  63133. lastY2 = y2;
  63134. lastX = x;
  63135. lastY = y;
  63136. }
  63137. else
  63138. {
  63139. ++index;
  63140. }
  63141. break;
  63142. case T('A'):
  63143. case T('a'):
  63144. if (parseCoords (d, x, y, index, false))
  63145. {
  63146. String num;
  63147. if (parseNextNumber (d, num, index, false))
  63148. {
  63149. const float angle = num.getFloatValue() * (180.0f / float_Pi);
  63150. if (parseNextNumber (d, num, index, false))
  63151. {
  63152. const bool largeArc = num.getIntValue() != 0;
  63153. if (parseNextNumber (d, num, index, false))
  63154. {
  63155. const bool sweep = num.getIntValue() != 0;
  63156. if (parseCoords (d, x2, y2, index, false))
  63157. {
  63158. if (isRelative)
  63159. {
  63160. x2 += lastX;
  63161. y2 += lastY;
  63162. }
  63163. if (lastX != x2 || lastY != y2)
  63164. {
  63165. double centreX, centreY, startAngle, deltaAngle;
  63166. double rx = x, ry = y;
  63167. endpointToCentreParameters (lastX, lastY, x2, y2,
  63168. angle, largeArc, sweep,
  63169. rx, ry, centreX, centreY,
  63170. startAngle, deltaAngle);
  63171. path.addCentredArc ((float) centreX, (float) centreY,
  63172. (float) rx, (float) ry,
  63173. angle, (float) startAngle, (float) (startAngle + deltaAngle),
  63174. false);
  63175. path.lineTo (x2, y2);
  63176. }
  63177. lastX2 = lastX;
  63178. lastY2 = lastY;
  63179. lastX = x2;
  63180. lastY = y2;
  63181. }
  63182. }
  63183. }
  63184. }
  63185. }
  63186. else
  63187. {
  63188. ++index;
  63189. }
  63190. break;
  63191. case T('Z'):
  63192. case T('z'):
  63193. path.closeSubPath();
  63194. while (CharacterFunctions::isWhitespace (d [index]))
  63195. ++index;
  63196. break;
  63197. default:
  63198. carryOn = false;
  63199. break;
  63200. }
  63201. if (! carryOn)
  63202. break;
  63203. }
  63204. return parseShape (xml, path);
  63205. }
  63206. Drawable* parseRect (const XmlElement& xml) const
  63207. {
  63208. Path rect;
  63209. const bool hasRX = xml.hasAttribute (T("rx"));
  63210. const bool hasRY = xml.hasAttribute (T("ry"));
  63211. if (hasRX || hasRY)
  63212. {
  63213. float rx = getCoordLength (xml.getStringAttribute (T("rx")), viewBoxW);
  63214. float ry = getCoordLength (xml.getStringAttribute (T("ry")), viewBoxH);
  63215. if (! hasRX)
  63216. rx = ry;
  63217. else if (! hasRY)
  63218. ry = rx;
  63219. rect.addRoundedRectangle (getCoordLength (xml.getStringAttribute (T("x")), viewBoxW),
  63220. getCoordLength (xml.getStringAttribute (T("y")), viewBoxH),
  63221. getCoordLength (xml.getStringAttribute (T("width")), viewBoxW),
  63222. getCoordLength (xml.getStringAttribute (T("height")), viewBoxH),
  63223. rx, ry);
  63224. }
  63225. else
  63226. {
  63227. rect.addRectangle (getCoordLength (xml.getStringAttribute (T("x")), viewBoxW),
  63228. getCoordLength (xml.getStringAttribute (T("y")), viewBoxH),
  63229. getCoordLength (xml.getStringAttribute (T("width")), viewBoxW),
  63230. getCoordLength (xml.getStringAttribute (T("height")), viewBoxH));
  63231. }
  63232. return parseShape (xml, rect);
  63233. }
  63234. Drawable* parseCircle (const XmlElement& xml) const
  63235. {
  63236. Path circle;
  63237. const float cx = getCoordLength (xml.getStringAttribute (T("cx")), viewBoxW);
  63238. const float cy = getCoordLength (xml.getStringAttribute (T("cy")), viewBoxH);
  63239. const float radius = getCoordLength (xml.getStringAttribute (T("r")), viewBoxW);
  63240. circle.addEllipse (cx - radius, cy - radius, radius * 2.0f, radius * 2.0f);
  63241. return parseShape (xml, circle);
  63242. }
  63243. Drawable* parseEllipse (const XmlElement& xml) const
  63244. {
  63245. Path ellipse;
  63246. const float cx = getCoordLength (xml.getStringAttribute (T("cx")), viewBoxW);
  63247. const float cy = getCoordLength (xml.getStringAttribute (T("cy")), viewBoxH);
  63248. const float radiusX = getCoordLength (xml.getStringAttribute (T("rx")), viewBoxW);
  63249. const float radiusY = getCoordLength (xml.getStringAttribute (T("ry")), viewBoxH);
  63250. ellipse.addEllipse (cx - radiusX, cy - radiusY, radiusX * 2.0f, radiusY * 2.0f);
  63251. return parseShape (xml, ellipse);
  63252. }
  63253. Drawable* parseLine (const XmlElement& xml) const
  63254. {
  63255. Path line;
  63256. const float x1 = getCoordLength (xml.getStringAttribute (T("x1")), viewBoxW);
  63257. const float y1 = getCoordLength (xml.getStringAttribute (T("y1")), viewBoxH);
  63258. const float x2 = getCoordLength (xml.getStringAttribute (T("x2")), viewBoxW);
  63259. const float y2 = getCoordLength (xml.getStringAttribute (T("y2")), viewBoxH);
  63260. line.startNewSubPath (x1, y1);
  63261. line.lineTo (x2, y2);
  63262. return parseShape (xml, line);
  63263. }
  63264. Drawable* parsePolygon (const XmlElement& xml, const bool isPolyline) const
  63265. {
  63266. const String points (xml.getStringAttribute (T("points")));
  63267. Path path;
  63268. int index = 0;
  63269. float x, y;
  63270. if (parseCoords (points, x, y, index, true))
  63271. {
  63272. float firstX = x;
  63273. float firstY = y;
  63274. float lastX = 0, lastY = 0;
  63275. path.startNewSubPath (x, y);
  63276. while (parseCoords (points, x, y, index, true))
  63277. {
  63278. lastX = x;
  63279. lastY = y;
  63280. path.lineTo (x, y);
  63281. }
  63282. if ((! isPolyline) || (firstX == lastX && firstY == lastY))
  63283. path.closeSubPath();
  63284. }
  63285. return parseShape (xml, path);
  63286. }
  63287. Drawable* parseShape (const XmlElement& xml, Path& path,
  63288. const bool parseTransform = true) const
  63289. {
  63290. if (parseTransform && xml.hasAttribute (T("transform")))
  63291. {
  63292. SVGState newState (*this);
  63293. newState.addTransform (xml);
  63294. return newState.parseShape (xml, path, false);
  63295. }
  63296. DrawablePath* dp = new DrawablePath();
  63297. dp->setSolidFill (Colours::transparentBlack);
  63298. path.applyTransform (transform);
  63299. dp->setPath (path);
  63300. Path::Iterator iter (path);
  63301. bool containsClosedSubPath = false;
  63302. while (iter.next())
  63303. {
  63304. if (iter.elementType == Path::Iterator::closePath)
  63305. {
  63306. containsClosedSubPath = true;
  63307. break;
  63308. }
  63309. }
  63310. Brush* const fillBrush
  63311. = getBrushForFill (path,
  63312. getStyleAttribute (&xml, T("fill")),
  63313. getStyleAttribute (&xml, T("fill-opacity")),
  63314. getStyleAttribute (&xml, T("opacity")),
  63315. containsClosedSubPath ? Colours::black
  63316. : Colours::transparentBlack);
  63317. if (fillBrush != 0)
  63318. {
  63319. if (! fillBrush->isInvisible())
  63320. {
  63321. fillBrush->applyTransform (transform);
  63322. dp->setFillBrush (*fillBrush);
  63323. }
  63324. delete fillBrush;
  63325. }
  63326. const String strokeType (getStyleAttribute (&xml, T("stroke")));
  63327. if (strokeType.isNotEmpty() && ! strokeType.equalsIgnoreCase (T("none")))
  63328. {
  63329. Brush* const strokeBrush
  63330. = getBrushForFill (path, strokeType,
  63331. getStyleAttribute (&xml, T("stroke-opacity")),
  63332. getStyleAttribute (&xml, T("opacity")),
  63333. Colours::transparentBlack);
  63334. if (strokeBrush != 0)
  63335. {
  63336. const PathStrokeType stroke (getStrokeFor (&xml));
  63337. if (! strokeBrush->isInvisible())
  63338. {
  63339. strokeBrush->applyTransform (transform);
  63340. dp->setOutline (stroke, *strokeBrush);
  63341. }
  63342. delete strokeBrush;
  63343. }
  63344. }
  63345. return dp;
  63346. }
  63347. const XmlElement* findLinkedElement (const XmlElement* e) const
  63348. {
  63349. const String id (e->getStringAttribute (T("xlink:href")));
  63350. if (! id.startsWithChar (T('#')))
  63351. return 0;
  63352. return findElementForId (topLevelXml, id.substring (1));
  63353. }
  63354. void addGradientStopsIn (ColourGradient& cg, const XmlElement* const fillXml) const
  63355. {
  63356. if (fillXml == 0)
  63357. return;
  63358. forEachXmlChildElementWithTagName (*fillXml, e, T("stop"))
  63359. {
  63360. int index = 0;
  63361. Colour col (parseColour (getStyleAttribute (e, T("stop-color")), index, Colours::black));
  63362. const String opacity (getStyleAttribute (e, T("stop-opacity"), T("1")));
  63363. col = col.withMultipliedAlpha (jlimit (0.0f, 1.0f, opacity.getFloatValue()));
  63364. double offset = e->getDoubleAttribute (T("offset"));
  63365. if (e->getStringAttribute (T("offset")).containsChar (T('%')))
  63366. offset *= 0.01;
  63367. cg.addColour (jlimit (0.0, 1.0, offset), col);
  63368. }
  63369. }
  63370. Brush* getBrushForFill (const Path& path,
  63371. const String& fill,
  63372. const String& fillOpacity,
  63373. const String& overallOpacity,
  63374. const Colour& defaultColour) const
  63375. {
  63376. float opacity = 1.0f;
  63377. if (overallOpacity.isNotEmpty())
  63378. opacity = jlimit (0.0f, 1.0f, overallOpacity.getFloatValue());
  63379. if (fillOpacity.isNotEmpty())
  63380. opacity *= (jlimit (0.0f, 1.0f, fillOpacity.getFloatValue()));
  63381. if (fill.startsWithIgnoreCase (T("url")))
  63382. {
  63383. const String id (fill.fromFirstOccurrenceOf (T("#"), false, false)
  63384. .upToLastOccurrenceOf (T(")"), false, false).trim());
  63385. const XmlElement* const fillXml = findElementForId (topLevelXml, id);
  63386. if (fillXml != 0
  63387. && (fillXml->hasTagName (T("linearGradient"))
  63388. || fillXml->hasTagName (T("radialGradient"))))
  63389. {
  63390. const XmlElement* inheritedFrom = findLinkedElement (fillXml);
  63391. ColourGradient cg;
  63392. addGradientStopsIn (cg, inheritedFrom);
  63393. addGradientStopsIn (cg, fillXml);
  63394. if (cg.getNumColours() > 0)
  63395. {
  63396. cg.addColour (0.0, cg.getColour (0));
  63397. cg.addColour (1.0, cg.getColour (cg.getNumColours() - 1));
  63398. }
  63399. else
  63400. {
  63401. cg.addColour (0.0, Colours::black);
  63402. cg.addColour (1.0, Colours::black);
  63403. }
  63404. if (overallOpacity.isNotEmpty())
  63405. cg.multiplyOpacity (overallOpacity.getFloatValue());
  63406. jassert (cg.getNumColours() > 0);
  63407. cg.isRadial = fillXml->hasTagName (T("radialGradient"));
  63408. cg.transform = parseTransform (fillXml->getStringAttribute (T("gradientTransform")));
  63409. float width = viewBoxW;
  63410. float height = viewBoxH;
  63411. float dx = 0.0;
  63412. float dy = 0.0;
  63413. const bool userSpace = fillXml->getStringAttribute (T("gradientUnits")).equalsIgnoreCase (T("userSpaceOnUse"));
  63414. if (! userSpace)
  63415. path.getBounds (dx, dy, width, height);
  63416. if (cg.isRadial)
  63417. {
  63418. cg.x1 = dx + getCoordLength (fillXml->getStringAttribute (T("cx"), T("50%")), width);
  63419. cg.y1 = dy + getCoordLength (fillXml->getStringAttribute (T("cy"), T("50%")), height);
  63420. const float radius = getCoordLength (fillXml->getStringAttribute (T("r"), T("50%")), width);
  63421. cg.x2 = cg.x1 + radius;
  63422. cg.y2 = cg.y1;
  63423. //xxx (the fx, fy focal point isn't handled properly here..)
  63424. }
  63425. else
  63426. {
  63427. cg.x1 = dx + getCoordLength (fillXml->getStringAttribute (T("x1"), T("0%")), width);
  63428. cg.y1 = dy + getCoordLength (fillXml->getStringAttribute (T("y1"), T("0%")), height);
  63429. cg.x2 = dx + getCoordLength (fillXml->getStringAttribute (T("x2"), T("100%")), width);
  63430. cg.y2 = dy + getCoordLength (fillXml->getStringAttribute (T("y2"), T("0%")), height);
  63431. if (cg.x1 == cg.x2 && cg.y1 == cg.y2)
  63432. return new SolidColourBrush (cg.getColour (cg.getNumColours() - 1));
  63433. }
  63434. return new GradientBrush (cg);
  63435. }
  63436. }
  63437. if (fill.equalsIgnoreCase (T("none")))
  63438. return new SolidColourBrush (Colours::transparentBlack);
  63439. int i = 0;
  63440. Colour colour (parseColour (fill, i, defaultColour));
  63441. colour = colour.withMultipliedAlpha (opacity);
  63442. return new SolidColourBrush (colour);
  63443. }
  63444. const PathStrokeType getStrokeFor (const XmlElement* const xml) const
  63445. {
  63446. const String width (getStyleAttribute (xml, T("stroke-width")));
  63447. const String cap (getStyleAttribute (xml, T("stroke-linecap")));
  63448. const String join (getStyleAttribute (xml, T("stroke-linejoin")));
  63449. //const String mitreLimit (getStyleAttribute (xml, T("stroke-miterlimit")));
  63450. //const String dashArray (getStyleAttribute (xml, T("stroke-dasharray")));
  63451. //const String dashOffset (getStyleAttribute (xml, T("stroke-dashoffset")));
  63452. PathStrokeType::JointStyle joinStyle = PathStrokeType::mitered;
  63453. PathStrokeType::EndCapStyle capStyle = PathStrokeType::butt;
  63454. if (join.equalsIgnoreCase (T("round")))
  63455. joinStyle = PathStrokeType::curved;
  63456. else if (join.equalsIgnoreCase (T("bevel")))
  63457. joinStyle = PathStrokeType::beveled;
  63458. if (cap.equalsIgnoreCase (T("round")))
  63459. capStyle = PathStrokeType::rounded;
  63460. else if (cap.equalsIgnoreCase (T("square")))
  63461. capStyle = PathStrokeType::square;
  63462. float ox = 0.0f, oy = 0.0f;
  63463. transform.transformPoint (ox, oy);
  63464. float x = getCoordLength (width, viewBoxW), y = 0.0f;
  63465. transform.transformPoint (x, y);
  63466. return PathStrokeType (width.isNotEmpty() ? juce_hypotf (x - ox, y - oy) : 1.0f,
  63467. joinStyle, capStyle);
  63468. }
  63469. Drawable* parseText (const XmlElement& xml)
  63470. {
  63471. Array <float> xCoords, yCoords, dxCoords, dyCoords;
  63472. getCoordList (xCoords, getInheritedAttribute (&xml, T("x")), true, true);
  63473. getCoordList (yCoords, getInheritedAttribute (&xml, T("y")), true, false);
  63474. getCoordList (dxCoords, getInheritedAttribute (&xml, T("dx")), true, true);
  63475. getCoordList (dyCoords, getInheritedAttribute (&xml, T("dy")), true, false);
  63476. //xxx not done text yet!
  63477. forEachXmlChildElement (xml, e)
  63478. {
  63479. if (e->isTextElement())
  63480. {
  63481. const String text (e->getText());
  63482. Path path;
  63483. parseShape (*e, path);
  63484. }
  63485. else if (e->hasTagName (T("tspan")))
  63486. {
  63487. parseText (*e);
  63488. }
  63489. }
  63490. return 0;
  63491. }
  63492. void addTransform (const XmlElement& xml)
  63493. {
  63494. transform = parseTransform (xml.getStringAttribute (T("transform")))
  63495. .followedBy (transform);
  63496. }
  63497. bool parseCoord (const String& s, float& value, int& index,
  63498. const bool allowUnits, const bool isX) const
  63499. {
  63500. String number;
  63501. if (! parseNextNumber (s, number, index, allowUnits))
  63502. {
  63503. value = 0;
  63504. return false;
  63505. }
  63506. value = getCoordLength (number, isX ? viewBoxW : viewBoxH);
  63507. return true;
  63508. }
  63509. bool parseCoords (const String& s, float& x, float& y,
  63510. int& index, const bool allowUnits) const
  63511. {
  63512. return parseCoord (s, x, index, allowUnits, true)
  63513. && parseCoord (s, y, index, allowUnits, false);
  63514. }
  63515. float getCoordLength (const String& s, const float sizeForProportions) const
  63516. {
  63517. float n = s.getFloatValue();
  63518. const int len = s.length();
  63519. if (len > 2)
  63520. {
  63521. const float dpi = 96.0f;
  63522. const tchar n1 = s [len - 2];
  63523. const tchar n2 = s [len - 1];
  63524. if (n1 == T('i') && n2 == T('n'))
  63525. n *= dpi;
  63526. else if (n1 == T('m') && n2 == T('m'))
  63527. n *= dpi / 25.4f;
  63528. else if (n1 == T('c') && n2 == T('m'))
  63529. n *= dpi / 2.54f;
  63530. else if (n1 == T('p') && n2 == T('c'))
  63531. n *= 15.0f;
  63532. else if (n2 == T('%'))
  63533. n *= 0.01f * sizeForProportions;
  63534. }
  63535. return n;
  63536. }
  63537. void getCoordList (Array <float>& coords, const String& list,
  63538. const bool allowUnits, const bool isX) const
  63539. {
  63540. int index = 0;
  63541. float value;
  63542. while (parseCoord (list, value, index, allowUnits, isX))
  63543. coords.add (value);
  63544. }
  63545. void parseCSSStyle (const XmlElement& xml)
  63546. {
  63547. cssStyleText = xml.getAllSubText() + T("\n") + cssStyleText;
  63548. }
  63549. const String getStyleAttribute (const XmlElement* xml, const String& attributeName,
  63550. const String& defaultValue = String::empty) const
  63551. {
  63552. if (xml->hasAttribute (attributeName))
  63553. return xml->getStringAttribute (attributeName, defaultValue);
  63554. const String styleAtt (xml->getStringAttribute (T("style")));
  63555. if (styleAtt.isNotEmpty())
  63556. {
  63557. const String value (getAttributeFromStyleList (styleAtt, attributeName, String::empty));
  63558. if (value.isNotEmpty())
  63559. return value;
  63560. }
  63561. else if (xml->hasAttribute (T("class")))
  63562. {
  63563. const String className (T(".") + xml->getStringAttribute (T("class")));
  63564. int index = cssStyleText.indexOfIgnoreCase (className + T(" "));
  63565. if (index < 0)
  63566. index = cssStyleText.indexOfIgnoreCase (className + T("{"));
  63567. if (index >= 0)
  63568. {
  63569. const int openBracket = cssStyleText.indexOfChar (index, T('{'));
  63570. if (openBracket > index)
  63571. {
  63572. const int closeBracket = cssStyleText.indexOfChar (openBracket, T('}'));
  63573. if (closeBracket > openBracket)
  63574. {
  63575. const String value (getAttributeFromStyleList (cssStyleText.substring (openBracket + 1, closeBracket), attributeName, defaultValue));
  63576. if (value.isNotEmpty())
  63577. return value;
  63578. }
  63579. }
  63580. }
  63581. }
  63582. xml = const_cast <XmlElement*> (topLevelXml)->findParentElementOf (xml);
  63583. if (xml != 0)
  63584. return getStyleAttribute (xml, attributeName, defaultValue);
  63585. return defaultValue;
  63586. }
  63587. const String getInheritedAttribute (const XmlElement* xml, const String& attributeName) const
  63588. {
  63589. if (xml->hasAttribute (attributeName))
  63590. return xml->getStringAttribute (attributeName);
  63591. xml = const_cast <XmlElement*> (topLevelXml)->findParentElementOf (xml);
  63592. if (xml != 0)
  63593. return getInheritedAttribute (xml, attributeName);
  63594. return String::empty;
  63595. }
  63596. static bool isIdentifierChar (const tchar c)
  63597. {
  63598. return CharacterFunctions::isLetter (c) || c == T('-');
  63599. }
  63600. static const String getAttributeFromStyleList (const String& list, const String& attributeName, const String& defaultValue)
  63601. {
  63602. int i = 0;
  63603. for (;;)
  63604. {
  63605. i = list.indexOf (i, attributeName);
  63606. if (i < 0)
  63607. break;
  63608. if ((i == 0 || (i > 0 && ! isIdentifierChar (list [i - 1])))
  63609. && ! isIdentifierChar (list [i + attributeName.length()]))
  63610. {
  63611. i = list.indexOfChar (i, T(':'));
  63612. if (i < 0)
  63613. break;
  63614. int end = list.indexOfChar (i, T(';'));
  63615. if (end < 0)
  63616. end = 0x7ffff;
  63617. return list.substring (i + 1, end).trim();
  63618. }
  63619. ++i;
  63620. }
  63621. return defaultValue;
  63622. }
  63623. static bool parseNextNumber (const String& source, String& value, int& index, const bool allowUnits)
  63624. {
  63625. const tchar* const s = (const tchar*) source;
  63626. while (CharacterFunctions::isWhitespace (s[index]) || s[index] == T(','))
  63627. ++index;
  63628. int start = index;
  63629. if (CharacterFunctions::isDigit (s[index]) || s[index] == T('.') || s[index] == T('-'))
  63630. ++index;
  63631. while (CharacterFunctions::isDigit (s[index]) || s[index] == T('.'))
  63632. ++index;
  63633. if ((s[index] == T('e') || s[index] == T('E'))
  63634. && (CharacterFunctions::isDigit (s[index + 1])
  63635. || s[index + 1] == T('-')
  63636. || s[index + 1] == T('+')))
  63637. {
  63638. index += 2;
  63639. while (CharacterFunctions::isDigit (s[index]))
  63640. ++index;
  63641. }
  63642. if (allowUnits)
  63643. {
  63644. while (CharacterFunctions::isLetter (s[index]))
  63645. ++index;
  63646. }
  63647. if (index == start)
  63648. return false;
  63649. value = String (s + start, index - start);
  63650. while (CharacterFunctions::isWhitespace (s[index]) || s[index] == T(','))
  63651. ++index;
  63652. return true;
  63653. }
  63654. static const Colour parseColour (const String& s, int& index, const Colour& defaultColour)
  63655. {
  63656. if (s [index] == T('#'))
  63657. {
  63658. uint32 hex [6];
  63659. zeromem (hex, sizeof (hex));
  63660. int numChars = 0;
  63661. for (int i = 6; --i >= 0;)
  63662. {
  63663. const int hexValue = CharacterFunctions::getHexDigitValue (s [++index]);
  63664. if (hexValue >= 0)
  63665. hex [numChars++] = hexValue;
  63666. else
  63667. break;
  63668. }
  63669. if (numChars <= 3)
  63670. return Colour ((uint8) (hex [0] * 0x11),
  63671. (uint8) (hex [1] * 0x11),
  63672. (uint8) (hex [2] * 0x11));
  63673. else
  63674. return Colour ((uint8) ((hex [0] << 4) + hex [1]),
  63675. (uint8) ((hex [2] << 4) + hex [3]),
  63676. (uint8) ((hex [4] << 4) + hex [5]));
  63677. }
  63678. else if (s [index] == T('r')
  63679. && s [index + 1] == T('g')
  63680. && s [index + 2] == T('b'))
  63681. {
  63682. const int openBracket = s.indexOfChar (index, T('('));
  63683. const int closeBracket = s.indexOfChar (openBracket, T(')'));
  63684. if (openBracket >= 3 && closeBracket > openBracket)
  63685. {
  63686. index = closeBracket;
  63687. StringArray tokens;
  63688. tokens.addTokens (s.substring (openBracket + 1, closeBracket), T(","), T(""));
  63689. tokens.trim();
  63690. tokens.removeEmptyStrings();
  63691. if (tokens[0].containsChar T('%'))
  63692. return Colour ((uint8) roundDoubleToInt (2.55 * tokens[0].getDoubleValue()),
  63693. (uint8) roundDoubleToInt (2.55 * tokens[1].getDoubleValue()),
  63694. (uint8) roundDoubleToInt (2.55 * tokens[2].getDoubleValue()));
  63695. else
  63696. return Colour ((uint8) tokens[0].getIntValue(),
  63697. (uint8) tokens[1].getIntValue(),
  63698. (uint8) tokens[2].getIntValue());
  63699. }
  63700. }
  63701. return Colours::findColourForName (s, defaultColour);
  63702. }
  63703. static const AffineTransform parseTransform (String t)
  63704. {
  63705. AffineTransform result;
  63706. while (t.isNotEmpty())
  63707. {
  63708. StringArray tokens;
  63709. tokens.addTokens (t.fromFirstOccurrenceOf (T("("), false, false)
  63710. .upToFirstOccurrenceOf (T(")"), false, false),
  63711. T(", "), 0);
  63712. tokens.removeEmptyStrings (true);
  63713. float numbers [6];
  63714. for (int i = 0; i < 6; ++i)
  63715. numbers[i] = tokens[i].getFloatValue();
  63716. AffineTransform trans;
  63717. if (t.startsWithIgnoreCase (T("matrix")))
  63718. {
  63719. trans = AffineTransform (numbers[0], numbers[2], numbers[4],
  63720. numbers[1], numbers[3], numbers[5]);
  63721. }
  63722. else if (t.startsWithIgnoreCase (T("translate")))
  63723. {
  63724. trans = trans.translated (numbers[0], numbers[1]);
  63725. }
  63726. else if (t.startsWithIgnoreCase (T("scale")))
  63727. {
  63728. if (tokens.size() == 1)
  63729. trans = trans.scaled (numbers[0], numbers[0]);
  63730. else
  63731. trans = trans.scaled (numbers[0], numbers[1]);
  63732. }
  63733. else if (t.startsWithIgnoreCase (T("rotate")))
  63734. {
  63735. if (tokens.size() != 3)
  63736. trans = trans.rotated (numbers[0] / (180.0f / float_Pi));
  63737. else
  63738. trans = trans.rotated (numbers[0] / (180.0f / float_Pi),
  63739. numbers[1], numbers[2]);
  63740. }
  63741. else if (t.startsWithIgnoreCase (T("skewX")))
  63742. {
  63743. trans = AffineTransform (1.0f, tanf (numbers[0] * (float_Pi / 180.0f)), 0.0f,
  63744. 0.0f, 1.0f, 0.0f);
  63745. }
  63746. else if (t.startsWithIgnoreCase (T("skewY")))
  63747. {
  63748. trans = AffineTransform (1.0f, 0.0f, 0.0f,
  63749. tanf (numbers[0] * (float_Pi / 180.0f)), 1.0f, 0.0f);
  63750. }
  63751. result = trans.followedBy (result);
  63752. t = t.fromFirstOccurrenceOf (T(")"), false, false).trimStart();
  63753. }
  63754. return result;
  63755. }
  63756. static void endpointToCentreParameters (const double x1, const double y1,
  63757. const double x2, const double y2,
  63758. const double angle,
  63759. const bool largeArc, const bool sweep,
  63760. double& rx, double& ry,
  63761. double& centreX, double& centreY,
  63762. double& startAngle, double& deltaAngle)
  63763. {
  63764. const double midX = (x1 - x2) * 0.5;
  63765. const double midY = (y1 - y2) * 0.5;
  63766. const double cosAngle = cos (angle);
  63767. const double sinAngle = sin (angle);
  63768. const double xp = cosAngle * midX + sinAngle * midY;
  63769. const double yp = cosAngle * midY - sinAngle * midX;
  63770. const double xp2 = xp * xp;
  63771. const double yp2 = yp * yp;
  63772. double rx2 = rx * rx;
  63773. double ry2 = ry * ry;
  63774. const double s = (xp2 / rx2) + (yp2 / ry2);
  63775. double c;
  63776. if (s <= 1.0)
  63777. {
  63778. c = sqrt (jmax (0.0, ((rx2 * ry2) - (rx2 * yp2) - (ry2 * xp2))
  63779. / (( rx2 * yp2) + (ry2 * xp2))));
  63780. if (largeArc == sweep)
  63781. c = -c;
  63782. }
  63783. else
  63784. {
  63785. const double s2 = sqrt (s);
  63786. rx *= s2;
  63787. ry *= s2;
  63788. rx2 = rx * rx;
  63789. ry2 = ry * ry;
  63790. c = 0;
  63791. }
  63792. const double cpx = ((rx * yp) / ry) * c;
  63793. const double cpy = ((-ry * xp) / rx) * c;
  63794. centreX = ((x1 + x2) * 0.5) + (cosAngle * cpx) - (sinAngle * cpy);
  63795. centreY = ((y1 + y2) * 0.5) + (sinAngle * cpx) + (cosAngle * cpy);
  63796. const double ux = (xp - cpx) / rx;
  63797. const double uy = (yp - cpy) / ry;
  63798. const double vx = (-xp - cpx) / rx;
  63799. const double vy = (-yp - cpy) / ry;
  63800. const double length = juce_hypot (ux, uy);
  63801. startAngle = acos (jlimit (-1.0, 1.0, ux / length));
  63802. if (uy < 0)
  63803. startAngle = -startAngle;
  63804. startAngle += double_Pi * 0.5;
  63805. deltaAngle = acos (jlimit (-1.0, 1.0, ((ux * vx) + (uy * vy))
  63806. / (length * juce_hypot (vx, vy))));
  63807. if ((ux * vy) - (uy * vx) < 0)
  63808. deltaAngle = -deltaAngle;
  63809. if (sweep)
  63810. {
  63811. if (deltaAngle < 0)
  63812. deltaAngle += double_Pi * 2.0;
  63813. }
  63814. else
  63815. {
  63816. if (deltaAngle > 0)
  63817. deltaAngle -= double_Pi * 2.0;
  63818. }
  63819. deltaAngle = fmod (deltaAngle, double_Pi * 2.0);
  63820. }
  63821. static const XmlElement* findElementForId (const XmlElement* const parent, const String& id)
  63822. {
  63823. forEachXmlChildElement (*parent, e)
  63824. {
  63825. if (e->compareAttribute (T("id"), id))
  63826. return e;
  63827. const XmlElement* const found = findElementForId (e, id);
  63828. if (found != 0)
  63829. return found;
  63830. }
  63831. return 0;
  63832. }
  63833. const SVGState& operator= (const SVGState&);
  63834. };
  63835. Drawable* Drawable::createFromSVG (const XmlElement& svgDocument)
  63836. {
  63837. SVGState state (&svgDocument);
  63838. return state.parseSVGElement (svgDocument);
  63839. }
  63840. END_JUCE_NAMESPACE
  63841. /********* End of inlined file: juce_SVGParser.cpp *********/
  63842. /********* Start of inlined file: juce_DropShadowEffect.cpp *********/
  63843. BEGIN_JUCE_NAMESPACE
  63844. #if JUCE_MSVC
  63845. #pragma optimize ("t", on) // try to avoid slowing everything down in debug builds
  63846. #endif
  63847. DropShadowEffect::DropShadowEffect()
  63848. : offsetX (0),
  63849. offsetY (0),
  63850. radius (4),
  63851. opacity (0.6f)
  63852. {
  63853. }
  63854. DropShadowEffect::~DropShadowEffect()
  63855. {
  63856. }
  63857. void DropShadowEffect::setShadowProperties (const float newRadius,
  63858. const float newOpacity,
  63859. const int newShadowOffsetX,
  63860. const int newShadowOffsetY)
  63861. {
  63862. radius = jmax (1.1f, newRadius);
  63863. offsetX = newShadowOffsetX;
  63864. offsetY = newShadowOffsetY;
  63865. opacity = newOpacity;
  63866. }
  63867. void DropShadowEffect::applyEffect (Image& image, Graphics& g)
  63868. {
  63869. const int w = image.getWidth();
  63870. const int h = image.getHeight();
  63871. int lineStride, pixelStride;
  63872. const PixelARGB* srcPixels = (const PixelARGB*) image.lockPixelDataReadOnly (0, 0, image.getWidth(), image.getHeight(), lineStride, pixelStride);
  63873. Image shadowImage (Image::SingleChannel, w, h, false);
  63874. int destStride, destPixelStride;
  63875. uint8* const shadowChannel = (uint8*) shadowImage.lockPixelDataReadWrite (0, 0, w, h, destStride, destPixelStride);
  63876. const int filter = roundFloatToInt (63.0f / radius);
  63877. const int radiusMinus1 = roundFloatToInt ((radius - 1.0f) * 63.0f);
  63878. for (int x = w; --x >= 0;)
  63879. {
  63880. int shadowAlpha = 0;
  63881. const PixelARGB* src = srcPixels + x;
  63882. uint8* shadowPix = shadowChannel + x;
  63883. for (int y = h; --y >= 0;)
  63884. {
  63885. shadowAlpha = ((shadowAlpha * radiusMinus1 + (src->getAlpha() << 6)) * filter) >> 12;
  63886. *shadowPix = (uint8) shadowAlpha;
  63887. src = (const PixelARGB*) (((const uint8*) src) + lineStride);
  63888. shadowPix += destStride;
  63889. }
  63890. }
  63891. for (int y = h; --y >= 0;)
  63892. {
  63893. int shadowAlpha = 0;
  63894. uint8* shadowPix = shadowChannel + y * destStride;
  63895. for (int x = w; --x >= 0;)
  63896. {
  63897. shadowAlpha = ((shadowAlpha * radiusMinus1 + (*shadowPix << 6)) * filter) >> 12;
  63898. *shadowPix++ = (uint8) shadowAlpha;
  63899. }
  63900. }
  63901. image.releasePixelDataReadOnly (srcPixels);
  63902. shadowImage.releasePixelDataReadWrite (shadowChannel);
  63903. g.setColour (Colours::black.withAlpha (opacity));
  63904. g.drawImageAt (&shadowImage, offsetX, offsetY, true);
  63905. g.setOpacity (1.0f);
  63906. g.drawImageAt (&image, 0, 0);
  63907. }
  63908. END_JUCE_NAMESPACE
  63909. /********* End of inlined file: juce_DropShadowEffect.cpp *********/
  63910. /********* Start of inlined file: juce_GlowEffect.cpp *********/
  63911. BEGIN_JUCE_NAMESPACE
  63912. GlowEffect::GlowEffect()
  63913. : radius (2.0f),
  63914. colour (Colours::white)
  63915. {
  63916. }
  63917. GlowEffect::~GlowEffect()
  63918. {
  63919. }
  63920. void GlowEffect::setGlowProperties (const float newRadius,
  63921. const Colour& newColour)
  63922. {
  63923. radius = newRadius;
  63924. colour = newColour;
  63925. }
  63926. void GlowEffect::applyEffect (Image& image, Graphics& g)
  63927. {
  63928. const int w = image.getWidth();
  63929. const int h = image.getHeight();
  63930. Image temp (image.getFormat(), w, h, true);
  63931. ImageConvolutionKernel blurKernel (roundFloatToInt (radius * 2.0f));
  63932. blurKernel.createGaussianBlur (radius);
  63933. blurKernel.rescaleAllValues (radius);
  63934. blurKernel.applyToImage (temp, &image, 0, 0, w, h);
  63935. g.setColour (colour);
  63936. g.drawImageAt (&temp, 0, 0, true);
  63937. g.setOpacity (1.0f);
  63938. g.drawImageAt (&image, 0, 0, false);
  63939. }
  63940. END_JUCE_NAMESPACE
  63941. /********* End of inlined file: juce_GlowEffect.cpp *********/
  63942. /********* Start of inlined file: juce_ReduceOpacityEffect.cpp *********/
  63943. BEGIN_JUCE_NAMESPACE
  63944. ReduceOpacityEffect::ReduceOpacityEffect (const float opacity_)
  63945. : opacity (opacity_)
  63946. {
  63947. }
  63948. ReduceOpacityEffect::~ReduceOpacityEffect()
  63949. {
  63950. }
  63951. void ReduceOpacityEffect::setOpacity (const float newOpacity)
  63952. {
  63953. opacity = jlimit (0.0f, 1.0f, newOpacity);
  63954. }
  63955. void ReduceOpacityEffect::applyEffect (Image& image, Graphics& g)
  63956. {
  63957. g.setOpacity (opacity);
  63958. g.drawImageAt (&image, 0, 0);
  63959. }
  63960. END_JUCE_NAMESPACE
  63961. /********* End of inlined file: juce_ReduceOpacityEffect.cpp *********/
  63962. /********* Start of inlined file: juce_Font.cpp *********/
  63963. BEGIN_JUCE_NAMESPACE
  63964. static const float minFontHeight = 0.1f;
  63965. static const float maxFontHeight = 10000.0f;
  63966. static const float defaultFontHeight = 14.0f;
  63967. static String defaultSans, defaultSerif, defaultFixed, fallbackFont;
  63968. Font::Font() throw()
  63969. : typefaceName (defaultSans),
  63970. height (defaultFontHeight),
  63971. horizontalScale (1.0f),
  63972. kerning (0),
  63973. ascent (0),
  63974. styleFlags (Font::plain)
  63975. {
  63976. }
  63977. void Font::resetToDefaultState() throw()
  63978. {
  63979. typefaceName = defaultSans;
  63980. height = defaultFontHeight;
  63981. horizontalScale = 1.0f;
  63982. kerning = 0;
  63983. ascent = 0;
  63984. styleFlags = Font::plain;
  63985. typeface = 0;
  63986. }
  63987. Font::Font (const float fontHeight,
  63988. const int styleFlags_) throw()
  63989. : typefaceName (defaultSans),
  63990. height (jlimit (minFontHeight, maxFontHeight, fontHeight)),
  63991. horizontalScale (1.0f),
  63992. kerning (0),
  63993. ascent (0),
  63994. styleFlags (styleFlags_)
  63995. {
  63996. }
  63997. Font::Font (const String& typefaceName_,
  63998. const float fontHeight,
  63999. const int styleFlags_) throw()
  64000. : typefaceName (typefaceName_),
  64001. height (jlimit (minFontHeight, maxFontHeight, fontHeight)),
  64002. horizontalScale (1.0f),
  64003. kerning (0),
  64004. ascent (0),
  64005. styleFlags (styleFlags_)
  64006. {
  64007. }
  64008. Font::Font (const Font& other) throw()
  64009. : typefaceName (other.typefaceName),
  64010. height (other.height),
  64011. horizontalScale (other.horizontalScale),
  64012. kerning (other.kerning),
  64013. ascent (other.ascent),
  64014. styleFlags (other.styleFlags),
  64015. typeface (other.typeface)
  64016. {
  64017. }
  64018. const Font& Font::operator= (const Font& other) throw()
  64019. {
  64020. if (this != &other)
  64021. {
  64022. typefaceName = other.typefaceName;
  64023. height = other.height;
  64024. styleFlags = other.styleFlags;
  64025. horizontalScale = other.horizontalScale;
  64026. kerning = other.kerning;
  64027. ascent = other.ascent;
  64028. typeface = other.typeface;
  64029. }
  64030. return *this;
  64031. }
  64032. Font::~Font() throw()
  64033. {
  64034. }
  64035. Font::Font (const Typeface& face) throw()
  64036. : height (11.0f),
  64037. horizontalScale (1.0f),
  64038. kerning (0),
  64039. ascent (0),
  64040. styleFlags (plain)
  64041. {
  64042. typefaceName = face.getName();
  64043. setBold (face.isBold());
  64044. setItalic (face.isItalic());
  64045. typeface = new Typeface (face);
  64046. }
  64047. bool Font::operator== (const Font& other) const throw()
  64048. {
  64049. return height == other.height
  64050. && horizontalScale == other.horizontalScale
  64051. && kerning == other.kerning
  64052. && styleFlags == other.styleFlags
  64053. && typefaceName == other.typefaceName;
  64054. }
  64055. bool Font::operator!= (const Font& other) const throw()
  64056. {
  64057. return ! operator== (other);
  64058. }
  64059. void Font::setTypefaceName (const String& faceName) throw()
  64060. {
  64061. typefaceName = faceName;
  64062. typeface = 0;
  64063. ascent = 0;
  64064. }
  64065. void Font::initialiseDefaultFontNames() throw()
  64066. {
  64067. Font::getDefaultFontNames (defaultSans,
  64068. defaultSerif,
  64069. defaultFixed);
  64070. }
  64071. void clearUpDefaultFontNames() throw() // called at shutdown by code in Typface
  64072. {
  64073. defaultSans = String::empty;
  64074. defaultSerif = String::empty;
  64075. defaultFixed = String::empty;
  64076. fallbackFont = String::empty;
  64077. }
  64078. const String Font::getDefaultSansSerifFontName() throw()
  64079. {
  64080. return defaultSans;
  64081. }
  64082. const String Font::getDefaultSerifFontName() throw()
  64083. {
  64084. return defaultSerif;
  64085. }
  64086. const String Font::getDefaultMonospacedFontName() throw()
  64087. {
  64088. return defaultFixed;
  64089. }
  64090. void Font::setDefaultSansSerifFontName (const String& name) throw()
  64091. {
  64092. defaultSans = name;
  64093. }
  64094. const String Font::getFallbackFontName() throw()
  64095. {
  64096. return fallbackFont;
  64097. }
  64098. void Font::setFallbackFontName (const String& name) throw()
  64099. {
  64100. fallbackFont = name;
  64101. }
  64102. void Font::setHeight (float newHeight) throw()
  64103. {
  64104. height = jlimit (minFontHeight, maxFontHeight, newHeight);
  64105. }
  64106. void Font::setHeightWithoutChangingWidth (float newHeight) throw()
  64107. {
  64108. newHeight = jlimit (minFontHeight, maxFontHeight, newHeight);
  64109. horizontalScale *= (height / newHeight);
  64110. height = newHeight;
  64111. }
  64112. void Font::setStyleFlags (const int newFlags) throw()
  64113. {
  64114. if (styleFlags != newFlags)
  64115. {
  64116. styleFlags = newFlags;
  64117. typeface = 0;
  64118. ascent = 0;
  64119. }
  64120. }
  64121. void Font::setSizeAndStyle (const float newHeight,
  64122. const int newStyleFlags,
  64123. const float newHorizontalScale,
  64124. const float newKerningAmount) throw()
  64125. {
  64126. height = jlimit (minFontHeight, maxFontHeight, newHeight);
  64127. horizontalScale = newHorizontalScale;
  64128. kerning = newKerningAmount;
  64129. setStyleFlags (newStyleFlags);
  64130. }
  64131. void Font::setHorizontalScale (const float scaleFactor) throw()
  64132. {
  64133. horizontalScale = scaleFactor;
  64134. }
  64135. void Font::setExtraKerningFactor (const float extraKerning) throw()
  64136. {
  64137. kerning = extraKerning;
  64138. }
  64139. void Font::setBold (const bool shouldBeBold) throw()
  64140. {
  64141. setStyleFlags (shouldBeBold ? (styleFlags | bold)
  64142. : (styleFlags & ~bold));
  64143. }
  64144. bool Font::isBold() const throw()
  64145. {
  64146. return (styleFlags & bold) != 0;
  64147. }
  64148. void Font::setItalic (const bool shouldBeItalic) throw()
  64149. {
  64150. setStyleFlags (shouldBeItalic ? (styleFlags | italic)
  64151. : (styleFlags & ~italic));
  64152. }
  64153. bool Font::isItalic() const throw()
  64154. {
  64155. return (styleFlags & italic) != 0;
  64156. }
  64157. void Font::setUnderline (const bool shouldBeUnderlined) throw()
  64158. {
  64159. setStyleFlags (shouldBeUnderlined ? (styleFlags | underlined)
  64160. : (styleFlags & ~underlined));
  64161. }
  64162. bool Font::isUnderlined() const throw()
  64163. {
  64164. return (styleFlags & underlined) != 0;
  64165. }
  64166. float Font::getAscent() const throw()
  64167. {
  64168. if (ascent == 0)
  64169. ascent = getTypeface()->getAscent();
  64170. return height * ascent;
  64171. }
  64172. float Font::getDescent() const throw()
  64173. {
  64174. return height - getAscent();
  64175. }
  64176. int Font::getStringWidth (const String& text) const throw()
  64177. {
  64178. return roundFloatToInt (getStringWidthFloat (text));
  64179. }
  64180. float Font::getStringWidthFloat (const String& text) const throw()
  64181. {
  64182. float x = 0.0f;
  64183. if (text.isNotEmpty())
  64184. {
  64185. Typeface* const typeface = getTypeface();
  64186. const juce_wchar* t = (const juce_wchar*) text;
  64187. do
  64188. {
  64189. const TypefaceGlyphInfo* const glyph = typeface->getGlyph (*t++);
  64190. if (glyph != 0)
  64191. x += kerning + glyph->getHorizontalSpacing (*t);
  64192. }
  64193. while (*t != 0);
  64194. x *= height;
  64195. x *= horizontalScale;
  64196. }
  64197. return x;
  64198. }
  64199. Typeface* Font::getTypeface() const throw()
  64200. {
  64201. if (typeface == 0)
  64202. typeface = Typeface::getTypefaceFor (*this);
  64203. return typeface;
  64204. }
  64205. void Font::findFonts (OwnedArray<Font>& destArray) throw()
  64206. {
  64207. const StringArray names (findAllTypefaceNames());
  64208. for (int i = 0; i < names.size(); ++i)
  64209. destArray.add (new Font (names[i], defaultFontHeight, Font::plain));
  64210. }
  64211. END_JUCE_NAMESPACE
  64212. /********* End of inlined file: juce_Font.cpp *********/
  64213. /********* Start of inlined file: juce_GlyphArrangement.cpp *********/
  64214. BEGIN_JUCE_NAMESPACE
  64215. #define SHOULD_WRAP(x, wrapwidth) (((x) - 0.0001f) >= (wrapwidth))
  64216. class FontGlyphAlphaMap
  64217. {
  64218. public:
  64219. bool draw (const Graphics& g, float x, const float y) const throw()
  64220. {
  64221. if (bitmap1 == 0)
  64222. return false;
  64223. x += xOrigin;
  64224. const float xFloor = floorf (x);
  64225. const int intX = (int) xFloor;
  64226. g.drawImageAt (((x - xFloor) >= 0.5f && bitmap2 != 0) ? bitmap2 : bitmap1,
  64227. intX, (int) floorf (y + yOrigin), true);
  64228. return true;
  64229. }
  64230. juce_UseDebuggingNewOperator
  64231. private:
  64232. Image* bitmap1;
  64233. Image* bitmap2;
  64234. float xOrigin, yOrigin;
  64235. int lastAccessCount;
  64236. Typeface::Ptr typeface;
  64237. float height, horizontalScale;
  64238. juce_wchar character;
  64239. friend class GlyphCache;
  64240. FontGlyphAlphaMap() throw()
  64241. : bitmap1 (0),
  64242. bitmap2 (0),
  64243. lastAccessCount (0),
  64244. height (0),
  64245. horizontalScale (0),
  64246. character (0)
  64247. {
  64248. }
  64249. ~FontGlyphAlphaMap() throw()
  64250. {
  64251. delete bitmap1;
  64252. delete bitmap2;
  64253. }
  64254. class AlphaBitmapRenderer
  64255. {
  64256. uint8* const data;
  64257. const int stride;
  64258. uint8* lineStart;
  64259. AlphaBitmapRenderer (const AlphaBitmapRenderer&);
  64260. const AlphaBitmapRenderer& operator= (const AlphaBitmapRenderer&);
  64261. public:
  64262. AlphaBitmapRenderer (uint8* const data_,
  64263. const int stride_) throw()
  64264. : data (data_),
  64265. stride (stride_)
  64266. {
  64267. }
  64268. forcedinline void setEdgeTableYPos (const int y) throw()
  64269. {
  64270. lineStart = data + (stride * y);
  64271. }
  64272. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) const throw()
  64273. {
  64274. lineStart [x] = (uint8) alphaLevel;
  64275. }
  64276. forcedinline void handleEdgeTableLine (const int x, int width, const int alphaLevel) const throw()
  64277. {
  64278. uint8* d = lineStart + x;
  64279. while (--width >= 0)
  64280. *d++ = (uint8) alphaLevel;
  64281. }
  64282. };
  64283. Image* createAlphaMapFromPath (const Path& path,
  64284. float& topLeftX, float& topLeftY,
  64285. float xScale, float yScale,
  64286. const float subPixelOffsetX) throw()
  64287. {
  64288. Image* im = 0;
  64289. float px, py, pw, ph;
  64290. path.getBounds (px, py, pw, ph);
  64291. topLeftX = floorf (px * xScale);
  64292. topLeftY = floorf (py * yScale);
  64293. int bitmapWidth = roundFloatToInt (pw * xScale) + 2;
  64294. int bitmapHeight = roundFloatToInt (ph * yScale) + 2;
  64295. im = new Image (Image::SingleChannel, bitmapWidth, bitmapHeight, true);
  64296. EdgeTable edgeTable (0, bitmapHeight, EdgeTable::Oversampling_16times);
  64297. edgeTable.addPath (path, AffineTransform::scale (xScale, yScale)
  64298. .translated (subPixelOffsetX - topLeftX, -topLeftY));
  64299. int stride, pixelStride;
  64300. uint8* const pixels = (uint8*) im->lockPixelDataReadWrite (0, 0, bitmapWidth, bitmapHeight, stride, pixelStride);
  64301. jassert (pixelStride == 1);
  64302. AlphaBitmapRenderer renderer (pixels, stride);
  64303. edgeTable.iterate (renderer, 0, 0, bitmapWidth, bitmapHeight, 0);
  64304. im->releasePixelDataReadWrite (pixels);
  64305. return im;
  64306. }
  64307. void generate (Typeface* const face,
  64308. const juce_wchar character_,
  64309. const float fontHeight,
  64310. const float fontHorizontalScale) throw()
  64311. {
  64312. character = character_;
  64313. typeface = face;
  64314. height = fontHeight;
  64315. horizontalScale = fontHorizontalScale;
  64316. const Path* const glyphPath = face->getOutlineForGlyph (character_);
  64317. deleteAndZero (bitmap1);
  64318. deleteAndZero (bitmap2);
  64319. const float fontHScale = fontHeight * fontHorizontalScale;
  64320. if (glyphPath != 0 && ! glyphPath->isEmpty())
  64321. {
  64322. bitmap1 = createAlphaMapFromPath (*glyphPath, xOrigin, yOrigin, fontHScale, fontHeight, 0.0f);
  64323. if (fontHScale < 24.0f)
  64324. bitmap2 = createAlphaMapFromPath (*glyphPath, xOrigin, yOrigin, fontHScale, fontHeight, 0.5f);
  64325. }
  64326. else
  64327. {
  64328. xOrigin = yOrigin = 0;
  64329. }
  64330. }
  64331. };
  64332. static const int defaultNumGlyphsToCache = 120;
  64333. class GlyphCache;
  64334. static GlyphCache* cacheInstance = 0;
  64335. class GlyphCache : private DeletedAtShutdown
  64336. {
  64337. public:
  64338. static GlyphCache* getInstance() throw()
  64339. {
  64340. if (cacheInstance == 0)
  64341. cacheInstance = new GlyphCache();
  64342. return cacheInstance;
  64343. }
  64344. const FontGlyphAlphaMap& getGlyphFor (Typeface* const typeface,
  64345. const float fontHeight,
  64346. const float fontHorizontalScale,
  64347. const juce_wchar character) throw()
  64348. {
  64349. ++accessCounter;
  64350. int oldestCounter = INT_MAX;
  64351. int oldestIndex = 0;
  64352. for (int i = numGlyphs; --i >= 0;)
  64353. {
  64354. FontGlyphAlphaMap& g = glyphs[i];
  64355. if (g.character == character
  64356. && g.height == fontHeight
  64357. && g.typeface->hashCode() == typeface->hashCode()
  64358. && g.horizontalScale == fontHorizontalScale)
  64359. {
  64360. g.lastAccessCount = accessCounter;
  64361. ++hits;
  64362. return g;
  64363. }
  64364. if (oldestCounter > g.lastAccessCount)
  64365. {
  64366. oldestCounter = g.lastAccessCount;
  64367. oldestIndex = i;
  64368. }
  64369. }
  64370. ++misses;
  64371. if (hits + misses > (numGlyphs << 4))
  64372. {
  64373. if (misses * 2 > hits)
  64374. setCacheSize (numGlyphs + 32);
  64375. hits = 0;
  64376. misses = 0;
  64377. oldestIndex = 0;
  64378. }
  64379. FontGlyphAlphaMap& oldest = glyphs [oldestIndex];
  64380. oldest.lastAccessCount = accessCounter;
  64381. oldest.generate (typeface,
  64382. character,
  64383. fontHeight,
  64384. fontHorizontalScale);
  64385. return oldest;
  64386. }
  64387. void setCacheSize (const int num) throw()
  64388. {
  64389. if (numGlyphs != num)
  64390. {
  64391. numGlyphs = num;
  64392. if (glyphs != 0)
  64393. delete[] glyphs;
  64394. glyphs = new FontGlyphAlphaMap [numGlyphs];
  64395. hits = 0;
  64396. misses = 0;
  64397. }
  64398. }
  64399. juce_UseDebuggingNewOperator
  64400. private:
  64401. FontGlyphAlphaMap* glyphs;
  64402. int numGlyphs, accessCounter;
  64403. int hits, misses;
  64404. GlyphCache() throw()
  64405. : glyphs (0),
  64406. numGlyphs (0),
  64407. accessCounter (0)
  64408. {
  64409. setCacheSize (defaultNumGlyphsToCache);
  64410. }
  64411. ~GlyphCache() throw()
  64412. {
  64413. delete[] glyphs;
  64414. jassert (cacheInstance == this);
  64415. cacheInstance = 0;
  64416. }
  64417. GlyphCache (const GlyphCache&);
  64418. const GlyphCache& operator= (const GlyphCache&);
  64419. };
  64420. PositionedGlyph::PositionedGlyph() throw()
  64421. {
  64422. }
  64423. void PositionedGlyph::draw (const Graphics& g) const throw()
  64424. {
  64425. if (! glyphInfo->isWhitespace())
  64426. {
  64427. if (fontHeight < 100.0f && fontHeight > 0.1f && ! g.isVectorDevice())
  64428. {
  64429. const FontGlyphAlphaMap& alphaMap
  64430. = GlyphCache::getInstance()->getGlyphFor (glyphInfo->getTypeface(),
  64431. fontHeight,
  64432. fontHorizontalScale,
  64433. getCharacter());
  64434. alphaMap.draw (g, x, y);
  64435. }
  64436. else
  64437. {
  64438. // that's a bit of a dodgy size, isn't it??
  64439. jassert (fontHeight > 0.0f && fontHeight < 4000.0f);
  64440. draw (g, AffineTransform::identity);
  64441. }
  64442. }
  64443. }
  64444. void PositionedGlyph::draw (const Graphics& g,
  64445. const AffineTransform& transform) const throw()
  64446. {
  64447. if (! glyphInfo->isWhitespace())
  64448. {
  64449. g.fillPath (glyphInfo->getPath(),
  64450. AffineTransform::scale (fontHeight * fontHorizontalScale, fontHeight)
  64451. .translated (x, y)
  64452. .followedBy (transform));
  64453. }
  64454. }
  64455. void PositionedGlyph::createPath (Path& path) const throw()
  64456. {
  64457. if (! glyphInfo->isWhitespace())
  64458. {
  64459. path.addPath (glyphInfo->getPath(),
  64460. AffineTransform::scale (fontHeight * fontHorizontalScale, fontHeight)
  64461. .translated (x, y));
  64462. }
  64463. }
  64464. bool PositionedGlyph::hitTest (float px, float py) const throw()
  64465. {
  64466. if (px >= getLeft() && px < getRight()
  64467. && py >= getTop() && py < getBottom()
  64468. && fontHeight > 0.0f
  64469. && ! glyphInfo->isWhitespace())
  64470. {
  64471. AffineTransform::translation (-x, -y)
  64472. .scaled (1.0f / (fontHeight * fontHorizontalScale), 1.0f / fontHeight)
  64473. .transformPoint (px, py);
  64474. return glyphInfo->getPath().contains (px, py);
  64475. }
  64476. return false;
  64477. }
  64478. void PositionedGlyph::moveBy (const float deltaX,
  64479. const float deltaY) throw()
  64480. {
  64481. x += deltaX;
  64482. y += deltaY;
  64483. }
  64484. GlyphArrangement::GlyphArrangement() throw()
  64485. : numGlyphs (0),
  64486. numAllocated (0),
  64487. glyphs (0)
  64488. {
  64489. }
  64490. GlyphArrangement::GlyphArrangement (const GlyphArrangement& other) throw()
  64491. : numGlyphs (0),
  64492. numAllocated (0),
  64493. glyphs (0)
  64494. {
  64495. addGlyphArrangement (other);
  64496. }
  64497. const GlyphArrangement& GlyphArrangement::operator= (const GlyphArrangement& other) throw()
  64498. {
  64499. if (this != &other)
  64500. {
  64501. clear();
  64502. addGlyphArrangement (other);
  64503. }
  64504. return *this;
  64505. }
  64506. GlyphArrangement::~GlyphArrangement() throw()
  64507. {
  64508. clear();
  64509. juce_free (glyphs);
  64510. }
  64511. void GlyphArrangement::ensureNumGlyphsAllocated (const int minGlyphs) throw()
  64512. {
  64513. if (numAllocated <= minGlyphs)
  64514. {
  64515. numAllocated = minGlyphs + 2;
  64516. if (glyphs == 0)
  64517. glyphs = (PositionedGlyph*) juce_malloc (numAllocated * sizeof (PositionedGlyph));
  64518. else
  64519. glyphs = (PositionedGlyph*) juce_realloc (glyphs, numAllocated * sizeof (PositionedGlyph));
  64520. }
  64521. }
  64522. void GlyphArrangement::incGlyphRefCount (const int i) const throw()
  64523. {
  64524. jassert (((unsigned int) i) < (unsigned int) numGlyphs);
  64525. if (glyphs[i].glyphInfo != 0 && glyphs[i].glyphInfo->getTypeface() != 0)
  64526. glyphs[i].glyphInfo->getTypeface()->incReferenceCount();
  64527. }
  64528. void GlyphArrangement::decGlyphRefCount (const int i) const throw()
  64529. {
  64530. if (glyphs[i].glyphInfo != 0 && glyphs[i].glyphInfo->getTypeface() != 0)
  64531. glyphs[i].glyphInfo->getTypeface()->decReferenceCount();
  64532. }
  64533. void GlyphArrangement::clear() throw()
  64534. {
  64535. for (int i = numGlyphs; --i >= 0;)
  64536. decGlyphRefCount (i);
  64537. numGlyphs = 0;
  64538. }
  64539. PositionedGlyph& GlyphArrangement::getGlyph (const int index) const throw()
  64540. {
  64541. jassert (((unsigned int) index) < (unsigned int) numGlyphs);
  64542. return glyphs [index];
  64543. }
  64544. void GlyphArrangement::addGlyphArrangement (const GlyphArrangement& other) throw()
  64545. {
  64546. ensureNumGlyphsAllocated (numGlyphs + other.numGlyphs);
  64547. memcpy (glyphs + numGlyphs, other.glyphs,
  64548. other.numGlyphs * sizeof (PositionedGlyph));
  64549. for (int i = other.numGlyphs; --i >= 0;)
  64550. incGlyphRefCount (numGlyphs++);
  64551. }
  64552. void GlyphArrangement::removeLast() throw()
  64553. {
  64554. if (numGlyphs > 0)
  64555. decGlyphRefCount (--numGlyphs);
  64556. }
  64557. void GlyphArrangement::removeRangeOfGlyphs (int startIndex, const int num) throw()
  64558. {
  64559. jassert (startIndex >= 0);
  64560. if (startIndex < 0)
  64561. startIndex = 0;
  64562. if (num < 0 || startIndex + num >= numGlyphs)
  64563. {
  64564. while (numGlyphs > startIndex)
  64565. removeLast();
  64566. }
  64567. else if (num > 0)
  64568. {
  64569. int i;
  64570. for (i = startIndex; i < startIndex + num; ++i)
  64571. decGlyphRefCount (i);
  64572. for (i = numGlyphs - (startIndex + num); --i >= 0;)
  64573. {
  64574. glyphs [startIndex] = glyphs [startIndex + num];
  64575. ++startIndex;
  64576. }
  64577. numGlyphs -= num;
  64578. }
  64579. }
  64580. void GlyphArrangement::addLineOfText (const Font& font,
  64581. const String& text,
  64582. const float xOffset,
  64583. const float yOffset) throw()
  64584. {
  64585. addCurtailedLineOfText (font, text,
  64586. xOffset, yOffset,
  64587. 1.0e10f, false);
  64588. }
  64589. void GlyphArrangement::addCurtailedLineOfText (const Font& font,
  64590. const String& text,
  64591. float xOffset,
  64592. const float yOffset,
  64593. const float maxWidthPixels,
  64594. const bool useEllipsis) throw()
  64595. {
  64596. const int textLen = text.length();
  64597. if (textLen > 0)
  64598. {
  64599. ensureNumGlyphsAllocated (numGlyphs + textLen + 3); // extra chars for ellipsis
  64600. Typeface* const typeface = font.getTypeface();
  64601. const float fontHeight = font.getHeight();
  64602. const float ascent = font.getAscent();
  64603. const float fontHorizontalScale = font.getHorizontalScale();
  64604. const float heightTimesScale = fontHorizontalScale * fontHeight;
  64605. const float kerningFactor = font.getExtraKerningFactor();
  64606. const float startX = xOffset;
  64607. const juce_wchar* const unicodeText = (const juce_wchar*) text;
  64608. for (int i = 0; i < textLen; ++i)
  64609. {
  64610. const TypefaceGlyphInfo* const glyph = typeface->getGlyph (unicodeText[i]);
  64611. if (glyph != 0)
  64612. {
  64613. jassert (numAllocated > numGlyphs);
  64614. ensureNumGlyphsAllocated (numGlyphs);
  64615. PositionedGlyph& pg = glyphs [numGlyphs];
  64616. pg.glyphInfo = glyph;
  64617. pg.x = xOffset;
  64618. pg.y = yOffset;
  64619. pg.w = heightTimesScale * glyph->getHorizontalSpacing (0);
  64620. pg.fontHeight = fontHeight;
  64621. pg.fontAscent = ascent;
  64622. pg.fontHorizontalScale = fontHorizontalScale;
  64623. pg.isUnderlined = font.isUnderlined();
  64624. xOffset += heightTimesScale * (kerningFactor + glyph->getHorizontalSpacing (unicodeText [i + 1]));
  64625. if (xOffset - startX > maxWidthPixels + 1.0f)
  64626. {
  64627. // curtail the string if it's too wide..
  64628. if (useEllipsis && textLen > 3 && numGlyphs >= 3)
  64629. appendEllipsis (font, startX + maxWidthPixels);
  64630. break;
  64631. }
  64632. else
  64633. {
  64634. if (glyph->getTypeface() != 0)
  64635. glyph->getTypeface()->incReferenceCount();
  64636. ++numGlyphs;
  64637. }
  64638. }
  64639. }
  64640. }
  64641. }
  64642. void GlyphArrangement::appendEllipsis (const Font& font, const float maxXPixels) throw()
  64643. {
  64644. const TypefaceGlyphInfo* const dotGlyph = font.getTypeface()->getGlyph (T('.'));
  64645. if (dotGlyph != 0)
  64646. {
  64647. if (numGlyphs > 0)
  64648. {
  64649. PositionedGlyph& glyph = glyphs [numGlyphs - 1];
  64650. const float fontHeight = glyph.fontHeight;
  64651. const float fontHorizontalScale = glyph.fontHorizontalScale;
  64652. const float fontAscent = glyph.fontAscent;
  64653. const float dx = fontHeight * fontHorizontalScale
  64654. * (font.getExtraKerningFactor() + dotGlyph->getHorizontalSpacing (T('.')));
  64655. float xOffset = 0.0f, yOffset = 0.0f;
  64656. for (int dotPos = 3; --dotPos >= 0 && numGlyphs > 0;)
  64657. {
  64658. removeLast();
  64659. jassert (numAllocated > numGlyphs);
  64660. PositionedGlyph& pg = glyphs [numGlyphs];
  64661. xOffset = pg.x;
  64662. yOffset = pg.y;
  64663. if (numGlyphs == 0 || xOffset + dx * 3 <= maxXPixels)
  64664. break;
  64665. }
  64666. for (int i = 3; --i >= 0;)
  64667. {
  64668. jassert (numAllocated > numGlyphs);
  64669. ensureNumGlyphsAllocated (numGlyphs);
  64670. PositionedGlyph& pg = glyphs [numGlyphs];
  64671. pg.glyphInfo = dotGlyph;
  64672. pg.x = xOffset;
  64673. pg.y = yOffset;
  64674. pg.w = dx;
  64675. pg.fontHeight = fontHeight;
  64676. pg.fontAscent = fontAscent;
  64677. pg.fontHorizontalScale = fontHorizontalScale;
  64678. pg.isUnderlined = font.isUnderlined();
  64679. xOffset += dx;
  64680. if (dotGlyph->getTypeface() != 0)
  64681. dotGlyph->getTypeface()->incReferenceCount();
  64682. ++numGlyphs;
  64683. }
  64684. }
  64685. }
  64686. }
  64687. void GlyphArrangement::addJustifiedText (const Font& font,
  64688. const String& text,
  64689. float x, float y,
  64690. const float maxLineWidth,
  64691. const Justification& horizontalLayout) throw()
  64692. {
  64693. int lineStartIndex = numGlyphs;
  64694. addLineOfText (font, text, x, y);
  64695. const float originalY = y;
  64696. while (lineStartIndex < numGlyphs)
  64697. {
  64698. int i = lineStartIndex;
  64699. if (glyphs[i].getCharacter() != T('\n') && glyphs[i].getCharacter() != T('\r'))
  64700. ++i;
  64701. const float lineMaxX = glyphs [lineStartIndex].getLeft() + maxLineWidth;
  64702. int lastWordBreakIndex = -1;
  64703. while (i < numGlyphs)
  64704. {
  64705. PositionedGlyph& pg = glyphs[i];
  64706. const juce_wchar c = pg.getCharacter();
  64707. if (c == T('\r') || c == T('\n'))
  64708. {
  64709. ++i;
  64710. if (c == T('\r') && i < numGlyphs && glyphs [i].getCharacter() == T('\n'))
  64711. ++i;
  64712. break;
  64713. }
  64714. else if (pg.isWhitespace())
  64715. {
  64716. lastWordBreakIndex = i + 1;
  64717. }
  64718. else if (SHOULD_WRAP (pg.getRight(), lineMaxX))
  64719. {
  64720. if (lastWordBreakIndex >= 0)
  64721. i = lastWordBreakIndex;
  64722. break;
  64723. }
  64724. ++i;
  64725. }
  64726. const float currentLineStartX = glyphs [lineStartIndex].getLeft();
  64727. float currentLineEndX = currentLineStartX;
  64728. for (int j = i; --j >= lineStartIndex;)
  64729. {
  64730. if (! glyphs[j].isWhitespace())
  64731. {
  64732. currentLineEndX = glyphs[j].getRight();
  64733. break;
  64734. }
  64735. }
  64736. float deltaX = 0.0f;
  64737. if (horizontalLayout.testFlags (Justification::horizontallyJustified))
  64738. spreadOutLine (lineStartIndex, i - lineStartIndex, maxLineWidth);
  64739. else if (horizontalLayout.testFlags (Justification::horizontallyCentred))
  64740. deltaX = (maxLineWidth - (currentLineEndX - currentLineStartX)) * 0.5f;
  64741. else if (horizontalLayout.testFlags (Justification::right))
  64742. deltaX = maxLineWidth - (currentLineEndX - currentLineStartX);
  64743. moveRangeOfGlyphs (lineStartIndex, i - lineStartIndex,
  64744. x + deltaX - currentLineStartX, y - originalY);
  64745. lineStartIndex = i;
  64746. y += font.getHeight();
  64747. }
  64748. }
  64749. void GlyphArrangement::addFittedText (const Font& f,
  64750. const String& text,
  64751. float x, float y,
  64752. float width, float height,
  64753. const Justification& layout,
  64754. int maximumLines,
  64755. const float minimumHorizontalScale) throw()
  64756. {
  64757. // doesn't make much sense if this is outside a sensible range of 0.5 to 1.0
  64758. jassert (minimumHorizontalScale > 0 && minimumHorizontalScale <= 1.0f);
  64759. if (text.containsAnyOf (T("\r\n")))
  64760. {
  64761. GlyphArrangement ga;
  64762. ga.addJustifiedText (f, text, x, y, width, layout);
  64763. float l, t, r, b;
  64764. ga.getBoundingBox (0, -1, l, t, r, b, false);
  64765. float dy = y - t;
  64766. if (layout.testFlags (Justification::verticallyCentred))
  64767. dy += (height - (b - t)) * 0.5f;
  64768. else if (layout.testFlags (Justification::bottom))
  64769. dy += height - (b - t);
  64770. ga.moveRangeOfGlyphs (0, -1, 0.0f, dy);
  64771. addGlyphArrangement (ga);
  64772. return;
  64773. }
  64774. int startIndex = numGlyphs;
  64775. addLineOfText (f, text.trim(), x, y);
  64776. if (numGlyphs > startIndex)
  64777. {
  64778. float lineWidth = glyphs[numGlyphs - 1].getRight() - glyphs[startIndex].getLeft();
  64779. if (lineWidth <= 0)
  64780. return;
  64781. if (lineWidth * minimumHorizontalScale < width)
  64782. {
  64783. if (lineWidth > width)
  64784. {
  64785. stretchRangeOfGlyphs (startIndex, numGlyphs - startIndex,
  64786. width / lineWidth);
  64787. }
  64788. justifyGlyphs (startIndex, numGlyphs - startIndex,
  64789. x, y, width, height, layout);
  64790. }
  64791. else if (maximumLines <= 1)
  64792. {
  64793. const float ratio = jmax (minimumHorizontalScale, width / lineWidth);
  64794. stretchRangeOfGlyphs (startIndex, numGlyphs - startIndex, ratio);
  64795. while (numGlyphs > 0 && glyphs [numGlyphs - 1].x + glyphs [numGlyphs - 1].w >= x + width)
  64796. removeLast();
  64797. appendEllipsis (f, x + width);
  64798. justifyGlyphs (startIndex, numGlyphs - startIndex,
  64799. x, y, width, height, layout);
  64800. }
  64801. else
  64802. {
  64803. Font font (f);
  64804. String txt (text.trim());
  64805. const int length = txt.length();
  64806. int numLines = 1;
  64807. const int originalStartIndex = startIndex;
  64808. if (length <= 12 && ! txt.containsAnyOf (T(" -\t\r\n")))
  64809. maximumLines = 1;
  64810. maximumLines = jmin (maximumLines, length);
  64811. while (numLines < maximumLines)
  64812. {
  64813. ++numLines;
  64814. const float newFontHeight = height / (float)numLines;
  64815. if (newFontHeight < 8.0f)
  64816. break;
  64817. if (newFontHeight < font.getHeight())
  64818. {
  64819. font.setHeight (newFontHeight);
  64820. while (numGlyphs > startIndex)
  64821. removeLast();
  64822. addLineOfText (font, txt, x, y);
  64823. lineWidth = glyphs[numGlyphs - 1].getRight() - glyphs[startIndex].getLeft();
  64824. }
  64825. if (numLines > lineWidth / width)
  64826. break;
  64827. }
  64828. if (numLines < 1)
  64829. numLines = 1;
  64830. float lineY = y;
  64831. float widthPerLine = lineWidth / numLines;
  64832. int lastLineStartIndex = 0;
  64833. for (int line = 0; line < numLines; ++line)
  64834. {
  64835. int i = startIndex;
  64836. lastLineStartIndex = i;
  64837. float lineStartX = glyphs[startIndex].getLeft();
  64838. while (i < numGlyphs)
  64839. {
  64840. lineWidth = (glyphs[i].getRight() - lineStartX);
  64841. if (lineWidth > widthPerLine)
  64842. {
  64843. // got to a point where the line's too long, so skip forward to find a
  64844. // good place to break it..
  64845. const int searchStartIndex = i;
  64846. while (i < numGlyphs)
  64847. {
  64848. if ((glyphs[i].getRight() - lineStartX) * minimumHorizontalScale < width)
  64849. {
  64850. if (glyphs[i].isWhitespace()
  64851. || glyphs[i].getCharacter() == T('-'))
  64852. {
  64853. ++i;
  64854. break;
  64855. }
  64856. }
  64857. else
  64858. {
  64859. // can't find a suitable break, so try looking backwards..
  64860. i = searchStartIndex;
  64861. for (int back = 1; back < jmin (5, i - startIndex - 1); ++back)
  64862. {
  64863. if (glyphs[i - back].isWhitespace()
  64864. || glyphs[i - back].getCharacter() == T('-'))
  64865. {
  64866. i -= back - 1;
  64867. break;
  64868. }
  64869. }
  64870. break;
  64871. }
  64872. ++i;
  64873. }
  64874. break;
  64875. }
  64876. ++i;
  64877. }
  64878. int wsStart = i;
  64879. while (wsStart > 0 && glyphs[wsStart - 1].isWhitespace())
  64880. --wsStart;
  64881. int wsEnd = i;
  64882. while (wsEnd < numGlyphs && glyphs[wsEnd].isWhitespace())
  64883. ++wsEnd;
  64884. removeRangeOfGlyphs (wsStart, wsEnd - wsStart);
  64885. i = jmax (wsStart, startIndex + 1);
  64886. lineWidth = glyphs[i - 1].getRight() - lineStartX;
  64887. if (lineWidth > width)
  64888. {
  64889. stretchRangeOfGlyphs (startIndex, i - startIndex,
  64890. width / lineWidth);
  64891. }
  64892. justifyGlyphs (startIndex, i - startIndex,
  64893. x, lineY, width, font.getHeight(),
  64894. layout.getOnlyHorizontalFlags() | Justification::verticallyCentred);
  64895. startIndex = i;
  64896. lineY += font.getHeight();
  64897. if (startIndex >= numGlyphs)
  64898. break;
  64899. }
  64900. if (startIndex < numGlyphs)
  64901. {
  64902. while (numGlyphs > startIndex)
  64903. removeLast();
  64904. if (startIndex - originalStartIndex > 4)
  64905. {
  64906. const float lineStartX = glyphs[lastLineStartIndex].getLeft();
  64907. appendEllipsis (font, lineStartX + width);
  64908. lineWidth = glyphs[startIndex - 1].getRight() - lineStartX;
  64909. if (lineWidth > width)
  64910. {
  64911. stretchRangeOfGlyphs (lastLineStartIndex, startIndex - lastLineStartIndex,
  64912. width / lineWidth);
  64913. }
  64914. justifyGlyphs (lastLineStartIndex, startIndex - lastLineStartIndex,
  64915. x, lineY - font.getHeight(), width, font.getHeight(),
  64916. layout.getOnlyHorizontalFlags() | Justification::verticallyCentred);
  64917. }
  64918. startIndex = numGlyphs;
  64919. }
  64920. justifyGlyphs (originalStartIndex, startIndex - originalStartIndex,
  64921. x, y, width, height, layout.getFlags() & ~Justification::horizontallyJustified);
  64922. }
  64923. }
  64924. }
  64925. void GlyphArrangement::moveRangeOfGlyphs (int startIndex, int num,
  64926. const float dx, const float dy) throw()
  64927. {
  64928. jassert (startIndex >= 0);
  64929. if (dx != 0.0f || dy != 0.0f)
  64930. {
  64931. if (num < 0 || startIndex + num > numGlyphs)
  64932. num = numGlyphs - startIndex;
  64933. while (--num >= 0)
  64934. {
  64935. jassert (((unsigned int) startIndex) <= (unsigned int) numGlyphs);
  64936. glyphs [startIndex++].moveBy (dx, dy);
  64937. }
  64938. }
  64939. }
  64940. void GlyphArrangement::stretchRangeOfGlyphs (int startIndex, int num,
  64941. const float horizontalScaleFactor) throw()
  64942. {
  64943. jassert (startIndex >= 0);
  64944. if (num < 0 || startIndex + num > numGlyphs)
  64945. num = numGlyphs - startIndex;
  64946. if (num > 0)
  64947. {
  64948. const float xAnchor = glyphs[startIndex].getLeft();
  64949. while (--num >= 0)
  64950. {
  64951. jassert (((unsigned int) startIndex) <= (unsigned int) numGlyphs);
  64952. PositionedGlyph& pg = glyphs[startIndex++];
  64953. pg.x = xAnchor + (pg.x - xAnchor) * horizontalScaleFactor;
  64954. pg.fontHorizontalScale *= horizontalScaleFactor;
  64955. pg.w *= horizontalScaleFactor;
  64956. }
  64957. }
  64958. }
  64959. void GlyphArrangement::getBoundingBox (int startIndex, int num,
  64960. float& left,
  64961. float& top,
  64962. float& right,
  64963. float& bottom,
  64964. const bool includeWhitespace) const throw()
  64965. {
  64966. jassert (startIndex >= 0);
  64967. if (num < 0 || startIndex + num > numGlyphs)
  64968. num = numGlyphs - startIndex;
  64969. left = 0.0f;
  64970. top = 0.0f;
  64971. right = 0.0f;
  64972. bottom = 0.0f;
  64973. bool isFirst = true;
  64974. while (--num >= 0)
  64975. {
  64976. const PositionedGlyph& pg = glyphs [startIndex++];
  64977. if (includeWhitespace || ! pg.isWhitespace())
  64978. {
  64979. if (isFirst)
  64980. {
  64981. isFirst = false;
  64982. left = pg.getLeft();
  64983. top = pg.getTop();
  64984. right = pg.getRight();
  64985. bottom = pg.getBottom();
  64986. }
  64987. else
  64988. {
  64989. left = jmin (left, pg.getLeft());
  64990. top = jmin (top, pg.getTop());
  64991. right = jmax (right, pg.getRight());
  64992. bottom = jmax (bottom, pg.getBottom());
  64993. }
  64994. }
  64995. }
  64996. }
  64997. void GlyphArrangement::justifyGlyphs (const int startIndex,
  64998. const int num,
  64999. const float x, const float y,
  65000. const float width, const float height,
  65001. const Justification& justification) throw()
  65002. {
  65003. jassert (num >= 0 && startIndex >= 0);
  65004. if (numGlyphs > 0 && num > 0)
  65005. {
  65006. float left, top, right, bottom;
  65007. getBoundingBox (startIndex, num, left, top, right, bottom,
  65008. ! justification.testFlags (Justification::horizontallyJustified
  65009. | Justification::horizontallyCentred));
  65010. float deltaX = 0.0f;
  65011. if (justification.testFlags (Justification::horizontallyJustified))
  65012. deltaX = x - left;
  65013. else if (justification.testFlags (Justification::horizontallyCentred))
  65014. deltaX = x + (width - (right - left)) * 0.5f - left;
  65015. else if (justification.testFlags (Justification::right))
  65016. deltaX = (x + width) - right;
  65017. else
  65018. deltaX = x - left;
  65019. float deltaY = 0.0f;
  65020. if (justification.testFlags (Justification::top))
  65021. deltaY = y - top;
  65022. else if (justification.testFlags (Justification::bottom))
  65023. deltaY = (y + height) - bottom;
  65024. else
  65025. deltaY = y + (height - (bottom - top)) * 0.5f - top;
  65026. moveRangeOfGlyphs (startIndex, num, deltaX, deltaY);
  65027. if (justification.testFlags (Justification::horizontallyJustified))
  65028. {
  65029. int lineStart = 0;
  65030. float baseY = glyphs [startIndex].getBaselineY();
  65031. int i;
  65032. for (i = 0; i < num; ++i)
  65033. {
  65034. const float glyphY = glyphs [startIndex + i].getBaselineY();
  65035. if (glyphY != baseY)
  65036. {
  65037. spreadOutLine (startIndex + lineStart, i - lineStart, width);
  65038. lineStart = i;
  65039. baseY = glyphY;
  65040. }
  65041. }
  65042. if (i > lineStart)
  65043. spreadOutLine (startIndex + lineStart, i - lineStart, width);
  65044. }
  65045. }
  65046. }
  65047. void GlyphArrangement::spreadOutLine (const int start, const int num, const float targetWidth) throw()
  65048. {
  65049. if (start + num < numGlyphs
  65050. && glyphs [start + num - 1].getCharacter() != T('\r')
  65051. && glyphs [start + num - 1].getCharacter() != T('\n'))
  65052. {
  65053. int numSpaces = 0;
  65054. int spacesAtEnd = 0;
  65055. for (int i = 0; i < num; ++i)
  65056. {
  65057. if (glyphs [start + i].isWhitespace())
  65058. {
  65059. ++spacesAtEnd;
  65060. ++numSpaces;
  65061. }
  65062. else
  65063. {
  65064. spacesAtEnd = 0;
  65065. }
  65066. }
  65067. numSpaces -= spacesAtEnd;
  65068. if (numSpaces > 0)
  65069. {
  65070. const float startX = glyphs [start].getLeft();
  65071. const float endX = glyphs [start + num - 1 - spacesAtEnd].getRight();
  65072. const float extraPaddingBetweenWords
  65073. = (targetWidth - (endX - startX)) / (float) numSpaces;
  65074. float deltaX = 0.0f;
  65075. for (int i = 0; i < num; ++i)
  65076. {
  65077. glyphs [start + i].moveBy (deltaX, 0.0);
  65078. if (glyphs [start + i].isWhitespace())
  65079. deltaX += extraPaddingBetweenWords;
  65080. }
  65081. }
  65082. }
  65083. }
  65084. void GlyphArrangement::draw (const Graphics& g) const throw()
  65085. {
  65086. for (int i = 0; i < numGlyphs; ++i)
  65087. {
  65088. glyphs[i].draw (g);
  65089. if (glyphs[i].isUnderlined)
  65090. {
  65091. const float lineThickness = (glyphs[i].fontHeight - glyphs[i].fontAscent) * 0.3f;
  65092. juce_wchar nextChar = 0;
  65093. if (i < numGlyphs - 1
  65094. && glyphs[i + 1].y == glyphs[i].y)
  65095. {
  65096. nextChar = glyphs[i + 1].glyphInfo->getCharacter();
  65097. }
  65098. g.fillRect (glyphs[i].x,
  65099. glyphs[i].y + lineThickness * 2.0f,
  65100. glyphs[i].fontHeight
  65101. * glyphs[i].fontHorizontalScale
  65102. * glyphs[i].glyphInfo->getHorizontalSpacing (nextChar),
  65103. lineThickness);
  65104. }
  65105. }
  65106. }
  65107. void GlyphArrangement::draw (const Graphics& g, const AffineTransform& transform) const throw()
  65108. {
  65109. for (int i = 0; i < numGlyphs; ++i)
  65110. {
  65111. glyphs[i].draw (g, transform);
  65112. if (glyphs[i].isUnderlined)
  65113. {
  65114. const float lineThickness = (glyphs[i].fontHeight - glyphs[i].fontAscent) * 0.3f;
  65115. juce_wchar nextChar = 0;
  65116. if (i < numGlyphs - 1
  65117. && glyphs[i + 1].y == glyphs[i].y)
  65118. {
  65119. nextChar = glyphs[i + 1].glyphInfo->getCharacter();
  65120. }
  65121. Path p;
  65122. p.addLineSegment (glyphs[i].x,
  65123. glyphs[i].y + lineThickness * 2.5f,
  65124. glyphs[i].x + glyphs[i].fontHeight
  65125. * glyphs[i].fontHorizontalScale
  65126. * glyphs[i].glyphInfo->getHorizontalSpacing (nextChar),
  65127. glyphs[i].y + lineThickness * 2.5f,
  65128. lineThickness);
  65129. g.fillPath (p, transform);
  65130. }
  65131. }
  65132. }
  65133. void GlyphArrangement::createPath (Path& path) const throw()
  65134. {
  65135. for (int i = 0; i < numGlyphs; ++i)
  65136. glyphs[i].createPath (path);
  65137. }
  65138. int GlyphArrangement::findGlyphIndexAt (float x, float y) const throw()
  65139. {
  65140. for (int i = 0; i < numGlyphs; ++i)
  65141. if (glyphs[i].hitTest (x, y))
  65142. return i;
  65143. return -1;
  65144. }
  65145. END_JUCE_NAMESPACE
  65146. /********* End of inlined file: juce_GlyphArrangement.cpp *********/
  65147. /********* Start of inlined file: juce_TextLayout.cpp *********/
  65148. BEGIN_JUCE_NAMESPACE
  65149. class TextLayoutToken
  65150. {
  65151. public:
  65152. String text;
  65153. Font font;
  65154. int x, y, w, h;
  65155. int line, lineHeight;
  65156. bool isWhitespace, isNewLine;
  65157. TextLayoutToken (const String& t,
  65158. const Font& f,
  65159. const bool isWhitespace_) throw()
  65160. : text (t),
  65161. font (f),
  65162. x(0),
  65163. y(0),
  65164. isWhitespace (isWhitespace_)
  65165. {
  65166. w = font.getStringWidth (t);
  65167. h = roundFloatToInt (f.getHeight());
  65168. isNewLine = t.containsAnyOf (T("\r\n"));
  65169. }
  65170. TextLayoutToken (const TextLayoutToken& other) throw()
  65171. : text (other.text),
  65172. font (other.font),
  65173. x (other.x),
  65174. y (other.y),
  65175. w (other.w),
  65176. h (other.h),
  65177. line (other.line),
  65178. lineHeight (other.lineHeight),
  65179. isWhitespace (other.isWhitespace),
  65180. isNewLine (other.isNewLine)
  65181. {
  65182. }
  65183. ~TextLayoutToken() throw()
  65184. {
  65185. }
  65186. void draw (Graphics& g,
  65187. const int xOffset,
  65188. const int yOffset) throw()
  65189. {
  65190. if (! isWhitespace)
  65191. {
  65192. g.setFont (font);
  65193. g.drawSingleLineText (text.trimEnd(),
  65194. xOffset + x,
  65195. yOffset + y + (lineHeight - h)
  65196. + roundFloatToInt (font.getAscent()));
  65197. }
  65198. }
  65199. juce_UseDebuggingNewOperator
  65200. };
  65201. TextLayout::TextLayout() throw()
  65202. : tokens (64),
  65203. totalLines (0)
  65204. {
  65205. }
  65206. TextLayout::TextLayout (const String& text,
  65207. const Font& font) throw()
  65208. : tokens (64),
  65209. totalLines (0)
  65210. {
  65211. appendText (text, font);
  65212. }
  65213. TextLayout::TextLayout (const TextLayout& other) throw()
  65214. : tokens (64),
  65215. totalLines (0)
  65216. {
  65217. *this = other;
  65218. }
  65219. const TextLayout& TextLayout::operator= (const TextLayout& other) throw()
  65220. {
  65221. if (this != &other)
  65222. {
  65223. clear();
  65224. totalLines = other.totalLines;
  65225. for (int i = 0; i < other.tokens.size(); ++i)
  65226. tokens.add (new TextLayoutToken (*(const TextLayoutToken*)(other.tokens.getUnchecked(i))));
  65227. }
  65228. return *this;
  65229. }
  65230. TextLayout::~TextLayout() throw()
  65231. {
  65232. clear();
  65233. }
  65234. void TextLayout::clear() throw()
  65235. {
  65236. for (int i = tokens.size(); --i >= 0;)
  65237. {
  65238. TextLayoutToken* const t = (TextLayoutToken*)tokens.getUnchecked(i);
  65239. delete t;
  65240. }
  65241. tokens.clear();
  65242. totalLines = 0;
  65243. }
  65244. void TextLayout::appendText (const String& text,
  65245. const Font& font) throw()
  65246. {
  65247. const tchar* t = text;
  65248. String currentString;
  65249. int lastCharType = 0;
  65250. for (;;)
  65251. {
  65252. const tchar c = *t++;
  65253. if (c == 0)
  65254. break;
  65255. int charType;
  65256. if (c == T('\r') || c == T('\n'))
  65257. {
  65258. charType = 0;
  65259. }
  65260. else if (CharacterFunctions::isWhitespace (c))
  65261. {
  65262. charType = 2;
  65263. }
  65264. else
  65265. {
  65266. charType = 1;
  65267. }
  65268. if (charType == 0 || charType != lastCharType)
  65269. {
  65270. if (currentString.isNotEmpty())
  65271. {
  65272. tokens.add (new TextLayoutToken (currentString, font,
  65273. lastCharType == 2 || lastCharType == 0));
  65274. }
  65275. currentString = String::charToString (c);
  65276. if (c == T('\r') && *t == T('\n'))
  65277. currentString += *t++;
  65278. }
  65279. else
  65280. {
  65281. currentString += c;
  65282. }
  65283. lastCharType = charType;
  65284. }
  65285. if (currentString.isNotEmpty())
  65286. tokens.add (new TextLayoutToken (currentString,
  65287. font,
  65288. lastCharType == 2));
  65289. }
  65290. void TextLayout::setText (const String& text, const Font& font) throw()
  65291. {
  65292. clear();
  65293. appendText (text, font);
  65294. }
  65295. void TextLayout::layout (int maxWidth,
  65296. const Justification& justification,
  65297. const bool attemptToBalanceLineLengths) throw()
  65298. {
  65299. if (attemptToBalanceLineLengths)
  65300. {
  65301. const int originalW = maxWidth;
  65302. int bestWidth = maxWidth;
  65303. float bestLineProportion = 0.0f;
  65304. while (maxWidth > originalW / 2)
  65305. {
  65306. layout (maxWidth, justification, false);
  65307. if (getNumLines() <= 1)
  65308. return;
  65309. const int lastLineW = getLineWidth (getNumLines() - 1);
  65310. const int lastButOneLineW = getLineWidth (getNumLines() - 2);
  65311. const float prop = lastLineW / (float) lastButOneLineW;
  65312. if (prop > 0.9f)
  65313. return;
  65314. if (prop > bestLineProportion)
  65315. {
  65316. bestLineProportion = prop;
  65317. bestWidth = maxWidth;
  65318. }
  65319. maxWidth -= 10;
  65320. }
  65321. layout (bestWidth, justification, false);
  65322. }
  65323. else
  65324. {
  65325. int x = 0;
  65326. int y = 0;
  65327. int h = 0;
  65328. totalLines = 0;
  65329. int i;
  65330. for (i = 0; i < tokens.size(); ++i)
  65331. {
  65332. TextLayoutToken* const t = (TextLayoutToken*)tokens.getUnchecked(i);
  65333. t->x = x;
  65334. t->y = y;
  65335. t->line = totalLines;
  65336. x += t->w;
  65337. h = jmax (h, t->h);
  65338. const TextLayoutToken* nextTok = (TextLayoutToken*) tokens [i + 1];
  65339. if (nextTok == 0)
  65340. break;
  65341. if (t->isNewLine || ((! nextTok->isWhitespace) && x + nextTok->w > maxWidth))
  65342. {
  65343. // finished a line, so go back and update the heights of the things on it
  65344. for (int j = i; j >= 0; --j)
  65345. {
  65346. TextLayoutToken* const tok = (TextLayoutToken*)tokens.getUnchecked(j);
  65347. if (tok->line == totalLines)
  65348. tok->lineHeight = h;
  65349. else
  65350. break;
  65351. }
  65352. x = 0;
  65353. y += h;
  65354. h = 0;
  65355. ++totalLines;
  65356. }
  65357. }
  65358. // finished a line, so go back and update the heights of the things on it
  65359. for (int j = jmin (i, tokens.size() - 1); j >= 0; --j)
  65360. {
  65361. TextLayoutToken* const t = (TextLayoutToken*) tokens.getUnchecked(j);
  65362. if (t->line == totalLines)
  65363. t->lineHeight = h;
  65364. else
  65365. break;
  65366. }
  65367. ++totalLines;
  65368. if (! justification.testFlags (Justification::left))
  65369. {
  65370. int totalW = getWidth();
  65371. for (i = totalLines; --i >= 0;)
  65372. {
  65373. const int lineW = getLineWidth (i);
  65374. int dx = 0;
  65375. if (justification.testFlags (Justification::horizontallyCentred))
  65376. dx = (totalW - lineW) / 2;
  65377. else if (justification.testFlags (Justification::right))
  65378. dx = totalW - lineW;
  65379. for (int j = tokens.size(); --j >= 0;)
  65380. {
  65381. TextLayoutToken* const t = (TextLayoutToken*)tokens.getUnchecked(j);
  65382. if (t->line == i)
  65383. t->x += dx;
  65384. }
  65385. }
  65386. }
  65387. }
  65388. }
  65389. int TextLayout::getLineWidth (const int lineNumber) const throw()
  65390. {
  65391. int maxW = 0;
  65392. for (int i = tokens.size(); --i >= 0;)
  65393. {
  65394. const TextLayoutToken* const t = (TextLayoutToken*) tokens.getUnchecked(i);
  65395. if (t->line == lineNumber && ! t->isWhitespace)
  65396. maxW = jmax (maxW, t->x + t->w);
  65397. }
  65398. return maxW;
  65399. }
  65400. int TextLayout::getWidth() const throw()
  65401. {
  65402. int maxW = 0;
  65403. for (int i = tokens.size(); --i >= 0;)
  65404. {
  65405. const TextLayoutToken* const t = (TextLayoutToken*) tokens.getUnchecked(i);
  65406. if (! t->isWhitespace)
  65407. maxW = jmax (maxW, t->x + t->w);
  65408. }
  65409. return maxW;
  65410. }
  65411. int TextLayout::getHeight() const throw()
  65412. {
  65413. int maxH = 0;
  65414. for (int i = tokens.size(); --i >= 0;)
  65415. {
  65416. const TextLayoutToken* const t = (TextLayoutToken*) tokens.getUnchecked(i);
  65417. if (! t->isWhitespace)
  65418. maxH = jmax (maxH, t->y + t->h);
  65419. }
  65420. return maxH;
  65421. }
  65422. void TextLayout::draw (Graphics& g,
  65423. const int xOffset,
  65424. const int yOffset) const throw()
  65425. {
  65426. for (int i = tokens.size(); --i >= 0;)
  65427. ((TextLayoutToken*) tokens.getUnchecked(i))->draw (g, xOffset, yOffset);
  65428. }
  65429. void TextLayout::drawWithin (Graphics& g,
  65430. int x, int y, int w, int h,
  65431. const Justification& justification) const throw()
  65432. {
  65433. justification.applyToRectangle (x, y, getWidth(), getHeight(),
  65434. x, y, w, h);
  65435. draw (g, x, y);
  65436. }
  65437. END_JUCE_NAMESPACE
  65438. /********* End of inlined file: juce_TextLayout.cpp *********/
  65439. /********* Start of inlined file: juce_Typeface.cpp *********/
  65440. BEGIN_JUCE_NAMESPACE
  65441. TypefaceGlyphInfo::TypefaceGlyphInfo (const juce_wchar character_,
  65442. const Path& shape,
  65443. const float horizontalSeparation,
  65444. Typeface* const typeface_) throw()
  65445. : character (character_),
  65446. path (shape),
  65447. width (horizontalSeparation),
  65448. typeface (typeface_)
  65449. {
  65450. }
  65451. TypefaceGlyphInfo::~TypefaceGlyphInfo() throw()
  65452. {
  65453. }
  65454. float TypefaceGlyphInfo::getHorizontalSpacing (const juce_wchar subsequentCharacter) const throw()
  65455. {
  65456. if (subsequentCharacter != 0)
  65457. {
  65458. const KerningPair* const pairs = (const KerningPair*) kerningPairs.getData();
  65459. const int numPairs = getNumKerningPairs();
  65460. for (int i = 0; i < numPairs; ++i)
  65461. if (pairs [i].character2 == subsequentCharacter)
  65462. return width + pairs [i].kerningAmount;
  65463. }
  65464. return width;
  65465. }
  65466. void TypefaceGlyphInfo::addKerningPair (const juce_wchar subsequentCharacter,
  65467. const float extraKerningAmount) throw()
  65468. {
  65469. const int numPairs = getNumKerningPairs();
  65470. kerningPairs.setSize ((numPairs + 1) * sizeof (KerningPair));
  65471. KerningPair& p = getKerningPair (numPairs);
  65472. p.character2 = subsequentCharacter;
  65473. p.kerningAmount = extraKerningAmount;
  65474. }
  65475. TypefaceGlyphInfo::KerningPair& TypefaceGlyphInfo::getKerningPair (const int index) const throw()
  65476. {
  65477. return ((KerningPair*) kerningPairs.getData()) [index];
  65478. }
  65479. int TypefaceGlyphInfo::getNumKerningPairs() const throw()
  65480. {
  65481. return kerningPairs.getSize() / sizeof (KerningPair);
  65482. }
  65483. Typeface::Typeface() throw()
  65484. : hash (0),
  65485. isFullyPopulated (false)
  65486. {
  65487. zeromem (lookupTable, sizeof (lookupTable));
  65488. }
  65489. Typeface::Typeface (const Typeface& other)
  65490. : typefaceName (other.typefaceName),
  65491. ascent (other.ascent),
  65492. bold (other.bold),
  65493. italic (other.italic),
  65494. isFullyPopulated (other.isFullyPopulated),
  65495. defaultCharacter (other.defaultCharacter)
  65496. {
  65497. zeromem (lookupTable, sizeof (lookupTable));
  65498. for (int i = 0; i < other.glyphs.size(); ++i)
  65499. addGlyphCopy ((const TypefaceGlyphInfo*) other.glyphs.getUnchecked(i));
  65500. updateHashCode();
  65501. }
  65502. Typeface::Typeface (const String& faceName,
  65503. const bool bold,
  65504. const bool italic)
  65505. : isFullyPopulated (false)
  65506. {
  65507. zeromem (lookupTable, sizeof (lookupTable));
  65508. initialiseTypefaceCharacteristics (faceName, bold, italic, false);
  65509. updateHashCode();
  65510. }
  65511. Typeface::~Typeface()
  65512. {
  65513. clear();
  65514. }
  65515. const Typeface& Typeface::operator= (const Typeface& other) throw()
  65516. {
  65517. if (this != &other)
  65518. {
  65519. clear();
  65520. typefaceName = other.typefaceName;
  65521. ascent = other.ascent;
  65522. bold = other.bold;
  65523. italic = other.italic;
  65524. isFullyPopulated = other.isFullyPopulated;
  65525. defaultCharacter = other.defaultCharacter;
  65526. for (int i = 0; i < other.glyphs.size(); ++i)
  65527. addGlyphCopy ((const TypefaceGlyphInfo*) other.glyphs.getUnchecked(i));
  65528. updateHashCode();
  65529. }
  65530. return *this;
  65531. }
  65532. void Typeface::updateHashCode() throw()
  65533. {
  65534. hash = typefaceName.hashCode();
  65535. if (bold)
  65536. hash ^= 0xffff;
  65537. if (italic)
  65538. hash ^= 0xffff0000;
  65539. }
  65540. void Typeface::clear() throw()
  65541. {
  65542. zeromem (lookupTable, sizeof (lookupTable));
  65543. typefaceName = String::empty;
  65544. bold = false;
  65545. italic = false;
  65546. for (int i = glyphs.size(); --i >= 0;)
  65547. {
  65548. TypefaceGlyphInfo* const g = (TypefaceGlyphInfo*) (glyphs.getUnchecked(i));
  65549. delete g;
  65550. }
  65551. glyphs.clear();
  65552. updateHashCode();
  65553. }
  65554. Typeface::Typeface (InputStream& serialisedTypefaceStream)
  65555. {
  65556. zeromem (lookupTable, sizeof (lookupTable));
  65557. isFullyPopulated = true;
  65558. GZIPDecompressorInputStream gzin (&serialisedTypefaceStream, false);
  65559. BufferedInputStream in (&gzin, 32768, false);
  65560. typefaceName = in.readString();
  65561. bold = in.readBool();
  65562. italic = in.readBool();
  65563. ascent = in.readFloat();
  65564. defaultCharacter = (juce_wchar) in.readShort();
  65565. int i, numChars = in.readInt();
  65566. for (i = 0; i < numChars; ++i)
  65567. {
  65568. const juce_wchar c = (juce_wchar) in.readShort();
  65569. const float width = in.readFloat();
  65570. Path p;
  65571. p.loadPathFromStream (in);
  65572. addGlyph (c, p, width);
  65573. }
  65574. const int numKerningPairs = in.readInt();
  65575. for (i = 0; i < numKerningPairs; ++i)
  65576. {
  65577. const juce_wchar char1 = (juce_wchar) in.readShort();
  65578. const juce_wchar char2 = (juce_wchar) in.readShort();
  65579. addKerningPair (char1, char2, in.readFloat());
  65580. }
  65581. updateHashCode();
  65582. }
  65583. void Typeface::serialise (OutputStream& outputStream)
  65584. {
  65585. GZIPCompressorOutputStream out (&outputStream);
  65586. out.writeString (typefaceName);
  65587. out.writeBool (bold);
  65588. out.writeBool (italic);
  65589. out.writeFloat (ascent);
  65590. out.writeShort ((short) (unsigned short) defaultCharacter);
  65591. out.writeInt (glyphs.size());
  65592. int i, numKerningPairs = 0;
  65593. for (i = 0; i < glyphs.size(); ++i)
  65594. {
  65595. const TypefaceGlyphInfo& g = *(const TypefaceGlyphInfo*)(glyphs.getUnchecked (i));
  65596. out.writeShort ((short) (unsigned short) g.character);
  65597. out.writeFloat (g.width);
  65598. g.path.writePathToStream (out);
  65599. numKerningPairs += g.getNumKerningPairs();
  65600. }
  65601. out.writeInt (numKerningPairs);
  65602. for (i = 0; i < glyphs.size(); ++i)
  65603. {
  65604. const TypefaceGlyphInfo& g = *(const TypefaceGlyphInfo*)(glyphs.getUnchecked (i));
  65605. for (int j = 0; j < g.getNumKerningPairs(); ++j)
  65606. {
  65607. const TypefaceGlyphInfo::KerningPair& p = g.getKerningPair (j);
  65608. out.writeShort ((short) (unsigned short) g.character);
  65609. out.writeShort ((short) (unsigned short) p.character2);
  65610. out.writeFloat (p.kerningAmount);
  65611. }
  65612. }
  65613. }
  65614. const Path* Typeface::getOutlineForGlyph (const juce_wchar character) throw()
  65615. {
  65616. const TypefaceGlyphInfo* const g = (const TypefaceGlyphInfo*) getGlyph (character);
  65617. if (g != 0)
  65618. return &(g->path);
  65619. else
  65620. return 0;
  65621. }
  65622. const TypefaceGlyphInfo* Typeface::getGlyph (const juce_wchar character) throw()
  65623. {
  65624. if (((unsigned int) character) < 128 && lookupTable [character] > 0)
  65625. return (const TypefaceGlyphInfo*) glyphs [(int) lookupTable [character]];
  65626. for (int i = 0; i < glyphs.size(); ++i)
  65627. {
  65628. const TypefaceGlyphInfo* const g = (const TypefaceGlyphInfo*) glyphs.getUnchecked(i);
  65629. if (g->character == character)
  65630. return g;
  65631. }
  65632. if ((! isFullyPopulated)
  65633. && findAndAddSystemGlyph (character))
  65634. {
  65635. for (int i = 0; i < glyphs.size(); ++i)
  65636. {
  65637. const TypefaceGlyphInfo* const g = (const TypefaceGlyphInfo*) glyphs.getUnchecked(i);
  65638. if (g->character == character)
  65639. return g;
  65640. }
  65641. }
  65642. if (CharacterFunctions::isWhitespace (character) && character != L' ')
  65643. {
  65644. const TypefaceGlyphInfo* spaceGlyph = getGlyph (L' ');
  65645. if (spaceGlyph != 0)
  65646. {
  65647. // Add a copy of the empty glyph, mapped onto this character
  65648. addGlyph (character, spaceGlyph->getPath(), spaceGlyph->getHorizontalSpacing (0));
  65649. spaceGlyph = (const TypefaceGlyphInfo*) glyphs [(int) lookupTable [character]];
  65650. }
  65651. return spaceGlyph;
  65652. }
  65653. else if (character != defaultCharacter)
  65654. {
  65655. const Font fallbackFont (Font::getFallbackFontName(), 10, 0);
  65656. Typeface* const fallbackTypeface = fallbackFont.getTypeface();
  65657. if (fallbackTypeface != 0 && fallbackTypeface != this)
  65658. return fallbackTypeface->getGlyph (character);
  65659. return getGlyph (defaultCharacter);
  65660. }
  65661. return 0;
  65662. }
  65663. void Typeface::addGlyph (const juce_wchar character,
  65664. const Path& path,
  65665. const float horizontalSpacing) throw()
  65666. {
  65667. #ifdef JUCE_DEBUG
  65668. for (int i = 0; i < glyphs.size(); ++i)
  65669. {
  65670. const TypefaceGlyphInfo* const g = (const TypefaceGlyphInfo*) glyphs.getUnchecked(i);
  65671. if (g->character == character)
  65672. jassertfalse;
  65673. }
  65674. #endif
  65675. if (((unsigned int) character) < 128)
  65676. lookupTable [character] = (short) glyphs.size();
  65677. glyphs.add (new TypefaceGlyphInfo (character,
  65678. path,
  65679. horizontalSpacing,
  65680. this));
  65681. }
  65682. void Typeface::addGlyphCopy (const TypefaceGlyphInfo* const glyphInfoToCopy) throw()
  65683. {
  65684. if (glyphInfoToCopy != 0)
  65685. {
  65686. if (glyphInfoToCopy->character > 0 && glyphInfoToCopy->character < 128)
  65687. lookupTable [glyphInfoToCopy->character] = (short) glyphs.size();
  65688. TypefaceGlyphInfo* const newOne
  65689. = new TypefaceGlyphInfo (glyphInfoToCopy->character,
  65690. glyphInfoToCopy->path,
  65691. glyphInfoToCopy->width,
  65692. this);
  65693. newOne->kerningPairs = glyphInfoToCopy->kerningPairs;
  65694. glyphs.add (newOne);
  65695. }
  65696. }
  65697. void Typeface::addKerningPair (const juce_wchar char1,
  65698. const juce_wchar char2,
  65699. const float extraAmount) throw()
  65700. {
  65701. TypefaceGlyphInfo* const g = (TypefaceGlyphInfo*) getGlyph (char1);
  65702. if (g != 0)
  65703. g->addKerningPair (char2, extraAmount);
  65704. }
  65705. void Typeface::setName (const String& name) throw()
  65706. {
  65707. typefaceName = name;
  65708. updateHashCode();
  65709. }
  65710. void Typeface::setAscent (const float newAscent) throw()
  65711. {
  65712. ascent = newAscent;
  65713. }
  65714. void Typeface::setDefaultCharacter (const juce_wchar newDefaultCharacter) throw()
  65715. {
  65716. defaultCharacter = newDefaultCharacter;
  65717. }
  65718. void Typeface::setBold (const bool shouldBeBold) throw()
  65719. {
  65720. bold = shouldBeBold;
  65721. updateHashCode();
  65722. }
  65723. void Typeface::setItalic (const bool shouldBeItalic) throw()
  65724. {
  65725. italic = shouldBeItalic;
  65726. updateHashCode();
  65727. }
  65728. class TypefaceCache;
  65729. static TypefaceCache* typefaceCacheInstance = 0;
  65730. void clearUpDefaultFontNames() throw(); // in juce_Font.cpp
  65731. class TypefaceCache : private DeletedAtShutdown
  65732. {
  65733. private:
  65734. struct CachedFace
  65735. {
  65736. CachedFace() throw()
  65737. : lastUsageCount (0),
  65738. flags (0)
  65739. {
  65740. }
  65741. String typefaceName;
  65742. int lastUsageCount;
  65743. int flags;
  65744. Typeface::Ptr typeFace;
  65745. };
  65746. int counter;
  65747. OwnedArray <CachedFace> faces;
  65748. TypefaceCache (const TypefaceCache&);
  65749. const TypefaceCache& operator= (const TypefaceCache&);
  65750. public:
  65751. TypefaceCache (int numToCache = 10)
  65752. : counter (1),
  65753. faces (2)
  65754. {
  65755. while (--numToCache >= 0)
  65756. {
  65757. CachedFace* const face = new CachedFace();
  65758. face->typeFace = new Typeface();
  65759. faces.add (face);
  65760. }
  65761. }
  65762. ~TypefaceCache()
  65763. {
  65764. faces.clear();
  65765. jassert (typefaceCacheInstance == this);
  65766. typefaceCacheInstance = 0;
  65767. // just a courtesy call to get avoid leaking these strings at shutdown
  65768. clearUpDefaultFontNames();
  65769. }
  65770. static TypefaceCache* getInstance() throw()
  65771. {
  65772. if (typefaceCacheInstance == 0)
  65773. typefaceCacheInstance = new TypefaceCache();
  65774. return typefaceCacheInstance;
  65775. }
  65776. const Typeface::Ptr findTypefaceFor (const Font& font) throw()
  65777. {
  65778. const int flags = font.getStyleFlags() & (Font::bold | Font::italic);
  65779. int i;
  65780. for (i = faces.size(); --i >= 0;)
  65781. {
  65782. CachedFace* const face = faces.getUnchecked(i);
  65783. if (face->flags == flags
  65784. && face->typefaceName == font.getTypefaceName())
  65785. {
  65786. face->lastUsageCount = ++counter;
  65787. return face->typeFace;
  65788. }
  65789. }
  65790. int replaceIndex = 0;
  65791. int bestLastUsageCount = INT_MAX;
  65792. for (i = faces.size(); --i >= 0;)
  65793. {
  65794. const int lu = faces.getUnchecked(i)->lastUsageCount;
  65795. if (bestLastUsageCount > lu)
  65796. {
  65797. bestLastUsageCount = lu;
  65798. replaceIndex = i;
  65799. }
  65800. }
  65801. CachedFace* const face = faces.getUnchecked (replaceIndex);
  65802. face->typefaceName = font.getTypefaceName();
  65803. face->flags = flags;
  65804. face->lastUsageCount = ++counter;
  65805. face->typeFace = new Typeface (font.getTypefaceName(),
  65806. font.isBold(),
  65807. font.isItalic());
  65808. return face->typeFace;
  65809. }
  65810. };
  65811. const Typeface::Ptr Typeface::getTypefaceFor (const Font& font) throw()
  65812. {
  65813. return TypefaceCache::getInstance()->findTypefaceFor (font);
  65814. }
  65815. END_JUCE_NAMESPACE
  65816. /********* End of inlined file: juce_Typeface.cpp *********/
  65817. /********* Start of inlined file: juce_AffineTransform.cpp *********/
  65818. BEGIN_JUCE_NAMESPACE
  65819. AffineTransform::AffineTransform() throw()
  65820. : mat00 (1.0f),
  65821. mat01 (0),
  65822. mat02 (0),
  65823. mat10 (0),
  65824. mat11 (1.0f),
  65825. mat12 (0)
  65826. {
  65827. }
  65828. AffineTransform::AffineTransform (const AffineTransform& other) throw()
  65829. : mat00 (other.mat00),
  65830. mat01 (other.mat01),
  65831. mat02 (other.mat02),
  65832. mat10 (other.mat10),
  65833. mat11 (other.mat11),
  65834. mat12 (other.mat12)
  65835. {
  65836. }
  65837. AffineTransform::AffineTransform (const float mat00_,
  65838. const float mat01_,
  65839. const float mat02_,
  65840. const float mat10_,
  65841. const float mat11_,
  65842. const float mat12_) throw()
  65843. : mat00 (mat00_),
  65844. mat01 (mat01_),
  65845. mat02 (mat02_),
  65846. mat10 (mat10_),
  65847. mat11 (mat11_),
  65848. mat12 (mat12_)
  65849. {
  65850. }
  65851. const AffineTransform& AffineTransform::operator= (const AffineTransform& other) throw()
  65852. {
  65853. mat00 = other.mat00;
  65854. mat01 = other.mat01;
  65855. mat02 = other.mat02;
  65856. mat10 = other.mat10;
  65857. mat11 = other.mat11;
  65858. mat12 = other.mat12;
  65859. return *this;
  65860. }
  65861. bool AffineTransform::operator== (const AffineTransform& other) const throw()
  65862. {
  65863. return mat00 == other.mat00
  65864. && mat01 == other.mat01
  65865. && mat02 == other.mat02
  65866. && mat10 == other.mat10
  65867. && mat11 == other.mat11
  65868. && mat12 == other.mat12;
  65869. }
  65870. bool AffineTransform::operator!= (const AffineTransform& other) const throw()
  65871. {
  65872. return ! operator== (other);
  65873. }
  65874. bool AffineTransform::isIdentity() const throw()
  65875. {
  65876. return (mat01 == 0)
  65877. && (mat02 == 0)
  65878. && (mat10 == 0)
  65879. && (mat12 == 0)
  65880. && (mat00 == 1.0f)
  65881. && (mat11 == 1.0f);
  65882. }
  65883. const AffineTransform AffineTransform::identity;
  65884. const AffineTransform AffineTransform::followedBy (const AffineTransform& other) const throw()
  65885. {
  65886. return AffineTransform (other.mat00 * mat00 + other.mat01 * mat10,
  65887. other.mat00 * mat01 + other.mat01 * mat11,
  65888. other.mat00 * mat02 + other.mat01 * mat12 + other.mat02,
  65889. other.mat10 * mat00 + other.mat11 * mat10,
  65890. other.mat10 * mat01 + other.mat11 * mat11,
  65891. other.mat10 * mat02 + other.mat11 * mat12 + other.mat12);
  65892. }
  65893. const AffineTransform AffineTransform::followedBy (const float omat00,
  65894. const float omat01,
  65895. const float omat02,
  65896. const float omat10,
  65897. const float omat11,
  65898. const float omat12) const throw()
  65899. {
  65900. return AffineTransform (omat00 * mat00 + omat01 * mat10,
  65901. omat00 * mat01 + omat01 * mat11,
  65902. omat00 * mat02 + omat01 * mat12 + omat02,
  65903. omat10 * mat00 + omat11 * mat10,
  65904. omat10 * mat01 + omat11 * mat11,
  65905. omat10 * mat02 + omat11 * mat12 + omat12);
  65906. }
  65907. const AffineTransform AffineTransform::translated (const float dx,
  65908. const float dy) const throw()
  65909. {
  65910. return followedBy (1.0f, 0, dx,
  65911. 0, 1.0f, dy);
  65912. }
  65913. const AffineTransform AffineTransform::translation (const float dx,
  65914. const float dy) throw()
  65915. {
  65916. return AffineTransform (1.0f, 0, dx,
  65917. 0, 1.0f, dy);
  65918. }
  65919. const AffineTransform AffineTransform::rotated (const float rad) const throw()
  65920. {
  65921. const float cosRad = cosf (rad);
  65922. const float sinRad = sinf (rad);
  65923. return followedBy (cosRad, -sinRad, 0,
  65924. sinRad, cosRad, 0);
  65925. }
  65926. const AffineTransform AffineTransform::rotation (const float rad) throw()
  65927. {
  65928. const float cosRad = cosf (rad);
  65929. const float sinRad = sinf (rad);
  65930. return AffineTransform (cosRad, -sinRad, 0,
  65931. sinRad, cosRad, 0);
  65932. }
  65933. const AffineTransform AffineTransform::rotated (const float angle,
  65934. const float pivotX,
  65935. const float pivotY) const throw()
  65936. {
  65937. return translated (-pivotX, -pivotY)
  65938. .rotated (angle)
  65939. .translated (pivotX, pivotY);
  65940. }
  65941. const AffineTransform AffineTransform::rotation (const float angle,
  65942. const float pivotX,
  65943. const float pivotY) throw()
  65944. {
  65945. return translation (-pivotX, -pivotY)
  65946. .rotated (angle)
  65947. .translated (pivotX, pivotY);
  65948. }
  65949. const AffineTransform AffineTransform::scaled (const float factorX,
  65950. const float factorY) const throw()
  65951. {
  65952. return followedBy (factorX, 0, 0,
  65953. 0, factorY, 0);
  65954. }
  65955. const AffineTransform AffineTransform::scale (const float factorX,
  65956. const float factorY) throw()
  65957. {
  65958. return AffineTransform (factorX, 0, 0,
  65959. 0, factorY, 0);
  65960. }
  65961. const AffineTransform AffineTransform::sheared (const float shearX,
  65962. const float shearY) const throw()
  65963. {
  65964. return followedBy (1.0f, shearX, 0,
  65965. shearY, 1.0f, 0);
  65966. }
  65967. const AffineTransform AffineTransform::inverted() const throw()
  65968. {
  65969. double determinant = (mat00 * mat11 - mat10 * mat01);
  65970. if (determinant != 0.0)
  65971. {
  65972. determinant = 1.0 / determinant;
  65973. const float dst00 = (float) (mat11 * determinant);
  65974. const float dst10 = (float) (-mat10 * determinant);
  65975. const float dst01 = (float) (-mat01 * determinant);
  65976. const float dst11 = (float) (mat00 * determinant);
  65977. return AffineTransform (dst00, dst01, -mat02 * dst00 - mat12 * dst01,
  65978. dst10, dst11, -mat02 * dst10 - mat12 * dst11);
  65979. }
  65980. else
  65981. {
  65982. // singularity..
  65983. return *this;
  65984. }
  65985. }
  65986. bool AffineTransform::isSingularity() const throw()
  65987. {
  65988. return (mat00 * mat11 - mat10 * mat01) == 0.0;
  65989. }
  65990. void AffineTransform::transformPoint (float& x,
  65991. float& y) const throw()
  65992. {
  65993. const float oldX = x;
  65994. x = mat00 * oldX + mat01 * y + mat02;
  65995. y = mat10 * oldX + mat11 * y + mat12;
  65996. }
  65997. void AffineTransform::transformPoint (double& x,
  65998. double& y) const throw()
  65999. {
  66000. const double oldX = x;
  66001. x = mat00 * oldX + mat01 * y + mat02;
  66002. y = mat10 * oldX + mat11 * y + mat12;
  66003. }
  66004. END_JUCE_NAMESPACE
  66005. /********* End of inlined file: juce_AffineTransform.cpp *********/
  66006. /********* Start of inlined file: juce_BorderSize.cpp *********/
  66007. BEGIN_JUCE_NAMESPACE
  66008. BorderSize::BorderSize() throw()
  66009. : top (0),
  66010. left (0),
  66011. bottom (0),
  66012. right (0)
  66013. {
  66014. }
  66015. BorderSize::BorderSize (const BorderSize& other) throw()
  66016. : top (other.top),
  66017. left (other.left),
  66018. bottom (other.bottom),
  66019. right (other.right)
  66020. {
  66021. }
  66022. BorderSize::BorderSize (const int topGap,
  66023. const int leftGap,
  66024. const int bottomGap,
  66025. const int rightGap) throw()
  66026. : top (topGap),
  66027. left (leftGap),
  66028. bottom (bottomGap),
  66029. right (rightGap)
  66030. {
  66031. }
  66032. BorderSize::BorderSize (const int allGaps) throw()
  66033. : top (allGaps),
  66034. left (allGaps),
  66035. bottom (allGaps),
  66036. right (allGaps)
  66037. {
  66038. }
  66039. BorderSize::~BorderSize() throw()
  66040. {
  66041. }
  66042. void BorderSize::setTop (const int newTopGap) throw()
  66043. {
  66044. top = newTopGap;
  66045. }
  66046. void BorderSize::setLeft (const int newLeftGap) throw()
  66047. {
  66048. left = newLeftGap;
  66049. }
  66050. void BorderSize::setBottom (const int newBottomGap) throw()
  66051. {
  66052. bottom = newBottomGap;
  66053. }
  66054. void BorderSize::setRight (const int newRightGap) throw()
  66055. {
  66056. right = newRightGap;
  66057. }
  66058. const Rectangle BorderSize::subtractedFrom (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::subtractFrom (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. const Rectangle BorderSize::addedTo (const Rectangle& r) const throw()
  66073. {
  66074. return Rectangle (r.getX() - left,
  66075. r.getY() - top,
  66076. r.getWidth() + (left + right),
  66077. r.getHeight() + (top + bottom));
  66078. }
  66079. void BorderSize::addTo (Rectangle& r) const throw()
  66080. {
  66081. r.setBounds (r.getX() - left,
  66082. r.getY() - top,
  66083. r.getWidth() + (left + right),
  66084. r.getHeight() + (top + bottom));
  66085. }
  66086. bool BorderSize::operator== (const BorderSize& other) const throw()
  66087. {
  66088. return top == other.top
  66089. && left == other.left
  66090. && bottom == other.bottom
  66091. && right == other.right;
  66092. }
  66093. bool BorderSize::operator!= (const BorderSize& other) const throw()
  66094. {
  66095. return ! operator== (other);
  66096. }
  66097. END_JUCE_NAMESPACE
  66098. /********* End of inlined file: juce_BorderSize.cpp *********/
  66099. /********* Start of inlined file: juce_Line.cpp *********/
  66100. BEGIN_JUCE_NAMESPACE
  66101. static bool juce_lineIntersection (const float x1, const float y1,
  66102. const float x2, const float y2,
  66103. const float x3, const float y3,
  66104. const float x4, const float y4,
  66105. float& intersectionX,
  66106. float& intersectionY) throw()
  66107. {
  66108. if (x2 != x3 || y2 != y3)
  66109. {
  66110. const float dx1 = x2 - x1;
  66111. const float dy1 = y2 - y1;
  66112. const float dx2 = x4 - x3;
  66113. const float dy2 = y4 - y3;
  66114. const float divisor = dx1 * dy2 - dx2 * dy1;
  66115. if (divisor == 0)
  66116. {
  66117. if (! ((dx1 == 0 && dy1 == 0) || (dx2 == 0 && dy2 == 0)))
  66118. {
  66119. if (dy1 == 0 && dy2 != 0)
  66120. {
  66121. const float along = (y1 - y3) / dy2;
  66122. intersectionX = x3 + along * dx2;
  66123. intersectionY = y1;
  66124. return along >= 0 && along <= 1.0f;
  66125. }
  66126. else if (dy2 == 0 && dy1 != 0)
  66127. {
  66128. const float along = (y3 - y1) / dy1;
  66129. intersectionX = x1 + along * dx1;
  66130. intersectionY = y3;
  66131. return along >= 0 && along <= 1.0f;
  66132. }
  66133. else if (dx1 == 0 && dx2 != 0)
  66134. {
  66135. const float along = (x1 - x3) / dx2;
  66136. intersectionX = x1;
  66137. intersectionY = y3 + along * dy2;
  66138. return along >= 0 && along <= 1.0f;
  66139. }
  66140. else if (dx2 == 0 && dx1 != 0)
  66141. {
  66142. const float along = (x3 - x1) / dx1;
  66143. intersectionX = x3;
  66144. intersectionY = y1 + along * dy1;
  66145. return along >= 0 && along <= 1.0f;
  66146. }
  66147. }
  66148. intersectionX = 0.5f * (x2 + x3);
  66149. intersectionY = 0.5f * (y2 + y3);
  66150. return false;
  66151. }
  66152. const float along1 = ((y1 - y3) * dx2 - (x1 - x3) * dy2) / divisor;
  66153. intersectionX = x1 + along1 * dx1;
  66154. intersectionY = y1 + along1 * dy1;
  66155. if (along1 < 0 || along1 > 1.0f)
  66156. return false;
  66157. const float along2 = ((y1 - y3) * dx1 - (x1 - x3) * dy1) / divisor;
  66158. return along2 >= 0 && along2 <= 1.0f;
  66159. }
  66160. intersectionX = x2;
  66161. intersectionY = y2;
  66162. return true;
  66163. }
  66164. Line::Line() throw()
  66165. : startX (0.0f),
  66166. startY (0.0f),
  66167. endX (0.0f),
  66168. endY (0.0f)
  66169. {
  66170. }
  66171. Line::Line (const Line& other) throw()
  66172. : startX (other.startX),
  66173. startY (other.startY),
  66174. endX (other.endX),
  66175. endY (other.endY)
  66176. {
  66177. }
  66178. Line::Line (const float startX_, const float startY_,
  66179. const float endX_, const float endY_) throw()
  66180. : startX (startX_),
  66181. startY (startY_),
  66182. endX (endX_),
  66183. endY (endY_)
  66184. {
  66185. }
  66186. Line::Line (const Point& start,
  66187. const Point& end) throw()
  66188. : startX (start.getX()),
  66189. startY (start.getY()),
  66190. endX (end.getX()),
  66191. endY (end.getY())
  66192. {
  66193. }
  66194. const Line& Line::operator= (const Line& other) throw()
  66195. {
  66196. startX = other.startX;
  66197. startY = other.startY;
  66198. endX = other.endX;
  66199. endY = other.endY;
  66200. return *this;
  66201. }
  66202. Line::~Line() throw()
  66203. {
  66204. }
  66205. const Point Line::getStart() const throw()
  66206. {
  66207. return Point (startX, startY);
  66208. }
  66209. const Point Line::getEnd() const throw()
  66210. {
  66211. return Point (endX, endY);
  66212. }
  66213. void Line::setStart (const float newStartX,
  66214. const float newStartY) throw()
  66215. {
  66216. startX = newStartX;
  66217. startY = newStartY;
  66218. }
  66219. void Line::setStart (const Point& newStart) throw()
  66220. {
  66221. startX = newStart.getX();
  66222. startY = newStart.getY();
  66223. }
  66224. void Line::setEnd (const float newEndX,
  66225. const float newEndY) throw()
  66226. {
  66227. endX = newEndX;
  66228. endY = newEndY;
  66229. }
  66230. void Line::setEnd (const Point& newEnd) throw()
  66231. {
  66232. endX = newEnd.getX();
  66233. endY = newEnd.getY();
  66234. }
  66235. bool Line::operator== (const Line& other) const throw()
  66236. {
  66237. return startX == other.startX
  66238. && startY == other.startY
  66239. && endX == other.endX
  66240. && endY == other.endY;
  66241. }
  66242. bool Line::operator!= (const Line& other) const throw()
  66243. {
  66244. return startX != other.startX
  66245. || startY != other.startY
  66246. || endX != other.endX
  66247. || endY != other.endY;
  66248. }
  66249. void Line::applyTransform (const AffineTransform& transform) throw()
  66250. {
  66251. transform.transformPoint (startX, startY);
  66252. transform.transformPoint (endX, endY);
  66253. }
  66254. float Line::getLength() const throw()
  66255. {
  66256. return (float) juce_hypot (startX - endX,
  66257. startY - endY);
  66258. }
  66259. float Line::getAngle() const throw()
  66260. {
  66261. return atan2f (endX - startX,
  66262. endY - startY);
  66263. }
  66264. const Point Line::getPointAlongLine (const float distanceFromStart) const throw()
  66265. {
  66266. const float alpha = distanceFromStart / getLength();
  66267. return Point (startX + (endX - startX) * alpha,
  66268. startY + (endY - startY) * alpha);
  66269. }
  66270. const Point Line::getPointAlongLine (const float offsetX,
  66271. const float offsetY) const throw()
  66272. {
  66273. const float dx = endX - startX;
  66274. const float dy = endY - startY;
  66275. const double length = juce_hypot (dx, dy);
  66276. if (length == 0)
  66277. return Point (startX, startY);
  66278. else
  66279. return Point (startX + (float) (((dx * offsetX) - (dy * offsetY)) / length),
  66280. startY + (float) (((dy * offsetX) + (dx * offsetY)) / length));
  66281. }
  66282. const Point Line::getPointAlongLineProportionally (const float alpha) const throw()
  66283. {
  66284. return Point (startX + (endX - startX) * alpha,
  66285. startY + (endY - startY) * alpha);
  66286. }
  66287. float Line::getDistanceFromLine (const float x,
  66288. const float y) const throw()
  66289. {
  66290. const double dx = endX - startX;
  66291. const double dy = endY - startY;
  66292. const double length = dx * dx + dy * dy;
  66293. if (length > 0)
  66294. {
  66295. const double prop = ((x - startX) * dx + (y - startY) * dy) / length;
  66296. if (prop >= 0.0f && prop < 1.0f)
  66297. {
  66298. return (float) juce_hypot (x - (startX + prop * dx),
  66299. y - (startY + prop * dy));
  66300. }
  66301. }
  66302. return (float) jmin (juce_hypot (x - startX, y - startY),
  66303. juce_hypot (x - endX, y - endY));
  66304. }
  66305. float Line::findNearestPointTo (const float x,
  66306. const float y) const throw()
  66307. {
  66308. const double dx = endX - startX;
  66309. const double dy = endY - startY;
  66310. const double length = dx * dx + dy * dy;
  66311. if (length <= 0.0)
  66312. return 0.0f;
  66313. return jlimit (0.0f, 1.0f,
  66314. (float) (((x - startX) * dx + (y - startY) * dy) / length));
  66315. }
  66316. const Line Line::withShortenedStart (const float distanceToShortenBy) const throw()
  66317. {
  66318. const float length = getLength();
  66319. return Line (getPointAlongLine (jmin (distanceToShortenBy, length)),
  66320. getEnd());
  66321. }
  66322. const Line Line::withShortenedEnd (const float distanceToShortenBy) const throw()
  66323. {
  66324. const float length = getLength();
  66325. return Line (getStart(),
  66326. getPointAlongLine (length - jmin (distanceToShortenBy, length)));
  66327. }
  66328. bool Line::clipToPath (const Path& path,
  66329. const bool keepSectionOutsidePath) throw()
  66330. {
  66331. const bool startInside = path.contains (startX, startY);
  66332. const bool endInside = path.contains (endX, endY);
  66333. if (startInside == endInside)
  66334. {
  66335. if (keepSectionOutsidePath != startInside)
  66336. {
  66337. // entirely outside the path
  66338. return false;
  66339. }
  66340. else
  66341. {
  66342. // entirely inside the path
  66343. startX = 0.0f;
  66344. startY = 0.0f;
  66345. endX = 0.0f;
  66346. endY = 0.0f;
  66347. return true;
  66348. }
  66349. }
  66350. else
  66351. {
  66352. bool changed = false;
  66353. PathFlatteningIterator iter (path, AffineTransform::identity);
  66354. while (iter.next())
  66355. {
  66356. float ix, iy;
  66357. if (intersects (Line (iter.x1, iter.y1,
  66358. iter.x2, iter.y2),
  66359. ix, iy))
  66360. {
  66361. if ((startInside && keepSectionOutsidePath)
  66362. || (endInside && ! keepSectionOutsidePath))
  66363. {
  66364. setStart (ix, iy);
  66365. }
  66366. else
  66367. {
  66368. setEnd (ix, iy);
  66369. }
  66370. changed = true;
  66371. }
  66372. }
  66373. return changed;
  66374. }
  66375. }
  66376. bool Line::intersects (const Line& line,
  66377. float& intersectionX,
  66378. float& intersectionY) const throw()
  66379. {
  66380. return juce_lineIntersection (startX, startY,
  66381. endX, endY,
  66382. line.startX, line.startY,
  66383. line.endX, line.endY,
  66384. intersectionX,
  66385. intersectionY);
  66386. }
  66387. bool Line::isVertical() const throw()
  66388. {
  66389. return startX == endX;
  66390. }
  66391. bool Line::isHorizontal() const throw()
  66392. {
  66393. return startY == endY;
  66394. }
  66395. bool Line::isPointAbove (const float x, const float y) const throw()
  66396. {
  66397. return startX != endX
  66398. && y < ((endY - startY) * (x - startX)) / (endX - startX) + startY;
  66399. }
  66400. END_JUCE_NAMESPACE
  66401. /********* End of inlined file: juce_Line.cpp *********/
  66402. /********* Start of inlined file: juce_Path.cpp *********/
  66403. BEGIN_JUCE_NAMESPACE
  66404. // tests that some co-ords aren't NaNs
  66405. #define CHECK_COORDS_ARE_VALID(x, y) \
  66406. jassert (x == x && y == y);
  66407. const float Path::lineMarker = 100001.0f;
  66408. const float Path::moveMarker = 100002.0f;
  66409. const float Path::quadMarker = 100003.0f;
  66410. const float Path::cubicMarker = 100004.0f;
  66411. const float Path::closeSubPathMarker = 100005.0f;
  66412. static const int defaultGranularity = 32;
  66413. Path::Path() throw()
  66414. : ArrayAllocationBase <float> (defaultGranularity),
  66415. numElements (0),
  66416. pathXMin (0),
  66417. pathXMax (0),
  66418. pathYMin (0),
  66419. pathYMax (0),
  66420. useNonZeroWinding (true)
  66421. {
  66422. }
  66423. Path::~Path() throw()
  66424. {
  66425. }
  66426. Path::Path (const Path& other) throw()
  66427. : ArrayAllocationBase <float> (defaultGranularity),
  66428. numElements (other.numElements),
  66429. pathXMin (other.pathXMin),
  66430. pathXMax (other.pathXMax),
  66431. pathYMin (other.pathYMin),
  66432. pathYMax (other.pathYMax),
  66433. useNonZeroWinding (other.useNonZeroWinding)
  66434. {
  66435. if (numElements > 0)
  66436. {
  66437. setAllocatedSize (numElements);
  66438. memcpy (elements, other.elements, numElements * sizeof (float));
  66439. }
  66440. }
  66441. const Path& Path::operator= (const Path& other) throw()
  66442. {
  66443. if (this != &other)
  66444. {
  66445. ensureAllocatedSize (other.numElements);
  66446. numElements = other.numElements;
  66447. pathXMin = other.pathXMin;
  66448. pathXMax = other.pathXMax;
  66449. pathYMin = other.pathYMin;
  66450. pathYMax = other.pathYMax;
  66451. useNonZeroWinding = other.useNonZeroWinding;
  66452. if (numElements > 0)
  66453. memcpy (elements, other.elements, numElements * sizeof (float));
  66454. }
  66455. return *this;
  66456. }
  66457. void Path::clear() throw()
  66458. {
  66459. numElements = 0;
  66460. pathXMin = 0;
  66461. pathYMin = 0;
  66462. pathYMax = 0;
  66463. pathXMax = 0;
  66464. }
  66465. void Path::swapWithPath (Path& other)
  66466. {
  66467. swapVariables <int> (this->numAllocated, other.numAllocated);
  66468. swapVariables <float*> (this->elements, other.elements);
  66469. swapVariables <int> (this->numElements, other.numElements);
  66470. swapVariables <float> (this->pathXMin, other.pathXMin);
  66471. swapVariables <float> (this->pathXMax, other.pathXMax);
  66472. swapVariables <float> (this->pathYMin, other.pathYMin);
  66473. swapVariables <float> (this->pathYMax, other.pathYMax);
  66474. swapVariables <bool> (this->useNonZeroWinding, other.useNonZeroWinding);
  66475. }
  66476. void Path::setUsingNonZeroWinding (const bool isNonZero) throw()
  66477. {
  66478. useNonZeroWinding = isNonZero;
  66479. }
  66480. void Path::scaleToFit (const float x, const float y, const float w, const float h,
  66481. const bool preserveProportions) throw()
  66482. {
  66483. applyTransform (getTransformToScaleToFit (x, y, w, h, preserveProportions));
  66484. }
  66485. bool Path::isEmpty() const throw()
  66486. {
  66487. int i = 0;
  66488. while (i < numElements)
  66489. {
  66490. const float type = elements [i++];
  66491. if (type == moveMarker)
  66492. {
  66493. i += 2;
  66494. }
  66495. else if (type == lineMarker
  66496. || type == quadMarker
  66497. || type == cubicMarker)
  66498. {
  66499. return false;
  66500. }
  66501. }
  66502. return true;
  66503. }
  66504. void Path::getBounds (float& x, float& y,
  66505. float& w, float& h) const throw()
  66506. {
  66507. x = pathXMin;
  66508. y = pathYMin;
  66509. w = pathXMax - pathXMin;
  66510. h = pathYMax - pathYMin;
  66511. }
  66512. void Path::getBoundsTransformed (const AffineTransform& transform,
  66513. float& x, float& y,
  66514. float& w, float& h) const throw()
  66515. {
  66516. float x1 = pathXMin;
  66517. float y1 = pathYMin;
  66518. transform.transformPoint (x1, y1);
  66519. float x2 = pathXMax;
  66520. float y2 = pathYMin;
  66521. transform.transformPoint (x2, y2);
  66522. float x3 = pathXMin;
  66523. float y3 = pathYMax;
  66524. transform.transformPoint (x3, y3);
  66525. float x4 = pathXMax;
  66526. float y4 = pathYMax;
  66527. transform.transformPoint (x4, y4);
  66528. x = jmin (x1, x2, x3, x4);
  66529. y = jmin (y1, y2, y3, y4);
  66530. w = jmax (x1, x2, x3, x4) - x;
  66531. h = jmax (y1, y2, y3, y4) - y;
  66532. }
  66533. void Path::startNewSubPath (const float x,
  66534. const float y) throw()
  66535. {
  66536. CHECK_COORDS_ARE_VALID (x, y);
  66537. if (numElements == 0)
  66538. {
  66539. pathXMin = pathXMax = x;
  66540. pathYMin = pathYMax = y;
  66541. }
  66542. else
  66543. {
  66544. pathXMin = jmin (pathXMin, x);
  66545. pathXMax = jmax (pathXMax, x);
  66546. pathYMin = jmin (pathYMin, y);
  66547. pathYMax = jmax (pathYMax, y);
  66548. }
  66549. ensureAllocatedSize (numElements + 3);
  66550. elements [numElements++] = moveMarker;
  66551. elements [numElements++] = x;
  66552. elements [numElements++] = y;
  66553. }
  66554. void Path::lineTo (const float x, const float y) throw()
  66555. {
  66556. CHECK_COORDS_ARE_VALID (x, y);
  66557. if (numElements == 0)
  66558. startNewSubPath (0, 0);
  66559. ensureAllocatedSize (numElements + 3);
  66560. elements [numElements++] = lineMarker;
  66561. elements [numElements++] = x;
  66562. elements [numElements++] = y;
  66563. pathXMin = jmin (pathXMin, x);
  66564. pathXMax = jmax (pathXMax, x);
  66565. pathYMin = jmin (pathYMin, y);
  66566. pathYMax = jmax (pathYMax, y);
  66567. }
  66568. void Path::quadraticTo (const float x1, const float y1,
  66569. const float x2, const float y2) throw()
  66570. {
  66571. CHECK_COORDS_ARE_VALID (x1, y1);
  66572. CHECK_COORDS_ARE_VALID (x2, y2);
  66573. if (numElements == 0)
  66574. startNewSubPath (0, 0);
  66575. ensureAllocatedSize (numElements + 5);
  66576. elements [numElements++] = quadMarker;
  66577. elements [numElements++] = x1;
  66578. elements [numElements++] = y1;
  66579. elements [numElements++] = x2;
  66580. elements [numElements++] = y2;
  66581. pathXMin = jmin (pathXMin, x1, x2);
  66582. pathXMax = jmax (pathXMax, x1, x2);
  66583. pathYMin = jmin (pathYMin, y1, y2);
  66584. pathYMax = jmax (pathYMax, y1, y2);
  66585. }
  66586. void Path::cubicTo (const float x1, const float y1,
  66587. const float x2, const float y2,
  66588. const float x3, const float y3) throw()
  66589. {
  66590. CHECK_COORDS_ARE_VALID (x1, y1);
  66591. CHECK_COORDS_ARE_VALID (x2, y2);
  66592. CHECK_COORDS_ARE_VALID (x3, y3);
  66593. if (numElements == 0)
  66594. startNewSubPath (0, 0);
  66595. ensureAllocatedSize (numElements + 7);
  66596. elements [numElements++] = cubicMarker;
  66597. elements [numElements++] = x1;
  66598. elements [numElements++] = y1;
  66599. elements [numElements++] = x2;
  66600. elements [numElements++] = y2;
  66601. elements [numElements++] = x3;
  66602. elements [numElements++] = y3;
  66603. pathXMin = jmin (pathXMin, x1, x2, x3);
  66604. pathXMax = jmax (pathXMax, x1, x2, x3);
  66605. pathYMin = jmin (pathYMin, y1, y2, y3);
  66606. pathYMax = jmax (pathYMax, y1, y2, y3);
  66607. }
  66608. void Path::closeSubPath() throw()
  66609. {
  66610. if (numElements > 0
  66611. && elements [numElements - 1] != closeSubPathMarker)
  66612. {
  66613. ensureAllocatedSize (numElements + 1);
  66614. elements [numElements++] = closeSubPathMarker;
  66615. }
  66616. }
  66617. const Point Path::getCurrentPosition() const
  66618. {
  66619. int i = numElements - 1;
  66620. if (i > 0 && elements[i] == closeSubPathMarker)
  66621. {
  66622. while (i >= 0)
  66623. {
  66624. if (elements[i] == moveMarker)
  66625. {
  66626. i += 2;
  66627. break;
  66628. }
  66629. --i;
  66630. }
  66631. }
  66632. if (i > 0)
  66633. return Point (elements [i - 1], elements [i]);
  66634. return Point (0.0f, 0.0f);
  66635. }
  66636. void Path::addRectangle (const float x, const float y,
  66637. const float w, const float h) throw()
  66638. {
  66639. startNewSubPath (x, y + h);
  66640. lineTo (x, y);
  66641. lineTo (x + w, y);
  66642. lineTo (x + w, y + h);
  66643. closeSubPath();
  66644. }
  66645. void Path::addRoundedRectangle (const float x, const float y,
  66646. const float w, const float h,
  66647. float csx,
  66648. float csy) throw()
  66649. {
  66650. csx = jmin (csx, w * 0.5f);
  66651. csy = jmin (csy, h * 0.5f);
  66652. const float cs45x = csx * 0.45f;
  66653. const float cs45y = csy * 0.45f;
  66654. const float x2 = x + w;
  66655. const float y2 = y + h;
  66656. startNewSubPath (x + csx, y);
  66657. lineTo (x2 - csx, y);
  66658. cubicTo (x2 - cs45x, y, x2, y + cs45y, x2, y + csy);
  66659. lineTo (x2, y2 - csy);
  66660. cubicTo (x2, y2 - cs45y, x2 - cs45x, y2, x2 - csx, y2);
  66661. lineTo (x + csx, y2);
  66662. cubicTo (x + cs45x, y2, x, y2 - cs45y, x, y2 - csy);
  66663. lineTo (x, y + csy);
  66664. cubicTo (x, y + cs45y, x + cs45x, y, x + csx, y);
  66665. closeSubPath();
  66666. }
  66667. void Path::addRoundedRectangle (const float x, const float y,
  66668. const float w, const float h,
  66669. float cs) throw()
  66670. {
  66671. addRoundedRectangle (x, y, w, h, cs, cs);
  66672. }
  66673. void Path::addTriangle (const float x1, const float y1,
  66674. const float x2, const float y2,
  66675. const float x3, const float y3) throw()
  66676. {
  66677. startNewSubPath (x1, y1);
  66678. lineTo (x2, y2);
  66679. lineTo (x3, y3);
  66680. closeSubPath();
  66681. }
  66682. void Path::addQuadrilateral (const float x1, const float y1,
  66683. const float x2, const float y2,
  66684. const float x3, const float y3,
  66685. const float x4, const float y4) throw()
  66686. {
  66687. startNewSubPath (x1, y1);
  66688. lineTo (x2, y2);
  66689. lineTo (x3, y3);
  66690. lineTo (x4, y4);
  66691. closeSubPath();
  66692. }
  66693. void Path::addEllipse (const float x, const float y,
  66694. const float w, const float h) throw()
  66695. {
  66696. const float hw = w * 0.5f;
  66697. const float hw55 = hw * 0.55f;
  66698. const float hh = h * 0.5f;
  66699. const float hh45 = hh * 0.55f;
  66700. const float cx = x + hw;
  66701. const float cy = y + hh;
  66702. startNewSubPath (cx, cy - hh);
  66703. cubicTo (cx + hw55, cy - hh, cx + hw, cy - hh45, cx + hw, cy);
  66704. cubicTo (cx + hw, cy + hh45, cx + hw55, cy + hh, cx, cy + hh);
  66705. cubicTo (cx - hw55, cy + hh, cx - hw, cy + hh45, cx - hw, cy);
  66706. cubicTo (cx - hw, cy - hh45, cx - hw55, cy - hh, cx, cy - hh);
  66707. closeSubPath();
  66708. }
  66709. void Path::addArc (const float x, const float y,
  66710. const float w, const float h,
  66711. const float fromRadians,
  66712. const float toRadians,
  66713. const bool startAsNewSubPath) throw()
  66714. {
  66715. const float radiusX = w / 2.0f;
  66716. const float radiusY = h / 2.0f;
  66717. addCentredArc (x + radiusX,
  66718. y + radiusY,
  66719. radiusX, radiusY,
  66720. 0.0f,
  66721. fromRadians, toRadians,
  66722. startAsNewSubPath);
  66723. }
  66724. static const float ellipseAngularIncrement = 0.05f;
  66725. void Path::addCentredArc (const float centreX, const float centreY,
  66726. const float radiusX, const float radiusY,
  66727. const float rotationOfEllipse,
  66728. const float fromRadians,
  66729. const float toRadians,
  66730. const bool startAsNewSubPath) throw()
  66731. {
  66732. if (radiusX > 0.0f && radiusY > 0.0f)
  66733. {
  66734. const AffineTransform rotation (AffineTransform::rotation (rotationOfEllipse, centreX, centreY));
  66735. float angle = fromRadians;
  66736. if (startAsNewSubPath)
  66737. {
  66738. float x = centreX + radiusX * sinf (angle);
  66739. float y = centreY - radiusY * cosf (angle);
  66740. if (rotationOfEllipse != 0)
  66741. rotation.transformPoint (x, y);
  66742. startNewSubPath (x, y);
  66743. }
  66744. if (fromRadians < toRadians)
  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. else
  66759. {
  66760. if (startAsNewSubPath)
  66761. angle -= ellipseAngularIncrement;
  66762. while (angle > toRadians)
  66763. {
  66764. float x = centreX + radiusX * sinf (angle);
  66765. float y = centreY - radiusY * cosf (angle);
  66766. if (rotationOfEllipse != 0)
  66767. rotation.transformPoint (x, y);
  66768. lineTo (x, y);
  66769. angle -= ellipseAngularIncrement;
  66770. }
  66771. }
  66772. float x = centreX + radiusX * sinf (toRadians);
  66773. float y = centreY - radiusY * cosf (toRadians);
  66774. if (rotationOfEllipse != 0)
  66775. rotation.transformPoint (x, y);
  66776. lineTo (x, y);
  66777. }
  66778. }
  66779. void Path::addPieSegment (const float x, const float y,
  66780. const float width, const float height,
  66781. const float fromRadians,
  66782. const float toRadians,
  66783. const float innerCircleProportionalSize)
  66784. {
  66785. float hw = width * 0.5f;
  66786. float hh = height * 0.5f;
  66787. const float centreX = x + hw;
  66788. const float centreY = y + hh;
  66789. startNewSubPath (centreX + hw * sinf (fromRadians),
  66790. centreY - hh * cosf (fromRadians));
  66791. addArc (x, y, width, height, fromRadians, toRadians);
  66792. if (fabs (fromRadians - toRadians) > float_Pi * 1.999f)
  66793. {
  66794. closeSubPath();
  66795. if (innerCircleProportionalSize > 0)
  66796. {
  66797. hw *= innerCircleProportionalSize;
  66798. hh *= innerCircleProportionalSize;
  66799. startNewSubPath (centreX + hw * sinf (toRadians),
  66800. centreY - hh * cosf (toRadians));
  66801. addArc (centreX - hw, centreY - hh, hw * 2.0f, hh * 2.0f,
  66802. toRadians, fromRadians);
  66803. }
  66804. }
  66805. else
  66806. {
  66807. if (innerCircleProportionalSize > 0)
  66808. {
  66809. hw *= innerCircleProportionalSize;
  66810. hh *= innerCircleProportionalSize;
  66811. addArc (centreX - hw, centreY - hh, hw * 2.0f, hh * 2.0f,
  66812. toRadians, fromRadians);
  66813. }
  66814. else
  66815. {
  66816. lineTo (centreX, centreY);
  66817. }
  66818. }
  66819. closeSubPath();
  66820. }
  66821. static void perpendicularOffset (const float x1, const float y1,
  66822. const float x2, const float y2,
  66823. const float offsetX, const float offsetY,
  66824. float& resultX, float& resultY) throw()
  66825. {
  66826. const float dx = x2 - x1;
  66827. const float dy = y2 - y1;
  66828. const float len = juce_hypotf (dx, dy);
  66829. if (len == 0)
  66830. {
  66831. resultX = x1;
  66832. resultY = y1;
  66833. }
  66834. else
  66835. {
  66836. resultX = x1 + ((dx * offsetX) - (dy * offsetY)) / len;
  66837. resultY = y1 + ((dy * offsetX) + (dx * offsetY)) / len;
  66838. }
  66839. }
  66840. void Path::addLineSegment (const float startX, const float startY,
  66841. const float endX, const float endY,
  66842. float lineThickness) throw()
  66843. {
  66844. lineThickness *= 0.5f;
  66845. float x, y;
  66846. perpendicularOffset (startX, startY, endX, endY,
  66847. 0, lineThickness, x, y);
  66848. startNewSubPath (x, y);
  66849. perpendicularOffset (startX, startY, endX, endY,
  66850. 0, -lineThickness, x, y);
  66851. lineTo (x, y);
  66852. perpendicularOffset (endX, endY, startX, startY,
  66853. 0, lineThickness, x, y);
  66854. lineTo (x, y);
  66855. perpendicularOffset (endX, endY, startX, startY,
  66856. 0, -lineThickness, x, y);
  66857. lineTo (x, y);
  66858. closeSubPath();
  66859. }
  66860. void Path::addArrow (const float startX, const float startY,
  66861. const float endX, const float endY,
  66862. float lineThickness,
  66863. float arrowheadWidth,
  66864. float arrowheadLength) throw()
  66865. {
  66866. lineThickness *= 0.5f;
  66867. arrowheadWidth *= 0.5f;
  66868. arrowheadLength = jmin (arrowheadLength, 0.8f * juce_hypotf (startX - endX,
  66869. startY - endY));
  66870. float x, y;
  66871. perpendicularOffset (startX, startY, endX, endY,
  66872. 0, lineThickness, x, y);
  66873. startNewSubPath (x, y);
  66874. perpendicularOffset (startX, startY, endX, endY,
  66875. 0, -lineThickness, x, y);
  66876. lineTo (x, y);
  66877. perpendicularOffset (endX, endY, startX, startY,
  66878. arrowheadLength, lineThickness, x, y);
  66879. lineTo (x, y);
  66880. perpendicularOffset (endX, endY, startX, startY,
  66881. arrowheadLength, arrowheadWidth, x, y);
  66882. lineTo (x, y);
  66883. perpendicularOffset (endX, endY, startX, startY,
  66884. 0, 0, x, y);
  66885. lineTo (x, y);
  66886. perpendicularOffset (endX, endY, startX, startY,
  66887. arrowheadLength, -arrowheadWidth, x, y);
  66888. lineTo (x, y);
  66889. perpendicularOffset (endX, endY, startX, startY,
  66890. arrowheadLength, -lineThickness, x, y);
  66891. lineTo (x, y);
  66892. closeSubPath();
  66893. }
  66894. void Path::addStar (const float centreX,
  66895. const float centreY,
  66896. const int numberOfPoints,
  66897. const float innerRadius,
  66898. const float outerRadius,
  66899. const float startAngle)
  66900. {
  66901. jassert (numberOfPoints > 1); // this would be silly.
  66902. if (numberOfPoints > 1)
  66903. {
  66904. const float angleBetweenPoints = float_Pi * 2.0f / numberOfPoints;
  66905. for (int i = 0; i < numberOfPoints; ++i)
  66906. {
  66907. float angle = startAngle + i * angleBetweenPoints;
  66908. const float x = centreX + outerRadius * sinf (angle);
  66909. const float y = centreY - outerRadius * cosf (angle);
  66910. if (i == 0)
  66911. startNewSubPath (x, y);
  66912. else
  66913. lineTo (x, y);
  66914. angle += angleBetweenPoints * 0.5f;
  66915. lineTo (centreX + innerRadius * sinf (angle),
  66916. centreY - innerRadius * cosf (angle));
  66917. }
  66918. closeSubPath();
  66919. }
  66920. }
  66921. void Path::addBubble (float x, float y,
  66922. float w, float h,
  66923. float cs,
  66924. float tipX,
  66925. float tipY,
  66926. int whichSide,
  66927. float arrowPos,
  66928. float arrowWidth)
  66929. {
  66930. if (w > 1.0f && h > 1.0f)
  66931. {
  66932. cs = jmin (cs, w * 0.5f, h * 0.5f);
  66933. const float cs2 = 2.0f * cs;
  66934. startNewSubPath (x + cs, y);
  66935. if (whichSide == 0)
  66936. {
  66937. const float halfArrowW = jmin (arrowWidth, w - cs2) * 0.5f;
  66938. const float arrowX1 = x + cs + jmax (0.0f, (w - cs2) * arrowPos - halfArrowW);
  66939. lineTo (arrowX1, y);
  66940. lineTo (tipX, tipY);
  66941. lineTo (arrowX1 + halfArrowW * 2.0f, y);
  66942. }
  66943. lineTo (x + w - cs, y);
  66944. if (cs > 0.0f)
  66945. addArc (x + w - cs2, y, cs2, cs2, 0, float_Pi * 0.5f);
  66946. if (whichSide == 3)
  66947. {
  66948. const float halfArrowH = jmin (arrowWidth, h - cs2) * 0.5f;
  66949. const float arrowY1 = y + cs + jmax (0.0f, (h - cs2) * arrowPos - halfArrowH);
  66950. lineTo (x + w, arrowY1);
  66951. lineTo (tipX, tipY);
  66952. lineTo (x + w, arrowY1 + halfArrowH * 2.0f);
  66953. }
  66954. lineTo (x + w, y + h - cs);
  66955. if (cs > 0.0f)
  66956. addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  66957. if (whichSide == 2)
  66958. {
  66959. const float halfArrowW = jmin (arrowWidth, w - cs2) * 0.5f;
  66960. const float arrowX1 = x + cs + jmax (0.0f, (w - cs2) * arrowPos - halfArrowW);
  66961. lineTo (arrowX1 + halfArrowW * 2.0f, y + h);
  66962. lineTo (tipX, tipY);
  66963. lineTo (arrowX1, y + h);
  66964. }
  66965. lineTo (x + cs, y + h);
  66966. if (cs > 0.0f)
  66967. addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  66968. if (whichSide == 1)
  66969. {
  66970. const float halfArrowH = jmin (arrowWidth, h - cs2) * 0.5f;
  66971. const float arrowY1 = y + cs + jmax (0.0f, (h - cs2) * arrowPos - halfArrowH);
  66972. lineTo (x, arrowY1 + halfArrowH * 2.0f);
  66973. lineTo (tipX, tipY);
  66974. lineTo (x, arrowY1);
  66975. }
  66976. lineTo (x, y + cs);
  66977. if (cs > 0.0f)
  66978. addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f - ellipseAngularIncrement);
  66979. closeSubPath();
  66980. }
  66981. }
  66982. void Path::addPath (const Path& other) throw()
  66983. {
  66984. int i = 0;
  66985. while (i < other.numElements)
  66986. {
  66987. const float type = other.elements [i++];
  66988. if (type == moveMarker)
  66989. {
  66990. startNewSubPath (other.elements [i],
  66991. other.elements [i + 1]);
  66992. i += 2;
  66993. }
  66994. else if (type == lineMarker)
  66995. {
  66996. lineTo (other.elements [i],
  66997. other.elements [i + 1]);
  66998. i += 2;
  66999. }
  67000. else if (type == quadMarker)
  67001. {
  67002. quadraticTo (other.elements [i],
  67003. other.elements [i + 1],
  67004. other.elements [i + 2],
  67005. other.elements [i + 3]);
  67006. i += 4;
  67007. }
  67008. else if (type == cubicMarker)
  67009. {
  67010. cubicTo (other.elements [i],
  67011. other.elements [i + 1],
  67012. other.elements [i + 2],
  67013. other.elements [i + 3],
  67014. other.elements [i + 4],
  67015. other.elements [i + 5]);
  67016. i += 6;
  67017. }
  67018. else if (type == closeSubPathMarker)
  67019. {
  67020. closeSubPath();
  67021. }
  67022. else
  67023. {
  67024. // something's gone wrong with the element list!
  67025. jassertfalse
  67026. }
  67027. }
  67028. }
  67029. void Path::addPath (const Path& other,
  67030. const AffineTransform& transformToApply) throw()
  67031. {
  67032. int i = 0;
  67033. while (i < other.numElements)
  67034. {
  67035. const float type = other.elements [i++];
  67036. if (type == closeSubPathMarker)
  67037. {
  67038. closeSubPath();
  67039. }
  67040. else
  67041. {
  67042. float x = other.elements [i++];
  67043. float y = other.elements [i++];
  67044. transformToApply.transformPoint (x, y);
  67045. if (type == moveMarker)
  67046. {
  67047. startNewSubPath (x, y);
  67048. }
  67049. else if (type == lineMarker)
  67050. {
  67051. lineTo (x, y);
  67052. }
  67053. else if (type == quadMarker)
  67054. {
  67055. float x2 = other.elements [i++];
  67056. float y2 = other.elements [i++];
  67057. transformToApply.transformPoint (x2, y2);
  67058. quadraticTo (x, y, x2, y2);
  67059. }
  67060. else if (type == cubicMarker)
  67061. {
  67062. float x2 = other.elements [i++];
  67063. float y2 = other.elements [i++];
  67064. float x3 = other.elements [i++];
  67065. float y3 = other.elements [i++];
  67066. transformToApply.transformPoint (x2, y2);
  67067. transformToApply.transformPoint (x3, y3);
  67068. cubicTo (x, y, x2, y2, x3, y3);
  67069. }
  67070. else
  67071. {
  67072. // something's gone wrong with the element list!
  67073. jassertfalse
  67074. }
  67075. }
  67076. }
  67077. }
  67078. void Path::applyTransform (const AffineTransform& transform) throw()
  67079. {
  67080. int i = 0;
  67081. pathYMin = pathXMin = 0;
  67082. pathYMax = pathXMax = 0;
  67083. bool setMaxMin = false;
  67084. while (i < numElements)
  67085. {
  67086. const float type = elements [i++];
  67087. if (type == moveMarker)
  67088. {
  67089. transform.transformPoint (elements [i],
  67090. elements [i + 1]);
  67091. if (setMaxMin)
  67092. {
  67093. pathXMin = jmin (pathXMin, elements [i]);
  67094. pathXMax = jmax (pathXMax, elements [i]);
  67095. pathYMin = jmin (pathYMin, elements [i + 1]);
  67096. pathYMax = jmax (pathYMax, elements [i + 1]);
  67097. }
  67098. else
  67099. {
  67100. pathXMin = pathXMax = elements [i];
  67101. pathYMin = pathYMax = elements [i + 1];
  67102. setMaxMin = true;
  67103. }
  67104. i += 2;
  67105. }
  67106. else if (type == lineMarker)
  67107. {
  67108. transform.transformPoint (elements [i],
  67109. elements [i + 1]);
  67110. pathXMin = jmin (pathXMin, elements [i]);
  67111. pathXMax = jmax (pathXMax, elements [i]);
  67112. pathYMin = jmin (pathYMin, elements [i + 1]);
  67113. pathYMax = jmax (pathYMax, elements [i + 1]);
  67114. i += 2;
  67115. }
  67116. else if (type == quadMarker)
  67117. {
  67118. transform.transformPoint (elements [i],
  67119. elements [i + 1]);
  67120. transform.transformPoint (elements [i + 2],
  67121. elements [i + 3]);
  67122. pathXMin = jmin (pathXMin, elements [i], elements [i + 2]);
  67123. pathXMax = jmax (pathXMax, elements [i], elements [i + 2]);
  67124. pathYMin = jmin (pathYMin, elements [i + 1], elements [i + 3]);
  67125. pathYMax = jmax (pathYMax, elements [i + 1], elements [i + 3]);
  67126. i += 4;
  67127. }
  67128. else if (type == cubicMarker)
  67129. {
  67130. transform.transformPoint (elements [i],
  67131. elements [i + 1]);
  67132. transform.transformPoint (elements [i + 2],
  67133. elements [i + 3]);
  67134. transform.transformPoint (elements [i + 4],
  67135. elements [i + 5]);
  67136. pathXMin = jmin (pathXMin, elements [i], elements [i + 2], elements [i + 4]);
  67137. pathXMax = jmax (pathXMax, elements [i], elements [i + 2], elements [i + 4]);
  67138. pathYMin = jmin (pathYMin, elements [i + 1], elements [i + 3], elements [i + 5]);
  67139. pathYMax = jmax (pathYMax, elements [i + 1], elements [i + 3], elements [i + 5]);
  67140. i += 6;
  67141. }
  67142. }
  67143. }
  67144. const AffineTransform Path::getTransformToScaleToFit (const float x, const float y,
  67145. const float w, const float h,
  67146. const bool preserveProportions,
  67147. const Justification& justification) const throw()
  67148. {
  67149. float sx, sy, sw, sh;
  67150. getBounds (sx, sy, sw, sh);
  67151. if (preserveProportions)
  67152. {
  67153. if (w <= 0 || h <= 0 || sw <= 0 || sh <= 0)
  67154. return AffineTransform::identity;
  67155. float newW, newH;
  67156. const float srcRatio = sh / sw;
  67157. if (srcRatio > h / w)
  67158. {
  67159. newW = h / srcRatio;
  67160. newH = h;
  67161. }
  67162. else
  67163. {
  67164. newW = w;
  67165. newH = w * srcRatio;
  67166. }
  67167. float newXCentre = x;
  67168. float newYCentre = y;
  67169. if (justification.testFlags (Justification::left))
  67170. newXCentre += newW * 0.5f;
  67171. else if (justification.testFlags (Justification::right))
  67172. newXCentre += w - newW * 0.5f;
  67173. else
  67174. newXCentre += w * 0.5f;
  67175. if (justification.testFlags (Justification::top))
  67176. newYCentre += newH * 0.5f;
  67177. else if (justification.testFlags (Justification::bottom))
  67178. newYCentre += h - newH * 0.5f;
  67179. else
  67180. newYCentre += h * 0.5f;
  67181. return AffineTransform::translation (sw * -0.5f - sx, sh * -0.5f - sy)
  67182. .scaled (newW / sw, newH / sh)
  67183. .translated (newXCentre, newYCentre);
  67184. }
  67185. else
  67186. {
  67187. return AffineTransform::translation (-sx, -sy)
  67188. .scaled (w / sw, h / sh)
  67189. .translated (x, y);
  67190. }
  67191. }
  67192. static const float collisionDetectionTolerence = 20.0f;
  67193. bool Path::contains (const float x, const float y) const throw()
  67194. {
  67195. if (x <= pathXMin || x >= pathXMax
  67196. || y <= pathYMin || y >= pathYMax)
  67197. return false;
  67198. PathFlatteningIterator i (*this, AffineTransform::identity, collisionDetectionTolerence);
  67199. int positiveCrossings = 0;
  67200. int negativeCrossings = 0;
  67201. while (i.next())
  67202. {
  67203. if ((i.y1 <= y && i.y2 > y)
  67204. || (i.y2 <= y && i.y1 > y))
  67205. {
  67206. const float intersectX = i.x1 + (i.x2 - i.x1) * (y - i.y1) / (i.y2 - i.y1);
  67207. if (intersectX <= x)
  67208. {
  67209. if (i.y1 < i.y2)
  67210. ++positiveCrossings;
  67211. else
  67212. ++negativeCrossings;
  67213. }
  67214. }
  67215. }
  67216. return (useNonZeroWinding) ? (negativeCrossings != positiveCrossings)
  67217. : ((negativeCrossings + positiveCrossings) & 1) != 0;
  67218. }
  67219. bool Path::intersectsLine (const float x1, const float y1,
  67220. const float x2, const float y2) throw()
  67221. {
  67222. PathFlatteningIterator i (*this, AffineTransform::identity, collisionDetectionTolerence);
  67223. const Line line1 (x1, y1, x2, y2);
  67224. while (i.next())
  67225. {
  67226. const Line line2 (i.x1, i.y1, i.x2, i.y2);
  67227. float ix, iy;
  67228. if (line1.intersects (line2, ix, iy))
  67229. return true;
  67230. }
  67231. return false;
  67232. }
  67233. const Path Path::createPathWithRoundedCorners (const float cornerRadius) const throw()
  67234. {
  67235. if (cornerRadius <= 0.01f)
  67236. return *this;
  67237. int indexOfPathStart = 0, indexOfPathStartThis = 0;
  67238. int n = 0;
  67239. bool lastWasLine = false, firstWasLine = false;
  67240. Path p;
  67241. while (n < numElements)
  67242. {
  67243. const float type = elements [n++];
  67244. if (type == moveMarker)
  67245. {
  67246. indexOfPathStart = p.numElements;
  67247. indexOfPathStartThis = n - 1;
  67248. const float x = elements [n++];
  67249. const float y = elements [n++];
  67250. p.startNewSubPath (x, y);
  67251. lastWasLine = false;
  67252. firstWasLine = (elements [n] == lineMarker);
  67253. }
  67254. else if (type == lineMarker || type == closeSubPathMarker)
  67255. {
  67256. float startX = 0, startY = 0, joinX = 0, joinY = 0, endX, endY;
  67257. if (type == lineMarker)
  67258. {
  67259. endX = elements [n++];
  67260. endY = elements [n++];
  67261. if (n > 8)
  67262. {
  67263. startX = elements [n - 8];
  67264. startY = elements [n - 7];
  67265. joinX = elements [n - 5];
  67266. joinY = elements [n - 4];
  67267. }
  67268. }
  67269. else
  67270. {
  67271. endX = elements [indexOfPathStartThis + 1];
  67272. endY = elements [indexOfPathStartThis + 2];
  67273. if (n > 6)
  67274. {
  67275. startX = elements [n - 6];
  67276. startY = elements [n - 5];
  67277. joinX = elements [n - 3];
  67278. joinY = elements [n - 2];
  67279. }
  67280. }
  67281. if (lastWasLine)
  67282. {
  67283. const double len1 = juce_hypot (startX - joinX,
  67284. startY - joinY);
  67285. if (len1 > 0)
  67286. {
  67287. const double propNeeded = jmin (0.5, cornerRadius / len1);
  67288. p.elements [p.numElements - 2] = (float) (joinX - (joinX - startX) * propNeeded);
  67289. p.elements [p.numElements - 1] = (float) (joinY - (joinY - startY) * propNeeded);
  67290. }
  67291. const double len2 = juce_hypot (endX - joinX,
  67292. endY - joinY);
  67293. if (len2 > 0)
  67294. {
  67295. const double propNeeded = jmin (0.5, cornerRadius / len2);
  67296. p.quadraticTo (joinX, joinY,
  67297. (float) (joinX + (endX - joinX) * propNeeded),
  67298. (float) (joinY + (endY - joinY) * propNeeded));
  67299. }
  67300. p.lineTo (endX, endY);
  67301. }
  67302. else if (type == lineMarker)
  67303. {
  67304. p.lineTo (endX, endY);
  67305. lastWasLine = true;
  67306. }
  67307. if (type == closeSubPathMarker)
  67308. {
  67309. if (firstWasLine)
  67310. {
  67311. startX = elements [n - 3];
  67312. startY = elements [n - 2];
  67313. joinX = endX;
  67314. joinY = endY;
  67315. endX = elements [indexOfPathStartThis + 4];
  67316. endY = elements [indexOfPathStartThis + 5];
  67317. const double len1 = juce_hypot (startX - joinX,
  67318. startY - joinY);
  67319. if (len1 > 0)
  67320. {
  67321. const double propNeeded = jmin (0.5, cornerRadius / len1);
  67322. p.elements [p.numElements - 2] = (float) (joinX - (joinX - startX) * propNeeded);
  67323. p.elements [p.numElements - 1] = (float) (joinY - (joinY - startY) * propNeeded);
  67324. }
  67325. const double len2 = juce_hypot (endX - joinX,
  67326. endY - joinY);
  67327. if (len2 > 0)
  67328. {
  67329. const double propNeeded = jmin (0.5, cornerRadius / len2);
  67330. endX = (float) (joinX + (endX - joinX) * propNeeded);
  67331. endY = (float) (joinY + (endY - joinY) * propNeeded);
  67332. p.quadraticTo (joinX, joinY, endX, endY);
  67333. p.elements [indexOfPathStart + 1] = endX;
  67334. p.elements [indexOfPathStart + 2] = endY;
  67335. }
  67336. }
  67337. p.closeSubPath();
  67338. }
  67339. }
  67340. else if (type == quadMarker)
  67341. {
  67342. lastWasLine = false;
  67343. const float x1 = elements [n++];
  67344. const float y1 = elements [n++];
  67345. const float x2 = elements [n++];
  67346. const float y2 = elements [n++];
  67347. p.quadraticTo (x1, y1, x2, y2);
  67348. }
  67349. else if (type == cubicMarker)
  67350. {
  67351. lastWasLine = false;
  67352. const float x1 = elements [n++];
  67353. const float y1 = elements [n++];
  67354. const float x2 = elements [n++];
  67355. const float y2 = elements [n++];
  67356. const float x3 = elements [n++];
  67357. const float y3 = elements [n++];
  67358. p.cubicTo (x1, y1, x2, y2, x3, y3);
  67359. }
  67360. }
  67361. return p;
  67362. }
  67363. void Path::loadPathFromStream (InputStream& source)
  67364. {
  67365. while (! source.isExhausted())
  67366. {
  67367. switch (source.readByte())
  67368. {
  67369. case 'm':
  67370. {
  67371. const float x = source.readFloat();
  67372. const float y = source.readFloat();
  67373. startNewSubPath (x, y);
  67374. break;
  67375. }
  67376. case 'l':
  67377. {
  67378. const float x = source.readFloat();
  67379. const float y = source.readFloat();
  67380. lineTo (x, y);
  67381. break;
  67382. }
  67383. case 'q':
  67384. {
  67385. const float x1 = source.readFloat();
  67386. const float y1 = source.readFloat();
  67387. const float x2 = source.readFloat();
  67388. const float y2 = source.readFloat();
  67389. quadraticTo (x1, y1, x2, y2);
  67390. break;
  67391. }
  67392. case 'b':
  67393. {
  67394. const float x1 = source.readFloat();
  67395. const float y1 = source.readFloat();
  67396. const float x2 = source.readFloat();
  67397. const float y2 = source.readFloat();
  67398. const float x3 = source.readFloat();
  67399. const float y3 = source.readFloat();
  67400. cubicTo (x1, y1, x2, y2, x3, y3);
  67401. break;
  67402. }
  67403. case 'c':
  67404. closeSubPath();
  67405. break;
  67406. case 'n':
  67407. useNonZeroWinding = true;
  67408. break;
  67409. case 'z':
  67410. useNonZeroWinding = false;
  67411. break;
  67412. case 'e':
  67413. return; // end of path marker
  67414. default:
  67415. jassertfalse // illegal char in the stream
  67416. break;
  67417. }
  67418. }
  67419. }
  67420. void Path::loadPathFromData (const unsigned char* const data,
  67421. const int numberOfBytes) throw()
  67422. {
  67423. MemoryInputStream in ((const char*) data, numberOfBytes, false);
  67424. loadPathFromStream (in);
  67425. }
  67426. void Path::writePathToStream (OutputStream& dest) const
  67427. {
  67428. dest.writeByte ((useNonZeroWinding) ? 'n' : 'z');
  67429. int i = 0;
  67430. while (i < numElements)
  67431. {
  67432. const float type = elements [i++];
  67433. if (type == moveMarker)
  67434. {
  67435. dest.writeByte ('m');
  67436. dest.writeFloat (elements [i++]);
  67437. dest.writeFloat (elements [i++]);
  67438. }
  67439. else if (type == lineMarker)
  67440. {
  67441. dest.writeByte ('l');
  67442. dest.writeFloat (elements [i++]);
  67443. dest.writeFloat (elements [i++]);
  67444. }
  67445. else if (type == quadMarker)
  67446. {
  67447. dest.writeByte ('q');
  67448. dest.writeFloat (elements [i++]);
  67449. dest.writeFloat (elements [i++]);
  67450. dest.writeFloat (elements [i++]);
  67451. dest.writeFloat (elements [i++]);
  67452. }
  67453. else if (type == cubicMarker)
  67454. {
  67455. dest.writeByte ('b');
  67456. dest.writeFloat (elements [i++]);
  67457. dest.writeFloat (elements [i++]);
  67458. dest.writeFloat (elements [i++]);
  67459. dest.writeFloat (elements [i++]);
  67460. dest.writeFloat (elements [i++]);
  67461. dest.writeFloat (elements [i++]);
  67462. }
  67463. else if (type == closeSubPathMarker)
  67464. {
  67465. dest.writeByte ('c');
  67466. }
  67467. }
  67468. dest.writeByte ('e'); // marks the end-of-path
  67469. }
  67470. const String Path::toString() const
  67471. {
  67472. String s;
  67473. s.preallocateStorage (numElements * 4);
  67474. if (! useNonZeroWinding)
  67475. s << T("a ");
  67476. int i = 0;
  67477. float lastMarker = 0.0f;
  67478. while (i < numElements)
  67479. {
  67480. const float marker = elements [i++];
  67481. tchar markerChar = 0;
  67482. int numCoords = 0;
  67483. if (marker == moveMarker)
  67484. {
  67485. markerChar = T('m');
  67486. numCoords = 2;
  67487. }
  67488. else if (marker == lineMarker)
  67489. {
  67490. markerChar = T('l');
  67491. numCoords = 2;
  67492. }
  67493. else if (marker == quadMarker)
  67494. {
  67495. markerChar = T('q');
  67496. numCoords = 4;
  67497. }
  67498. else if (marker == cubicMarker)
  67499. {
  67500. markerChar = T('c');
  67501. numCoords = 6;
  67502. }
  67503. else
  67504. {
  67505. jassert (marker == closeSubPathMarker);
  67506. markerChar = T('z');
  67507. }
  67508. if (marker != lastMarker)
  67509. {
  67510. s << markerChar << T(' ');
  67511. lastMarker = marker;
  67512. }
  67513. while (--numCoords >= 0 && i < numElements)
  67514. {
  67515. String n (elements [i++], 3);
  67516. while (n.endsWithChar (T('0')))
  67517. n = n.dropLastCharacters (1);
  67518. if (n.endsWithChar (T('.')))
  67519. n = n.dropLastCharacters (1);
  67520. s << n << T(' ');
  67521. }
  67522. }
  67523. return s.trimEnd();
  67524. }
  67525. static const String nextToken (const tchar*& t)
  67526. {
  67527. while (*t == T(' '))
  67528. ++t;
  67529. const tchar* const start = t;
  67530. while (*t != 0 && *t != T(' '))
  67531. ++t;
  67532. const int length = (int) (t - start);
  67533. while (*t == T(' '))
  67534. ++t;
  67535. return String (start, length);
  67536. }
  67537. void Path::restoreFromString (const String& stringVersion)
  67538. {
  67539. clear();
  67540. setUsingNonZeroWinding (true);
  67541. const tchar* t = stringVersion;
  67542. tchar marker = T('m');
  67543. int numValues = 2;
  67544. float values [6];
  67545. while (*t != 0)
  67546. {
  67547. const String token (nextToken (t));
  67548. const tchar firstChar = token[0];
  67549. int startNum = 0;
  67550. if (firstChar == T('m') || firstChar == T('l'))
  67551. {
  67552. marker = firstChar;
  67553. numValues = 2;
  67554. }
  67555. else if (firstChar == T('q'))
  67556. {
  67557. marker = firstChar;
  67558. numValues = 4;
  67559. }
  67560. else if (firstChar == T('c'))
  67561. {
  67562. marker = firstChar;
  67563. numValues = 6;
  67564. }
  67565. else if (firstChar == T('z'))
  67566. {
  67567. marker = firstChar;
  67568. numValues = 0;
  67569. }
  67570. else if (firstChar == T('a'))
  67571. {
  67572. setUsingNonZeroWinding (false);
  67573. continue;
  67574. }
  67575. else
  67576. {
  67577. ++startNum;
  67578. values [0] = token.getFloatValue();
  67579. }
  67580. for (int i = startNum; i < numValues; ++i)
  67581. values [i] = nextToken (t).getFloatValue();
  67582. switch (marker)
  67583. {
  67584. case T('m'):
  67585. startNewSubPath (values[0], values[1]);
  67586. break;
  67587. case T('l'):
  67588. lineTo (values[0], values[1]);
  67589. break;
  67590. case T('q'):
  67591. quadraticTo (values[0], values[1],
  67592. values[2], values[3]);
  67593. break;
  67594. case T('c'):
  67595. cubicTo (values[0], values[1],
  67596. values[2], values[3],
  67597. values[4], values[5]);
  67598. break;
  67599. case T('z'):
  67600. closeSubPath();
  67601. break;
  67602. default:
  67603. jassertfalse // illegal string format?
  67604. break;
  67605. }
  67606. }
  67607. }
  67608. Path::Iterator::Iterator (const Path& path_)
  67609. : path (path_),
  67610. index (0)
  67611. {
  67612. }
  67613. Path::Iterator::~Iterator()
  67614. {
  67615. }
  67616. bool Path::Iterator::next()
  67617. {
  67618. const float* const elements = path.elements;
  67619. if (index < path.numElements)
  67620. {
  67621. const float type = elements [index++];
  67622. if (type == moveMarker)
  67623. {
  67624. elementType = startNewSubPath;
  67625. x1 = elements [index++];
  67626. y1 = elements [index++];
  67627. }
  67628. else if (type == lineMarker)
  67629. {
  67630. elementType = lineTo;
  67631. x1 = elements [index++];
  67632. y1 = elements [index++];
  67633. }
  67634. else if (type == quadMarker)
  67635. {
  67636. elementType = quadraticTo;
  67637. x1 = elements [index++];
  67638. y1 = elements [index++];
  67639. x2 = elements [index++];
  67640. y2 = elements [index++];
  67641. }
  67642. else if (type == cubicMarker)
  67643. {
  67644. elementType = cubicTo;
  67645. x1 = elements [index++];
  67646. y1 = elements [index++];
  67647. x2 = elements [index++];
  67648. y2 = elements [index++];
  67649. x3 = elements [index++];
  67650. y3 = elements [index++];
  67651. }
  67652. else if (type == closeSubPathMarker)
  67653. {
  67654. elementType = closePath;
  67655. }
  67656. return true;
  67657. }
  67658. return false;
  67659. }
  67660. END_JUCE_NAMESPACE
  67661. /********* End of inlined file: juce_Path.cpp *********/
  67662. /********* Start of inlined file: juce_PathIterator.cpp *********/
  67663. BEGIN_JUCE_NAMESPACE
  67664. #if JUCE_MSVC
  67665. #pragma optimize ("t", on)
  67666. #endif
  67667. PathFlatteningIterator::PathFlatteningIterator (const Path& path_,
  67668. const AffineTransform& transform_,
  67669. float tolerence_) throw()
  67670. : x2 (0),
  67671. y2 (0),
  67672. closesSubPath (false),
  67673. subPathIndex (-1),
  67674. path (path_),
  67675. transform (transform_),
  67676. points (path_.elements),
  67677. tolerence (tolerence_ * tolerence_),
  67678. subPathCloseX (0),
  67679. subPathCloseY (0),
  67680. index (0),
  67681. stackSize (32)
  67682. {
  67683. stackBase = (float*) juce_malloc (stackSize * sizeof (float));
  67684. isIdentityTransform = transform.isIdentity();
  67685. stackPos = stackBase;
  67686. }
  67687. PathFlatteningIterator::~PathFlatteningIterator() throw()
  67688. {
  67689. juce_free (stackBase);
  67690. }
  67691. bool PathFlatteningIterator::next() throw()
  67692. {
  67693. x1 = x2;
  67694. y1 = y2;
  67695. float x3 = 0;
  67696. float y3 = 0;
  67697. float x4 = 0;
  67698. float y4 = 0;
  67699. float type;
  67700. for (;;)
  67701. {
  67702. if (stackPos == stackBase)
  67703. {
  67704. if (index >= path.numElements)
  67705. {
  67706. return false;
  67707. }
  67708. else
  67709. {
  67710. type = points [index++];
  67711. if (type != Path::closeSubPathMarker)
  67712. {
  67713. x2 = points [index++];
  67714. y2 = points [index++];
  67715. if (! isIdentityTransform)
  67716. transform.transformPoint (x2, y2);
  67717. if (type == Path::quadMarker)
  67718. {
  67719. x3 = points [index++];
  67720. y3 = points [index++];
  67721. if (! isIdentityTransform)
  67722. transform.transformPoint (x3, y3);
  67723. }
  67724. else if (type == Path::cubicMarker)
  67725. {
  67726. x3 = points [index++];
  67727. y3 = points [index++];
  67728. x4 = points [index++];
  67729. y4 = points [index++];
  67730. if (! isIdentityTransform)
  67731. {
  67732. transform.transformPoint (x3, y3);
  67733. transform.transformPoint (x4, y4);
  67734. }
  67735. }
  67736. }
  67737. }
  67738. }
  67739. else
  67740. {
  67741. type = *--stackPos;
  67742. if (type != Path::closeSubPathMarker)
  67743. {
  67744. x2 = *--stackPos;
  67745. y2 = *--stackPos;
  67746. if (type == Path::quadMarker)
  67747. {
  67748. x3 = *--stackPos;
  67749. y3 = *--stackPos;
  67750. }
  67751. else if (type == Path::cubicMarker)
  67752. {
  67753. x3 = *--stackPos;
  67754. y3 = *--stackPos;
  67755. x4 = *--stackPos;
  67756. y4 = *--stackPos;
  67757. }
  67758. }
  67759. }
  67760. if (type == Path::lineMarker)
  67761. {
  67762. ++subPathIndex;
  67763. closesSubPath = (stackPos == stackBase)
  67764. && (index < path.numElements)
  67765. && (points [index] == Path::closeSubPathMarker)
  67766. && x2 == subPathCloseX
  67767. && y2 == subPathCloseY;
  67768. return true;
  67769. }
  67770. else if (type == Path::quadMarker)
  67771. {
  67772. const int offset = (int) (stackPos - stackBase);
  67773. if (offset >= stackSize - 10)
  67774. {
  67775. stackSize <<= 1;
  67776. stackBase = (float*) juce_realloc (stackBase, stackSize * sizeof (float));
  67777. stackPos = stackBase + offset;
  67778. }
  67779. const float dx1 = x1 - x2;
  67780. const float dy1 = y1 - y2;
  67781. const float dx2 = x2 - x3;
  67782. const float dy2 = y2 - y3;
  67783. const float m1x = (x1 + x2) * 0.5f;
  67784. const float m1y = (y1 + y2) * 0.5f;
  67785. const float m2x = (x2 + x3) * 0.5f;
  67786. const float m2y = (y2 + y3) * 0.5f;
  67787. const float m3x = (m1x + m2x) * 0.5f;
  67788. const float m3y = (m1y + m2y) * 0.5f;
  67789. if (dx1*dx1 + dy1*dy1 + dx2*dx2 + dy2*dy2 > tolerence)
  67790. {
  67791. *stackPos++ = y3;
  67792. *stackPos++ = x3;
  67793. *stackPos++ = m2y;
  67794. *stackPos++ = m2x;
  67795. *stackPos++ = Path::quadMarker;
  67796. *stackPos++ = m3y;
  67797. *stackPos++ = m3x;
  67798. *stackPos++ = m1y;
  67799. *stackPos++ = m1x;
  67800. *stackPos++ = Path::quadMarker;
  67801. }
  67802. else
  67803. {
  67804. *stackPos++ = y3;
  67805. *stackPos++ = x3;
  67806. *stackPos++ = Path::lineMarker;
  67807. *stackPos++ = m3y;
  67808. *stackPos++ = m3x;
  67809. *stackPos++ = Path::lineMarker;
  67810. }
  67811. jassert (stackPos < stackBase + stackSize);
  67812. }
  67813. else if (type == Path::cubicMarker)
  67814. {
  67815. const int offset = (int) (stackPos - stackBase);
  67816. if (offset >= stackSize - 16)
  67817. {
  67818. stackSize <<= 1;
  67819. stackBase = (float*) juce_realloc (stackBase, stackSize * sizeof (float));
  67820. stackPos = stackBase + offset;
  67821. }
  67822. const float dx1 = x1 - x2;
  67823. const float dy1 = y1 - y2;
  67824. const float dx2 = x2 - x3;
  67825. const float dy2 = y2 - y3;
  67826. const float dx3 = x3 - x4;
  67827. const float dy3 = y3 - y4;
  67828. const float m1x = (x1 + x2) * 0.5f;
  67829. const float m1y = (y1 + y2) * 0.5f;
  67830. const float m2x = (x3 + x2) * 0.5f;
  67831. const float m2y = (y3 + y2) * 0.5f;
  67832. const float m3x = (x3 + x4) * 0.5f;
  67833. const float m3y = (y3 + y4) * 0.5f;
  67834. const float m4x = (m1x + m2x) * 0.5f;
  67835. const float m4y = (m1y + m2y) * 0.5f;
  67836. const float m5x = (m3x + m2x) * 0.5f;
  67837. const float m5y = (m3y + m2y) * 0.5f;
  67838. if (dx1*dx1 + dy1*dy1 + dx2*dx2
  67839. + dy2*dy2 + dx3*dx3 + dy3*dy3 > tolerence)
  67840. {
  67841. *stackPos++ = y4;
  67842. *stackPos++ = x4;
  67843. *stackPos++ = m3y;
  67844. *stackPos++ = m3x;
  67845. *stackPos++ = m5y;
  67846. *stackPos++ = m5x;
  67847. *stackPos++ = Path::cubicMarker;
  67848. *stackPos++ = (m4y + m5y) * 0.5f;
  67849. *stackPos++ = (m4x + m5x) * 0.5f;
  67850. *stackPos++ = m4y;
  67851. *stackPos++ = m4x;
  67852. *stackPos++ = m1y;
  67853. *stackPos++ = m1x;
  67854. *stackPos++ = Path::cubicMarker;
  67855. }
  67856. else
  67857. {
  67858. *stackPos++ = y4;
  67859. *stackPos++ = x4;
  67860. *stackPos++ = Path::lineMarker;
  67861. *stackPos++ = m5y;
  67862. *stackPos++ = m5x;
  67863. *stackPos++ = Path::lineMarker;
  67864. *stackPos++ = m4y;
  67865. *stackPos++ = m4x;
  67866. *stackPos++ = Path::lineMarker;
  67867. }
  67868. }
  67869. else if (type == Path::closeSubPathMarker)
  67870. {
  67871. if (x2 != subPathCloseX || y2 != subPathCloseY)
  67872. {
  67873. x1 = x2;
  67874. y1 = y2;
  67875. x2 = subPathCloseX;
  67876. y2 = subPathCloseY;
  67877. closesSubPath = true;
  67878. return true;
  67879. }
  67880. }
  67881. else
  67882. {
  67883. subPathIndex = -1;
  67884. subPathCloseX = x1 = x2;
  67885. subPathCloseY = y1 = y2;
  67886. }
  67887. }
  67888. }
  67889. END_JUCE_NAMESPACE
  67890. /********* End of inlined file: juce_PathIterator.cpp *********/
  67891. /********* Start of inlined file: juce_PathStrokeType.cpp *********/
  67892. BEGIN_JUCE_NAMESPACE
  67893. PathStrokeType::PathStrokeType (const float strokeThickness,
  67894. const JointStyle jointStyle_,
  67895. const EndCapStyle endStyle_) throw()
  67896. : thickness (strokeThickness),
  67897. jointStyle (jointStyle_),
  67898. endStyle (endStyle_)
  67899. {
  67900. }
  67901. PathStrokeType::PathStrokeType (const PathStrokeType& other) throw()
  67902. : thickness (other.thickness),
  67903. jointStyle (other.jointStyle),
  67904. endStyle (other.endStyle)
  67905. {
  67906. }
  67907. const PathStrokeType& PathStrokeType::operator= (const PathStrokeType& other) throw()
  67908. {
  67909. thickness = other.thickness;
  67910. jointStyle = other.jointStyle;
  67911. endStyle = other.endStyle;
  67912. return *this;
  67913. }
  67914. PathStrokeType::~PathStrokeType() throw()
  67915. {
  67916. }
  67917. bool PathStrokeType::operator== (const PathStrokeType& other) const throw()
  67918. {
  67919. return thickness == other.thickness
  67920. && jointStyle == other.jointStyle
  67921. && endStyle == other.endStyle;
  67922. }
  67923. bool PathStrokeType::operator!= (const PathStrokeType& other) const throw()
  67924. {
  67925. return ! operator== (other);
  67926. }
  67927. static bool lineIntersection (const float x1, const float y1,
  67928. const float x2, const float y2,
  67929. const float x3, const float y3,
  67930. const float x4, const float y4,
  67931. float& intersectionX,
  67932. float& intersectionY,
  67933. float& distanceBeyondLine1EndSquared) throw()
  67934. {
  67935. if (x2 != x3 || y2 != y3)
  67936. {
  67937. const float dx1 = x2 - x1;
  67938. const float dy1 = y2 - y1;
  67939. const float dx2 = x4 - x3;
  67940. const float dy2 = y4 - y3;
  67941. const float divisor = dx1 * dy2 - dx2 * dy1;
  67942. if (divisor == 0)
  67943. {
  67944. if (! ((dx1 == 0 && dy1 == 0) || (dx2 == 0 && dy2 == 0)))
  67945. {
  67946. if (dy1 == 0 && dy2 != 0)
  67947. {
  67948. const float along = (y1 - y3) / dy2;
  67949. intersectionX = x3 + along * dx2;
  67950. intersectionY = y1;
  67951. distanceBeyondLine1EndSquared = intersectionX - x2;
  67952. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  67953. if ((x2 > x1) == (intersectionX < x2))
  67954. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  67955. return along >= 0 && along <= 1.0f;
  67956. }
  67957. else if (dy2 == 0 && dy1 != 0)
  67958. {
  67959. const float along = (y3 - y1) / dy1;
  67960. intersectionX = x1 + along * dx1;
  67961. intersectionY = y3;
  67962. distanceBeyondLine1EndSquared = (along - 1.0f) * dx1;
  67963. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  67964. if (along < 1.0f)
  67965. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  67966. return along >= 0 && along <= 1.0f;
  67967. }
  67968. else if (dx1 == 0 && dx2 != 0)
  67969. {
  67970. const float along = (x1 - x3) / dx2;
  67971. intersectionX = x1;
  67972. intersectionY = y3 + along * dy2;
  67973. distanceBeyondLine1EndSquared = intersectionY - y2;
  67974. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  67975. if ((y2 > y1) == (intersectionY < y2))
  67976. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  67977. return along >= 0 && along <= 1.0f;
  67978. }
  67979. else if (dx2 == 0 && dx1 != 0)
  67980. {
  67981. const float along = (x3 - x1) / dx1;
  67982. intersectionX = x3;
  67983. intersectionY = y1 + along * dy1;
  67984. distanceBeyondLine1EndSquared = (along - 1.0f) * dy1;
  67985. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  67986. if (along < 1.0f)
  67987. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  67988. return along >= 0 && along <= 1.0f;
  67989. }
  67990. }
  67991. intersectionX = 0.5f * (x2 + x3);
  67992. intersectionY = 0.5f * (y2 + y3);
  67993. distanceBeyondLine1EndSquared = 0.0f;
  67994. return false;
  67995. }
  67996. else
  67997. {
  67998. const float along1 = ((y1 - y3) * dx2 - (x1 - x3) * dy2) / divisor;
  67999. intersectionX = x1 + along1 * dx1;
  68000. intersectionY = y1 + along1 * dy1;
  68001. if (along1 >= 0 && along1 <= 1.0f)
  68002. {
  68003. const float along2 = ((y1 - y3) * dx1 - (x1 - x3) * dy1);
  68004. if (along2 >= 0 && along2 <= divisor)
  68005. {
  68006. distanceBeyondLine1EndSquared = 0.0f;
  68007. return true;
  68008. }
  68009. }
  68010. distanceBeyondLine1EndSquared = along1 - 1.0f;
  68011. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  68012. distanceBeyondLine1EndSquared *= (dx1 * dx1 + dy1 * dy1);
  68013. if (along1 < 1.0f)
  68014. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  68015. return false;
  68016. }
  68017. }
  68018. intersectionX = x2;
  68019. intersectionY = y2;
  68020. distanceBeyondLine1EndSquared = 0.0f;
  68021. return true;
  68022. }
  68023. // part of stroke drawing stuff
  68024. static void addEdgeAndJoint (Path& destPath,
  68025. const PathStrokeType::JointStyle style,
  68026. const float maxMiterExtensionSquared, const float width,
  68027. const float x1, const float y1,
  68028. const float x2, const float y2,
  68029. const float x3, const float y3,
  68030. const float x4, const float y4,
  68031. const float midX, const float midY) throw()
  68032. {
  68033. if (style == PathStrokeType::beveled
  68034. || (x3 == x4 && y3 == y4)
  68035. || (x1 == x2 && y1 == y2))
  68036. {
  68037. destPath.lineTo (x2, y2);
  68038. destPath.lineTo (x3, y3);
  68039. }
  68040. else
  68041. {
  68042. float jx, jy, distanceBeyondLine1EndSquared;
  68043. // if they intersect, use this point..
  68044. if (lineIntersection (x1, y1, x2, y2,
  68045. x3, y3, x4, y4,
  68046. jx, jy, distanceBeyondLine1EndSquared))
  68047. {
  68048. destPath.lineTo (jx, jy);
  68049. }
  68050. else
  68051. {
  68052. if (style == PathStrokeType::mitered)
  68053. {
  68054. if (distanceBeyondLine1EndSquared < maxMiterExtensionSquared
  68055. && distanceBeyondLine1EndSquared > 0.0f)
  68056. {
  68057. destPath.lineTo (jx, jy);
  68058. }
  68059. else
  68060. {
  68061. // the end sticks out too far, so just use a blunt joint
  68062. destPath.lineTo (x2, y2);
  68063. destPath.lineTo (x3, y3);
  68064. }
  68065. }
  68066. else
  68067. {
  68068. // curved joints
  68069. float angle = atan2f (x2 - midX, y2 - midY);
  68070. float angle2 = atan2f (x3 - midX, y3 - midY);
  68071. while (angle < angle2 - 0.01f)
  68072. angle2 -= float_Pi * 2.0f;
  68073. destPath.lineTo (x2, y2);
  68074. while (angle > angle2)
  68075. {
  68076. destPath.lineTo (midX + width * sinf (angle),
  68077. midY + width * cosf (angle));
  68078. angle -= 0.1f;
  68079. }
  68080. destPath.lineTo (x3, y3);
  68081. }
  68082. }
  68083. }
  68084. }
  68085. static inline void addLineEnd (Path& destPath,
  68086. const PathStrokeType::EndCapStyle style,
  68087. const float x1, const float y1,
  68088. const float x2, const float y2,
  68089. const float width) throw()
  68090. {
  68091. if (style == PathStrokeType::butt)
  68092. {
  68093. destPath.lineTo (x2, y2);
  68094. }
  68095. else
  68096. {
  68097. float offx1, offy1, offx2, offy2;
  68098. float dx = x2 - x1;
  68099. float dy = y2 - y1;
  68100. const float len = juce_hypotf (dx, dy);
  68101. if (len == 0)
  68102. {
  68103. offx1 = offx2 = x1;
  68104. offy1 = offy2 = y1;
  68105. }
  68106. else
  68107. {
  68108. const float offset = width / len;
  68109. dx *= offset;
  68110. dy *= offset;
  68111. offx1 = x1 + dy;
  68112. offy1 = y1 - dx;
  68113. offx2 = x2 + dy;
  68114. offy2 = y2 - dx;
  68115. }
  68116. if (style == PathStrokeType::square)
  68117. {
  68118. // sqaure ends
  68119. destPath.lineTo (offx1, offy1);
  68120. destPath.lineTo (offx2, offy2);
  68121. destPath.lineTo (x2, y2);
  68122. }
  68123. else
  68124. {
  68125. // rounded ends
  68126. const float midx = (offx1 + offx2) * 0.5f;
  68127. const float midy = (offy1 + offy2) * 0.5f;
  68128. destPath.cubicTo (x1 + (offx1 - x1) * 0.55f, y1 + (offy1 - y1) * 0.55f,
  68129. offx1 + (midx - offx1) * 0.45f, offy1 + (midy - offy1) * 0.45f,
  68130. midx, midy);
  68131. destPath.cubicTo (midx + (offx2 - midx) * 0.55f, midy + (offy2 - midy) * 0.55f,
  68132. offx2 + (x2 - offx2) * 0.45f, offy2 + (y2 - offy2) * 0.45f,
  68133. x2, y2);
  68134. }
  68135. }
  68136. }
  68137. struct LineSection
  68138. {
  68139. LineSection() throw() {}
  68140. LineSection (int) throw() {}
  68141. float x1, y1, x2, y2; // original line
  68142. float lx1, ly1, lx2, ly2; // the left-hand stroke
  68143. float rx1, ry1, rx2, ry2; // the right-hand stroke
  68144. };
  68145. static void addSubPath (Path& destPath, const Array <LineSection>& subPath,
  68146. const bool isClosed,
  68147. const float width, const float maxMiterExtensionSquared,
  68148. const PathStrokeType::JointStyle jointStyle, const PathStrokeType::EndCapStyle endStyle) throw()
  68149. {
  68150. jassert (subPath.size() > 0);
  68151. const LineSection& firstLine = subPath.getReference (0);
  68152. float lastX1 = firstLine.lx1;
  68153. float lastY1 = firstLine.ly1;
  68154. float lastX2 = firstLine.lx2;
  68155. float lastY2 = firstLine.ly2;
  68156. if (isClosed)
  68157. {
  68158. destPath.startNewSubPath (lastX1, lastY1);
  68159. }
  68160. else
  68161. {
  68162. destPath.startNewSubPath (firstLine.rx2, firstLine.ry2);
  68163. addLineEnd (destPath, endStyle,
  68164. firstLine.rx2, firstLine.ry2,
  68165. lastX1, lastY1,
  68166. width);
  68167. }
  68168. int i;
  68169. for (i = 1; i < subPath.size(); ++i)
  68170. {
  68171. const LineSection& l = subPath.getReference (i);
  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. lastX1 = l.lx1;
  68178. lastY1 = l.ly1;
  68179. lastX2 = l.lx2;
  68180. lastY2 = l.ly2;
  68181. }
  68182. const LineSection& lastLine = subPath.getReference (subPath.size() - 1);
  68183. if (isClosed)
  68184. {
  68185. const LineSection& l = subPath.getReference (0);
  68186. addEdgeAndJoint (destPath, jointStyle,
  68187. maxMiterExtensionSquared, width,
  68188. lastX1, lastY1, lastX2, lastY2,
  68189. l.lx1, l.ly1, l.lx2, l.ly2,
  68190. l.x1, l.y1);
  68191. destPath.closeSubPath();
  68192. destPath.startNewSubPath (lastLine.rx1, lastLine.ry1);
  68193. }
  68194. else
  68195. {
  68196. destPath.lineTo (lastX2, lastY2);
  68197. addLineEnd (destPath, endStyle,
  68198. lastX2, lastY2,
  68199. lastLine.rx1, lastLine.ry1,
  68200. width);
  68201. }
  68202. lastX1 = lastLine.rx1;
  68203. lastY1 = lastLine.ry1;
  68204. lastX2 = lastLine.rx2;
  68205. lastY2 = lastLine.ry2;
  68206. for (i = subPath.size() - 1; --i >= 0;)
  68207. {
  68208. const LineSection& l = subPath.getReference (i);
  68209. addEdgeAndJoint (destPath, jointStyle,
  68210. maxMiterExtensionSquared, width,
  68211. lastX1, lastY1, lastX2, lastY2,
  68212. l.rx1, l.ry1, l.rx2, l.ry2,
  68213. l.x2, l.y2);
  68214. lastX1 = l.rx1;
  68215. lastY1 = l.ry1;
  68216. lastX2 = l.rx2;
  68217. lastY2 = l.ry2;
  68218. }
  68219. if (isClosed)
  68220. {
  68221. addEdgeAndJoint (destPath, jointStyle,
  68222. maxMiterExtensionSquared, width,
  68223. lastX1, lastY1, lastX2, lastY2,
  68224. lastLine.rx1, lastLine.ry1, lastLine.rx2, lastLine.ry2,
  68225. lastLine.x2, lastLine.y2);
  68226. }
  68227. else
  68228. {
  68229. // do the last line
  68230. destPath.lineTo (lastX2, lastY2);
  68231. }
  68232. destPath.closeSubPath();
  68233. }
  68234. void PathStrokeType::createStrokedPath (Path& destPath,
  68235. const Path& source,
  68236. const AffineTransform& transform,
  68237. const float extraAccuracy) const throw()
  68238. {
  68239. if (thickness <= 0)
  68240. {
  68241. destPath.clear();
  68242. return;
  68243. }
  68244. const Path* sourcePath = &source;
  68245. Path temp;
  68246. if (sourcePath == &destPath)
  68247. {
  68248. destPath.swapWithPath (temp);
  68249. sourcePath = &temp;
  68250. }
  68251. else
  68252. {
  68253. destPath.clear();
  68254. }
  68255. destPath.setUsingNonZeroWinding (true);
  68256. const float maxMiterExtensionSquared = 9.0f * thickness * thickness;
  68257. const float width = 0.5f * thickness;
  68258. // Iterate the path, creating a list of the
  68259. // left/right-hand lines along either side of it...
  68260. PathFlatteningIterator it (*sourcePath, transform, 9.0f / extraAccuracy);
  68261. Array <LineSection> subPath;
  68262. LineSection l;
  68263. l.x1 = 0;
  68264. l.y1 = 0;
  68265. const float minSegmentLength = 2.0f / (extraAccuracy * extraAccuracy);
  68266. while (it.next())
  68267. {
  68268. if (it.subPathIndex == 0)
  68269. {
  68270. if (subPath.size() > 0)
  68271. {
  68272. addSubPath (destPath, subPath, false, width, maxMiterExtensionSquared, jointStyle, endStyle);
  68273. subPath.clearQuick();
  68274. }
  68275. l.x1 = it.x1;
  68276. l.y1 = it.y1;
  68277. }
  68278. l.x2 = it.x2;
  68279. l.y2 = it.y2;
  68280. float dx = l.x2 - l.x1;
  68281. float dy = l.y2 - l.y1;
  68282. const float hypotSquared = dx*dx + dy*dy;
  68283. if (it.closesSubPath || hypotSquared > minSegmentLength || it.isLastInSubpath())
  68284. {
  68285. const float len = sqrtf (hypotSquared);
  68286. if (len == 0)
  68287. {
  68288. l.rx1 = l.rx2 = l.lx1 = l.lx2 = l.x1;
  68289. l.ry1 = l.ry2 = l.ly1 = l.ly2 = l.y1;
  68290. }
  68291. else
  68292. {
  68293. const float offset = width / len;
  68294. dx *= offset;
  68295. dy *= offset;
  68296. l.rx2 = l.x1 - dy;
  68297. l.ry2 = l.y1 + dx;
  68298. l.lx1 = l.x1 + dy;
  68299. l.ly1 = l.y1 - dx;
  68300. l.lx2 = l.x2 + dy;
  68301. l.ly2 = l.y2 - dx;
  68302. l.rx1 = l.x2 - dy;
  68303. l.ry1 = l.y2 + dx;
  68304. }
  68305. subPath.add (l);
  68306. if (it.closesSubPath)
  68307. {
  68308. addSubPath (destPath, subPath, true, width, maxMiterExtensionSquared, jointStyle, endStyle);
  68309. subPath.clearQuick();
  68310. }
  68311. else
  68312. {
  68313. l.x1 = it.x2;
  68314. l.y1 = it.y2;
  68315. }
  68316. }
  68317. }
  68318. if (subPath.size() > 0)
  68319. addSubPath (destPath, subPath, false, width, maxMiterExtensionSquared, jointStyle, endStyle);
  68320. }
  68321. void PathStrokeType::createDashedStroke (Path& destPath,
  68322. const Path& sourcePath,
  68323. const float* dashLengths,
  68324. int numDashLengths,
  68325. const AffineTransform& transform,
  68326. const float extraAccuracy) const throw()
  68327. {
  68328. if (thickness <= 0)
  68329. return;
  68330. // this should really be an even number..
  68331. jassert ((numDashLengths & 1) == 0);
  68332. Path newDestPath;
  68333. PathFlatteningIterator it (sourcePath, transform, 9.0f / extraAccuracy);
  68334. bool first = true;
  68335. int dashNum = 0;
  68336. float pos = 0.0f, lineLen = 0.0f, lineEndPos = 0.0f;
  68337. float dx = 0.0f, dy = 0.0f;
  68338. for (;;)
  68339. {
  68340. const bool isSolid = ((dashNum & 1) == 0);
  68341. const float dashLen = dashLengths [dashNum++ % numDashLengths];
  68342. jassert (dashLen > 0); // must be a positive increment!
  68343. if (dashLen <= 0)
  68344. break;
  68345. pos += dashLen;
  68346. while (pos > lineEndPos)
  68347. {
  68348. if (! it.next())
  68349. {
  68350. if (isSolid && ! first)
  68351. newDestPath.lineTo (it.x2, it.y2);
  68352. createStrokedPath (destPath, newDestPath, AffineTransform::identity, extraAccuracy);
  68353. return;
  68354. }
  68355. if (isSolid && ! first)
  68356. {
  68357. newDestPath.lineTo (it.x1, it.y1);
  68358. }
  68359. else
  68360. {
  68361. newDestPath.startNewSubPath (it.x1, it.y1);
  68362. first = false;
  68363. }
  68364. dx = it.x2 - it.x1;
  68365. dy = it.y2 - it.y1;
  68366. lineLen = juce_hypotf (dx, dy);
  68367. lineEndPos += lineLen;
  68368. }
  68369. const float alpha = (pos - (lineEndPos - lineLen)) / lineLen;
  68370. if (isSolid)
  68371. newDestPath.lineTo (it.x1 + dx * alpha,
  68372. it.y1 + dy * alpha);
  68373. else
  68374. newDestPath.startNewSubPath (it.x1 + dx * alpha,
  68375. it.y1 + dy * alpha);
  68376. }
  68377. }
  68378. END_JUCE_NAMESPACE
  68379. /********* End of inlined file: juce_PathStrokeType.cpp *********/
  68380. /********* Start of inlined file: juce_Point.cpp *********/
  68381. BEGIN_JUCE_NAMESPACE
  68382. Point::Point() throw()
  68383. : x (0.0f),
  68384. y (0.0f)
  68385. {
  68386. }
  68387. Point::Point (const Point& other) throw()
  68388. : x (other.x),
  68389. y (other.y)
  68390. {
  68391. }
  68392. const Point& Point::operator= (const Point& other) throw()
  68393. {
  68394. x = other.x;
  68395. y = other.y;
  68396. return *this;
  68397. }
  68398. Point::Point (const float x_,
  68399. const float y_) throw()
  68400. : x (x_),
  68401. y (y_)
  68402. {
  68403. }
  68404. Point::~Point() throw()
  68405. {
  68406. }
  68407. void Point::setXY (const float x_,
  68408. const float y_) throw()
  68409. {
  68410. x = x_;
  68411. y = y_;
  68412. }
  68413. void Point::applyTransform (const AffineTransform& transform) throw()
  68414. {
  68415. transform.transformPoint (x, y);
  68416. }
  68417. END_JUCE_NAMESPACE
  68418. /********* End of inlined file: juce_Point.cpp *********/
  68419. /********* Start of inlined file: juce_PositionedRectangle.cpp *********/
  68420. BEGIN_JUCE_NAMESPACE
  68421. PositionedRectangle::PositionedRectangle() throw()
  68422. : x (0.0),
  68423. y (0.0),
  68424. w (0.0),
  68425. h (0.0),
  68426. xMode (anchorAtLeftOrTop | absoluteFromParentTopLeft),
  68427. yMode (anchorAtLeftOrTop | absoluteFromParentTopLeft),
  68428. wMode (absoluteSize),
  68429. hMode (absoluteSize)
  68430. {
  68431. }
  68432. PositionedRectangle::PositionedRectangle (const PositionedRectangle& other) throw()
  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. }
  68443. const PositionedRectangle& PositionedRectangle::operator= (const PositionedRectangle& other) throw()
  68444. {
  68445. if (this != &other)
  68446. {
  68447. x = other.x;
  68448. y = other.y;
  68449. w = other.w;
  68450. h = other.h;
  68451. xMode = other.xMode;
  68452. yMode = other.yMode;
  68453. wMode = other.wMode;
  68454. hMode = other.hMode;
  68455. }
  68456. return *this;
  68457. }
  68458. PositionedRectangle::~PositionedRectangle() throw()
  68459. {
  68460. }
  68461. const bool PositionedRectangle::operator== (const PositionedRectangle& other) const throw()
  68462. {
  68463. return x == other.x
  68464. && y == other.y
  68465. && w == other.w
  68466. && h == other.h
  68467. && xMode == other.xMode
  68468. && yMode == other.yMode
  68469. && wMode == other.wMode
  68470. && hMode == other.hMode;
  68471. }
  68472. const bool PositionedRectangle::operator!= (const PositionedRectangle& other) const throw()
  68473. {
  68474. return ! operator== (other);
  68475. }
  68476. PositionedRectangle::PositionedRectangle (const String& stringVersion) throw()
  68477. {
  68478. StringArray tokens;
  68479. tokens.addTokens (stringVersion, false);
  68480. decodePosString (tokens [0], xMode, x);
  68481. decodePosString (tokens [1], yMode, y);
  68482. decodeSizeString (tokens [2], wMode, w);
  68483. decodeSizeString (tokens [3], hMode, h);
  68484. }
  68485. const String PositionedRectangle::toString() const throw()
  68486. {
  68487. String s;
  68488. s.preallocateStorage (12);
  68489. addPosDescription (s, xMode, x);
  68490. s << T(' ');
  68491. addPosDescription (s, yMode, y);
  68492. s << T(' ');
  68493. addSizeDescription (s, wMode, w);
  68494. s << T(' ');
  68495. addSizeDescription (s, hMode, h);
  68496. return s;
  68497. }
  68498. const Rectangle PositionedRectangle::getRectangle (const Rectangle& target) const throw()
  68499. {
  68500. jassert (! target.isEmpty());
  68501. double x_, y_, w_, h_;
  68502. applyPosAndSize (x_, w_, x, w, xMode, wMode, target.getX(), target.getWidth());
  68503. applyPosAndSize (y_, h_, y, h, yMode, hMode, target.getY(), target.getHeight());
  68504. return Rectangle (roundDoubleToInt (x_), roundDoubleToInt (y_),
  68505. roundDoubleToInt (w_), roundDoubleToInt (h_));
  68506. }
  68507. void PositionedRectangle::getRectangleDouble (const Rectangle& target,
  68508. double& x_, double& y_,
  68509. double& w_, double& h_) const throw()
  68510. {
  68511. jassert (! target.isEmpty());
  68512. applyPosAndSize (x_, w_, x, w, xMode, wMode, target.getX(), target.getWidth());
  68513. applyPosAndSize (y_, h_, y, h, yMode, hMode, target.getY(), target.getHeight());
  68514. }
  68515. void PositionedRectangle::applyToComponent (Component& comp) const throw()
  68516. {
  68517. comp.setBounds (getRectangle (Rectangle (0, 0, comp.getParentWidth(), comp.getParentHeight())));
  68518. }
  68519. void PositionedRectangle::updateFrom (const Rectangle& rectangle,
  68520. const Rectangle& target) throw()
  68521. {
  68522. updatePosAndSize (x, w, rectangle.getX(), rectangle.getWidth(), xMode, wMode, target.getX(), target.getWidth());
  68523. updatePosAndSize (y, h, rectangle.getY(), rectangle.getHeight(), yMode, hMode, target.getY(), target.getHeight());
  68524. }
  68525. void PositionedRectangle::updateFromDouble (const double newX, const double newY,
  68526. const double newW, const double newH,
  68527. const Rectangle& target) throw()
  68528. {
  68529. updatePosAndSize (x, w, newX, newW, xMode, wMode, target.getX(), target.getWidth());
  68530. updatePosAndSize (y, h, newY, newH, yMode, hMode, target.getY(), target.getHeight());
  68531. }
  68532. void PositionedRectangle::updateFromComponent (const Component& comp) throw()
  68533. {
  68534. if (comp.getParentComponent() == 0 && ! comp.isOnDesktop())
  68535. updateFrom (comp.getBounds(), Rectangle());
  68536. else
  68537. updateFrom (comp.getBounds(), Rectangle (0, 0, comp.getParentWidth(), comp.getParentHeight()));
  68538. }
  68539. PositionedRectangle::AnchorPoint PositionedRectangle::getAnchorPointX() const throw()
  68540. {
  68541. return (AnchorPoint) (xMode & (anchorAtLeftOrTop | anchorAtRightOrBottom | anchorAtCentre));
  68542. }
  68543. PositionedRectangle::PositionMode PositionedRectangle::getPositionModeX() const throw()
  68544. {
  68545. return (PositionMode) (xMode & (absoluteFromParentTopLeft
  68546. | absoluteFromParentBottomRight
  68547. | absoluteFromParentCentre
  68548. | proportionOfParentSize));
  68549. }
  68550. PositionedRectangle::AnchorPoint PositionedRectangle::getAnchorPointY() const throw()
  68551. {
  68552. return (AnchorPoint) (yMode & (anchorAtLeftOrTop | anchorAtRightOrBottom | anchorAtCentre));
  68553. }
  68554. PositionedRectangle::PositionMode PositionedRectangle::getPositionModeY() const throw()
  68555. {
  68556. return (PositionMode) (yMode & (absoluteFromParentTopLeft
  68557. | absoluteFromParentBottomRight
  68558. | absoluteFromParentCentre
  68559. | proportionOfParentSize));
  68560. }
  68561. PositionedRectangle::SizeMode PositionedRectangle::getWidthMode() const throw()
  68562. {
  68563. return (SizeMode) wMode;
  68564. }
  68565. PositionedRectangle::SizeMode PositionedRectangle::getHeightMode() const throw()
  68566. {
  68567. return (SizeMode) hMode;
  68568. }
  68569. void PositionedRectangle::setModes (const AnchorPoint xAnchor,
  68570. const PositionMode xMode_,
  68571. const AnchorPoint yAnchor,
  68572. const PositionMode yMode_,
  68573. const SizeMode widthMode,
  68574. const SizeMode heightMode,
  68575. const Rectangle& target) throw()
  68576. {
  68577. if (xMode != (xAnchor | xMode_) || wMode != widthMode)
  68578. {
  68579. double tx, tw;
  68580. applyPosAndSize (tx, tw, x, w, xMode, wMode, target.getX(), target.getWidth());
  68581. xMode = (uint8) (xAnchor | xMode_);
  68582. wMode = (uint8) widthMode;
  68583. updatePosAndSize (x, w, tx, tw, xMode, wMode, target.getX(), target.getWidth());
  68584. }
  68585. if (yMode != (yAnchor | yMode_) || hMode != heightMode)
  68586. {
  68587. double ty, th;
  68588. applyPosAndSize (ty, th, y, h, yMode, hMode, target.getY(), target.getHeight());
  68589. yMode = (uint8) (yAnchor | yMode_);
  68590. hMode = (uint8) heightMode;
  68591. updatePosAndSize (y, h, ty, th, yMode, hMode, target.getY(), target.getHeight());
  68592. }
  68593. }
  68594. bool PositionedRectangle::isPositionAbsolute() const throw()
  68595. {
  68596. return xMode == absoluteFromParentTopLeft
  68597. && yMode == absoluteFromParentTopLeft
  68598. && wMode == absoluteSize
  68599. && hMode == absoluteSize;
  68600. }
  68601. void PositionedRectangle::addPosDescription (String& s, const uint8 mode, const double value) const throw()
  68602. {
  68603. if ((mode & proportionOfParentSize) != 0)
  68604. {
  68605. s << (roundDoubleToInt (value * 100000.0) / 1000.0) << T('%');
  68606. }
  68607. else
  68608. {
  68609. s << (roundDoubleToInt (value * 100.0) / 100.0);
  68610. if ((mode & absoluteFromParentBottomRight) != 0)
  68611. s << T('R');
  68612. else if ((mode & absoluteFromParentCentre) != 0)
  68613. s << T('C');
  68614. }
  68615. if ((mode & anchorAtRightOrBottom) != 0)
  68616. s << T('r');
  68617. else if ((mode & anchorAtCentre) != 0)
  68618. s << T('c');
  68619. }
  68620. void PositionedRectangle::addSizeDescription (String& s, const uint8 mode, const double value) const throw()
  68621. {
  68622. if (mode == proportionalSize)
  68623. s << (roundDoubleToInt (value * 100000.0) / 1000.0) << T('%');
  68624. else if (mode == parentSizeMinusAbsolute)
  68625. s << (roundDoubleToInt (value * 100.0) / 100.0) << T('M');
  68626. else
  68627. s << (roundDoubleToInt (value * 100.0) / 100.0);
  68628. }
  68629. void PositionedRectangle::decodePosString (const String& s, uint8& mode, double& value) throw()
  68630. {
  68631. if (s.containsChar (T('r')))
  68632. mode = anchorAtRightOrBottom;
  68633. else if (s.containsChar (T('c')))
  68634. mode = anchorAtCentre;
  68635. else
  68636. mode = anchorAtLeftOrTop;
  68637. if (s.containsChar (T('%')))
  68638. {
  68639. mode |= proportionOfParentSize;
  68640. value = s.removeCharacters (T("%rcRC")).getDoubleValue() / 100.0;
  68641. }
  68642. else
  68643. {
  68644. if (s.containsChar (T('R')))
  68645. mode |= absoluteFromParentBottomRight;
  68646. else if (s.containsChar (T('C')))
  68647. mode |= absoluteFromParentCentre;
  68648. else
  68649. mode |= absoluteFromParentTopLeft;
  68650. value = s.removeCharacters (T("rcRC")).getDoubleValue();
  68651. }
  68652. }
  68653. void PositionedRectangle::decodeSizeString (const String& s, uint8& mode, double& value) throw()
  68654. {
  68655. if (s.containsChar (T('%')))
  68656. {
  68657. mode = proportionalSize;
  68658. value = s.upToFirstOccurrenceOf (T("%"), false, false).getDoubleValue() / 100.0;
  68659. }
  68660. else if (s.containsChar (T('M')))
  68661. {
  68662. mode = parentSizeMinusAbsolute;
  68663. value = s.getDoubleValue();
  68664. }
  68665. else
  68666. {
  68667. mode = absoluteSize;
  68668. value = s.getDoubleValue();
  68669. }
  68670. }
  68671. void PositionedRectangle::applyPosAndSize (double& xOut, double& wOut,
  68672. const double x, const double w,
  68673. const uint8 xMode, const uint8 wMode,
  68674. const int parentPos,
  68675. const int parentSize) const throw()
  68676. {
  68677. if (wMode == proportionalSize)
  68678. wOut = roundDoubleToInt (w * parentSize);
  68679. else if (wMode == parentSizeMinusAbsolute)
  68680. wOut = jmax (0, parentSize - roundDoubleToInt (w));
  68681. else
  68682. wOut = roundDoubleToInt (w);
  68683. if ((xMode & proportionOfParentSize) != 0)
  68684. xOut = parentPos + x * parentSize;
  68685. else if ((xMode & absoluteFromParentBottomRight) != 0)
  68686. xOut = (parentPos + parentSize) - x;
  68687. else if ((xMode & absoluteFromParentCentre) != 0)
  68688. xOut = x + (parentPos + parentSize / 2);
  68689. else
  68690. xOut = x + parentPos;
  68691. if ((xMode & anchorAtRightOrBottom) != 0)
  68692. xOut -= wOut;
  68693. else if ((xMode & anchorAtCentre) != 0)
  68694. xOut -= wOut / 2;
  68695. }
  68696. void PositionedRectangle::updatePosAndSize (double& xOut, double& wOut,
  68697. double x, const double w,
  68698. const uint8 xMode, const uint8 wMode,
  68699. const int parentPos,
  68700. const int parentSize) const throw()
  68701. {
  68702. if (wMode == proportionalSize)
  68703. {
  68704. if (parentSize > 0)
  68705. wOut = w / parentSize;
  68706. }
  68707. else if (wMode == parentSizeMinusAbsolute)
  68708. wOut = parentSize - w;
  68709. else
  68710. wOut = w;
  68711. if ((xMode & anchorAtRightOrBottom) != 0)
  68712. x += w;
  68713. else if ((xMode & anchorAtCentre) != 0)
  68714. x += w / 2;
  68715. if ((xMode & proportionOfParentSize) != 0)
  68716. {
  68717. if (parentSize > 0)
  68718. xOut = (x - parentPos) / parentSize;
  68719. }
  68720. else if ((xMode & absoluteFromParentBottomRight) != 0)
  68721. xOut = (parentPos + parentSize) - x;
  68722. else if ((xMode & absoluteFromParentCentre) != 0)
  68723. xOut = x - (parentPos + parentSize / 2);
  68724. else
  68725. xOut = x - parentPos;
  68726. }
  68727. END_JUCE_NAMESPACE
  68728. /********* End of inlined file: juce_PositionedRectangle.cpp *********/
  68729. /********* Start of inlined file: juce_Rectangle.cpp *********/
  68730. BEGIN_JUCE_NAMESPACE
  68731. Rectangle::Rectangle() throw()
  68732. : x (0),
  68733. y (0),
  68734. w (0),
  68735. h (0)
  68736. {
  68737. }
  68738. Rectangle::Rectangle (const int x_, const int y_,
  68739. const int w_, const int h_) throw()
  68740. : x (x_),
  68741. y (y_),
  68742. w (w_),
  68743. h (h_)
  68744. {
  68745. }
  68746. Rectangle::Rectangle (const int w_, const int h_) throw()
  68747. : x (0),
  68748. y (0),
  68749. w (w_),
  68750. h (h_)
  68751. {
  68752. }
  68753. Rectangle::Rectangle (const Rectangle& other) throw()
  68754. : x (other.x),
  68755. y (other.y),
  68756. w (other.w),
  68757. h (other.h)
  68758. {
  68759. }
  68760. Rectangle::~Rectangle() throw()
  68761. {
  68762. }
  68763. bool Rectangle::isEmpty() const throw()
  68764. {
  68765. return w <= 0 || h <= 0;
  68766. }
  68767. void Rectangle::setBounds (const int x_,
  68768. const int y_,
  68769. const int w_,
  68770. const int h_) throw()
  68771. {
  68772. x = x_;
  68773. y = y_;
  68774. w = w_;
  68775. h = h_;
  68776. }
  68777. void Rectangle::setPosition (const int x_,
  68778. const int y_) throw()
  68779. {
  68780. x = x_;
  68781. y = y_;
  68782. }
  68783. void Rectangle::setSize (const int w_,
  68784. const int h_) throw()
  68785. {
  68786. w = w_;
  68787. h = h_;
  68788. }
  68789. void Rectangle::translate (const int dx,
  68790. const int dy) throw()
  68791. {
  68792. x += dx;
  68793. y += dy;
  68794. }
  68795. const Rectangle Rectangle::translated (const int dx,
  68796. const int dy) const throw()
  68797. {
  68798. return Rectangle (x + dx, y + dy, w, h);
  68799. }
  68800. void Rectangle::expand (const int deltaX,
  68801. const int deltaY) throw()
  68802. {
  68803. const int nw = jmax (0, w + deltaX + deltaX);
  68804. const int nh = jmax (0, h + deltaY + deltaY);
  68805. setBounds (x - deltaX,
  68806. y - deltaY,
  68807. nw, nh);
  68808. }
  68809. const Rectangle Rectangle::expanded (const int deltaX,
  68810. const int deltaY) const throw()
  68811. {
  68812. const int nw = jmax (0, w + deltaX + deltaX);
  68813. const int nh = jmax (0, h + deltaY + deltaY);
  68814. return Rectangle (x - deltaX,
  68815. y - deltaY,
  68816. nw, nh);
  68817. }
  68818. void Rectangle::reduce (const int deltaX,
  68819. const int deltaY) throw()
  68820. {
  68821. expand (-deltaX, -deltaY);
  68822. }
  68823. const Rectangle Rectangle::reduced (const int deltaX,
  68824. const int deltaY) const throw()
  68825. {
  68826. return expanded (-deltaX, -deltaY);
  68827. }
  68828. bool Rectangle::operator== (const Rectangle& other) const throw()
  68829. {
  68830. return x == other.x
  68831. && y == other.y
  68832. && w == other.w
  68833. && h == other.h;
  68834. }
  68835. bool Rectangle::operator!= (const Rectangle& other) const throw()
  68836. {
  68837. return x != other.x
  68838. || y != other.y
  68839. || w != other.w
  68840. || h != other.h;
  68841. }
  68842. bool Rectangle::contains (const int px,
  68843. const int py) const throw()
  68844. {
  68845. return px >= x
  68846. && py >= y
  68847. && px < x + w
  68848. && py < y + h;
  68849. }
  68850. bool Rectangle::contains (const Rectangle& other) const throw()
  68851. {
  68852. return x <= other.x
  68853. && y <= other.y
  68854. && x + w >= other.x + other.w
  68855. && y + h >= other.y + other.h;
  68856. }
  68857. bool Rectangle::intersects (const Rectangle& other) const throw()
  68858. {
  68859. return x + w > other.x
  68860. && y + h > other.y
  68861. && x < other.x + other.w
  68862. && y < other.y + other.h
  68863. && w > 0
  68864. && h > 0;
  68865. }
  68866. const Rectangle Rectangle::getIntersection (const Rectangle& other) const throw()
  68867. {
  68868. const int nx = jmax (x, other.x);
  68869. const int ny = jmax (y, other.y);
  68870. const int nw = jmin (x + w, other.x + other.w) - nx;
  68871. const int nh = jmin (y + h, other.y + other.h) - ny;
  68872. if (nw >= 0 && nh >= 0)
  68873. return Rectangle (nx, ny, nw, nh);
  68874. else
  68875. return Rectangle();
  68876. }
  68877. bool Rectangle::intersectRectangle (int& x1, int& y1, int& w1, int& h1) const throw()
  68878. {
  68879. const int maxX = jmax (x1, x);
  68880. w1 = jmin (x1 + w1, x + w) - maxX;
  68881. if (w1 > 0)
  68882. {
  68883. const int maxY = jmax (y1, y);
  68884. h1 = jmin (y1 + h1, y + h) - maxY;
  68885. if (h1 > 0)
  68886. {
  68887. x1 = maxX;
  68888. y1 = maxY;
  68889. return true;
  68890. }
  68891. }
  68892. return false;
  68893. }
  68894. bool Rectangle::intersectRectangles (int& x1, int& y1, int& w1, int& h1,
  68895. int x2, int y2, int w2, int h2) throw()
  68896. {
  68897. const int x = jmax (x1, x2);
  68898. w1 = jmin (x1 + w1, x2 + w2) - x;
  68899. if (w1 > 0)
  68900. {
  68901. const int y = jmax (y1, y2);
  68902. h1 = jmin (y1 + h1, y2 + h2) - y;
  68903. if (h1 > 0)
  68904. {
  68905. x1 = x;
  68906. y1 = y;
  68907. return true;
  68908. }
  68909. }
  68910. return false;
  68911. }
  68912. const Rectangle Rectangle::getUnion (const Rectangle& other) const throw()
  68913. {
  68914. const int newX = jmin (x, other.x);
  68915. const int newY = jmin (y, other.y);
  68916. return Rectangle (newX, newY,
  68917. jmax (x + w, other.x + other.w) - newX,
  68918. jmax (y + h, other.y + other.h) - newY);
  68919. }
  68920. bool Rectangle::enlargeIfAdjacent (const Rectangle& other) throw()
  68921. {
  68922. if (x == other.x && getRight() == other.getRight()
  68923. && (other.getBottom() >= y && other.y <= getBottom()))
  68924. {
  68925. const int newY = jmin (y, other.y);
  68926. h = jmax (getBottom(), other.getBottom()) - newY;
  68927. y = newY;
  68928. return true;
  68929. }
  68930. else if (y == other.y && getBottom() == other.getBottom()
  68931. && (other.getRight() >= x && other.x <= getRight()))
  68932. {
  68933. const int newX = jmin (x, other.x);
  68934. w = jmax (getRight(), other.getRight()) - newX;
  68935. x = newX;
  68936. return true;
  68937. }
  68938. return false;
  68939. }
  68940. bool Rectangle::reduceIfPartlyContainedIn (const Rectangle& other) throw()
  68941. {
  68942. int inside = 0;
  68943. const int otherR = other.getRight();
  68944. if (x >= other.x && x < otherR)
  68945. inside = 1;
  68946. const int otherB = other.getBottom();
  68947. if (y >= other.y && y < otherB)
  68948. inside |= 2;
  68949. const int r = x + w;
  68950. if (r >= other.x && r < otherR)
  68951. inside |= 4;
  68952. const int b = y + h;
  68953. if (b >= other.y && b < otherB)
  68954. inside |= 8;
  68955. switch (inside)
  68956. {
  68957. case 1 + 2 + 8:
  68958. w = r - otherR;
  68959. x = otherR;
  68960. return true;
  68961. case 1 + 2 + 4:
  68962. h = b - otherB;
  68963. y = otherB;
  68964. return true;
  68965. case 2 + 4 + 8:
  68966. w = other.x - x;
  68967. return true;
  68968. case 1 + 4 + 8:
  68969. h = other.y - y;
  68970. return true;
  68971. }
  68972. return false;
  68973. }
  68974. const String Rectangle::toString() const throw()
  68975. {
  68976. String s;
  68977. s.preallocateStorage (16);
  68978. s << x << T(' ')
  68979. << y << T(' ')
  68980. << w << T(' ')
  68981. << h;
  68982. return s;
  68983. }
  68984. const Rectangle Rectangle::fromString (const String& stringVersion)
  68985. {
  68986. StringArray toks;
  68987. toks.addTokens (stringVersion.trim(), T(",; \t\r\n"), 0);
  68988. return Rectangle (toks[0].trim().getIntValue(),
  68989. toks[1].trim().getIntValue(),
  68990. toks[2].trim().getIntValue(),
  68991. toks[3].trim().getIntValue());
  68992. }
  68993. END_JUCE_NAMESPACE
  68994. /********* End of inlined file: juce_Rectangle.cpp *********/
  68995. /********* Start of inlined file: juce_RectangleList.cpp *********/
  68996. BEGIN_JUCE_NAMESPACE
  68997. RectangleList::RectangleList() throw()
  68998. {
  68999. }
  69000. RectangleList::RectangleList (const Rectangle& rect) throw()
  69001. {
  69002. if (! rect.isEmpty())
  69003. rects.add (rect);
  69004. }
  69005. RectangleList::RectangleList (const RectangleList& other) throw()
  69006. : rects (other.rects)
  69007. {
  69008. }
  69009. const RectangleList& RectangleList::operator= (const RectangleList& other) throw()
  69010. {
  69011. if (this != &other)
  69012. rects = other.rects;
  69013. return *this;
  69014. }
  69015. RectangleList::~RectangleList() throw()
  69016. {
  69017. }
  69018. void RectangleList::clear() throw()
  69019. {
  69020. rects.clearQuick();
  69021. }
  69022. const Rectangle RectangleList::getRectangle (const int index) const throw()
  69023. {
  69024. if (((unsigned int) index) < (unsigned int) rects.size())
  69025. return rects.getReference (index);
  69026. return Rectangle();
  69027. }
  69028. bool RectangleList::isEmpty() const throw()
  69029. {
  69030. return rects.size() == 0;
  69031. }
  69032. RectangleList::Iterator::Iterator (const RectangleList& list) throw()
  69033. : current (0),
  69034. owner (list),
  69035. index (list.rects.size())
  69036. {
  69037. }
  69038. RectangleList::Iterator::~Iterator() throw()
  69039. {
  69040. }
  69041. bool RectangleList::Iterator::next() throw()
  69042. {
  69043. if (--index >= 0)
  69044. {
  69045. current = & (owner.rects.getReference (index));
  69046. return true;
  69047. }
  69048. return false;
  69049. }
  69050. void RectangleList::add (const Rectangle& rect) throw()
  69051. {
  69052. if (! rect.isEmpty())
  69053. {
  69054. if (rects.size() == 0)
  69055. {
  69056. rects.add (rect);
  69057. }
  69058. else
  69059. {
  69060. bool anyOverlaps = false;
  69061. int i;
  69062. for (i = rects.size(); --i >= 0;)
  69063. {
  69064. Rectangle& ourRect = rects.getReference (i);
  69065. if (rect.intersects (ourRect))
  69066. {
  69067. if (rect.contains (ourRect))
  69068. rects.remove (i);
  69069. else if (! ourRect.reduceIfPartlyContainedIn (rect))
  69070. anyOverlaps = true;
  69071. }
  69072. }
  69073. if (anyOverlaps && rects.size() > 0)
  69074. {
  69075. RectangleList r (rect);
  69076. for (i = rects.size(); --i >= 0;)
  69077. {
  69078. const Rectangle& ourRect = rects.getReference (i);
  69079. if (rect.intersects (ourRect))
  69080. {
  69081. r.subtract (ourRect);
  69082. if (r.rects.size() == 0)
  69083. return;
  69084. }
  69085. }
  69086. for (i = r.getNumRectangles(); --i >= 0;)
  69087. rects.add (r.rects.getReference (i));
  69088. }
  69089. else
  69090. {
  69091. rects.add (rect);
  69092. }
  69093. }
  69094. }
  69095. }
  69096. void RectangleList::addWithoutMerging (const Rectangle& rect) throw()
  69097. {
  69098. rects.add (rect);
  69099. }
  69100. void RectangleList::add (const int x, const int y, const int w, const int h) throw()
  69101. {
  69102. if (rects.size() == 0)
  69103. {
  69104. if (w > 0 && h > 0)
  69105. rects.add (Rectangle (x, y, w, h));
  69106. }
  69107. else
  69108. {
  69109. add (Rectangle (x, y, w, h));
  69110. }
  69111. }
  69112. void RectangleList::add (const RectangleList& other) throw()
  69113. {
  69114. for (int i = 0; i < other.rects.size(); ++i)
  69115. add (other.rects.getReference (i));
  69116. }
  69117. void RectangleList::subtract (const Rectangle& rect) throw()
  69118. {
  69119. const int originalNumRects = rects.size();
  69120. if (originalNumRects > 0)
  69121. {
  69122. const int x1 = rect.x;
  69123. const int y1 = rect.y;
  69124. const int x2 = x1 + rect.w;
  69125. const int y2 = y1 + rect.h;
  69126. for (int i = getNumRectangles(); --i >= 0;)
  69127. {
  69128. Rectangle& r = rects.getReference (i);
  69129. const int rx1 = r.x;
  69130. const int ry1 = r.y;
  69131. const int rx2 = rx1 + r.w;
  69132. const int ry2 = ry1 + r.h;
  69133. if (! (x2 <= rx1 || x1 >= rx2 || y2 <= ry1 || y1 >= ry2))
  69134. {
  69135. if (x1 > rx1 && x1 < rx2)
  69136. {
  69137. if (y1 <= ry1 && y2 >= ry2 && x2 >= rx2)
  69138. {
  69139. r.w = x1 - rx1;
  69140. }
  69141. else
  69142. {
  69143. r.x = x1;
  69144. r.w = rx2 - x1;
  69145. rects.insert (i + 1, Rectangle (rx1, ry1, x1 - rx1, ry2 - ry1));
  69146. i += 2;
  69147. }
  69148. }
  69149. else if (x2 > rx1 && x2 < rx2)
  69150. {
  69151. r.x = x2;
  69152. r.w = rx2 - x2;
  69153. if (y1 > ry1 || y2 < ry2 || x1 > rx1)
  69154. {
  69155. rects.insert (i + 1, Rectangle (rx1, ry1, x2 - rx1, ry2 - ry1));
  69156. i += 2;
  69157. }
  69158. }
  69159. else if (y1 > ry1 && y1 < ry2)
  69160. {
  69161. if (x1 <= rx1 && x2 >= rx2 && y2 >= ry2)
  69162. {
  69163. r.h = y1 - ry1;
  69164. }
  69165. else
  69166. {
  69167. r.y = y1;
  69168. r.h = ry2 - y1;
  69169. rects.insert (i + 1, Rectangle (rx1, ry1, rx2 - rx1, y1 - ry1));
  69170. i += 2;
  69171. }
  69172. }
  69173. else if (y2 > ry1 && y2 < ry2)
  69174. {
  69175. r.y = y2;
  69176. r.h = ry2 - y2;
  69177. if (x1 > rx1 || x2 < rx2 || y1 > ry1)
  69178. {
  69179. rects.insert (i + 1, Rectangle (rx1, ry1, rx2 - rx1, y2 - ry1));
  69180. i += 2;
  69181. }
  69182. }
  69183. else
  69184. {
  69185. rects.remove (i);
  69186. }
  69187. }
  69188. }
  69189. if (rects.size() > originalNumRects + 10)
  69190. consolidate();
  69191. }
  69192. }
  69193. void RectangleList::subtract (const RectangleList& otherList) throw()
  69194. {
  69195. for (int i = otherList.rects.size(); --i >= 0;)
  69196. subtract (otherList.rects.getReference (i));
  69197. }
  69198. bool RectangleList::clipTo (const Rectangle& rect) throw()
  69199. {
  69200. bool notEmpty = false;
  69201. if (rect.isEmpty())
  69202. {
  69203. clear();
  69204. }
  69205. else
  69206. {
  69207. for (int i = rects.size(); --i >= 0;)
  69208. {
  69209. Rectangle& r = rects.getReference (i);
  69210. if (! rect.intersectRectangle (r.x, r.y, r.w, r.h))
  69211. rects.remove (i);
  69212. else
  69213. notEmpty = true;
  69214. }
  69215. }
  69216. return notEmpty;
  69217. }
  69218. bool RectangleList::clipTo (const RectangleList& other) throw()
  69219. {
  69220. if (rects.size() == 0)
  69221. return false;
  69222. RectangleList result;
  69223. for (int j = 0; j < rects.size(); ++j)
  69224. {
  69225. const Rectangle& rect = rects.getReference (j);
  69226. for (int i = other.rects.size(); --i >= 0;)
  69227. {
  69228. Rectangle r (other.rects.getReference (i));
  69229. if (rect.intersectRectangle (r.x, r.y, r.w, r.h))
  69230. result.rects.add (r);
  69231. }
  69232. }
  69233. swapWith (result);
  69234. return ! isEmpty();
  69235. }
  69236. bool RectangleList::getIntersectionWith (const Rectangle& rect, RectangleList& destRegion) const throw()
  69237. {
  69238. destRegion.clear();
  69239. if (! rect.isEmpty())
  69240. {
  69241. for (int i = rects.size(); --i >= 0;)
  69242. {
  69243. Rectangle r (rects.getReference (i));
  69244. if (rect.intersectRectangle (r.x, r.y, r.w, r.h))
  69245. destRegion.rects.add (r);
  69246. }
  69247. }
  69248. return destRegion.rects.size() > 0;
  69249. }
  69250. void RectangleList::swapWith (RectangleList& otherList) throw()
  69251. {
  69252. rects.swapWithArray (otherList.rects);
  69253. }
  69254. void RectangleList::consolidate() throw()
  69255. {
  69256. int i;
  69257. for (i = 0; i < getNumRectangles() - 1; ++i)
  69258. {
  69259. Rectangle& r = rects.getReference (i);
  69260. const int rx1 = r.x;
  69261. const int ry1 = r.y;
  69262. const int rx2 = rx1 + r.w;
  69263. const int ry2 = ry1 + r.h;
  69264. for (int j = rects.size(); --j > i;)
  69265. {
  69266. Rectangle& r2 = rects.getReference (j);
  69267. const int jrx1 = r2.x;
  69268. const int jry1 = r2.y;
  69269. const int jrx2 = jrx1 + r2.w;
  69270. const int jry2 = jry1 + r2.h;
  69271. // if the vertical edges of any blocks are touching and their horizontals don't
  69272. // line up, split them horizontally..
  69273. if (jrx1 == rx2 || jrx2 == rx1)
  69274. {
  69275. if (jry1 > ry1 && jry1 < ry2)
  69276. {
  69277. r.h = jry1 - ry1;
  69278. rects.add (Rectangle (rx1, jry1, rx2 - rx1, ry2 - jry1));
  69279. i = -1;
  69280. break;
  69281. }
  69282. if (jry2 > ry1 && jry2 < ry2)
  69283. {
  69284. r.h = jry2 - ry1;
  69285. rects.add (Rectangle (rx1, jry2, rx2 - rx1, ry2 - jry2));
  69286. i = -1;
  69287. break;
  69288. }
  69289. else if (ry1 > jry1 && ry1 < jry2)
  69290. {
  69291. r2.h = ry1 - jry1;
  69292. rects.add (Rectangle (jrx1, ry1, jrx2 - jrx1, jry2 - ry1));
  69293. i = -1;
  69294. break;
  69295. }
  69296. else if (ry2 > jry1 && ry2 < jry2)
  69297. {
  69298. r2.h = ry2 - jry1;
  69299. rects.add (Rectangle (jrx1, ry2, jrx2 - jrx1, jry2 - ry2));
  69300. i = -1;
  69301. break;
  69302. }
  69303. }
  69304. }
  69305. }
  69306. for (i = 0; i < rects.size() - 1; ++i)
  69307. {
  69308. Rectangle& r = rects.getReference (i);
  69309. for (int j = rects.size(); --j > i;)
  69310. {
  69311. if (r.enlargeIfAdjacent (rects.getReference (j)))
  69312. {
  69313. rects.remove (j);
  69314. i = -1;
  69315. break;
  69316. }
  69317. }
  69318. }
  69319. }
  69320. bool RectangleList::containsPoint (const int x, const int y) const throw()
  69321. {
  69322. for (int i = getNumRectangles(); --i >= 0;)
  69323. if (rects.getReference (i).contains (x, y))
  69324. return true;
  69325. return false;
  69326. }
  69327. bool RectangleList::containsRectangle (const Rectangle& rectangleToCheck) const throw()
  69328. {
  69329. if (rects.size() > 1)
  69330. {
  69331. RectangleList r (rectangleToCheck);
  69332. for (int i = rects.size(); --i >= 0;)
  69333. {
  69334. r.subtract (rects.getReference (i));
  69335. if (r.rects.size() == 0)
  69336. return true;
  69337. }
  69338. }
  69339. else if (rects.size() > 0)
  69340. {
  69341. return rects.getReference (0).contains (rectangleToCheck);
  69342. }
  69343. return false;
  69344. }
  69345. bool RectangleList::intersectsRectangle (const Rectangle& rectangleToCheck) const throw()
  69346. {
  69347. for (int i = rects.size(); --i >= 0;)
  69348. if (rects.getReference (i).intersects (rectangleToCheck))
  69349. return true;
  69350. return false;
  69351. }
  69352. bool RectangleList::intersects (const RectangleList& other) const throw()
  69353. {
  69354. for (int i = rects.size(); --i >= 0;)
  69355. if (other.intersectsRectangle (rects.getReference (i)))
  69356. return true;
  69357. return false;
  69358. }
  69359. const Rectangle RectangleList::getBounds() const throw()
  69360. {
  69361. if (rects.size() <= 1)
  69362. {
  69363. if (rects.size() == 0)
  69364. return Rectangle();
  69365. else
  69366. return rects.getReference (0);
  69367. }
  69368. else
  69369. {
  69370. const Rectangle& r = rects.getReference (0);
  69371. int minX = r.x;
  69372. int minY = r.y;
  69373. int maxX = minX + r.w;
  69374. int maxY = minY + r.h;
  69375. for (int i = rects.size(); --i > 0;)
  69376. {
  69377. const Rectangle& r2 = rects.getReference (i);
  69378. minX = jmin (minX, r2.x);
  69379. minY = jmin (minY, r2.y);
  69380. maxX = jmax (maxX, r2.getRight());
  69381. maxY = jmax (maxY, r2.getBottom());
  69382. }
  69383. return Rectangle (minX, minY, maxX - minX, maxY - minY);
  69384. }
  69385. }
  69386. void RectangleList::offsetAll (const int dx, const int dy) throw()
  69387. {
  69388. for (int i = rects.size(); --i >= 0;)
  69389. {
  69390. Rectangle& r = rects.getReference (i);
  69391. r.x += dx;
  69392. r.y += dy;
  69393. }
  69394. }
  69395. const Path RectangleList::toPath() const throw()
  69396. {
  69397. Path p;
  69398. for (int i = rects.size(); --i >= 0;)
  69399. {
  69400. const Rectangle& r = rects.getReference (i);
  69401. p.addRectangle ((float) r.x,
  69402. (float) r.y,
  69403. (float) r.w,
  69404. (float) r.h);
  69405. }
  69406. return p;
  69407. }
  69408. END_JUCE_NAMESPACE
  69409. /********* End of inlined file: juce_RectangleList.cpp *********/
  69410. /********* Start of inlined file: juce_Image.cpp *********/
  69411. BEGIN_JUCE_NAMESPACE
  69412. static const int fullAlphaThreshold = 253;
  69413. Image::Image (const PixelFormat format_,
  69414. const int imageWidth_,
  69415. const int imageHeight_)
  69416. : format (format_),
  69417. imageWidth (imageWidth_),
  69418. imageHeight (imageHeight_),
  69419. imageData (0)
  69420. {
  69421. jassert (format_ == RGB || format_ == ARGB || format_ == SingleChannel);
  69422. jassert (imageWidth_ > 0 && imageHeight_ > 0); // it's illegal to create a zero-sized image - the
  69423. // actual image will be at least 1x1.
  69424. }
  69425. Image::Image (const PixelFormat format_,
  69426. const int imageWidth_,
  69427. const int imageHeight_,
  69428. const bool clearImage)
  69429. : format (format_),
  69430. imageWidth (imageWidth_),
  69431. imageHeight (imageHeight_)
  69432. {
  69433. jassert (format_ == RGB || format_ == ARGB || format_ == SingleChannel);
  69434. jassert (imageWidth_ > 0 && imageHeight_ > 0); // it's illegal to create a zero-sized image - the
  69435. // actual image will be at least 1x1.
  69436. pixelStride = (format == RGB) ? 3 : ((format == ARGB) ? 4 : 1);
  69437. lineStride = (pixelStride * jmax (1, imageWidth_) + 3) & ~3;
  69438. const int dataSize = lineStride * jmax (1, imageHeight_);
  69439. imageData = (uint8*) (clearImage ? juce_calloc (dataSize)
  69440. : juce_malloc (dataSize));
  69441. }
  69442. Image::Image (const Image& other)
  69443. : format (other.format),
  69444. imageWidth (other.imageWidth),
  69445. imageHeight (other.imageHeight)
  69446. {
  69447. pixelStride = (format == RGB) ? 3 : ((format == ARGB) ? 4 : 1);
  69448. lineStride = (pixelStride * jmax (1, imageWidth) + 3) & ~3;
  69449. const int dataSize = lineStride * jmax (1, imageHeight);
  69450. imageData = (uint8*) juce_malloc (dataSize);
  69451. int ls, ps;
  69452. const uint8* srcData = other.lockPixelDataReadOnly (0, 0, imageWidth, imageHeight, ls, ps);
  69453. setPixelData (0, 0, imageWidth, imageHeight, srcData, ls);
  69454. other.releasePixelDataReadOnly (srcData);
  69455. }
  69456. Image::~Image()
  69457. {
  69458. juce_free (imageData);
  69459. }
  69460. LowLevelGraphicsContext* Image::createLowLevelContext()
  69461. {
  69462. return new LowLevelGraphicsSoftwareRenderer (*this);
  69463. }
  69464. uint8* Image::lockPixelDataReadWrite (int x, int y, int w, int h, int& ls, int& ps)
  69465. {
  69466. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= imageWidth && y + h <= imageHeight);
  69467. w = w;
  69468. h = h;
  69469. ls = lineStride;
  69470. ps = pixelStride;
  69471. return imageData + x * pixelStride + y * lineStride;
  69472. }
  69473. void Image::releasePixelDataReadWrite (void*)
  69474. {
  69475. }
  69476. const uint8* Image::lockPixelDataReadOnly (int x, int y, int w, int h, int& ls, int& ps) const
  69477. {
  69478. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= imageWidth && y + h <= imageHeight);
  69479. w = w;
  69480. h = h;
  69481. ls = lineStride;
  69482. ps = pixelStride;
  69483. return imageData + x * pixelStride + y * lineStride;
  69484. }
  69485. void Image::releasePixelDataReadOnly (const void*) const
  69486. {
  69487. }
  69488. void Image::setPixelData (int x, int y, int w, int h,
  69489. const uint8* sourcePixelData, int sourceLineStride)
  69490. {
  69491. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= imageWidth && y + h <= imageHeight);
  69492. if (Rectangle::intersectRectangles (x, y, w, h, 0, 0, imageWidth, imageHeight))
  69493. {
  69494. int ls, ps;
  69495. uint8* dest = lockPixelDataReadWrite (x, y, w, h, ls, ps);
  69496. for (int i = 0; i < h; ++i)
  69497. {
  69498. memcpy (dest + ls * i,
  69499. sourcePixelData + sourceLineStride * i,
  69500. w * pixelStride);
  69501. }
  69502. releasePixelDataReadWrite (dest);
  69503. }
  69504. }
  69505. void Image::clear (int dx, int dy, int dw, int dh,
  69506. const Colour& colourToClearTo)
  69507. {
  69508. const PixelARGB col (colourToClearTo.getPixelARGB());
  69509. int ls, ps;
  69510. uint8* dstData = lockPixelDataReadWrite (dx, dy, dw, dh, ls, ps);
  69511. uint8* dest = dstData;
  69512. while (--dh >= 0)
  69513. {
  69514. uint8* line = dest;
  69515. dest += ls;
  69516. if (isARGB())
  69517. {
  69518. for (int x = dw; --x >= 0;)
  69519. {
  69520. ((PixelARGB*) line)->set (col);
  69521. line += ps;
  69522. }
  69523. }
  69524. else if (isRGB())
  69525. {
  69526. for (int x = dw; --x >= 0;)
  69527. {
  69528. ((PixelRGB*) line)->set (col);
  69529. line += ps;
  69530. }
  69531. }
  69532. else
  69533. {
  69534. for (int x = dw; --x >= 0;)
  69535. {
  69536. *line = col.getAlpha();
  69537. line += ps;
  69538. }
  69539. }
  69540. }
  69541. releasePixelDataReadWrite (dstData);
  69542. }
  69543. Image* Image::createCopy (int newWidth, int newHeight,
  69544. const Graphics::ResamplingQuality quality) const
  69545. {
  69546. if (newWidth < 0)
  69547. newWidth = imageWidth;
  69548. if (newHeight < 0)
  69549. newHeight = imageHeight;
  69550. Image* const newImage = new Image (format, newWidth, newHeight, true);
  69551. Graphics g (*newImage);
  69552. g.setImageResamplingQuality (quality);
  69553. g.drawImage (this,
  69554. 0, 0, newWidth, newHeight,
  69555. 0, 0, imageWidth, imageHeight,
  69556. false);
  69557. return newImage;
  69558. }
  69559. const Colour Image::getPixelAt (const int x, const int y) const
  69560. {
  69561. Colour c;
  69562. if (((unsigned int) x) < (unsigned int) imageWidth
  69563. && ((unsigned int) y) < (unsigned int) imageHeight)
  69564. {
  69565. int ls, ps;
  69566. const uint8* const pixels = lockPixelDataReadOnly (x, y, 1, 1, ls, ps);
  69567. if (isARGB())
  69568. {
  69569. PixelARGB p (*(const PixelARGB*) pixels);
  69570. p.unpremultiply();
  69571. c = Colour (p.getARGB());
  69572. }
  69573. else if (isRGB())
  69574. c = Colour (((const PixelRGB*) pixels)->getARGB());
  69575. else
  69576. c = Colour ((uint8) 0, (uint8) 0, (uint8) 0, *pixels);
  69577. releasePixelDataReadOnly (pixels);
  69578. }
  69579. return c;
  69580. }
  69581. void Image::setPixelAt (const int x, const int y,
  69582. const Colour& colour)
  69583. {
  69584. if (((unsigned int) x) < (unsigned int) imageWidth
  69585. && ((unsigned int) y) < (unsigned int) imageHeight)
  69586. {
  69587. int ls, ps;
  69588. uint8* const pixels = lockPixelDataReadWrite (x, y, 1, 1, ls, ps);
  69589. const PixelARGB col (colour.getPixelARGB());
  69590. if (isARGB())
  69591. ((PixelARGB*) pixels)->set (col);
  69592. else if (isRGB())
  69593. ((PixelRGB*) pixels)->set (col);
  69594. else
  69595. *pixels = col.getAlpha();
  69596. releasePixelDataReadWrite (pixels);
  69597. }
  69598. }
  69599. void Image::multiplyAlphaAt (const int x, const int y,
  69600. const float multiplier)
  69601. {
  69602. if (((unsigned int) x) < (unsigned int) imageWidth
  69603. && ((unsigned int) y) < (unsigned int) imageHeight
  69604. && hasAlphaChannel())
  69605. {
  69606. int ls, ps;
  69607. uint8* const pixels = lockPixelDataReadWrite (x, y, 1, 1, ls, ps);
  69608. if (isARGB())
  69609. ((PixelARGB*) pixels)->multiplyAlpha (multiplier);
  69610. else
  69611. *pixels = (uint8) (*pixels * multiplier);
  69612. releasePixelDataReadWrite (pixels);
  69613. }
  69614. }
  69615. void Image::multiplyAllAlphas (const float amountToMultiplyBy)
  69616. {
  69617. if (hasAlphaChannel())
  69618. {
  69619. int ls, ps;
  69620. uint8* const pixels = lockPixelDataReadWrite (0, 0, getWidth(), getHeight(), ls, ps);
  69621. if (isARGB())
  69622. {
  69623. for (int y = 0; y < imageHeight; ++y)
  69624. {
  69625. uint8* p = pixels + y * ls;
  69626. for (int x = 0; x < imageWidth; ++x)
  69627. {
  69628. ((PixelARGB*) p)->multiplyAlpha (amountToMultiplyBy);
  69629. p += ps;
  69630. }
  69631. }
  69632. }
  69633. else
  69634. {
  69635. for (int y = 0; y < imageHeight; ++y)
  69636. {
  69637. uint8* p = pixels + y * ls;
  69638. for (int x = 0; x < imageWidth; ++x)
  69639. {
  69640. *p = (uint8) (*p * amountToMultiplyBy);
  69641. p += ps;
  69642. }
  69643. }
  69644. }
  69645. releasePixelDataReadWrite (pixels);
  69646. }
  69647. else
  69648. {
  69649. jassertfalse // can't do this without an alpha-channel!
  69650. }
  69651. }
  69652. void Image::desaturate()
  69653. {
  69654. if (isARGB() || isRGB())
  69655. {
  69656. int ls, ps;
  69657. uint8* const pixels = lockPixelDataReadWrite (0, 0, getWidth(), getHeight(), ls, ps);
  69658. if (isARGB())
  69659. {
  69660. for (int y = 0; y < imageHeight; ++y)
  69661. {
  69662. uint8* p = pixels + y * ls;
  69663. for (int x = 0; x < imageWidth; ++x)
  69664. {
  69665. ((PixelARGB*) p)->desaturate();
  69666. p += ps;
  69667. }
  69668. }
  69669. }
  69670. else
  69671. {
  69672. for (int y = 0; y < imageHeight; ++y)
  69673. {
  69674. uint8* p = pixels + y * ls;
  69675. for (int x = 0; x < imageWidth; ++x)
  69676. {
  69677. ((PixelRGB*) p)->desaturate();
  69678. p += ps;
  69679. }
  69680. }
  69681. }
  69682. releasePixelDataReadWrite (pixels);
  69683. }
  69684. }
  69685. void Image::createSolidAreaMask (RectangleList& result, const float alphaThreshold) const
  69686. {
  69687. if (hasAlphaChannel())
  69688. {
  69689. const uint8 threshold = (uint8) jlimit (0, 255, roundFloatToInt (alphaThreshold * 255.0f));
  69690. SparseSet <int> pixelsOnRow;
  69691. int ls, ps;
  69692. const uint8* const pixels = lockPixelDataReadOnly (0, 0, imageWidth, imageHeight, ls, ps);
  69693. for (int y = 0; y < imageHeight; ++y)
  69694. {
  69695. pixelsOnRow.clear();
  69696. const uint8* lineData = pixels + ls * y;
  69697. if (isARGB())
  69698. {
  69699. for (int x = 0; x < imageWidth; ++x)
  69700. {
  69701. if (((const PixelARGB*) lineData)->getAlpha() >= threshold)
  69702. pixelsOnRow.addRange (x, 1);
  69703. lineData += ps;
  69704. }
  69705. }
  69706. else
  69707. {
  69708. for (int x = 0; x < imageWidth; ++x)
  69709. {
  69710. if (*lineData >= threshold)
  69711. pixelsOnRow.addRange (x, 1);
  69712. lineData += ps;
  69713. }
  69714. }
  69715. for (int i = 0; i < pixelsOnRow.getNumRanges(); ++i)
  69716. {
  69717. int x, w;
  69718. if (pixelsOnRow.getRange (i, x, w))
  69719. result.add (Rectangle (x, y, w, 1));
  69720. }
  69721. result.consolidate();
  69722. }
  69723. releasePixelDataReadOnly (pixels);
  69724. }
  69725. else
  69726. {
  69727. result.add (0, 0, imageWidth, imageHeight);
  69728. }
  69729. }
  69730. void Image::moveImageSection (int dx, int dy,
  69731. int sx, int sy,
  69732. int w, int h)
  69733. {
  69734. if (dx < 0)
  69735. {
  69736. w += dx;
  69737. sx -= dx;
  69738. dx = 0;
  69739. }
  69740. if (dy < 0)
  69741. {
  69742. h += dy;
  69743. sy -= dy;
  69744. dy = 0;
  69745. }
  69746. if (sx < 0)
  69747. {
  69748. w += sx;
  69749. dx -= sx;
  69750. sx = 0;
  69751. }
  69752. if (sy < 0)
  69753. {
  69754. h += sy;
  69755. dy -= sy;
  69756. sy = 0;
  69757. }
  69758. const int minX = jmin (dx, sx);
  69759. const int minY = jmin (dy, sy);
  69760. w = jmin (w, getWidth() - jmax (sx, dx));
  69761. h = jmin (h, getHeight() - jmax (sy, dy));
  69762. if (w > 0 && h > 0)
  69763. {
  69764. const int maxX = jmax (dx, sx) + w;
  69765. const int maxY = jmax (dy, sy) + h;
  69766. int ls, ps;
  69767. uint8* const pixels = lockPixelDataReadWrite (minX, minY, maxX - minX, maxY - minY, ls, ps);
  69768. uint8* dst = pixels + ls * (dy - minY) + ps * (dx - minX);
  69769. const uint8* src = pixels + ls * (sy - minY) + ps * (sx - minX);
  69770. const int lineSize = ps * w;
  69771. if (dy > sy)
  69772. {
  69773. while (--h >= 0)
  69774. {
  69775. const int offset = h * ls;
  69776. memmove (dst + offset, src + offset, lineSize);
  69777. }
  69778. }
  69779. else if (dst != src)
  69780. {
  69781. while (--h >= 0)
  69782. {
  69783. memmove (dst, src, lineSize);
  69784. dst += ls;
  69785. src += ls;
  69786. }
  69787. }
  69788. releasePixelDataReadWrite (pixels);
  69789. }
  69790. }
  69791. END_JUCE_NAMESPACE
  69792. /********* End of inlined file: juce_Image.cpp *********/
  69793. /********* Start of inlined file: juce_ImageCache.cpp *********/
  69794. BEGIN_JUCE_NAMESPACE
  69795. struct CachedImageInfo
  69796. {
  69797. Image* image;
  69798. int64 hashCode;
  69799. int refCount;
  69800. unsigned int releaseTime;
  69801. juce_UseDebuggingNewOperator
  69802. };
  69803. static ImageCache* instance = 0;
  69804. static int cacheTimeout = 5000;
  69805. ImageCache::ImageCache() throw()
  69806. : images (4)
  69807. {
  69808. }
  69809. ImageCache::~ImageCache()
  69810. {
  69811. const ScopedLock sl (lock);
  69812. for (int i = images.size(); --i >= 0;)
  69813. {
  69814. CachedImageInfo* const ci = (CachedImageInfo*)(images.getUnchecked(i));
  69815. delete ci->image;
  69816. delete ci;
  69817. }
  69818. images.clear();
  69819. jassert (instance == this);
  69820. instance = 0;
  69821. }
  69822. Image* ImageCache::getFromHashCode (const int64 hashCode)
  69823. {
  69824. if (instance != 0)
  69825. {
  69826. const ScopedLock sl (instance->lock);
  69827. for (int i = instance->images.size(); --i >= 0;)
  69828. {
  69829. CachedImageInfo* const ci = (CachedImageInfo*) instance->images.getUnchecked(i);
  69830. if (ci->hashCode == hashCode)
  69831. {
  69832. atomicIncrement (ci->refCount);
  69833. return ci->image;
  69834. }
  69835. }
  69836. }
  69837. return 0;
  69838. }
  69839. void ImageCache::addImageToCache (Image* const image,
  69840. const int64 hashCode)
  69841. {
  69842. if (image != 0)
  69843. {
  69844. if (instance == 0)
  69845. instance = new ImageCache();
  69846. CachedImageInfo* const newC = new CachedImageInfo();
  69847. newC->hashCode = hashCode;
  69848. newC->image = image;
  69849. newC->refCount = 1;
  69850. newC->releaseTime = 0;
  69851. const ScopedLock sl (instance->lock);
  69852. instance->images.add (newC);
  69853. }
  69854. }
  69855. void ImageCache::release (Image* const imageToRelease)
  69856. {
  69857. if (imageToRelease != 0 && instance != 0)
  69858. {
  69859. const ScopedLock sl (instance->lock);
  69860. for (int i = instance->images.size(); --i >= 0;)
  69861. {
  69862. CachedImageInfo* const ci = (CachedImageInfo*) instance->images.getUnchecked(i);
  69863. if (ci->image == imageToRelease)
  69864. {
  69865. if (--(ci->refCount) == 0)
  69866. ci->releaseTime = Time::getApproximateMillisecondCounter();
  69867. if (! instance->isTimerRunning())
  69868. instance->startTimer (999);
  69869. break;
  69870. }
  69871. }
  69872. }
  69873. }
  69874. bool ImageCache::isImageInCache (Image* const imageToLookFor)
  69875. {
  69876. if (instance != 0)
  69877. {
  69878. const ScopedLock sl (instance->lock);
  69879. for (int i = instance->images.size(); --i >= 0;)
  69880. if (((const CachedImageInfo*) instance->images.getUnchecked(i))->image == imageToLookFor)
  69881. return true;
  69882. }
  69883. return false;
  69884. }
  69885. void ImageCache::incReferenceCount (Image* const image)
  69886. {
  69887. if (instance != 0)
  69888. {
  69889. const ScopedLock sl (instance->lock);
  69890. for (int i = instance->images.size(); --i >= 0;)
  69891. {
  69892. CachedImageInfo* const ci = (CachedImageInfo*) instance->images.getUnchecked(i);
  69893. if (ci->image == image)
  69894. {
  69895. ci->refCount++;
  69896. return;
  69897. }
  69898. }
  69899. }
  69900. jassertfalse // (trying to inc the ref count of an image that's not in the cache)
  69901. }
  69902. void ImageCache::timerCallback()
  69903. {
  69904. int numberStillNeedingReleasing = 0;
  69905. const unsigned int now = Time::getApproximateMillisecondCounter();
  69906. const ScopedLock sl (lock);
  69907. for (int i = images.size(); --i >= 0;)
  69908. {
  69909. CachedImageInfo* const ci = (CachedImageInfo*) images.getUnchecked(i);
  69910. if (ci->refCount <= 0)
  69911. {
  69912. if (now > ci->releaseTime + cacheTimeout
  69913. || now < ci->releaseTime - 1000)
  69914. {
  69915. images.remove (i);
  69916. delete ci->image;
  69917. delete ci;
  69918. }
  69919. else
  69920. {
  69921. ++numberStillNeedingReleasing;
  69922. }
  69923. }
  69924. }
  69925. if (numberStillNeedingReleasing == 0)
  69926. stopTimer();
  69927. }
  69928. Image* ImageCache::getFromFile (const File& file)
  69929. {
  69930. const int64 hashCode = file.getFullPathName().hashCode64();
  69931. Image* image = getFromHashCode (hashCode);
  69932. if (image == 0)
  69933. {
  69934. image = ImageFileFormat::loadFrom (file);
  69935. addImageToCache (image, hashCode);
  69936. }
  69937. return image;
  69938. }
  69939. Image* ImageCache::getFromMemory (const void* imageData,
  69940. const int dataSize)
  69941. {
  69942. const int64 hashCode = (int64) (pointer_sized_int) imageData;
  69943. Image* image = getFromHashCode (hashCode);
  69944. if (image == 0)
  69945. {
  69946. image = ImageFileFormat::loadFrom (imageData, dataSize);
  69947. addImageToCache (image, hashCode);
  69948. }
  69949. return image;
  69950. }
  69951. void ImageCache::setCacheTimeout (const int millisecs)
  69952. {
  69953. cacheTimeout = millisecs;
  69954. }
  69955. END_JUCE_NAMESPACE
  69956. /********* End of inlined file: juce_ImageCache.cpp *********/
  69957. /********* Start of inlined file: juce_ImageConvolutionKernel.cpp *********/
  69958. BEGIN_JUCE_NAMESPACE
  69959. ImageConvolutionKernel::ImageConvolutionKernel (const int size_) throw()
  69960. : size (size_)
  69961. {
  69962. values = new float* [size];
  69963. for (int i = size; --i >= 0;)
  69964. values[i] = new float [size];
  69965. clear();
  69966. }
  69967. ImageConvolutionKernel::~ImageConvolutionKernel() throw()
  69968. {
  69969. for (int i = size; --i >= 0;)
  69970. delete[] values[i];
  69971. delete[] values;
  69972. }
  69973. void ImageConvolutionKernel::setKernelValue (const int x,
  69974. const int y,
  69975. const float value) throw()
  69976. {
  69977. if (((unsigned int) x) < (unsigned int) size
  69978. && ((unsigned int) y) < (unsigned int) size)
  69979. {
  69980. values[x][y] = value;
  69981. }
  69982. else
  69983. {
  69984. jassertfalse
  69985. }
  69986. }
  69987. void ImageConvolutionKernel::clear() throw()
  69988. {
  69989. for (int y = size; --y >= 0;)
  69990. for (int x = size; --x >= 0;)
  69991. values[x][y] = 0;
  69992. }
  69993. void ImageConvolutionKernel::setOverallSum (const float desiredTotalSum) throw()
  69994. {
  69995. double currentTotal = 0.0;
  69996. for (int y = size; --y >= 0;)
  69997. for (int x = size; --x >= 0;)
  69998. currentTotal += values[x][y];
  69999. rescaleAllValues ((float) (desiredTotalSum / currentTotal));
  70000. }
  70001. void ImageConvolutionKernel::rescaleAllValues (const float multiplier) throw()
  70002. {
  70003. for (int y = size; --y >= 0;)
  70004. for (int x = size; --x >= 0;)
  70005. values[x][y] *= multiplier;
  70006. }
  70007. void ImageConvolutionKernel::createGaussianBlur (const float radius) throw()
  70008. {
  70009. const double radiusFactor = -1.0 / (radius * radius * 2);
  70010. const int centre = size >> 1;
  70011. for (int y = size; --y >= 0;)
  70012. {
  70013. for (int x = size; --x >= 0;)
  70014. {
  70015. const int cx = x - centre;
  70016. const int cy = y - centre;
  70017. values[x][y] = (float) exp (radiusFactor * (cx * cx + cy * cy));
  70018. }
  70019. }
  70020. setOverallSum (1.0f);
  70021. }
  70022. void ImageConvolutionKernel::applyToImage (Image& destImage,
  70023. const Image* sourceImage,
  70024. int dx,
  70025. int dy,
  70026. int dw,
  70027. int dh) const
  70028. {
  70029. Image* imageCreated = 0;
  70030. if (sourceImage == 0)
  70031. {
  70032. sourceImage = imageCreated = destImage.createCopy();
  70033. }
  70034. else
  70035. {
  70036. jassert (sourceImage->getWidth() == destImage.getWidth()
  70037. && sourceImage->getHeight() == destImage.getHeight()
  70038. && sourceImage->getFormat() == destImage.getFormat());
  70039. if (sourceImage->getWidth() != destImage.getWidth()
  70040. || sourceImage->getHeight() != destImage.getHeight()
  70041. || sourceImage->getFormat() != destImage.getFormat())
  70042. return;
  70043. }
  70044. const int imageWidth = destImage.getWidth();
  70045. const int imageHeight = destImage.getHeight();
  70046. if (dx >= imageWidth || dy >= imageHeight)
  70047. return;
  70048. if (dx + dw > imageWidth)
  70049. dw = imageWidth - dx;
  70050. if (dy + dh > imageHeight)
  70051. dh = imageHeight - dy;
  70052. const int dx2 = dx + dw;
  70053. const int dy2 = dy + dh;
  70054. int lineStride, pixelStride;
  70055. uint8* pixels = destImage.lockPixelDataReadWrite (dx, dy, dw, dh, lineStride, pixelStride);
  70056. uint8* line = pixels;
  70057. int srcLineStride, srcPixelStride;
  70058. const uint8* srcPixels = sourceImage->lockPixelDataReadOnly (0, 0, sourceImage->getWidth(), sourceImage->getHeight(), srcLineStride, srcPixelStride);
  70059. if (pixelStride == 4)
  70060. {
  70061. for (int y = dy; y < dy2; ++y)
  70062. {
  70063. uint8* dest = line;
  70064. line += lineStride;
  70065. for (int x = dx; x < dx2; ++x)
  70066. {
  70067. float c1 = 0;
  70068. float c2 = 0;
  70069. float c3 = 0;
  70070. float c4 = 0;
  70071. for (int yy = 0; yy < size; ++yy)
  70072. {
  70073. const int sy = y + yy - (size >> 1);
  70074. if (sy >= imageHeight)
  70075. break;
  70076. if (sy >= 0)
  70077. {
  70078. int sx = x - (size >> 1);
  70079. const uint8* src = srcPixels + srcLineStride * sy + srcPixelStride * sx;
  70080. for (int xx = 0; xx < size; ++xx)
  70081. {
  70082. if (sx >= imageWidth)
  70083. break;
  70084. if (sx >= 0)
  70085. {
  70086. const float kernelMult = values[xx][yy];
  70087. c1 += kernelMult * *src++;
  70088. c2 += kernelMult * *src++;
  70089. c3 += kernelMult * *src++;
  70090. c4 += kernelMult * *src++;
  70091. }
  70092. else
  70093. {
  70094. src += 4;
  70095. }
  70096. ++sx;
  70097. }
  70098. }
  70099. }
  70100. *dest++ = (uint8) jmin (0xff, roundFloatToInt (c1));
  70101. *dest++ = (uint8) jmin (0xff, roundFloatToInt (c2));
  70102. *dest++ = (uint8) jmin (0xff, roundFloatToInt (c3));
  70103. *dest++ = (uint8) jmin (0xff, roundFloatToInt (c4));
  70104. }
  70105. }
  70106. }
  70107. else if (pixelStride == 3)
  70108. {
  70109. for (int y = dy; y < dy2; ++y)
  70110. {
  70111. uint8* dest = line;
  70112. line += lineStride;
  70113. for (int x = dx; x < dx2; ++x)
  70114. {
  70115. float c1 = 0;
  70116. float c2 = 0;
  70117. float c3 = 0;
  70118. for (int yy = 0; yy < size; ++yy)
  70119. {
  70120. const int sy = y + yy - (size >> 1);
  70121. if (sy >= imageHeight)
  70122. break;
  70123. if (sy >= 0)
  70124. {
  70125. int sx = x - (size >> 1);
  70126. const uint8* src = srcPixels + srcLineStride * sy + srcPixelStride * sx;
  70127. for (int xx = 0; xx < size; ++xx)
  70128. {
  70129. if (sx >= imageWidth)
  70130. break;
  70131. if (sx >= 0)
  70132. {
  70133. const float kernelMult = values[xx][yy];
  70134. c1 += kernelMult * *src++;
  70135. c2 += kernelMult * *src++;
  70136. c3 += kernelMult * *src++;
  70137. }
  70138. else
  70139. {
  70140. src += 3;
  70141. }
  70142. ++sx;
  70143. }
  70144. }
  70145. }
  70146. *dest++ = (uint8) roundFloatToInt (c1);
  70147. *dest++ = (uint8) roundFloatToInt (c2);
  70148. *dest++ = (uint8) roundFloatToInt (c3);
  70149. }
  70150. }
  70151. }
  70152. sourceImage->releasePixelDataReadOnly (srcPixels);
  70153. destImage.releasePixelDataReadWrite (pixels);
  70154. if (imageCreated != 0)
  70155. delete imageCreated;
  70156. }
  70157. END_JUCE_NAMESPACE
  70158. /********* End of inlined file: juce_ImageConvolutionKernel.cpp *********/
  70159. /********* Start of inlined file: juce_ImageFileFormat.cpp *********/
  70160. BEGIN_JUCE_NAMESPACE
  70161. /********* Start of inlined file: juce_GIFLoader.h *********/
  70162. #ifndef __JUCE_GIFLOADER_JUCEHEADER__
  70163. #define __JUCE_GIFLOADER_JUCEHEADER__
  70164. #ifndef DOXYGEN
  70165. static const int maxGifCode = 1 << 12;
  70166. /**
  70167. Used internally by ImageFileFormat - don't use this class directly in your
  70168. application.
  70169. @see ImageFileFormat
  70170. */
  70171. class GIFLoader
  70172. {
  70173. public:
  70174. GIFLoader (InputStream& in);
  70175. ~GIFLoader() throw();
  70176. Image* getImage() const throw() { return image; }
  70177. private:
  70178. Image* image;
  70179. InputStream& input;
  70180. uint8 buffer [300];
  70181. uint8 palette [256][4];
  70182. bool dataBlockIsZero, fresh, finished;
  70183. int currentBit, lastBit, lastByteIndex;
  70184. int codeSize, setCodeSize;
  70185. int maxCode, maxCodeSize;
  70186. int firstcode, oldcode;
  70187. int clearCode, end_code;
  70188. int table [2] [maxGifCode];
  70189. int stack [2 * maxGifCode];
  70190. int *sp;
  70191. bool getSizeFromHeader (int& width, int& height);
  70192. bool readPalette (const int numCols);
  70193. int readDataBlock (unsigned char* dest);
  70194. int processExtension (int type, int& transparent);
  70195. int readLZWByte (bool initialise, int input_code_size);
  70196. int getCode (int code_size, bool initialise);
  70197. bool readImage (int width, int height,
  70198. int interlace, int transparent);
  70199. GIFLoader (const GIFLoader&);
  70200. const GIFLoader& operator= (const GIFLoader&);
  70201. };
  70202. #endif // DOXYGEN
  70203. #endif // __JUCE_GIFLOADER_JUCEHEADER__
  70204. /********* End of inlined file: juce_GIFLoader.h *********/
  70205. Image* juce_loadPNGImageFromStream (InputStream& inputStream) throw();
  70206. bool juce_writePNGImageToStream (const Image& image, OutputStream& out) throw();
  70207. PNGImageFormat::PNGImageFormat() throw() {}
  70208. PNGImageFormat::~PNGImageFormat() throw() {}
  70209. const String PNGImageFormat::getFormatName()
  70210. {
  70211. return T("PNG");
  70212. }
  70213. bool PNGImageFormat::canUnderstand (InputStream& in)
  70214. {
  70215. const int bytesNeeded = 4;
  70216. char header [bytesNeeded];
  70217. return in.read (header, bytesNeeded) == bytesNeeded
  70218. && header[1] == 'P'
  70219. && header[2] == 'N'
  70220. && header[3] == 'G';
  70221. }
  70222. Image* PNGImageFormat::decodeImage (InputStream& in)
  70223. {
  70224. return juce_loadPNGImageFromStream (in);
  70225. }
  70226. bool PNGImageFormat::writeImageToStream (const Image& sourceImage,
  70227. OutputStream& destStream)
  70228. {
  70229. return juce_writePNGImageToStream (sourceImage, destStream);
  70230. }
  70231. Image* juce_loadJPEGImageFromStream (InputStream& inputStream) throw();
  70232. bool juce_writeJPEGImageToStream (const Image& image, OutputStream& out, float quality) throw();
  70233. JPEGImageFormat::JPEGImageFormat() throw()
  70234. : quality (-1.0f)
  70235. {
  70236. }
  70237. JPEGImageFormat::~JPEGImageFormat() throw() {}
  70238. void JPEGImageFormat::setQuality (const float newQuality)
  70239. {
  70240. quality = newQuality;
  70241. }
  70242. const String JPEGImageFormat::getFormatName()
  70243. {
  70244. return T("JPEG");
  70245. }
  70246. bool JPEGImageFormat::canUnderstand (InputStream& in)
  70247. {
  70248. const int bytesNeeded = 10;
  70249. uint8 header [bytesNeeded];
  70250. if (in.read (header, bytesNeeded) == bytesNeeded)
  70251. {
  70252. return header[0] == 0xff
  70253. && header[1] == 0xd8
  70254. && header[2] == 0xff
  70255. && (header[3] == 0xe0 || header[3] == 0xe1);
  70256. }
  70257. return false;
  70258. }
  70259. Image* JPEGImageFormat::decodeImage (InputStream& in)
  70260. {
  70261. return juce_loadJPEGImageFromStream (in);
  70262. }
  70263. bool JPEGImageFormat::writeImageToStream (const Image& sourceImage,
  70264. OutputStream& destStream)
  70265. {
  70266. return juce_writeJPEGImageToStream (sourceImage, destStream, quality);
  70267. }
  70268. class GIFImageFormat : public ImageFileFormat
  70269. {
  70270. public:
  70271. GIFImageFormat() throw() {}
  70272. ~GIFImageFormat() throw() {}
  70273. const String getFormatName()
  70274. {
  70275. return T("GIF");
  70276. }
  70277. bool canUnderstand (InputStream& in)
  70278. {
  70279. const int bytesNeeded = 4;
  70280. char header [bytesNeeded];
  70281. return (in.read (header, bytesNeeded) == bytesNeeded)
  70282. && header[0] == 'G'
  70283. && header[1] == 'I'
  70284. && header[2] == 'F';
  70285. }
  70286. Image* decodeImage (InputStream& in)
  70287. {
  70288. GIFLoader* const loader = new GIFLoader (in);
  70289. Image* const im = loader->getImage();
  70290. delete loader;
  70291. return im;
  70292. }
  70293. bool writeImageToStream (const Image& /*sourceImage*/, OutputStream& /*destStream*/)
  70294. {
  70295. return false;
  70296. }
  70297. };
  70298. ImageFileFormat* ImageFileFormat::findImageFormatForStream (InputStream& input)
  70299. {
  70300. static PNGImageFormat png;
  70301. static JPEGImageFormat jpg;
  70302. static GIFImageFormat gif;
  70303. ImageFileFormat* formats[4];
  70304. int numFormats = 0;
  70305. formats [numFormats++] = &png;
  70306. formats [numFormats++] = &jpg;
  70307. formats [numFormats++] = &gif;
  70308. const int64 streamPos = input.getPosition();
  70309. for (int i = 0; i < numFormats; ++i)
  70310. {
  70311. const bool found = formats[i]->canUnderstand (input);
  70312. input.setPosition (streamPos);
  70313. if (found)
  70314. return formats[i];
  70315. }
  70316. return 0;
  70317. }
  70318. Image* ImageFileFormat::loadFrom (InputStream& input)
  70319. {
  70320. ImageFileFormat* const format = findImageFormatForStream (input);
  70321. if (format != 0)
  70322. return format->decodeImage (input);
  70323. return 0;
  70324. }
  70325. Image* ImageFileFormat::loadFrom (const File& file)
  70326. {
  70327. InputStream* const in = file.createInputStream();
  70328. if (in != 0)
  70329. {
  70330. BufferedInputStream b (in, 8192, true);
  70331. return loadFrom (b);
  70332. }
  70333. return 0;
  70334. }
  70335. Image* ImageFileFormat::loadFrom (const void* rawData, const int numBytes)
  70336. {
  70337. if (rawData != 0 && numBytes > 4)
  70338. {
  70339. MemoryInputStream stream (rawData, numBytes, false);
  70340. return loadFrom (stream);
  70341. }
  70342. return 0;
  70343. }
  70344. END_JUCE_NAMESPACE
  70345. /********* End of inlined file: juce_ImageFileFormat.cpp *********/
  70346. /********* Start of inlined file: juce_GIFLoader.cpp *********/
  70347. BEGIN_JUCE_NAMESPACE
  70348. static inline int makeWord (const unsigned char a, const unsigned char b) throw()
  70349. {
  70350. return (b << 8) | a;
  70351. }
  70352. GIFLoader::GIFLoader (InputStream& in)
  70353. : image (0),
  70354. input (in),
  70355. dataBlockIsZero (false),
  70356. fresh (false),
  70357. finished (false)
  70358. {
  70359. currentBit = lastBit = lastByteIndex = 0;
  70360. maxCode = maxCodeSize = codeSize = setCodeSize = 0;
  70361. firstcode = oldcode = 0;
  70362. clearCode = end_code = 0;
  70363. int imageWidth, imageHeight;
  70364. int transparent = -1;
  70365. if (! getSizeFromHeader (imageWidth, imageHeight))
  70366. return;
  70367. if ((imageWidth <= 0) || (imageHeight <= 0))
  70368. return;
  70369. unsigned char buf [16];
  70370. if (in.read (buf, 3) != 3)
  70371. return;
  70372. int numColours = 2 << (buf[0] & 7);
  70373. if ((buf[0] & 0x80) != 0)
  70374. readPalette (numColours);
  70375. for (;;)
  70376. {
  70377. if (input.read (buf, 1) != 1)
  70378. break;
  70379. if (buf[0] == ';')
  70380. break;
  70381. if (buf[0] == '!')
  70382. {
  70383. if (input.read (buf, 1) != 1)
  70384. break;
  70385. if (processExtension (buf[0], transparent) < 0)
  70386. break;
  70387. continue;
  70388. }
  70389. if (buf[0] != ',')
  70390. continue;
  70391. if (input.read (buf, 9) != 9)
  70392. break;
  70393. imageWidth = makeWord (buf[4], buf[5]);
  70394. imageHeight = makeWord (buf[6], buf[7]);
  70395. numColours = 2 << (buf[8] & 7);
  70396. if ((buf[8] & 0x80) != 0)
  70397. if (! readPalette (numColours))
  70398. break;
  70399. image = new Image ((transparent >= 0) ? Image::ARGB : Image::RGB,
  70400. imageWidth, imageHeight, (transparent >= 0));
  70401. readImage (imageWidth, imageHeight,
  70402. (buf[8] & 0x40) != 0,
  70403. transparent);
  70404. break;
  70405. }
  70406. }
  70407. GIFLoader::~GIFLoader() throw()
  70408. {
  70409. }
  70410. bool GIFLoader::getSizeFromHeader (int& w, int& h)
  70411. {
  70412. unsigned char b [8];
  70413. if (input.read (b, 6) == 6)
  70414. {
  70415. if ((strncmp ("GIF87a", (char*) b, 6) == 0)
  70416. || (strncmp ("GIF89a", (char*) b, 6) == 0))
  70417. {
  70418. if (input.read (b, 4) == 4)
  70419. {
  70420. w = makeWord (b[0], b[1]);
  70421. h = makeWord (b[2], b[3]);
  70422. return true;
  70423. }
  70424. }
  70425. }
  70426. return false;
  70427. }
  70428. bool GIFLoader::readPalette (const int numCols)
  70429. {
  70430. unsigned char rgb[4];
  70431. for (int i = 0; i < numCols; ++i)
  70432. {
  70433. input.read (rgb, 3);
  70434. palette [i][0] = rgb[0];
  70435. palette [i][1] = rgb[1];
  70436. palette [i][2] = rgb[2];
  70437. palette [i][3] = 0xff;
  70438. }
  70439. return true;
  70440. }
  70441. int GIFLoader::readDataBlock (unsigned char* const dest)
  70442. {
  70443. unsigned char n;
  70444. if (input.read (&n, 1) == 1)
  70445. {
  70446. dataBlockIsZero = (n == 0);
  70447. if (dataBlockIsZero || (input.read (dest, n) == n))
  70448. return n;
  70449. }
  70450. return -1;
  70451. }
  70452. int GIFLoader::processExtension (const int type, int& transparent)
  70453. {
  70454. unsigned char b [300];
  70455. int n = 0;
  70456. if (type == 0xf9)
  70457. {
  70458. n = readDataBlock (b);
  70459. if (n < 0)
  70460. return 1;
  70461. if ((b[0] & 0x1) != 0)
  70462. transparent = b[3];
  70463. }
  70464. do
  70465. {
  70466. n = readDataBlock (b);
  70467. }
  70468. while (n > 0);
  70469. return n;
  70470. }
  70471. int GIFLoader::getCode (const int codeSize, const bool initialise)
  70472. {
  70473. if (initialise)
  70474. {
  70475. currentBit = 0;
  70476. lastBit = 0;
  70477. finished = false;
  70478. return 0;
  70479. }
  70480. if ((currentBit + codeSize) >= lastBit)
  70481. {
  70482. if (finished)
  70483. return -1;
  70484. buffer[0] = buffer [lastByteIndex - 2];
  70485. buffer[1] = buffer [lastByteIndex - 1];
  70486. const int n = readDataBlock (&buffer[2]);
  70487. if (n == 0)
  70488. finished = true;
  70489. lastByteIndex = 2 + n;
  70490. currentBit = (currentBit - lastBit) + 16;
  70491. lastBit = (2 + n) * 8 ;
  70492. }
  70493. int result = 0;
  70494. int i = currentBit;
  70495. for (int j = 0; j < codeSize; ++j)
  70496. {
  70497. result |= ((buffer[i >> 3] & (1 << (i & 7))) != 0) << j;
  70498. ++i;
  70499. }
  70500. currentBit += codeSize;
  70501. return result;
  70502. }
  70503. int GIFLoader::readLZWByte (const bool initialise, const int inputCodeSize)
  70504. {
  70505. int code, incode, i;
  70506. if (initialise)
  70507. {
  70508. setCodeSize = inputCodeSize;
  70509. codeSize = setCodeSize + 1;
  70510. clearCode = 1 << setCodeSize;
  70511. end_code = clearCode + 1;
  70512. maxCodeSize = 2 * clearCode;
  70513. maxCode = clearCode + 2;
  70514. getCode (0, true);
  70515. fresh = true;
  70516. for (i = 0; i < clearCode; ++i)
  70517. {
  70518. table[0][i] = 0;
  70519. table[1][i] = i;
  70520. }
  70521. for (; i < maxGifCode; ++i)
  70522. {
  70523. table[0][i] = 0;
  70524. table[1][i] = 0;
  70525. }
  70526. sp = stack;
  70527. return 0;
  70528. }
  70529. else if (fresh)
  70530. {
  70531. fresh = false;
  70532. do
  70533. {
  70534. firstcode = oldcode
  70535. = getCode (codeSize, false);
  70536. }
  70537. while (firstcode == clearCode);
  70538. return firstcode;
  70539. }
  70540. if (sp > stack)
  70541. return *--sp;
  70542. while ((code = getCode (codeSize, false)) >= 0)
  70543. {
  70544. if (code == clearCode)
  70545. {
  70546. for (i = 0; i < clearCode; ++i)
  70547. {
  70548. table[0][i] = 0;
  70549. table[1][i] = i;
  70550. }
  70551. for (; i < maxGifCode; ++i)
  70552. {
  70553. table[0][i] = 0;
  70554. table[1][i] = 0;
  70555. }
  70556. codeSize = setCodeSize + 1;
  70557. maxCodeSize = 2 * clearCode;
  70558. maxCode = clearCode + 2;
  70559. sp = stack;
  70560. firstcode = oldcode = getCode (codeSize, false);
  70561. return firstcode;
  70562. }
  70563. else if (code == end_code)
  70564. {
  70565. if (dataBlockIsZero)
  70566. return -2;
  70567. unsigned char buf [260];
  70568. int n;
  70569. while ((n = readDataBlock (buf)) > 0)
  70570. {}
  70571. if (n != 0)
  70572. return -2;
  70573. }
  70574. incode = code;
  70575. if (code >= maxCode)
  70576. {
  70577. *sp++ = firstcode;
  70578. code = oldcode;
  70579. }
  70580. while (code >= clearCode)
  70581. {
  70582. *sp++ = table[1][code];
  70583. if (code == table[0][code])
  70584. return -2;
  70585. code = table[0][code];
  70586. }
  70587. *sp++ = firstcode = table[1][code];
  70588. if ((code = maxCode) < maxGifCode)
  70589. {
  70590. table[0][code] = oldcode;
  70591. table[1][code] = firstcode;
  70592. ++maxCode;
  70593. if ((maxCode >= maxCodeSize)
  70594. && (maxCodeSize < maxGifCode))
  70595. {
  70596. maxCodeSize <<= 1;
  70597. ++codeSize;
  70598. }
  70599. }
  70600. oldcode = incode;
  70601. if (sp > stack)
  70602. return *--sp;
  70603. }
  70604. return code;
  70605. }
  70606. bool GIFLoader::readImage (const int width, const int height,
  70607. const int interlace, const int transparent)
  70608. {
  70609. unsigned char c;
  70610. if (input.read (&c, 1) != 1
  70611. || readLZWByte (true, c) < 0)
  70612. return false;
  70613. if (transparent >= 0)
  70614. {
  70615. palette [transparent][0] = 0;
  70616. palette [transparent][1] = 0;
  70617. palette [transparent][2] = 0;
  70618. palette [transparent][3] = 0;
  70619. }
  70620. int index;
  70621. int xpos = 0, ypos = 0, pass = 0;
  70622. int stride, pixelStride;
  70623. uint8* const pixels = image->lockPixelDataReadWrite (0, 0, width, height, stride, pixelStride);
  70624. uint8* p = pixels;
  70625. const bool hasAlpha = image->hasAlphaChannel();
  70626. while ((index = readLZWByte (false, c)) >= 0)
  70627. {
  70628. const uint8* const paletteEntry = palette [index];
  70629. if (hasAlpha)
  70630. {
  70631. ((PixelARGB*) p)->setARGB (paletteEntry[3],
  70632. paletteEntry[0],
  70633. paletteEntry[1],
  70634. paletteEntry[2]);
  70635. ((PixelARGB*) p)->premultiply();
  70636. p += pixelStride;
  70637. }
  70638. else
  70639. {
  70640. ((PixelRGB*) p)->setARGB (0,
  70641. paletteEntry[0],
  70642. paletteEntry[1],
  70643. paletteEntry[2]);
  70644. p += pixelStride;
  70645. }
  70646. ++xpos;
  70647. if (xpos == width)
  70648. {
  70649. xpos = 0;
  70650. if (interlace)
  70651. {
  70652. switch (pass)
  70653. {
  70654. case 0:
  70655. case 1:
  70656. ypos += 8;
  70657. break;
  70658. case 2:
  70659. ypos += 4;
  70660. break;
  70661. case 3:
  70662. ypos += 2;
  70663. break;
  70664. }
  70665. while (ypos >= height)
  70666. {
  70667. ++pass;
  70668. switch (pass)
  70669. {
  70670. case 1:
  70671. ypos = 4;
  70672. break;
  70673. case 2:
  70674. ypos = 2;
  70675. break;
  70676. case 3:
  70677. ypos = 1;
  70678. break;
  70679. default:
  70680. return true;
  70681. }
  70682. }
  70683. }
  70684. else
  70685. {
  70686. ++ypos;
  70687. }
  70688. p = pixels + xpos * pixelStride + ypos * stride;
  70689. }
  70690. if (ypos >= height)
  70691. break;
  70692. }
  70693. image->releasePixelDataReadWrite (pixels);
  70694. return true;
  70695. }
  70696. END_JUCE_NAMESPACE
  70697. /********* End of inlined file: juce_GIFLoader.cpp *********/
  70698. #endif
  70699. //==============================================================================
  70700. // some files include lots of library code, so leave them to the end to avoid cluttering
  70701. // up the build for the clean files.
  70702. /********* Start of inlined file: juce_GZIPCompressorOutputStream.cpp *********/
  70703. namespace zlibNamespace
  70704. {
  70705. #undef OS_CODE
  70706. #undef fdopen
  70707. /********* Start of inlined file: zlib.h *********/
  70708. #ifndef ZLIB_H
  70709. #define ZLIB_H
  70710. /********* Start of inlined file: zconf.h *********/
  70711. /* @(#) $Id: zconf.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  70712. #ifndef ZCONF_H
  70713. #define ZCONF_H
  70714. // *** Just a few hacks here to make it compile nicely with Juce..
  70715. #define Z_PREFIX 1
  70716. #undef __MACTYPES__
  70717. #ifdef _MSC_VER
  70718. #pragma warning (disable : 4131 4127 4244 4267)
  70719. #endif
  70720. /*
  70721. * If you *really* need a unique prefix for all types and library functions,
  70722. * compile with -DZ_PREFIX. The "standard" zlib should be compiled without it.
  70723. */
  70724. #ifdef Z_PREFIX
  70725. # define deflateInit_ z_deflateInit_
  70726. # define deflate z_deflate
  70727. # define deflateEnd z_deflateEnd
  70728. # define inflateInit_ z_inflateInit_
  70729. # define inflate z_inflate
  70730. # define inflateEnd z_inflateEnd
  70731. # define deflateInit2_ z_deflateInit2_
  70732. # define deflateSetDictionary z_deflateSetDictionary
  70733. # define deflateCopy z_deflateCopy
  70734. # define deflateReset z_deflateReset
  70735. # define deflateParams z_deflateParams
  70736. # define deflateBound z_deflateBound
  70737. # define deflatePrime z_deflatePrime
  70738. # define inflateInit2_ z_inflateInit2_
  70739. # define inflateSetDictionary z_inflateSetDictionary
  70740. # define inflateSync z_inflateSync
  70741. # define inflateSyncPoint z_inflateSyncPoint
  70742. # define inflateCopy z_inflateCopy
  70743. # define inflateReset z_inflateReset
  70744. # define inflateBack z_inflateBack
  70745. # define inflateBackEnd z_inflateBackEnd
  70746. # define compress z_compress
  70747. # define compress2 z_compress2
  70748. # define compressBound z_compressBound
  70749. # define uncompress z_uncompress
  70750. # define adler32 z_adler32
  70751. # define crc32 z_crc32
  70752. # define get_crc_table z_get_crc_table
  70753. # define zError z_zError
  70754. # define alloc_func z_alloc_func
  70755. # define free_func z_free_func
  70756. # define in_func z_in_func
  70757. # define out_func z_out_func
  70758. # define Byte z_Byte
  70759. # define uInt z_uInt
  70760. # define uLong z_uLong
  70761. # define Bytef z_Bytef
  70762. # define charf z_charf
  70763. # define intf z_intf
  70764. # define uIntf z_uIntf
  70765. # define uLongf z_uLongf
  70766. # define voidpf z_voidpf
  70767. # define voidp z_voidp
  70768. #endif
  70769. #if defined(__MSDOS__) && !defined(MSDOS)
  70770. # define MSDOS
  70771. #endif
  70772. #if (defined(OS_2) || defined(__OS2__)) && !defined(OS2)
  70773. # define OS2
  70774. #endif
  70775. #if defined(_WINDOWS) && !defined(WINDOWS)
  70776. # define WINDOWS
  70777. #endif
  70778. #if defined(_WIN32) || defined(_WIN32_WCE) || defined(__WIN32__)
  70779. # ifndef WIN32
  70780. # define WIN32
  70781. # endif
  70782. #endif
  70783. #if (defined(MSDOS) || defined(OS2) || defined(WINDOWS)) && !defined(WIN32)
  70784. # if !defined(__GNUC__) && !defined(__FLAT__) && !defined(__386__)
  70785. # ifndef SYS16BIT
  70786. # define SYS16BIT
  70787. # endif
  70788. # endif
  70789. #endif
  70790. /*
  70791. * Compile with -DMAXSEG_64K if the alloc function cannot allocate more
  70792. * than 64k bytes at a time (needed on systems with 16-bit int).
  70793. */
  70794. #ifdef SYS16BIT
  70795. # define MAXSEG_64K
  70796. #endif
  70797. #ifdef MSDOS
  70798. # define UNALIGNED_OK
  70799. #endif
  70800. #ifdef __STDC_VERSION__
  70801. # ifndef STDC
  70802. # define STDC
  70803. # endif
  70804. # if __STDC_VERSION__ >= 199901L
  70805. # ifndef STDC99
  70806. # define STDC99
  70807. # endif
  70808. # endif
  70809. #endif
  70810. #if !defined(STDC) && (defined(__STDC__) || defined(__cplusplus))
  70811. # define STDC
  70812. #endif
  70813. #if !defined(STDC) && (defined(__GNUC__) || defined(__BORLANDC__))
  70814. # define STDC
  70815. #endif
  70816. #if !defined(STDC) && (defined(MSDOS) || defined(WINDOWS) || defined(WIN32))
  70817. # define STDC
  70818. #endif
  70819. #if !defined(STDC) && (defined(OS2) || defined(__HOS_AIX__))
  70820. # define STDC
  70821. #endif
  70822. #if defined(__OS400__) && !defined(STDC) /* iSeries (formerly AS/400). */
  70823. # define STDC
  70824. #endif
  70825. #ifndef STDC
  70826. # ifndef const /* cannot use !defined(STDC) && !defined(const) on Mac */
  70827. # define const /* note: need a more gentle solution here */
  70828. # endif
  70829. #endif
  70830. /* Some Mac compilers merge all .h files incorrectly: */
  70831. #if defined(__MWERKS__)||defined(applec)||defined(THINK_C)||defined(__SC__)
  70832. # define NO_DUMMY_DECL
  70833. #endif
  70834. /* Maximum value for memLevel in deflateInit2 */
  70835. #ifndef MAX_MEM_LEVEL
  70836. # ifdef MAXSEG_64K
  70837. # define MAX_MEM_LEVEL 8
  70838. # else
  70839. # define MAX_MEM_LEVEL 9
  70840. # endif
  70841. #endif
  70842. /* Maximum value for windowBits in deflateInit2 and inflateInit2.
  70843. * WARNING: reducing MAX_WBITS makes minigzip unable to extract .gz files
  70844. * created by gzip. (Files created by minigzip can still be extracted by
  70845. * gzip.)
  70846. */
  70847. #ifndef MAX_WBITS
  70848. # define MAX_WBITS 15 /* 32K LZ77 window */
  70849. #endif
  70850. /* The memory requirements for deflate are (in bytes):
  70851. (1 << (windowBits+2)) + (1 << (memLevel+9))
  70852. that is: 128K for windowBits=15 + 128K for memLevel = 8 (default values)
  70853. plus a few kilobytes for small objects. For example, if you want to reduce
  70854. the default memory requirements from 256K to 128K, compile with
  70855. make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7"
  70856. Of course this will generally degrade compression (there's no free lunch).
  70857. The memory requirements for inflate are (in bytes) 1 << windowBits
  70858. that is, 32K for windowBits=15 (default value) plus a few kilobytes
  70859. for small objects.
  70860. */
  70861. /* Type declarations */
  70862. #ifndef OF /* function prototypes */
  70863. # ifdef STDC
  70864. # define OF(args) args
  70865. # else
  70866. # define OF(args) ()
  70867. # endif
  70868. #endif
  70869. /* The following definitions for FAR are needed only for MSDOS mixed
  70870. * model programming (small or medium model with some far allocations).
  70871. * This was tested only with MSC; for other MSDOS compilers you may have
  70872. * to define NO_MEMCPY in zutil.h. If you don't need the mixed model,
  70873. * just define FAR to be empty.
  70874. */
  70875. #ifdef SYS16BIT
  70876. # if defined(M_I86SM) || defined(M_I86MM)
  70877. /* MSC small or medium model */
  70878. # define SMALL_MEDIUM
  70879. # ifdef _MSC_VER
  70880. # define FAR _far
  70881. # else
  70882. # define FAR far
  70883. # endif
  70884. # endif
  70885. # if (defined(__SMALL__) || defined(__MEDIUM__))
  70886. /* Turbo C small or medium model */
  70887. # define SMALL_MEDIUM
  70888. # ifdef __BORLANDC__
  70889. # define FAR _far
  70890. # else
  70891. # define FAR far
  70892. # endif
  70893. # endif
  70894. #endif
  70895. #if defined(WINDOWS) || defined(WIN32)
  70896. /* If building or using zlib as a DLL, define ZLIB_DLL.
  70897. * This is not mandatory, but it offers a little performance increase.
  70898. */
  70899. # ifdef ZLIB_DLL
  70900. # if defined(WIN32) && (!defined(__BORLANDC__) || (__BORLANDC__ >= 0x500))
  70901. # ifdef ZLIB_INTERNAL
  70902. # define ZEXTERN extern __declspec(dllexport)
  70903. # else
  70904. # define ZEXTERN extern __declspec(dllimport)
  70905. # endif
  70906. # endif
  70907. # endif /* ZLIB_DLL */
  70908. /* If building or using zlib with the WINAPI/WINAPIV calling convention,
  70909. * define ZLIB_WINAPI.
  70910. * Caution: the standard ZLIB1.DLL is NOT compiled using ZLIB_WINAPI.
  70911. */
  70912. # ifdef ZLIB_WINAPI
  70913. # ifdef FAR
  70914. # undef FAR
  70915. # endif
  70916. # include <windows.h>
  70917. /* No need for _export, use ZLIB.DEF instead. */
  70918. /* For complete Windows compatibility, use WINAPI, not __stdcall. */
  70919. # define ZEXPORT WINAPI
  70920. # ifdef WIN32
  70921. # define ZEXPORTVA WINAPIV
  70922. # else
  70923. # define ZEXPORTVA FAR CDECL
  70924. # endif
  70925. # endif
  70926. #endif
  70927. #if defined (__BEOS__)
  70928. # ifdef ZLIB_DLL
  70929. # ifdef ZLIB_INTERNAL
  70930. # define ZEXPORT __declspec(dllexport)
  70931. # define ZEXPORTVA __declspec(dllexport)
  70932. # else
  70933. # define ZEXPORT __declspec(dllimport)
  70934. # define ZEXPORTVA __declspec(dllimport)
  70935. # endif
  70936. # endif
  70937. #endif
  70938. #ifndef ZEXTERN
  70939. # define ZEXTERN extern
  70940. #endif
  70941. #ifndef ZEXPORT
  70942. # define ZEXPORT
  70943. #endif
  70944. #ifndef ZEXPORTVA
  70945. # define ZEXPORTVA
  70946. #endif
  70947. #ifndef FAR
  70948. # define FAR
  70949. #endif
  70950. #if !defined(__MACTYPES__)
  70951. typedef unsigned char Byte; /* 8 bits */
  70952. #endif
  70953. typedef unsigned int uInt; /* 16 bits or more */
  70954. typedef unsigned long uLong; /* 32 bits or more */
  70955. #ifdef SMALL_MEDIUM
  70956. /* Borland C/C++ and some old MSC versions ignore FAR inside typedef */
  70957. # define Bytef Byte FAR
  70958. #else
  70959. typedef Byte FAR Bytef;
  70960. #endif
  70961. typedef char FAR charf;
  70962. typedef int FAR intf;
  70963. typedef uInt FAR uIntf;
  70964. typedef uLong FAR uLongf;
  70965. #ifdef STDC
  70966. typedef void const *voidpc;
  70967. typedef void FAR *voidpf;
  70968. typedef void *voidp;
  70969. #else
  70970. typedef Byte const *voidpc;
  70971. typedef Byte FAR *voidpf;
  70972. typedef Byte *voidp;
  70973. #endif
  70974. #if 0 /* HAVE_UNISTD_H -- this line is updated by ./configure */
  70975. # include <sys/types.h> /* for off_t */
  70976. # include <unistd.h> /* for SEEK_* and off_t */
  70977. # ifdef VMS
  70978. # include <unixio.h> /* for off_t */
  70979. # endif
  70980. # define z_off_t off_t
  70981. #endif
  70982. #ifndef SEEK_SET
  70983. # define SEEK_SET 0 /* Seek from beginning of file. */
  70984. # define SEEK_CUR 1 /* Seek from current position. */
  70985. # define SEEK_END 2 /* Set file pointer to EOF plus "offset" */
  70986. #endif
  70987. #ifndef z_off_t
  70988. # define z_off_t long
  70989. #endif
  70990. #if defined(__OS400__)
  70991. # define NO_vsnprintf
  70992. #endif
  70993. #if defined(__MVS__)
  70994. # define NO_vsnprintf
  70995. # ifdef FAR
  70996. # undef FAR
  70997. # endif
  70998. #endif
  70999. /* MVS linker does not support external names larger than 8 bytes */
  71000. #if defined(__MVS__)
  71001. # pragma map(deflateInit_,"DEIN")
  71002. # pragma map(deflateInit2_,"DEIN2")
  71003. # pragma map(deflateEnd,"DEEND")
  71004. # pragma map(deflateBound,"DEBND")
  71005. # pragma map(inflateInit_,"ININ")
  71006. # pragma map(inflateInit2_,"ININ2")
  71007. # pragma map(inflateEnd,"INEND")
  71008. # pragma map(inflateSync,"INSY")
  71009. # pragma map(inflateSetDictionary,"INSEDI")
  71010. # pragma map(compressBound,"CMBND")
  71011. # pragma map(inflate_table,"INTABL")
  71012. # pragma map(inflate_fast,"INFA")
  71013. # pragma map(inflate_copyright,"INCOPY")
  71014. #endif
  71015. #endif /* ZCONF_H */
  71016. /********* End of inlined file: zconf.h *********/
  71017. #ifdef __cplusplus
  71018. extern "C" {
  71019. #endif
  71020. #define ZLIB_VERSION "1.2.3"
  71021. #define ZLIB_VERNUM 0x1230
  71022. /*
  71023. The 'zlib' compression library provides in-memory compression and
  71024. decompression functions, including integrity checks of the uncompressed
  71025. data. This version of the library supports only one compression method
  71026. (deflation) but other algorithms will be added later and will have the same
  71027. stream interface.
  71028. Compression can be done in a single step if the buffers are large
  71029. enough (for example if an input file is mmap'ed), or can be done by
  71030. repeated calls of the compression function. In the latter case, the
  71031. application must provide more input and/or consume the output
  71032. (providing more output space) before each call.
  71033. The compressed data format used by default by the in-memory functions is
  71034. the zlib format, which is a zlib wrapper documented in RFC 1950, wrapped
  71035. around a deflate stream, which is itself documented in RFC 1951.
  71036. The library also supports reading and writing files in gzip (.gz) format
  71037. with an interface similar to that of stdio using the functions that start
  71038. with "gz". The gzip format is different from the zlib format. gzip is a
  71039. gzip wrapper, documented in RFC 1952, wrapped around a deflate stream.
  71040. This library can optionally read and write gzip streams in memory as well.
  71041. The zlib format was designed to be compact and fast for use in memory
  71042. and on communications channels. The gzip format was designed for single-
  71043. file compression on file systems, has a larger header than zlib to maintain
  71044. directory information, and uses a different, slower check method than zlib.
  71045. The library does not install any signal handler. The decoder checks
  71046. the consistency of the compressed data, so the library should never
  71047. crash even in case of corrupted input.
  71048. */
  71049. typedef voidpf (*alloc_func) OF((voidpf opaque, uInt items, uInt size));
  71050. typedef void (*free_func) OF((voidpf opaque, voidpf address));
  71051. struct internal_state;
  71052. typedef struct z_stream_s {
  71053. Bytef *next_in; /* next input byte */
  71054. uInt avail_in; /* number of bytes available at next_in */
  71055. uLong total_in; /* total nb of input bytes read so far */
  71056. Bytef *next_out; /* next output byte should be put there */
  71057. uInt avail_out; /* remaining free space at next_out */
  71058. uLong total_out; /* total nb of bytes output so far */
  71059. char *msg; /* last error message, NULL if no error */
  71060. struct internal_state FAR *state; /* not visible by applications */
  71061. alloc_func zalloc; /* used to allocate the internal state */
  71062. free_func zfree; /* used to free the internal state */
  71063. voidpf opaque; /* private data object passed to zalloc and zfree */
  71064. int data_type; /* best guess about the data type: binary or text */
  71065. uLong adler; /* adler32 value of the uncompressed data */
  71066. uLong reserved; /* reserved for future use */
  71067. } z_stream;
  71068. typedef z_stream FAR *z_streamp;
  71069. /*
  71070. gzip header information passed to and from zlib routines. See RFC 1952
  71071. for more details on the meanings of these fields.
  71072. */
  71073. typedef struct gz_header_s {
  71074. int text; /* true if compressed data believed to be text */
  71075. uLong time; /* modification time */
  71076. int xflags; /* extra flags (not used when writing a gzip file) */
  71077. int os; /* operating system */
  71078. Bytef *extra; /* pointer to extra field or Z_NULL if none */
  71079. uInt extra_len; /* extra field length (valid if extra != Z_NULL) */
  71080. uInt extra_max; /* space at extra (only when reading header) */
  71081. Bytef *name; /* pointer to zero-terminated file name or Z_NULL */
  71082. uInt name_max; /* space at name (only when reading header) */
  71083. Bytef *comment; /* pointer to zero-terminated comment or Z_NULL */
  71084. uInt comm_max; /* space at comment (only when reading header) */
  71085. int hcrc; /* true if there was or will be a header crc */
  71086. int done; /* true when done reading gzip header (not used
  71087. when writing a gzip file) */
  71088. } gz_header;
  71089. typedef gz_header FAR *gz_headerp;
  71090. /*
  71091. The application must update next_in and avail_in when avail_in has
  71092. dropped to zero. It must update next_out and avail_out when avail_out
  71093. has dropped to zero. The application must initialize zalloc, zfree and
  71094. opaque before calling the init function. All other fields are set by the
  71095. compression library and must not be updated by the application.
  71096. The opaque value provided by the application will be passed as the first
  71097. parameter for calls of zalloc and zfree. This can be useful for custom
  71098. memory management. The compression library attaches no meaning to the
  71099. opaque value.
  71100. zalloc must return Z_NULL if there is not enough memory for the object.
  71101. If zlib is used in a multi-threaded application, zalloc and zfree must be
  71102. thread safe.
  71103. On 16-bit systems, the functions zalloc and zfree must be able to allocate
  71104. exactly 65536 bytes, but will not be required to allocate more than this
  71105. if the symbol MAXSEG_64K is defined (see zconf.h). WARNING: On MSDOS,
  71106. pointers returned by zalloc for objects of exactly 65536 bytes *must*
  71107. have their offset normalized to zero. The default allocation function
  71108. provided by this library ensures this (see zutil.c). To reduce memory
  71109. requirements and avoid any allocation of 64K objects, at the expense of
  71110. compression ratio, compile the library with -DMAX_WBITS=14 (see zconf.h).
  71111. The fields total_in and total_out can be used for statistics or
  71112. progress reports. After compression, total_in holds the total size of
  71113. the uncompressed data and may be saved for use in the decompressor
  71114. (particularly if the decompressor wants to decompress everything in
  71115. a single step).
  71116. */
  71117. /* constants */
  71118. #define Z_NO_FLUSH 0
  71119. #define Z_PARTIAL_FLUSH 1 /* will be removed, use Z_SYNC_FLUSH instead */
  71120. #define Z_SYNC_FLUSH 2
  71121. #define Z_FULL_FLUSH 3
  71122. #define Z_FINISH 4
  71123. #define Z_BLOCK 5
  71124. /* Allowed flush values; see deflate() and inflate() below for details */
  71125. #define Z_OK 0
  71126. #define Z_STREAM_END 1
  71127. #define Z_NEED_DICT 2
  71128. #define Z_ERRNO (-1)
  71129. #define Z_STREAM_ERROR (-2)
  71130. #define Z_DATA_ERROR (-3)
  71131. #define Z_MEM_ERROR (-4)
  71132. #define Z_BUF_ERROR (-5)
  71133. #define Z_VERSION_ERROR (-6)
  71134. /* Return codes for the compression/decompression functions. Negative
  71135. * values are errors, positive values are used for special but normal events.
  71136. */
  71137. #define Z_NO_COMPRESSION 0
  71138. #define Z_BEST_SPEED 1
  71139. #define Z_BEST_COMPRESSION 9
  71140. #define Z_DEFAULT_COMPRESSION (-1)
  71141. /* compression levels */
  71142. #define Z_FILTERED 1
  71143. #define Z_HUFFMAN_ONLY 2
  71144. #define Z_RLE 3
  71145. #define Z_FIXED 4
  71146. #define Z_DEFAULT_STRATEGY 0
  71147. /* compression strategy; see deflateInit2() below for details */
  71148. #define Z_BINARY 0
  71149. #define Z_TEXT 1
  71150. #define Z_ASCII Z_TEXT /* for compatibility with 1.2.2 and earlier */
  71151. #define Z_UNKNOWN 2
  71152. /* Possible values of the data_type field (though see inflate()) */
  71153. #define Z_DEFLATED 8
  71154. /* The deflate compression method (the only one supported in this version) */
  71155. #define Z_NULL 0 /* for initializing zalloc, zfree, opaque */
  71156. #define zlib_version zlibVersion()
  71157. /* for compatibility with versions < 1.0.2 */
  71158. /* basic functions */
  71159. //ZEXTERN const char * ZEXPORT zlibVersion OF((void));
  71160. /* The application can compare zlibVersion and ZLIB_VERSION for consistency.
  71161. If the first character differs, the library code actually used is
  71162. not compatible with the zlib.h header file used by the application.
  71163. This check is automatically made by deflateInit and inflateInit.
  71164. */
  71165. /*
  71166. ZEXTERN int ZEXPORT deflateInit OF((z_streamp strm, int level));
  71167. Initializes the internal stream state for compression. The fields
  71168. zalloc, zfree and opaque must be initialized before by the caller.
  71169. If zalloc and zfree are set to Z_NULL, deflateInit updates them to
  71170. use default allocation functions.
  71171. The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9:
  71172. 1 gives best speed, 9 gives best compression, 0 gives no compression at
  71173. all (the input data is simply copied a block at a time).
  71174. Z_DEFAULT_COMPRESSION requests a default compromise between speed and
  71175. compression (currently equivalent to level 6).
  71176. deflateInit returns Z_OK if success, Z_MEM_ERROR if there was not
  71177. enough memory, Z_STREAM_ERROR if level is not a valid compression level,
  71178. Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible
  71179. with the version assumed by the caller (ZLIB_VERSION).
  71180. msg is set to null if there is no error message. deflateInit does not
  71181. perform any compression: this will be done by deflate().
  71182. */
  71183. ZEXTERN int ZEXPORT deflate OF((z_streamp strm, int flush));
  71184. /*
  71185. deflate compresses as much data as possible, and stops when the input
  71186. buffer becomes empty or the output buffer becomes full. It may introduce some
  71187. output latency (reading input without producing any output) except when
  71188. forced to flush.
  71189. The detailed semantics are as follows. deflate performs one or both of the
  71190. following actions:
  71191. - Compress more input starting at next_in and update next_in and avail_in
  71192. accordingly. If not all input can be processed (because there is not
  71193. enough room in the output buffer), next_in and avail_in are updated and
  71194. processing will resume at this point for the next call of deflate().
  71195. - Provide more output starting at next_out and update next_out and avail_out
  71196. accordingly. This action is forced if the parameter flush is non zero.
  71197. Forcing flush frequently degrades the compression ratio, so this parameter
  71198. should be set only when necessary (in interactive applications).
  71199. Some output may be provided even if flush is not set.
  71200. Before the call of deflate(), the application should ensure that at least
  71201. one of the actions is possible, by providing more input and/or consuming
  71202. more output, and updating avail_in or avail_out accordingly; avail_out
  71203. should never be zero before the call. The application can consume the
  71204. compressed output when it wants, for example when the output buffer is full
  71205. (avail_out == 0), or after each call of deflate(). If deflate returns Z_OK
  71206. and with zero avail_out, it must be called again after making room in the
  71207. output buffer because there might be more output pending.
  71208. Normally the parameter flush is set to Z_NO_FLUSH, which allows deflate to
  71209. decide how much data to accumualte before producing output, in order to
  71210. maximize compression.
  71211. If the parameter flush is set to Z_SYNC_FLUSH, all pending output is
  71212. flushed to the output buffer and the output is aligned on a byte boundary, so
  71213. that the decompressor can get all input data available so far. (In particular
  71214. avail_in is zero after the call if enough output space has been provided
  71215. before the call.) Flushing may degrade compression for some compression
  71216. algorithms and so it should be used only when necessary.
  71217. If flush is set to Z_FULL_FLUSH, all output is flushed as with
  71218. Z_SYNC_FLUSH, and the compression state is reset so that decompression can
  71219. restart from this point if previous compressed data has been damaged or if
  71220. random access is desired. Using Z_FULL_FLUSH too often can seriously degrade
  71221. compression.
  71222. If deflate returns with avail_out == 0, this function must be called again
  71223. with the same value of the flush parameter and more output space (updated
  71224. avail_out), until the flush is complete (deflate returns with non-zero
  71225. avail_out). In the case of a Z_FULL_FLUSH or Z_SYNC_FLUSH, make sure that
  71226. avail_out is greater than six to avoid repeated flush markers due to
  71227. avail_out == 0 on return.
  71228. If the parameter flush is set to Z_FINISH, pending input is processed,
  71229. pending output is flushed and deflate returns with Z_STREAM_END if there
  71230. was enough output space; if deflate returns with Z_OK, this function must be
  71231. called again with Z_FINISH and more output space (updated avail_out) but no
  71232. more input data, until it returns with Z_STREAM_END or an error. After
  71233. deflate has returned Z_STREAM_END, the only possible operations on the
  71234. stream are deflateReset or deflateEnd.
  71235. Z_FINISH can be used immediately after deflateInit if all the compression
  71236. is to be done in a single step. In this case, avail_out must be at least
  71237. the value returned by deflateBound (see below). If deflate does not return
  71238. Z_STREAM_END, then it must be called again as described above.
  71239. deflate() sets strm->adler to the adler32 checksum of all input read
  71240. so far (that is, total_in bytes).
  71241. deflate() may update strm->data_type if it can make a good guess about
  71242. the input data type (Z_BINARY or Z_TEXT). In doubt, the data is considered
  71243. binary. This field is only for information purposes and does not affect
  71244. the compression algorithm in any manner.
  71245. deflate() returns Z_OK if some progress has been made (more input
  71246. processed or more output produced), Z_STREAM_END if all input has been
  71247. consumed and all output has been produced (only when flush is set to
  71248. Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for example
  71249. if next_in or next_out was NULL), Z_BUF_ERROR if no progress is possible
  71250. (for example avail_in or avail_out was zero). Note that Z_BUF_ERROR is not
  71251. fatal, and deflate() can be called again with more input and more output
  71252. space to continue compressing.
  71253. */
  71254. ZEXTERN int ZEXPORT deflateEnd OF((z_streamp strm));
  71255. /*
  71256. All dynamically allocated data structures for this stream are freed.
  71257. This function discards any unprocessed input and does not flush any
  71258. pending output.
  71259. deflateEnd returns Z_OK if success, Z_STREAM_ERROR if the
  71260. stream state was inconsistent, Z_DATA_ERROR if the stream was freed
  71261. prematurely (some input or output was discarded). In the error case,
  71262. msg may be set but then points to a static string (which must not be
  71263. deallocated).
  71264. */
  71265. /*
  71266. ZEXTERN int ZEXPORT inflateInit OF((z_streamp strm));
  71267. Initializes the internal stream state for decompression. The fields
  71268. next_in, avail_in, zalloc, zfree and opaque must be initialized before by
  71269. the caller. If next_in is not Z_NULL and avail_in is large enough (the exact
  71270. value depends on the compression method), inflateInit determines the
  71271. compression method from the zlib header and allocates all data structures
  71272. accordingly; otherwise the allocation will be deferred to the first call of
  71273. inflate. If zalloc and zfree are set to Z_NULL, inflateInit updates them to
  71274. use default allocation functions.
  71275. inflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough
  71276. memory, Z_VERSION_ERROR if the zlib library version is incompatible with the
  71277. version assumed by the caller. msg is set to null if there is no error
  71278. message. inflateInit does not perform any decompression apart from reading
  71279. the zlib header if present: this will be done by inflate(). (So next_in and
  71280. avail_in may be modified, but next_out and avail_out are unchanged.)
  71281. */
  71282. ZEXTERN int ZEXPORT inflate OF((z_streamp strm, int flush));
  71283. /*
  71284. inflate decompresses as much data as possible, and stops when the input
  71285. buffer becomes empty or the output buffer becomes full. It may introduce
  71286. some output latency (reading input without producing any output) except when
  71287. forced to flush.
  71288. The detailed semantics are as follows. inflate performs one or both of the
  71289. following actions:
  71290. - Decompress more input starting at next_in and update next_in and avail_in
  71291. accordingly. If not all input can be processed (because there is not
  71292. enough room in the output buffer), next_in is updated and processing
  71293. will resume at this point for the next call of inflate().
  71294. - Provide more output starting at next_out and update next_out and avail_out
  71295. accordingly. inflate() provides as much output as possible, until there
  71296. is no more input data or no more space in the output buffer (see below
  71297. about the flush parameter).
  71298. Before the call of inflate(), the application should ensure that at least
  71299. one of the actions is possible, by providing more input and/or consuming
  71300. more output, and updating the next_* and avail_* values accordingly.
  71301. The application can consume the uncompressed output when it wants, for
  71302. example when the output buffer is full (avail_out == 0), or after each
  71303. call of inflate(). If inflate returns Z_OK and with zero avail_out, it
  71304. must be called again after making room in the output buffer because there
  71305. might be more output pending.
  71306. The flush parameter of inflate() can be Z_NO_FLUSH, Z_SYNC_FLUSH,
  71307. Z_FINISH, or Z_BLOCK. Z_SYNC_FLUSH requests that inflate() flush as much
  71308. output as possible to the output buffer. Z_BLOCK requests that inflate() stop
  71309. if and when it gets to the next deflate block boundary. When decoding the
  71310. zlib or gzip format, this will cause inflate() to return immediately after
  71311. the header and before the first block. When doing a raw inflate, inflate()
  71312. will go ahead and process the first block, and will return when it gets to
  71313. the end of that block, or when it runs out of data.
  71314. The Z_BLOCK option assists in appending to or combining deflate streams.
  71315. Also to assist in this, on return inflate() will set strm->data_type to the
  71316. number of unused bits in the last byte taken from strm->next_in, plus 64
  71317. if inflate() is currently decoding the last block in the deflate stream,
  71318. plus 128 if inflate() returned immediately after decoding an end-of-block
  71319. code or decoding the complete header up to just before the first byte of the
  71320. deflate stream. The end-of-block will not be indicated until all of the
  71321. uncompressed data from that block has been written to strm->next_out. The
  71322. number of unused bits may in general be greater than seven, except when
  71323. bit 7 of data_type is set, in which case the number of unused bits will be
  71324. less than eight.
  71325. inflate() should normally be called until it returns Z_STREAM_END or an
  71326. error. However if all decompression is to be performed in a single step
  71327. (a single call of inflate), the parameter flush should be set to
  71328. Z_FINISH. In this case all pending input is processed and all pending
  71329. output is flushed; avail_out must be large enough to hold all the
  71330. uncompressed data. (The size of the uncompressed data may have been saved
  71331. by the compressor for this purpose.) The next operation on this stream must
  71332. be inflateEnd to deallocate the decompression state. The use of Z_FINISH
  71333. is never required, but can be used to inform inflate that a faster approach
  71334. may be used for the single inflate() call.
  71335. In this implementation, inflate() always flushes as much output as
  71336. possible to the output buffer, and always uses the faster approach on the
  71337. first call. So the only effect of the flush parameter in this implementation
  71338. is on the return value of inflate(), as noted below, or when it returns early
  71339. because Z_BLOCK is used.
  71340. If a preset dictionary is needed after this call (see inflateSetDictionary
  71341. below), inflate sets strm->adler to the adler32 checksum of the dictionary
  71342. chosen by the compressor and returns Z_NEED_DICT; otherwise it sets
  71343. strm->adler to the adler32 checksum of all output produced so far (that is,
  71344. total_out bytes) and returns Z_OK, Z_STREAM_END or an error code as described
  71345. below. At the end of the stream, inflate() checks that its computed adler32
  71346. checksum is equal to that saved by the compressor and returns Z_STREAM_END
  71347. only if the checksum is correct.
  71348. inflate() will decompress and check either zlib-wrapped or gzip-wrapped
  71349. deflate data. The header type is detected automatically. Any information
  71350. contained in the gzip header is not retained, so applications that need that
  71351. information should instead use raw inflate, see inflateInit2() below, or
  71352. inflateBack() and perform their own processing of the gzip header and
  71353. trailer.
  71354. inflate() returns Z_OK if some progress has been made (more input processed
  71355. or more output produced), Z_STREAM_END if the end of the compressed data has
  71356. been reached and all uncompressed output has been produced, Z_NEED_DICT if a
  71357. preset dictionary is needed at this point, Z_DATA_ERROR if the input data was
  71358. corrupted (input stream not conforming to the zlib format or incorrect check
  71359. value), Z_STREAM_ERROR if the stream structure was inconsistent (for example
  71360. if next_in or next_out was NULL), Z_MEM_ERROR if there was not enough memory,
  71361. Z_BUF_ERROR if no progress is possible or if there was not enough room in the
  71362. output buffer when Z_FINISH is used. Note that Z_BUF_ERROR is not fatal, and
  71363. inflate() can be called again with more input and more output space to
  71364. continue decompressing. If Z_DATA_ERROR is returned, the application may then
  71365. call inflateSync() to look for a good compression block if a partial recovery
  71366. of the data is desired.
  71367. */
  71368. ZEXTERN int ZEXPORT inflateEnd OF((z_streamp strm));
  71369. /*
  71370. All dynamically allocated data structures for this stream are freed.
  71371. This function discards any unprocessed input and does not flush any
  71372. pending output.
  71373. inflateEnd returns Z_OK if success, Z_STREAM_ERROR if the stream state
  71374. was inconsistent. In the error case, msg may be set but then points to a
  71375. static string (which must not be deallocated).
  71376. */
  71377. /* Advanced functions */
  71378. /*
  71379. The following functions are needed only in some special applications.
  71380. */
  71381. /*
  71382. ZEXTERN int ZEXPORT deflateInit2 OF((z_streamp strm,
  71383. int level,
  71384. int method,
  71385. int windowBits,
  71386. int memLevel,
  71387. int strategy));
  71388. This is another version of deflateInit with more compression options. The
  71389. fields next_in, zalloc, zfree and opaque must be initialized before by
  71390. the caller.
  71391. The method parameter is the compression method. It must be Z_DEFLATED in
  71392. this version of the library.
  71393. The windowBits parameter is the base two logarithm of the window size
  71394. (the size of the history buffer). It should be in the range 8..15 for this
  71395. version of the library. Larger values of this parameter result in better
  71396. compression at the expense of memory usage. The default value is 15 if
  71397. deflateInit is used instead.
  71398. windowBits can also be -8..-15 for raw deflate. In this case, -windowBits
  71399. determines the window size. deflate() will then generate raw deflate data
  71400. with no zlib header or trailer, and will not compute an adler32 check value.
  71401. windowBits can also be greater than 15 for optional gzip encoding. Add
  71402. 16 to windowBits to write a simple gzip header and trailer around the
  71403. compressed data instead of a zlib wrapper. The gzip header will have no
  71404. file name, no extra data, no comment, no modification time (set to zero),
  71405. no header crc, and the operating system will be set to 255 (unknown). If a
  71406. gzip stream is being written, strm->adler is a crc32 instead of an adler32.
  71407. The memLevel parameter specifies how much memory should be allocated
  71408. for the internal compression state. memLevel=1 uses minimum memory but
  71409. is slow and reduces compression ratio; memLevel=9 uses maximum memory
  71410. for optimal speed. The default value is 8. See zconf.h for total memory
  71411. usage as a function of windowBits and memLevel.
  71412. The strategy parameter is used to tune the compression algorithm. Use the
  71413. value Z_DEFAULT_STRATEGY for normal data, Z_FILTERED for data produced by a
  71414. filter (or predictor), Z_HUFFMAN_ONLY to force Huffman encoding only (no
  71415. string match), or Z_RLE to limit match distances to one (run-length
  71416. encoding). Filtered data consists mostly of small values with a somewhat
  71417. random distribution. In this case, the compression algorithm is tuned to
  71418. compress them better. The effect of Z_FILTERED is to force more Huffman
  71419. coding and less string matching; it is somewhat intermediate between
  71420. Z_DEFAULT and Z_HUFFMAN_ONLY. Z_RLE is designed to be almost as fast as
  71421. Z_HUFFMAN_ONLY, but give better compression for PNG image data. The strategy
  71422. parameter only affects the compression ratio but not the correctness of the
  71423. compressed output even if it is not set appropriately. Z_FIXED prevents the
  71424. use of dynamic Huffman codes, allowing for a simpler decoder for special
  71425. applications.
  71426. deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  71427. memory, Z_STREAM_ERROR if a parameter is invalid (such as an invalid
  71428. method). msg is set to null if there is no error message. deflateInit2 does
  71429. not perform any compression: this will be done by deflate().
  71430. */
  71431. ZEXTERN int ZEXPORT deflateSetDictionary OF((z_streamp strm,
  71432. const Bytef *dictionary,
  71433. uInt dictLength));
  71434. /*
  71435. Initializes the compression dictionary from the given byte sequence
  71436. without producing any compressed output. This function must be called
  71437. immediately after deflateInit, deflateInit2 or deflateReset, before any
  71438. call of deflate. The compressor and decompressor must use exactly the same
  71439. dictionary (see inflateSetDictionary).
  71440. The dictionary should consist of strings (byte sequences) that are likely
  71441. to be encountered later in the data to be compressed, with the most commonly
  71442. used strings preferably put towards the end of the dictionary. Using a
  71443. dictionary is most useful when the data to be compressed is short and can be
  71444. predicted with good accuracy; the data can then be compressed better than
  71445. with the default empty dictionary.
  71446. Depending on the size of the compression data structures selected by
  71447. deflateInit or deflateInit2, a part of the dictionary may in effect be
  71448. discarded, for example if the dictionary is larger than the window size in
  71449. deflate or deflate2. Thus the strings most likely to be useful should be
  71450. put at the end of the dictionary, not at the front. In addition, the
  71451. current implementation of deflate will use at most the window size minus
  71452. 262 bytes of the provided dictionary.
  71453. Upon return of this function, strm->adler is set to the adler32 value
  71454. of the dictionary; the decompressor may later use this value to determine
  71455. which dictionary has been used by the compressor. (The adler32 value
  71456. applies to the whole dictionary even if only a subset of the dictionary is
  71457. actually used by the compressor.) If a raw deflate was requested, then the
  71458. adler32 value is not computed and strm->adler is not set.
  71459. deflateSetDictionary returns Z_OK if success, or Z_STREAM_ERROR if a
  71460. parameter is invalid (such as NULL dictionary) or the stream state is
  71461. inconsistent (for example if deflate has already been called for this stream
  71462. or if the compression method is bsort). deflateSetDictionary does not
  71463. perform any compression: this will be done by deflate().
  71464. */
  71465. ZEXTERN int ZEXPORT deflateCopy OF((z_streamp dest,
  71466. z_streamp source));
  71467. /*
  71468. Sets the destination stream as a complete copy of the source stream.
  71469. This function can be useful when several compression strategies will be
  71470. tried, for example when there are several ways of pre-processing the input
  71471. data with a filter. The streams that will be discarded should then be freed
  71472. by calling deflateEnd. Note that deflateCopy duplicates the internal
  71473. compression state which can be quite large, so this strategy is slow and
  71474. can consume lots of memory.
  71475. deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
  71476. enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
  71477. (such as zalloc being NULL). msg is left unchanged in both source and
  71478. destination.
  71479. */
  71480. ZEXTERN int ZEXPORT deflateReset OF((z_streamp strm));
  71481. /*
  71482. This function is equivalent to deflateEnd followed by deflateInit,
  71483. but does not free and reallocate all the internal compression state.
  71484. The stream will keep the same compression level and any other attributes
  71485. that may have been set by deflateInit2.
  71486. deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
  71487. stream state was inconsistent (such as zalloc or state being NULL).
  71488. */
  71489. ZEXTERN int ZEXPORT deflateParams OF((z_streamp strm,
  71490. int level,
  71491. int strategy));
  71492. /*
  71493. Dynamically update the compression level and compression strategy. The
  71494. interpretation of level and strategy is as in deflateInit2. This can be
  71495. used to switch between compression and straight copy of the input data, or
  71496. to switch to a different kind of input data requiring a different
  71497. strategy. If the compression level is changed, the input available so far
  71498. is compressed with the old level (and may be flushed); the new level will
  71499. take effect only at the next call of deflate().
  71500. Before the call of deflateParams, the stream state must be set as for
  71501. a call of deflate(), since the currently available input may have to
  71502. be compressed and flushed. In particular, strm->avail_out must be non-zero.
  71503. deflateParams returns Z_OK if success, Z_STREAM_ERROR if the source
  71504. stream state was inconsistent or if a parameter was invalid, Z_BUF_ERROR
  71505. if strm->avail_out was zero.
  71506. */
  71507. ZEXTERN int ZEXPORT deflateTune OF((z_streamp strm,
  71508. int good_length,
  71509. int max_lazy,
  71510. int nice_length,
  71511. int max_chain));
  71512. /*
  71513. Fine tune deflate's internal compression parameters. This should only be
  71514. used by someone who understands the algorithm used by zlib's deflate for
  71515. searching for the best matching string, and even then only by the most
  71516. fanatic optimizer trying to squeeze out the last compressed bit for their
  71517. specific input data. Read the deflate.c source code for the meaning of the
  71518. max_lazy, good_length, nice_length, and max_chain parameters.
  71519. deflateTune() can be called after deflateInit() or deflateInit2(), and
  71520. returns Z_OK on success, or Z_STREAM_ERROR for an invalid deflate stream.
  71521. */
  71522. ZEXTERN uLong ZEXPORT deflateBound OF((z_streamp strm,
  71523. uLong sourceLen));
  71524. /*
  71525. deflateBound() returns an upper bound on the compressed size after
  71526. deflation of sourceLen bytes. It must be called after deflateInit()
  71527. or deflateInit2(). This would be used to allocate an output buffer
  71528. for deflation in a single pass, and so would be called before deflate().
  71529. */
  71530. ZEXTERN int ZEXPORT deflatePrime OF((z_streamp strm,
  71531. int bits,
  71532. int value));
  71533. /*
  71534. deflatePrime() inserts bits in the deflate output stream. The intent
  71535. is that this function is used to start off the deflate output with the
  71536. bits leftover from a previous deflate stream when appending to it. As such,
  71537. this function can only be used for raw deflate, and must be used before the
  71538. first deflate() call after a deflateInit2() or deflateReset(). bits must be
  71539. less than or equal to 16, and that many of the least significant bits of
  71540. value will be inserted in the output.
  71541. deflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source
  71542. stream state was inconsistent.
  71543. */
  71544. ZEXTERN int ZEXPORT deflateSetHeader OF((z_streamp strm,
  71545. gz_headerp head));
  71546. /*
  71547. deflateSetHeader() provides gzip header information for when a gzip
  71548. stream is requested by deflateInit2(). deflateSetHeader() may be called
  71549. after deflateInit2() or deflateReset() and before the first call of
  71550. deflate(). The text, time, os, extra field, name, and comment information
  71551. in the provided gz_header structure are written to the gzip header (xflag is
  71552. ignored -- the extra flags are set according to the compression level). The
  71553. caller must assure that, if not Z_NULL, name and comment are terminated with
  71554. a zero byte, and that if extra is not Z_NULL, that extra_len bytes are
  71555. available there. If hcrc is true, a gzip header crc is included. Note that
  71556. the current versions of the command-line version of gzip (up through version
  71557. 1.3.x) do not support header crc's, and will report that it is a "multi-part
  71558. gzip file" and give up.
  71559. If deflateSetHeader is not used, the default gzip header has text false,
  71560. the time set to zero, and os set to 255, with no extra, name, or comment
  71561. fields. The gzip header is returned to the default state by deflateReset().
  71562. deflateSetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
  71563. stream state was inconsistent.
  71564. */
  71565. /*
  71566. ZEXTERN int ZEXPORT inflateInit2 OF((z_streamp strm,
  71567. int windowBits));
  71568. This is another version of inflateInit with an extra parameter. The
  71569. fields next_in, avail_in, zalloc, zfree and opaque must be initialized
  71570. before by the caller.
  71571. The windowBits parameter is the base two logarithm of the maximum window
  71572. size (the size of the history buffer). It should be in the range 8..15 for
  71573. this version of the library. The default value is 15 if inflateInit is used
  71574. instead. windowBits must be greater than or equal to the windowBits value
  71575. provided to deflateInit2() while compressing, or it must be equal to 15 if
  71576. deflateInit2() was not used. If a compressed stream with a larger window
  71577. size is given as input, inflate() will return with the error code
  71578. Z_DATA_ERROR instead of trying to allocate a larger window.
  71579. windowBits can also be -8..-15 for raw inflate. In this case, -windowBits
  71580. determines the window size. inflate() will then process raw deflate data,
  71581. not looking for a zlib or gzip header, not generating a check value, and not
  71582. looking for any check values for comparison at the end of the stream. This
  71583. is for use with other formats that use the deflate compressed data format
  71584. such as zip. Those formats provide their own check values. If a custom
  71585. format is developed using the raw deflate format for compressed data, it is
  71586. recommended that a check value such as an adler32 or a crc32 be applied to
  71587. the uncompressed data as is done in the zlib, gzip, and zip formats. For
  71588. most applications, the zlib format should be used as is. Note that comments
  71589. above on the use in deflateInit2() applies to the magnitude of windowBits.
  71590. windowBits can also be greater than 15 for optional gzip decoding. Add
  71591. 32 to windowBits to enable zlib and gzip decoding with automatic header
  71592. detection, or add 16 to decode only the gzip format (the zlib format will
  71593. return a Z_DATA_ERROR). If a gzip stream is being decoded, strm->adler is
  71594. a crc32 instead of an adler32.
  71595. inflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  71596. memory, Z_STREAM_ERROR if a parameter is invalid (such as a null strm). msg
  71597. is set to null if there is no error message. inflateInit2 does not perform
  71598. any decompression apart from reading the zlib header if present: this will
  71599. be done by inflate(). (So next_in and avail_in may be modified, but next_out
  71600. and avail_out are unchanged.)
  71601. */
  71602. ZEXTERN int ZEXPORT inflateSetDictionary OF((z_streamp strm,
  71603. const Bytef *dictionary,
  71604. uInt dictLength));
  71605. /*
  71606. Initializes the decompression dictionary from the given uncompressed byte
  71607. sequence. This function must be called immediately after a call of inflate,
  71608. if that call returned Z_NEED_DICT. The dictionary chosen by the compressor
  71609. can be determined from the adler32 value returned by that call of inflate.
  71610. The compressor and decompressor must use exactly the same dictionary (see
  71611. deflateSetDictionary). For raw inflate, this function can be called
  71612. immediately after inflateInit2() or inflateReset() and before any call of
  71613. inflate() to set the dictionary. The application must insure that the
  71614. dictionary that was used for compression is provided.
  71615. inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a
  71616. parameter is invalid (such as NULL dictionary) or the stream state is
  71617. inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the
  71618. expected one (incorrect adler32 value). inflateSetDictionary does not
  71619. perform any decompression: this will be done by subsequent calls of
  71620. inflate().
  71621. */
  71622. ZEXTERN int ZEXPORT inflateSync OF((z_streamp strm));
  71623. /*
  71624. Skips invalid compressed data until a full flush point (see above the
  71625. description of deflate with Z_FULL_FLUSH) can be found, or until all
  71626. available input is skipped. No output is provided.
  71627. inflateSync returns Z_OK if a full flush point has been found, Z_BUF_ERROR
  71628. if no more input was provided, Z_DATA_ERROR if no flush point has been found,
  71629. or Z_STREAM_ERROR if the stream structure was inconsistent. In the success
  71630. case, the application may save the current current value of total_in which
  71631. indicates where valid compressed data was found. In the error case, the
  71632. application may repeatedly call inflateSync, providing more input each time,
  71633. until success or end of the input data.
  71634. */
  71635. ZEXTERN int ZEXPORT inflateCopy OF((z_streamp dest,
  71636. z_streamp source));
  71637. /*
  71638. Sets the destination stream as a complete copy of the source stream.
  71639. This function can be useful when randomly accessing a large stream. The
  71640. first pass through the stream can periodically record the inflate state,
  71641. allowing restarting inflate at those points when randomly accessing the
  71642. stream.
  71643. inflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
  71644. enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
  71645. (such as zalloc being NULL). msg is left unchanged in both source and
  71646. destination.
  71647. */
  71648. ZEXTERN int ZEXPORT inflateReset OF((z_streamp strm));
  71649. /*
  71650. This function is equivalent to inflateEnd followed by inflateInit,
  71651. but does not free and reallocate all the internal decompression state.
  71652. The stream will keep attributes that may have been set by inflateInit2.
  71653. inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
  71654. stream state was inconsistent (such as zalloc or state being NULL).
  71655. */
  71656. ZEXTERN int ZEXPORT inflatePrime OF((z_streamp strm,
  71657. int bits,
  71658. int value));
  71659. /*
  71660. This function inserts bits in the inflate input stream. The intent is
  71661. that this function is used to start inflating at a bit position in the
  71662. middle of a byte. The provided bits will be used before any bytes are used
  71663. from next_in. This function should only be used with raw inflate, and
  71664. should be used before the first inflate() call after inflateInit2() or
  71665. inflateReset(). bits must be less than or equal to 16, and that many of the
  71666. least significant bits of value will be inserted in the input.
  71667. inflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source
  71668. stream state was inconsistent.
  71669. */
  71670. ZEXTERN int ZEXPORT inflateGetHeader OF((z_streamp strm,
  71671. gz_headerp head));
  71672. /*
  71673. inflateGetHeader() requests that gzip header information be stored in the
  71674. provided gz_header structure. inflateGetHeader() may be called after
  71675. inflateInit2() or inflateReset(), and before the first call of inflate().
  71676. As inflate() processes the gzip stream, head->done is zero until the header
  71677. is completed, at which time head->done is set to one. If a zlib stream is
  71678. being decoded, then head->done is set to -1 to indicate that there will be
  71679. no gzip header information forthcoming. Note that Z_BLOCK can be used to
  71680. force inflate() to return immediately after header processing is complete
  71681. and before any actual data is decompressed.
  71682. The text, time, xflags, and os fields are filled in with the gzip header
  71683. contents. hcrc is set to true if there is a header CRC. (The header CRC
  71684. was valid if done is set to one.) If extra is not Z_NULL, then extra_max
  71685. contains the maximum number of bytes to write to extra. Once done is true,
  71686. extra_len contains the actual extra field length, and extra contains the
  71687. extra field, or that field truncated if extra_max is less than extra_len.
  71688. If name is not Z_NULL, then up to name_max characters are written there,
  71689. terminated with a zero unless the length is greater than name_max. If
  71690. comment is not Z_NULL, then up to comm_max characters are written there,
  71691. terminated with a zero unless the length is greater than comm_max. When
  71692. any of extra, name, or comment are not Z_NULL and the respective field is
  71693. not present in the header, then that field is set to Z_NULL to signal its
  71694. absence. This allows the use of deflateSetHeader() with the returned
  71695. structure to duplicate the header. However if those fields are set to
  71696. allocated memory, then the application will need to save those pointers
  71697. elsewhere so that they can be eventually freed.
  71698. If inflateGetHeader is not used, then the header information is simply
  71699. discarded. The header is always checked for validity, including the header
  71700. CRC if present. inflateReset() will reset the process to discard the header
  71701. information. The application would need to call inflateGetHeader() again to
  71702. retrieve the header from the next gzip stream.
  71703. inflateGetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
  71704. stream state was inconsistent.
  71705. */
  71706. /*
  71707. ZEXTERN int ZEXPORT inflateBackInit OF((z_streamp strm, int windowBits,
  71708. unsigned char FAR *window));
  71709. Initialize the internal stream state for decompression using inflateBack()
  71710. calls. The fields zalloc, zfree and opaque in strm must be initialized
  71711. before the call. If zalloc and zfree are Z_NULL, then the default library-
  71712. derived memory allocation routines are used. windowBits is the base two
  71713. logarithm of the window size, in the range 8..15. window is a caller
  71714. supplied buffer of that size. Except for special applications where it is
  71715. assured that deflate was used with small window sizes, windowBits must be 15
  71716. and a 32K byte window must be supplied to be able to decompress general
  71717. deflate streams.
  71718. See inflateBack() for the usage of these routines.
  71719. inflateBackInit will return Z_OK on success, Z_STREAM_ERROR if any of
  71720. the paramaters are invalid, Z_MEM_ERROR if the internal state could not
  71721. be allocated, or Z_VERSION_ERROR if the version of the library does not
  71722. match the version of the header file.
  71723. */
  71724. typedef unsigned (*in_func) OF((void FAR *, unsigned char FAR * FAR *));
  71725. typedef int (*out_func) OF((void FAR *, unsigned char FAR *, unsigned));
  71726. ZEXTERN int ZEXPORT inflateBack OF((z_streamp strm,
  71727. in_func in, void FAR *in_desc,
  71728. out_func out, void FAR *out_desc));
  71729. /*
  71730. inflateBack() does a raw inflate with a single call using a call-back
  71731. interface for input and output. This is more efficient than inflate() for
  71732. file i/o applications in that it avoids copying between the output and the
  71733. sliding window by simply making the window itself the output buffer. This
  71734. function trusts the application to not change the output buffer passed by
  71735. the output function, at least until inflateBack() returns.
  71736. inflateBackInit() must be called first to allocate the internal state
  71737. and to initialize the state with the user-provided window buffer.
  71738. inflateBack() may then be used multiple times to inflate a complete, raw
  71739. deflate stream with each call. inflateBackEnd() is then called to free
  71740. the allocated state.
  71741. A raw deflate stream is one with no zlib or gzip header or trailer.
  71742. This routine would normally be used in a utility that reads zip or gzip
  71743. files and writes out uncompressed files. The utility would decode the
  71744. header and process the trailer on its own, hence this routine expects
  71745. only the raw deflate stream to decompress. This is different from the
  71746. normal behavior of inflate(), which expects either a zlib or gzip header and
  71747. trailer around the deflate stream.
  71748. inflateBack() uses two subroutines supplied by the caller that are then
  71749. called by inflateBack() for input and output. inflateBack() calls those
  71750. routines until it reads a complete deflate stream and writes out all of the
  71751. uncompressed data, or until it encounters an error. The function's
  71752. parameters and return types are defined above in the in_func and out_func
  71753. typedefs. inflateBack() will call in(in_desc, &buf) which should return the
  71754. number of bytes of provided input, and a pointer to that input in buf. If
  71755. there is no input available, in() must return zero--buf is ignored in that
  71756. case--and inflateBack() will return a buffer error. inflateBack() will call
  71757. out(out_desc, buf, len) to write the uncompressed data buf[0..len-1]. out()
  71758. should return zero on success, or non-zero on failure. If out() returns
  71759. non-zero, inflateBack() will return with an error. Neither in() nor out()
  71760. are permitted to change the contents of the window provided to
  71761. inflateBackInit(), which is also the buffer that out() uses to write from.
  71762. The length written by out() will be at most the window size. Any non-zero
  71763. amount of input may be provided by in().
  71764. For convenience, inflateBack() can be provided input on the first call by
  71765. setting strm->next_in and strm->avail_in. If that input is exhausted, then
  71766. in() will be called. Therefore strm->next_in must be initialized before
  71767. calling inflateBack(). If strm->next_in is Z_NULL, then in() will be called
  71768. immediately for input. If strm->next_in is not Z_NULL, then strm->avail_in
  71769. must also be initialized, and then if strm->avail_in is not zero, input will
  71770. initially be taken from strm->next_in[0 .. strm->avail_in - 1].
  71771. The in_desc and out_desc parameters of inflateBack() is passed as the
  71772. first parameter of in() and out() respectively when they are called. These
  71773. descriptors can be optionally used to pass any information that the caller-
  71774. supplied in() and out() functions need to do their job.
  71775. On return, inflateBack() will set strm->next_in and strm->avail_in to
  71776. pass back any unused input that was provided by the last in() call. The
  71777. return values of inflateBack() can be Z_STREAM_END on success, Z_BUF_ERROR
  71778. if in() or out() returned an error, Z_DATA_ERROR if there was a format
  71779. error in the deflate stream (in which case strm->msg is set to indicate the
  71780. nature of the error), or Z_STREAM_ERROR if the stream was not properly
  71781. initialized. In the case of Z_BUF_ERROR, an input or output error can be
  71782. distinguished using strm->next_in which will be Z_NULL only if in() returned
  71783. an error. If strm->next is not Z_NULL, then the Z_BUF_ERROR was due to
  71784. out() returning non-zero. (in() will always be called before out(), so
  71785. strm->next_in is assured to be defined if out() returns non-zero.) Note
  71786. that inflateBack() cannot return Z_OK.
  71787. */
  71788. ZEXTERN int ZEXPORT inflateBackEnd OF((z_streamp strm));
  71789. /*
  71790. All memory allocated by inflateBackInit() is freed.
  71791. inflateBackEnd() returns Z_OK on success, or Z_STREAM_ERROR if the stream
  71792. state was inconsistent.
  71793. */
  71794. //ZEXTERN uLong ZEXPORT zlibCompileFlags OF((void));
  71795. /* Return flags indicating compile-time options.
  71796. Type sizes, two bits each, 00 = 16 bits, 01 = 32, 10 = 64, 11 = other:
  71797. 1.0: size of uInt
  71798. 3.2: size of uLong
  71799. 5.4: size of voidpf (pointer)
  71800. 7.6: size of z_off_t
  71801. Compiler, assembler, and debug options:
  71802. 8: DEBUG
  71803. 9: ASMV or ASMINF -- use ASM code
  71804. 10: ZLIB_WINAPI -- exported functions use the WINAPI calling convention
  71805. 11: 0 (reserved)
  71806. One-time table building (smaller code, but not thread-safe if true):
  71807. 12: BUILDFIXED -- build static block decoding tables when needed
  71808. 13: DYNAMIC_CRC_TABLE -- build CRC calculation tables when needed
  71809. 14,15: 0 (reserved)
  71810. Library content (indicates missing functionality):
  71811. 16: NO_GZCOMPRESS -- gz* functions cannot compress (to avoid linking
  71812. deflate code when not needed)
  71813. 17: NO_GZIP -- deflate can't write gzip streams, and inflate can't detect
  71814. and decode gzip streams (to avoid linking crc code)
  71815. 18-19: 0 (reserved)
  71816. Operation variations (changes in library functionality):
  71817. 20: PKZIP_BUG_WORKAROUND -- slightly more permissive inflate
  71818. 21: FASTEST -- deflate algorithm with only one, lowest compression level
  71819. 22,23: 0 (reserved)
  71820. The sprintf variant used by gzprintf (zero is best):
  71821. 24: 0 = vs*, 1 = s* -- 1 means limited to 20 arguments after the format
  71822. 25: 0 = *nprintf, 1 = *printf -- 1 means gzprintf() not secure!
  71823. 26: 0 = returns value, 1 = void -- 1 means inferred string length returned
  71824. Remainder:
  71825. 27-31: 0 (reserved)
  71826. */
  71827. /* utility functions */
  71828. /*
  71829. The following utility functions are implemented on top of the
  71830. basic stream-oriented functions. To simplify the interface, some
  71831. default options are assumed (compression level and memory usage,
  71832. standard memory allocation functions). The source code of these
  71833. utility functions can easily be modified if you need special options.
  71834. */
  71835. ZEXTERN int ZEXPORT compress OF((Bytef *dest, uLongf *destLen,
  71836. const Bytef *source, uLong sourceLen));
  71837. /*
  71838. Compresses the source buffer into the destination buffer. sourceLen is
  71839. the byte length of the source buffer. Upon entry, destLen is the total
  71840. size of the destination buffer, which must be at least the value returned
  71841. by compressBound(sourceLen). Upon exit, destLen is the actual size of the
  71842. compressed buffer.
  71843. This function can be used to compress a whole file at once if the
  71844. input file is mmap'ed.
  71845. compress returns Z_OK if success, Z_MEM_ERROR if there was not
  71846. enough memory, Z_BUF_ERROR if there was not enough room in the output
  71847. buffer.
  71848. */
  71849. ZEXTERN int ZEXPORT compress2 OF((Bytef *dest, uLongf *destLen,
  71850. const Bytef *source, uLong sourceLen,
  71851. int level));
  71852. /*
  71853. Compresses the source buffer into the destination buffer. The level
  71854. parameter has the same meaning as in deflateInit. sourceLen is the byte
  71855. length of the source buffer. Upon entry, destLen is the total size of the
  71856. destination buffer, which must be at least the value returned by
  71857. compressBound(sourceLen). Upon exit, destLen is the actual size of the
  71858. compressed buffer.
  71859. compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  71860. memory, Z_BUF_ERROR if there was not enough room in the output buffer,
  71861. Z_STREAM_ERROR if the level parameter is invalid.
  71862. */
  71863. ZEXTERN uLong ZEXPORT compressBound OF((uLong sourceLen));
  71864. /*
  71865. compressBound() returns an upper bound on the compressed size after
  71866. compress() or compress2() on sourceLen bytes. It would be used before
  71867. a compress() or compress2() call to allocate the destination buffer.
  71868. */
  71869. ZEXTERN int ZEXPORT uncompress OF((Bytef *dest, uLongf *destLen,
  71870. const Bytef *source, uLong sourceLen));
  71871. /*
  71872. Decompresses the source buffer into the destination buffer. sourceLen is
  71873. the byte length of the source buffer. Upon entry, destLen is the total
  71874. size of the destination buffer, which must be large enough to hold the
  71875. entire uncompressed data. (The size of the uncompressed data must have
  71876. been saved previously by the compressor and transmitted to the decompressor
  71877. by some mechanism outside the scope of this compression library.)
  71878. Upon exit, destLen is the actual size of the compressed buffer.
  71879. This function can be used to decompress a whole file at once if the
  71880. input file is mmap'ed.
  71881. uncompress returns Z_OK if success, Z_MEM_ERROR if there was not
  71882. enough memory, Z_BUF_ERROR if there was not enough room in the output
  71883. buffer, or Z_DATA_ERROR if the input data was corrupted or incomplete.
  71884. */
  71885. typedef voidp gzFile;
  71886. ZEXTERN gzFile ZEXPORT gzopen OF((const char *path, const char *mode));
  71887. /*
  71888. Opens a gzip (.gz) file for reading or writing. The mode parameter
  71889. is as in fopen ("rb" or "wb") but can also include a compression level
  71890. ("wb9") or a strategy: 'f' for filtered data as in "wb6f", 'h' for
  71891. Huffman only compression as in "wb1h", or 'R' for run-length encoding
  71892. as in "wb1R". (See the description of deflateInit2 for more information
  71893. about the strategy parameter.)
  71894. gzopen can be used to read a file which is not in gzip format; in this
  71895. case gzread will directly read from the file without decompression.
  71896. gzopen returns NULL if the file could not be opened or if there was
  71897. insufficient memory to allocate the (de)compression state; errno
  71898. can be checked to distinguish the two cases (if errno is zero, the
  71899. zlib error is Z_MEM_ERROR). */
  71900. ZEXTERN gzFile ZEXPORT gzdopen OF((int fd, const char *mode));
  71901. /*
  71902. gzdopen() associates a gzFile with the file descriptor fd. File
  71903. descriptors are obtained from calls like open, dup, creat, pipe or
  71904. fileno (in the file has been previously opened with fopen).
  71905. The mode parameter is as in gzopen.
  71906. The next call of gzclose on the returned gzFile will also close the
  71907. file descriptor fd, just like fclose(fdopen(fd), mode) closes the file
  71908. descriptor fd. If you want to keep fd open, use gzdopen(dup(fd), mode).
  71909. gzdopen returns NULL if there was insufficient memory to allocate
  71910. the (de)compression state.
  71911. */
  71912. ZEXTERN int ZEXPORT gzsetparams OF((gzFile file, int level, int strategy));
  71913. /*
  71914. Dynamically update the compression level or strategy. See the description
  71915. of deflateInit2 for the meaning of these parameters.
  71916. gzsetparams returns Z_OK if success, or Z_STREAM_ERROR if the file was not
  71917. opened for writing.
  71918. */
  71919. ZEXTERN int ZEXPORT gzread OF((gzFile file, voidp buf, unsigned len));
  71920. /*
  71921. Reads the given number of uncompressed bytes from the compressed file.
  71922. If the input file was not in gzip format, gzread copies the given number
  71923. of bytes into the buffer.
  71924. gzread returns the number of uncompressed bytes actually read (0 for
  71925. end of file, -1 for error). */
  71926. ZEXTERN int ZEXPORT gzwrite OF((gzFile file,
  71927. voidpc buf, unsigned len));
  71928. /*
  71929. Writes the given number of uncompressed bytes into the compressed file.
  71930. gzwrite returns the number of uncompressed bytes actually written
  71931. (0 in case of error).
  71932. */
  71933. ZEXTERN int ZEXPORTVA gzprintf OF((gzFile file, const char *format, ...));
  71934. /*
  71935. Converts, formats, and writes the args to the compressed file under
  71936. control of the format string, as in fprintf. gzprintf returns the number of
  71937. uncompressed bytes actually written (0 in case of error). The number of
  71938. uncompressed bytes written is limited to 4095. The caller should assure that
  71939. this limit is not exceeded. If it is exceeded, then gzprintf() will return
  71940. return an error (0) with nothing written. In this case, there may also be a
  71941. buffer overflow with unpredictable consequences, which is possible only if
  71942. zlib was compiled with the insecure functions sprintf() or vsprintf()
  71943. because the secure snprintf() or vsnprintf() functions were not available.
  71944. */
  71945. ZEXTERN int ZEXPORT gzputs OF((gzFile file, const char *s));
  71946. /*
  71947. Writes the given null-terminated string to the compressed file, excluding
  71948. the terminating null character.
  71949. gzputs returns the number of characters written, or -1 in case of error.
  71950. */
  71951. ZEXTERN char * ZEXPORT gzgets OF((gzFile file, char *buf, int len));
  71952. /*
  71953. Reads bytes from the compressed file until len-1 characters are read, or
  71954. a newline character is read and transferred to buf, or an end-of-file
  71955. condition is encountered. The string is then terminated with a null
  71956. character.
  71957. gzgets returns buf, or Z_NULL in case of error.
  71958. */
  71959. ZEXTERN int ZEXPORT gzputc OF((gzFile file, int c));
  71960. /*
  71961. Writes c, converted to an unsigned char, into the compressed file.
  71962. gzputc returns the value that was written, or -1 in case of error.
  71963. */
  71964. ZEXTERN int ZEXPORT gzgetc OF((gzFile file));
  71965. /*
  71966. Reads one byte from the compressed file. gzgetc returns this byte
  71967. or -1 in case of end of file or error.
  71968. */
  71969. ZEXTERN int ZEXPORT gzungetc OF((int c, gzFile file));
  71970. /*
  71971. Push one character back onto the stream to be read again later.
  71972. Only one character of push-back is allowed. gzungetc() returns the
  71973. character pushed, or -1 on failure. gzungetc() will fail if a
  71974. character has been pushed but not read yet, or if c is -1. The pushed
  71975. character will be discarded if the stream is repositioned with gzseek()
  71976. or gzrewind().
  71977. */
  71978. ZEXTERN int ZEXPORT gzflush OF((gzFile file, int flush));
  71979. /*
  71980. Flushes all pending output into the compressed file. The parameter
  71981. flush is as in the deflate() function. The return value is the zlib
  71982. error number (see function gzerror below). gzflush returns Z_OK if
  71983. the flush parameter is Z_FINISH and all output could be flushed.
  71984. gzflush should be called only when strictly necessary because it can
  71985. degrade compression.
  71986. */
  71987. ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile file,
  71988. z_off_t offset, int whence));
  71989. /*
  71990. Sets the starting position for the next gzread or gzwrite on the
  71991. given compressed file. The offset represents a number of bytes in the
  71992. uncompressed data stream. The whence parameter is defined as in lseek(2);
  71993. the value SEEK_END is not supported.
  71994. If the file is opened for reading, this function is emulated but can be
  71995. extremely slow. If the file is opened for writing, only forward seeks are
  71996. supported; gzseek then compresses a sequence of zeroes up to the new
  71997. starting position.
  71998. gzseek returns the resulting offset location as measured in bytes from
  71999. the beginning of the uncompressed stream, or -1 in case of error, in
  72000. particular if the file is opened for writing and the new starting position
  72001. would be before the current position.
  72002. */
  72003. ZEXTERN int ZEXPORT gzrewind OF((gzFile file));
  72004. /*
  72005. Rewinds the given file. This function is supported only for reading.
  72006. gzrewind(file) is equivalent to (int)gzseek(file, 0L, SEEK_SET)
  72007. */
  72008. ZEXTERN z_off_t ZEXPORT gztell OF((gzFile file));
  72009. /*
  72010. Returns the starting position for the next gzread or gzwrite on the
  72011. given compressed file. This position represents a number of bytes in the
  72012. uncompressed data stream.
  72013. gztell(file) is equivalent to gzseek(file, 0L, SEEK_CUR)
  72014. */
  72015. ZEXTERN int ZEXPORT gzeof OF((gzFile file));
  72016. /*
  72017. Returns 1 when EOF has previously been detected reading the given
  72018. input stream, otherwise zero.
  72019. */
  72020. ZEXTERN int ZEXPORT gzdirect OF((gzFile file));
  72021. /*
  72022. Returns 1 if file is being read directly without decompression, otherwise
  72023. zero.
  72024. */
  72025. ZEXTERN int ZEXPORT gzclose OF((gzFile file));
  72026. /*
  72027. Flushes all pending output if necessary, closes the compressed file
  72028. and deallocates all the (de)compression state. The return value is the zlib
  72029. error number (see function gzerror below).
  72030. */
  72031. ZEXTERN const char * ZEXPORT gzerror OF((gzFile file, int *errnum));
  72032. /*
  72033. Returns the error message for the last error which occurred on the
  72034. given compressed file. errnum is set to zlib error number. If an
  72035. error occurred in the file system and not in the compression library,
  72036. errnum is set to Z_ERRNO and the application may consult errno
  72037. to get the exact error code.
  72038. */
  72039. ZEXTERN void ZEXPORT gzclearerr OF((gzFile file));
  72040. /*
  72041. Clears the error and end-of-file flags for file. This is analogous to the
  72042. clearerr() function in stdio. This is useful for continuing to read a gzip
  72043. file that is being written concurrently.
  72044. */
  72045. /* checksum functions */
  72046. /*
  72047. These functions are not related to compression but are exported
  72048. anyway because they might be useful in applications using the
  72049. compression library.
  72050. */
  72051. ZEXTERN uLong ZEXPORT adler32 OF((uLong adler, const Bytef *buf, uInt len));
  72052. /*
  72053. Update a running Adler-32 checksum with the bytes buf[0..len-1] and
  72054. return the updated checksum. If buf is NULL, this function returns
  72055. the required initial value for the checksum.
  72056. An Adler-32 checksum is almost as reliable as a CRC32 but can be computed
  72057. much faster. Usage example:
  72058. uLong adler = adler32(0L, Z_NULL, 0);
  72059. while (read_buffer(buffer, length) != EOF) {
  72060. adler = adler32(adler, buffer, length);
  72061. }
  72062. if (adler != original_adler) error();
  72063. */
  72064. ZEXTERN uLong ZEXPORT adler32_combine OF((uLong adler1, uLong adler2,
  72065. z_off_t len2));
  72066. /*
  72067. Combine two Adler-32 checksums into one. For two sequences of bytes, seq1
  72068. and seq2 with lengths len1 and len2, Adler-32 checksums were calculated for
  72069. each, adler1 and adler2. adler32_combine() returns the Adler-32 checksum of
  72070. seq1 and seq2 concatenated, requiring only adler1, adler2, and len2.
  72071. */
  72072. ZEXTERN uLong ZEXPORT crc32 OF((uLong crc, const Bytef *buf, uInt len));
  72073. /*
  72074. Update a running CRC-32 with the bytes buf[0..len-1] and return the
  72075. updated CRC-32. If buf is NULL, this function returns the required initial
  72076. value for the for the crc. Pre- and post-conditioning (one's complement) is
  72077. performed within this function so it shouldn't be done by the application.
  72078. Usage example:
  72079. uLong crc = crc32(0L, Z_NULL, 0);
  72080. while (read_buffer(buffer, length) != EOF) {
  72081. crc = crc32(crc, buffer, length);
  72082. }
  72083. if (crc != original_crc) error();
  72084. */
  72085. ZEXTERN uLong ZEXPORT crc32_combine OF((uLong crc1, uLong crc2, z_off_t len2));
  72086. /*
  72087. Combine two CRC-32 check values into one. For two sequences of bytes,
  72088. seq1 and seq2 with lengths len1 and len2, CRC-32 check values were
  72089. calculated for each, crc1 and crc2. crc32_combine() returns the CRC-32
  72090. check value of seq1 and seq2 concatenated, requiring only crc1, crc2, and
  72091. len2.
  72092. */
  72093. /* various hacks, don't look :) */
  72094. /* deflateInit and inflateInit are macros to allow checking the zlib version
  72095. * and the compiler's view of z_stream:
  72096. */
  72097. ZEXTERN int ZEXPORT deflateInit_ OF((z_streamp strm, int level,
  72098. const char *version, int stream_size));
  72099. ZEXTERN int ZEXPORT inflateInit_ OF((z_streamp strm,
  72100. const char *version, int stream_size));
  72101. ZEXTERN int ZEXPORT deflateInit2_ OF((z_streamp strm, int level, int method,
  72102. int windowBits, int memLevel,
  72103. int strategy, const char *version,
  72104. int stream_size));
  72105. ZEXTERN int ZEXPORT inflateInit2_ OF((z_streamp strm, int windowBits,
  72106. const char *version, int stream_size));
  72107. ZEXTERN int ZEXPORT inflateBackInit_ OF((z_streamp strm, int windowBits,
  72108. unsigned char FAR *window,
  72109. const char *version,
  72110. int stream_size));
  72111. #define deflateInit(strm, level) \
  72112. deflateInit_((strm), (level), ZLIB_VERSION, sizeof(z_stream))
  72113. #define inflateInit(strm) \
  72114. inflateInit_((strm), ZLIB_VERSION, sizeof(z_stream))
  72115. #define deflateInit2(strm, level, method, windowBits, memLevel, strategy) \
  72116. deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\
  72117. (strategy), ZLIB_VERSION, sizeof(z_stream))
  72118. #define inflateInit2(strm, windowBits) \
  72119. inflateInit2_((strm), (windowBits), ZLIB_VERSION, sizeof(z_stream))
  72120. #define inflateBackInit(strm, windowBits, window) \
  72121. inflateBackInit_((strm), (windowBits), (window), \
  72122. ZLIB_VERSION, sizeof(z_stream))
  72123. #if !defined(ZUTIL_H) && !defined(NO_DUMMY_DECL)
  72124. struct internal_state {int dummy;}; /* hack for buggy compilers */
  72125. #endif
  72126. ZEXTERN const char * ZEXPORT zError OF((int));
  72127. ZEXTERN int ZEXPORT inflateSyncPoint OF((z_streamp z));
  72128. ZEXTERN const uLongf * ZEXPORT get_crc_table OF((void));
  72129. #ifdef __cplusplus
  72130. }
  72131. #endif
  72132. #endif /* ZLIB_H */
  72133. /********* End of inlined file: zlib.h *********/
  72134. #undef OS_CODE
  72135. }
  72136. BEGIN_JUCE_NAMESPACE
  72137. using namespace zlibNamespace;
  72138. // internal helper object that holds the zlib structures so they don't have to be
  72139. // included publicly.
  72140. class GZIPCompressorHelper
  72141. {
  72142. private:
  72143. z_stream* stream;
  72144. uint8* data;
  72145. int dataSize, compLevel, strategy;
  72146. bool setParams;
  72147. public:
  72148. bool finished, shouldFinish;
  72149. GZIPCompressorHelper (const int compressionLevel, const bool nowrap)
  72150. : data (0),
  72151. dataSize (0),
  72152. compLevel (compressionLevel),
  72153. strategy (0),
  72154. setParams (true),
  72155. finished (false),
  72156. shouldFinish (false)
  72157. {
  72158. stream = (z_stream*) juce_calloc (sizeof (z_stream));
  72159. if (deflateInit2 (stream,
  72160. compLevel,
  72161. Z_DEFLATED,
  72162. nowrap ? -MAX_WBITS : MAX_WBITS,
  72163. 8,
  72164. strategy) != Z_OK)
  72165. {
  72166. juce_free (stream);
  72167. stream = 0;
  72168. }
  72169. }
  72170. ~GZIPCompressorHelper()
  72171. {
  72172. if (stream != 0)
  72173. {
  72174. deflateEnd (stream);
  72175. juce_free (stream);
  72176. }
  72177. }
  72178. bool needsInput() const throw()
  72179. {
  72180. return dataSize <= 0;
  72181. }
  72182. void setInput (uint8* const newData, const int size) throw()
  72183. {
  72184. data = newData;
  72185. dataSize = size;
  72186. }
  72187. int doNextBlock (uint8* const dest, const int destSize) throw()
  72188. {
  72189. if (stream != 0)
  72190. {
  72191. stream->next_in = data;
  72192. stream->next_out = dest;
  72193. stream->avail_in = dataSize;
  72194. stream->avail_out = destSize;
  72195. const int result = setParams ? deflateParams (stream, compLevel, strategy)
  72196. : deflate (stream, shouldFinish ? Z_FINISH : Z_NO_FLUSH);
  72197. setParams = false;
  72198. switch (result)
  72199. {
  72200. case Z_STREAM_END:
  72201. finished = true;
  72202. case Z_OK:
  72203. data += dataSize - stream->avail_in;
  72204. dataSize = stream->avail_in;
  72205. return destSize - stream->avail_out;
  72206. default:
  72207. break;
  72208. }
  72209. }
  72210. return 0;
  72211. }
  72212. };
  72213. const int gzipCompBufferSize = 32768;
  72214. GZIPCompressorOutputStream::GZIPCompressorOutputStream (OutputStream* const destStream_,
  72215. int compressionLevel,
  72216. const bool deleteDestStream_,
  72217. const bool noWrap)
  72218. : destStream (destStream_),
  72219. deleteDestStream (deleteDestStream_)
  72220. {
  72221. if (compressionLevel < 1 || compressionLevel > 9)
  72222. compressionLevel = -1;
  72223. helper = new GZIPCompressorHelper (compressionLevel, noWrap);
  72224. buffer = (uint8*) juce_malloc (gzipCompBufferSize);
  72225. }
  72226. GZIPCompressorOutputStream::~GZIPCompressorOutputStream()
  72227. {
  72228. flush();
  72229. GZIPCompressorHelper* const h = (GZIPCompressorHelper*) helper;
  72230. delete h;
  72231. juce_free (buffer);
  72232. if (deleteDestStream)
  72233. delete destStream;
  72234. }
  72235. void GZIPCompressorOutputStream::flush()
  72236. {
  72237. GZIPCompressorHelper* const h = (GZIPCompressorHelper*) helper;
  72238. if (! h->finished)
  72239. {
  72240. h->shouldFinish = true;
  72241. while (! h->finished)
  72242. doNextBlock();
  72243. }
  72244. destStream->flush();
  72245. }
  72246. bool GZIPCompressorOutputStream::write (const void* destBuffer, int howMany)
  72247. {
  72248. GZIPCompressorHelper* const h = (GZIPCompressorHelper*) helper;
  72249. if (! h->finished)
  72250. {
  72251. h->setInput ((uint8*) destBuffer, howMany);
  72252. while (! h->needsInput())
  72253. {
  72254. if (! doNextBlock())
  72255. return false;
  72256. }
  72257. }
  72258. return true;
  72259. }
  72260. bool GZIPCompressorOutputStream::doNextBlock()
  72261. {
  72262. GZIPCompressorHelper* const h = (GZIPCompressorHelper*) helper;
  72263. const int len = h->doNextBlock (buffer, gzipCompBufferSize);
  72264. if (len > 0)
  72265. return destStream->write (buffer, len);
  72266. else
  72267. return true;
  72268. }
  72269. int64 GZIPCompressorOutputStream::getPosition()
  72270. {
  72271. return destStream->getPosition();
  72272. }
  72273. bool GZIPCompressorOutputStream::setPosition (int64 /*newPosition*/)
  72274. {
  72275. jassertfalse // can't do it!
  72276. return false;
  72277. }
  72278. END_JUCE_NAMESPACE
  72279. /********* End of inlined file: juce_GZIPCompressorOutputStream.cpp *********/
  72280. /********* Start of inlined file: juce_GZIPDecompressorInputStream.cpp *********/
  72281. #if JUCE_MSVC
  72282. #pragma warning (push)
  72283. #pragma warning (disable: 4309 4305)
  72284. #endif
  72285. namespace zlibNamespace
  72286. {
  72287. extern "C"
  72288. {
  72289. #undef OS_CODE
  72290. #undef fdopen
  72291. #define ZLIB_INTERNAL
  72292. #define NO_DUMMY_DECL
  72293. /********* Start of inlined file: adler32.c *********/
  72294. /* @(#) $Id: adler32.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  72295. #define ZLIB_INTERNAL
  72296. #define BASE 65521UL /* largest prime smaller than 65536 */
  72297. #define NMAX 5552
  72298. /* NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 */
  72299. #define DO1(buf,i) {adler += (buf)[i]; sum2 += adler;}
  72300. #define DO2(buf,i) DO1(buf,i); DO1(buf,i+1);
  72301. #define DO4(buf,i) DO2(buf,i); DO2(buf,i+2);
  72302. #define DO8(buf,i) DO4(buf,i); DO4(buf,i+4);
  72303. #define DO16(buf) DO8(buf,0); DO8(buf,8);
  72304. /* use NO_DIVIDE if your processor does not do division in hardware */
  72305. #ifdef NO_DIVIDE
  72306. # define MOD(a) \
  72307. do { \
  72308. if (a >= (BASE << 16)) a -= (BASE << 16); \
  72309. if (a >= (BASE << 15)) a -= (BASE << 15); \
  72310. if (a >= (BASE << 14)) a -= (BASE << 14); \
  72311. if (a >= (BASE << 13)) a -= (BASE << 13); \
  72312. if (a >= (BASE << 12)) a -= (BASE << 12); \
  72313. if (a >= (BASE << 11)) a -= (BASE << 11); \
  72314. if (a >= (BASE << 10)) a -= (BASE << 10); \
  72315. if (a >= (BASE << 9)) a -= (BASE << 9); \
  72316. if (a >= (BASE << 8)) a -= (BASE << 8); \
  72317. if (a >= (BASE << 7)) a -= (BASE << 7); \
  72318. if (a >= (BASE << 6)) a -= (BASE << 6); \
  72319. if (a >= (BASE << 5)) a -= (BASE << 5); \
  72320. if (a >= (BASE << 4)) a -= (BASE << 4); \
  72321. if (a >= (BASE << 3)) a -= (BASE << 3); \
  72322. if (a >= (BASE << 2)) a -= (BASE << 2); \
  72323. if (a >= (BASE << 1)) a -= (BASE << 1); \
  72324. if (a >= BASE) a -= BASE; \
  72325. } while (0)
  72326. # define MOD4(a) \
  72327. do { \
  72328. if (a >= (BASE << 4)) a -= (BASE << 4); \
  72329. if (a >= (BASE << 3)) a -= (BASE << 3); \
  72330. if (a >= (BASE << 2)) a -= (BASE << 2); \
  72331. if (a >= (BASE << 1)) a -= (BASE << 1); \
  72332. if (a >= BASE) a -= BASE; \
  72333. } while (0)
  72334. #else
  72335. # define MOD(a) a %= BASE
  72336. # define MOD4(a) a %= BASE
  72337. #endif
  72338. /* ========================================================================= */
  72339. uLong ZEXPORT adler32(uLong adler, const Bytef *buf, uInt len)
  72340. {
  72341. unsigned long sum2;
  72342. unsigned n;
  72343. /* split Adler-32 into component sums */
  72344. sum2 = (adler >> 16) & 0xffff;
  72345. adler &= 0xffff;
  72346. /* in case user likes doing a byte at a time, keep it fast */
  72347. if (len == 1) {
  72348. adler += buf[0];
  72349. if (adler >= BASE)
  72350. adler -= BASE;
  72351. sum2 += adler;
  72352. if (sum2 >= BASE)
  72353. sum2 -= BASE;
  72354. return adler | (sum2 << 16);
  72355. }
  72356. /* initial Adler-32 value (deferred check for len == 1 speed) */
  72357. if (buf == Z_NULL)
  72358. return 1L;
  72359. /* in case short lengths are provided, keep it somewhat fast */
  72360. if (len < 16) {
  72361. while (len--) {
  72362. adler += *buf++;
  72363. sum2 += adler;
  72364. }
  72365. if (adler >= BASE)
  72366. adler -= BASE;
  72367. MOD4(sum2); /* only added so many BASE's */
  72368. return adler | (sum2 << 16);
  72369. }
  72370. /* do length NMAX blocks -- requires just one modulo operation */
  72371. while (len >= NMAX) {
  72372. len -= NMAX;
  72373. n = NMAX / 16; /* NMAX is divisible by 16 */
  72374. do {
  72375. DO16(buf); /* 16 sums unrolled */
  72376. buf += 16;
  72377. } while (--n);
  72378. MOD(adler);
  72379. MOD(sum2);
  72380. }
  72381. /* do remaining bytes (less than NMAX, still just one modulo) */
  72382. if (len) { /* avoid modulos if none remaining */
  72383. while (len >= 16) {
  72384. len -= 16;
  72385. DO16(buf);
  72386. buf += 16;
  72387. }
  72388. while (len--) {
  72389. adler += *buf++;
  72390. sum2 += adler;
  72391. }
  72392. MOD(adler);
  72393. MOD(sum2);
  72394. }
  72395. /* return recombined sums */
  72396. return adler | (sum2 << 16);
  72397. }
  72398. /* ========================================================================= */
  72399. uLong ZEXPORT adler32_combine(uLong adler1, uLong adler2, z_off_t len2)
  72400. {
  72401. unsigned long sum1;
  72402. unsigned long sum2;
  72403. unsigned rem;
  72404. /* the derivation of this formula is left as an exercise for the reader */
  72405. rem = (unsigned)(len2 % BASE);
  72406. sum1 = adler1 & 0xffff;
  72407. sum2 = rem * sum1;
  72408. MOD(sum2);
  72409. sum1 += (adler2 & 0xffff) + BASE - 1;
  72410. sum2 += ((adler1 >> 16) & 0xffff) + ((adler2 >> 16) & 0xffff) + BASE - rem;
  72411. if (sum1 > BASE) sum1 -= BASE;
  72412. if (sum1 > BASE) sum1 -= BASE;
  72413. if (sum2 > (BASE << 1)) sum2 -= (BASE << 1);
  72414. if (sum2 > BASE) sum2 -= BASE;
  72415. return sum1 | (sum2 << 16);
  72416. }
  72417. /********* End of inlined file: adler32.c *********/
  72418. /********* Start of inlined file: compress.c *********/
  72419. /* @(#) $Id: compress.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  72420. #define ZLIB_INTERNAL
  72421. /* ===========================================================================
  72422. Compresses the source buffer into the destination buffer. The level
  72423. parameter has the same meaning as in deflateInit. sourceLen is the byte
  72424. length of the source buffer. Upon entry, destLen is the total size of the
  72425. destination buffer, which must be at least 0.1% larger than sourceLen plus
  72426. 12 bytes. Upon exit, destLen is the actual size of the compressed buffer.
  72427. compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  72428. memory, Z_BUF_ERROR if there was not enough room in the output buffer,
  72429. Z_STREAM_ERROR if the level parameter is invalid.
  72430. */
  72431. int ZEXPORT compress2 (Bytef *dest, uLongf *destLen, const Bytef *source,
  72432. uLong sourceLen, int level)
  72433. {
  72434. z_stream stream;
  72435. int err;
  72436. stream.next_in = (Bytef*)source;
  72437. stream.avail_in = (uInt)sourceLen;
  72438. #ifdef MAXSEG_64K
  72439. /* Check for source > 64K on 16-bit machine: */
  72440. if ((uLong)stream.avail_in != sourceLen) return Z_BUF_ERROR;
  72441. #endif
  72442. stream.next_out = dest;
  72443. stream.avail_out = (uInt)*destLen;
  72444. if ((uLong)stream.avail_out != *destLen) return Z_BUF_ERROR;
  72445. stream.zalloc = (alloc_func)0;
  72446. stream.zfree = (free_func)0;
  72447. stream.opaque = (voidpf)0;
  72448. err = deflateInit(&stream, level);
  72449. if (err != Z_OK) return err;
  72450. err = deflate(&stream, Z_FINISH);
  72451. if (err != Z_STREAM_END) {
  72452. deflateEnd(&stream);
  72453. return err == Z_OK ? Z_BUF_ERROR : err;
  72454. }
  72455. *destLen = stream.total_out;
  72456. err = deflateEnd(&stream);
  72457. return err;
  72458. }
  72459. /* ===========================================================================
  72460. */
  72461. int ZEXPORT compress (Bytef *dest, uLongf *destLen, const Bytef *source, uLong sourceLen)
  72462. {
  72463. return compress2(dest, destLen, source, sourceLen, Z_DEFAULT_COMPRESSION);
  72464. }
  72465. /* ===========================================================================
  72466. If the default memLevel or windowBits for deflateInit() is changed, then
  72467. this function needs to be updated.
  72468. */
  72469. uLong ZEXPORT compressBound (uLong sourceLen)
  72470. {
  72471. return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) + 11;
  72472. }
  72473. /********* End of inlined file: compress.c *********/
  72474. #undef DO1
  72475. #undef DO8
  72476. /********* Start of inlined file: crc32.c *********/
  72477. /* @(#) $Id: crc32.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  72478. /*
  72479. Note on the use of DYNAMIC_CRC_TABLE: there is no mutex or semaphore
  72480. protection on the static variables used to control the first-use generation
  72481. of the crc tables. Therefore, if you #define DYNAMIC_CRC_TABLE, you should
  72482. first call get_crc_table() to initialize the tables before allowing more than
  72483. one thread to use crc32().
  72484. */
  72485. #ifdef MAKECRCH
  72486. # include <stdio.h>
  72487. # ifndef DYNAMIC_CRC_TABLE
  72488. # define DYNAMIC_CRC_TABLE
  72489. # endif /* !DYNAMIC_CRC_TABLE */
  72490. #endif /* MAKECRCH */
  72491. /********* Start of inlined file: zutil.h *********/
  72492. /* WARNING: this file should *not* be used by applications. It is
  72493. part of the implementation of the compression library and is
  72494. subject to change. Applications should only use zlib.h.
  72495. */
  72496. /* @(#) $Id: zutil.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  72497. #ifndef ZUTIL_H
  72498. #define ZUTIL_H
  72499. #define ZLIB_INTERNAL
  72500. #ifdef STDC
  72501. # ifndef _WIN32_WCE
  72502. # include <stddef.h>
  72503. # endif
  72504. # include <string.h>
  72505. # include <stdlib.h>
  72506. #endif
  72507. #ifdef NO_ERRNO_H
  72508. # ifdef _WIN32_WCE
  72509. /* The Microsoft C Run-Time Library for Windows CE doesn't have
  72510. * errno. We define it as a global variable to simplify porting.
  72511. * Its value is always 0 and should not be used. We rename it to
  72512. * avoid conflict with other libraries that use the same workaround.
  72513. */
  72514. # define errno z_errno
  72515. # endif
  72516. extern int errno;
  72517. #else
  72518. # ifndef _WIN32_WCE
  72519. # include <errno.h>
  72520. # endif
  72521. #endif
  72522. #ifndef local
  72523. # define local static
  72524. #endif
  72525. /* compile with -Dlocal if your debugger can't find static symbols */
  72526. typedef unsigned char uch;
  72527. typedef uch FAR uchf;
  72528. typedef unsigned short ush;
  72529. typedef ush FAR ushf;
  72530. typedef unsigned long ulg;
  72531. extern const char * const z_errmsg[10]; /* indexed by 2-zlib_error */
  72532. /* (size given to avoid silly warnings with Visual C++) */
  72533. #define ERR_MSG(err) z_errmsg[Z_NEED_DICT-(err)]
  72534. #define ERR_RETURN(strm,err) \
  72535. return (strm->msg = (char*)ERR_MSG(err), (err))
  72536. /* To be used only when the state is known to be valid */
  72537. /* common constants */
  72538. #ifndef DEF_WBITS
  72539. # define DEF_WBITS MAX_WBITS
  72540. #endif
  72541. /* default windowBits for decompression. MAX_WBITS is for compression only */
  72542. #if MAX_MEM_LEVEL >= 8
  72543. # define DEF_MEM_LEVEL 8
  72544. #else
  72545. # define DEF_MEM_LEVEL MAX_MEM_LEVEL
  72546. #endif
  72547. /* default memLevel */
  72548. #define STORED_BLOCK 0
  72549. #define STATIC_TREES 1
  72550. #define DYN_TREES 2
  72551. /* The three kinds of block type */
  72552. #define MIN_MATCH 3
  72553. #define MAX_MATCH 258
  72554. /* The minimum and maximum match lengths */
  72555. #define PRESET_DICT 0x20 /* preset dictionary flag in zlib header */
  72556. /* target dependencies */
  72557. #if defined(MSDOS) || (defined(WINDOWS) && !defined(WIN32))
  72558. # define OS_CODE 0x00
  72559. # if defined(__TURBOC__) || defined(__BORLANDC__)
  72560. # if(__STDC__ == 1) && (defined(__LARGE__) || defined(__COMPACT__))
  72561. /* Allow compilation with ANSI keywords only enabled */
  72562. void _Cdecl farfree( void *block );
  72563. void *_Cdecl farmalloc( unsigned long nbytes );
  72564. # else
  72565. # include <alloc.h>
  72566. # endif
  72567. # else /* MSC or DJGPP */
  72568. # include <malloc.h>
  72569. # endif
  72570. #endif
  72571. #ifdef AMIGA
  72572. # define OS_CODE 0x01
  72573. #endif
  72574. #if defined(VAXC) || defined(VMS)
  72575. # define OS_CODE 0x02
  72576. # define F_OPEN(name, mode) \
  72577. fopen((name), (mode), "mbc=60", "ctx=stm", "rfm=fix", "mrs=512")
  72578. #endif
  72579. #if defined(ATARI) || defined(atarist)
  72580. # define OS_CODE 0x05
  72581. #endif
  72582. #ifdef OS2
  72583. # define OS_CODE 0x06
  72584. # ifdef M_I86
  72585. #include <malloc.h>
  72586. # endif
  72587. #endif
  72588. #if defined(MACOS) || TARGET_OS_MAC
  72589. # define OS_CODE 0x07
  72590. # if defined(__MWERKS__) && __dest_os != __be_os && __dest_os != __win32_os
  72591. # include <unix.h> /* for fdopen */
  72592. # else
  72593. # ifndef fdopen
  72594. # define fdopen(fd,mode) NULL /* No fdopen() */
  72595. # endif
  72596. # endif
  72597. #endif
  72598. #ifdef TOPS20
  72599. # define OS_CODE 0x0a
  72600. #endif
  72601. #ifdef WIN32
  72602. # ifndef __CYGWIN__ /* Cygwin is Unix, not Win32 */
  72603. # define OS_CODE 0x0b
  72604. # endif
  72605. #endif
  72606. #ifdef __50SERIES /* Prime/PRIMOS */
  72607. # define OS_CODE 0x0f
  72608. #endif
  72609. #if defined(_BEOS_) || defined(RISCOS)
  72610. # define fdopen(fd,mode) NULL /* No fdopen() */
  72611. #endif
  72612. #if (defined(_MSC_VER) && (_MSC_VER > 600))
  72613. # if defined(_WIN32_WCE)
  72614. # define fdopen(fd,mode) NULL /* No fdopen() */
  72615. # ifndef _PTRDIFF_T_DEFINED
  72616. typedef int ptrdiff_t;
  72617. # define _PTRDIFF_T_DEFINED
  72618. # endif
  72619. # else
  72620. # define fdopen(fd,type) _fdopen(fd,type)
  72621. # endif
  72622. #endif
  72623. /* common defaults */
  72624. #ifndef OS_CODE
  72625. # define OS_CODE 0x03 /* assume Unix */
  72626. #endif
  72627. #ifndef F_OPEN
  72628. # define F_OPEN(name, mode) fopen((name), (mode))
  72629. #endif
  72630. /* functions */
  72631. #if defined(STDC99) || (defined(__TURBOC__) && __TURBOC__ >= 0x550)
  72632. # ifndef HAVE_VSNPRINTF
  72633. # define HAVE_VSNPRINTF
  72634. # endif
  72635. #endif
  72636. #if defined(__CYGWIN__)
  72637. # ifndef HAVE_VSNPRINTF
  72638. # define HAVE_VSNPRINTF
  72639. # endif
  72640. #endif
  72641. #ifndef HAVE_VSNPRINTF
  72642. # ifdef MSDOS
  72643. /* vsnprintf may exist on some MS-DOS compilers (DJGPP?),
  72644. but for now we just assume it doesn't. */
  72645. # define NO_vsnprintf
  72646. # endif
  72647. # ifdef __TURBOC__
  72648. # define NO_vsnprintf
  72649. # endif
  72650. # ifdef WIN32
  72651. /* In Win32, vsnprintf is available as the "non-ANSI" _vsnprintf. */
  72652. # if !defined(vsnprintf) && !defined(NO_vsnprintf)
  72653. # define vsnprintf _vsnprintf
  72654. # endif
  72655. # endif
  72656. # ifdef __SASC
  72657. # define NO_vsnprintf
  72658. # endif
  72659. #endif
  72660. #ifdef VMS
  72661. # define NO_vsnprintf
  72662. #endif
  72663. #if defined(pyr)
  72664. # define NO_MEMCPY
  72665. #endif
  72666. #if defined(SMALL_MEDIUM) && !defined(_MSC_VER) && !defined(__SC__)
  72667. /* Use our own functions for small and medium model with MSC <= 5.0.
  72668. * You may have to use the same strategy for Borland C (untested).
  72669. * The __SC__ check is for Symantec.
  72670. */
  72671. # define NO_MEMCPY
  72672. #endif
  72673. #if defined(STDC) && !defined(HAVE_MEMCPY) && !defined(NO_MEMCPY)
  72674. # define HAVE_MEMCPY
  72675. #endif
  72676. #ifdef HAVE_MEMCPY
  72677. # ifdef SMALL_MEDIUM /* MSDOS small or medium model */
  72678. # define zmemcpy _fmemcpy
  72679. # define zmemcmp _fmemcmp
  72680. # define zmemzero(dest, len) _fmemset(dest, 0, len)
  72681. # else
  72682. # define zmemcpy memcpy
  72683. # define zmemcmp memcmp
  72684. # define zmemzero(dest, len) memset(dest, 0, len)
  72685. # endif
  72686. #else
  72687. extern void zmemcpy OF((Bytef* dest, const Bytef* source, uInt len));
  72688. extern int zmemcmp OF((const Bytef* s1, const Bytef* s2, uInt len));
  72689. extern void zmemzero OF((Bytef* dest, uInt len));
  72690. #endif
  72691. /* Diagnostic functions */
  72692. #ifdef DEBUG
  72693. # include <stdio.h>
  72694. extern int z_verbose;
  72695. extern void z_error OF((char *m));
  72696. # define Assert(cond,msg) {if(!(cond)) z_error(msg);}
  72697. # define Trace(x) {if (z_verbose>=0) fprintf x ;}
  72698. # define Tracev(x) {if (z_verbose>0) fprintf x ;}
  72699. # define Tracevv(x) {if (z_verbose>1) fprintf x ;}
  72700. # define Tracec(c,x) {if (z_verbose>0 && (c)) fprintf x ;}
  72701. # define Tracecv(c,x) {if (z_verbose>1 && (c)) fprintf x ;}
  72702. #else
  72703. # define Assert(cond,msg)
  72704. # define Trace(x)
  72705. # define Tracev(x)
  72706. # define Tracevv(x)
  72707. # define Tracec(c,x)
  72708. # define Tracecv(c,x)
  72709. #endif
  72710. voidpf zcalloc OF((voidpf opaque, unsigned items, unsigned size));
  72711. void zcfree OF((voidpf opaque, voidpf ptr));
  72712. #define ZALLOC(strm, items, size) \
  72713. (*((strm)->zalloc))((strm)->opaque, (items), (size))
  72714. #define ZFREE(strm, addr) (*((strm)->zfree))((strm)->opaque, (voidpf)(addr))
  72715. #define TRY_FREE(s, p) {if (p) ZFREE(s, p);}
  72716. #endif /* ZUTIL_H */
  72717. /********* End of inlined file: zutil.h *********/
  72718. /* for STDC and FAR definitions */
  72719. #define local static
  72720. /* Find a four-byte integer type for crc32_little() and crc32_big(). */
  72721. #ifndef NOBYFOUR
  72722. # ifdef STDC /* need ANSI C limits.h to determine sizes */
  72723. # include <limits.h>
  72724. # define BYFOUR
  72725. # if (UINT_MAX == 0xffffffffUL)
  72726. typedef unsigned int u4;
  72727. # else
  72728. # if (ULONG_MAX == 0xffffffffUL)
  72729. typedef unsigned long u4;
  72730. # else
  72731. # if (USHRT_MAX == 0xffffffffUL)
  72732. typedef unsigned short u4;
  72733. # else
  72734. # undef BYFOUR /* can't find a four-byte integer type! */
  72735. # endif
  72736. # endif
  72737. # endif
  72738. # endif /* STDC */
  72739. #endif /* !NOBYFOUR */
  72740. /* Definitions for doing the crc four data bytes at a time. */
  72741. #ifdef BYFOUR
  72742. # define REV(w) (((w)>>24)+(((w)>>8)&0xff00)+ \
  72743. (((w)&0xff00)<<8)+(((w)&0xff)<<24))
  72744. local unsigned long crc32_little OF((unsigned long,
  72745. const unsigned char FAR *, unsigned));
  72746. local unsigned long crc32_big OF((unsigned long,
  72747. const unsigned char FAR *, unsigned));
  72748. # define TBLS 8
  72749. #else
  72750. # define TBLS 1
  72751. #endif /* BYFOUR */
  72752. /* Local functions for crc concatenation */
  72753. local unsigned long gf2_matrix_times OF((unsigned long *mat,
  72754. unsigned long vec));
  72755. local void gf2_matrix_square OF((unsigned long *square, unsigned long *mat));
  72756. #ifdef DYNAMIC_CRC_TABLE
  72757. local volatile int crc_table_empty = 1;
  72758. local unsigned long FAR crc_table[TBLS][256];
  72759. local void make_crc_table OF((void));
  72760. #ifdef MAKECRCH
  72761. local void write_table OF((FILE *, const unsigned long FAR *));
  72762. #endif /* MAKECRCH */
  72763. /*
  72764. Generate tables for a byte-wise 32-bit CRC calculation on the polynomial:
  72765. 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.
  72766. Polynomials over GF(2) are represented in binary, one bit per coefficient,
  72767. with the lowest powers in the most significant bit. Then adding polynomials
  72768. is just exclusive-or, and multiplying a polynomial by x is a right shift by
  72769. one. If we call the above polynomial p, and represent a byte as the
  72770. polynomial q, also with the lowest power in the most significant bit (so the
  72771. byte 0xb1 is the polynomial x^7+x^3+x+1), then the CRC is (q*x^32) mod p,
  72772. where a mod b means the remainder after dividing a by b.
  72773. This calculation is done using the shift-register method of multiplying and
  72774. taking the remainder. The register is initialized to zero, and for each
  72775. incoming bit, x^32 is added mod p to the register if the bit is a one (where
  72776. x^32 mod p is p+x^32 = x^26+...+1), and the register is multiplied mod p by
  72777. x (which is shifting right by one and adding x^32 mod p if the bit shifted
  72778. out is a one). We start with the highest power (least significant bit) of
  72779. q and repeat for all eight bits of q.
  72780. The first table is simply the CRC of all possible eight bit values. This is
  72781. all the information needed to generate CRCs on data a byte at a time for all
  72782. combinations of CRC register values and incoming bytes. The remaining tables
  72783. allow for word-at-a-time CRC calculation for both big-endian and little-
  72784. endian machines, where a word is four bytes.
  72785. */
  72786. local void make_crc_table()
  72787. {
  72788. unsigned long c;
  72789. int n, k;
  72790. unsigned long poly; /* polynomial exclusive-or pattern */
  72791. /* terms of polynomial defining this crc (except x^32): */
  72792. static volatile int first = 1; /* flag to limit concurrent making */
  72793. static const unsigned char p[] = {0,1,2,4,5,7,8,10,11,12,16,22,23,26};
  72794. /* See if another task is already doing this (not thread-safe, but better
  72795. than nothing -- significantly reduces duration of vulnerability in
  72796. case the advice about DYNAMIC_CRC_TABLE is ignored) */
  72797. if (first) {
  72798. first = 0;
  72799. /* make exclusive-or pattern from polynomial (0xedb88320UL) */
  72800. poly = 0UL;
  72801. for (n = 0; n < sizeof(p)/sizeof(unsigned char); n++)
  72802. poly |= 1UL << (31 - p[n]);
  72803. /* generate a crc for every 8-bit value */
  72804. for (n = 0; n < 256; n++) {
  72805. c = (unsigned long)n;
  72806. for (k = 0; k < 8; k++)
  72807. c = c & 1 ? poly ^ (c >> 1) : c >> 1;
  72808. crc_table[0][n] = c;
  72809. }
  72810. #ifdef BYFOUR
  72811. /* generate crc for each value followed by one, two, and three zeros,
  72812. and then the byte reversal of those as well as the first table */
  72813. for (n = 0; n < 256; n++) {
  72814. c = crc_table[0][n];
  72815. crc_table[4][n] = REV(c);
  72816. for (k = 1; k < 4; k++) {
  72817. c = crc_table[0][c & 0xff] ^ (c >> 8);
  72818. crc_table[k][n] = c;
  72819. crc_table[k + 4][n] = REV(c);
  72820. }
  72821. }
  72822. #endif /* BYFOUR */
  72823. crc_table_empty = 0;
  72824. }
  72825. else { /* not first */
  72826. /* wait for the other guy to finish (not efficient, but rare) */
  72827. while (crc_table_empty)
  72828. ;
  72829. }
  72830. #ifdef MAKECRCH
  72831. /* write out CRC tables to crc32.h */
  72832. {
  72833. FILE *out;
  72834. out = fopen("crc32.h", "w");
  72835. if (out == NULL) return;
  72836. fprintf(out, "/* crc32.h -- tables for rapid CRC calculation\n");
  72837. fprintf(out, " * Generated automatically by crc32.c\n */\n\n");
  72838. fprintf(out, "local const unsigned long FAR ");
  72839. fprintf(out, "crc_table[TBLS][256] =\n{\n {\n");
  72840. write_table(out, crc_table[0]);
  72841. # ifdef BYFOUR
  72842. fprintf(out, "#ifdef BYFOUR\n");
  72843. for (k = 1; k < 8; k++) {
  72844. fprintf(out, " },\n {\n");
  72845. write_table(out, crc_table[k]);
  72846. }
  72847. fprintf(out, "#endif\n");
  72848. # endif /* BYFOUR */
  72849. fprintf(out, " }\n};\n");
  72850. fclose(out);
  72851. }
  72852. #endif /* MAKECRCH */
  72853. }
  72854. #ifdef MAKECRCH
  72855. local void write_table(out, table)
  72856. FILE *out;
  72857. const unsigned long FAR *table;
  72858. {
  72859. int n;
  72860. for (n = 0; n < 256; n++)
  72861. fprintf(out, "%s0x%08lxUL%s", n % 5 ? "" : " ", table[n],
  72862. n == 255 ? "\n" : (n % 5 == 4 ? ",\n" : ", "));
  72863. }
  72864. #endif /* MAKECRCH */
  72865. #else /* !DYNAMIC_CRC_TABLE */
  72866. /* ========================================================================
  72867. * Tables of CRC-32s of all single-byte values, made by make_crc_table().
  72868. */
  72869. /********* Start of inlined file: crc32.h *********/
  72870. local const unsigned long FAR crc_table[TBLS][256] =
  72871. {
  72872. {
  72873. 0x00000000UL, 0x77073096UL, 0xee0e612cUL, 0x990951baUL, 0x076dc419UL,
  72874. 0x706af48fUL, 0xe963a535UL, 0x9e6495a3UL, 0x0edb8832UL, 0x79dcb8a4UL,
  72875. 0xe0d5e91eUL, 0x97d2d988UL, 0x09b64c2bUL, 0x7eb17cbdUL, 0xe7b82d07UL,
  72876. 0x90bf1d91UL, 0x1db71064UL, 0x6ab020f2UL, 0xf3b97148UL, 0x84be41deUL,
  72877. 0x1adad47dUL, 0x6ddde4ebUL, 0xf4d4b551UL, 0x83d385c7UL, 0x136c9856UL,
  72878. 0x646ba8c0UL, 0xfd62f97aUL, 0x8a65c9ecUL, 0x14015c4fUL, 0x63066cd9UL,
  72879. 0xfa0f3d63UL, 0x8d080df5UL, 0x3b6e20c8UL, 0x4c69105eUL, 0xd56041e4UL,
  72880. 0xa2677172UL, 0x3c03e4d1UL, 0x4b04d447UL, 0xd20d85fdUL, 0xa50ab56bUL,
  72881. 0x35b5a8faUL, 0x42b2986cUL, 0xdbbbc9d6UL, 0xacbcf940UL, 0x32d86ce3UL,
  72882. 0x45df5c75UL, 0xdcd60dcfUL, 0xabd13d59UL, 0x26d930acUL, 0x51de003aUL,
  72883. 0xc8d75180UL, 0xbfd06116UL, 0x21b4f4b5UL, 0x56b3c423UL, 0xcfba9599UL,
  72884. 0xb8bda50fUL, 0x2802b89eUL, 0x5f058808UL, 0xc60cd9b2UL, 0xb10be924UL,
  72885. 0x2f6f7c87UL, 0x58684c11UL, 0xc1611dabUL, 0xb6662d3dUL, 0x76dc4190UL,
  72886. 0x01db7106UL, 0x98d220bcUL, 0xefd5102aUL, 0x71b18589UL, 0x06b6b51fUL,
  72887. 0x9fbfe4a5UL, 0xe8b8d433UL, 0x7807c9a2UL, 0x0f00f934UL, 0x9609a88eUL,
  72888. 0xe10e9818UL, 0x7f6a0dbbUL, 0x086d3d2dUL, 0x91646c97UL, 0xe6635c01UL,
  72889. 0x6b6b51f4UL, 0x1c6c6162UL, 0x856530d8UL, 0xf262004eUL, 0x6c0695edUL,
  72890. 0x1b01a57bUL, 0x8208f4c1UL, 0xf50fc457UL, 0x65b0d9c6UL, 0x12b7e950UL,
  72891. 0x8bbeb8eaUL, 0xfcb9887cUL, 0x62dd1ddfUL, 0x15da2d49UL, 0x8cd37cf3UL,
  72892. 0xfbd44c65UL, 0x4db26158UL, 0x3ab551ceUL, 0xa3bc0074UL, 0xd4bb30e2UL,
  72893. 0x4adfa541UL, 0x3dd895d7UL, 0xa4d1c46dUL, 0xd3d6f4fbUL, 0x4369e96aUL,
  72894. 0x346ed9fcUL, 0xad678846UL, 0xda60b8d0UL, 0x44042d73UL, 0x33031de5UL,
  72895. 0xaa0a4c5fUL, 0xdd0d7cc9UL, 0x5005713cUL, 0x270241aaUL, 0xbe0b1010UL,
  72896. 0xc90c2086UL, 0x5768b525UL, 0x206f85b3UL, 0xb966d409UL, 0xce61e49fUL,
  72897. 0x5edef90eUL, 0x29d9c998UL, 0xb0d09822UL, 0xc7d7a8b4UL, 0x59b33d17UL,
  72898. 0x2eb40d81UL, 0xb7bd5c3bUL, 0xc0ba6cadUL, 0xedb88320UL, 0x9abfb3b6UL,
  72899. 0x03b6e20cUL, 0x74b1d29aUL, 0xead54739UL, 0x9dd277afUL, 0x04db2615UL,
  72900. 0x73dc1683UL, 0xe3630b12UL, 0x94643b84UL, 0x0d6d6a3eUL, 0x7a6a5aa8UL,
  72901. 0xe40ecf0bUL, 0x9309ff9dUL, 0x0a00ae27UL, 0x7d079eb1UL, 0xf00f9344UL,
  72902. 0x8708a3d2UL, 0x1e01f268UL, 0x6906c2feUL, 0xf762575dUL, 0x806567cbUL,
  72903. 0x196c3671UL, 0x6e6b06e7UL, 0xfed41b76UL, 0x89d32be0UL, 0x10da7a5aUL,
  72904. 0x67dd4accUL, 0xf9b9df6fUL, 0x8ebeeff9UL, 0x17b7be43UL, 0x60b08ed5UL,
  72905. 0xd6d6a3e8UL, 0xa1d1937eUL, 0x38d8c2c4UL, 0x4fdff252UL, 0xd1bb67f1UL,
  72906. 0xa6bc5767UL, 0x3fb506ddUL, 0x48b2364bUL, 0xd80d2bdaUL, 0xaf0a1b4cUL,
  72907. 0x36034af6UL, 0x41047a60UL, 0xdf60efc3UL, 0xa867df55UL, 0x316e8eefUL,
  72908. 0x4669be79UL, 0xcb61b38cUL, 0xbc66831aUL, 0x256fd2a0UL, 0x5268e236UL,
  72909. 0xcc0c7795UL, 0xbb0b4703UL, 0x220216b9UL, 0x5505262fUL, 0xc5ba3bbeUL,
  72910. 0xb2bd0b28UL, 0x2bb45a92UL, 0x5cb36a04UL, 0xc2d7ffa7UL, 0xb5d0cf31UL,
  72911. 0x2cd99e8bUL, 0x5bdeae1dUL, 0x9b64c2b0UL, 0xec63f226UL, 0x756aa39cUL,
  72912. 0x026d930aUL, 0x9c0906a9UL, 0xeb0e363fUL, 0x72076785UL, 0x05005713UL,
  72913. 0x95bf4a82UL, 0xe2b87a14UL, 0x7bb12baeUL, 0x0cb61b38UL, 0x92d28e9bUL,
  72914. 0xe5d5be0dUL, 0x7cdcefb7UL, 0x0bdbdf21UL, 0x86d3d2d4UL, 0xf1d4e242UL,
  72915. 0x68ddb3f8UL, 0x1fda836eUL, 0x81be16cdUL, 0xf6b9265bUL, 0x6fb077e1UL,
  72916. 0x18b74777UL, 0x88085ae6UL, 0xff0f6a70UL, 0x66063bcaUL, 0x11010b5cUL,
  72917. 0x8f659effUL, 0xf862ae69UL, 0x616bffd3UL, 0x166ccf45UL, 0xa00ae278UL,
  72918. 0xd70dd2eeUL, 0x4e048354UL, 0x3903b3c2UL, 0xa7672661UL, 0xd06016f7UL,
  72919. 0x4969474dUL, 0x3e6e77dbUL, 0xaed16a4aUL, 0xd9d65adcUL, 0x40df0b66UL,
  72920. 0x37d83bf0UL, 0xa9bcae53UL, 0xdebb9ec5UL, 0x47b2cf7fUL, 0x30b5ffe9UL,
  72921. 0xbdbdf21cUL, 0xcabac28aUL, 0x53b39330UL, 0x24b4a3a6UL, 0xbad03605UL,
  72922. 0xcdd70693UL, 0x54de5729UL, 0x23d967bfUL, 0xb3667a2eUL, 0xc4614ab8UL,
  72923. 0x5d681b02UL, 0x2a6f2b94UL, 0xb40bbe37UL, 0xc30c8ea1UL, 0x5a05df1bUL,
  72924. 0x2d02ef8dUL
  72925. #ifdef BYFOUR
  72926. },
  72927. {
  72928. 0x00000000UL, 0x191b3141UL, 0x32366282UL, 0x2b2d53c3UL, 0x646cc504UL,
  72929. 0x7d77f445UL, 0x565aa786UL, 0x4f4196c7UL, 0xc8d98a08UL, 0xd1c2bb49UL,
  72930. 0xfaefe88aUL, 0xe3f4d9cbUL, 0xacb54f0cUL, 0xb5ae7e4dUL, 0x9e832d8eUL,
  72931. 0x87981ccfUL, 0x4ac21251UL, 0x53d92310UL, 0x78f470d3UL, 0x61ef4192UL,
  72932. 0x2eaed755UL, 0x37b5e614UL, 0x1c98b5d7UL, 0x05838496UL, 0x821b9859UL,
  72933. 0x9b00a918UL, 0xb02dfadbUL, 0xa936cb9aUL, 0xe6775d5dUL, 0xff6c6c1cUL,
  72934. 0xd4413fdfUL, 0xcd5a0e9eUL, 0x958424a2UL, 0x8c9f15e3UL, 0xa7b24620UL,
  72935. 0xbea97761UL, 0xf1e8e1a6UL, 0xe8f3d0e7UL, 0xc3de8324UL, 0xdac5b265UL,
  72936. 0x5d5daeaaUL, 0x44469febUL, 0x6f6bcc28UL, 0x7670fd69UL, 0x39316baeUL,
  72937. 0x202a5aefUL, 0x0b07092cUL, 0x121c386dUL, 0xdf4636f3UL, 0xc65d07b2UL,
  72938. 0xed705471UL, 0xf46b6530UL, 0xbb2af3f7UL, 0xa231c2b6UL, 0x891c9175UL,
  72939. 0x9007a034UL, 0x179fbcfbUL, 0x0e848dbaUL, 0x25a9de79UL, 0x3cb2ef38UL,
  72940. 0x73f379ffUL, 0x6ae848beUL, 0x41c51b7dUL, 0x58de2a3cUL, 0xf0794f05UL,
  72941. 0xe9627e44UL, 0xc24f2d87UL, 0xdb541cc6UL, 0x94158a01UL, 0x8d0ebb40UL,
  72942. 0xa623e883UL, 0xbf38d9c2UL, 0x38a0c50dUL, 0x21bbf44cUL, 0x0a96a78fUL,
  72943. 0x138d96ceUL, 0x5ccc0009UL, 0x45d73148UL, 0x6efa628bUL, 0x77e153caUL,
  72944. 0xbabb5d54UL, 0xa3a06c15UL, 0x888d3fd6UL, 0x91960e97UL, 0xded79850UL,
  72945. 0xc7cca911UL, 0xece1fad2UL, 0xf5facb93UL, 0x7262d75cUL, 0x6b79e61dUL,
  72946. 0x4054b5deUL, 0x594f849fUL, 0x160e1258UL, 0x0f152319UL, 0x243870daUL,
  72947. 0x3d23419bUL, 0x65fd6ba7UL, 0x7ce65ae6UL, 0x57cb0925UL, 0x4ed03864UL,
  72948. 0x0191aea3UL, 0x188a9fe2UL, 0x33a7cc21UL, 0x2abcfd60UL, 0xad24e1afUL,
  72949. 0xb43fd0eeUL, 0x9f12832dUL, 0x8609b26cUL, 0xc94824abUL, 0xd05315eaUL,
  72950. 0xfb7e4629UL, 0xe2657768UL, 0x2f3f79f6UL, 0x362448b7UL, 0x1d091b74UL,
  72951. 0x04122a35UL, 0x4b53bcf2UL, 0x52488db3UL, 0x7965de70UL, 0x607eef31UL,
  72952. 0xe7e6f3feUL, 0xfefdc2bfUL, 0xd5d0917cUL, 0xcccba03dUL, 0x838a36faUL,
  72953. 0x9a9107bbUL, 0xb1bc5478UL, 0xa8a76539UL, 0x3b83984bUL, 0x2298a90aUL,
  72954. 0x09b5fac9UL, 0x10aecb88UL, 0x5fef5d4fUL, 0x46f46c0eUL, 0x6dd93fcdUL,
  72955. 0x74c20e8cUL, 0xf35a1243UL, 0xea412302UL, 0xc16c70c1UL, 0xd8774180UL,
  72956. 0x9736d747UL, 0x8e2de606UL, 0xa500b5c5UL, 0xbc1b8484UL, 0x71418a1aUL,
  72957. 0x685abb5bUL, 0x4377e898UL, 0x5a6cd9d9UL, 0x152d4f1eUL, 0x0c367e5fUL,
  72958. 0x271b2d9cUL, 0x3e001cddUL, 0xb9980012UL, 0xa0833153UL, 0x8bae6290UL,
  72959. 0x92b553d1UL, 0xddf4c516UL, 0xc4eff457UL, 0xefc2a794UL, 0xf6d996d5UL,
  72960. 0xae07bce9UL, 0xb71c8da8UL, 0x9c31de6bUL, 0x852aef2aUL, 0xca6b79edUL,
  72961. 0xd37048acUL, 0xf85d1b6fUL, 0xe1462a2eUL, 0x66de36e1UL, 0x7fc507a0UL,
  72962. 0x54e85463UL, 0x4df36522UL, 0x02b2f3e5UL, 0x1ba9c2a4UL, 0x30849167UL,
  72963. 0x299fa026UL, 0xe4c5aeb8UL, 0xfdde9ff9UL, 0xd6f3cc3aUL, 0xcfe8fd7bUL,
  72964. 0x80a96bbcUL, 0x99b25afdUL, 0xb29f093eUL, 0xab84387fUL, 0x2c1c24b0UL,
  72965. 0x350715f1UL, 0x1e2a4632UL, 0x07317773UL, 0x4870e1b4UL, 0x516bd0f5UL,
  72966. 0x7a468336UL, 0x635db277UL, 0xcbfad74eUL, 0xd2e1e60fUL, 0xf9ccb5ccUL,
  72967. 0xe0d7848dUL, 0xaf96124aUL, 0xb68d230bUL, 0x9da070c8UL, 0x84bb4189UL,
  72968. 0x03235d46UL, 0x1a386c07UL, 0x31153fc4UL, 0x280e0e85UL, 0x674f9842UL,
  72969. 0x7e54a903UL, 0x5579fac0UL, 0x4c62cb81UL, 0x8138c51fUL, 0x9823f45eUL,
  72970. 0xb30ea79dUL, 0xaa1596dcUL, 0xe554001bUL, 0xfc4f315aUL, 0xd7626299UL,
  72971. 0xce7953d8UL, 0x49e14f17UL, 0x50fa7e56UL, 0x7bd72d95UL, 0x62cc1cd4UL,
  72972. 0x2d8d8a13UL, 0x3496bb52UL, 0x1fbbe891UL, 0x06a0d9d0UL, 0x5e7ef3ecUL,
  72973. 0x4765c2adUL, 0x6c48916eUL, 0x7553a02fUL, 0x3a1236e8UL, 0x230907a9UL,
  72974. 0x0824546aUL, 0x113f652bUL, 0x96a779e4UL, 0x8fbc48a5UL, 0xa4911b66UL,
  72975. 0xbd8a2a27UL, 0xf2cbbce0UL, 0xebd08da1UL, 0xc0fdde62UL, 0xd9e6ef23UL,
  72976. 0x14bce1bdUL, 0x0da7d0fcUL, 0x268a833fUL, 0x3f91b27eUL, 0x70d024b9UL,
  72977. 0x69cb15f8UL, 0x42e6463bUL, 0x5bfd777aUL, 0xdc656bb5UL, 0xc57e5af4UL,
  72978. 0xee530937UL, 0xf7483876UL, 0xb809aeb1UL, 0xa1129ff0UL, 0x8a3fcc33UL,
  72979. 0x9324fd72UL
  72980. },
  72981. {
  72982. 0x00000000UL, 0x01c26a37UL, 0x0384d46eUL, 0x0246be59UL, 0x0709a8dcUL,
  72983. 0x06cbc2ebUL, 0x048d7cb2UL, 0x054f1685UL, 0x0e1351b8UL, 0x0fd13b8fUL,
  72984. 0x0d9785d6UL, 0x0c55efe1UL, 0x091af964UL, 0x08d89353UL, 0x0a9e2d0aUL,
  72985. 0x0b5c473dUL, 0x1c26a370UL, 0x1de4c947UL, 0x1fa2771eUL, 0x1e601d29UL,
  72986. 0x1b2f0bacUL, 0x1aed619bUL, 0x18abdfc2UL, 0x1969b5f5UL, 0x1235f2c8UL,
  72987. 0x13f798ffUL, 0x11b126a6UL, 0x10734c91UL, 0x153c5a14UL, 0x14fe3023UL,
  72988. 0x16b88e7aUL, 0x177ae44dUL, 0x384d46e0UL, 0x398f2cd7UL, 0x3bc9928eUL,
  72989. 0x3a0bf8b9UL, 0x3f44ee3cUL, 0x3e86840bUL, 0x3cc03a52UL, 0x3d025065UL,
  72990. 0x365e1758UL, 0x379c7d6fUL, 0x35dac336UL, 0x3418a901UL, 0x3157bf84UL,
  72991. 0x3095d5b3UL, 0x32d36beaUL, 0x331101ddUL, 0x246be590UL, 0x25a98fa7UL,
  72992. 0x27ef31feUL, 0x262d5bc9UL, 0x23624d4cUL, 0x22a0277bUL, 0x20e69922UL,
  72993. 0x2124f315UL, 0x2a78b428UL, 0x2bbade1fUL, 0x29fc6046UL, 0x283e0a71UL,
  72994. 0x2d711cf4UL, 0x2cb376c3UL, 0x2ef5c89aUL, 0x2f37a2adUL, 0x709a8dc0UL,
  72995. 0x7158e7f7UL, 0x731e59aeUL, 0x72dc3399UL, 0x7793251cUL, 0x76514f2bUL,
  72996. 0x7417f172UL, 0x75d59b45UL, 0x7e89dc78UL, 0x7f4bb64fUL, 0x7d0d0816UL,
  72997. 0x7ccf6221UL, 0x798074a4UL, 0x78421e93UL, 0x7a04a0caUL, 0x7bc6cafdUL,
  72998. 0x6cbc2eb0UL, 0x6d7e4487UL, 0x6f38fadeUL, 0x6efa90e9UL, 0x6bb5866cUL,
  72999. 0x6a77ec5bUL, 0x68315202UL, 0x69f33835UL, 0x62af7f08UL, 0x636d153fUL,
  73000. 0x612bab66UL, 0x60e9c151UL, 0x65a6d7d4UL, 0x6464bde3UL, 0x662203baUL,
  73001. 0x67e0698dUL, 0x48d7cb20UL, 0x4915a117UL, 0x4b531f4eUL, 0x4a917579UL,
  73002. 0x4fde63fcUL, 0x4e1c09cbUL, 0x4c5ab792UL, 0x4d98dda5UL, 0x46c49a98UL,
  73003. 0x4706f0afUL, 0x45404ef6UL, 0x448224c1UL, 0x41cd3244UL, 0x400f5873UL,
  73004. 0x4249e62aUL, 0x438b8c1dUL, 0x54f16850UL, 0x55330267UL, 0x5775bc3eUL,
  73005. 0x56b7d609UL, 0x53f8c08cUL, 0x523aaabbUL, 0x507c14e2UL, 0x51be7ed5UL,
  73006. 0x5ae239e8UL, 0x5b2053dfUL, 0x5966ed86UL, 0x58a487b1UL, 0x5deb9134UL,
  73007. 0x5c29fb03UL, 0x5e6f455aUL, 0x5fad2f6dUL, 0xe1351b80UL, 0xe0f771b7UL,
  73008. 0xe2b1cfeeUL, 0xe373a5d9UL, 0xe63cb35cUL, 0xe7fed96bUL, 0xe5b86732UL,
  73009. 0xe47a0d05UL, 0xef264a38UL, 0xeee4200fUL, 0xeca29e56UL, 0xed60f461UL,
  73010. 0xe82fe2e4UL, 0xe9ed88d3UL, 0xebab368aUL, 0xea695cbdUL, 0xfd13b8f0UL,
  73011. 0xfcd1d2c7UL, 0xfe976c9eUL, 0xff5506a9UL, 0xfa1a102cUL, 0xfbd87a1bUL,
  73012. 0xf99ec442UL, 0xf85cae75UL, 0xf300e948UL, 0xf2c2837fUL, 0xf0843d26UL,
  73013. 0xf1465711UL, 0xf4094194UL, 0xf5cb2ba3UL, 0xf78d95faUL, 0xf64fffcdUL,
  73014. 0xd9785d60UL, 0xd8ba3757UL, 0xdafc890eUL, 0xdb3ee339UL, 0xde71f5bcUL,
  73015. 0xdfb39f8bUL, 0xddf521d2UL, 0xdc374be5UL, 0xd76b0cd8UL, 0xd6a966efUL,
  73016. 0xd4efd8b6UL, 0xd52db281UL, 0xd062a404UL, 0xd1a0ce33UL, 0xd3e6706aUL,
  73017. 0xd2241a5dUL, 0xc55efe10UL, 0xc49c9427UL, 0xc6da2a7eUL, 0xc7184049UL,
  73018. 0xc25756ccUL, 0xc3953cfbUL, 0xc1d382a2UL, 0xc011e895UL, 0xcb4dafa8UL,
  73019. 0xca8fc59fUL, 0xc8c97bc6UL, 0xc90b11f1UL, 0xcc440774UL, 0xcd866d43UL,
  73020. 0xcfc0d31aUL, 0xce02b92dUL, 0x91af9640UL, 0x906dfc77UL, 0x922b422eUL,
  73021. 0x93e92819UL, 0x96a63e9cUL, 0x976454abUL, 0x9522eaf2UL, 0x94e080c5UL,
  73022. 0x9fbcc7f8UL, 0x9e7eadcfUL, 0x9c381396UL, 0x9dfa79a1UL, 0x98b56f24UL,
  73023. 0x99770513UL, 0x9b31bb4aUL, 0x9af3d17dUL, 0x8d893530UL, 0x8c4b5f07UL,
  73024. 0x8e0de15eUL, 0x8fcf8b69UL, 0x8a809decUL, 0x8b42f7dbUL, 0x89044982UL,
  73025. 0x88c623b5UL, 0x839a6488UL, 0x82580ebfUL, 0x801eb0e6UL, 0x81dcdad1UL,
  73026. 0x8493cc54UL, 0x8551a663UL, 0x8717183aUL, 0x86d5720dUL, 0xa9e2d0a0UL,
  73027. 0xa820ba97UL, 0xaa6604ceUL, 0xaba46ef9UL, 0xaeeb787cUL, 0xaf29124bUL,
  73028. 0xad6fac12UL, 0xacadc625UL, 0xa7f18118UL, 0xa633eb2fUL, 0xa4755576UL,
  73029. 0xa5b73f41UL, 0xa0f829c4UL, 0xa13a43f3UL, 0xa37cfdaaUL, 0xa2be979dUL,
  73030. 0xb5c473d0UL, 0xb40619e7UL, 0xb640a7beUL, 0xb782cd89UL, 0xb2cddb0cUL,
  73031. 0xb30fb13bUL, 0xb1490f62UL, 0xb08b6555UL, 0xbbd72268UL, 0xba15485fUL,
  73032. 0xb853f606UL, 0xb9919c31UL, 0xbcde8ab4UL, 0xbd1ce083UL, 0xbf5a5edaUL,
  73033. 0xbe9834edUL
  73034. },
  73035. {
  73036. 0x00000000UL, 0xb8bc6765UL, 0xaa09c88bUL, 0x12b5afeeUL, 0x8f629757UL,
  73037. 0x37def032UL, 0x256b5fdcUL, 0x9dd738b9UL, 0xc5b428efUL, 0x7d084f8aUL,
  73038. 0x6fbde064UL, 0xd7018701UL, 0x4ad6bfb8UL, 0xf26ad8ddUL, 0xe0df7733UL,
  73039. 0x58631056UL, 0x5019579fUL, 0xe8a530faUL, 0xfa109f14UL, 0x42acf871UL,
  73040. 0xdf7bc0c8UL, 0x67c7a7adUL, 0x75720843UL, 0xcdce6f26UL, 0x95ad7f70UL,
  73041. 0x2d111815UL, 0x3fa4b7fbUL, 0x8718d09eUL, 0x1acfe827UL, 0xa2738f42UL,
  73042. 0xb0c620acUL, 0x087a47c9UL, 0xa032af3eUL, 0x188ec85bUL, 0x0a3b67b5UL,
  73043. 0xb28700d0UL, 0x2f503869UL, 0x97ec5f0cUL, 0x8559f0e2UL, 0x3de59787UL,
  73044. 0x658687d1UL, 0xdd3ae0b4UL, 0xcf8f4f5aUL, 0x7733283fUL, 0xeae41086UL,
  73045. 0x525877e3UL, 0x40edd80dUL, 0xf851bf68UL, 0xf02bf8a1UL, 0x48979fc4UL,
  73046. 0x5a22302aUL, 0xe29e574fUL, 0x7f496ff6UL, 0xc7f50893UL, 0xd540a77dUL,
  73047. 0x6dfcc018UL, 0x359fd04eUL, 0x8d23b72bUL, 0x9f9618c5UL, 0x272a7fa0UL,
  73048. 0xbafd4719UL, 0x0241207cUL, 0x10f48f92UL, 0xa848e8f7UL, 0x9b14583dUL,
  73049. 0x23a83f58UL, 0x311d90b6UL, 0x89a1f7d3UL, 0x1476cf6aUL, 0xaccaa80fUL,
  73050. 0xbe7f07e1UL, 0x06c36084UL, 0x5ea070d2UL, 0xe61c17b7UL, 0xf4a9b859UL,
  73051. 0x4c15df3cUL, 0xd1c2e785UL, 0x697e80e0UL, 0x7bcb2f0eUL, 0xc377486bUL,
  73052. 0xcb0d0fa2UL, 0x73b168c7UL, 0x6104c729UL, 0xd9b8a04cUL, 0x446f98f5UL,
  73053. 0xfcd3ff90UL, 0xee66507eUL, 0x56da371bUL, 0x0eb9274dUL, 0xb6054028UL,
  73054. 0xa4b0efc6UL, 0x1c0c88a3UL, 0x81dbb01aUL, 0x3967d77fUL, 0x2bd27891UL,
  73055. 0x936e1ff4UL, 0x3b26f703UL, 0x839a9066UL, 0x912f3f88UL, 0x299358edUL,
  73056. 0xb4446054UL, 0x0cf80731UL, 0x1e4da8dfUL, 0xa6f1cfbaUL, 0xfe92dfecUL,
  73057. 0x462eb889UL, 0x549b1767UL, 0xec277002UL, 0x71f048bbUL, 0xc94c2fdeUL,
  73058. 0xdbf98030UL, 0x6345e755UL, 0x6b3fa09cUL, 0xd383c7f9UL, 0xc1366817UL,
  73059. 0x798a0f72UL, 0xe45d37cbUL, 0x5ce150aeUL, 0x4e54ff40UL, 0xf6e89825UL,
  73060. 0xae8b8873UL, 0x1637ef16UL, 0x048240f8UL, 0xbc3e279dUL, 0x21e91f24UL,
  73061. 0x99557841UL, 0x8be0d7afUL, 0x335cb0caUL, 0xed59b63bUL, 0x55e5d15eUL,
  73062. 0x47507eb0UL, 0xffec19d5UL, 0x623b216cUL, 0xda874609UL, 0xc832e9e7UL,
  73063. 0x708e8e82UL, 0x28ed9ed4UL, 0x9051f9b1UL, 0x82e4565fUL, 0x3a58313aUL,
  73064. 0xa78f0983UL, 0x1f336ee6UL, 0x0d86c108UL, 0xb53aa66dUL, 0xbd40e1a4UL,
  73065. 0x05fc86c1UL, 0x1749292fUL, 0xaff54e4aUL, 0x322276f3UL, 0x8a9e1196UL,
  73066. 0x982bbe78UL, 0x2097d91dUL, 0x78f4c94bUL, 0xc048ae2eUL, 0xd2fd01c0UL,
  73067. 0x6a4166a5UL, 0xf7965e1cUL, 0x4f2a3979UL, 0x5d9f9697UL, 0xe523f1f2UL,
  73068. 0x4d6b1905UL, 0xf5d77e60UL, 0xe762d18eUL, 0x5fdeb6ebUL, 0xc2098e52UL,
  73069. 0x7ab5e937UL, 0x680046d9UL, 0xd0bc21bcUL, 0x88df31eaUL, 0x3063568fUL,
  73070. 0x22d6f961UL, 0x9a6a9e04UL, 0x07bda6bdUL, 0xbf01c1d8UL, 0xadb46e36UL,
  73071. 0x15080953UL, 0x1d724e9aUL, 0xa5ce29ffUL, 0xb77b8611UL, 0x0fc7e174UL,
  73072. 0x9210d9cdUL, 0x2aacbea8UL, 0x38191146UL, 0x80a57623UL, 0xd8c66675UL,
  73073. 0x607a0110UL, 0x72cfaefeUL, 0xca73c99bUL, 0x57a4f122UL, 0xef189647UL,
  73074. 0xfdad39a9UL, 0x45115eccUL, 0x764dee06UL, 0xcef18963UL, 0xdc44268dUL,
  73075. 0x64f841e8UL, 0xf92f7951UL, 0x41931e34UL, 0x5326b1daUL, 0xeb9ad6bfUL,
  73076. 0xb3f9c6e9UL, 0x0b45a18cUL, 0x19f00e62UL, 0xa14c6907UL, 0x3c9b51beUL,
  73077. 0x842736dbUL, 0x96929935UL, 0x2e2efe50UL, 0x2654b999UL, 0x9ee8defcUL,
  73078. 0x8c5d7112UL, 0x34e11677UL, 0xa9362eceUL, 0x118a49abUL, 0x033fe645UL,
  73079. 0xbb838120UL, 0xe3e09176UL, 0x5b5cf613UL, 0x49e959fdUL, 0xf1553e98UL,
  73080. 0x6c820621UL, 0xd43e6144UL, 0xc68bceaaUL, 0x7e37a9cfUL, 0xd67f4138UL,
  73081. 0x6ec3265dUL, 0x7c7689b3UL, 0xc4caeed6UL, 0x591dd66fUL, 0xe1a1b10aUL,
  73082. 0xf3141ee4UL, 0x4ba87981UL, 0x13cb69d7UL, 0xab770eb2UL, 0xb9c2a15cUL,
  73083. 0x017ec639UL, 0x9ca9fe80UL, 0x241599e5UL, 0x36a0360bUL, 0x8e1c516eUL,
  73084. 0x866616a7UL, 0x3eda71c2UL, 0x2c6fde2cUL, 0x94d3b949UL, 0x090481f0UL,
  73085. 0xb1b8e695UL, 0xa30d497bUL, 0x1bb12e1eUL, 0x43d23e48UL, 0xfb6e592dUL,
  73086. 0xe9dbf6c3UL, 0x516791a6UL, 0xccb0a91fUL, 0x740cce7aUL, 0x66b96194UL,
  73087. 0xde0506f1UL
  73088. },
  73089. {
  73090. 0x00000000UL, 0x96300777UL, 0x2c610eeeUL, 0xba510999UL, 0x19c46d07UL,
  73091. 0x8ff46a70UL, 0x35a563e9UL, 0xa395649eUL, 0x3288db0eUL, 0xa4b8dc79UL,
  73092. 0x1ee9d5e0UL, 0x88d9d297UL, 0x2b4cb609UL, 0xbd7cb17eUL, 0x072db8e7UL,
  73093. 0x911dbf90UL, 0x6410b71dUL, 0xf220b06aUL, 0x4871b9f3UL, 0xde41be84UL,
  73094. 0x7dd4da1aUL, 0xebe4dd6dUL, 0x51b5d4f4UL, 0xc785d383UL, 0x56986c13UL,
  73095. 0xc0a86b64UL, 0x7af962fdUL, 0xecc9658aUL, 0x4f5c0114UL, 0xd96c0663UL,
  73096. 0x633d0ffaUL, 0xf50d088dUL, 0xc8206e3bUL, 0x5e10694cUL, 0xe44160d5UL,
  73097. 0x727167a2UL, 0xd1e4033cUL, 0x47d4044bUL, 0xfd850dd2UL, 0x6bb50aa5UL,
  73098. 0xfaa8b535UL, 0x6c98b242UL, 0xd6c9bbdbUL, 0x40f9bcacUL, 0xe36cd832UL,
  73099. 0x755cdf45UL, 0xcf0dd6dcUL, 0x593dd1abUL, 0xac30d926UL, 0x3a00de51UL,
  73100. 0x8051d7c8UL, 0x1661d0bfUL, 0xb5f4b421UL, 0x23c4b356UL, 0x9995bacfUL,
  73101. 0x0fa5bdb8UL, 0x9eb80228UL, 0x0888055fUL, 0xb2d90cc6UL, 0x24e90bb1UL,
  73102. 0x877c6f2fUL, 0x114c6858UL, 0xab1d61c1UL, 0x3d2d66b6UL, 0x9041dc76UL,
  73103. 0x0671db01UL, 0xbc20d298UL, 0x2a10d5efUL, 0x8985b171UL, 0x1fb5b606UL,
  73104. 0xa5e4bf9fUL, 0x33d4b8e8UL, 0xa2c90778UL, 0x34f9000fUL, 0x8ea80996UL,
  73105. 0x18980ee1UL, 0xbb0d6a7fUL, 0x2d3d6d08UL, 0x976c6491UL, 0x015c63e6UL,
  73106. 0xf4516b6bUL, 0x62616c1cUL, 0xd8306585UL, 0x4e0062f2UL, 0xed95066cUL,
  73107. 0x7ba5011bUL, 0xc1f40882UL, 0x57c40ff5UL, 0xc6d9b065UL, 0x50e9b712UL,
  73108. 0xeab8be8bUL, 0x7c88b9fcUL, 0xdf1ddd62UL, 0x492dda15UL, 0xf37cd38cUL,
  73109. 0x654cd4fbUL, 0x5861b24dUL, 0xce51b53aUL, 0x7400bca3UL, 0xe230bbd4UL,
  73110. 0x41a5df4aUL, 0xd795d83dUL, 0x6dc4d1a4UL, 0xfbf4d6d3UL, 0x6ae96943UL,
  73111. 0xfcd96e34UL, 0x468867adUL, 0xd0b860daUL, 0x732d0444UL, 0xe51d0333UL,
  73112. 0x5f4c0aaaUL, 0xc97c0dddUL, 0x3c710550UL, 0xaa410227UL, 0x10100bbeUL,
  73113. 0x86200cc9UL, 0x25b56857UL, 0xb3856f20UL, 0x09d466b9UL, 0x9fe461ceUL,
  73114. 0x0ef9de5eUL, 0x98c9d929UL, 0x2298d0b0UL, 0xb4a8d7c7UL, 0x173db359UL,
  73115. 0x810db42eUL, 0x3b5cbdb7UL, 0xad6cbac0UL, 0x2083b8edUL, 0xb6b3bf9aUL,
  73116. 0x0ce2b603UL, 0x9ad2b174UL, 0x3947d5eaUL, 0xaf77d29dUL, 0x1526db04UL,
  73117. 0x8316dc73UL, 0x120b63e3UL, 0x843b6494UL, 0x3e6a6d0dUL, 0xa85a6a7aUL,
  73118. 0x0bcf0ee4UL, 0x9dff0993UL, 0x27ae000aUL, 0xb19e077dUL, 0x44930ff0UL,
  73119. 0xd2a30887UL, 0x68f2011eUL, 0xfec20669UL, 0x5d5762f7UL, 0xcb676580UL,
  73120. 0x71366c19UL, 0xe7066b6eUL, 0x761bd4feUL, 0xe02bd389UL, 0x5a7ada10UL,
  73121. 0xcc4add67UL, 0x6fdfb9f9UL, 0xf9efbe8eUL, 0x43beb717UL, 0xd58eb060UL,
  73122. 0xe8a3d6d6UL, 0x7e93d1a1UL, 0xc4c2d838UL, 0x52f2df4fUL, 0xf167bbd1UL,
  73123. 0x6757bca6UL, 0xdd06b53fUL, 0x4b36b248UL, 0xda2b0dd8UL, 0x4c1b0aafUL,
  73124. 0xf64a0336UL, 0x607a0441UL, 0xc3ef60dfUL, 0x55df67a8UL, 0xef8e6e31UL,
  73125. 0x79be6946UL, 0x8cb361cbUL, 0x1a8366bcUL, 0xa0d26f25UL, 0x36e26852UL,
  73126. 0x95770cccUL, 0x03470bbbUL, 0xb9160222UL, 0x2f260555UL, 0xbe3bbac5UL,
  73127. 0x280bbdb2UL, 0x925ab42bUL, 0x046ab35cUL, 0xa7ffd7c2UL, 0x31cfd0b5UL,
  73128. 0x8b9ed92cUL, 0x1daede5bUL, 0xb0c2649bUL, 0x26f263ecUL, 0x9ca36a75UL,
  73129. 0x0a936d02UL, 0xa906099cUL, 0x3f360eebUL, 0x85670772UL, 0x13570005UL,
  73130. 0x824abf95UL, 0x147ab8e2UL, 0xae2bb17bUL, 0x381bb60cUL, 0x9b8ed292UL,
  73131. 0x0dbed5e5UL, 0xb7efdc7cUL, 0x21dfdb0bUL, 0xd4d2d386UL, 0x42e2d4f1UL,
  73132. 0xf8b3dd68UL, 0x6e83da1fUL, 0xcd16be81UL, 0x5b26b9f6UL, 0xe177b06fUL,
  73133. 0x7747b718UL, 0xe65a0888UL, 0x706a0fffUL, 0xca3b0666UL, 0x5c0b0111UL,
  73134. 0xff9e658fUL, 0x69ae62f8UL, 0xd3ff6b61UL, 0x45cf6c16UL, 0x78e20aa0UL,
  73135. 0xeed20dd7UL, 0x5483044eUL, 0xc2b30339UL, 0x612667a7UL, 0xf71660d0UL,
  73136. 0x4d476949UL, 0xdb776e3eUL, 0x4a6ad1aeUL, 0xdc5ad6d9UL, 0x660bdf40UL,
  73137. 0xf03bd837UL, 0x53aebca9UL, 0xc59ebbdeUL, 0x7fcfb247UL, 0xe9ffb530UL,
  73138. 0x1cf2bdbdUL, 0x8ac2bacaUL, 0x3093b353UL, 0xa6a3b424UL, 0x0536d0baUL,
  73139. 0x9306d7cdUL, 0x2957de54UL, 0xbf67d923UL, 0x2e7a66b3UL, 0xb84a61c4UL,
  73140. 0x021b685dUL, 0x942b6f2aUL, 0x37be0bb4UL, 0xa18e0cc3UL, 0x1bdf055aUL,
  73141. 0x8def022dUL
  73142. },
  73143. {
  73144. 0x00000000UL, 0x41311b19UL, 0x82623632UL, 0xc3532d2bUL, 0x04c56c64UL,
  73145. 0x45f4777dUL, 0x86a75a56UL, 0xc796414fUL, 0x088ad9c8UL, 0x49bbc2d1UL,
  73146. 0x8ae8effaUL, 0xcbd9f4e3UL, 0x0c4fb5acUL, 0x4d7eaeb5UL, 0x8e2d839eUL,
  73147. 0xcf1c9887UL, 0x5112c24aUL, 0x1023d953UL, 0xd370f478UL, 0x9241ef61UL,
  73148. 0x55d7ae2eUL, 0x14e6b537UL, 0xd7b5981cUL, 0x96848305UL, 0x59981b82UL,
  73149. 0x18a9009bUL, 0xdbfa2db0UL, 0x9acb36a9UL, 0x5d5d77e6UL, 0x1c6c6cffUL,
  73150. 0xdf3f41d4UL, 0x9e0e5acdUL, 0xa2248495UL, 0xe3159f8cUL, 0x2046b2a7UL,
  73151. 0x6177a9beUL, 0xa6e1e8f1UL, 0xe7d0f3e8UL, 0x2483dec3UL, 0x65b2c5daUL,
  73152. 0xaaae5d5dUL, 0xeb9f4644UL, 0x28cc6b6fUL, 0x69fd7076UL, 0xae6b3139UL,
  73153. 0xef5a2a20UL, 0x2c09070bUL, 0x6d381c12UL, 0xf33646dfUL, 0xb2075dc6UL,
  73154. 0x715470edUL, 0x30656bf4UL, 0xf7f32abbUL, 0xb6c231a2UL, 0x75911c89UL,
  73155. 0x34a00790UL, 0xfbbc9f17UL, 0xba8d840eUL, 0x79dea925UL, 0x38efb23cUL,
  73156. 0xff79f373UL, 0xbe48e86aUL, 0x7d1bc541UL, 0x3c2ade58UL, 0x054f79f0UL,
  73157. 0x447e62e9UL, 0x872d4fc2UL, 0xc61c54dbUL, 0x018a1594UL, 0x40bb0e8dUL,
  73158. 0x83e823a6UL, 0xc2d938bfUL, 0x0dc5a038UL, 0x4cf4bb21UL, 0x8fa7960aUL,
  73159. 0xce968d13UL, 0x0900cc5cUL, 0x4831d745UL, 0x8b62fa6eUL, 0xca53e177UL,
  73160. 0x545dbbbaUL, 0x156ca0a3UL, 0xd63f8d88UL, 0x970e9691UL, 0x5098d7deUL,
  73161. 0x11a9ccc7UL, 0xd2fae1ecUL, 0x93cbfaf5UL, 0x5cd76272UL, 0x1de6796bUL,
  73162. 0xdeb55440UL, 0x9f844f59UL, 0x58120e16UL, 0x1923150fUL, 0xda703824UL,
  73163. 0x9b41233dUL, 0xa76bfd65UL, 0xe65ae67cUL, 0x2509cb57UL, 0x6438d04eUL,
  73164. 0xa3ae9101UL, 0xe29f8a18UL, 0x21cca733UL, 0x60fdbc2aUL, 0xafe124adUL,
  73165. 0xeed03fb4UL, 0x2d83129fUL, 0x6cb20986UL, 0xab2448c9UL, 0xea1553d0UL,
  73166. 0x29467efbUL, 0x687765e2UL, 0xf6793f2fUL, 0xb7482436UL, 0x741b091dUL,
  73167. 0x352a1204UL, 0xf2bc534bUL, 0xb38d4852UL, 0x70de6579UL, 0x31ef7e60UL,
  73168. 0xfef3e6e7UL, 0xbfc2fdfeUL, 0x7c91d0d5UL, 0x3da0cbccUL, 0xfa368a83UL,
  73169. 0xbb07919aUL, 0x7854bcb1UL, 0x3965a7a8UL, 0x4b98833bUL, 0x0aa99822UL,
  73170. 0xc9fab509UL, 0x88cbae10UL, 0x4f5def5fUL, 0x0e6cf446UL, 0xcd3fd96dUL,
  73171. 0x8c0ec274UL, 0x43125af3UL, 0x022341eaUL, 0xc1706cc1UL, 0x804177d8UL,
  73172. 0x47d73697UL, 0x06e62d8eUL, 0xc5b500a5UL, 0x84841bbcUL, 0x1a8a4171UL,
  73173. 0x5bbb5a68UL, 0x98e87743UL, 0xd9d96c5aUL, 0x1e4f2d15UL, 0x5f7e360cUL,
  73174. 0x9c2d1b27UL, 0xdd1c003eUL, 0x120098b9UL, 0x533183a0UL, 0x9062ae8bUL,
  73175. 0xd153b592UL, 0x16c5f4ddUL, 0x57f4efc4UL, 0x94a7c2efUL, 0xd596d9f6UL,
  73176. 0xe9bc07aeUL, 0xa88d1cb7UL, 0x6bde319cUL, 0x2aef2a85UL, 0xed796bcaUL,
  73177. 0xac4870d3UL, 0x6f1b5df8UL, 0x2e2a46e1UL, 0xe136de66UL, 0xa007c57fUL,
  73178. 0x6354e854UL, 0x2265f34dUL, 0xe5f3b202UL, 0xa4c2a91bUL, 0x67918430UL,
  73179. 0x26a09f29UL, 0xb8aec5e4UL, 0xf99fdefdUL, 0x3accf3d6UL, 0x7bfde8cfUL,
  73180. 0xbc6ba980UL, 0xfd5ab299UL, 0x3e099fb2UL, 0x7f3884abUL, 0xb0241c2cUL,
  73181. 0xf1150735UL, 0x32462a1eUL, 0x73773107UL, 0xb4e17048UL, 0xf5d06b51UL,
  73182. 0x3683467aUL, 0x77b25d63UL, 0x4ed7facbUL, 0x0fe6e1d2UL, 0xccb5ccf9UL,
  73183. 0x8d84d7e0UL, 0x4a1296afUL, 0x0b238db6UL, 0xc870a09dUL, 0x8941bb84UL,
  73184. 0x465d2303UL, 0x076c381aUL, 0xc43f1531UL, 0x850e0e28UL, 0x42984f67UL,
  73185. 0x03a9547eUL, 0xc0fa7955UL, 0x81cb624cUL, 0x1fc53881UL, 0x5ef42398UL,
  73186. 0x9da70eb3UL, 0xdc9615aaUL, 0x1b0054e5UL, 0x5a314ffcUL, 0x996262d7UL,
  73187. 0xd85379ceUL, 0x174fe149UL, 0x567efa50UL, 0x952dd77bUL, 0xd41ccc62UL,
  73188. 0x138a8d2dUL, 0x52bb9634UL, 0x91e8bb1fUL, 0xd0d9a006UL, 0xecf37e5eUL,
  73189. 0xadc26547UL, 0x6e91486cUL, 0x2fa05375UL, 0xe836123aUL, 0xa9070923UL,
  73190. 0x6a542408UL, 0x2b653f11UL, 0xe479a796UL, 0xa548bc8fUL, 0x661b91a4UL,
  73191. 0x272a8abdUL, 0xe0bccbf2UL, 0xa18dd0ebUL, 0x62defdc0UL, 0x23efe6d9UL,
  73192. 0xbde1bc14UL, 0xfcd0a70dUL, 0x3f838a26UL, 0x7eb2913fUL, 0xb924d070UL,
  73193. 0xf815cb69UL, 0x3b46e642UL, 0x7a77fd5bUL, 0xb56b65dcUL, 0xf45a7ec5UL,
  73194. 0x370953eeUL, 0x763848f7UL, 0xb1ae09b8UL, 0xf09f12a1UL, 0x33cc3f8aUL,
  73195. 0x72fd2493UL
  73196. },
  73197. {
  73198. 0x00000000UL, 0x376ac201UL, 0x6ed48403UL, 0x59be4602UL, 0xdca80907UL,
  73199. 0xebc2cb06UL, 0xb27c8d04UL, 0x85164f05UL, 0xb851130eUL, 0x8f3bd10fUL,
  73200. 0xd685970dUL, 0xe1ef550cUL, 0x64f91a09UL, 0x5393d808UL, 0x0a2d9e0aUL,
  73201. 0x3d475c0bUL, 0x70a3261cUL, 0x47c9e41dUL, 0x1e77a21fUL, 0x291d601eUL,
  73202. 0xac0b2f1bUL, 0x9b61ed1aUL, 0xc2dfab18UL, 0xf5b56919UL, 0xc8f23512UL,
  73203. 0xff98f713UL, 0xa626b111UL, 0x914c7310UL, 0x145a3c15UL, 0x2330fe14UL,
  73204. 0x7a8eb816UL, 0x4de47a17UL, 0xe0464d38UL, 0xd72c8f39UL, 0x8e92c93bUL,
  73205. 0xb9f80b3aUL, 0x3cee443fUL, 0x0b84863eUL, 0x523ac03cUL, 0x6550023dUL,
  73206. 0x58175e36UL, 0x6f7d9c37UL, 0x36c3da35UL, 0x01a91834UL, 0x84bf5731UL,
  73207. 0xb3d59530UL, 0xea6bd332UL, 0xdd011133UL, 0x90e56b24UL, 0xa78fa925UL,
  73208. 0xfe31ef27UL, 0xc95b2d26UL, 0x4c4d6223UL, 0x7b27a022UL, 0x2299e620UL,
  73209. 0x15f32421UL, 0x28b4782aUL, 0x1fdeba2bUL, 0x4660fc29UL, 0x710a3e28UL,
  73210. 0xf41c712dUL, 0xc376b32cUL, 0x9ac8f52eUL, 0xada2372fUL, 0xc08d9a70UL,
  73211. 0xf7e75871UL, 0xae591e73UL, 0x9933dc72UL, 0x1c259377UL, 0x2b4f5176UL,
  73212. 0x72f11774UL, 0x459bd575UL, 0x78dc897eUL, 0x4fb64b7fUL, 0x16080d7dUL,
  73213. 0x2162cf7cUL, 0xa4748079UL, 0x931e4278UL, 0xcaa0047aUL, 0xfdcac67bUL,
  73214. 0xb02ebc6cUL, 0x87447e6dUL, 0xdefa386fUL, 0xe990fa6eUL, 0x6c86b56bUL,
  73215. 0x5bec776aUL, 0x02523168UL, 0x3538f369UL, 0x087faf62UL, 0x3f156d63UL,
  73216. 0x66ab2b61UL, 0x51c1e960UL, 0xd4d7a665UL, 0xe3bd6464UL, 0xba032266UL,
  73217. 0x8d69e067UL, 0x20cbd748UL, 0x17a11549UL, 0x4e1f534bUL, 0x7975914aUL,
  73218. 0xfc63de4fUL, 0xcb091c4eUL, 0x92b75a4cUL, 0xa5dd984dUL, 0x989ac446UL,
  73219. 0xaff00647UL, 0xf64e4045UL, 0xc1248244UL, 0x4432cd41UL, 0x73580f40UL,
  73220. 0x2ae64942UL, 0x1d8c8b43UL, 0x5068f154UL, 0x67023355UL, 0x3ebc7557UL,
  73221. 0x09d6b756UL, 0x8cc0f853UL, 0xbbaa3a52UL, 0xe2147c50UL, 0xd57ebe51UL,
  73222. 0xe839e25aUL, 0xdf53205bUL, 0x86ed6659UL, 0xb187a458UL, 0x3491eb5dUL,
  73223. 0x03fb295cUL, 0x5a456f5eUL, 0x6d2fad5fUL, 0x801b35e1UL, 0xb771f7e0UL,
  73224. 0xeecfb1e2UL, 0xd9a573e3UL, 0x5cb33ce6UL, 0x6bd9fee7UL, 0x3267b8e5UL,
  73225. 0x050d7ae4UL, 0x384a26efUL, 0x0f20e4eeUL, 0x569ea2ecUL, 0x61f460edUL,
  73226. 0xe4e22fe8UL, 0xd388ede9UL, 0x8a36abebUL, 0xbd5c69eaUL, 0xf0b813fdUL,
  73227. 0xc7d2d1fcUL, 0x9e6c97feUL, 0xa90655ffUL, 0x2c101afaUL, 0x1b7ad8fbUL,
  73228. 0x42c49ef9UL, 0x75ae5cf8UL, 0x48e900f3UL, 0x7f83c2f2UL, 0x263d84f0UL,
  73229. 0x115746f1UL, 0x944109f4UL, 0xa32bcbf5UL, 0xfa958df7UL, 0xcdff4ff6UL,
  73230. 0x605d78d9UL, 0x5737bad8UL, 0x0e89fcdaUL, 0x39e33edbUL, 0xbcf571deUL,
  73231. 0x8b9fb3dfUL, 0xd221f5ddUL, 0xe54b37dcUL, 0xd80c6bd7UL, 0xef66a9d6UL,
  73232. 0xb6d8efd4UL, 0x81b22dd5UL, 0x04a462d0UL, 0x33cea0d1UL, 0x6a70e6d3UL,
  73233. 0x5d1a24d2UL, 0x10fe5ec5UL, 0x27949cc4UL, 0x7e2adac6UL, 0x494018c7UL,
  73234. 0xcc5657c2UL, 0xfb3c95c3UL, 0xa282d3c1UL, 0x95e811c0UL, 0xa8af4dcbUL,
  73235. 0x9fc58fcaUL, 0xc67bc9c8UL, 0xf1110bc9UL, 0x740744ccUL, 0x436d86cdUL,
  73236. 0x1ad3c0cfUL, 0x2db902ceUL, 0x4096af91UL, 0x77fc6d90UL, 0x2e422b92UL,
  73237. 0x1928e993UL, 0x9c3ea696UL, 0xab546497UL, 0xf2ea2295UL, 0xc580e094UL,
  73238. 0xf8c7bc9fUL, 0xcfad7e9eUL, 0x9613389cUL, 0xa179fa9dUL, 0x246fb598UL,
  73239. 0x13057799UL, 0x4abb319bUL, 0x7dd1f39aUL, 0x3035898dUL, 0x075f4b8cUL,
  73240. 0x5ee10d8eUL, 0x698bcf8fUL, 0xec9d808aUL, 0xdbf7428bUL, 0x82490489UL,
  73241. 0xb523c688UL, 0x88649a83UL, 0xbf0e5882UL, 0xe6b01e80UL, 0xd1dadc81UL,
  73242. 0x54cc9384UL, 0x63a65185UL, 0x3a181787UL, 0x0d72d586UL, 0xa0d0e2a9UL,
  73243. 0x97ba20a8UL, 0xce0466aaUL, 0xf96ea4abUL, 0x7c78ebaeUL, 0x4b1229afUL,
  73244. 0x12ac6fadUL, 0x25c6adacUL, 0x1881f1a7UL, 0x2feb33a6UL, 0x765575a4UL,
  73245. 0x413fb7a5UL, 0xc429f8a0UL, 0xf3433aa1UL, 0xaafd7ca3UL, 0x9d97bea2UL,
  73246. 0xd073c4b5UL, 0xe71906b4UL, 0xbea740b6UL, 0x89cd82b7UL, 0x0cdbcdb2UL,
  73247. 0x3bb10fb3UL, 0x620f49b1UL, 0x55658bb0UL, 0x6822d7bbUL, 0x5f4815baUL,
  73248. 0x06f653b8UL, 0x319c91b9UL, 0xb48adebcUL, 0x83e01cbdUL, 0xda5e5abfUL,
  73249. 0xed3498beUL
  73250. },
  73251. {
  73252. 0x00000000UL, 0x6567bcb8UL, 0x8bc809aaUL, 0xeeafb512UL, 0x5797628fUL,
  73253. 0x32f0de37UL, 0xdc5f6b25UL, 0xb938d79dUL, 0xef28b4c5UL, 0x8a4f087dUL,
  73254. 0x64e0bd6fUL, 0x018701d7UL, 0xb8bfd64aUL, 0xddd86af2UL, 0x3377dfe0UL,
  73255. 0x56106358UL, 0x9f571950UL, 0xfa30a5e8UL, 0x149f10faUL, 0x71f8ac42UL,
  73256. 0xc8c07bdfUL, 0xada7c767UL, 0x43087275UL, 0x266fcecdUL, 0x707fad95UL,
  73257. 0x1518112dUL, 0xfbb7a43fUL, 0x9ed01887UL, 0x27e8cf1aUL, 0x428f73a2UL,
  73258. 0xac20c6b0UL, 0xc9477a08UL, 0x3eaf32a0UL, 0x5bc88e18UL, 0xb5673b0aUL,
  73259. 0xd00087b2UL, 0x6938502fUL, 0x0c5fec97UL, 0xe2f05985UL, 0x8797e53dUL,
  73260. 0xd1878665UL, 0xb4e03addUL, 0x5a4f8fcfUL, 0x3f283377UL, 0x8610e4eaUL,
  73261. 0xe3775852UL, 0x0dd8ed40UL, 0x68bf51f8UL, 0xa1f82bf0UL, 0xc49f9748UL,
  73262. 0x2a30225aUL, 0x4f579ee2UL, 0xf66f497fUL, 0x9308f5c7UL, 0x7da740d5UL,
  73263. 0x18c0fc6dUL, 0x4ed09f35UL, 0x2bb7238dUL, 0xc518969fUL, 0xa07f2a27UL,
  73264. 0x1947fdbaUL, 0x7c204102UL, 0x928ff410UL, 0xf7e848a8UL, 0x3d58149bUL,
  73265. 0x583fa823UL, 0xb6901d31UL, 0xd3f7a189UL, 0x6acf7614UL, 0x0fa8caacUL,
  73266. 0xe1077fbeUL, 0x8460c306UL, 0xd270a05eUL, 0xb7171ce6UL, 0x59b8a9f4UL,
  73267. 0x3cdf154cUL, 0x85e7c2d1UL, 0xe0807e69UL, 0x0e2fcb7bUL, 0x6b4877c3UL,
  73268. 0xa20f0dcbUL, 0xc768b173UL, 0x29c70461UL, 0x4ca0b8d9UL, 0xf5986f44UL,
  73269. 0x90ffd3fcUL, 0x7e5066eeUL, 0x1b37da56UL, 0x4d27b90eUL, 0x284005b6UL,
  73270. 0xc6efb0a4UL, 0xa3880c1cUL, 0x1ab0db81UL, 0x7fd76739UL, 0x9178d22bUL,
  73271. 0xf41f6e93UL, 0x03f7263bUL, 0x66909a83UL, 0x883f2f91UL, 0xed589329UL,
  73272. 0x546044b4UL, 0x3107f80cUL, 0xdfa84d1eUL, 0xbacff1a6UL, 0xecdf92feUL,
  73273. 0x89b82e46UL, 0x67179b54UL, 0x027027ecUL, 0xbb48f071UL, 0xde2f4cc9UL,
  73274. 0x3080f9dbUL, 0x55e74563UL, 0x9ca03f6bUL, 0xf9c783d3UL, 0x176836c1UL,
  73275. 0x720f8a79UL, 0xcb375de4UL, 0xae50e15cUL, 0x40ff544eUL, 0x2598e8f6UL,
  73276. 0x73888baeUL, 0x16ef3716UL, 0xf8408204UL, 0x9d273ebcUL, 0x241fe921UL,
  73277. 0x41785599UL, 0xafd7e08bUL, 0xcab05c33UL, 0x3bb659edUL, 0x5ed1e555UL,
  73278. 0xb07e5047UL, 0xd519ecffUL, 0x6c213b62UL, 0x094687daUL, 0xe7e932c8UL,
  73279. 0x828e8e70UL, 0xd49eed28UL, 0xb1f95190UL, 0x5f56e482UL, 0x3a31583aUL,
  73280. 0x83098fa7UL, 0xe66e331fUL, 0x08c1860dUL, 0x6da63ab5UL, 0xa4e140bdUL,
  73281. 0xc186fc05UL, 0x2f294917UL, 0x4a4ef5afUL, 0xf3762232UL, 0x96119e8aUL,
  73282. 0x78be2b98UL, 0x1dd99720UL, 0x4bc9f478UL, 0x2eae48c0UL, 0xc001fdd2UL,
  73283. 0xa566416aUL, 0x1c5e96f7UL, 0x79392a4fUL, 0x97969f5dUL, 0xf2f123e5UL,
  73284. 0x05196b4dUL, 0x607ed7f5UL, 0x8ed162e7UL, 0xebb6de5fUL, 0x528e09c2UL,
  73285. 0x37e9b57aUL, 0xd9460068UL, 0xbc21bcd0UL, 0xea31df88UL, 0x8f566330UL,
  73286. 0x61f9d622UL, 0x049e6a9aUL, 0xbda6bd07UL, 0xd8c101bfUL, 0x366eb4adUL,
  73287. 0x53090815UL, 0x9a4e721dUL, 0xff29cea5UL, 0x11867bb7UL, 0x74e1c70fUL,
  73288. 0xcdd91092UL, 0xa8beac2aUL, 0x46111938UL, 0x2376a580UL, 0x7566c6d8UL,
  73289. 0x10017a60UL, 0xfeaecf72UL, 0x9bc973caUL, 0x22f1a457UL, 0x479618efUL,
  73290. 0xa939adfdUL, 0xcc5e1145UL, 0x06ee4d76UL, 0x6389f1ceUL, 0x8d2644dcUL,
  73291. 0xe841f864UL, 0x51792ff9UL, 0x341e9341UL, 0xdab12653UL, 0xbfd69aebUL,
  73292. 0xe9c6f9b3UL, 0x8ca1450bUL, 0x620ef019UL, 0x07694ca1UL, 0xbe519b3cUL,
  73293. 0xdb362784UL, 0x35999296UL, 0x50fe2e2eUL, 0x99b95426UL, 0xfcdee89eUL,
  73294. 0x12715d8cUL, 0x7716e134UL, 0xce2e36a9UL, 0xab498a11UL, 0x45e63f03UL,
  73295. 0x208183bbUL, 0x7691e0e3UL, 0x13f65c5bUL, 0xfd59e949UL, 0x983e55f1UL,
  73296. 0x2106826cUL, 0x44613ed4UL, 0xaace8bc6UL, 0xcfa9377eUL, 0x38417fd6UL,
  73297. 0x5d26c36eUL, 0xb389767cUL, 0xd6eecac4UL, 0x6fd61d59UL, 0x0ab1a1e1UL,
  73298. 0xe41e14f3UL, 0x8179a84bUL, 0xd769cb13UL, 0xb20e77abUL, 0x5ca1c2b9UL,
  73299. 0x39c67e01UL, 0x80fea99cUL, 0xe5991524UL, 0x0b36a036UL, 0x6e511c8eUL,
  73300. 0xa7166686UL, 0xc271da3eUL, 0x2cde6f2cUL, 0x49b9d394UL, 0xf0810409UL,
  73301. 0x95e6b8b1UL, 0x7b490da3UL, 0x1e2eb11bUL, 0x483ed243UL, 0x2d596efbUL,
  73302. 0xc3f6dbe9UL, 0xa6916751UL, 0x1fa9b0ccUL, 0x7ace0c74UL, 0x9461b966UL,
  73303. 0xf10605deUL
  73304. #endif
  73305. }
  73306. };
  73307. /********* End of inlined file: crc32.h *********/
  73308. #endif /* DYNAMIC_CRC_TABLE */
  73309. /* =========================================================================
  73310. * This function can be used by asm versions of crc32()
  73311. */
  73312. const unsigned long FAR * ZEXPORT get_crc_table()
  73313. {
  73314. #ifdef DYNAMIC_CRC_TABLE
  73315. if (crc_table_empty)
  73316. make_crc_table();
  73317. #endif /* DYNAMIC_CRC_TABLE */
  73318. return (const unsigned long FAR *)crc_table;
  73319. }
  73320. /* ========================================================================= */
  73321. #define DO1 crc = crc_table[0][((int)crc ^ (*buf++)) & 0xff] ^ (crc >> 8)
  73322. #define DO8 DO1; DO1; DO1; DO1; DO1; DO1; DO1; DO1
  73323. /* ========================================================================= */
  73324. unsigned long ZEXPORT crc32 (unsigned long crc, const unsigned char FAR *buf, unsigned len)
  73325. {
  73326. if (buf == Z_NULL) return 0UL;
  73327. #ifdef DYNAMIC_CRC_TABLE
  73328. if (crc_table_empty)
  73329. make_crc_table();
  73330. #endif /* DYNAMIC_CRC_TABLE */
  73331. #ifdef BYFOUR
  73332. if (sizeof(void *) == sizeof(ptrdiff_t)) {
  73333. u4 endian;
  73334. endian = 1;
  73335. if (*((unsigned char *)(&endian)))
  73336. return crc32_little(crc, buf, len);
  73337. else
  73338. return crc32_big(crc, buf, len);
  73339. }
  73340. #endif /* BYFOUR */
  73341. crc = crc ^ 0xffffffffUL;
  73342. while (len >= 8) {
  73343. DO8;
  73344. len -= 8;
  73345. }
  73346. if (len) do {
  73347. DO1;
  73348. } while (--len);
  73349. return crc ^ 0xffffffffUL;
  73350. }
  73351. #ifdef BYFOUR
  73352. /* ========================================================================= */
  73353. #define DOLIT4 c ^= *buf4++; \
  73354. c = crc_table[3][c & 0xff] ^ crc_table[2][(c >> 8) & 0xff] ^ \
  73355. crc_table[1][(c >> 16) & 0xff] ^ crc_table[0][c >> 24]
  73356. #define DOLIT32 DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4
  73357. /* ========================================================================= */
  73358. local unsigned long crc32_little(unsigned long crc, const unsigned char FAR *buf, unsigned len)
  73359. {
  73360. register u4 c;
  73361. register const u4 FAR *buf4;
  73362. c = (u4)crc;
  73363. c = ~c;
  73364. while (len && ((ptrdiff_t)buf & 3)) {
  73365. c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8);
  73366. len--;
  73367. }
  73368. buf4 = (const u4 FAR *)(const void FAR *)buf;
  73369. while (len >= 32) {
  73370. DOLIT32;
  73371. len -= 32;
  73372. }
  73373. while (len >= 4) {
  73374. DOLIT4;
  73375. len -= 4;
  73376. }
  73377. buf = (const unsigned char FAR *)buf4;
  73378. if (len) do {
  73379. c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8);
  73380. } while (--len);
  73381. c = ~c;
  73382. return (unsigned long)c;
  73383. }
  73384. /* ========================================================================= */
  73385. #define DOBIG4 c ^= *++buf4; \
  73386. c = crc_table[4][c & 0xff] ^ crc_table[5][(c >> 8) & 0xff] ^ \
  73387. crc_table[6][(c >> 16) & 0xff] ^ crc_table[7][c >> 24]
  73388. #define DOBIG32 DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4
  73389. /* ========================================================================= */
  73390. local unsigned long crc32_big (unsigned long crc, const unsigned char FAR *buf, unsigned len)
  73391. {
  73392. register u4 c;
  73393. register const u4 FAR *buf4;
  73394. c = REV((u4)crc);
  73395. c = ~c;
  73396. while (len && ((ptrdiff_t)buf & 3)) {
  73397. c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
  73398. len--;
  73399. }
  73400. buf4 = (const u4 FAR *)(const void FAR *)buf;
  73401. buf4--;
  73402. while (len >= 32) {
  73403. DOBIG32;
  73404. len -= 32;
  73405. }
  73406. while (len >= 4) {
  73407. DOBIG4;
  73408. len -= 4;
  73409. }
  73410. buf4++;
  73411. buf = (const unsigned char FAR *)buf4;
  73412. if (len) do {
  73413. c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
  73414. } while (--len);
  73415. c = ~c;
  73416. return (unsigned long)(REV(c));
  73417. }
  73418. #endif /* BYFOUR */
  73419. #define GF2_DIM 32 /* dimension of GF(2) vectors (length of CRC) */
  73420. /* ========================================================================= */
  73421. local unsigned long gf2_matrix_times (unsigned long *mat, unsigned long vec)
  73422. {
  73423. unsigned long sum;
  73424. sum = 0;
  73425. while (vec) {
  73426. if (vec & 1)
  73427. sum ^= *mat;
  73428. vec >>= 1;
  73429. mat++;
  73430. }
  73431. return sum;
  73432. }
  73433. /* ========================================================================= */
  73434. local void gf2_matrix_square (unsigned long *square, unsigned long *mat)
  73435. {
  73436. int n;
  73437. for (n = 0; n < GF2_DIM; n++)
  73438. square[n] = gf2_matrix_times(mat, mat[n]);
  73439. }
  73440. /* ========================================================================= */
  73441. uLong ZEXPORT crc32_combine (uLong crc1, uLong crc2, z_off_t len2)
  73442. {
  73443. int n;
  73444. unsigned long row;
  73445. unsigned long even[GF2_DIM]; /* even-power-of-two zeros operator */
  73446. unsigned long odd[GF2_DIM]; /* odd-power-of-two zeros operator */
  73447. /* degenerate case */
  73448. if (len2 == 0)
  73449. return crc1;
  73450. /* put operator for one zero bit in odd */
  73451. odd[0] = 0xedb88320L; /* CRC-32 polynomial */
  73452. row = 1;
  73453. for (n = 1; n < GF2_DIM; n++) {
  73454. odd[n] = row;
  73455. row <<= 1;
  73456. }
  73457. /* put operator for two zero bits in even */
  73458. gf2_matrix_square(even, odd);
  73459. /* put operator for four zero bits in odd */
  73460. gf2_matrix_square(odd, even);
  73461. /* apply len2 zeros to crc1 (first square will put the operator for one
  73462. zero byte, eight zero bits, in even) */
  73463. do {
  73464. /* apply zeros operator for this bit of len2 */
  73465. gf2_matrix_square(even, odd);
  73466. if (len2 & 1)
  73467. crc1 = gf2_matrix_times(even, crc1);
  73468. len2 >>= 1;
  73469. /* if no more bits set, then done */
  73470. if (len2 == 0)
  73471. break;
  73472. /* another iteration of the loop with odd and even swapped */
  73473. gf2_matrix_square(odd, even);
  73474. if (len2 & 1)
  73475. crc1 = gf2_matrix_times(odd, crc1);
  73476. len2 >>= 1;
  73477. /* if no more bits set, then done */
  73478. } while (len2 != 0);
  73479. /* return combined crc */
  73480. crc1 ^= crc2;
  73481. return crc1;
  73482. }
  73483. /********* End of inlined file: crc32.c *********/
  73484. /********* Start of inlined file: deflate.c *********/
  73485. /*
  73486. * ALGORITHM
  73487. *
  73488. * The "deflation" process depends on being able to identify portions
  73489. * of the input text which are identical to earlier input (within a
  73490. * sliding window trailing behind the input currently being processed).
  73491. *
  73492. * The most straightforward technique turns out to be the fastest for
  73493. * most input files: try all possible matches and select the longest.
  73494. * The key feature of this algorithm is that insertions into the string
  73495. * dictionary are very simple and thus fast, and deletions are avoided
  73496. * completely. Insertions are performed at each input character, whereas
  73497. * string matches are performed only when the previous match ends. So it
  73498. * is preferable to spend more time in matches to allow very fast string
  73499. * insertions and avoid deletions. The matching algorithm for small
  73500. * strings is inspired from that of Rabin & Karp. A brute force approach
  73501. * is used to find longer strings when a small match has been found.
  73502. * A similar algorithm is used in comic (by Jan-Mark Wams) and freeze
  73503. * (by Leonid Broukhis).
  73504. * A previous version of this file used a more sophisticated algorithm
  73505. * (by Fiala and Greene) which is guaranteed to run in linear amortized
  73506. * time, but has a larger average cost, uses more memory and is patented.
  73507. * However the F&G algorithm may be faster for some highly redundant
  73508. * files if the parameter max_chain_length (described below) is too large.
  73509. *
  73510. * ACKNOWLEDGEMENTS
  73511. *
  73512. * The idea of lazy evaluation of matches is due to Jan-Mark Wams, and
  73513. * I found it in 'freeze' written by Leonid Broukhis.
  73514. * Thanks to many people for bug reports and testing.
  73515. *
  73516. * REFERENCES
  73517. *
  73518. * Deutsch, L.P.,"DEFLATE Compressed Data Format Specification".
  73519. * Available in http://www.ietf.org/rfc/rfc1951.txt
  73520. *
  73521. * A description of the Rabin and Karp algorithm is given in the book
  73522. * "Algorithms" by R. Sedgewick, Addison-Wesley, p252.
  73523. *
  73524. * Fiala,E.R., and Greene,D.H.
  73525. * Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-595
  73526. *
  73527. */
  73528. /* @(#) $Id: deflate.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  73529. /********* Start of inlined file: deflate.h *********/
  73530. /* WARNING: this file should *not* be used by applications. It is
  73531. part of the implementation of the compression library and is
  73532. subject to change. Applications should only use zlib.h.
  73533. */
  73534. /* @(#) $Id: deflate.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  73535. #ifndef DEFLATE_H
  73536. #define DEFLATE_H
  73537. /* define NO_GZIP when compiling if you want to disable gzip header and
  73538. trailer creation by deflate(). NO_GZIP would be used to avoid linking in
  73539. the crc code when it is not needed. For shared libraries, gzip encoding
  73540. should be left enabled. */
  73541. #ifndef NO_GZIP
  73542. # define GZIP
  73543. #endif
  73544. #define NO_DUMMY_DECL
  73545. /* ===========================================================================
  73546. * Internal compression state.
  73547. */
  73548. #define LENGTH_CODES 29
  73549. /* number of length codes, not counting the special END_BLOCK code */
  73550. #define LITERALS 256
  73551. /* number of literal bytes 0..255 */
  73552. #define L_CODES (LITERALS+1+LENGTH_CODES)
  73553. /* number of Literal or Length codes, including the END_BLOCK code */
  73554. #define D_CODES 30
  73555. /* number of distance codes */
  73556. #define BL_CODES 19
  73557. /* number of codes used to transfer the bit lengths */
  73558. #define HEAP_SIZE (2*L_CODES+1)
  73559. /* maximum heap size */
  73560. #define MAX_BITS 15
  73561. /* All codes must not exceed MAX_BITS bits */
  73562. #define INIT_STATE 42
  73563. #define EXTRA_STATE 69
  73564. #define NAME_STATE 73
  73565. #define COMMENT_STATE 91
  73566. #define HCRC_STATE 103
  73567. #define BUSY_STATE 113
  73568. #define FINISH_STATE 666
  73569. /* Stream status */
  73570. /* Data structure describing a single value and its code string. */
  73571. typedef struct ct_data_s {
  73572. union {
  73573. ush freq; /* frequency count */
  73574. ush code; /* bit string */
  73575. } fc;
  73576. union {
  73577. ush dad; /* father node in Huffman tree */
  73578. ush len; /* length of bit string */
  73579. } dl;
  73580. } FAR ct_data;
  73581. #define Freq fc.freq
  73582. #define Code fc.code
  73583. #define Dad dl.dad
  73584. #define Len dl.len
  73585. typedef struct static_tree_desc_s static_tree_desc;
  73586. typedef struct tree_desc_s {
  73587. ct_data *dyn_tree; /* the dynamic tree */
  73588. int max_code; /* largest code with non zero frequency */
  73589. static_tree_desc *stat_desc; /* the corresponding static tree */
  73590. } FAR tree_desc;
  73591. typedef ush Pos;
  73592. typedef Pos FAR Posf;
  73593. typedef unsigned IPos;
  73594. /* A Pos is an index in the character window. We use short instead of int to
  73595. * save space in the various tables. IPos is used only for parameter passing.
  73596. */
  73597. typedef struct internal_state {
  73598. z_streamp strm; /* pointer back to this zlib stream */
  73599. int status; /* as the name implies */
  73600. Bytef *pending_buf; /* output still pending */
  73601. ulg pending_buf_size; /* size of pending_buf */
  73602. Bytef *pending_out; /* next pending byte to output to the stream */
  73603. uInt pending; /* nb of bytes in the pending buffer */
  73604. int wrap; /* bit 0 true for zlib, bit 1 true for gzip */
  73605. gz_headerp gzhead; /* gzip header information to write */
  73606. uInt gzindex; /* where in extra, name, or comment */
  73607. Byte method; /* STORED (for zip only) or DEFLATED */
  73608. int last_flush; /* value of flush param for previous deflate call */
  73609. /* used by deflate.c: */
  73610. uInt w_size; /* LZ77 window size (32K by default) */
  73611. uInt w_bits; /* log2(w_size) (8..16) */
  73612. uInt w_mask; /* w_size - 1 */
  73613. Bytef *window;
  73614. /* Sliding window. Input bytes are read into the second half of the window,
  73615. * and move to the first half later to keep a dictionary of at least wSize
  73616. * bytes. With this organization, matches are limited to a distance of
  73617. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  73618. * performed with a length multiple of the block size. Also, it limits
  73619. * the window size to 64K, which is quite useful on MSDOS.
  73620. * To do: use the user input buffer as sliding window.
  73621. */
  73622. ulg window_size;
  73623. /* Actual size of window: 2*wSize, except when the user input buffer
  73624. * is directly used as sliding window.
  73625. */
  73626. Posf *prev;
  73627. /* Link to older string with same hash index. To limit the size of this
  73628. * array to 64K, this link is maintained only for the last 32K strings.
  73629. * An index in this array is thus a window index modulo 32K.
  73630. */
  73631. Posf *head; /* Heads of the hash chains or NIL. */
  73632. uInt ins_h; /* hash index of string to be inserted */
  73633. uInt hash_size; /* number of elements in hash table */
  73634. uInt hash_bits; /* log2(hash_size) */
  73635. uInt hash_mask; /* hash_size-1 */
  73636. uInt hash_shift;
  73637. /* Number of bits by which ins_h must be shifted at each input
  73638. * step. It must be such that after MIN_MATCH steps, the oldest
  73639. * byte no longer takes part in the hash key, that is:
  73640. * hash_shift * MIN_MATCH >= hash_bits
  73641. */
  73642. long block_start;
  73643. /* Window position at the beginning of the current output block. Gets
  73644. * negative when the window is moved backwards.
  73645. */
  73646. uInt match_length; /* length of best match */
  73647. IPos prev_match; /* previous match */
  73648. int match_available; /* set if previous match exists */
  73649. uInt strstart; /* start of string to insert */
  73650. uInt match_start; /* start of matching string */
  73651. uInt lookahead; /* number of valid bytes ahead in window */
  73652. uInt prev_length;
  73653. /* Length of the best match at previous step. Matches not greater than this
  73654. * are discarded. This is used in the lazy match evaluation.
  73655. */
  73656. uInt max_chain_length;
  73657. /* To speed up deflation, hash chains are never searched beyond this
  73658. * length. A higher limit improves compression ratio but degrades the
  73659. * speed.
  73660. */
  73661. uInt max_lazy_match;
  73662. /* Attempt to find a better match only when the current match is strictly
  73663. * smaller than this value. This mechanism is used only for compression
  73664. * levels >= 4.
  73665. */
  73666. # define max_insert_length max_lazy_match
  73667. /* Insert new strings in the hash table only if the match length is not
  73668. * greater than this length. This saves time but degrades compression.
  73669. * max_insert_length is used only for compression levels <= 3.
  73670. */
  73671. int level; /* compression level (1..9) */
  73672. int strategy; /* favor or force Huffman coding*/
  73673. uInt good_match;
  73674. /* Use a faster search when the previous match is longer than this */
  73675. int nice_match; /* Stop searching when current match exceeds this */
  73676. /* used by trees.c: */
  73677. /* Didn't use ct_data typedef below to supress compiler warning */
  73678. struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  73679. struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  73680. struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  73681. struct tree_desc_s l_desc; /* desc. for literal tree */
  73682. struct tree_desc_s d_desc; /* desc. for distance tree */
  73683. struct tree_desc_s bl_desc; /* desc. for bit length tree */
  73684. ush bl_count[MAX_BITS+1];
  73685. /* number of codes at each bit length for an optimal tree */
  73686. int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  73687. int heap_len; /* number of elements in the heap */
  73688. int heap_max; /* element of largest frequency */
  73689. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  73690. * The same heap array is used to build all trees.
  73691. */
  73692. uch depth[2*L_CODES+1];
  73693. /* Depth of each subtree used as tie breaker for trees of equal frequency
  73694. */
  73695. uchf *l_buf; /* buffer for literals or lengths */
  73696. uInt lit_bufsize;
  73697. /* Size of match buffer for literals/lengths. There are 4 reasons for
  73698. * limiting lit_bufsize to 64K:
  73699. * - frequencies can be kept in 16 bit counters
  73700. * - if compression is not successful for the first block, all input
  73701. * data is still in the window so we can still emit a stored block even
  73702. * when input comes from standard input. (This can also be done for
  73703. * all blocks if lit_bufsize is not greater than 32K.)
  73704. * - if compression is not successful for a file smaller than 64K, we can
  73705. * even emit a stored file instead of a stored block (saving 5 bytes).
  73706. * This is applicable only for zip (not gzip or zlib).
  73707. * - creating new Huffman trees less frequently may not provide fast
  73708. * adaptation to changes in the input data statistics. (Take for
  73709. * example a binary file with poorly compressible code followed by
  73710. * a highly compressible string table.) Smaller buffer sizes give
  73711. * fast adaptation but have of course the overhead of transmitting
  73712. * trees more frequently.
  73713. * - I can't count above 4
  73714. */
  73715. uInt last_lit; /* running index in l_buf */
  73716. ushf *d_buf;
  73717. /* Buffer for distances. To simplify the code, d_buf and l_buf have
  73718. * the same number of elements. To use different lengths, an extra flag
  73719. * array would be necessary.
  73720. */
  73721. ulg opt_len; /* bit length of current block with optimal trees */
  73722. ulg static_len; /* bit length of current block with static trees */
  73723. uInt matches; /* number of string matches in current block */
  73724. int last_eob_len; /* bit length of EOB code for last block */
  73725. #ifdef DEBUG
  73726. ulg compressed_len; /* total bit length of compressed file mod 2^32 */
  73727. ulg bits_sent; /* bit length of compressed data sent mod 2^32 */
  73728. #endif
  73729. ush bi_buf;
  73730. /* Output buffer. bits are inserted starting at the bottom (least
  73731. * significant bits).
  73732. */
  73733. int bi_valid;
  73734. /* Number of valid bits in bi_buf. All bits above the last valid bit
  73735. * are always zero.
  73736. */
  73737. } FAR deflate_state;
  73738. /* Output a byte on the stream.
  73739. * IN assertion: there is enough room in pending_buf.
  73740. */
  73741. #define put_byte(s, c) {s->pending_buf[s->pending++] = (c);}
  73742. #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
  73743. /* Minimum amount of lookahead, except at the end of the input file.
  73744. * See deflate.c for comments about the MIN_MATCH+1.
  73745. */
  73746. #define MAX_DIST(s) ((s)->w_size-MIN_LOOKAHEAD)
  73747. /* In order to simplify the code, particularly on 16 bit machines, match
  73748. * distances are limited to MAX_DIST instead of WSIZE.
  73749. */
  73750. /* in trees.c */
  73751. void _tr_init OF((deflate_state *s));
  73752. int _tr_tally OF((deflate_state *s, unsigned dist, unsigned lc));
  73753. void _tr_flush_block OF((deflate_state *s, charf *buf, ulg stored_len,
  73754. int eof));
  73755. void _tr_align OF((deflate_state *s));
  73756. void _tr_stored_block OF((deflate_state *s, charf *buf, ulg stored_len,
  73757. int eof));
  73758. #define d_code(dist) \
  73759. ((dist) < 256 ? _dist_code[dist] : _dist_code[256+((dist)>>7)])
  73760. /* Mapping from a distance to a distance code. dist is the distance - 1 and
  73761. * must not have side effects. _dist_code[256] and _dist_code[257] are never
  73762. * used.
  73763. */
  73764. #ifndef DEBUG
  73765. /* Inline versions of _tr_tally for speed: */
  73766. #if defined(GEN_TREES_H) || !defined(STDC)
  73767. extern uch _length_code[];
  73768. extern uch _dist_code[];
  73769. #else
  73770. extern const uch _length_code[];
  73771. extern const uch _dist_code[];
  73772. #endif
  73773. # define _tr_tally_lit(s, c, flush) \
  73774. { uch cc = (c); \
  73775. s->d_buf[s->last_lit] = 0; \
  73776. s->l_buf[s->last_lit++] = cc; \
  73777. s->dyn_ltree[cc].Freq++; \
  73778. flush = (s->last_lit == s->lit_bufsize-1); \
  73779. }
  73780. # define _tr_tally_dist(s, distance, length, flush) \
  73781. { uch len = (length); \
  73782. ush dist = (distance); \
  73783. s->d_buf[s->last_lit] = dist; \
  73784. s->l_buf[s->last_lit++] = len; \
  73785. dist--; \
  73786. s->dyn_ltree[_length_code[len]+LITERALS+1].Freq++; \
  73787. s->dyn_dtree[d_code(dist)].Freq++; \
  73788. flush = (s->last_lit == s->lit_bufsize-1); \
  73789. }
  73790. #else
  73791. # define _tr_tally_lit(s, c, flush) flush = _tr_tally(s, 0, c)
  73792. # define _tr_tally_dist(s, distance, length, flush) \
  73793. flush = _tr_tally(s, distance, length)
  73794. #endif
  73795. #endif /* DEFLATE_H */
  73796. /********* End of inlined file: deflate.h *********/
  73797. const char deflate_copyright[] =
  73798. " deflate 1.2.3 Copyright 1995-2005 Jean-loup Gailly ";
  73799. /*
  73800. If you use the zlib library in a product, an acknowledgment is welcome
  73801. in the documentation of your product. If for some reason you cannot
  73802. include such an acknowledgment, I would appreciate that you keep this
  73803. copyright string in the executable of your product.
  73804. */
  73805. /* ===========================================================================
  73806. * Function prototypes.
  73807. */
  73808. typedef enum {
  73809. need_more, /* block not completed, need more input or more output */
  73810. block_done, /* block flush performed */
  73811. finish_started, /* finish started, need only more output at next deflate */
  73812. finish_done /* finish done, accept no more input or output */
  73813. } block_state;
  73814. typedef block_state (*compress_func) OF((deflate_state *s, int flush));
  73815. /* Compression function. Returns the block state after the call. */
  73816. local void fill_window OF((deflate_state *s));
  73817. local block_state deflate_stored OF((deflate_state *s, int flush));
  73818. local block_state deflate_fast OF((deflate_state *s, int flush));
  73819. #ifndef FASTEST
  73820. local block_state deflate_slow OF((deflate_state *s, int flush));
  73821. #endif
  73822. local void lm_init OF((deflate_state *s));
  73823. local void putShortMSB OF((deflate_state *s, uInt b));
  73824. local void flush_pending OF((z_streamp strm));
  73825. local int read_buf OF((z_streamp strm, Bytef *buf, unsigned size));
  73826. #ifndef FASTEST
  73827. #ifdef ASMV
  73828. void match_init OF((void)); /* asm code initialization */
  73829. uInt longest_match OF((deflate_state *s, IPos cur_match));
  73830. #else
  73831. local uInt longest_match OF((deflate_state *s, IPos cur_match));
  73832. #endif
  73833. #endif
  73834. local uInt longest_match_fast OF((deflate_state *s, IPos cur_match));
  73835. #ifdef DEBUG
  73836. local void check_match OF((deflate_state *s, IPos start, IPos match,
  73837. int length));
  73838. #endif
  73839. /* ===========================================================================
  73840. * Local data
  73841. */
  73842. #define NIL 0
  73843. /* Tail of hash chains */
  73844. #ifndef TOO_FAR
  73845. # define TOO_FAR 4096
  73846. #endif
  73847. /* Matches of length 3 are discarded if their distance exceeds TOO_FAR */
  73848. #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
  73849. /* Minimum amount of lookahead, except at the end of the input file.
  73850. * See deflate.c for comments about the MIN_MATCH+1.
  73851. */
  73852. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  73853. * the desired pack level (0..9). The values given below have been tuned to
  73854. * exclude worst case performance for pathological files. Better values may be
  73855. * found for specific files.
  73856. */
  73857. typedef struct config_s {
  73858. ush good_length; /* reduce lazy search above this match length */
  73859. ush max_lazy; /* do not perform lazy search above this match length */
  73860. ush nice_length; /* quit search above this match length */
  73861. ush max_chain;
  73862. compress_func func;
  73863. } config;
  73864. #ifdef FASTEST
  73865. local const config configuration_table[2] = {
  73866. /* good lazy nice chain */
  73867. /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */
  73868. /* 1 */ {4, 4, 8, 4, deflate_fast}}; /* max speed, no lazy matches */
  73869. #else
  73870. local const config configuration_table[10] = {
  73871. /* good lazy nice chain */
  73872. /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */
  73873. /* 1 */ {4, 4, 8, 4, deflate_fast}, /* max speed, no lazy matches */
  73874. /* 2 */ {4, 5, 16, 8, deflate_fast},
  73875. /* 3 */ {4, 6, 32, 32, deflate_fast},
  73876. /* 4 */ {4, 4, 16, 16, deflate_slow}, /* lazy matches */
  73877. /* 5 */ {8, 16, 32, 32, deflate_slow},
  73878. /* 6 */ {8, 16, 128, 128, deflate_slow},
  73879. /* 7 */ {8, 32, 128, 256, deflate_slow},
  73880. /* 8 */ {32, 128, 258, 1024, deflate_slow},
  73881. /* 9 */ {32, 258, 258, 4096, deflate_slow}}; /* max compression */
  73882. #endif
  73883. /* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4
  73884. * For deflate_fast() (levels <= 3) good is ignored and lazy has a different
  73885. * meaning.
  73886. */
  73887. #define EQUAL 0
  73888. /* result of memcmp for equal strings */
  73889. #ifndef NO_DUMMY_DECL
  73890. struct static_tree_desc_s {int dummy;}; /* for buggy compilers */
  73891. #endif
  73892. /* ===========================================================================
  73893. * Update a hash value with the given input byte
  73894. * IN assertion: all calls to to UPDATE_HASH are made with consecutive
  73895. * input characters, so that a running hash key can be computed from the
  73896. * previous key instead of complete recalculation each time.
  73897. */
  73898. #define UPDATE_HASH(s,h,c) (h = (((h)<<s->hash_shift) ^ (c)) & s->hash_mask)
  73899. /* ===========================================================================
  73900. * Insert string str in the dictionary and set match_head to the previous head
  73901. * of the hash chain (the most recent string with same hash key). Return
  73902. * the previous length of the hash chain.
  73903. * If this file is compiled with -DFASTEST, the compression level is forced
  73904. * to 1, and no hash chains are maintained.
  73905. * IN assertion: all calls to to INSERT_STRING are made with consecutive
  73906. * input characters and the first MIN_MATCH bytes of str are valid
  73907. * (except for the last MIN_MATCH-1 bytes of the input file).
  73908. */
  73909. #ifdef FASTEST
  73910. #define INSERT_STRING(s, str, match_head) \
  73911. (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
  73912. match_head = s->head[s->ins_h], \
  73913. s->head[s->ins_h] = (Pos)(str))
  73914. #else
  73915. #define INSERT_STRING(s, str, match_head) \
  73916. (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
  73917. match_head = s->prev[(str) & s->w_mask] = s->head[s->ins_h], \
  73918. s->head[s->ins_h] = (Pos)(str))
  73919. #endif
  73920. /* ===========================================================================
  73921. * Initialize the hash table (avoiding 64K overflow for 16 bit systems).
  73922. * prev[] will be initialized on the fly.
  73923. */
  73924. #define CLEAR_HASH(s) \
  73925. s->head[s->hash_size-1] = NIL; \
  73926. zmemzero((Bytef *)s->head, (unsigned)(s->hash_size-1)*sizeof(*s->head));
  73927. /* ========================================================================= */
  73928. int ZEXPORT deflateInit_(z_streamp strm, int level, const char *version, int stream_size)
  73929. {
  73930. return deflateInit2_(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL,
  73931. Z_DEFAULT_STRATEGY, version, stream_size);
  73932. /* To do: ignore strm->next_in if we use it as window */
  73933. }
  73934. /* ========================================================================= */
  73935. int ZEXPORT deflateInit2_ (z_streamp strm, int level, int method, int windowBits, int memLevel, int strategy, const char *version, int stream_size)
  73936. {
  73937. deflate_state *s;
  73938. int wrap = 1;
  73939. static const char my_version[] = ZLIB_VERSION;
  73940. ushf *overlay;
  73941. /* We overlay pending_buf and d_buf+l_buf. This works since the average
  73942. * output size for (length,distance) codes is <= 24 bits.
  73943. */
  73944. if (version == Z_NULL || version[0] != my_version[0] ||
  73945. stream_size != sizeof(z_stream)) {
  73946. return Z_VERSION_ERROR;
  73947. }
  73948. if (strm == Z_NULL) return Z_STREAM_ERROR;
  73949. strm->msg = Z_NULL;
  73950. if (strm->zalloc == (alloc_func)0) {
  73951. strm->zalloc = zcalloc;
  73952. strm->opaque = (voidpf)0;
  73953. }
  73954. if (strm->zfree == (free_func)0) strm->zfree = zcfree;
  73955. #ifdef FASTEST
  73956. if (level != 0) level = 1;
  73957. #else
  73958. if (level == Z_DEFAULT_COMPRESSION) level = 6;
  73959. #endif
  73960. if (windowBits < 0) { /* suppress zlib wrapper */
  73961. wrap = 0;
  73962. windowBits = -windowBits;
  73963. }
  73964. #ifdef GZIP
  73965. else if (windowBits > 15) {
  73966. wrap = 2; /* write gzip wrapper instead */
  73967. windowBits -= 16;
  73968. }
  73969. #endif
  73970. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED ||
  73971. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  73972. strategy < 0 || strategy > Z_FIXED) {
  73973. return Z_STREAM_ERROR;
  73974. }
  73975. if (windowBits == 8) windowBits = 9; /* until 256-byte window bug fixed */
  73976. s = (deflate_state *) ZALLOC(strm, 1, sizeof(deflate_state));
  73977. if (s == Z_NULL) return Z_MEM_ERROR;
  73978. strm->state = (struct internal_state FAR *)s;
  73979. s->strm = strm;
  73980. s->wrap = wrap;
  73981. s->gzhead = Z_NULL;
  73982. s->w_bits = windowBits;
  73983. s->w_size = 1 << s->w_bits;
  73984. s->w_mask = s->w_size - 1;
  73985. s->hash_bits = memLevel + 7;
  73986. s->hash_size = 1 << s->hash_bits;
  73987. s->hash_mask = s->hash_size - 1;
  73988. s->hash_shift = ((s->hash_bits+MIN_MATCH-1)/MIN_MATCH);
  73989. s->window = (Bytef *) ZALLOC(strm, s->w_size, 2*sizeof(Byte));
  73990. s->prev = (Posf *) ZALLOC(strm, s->w_size, sizeof(Pos));
  73991. s->head = (Posf *) ZALLOC(strm, s->hash_size, sizeof(Pos));
  73992. s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  73993. overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);
  73994. s->pending_buf = (uchf *) overlay;
  73995. s->pending_buf_size = (ulg)s->lit_bufsize * (sizeof(ush)+2L);
  73996. if (s->window == Z_NULL || s->prev == Z_NULL || s->head == Z_NULL ||
  73997. s->pending_buf == Z_NULL) {
  73998. s->status = FINISH_STATE;
  73999. strm->msg = (char*)ERR_MSG(Z_MEM_ERROR);
  74000. deflateEnd (strm);
  74001. return Z_MEM_ERROR;
  74002. }
  74003. s->d_buf = overlay + s->lit_bufsize/sizeof(ush);
  74004. s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;
  74005. s->level = level;
  74006. s->strategy = strategy;
  74007. s->method = (Byte)method;
  74008. return deflateReset(strm);
  74009. }
  74010. /* ========================================================================= */
  74011. int ZEXPORT deflateSetDictionary (z_streamp strm, const Bytef *dictionary, uInt dictLength)
  74012. {
  74013. deflate_state *s;
  74014. uInt length = dictLength;
  74015. uInt n;
  74016. IPos hash_head = 0;
  74017. if (strm == Z_NULL || strm->state == Z_NULL || dictionary == Z_NULL ||
  74018. strm->state->wrap == 2 ||
  74019. (strm->state->wrap == 1 && strm->state->status != INIT_STATE))
  74020. return Z_STREAM_ERROR;
  74021. s = strm->state;
  74022. if (s->wrap)
  74023. strm->adler = adler32(strm->adler, dictionary, dictLength);
  74024. if (length < MIN_MATCH) return Z_OK;
  74025. if (length > MAX_DIST(s)) {
  74026. length = MAX_DIST(s);
  74027. dictionary += dictLength - length; /* use the tail of the dictionary */
  74028. }
  74029. zmemcpy(s->window, dictionary, length);
  74030. s->strstart = length;
  74031. s->block_start = (long)length;
  74032. /* Insert all strings in the hash table (except for the last two bytes).
  74033. * s->lookahead stays null, so s->ins_h will be recomputed at the next
  74034. * call of fill_window.
  74035. */
  74036. s->ins_h = s->window[0];
  74037. UPDATE_HASH(s, s->ins_h, s->window[1]);
  74038. for (n = 0; n <= length - MIN_MATCH; n++) {
  74039. INSERT_STRING(s, n, hash_head);
  74040. }
  74041. if (hash_head) hash_head = 0; /* to make compiler happy */
  74042. return Z_OK;
  74043. }
  74044. /* ========================================================================= */
  74045. int ZEXPORT deflateReset (z_streamp strm)
  74046. {
  74047. deflate_state *s;
  74048. if (strm == Z_NULL || strm->state == Z_NULL ||
  74049. strm->zalloc == (alloc_func)0 || strm->zfree == (free_func)0) {
  74050. return Z_STREAM_ERROR;
  74051. }
  74052. strm->total_in = strm->total_out = 0;
  74053. strm->msg = Z_NULL; /* use zfree if we ever allocate msg dynamically */
  74054. strm->data_type = Z_UNKNOWN;
  74055. s = (deflate_state *)strm->state;
  74056. s->pending = 0;
  74057. s->pending_out = s->pending_buf;
  74058. if (s->wrap < 0) {
  74059. s->wrap = -s->wrap; /* was made negative by deflate(..., Z_FINISH); */
  74060. }
  74061. s->status = s->wrap ? INIT_STATE : BUSY_STATE;
  74062. strm->adler =
  74063. #ifdef GZIP
  74064. s->wrap == 2 ? crc32(0L, Z_NULL, 0) :
  74065. #endif
  74066. adler32(0L, Z_NULL, 0);
  74067. s->last_flush = Z_NO_FLUSH;
  74068. _tr_init(s);
  74069. lm_init(s);
  74070. return Z_OK;
  74071. }
  74072. /* ========================================================================= */
  74073. int ZEXPORT deflateSetHeader (z_streamp strm, gz_headerp head)
  74074. {
  74075. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  74076. if (strm->state->wrap != 2) return Z_STREAM_ERROR;
  74077. strm->state->gzhead = head;
  74078. return Z_OK;
  74079. }
  74080. /* ========================================================================= */
  74081. int ZEXPORT deflatePrime (z_streamp strm, int bits, int value)
  74082. {
  74083. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  74084. strm->state->bi_valid = bits;
  74085. strm->state->bi_buf = (ush)(value & ((1 << bits) - 1));
  74086. return Z_OK;
  74087. }
  74088. /* ========================================================================= */
  74089. int ZEXPORT deflateParams (z_streamp strm, int level, int strategy)
  74090. {
  74091. deflate_state *s;
  74092. compress_func func;
  74093. int err = Z_OK;
  74094. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  74095. s = strm->state;
  74096. #ifdef FASTEST
  74097. if (level != 0) level = 1;
  74098. #else
  74099. if (level == Z_DEFAULT_COMPRESSION) level = 6;
  74100. #endif
  74101. if (level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED) {
  74102. return Z_STREAM_ERROR;
  74103. }
  74104. func = configuration_table[s->level].func;
  74105. if (func != configuration_table[level].func && strm->total_in != 0) {
  74106. /* Flush the last buffer: */
  74107. err = deflate(strm, Z_PARTIAL_FLUSH);
  74108. }
  74109. if (s->level != level) {
  74110. s->level = level;
  74111. s->max_lazy_match = configuration_table[level].max_lazy;
  74112. s->good_match = configuration_table[level].good_length;
  74113. s->nice_match = configuration_table[level].nice_length;
  74114. s->max_chain_length = configuration_table[level].max_chain;
  74115. }
  74116. s->strategy = strategy;
  74117. return err;
  74118. }
  74119. /* ========================================================================= */
  74120. int ZEXPORT deflateTune (z_streamp strm, int good_length, int max_lazy, int nice_length, int max_chain)
  74121. {
  74122. deflate_state *s;
  74123. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  74124. s = strm->state;
  74125. s->good_match = good_length;
  74126. s->max_lazy_match = max_lazy;
  74127. s->nice_match = nice_length;
  74128. s->max_chain_length = max_chain;
  74129. return Z_OK;
  74130. }
  74131. /* =========================================================================
  74132. * For the default windowBits of 15 and memLevel of 8, this function returns
  74133. * a close to exact, as well as small, upper bound on the compressed size.
  74134. * They are coded as constants here for a reason--if the #define's are
  74135. * changed, then this function needs to be changed as well. The return
  74136. * value for 15 and 8 only works for those exact settings.
  74137. *
  74138. * For any setting other than those defaults for windowBits and memLevel,
  74139. * the value returned is a conservative worst case for the maximum expansion
  74140. * resulting from using fixed blocks instead of stored blocks, which deflate
  74141. * can emit on compressed data for some combinations of the parameters.
  74142. *
  74143. * This function could be more sophisticated to provide closer upper bounds
  74144. * for every combination of windowBits and memLevel, as well as wrap.
  74145. * But even the conservative upper bound of about 14% expansion does not
  74146. * seem onerous for output buffer allocation.
  74147. */
  74148. uLong ZEXPORT deflateBound (z_streamp strm, uLong sourceLen)
  74149. {
  74150. deflate_state *s;
  74151. uLong destLen;
  74152. /* conservative upper bound */
  74153. destLen = sourceLen +
  74154. ((sourceLen + 7) >> 3) + ((sourceLen + 63) >> 6) + 11;
  74155. /* if can't get parameters, return conservative bound */
  74156. if (strm == Z_NULL || strm->state == Z_NULL)
  74157. return destLen;
  74158. /* if not default parameters, return conservative bound */
  74159. s = strm->state;
  74160. if (s->w_bits != 15 || s->hash_bits != 8 + 7)
  74161. return destLen;
  74162. /* default settings: return tight bound for that case */
  74163. return compressBound(sourceLen);
  74164. }
  74165. /* =========================================================================
  74166. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  74167. * IN assertion: the stream state is correct and there is enough room in
  74168. * pending_buf.
  74169. */
  74170. local void putShortMSB (deflate_state *s, uInt b)
  74171. {
  74172. put_byte(s, (Byte)(b >> 8));
  74173. put_byte(s, (Byte)(b & 0xff));
  74174. }
  74175. /* =========================================================================
  74176. * Flush as much pending output as possible. All deflate() output goes
  74177. * through this function so some applications may wish to modify it
  74178. * to avoid allocating a large strm->next_out buffer and copying into it.
  74179. * (See also read_buf()).
  74180. */
  74181. local void flush_pending (z_streamp strm)
  74182. {
  74183. unsigned len = strm->state->pending;
  74184. if (len > strm->avail_out) len = strm->avail_out;
  74185. if (len == 0) return;
  74186. zmemcpy(strm->next_out, strm->state->pending_out, len);
  74187. strm->next_out += len;
  74188. strm->state->pending_out += len;
  74189. strm->total_out += len;
  74190. strm->avail_out -= len;
  74191. strm->state->pending -= len;
  74192. if (strm->state->pending == 0) {
  74193. strm->state->pending_out = strm->state->pending_buf;
  74194. }
  74195. }
  74196. /* ========================================================================= */
  74197. int ZEXPORT deflate (z_streamp strm, int flush)
  74198. {
  74199. int old_flush; /* value of flush param for previous deflate call */
  74200. deflate_state *s;
  74201. if (strm == Z_NULL || strm->state == Z_NULL ||
  74202. flush > Z_FINISH || flush < 0) {
  74203. return Z_STREAM_ERROR;
  74204. }
  74205. s = strm->state;
  74206. if (strm->next_out == Z_NULL ||
  74207. (strm->next_in == Z_NULL && strm->avail_in != 0) ||
  74208. (s->status == FINISH_STATE && flush != Z_FINISH)) {
  74209. ERR_RETURN(strm, Z_STREAM_ERROR);
  74210. }
  74211. if (strm->avail_out == 0) ERR_RETURN(strm, Z_BUF_ERROR);
  74212. s->strm = strm; /* just in case */
  74213. old_flush = s->last_flush;
  74214. s->last_flush = flush;
  74215. /* Write the header */
  74216. if (s->status == INIT_STATE) {
  74217. #ifdef GZIP
  74218. if (s->wrap == 2) {
  74219. strm->adler = crc32(0L, Z_NULL, 0);
  74220. put_byte(s, 31);
  74221. put_byte(s, 139);
  74222. put_byte(s, 8);
  74223. if (s->gzhead == NULL) {
  74224. put_byte(s, 0);
  74225. put_byte(s, 0);
  74226. put_byte(s, 0);
  74227. put_byte(s, 0);
  74228. put_byte(s, 0);
  74229. put_byte(s, s->level == 9 ? 2 :
  74230. (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
  74231. 4 : 0));
  74232. put_byte(s, OS_CODE);
  74233. s->status = BUSY_STATE;
  74234. }
  74235. else {
  74236. put_byte(s, (s->gzhead->text ? 1 : 0) +
  74237. (s->gzhead->hcrc ? 2 : 0) +
  74238. (s->gzhead->extra == Z_NULL ? 0 : 4) +
  74239. (s->gzhead->name == Z_NULL ? 0 : 8) +
  74240. (s->gzhead->comment == Z_NULL ? 0 : 16)
  74241. );
  74242. put_byte(s, (Byte)(s->gzhead->time & 0xff));
  74243. put_byte(s, (Byte)((s->gzhead->time >> 8) & 0xff));
  74244. put_byte(s, (Byte)((s->gzhead->time >> 16) & 0xff));
  74245. put_byte(s, (Byte)((s->gzhead->time >> 24) & 0xff));
  74246. put_byte(s, s->level == 9 ? 2 :
  74247. (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
  74248. 4 : 0));
  74249. put_byte(s, s->gzhead->os & 0xff);
  74250. if (s->gzhead->extra != NULL) {
  74251. put_byte(s, s->gzhead->extra_len & 0xff);
  74252. put_byte(s, (s->gzhead->extra_len >> 8) & 0xff);
  74253. }
  74254. if (s->gzhead->hcrc)
  74255. strm->adler = crc32(strm->adler, s->pending_buf,
  74256. s->pending);
  74257. s->gzindex = 0;
  74258. s->status = EXTRA_STATE;
  74259. }
  74260. }
  74261. else
  74262. #endif
  74263. {
  74264. uInt header = (Z_DEFLATED + ((s->w_bits-8)<<4)) << 8;
  74265. uInt level_flags;
  74266. if (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2)
  74267. level_flags = 0;
  74268. else if (s->level < 6)
  74269. level_flags = 1;
  74270. else if (s->level == 6)
  74271. level_flags = 2;
  74272. else
  74273. level_flags = 3;
  74274. header |= (level_flags << 6);
  74275. if (s->strstart != 0) header |= PRESET_DICT;
  74276. header += 31 - (header % 31);
  74277. s->status = BUSY_STATE;
  74278. putShortMSB(s, header);
  74279. /* Save the adler32 of the preset dictionary: */
  74280. if (s->strstart != 0) {
  74281. putShortMSB(s, (uInt)(strm->adler >> 16));
  74282. putShortMSB(s, (uInt)(strm->adler & 0xffff));
  74283. }
  74284. strm->adler = adler32(0L, Z_NULL, 0);
  74285. }
  74286. }
  74287. #ifdef GZIP
  74288. if (s->status == EXTRA_STATE) {
  74289. if (s->gzhead->extra != NULL) {
  74290. uInt beg = s->pending; /* start of bytes to update crc */
  74291. while (s->gzindex < (s->gzhead->extra_len & 0xffff)) {
  74292. if (s->pending == s->pending_buf_size) {
  74293. if (s->gzhead->hcrc && s->pending > beg)
  74294. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  74295. s->pending - beg);
  74296. flush_pending(strm);
  74297. beg = s->pending;
  74298. if (s->pending == s->pending_buf_size)
  74299. break;
  74300. }
  74301. put_byte(s, s->gzhead->extra[s->gzindex]);
  74302. s->gzindex++;
  74303. }
  74304. if (s->gzhead->hcrc && s->pending > beg)
  74305. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  74306. s->pending - beg);
  74307. if (s->gzindex == s->gzhead->extra_len) {
  74308. s->gzindex = 0;
  74309. s->status = NAME_STATE;
  74310. }
  74311. }
  74312. else
  74313. s->status = NAME_STATE;
  74314. }
  74315. if (s->status == NAME_STATE) {
  74316. if (s->gzhead->name != NULL) {
  74317. uInt beg = s->pending; /* start of bytes to update crc */
  74318. int val;
  74319. do {
  74320. if (s->pending == s->pending_buf_size) {
  74321. if (s->gzhead->hcrc && s->pending > beg)
  74322. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  74323. s->pending - beg);
  74324. flush_pending(strm);
  74325. beg = s->pending;
  74326. if (s->pending == s->pending_buf_size) {
  74327. val = 1;
  74328. break;
  74329. }
  74330. }
  74331. val = s->gzhead->name[s->gzindex++];
  74332. put_byte(s, val);
  74333. } while (val != 0);
  74334. if (s->gzhead->hcrc && s->pending > beg)
  74335. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  74336. s->pending - beg);
  74337. if (val == 0) {
  74338. s->gzindex = 0;
  74339. s->status = COMMENT_STATE;
  74340. }
  74341. }
  74342. else
  74343. s->status = COMMENT_STATE;
  74344. }
  74345. if (s->status == COMMENT_STATE) {
  74346. if (s->gzhead->comment != NULL) {
  74347. uInt beg = s->pending; /* start of bytes to update crc */
  74348. int val;
  74349. do {
  74350. if (s->pending == s->pending_buf_size) {
  74351. if (s->gzhead->hcrc && s->pending > beg)
  74352. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  74353. s->pending - beg);
  74354. flush_pending(strm);
  74355. beg = s->pending;
  74356. if (s->pending == s->pending_buf_size) {
  74357. val = 1;
  74358. break;
  74359. }
  74360. }
  74361. val = s->gzhead->comment[s->gzindex++];
  74362. put_byte(s, val);
  74363. } while (val != 0);
  74364. if (s->gzhead->hcrc && s->pending > beg)
  74365. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  74366. s->pending - beg);
  74367. if (val == 0)
  74368. s->status = HCRC_STATE;
  74369. }
  74370. else
  74371. s->status = HCRC_STATE;
  74372. }
  74373. if (s->status == HCRC_STATE) {
  74374. if (s->gzhead->hcrc) {
  74375. if (s->pending + 2 > s->pending_buf_size)
  74376. flush_pending(strm);
  74377. if (s->pending + 2 <= s->pending_buf_size) {
  74378. put_byte(s, (Byte)(strm->adler & 0xff));
  74379. put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
  74380. strm->adler = crc32(0L, Z_NULL, 0);
  74381. s->status = BUSY_STATE;
  74382. }
  74383. }
  74384. else
  74385. s->status = BUSY_STATE;
  74386. }
  74387. #endif
  74388. /* Flush as much pending output as possible */
  74389. if (s->pending != 0) {
  74390. flush_pending(strm);
  74391. if (strm->avail_out == 0) {
  74392. /* Since avail_out is 0, deflate will be called again with
  74393. * more output space, but possibly with both pending and
  74394. * avail_in equal to zero. There won't be anything to do,
  74395. * but this is not an error situation so make sure we
  74396. * return OK instead of BUF_ERROR at next call of deflate:
  74397. */
  74398. s->last_flush = -1;
  74399. return Z_OK;
  74400. }
  74401. /* Make sure there is something to do and avoid duplicate consecutive
  74402. * flushes. For repeated and useless calls with Z_FINISH, we keep
  74403. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  74404. */
  74405. } else if (strm->avail_in == 0 && flush <= old_flush &&
  74406. flush != Z_FINISH) {
  74407. ERR_RETURN(strm, Z_BUF_ERROR);
  74408. }
  74409. /* User must not provide more input after the first FINISH: */
  74410. if (s->status == FINISH_STATE && strm->avail_in != 0) {
  74411. ERR_RETURN(strm, Z_BUF_ERROR);
  74412. }
  74413. /* Start a new block or continue the current one.
  74414. */
  74415. if (strm->avail_in != 0 || s->lookahead != 0 ||
  74416. (flush != Z_NO_FLUSH && s->status != FINISH_STATE)) {
  74417. block_state bstate;
  74418. bstate = (*(configuration_table[s->level].func))(s, flush);
  74419. if (bstate == finish_started || bstate == finish_done) {
  74420. s->status = FINISH_STATE;
  74421. }
  74422. if (bstate == need_more || bstate == finish_started) {
  74423. if (strm->avail_out == 0) {
  74424. s->last_flush = -1; /* avoid BUF_ERROR next call, see above */
  74425. }
  74426. return Z_OK;
  74427. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  74428. * of deflate should use the same flush parameter to make sure
  74429. * that the flush is complete. So we don't have to output an
  74430. * empty block here, this will be done at next call. This also
  74431. * ensures that for a very small output buffer, we emit at most
  74432. * one empty block.
  74433. */
  74434. }
  74435. if (bstate == block_done) {
  74436. if (flush == Z_PARTIAL_FLUSH) {
  74437. _tr_align(s);
  74438. } else { /* FULL_FLUSH or SYNC_FLUSH */
  74439. _tr_stored_block(s, (char*)0, 0L, 0);
  74440. /* For a full flush, this empty block will be recognized
  74441. * as a special marker by inflate_sync().
  74442. */
  74443. if (flush == Z_FULL_FLUSH) {
  74444. CLEAR_HASH(s); /* forget history */
  74445. }
  74446. }
  74447. flush_pending(strm);
  74448. if (strm->avail_out == 0) {
  74449. s->last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  74450. return Z_OK;
  74451. }
  74452. }
  74453. }
  74454. Assert(strm->avail_out > 0, "bug2");
  74455. if (flush != Z_FINISH) return Z_OK;
  74456. if (s->wrap <= 0) return Z_STREAM_END;
  74457. /* Write the trailer */
  74458. #ifdef GZIP
  74459. if (s->wrap == 2) {
  74460. put_byte(s, (Byte)(strm->adler & 0xff));
  74461. put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
  74462. put_byte(s, (Byte)((strm->adler >> 16) & 0xff));
  74463. put_byte(s, (Byte)((strm->adler >> 24) & 0xff));
  74464. put_byte(s, (Byte)(strm->total_in & 0xff));
  74465. put_byte(s, (Byte)((strm->total_in >> 8) & 0xff));
  74466. put_byte(s, (Byte)((strm->total_in >> 16) & 0xff));
  74467. put_byte(s, (Byte)((strm->total_in >> 24) & 0xff));
  74468. }
  74469. else
  74470. #endif
  74471. {
  74472. putShortMSB(s, (uInt)(strm->adler >> 16));
  74473. putShortMSB(s, (uInt)(strm->adler & 0xffff));
  74474. }
  74475. flush_pending(strm);
  74476. /* If avail_out is zero, the application will call deflate again
  74477. * to flush the rest.
  74478. */
  74479. if (s->wrap > 0) s->wrap = -s->wrap; /* write the trailer only once! */
  74480. return s->pending != 0 ? Z_OK : Z_STREAM_END;
  74481. }
  74482. /* ========================================================================= */
  74483. int ZEXPORT deflateEnd (z_streamp strm)
  74484. {
  74485. int status;
  74486. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  74487. status = strm->state->status;
  74488. if (status != INIT_STATE &&
  74489. status != EXTRA_STATE &&
  74490. status != NAME_STATE &&
  74491. status != COMMENT_STATE &&
  74492. status != HCRC_STATE &&
  74493. status != BUSY_STATE &&
  74494. status != FINISH_STATE) {
  74495. return Z_STREAM_ERROR;
  74496. }
  74497. /* Deallocate in reverse order of allocations: */
  74498. TRY_FREE(strm, strm->state->pending_buf);
  74499. TRY_FREE(strm, strm->state->head);
  74500. TRY_FREE(strm, strm->state->prev);
  74501. TRY_FREE(strm, strm->state->window);
  74502. ZFREE(strm, strm->state);
  74503. strm->state = Z_NULL;
  74504. return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK;
  74505. }
  74506. /* =========================================================================
  74507. * Copy the source state to the destination state.
  74508. * To simplify the source, this is not supported for 16-bit MSDOS (which
  74509. * doesn't have enough memory anyway to duplicate compression states).
  74510. */
  74511. int ZEXPORT deflateCopy (z_streamp dest, z_streamp source)
  74512. {
  74513. #ifdef MAXSEG_64K
  74514. return Z_STREAM_ERROR;
  74515. #else
  74516. deflate_state *ds;
  74517. deflate_state *ss;
  74518. ushf *overlay;
  74519. if (source == Z_NULL || dest == Z_NULL || source->state == Z_NULL) {
  74520. return Z_STREAM_ERROR;
  74521. }
  74522. ss = source->state;
  74523. zmemcpy(dest, source, sizeof(z_stream));
  74524. ds = (deflate_state *) ZALLOC(dest, 1, sizeof(deflate_state));
  74525. if (ds == Z_NULL) return Z_MEM_ERROR;
  74526. dest->state = (struct internal_state FAR *) ds;
  74527. zmemcpy(ds, ss, sizeof(deflate_state));
  74528. ds->strm = dest;
  74529. ds->window = (Bytef *) ZALLOC(dest, ds->w_size, 2*sizeof(Byte));
  74530. ds->prev = (Posf *) ZALLOC(dest, ds->w_size, sizeof(Pos));
  74531. ds->head = (Posf *) ZALLOC(dest, ds->hash_size, sizeof(Pos));
  74532. overlay = (ushf *) ZALLOC(dest, ds->lit_bufsize, sizeof(ush)+2);
  74533. ds->pending_buf = (uchf *) overlay;
  74534. if (ds->window == Z_NULL || ds->prev == Z_NULL || ds->head == Z_NULL ||
  74535. ds->pending_buf == Z_NULL) {
  74536. deflateEnd (dest);
  74537. return Z_MEM_ERROR;
  74538. }
  74539. /* following zmemcpy do not work for 16-bit MSDOS */
  74540. zmemcpy(ds->window, ss->window, ds->w_size * 2 * sizeof(Byte));
  74541. zmemcpy(ds->prev, ss->prev, ds->w_size * sizeof(Pos));
  74542. zmemcpy(ds->head, ss->head, ds->hash_size * sizeof(Pos));
  74543. zmemcpy(ds->pending_buf, ss->pending_buf, (uInt)ds->pending_buf_size);
  74544. ds->pending_out = ds->pending_buf + (ss->pending_out - ss->pending_buf);
  74545. ds->d_buf = overlay + ds->lit_bufsize/sizeof(ush);
  74546. ds->l_buf = ds->pending_buf + (1+sizeof(ush))*ds->lit_bufsize;
  74547. ds->l_desc.dyn_tree = ds->dyn_ltree;
  74548. ds->d_desc.dyn_tree = ds->dyn_dtree;
  74549. ds->bl_desc.dyn_tree = ds->bl_tree;
  74550. return Z_OK;
  74551. #endif /* MAXSEG_64K */
  74552. }
  74553. /* ===========================================================================
  74554. * Read a new buffer from the current input stream, update the adler32
  74555. * and total number of bytes read. All deflate() input goes through
  74556. * this function so some applications may wish to modify it to avoid
  74557. * allocating a large strm->next_in buffer and copying from it.
  74558. * (See also flush_pending()).
  74559. */
  74560. local int read_buf (z_streamp strm, Bytef *buf, unsigned size)
  74561. {
  74562. unsigned len = strm->avail_in;
  74563. if (len > size) len = size;
  74564. if (len == 0) return 0;
  74565. strm->avail_in -= len;
  74566. if (strm->state->wrap == 1) {
  74567. strm->adler = adler32(strm->adler, strm->next_in, len);
  74568. }
  74569. #ifdef GZIP
  74570. else if (strm->state->wrap == 2) {
  74571. strm->adler = crc32(strm->adler, strm->next_in, len);
  74572. }
  74573. #endif
  74574. zmemcpy(buf, strm->next_in, len);
  74575. strm->next_in += len;
  74576. strm->total_in += len;
  74577. return (int)len;
  74578. }
  74579. /* ===========================================================================
  74580. * Initialize the "longest match" routines for a new zlib stream
  74581. */
  74582. local void lm_init (deflate_state *s)
  74583. {
  74584. s->window_size = (ulg)2L*s->w_size;
  74585. CLEAR_HASH(s);
  74586. /* Set the default configuration parameters:
  74587. */
  74588. s->max_lazy_match = configuration_table[s->level].max_lazy;
  74589. s->good_match = configuration_table[s->level].good_length;
  74590. s->nice_match = configuration_table[s->level].nice_length;
  74591. s->max_chain_length = configuration_table[s->level].max_chain;
  74592. s->strstart = 0;
  74593. s->block_start = 0L;
  74594. s->lookahead = 0;
  74595. s->match_length = s->prev_length = MIN_MATCH-1;
  74596. s->match_available = 0;
  74597. s->ins_h = 0;
  74598. #ifndef FASTEST
  74599. #ifdef ASMV
  74600. match_init(); /* initialize the asm code */
  74601. #endif
  74602. #endif
  74603. }
  74604. #ifndef FASTEST
  74605. /* ===========================================================================
  74606. * Set match_start to the longest match starting at the given string and
  74607. * return its length. Matches shorter or equal to prev_length are discarded,
  74608. * in which case the result is equal to prev_length and match_start is
  74609. * garbage.
  74610. * IN assertions: cur_match is the head of the hash chain for the current
  74611. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  74612. * OUT assertion: the match length is not greater than s->lookahead.
  74613. */
  74614. #ifndef ASMV
  74615. /* For 80x86 and 680x0, an optimized version will be provided in match.asm or
  74616. * match.S. The code will be functionally equivalent.
  74617. */
  74618. local uInt longest_match(deflate_state *s, IPos cur_match)
  74619. {
  74620. unsigned chain_length = s->max_chain_length;/* max hash chain length */
  74621. register Bytef *scan = s->window + s->strstart; /* current string */
  74622. register Bytef *match; /* matched string */
  74623. register int len; /* length of current match */
  74624. int best_len = s->prev_length; /* best match length so far */
  74625. int nice_match = s->nice_match; /* stop if match long enough */
  74626. IPos limit = s->strstart > (IPos)MAX_DIST(s) ?
  74627. s->strstart - (IPos)MAX_DIST(s) : NIL;
  74628. /* Stop when cur_match becomes <= limit. To simplify the code,
  74629. * we prevent matches with the string of window index 0.
  74630. */
  74631. Posf *prev = s->prev;
  74632. uInt wmask = s->w_mask;
  74633. #ifdef UNALIGNED_OK
  74634. /* Compare two bytes at a time. Note: this is not always beneficial.
  74635. * Try with and without -DUNALIGNED_OK to check.
  74636. */
  74637. register Bytef *strend = s->window + s->strstart + MAX_MATCH - 1;
  74638. register ush scan_start = *(ushf*)scan;
  74639. register ush scan_end = *(ushf*)(scan+best_len-1);
  74640. #else
  74641. register Bytef *strend = s->window + s->strstart + MAX_MATCH;
  74642. register Byte scan_end1 = scan[best_len-1];
  74643. register Byte scan_end = scan[best_len];
  74644. #endif
  74645. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  74646. * It is easy to get rid of this optimization if necessary.
  74647. */
  74648. Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  74649. /* Do not waste too much time if we already have a good match: */
  74650. if (s->prev_length >= s->good_match) {
  74651. chain_length >>= 2;
  74652. }
  74653. /* Do not look for matches beyond the end of the input. This is necessary
  74654. * to make deflate deterministic.
  74655. */
  74656. if ((uInt)nice_match > s->lookahead) nice_match = s->lookahead;
  74657. Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  74658. do {
  74659. Assert(cur_match < s->strstart, "no future");
  74660. match = s->window + cur_match;
  74661. /* Skip to next match if the match length cannot increase
  74662. * or if the match length is less than 2. Note that the checks below
  74663. * for insufficient lookahead only occur occasionally for performance
  74664. * reasons. Therefore uninitialized memory will be accessed, and
  74665. * conditional jumps will be made that depend on those values.
  74666. * However the length of the match is limited to the lookahead, so
  74667. * the output of deflate is not affected by the uninitialized values.
  74668. */
  74669. #if (defined(UNALIGNED_OK) && MAX_MATCH == 258)
  74670. /* This code assumes sizeof(unsigned short) == 2. Do not use
  74671. * UNALIGNED_OK if your compiler uses a different size.
  74672. */
  74673. if (*(ushf*)(match+best_len-1) != scan_end ||
  74674. *(ushf*)match != scan_start) continue;
  74675. /* It is not necessary to compare scan[2] and match[2] since they are
  74676. * always equal when the other bytes match, given that the hash keys
  74677. * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at
  74678. * strstart+3, +5, ... up to strstart+257. We check for insufficient
  74679. * lookahead only every 4th comparison; the 128th check will be made
  74680. * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is
  74681. * necessary to put more guard bytes at the end of the window, or
  74682. * to check more often for insufficient lookahead.
  74683. */
  74684. Assert(scan[2] == match[2], "scan[2]?");
  74685. scan++, match++;
  74686. do {
  74687. } while (*(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  74688. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  74689. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  74690. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  74691. scan < strend);
  74692. /* The funny "do {}" generates better code on most compilers */
  74693. /* Here, scan <= window+strstart+257 */
  74694. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  74695. if (*scan == *match) scan++;
  74696. len = (MAX_MATCH - 1) - (int)(strend-scan);
  74697. scan = strend - (MAX_MATCH-1);
  74698. #else /* UNALIGNED_OK */
  74699. if (match[best_len] != scan_end ||
  74700. match[best_len-1] != scan_end1 ||
  74701. *match != *scan ||
  74702. *++match != scan[1]) continue;
  74703. /* The check at best_len-1 can be removed because it will be made
  74704. * again later. (This heuristic is not always a win.)
  74705. * It is not necessary to compare scan[2] and match[2] since they
  74706. * are always equal when the other bytes match, given that
  74707. * the hash keys are equal and that HASH_BITS >= 8.
  74708. */
  74709. scan += 2, match++;
  74710. Assert(*scan == *match, "match[2]?");
  74711. /* We check for insufficient lookahead only every 8th comparison;
  74712. * the 256th check will be made at strstart+258.
  74713. */
  74714. do {
  74715. } while (*++scan == *++match && *++scan == *++match &&
  74716. *++scan == *++match && *++scan == *++match &&
  74717. *++scan == *++match && *++scan == *++match &&
  74718. *++scan == *++match && *++scan == *++match &&
  74719. scan < strend);
  74720. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  74721. len = MAX_MATCH - (int)(strend - scan);
  74722. scan = strend - MAX_MATCH;
  74723. #endif /* UNALIGNED_OK */
  74724. if (len > best_len) {
  74725. s->match_start = cur_match;
  74726. best_len = len;
  74727. if (len >= nice_match) break;
  74728. #ifdef UNALIGNED_OK
  74729. scan_end = *(ushf*)(scan+best_len-1);
  74730. #else
  74731. scan_end1 = scan[best_len-1];
  74732. scan_end = scan[best_len];
  74733. #endif
  74734. }
  74735. } while ((cur_match = prev[cur_match & wmask]) > limit
  74736. && --chain_length != 0);
  74737. if ((uInt)best_len <= s->lookahead) return (uInt)best_len;
  74738. return s->lookahead;
  74739. }
  74740. #endif /* ASMV */
  74741. #endif /* FASTEST */
  74742. /* ---------------------------------------------------------------------------
  74743. * Optimized version for level == 1 or strategy == Z_RLE only
  74744. */
  74745. local uInt longest_match_fast (deflate_state *s, IPos cur_match)
  74746. {
  74747. register Bytef *scan = s->window + s->strstart; /* current string */
  74748. register Bytef *match; /* matched string */
  74749. register int len; /* length of current match */
  74750. register Bytef *strend = s->window + s->strstart + MAX_MATCH;
  74751. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  74752. * It is easy to get rid of this optimization if necessary.
  74753. */
  74754. Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  74755. Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  74756. Assert(cur_match < s->strstart, "no future");
  74757. match = s->window + cur_match;
  74758. /* Return failure if the match length is less than 2:
  74759. */
  74760. if (match[0] != scan[0] || match[1] != scan[1]) return MIN_MATCH-1;
  74761. /* The check at best_len-1 can be removed because it will be made
  74762. * again later. (This heuristic is not always a win.)
  74763. * It is not necessary to compare scan[2] and match[2] since they
  74764. * are always equal when the other bytes match, given that
  74765. * the hash keys are equal and that HASH_BITS >= 8.
  74766. */
  74767. scan += 2, match += 2;
  74768. Assert(*scan == *match, "match[2]?");
  74769. /* We check for insufficient lookahead only every 8th comparison;
  74770. * the 256th check will be made at strstart+258.
  74771. */
  74772. do {
  74773. } while (*++scan == *++match && *++scan == *++match &&
  74774. *++scan == *++match && *++scan == *++match &&
  74775. *++scan == *++match && *++scan == *++match &&
  74776. *++scan == *++match && *++scan == *++match &&
  74777. scan < strend);
  74778. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  74779. len = MAX_MATCH - (int)(strend - scan);
  74780. if (len < MIN_MATCH) return MIN_MATCH - 1;
  74781. s->match_start = cur_match;
  74782. return (uInt)len <= s->lookahead ? (uInt)len : s->lookahead;
  74783. }
  74784. #ifdef DEBUG
  74785. /* ===========================================================================
  74786. * Check that the match at match_start is indeed a match.
  74787. */
  74788. local void check_match(deflate_state *s, IPos start, IPos match, int length)
  74789. {
  74790. /* check that the match is indeed a match */
  74791. if (zmemcmp(s->window + match,
  74792. s->window + start, length) != EQUAL) {
  74793. fprintf(stderr, " start %u, match %u, length %d\n",
  74794. start, match, length);
  74795. do {
  74796. fprintf(stderr, "%c%c", s->window[match++], s->window[start++]);
  74797. } while (--length != 0);
  74798. z_error("invalid match");
  74799. }
  74800. if (z_verbose > 1) {
  74801. fprintf(stderr,"\\[%d,%d]", start-match, length);
  74802. do { putc(s->window[start++], stderr); } while (--length != 0);
  74803. }
  74804. }
  74805. #else
  74806. # define check_match(s, start, match, length)
  74807. #endif /* DEBUG */
  74808. /* ===========================================================================
  74809. * Fill the window when the lookahead becomes insufficient.
  74810. * Updates strstart and lookahead.
  74811. *
  74812. * IN assertion: lookahead < MIN_LOOKAHEAD
  74813. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  74814. * At least one byte has been read, or avail_in == 0; reads are
  74815. * performed for at least two bytes (required for the zip translate_eol
  74816. * option -- not supported here).
  74817. */
  74818. local void fill_window (deflate_state *s)
  74819. {
  74820. register unsigned n, m;
  74821. register Posf *p;
  74822. unsigned more; /* Amount of free space at the end of the window. */
  74823. uInt wsize = s->w_size;
  74824. do {
  74825. more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart);
  74826. /* Deal with !@#$% 64K limit: */
  74827. if (sizeof(int) <= 2) {
  74828. if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  74829. more = wsize;
  74830. } else if (more == (unsigned)(-1)) {
  74831. /* Very unlikely, but possible on 16 bit machine if
  74832. * strstart == 0 && lookahead == 1 (input done a byte at time)
  74833. */
  74834. more--;
  74835. }
  74836. }
  74837. /* If the window is almost full and there is insufficient lookahead,
  74838. * move the upper half to the lower one to make room in the upper half.
  74839. */
  74840. if (s->strstart >= wsize+MAX_DIST(s)) {
  74841. zmemcpy(s->window, s->window+wsize, (unsigned)wsize);
  74842. s->match_start -= wsize;
  74843. s->strstart -= wsize; /* we now have strstart >= MAX_DIST */
  74844. s->block_start -= (long) wsize;
  74845. /* Slide the hash table (could be avoided with 32 bit values
  74846. at the expense of memory usage). We slide even when level == 0
  74847. to keep the hash table consistent if we switch back to level > 0
  74848. later. (Using level 0 permanently is not an optimal usage of
  74849. zlib, so we don't care about this pathological case.)
  74850. */
  74851. /* %%% avoid this when Z_RLE */
  74852. n = s->hash_size;
  74853. p = &s->head[n];
  74854. do {
  74855. m = *--p;
  74856. *p = (Pos)(m >= wsize ? m-wsize : NIL);
  74857. } while (--n);
  74858. n = wsize;
  74859. #ifndef FASTEST
  74860. p = &s->prev[n];
  74861. do {
  74862. m = *--p;
  74863. *p = (Pos)(m >= wsize ? m-wsize : NIL);
  74864. /* If n is not on any hash chain, prev[n] is garbage but
  74865. * its value will never be used.
  74866. */
  74867. } while (--n);
  74868. #endif
  74869. more += wsize;
  74870. }
  74871. if (s->strm->avail_in == 0) return;
  74872. /* If there was no sliding:
  74873. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  74874. * more == window_size - lookahead - strstart
  74875. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  74876. * => more >= window_size - 2*WSIZE + 2
  74877. * In the BIG_MEM or MMAP case (not yet supported),
  74878. * window_size == input_size + MIN_LOOKAHEAD &&
  74879. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  74880. * Otherwise, window_size == 2*WSIZE so more >= 2.
  74881. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  74882. */
  74883. Assert(more >= 2, "more < 2");
  74884. n = read_buf(s->strm, s->window + s->strstart + s->lookahead, more);
  74885. s->lookahead += n;
  74886. /* Initialize the hash value now that we have some input: */
  74887. if (s->lookahead >= MIN_MATCH) {
  74888. s->ins_h = s->window[s->strstart];
  74889. UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
  74890. #if MIN_MATCH != 3
  74891. Call UPDATE_HASH() MIN_MATCH-3 more times
  74892. #endif
  74893. }
  74894. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  74895. * but this is not important since only literal bytes will be emitted.
  74896. */
  74897. } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0);
  74898. }
  74899. /* ===========================================================================
  74900. * Flush the current block, with given end-of-file flag.
  74901. * IN assertion: strstart is set to the end of the current match.
  74902. */
  74903. #define FLUSH_BLOCK_ONLY(s, eof) { \
  74904. _tr_flush_block(s, (s->block_start >= 0L ? \
  74905. (charf *)&s->window[(unsigned)s->block_start] : \
  74906. (charf *)Z_NULL), \
  74907. (ulg)((long)s->strstart - s->block_start), \
  74908. (eof)); \
  74909. s->block_start = s->strstart; \
  74910. flush_pending(s->strm); \
  74911. Tracev((stderr,"[FLUSH]")); \
  74912. }
  74913. /* Same but force premature exit if necessary. */
  74914. #define FLUSH_BLOCK(s, eof) { \
  74915. FLUSH_BLOCK_ONLY(s, eof); \
  74916. if (s->strm->avail_out == 0) return (eof) ? finish_started : need_more; \
  74917. }
  74918. /* ===========================================================================
  74919. * Copy without compression as much as possible from the input stream, return
  74920. * the current block state.
  74921. * This function does not insert new strings in the dictionary since
  74922. * uncompressible data is probably not useful. This function is used
  74923. * only for the level=0 compression option.
  74924. * NOTE: this function should be optimized to avoid extra copying from
  74925. * window to pending_buf.
  74926. */
  74927. local block_state deflate_stored(deflate_state *s, int flush)
  74928. {
  74929. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  74930. * to pending_buf_size, and each stored block has a 5 byte header:
  74931. */
  74932. ulg max_block_size = 0xffff;
  74933. ulg max_start;
  74934. if (max_block_size > s->pending_buf_size - 5) {
  74935. max_block_size = s->pending_buf_size - 5;
  74936. }
  74937. /* Copy as much as possible from input to output: */
  74938. for (;;) {
  74939. /* Fill the window as much as possible: */
  74940. if (s->lookahead <= 1) {
  74941. Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  74942. s->block_start >= (long)s->w_size, "slide too late");
  74943. fill_window(s);
  74944. if (s->lookahead == 0 && flush == Z_NO_FLUSH) return need_more;
  74945. if (s->lookahead == 0) break; /* flush the current block */
  74946. }
  74947. Assert(s->block_start >= 0L, "block gone");
  74948. s->strstart += s->lookahead;
  74949. s->lookahead = 0;
  74950. /* Emit a stored block if pending_buf will be full: */
  74951. max_start = s->block_start + max_block_size;
  74952. if (s->strstart == 0 || (ulg)s->strstart >= max_start) {
  74953. /* strstart == 0 is possible when wraparound on 16-bit machine */
  74954. s->lookahead = (uInt)(s->strstart - max_start);
  74955. s->strstart = (uInt)max_start;
  74956. FLUSH_BLOCK(s, 0);
  74957. }
  74958. /* Flush if we may have to slide, otherwise block_start may become
  74959. * negative and the data will be gone:
  74960. */
  74961. if (s->strstart - (uInt)s->block_start >= MAX_DIST(s)) {
  74962. FLUSH_BLOCK(s, 0);
  74963. }
  74964. }
  74965. FLUSH_BLOCK(s, flush == Z_FINISH);
  74966. return flush == Z_FINISH ? finish_done : block_done;
  74967. }
  74968. /* ===========================================================================
  74969. * Compress as much as possible from the input stream, return the current
  74970. * block state.
  74971. * This function does not perform lazy evaluation of matches and inserts
  74972. * new strings in the dictionary only for unmatched strings or for short
  74973. * matches. It is used only for the fast compression options.
  74974. */
  74975. local block_state deflate_fast(deflate_state *s, int flush)
  74976. {
  74977. IPos hash_head = NIL; /* head of the hash chain */
  74978. int bflush; /* set if current block must be flushed */
  74979. for (;;) {
  74980. /* Make sure that we always have enough lookahead, except
  74981. * at the end of the input file. We need MAX_MATCH bytes
  74982. * for the next match, plus MIN_MATCH bytes to insert the
  74983. * string following the next match.
  74984. */
  74985. if (s->lookahead < MIN_LOOKAHEAD) {
  74986. fill_window(s);
  74987. if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
  74988. return need_more;
  74989. }
  74990. if (s->lookahead == 0) break; /* flush the current block */
  74991. }
  74992. /* Insert the string window[strstart .. strstart+2] in the
  74993. * dictionary, and set hash_head to the head of the hash chain:
  74994. */
  74995. if (s->lookahead >= MIN_MATCH) {
  74996. INSERT_STRING(s, s->strstart, hash_head);
  74997. }
  74998. /* Find the longest match, discarding those <= prev_length.
  74999. * At this point we have always match_length < MIN_MATCH
  75000. */
  75001. if (hash_head != NIL && s->strstart - hash_head <= MAX_DIST(s)) {
  75002. /* To simplify the code, we prevent matches with the string
  75003. * of window index 0 (in particular we have to avoid a match
  75004. * of the string with itself at the start of the input file).
  75005. */
  75006. #ifdef FASTEST
  75007. if ((s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) ||
  75008. (s->strategy == Z_RLE && s->strstart - hash_head == 1)) {
  75009. s->match_length = longest_match_fast (s, hash_head);
  75010. }
  75011. #else
  75012. if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) {
  75013. s->match_length = longest_match (s, hash_head);
  75014. } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) {
  75015. s->match_length = longest_match_fast (s, hash_head);
  75016. }
  75017. #endif
  75018. /* longest_match() or longest_match_fast() sets match_start */
  75019. }
  75020. if (s->match_length >= MIN_MATCH) {
  75021. check_match(s, s->strstart, s->match_start, s->match_length);
  75022. _tr_tally_dist(s, s->strstart - s->match_start,
  75023. s->match_length - MIN_MATCH, bflush);
  75024. s->lookahead -= s->match_length;
  75025. /* Insert new strings in the hash table only if the match length
  75026. * is not too large. This saves time but degrades compression.
  75027. */
  75028. #ifndef FASTEST
  75029. if (s->match_length <= s->max_insert_length &&
  75030. s->lookahead >= MIN_MATCH) {
  75031. s->match_length--; /* string at strstart already in table */
  75032. do {
  75033. s->strstart++;
  75034. INSERT_STRING(s, s->strstart, hash_head);
  75035. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  75036. * always MIN_MATCH bytes ahead.
  75037. */
  75038. } while (--s->match_length != 0);
  75039. s->strstart++;
  75040. } else
  75041. #endif
  75042. {
  75043. s->strstart += s->match_length;
  75044. s->match_length = 0;
  75045. s->ins_h = s->window[s->strstart];
  75046. UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
  75047. #if MIN_MATCH != 3
  75048. Call UPDATE_HASH() MIN_MATCH-3 more times
  75049. #endif
  75050. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  75051. * matter since it will be recomputed at next deflate call.
  75052. */
  75053. }
  75054. } else {
  75055. /* No match, output a literal byte */
  75056. Tracevv((stderr,"%c", s->window[s->strstart]));
  75057. _tr_tally_lit (s, s->window[s->strstart], bflush);
  75058. s->lookahead--;
  75059. s->strstart++;
  75060. }
  75061. if (bflush) FLUSH_BLOCK(s, 0);
  75062. }
  75063. FLUSH_BLOCK(s, flush == Z_FINISH);
  75064. return flush == Z_FINISH ? finish_done : block_done;
  75065. }
  75066. #ifndef FASTEST
  75067. /* ===========================================================================
  75068. * Same as above, but achieves better compression. We use a lazy
  75069. * evaluation for matches: a match is finally adopted only if there is
  75070. * no better match at the next window position.
  75071. */
  75072. local block_state deflate_slow(deflate_state *s, int flush)
  75073. {
  75074. IPos hash_head = NIL; /* head of hash chain */
  75075. int bflush; /* set if current block must be flushed */
  75076. /* Process the input block. */
  75077. for (;;) {
  75078. /* Make sure that we always have enough lookahead, except
  75079. * at the end of the input file. We need MAX_MATCH bytes
  75080. * for the next match, plus MIN_MATCH bytes to insert the
  75081. * string following the next match.
  75082. */
  75083. if (s->lookahead < MIN_LOOKAHEAD) {
  75084. fill_window(s);
  75085. if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
  75086. return need_more;
  75087. }
  75088. if (s->lookahead == 0) break; /* flush the current block */
  75089. }
  75090. /* Insert the string window[strstart .. strstart+2] in the
  75091. * dictionary, and set hash_head to the head of the hash chain:
  75092. */
  75093. if (s->lookahead >= MIN_MATCH) {
  75094. INSERT_STRING(s, s->strstart, hash_head);
  75095. }
  75096. /* Find the longest match, discarding those <= prev_length.
  75097. */
  75098. s->prev_length = s->match_length, s->prev_match = s->match_start;
  75099. s->match_length = MIN_MATCH-1;
  75100. if (hash_head != NIL && s->prev_length < s->max_lazy_match &&
  75101. s->strstart - hash_head <= MAX_DIST(s)) {
  75102. /* To simplify the code, we prevent matches with the string
  75103. * of window index 0 (in particular we have to avoid a match
  75104. * of the string with itself at the start of the input file).
  75105. */
  75106. if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) {
  75107. s->match_length = longest_match (s, hash_head);
  75108. } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) {
  75109. s->match_length = longest_match_fast (s, hash_head);
  75110. }
  75111. /* longest_match() or longest_match_fast() sets match_start */
  75112. if (s->match_length <= 5 && (s->strategy == Z_FILTERED
  75113. #if TOO_FAR <= 32767
  75114. || (s->match_length == MIN_MATCH &&
  75115. s->strstart - s->match_start > TOO_FAR)
  75116. #endif
  75117. )) {
  75118. /* If prev_match is also MIN_MATCH, match_start is garbage
  75119. * but we will ignore the current match anyway.
  75120. */
  75121. s->match_length = MIN_MATCH-1;
  75122. }
  75123. }
  75124. /* If there was a match at the previous step and the current
  75125. * match is not better, output the previous match:
  75126. */
  75127. if (s->prev_length >= MIN_MATCH && s->match_length <= s->prev_length) {
  75128. uInt max_insert = s->strstart + s->lookahead - MIN_MATCH;
  75129. /* Do not insert strings in hash table beyond this. */
  75130. check_match(s, s->strstart-1, s->prev_match, s->prev_length);
  75131. _tr_tally_dist(s, s->strstart -1 - s->prev_match,
  75132. s->prev_length - MIN_MATCH, bflush);
  75133. /* Insert in hash table all strings up to the end of the match.
  75134. * strstart-1 and strstart are already inserted. If there is not
  75135. * enough lookahead, the last two strings are not inserted in
  75136. * the hash table.
  75137. */
  75138. s->lookahead -= s->prev_length-1;
  75139. s->prev_length -= 2;
  75140. do {
  75141. if (++s->strstart <= max_insert) {
  75142. INSERT_STRING(s, s->strstart, hash_head);
  75143. }
  75144. } while (--s->prev_length != 0);
  75145. s->match_available = 0;
  75146. s->match_length = MIN_MATCH-1;
  75147. s->strstart++;
  75148. if (bflush) FLUSH_BLOCK(s, 0);
  75149. } else if (s->match_available) {
  75150. /* If there was no match at the previous position, output a
  75151. * single literal. If there was a match but the current match
  75152. * is longer, truncate the previous match to a single literal.
  75153. */
  75154. Tracevv((stderr,"%c", s->window[s->strstart-1]));
  75155. _tr_tally_lit(s, s->window[s->strstart-1], bflush);
  75156. if (bflush) {
  75157. FLUSH_BLOCK_ONLY(s, 0);
  75158. }
  75159. s->strstart++;
  75160. s->lookahead--;
  75161. if (s->strm->avail_out == 0) return need_more;
  75162. } else {
  75163. /* There is no previous match to compare with, wait for
  75164. * the next step to decide.
  75165. */
  75166. s->match_available = 1;
  75167. s->strstart++;
  75168. s->lookahead--;
  75169. }
  75170. }
  75171. Assert (flush != Z_NO_FLUSH, "no flush?");
  75172. if (s->match_available) {
  75173. Tracevv((stderr,"%c", s->window[s->strstart-1]));
  75174. _tr_tally_lit(s, s->window[s->strstart-1], bflush);
  75175. s->match_available = 0;
  75176. }
  75177. FLUSH_BLOCK(s, flush == Z_FINISH);
  75178. return flush == Z_FINISH ? finish_done : block_done;
  75179. }
  75180. #endif /* FASTEST */
  75181. #if 0
  75182. /* ===========================================================================
  75183. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  75184. * one. Do not maintain a hash table. (It will be regenerated if this run of
  75185. * deflate switches away from Z_RLE.)
  75186. */
  75187. local block_state deflate_rle(s, flush)
  75188. deflate_state *s;
  75189. int flush;
  75190. {
  75191. int bflush; /* set if current block must be flushed */
  75192. uInt run; /* length of run */
  75193. uInt max; /* maximum length of run */
  75194. uInt prev; /* byte at distance one to match */
  75195. Bytef *scan; /* scan for end of run */
  75196. for (;;) {
  75197. /* Make sure that we always have enough lookahead, except
  75198. * at the end of the input file. We need MAX_MATCH bytes
  75199. * for the longest encodable run.
  75200. */
  75201. if (s->lookahead < MAX_MATCH) {
  75202. fill_window(s);
  75203. if (s->lookahead < MAX_MATCH && flush == Z_NO_FLUSH) {
  75204. return need_more;
  75205. }
  75206. if (s->lookahead == 0) break; /* flush the current block */
  75207. }
  75208. /* See how many times the previous byte repeats */
  75209. run = 0;
  75210. if (s->strstart > 0) { /* if there is a previous byte, that is */
  75211. max = s->lookahead < MAX_MATCH ? s->lookahead : MAX_MATCH;
  75212. scan = s->window + s->strstart - 1;
  75213. prev = *scan++;
  75214. do {
  75215. if (*scan++ != prev)
  75216. break;
  75217. } while (++run < max);
  75218. }
  75219. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  75220. if (run >= MIN_MATCH) {
  75221. check_match(s, s->strstart, s->strstart - 1, run);
  75222. _tr_tally_dist(s, 1, run - MIN_MATCH, bflush);
  75223. s->lookahead -= run;
  75224. s->strstart += run;
  75225. } else {
  75226. /* No match, output a literal byte */
  75227. Tracevv((stderr,"%c", s->window[s->strstart]));
  75228. _tr_tally_lit (s, s->window[s->strstart], bflush);
  75229. s->lookahead--;
  75230. s->strstart++;
  75231. }
  75232. if (bflush) FLUSH_BLOCK(s, 0);
  75233. }
  75234. FLUSH_BLOCK(s, flush == Z_FINISH);
  75235. return flush == Z_FINISH ? finish_done : block_done;
  75236. }
  75237. #endif
  75238. /********* End of inlined file: deflate.c *********/
  75239. /********* Start of inlined file: infback.c *********/
  75240. /*
  75241. This code is largely copied from inflate.c. Normally either infback.o or
  75242. inflate.o would be linked into an application--not both. The interface
  75243. with inffast.c is retained so that optimized assembler-coded versions of
  75244. inflate_fast() can be used with either inflate.c or infback.c.
  75245. */
  75246. /********* Start of inlined file: inftrees.h *********/
  75247. /* WARNING: this file should *not* be used by applications. It is
  75248. part of the implementation of the compression library and is
  75249. subject to change. Applications should only use zlib.h.
  75250. */
  75251. #ifndef _INFTREES_H_
  75252. #define _INFTREES_H_
  75253. /* Structure for decoding tables. Each entry provides either the
  75254. information needed to do the operation requested by the code that
  75255. indexed that table entry, or it provides a pointer to another
  75256. table that indexes more bits of the code. op indicates whether
  75257. the entry is a pointer to another table, a literal, a length or
  75258. distance, an end-of-block, or an invalid code. For a table
  75259. pointer, the low four bits of op is the number of index bits of
  75260. that table. For a length or distance, the low four bits of op
  75261. is the number of extra bits to get after the code. bits is
  75262. the number of bits in this code or part of the code to drop off
  75263. of the bit buffer. val is the actual byte to output in the case
  75264. of a literal, the base length or distance, or the offset from
  75265. the current table to the next table. Each entry is four bytes. */
  75266. typedef struct {
  75267. unsigned char op; /* operation, extra bits, table bits */
  75268. unsigned char bits; /* bits in this part of the code */
  75269. unsigned short val; /* offset in table or code value */
  75270. } code;
  75271. /* op values as set by inflate_table():
  75272. 00000000 - literal
  75273. 0000tttt - table link, tttt != 0 is the number of table index bits
  75274. 0001eeee - length or distance, eeee is the number of extra bits
  75275. 01100000 - end of block
  75276. 01000000 - invalid code
  75277. */
  75278. /* Maximum size of dynamic tree. The maximum found in a long but non-
  75279. exhaustive search was 1444 code structures (852 for length/literals
  75280. and 592 for distances, the latter actually the result of an
  75281. exhaustive search). The true maximum is not known, but the value
  75282. below is more than safe. */
  75283. #define ENOUGH 2048
  75284. #define MAXD 592
  75285. /* Type of code to build for inftable() */
  75286. typedef enum {
  75287. CODES,
  75288. LENS,
  75289. DISTS
  75290. } codetype;
  75291. extern int inflate_table OF((codetype type, unsigned short FAR *lens,
  75292. unsigned codes, code FAR * FAR *table,
  75293. unsigned FAR *bits, unsigned short FAR *work));
  75294. #endif
  75295. /********* End of inlined file: inftrees.h *********/
  75296. /********* Start of inlined file: inflate.h *********/
  75297. /* WARNING: this file should *not* be used by applications. It is
  75298. part of the implementation of the compression library and is
  75299. subject to change. Applications should only use zlib.h.
  75300. */
  75301. #ifndef _INFLATE_H_
  75302. #define _INFLATE_H_
  75303. /* define NO_GZIP when compiling if you want to disable gzip header and
  75304. trailer decoding by inflate(). NO_GZIP would be used to avoid linking in
  75305. the crc code when it is not needed. For shared libraries, gzip decoding
  75306. should be left enabled. */
  75307. #ifndef NO_GZIP
  75308. # define GUNZIP
  75309. #endif
  75310. /* Possible inflate modes between inflate() calls */
  75311. typedef enum {
  75312. HEAD, /* i: waiting for magic header */
  75313. FLAGS, /* i: waiting for method and flags (gzip) */
  75314. TIME, /* i: waiting for modification time (gzip) */
  75315. OS, /* i: waiting for extra flags and operating system (gzip) */
  75316. EXLEN, /* i: waiting for extra length (gzip) */
  75317. EXTRA, /* i: waiting for extra bytes (gzip) */
  75318. NAME, /* i: waiting for end of file name (gzip) */
  75319. COMMENT, /* i: waiting for end of comment (gzip) */
  75320. HCRC, /* i: waiting for header crc (gzip) */
  75321. DICTID, /* i: waiting for dictionary check value */
  75322. DICT, /* waiting for inflateSetDictionary() call */
  75323. TYPE, /* i: waiting for type bits, including last-flag bit */
  75324. TYPEDO, /* i: same, but skip check to exit inflate on new block */
  75325. STORED, /* i: waiting for stored size (length and complement) */
  75326. COPY, /* i/o: waiting for input or output to copy stored block */
  75327. TABLE, /* i: waiting for dynamic block table lengths */
  75328. LENLENS, /* i: waiting for code length code lengths */
  75329. CODELENS, /* i: waiting for length/lit and distance code lengths */
  75330. LEN, /* i: waiting for length/lit code */
  75331. LENEXT, /* i: waiting for length extra bits */
  75332. DIST, /* i: waiting for distance code */
  75333. DISTEXT, /* i: waiting for distance extra bits */
  75334. MATCH, /* o: waiting for output space to copy string */
  75335. LIT, /* o: waiting for output space to write literal */
  75336. CHECK, /* i: waiting for 32-bit check value */
  75337. LENGTH, /* i: waiting for 32-bit length (gzip) */
  75338. DONE, /* finished check, done -- remain here until reset */
  75339. BAD, /* got a data error -- remain here until reset */
  75340. MEM, /* got an inflate() memory error -- remain here until reset */
  75341. SYNC /* looking for synchronization bytes to restart inflate() */
  75342. } inflate_mode;
  75343. /*
  75344. State transitions between above modes -
  75345. (most modes can go to the BAD or MEM mode -- not shown for clarity)
  75346. Process header:
  75347. HEAD -> (gzip) or (zlib)
  75348. (gzip) -> FLAGS -> TIME -> OS -> EXLEN -> EXTRA -> NAME
  75349. NAME -> COMMENT -> HCRC -> TYPE
  75350. (zlib) -> DICTID or TYPE
  75351. DICTID -> DICT -> TYPE
  75352. Read deflate blocks:
  75353. TYPE -> STORED or TABLE or LEN or CHECK
  75354. STORED -> COPY -> TYPE
  75355. TABLE -> LENLENS -> CODELENS -> LEN
  75356. Read deflate codes:
  75357. LEN -> LENEXT or LIT or TYPE
  75358. LENEXT -> DIST -> DISTEXT -> MATCH -> LEN
  75359. LIT -> LEN
  75360. Process trailer:
  75361. CHECK -> LENGTH -> DONE
  75362. */
  75363. /* state maintained between inflate() calls. Approximately 7K bytes. */
  75364. struct inflate_state {
  75365. inflate_mode mode; /* current inflate mode */
  75366. int last; /* true if processing last block */
  75367. int wrap; /* bit 0 true for zlib, bit 1 true for gzip */
  75368. int havedict; /* true if dictionary provided */
  75369. int flags; /* gzip header method and flags (0 if zlib) */
  75370. unsigned dmax; /* zlib header max distance (INFLATE_STRICT) */
  75371. unsigned long check; /* protected copy of check value */
  75372. unsigned long total; /* protected copy of output count */
  75373. gz_headerp head; /* where to save gzip header information */
  75374. /* sliding window */
  75375. unsigned wbits; /* log base 2 of requested window size */
  75376. unsigned wsize; /* window size or zero if not using window */
  75377. unsigned whave; /* valid bytes in the window */
  75378. unsigned write; /* window write index */
  75379. unsigned char FAR *window; /* allocated sliding window, if needed */
  75380. /* bit accumulator */
  75381. unsigned long hold; /* input bit accumulator */
  75382. unsigned bits; /* number of bits in "in" */
  75383. /* for string and stored block copying */
  75384. unsigned length; /* literal or length of data to copy */
  75385. unsigned offset; /* distance back to copy string from */
  75386. /* for table and code decoding */
  75387. unsigned extra; /* extra bits needed */
  75388. /* fixed and dynamic code tables */
  75389. code const FAR *lencode; /* starting table for length/literal codes */
  75390. code const FAR *distcode; /* starting table for distance codes */
  75391. unsigned lenbits; /* index bits for lencode */
  75392. unsigned distbits; /* index bits for distcode */
  75393. /* dynamic table building */
  75394. unsigned ncode; /* number of code length code lengths */
  75395. unsigned nlen; /* number of length code lengths */
  75396. unsigned ndist; /* number of distance code lengths */
  75397. unsigned have; /* number of code lengths in lens[] */
  75398. code FAR *next; /* next available space in codes[] */
  75399. unsigned short lens[320]; /* temporary storage for code lengths */
  75400. unsigned short work[288]; /* work area for code table building */
  75401. code codes[ENOUGH]; /* space for code tables */
  75402. };
  75403. #endif
  75404. /********* End of inlined file: inflate.h *********/
  75405. /********* Start of inlined file: inffast.h *********/
  75406. /* WARNING: this file should *not* be used by applications. It is
  75407. part of the implementation of the compression library and is
  75408. subject to change. Applications should only use zlib.h.
  75409. */
  75410. void inflate_fast OF((z_streamp strm, unsigned start));
  75411. /********* End of inlined file: inffast.h *********/
  75412. /* function prototypes */
  75413. local void fixedtables1 OF((struct inflate_state FAR *state));
  75414. /*
  75415. strm provides memory allocation functions in zalloc and zfree, or
  75416. Z_NULL to use the library memory allocation functions.
  75417. windowBits is in the range 8..15, and window is a user-supplied
  75418. window and output buffer that is 2**windowBits bytes.
  75419. */
  75420. int ZEXPORT inflateBackInit_(z_streamp strm, int windowBits, unsigned char FAR *window, const char *version, int stream_size)
  75421. {
  75422. struct inflate_state FAR *state;
  75423. if (version == Z_NULL || version[0] != ZLIB_VERSION[0] ||
  75424. stream_size != (int)(sizeof(z_stream)))
  75425. return Z_VERSION_ERROR;
  75426. if (strm == Z_NULL || window == Z_NULL ||
  75427. windowBits < 8 || windowBits > 15)
  75428. return Z_STREAM_ERROR;
  75429. strm->msg = Z_NULL; /* in case we return an error */
  75430. if (strm->zalloc == (alloc_func)0) {
  75431. strm->zalloc = zcalloc;
  75432. strm->opaque = (voidpf)0;
  75433. }
  75434. if (strm->zfree == (free_func)0) strm->zfree = zcfree;
  75435. state = (struct inflate_state FAR *)ZALLOC(strm, 1,
  75436. sizeof(struct inflate_state));
  75437. if (state == Z_NULL) return Z_MEM_ERROR;
  75438. Tracev((stderr, "inflate: allocated\n"));
  75439. strm->state = (struct internal_state FAR *)state;
  75440. state->dmax = 32768U;
  75441. state->wbits = windowBits;
  75442. state->wsize = 1U << windowBits;
  75443. state->window = window;
  75444. state->write = 0;
  75445. state->whave = 0;
  75446. return Z_OK;
  75447. }
  75448. /*
  75449. Return state with length and distance decoding tables and index sizes set to
  75450. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  75451. If BUILDFIXED is defined, then instead this routine builds the tables the
  75452. first time it's called, and returns those tables the first time and
  75453. thereafter. This reduces the size of the code by about 2K bytes, in
  75454. exchange for a little execution time. However, BUILDFIXED should not be
  75455. used for threaded applications, since the rewriting of the tables and virgin
  75456. may not be thread-safe.
  75457. */
  75458. local void fixedtables1 (struct inflate_state FAR *state)
  75459. {
  75460. #ifdef BUILDFIXED
  75461. static int virgin = 1;
  75462. static code *lenfix, *distfix;
  75463. static code fixed[544];
  75464. /* build fixed huffman tables if first call (may not be thread safe) */
  75465. if (virgin) {
  75466. unsigned sym, bits;
  75467. static code *next;
  75468. /* literal/length table */
  75469. sym = 0;
  75470. while (sym < 144) state->lens[sym++] = 8;
  75471. while (sym < 256) state->lens[sym++] = 9;
  75472. while (sym < 280) state->lens[sym++] = 7;
  75473. while (sym < 288) state->lens[sym++] = 8;
  75474. next = fixed;
  75475. lenfix = next;
  75476. bits = 9;
  75477. inflate_table(LENS, state->lens, 288, &(next), &(bits), state->work);
  75478. /* distance table */
  75479. sym = 0;
  75480. while (sym < 32) state->lens[sym++] = 5;
  75481. distfix = next;
  75482. bits = 5;
  75483. inflate_table(DISTS, state->lens, 32, &(next), &(bits), state->work);
  75484. /* do this just once */
  75485. virgin = 0;
  75486. }
  75487. #else /* !BUILDFIXED */
  75488. /********* Start of inlined file: inffixed.h *********/
  75489. /* inffixed.h -- table for decoding fixed codes
  75490. * Generated automatically by makefixed().
  75491. */
  75492. /* WARNING: this file should *not* be used by applications. It
  75493. is part of the implementation of the compression library and
  75494. is subject to change. Applications should only use zlib.h.
  75495. */
  75496. static const code lenfix[512] = {
  75497. {96,7,0},{0,8,80},{0,8,16},{20,8,115},{18,7,31},{0,8,112},{0,8,48},
  75498. {0,9,192},{16,7,10},{0,8,96},{0,8,32},{0,9,160},{0,8,0},{0,8,128},
  75499. {0,8,64},{0,9,224},{16,7,6},{0,8,88},{0,8,24},{0,9,144},{19,7,59},
  75500. {0,8,120},{0,8,56},{0,9,208},{17,7,17},{0,8,104},{0,8,40},{0,9,176},
  75501. {0,8,8},{0,8,136},{0,8,72},{0,9,240},{16,7,4},{0,8,84},{0,8,20},
  75502. {21,8,227},{19,7,43},{0,8,116},{0,8,52},{0,9,200},{17,7,13},{0,8,100},
  75503. {0,8,36},{0,9,168},{0,8,4},{0,8,132},{0,8,68},{0,9,232},{16,7,8},
  75504. {0,8,92},{0,8,28},{0,9,152},{20,7,83},{0,8,124},{0,8,60},{0,9,216},
  75505. {18,7,23},{0,8,108},{0,8,44},{0,9,184},{0,8,12},{0,8,140},{0,8,76},
  75506. {0,9,248},{16,7,3},{0,8,82},{0,8,18},{21,8,163},{19,7,35},{0,8,114},
  75507. {0,8,50},{0,9,196},{17,7,11},{0,8,98},{0,8,34},{0,9,164},{0,8,2},
  75508. {0,8,130},{0,8,66},{0,9,228},{16,7,7},{0,8,90},{0,8,26},{0,9,148},
  75509. {20,7,67},{0,8,122},{0,8,58},{0,9,212},{18,7,19},{0,8,106},{0,8,42},
  75510. {0,9,180},{0,8,10},{0,8,138},{0,8,74},{0,9,244},{16,7,5},{0,8,86},
  75511. {0,8,22},{64,8,0},{19,7,51},{0,8,118},{0,8,54},{0,9,204},{17,7,15},
  75512. {0,8,102},{0,8,38},{0,9,172},{0,8,6},{0,8,134},{0,8,70},{0,9,236},
  75513. {16,7,9},{0,8,94},{0,8,30},{0,9,156},{20,7,99},{0,8,126},{0,8,62},
  75514. {0,9,220},{18,7,27},{0,8,110},{0,8,46},{0,9,188},{0,8,14},{0,8,142},
  75515. {0,8,78},{0,9,252},{96,7,0},{0,8,81},{0,8,17},{21,8,131},{18,7,31},
  75516. {0,8,113},{0,8,49},{0,9,194},{16,7,10},{0,8,97},{0,8,33},{0,9,162},
  75517. {0,8,1},{0,8,129},{0,8,65},{0,9,226},{16,7,6},{0,8,89},{0,8,25},
  75518. {0,9,146},{19,7,59},{0,8,121},{0,8,57},{0,9,210},{17,7,17},{0,8,105},
  75519. {0,8,41},{0,9,178},{0,8,9},{0,8,137},{0,8,73},{0,9,242},{16,7,4},
  75520. {0,8,85},{0,8,21},{16,8,258},{19,7,43},{0,8,117},{0,8,53},{0,9,202},
  75521. {17,7,13},{0,8,101},{0,8,37},{0,9,170},{0,8,5},{0,8,133},{0,8,69},
  75522. {0,9,234},{16,7,8},{0,8,93},{0,8,29},{0,9,154},{20,7,83},{0,8,125},
  75523. {0,8,61},{0,9,218},{18,7,23},{0,8,109},{0,8,45},{0,9,186},{0,8,13},
  75524. {0,8,141},{0,8,77},{0,9,250},{16,7,3},{0,8,83},{0,8,19},{21,8,195},
  75525. {19,7,35},{0,8,115},{0,8,51},{0,9,198},{17,7,11},{0,8,99},{0,8,35},
  75526. {0,9,166},{0,8,3},{0,8,131},{0,8,67},{0,9,230},{16,7,7},{0,8,91},
  75527. {0,8,27},{0,9,150},{20,7,67},{0,8,123},{0,8,59},{0,9,214},{18,7,19},
  75528. {0,8,107},{0,8,43},{0,9,182},{0,8,11},{0,8,139},{0,8,75},{0,9,246},
  75529. {16,7,5},{0,8,87},{0,8,23},{64,8,0},{19,7,51},{0,8,119},{0,8,55},
  75530. {0,9,206},{17,7,15},{0,8,103},{0,8,39},{0,9,174},{0,8,7},{0,8,135},
  75531. {0,8,71},{0,9,238},{16,7,9},{0,8,95},{0,8,31},{0,9,158},{20,7,99},
  75532. {0,8,127},{0,8,63},{0,9,222},{18,7,27},{0,8,111},{0,8,47},{0,9,190},
  75533. {0,8,15},{0,8,143},{0,8,79},{0,9,254},{96,7,0},{0,8,80},{0,8,16},
  75534. {20,8,115},{18,7,31},{0,8,112},{0,8,48},{0,9,193},{16,7,10},{0,8,96},
  75535. {0,8,32},{0,9,161},{0,8,0},{0,8,128},{0,8,64},{0,9,225},{16,7,6},
  75536. {0,8,88},{0,8,24},{0,9,145},{19,7,59},{0,8,120},{0,8,56},{0,9,209},
  75537. {17,7,17},{0,8,104},{0,8,40},{0,9,177},{0,8,8},{0,8,136},{0,8,72},
  75538. {0,9,241},{16,7,4},{0,8,84},{0,8,20},{21,8,227},{19,7,43},{0,8,116},
  75539. {0,8,52},{0,9,201},{17,7,13},{0,8,100},{0,8,36},{0,9,169},{0,8,4},
  75540. {0,8,132},{0,8,68},{0,9,233},{16,7,8},{0,8,92},{0,8,28},{0,9,153},
  75541. {20,7,83},{0,8,124},{0,8,60},{0,9,217},{18,7,23},{0,8,108},{0,8,44},
  75542. {0,9,185},{0,8,12},{0,8,140},{0,8,76},{0,9,249},{16,7,3},{0,8,82},
  75543. {0,8,18},{21,8,163},{19,7,35},{0,8,114},{0,8,50},{0,9,197},{17,7,11},
  75544. {0,8,98},{0,8,34},{0,9,165},{0,8,2},{0,8,130},{0,8,66},{0,9,229},
  75545. {16,7,7},{0,8,90},{0,8,26},{0,9,149},{20,7,67},{0,8,122},{0,8,58},
  75546. {0,9,213},{18,7,19},{0,8,106},{0,8,42},{0,9,181},{0,8,10},{0,8,138},
  75547. {0,8,74},{0,9,245},{16,7,5},{0,8,86},{0,8,22},{64,8,0},{19,7,51},
  75548. {0,8,118},{0,8,54},{0,9,205},{17,7,15},{0,8,102},{0,8,38},{0,9,173},
  75549. {0,8,6},{0,8,134},{0,8,70},{0,9,237},{16,7,9},{0,8,94},{0,8,30},
  75550. {0,9,157},{20,7,99},{0,8,126},{0,8,62},{0,9,221},{18,7,27},{0,8,110},
  75551. {0,8,46},{0,9,189},{0,8,14},{0,8,142},{0,8,78},{0,9,253},{96,7,0},
  75552. {0,8,81},{0,8,17},{21,8,131},{18,7,31},{0,8,113},{0,8,49},{0,9,195},
  75553. {16,7,10},{0,8,97},{0,8,33},{0,9,163},{0,8,1},{0,8,129},{0,8,65},
  75554. {0,9,227},{16,7,6},{0,8,89},{0,8,25},{0,9,147},{19,7,59},{0,8,121},
  75555. {0,8,57},{0,9,211},{17,7,17},{0,8,105},{0,8,41},{0,9,179},{0,8,9},
  75556. {0,8,137},{0,8,73},{0,9,243},{16,7,4},{0,8,85},{0,8,21},{16,8,258},
  75557. {19,7,43},{0,8,117},{0,8,53},{0,9,203},{17,7,13},{0,8,101},{0,8,37},
  75558. {0,9,171},{0,8,5},{0,8,133},{0,8,69},{0,9,235},{16,7,8},{0,8,93},
  75559. {0,8,29},{0,9,155},{20,7,83},{0,8,125},{0,8,61},{0,9,219},{18,7,23},
  75560. {0,8,109},{0,8,45},{0,9,187},{0,8,13},{0,8,141},{0,8,77},{0,9,251},
  75561. {16,7,3},{0,8,83},{0,8,19},{21,8,195},{19,7,35},{0,8,115},{0,8,51},
  75562. {0,9,199},{17,7,11},{0,8,99},{0,8,35},{0,9,167},{0,8,3},{0,8,131},
  75563. {0,8,67},{0,9,231},{16,7,7},{0,8,91},{0,8,27},{0,9,151},{20,7,67},
  75564. {0,8,123},{0,8,59},{0,9,215},{18,7,19},{0,8,107},{0,8,43},{0,9,183},
  75565. {0,8,11},{0,8,139},{0,8,75},{0,9,247},{16,7,5},{0,8,87},{0,8,23},
  75566. {64,8,0},{19,7,51},{0,8,119},{0,8,55},{0,9,207},{17,7,15},{0,8,103},
  75567. {0,8,39},{0,9,175},{0,8,7},{0,8,135},{0,8,71},{0,9,239},{16,7,9},
  75568. {0,8,95},{0,8,31},{0,9,159},{20,7,99},{0,8,127},{0,8,63},{0,9,223},
  75569. {18,7,27},{0,8,111},{0,8,47},{0,9,191},{0,8,15},{0,8,143},{0,8,79},
  75570. {0,9,255}
  75571. };
  75572. static const code distfix[32] = {
  75573. {16,5,1},{23,5,257},{19,5,17},{27,5,4097},{17,5,5},{25,5,1025},
  75574. {21,5,65},{29,5,16385},{16,5,3},{24,5,513},{20,5,33},{28,5,8193},
  75575. {18,5,9},{26,5,2049},{22,5,129},{64,5,0},{16,5,2},{23,5,385},
  75576. {19,5,25},{27,5,6145},{17,5,7},{25,5,1537},{21,5,97},{29,5,24577},
  75577. {16,5,4},{24,5,769},{20,5,49},{28,5,12289},{18,5,13},{26,5,3073},
  75578. {22,5,193},{64,5,0}
  75579. };
  75580. /********* End of inlined file: inffixed.h *********/
  75581. #endif /* BUILDFIXED */
  75582. state->lencode = lenfix;
  75583. state->lenbits = 9;
  75584. state->distcode = distfix;
  75585. state->distbits = 5;
  75586. }
  75587. /* Macros for inflateBack(): */
  75588. /* Load returned state from inflate_fast() */
  75589. #define LOAD() \
  75590. do { \
  75591. put = strm->next_out; \
  75592. left = strm->avail_out; \
  75593. next = strm->next_in; \
  75594. have = strm->avail_in; \
  75595. hold = state->hold; \
  75596. bits = state->bits; \
  75597. } while (0)
  75598. /* Set state from registers for inflate_fast() */
  75599. #define RESTORE() \
  75600. do { \
  75601. strm->next_out = put; \
  75602. strm->avail_out = left; \
  75603. strm->next_in = next; \
  75604. strm->avail_in = have; \
  75605. state->hold = hold; \
  75606. state->bits = bits; \
  75607. } while (0)
  75608. /* Clear the input bit accumulator */
  75609. #define INITBITS() \
  75610. do { \
  75611. hold = 0; \
  75612. bits = 0; \
  75613. } while (0)
  75614. /* Assure that some input is available. If input is requested, but denied,
  75615. then return a Z_BUF_ERROR from inflateBack(). */
  75616. #define PULL() \
  75617. do { \
  75618. if (have == 0) { \
  75619. have = in(in_desc, &next); \
  75620. if (have == 0) { \
  75621. next = Z_NULL; \
  75622. ret = Z_BUF_ERROR; \
  75623. goto inf_leave; \
  75624. } \
  75625. } \
  75626. } while (0)
  75627. /* Get a byte of input into the bit accumulator, or return from inflateBack()
  75628. with an error if there is no input available. */
  75629. #define PULLBYTE() \
  75630. do { \
  75631. PULL(); \
  75632. have--; \
  75633. hold += (unsigned long)(*next++) << bits; \
  75634. bits += 8; \
  75635. } while (0)
  75636. /* Assure that there are at least n bits in the bit accumulator. If there is
  75637. not enough available input to do that, then return from inflateBack() with
  75638. an error. */
  75639. #define NEEDBITS(n) \
  75640. do { \
  75641. while (bits < (unsigned)(n)) \
  75642. PULLBYTE(); \
  75643. } while (0)
  75644. /* Return the low n bits of the bit accumulator (n < 16) */
  75645. #define BITS(n) \
  75646. ((unsigned)hold & ((1U << (n)) - 1))
  75647. /* Remove n bits from the bit accumulator */
  75648. #define DROPBITS(n) \
  75649. do { \
  75650. hold >>= (n); \
  75651. bits -= (unsigned)(n); \
  75652. } while (0)
  75653. /* Remove zero to seven bits as needed to go to a byte boundary */
  75654. #define BYTEBITS() \
  75655. do { \
  75656. hold >>= bits & 7; \
  75657. bits -= bits & 7; \
  75658. } while (0)
  75659. /* Assure that some output space is available, by writing out the window
  75660. if it's full. If the write fails, return from inflateBack() with a
  75661. Z_BUF_ERROR. */
  75662. #define ROOM() \
  75663. do { \
  75664. if (left == 0) { \
  75665. put = state->window; \
  75666. left = state->wsize; \
  75667. state->whave = left; \
  75668. if (out(out_desc, put, left)) { \
  75669. ret = Z_BUF_ERROR; \
  75670. goto inf_leave; \
  75671. } \
  75672. } \
  75673. } while (0)
  75674. /*
  75675. strm provides the memory allocation functions and window buffer on input,
  75676. and provides information on the unused input on return. For Z_DATA_ERROR
  75677. returns, strm will also provide an error message.
  75678. in() and out() are the call-back input and output functions. When
  75679. inflateBack() needs more input, it calls in(). When inflateBack() has
  75680. filled the window with output, or when it completes with data in the
  75681. window, it calls out() to write out the data. The application must not
  75682. change the provided input until in() is called again or inflateBack()
  75683. returns. The application must not change the window/output buffer until
  75684. inflateBack() returns.
  75685. in() and out() are called with a descriptor parameter provided in the
  75686. inflateBack() call. This parameter can be a structure that provides the
  75687. information required to do the read or write, as well as accumulated
  75688. information on the input and output such as totals and check values.
  75689. in() should return zero on failure. out() should return non-zero on
  75690. failure. If either in() or out() fails, than inflateBack() returns a
  75691. Z_BUF_ERROR. strm->next_in can be checked for Z_NULL to see whether it
  75692. was in() or out() that caused in the error. Otherwise, inflateBack()
  75693. returns Z_STREAM_END on success, Z_DATA_ERROR for an deflate format
  75694. error, or Z_MEM_ERROR if it could not allocate memory for the state.
  75695. inflateBack() can also return Z_STREAM_ERROR if the input parameters
  75696. are not correct, i.e. strm is Z_NULL or the state was not initialized.
  75697. */
  75698. int ZEXPORT inflateBack(z_streamp strm, in_func in, void FAR *in_desc, out_func out, void FAR *out_desc)
  75699. {
  75700. struct inflate_state FAR *state;
  75701. unsigned char FAR *next; /* next input */
  75702. unsigned char FAR *put; /* next output */
  75703. unsigned have, left; /* available input and output */
  75704. unsigned long hold; /* bit buffer */
  75705. unsigned bits; /* bits in bit buffer */
  75706. unsigned copy; /* number of stored or match bytes to copy */
  75707. unsigned char FAR *from; /* where to copy match bytes from */
  75708. code thisx; /* current decoding table entry */
  75709. code last; /* parent table entry */
  75710. unsigned len; /* length to copy for repeats, bits to drop */
  75711. int ret; /* return code */
  75712. static const unsigned short order[19] = /* permutation of code lengths */
  75713. {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
  75714. /* Check that the strm exists and that the state was initialized */
  75715. if (strm == Z_NULL || strm->state == Z_NULL)
  75716. return Z_STREAM_ERROR;
  75717. state = (struct inflate_state FAR *)strm->state;
  75718. /* Reset the state */
  75719. strm->msg = Z_NULL;
  75720. state->mode = TYPE;
  75721. state->last = 0;
  75722. state->whave = 0;
  75723. next = strm->next_in;
  75724. have = next != Z_NULL ? strm->avail_in : 0;
  75725. hold = 0;
  75726. bits = 0;
  75727. put = state->window;
  75728. left = state->wsize;
  75729. /* Inflate until end of block marked as last */
  75730. for (;;)
  75731. switch (state->mode) {
  75732. case TYPE:
  75733. /* determine and dispatch block type */
  75734. if (state->last) {
  75735. BYTEBITS();
  75736. state->mode = DONE;
  75737. break;
  75738. }
  75739. NEEDBITS(3);
  75740. state->last = BITS(1);
  75741. DROPBITS(1);
  75742. switch (BITS(2)) {
  75743. case 0: /* stored block */
  75744. Tracev((stderr, "inflate: stored block%s\n",
  75745. state->last ? " (last)" : ""));
  75746. state->mode = STORED;
  75747. break;
  75748. case 1: /* fixed block */
  75749. fixedtables1(state);
  75750. Tracev((stderr, "inflate: fixed codes block%s\n",
  75751. state->last ? " (last)" : ""));
  75752. state->mode = LEN; /* decode codes */
  75753. break;
  75754. case 2: /* dynamic block */
  75755. Tracev((stderr, "inflate: dynamic codes block%s\n",
  75756. state->last ? " (last)" : ""));
  75757. state->mode = TABLE;
  75758. break;
  75759. case 3:
  75760. strm->msg = (char *)"invalid block type";
  75761. state->mode = BAD;
  75762. }
  75763. DROPBITS(2);
  75764. break;
  75765. case STORED:
  75766. /* get and verify stored block length */
  75767. BYTEBITS(); /* go to byte boundary */
  75768. NEEDBITS(32);
  75769. if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) {
  75770. strm->msg = (char *)"invalid stored block lengths";
  75771. state->mode = BAD;
  75772. break;
  75773. }
  75774. state->length = (unsigned)hold & 0xffff;
  75775. Tracev((stderr, "inflate: stored length %u\n",
  75776. state->length));
  75777. INITBITS();
  75778. /* copy stored block from input to output */
  75779. while (state->length != 0) {
  75780. copy = state->length;
  75781. PULL();
  75782. ROOM();
  75783. if (copy > have) copy = have;
  75784. if (copy > left) copy = left;
  75785. zmemcpy(put, next, copy);
  75786. have -= copy;
  75787. next += copy;
  75788. left -= copy;
  75789. put += copy;
  75790. state->length -= copy;
  75791. }
  75792. Tracev((stderr, "inflate: stored end\n"));
  75793. state->mode = TYPE;
  75794. break;
  75795. case TABLE:
  75796. /* get dynamic table entries descriptor */
  75797. NEEDBITS(14);
  75798. state->nlen = BITS(5) + 257;
  75799. DROPBITS(5);
  75800. state->ndist = BITS(5) + 1;
  75801. DROPBITS(5);
  75802. state->ncode = BITS(4) + 4;
  75803. DROPBITS(4);
  75804. #ifndef PKZIP_BUG_WORKAROUND
  75805. if (state->nlen > 286 || state->ndist > 30) {
  75806. strm->msg = (char *)"too many length or distance symbols";
  75807. state->mode = BAD;
  75808. break;
  75809. }
  75810. #endif
  75811. Tracev((stderr, "inflate: table sizes ok\n"));
  75812. /* get code length code lengths (not a typo) */
  75813. state->have = 0;
  75814. while (state->have < state->ncode) {
  75815. NEEDBITS(3);
  75816. state->lens[order[state->have++]] = (unsigned short)BITS(3);
  75817. DROPBITS(3);
  75818. }
  75819. while (state->have < 19)
  75820. state->lens[order[state->have++]] = 0;
  75821. state->next = state->codes;
  75822. state->lencode = (code const FAR *)(state->next);
  75823. state->lenbits = 7;
  75824. ret = inflate_table(CODES, state->lens, 19, &(state->next),
  75825. &(state->lenbits), state->work);
  75826. if (ret) {
  75827. strm->msg = (char *)"invalid code lengths set";
  75828. state->mode = BAD;
  75829. break;
  75830. }
  75831. Tracev((stderr, "inflate: code lengths ok\n"));
  75832. /* get length and distance code code lengths */
  75833. state->have = 0;
  75834. while (state->have < state->nlen + state->ndist) {
  75835. for (;;) {
  75836. thisx = state->lencode[BITS(state->lenbits)];
  75837. if ((unsigned)(thisx.bits) <= bits) break;
  75838. PULLBYTE();
  75839. }
  75840. if (thisx.val < 16) {
  75841. NEEDBITS(thisx.bits);
  75842. DROPBITS(thisx.bits);
  75843. state->lens[state->have++] = thisx.val;
  75844. }
  75845. else {
  75846. if (thisx.val == 16) {
  75847. NEEDBITS(thisx.bits + 2);
  75848. DROPBITS(thisx.bits);
  75849. if (state->have == 0) {
  75850. strm->msg = (char *)"invalid bit length repeat";
  75851. state->mode = BAD;
  75852. break;
  75853. }
  75854. len = (unsigned)(state->lens[state->have - 1]);
  75855. copy = 3 + BITS(2);
  75856. DROPBITS(2);
  75857. }
  75858. else if (thisx.val == 17) {
  75859. NEEDBITS(thisx.bits + 3);
  75860. DROPBITS(thisx.bits);
  75861. len = 0;
  75862. copy = 3 + BITS(3);
  75863. DROPBITS(3);
  75864. }
  75865. else {
  75866. NEEDBITS(thisx.bits + 7);
  75867. DROPBITS(thisx.bits);
  75868. len = 0;
  75869. copy = 11 + BITS(7);
  75870. DROPBITS(7);
  75871. }
  75872. if (state->have + copy > state->nlen + state->ndist) {
  75873. strm->msg = (char *)"invalid bit length repeat";
  75874. state->mode = BAD;
  75875. break;
  75876. }
  75877. while (copy--)
  75878. state->lens[state->have++] = (unsigned short)len;
  75879. }
  75880. }
  75881. /* handle error breaks in while */
  75882. if (state->mode == BAD) break;
  75883. /* build code tables */
  75884. state->next = state->codes;
  75885. state->lencode = (code const FAR *)(state->next);
  75886. state->lenbits = 9;
  75887. ret = inflate_table(LENS, state->lens, state->nlen, &(state->next),
  75888. &(state->lenbits), state->work);
  75889. if (ret) {
  75890. strm->msg = (char *)"invalid literal/lengths set";
  75891. state->mode = BAD;
  75892. break;
  75893. }
  75894. state->distcode = (code const FAR *)(state->next);
  75895. state->distbits = 6;
  75896. ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist,
  75897. &(state->next), &(state->distbits), state->work);
  75898. if (ret) {
  75899. strm->msg = (char *)"invalid distances set";
  75900. state->mode = BAD;
  75901. break;
  75902. }
  75903. Tracev((stderr, "inflate: codes ok\n"));
  75904. state->mode = LEN;
  75905. case LEN:
  75906. /* use inflate_fast() if we have enough input and output */
  75907. if (have >= 6 && left >= 258) {
  75908. RESTORE();
  75909. if (state->whave < state->wsize)
  75910. state->whave = state->wsize - left;
  75911. inflate_fast(strm, state->wsize);
  75912. LOAD();
  75913. break;
  75914. }
  75915. /* get a literal, length, or end-of-block code */
  75916. for (;;) {
  75917. thisx = state->lencode[BITS(state->lenbits)];
  75918. if ((unsigned)(thisx.bits) <= bits) break;
  75919. PULLBYTE();
  75920. }
  75921. if (thisx.op && (thisx.op & 0xf0) == 0) {
  75922. last = thisx;
  75923. for (;;) {
  75924. thisx = state->lencode[last.val +
  75925. (BITS(last.bits + last.op) >> last.bits)];
  75926. if ((unsigned)(last.bits + thisx.bits) <= bits) break;
  75927. PULLBYTE();
  75928. }
  75929. DROPBITS(last.bits);
  75930. }
  75931. DROPBITS(thisx.bits);
  75932. state->length = (unsigned)thisx.val;
  75933. /* process literal */
  75934. if (thisx.op == 0) {
  75935. Tracevv((stderr, thisx.val >= 0x20 && thisx.val < 0x7f ?
  75936. "inflate: literal '%c'\n" :
  75937. "inflate: literal 0x%02x\n", thisx.val));
  75938. ROOM();
  75939. *put++ = (unsigned char)(state->length);
  75940. left--;
  75941. state->mode = LEN;
  75942. break;
  75943. }
  75944. /* process end of block */
  75945. if (thisx.op & 32) {
  75946. Tracevv((stderr, "inflate: end of block\n"));
  75947. state->mode = TYPE;
  75948. break;
  75949. }
  75950. /* invalid code */
  75951. if (thisx.op & 64) {
  75952. strm->msg = (char *)"invalid literal/length code";
  75953. state->mode = BAD;
  75954. break;
  75955. }
  75956. /* length code -- get extra bits, if any */
  75957. state->extra = (unsigned)(thisx.op) & 15;
  75958. if (state->extra != 0) {
  75959. NEEDBITS(state->extra);
  75960. state->length += BITS(state->extra);
  75961. DROPBITS(state->extra);
  75962. }
  75963. Tracevv((stderr, "inflate: length %u\n", state->length));
  75964. /* get distance code */
  75965. for (;;) {
  75966. thisx = state->distcode[BITS(state->distbits)];
  75967. if ((unsigned)(thisx.bits) <= bits) break;
  75968. PULLBYTE();
  75969. }
  75970. if ((thisx.op & 0xf0) == 0) {
  75971. last = thisx;
  75972. for (;;) {
  75973. thisx = state->distcode[last.val +
  75974. (BITS(last.bits + last.op) >> last.bits)];
  75975. if ((unsigned)(last.bits + thisx.bits) <= bits) break;
  75976. PULLBYTE();
  75977. }
  75978. DROPBITS(last.bits);
  75979. }
  75980. DROPBITS(thisx.bits);
  75981. if (thisx.op & 64) {
  75982. strm->msg = (char *)"invalid distance code";
  75983. state->mode = BAD;
  75984. break;
  75985. }
  75986. state->offset = (unsigned)thisx.val;
  75987. /* get distance extra bits, if any */
  75988. state->extra = (unsigned)(thisx.op) & 15;
  75989. if (state->extra != 0) {
  75990. NEEDBITS(state->extra);
  75991. state->offset += BITS(state->extra);
  75992. DROPBITS(state->extra);
  75993. }
  75994. if (state->offset > state->wsize - (state->whave < state->wsize ?
  75995. left : 0)) {
  75996. strm->msg = (char *)"invalid distance too far back";
  75997. state->mode = BAD;
  75998. break;
  75999. }
  76000. Tracevv((stderr, "inflate: distance %u\n", state->offset));
  76001. /* copy match from window to output */
  76002. do {
  76003. ROOM();
  76004. copy = state->wsize - state->offset;
  76005. if (copy < left) {
  76006. from = put + copy;
  76007. copy = left - copy;
  76008. }
  76009. else {
  76010. from = put - state->offset;
  76011. copy = left;
  76012. }
  76013. if (copy > state->length) copy = state->length;
  76014. state->length -= copy;
  76015. left -= copy;
  76016. do {
  76017. *put++ = *from++;
  76018. } while (--copy);
  76019. } while (state->length != 0);
  76020. break;
  76021. case DONE:
  76022. /* inflate stream terminated properly -- write leftover output */
  76023. ret = Z_STREAM_END;
  76024. if (left < state->wsize) {
  76025. if (out(out_desc, state->window, state->wsize - left))
  76026. ret = Z_BUF_ERROR;
  76027. }
  76028. goto inf_leave;
  76029. case BAD:
  76030. ret = Z_DATA_ERROR;
  76031. goto inf_leave;
  76032. default: /* can't happen, but makes compilers happy */
  76033. ret = Z_STREAM_ERROR;
  76034. goto inf_leave;
  76035. }
  76036. /* Return unused input */
  76037. inf_leave:
  76038. strm->next_in = next;
  76039. strm->avail_in = have;
  76040. return ret;
  76041. }
  76042. int ZEXPORT inflateBackEnd (z_streamp strm)
  76043. {
  76044. if (strm == Z_NULL || strm->state == Z_NULL || strm->zfree == (free_func)0)
  76045. return Z_STREAM_ERROR;
  76046. ZFREE(strm, strm->state);
  76047. strm->state = Z_NULL;
  76048. Tracev((stderr, "inflate: end\n"));
  76049. return Z_OK;
  76050. }
  76051. /********* End of inlined file: infback.c *********/
  76052. /********* Start of inlined file: inffast.c *********/
  76053. /********* Start of inlined file: inffast.h *********/
  76054. /* WARNING: this file should *not* be used by applications. It is
  76055. part of the implementation of the compression library and is
  76056. subject to change. Applications should only use zlib.h.
  76057. */
  76058. void inflate_fast OF((z_streamp strm, unsigned start));
  76059. /********* End of inlined file: inffast.h *********/
  76060. #ifndef ASMINF
  76061. /* Allow machine dependent optimization for post-increment or pre-increment.
  76062. Based on testing to date,
  76063. Pre-increment preferred for:
  76064. - PowerPC G3 (Adler)
  76065. - MIPS R5000 (Randers-Pehrson)
  76066. Post-increment preferred for:
  76067. - none
  76068. No measurable difference:
  76069. - Pentium III (Anderson)
  76070. - M68060 (Nikl)
  76071. */
  76072. #ifdef POSTINC
  76073. # define OFF 0
  76074. # define PUP(a) *(a)++
  76075. #else
  76076. # define OFF 1
  76077. # define PUP(a) *++(a)
  76078. #endif
  76079. /*
  76080. Decode literal, length, and distance codes and write out the resulting
  76081. literal and match bytes until either not enough input or output is
  76082. available, an end-of-block is encountered, or a data error is encountered.
  76083. When large enough input and output buffers are supplied to inflate(), for
  76084. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  76085. inflate execution time is spent in this routine.
  76086. Entry assumptions:
  76087. state->mode == LEN
  76088. strm->avail_in >= 6
  76089. strm->avail_out >= 258
  76090. start >= strm->avail_out
  76091. state->bits < 8
  76092. On return, state->mode is one of:
  76093. LEN -- ran out of enough output space or enough available input
  76094. TYPE -- reached end of block code, inflate() to interpret next block
  76095. BAD -- error in block data
  76096. Notes:
  76097. - The maximum input bits used by a length/distance pair is 15 bits for the
  76098. length code, 5 bits for the length extra, 15 bits for the distance code,
  76099. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  76100. Therefore if strm->avail_in >= 6, then there is enough input to avoid
  76101. checking for available input while decoding.
  76102. - The maximum bytes that a single length/distance pair can output is 258
  76103. bytes, which is the maximum length that can be coded. inflate_fast()
  76104. requires strm->avail_out >= 258 for each loop to avoid checking for
  76105. output space.
  76106. */
  76107. void inflate_fast (z_streamp strm, unsigned start)
  76108. {
  76109. struct inflate_state FAR *state;
  76110. unsigned char FAR *in; /* local strm->next_in */
  76111. unsigned char FAR *last; /* while in < last, enough input available */
  76112. unsigned char FAR *out; /* local strm->next_out */
  76113. unsigned char FAR *beg; /* inflate()'s initial strm->next_out */
  76114. unsigned char FAR *end; /* while out < end, enough space available */
  76115. #ifdef INFLATE_STRICT
  76116. unsigned dmax; /* maximum distance from zlib header */
  76117. #endif
  76118. unsigned wsize; /* window size or zero if not using window */
  76119. unsigned whave; /* valid bytes in the window */
  76120. unsigned write; /* window write index */
  76121. unsigned char FAR *window; /* allocated sliding window, if wsize != 0 */
  76122. unsigned long hold; /* local strm->hold */
  76123. unsigned bits; /* local strm->bits */
  76124. code const FAR *lcode; /* local strm->lencode */
  76125. code const FAR *dcode; /* local strm->distcode */
  76126. unsigned lmask; /* mask for first level of length codes */
  76127. unsigned dmask; /* mask for first level of distance codes */
  76128. code thisx; /* retrieved table entry */
  76129. unsigned op; /* code bits, operation, extra bits, or */
  76130. /* window position, window bytes to copy */
  76131. unsigned len; /* match length, unused bytes */
  76132. unsigned dist; /* match distance */
  76133. unsigned char FAR *from; /* where to copy match from */
  76134. /* copy state to local variables */
  76135. state = (struct inflate_state FAR *)strm->state;
  76136. in = strm->next_in - OFF;
  76137. last = in + (strm->avail_in - 5);
  76138. out = strm->next_out - OFF;
  76139. beg = out - (start - strm->avail_out);
  76140. end = out + (strm->avail_out - 257);
  76141. #ifdef INFLATE_STRICT
  76142. dmax = state->dmax;
  76143. #endif
  76144. wsize = state->wsize;
  76145. whave = state->whave;
  76146. write = state->write;
  76147. window = state->window;
  76148. hold = state->hold;
  76149. bits = state->bits;
  76150. lcode = state->lencode;
  76151. dcode = state->distcode;
  76152. lmask = (1U << state->lenbits) - 1;
  76153. dmask = (1U << state->distbits) - 1;
  76154. /* decode literals and length/distances until end-of-block or not enough
  76155. input data or output space */
  76156. do {
  76157. if (bits < 15) {
  76158. hold += (unsigned long)(PUP(in)) << bits;
  76159. bits += 8;
  76160. hold += (unsigned long)(PUP(in)) << bits;
  76161. bits += 8;
  76162. }
  76163. thisx = lcode[hold & lmask];
  76164. dolen:
  76165. op = (unsigned)(thisx.bits);
  76166. hold >>= op;
  76167. bits -= op;
  76168. op = (unsigned)(thisx.op);
  76169. if (op == 0) { /* literal */
  76170. Tracevv((stderr, thisx.val >= 0x20 && thisx.val < 0x7f ?
  76171. "inflate: literal '%c'\n" :
  76172. "inflate: literal 0x%02x\n", thisx.val));
  76173. PUP(out) = (unsigned char)(thisx.val);
  76174. }
  76175. else if (op & 16) { /* length base */
  76176. len = (unsigned)(thisx.val);
  76177. op &= 15; /* number of extra bits */
  76178. if (op) {
  76179. if (bits < op) {
  76180. hold += (unsigned long)(PUP(in)) << bits;
  76181. bits += 8;
  76182. }
  76183. len += (unsigned)hold & ((1U << op) - 1);
  76184. hold >>= op;
  76185. bits -= op;
  76186. }
  76187. Tracevv((stderr, "inflate: length %u\n", len));
  76188. if (bits < 15) {
  76189. hold += (unsigned long)(PUP(in)) << bits;
  76190. bits += 8;
  76191. hold += (unsigned long)(PUP(in)) << bits;
  76192. bits += 8;
  76193. }
  76194. thisx = dcode[hold & dmask];
  76195. dodist:
  76196. op = (unsigned)(thisx.bits);
  76197. hold >>= op;
  76198. bits -= op;
  76199. op = (unsigned)(thisx.op);
  76200. if (op & 16) { /* distance base */
  76201. dist = (unsigned)(thisx.val);
  76202. op &= 15; /* number of extra bits */
  76203. if (bits < op) {
  76204. hold += (unsigned long)(PUP(in)) << bits;
  76205. bits += 8;
  76206. if (bits < op) {
  76207. hold += (unsigned long)(PUP(in)) << bits;
  76208. bits += 8;
  76209. }
  76210. }
  76211. dist += (unsigned)hold & ((1U << op) - 1);
  76212. #ifdef INFLATE_STRICT
  76213. if (dist > dmax) {
  76214. strm->msg = (char *)"invalid distance too far back";
  76215. state->mode = BAD;
  76216. break;
  76217. }
  76218. #endif
  76219. hold >>= op;
  76220. bits -= op;
  76221. Tracevv((stderr, "inflate: distance %u\n", dist));
  76222. op = (unsigned)(out - beg); /* max distance in output */
  76223. if (dist > op) { /* see if copy from window */
  76224. op = dist - op; /* distance back in window */
  76225. if (op > whave) {
  76226. strm->msg = (char *)"invalid distance too far back";
  76227. state->mode = BAD;
  76228. break;
  76229. }
  76230. from = window - OFF;
  76231. if (write == 0) { /* very common case */
  76232. from += wsize - op;
  76233. if (op < len) { /* some from window */
  76234. len -= op;
  76235. do {
  76236. PUP(out) = PUP(from);
  76237. } while (--op);
  76238. from = out - dist; /* rest from output */
  76239. }
  76240. }
  76241. else if (write < op) { /* wrap around window */
  76242. from += wsize + write - op;
  76243. op -= write;
  76244. if (op < len) { /* some from end of window */
  76245. len -= op;
  76246. do {
  76247. PUP(out) = PUP(from);
  76248. } while (--op);
  76249. from = window - OFF;
  76250. if (write < len) { /* some from start of window */
  76251. op = write;
  76252. len -= op;
  76253. do {
  76254. PUP(out) = PUP(from);
  76255. } while (--op);
  76256. from = out - dist; /* rest from output */
  76257. }
  76258. }
  76259. }
  76260. else { /* contiguous in window */
  76261. from += write - op;
  76262. if (op < len) { /* some from window */
  76263. len -= op;
  76264. do {
  76265. PUP(out) = PUP(from);
  76266. } while (--op);
  76267. from = out - dist; /* rest from output */
  76268. }
  76269. }
  76270. while (len > 2) {
  76271. PUP(out) = PUP(from);
  76272. PUP(out) = PUP(from);
  76273. PUP(out) = PUP(from);
  76274. len -= 3;
  76275. }
  76276. if (len) {
  76277. PUP(out) = PUP(from);
  76278. if (len > 1)
  76279. PUP(out) = PUP(from);
  76280. }
  76281. }
  76282. else {
  76283. from = out - dist; /* copy direct from output */
  76284. do { /* minimum length is three */
  76285. PUP(out) = PUP(from);
  76286. PUP(out) = PUP(from);
  76287. PUP(out) = PUP(from);
  76288. len -= 3;
  76289. } while (len > 2);
  76290. if (len) {
  76291. PUP(out) = PUP(from);
  76292. if (len > 1)
  76293. PUP(out) = PUP(from);
  76294. }
  76295. }
  76296. }
  76297. else if ((op & 64) == 0) { /* 2nd level distance code */
  76298. thisx = dcode[thisx.val + (hold & ((1U << op) - 1))];
  76299. goto dodist;
  76300. }
  76301. else {
  76302. strm->msg = (char *)"invalid distance code";
  76303. state->mode = BAD;
  76304. break;
  76305. }
  76306. }
  76307. else if ((op & 64) == 0) { /* 2nd level length code */
  76308. thisx = lcode[thisx.val + (hold & ((1U << op) - 1))];
  76309. goto dolen;
  76310. }
  76311. else if (op & 32) { /* end-of-block */
  76312. Tracevv((stderr, "inflate: end of block\n"));
  76313. state->mode = TYPE;
  76314. break;
  76315. }
  76316. else {
  76317. strm->msg = (char *)"invalid literal/length code";
  76318. state->mode = BAD;
  76319. break;
  76320. }
  76321. } while (in < last && out < end);
  76322. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  76323. len = bits >> 3;
  76324. in -= len;
  76325. bits -= len << 3;
  76326. hold &= (1U << bits) - 1;
  76327. /* update state and return */
  76328. strm->next_in = in + OFF;
  76329. strm->next_out = out + OFF;
  76330. strm->avail_in = (unsigned)(in < last ? 5 + (last - in) : 5 - (in - last));
  76331. strm->avail_out = (unsigned)(out < end ?
  76332. 257 + (end - out) : 257 - (out - end));
  76333. state->hold = hold;
  76334. state->bits = bits;
  76335. return;
  76336. }
  76337. /*
  76338. inflate_fast() speedups that turned out slower (on a PowerPC G3 750CXe):
  76339. - Using bit fields for code structure
  76340. - Different op definition to avoid & for extra bits (do & for table bits)
  76341. - Three separate decoding do-loops for direct, window, and write == 0
  76342. - Special case for distance > 1 copies to do overlapped load and store copy
  76343. - Explicit branch predictions (based on measured branch probabilities)
  76344. - Deferring match copy and interspersed it with decoding subsequent codes
  76345. - Swapping literal/length else
  76346. - Swapping window/direct else
  76347. - Larger unrolled copy loops (three is about right)
  76348. - Moving len -= 3 statement into middle of loop
  76349. */
  76350. #endif /* !ASMINF */
  76351. /********* End of inlined file: inffast.c *********/
  76352. #undef PULLBYTE
  76353. #undef LOAD
  76354. #undef RESTORE
  76355. #undef INITBITS
  76356. #undef NEEDBITS
  76357. #undef DROPBITS
  76358. #undef BYTEBITS
  76359. /********* Start of inlined file: inflate.c *********/
  76360. /*
  76361. * Change history:
  76362. *
  76363. * 1.2.beta0 24 Nov 2002
  76364. * - First version -- complete rewrite of inflate to simplify code, avoid
  76365. * creation of window when not needed, minimize use of window when it is
  76366. * needed, make inffast.c even faster, implement gzip decoding, and to
  76367. * improve code readability and style over the previous zlib inflate code
  76368. *
  76369. * 1.2.beta1 25 Nov 2002
  76370. * - Use pointers for available input and output checking in inffast.c
  76371. * - Remove input and output counters in inffast.c
  76372. * - Change inffast.c entry and loop from avail_in >= 7 to >= 6
  76373. * - Remove unnecessary second byte pull from length extra in inffast.c
  76374. * - Unroll direct copy to three copies per loop in inffast.c
  76375. *
  76376. * 1.2.beta2 4 Dec 2002
  76377. * - Change external routine names to reduce potential conflicts
  76378. * - Correct filename to inffixed.h for fixed tables in inflate.c
  76379. * - Make hbuf[] unsigned char to match parameter type in inflate.c
  76380. * - Change strm->next_out[-state->offset] to *(strm->next_out - state->offset)
  76381. * to avoid negation problem on Alphas (64 bit) in inflate.c
  76382. *
  76383. * 1.2.beta3 22 Dec 2002
  76384. * - Add comments on state->bits assertion in inffast.c
  76385. * - Add comments on op field in inftrees.h
  76386. * - Fix bug in reuse of allocated window after inflateReset()
  76387. * - Remove bit fields--back to byte structure for speed
  76388. * - Remove distance extra == 0 check in inflate_fast()--only helps for lengths
  76389. * - Change post-increments to pre-increments in inflate_fast(), PPC biased?
  76390. * - Add compile time option, POSTINC, to use post-increments instead (Intel?)
  76391. * - Make MATCH copy in inflate() much faster for when inflate_fast() not used
  76392. * - Use local copies of stream next and avail values, as well as local bit
  76393. * buffer and bit count in inflate()--for speed when inflate_fast() not used
  76394. *
  76395. * 1.2.beta4 1 Jan 2003
  76396. * - Split ptr - 257 statements in inflate_table() to avoid compiler warnings
  76397. * - Move a comment on output buffer sizes from inffast.c to inflate.c
  76398. * - Add comments in inffast.c to introduce the inflate_fast() routine
  76399. * - Rearrange window copies in inflate_fast() for speed and simplification
  76400. * - Unroll last copy for window match in inflate_fast()
  76401. * - Use local copies of window variables in inflate_fast() for speed
  76402. * - Pull out common write == 0 case for speed in inflate_fast()
  76403. * - Make op and len in inflate_fast() unsigned for consistency
  76404. * - Add FAR to lcode and dcode declarations in inflate_fast()
  76405. * - Simplified bad distance check in inflate_fast()
  76406. * - Added inflateBackInit(), inflateBack(), and inflateBackEnd() in new
  76407. * source file infback.c to provide a call-back interface to inflate for
  76408. * programs like gzip and unzip -- uses window as output buffer to avoid
  76409. * window copying
  76410. *
  76411. * 1.2.beta5 1 Jan 2003
  76412. * - Improved inflateBack() interface to allow the caller to provide initial
  76413. * input in strm.
  76414. * - Fixed stored blocks bug in inflateBack()
  76415. *
  76416. * 1.2.beta6 4 Jan 2003
  76417. * - Added comments in inffast.c on effectiveness of POSTINC
  76418. * - Typecasting all around to reduce compiler warnings
  76419. * - Changed loops from while (1) or do {} while (1) to for (;;), again to
  76420. * make compilers happy
  76421. * - Changed type of window in inflateBackInit() to unsigned char *
  76422. *
  76423. * 1.2.beta7 27 Jan 2003
  76424. * - Changed many types to unsigned or unsigned short to avoid warnings
  76425. * - Added inflateCopy() function
  76426. *
  76427. * 1.2.0 9 Mar 2003
  76428. * - Changed inflateBack() interface to provide separate opaque descriptors
  76429. * for the in() and out() functions
  76430. * - Changed inflateBack() argument and in_func typedef to swap the length
  76431. * and buffer address return values for the input function
  76432. * - Check next_in and next_out for Z_NULL on entry to inflate()
  76433. *
  76434. * The history for versions after 1.2.0 are in ChangeLog in zlib distribution.
  76435. */
  76436. /********* Start of inlined file: inffast.h *********/
  76437. /* WARNING: this file should *not* be used by applications. It is
  76438. part of the implementation of the compression library and is
  76439. subject to change. Applications should only use zlib.h.
  76440. */
  76441. void inflate_fast OF((z_streamp strm, unsigned start));
  76442. /********* End of inlined file: inffast.h *********/
  76443. #ifdef MAKEFIXED
  76444. # ifndef BUILDFIXED
  76445. # define BUILDFIXED
  76446. # endif
  76447. #endif
  76448. /* function prototypes */
  76449. local void fixedtables OF((struct inflate_state FAR *state));
  76450. local int updatewindow OF((z_streamp strm, unsigned out));
  76451. #ifdef BUILDFIXED
  76452. void makefixed OF((void));
  76453. #endif
  76454. local unsigned syncsearch OF((unsigned FAR *have, unsigned char FAR *buf,
  76455. unsigned len));
  76456. int ZEXPORT inflateReset (z_streamp strm)
  76457. {
  76458. struct inflate_state FAR *state;
  76459. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  76460. state = (struct inflate_state FAR *)strm->state;
  76461. strm->total_in = strm->total_out = state->total = 0;
  76462. strm->msg = Z_NULL;
  76463. strm->adler = 1; /* to support ill-conceived Java test suite */
  76464. state->mode = HEAD;
  76465. state->last = 0;
  76466. state->havedict = 0;
  76467. state->dmax = 32768U;
  76468. state->head = Z_NULL;
  76469. state->wsize = 0;
  76470. state->whave = 0;
  76471. state->write = 0;
  76472. state->hold = 0;
  76473. state->bits = 0;
  76474. state->lencode = state->distcode = state->next = state->codes;
  76475. Tracev((stderr, "inflate: reset\n"));
  76476. return Z_OK;
  76477. }
  76478. int ZEXPORT inflatePrime (z_streamp strm, int bits, int value)
  76479. {
  76480. struct inflate_state FAR *state;
  76481. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  76482. state = (struct inflate_state FAR *)strm->state;
  76483. if (bits > 16 || state->bits + bits > 32) return Z_STREAM_ERROR;
  76484. value &= (1L << bits) - 1;
  76485. state->hold += value << state->bits;
  76486. state->bits += bits;
  76487. return Z_OK;
  76488. }
  76489. int ZEXPORT inflateInit2_(z_streamp strm, int windowBits, const char *version, int stream_size)
  76490. {
  76491. struct inflate_state FAR *state;
  76492. if (version == Z_NULL || version[0] != ZLIB_VERSION[0] ||
  76493. stream_size != (int)(sizeof(z_stream)))
  76494. return Z_VERSION_ERROR;
  76495. if (strm == Z_NULL) return Z_STREAM_ERROR;
  76496. strm->msg = Z_NULL; /* in case we return an error */
  76497. if (strm->zalloc == (alloc_func)0) {
  76498. strm->zalloc = zcalloc;
  76499. strm->opaque = (voidpf)0;
  76500. }
  76501. if (strm->zfree == (free_func)0) strm->zfree = zcfree;
  76502. state = (struct inflate_state FAR *)
  76503. ZALLOC(strm, 1, sizeof(struct inflate_state));
  76504. if (state == Z_NULL) return Z_MEM_ERROR;
  76505. Tracev((stderr, "inflate: allocated\n"));
  76506. strm->state = (struct internal_state FAR *)state;
  76507. if (windowBits < 0) {
  76508. state->wrap = 0;
  76509. windowBits = -windowBits;
  76510. }
  76511. else {
  76512. state->wrap = (windowBits >> 4) + 1;
  76513. #ifdef GUNZIP
  76514. if (windowBits < 48) windowBits &= 15;
  76515. #endif
  76516. }
  76517. if (windowBits < 8 || windowBits > 15) {
  76518. ZFREE(strm, state);
  76519. strm->state = Z_NULL;
  76520. return Z_STREAM_ERROR;
  76521. }
  76522. state->wbits = (unsigned)windowBits;
  76523. state->window = Z_NULL;
  76524. return inflateReset(strm);
  76525. }
  76526. int ZEXPORT inflateInit_ (z_streamp strm, const char *version, int stream_size)
  76527. {
  76528. return inflateInit2_(strm, DEF_WBITS, version, stream_size);
  76529. }
  76530. /*
  76531. Return state with length and distance decoding tables and index sizes set to
  76532. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  76533. If BUILDFIXED is defined, then instead this routine builds the tables the
  76534. first time it's called, and returns those tables the first time and
  76535. thereafter. This reduces the size of the code by about 2K bytes, in
  76536. exchange for a little execution time. However, BUILDFIXED should not be
  76537. used for threaded applications, since the rewriting of the tables and virgin
  76538. may not be thread-safe.
  76539. */
  76540. local void fixedtables (struct inflate_state FAR *state)
  76541. {
  76542. #ifdef BUILDFIXED
  76543. static int virgin = 1;
  76544. static code *lenfix, *distfix;
  76545. static code fixed[544];
  76546. /* build fixed huffman tables if first call (may not be thread safe) */
  76547. if (virgin) {
  76548. unsigned sym, bits;
  76549. static code *next;
  76550. /* literal/length table */
  76551. sym = 0;
  76552. while (sym < 144) state->lens[sym++] = 8;
  76553. while (sym < 256) state->lens[sym++] = 9;
  76554. while (sym < 280) state->lens[sym++] = 7;
  76555. while (sym < 288) state->lens[sym++] = 8;
  76556. next = fixed;
  76557. lenfix = next;
  76558. bits = 9;
  76559. inflate_table(LENS, state->lens, 288, &(next), &(bits), state->work);
  76560. /* distance table */
  76561. sym = 0;
  76562. while (sym < 32) state->lens[sym++] = 5;
  76563. distfix = next;
  76564. bits = 5;
  76565. inflate_table(DISTS, state->lens, 32, &(next), &(bits), state->work);
  76566. /* do this just once */
  76567. virgin = 0;
  76568. }
  76569. #else /* !BUILDFIXED */
  76570. /********* Start of inlined file: inffixed.h *********/
  76571. /* inffixed.h -- table for decoding fixed codes
  76572. * Generated automatically by makefixed().
  76573. */
  76574. /* WARNING: this file should *not* be used by applications. It
  76575. is part of the implementation of the compression library and
  76576. is subject to change. Applications should only use zlib.h.
  76577. */
  76578. static const code lenfix[512] = {
  76579. {96,7,0},{0,8,80},{0,8,16},{20,8,115},{18,7,31},{0,8,112},{0,8,48},
  76580. {0,9,192},{16,7,10},{0,8,96},{0,8,32},{0,9,160},{0,8,0},{0,8,128},
  76581. {0,8,64},{0,9,224},{16,7,6},{0,8,88},{0,8,24},{0,9,144},{19,7,59},
  76582. {0,8,120},{0,8,56},{0,9,208},{17,7,17},{0,8,104},{0,8,40},{0,9,176},
  76583. {0,8,8},{0,8,136},{0,8,72},{0,9,240},{16,7,4},{0,8,84},{0,8,20},
  76584. {21,8,227},{19,7,43},{0,8,116},{0,8,52},{0,9,200},{17,7,13},{0,8,100},
  76585. {0,8,36},{0,9,168},{0,8,4},{0,8,132},{0,8,68},{0,9,232},{16,7,8},
  76586. {0,8,92},{0,8,28},{0,9,152},{20,7,83},{0,8,124},{0,8,60},{0,9,216},
  76587. {18,7,23},{0,8,108},{0,8,44},{0,9,184},{0,8,12},{0,8,140},{0,8,76},
  76588. {0,9,248},{16,7,3},{0,8,82},{0,8,18},{21,8,163},{19,7,35},{0,8,114},
  76589. {0,8,50},{0,9,196},{17,7,11},{0,8,98},{0,8,34},{0,9,164},{0,8,2},
  76590. {0,8,130},{0,8,66},{0,9,228},{16,7,7},{0,8,90},{0,8,26},{0,9,148},
  76591. {20,7,67},{0,8,122},{0,8,58},{0,9,212},{18,7,19},{0,8,106},{0,8,42},
  76592. {0,9,180},{0,8,10},{0,8,138},{0,8,74},{0,9,244},{16,7,5},{0,8,86},
  76593. {0,8,22},{64,8,0},{19,7,51},{0,8,118},{0,8,54},{0,9,204},{17,7,15},
  76594. {0,8,102},{0,8,38},{0,9,172},{0,8,6},{0,8,134},{0,8,70},{0,9,236},
  76595. {16,7,9},{0,8,94},{0,8,30},{0,9,156},{20,7,99},{0,8,126},{0,8,62},
  76596. {0,9,220},{18,7,27},{0,8,110},{0,8,46},{0,9,188},{0,8,14},{0,8,142},
  76597. {0,8,78},{0,9,252},{96,7,0},{0,8,81},{0,8,17},{21,8,131},{18,7,31},
  76598. {0,8,113},{0,8,49},{0,9,194},{16,7,10},{0,8,97},{0,8,33},{0,9,162},
  76599. {0,8,1},{0,8,129},{0,8,65},{0,9,226},{16,7,6},{0,8,89},{0,8,25},
  76600. {0,9,146},{19,7,59},{0,8,121},{0,8,57},{0,9,210},{17,7,17},{0,8,105},
  76601. {0,8,41},{0,9,178},{0,8,9},{0,8,137},{0,8,73},{0,9,242},{16,7,4},
  76602. {0,8,85},{0,8,21},{16,8,258},{19,7,43},{0,8,117},{0,8,53},{0,9,202},
  76603. {17,7,13},{0,8,101},{0,8,37},{0,9,170},{0,8,5},{0,8,133},{0,8,69},
  76604. {0,9,234},{16,7,8},{0,8,93},{0,8,29},{0,9,154},{20,7,83},{0,8,125},
  76605. {0,8,61},{0,9,218},{18,7,23},{0,8,109},{0,8,45},{0,9,186},{0,8,13},
  76606. {0,8,141},{0,8,77},{0,9,250},{16,7,3},{0,8,83},{0,8,19},{21,8,195},
  76607. {19,7,35},{0,8,115},{0,8,51},{0,9,198},{17,7,11},{0,8,99},{0,8,35},
  76608. {0,9,166},{0,8,3},{0,8,131},{0,8,67},{0,9,230},{16,7,7},{0,8,91},
  76609. {0,8,27},{0,9,150},{20,7,67},{0,8,123},{0,8,59},{0,9,214},{18,7,19},
  76610. {0,8,107},{0,8,43},{0,9,182},{0,8,11},{0,8,139},{0,8,75},{0,9,246},
  76611. {16,7,5},{0,8,87},{0,8,23},{64,8,0},{19,7,51},{0,8,119},{0,8,55},
  76612. {0,9,206},{17,7,15},{0,8,103},{0,8,39},{0,9,174},{0,8,7},{0,8,135},
  76613. {0,8,71},{0,9,238},{16,7,9},{0,8,95},{0,8,31},{0,9,158},{20,7,99},
  76614. {0,8,127},{0,8,63},{0,9,222},{18,7,27},{0,8,111},{0,8,47},{0,9,190},
  76615. {0,8,15},{0,8,143},{0,8,79},{0,9,254},{96,7,0},{0,8,80},{0,8,16},
  76616. {20,8,115},{18,7,31},{0,8,112},{0,8,48},{0,9,193},{16,7,10},{0,8,96},
  76617. {0,8,32},{0,9,161},{0,8,0},{0,8,128},{0,8,64},{0,9,225},{16,7,6},
  76618. {0,8,88},{0,8,24},{0,9,145},{19,7,59},{0,8,120},{0,8,56},{0,9,209},
  76619. {17,7,17},{0,8,104},{0,8,40},{0,9,177},{0,8,8},{0,8,136},{0,8,72},
  76620. {0,9,241},{16,7,4},{0,8,84},{0,8,20},{21,8,227},{19,7,43},{0,8,116},
  76621. {0,8,52},{0,9,201},{17,7,13},{0,8,100},{0,8,36},{0,9,169},{0,8,4},
  76622. {0,8,132},{0,8,68},{0,9,233},{16,7,8},{0,8,92},{0,8,28},{0,9,153},
  76623. {20,7,83},{0,8,124},{0,8,60},{0,9,217},{18,7,23},{0,8,108},{0,8,44},
  76624. {0,9,185},{0,8,12},{0,8,140},{0,8,76},{0,9,249},{16,7,3},{0,8,82},
  76625. {0,8,18},{21,8,163},{19,7,35},{0,8,114},{0,8,50},{0,9,197},{17,7,11},
  76626. {0,8,98},{0,8,34},{0,9,165},{0,8,2},{0,8,130},{0,8,66},{0,9,229},
  76627. {16,7,7},{0,8,90},{0,8,26},{0,9,149},{20,7,67},{0,8,122},{0,8,58},
  76628. {0,9,213},{18,7,19},{0,8,106},{0,8,42},{0,9,181},{0,8,10},{0,8,138},
  76629. {0,8,74},{0,9,245},{16,7,5},{0,8,86},{0,8,22},{64,8,0},{19,7,51},
  76630. {0,8,118},{0,8,54},{0,9,205},{17,7,15},{0,8,102},{0,8,38},{0,9,173},
  76631. {0,8,6},{0,8,134},{0,8,70},{0,9,237},{16,7,9},{0,8,94},{0,8,30},
  76632. {0,9,157},{20,7,99},{0,8,126},{0,8,62},{0,9,221},{18,7,27},{0,8,110},
  76633. {0,8,46},{0,9,189},{0,8,14},{0,8,142},{0,8,78},{0,9,253},{96,7,0},
  76634. {0,8,81},{0,8,17},{21,8,131},{18,7,31},{0,8,113},{0,8,49},{0,9,195},
  76635. {16,7,10},{0,8,97},{0,8,33},{0,9,163},{0,8,1},{0,8,129},{0,8,65},
  76636. {0,9,227},{16,7,6},{0,8,89},{0,8,25},{0,9,147},{19,7,59},{0,8,121},
  76637. {0,8,57},{0,9,211},{17,7,17},{0,8,105},{0,8,41},{0,9,179},{0,8,9},
  76638. {0,8,137},{0,8,73},{0,9,243},{16,7,4},{0,8,85},{0,8,21},{16,8,258},
  76639. {19,7,43},{0,8,117},{0,8,53},{0,9,203},{17,7,13},{0,8,101},{0,8,37},
  76640. {0,9,171},{0,8,5},{0,8,133},{0,8,69},{0,9,235},{16,7,8},{0,8,93},
  76641. {0,8,29},{0,9,155},{20,7,83},{0,8,125},{0,8,61},{0,9,219},{18,7,23},
  76642. {0,8,109},{0,8,45},{0,9,187},{0,8,13},{0,8,141},{0,8,77},{0,9,251},
  76643. {16,7,3},{0,8,83},{0,8,19},{21,8,195},{19,7,35},{0,8,115},{0,8,51},
  76644. {0,9,199},{17,7,11},{0,8,99},{0,8,35},{0,9,167},{0,8,3},{0,8,131},
  76645. {0,8,67},{0,9,231},{16,7,7},{0,8,91},{0,8,27},{0,9,151},{20,7,67},
  76646. {0,8,123},{0,8,59},{0,9,215},{18,7,19},{0,8,107},{0,8,43},{0,9,183},
  76647. {0,8,11},{0,8,139},{0,8,75},{0,9,247},{16,7,5},{0,8,87},{0,8,23},
  76648. {64,8,0},{19,7,51},{0,8,119},{0,8,55},{0,9,207},{17,7,15},{0,8,103},
  76649. {0,8,39},{0,9,175},{0,8,7},{0,8,135},{0,8,71},{0,9,239},{16,7,9},
  76650. {0,8,95},{0,8,31},{0,9,159},{20,7,99},{0,8,127},{0,8,63},{0,9,223},
  76651. {18,7,27},{0,8,111},{0,8,47},{0,9,191},{0,8,15},{0,8,143},{0,8,79},
  76652. {0,9,255}
  76653. };
  76654. static const code distfix[32] = {
  76655. {16,5,1},{23,5,257},{19,5,17},{27,5,4097},{17,5,5},{25,5,1025},
  76656. {21,5,65},{29,5,16385},{16,5,3},{24,5,513},{20,5,33},{28,5,8193},
  76657. {18,5,9},{26,5,2049},{22,5,129},{64,5,0},{16,5,2},{23,5,385},
  76658. {19,5,25},{27,5,6145},{17,5,7},{25,5,1537},{21,5,97},{29,5,24577},
  76659. {16,5,4},{24,5,769},{20,5,49},{28,5,12289},{18,5,13},{26,5,3073},
  76660. {22,5,193},{64,5,0}
  76661. };
  76662. /********* End of inlined file: inffixed.h *********/
  76663. #endif /* BUILDFIXED */
  76664. state->lencode = lenfix;
  76665. state->lenbits = 9;
  76666. state->distcode = distfix;
  76667. state->distbits = 5;
  76668. }
  76669. #ifdef MAKEFIXED
  76670. #include <stdio.h>
  76671. /*
  76672. Write out the inffixed.h that is #include'd above. Defining MAKEFIXED also
  76673. defines BUILDFIXED, so the tables are built on the fly. makefixed() writes
  76674. those tables to stdout, which would be piped to inffixed.h. A small program
  76675. can simply call makefixed to do this:
  76676. void makefixed(void);
  76677. int main(void)
  76678. {
  76679. makefixed();
  76680. return 0;
  76681. }
  76682. Then that can be linked with zlib built with MAKEFIXED defined and run:
  76683. a.out > inffixed.h
  76684. */
  76685. void makefixed()
  76686. {
  76687. unsigned low, size;
  76688. struct inflate_state state;
  76689. fixedtables(&state);
  76690. puts(" /* inffixed.h -- table for decoding fixed codes");
  76691. puts(" * Generated automatically by makefixed().");
  76692. puts(" */");
  76693. puts("");
  76694. puts(" /* WARNING: this file should *not* be used by applications.");
  76695. puts(" It is part of the implementation of this library and is");
  76696. puts(" subject to change. Applications should only use zlib.h.");
  76697. puts(" */");
  76698. puts("");
  76699. size = 1U << 9;
  76700. printf(" static const code lenfix[%u] = {", size);
  76701. low = 0;
  76702. for (;;) {
  76703. if ((low % 7) == 0) printf("\n ");
  76704. printf("{%u,%u,%d}", state.lencode[low].op, state.lencode[low].bits,
  76705. state.lencode[low].val);
  76706. if (++low == size) break;
  76707. putchar(',');
  76708. }
  76709. puts("\n };");
  76710. size = 1U << 5;
  76711. printf("\n static const code distfix[%u] = {", size);
  76712. low = 0;
  76713. for (;;) {
  76714. if ((low % 6) == 0) printf("\n ");
  76715. printf("{%u,%u,%d}", state.distcode[low].op, state.distcode[low].bits,
  76716. state.distcode[low].val);
  76717. if (++low == size) break;
  76718. putchar(',');
  76719. }
  76720. puts("\n };");
  76721. }
  76722. #endif /* MAKEFIXED */
  76723. /*
  76724. Update the window with the last wsize (normally 32K) bytes written before
  76725. returning. If window does not exist yet, create it. This is only called
  76726. when a window is already in use, or when output has been written during this
  76727. inflate call, but the end of the deflate stream has not been reached yet.
  76728. It is also called to create a window for dictionary data when a dictionary
  76729. is loaded.
  76730. Providing output buffers larger than 32K to inflate() should provide a speed
  76731. advantage, since only the last 32K of output is copied to the sliding window
  76732. upon return from inflate(), and since all distances after the first 32K of
  76733. output will fall in the output data, making match copies simpler and faster.
  76734. The advantage may be dependent on the size of the processor's data caches.
  76735. */
  76736. local int updatewindow (z_streamp strm, unsigned out)
  76737. {
  76738. struct inflate_state FAR *state;
  76739. unsigned copy, dist;
  76740. state = (struct inflate_state FAR *)strm->state;
  76741. /* if it hasn't been done already, allocate space for the window */
  76742. if (state->window == Z_NULL) {
  76743. state->window = (unsigned char FAR *)
  76744. ZALLOC(strm, 1U << state->wbits,
  76745. sizeof(unsigned char));
  76746. if (state->window == Z_NULL) return 1;
  76747. }
  76748. /* if window not in use yet, initialize */
  76749. if (state->wsize == 0) {
  76750. state->wsize = 1U << state->wbits;
  76751. state->write = 0;
  76752. state->whave = 0;
  76753. }
  76754. /* copy state->wsize or less output bytes into the circular window */
  76755. copy = out - strm->avail_out;
  76756. if (copy >= state->wsize) {
  76757. zmemcpy(state->window, strm->next_out - state->wsize, state->wsize);
  76758. state->write = 0;
  76759. state->whave = state->wsize;
  76760. }
  76761. else {
  76762. dist = state->wsize - state->write;
  76763. if (dist > copy) dist = copy;
  76764. zmemcpy(state->window + state->write, strm->next_out - copy, dist);
  76765. copy -= dist;
  76766. if (copy) {
  76767. zmemcpy(state->window, strm->next_out - copy, copy);
  76768. state->write = copy;
  76769. state->whave = state->wsize;
  76770. }
  76771. else {
  76772. state->write += dist;
  76773. if (state->write == state->wsize) state->write = 0;
  76774. if (state->whave < state->wsize) state->whave += dist;
  76775. }
  76776. }
  76777. return 0;
  76778. }
  76779. /* Macros for inflate(): */
  76780. /* check function to use adler32() for zlib or crc32() for gzip */
  76781. #ifdef GUNZIP
  76782. # define UPDATE(check, buf, len) \
  76783. (state->flags ? crc32(check, buf, len) : adler32(check, buf, len))
  76784. #else
  76785. # define UPDATE(check, buf, len) adler32(check, buf, len)
  76786. #endif
  76787. /* check macros for header crc */
  76788. #ifdef GUNZIP
  76789. # define CRC2(check, word) \
  76790. do { \
  76791. hbuf[0] = (unsigned char)(word); \
  76792. hbuf[1] = (unsigned char)((word) >> 8); \
  76793. check = crc32(check, hbuf, 2); \
  76794. } while (0)
  76795. # define CRC4(check, word) \
  76796. do { \
  76797. hbuf[0] = (unsigned char)(word); \
  76798. hbuf[1] = (unsigned char)((word) >> 8); \
  76799. hbuf[2] = (unsigned char)((word) >> 16); \
  76800. hbuf[3] = (unsigned char)((word) >> 24); \
  76801. check = crc32(check, hbuf, 4); \
  76802. } while (0)
  76803. #endif
  76804. /* Load registers with state in inflate() for speed */
  76805. #define LOAD() \
  76806. do { \
  76807. put = strm->next_out; \
  76808. left = strm->avail_out; \
  76809. next = strm->next_in; \
  76810. have = strm->avail_in; \
  76811. hold = state->hold; \
  76812. bits = state->bits; \
  76813. } while (0)
  76814. /* Restore state from registers in inflate() */
  76815. #define RESTORE() \
  76816. do { \
  76817. strm->next_out = put; \
  76818. strm->avail_out = left; \
  76819. strm->next_in = next; \
  76820. strm->avail_in = have; \
  76821. state->hold = hold; \
  76822. state->bits = bits; \
  76823. } while (0)
  76824. /* Clear the input bit accumulator */
  76825. #define INITBITS() \
  76826. do { \
  76827. hold = 0; \
  76828. bits = 0; \
  76829. } while (0)
  76830. /* Get a byte of input into the bit accumulator, or return from inflate()
  76831. if there is no input available. */
  76832. #define PULLBYTE() \
  76833. do { \
  76834. if (have == 0) goto inf_leave; \
  76835. have--; \
  76836. hold += (unsigned long)(*next++) << bits; \
  76837. bits += 8; \
  76838. } while (0)
  76839. /* Assure that there are at least n bits in the bit accumulator. If there is
  76840. not enough available input to do that, then return from inflate(). */
  76841. #define NEEDBITS(n) \
  76842. do { \
  76843. while (bits < (unsigned)(n)) \
  76844. PULLBYTE(); \
  76845. } while (0)
  76846. /* Return the low n bits of the bit accumulator (n < 16) */
  76847. #define BITS(n) \
  76848. ((unsigned)hold & ((1U << (n)) - 1))
  76849. /* Remove n bits from the bit accumulator */
  76850. #define DROPBITS(n) \
  76851. do { \
  76852. hold >>= (n); \
  76853. bits -= (unsigned)(n); \
  76854. } while (0)
  76855. /* Remove zero to seven bits as needed to go to a byte boundary */
  76856. #define BYTEBITS() \
  76857. do { \
  76858. hold >>= bits & 7; \
  76859. bits -= bits & 7; \
  76860. } while (0)
  76861. /* Reverse the bytes in a 32-bit value */
  76862. #define REVERSE(q) \
  76863. ((((q) >> 24) & 0xff) + (((q) >> 8) & 0xff00) + \
  76864. (((q) & 0xff00) << 8) + (((q) & 0xff) << 24))
  76865. /*
  76866. inflate() uses a state machine to process as much input data and generate as
  76867. much output data as possible before returning. The state machine is
  76868. structured roughly as follows:
  76869. for (;;) switch (state) {
  76870. ...
  76871. case STATEn:
  76872. if (not enough input data or output space to make progress)
  76873. return;
  76874. ... make progress ...
  76875. state = STATEm;
  76876. break;
  76877. ...
  76878. }
  76879. so when inflate() is called again, the same case is attempted again, and
  76880. if the appropriate resources are provided, the machine proceeds to the
  76881. next state. The NEEDBITS() macro is usually the way the state evaluates
  76882. whether it can proceed or should return. NEEDBITS() does the return if
  76883. the requested bits are not available. The typical use of the BITS macros
  76884. is:
  76885. NEEDBITS(n);
  76886. ... do something with BITS(n) ...
  76887. DROPBITS(n);
  76888. where NEEDBITS(n) either returns from inflate() if there isn't enough
  76889. input left to load n bits into the accumulator, or it continues. BITS(n)
  76890. gives the low n bits in the accumulator. When done, DROPBITS(n) drops
  76891. the low n bits off the accumulator. INITBITS() clears the accumulator
  76892. and sets the number of available bits to zero. BYTEBITS() discards just
  76893. enough bits to put the accumulator on a byte boundary. After BYTEBITS()
  76894. and a NEEDBITS(8), then BITS(8) would return the next byte in the stream.
  76895. NEEDBITS(n) uses PULLBYTE() to get an available byte of input, or to return
  76896. if there is no input available. The decoding of variable length codes uses
  76897. PULLBYTE() directly in order to pull just enough bytes to decode the next
  76898. code, and no more.
  76899. Some states loop until they get enough input, making sure that enough
  76900. state information is maintained to continue the loop where it left off
  76901. if NEEDBITS() returns in the loop. For example, want, need, and keep
  76902. would all have to actually be part of the saved state in case NEEDBITS()
  76903. returns:
  76904. case STATEw:
  76905. while (want < need) {
  76906. NEEDBITS(n);
  76907. keep[want++] = BITS(n);
  76908. DROPBITS(n);
  76909. }
  76910. state = STATEx;
  76911. case STATEx:
  76912. As shown above, if the next state is also the next case, then the break
  76913. is omitted.
  76914. A state may also return if there is not enough output space available to
  76915. complete that state. Those states are copying stored data, writing a
  76916. literal byte, and copying a matching string.
  76917. When returning, a "goto inf_leave" is used to update the total counters,
  76918. update the check value, and determine whether any progress has been made
  76919. during that inflate() call in order to return the proper return code.
  76920. Progress is defined as a change in either strm->avail_in or strm->avail_out.
  76921. When there is a window, goto inf_leave will update the window with the last
  76922. output written. If a goto inf_leave occurs in the middle of decompression
  76923. and there is no window currently, goto inf_leave will create one and copy
  76924. output to the window for the next call of inflate().
  76925. In this implementation, the flush parameter of inflate() only affects the
  76926. return code (per zlib.h). inflate() always writes as much as possible to
  76927. strm->next_out, given the space available and the provided input--the effect
  76928. documented in zlib.h of Z_SYNC_FLUSH. Furthermore, inflate() always defers
  76929. the allocation of and copying into a sliding window until necessary, which
  76930. provides the effect documented in zlib.h for Z_FINISH when the entire input
  76931. stream available. So the only thing the flush parameter actually does is:
  76932. when flush is set to Z_FINISH, inflate() cannot return Z_OK. Instead it
  76933. will return Z_BUF_ERROR if it has not reached the end of the stream.
  76934. */
  76935. int ZEXPORT inflate (z_streamp strm, int flush)
  76936. {
  76937. struct inflate_state FAR *state;
  76938. unsigned char FAR *next; /* next input */
  76939. unsigned char FAR *put; /* next output */
  76940. unsigned have, left; /* available input and output */
  76941. unsigned long hold; /* bit buffer */
  76942. unsigned bits; /* bits in bit buffer */
  76943. unsigned in, out; /* save starting available input and output */
  76944. unsigned copy; /* number of stored or match bytes to copy */
  76945. unsigned char FAR *from; /* where to copy match bytes from */
  76946. code thisx; /* current decoding table entry */
  76947. code last; /* parent table entry */
  76948. unsigned len; /* length to copy for repeats, bits to drop */
  76949. int ret; /* return code */
  76950. #ifdef GUNZIP
  76951. unsigned char hbuf[4]; /* buffer for gzip header crc calculation */
  76952. #endif
  76953. static const unsigned short order[19] = /* permutation of code lengths */
  76954. {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
  76955. if (strm == Z_NULL || strm->state == Z_NULL || strm->next_out == Z_NULL ||
  76956. (strm->next_in == Z_NULL && strm->avail_in != 0))
  76957. return Z_STREAM_ERROR;
  76958. state = (struct inflate_state FAR *)strm->state;
  76959. if (state->mode == TYPE) state->mode = TYPEDO; /* skip check */
  76960. LOAD();
  76961. in = have;
  76962. out = left;
  76963. ret = Z_OK;
  76964. for (;;)
  76965. switch (state->mode) {
  76966. case HEAD:
  76967. if (state->wrap == 0) {
  76968. state->mode = TYPEDO;
  76969. break;
  76970. }
  76971. NEEDBITS(16);
  76972. #ifdef GUNZIP
  76973. if ((state->wrap & 2) && hold == 0x8b1f) { /* gzip header */
  76974. state->check = crc32(0L, Z_NULL, 0);
  76975. CRC2(state->check, hold);
  76976. INITBITS();
  76977. state->mode = FLAGS;
  76978. break;
  76979. }
  76980. state->flags = 0; /* expect zlib header */
  76981. if (state->head != Z_NULL)
  76982. state->head->done = -1;
  76983. if (!(state->wrap & 1) || /* check if zlib header allowed */
  76984. #else
  76985. if (
  76986. #endif
  76987. ((BITS(8) << 8) + (hold >> 8)) % 31) {
  76988. strm->msg = (char *)"incorrect header check";
  76989. state->mode = BAD;
  76990. break;
  76991. }
  76992. if (BITS(4) != Z_DEFLATED) {
  76993. strm->msg = (char *)"unknown compression method";
  76994. state->mode = BAD;
  76995. break;
  76996. }
  76997. DROPBITS(4);
  76998. len = BITS(4) + 8;
  76999. if (len > state->wbits) {
  77000. strm->msg = (char *)"invalid window size";
  77001. state->mode = BAD;
  77002. break;
  77003. }
  77004. state->dmax = 1U << len;
  77005. Tracev((stderr, "inflate: zlib header ok\n"));
  77006. strm->adler = state->check = adler32(0L, Z_NULL, 0);
  77007. state->mode = hold & 0x200 ? DICTID : TYPE;
  77008. INITBITS();
  77009. break;
  77010. #ifdef GUNZIP
  77011. case FLAGS:
  77012. NEEDBITS(16);
  77013. state->flags = (int)(hold);
  77014. if ((state->flags & 0xff) != Z_DEFLATED) {
  77015. strm->msg = (char *)"unknown compression method";
  77016. state->mode = BAD;
  77017. break;
  77018. }
  77019. if (state->flags & 0xe000) {
  77020. strm->msg = (char *)"unknown header flags set";
  77021. state->mode = BAD;
  77022. break;
  77023. }
  77024. if (state->head != Z_NULL)
  77025. state->head->text = (int)((hold >> 8) & 1);
  77026. if (state->flags & 0x0200) CRC2(state->check, hold);
  77027. INITBITS();
  77028. state->mode = TIME;
  77029. case TIME:
  77030. NEEDBITS(32);
  77031. if (state->head != Z_NULL)
  77032. state->head->time = hold;
  77033. if (state->flags & 0x0200) CRC4(state->check, hold);
  77034. INITBITS();
  77035. state->mode = OS;
  77036. case OS:
  77037. NEEDBITS(16);
  77038. if (state->head != Z_NULL) {
  77039. state->head->xflags = (int)(hold & 0xff);
  77040. state->head->os = (int)(hold >> 8);
  77041. }
  77042. if (state->flags & 0x0200) CRC2(state->check, hold);
  77043. INITBITS();
  77044. state->mode = EXLEN;
  77045. case EXLEN:
  77046. if (state->flags & 0x0400) {
  77047. NEEDBITS(16);
  77048. state->length = (unsigned)(hold);
  77049. if (state->head != Z_NULL)
  77050. state->head->extra_len = (unsigned)hold;
  77051. if (state->flags & 0x0200) CRC2(state->check, hold);
  77052. INITBITS();
  77053. }
  77054. else if (state->head != Z_NULL)
  77055. state->head->extra = Z_NULL;
  77056. state->mode = EXTRA;
  77057. case EXTRA:
  77058. if (state->flags & 0x0400) {
  77059. copy = state->length;
  77060. if (copy > have) copy = have;
  77061. if (copy) {
  77062. if (state->head != Z_NULL &&
  77063. state->head->extra != Z_NULL) {
  77064. len = state->head->extra_len - state->length;
  77065. zmemcpy(state->head->extra + len, next,
  77066. len + copy > state->head->extra_max ?
  77067. state->head->extra_max - len : copy);
  77068. }
  77069. if (state->flags & 0x0200)
  77070. state->check = crc32(state->check, next, copy);
  77071. have -= copy;
  77072. next += copy;
  77073. state->length -= copy;
  77074. }
  77075. if (state->length) goto inf_leave;
  77076. }
  77077. state->length = 0;
  77078. state->mode = NAME;
  77079. case NAME:
  77080. if (state->flags & 0x0800) {
  77081. if (have == 0) goto inf_leave;
  77082. copy = 0;
  77083. do {
  77084. len = (unsigned)(next[copy++]);
  77085. if (state->head != Z_NULL &&
  77086. state->head->name != Z_NULL &&
  77087. state->length < state->head->name_max)
  77088. state->head->name[state->length++] = len;
  77089. } while (len && copy < have);
  77090. if (state->flags & 0x0200)
  77091. state->check = crc32(state->check, next, copy);
  77092. have -= copy;
  77093. next += copy;
  77094. if (len) goto inf_leave;
  77095. }
  77096. else if (state->head != Z_NULL)
  77097. state->head->name = Z_NULL;
  77098. state->length = 0;
  77099. state->mode = COMMENT;
  77100. case COMMENT:
  77101. if (state->flags & 0x1000) {
  77102. if (have == 0) goto inf_leave;
  77103. copy = 0;
  77104. do {
  77105. len = (unsigned)(next[copy++]);
  77106. if (state->head != Z_NULL &&
  77107. state->head->comment != Z_NULL &&
  77108. state->length < state->head->comm_max)
  77109. state->head->comment[state->length++] = len;
  77110. } while (len && copy < have);
  77111. if (state->flags & 0x0200)
  77112. state->check = crc32(state->check, next, copy);
  77113. have -= copy;
  77114. next += copy;
  77115. if (len) goto inf_leave;
  77116. }
  77117. else if (state->head != Z_NULL)
  77118. state->head->comment = Z_NULL;
  77119. state->mode = HCRC;
  77120. case HCRC:
  77121. if (state->flags & 0x0200) {
  77122. NEEDBITS(16);
  77123. if (hold != (state->check & 0xffff)) {
  77124. strm->msg = (char *)"header crc mismatch";
  77125. state->mode = BAD;
  77126. break;
  77127. }
  77128. INITBITS();
  77129. }
  77130. if (state->head != Z_NULL) {
  77131. state->head->hcrc = (int)((state->flags >> 9) & 1);
  77132. state->head->done = 1;
  77133. }
  77134. strm->adler = state->check = crc32(0L, Z_NULL, 0);
  77135. state->mode = TYPE;
  77136. break;
  77137. #endif
  77138. case DICTID:
  77139. NEEDBITS(32);
  77140. strm->adler = state->check = REVERSE(hold);
  77141. INITBITS();
  77142. state->mode = DICT;
  77143. case DICT:
  77144. if (state->havedict == 0) {
  77145. RESTORE();
  77146. return Z_NEED_DICT;
  77147. }
  77148. strm->adler = state->check = adler32(0L, Z_NULL, 0);
  77149. state->mode = TYPE;
  77150. case TYPE:
  77151. if (flush == Z_BLOCK) goto inf_leave;
  77152. case TYPEDO:
  77153. if (state->last) {
  77154. BYTEBITS();
  77155. state->mode = CHECK;
  77156. break;
  77157. }
  77158. NEEDBITS(3);
  77159. state->last = BITS(1);
  77160. DROPBITS(1);
  77161. switch (BITS(2)) {
  77162. case 0: /* stored block */
  77163. Tracev((stderr, "inflate: stored block%s\n",
  77164. state->last ? " (last)" : ""));
  77165. state->mode = STORED;
  77166. break;
  77167. case 1: /* fixed block */
  77168. fixedtables(state);
  77169. Tracev((stderr, "inflate: fixed codes block%s\n",
  77170. state->last ? " (last)" : ""));
  77171. state->mode = LEN; /* decode codes */
  77172. break;
  77173. case 2: /* dynamic block */
  77174. Tracev((stderr, "inflate: dynamic codes block%s\n",
  77175. state->last ? " (last)" : ""));
  77176. state->mode = TABLE;
  77177. break;
  77178. case 3:
  77179. strm->msg = (char *)"invalid block type";
  77180. state->mode = BAD;
  77181. }
  77182. DROPBITS(2);
  77183. break;
  77184. case STORED:
  77185. BYTEBITS(); /* go to byte boundary */
  77186. NEEDBITS(32);
  77187. if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) {
  77188. strm->msg = (char *)"invalid stored block lengths";
  77189. state->mode = BAD;
  77190. break;
  77191. }
  77192. state->length = (unsigned)hold & 0xffff;
  77193. Tracev((stderr, "inflate: stored length %u\n",
  77194. state->length));
  77195. INITBITS();
  77196. state->mode = COPY;
  77197. case COPY:
  77198. copy = state->length;
  77199. if (copy) {
  77200. if (copy > have) copy = have;
  77201. if (copy > left) copy = left;
  77202. if (copy == 0) goto inf_leave;
  77203. zmemcpy(put, next, copy);
  77204. have -= copy;
  77205. next += copy;
  77206. left -= copy;
  77207. put += copy;
  77208. state->length -= copy;
  77209. break;
  77210. }
  77211. Tracev((stderr, "inflate: stored end\n"));
  77212. state->mode = TYPE;
  77213. break;
  77214. case TABLE:
  77215. NEEDBITS(14);
  77216. state->nlen = BITS(5) + 257;
  77217. DROPBITS(5);
  77218. state->ndist = BITS(5) + 1;
  77219. DROPBITS(5);
  77220. state->ncode = BITS(4) + 4;
  77221. DROPBITS(4);
  77222. #ifndef PKZIP_BUG_WORKAROUND
  77223. if (state->nlen > 286 || state->ndist > 30) {
  77224. strm->msg = (char *)"too many length or distance symbols";
  77225. state->mode = BAD;
  77226. break;
  77227. }
  77228. #endif
  77229. Tracev((stderr, "inflate: table sizes ok\n"));
  77230. state->have = 0;
  77231. state->mode = LENLENS;
  77232. case LENLENS:
  77233. while (state->have < state->ncode) {
  77234. NEEDBITS(3);
  77235. state->lens[order[state->have++]] = (unsigned short)BITS(3);
  77236. DROPBITS(3);
  77237. }
  77238. while (state->have < 19)
  77239. state->lens[order[state->have++]] = 0;
  77240. state->next = state->codes;
  77241. state->lencode = (code const FAR *)(state->next);
  77242. state->lenbits = 7;
  77243. ret = inflate_table(CODES, state->lens, 19, &(state->next),
  77244. &(state->lenbits), state->work);
  77245. if (ret) {
  77246. strm->msg = (char *)"invalid code lengths set";
  77247. state->mode = BAD;
  77248. break;
  77249. }
  77250. Tracev((stderr, "inflate: code lengths ok\n"));
  77251. state->have = 0;
  77252. state->mode = CODELENS;
  77253. case CODELENS:
  77254. while (state->have < state->nlen + state->ndist) {
  77255. for (;;) {
  77256. thisx = state->lencode[BITS(state->lenbits)];
  77257. if ((unsigned)(thisx.bits) <= bits) break;
  77258. PULLBYTE();
  77259. }
  77260. if (thisx.val < 16) {
  77261. NEEDBITS(thisx.bits);
  77262. DROPBITS(thisx.bits);
  77263. state->lens[state->have++] = thisx.val;
  77264. }
  77265. else {
  77266. if (thisx.val == 16) {
  77267. NEEDBITS(thisx.bits + 2);
  77268. DROPBITS(thisx.bits);
  77269. if (state->have == 0) {
  77270. strm->msg = (char *)"invalid bit length repeat";
  77271. state->mode = BAD;
  77272. break;
  77273. }
  77274. len = state->lens[state->have - 1];
  77275. copy = 3 + BITS(2);
  77276. DROPBITS(2);
  77277. }
  77278. else if (thisx.val == 17) {
  77279. NEEDBITS(thisx.bits + 3);
  77280. DROPBITS(thisx.bits);
  77281. len = 0;
  77282. copy = 3 + BITS(3);
  77283. DROPBITS(3);
  77284. }
  77285. else {
  77286. NEEDBITS(thisx.bits + 7);
  77287. DROPBITS(thisx.bits);
  77288. len = 0;
  77289. copy = 11 + BITS(7);
  77290. DROPBITS(7);
  77291. }
  77292. if (state->have + copy > state->nlen + state->ndist) {
  77293. strm->msg = (char *)"invalid bit length repeat";
  77294. state->mode = BAD;
  77295. break;
  77296. }
  77297. while (copy--)
  77298. state->lens[state->have++] = (unsigned short)len;
  77299. }
  77300. }
  77301. /* handle error breaks in while */
  77302. if (state->mode == BAD) break;
  77303. /* build code tables */
  77304. state->next = state->codes;
  77305. state->lencode = (code const FAR *)(state->next);
  77306. state->lenbits = 9;
  77307. ret = inflate_table(LENS, state->lens, state->nlen, &(state->next),
  77308. &(state->lenbits), state->work);
  77309. if (ret) {
  77310. strm->msg = (char *)"invalid literal/lengths set";
  77311. state->mode = BAD;
  77312. break;
  77313. }
  77314. state->distcode = (code const FAR *)(state->next);
  77315. state->distbits = 6;
  77316. ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist,
  77317. &(state->next), &(state->distbits), state->work);
  77318. if (ret) {
  77319. strm->msg = (char *)"invalid distances set";
  77320. state->mode = BAD;
  77321. break;
  77322. }
  77323. Tracev((stderr, "inflate: codes ok\n"));
  77324. state->mode = LEN;
  77325. case LEN:
  77326. if (have >= 6 && left >= 258) {
  77327. RESTORE();
  77328. inflate_fast(strm, out);
  77329. LOAD();
  77330. break;
  77331. }
  77332. for (;;) {
  77333. thisx = state->lencode[BITS(state->lenbits)];
  77334. if ((unsigned)(thisx.bits) <= bits) break;
  77335. PULLBYTE();
  77336. }
  77337. if (thisx.op && (thisx.op & 0xf0) == 0) {
  77338. last = thisx;
  77339. for (;;) {
  77340. thisx = state->lencode[last.val +
  77341. (BITS(last.bits + last.op) >> last.bits)];
  77342. if ((unsigned)(last.bits + thisx.bits) <= bits) break;
  77343. PULLBYTE();
  77344. }
  77345. DROPBITS(last.bits);
  77346. }
  77347. DROPBITS(thisx.bits);
  77348. state->length = (unsigned)thisx.val;
  77349. if ((int)(thisx.op) == 0) {
  77350. Tracevv((stderr, thisx.val >= 0x20 && thisx.val < 0x7f ?
  77351. "inflate: literal '%c'\n" :
  77352. "inflate: literal 0x%02x\n", thisx.val));
  77353. state->mode = LIT;
  77354. break;
  77355. }
  77356. if (thisx.op & 32) {
  77357. Tracevv((stderr, "inflate: end of block\n"));
  77358. state->mode = TYPE;
  77359. break;
  77360. }
  77361. if (thisx.op & 64) {
  77362. strm->msg = (char *)"invalid literal/length code";
  77363. state->mode = BAD;
  77364. break;
  77365. }
  77366. state->extra = (unsigned)(thisx.op) & 15;
  77367. state->mode = LENEXT;
  77368. case LENEXT:
  77369. if (state->extra) {
  77370. NEEDBITS(state->extra);
  77371. state->length += BITS(state->extra);
  77372. DROPBITS(state->extra);
  77373. }
  77374. Tracevv((stderr, "inflate: length %u\n", state->length));
  77375. state->mode = DIST;
  77376. case DIST:
  77377. for (;;) {
  77378. thisx = state->distcode[BITS(state->distbits)];
  77379. if ((unsigned)(thisx.bits) <= bits) break;
  77380. PULLBYTE();
  77381. }
  77382. if ((thisx.op & 0xf0) == 0) {
  77383. last = thisx;
  77384. for (;;) {
  77385. thisx = state->distcode[last.val +
  77386. (BITS(last.bits + last.op) >> last.bits)];
  77387. if ((unsigned)(last.bits + thisx.bits) <= bits) break;
  77388. PULLBYTE();
  77389. }
  77390. DROPBITS(last.bits);
  77391. }
  77392. DROPBITS(thisx.bits);
  77393. if (thisx.op & 64) {
  77394. strm->msg = (char *)"invalid distance code";
  77395. state->mode = BAD;
  77396. break;
  77397. }
  77398. state->offset = (unsigned)thisx.val;
  77399. state->extra = (unsigned)(thisx.op) & 15;
  77400. state->mode = DISTEXT;
  77401. case DISTEXT:
  77402. if (state->extra) {
  77403. NEEDBITS(state->extra);
  77404. state->offset += BITS(state->extra);
  77405. DROPBITS(state->extra);
  77406. }
  77407. #ifdef INFLATE_STRICT
  77408. if (state->offset > state->dmax) {
  77409. strm->msg = (char *)"invalid distance too far back";
  77410. state->mode = BAD;
  77411. break;
  77412. }
  77413. #endif
  77414. if (state->offset > state->whave + out - left) {
  77415. strm->msg = (char *)"invalid distance too far back";
  77416. state->mode = BAD;
  77417. break;
  77418. }
  77419. Tracevv((stderr, "inflate: distance %u\n", state->offset));
  77420. state->mode = MATCH;
  77421. case MATCH:
  77422. if (left == 0) goto inf_leave;
  77423. copy = out - left;
  77424. if (state->offset > copy) { /* copy from window */
  77425. copy = state->offset - copy;
  77426. if (copy > state->write) {
  77427. copy -= state->write;
  77428. from = state->window + (state->wsize - copy);
  77429. }
  77430. else
  77431. from = state->window + (state->write - copy);
  77432. if (copy > state->length) copy = state->length;
  77433. }
  77434. else { /* copy from output */
  77435. from = put - state->offset;
  77436. copy = state->length;
  77437. }
  77438. if (copy > left) copy = left;
  77439. left -= copy;
  77440. state->length -= copy;
  77441. do {
  77442. *put++ = *from++;
  77443. } while (--copy);
  77444. if (state->length == 0) state->mode = LEN;
  77445. break;
  77446. case LIT:
  77447. if (left == 0) goto inf_leave;
  77448. *put++ = (unsigned char)(state->length);
  77449. left--;
  77450. state->mode = LEN;
  77451. break;
  77452. case CHECK:
  77453. if (state->wrap) {
  77454. NEEDBITS(32);
  77455. out -= left;
  77456. strm->total_out += out;
  77457. state->total += out;
  77458. if (out)
  77459. strm->adler = state->check =
  77460. UPDATE(state->check, put - out, out);
  77461. out = left;
  77462. if ((
  77463. #ifdef GUNZIP
  77464. state->flags ? hold :
  77465. #endif
  77466. REVERSE(hold)) != state->check) {
  77467. strm->msg = (char *)"incorrect data check";
  77468. state->mode = BAD;
  77469. break;
  77470. }
  77471. INITBITS();
  77472. Tracev((stderr, "inflate: check matches trailer\n"));
  77473. }
  77474. #ifdef GUNZIP
  77475. state->mode = LENGTH;
  77476. case LENGTH:
  77477. if (state->wrap && state->flags) {
  77478. NEEDBITS(32);
  77479. if (hold != (state->total & 0xffffffffUL)) {
  77480. strm->msg = (char *)"incorrect length check";
  77481. state->mode = BAD;
  77482. break;
  77483. }
  77484. INITBITS();
  77485. Tracev((stderr, "inflate: length matches trailer\n"));
  77486. }
  77487. #endif
  77488. state->mode = DONE;
  77489. case DONE:
  77490. ret = Z_STREAM_END;
  77491. goto inf_leave;
  77492. case BAD:
  77493. ret = Z_DATA_ERROR;
  77494. goto inf_leave;
  77495. case MEM:
  77496. return Z_MEM_ERROR;
  77497. case SYNC:
  77498. default:
  77499. return Z_STREAM_ERROR;
  77500. }
  77501. /*
  77502. Return from inflate(), updating the total counts and the check value.
  77503. If there was no progress during the inflate() call, return a buffer
  77504. error. Call updatewindow() to create and/or update the window state.
  77505. Note: a memory error from inflate() is non-recoverable.
  77506. */
  77507. inf_leave:
  77508. RESTORE();
  77509. if (state->wsize || (state->mode < CHECK && out != strm->avail_out))
  77510. if (updatewindow(strm, out)) {
  77511. state->mode = MEM;
  77512. return Z_MEM_ERROR;
  77513. }
  77514. in -= strm->avail_in;
  77515. out -= strm->avail_out;
  77516. strm->total_in += in;
  77517. strm->total_out += out;
  77518. state->total += out;
  77519. if (state->wrap && out)
  77520. strm->adler = state->check =
  77521. UPDATE(state->check, strm->next_out - out, out);
  77522. strm->data_type = state->bits + (state->last ? 64 : 0) +
  77523. (state->mode == TYPE ? 128 : 0);
  77524. if (((in == 0 && out == 0) || flush == Z_FINISH) && ret == Z_OK)
  77525. ret = Z_BUF_ERROR;
  77526. return ret;
  77527. }
  77528. int ZEXPORT inflateEnd (z_streamp strm)
  77529. {
  77530. struct inflate_state FAR *state;
  77531. if (strm == Z_NULL || strm->state == Z_NULL || strm->zfree == (free_func)0)
  77532. return Z_STREAM_ERROR;
  77533. state = (struct inflate_state FAR *)strm->state;
  77534. if (state->window != Z_NULL) ZFREE(strm, state->window);
  77535. ZFREE(strm, strm->state);
  77536. strm->state = Z_NULL;
  77537. Tracev((stderr, "inflate: end\n"));
  77538. return Z_OK;
  77539. }
  77540. int ZEXPORT inflateSetDictionary (z_streamp strm, const Bytef *dictionary, uInt dictLength)
  77541. {
  77542. struct inflate_state FAR *state;
  77543. unsigned long id_;
  77544. /* check state */
  77545. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  77546. state = (struct inflate_state FAR *)strm->state;
  77547. if (state->wrap != 0 && state->mode != DICT)
  77548. return Z_STREAM_ERROR;
  77549. /* check for correct dictionary id */
  77550. if (state->mode == DICT) {
  77551. id_ = adler32(0L, Z_NULL, 0);
  77552. id_ = adler32(id_, dictionary, dictLength);
  77553. if (id_ != state->check)
  77554. return Z_DATA_ERROR;
  77555. }
  77556. /* copy dictionary to window */
  77557. if (updatewindow(strm, strm->avail_out)) {
  77558. state->mode = MEM;
  77559. return Z_MEM_ERROR;
  77560. }
  77561. if (dictLength > state->wsize) {
  77562. zmemcpy(state->window, dictionary + dictLength - state->wsize,
  77563. state->wsize);
  77564. state->whave = state->wsize;
  77565. }
  77566. else {
  77567. zmemcpy(state->window + state->wsize - dictLength, dictionary,
  77568. dictLength);
  77569. state->whave = dictLength;
  77570. }
  77571. state->havedict = 1;
  77572. Tracev((stderr, "inflate: dictionary set\n"));
  77573. return Z_OK;
  77574. }
  77575. int ZEXPORT inflateGetHeader (z_streamp strm, gz_headerp head)
  77576. {
  77577. struct inflate_state FAR *state;
  77578. /* check state */
  77579. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  77580. state = (struct inflate_state FAR *)strm->state;
  77581. if ((state->wrap & 2) == 0) return Z_STREAM_ERROR;
  77582. /* save header structure */
  77583. state->head = head;
  77584. head->done = 0;
  77585. return Z_OK;
  77586. }
  77587. /*
  77588. Search buf[0..len-1] for the pattern: 0, 0, 0xff, 0xff. Return when found
  77589. or when out of input. When called, *have is the number of pattern bytes
  77590. found in order so far, in 0..3. On return *have is updated to the new
  77591. state. If on return *have equals four, then the pattern was found and the
  77592. return value is how many bytes were read including the last byte of the
  77593. pattern. If *have is less than four, then the pattern has not been found
  77594. yet and the return value is len. In the latter case, syncsearch() can be
  77595. called again with more data and the *have state. *have is initialized to
  77596. zero for the first call.
  77597. */
  77598. local unsigned syncsearch (unsigned FAR *have, unsigned char FAR *buf, unsigned len)
  77599. {
  77600. unsigned got;
  77601. unsigned next;
  77602. got = *have;
  77603. next = 0;
  77604. while (next < len && got < 4) {
  77605. if ((int)(buf[next]) == (got < 2 ? 0 : 0xff))
  77606. got++;
  77607. else if (buf[next])
  77608. got = 0;
  77609. else
  77610. got = 4 - got;
  77611. next++;
  77612. }
  77613. *have = got;
  77614. return next;
  77615. }
  77616. int ZEXPORT inflateSync (z_streamp strm)
  77617. {
  77618. unsigned len; /* number of bytes to look at or looked at */
  77619. unsigned long in, out; /* temporary to save total_in and total_out */
  77620. unsigned char buf[4]; /* to restore bit buffer to byte string */
  77621. struct inflate_state FAR *state;
  77622. /* check parameters */
  77623. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  77624. state = (struct inflate_state FAR *)strm->state;
  77625. if (strm->avail_in == 0 && state->bits < 8) return Z_BUF_ERROR;
  77626. /* if first time, start search in bit buffer */
  77627. if (state->mode != SYNC) {
  77628. state->mode = SYNC;
  77629. state->hold <<= state->bits & 7;
  77630. state->bits -= state->bits & 7;
  77631. len = 0;
  77632. while (state->bits >= 8) {
  77633. buf[len++] = (unsigned char)(state->hold);
  77634. state->hold >>= 8;
  77635. state->bits -= 8;
  77636. }
  77637. state->have = 0;
  77638. syncsearch(&(state->have), buf, len);
  77639. }
  77640. /* search available input */
  77641. len = syncsearch(&(state->have), strm->next_in, strm->avail_in);
  77642. strm->avail_in -= len;
  77643. strm->next_in += len;
  77644. strm->total_in += len;
  77645. /* return no joy or set up to restart inflate() on a new block */
  77646. if (state->have != 4) return Z_DATA_ERROR;
  77647. in = strm->total_in; out = strm->total_out;
  77648. inflateReset(strm);
  77649. strm->total_in = in; strm->total_out = out;
  77650. state->mode = TYPE;
  77651. return Z_OK;
  77652. }
  77653. /*
  77654. Returns true if inflate is currently at the end of a block generated by
  77655. Z_SYNC_FLUSH or Z_FULL_FLUSH. This function is used by one PPP
  77656. implementation to provide an additional safety check. PPP uses
  77657. Z_SYNC_FLUSH but removes the length bytes of the resulting empty stored
  77658. block. When decompressing, PPP checks that at the end of input packet,
  77659. inflate is waiting for these length bytes.
  77660. */
  77661. int ZEXPORT inflateSyncPoint (z_streamp strm)
  77662. {
  77663. struct inflate_state FAR *state;
  77664. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  77665. state = (struct inflate_state FAR *)strm->state;
  77666. return state->mode == STORED && state->bits == 0;
  77667. }
  77668. int ZEXPORT inflateCopy(z_streamp dest, z_streamp source)
  77669. {
  77670. struct inflate_state FAR *state;
  77671. struct inflate_state FAR *copy;
  77672. unsigned char FAR *window;
  77673. unsigned wsize;
  77674. /* check input */
  77675. if (dest == Z_NULL || source == Z_NULL || source->state == Z_NULL ||
  77676. source->zalloc == (alloc_func)0 || source->zfree == (free_func)0)
  77677. return Z_STREAM_ERROR;
  77678. state = (struct inflate_state FAR *)source->state;
  77679. /* allocate space */
  77680. copy = (struct inflate_state FAR *)
  77681. ZALLOC(source, 1, sizeof(struct inflate_state));
  77682. if (copy == Z_NULL) return Z_MEM_ERROR;
  77683. window = Z_NULL;
  77684. if (state->window != Z_NULL) {
  77685. window = (unsigned char FAR *)
  77686. ZALLOC(source, 1U << state->wbits, sizeof(unsigned char));
  77687. if (window == Z_NULL) {
  77688. ZFREE(source, copy);
  77689. return Z_MEM_ERROR;
  77690. }
  77691. }
  77692. /* copy state */
  77693. zmemcpy(dest, source, sizeof(z_stream));
  77694. zmemcpy(copy, state, sizeof(struct inflate_state));
  77695. if (state->lencode >= state->codes &&
  77696. state->lencode <= state->codes + ENOUGH - 1) {
  77697. copy->lencode = copy->codes + (state->lencode - state->codes);
  77698. copy->distcode = copy->codes + (state->distcode - state->codes);
  77699. }
  77700. copy->next = copy->codes + (state->next - state->codes);
  77701. if (window != Z_NULL) {
  77702. wsize = 1U << state->wbits;
  77703. zmemcpy(window, state->window, wsize);
  77704. }
  77705. copy->window = window;
  77706. dest->state = (struct internal_state FAR *)copy;
  77707. return Z_OK;
  77708. }
  77709. /********* End of inlined file: inflate.c *********/
  77710. /********* Start of inlined file: inftrees.c *********/
  77711. #define MAXBITS 15
  77712. const char inflate_copyright[] =
  77713. " inflate 1.2.3 Copyright 1995-2005 Mark Adler ";
  77714. /*
  77715. If you use the zlib library in a product, an acknowledgment is welcome
  77716. in the documentation of your product. If for some reason you cannot
  77717. include such an acknowledgment, I would appreciate that you keep this
  77718. copyright string in the executable of your product.
  77719. */
  77720. /*
  77721. Build a set of tables to decode the provided canonical Huffman code.
  77722. The code lengths are lens[0..codes-1]. The result starts at *table,
  77723. whose indices are 0..2^bits-1. work is a writable array of at least
  77724. lens shorts, which is used as a work area. type is the type of code
  77725. to be generated, CODES, LENS, or DISTS. On return, zero is success,
  77726. -1 is an invalid code, and +1 means that ENOUGH isn't enough. table
  77727. on return points to the next available entry's address. bits is the
  77728. requested root table index bits, and on return it is the actual root
  77729. table index bits. It will differ if the request is greater than the
  77730. longest code or if it is less than the shortest code.
  77731. */
  77732. int inflate_table (codetype type,
  77733. unsigned short FAR *lens,
  77734. unsigned codes,
  77735. code FAR * FAR *table,
  77736. unsigned FAR *bits,
  77737. unsigned short FAR *work)
  77738. {
  77739. unsigned len; /* a code's length in bits */
  77740. unsigned sym; /* index of code symbols */
  77741. unsigned min, max; /* minimum and maximum code lengths */
  77742. unsigned root; /* number of index bits for root table */
  77743. unsigned curr; /* number of index bits for current table */
  77744. unsigned drop; /* code bits to drop for sub-table */
  77745. int left; /* number of prefix codes available */
  77746. unsigned used; /* code entries in table used */
  77747. unsigned huff; /* Huffman code */
  77748. unsigned incr; /* for incrementing code, index */
  77749. unsigned fill; /* index for replicating entries */
  77750. unsigned low; /* low bits for current root entry */
  77751. unsigned mask; /* mask for low root bits */
  77752. code thisx; /* table entry for duplication */
  77753. code FAR *next; /* next available space in table */
  77754. const unsigned short FAR *base; /* base value table to use */
  77755. const unsigned short FAR *extra; /* extra bits table to use */
  77756. int end; /* use base and extra for symbol > end */
  77757. unsigned short count[MAXBITS+1]; /* number of codes of each length */
  77758. unsigned short offs[MAXBITS+1]; /* offsets in table for each length */
  77759. static const unsigned short lbase[31] = { /* Length codes 257..285 base */
  77760. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  77761. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0};
  77762. static const unsigned short lext[31] = { /* Length codes 257..285 extra */
  77763. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  77764. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 201, 196};
  77765. static const unsigned short dbase[32] = { /* Distance codes 0..29 base */
  77766. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  77767. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  77768. 8193, 12289, 16385, 24577, 0, 0};
  77769. static const unsigned short dext[32] = { /* Distance codes 0..29 extra */
  77770. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  77771. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  77772. 28, 28, 29, 29, 64, 64};
  77773. /*
  77774. Process a set of code lengths to create a canonical Huffman code. The
  77775. code lengths are lens[0..codes-1]. Each length corresponds to the
  77776. symbols 0..codes-1. The Huffman code is generated by first sorting the
  77777. symbols by length from short to long, and retaining the symbol order
  77778. for codes with equal lengths. Then the code starts with all zero bits
  77779. for the first code of the shortest length, and the codes are integer
  77780. increments for the same length, and zeros are appended as the length
  77781. increases. For the deflate format, these bits are stored backwards
  77782. from their more natural integer increment ordering, and so when the
  77783. decoding tables are built in the large loop below, the integer codes
  77784. are incremented backwards.
  77785. This routine assumes, but does not check, that all of the entries in
  77786. lens[] are in the range 0..MAXBITS. The caller must assure this.
  77787. 1..MAXBITS is interpreted as that code length. zero means that that
  77788. symbol does not occur in this code.
  77789. The codes are sorted by computing a count of codes for each length,
  77790. creating from that a table of starting indices for each length in the
  77791. sorted table, and then entering the symbols in order in the sorted
  77792. table. The sorted table is work[], with that space being provided by
  77793. the caller.
  77794. The length counts are used for other purposes as well, i.e. finding
  77795. the minimum and maximum length codes, determining if there are any
  77796. codes at all, checking for a valid set of lengths, and looking ahead
  77797. at length counts to determine sub-table sizes when building the
  77798. decoding tables.
  77799. */
  77800. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  77801. for (len = 0; len <= MAXBITS; len++)
  77802. count[len] = 0;
  77803. for (sym = 0; sym < codes; sym++)
  77804. count[lens[sym]]++;
  77805. /* bound code lengths, force root to be within code lengths */
  77806. root = *bits;
  77807. for (max = MAXBITS; max >= 1; max--)
  77808. if (count[max] != 0) break;
  77809. if (root > max) root = max;
  77810. if (max == 0) { /* no symbols to code at all */
  77811. thisx.op = (unsigned char)64; /* invalid code marker */
  77812. thisx.bits = (unsigned char)1;
  77813. thisx.val = (unsigned short)0;
  77814. *(*table)++ = thisx; /* make a table to force an error */
  77815. *(*table)++ = thisx;
  77816. *bits = 1;
  77817. return 0; /* no symbols, but wait for decoding to report error */
  77818. }
  77819. for (min = 1; min <= MAXBITS; min++)
  77820. if (count[min] != 0) break;
  77821. if (root < min) root = min;
  77822. /* check for an over-subscribed or incomplete set of lengths */
  77823. left = 1;
  77824. for (len = 1; len <= MAXBITS; len++) {
  77825. left <<= 1;
  77826. left -= count[len];
  77827. if (left < 0) return -1; /* over-subscribed */
  77828. }
  77829. if (left > 0 && (type == CODES || max != 1))
  77830. return -1; /* incomplete set */
  77831. /* generate offsets into symbol table for each length for sorting */
  77832. offs[1] = 0;
  77833. for (len = 1; len < MAXBITS; len++)
  77834. offs[len + 1] = offs[len] + count[len];
  77835. /* sort symbols by length, by symbol order within each length */
  77836. for (sym = 0; sym < codes; sym++)
  77837. if (lens[sym] != 0) work[offs[lens[sym]]++] = (unsigned short)sym;
  77838. /*
  77839. Create and fill in decoding tables. In this loop, the table being
  77840. filled is at next and has curr index bits. The code being used is huff
  77841. with length len. That code is converted to an index by dropping drop
  77842. bits off of the bottom. For codes where len is less than drop + curr,
  77843. those top drop + curr - len bits are incremented through all values to
  77844. fill the table with replicated entries.
  77845. root is the number of index bits for the root table. When len exceeds
  77846. root, sub-tables are created pointed to by the root entry with an index
  77847. of the low root bits of huff. This is saved in low to check for when a
  77848. new sub-table should be started. drop is zero when the root table is
  77849. being filled, and drop is root when sub-tables are being filled.
  77850. When a new sub-table is needed, it is necessary to look ahead in the
  77851. code lengths to determine what size sub-table is needed. The length
  77852. counts are used for this, and so count[] is decremented as codes are
  77853. entered in the tables.
  77854. used keeps track of how many table entries have been allocated from the
  77855. provided *table space. It is checked when a LENS table is being made
  77856. against the space in *table, ENOUGH, minus the maximum space needed by
  77857. the worst case distance code, MAXD. This should never happen, but the
  77858. sufficiency of ENOUGH has not been proven exhaustively, hence the check.
  77859. This assumes that when type == LENS, bits == 9.
  77860. sym increments through all symbols, and the loop terminates when
  77861. all codes of length max, i.e. all codes, have been processed. This
  77862. routine permits incomplete codes, so another loop after this one fills
  77863. in the rest of the decoding tables with invalid code markers.
  77864. */
  77865. /* set up for code type */
  77866. switch (type) {
  77867. case CODES:
  77868. base = extra = work; /* dummy value--not used */
  77869. end = 19;
  77870. break;
  77871. case LENS:
  77872. base = lbase;
  77873. base -= 257;
  77874. extra = lext;
  77875. extra -= 257;
  77876. end = 256;
  77877. break;
  77878. default: /* DISTS */
  77879. base = dbase;
  77880. extra = dext;
  77881. end = -1;
  77882. }
  77883. /* initialize state for loop */
  77884. huff = 0; /* starting code */
  77885. sym = 0; /* starting code symbol */
  77886. len = min; /* starting code length */
  77887. next = *table; /* current table to fill in */
  77888. curr = root; /* current table index bits */
  77889. drop = 0; /* current bits to drop from code for index */
  77890. low = (unsigned)(-1); /* trigger new sub-table when len > root */
  77891. used = 1U << root; /* use root table entries */
  77892. mask = used - 1; /* mask for comparing low */
  77893. /* check available table space */
  77894. if (type == LENS && used >= ENOUGH - MAXD)
  77895. return 1;
  77896. /* process all codes and make table entries */
  77897. for (;;) {
  77898. /* create table entry */
  77899. thisx.bits = (unsigned char)(len - drop);
  77900. if ((int)(work[sym]) < end) {
  77901. thisx.op = (unsigned char)0;
  77902. thisx.val = work[sym];
  77903. }
  77904. else if ((int)(work[sym]) > end) {
  77905. thisx.op = (unsigned char)(extra[work[sym]]);
  77906. thisx.val = base[work[sym]];
  77907. }
  77908. else {
  77909. thisx.op = (unsigned char)(32 + 64); /* end of block */
  77910. thisx.val = 0;
  77911. }
  77912. /* replicate for those indices with low len bits equal to huff */
  77913. incr = 1U << (len - drop);
  77914. fill = 1U << curr;
  77915. min = fill; /* save offset to next table */
  77916. do {
  77917. fill -= incr;
  77918. next[(huff >> drop) + fill] = thisx;
  77919. } while (fill != 0);
  77920. /* backwards increment the len-bit code huff */
  77921. incr = 1U << (len - 1);
  77922. while (huff & incr)
  77923. incr >>= 1;
  77924. if (incr != 0) {
  77925. huff &= incr - 1;
  77926. huff += incr;
  77927. }
  77928. else
  77929. huff = 0;
  77930. /* go to next symbol, update count, len */
  77931. sym++;
  77932. if (--(count[len]) == 0) {
  77933. if (len == max) break;
  77934. len = lens[work[sym]];
  77935. }
  77936. /* create new sub-table if needed */
  77937. if (len > root && (huff & mask) != low) {
  77938. /* if first time, transition to sub-tables */
  77939. if (drop == 0)
  77940. drop = root;
  77941. /* increment past last table */
  77942. next += min; /* here min is 1 << curr */
  77943. /* determine length of next table */
  77944. curr = len - drop;
  77945. left = (int)(1 << curr);
  77946. while (curr + drop < max) {
  77947. left -= count[curr + drop];
  77948. if (left <= 0) break;
  77949. curr++;
  77950. left <<= 1;
  77951. }
  77952. /* check for enough space */
  77953. used += 1U << curr;
  77954. if (type == LENS && used >= ENOUGH - MAXD)
  77955. return 1;
  77956. /* point entry in root table to sub-table */
  77957. low = huff & mask;
  77958. (*table)[low].op = (unsigned char)curr;
  77959. (*table)[low].bits = (unsigned char)root;
  77960. (*table)[low].val = (unsigned short)(next - *table);
  77961. }
  77962. }
  77963. /*
  77964. Fill in rest of table for incomplete codes. This loop is similar to the
  77965. loop above in incrementing huff for table indices. It is assumed that
  77966. len is equal to curr + drop, so there is no loop needed to increment
  77967. through high index bits. When the current sub-table is filled, the loop
  77968. drops back to the root table to fill in any remaining entries there.
  77969. */
  77970. thisx.op = (unsigned char)64; /* invalid code marker */
  77971. thisx.bits = (unsigned char)(len - drop);
  77972. thisx.val = (unsigned short)0;
  77973. while (huff != 0) {
  77974. /* when done with sub-table, drop back to root table */
  77975. if (drop != 0 && (huff & mask) != low) {
  77976. drop = 0;
  77977. len = root;
  77978. next = *table;
  77979. thisx.bits = (unsigned char)len;
  77980. }
  77981. /* put invalid code marker in table */
  77982. next[huff >> drop] = thisx;
  77983. /* backwards increment the len-bit code huff */
  77984. incr = 1U << (len - 1);
  77985. while (huff & incr)
  77986. incr >>= 1;
  77987. if (incr != 0) {
  77988. huff &= incr - 1;
  77989. huff += incr;
  77990. }
  77991. else
  77992. huff = 0;
  77993. }
  77994. /* set return parameters */
  77995. *table += used;
  77996. *bits = root;
  77997. return 0;
  77998. }
  77999. /********* End of inlined file: inftrees.c *********/
  78000. /********* Start of inlined file: trees.c *********/
  78001. /*
  78002. * ALGORITHM
  78003. *
  78004. * The "deflation" process uses several Huffman trees. The more
  78005. * common source values are represented by shorter bit sequences.
  78006. *
  78007. * Each code tree is stored in a compressed form which is itself
  78008. * a Huffman encoding of the lengths of all the code strings (in
  78009. * ascending order by source values). The actual code strings are
  78010. * reconstructed from the lengths in the inflate process, as described
  78011. * in the deflate specification.
  78012. *
  78013. * REFERENCES
  78014. *
  78015. * Deutsch, L.P.,"'Deflate' Compressed Data Format Specification".
  78016. * Available in ftp.uu.net:/pub/archiving/zip/doc/deflate-1.1.doc
  78017. *
  78018. * Storer, James A.
  78019. * Data Compression: Methods and Theory, pp. 49-50.
  78020. * Computer Science Press, 1988. ISBN 0-7167-8156-5.
  78021. *
  78022. * Sedgewick, R.
  78023. * Algorithms, p290.
  78024. * Addison-Wesley, 1983. ISBN 0-201-06672-6.
  78025. */
  78026. /* @(#) $Id: trees.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  78027. /* #define GEN_TREES_H */
  78028. #ifdef DEBUG
  78029. # include <ctype.h>
  78030. #endif
  78031. /* ===========================================================================
  78032. * Constants
  78033. */
  78034. #define MAX_BL_BITS 7
  78035. /* Bit length codes must not exceed MAX_BL_BITS bits */
  78036. #define END_BLOCK 256
  78037. /* end of block literal code */
  78038. #define REP_3_6 16
  78039. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  78040. #define REPZ_3_10 17
  78041. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  78042. #define REPZ_11_138 18
  78043. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  78044. local const int extra_lbits[LENGTH_CODES] /* extra bits for each length code */
  78045. = {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};
  78046. local const int extra_dbits[D_CODES] /* extra bits for each distance code */
  78047. = {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};
  78048. local const int extra_blbits[BL_CODES]/* extra bits for each bit length code */
  78049. = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7};
  78050. local const uch bl_order[BL_CODES]
  78051. = {16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15};
  78052. /* The lengths of the bit length codes are sent in order of decreasing
  78053. * probability, to avoid transmitting the lengths for unused bit length codes.
  78054. */
  78055. #define Buf_size (8 * 2*sizeof(char))
  78056. /* Number of bits used within bi_buf. (bi_buf might be implemented on
  78057. * more than 16 bits on some systems.)
  78058. */
  78059. /* ===========================================================================
  78060. * Local data. These are initialized only once.
  78061. */
  78062. #define DIST_CODE_LEN 512 /* see definition of array dist_code below */
  78063. #if defined(GEN_TREES_H) || !defined(STDC)
  78064. /* non ANSI compilers may not accept trees.h */
  78065. local ct_data static_ltree[L_CODES+2];
  78066. /* The static literal tree. Since the bit lengths are imposed, there is no
  78067. * need for the L_CODES extra codes used during heap construction. However
  78068. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  78069. * below).
  78070. */
  78071. local ct_data static_dtree[D_CODES];
  78072. /* The static distance tree. (Actually a trivial tree since all codes use
  78073. * 5 bits.)
  78074. */
  78075. uch _dist_code[DIST_CODE_LEN];
  78076. /* Distance codes. The first 256 values correspond to the distances
  78077. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  78078. * the 15 bit distances.
  78079. */
  78080. uch _length_code[MAX_MATCH-MIN_MATCH+1];
  78081. /* length code for each normalized match length (0 == MIN_MATCH) */
  78082. local int base_length[LENGTH_CODES];
  78083. /* First normalized length for each code (0 = MIN_MATCH) */
  78084. local int base_dist[D_CODES];
  78085. /* First normalized distance for each code (0 = distance of 1) */
  78086. #else
  78087. /********* Start of inlined file: trees.h *********/
  78088. local const ct_data static_ltree[L_CODES+2] = {
  78089. {{ 12},{ 8}}, {{140},{ 8}}, {{ 76},{ 8}}, {{204},{ 8}}, {{ 44},{ 8}},
  78090. {{172},{ 8}}, {{108},{ 8}}, {{236},{ 8}}, {{ 28},{ 8}}, {{156},{ 8}},
  78091. {{ 92},{ 8}}, {{220},{ 8}}, {{ 60},{ 8}}, {{188},{ 8}}, {{124},{ 8}},
  78092. {{252},{ 8}}, {{ 2},{ 8}}, {{130},{ 8}}, {{ 66},{ 8}}, {{194},{ 8}},
  78093. {{ 34},{ 8}}, {{162},{ 8}}, {{ 98},{ 8}}, {{226},{ 8}}, {{ 18},{ 8}},
  78094. {{146},{ 8}}, {{ 82},{ 8}}, {{210},{ 8}}, {{ 50},{ 8}}, {{178},{ 8}},
  78095. {{114},{ 8}}, {{242},{ 8}}, {{ 10},{ 8}}, {{138},{ 8}}, {{ 74},{ 8}},
  78096. {{202},{ 8}}, {{ 42},{ 8}}, {{170},{ 8}}, {{106},{ 8}}, {{234},{ 8}},
  78097. {{ 26},{ 8}}, {{154},{ 8}}, {{ 90},{ 8}}, {{218},{ 8}}, {{ 58},{ 8}},
  78098. {{186},{ 8}}, {{122},{ 8}}, {{250},{ 8}}, {{ 6},{ 8}}, {{134},{ 8}},
  78099. {{ 70},{ 8}}, {{198},{ 8}}, {{ 38},{ 8}}, {{166},{ 8}}, {{102},{ 8}},
  78100. {{230},{ 8}}, {{ 22},{ 8}}, {{150},{ 8}}, {{ 86},{ 8}}, {{214},{ 8}},
  78101. {{ 54},{ 8}}, {{182},{ 8}}, {{118},{ 8}}, {{246},{ 8}}, {{ 14},{ 8}},
  78102. {{142},{ 8}}, {{ 78},{ 8}}, {{206},{ 8}}, {{ 46},{ 8}}, {{174},{ 8}},
  78103. {{110},{ 8}}, {{238},{ 8}}, {{ 30},{ 8}}, {{158},{ 8}}, {{ 94},{ 8}},
  78104. {{222},{ 8}}, {{ 62},{ 8}}, {{190},{ 8}}, {{126},{ 8}}, {{254},{ 8}},
  78105. {{ 1},{ 8}}, {{129},{ 8}}, {{ 65},{ 8}}, {{193},{ 8}}, {{ 33},{ 8}},
  78106. {{161},{ 8}}, {{ 97},{ 8}}, {{225},{ 8}}, {{ 17},{ 8}}, {{145},{ 8}},
  78107. {{ 81},{ 8}}, {{209},{ 8}}, {{ 49},{ 8}}, {{177},{ 8}}, {{113},{ 8}},
  78108. {{241},{ 8}}, {{ 9},{ 8}}, {{137},{ 8}}, {{ 73},{ 8}}, {{201},{ 8}},
  78109. {{ 41},{ 8}}, {{169},{ 8}}, {{105},{ 8}}, {{233},{ 8}}, {{ 25},{ 8}},
  78110. {{153},{ 8}}, {{ 89},{ 8}}, {{217},{ 8}}, {{ 57},{ 8}}, {{185},{ 8}},
  78111. {{121},{ 8}}, {{249},{ 8}}, {{ 5},{ 8}}, {{133},{ 8}}, {{ 69},{ 8}},
  78112. {{197},{ 8}}, {{ 37},{ 8}}, {{165},{ 8}}, {{101},{ 8}}, {{229},{ 8}},
  78113. {{ 21},{ 8}}, {{149},{ 8}}, {{ 85},{ 8}}, {{213},{ 8}}, {{ 53},{ 8}},
  78114. {{181},{ 8}}, {{117},{ 8}}, {{245},{ 8}}, {{ 13},{ 8}}, {{141},{ 8}},
  78115. {{ 77},{ 8}}, {{205},{ 8}}, {{ 45},{ 8}}, {{173},{ 8}}, {{109},{ 8}},
  78116. {{237},{ 8}}, {{ 29},{ 8}}, {{157},{ 8}}, {{ 93},{ 8}}, {{221},{ 8}},
  78117. {{ 61},{ 8}}, {{189},{ 8}}, {{125},{ 8}}, {{253},{ 8}}, {{ 19},{ 9}},
  78118. {{275},{ 9}}, {{147},{ 9}}, {{403},{ 9}}, {{ 83},{ 9}}, {{339},{ 9}},
  78119. {{211},{ 9}}, {{467},{ 9}}, {{ 51},{ 9}}, {{307},{ 9}}, {{179},{ 9}},
  78120. {{435},{ 9}}, {{115},{ 9}}, {{371},{ 9}}, {{243},{ 9}}, {{499},{ 9}},
  78121. {{ 11},{ 9}}, {{267},{ 9}}, {{139},{ 9}}, {{395},{ 9}}, {{ 75},{ 9}},
  78122. {{331},{ 9}}, {{203},{ 9}}, {{459},{ 9}}, {{ 43},{ 9}}, {{299},{ 9}},
  78123. {{171},{ 9}}, {{427},{ 9}}, {{107},{ 9}}, {{363},{ 9}}, {{235},{ 9}},
  78124. {{491},{ 9}}, {{ 27},{ 9}}, {{283},{ 9}}, {{155},{ 9}}, {{411},{ 9}},
  78125. {{ 91},{ 9}}, {{347},{ 9}}, {{219},{ 9}}, {{475},{ 9}}, {{ 59},{ 9}},
  78126. {{315},{ 9}}, {{187},{ 9}}, {{443},{ 9}}, {{123},{ 9}}, {{379},{ 9}},
  78127. {{251},{ 9}}, {{507},{ 9}}, {{ 7},{ 9}}, {{263},{ 9}}, {{135},{ 9}},
  78128. {{391},{ 9}}, {{ 71},{ 9}}, {{327},{ 9}}, {{199},{ 9}}, {{455},{ 9}},
  78129. {{ 39},{ 9}}, {{295},{ 9}}, {{167},{ 9}}, {{423},{ 9}}, {{103},{ 9}},
  78130. {{359},{ 9}}, {{231},{ 9}}, {{487},{ 9}}, {{ 23},{ 9}}, {{279},{ 9}},
  78131. {{151},{ 9}}, {{407},{ 9}}, {{ 87},{ 9}}, {{343},{ 9}}, {{215},{ 9}},
  78132. {{471},{ 9}}, {{ 55},{ 9}}, {{311},{ 9}}, {{183},{ 9}}, {{439},{ 9}},
  78133. {{119},{ 9}}, {{375},{ 9}}, {{247},{ 9}}, {{503},{ 9}}, {{ 15},{ 9}},
  78134. {{271},{ 9}}, {{143},{ 9}}, {{399},{ 9}}, {{ 79},{ 9}}, {{335},{ 9}},
  78135. {{207},{ 9}}, {{463},{ 9}}, {{ 47},{ 9}}, {{303},{ 9}}, {{175},{ 9}},
  78136. {{431},{ 9}}, {{111},{ 9}}, {{367},{ 9}}, {{239},{ 9}}, {{495},{ 9}},
  78137. {{ 31},{ 9}}, {{287},{ 9}}, {{159},{ 9}}, {{415},{ 9}}, {{ 95},{ 9}},
  78138. {{351},{ 9}}, {{223},{ 9}}, {{479},{ 9}}, {{ 63},{ 9}}, {{319},{ 9}},
  78139. {{191},{ 9}}, {{447},{ 9}}, {{127},{ 9}}, {{383},{ 9}}, {{255},{ 9}},
  78140. {{511},{ 9}}, {{ 0},{ 7}}, {{ 64},{ 7}}, {{ 32},{ 7}}, {{ 96},{ 7}},
  78141. {{ 16},{ 7}}, {{ 80},{ 7}}, {{ 48},{ 7}}, {{112},{ 7}}, {{ 8},{ 7}},
  78142. {{ 72},{ 7}}, {{ 40},{ 7}}, {{104},{ 7}}, {{ 24},{ 7}}, {{ 88},{ 7}},
  78143. {{ 56},{ 7}}, {{120},{ 7}}, {{ 4},{ 7}}, {{ 68},{ 7}}, {{ 36},{ 7}},
  78144. {{100},{ 7}}, {{ 20},{ 7}}, {{ 84},{ 7}}, {{ 52},{ 7}}, {{116},{ 7}},
  78145. {{ 3},{ 8}}, {{131},{ 8}}, {{ 67},{ 8}}, {{195},{ 8}}, {{ 35},{ 8}},
  78146. {{163},{ 8}}, {{ 99},{ 8}}, {{227},{ 8}}
  78147. };
  78148. local const ct_data static_dtree[D_CODES] = {
  78149. {{ 0},{ 5}}, {{16},{ 5}}, {{ 8},{ 5}}, {{24},{ 5}}, {{ 4},{ 5}},
  78150. {{20},{ 5}}, {{12},{ 5}}, {{28},{ 5}}, {{ 2},{ 5}}, {{18},{ 5}},
  78151. {{10},{ 5}}, {{26},{ 5}}, {{ 6},{ 5}}, {{22},{ 5}}, {{14},{ 5}},
  78152. {{30},{ 5}}, {{ 1},{ 5}}, {{17},{ 5}}, {{ 9},{ 5}}, {{25},{ 5}},
  78153. {{ 5},{ 5}}, {{21},{ 5}}, {{13},{ 5}}, {{29},{ 5}}, {{ 3},{ 5}},
  78154. {{19},{ 5}}, {{11},{ 5}}, {{27},{ 5}}, {{ 7},{ 5}}, {{23},{ 5}}
  78155. };
  78156. const uch _dist_code[DIST_CODE_LEN] = {
  78157. 0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8,
  78158. 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10,
  78159. 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11,
  78160. 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
  78161. 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13,
  78162. 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
  78163. 13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  78164. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  78165. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  78166. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15,
  78167. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
  78168. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
  78169. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 16, 17,
  78170. 18, 18, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22,
  78171. 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  78172. 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
  78173. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
  78174. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27,
  78175. 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  78176. 27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  78177. 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  78178. 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  78179. 28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  78180. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  78181. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  78182. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29
  78183. };
  78184. const uch _length_code[MAX_MATCH-MIN_MATCH+1]= {
  78185. 0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 12, 12,
  78186. 13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16,
  78187. 17, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19,
  78188. 19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
  78189. 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22,
  78190. 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23,
  78191. 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  78192. 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  78193. 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
  78194. 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26,
  78195. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
  78196. 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  78197. 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28
  78198. };
  78199. local const int base_length[LENGTH_CODES] = {
  78200. 0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48, 56,
  78201. 64, 80, 96, 112, 128, 160, 192, 224, 0
  78202. };
  78203. local const int base_dist[D_CODES] = {
  78204. 0, 1, 2, 3, 4, 6, 8, 12, 16, 24,
  78205. 32, 48, 64, 96, 128, 192, 256, 384, 512, 768,
  78206. 1024, 1536, 2048, 3072, 4096, 6144, 8192, 12288, 16384, 24576
  78207. };
  78208. /********* End of inlined file: trees.h *********/
  78209. #endif /* GEN_TREES_H */
  78210. struct static_tree_desc_s {
  78211. const ct_data *static_tree; /* static tree or NULL */
  78212. const intf *extra_bits; /* extra bits for each code or NULL */
  78213. int extra_base; /* base index for extra_bits */
  78214. int elems; /* max number of elements in the tree */
  78215. int max_length; /* max bit length for the codes */
  78216. };
  78217. local static_tree_desc static_l_desc =
  78218. {static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS};
  78219. local static_tree_desc static_d_desc =
  78220. {static_dtree, extra_dbits, 0, D_CODES, MAX_BITS};
  78221. local static_tree_desc static_bl_desc =
  78222. {(const ct_data *)0, extra_blbits, 0, BL_CODES, MAX_BL_BITS};
  78223. /* ===========================================================================
  78224. * Local (static) routines in this file.
  78225. */
  78226. local void tr_static_init OF((void));
  78227. local void init_block OF((deflate_state *s));
  78228. local void pqdownheap OF((deflate_state *s, ct_data *tree, int k));
  78229. local void gen_bitlen OF((deflate_state *s, tree_desc *desc));
  78230. local void gen_codes OF((ct_data *tree, int max_code, ushf *bl_count));
  78231. local void build_tree OF((deflate_state *s, tree_desc *desc));
  78232. local void scan_tree OF((deflate_state *s, ct_data *tree, int max_code));
  78233. local void send_tree OF((deflate_state *s, ct_data *tree, int max_code));
  78234. local int build_bl_tree OF((deflate_state *s));
  78235. local void send_all_trees OF((deflate_state *s, int lcodes, int dcodes,
  78236. int blcodes));
  78237. local void compress_block OF((deflate_state *s, ct_data *ltree,
  78238. ct_data *dtree));
  78239. local void set_data_type OF((deflate_state *s));
  78240. local unsigned bi_reverse OF((unsigned value, int length));
  78241. local void bi_windup OF((deflate_state *s));
  78242. local void bi_flush OF((deflate_state *s));
  78243. local void copy_block OF((deflate_state *s, charf *buf, unsigned len,
  78244. int header));
  78245. #ifdef GEN_TREES_H
  78246. local void gen_trees_header OF((void));
  78247. #endif
  78248. #ifndef DEBUG
  78249. # define send_code(s, c, tree) send_bits(s, tree[c].Code, tree[c].Len)
  78250. /* Send a code of the given tree. c and tree must not have side effects */
  78251. #else /* DEBUG */
  78252. # define send_code(s, c, tree) \
  78253. { if (z_verbose>2) fprintf(stderr,"\ncd %3d ",(c)); \
  78254. send_bits(s, tree[c].Code, tree[c].Len); }
  78255. #endif
  78256. /* ===========================================================================
  78257. * Output a short LSB first on the stream.
  78258. * IN assertion: there is enough room in pendingBuf.
  78259. */
  78260. #define put_short(s, w) { \
  78261. put_byte(s, (uch)((w) & 0xff)); \
  78262. put_byte(s, (uch)((ush)(w) >> 8)); \
  78263. }
  78264. /* ===========================================================================
  78265. * Send a value on a given number of bits.
  78266. * IN assertion: length <= 16 and value fits in length bits.
  78267. */
  78268. #ifdef DEBUG
  78269. local void send_bits OF((deflate_state *s, int value, int length));
  78270. local void send_bits (deflate_state *s, int value, int length)
  78271. {
  78272. Tracevv((stderr," l %2d v %4x ", length, value));
  78273. Assert(length > 0 && length <= 15, "invalid length");
  78274. s->bits_sent += (ulg)length;
  78275. /* If not enough room in bi_buf, use (valid) bits from bi_buf and
  78276. * (16 - bi_valid) bits from value, leaving (width - (16-bi_valid))
  78277. * unused bits in value.
  78278. */
  78279. if (s->bi_valid > (int)Buf_size - length) {
  78280. s->bi_buf |= (value << s->bi_valid);
  78281. put_short(s, s->bi_buf);
  78282. s->bi_buf = (ush)value >> (Buf_size - s->bi_valid);
  78283. s->bi_valid += length - Buf_size;
  78284. } else {
  78285. s->bi_buf |= value << s->bi_valid;
  78286. s->bi_valid += length;
  78287. }
  78288. }
  78289. #else /* !DEBUG */
  78290. #define send_bits(s, value, length) \
  78291. { int len = length;\
  78292. if (s->bi_valid > (int)Buf_size - len) {\
  78293. int val = value;\
  78294. s->bi_buf |= (val << s->bi_valid);\
  78295. put_short(s, s->bi_buf);\
  78296. s->bi_buf = (ush)val >> (Buf_size - s->bi_valid);\
  78297. s->bi_valid += len - Buf_size;\
  78298. } else {\
  78299. s->bi_buf |= (value) << s->bi_valid;\
  78300. s->bi_valid += len;\
  78301. }\
  78302. }
  78303. #endif /* DEBUG */
  78304. /* the arguments must not have side effects */
  78305. /* ===========================================================================
  78306. * Initialize the various 'constant' tables.
  78307. */
  78308. local void tr_static_init()
  78309. {
  78310. #if defined(GEN_TREES_H) || !defined(STDC)
  78311. static int static_init_done = 0;
  78312. int n; /* iterates over tree elements */
  78313. int bits; /* bit counter */
  78314. int length; /* length value */
  78315. int code; /* code value */
  78316. int dist; /* distance index */
  78317. ush bl_count[MAX_BITS+1];
  78318. /* number of codes at each bit length for an optimal tree */
  78319. if (static_init_done) return;
  78320. /* For some embedded targets, global variables are not initialized: */
  78321. static_l_desc.static_tree = static_ltree;
  78322. static_l_desc.extra_bits = extra_lbits;
  78323. static_d_desc.static_tree = static_dtree;
  78324. static_d_desc.extra_bits = extra_dbits;
  78325. static_bl_desc.extra_bits = extra_blbits;
  78326. /* Initialize the mapping length (0..255) -> length code (0..28) */
  78327. length = 0;
  78328. for (code = 0; code < LENGTH_CODES-1; code++) {
  78329. base_length[code] = length;
  78330. for (n = 0; n < (1<<extra_lbits[code]); n++) {
  78331. _length_code[length++] = (uch)code;
  78332. }
  78333. }
  78334. Assert (length == 256, "tr_static_init: length != 256");
  78335. /* Note that the length 255 (match length 258) can be represented
  78336. * in two different ways: code 284 + 5 bits or code 285, so we
  78337. * overwrite length_code[255] to use the best encoding:
  78338. */
  78339. _length_code[length-1] = (uch)code;
  78340. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  78341. dist = 0;
  78342. for (code = 0 ; code < 16; code++) {
  78343. base_dist[code] = dist;
  78344. for (n = 0; n < (1<<extra_dbits[code]); n++) {
  78345. _dist_code[dist++] = (uch)code;
  78346. }
  78347. }
  78348. Assert (dist == 256, "tr_static_init: dist != 256");
  78349. dist >>= 7; /* from now on, all distances are divided by 128 */
  78350. for ( ; code < D_CODES; code++) {
  78351. base_dist[code] = dist << 7;
  78352. for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  78353. _dist_code[256 + dist++] = (uch)code;
  78354. }
  78355. }
  78356. Assert (dist == 256, "tr_static_init: 256+dist != 512");
  78357. /* Construct the codes of the static literal tree */
  78358. for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0;
  78359. n = 0;
  78360. while (n <= 143) static_ltree[n++].Len = 8, bl_count[8]++;
  78361. while (n <= 255) static_ltree[n++].Len = 9, bl_count[9]++;
  78362. while (n <= 279) static_ltree[n++].Len = 7, bl_count[7]++;
  78363. while (n <= 287) static_ltree[n++].Len = 8, bl_count[8]++;
  78364. /* Codes 286 and 287 do not exist, but we must include them in the
  78365. * tree construction to get a canonical Huffman tree (longest code
  78366. * all ones)
  78367. */
  78368. gen_codes((ct_data *)static_ltree, L_CODES+1, bl_count);
  78369. /* The static distance tree is trivial: */
  78370. for (n = 0; n < D_CODES; n++) {
  78371. static_dtree[n].Len = 5;
  78372. static_dtree[n].Code = bi_reverse((unsigned)n, 5);
  78373. }
  78374. static_init_done = 1;
  78375. # ifdef GEN_TREES_H
  78376. gen_trees_header();
  78377. # endif
  78378. #endif /* defined(GEN_TREES_H) || !defined(STDC) */
  78379. }
  78380. /* ===========================================================================
  78381. * Genererate the file trees.h describing the static trees.
  78382. */
  78383. #ifdef GEN_TREES_H
  78384. # ifndef DEBUG
  78385. # include <stdio.h>
  78386. # endif
  78387. # define SEPARATOR(i, last, width) \
  78388. ((i) == (last)? "\n};\n\n" : \
  78389. ((i) % (width) == (width)-1 ? ",\n" : ", "))
  78390. void gen_trees_header()
  78391. {
  78392. FILE *header = fopen("trees.h", "w");
  78393. int i;
  78394. Assert (header != NULL, "Can't open trees.h");
  78395. fprintf(header,
  78396. "/* header created automatically with -DGEN_TREES_H */\n\n");
  78397. fprintf(header, "local const ct_data static_ltree[L_CODES+2] = {\n");
  78398. for (i = 0; i < L_CODES+2; i++) {
  78399. fprintf(header, "{{%3u},{%3u}}%s", static_ltree[i].Code,
  78400. static_ltree[i].Len, SEPARATOR(i, L_CODES+1, 5));
  78401. }
  78402. fprintf(header, "local const ct_data static_dtree[D_CODES] = {\n");
  78403. for (i = 0; i < D_CODES; i++) {
  78404. fprintf(header, "{{%2u},{%2u}}%s", static_dtree[i].Code,
  78405. static_dtree[i].Len, SEPARATOR(i, D_CODES-1, 5));
  78406. }
  78407. fprintf(header, "const uch _dist_code[DIST_CODE_LEN] = {\n");
  78408. for (i = 0; i < DIST_CODE_LEN; i++) {
  78409. fprintf(header, "%2u%s", _dist_code[i],
  78410. SEPARATOR(i, DIST_CODE_LEN-1, 20));
  78411. }
  78412. fprintf(header, "const uch _length_code[MAX_MATCH-MIN_MATCH+1]= {\n");
  78413. for (i = 0; i < MAX_MATCH-MIN_MATCH+1; i++) {
  78414. fprintf(header, "%2u%s", _length_code[i],
  78415. SEPARATOR(i, MAX_MATCH-MIN_MATCH, 20));
  78416. }
  78417. fprintf(header, "local const int base_length[LENGTH_CODES] = {\n");
  78418. for (i = 0; i < LENGTH_CODES; i++) {
  78419. fprintf(header, "%1u%s", base_length[i],
  78420. SEPARATOR(i, LENGTH_CODES-1, 20));
  78421. }
  78422. fprintf(header, "local const int base_dist[D_CODES] = {\n");
  78423. for (i = 0; i < D_CODES; i++) {
  78424. fprintf(header, "%5u%s", base_dist[i],
  78425. SEPARATOR(i, D_CODES-1, 10));
  78426. }
  78427. fclose(header);
  78428. }
  78429. #endif /* GEN_TREES_H */
  78430. /* ===========================================================================
  78431. * Initialize the tree data structures for a new zlib stream.
  78432. */
  78433. void _tr_init(deflate_state *s)
  78434. {
  78435. tr_static_init();
  78436. s->l_desc.dyn_tree = s->dyn_ltree;
  78437. s->l_desc.stat_desc = &static_l_desc;
  78438. s->d_desc.dyn_tree = s->dyn_dtree;
  78439. s->d_desc.stat_desc = &static_d_desc;
  78440. s->bl_desc.dyn_tree = s->bl_tree;
  78441. s->bl_desc.stat_desc = &static_bl_desc;
  78442. s->bi_buf = 0;
  78443. s->bi_valid = 0;
  78444. s->last_eob_len = 8; /* enough lookahead for inflate */
  78445. #ifdef DEBUG
  78446. s->compressed_len = 0L;
  78447. s->bits_sent = 0L;
  78448. #endif
  78449. /* Initialize the first block of the first file: */
  78450. init_block(s);
  78451. }
  78452. /* ===========================================================================
  78453. * Initialize a new block.
  78454. */
  78455. local void init_block (deflate_state *s)
  78456. {
  78457. int n; /* iterates over tree elements */
  78458. /* Initialize the trees. */
  78459. for (n = 0; n < L_CODES; n++) s->dyn_ltree[n].Freq = 0;
  78460. for (n = 0; n < D_CODES; n++) s->dyn_dtree[n].Freq = 0;
  78461. for (n = 0; n < BL_CODES; n++) s->bl_tree[n].Freq = 0;
  78462. s->dyn_ltree[END_BLOCK].Freq = 1;
  78463. s->opt_len = s->static_len = 0L;
  78464. s->last_lit = s->matches = 0;
  78465. }
  78466. #define SMALLEST 1
  78467. /* Index within the heap array of least frequent node in the Huffman tree */
  78468. /* ===========================================================================
  78469. * Remove the smallest element from the heap and recreate the heap with
  78470. * one less element. Updates heap and heap_len.
  78471. */
  78472. #define pqremove(s, tree, top) \
  78473. {\
  78474. top = s->heap[SMALLEST]; \
  78475. s->heap[SMALLEST] = s->heap[s->heap_len--]; \
  78476. pqdownheap(s, tree, SMALLEST); \
  78477. }
  78478. /* ===========================================================================
  78479. * Compares to subtrees, using the tree depth as tie breaker when
  78480. * the subtrees have equal frequency. This minimizes the worst case length.
  78481. */
  78482. #define smaller(tree, n, m, depth) \
  78483. (tree[n].Freq < tree[m].Freq || \
  78484. (tree[n].Freq == tree[m].Freq && depth[n] <= depth[m]))
  78485. /* ===========================================================================
  78486. * Restore the heap property by moving down the tree starting at node k,
  78487. * exchanging a node with the smallest of its two sons if necessary, stopping
  78488. * when the heap property is re-established (each father smaller than its
  78489. * two sons).
  78490. */
  78491. local void pqdownheap (deflate_state *s,
  78492. ct_data *tree, /* the tree to restore */
  78493. int k) /* node to move down */
  78494. {
  78495. int v = s->heap[k];
  78496. int j = k << 1; /* left son of k */
  78497. while (j <= s->heap_len) {
  78498. /* Set j to the smallest of the two sons: */
  78499. if (j < s->heap_len &&
  78500. smaller(tree, s->heap[j+1], s->heap[j], s->depth)) {
  78501. j++;
  78502. }
  78503. /* Exit if v is smaller than both sons */
  78504. if (smaller(tree, v, s->heap[j], s->depth)) break;
  78505. /* Exchange v with the smallest son */
  78506. s->heap[k] = s->heap[j]; k = j;
  78507. /* And continue down the tree, setting j to the left son of k */
  78508. j <<= 1;
  78509. }
  78510. s->heap[k] = v;
  78511. }
  78512. /* ===========================================================================
  78513. * Compute the optimal bit lengths for a tree and update the total bit length
  78514. * for the current block.
  78515. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  78516. * above are the tree nodes sorted by increasing frequency.
  78517. * OUT assertions: the field len is set to the optimal bit length, the
  78518. * array bl_count contains the frequencies for each bit length.
  78519. * The length opt_len is updated; static_len is also updated if stree is
  78520. * not null.
  78521. */
  78522. local void gen_bitlen (deflate_state *s, tree_desc *desc)
  78523. {
  78524. ct_data *tree = desc->dyn_tree;
  78525. int max_code = desc->max_code;
  78526. const ct_data *stree = desc->stat_desc->static_tree;
  78527. const intf *extra = desc->stat_desc->extra_bits;
  78528. int base = desc->stat_desc->extra_base;
  78529. int max_length = desc->stat_desc->max_length;
  78530. int h; /* heap index */
  78531. int n, m; /* iterate over the tree elements */
  78532. int bits; /* bit length */
  78533. int xbits; /* extra bits */
  78534. ush f; /* frequency */
  78535. int overflow = 0; /* number of elements with bit length too large */
  78536. for (bits = 0; bits <= MAX_BITS; bits++) s->bl_count[bits] = 0;
  78537. /* In a first pass, compute the optimal bit lengths (which may
  78538. * overflow in the case of the bit length tree).
  78539. */
  78540. tree[s->heap[s->heap_max]].Len = 0; /* root of the heap */
  78541. for (h = s->heap_max+1; h < HEAP_SIZE; h++) {
  78542. n = s->heap[h];
  78543. bits = tree[tree[n].Dad].Len + 1;
  78544. if (bits > max_length) bits = max_length, overflow++;
  78545. tree[n].Len = (ush)bits;
  78546. /* We overwrite tree[n].Dad which is no longer needed */
  78547. if (n > max_code) continue; /* not a leaf node */
  78548. s->bl_count[bits]++;
  78549. xbits = 0;
  78550. if (n >= base) xbits = extra[n-base];
  78551. f = tree[n].Freq;
  78552. s->opt_len += (ulg)f * (bits + xbits);
  78553. if (stree) s->static_len += (ulg)f * (stree[n].Len + xbits);
  78554. }
  78555. if (overflow == 0) return;
  78556. Trace((stderr,"\nbit length overflow\n"));
  78557. /* This happens for example on obj2 and pic of the Calgary corpus */
  78558. /* Find the first bit length which could increase: */
  78559. do {
  78560. bits = max_length-1;
  78561. while (s->bl_count[bits] == 0) bits--;
  78562. s->bl_count[bits]--; /* move one leaf down the tree */
  78563. s->bl_count[bits+1] += 2; /* move one overflow item as its brother */
  78564. s->bl_count[max_length]--;
  78565. /* The brother of the overflow item also moves one step up,
  78566. * but this does not affect bl_count[max_length]
  78567. */
  78568. overflow -= 2;
  78569. } while (overflow > 0);
  78570. /* Now recompute all bit lengths, scanning in increasing frequency.
  78571. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  78572. * lengths instead of fixing only the wrong ones. This idea is taken
  78573. * from 'ar' written by Haruhiko Okumura.)
  78574. */
  78575. for (bits = max_length; bits != 0; bits--) {
  78576. n = s->bl_count[bits];
  78577. while (n != 0) {
  78578. m = s->heap[--h];
  78579. if (m > max_code) continue;
  78580. if ((unsigned) tree[m].Len != (unsigned) bits) {
  78581. Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  78582. s->opt_len += ((long)bits - (long)tree[m].Len)
  78583. *(long)tree[m].Freq;
  78584. tree[m].Len = (ush)bits;
  78585. }
  78586. n--;
  78587. }
  78588. }
  78589. }
  78590. /* ===========================================================================
  78591. * Generate the codes for a given tree and bit counts (which need not be
  78592. * optimal).
  78593. * IN assertion: the array bl_count contains the bit length statistics for
  78594. * the given tree and the field len is set for all tree elements.
  78595. * OUT assertion: the field code is set for all tree elements of non
  78596. * zero code length.
  78597. */
  78598. local void gen_codes (ct_data *tree, /* the tree to decorate */
  78599. int max_code, /* largest code with non zero frequency */
  78600. ushf *bl_count) /* number of codes at each bit length */
  78601. {
  78602. ush next_code[MAX_BITS+1]; /* next code value for each bit length */
  78603. ush code = 0; /* running code value */
  78604. int bits; /* bit index */
  78605. int n; /* code index */
  78606. /* The distribution counts are first used to generate the code values
  78607. * without bit reversal.
  78608. */
  78609. for (bits = 1; bits <= MAX_BITS; bits++) {
  78610. next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  78611. }
  78612. /* Check that the bit counts in bl_count are consistent. The last code
  78613. * must be all ones.
  78614. */
  78615. Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  78616. "inconsistent bit counts");
  78617. Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  78618. for (n = 0; n <= max_code; n++) {
  78619. int len = tree[n].Len;
  78620. if (len == 0) continue;
  78621. /* Now reverse the bits */
  78622. tree[n].Code = bi_reverse(next_code[len]++, len);
  78623. Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  78624. n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  78625. }
  78626. }
  78627. /* ===========================================================================
  78628. * Construct one Huffman tree and assigns the code bit strings and lengths.
  78629. * Update the total bit length for the current block.
  78630. * IN assertion: the field freq is set for all tree elements.
  78631. * OUT assertions: the fields len and code are set to the optimal bit length
  78632. * and corresponding code. The length opt_len is updated; static_len is
  78633. * also updated if stree is not null. The field max_code is set.
  78634. */
  78635. local void build_tree (deflate_state *s,
  78636. tree_desc *desc) /* the tree descriptor */
  78637. {
  78638. ct_data *tree = desc->dyn_tree;
  78639. const ct_data *stree = desc->stat_desc->static_tree;
  78640. int elems = desc->stat_desc->elems;
  78641. int n, m; /* iterate over heap elements */
  78642. int max_code = -1; /* largest code with non zero frequency */
  78643. int node; /* new node being created */
  78644. /* Construct the initial heap, with least frequent element in
  78645. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  78646. * heap[0] is not used.
  78647. */
  78648. s->heap_len = 0, s->heap_max = HEAP_SIZE;
  78649. for (n = 0; n < elems; n++) {
  78650. if (tree[n].Freq != 0) {
  78651. s->heap[++(s->heap_len)] = max_code = n;
  78652. s->depth[n] = 0;
  78653. } else {
  78654. tree[n].Len = 0;
  78655. }
  78656. }
  78657. /* The pkzip format requires that at least one distance code exists,
  78658. * and that at least one bit should be sent even if there is only one
  78659. * possible code. So to avoid special checks later on we force at least
  78660. * two codes of non zero frequency.
  78661. */
  78662. while (s->heap_len < 2) {
  78663. node = s->heap[++(s->heap_len)] = (max_code < 2 ? ++max_code : 0);
  78664. tree[node].Freq = 1;
  78665. s->depth[node] = 0;
  78666. s->opt_len--; if (stree) s->static_len -= stree[node].Len;
  78667. /* node is 0 or 1 so it does not have extra bits */
  78668. }
  78669. desc->max_code = max_code;
  78670. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  78671. * establish sub-heaps of increasing lengths:
  78672. */
  78673. for (n = s->heap_len/2; n >= 1; n--) pqdownheap(s, tree, n);
  78674. /* Construct the Huffman tree by repeatedly combining the least two
  78675. * frequent nodes.
  78676. */
  78677. node = elems; /* next internal node of the tree */
  78678. do {
  78679. pqremove(s, tree, n); /* n = node of least frequency */
  78680. m = s->heap[SMALLEST]; /* m = node of next least frequency */
  78681. s->heap[--(s->heap_max)] = n; /* keep the nodes sorted by frequency */
  78682. s->heap[--(s->heap_max)] = m;
  78683. /* Create a new node father of n and m */
  78684. tree[node].Freq = tree[n].Freq + tree[m].Freq;
  78685. s->depth[node] = (uch)((s->depth[n] >= s->depth[m] ?
  78686. s->depth[n] : s->depth[m]) + 1);
  78687. tree[n].Dad = tree[m].Dad = (ush)node;
  78688. #ifdef DUMP_BL_TREE
  78689. if (tree == s->bl_tree) {
  78690. fprintf(stderr,"\nnode %d(%d), sons %d(%d) %d(%d)",
  78691. node, tree[node].Freq, n, tree[n].Freq, m, tree[m].Freq);
  78692. }
  78693. #endif
  78694. /* and insert the new node in the heap */
  78695. s->heap[SMALLEST] = node++;
  78696. pqdownheap(s, tree, SMALLEST);
  78697. } while (s->heap_len >= 2);
  78698. s->heap[--(s->heap_max)] = s->heap[SMALLEST];
  78699. /* At this point, the fields freq and dad are set. We can now
  78700. * generate the bit lengths.
  78701. */
  78702. gen_bitlen(s, (tree_desc *)desc);
  78703. /* The field len is now set, we can generate the bit codes */
  78704. gen_codes ((ct_data *)tree, max_code, s->bl_count);
  78705. }
  78706. /* ===========================================================================
  78707. * Scan a literal or distance tree to determine the frequencies of the codes
  78708. * in the bit length tree.
  78709. */
  78710. local void scan_tree (deflate_state *s,
  78711. ct_data *tree, /* the tree to be scanned */
  78712. int max_code) /* and its largest code of non zero frequency */
  78713. {
  78714. int n; /* iterates over all tree elements */
  78715. int prevlen = -1; /* last emitted length */
  78716. int curlen; /* length of current code */
  78717. int nextlen = tree[0].Len; /* length of next code */
  78718. int count = 0; /* repeat count of the current code */
  78719. int max_count = 7; /* max repeat count */
  78720. int min_count = 4; /* min repeat count */
  78721. if (nextlen == 0) max_count = 138, min_count = 3;
  78722. tree[max_code+1].Len = (ush)0xffff; /* guard */
  78723. for (n = 0; n <= max_code; n++) {
  78724. curlen = nextlen; nextlen = tree[n+1].Len;
  78725. if (++count < max_count && curlen == nextlen) {
  78726. continue;
  78727. } else if (count < min_count) {
  78728. s->bl_tree[curlen].Freq += count;
  78729. } else if (curlen != 0) {
  78730. if (curlen != prevlen) s->bl_tree[curlen].Freq++;
  78731. s->bl_tree[REP_3_6].Freq++;
  78732. } else if (count <= 10) {
  78733. s->bl_tree[REPZ_3_10].Freq++;
  78734. } else {
  78735. s->bl_tree[REPZ_11_138].Freq++;
  78736. }
  78737. count = 0; prevlen = curlen;
  78738. if (nextlen == 0) {
  78739. max_count = 138, min_count = 3;
  78740. } else if (curlen == nextlen) {
  78741. max_count = 6, min_count = 3;
  78742. } else {
  78743. max_count = 7, min_count = 4;
  78744. }
  78745. }
  78746. }
  78747. /* ===========================================================================
  78748. * Send a literal or distance tree in compressed form, using the codes in
  78749. * bl_tree.
  78750. */
  78751. local void send_tree (deflate_state *s,
  78752. ct_data *tree, /* the tree to be scanned */
  78753. int max_code) /* and its largest code of non zero frequency */
  78754. {
  78755. int n; /* iterates over all tree elements */
  78756. int prevlen = -1; /* last emitted length */
  78757. int curlen; /* length of current code */
  78758. int nextlen = tree[0].Len; /* length of next code */
  78759. int count = 0; /* repeat count of the current code */
  78760. int max_count = 7; /* max repeat count */
  78761. int min_count = 4; /* min repeat count */
  78762. /* tree[max_code+1].Len = -1; */ /* guard already set */
  78763. if (nextlen == 0) max_count = 138, min_count = 3;
  78764. for (n = 0; n <= max_code; n++) {
  78765. curlen = nextlen; nextlen = tree[n+1].Len;
  78766. if (++count < max_count && curlen == nextlen) {
  78767. continue;
  78768. } else if (count < min_count) {
  78769. do { send_code(s, curlen, s->bl_tree); } while (--count != 0);
  78770. } else if (curlen != 0) {
  78771. if (curlen != prevlen) {
  78772. send_code(s, curlen, s->bl_tree); count--;
  78773. }
  78774. Assert(count >= 3 && count <= 6, " 3_6?");
  78775. send_code(s, REP_3_6, s->bl_tree); send_bits(s, count-3, 2);
  78776. } else if (count <= 10) {
  78777. send_code(s, REPZ_3_10, s->bl_tree); send_bits(s, count-3, 3);
  78778. } else {
  78779. send_code(s, REPZ_11_138, s->bl_tree); send_bits(s, count-11, 7);
  78780. }
  78781. count = 0; prevlen = curlen;
  78782. if (nextlen == 0) {
  78783. max_count = 138, min_count = 3;
  78784. } else if (curlen == nextlen) {
  78785. max_count = 6, min_count = 3;
  78786. } else {
  78787. max_count = 7, min_count = 4;
  78788. }
  78789. }
  78790. }
  78791. /* ===========================================================================
  78792. * Construct the Huffman tree for the bit lengths and return the index in
  78793. * bl_order of the last bit length code to send.
  78794. */
  78795. local int build_bl_tree (deflate_state *s)
  78796. {
  78797. int max_blindex; /* index of last bit length code of non zero freq */
  78798. /* Determine the bit length frequencies for literal and distance trees */
  78799. scan_tree(s, (ct_data *)s->dyn_ltree, s->l_desc.max_code);
  78800. scan_tree(s, (ct_data *)s->dyn_dtree, s->d_desc.max_code);
  78801. /* Build the bit length tree: */
  78802. build_tree(s, (tree_desc *)(&(s->bl_desc)));
  78803. /* opt_len now includes the length of the tree representations, except
  78804. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  78805. */
  78806. /* Determine the number of bit length codes to send. The pkzip format
  78807. * requires that at least 4 bit length codes be sent. (appnote.txt says
  78808. * 3 but the actual value used is 4.)
  78809. */
  78810. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  78811. if (s->bl_tree[bl_order[max_blindex]].Len != 0) break;
  78812. }
  78813. /* Update opt_len to include the bit length tree and counts */
  78814. s->opt_len += 3*(max_blindex+1) + 5+5+4;
  78815. Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  78816. s->opt_len, s->static_len));
  78817. return max_blindex;
  78818. }
  78819. /* ===========================================================================
  78820. * Send the header for a block using dynamic Huffman trees: the counts, the
  78821. * lengths of the bit length codes, the literal tree and the distance tree.
  78822. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  78823. */
  78824. local void send_all_trees (deflate_state *s,
  78825. int lcodes, int dcodes, int blcodes) /* number of codes for each tree */
  78826. {
  78827. int rank; /* index in bl_order */
  78828. Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  78829. Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  78830. "too many codes");
  78831. Tracev((stderr, "\nbl counts: "));
  78832. send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  78833. send_bits(s, dcodes-1, 5);
  78834. send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
  78835. for (rank = 0; rank < blcodes; rank++) {
  78836. Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  78837. send_bits(s, s->bl_tree[bl_order[rank]].Len, 3);
  78838. }
  78839. Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  78840. send_tree(s, (ct_data *)s->dyn_ltree, lcodes-1); /* literal tree */
  78841. Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  78842. send_tree(s, (ct_data *)s->dyn_dtree, dcodes-1); /* distance tree */
  78843. Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  78844. }
  78845. /* ===========================================================================
  78846. * Send a stored block
  78847. */
  78848. void _tr_stored_block (deflate_state *s, charf *buf, ulg stored_len, int eof)
  78849. {
  78850. send_bits(s, (STORED_BLOCK<<1)+eof, 3); /* send block type */
  78851. #ifdef DEBUG
  78852. s->compressed_len = (s->compressed_len + 3 + 7) & (ulg)~7L;
  78853. s->compressed_len += (stored_len + 4) << 3;
  78854. #endif
  78855. copy_block(s, buf, (unsigned)stored_len, 1); /* with header */
  78856. }
  78857. /* ===========================================================================
  78858. * Send one empty static block to give enough lookahead for inflate.
  78859. * This takes 10 bits, of which 7 may remain in the bit buffer.
  78860. * The current inflate code requires 9 bits of lookahead. If the
  78861. * last two codes for the previous block (real code plus EOB) were coded
  78862. * on 5 bits or less, inflate may have only 5+3 bits of lookahead to decode
  78863. * the last real code. In this case we send two empty static blocks instead
  78864. * of one. (There are no problems if the previous block is stored or fixed.)
  78865. * To simplify the code, we assume the worst case of last real code encoded
  78866. * on one bit only.
  78867. */
  78868. void _tr_align (deflate_state *s)
  78869. {
  78870. send_bits(s, STATIC_TREES<<1, 3);
  78871. send_code(s, END_BLOCK, static_ltree);
  78872. #ifdef DEBUG
  78873. s->compressed_len += 10L; /* 3 for block type, 7 for EOB */
  78874. #endif
  78875. bi_flush(s);
  78876. /* Of the 10 bits for the empty block, we have already sent
  78877. * (10 - bi_valid) bits. The lookahead for the last real code (before
  78878. * the EOB of the previous block) was thus at least one plus the length
  78879. * of the EOB plus what we have just sent of the empty static block.
  78880. */
  78881. if (1 + s->last_eob_len + 10 - s->bi_valid < 9) {
  78882. send_bits(s, STATIC_TREES<<1, 3);
  78883. send_code(s, END_BLOCK, static_ltree);
  78884. #ifdef DEBUG
  78885. s->compressed_len += 10L;
  78886. #endif
  78887. bi_flush(s);
  78888. }
  78889. s->last_eob_len = 7;
  78890. }
  78891. /* ===========================================================================
  78892. * Determine the best encoding for the current block: dynamic trees, static
  78893. * trees or store, and output the encoded block to the zip file.
  78894. */
  78895. void _tr_flush_block (deflate_state *s,
  78896. charf *buf, /* input block, or NULL if too old */
  78897. ulg stored_len, /* length of input block */
  78898. int eof) /* true if this is the last block for a file */
  78899. {
  78900. ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  78901. int max_blindex = 0; /* index of last bit length code of non zero freq */
  78902. /* Build the Huffman trees unless a stored block is forced */
  78903. if (s->level > 0) {
  78904. /* Check if the file is binary or text */
  78905. if (stored_len > 0 && s->strm->data_type == Z_UNKNOWN)
  78906. set_data_type(s);
  78907. /* Construct the literal and distance trees */
  78908. build_tree(s, (tree_desc *)(&(s->l_desc)));
  78909. Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  78910. s->static_len));
  78911. build_tree(s, (tree_desc *)(&(s->d_desc)));
  78912. Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  78913. s->static_len));
  78914. /* At this point, opt_len and static_len are the total bit lengths of
  78915. * the compressed block data, excluding the tree representations.
  78916. */
  78917. /* Build the bit length tree for the above two trees, and get the index
  78918. * in bl_order of the last bit length code to send.
  78919. */
  78920. max_blindex = build_bl_tree(s);
  78921. /* Determine the best encoding. Compute the block lengths in bytes. */
  78922. opt_lenb = (s->opt_len+3+7)>>3;
  78923. static_lenb = (s->static_len+3+7)>>3;
  78924. Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  78925. opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  78926. s->last_lit));
  78927. if (static_lenb <= opt_lenb) opt_lenb = static_lenb;
  78928. } else {
  78929. Assert(buf != (char*)0, "lost buf");
  78930. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  78931. }
  78932. #ifdef FORCE_STORED
  78933. if (buf != (char*)0) { /* force stored block */
  78934. #else
  78935. if (stored_len+4 <= opt_lenb && buf != (char*)0) {
  78936. /* 4: two words for the lengths */
  78937. #endif
  78938. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  78939. * Otherwise we can't have processed more than WSIZE input bytes since
  78940. * the last block flush, because compression would have been
  78941. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  78942. * transform a block into a stored block.
  78943. */
  78944. _tr_stored_block(s, buf, stored_len, eof);
  78945. #ifdef FORCE_STATIC
  78946. } else if (static_lenb >= 0) { /* force static trees */
  78947. #else
  78948. } else if (s->strategy == Z_FIXED || static_lenb == opt_lenb) {
  78949. #endif
  78950. send_bits(s, (STATIC_TREES<<1)+eof, 3);
  78951. compress_block(s, (ct_data *)static_ltree, (ct_data *)static_dtree);
  78952. #ifdef DEBUG
  78953. s->compressed_len += 3 + s->static_len;
  78954. #endif
  78955. } else {
  78956. send_bits(s, (DYN_TREES<<1)+eof, 3);
  78957. send_all_trees(s, s->l_desc.max_code+1, s->d_desc.max_code+1,
  78958. max_blindex+1);
  78959. compress_block(s, (ct_data *)s->dyn_ltree, (ct_data *)s->dyn_dtree);
  78960. #ifdef DEBUG
  78961. s->compressed_len += 3 + s->opt_len;
  78962. #endif
  78963. }
  78964. Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  78965. /* The above check is made mod 2^32, for files larger than 512 MB
  78966. * and uLong implemented on 32 bits.
  78967. */
  78968. init_block(s);
  78969. if (eof) {
  78970. bi_windup(s);
  78971. #ifdef DEBUG
  78972. s->compressed_len += 7; /* align on byte boundary */
  78973. #endif
  78974. }
  78975. Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  78976. s->compressed_len-7*eof));
  78977. }
  78978. /* ===========================================================================
  78979. * Save the match info and tally the frequency counts. Return true if
  78980. * the current block must be flushed.
  78981. */
  78982. int _tr_tally (deflate_state *s,
  78983. unsigned dist, /* distance of matched string */
  78984. unsigned lc) /* match length-MIN_MATCH or unmatched char (if dist==0) */
  78985. {
  78986. s->d_buf[s->last_lit] = (ush)dist;
  78987. s->l_buf[s->last_lit++] = (uch)lc;
  78988. if (dist == 0) {
  78989. /* lc is the unmatched char */
  78990. s->dyn_ltree[lc].Freq++;
  78991. } else {
  78992. s->matches++;
  78993. /* Here, lc is the match length - MIN_MATCH */
  78994. dist--; /* dist = match distance - 1 */
  78995. Assert((ush)dist < (ush)MAX_DIST(s) &&
  78996. (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  78997. (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  78998. s->dyn_ltree[_length_code[lc]+LITERALS+1].Freq++;
  78999. s->dyn_dtree[d_code(dist)].Freq++;
  79000. }
  79001. #ifdef TRUNCATE_BLOCK
  79002. /* Try to guess if it is profitable to stop the current block here */
  79003. if ((s->last_lit & 0x1fff) == 0 && s->level > 2) {
  79004. /* Compute an upper bound for the compressed length */
  79005. ulg out_length = (ulg)s->last_lit*8L;
  79006. ulg in_length = (ulg)((long)s->strstart - s->block_start);
  79007. int dcode;
  79008. for (dcode = 0; dcode < D_CODES; dcode++) {
  79009. out_length += (ulg)s->dyn_dtree[dcode].Freq *
  79010. (5L+extra_dbits[dcode]);
  79011. }
  79012. out_length >>= 3;
  79013. Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  79014. s->last_lit, in_length, out_length,
  79015. 100L - out_length*100L/in_length));
  79016. if (s->matches < s->last_lit/2 && out_length < in_length/2) return 1;
  79017. }
  79018. #endif
  79019. return (s->last_lit == s->lit_bufsize-1);
  79020. /* We avoid equality with lit_bufsize because of wraparound at 64K
  79021. * on 16 bit machines and because stored blocks are restricted to
  79022. * 64K-1 bytes.
  79023. */
  79024. }
  79025. /* ===========================================================================
  79026. * Send the block data compressed using the given Huffman trees
  79027. */
  79028. local void compress_block (deflate_state *s,
  79029. ct_data *ltree, /* literal tree */
  79030. ct_data *dtree) /* distance tree */
  79031. {
  79032. unsigned dist; /* distance of matched string */
  79033. int lc; /* match length or unmatched char (if dist == 0) */
  79034. unsigned lx = 0; /* running index in l_buf */
  79035. unsigned code; /* the code to send */
  79036. int extra; /* number of extra bits to send */
  79037. if (s->last_lit != 0) do {
  79038. dist = s->d_buf[lx];
  79039. lc = s->l_buf[lx++];
  79040. if (dist == 0) {
  79041. send_code(s, lc, ltree); /* send a literal byte */
  79042. Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  79043. } else {
  79044. /* Here, lc is the match length - MIN_MATCH */
  79045. code = _length_code[lc];
  79046. send_code(s, code+LITERALS+1, ltree); /* send the length code */
  79047. extra = extra_lbits[code];
  79048. if (extra != 0) {
  79049. lc -= base_length[code];
  79050. send_bits(s, lc, extra); /* send the extra length bits */
  79051. }
  79052. dist--; /* dist is now the match distance - 1 */
  79053. code = d_code(dist);
  79054. Assert (code < D_CODES, "bad d_code");
  79055. send_code(s, code, dtree); /* send the distance code */
  79056. extra = extra_dbits[code];
  79057. if (extra != 0) {
  79058. dist -= base_dist[code];
  79059. send_bits(s, dist, extra); /* send the extra distance bits */
  79060. }
  79061. } /* literal or match pair ? */
  79062. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  79063. Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  79064. "pendingBuf overflow");
  79065. } while (lx < s->last_lit);
  79066. send_code(s, END_BLOCK, ltree);
  79067. s->last_eob_len = ltree[END_BLOCK].Len;
  79068. }
  79069. /* ===========================================================================
  79070. * Set the data type to BINARY or TEXT, using a crude approximation:
  79071. * set it to Z_TEXT if all symbols are either printable characters (33 to 255)
  79072. * or white spaces (9 to 13, or 32); or set it to Z_BINARY otherwise.
  79073. * IN assertion: the fields Freq of dyn_ltree are set.
  79074. */
  79075. local void set_data_type (deflate_state *s)
  79076. {
  79077. int n;
  79078. for (n = 0; n < 9; n++)
  79079. if (s->dyn_ltree[n].Freq != 0)
  79080. break;
  79081. if (n == 9)
  79082. for (n = 14; n < 32; n++)
  79083. if (s->dyn_ltree[n].Freq != 0)
  79084. break;
  79085. s->strm->data_type = (n == 32) ? Z_TEXT : Z_BINARY;
  79086. }
  79087. /* ===========================================================================
  79088. * Reverse the first len bits of a code, using straightforward code (a faster
  79089. * method would use a table)
  79090. * IN assertion: 1 <= len <= 15
  79091. */
  79092. local unsigned bi_reverse (unsigned code, int len)
  79093. {
  79094. register unsigned res = 0;
  79095. do {
  79096. res |= code & 1;
  79097. code >>= 1, res <<= 1;
  79098. } while (--len > 0);
  79099. return res >> 1;
  79100. }
  79101. /* ===========================================================================
  79102. * Flush the bit buffer, keeping at most 7 bits in it.
  79103. */
  79104. local void bi_flush (deflate_state *s)
  79105. {
  79106. if (s->bi_valid == 16) {
  79107. put_short(s, s->bi_buf);
  79108. s->bi_buf = 0;
  79109. s->bi_valid = 0;
  79110. } else if (s->bi_valid >= 8) {
  79111. put_byte(s, (Byte)s->bi_buf);
  79112. s->bi_buf >>= 8;
  79113. s->bi_valid -= 8;
  79114. }
  79115. }
  79116. /* ===========================================================================
  79117. * Flush the bit buffer and align the output on a byte boundary
  79118. */
  79119. local void bi_windup (deflate_state *s)
  79120. {
  79121. if (s->bi_valid > 8) {
  79122. put_short(s, s->bi_buf);
  79123. } else if (s->bi_valid > 0) {
  79124. put_byte(s, (Byte)s->bi_buf);
  79125. }
  79126. s->bi_buf = 0;
  79127. s->bi_valid = 0;
  79128. #ifdef DEBUG
  79129. s->bits_sent = (s->bits_sent+7) & ~7;
  79130. #endif
  79131. }
  79132. /* ===========================================================================
  79133. * Copy a stored block, storing first the length and its
  79134. * one's complement if requested.
  79135. */
  79136. local void copy_block(deflate_state *s,
  79137. charf *buf, /* the input data */
  79138. unsigned len, /* its length */
  79139. int header) /* true if block header must be written */
  79140. {
  79141. bi_windup(s); /* align on byte boundary */
  79142. s->last_eob_len = 8; /* enough lookahead for inflate */
  79143. if (header) {
  79144. put_short(s, (ush)len);
  79145. put_short(s, (ush)~len);
  79146. #ifdef DEBUG
  79147. s->bits_sent += 2*16;
  79148. #endif
  79149. }
  79150. #ifdef DEBUG
  79151. s->bits_sent += (ulg)len<<3;
  79152. #endif
  79153. while (len--) {
  79154. put_byte(s, *buf++);
  79155. }
  79156. }
  79157. /********* End of inlined file: trees.c *********/
  79158. /********* Start of inlined file: uncompr.c *********/
  79159. /* @(#) $Id: uncompr.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  79160. #define ZLIB_INTERNAL
  79161. /* ===========================================================================
  79162. Decompresses the source buffer into the destination buffer. sourceLen is
  79163. the byte length of the source buffer. Upon entry, destLen is the total
  79164. size of the destination buffer, which must be large enough to hold the
  79165. entire uncompressed data. (The size of the uncompressed data must have
  79166. been saved previously by the compressor and transmitted to the decompressor
  79167. by some mechanism outside the scope of this compression library.)
  79168. Upon exit, destLen is the actual size of the compressed buffer.
  79169. This function can be used to decompress a whole file at once if the
  79170. input file is mmap'ed.
  79171. uncompress returns Z_OK if success, Z_MEM_ERROR if there was not
  79172. enough memory, Z_BUF_ERROR if there was not enough room in the output
  79173. buffer, or Z_DATA_ERROR if the input data was corrupted.
  79174. */
  79175. int ZEXPORT uncompress (Bytef *dest,
  79176. uLongf *destLen,
  79177. const Bytef *source,
  79178. uLong sourceLen)
  79179. {
  79180. z_stream stream;
  79181. int err;
  79182. stream.next_in = (Bytef*)source;
  79183. stream.avail_in = (uInt)sourceLen;
  79184. /* Check for source > 64K on 16-bit machine: */
  79185. if ((uLong)stream.avail_in != sourceLen) return Z_BUF_ERROR;
  79186. stream.next_out = dest;
  79187. stream.avail_out = (uInt)*destLen;
  79188. if ((uLong)stream.avail_out != *destLen) return Z_BUF_ERROR;
  79189. stream.zalloc = (alloc_func)0;
  79190. stream.zfree = (free_func)0;
  79191. err = inflateInit(&stream);
  79192. if (err != Z_OK) return err;
  79193. err = inflate(&stream, Z_FINISH);
  79194. if (err != Z_STREAM_END) {
  79195. inflateEnd(&stream);
  79196. if (err == Z_NEED_DICT || (err == Z_BUF_ERROR && stream.avail_in == 0))
  79197. return Z_DATA_ERROR;
  79198. return err;
  79199. }
  79200. *destLen = stream.total_out;
  79201. err = inflateEnd(&stream);
  79202. return err;
  79203. }
  79204. /********* End of inlined file: uncompr.c *********/
  79205. /********* Start of inlined file: zutil.c *********/
  79206. /* @(#) $Id: zutil.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  79207. #ifndef NO_DUMMY_DECL
  79208. struct internal_state {int dummy;}; /* for buggy compilers */
  79209. #endif
  79210. const char * const z_errmsg[10] = {
  79211. "need dictionary", /* Z_NEED_DICT 2 */
  79212. "stream end", /* Z_STREAM_END 1 */
  79213. "", /* Z_OK 0 */
  79214. "file error", /* Z_ERRNO (-1) */
  79215. "stream error", /* Z_STREAM_ERROR (-2) */
  79216. "data error", /* Z_DATA_ERROR (-3) */
  79217. "insufficient memory", /* Z_MEM_ERROR (-4) */
  79218. "buffer error", /* Z_BUF_ERROR (-5) */
  79219. "incompatible version",/* Z_VERSION_ERROR (-6) */
  79220. ""};
  79221. /*const char * ZEXPORT zlibVersion()
  79222. {
  79223. return ZLIB_VERSION;
  79224. }
  79225. uLong ZEXPORT zlibCompileFlags()
  79226. {
  79227. uLong flags;
  79228. flags = 0;
  79229. switch (sizeof(uInt)) {
  79230. case 2: break;
  79231. case 4: flags += 1; break;
  79232. case 8: flags += 2; break;
  79233. default: flags += 3;
  79234. }
  79235. switch (sizeof(uLong)) {
  79236. case 2: break;
  79237. case 4: flags += 1 << 2; break;
  79238. case 8: flags += 2 << 2; break;
  79239. default: flags += 3 << 2;
  79240. }
  79241. switch (sizeof(voidpf)) {
  79242. case 2: break;
  79243. case 4: flags += 1 << 4; break;
  79244. case 8: flags += 2 << 4; break;
  79245. default: flags += 3 << 4;
  79246. }
  79247. switch (sizeof(z_off_t)) {
  79248. case 2: break;
  79249. case 4: flags += 1 << 6; break;
  79250. case 8: flags += 2 << 6; break;
  79251. default: flags += 3 << 6;
  79252. }
  79253. #ifdef DEBUG
  79254. flags += 1 << 8;
  79255. #endif
  79256. #if defined(ASMV) || defined(ASMINF)
  79257. flags += 1 << 9;
  79258. #endif
  79259. #ifdef ZLIB_WINAPI
  79260. flags += 1 << 10;
  79261. #endif
  79262. #ifdef BUILDFIXED
  79263. flags += 1 << 12;
  79264. #endif
  79265. #ifdef DYNAMIC_CRC_TABLE
  79266. flags += 1 << 13;
  79267. #endif
  79268. #ifdef NO_GZCOMPRESS
  79269. flags += 1L << 16;
  79270. #endif
  79271. #ifdef NO_GZIP
  79272. flags += 1L << 17;
  79273. #endif
  79274. #ifdef PKZIP_BUG_WORKAROUND
  79275. flags += 1L << 20;
  79276. #endif
  79277. #ifdef FASTEST
  79278. flags += 1L << 21;
  79279. #endif
  79280. #ifdef STDC
  79281. # ifdef NO_vsnprintf
  79282. flags += 1L << 25;
  79283. # ifdef HAS_vsprintf_void
  79284. flags += 1L << 26;
  79285. # endif
  79286. # else
  79287. # ifdef HAS_vsnprintf_void
  79288. flags += 1L << 26;
  79289. # endif
  79290. # endif
  79291. #else
  79292. flags += 1L << 24;
  79293. # ifdef NO_snprintf
  79294. flags += 1L << 25;
  79295. # ifdef HAS_sprintf_void
  79296. flags += 1L << 26;
  79297. # endif
  79298. # else
  79299. # ifdef HAS_snprintf_void
  79300. flags += 1L << 26;
  79301. # endif
  79302. # endif
  79303. #endif
  79304. return flags;
  79305. }*/
  79306. #ifdef DEBUG
  79307. # ifndef verbose
  79308. # define verbose 0
  79309. # endif
  79310. int z_verbose = verbose;
  79311. void z_error (char *m)
  79312. {
  79313. fprintf(stderr, "%s\n", m);
  79314. exit(1);
  79315. }
  79316. #endif
  79317. /* exported to allow conversion of error code to string for compress() and
  79318. * uncompress()
  79319. */
  79320. const char * ZEXPORT zError(int err)
  79321. {
  79322. return ERR_MSG(err);
  79323. }
  79324. #if defined(_WIN32_WCE)
  79325. /* The Microsoft C Run-Time Library for Windows CE doesn't have
  79326. * errno. We define it as a global variable to simplify porting.
  79327. * Its value is always 0 and should not be used.
  79328. */
  79329. int errno = 0;
  79330. #endif
  79331. #ifndef HAVE_MEMCPY
  79332. void zmemcpy(dest, source, len)
  79333. Bytef* dest;
  79334. const Bytef* source;
  79335. uInt len;
  79336. {
  79337. if (len == 0) return;
  79338. do {
  79339. *dest++ = *source++; /* ??? to be unrolled */
  79340. } while (--len != 0);
  79341. }
  79342. int zmemcmp(s1, s2, len)
  79343. const Bytef* s1;
  79344. const Bytef* s2;
  79345. uInt len;
  79346. {
  79347. uInt j;
  79348. for (j = 0; j < len; j++) {
  79349. if (s1[j] != s2[j]) return 2*(s1[j] > s2[j])-1;
  79350. }
  79351. return 0;
  79352. }
  79353. void zmemzero(dest, len)
  79354. Bytef* dest;
  79355. uInt len;
  79356. {
  79357. if (len == 0) return;
  79358. do {
  79359. *dest++ = 0; /* ??? to be unrolled */
  79360. } while (--len != 0);
  79361. }
  79362. #endif
  79363. #ifdef SYS16BIT
  79364. #ifdef __TURBOC__
  79365. /* Turbo C in 16-bit mode */
  79366. # define MY_ZCALLOC
  79367. /* Turbo C malloc() does not allow dynamic allocation of 64K bytes
  79368. * and farmalloc(64K) returns a pointer with an offset of 8, so we
  79369. * must fix the pointer. Warning: the pointer must be put back to its
  79370. * original form in order to free it, use zcfree().
  79371. */
  79372. #define MAX_PTR 10
  79373. /* 10*64K = 640K */
  79374. local int next_ptr = 0;
  79375. typedef struct ptr_table_s {
  79376. voidpf org_ptr;
  79377. voidpf new_ptr;
  79378. } ptr_table;
  79379. local ptr_table table[MAX_PTR];
  79380. /* This table is used to remember the original form of pointers
  79381. * to large buffers (64K). Such pointers are normalized with a zero offset.
  79382. * Since MSDOS is not a preemptive multitasking OS, this table is not
  79383. * protected from concurrent access. This hack doesn't work anyway on
  79384. * a protected system like OS/2. Use Microsoft C instead.
  79385. */
  79386. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  79387. {
  79388. voidpf buf = opaque; /* just to make some compilers happy */
  79389. ulg bsize = (ulg)items*size;
  79390. /* If we allocate less than 65520 bytes, we assume that farmalloc
  79391. * will return a usable pointer which doesn't have to be normalized.
  79392. */
  79393. if (bsize < 65520L) {
  79394. buf = farmalloc(bsize);
  79395. if (*(ush*)&buf != 0) return buf;
  79396. } else {
  79397. buf = farmalloc(bsize + 16L);
  79398. }
  79399. if (buf == NULL || next_ptr >= MAX_PTR) return NULL;
  79400. table[next_ptr].org_ptr = buf;
  79401. /* Normalize the pointer to seg:0 */
  79402. *((ush*)&buf+1) += ((ush)((uch*)buf-0) + 15) >> 4;
  79403. *(ush*)&buf = 0;
  79404. table[next_ptr++].new_ptr = buf;
  79405. return buf;
  79406. }
  79407. void zcfree (voidpf opaque, voidpf ptr)
  79408. {
  79409. int n;
  79410. if (*(ush*)&ptr != 0) { /* object < 64K */
  79411. farfree(ptr);
  79412. return;
  79413. }
  79414. /* Find the original pointer */
  79415. for (n = 0; n < next_ptr; n++) {
  79416. if (ptr != table[n].new_ptr) continue;
  79417. farfree(table[n].org_ptr);
  79418. while (++n < next_ptr) {
  79419. table[n-1] = table[n];
  79420. }
  79421. next_ptr--;
  79422. return;
  79423. }
  79424. ptr = opaque; /* just to make some compilers happy */
  79425. Assert(0, "zcfree: ptr not found");
  79426. }
  79427. #endif /* __TURBOC__ */
  79428. #ifdef M_I86
  79429. /* Microsoft C in 16-bit mode */
  79430. # define MY_ZCALLOC
  79431. #if (!defined(_MSC_VER) || (_MSC_VER <= 600))
  79432. # define _halloc halloc
  79433. # define _hfree hfree
  79434. #endif
  79435. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  79436. {
  79437. if (opaque) opaque = 0; /* to make compiler happy */
  79438. return _halloc((long)items, size);
  79439. }
  79440. void zcfree (voidpf opaque, voidpf ptr)
  79441. {
  79442. if (opaque) opaque = 0; /* to make compiler happy */
  79443. _hfree(ptr);
  79444. }
  79445. #endif /* M_I86 */
  79446. #endif /* SYS16BIT */
  79447. #ifndef MY_ZCALLOC /* Any system without a special alloc function */
  79448. #ifndef STDC
  79449. extern voidp malloc OF((uInt size));
  79450. extern voidp calloc OF((uInt items, uInt size));
  79451. extern void free OF((voidpf ptr));
  79452. #endif
  79453. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  79454. {
  79455. if (opaque) items += size - size; /* make compiler happy */
  79456. return sizeof(uInt) > 2 ? (voidpf)malloc(items * size) :
  79457. (voidpf)calloc(items, size);
  79458. }
  79459. void zcfree (voidpf opaque, voidpf ptr)
  79460. {
  79461. free(ptr);
  79462. if (opaque) return; /* make compiler happy */
  79463. }
  79464. #endif /* MY_ZCALLOC */
  79465. /********* End of inlined file: zutil.c *********/
  79466. }
  79467. }
  79468. #if JUCE_MSVC
  79469. #pragma warning (pop)
  79470. #endif
  79471. BEGIN_JUCE_NAMESPACE
  79472. using namespace zlibNamespace;
  79473. // internal helper object that holds the zlib structures so they don't have to be
  79474. // included publicly.
  79475. class GZIPDecompressHelper
  79476. {
  79477. private:
  79478. z_stream* stream;
  79479. uint8* data;
  79480. int dataSize;
  79481. public:
  79482. bool finished, needsDictionary, error;
  79483. GZIPDecompressHelper (const bool noWrap) throw()
  79484. : data (0),
  79485. dataSize (0),
  79486. finished (false),
  79487. needsDictionary (false),
  79488. error (false)
  79489. {
  79490. stream = (z_stream*) juce_calloc (sizeof (z_stream));
  79491. if (inflateInit2 (stream, (noWrap) ? -MAX_WBITS
  79492. : MAX_WBITS) != Z_OK)
  79493. {
  79494. juce_free (stream);
  79495. stream = 0;
  79496. error = true;
  79497. finished = true;
  79498. }
  79499. }
  79500. ~GZIPDecompressHelper() throw()
  79501. {
  79502. if (stream != 0)
  79503. {
  79504. inflateEnd (stream);
  79505. juce_free (stream);
  79506. }
  79507. }
  79508. bool needsInput() const throw() { return dataSize <= 0; }
  79509. int getTotalOut() const throw() { return (stream != 0) ? stream->total_out : 0; }
  79510. void setInput (uint8* const data_, const int size) throw()
  79511. {
  79512. data = data_;
  79513. dataSize = size;
  79514. }
  79515. int doNextBlock (uint8* const dest, const int destSize) throw()
  79516. {
  79517. if (stream != 0 && data != 0 && ! finished)
  79518. {
  79519. stream->next_in = data;
  79520. stream->next_out = dest;
  79521. stream->avail_in = dataSize;
  79522. stream->avail_out = destSize;
  79523. switch (inflate (stream, Z_PARTIAL_FLUSH))
  79524. {
  79525. case Z_STREAM_END:
  79526. finished = true;
  79527. // deliberate fall-through
  79528. case Z_OK:
  79529. data += dataSize - stream->avail_in;
  79530. dataSize = stream->avail_in;
  79531. return destSize - stream->avail_out;
  79532. case Z_NEED_DICT:
  79533. needsDictionary = true;
  79534. data += dataSize - stream->avail_in;
  79535. dataSize = stream->avail_in;
  79536. break;
  79537. case Z_DATA_ERROR:
  79538. case Z_MEM_ERROR:
  79539. error = true;
  79540. default:
  79541. break;
  79542. }
  79543. }
  79544. return 0;
  79545. }
  79546. };
  79547. const int gzipDecompBufferSize = 32768;
  79548. GZIPDecompressorInputStream::GZIPDecompressorInputStream (InputStream* const sourceStream_,
  79549. const bool deleteSourceWhenDestroyed_,
  79550. const bool noWrap_,
  79551. const int64 uncompressedStreamLength_)
  79552. : sourceStream (sourceStream_),
  79553. uncompressedStreamLength (uncompressedStreamLength_),
  79554. deleteSourceWhenDestroyed (deleteSourceWhenDestroyed_),
  79555. noWrap (noWrap_),
  79556. isEof (false),
  79557. activeBufferSize (0),
  79558. originalSourcePos (sourceStream_->getPosition())
  79559. {
  79560. buffer = (uint8*) juce_malloc (gzipDecompBufferSize);
  79561. helper = new GZIPDecompressHelper (noWrap_);
  79562. }
  79563. GZIPDecompressorInputStream::~GZIPDecompressorInputStream()
  79564. {
  79565. juce_free (buffer);
  79566. if (deleteSourceWhenDestroyed)
  79567. delete sourceStream;
  79568. GZIPDecompressHelper* const h = (GZIPDecompressHelper*) helper;
  79569. delete h;
  79570. }
  79571. int64 GZIPDecompressorInputStream::getTotalLength()
  79572. {
  79573. return uncompressedStreamLength;
  79574. }
  79575. int GZIPDecompressorInputStream::read (void* destBuffer, int howMany)
  79576. {
  79577. GZIPDecompressHelper* const h = (GZIPDecompressHelper*) helper;
  79578. if ((howMany > 0) && ! isEof)
  79579. {
  79580. jassert (destBuffer != 0);
  79581. if (destBuffer != 0)
  79582. {
  79583. int numRead = 0;
  79584. uint8* d = (uint8*) destBuffer;
  79585. while (! h->error)
  79586. {
  79587. const int n = h->doNextBlock (d, howMany);
  79588. if (n == 0)
  79589. {
  79590. if (h->finished || h->needsDictionary)
  79591. {
  79592. isEof = true;
  79593. return numRead;
  79594. }
  79595. if (h->needsInput())
  79596. {
  79597. activeBufferSize = sourceStream->read (buffer, gzipDecompBufferSize);
  79598. if (activeBufferSize > 0)
  79599. {
  79600. h->setInput ((uint8*) buffer, activeBufferSize);
  79601. }
  79602. else
  79603. {
  79604. isEof = true;
  79605. return numRead;
  79606. }
  79607. }
  79608. }
  79609. else
  79610. {
  79611. numRead += n;
  79612. howMany -= n;
  79613. d += n;
  79614. if (howMany <= 0)
  79615. return numRead;
  79616. }
  79617. }
  79618. }
  79619. }
  79620. return 0;
  79621. }
  79622. bool GZIPDecompressorInputStream::isExhausted()
  79623. {
  79624. const GZIPDecompressHelper* const h = (GZIPDecompressHelper*) helper;
  79625. return h->error || isEof;
  79626. }
  79627. int64 GZIPDecompressorInputStream::getPosition()
  79628. {
  79629. const GZIPDecompressHelper* const h = (GZIPDecompressHelper*) helper;
  79630. return h->getTotalOut() + activeBufferSize;
  79631. }
  79632. bool GZIPDecompressorInputStream::setPosition (int64 newPos)
  79633. {
  79634. const int64 currentPos = getPosition();
  79635. if (newPos != currentPos)
  79636. {
  79637. // reset the stream and start again..
  79638. GZIPDecompressHelper* const h = (GZIPDecompressHelper*) helper;
  79639. delete h;
  79640. isEof = false;
  79641. activeBufferSize = 0;
  79642. helper = new GZIPDecompressHelper (noWrap);
  79643. sourceStream->setPosition (originalSourcePos);
  79644. skipNextBytes (newPos);
  79645. }
  79646. return true;
  79647. }
  79648. END_JUCE_NAMESPACE
  79649. /********* End of inlined file: juce_GZIPDecompressorInputStream.cpp *********/
  79650. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  79651. /********* Start of inlined file: juce_FlacAudioFormat.cpp *********/
  79652. #ifdef _MSC_VER
  79653. #include <windows.h>
  79654. #endif
  79655. #if JUCE_USE_FLAC
  79656. #ifdef _MSC_VER
  79657. #pragma warning (disable : 4505)
  79658. #pragma warning (push)
  79659. #endif
  79660. namespace FlacNamespace
  79661. {
  79662. #define FLAC__NO_DLL 1
  79663. #if ! defined (SIZE_MAX)
  79664. #define SIZE_MAX 0xffffffff
  79665. #endif
  79666. #define __STDC_LIMIT_MACROS 1
  79667. /********* Start of inlined file: all.h *********/
  79668. #ifndef FLAC__ALL_H
  79669. #define FLAC__ALL_H
  79670. /********* Start of inlined file: export.h *********/
  79671. #ifndef FLAC__EXPORT_H
  79672. #define FLAC__EXPORT_H
  79673. /** \file include/FLAC/export.h
  79674. *
  79675. * \brief
  79676. * This module contains #defines and symbols for exporting function
  79677. * calls, and providing version information and compiled-in features.
  79678. *
  79679. * See the \link flac_export export \endlink module.
  79680. */
  79681. /** \defgroup flac_export FLAC/export.h: export symbols
  79682. * \ingroup flac
  79683. *
  79684. * \brief
  79685. * This module contains #defines and symbols for exporting function
  79686. * calls, and providing version information and compiled-in features.
  79687. *
  79688. * If you are compiling with MSVC and will link to the static library
  79689. * (libFLAC.lib) you should define FLAC__NO_DLL in your project to
  79690. * make sure the symbols are exported properly.
  79691. *
  79692. * \{
  79693. */
  79694. #if defined(FLAC__NO_DLL) || !defined(_MSC_VER)
  79695. #define FLAC_API
  79696. #else
  79697. #ifdef FLAC_API_EXPORTS
  79698. #define FLAC_API _declspec(dllexport)
  79699. #else
  79700. #define FLAC_API _declspec(dllimport)
  79701. #endif
  79702. #endif
  79703. /** These #defines will mirror the libtool-based library version number, see
  79704. * http://www.gnu.org/software/libtool/manual.html#Libtool-versioning
  79705. */
  79706. #define FLAC_API_VERSION_CURRENT 10
  79707. #define FLAC_API_VERSION_REVISION 0 /**< see above */
  79708. #define FLAC_API_VERSION_AGE 2 /**< see above */
  79709. #ifdef __cplusplus
  79710. extern "C" {
  79711. #endif
  79712. /** \c 1 if the library has been compiled with support for Ogg FLAC, else \c 0. */
  79713. extern FLAC_API int FLAC_API_SUPPORTS_OGG_FLAC;
  79714. #ifdef __cplusplus
  79715. }
  79716. #endif
  79717. /* \} */
  79718. #endif
  79719. /********* End of inlined file: export.h *********/
  79720. /********* Start of inlined file: assert.h *********/
  79721. #ifndef FLAC__ASSERT_H
  79722. #define FLAC__ASSERT_H
  79723. /* we need this since some compilers (like MSVC) leave assert()s on release code (and we don't want to use their ASSERT) */
  79724. #ifdef DEBUG
  79725. #include <assert.h>
  79726. #define FLAC__ASSERT(x) assert(x)
  79727. #define FLAC__ASSERT_DECLARATION(x) x
  79728. #else
  79729. #define FLAC__ASSERT(x)
  79730. #define FLAC__ASSERT_DECLARATION(x)
  79731. #endif
  79732. #endif
  79733. /********* End of inlined file: assert.h *********/
  79734. /********* Start of inlined file: callback.h *********/
  79735. #ifndef FLAC__CALLBACK_H
  79736. #define FLAC__CALLBACK_H
  79737. /********* Start of inlined file: ordinals.h *********/
  79738. #ifndef FLAC__ORDINALS_H
  79739. #define FLAC__ORDINALS_H
  79740. #if !(defined(_MSC_VER) || defined(__BORLANDC__) || defined(__EMX__))
  79741. #include <inttypes.h>
  79742. #endif
  79743. typedef signed char FLAC__int8;
  79744. typedef unsigned char FLAC__uint8;
  79745. #if defined(_MSC_VER) || defined(__BORLANDC__)
  79746. typedef __int16 FLAC__int16;
  79747. typedef __int32 FLAC__int32;
  79748. typedef __int64 FLAC__int64;
  79749. typedef unsigned __int16 FLAC__uint16;
  79750. typedef unsigned __int32 FLAC__uint32;
  79751. typedef unsigned __int64 FLAC__uint64;
  79752. #elif defined(__EMX__)
  79753. typedef short FLAC__int16;
  79754. typedef long FLAC__int32;
  79755. typedef long long FLAC__int64;
  79756. typedef unsigned short FLAC__uint16;
  79757. typedef unsigned long FLAC__uint32;
  79758. typedef unsigned long long FLAC__uint64;
  79759. #else
  79760. typedef int16_t FLAC__int16;
  79761. typedef int32_t FLAC__int32;
  79762. typedef int64_t FLAC__int64;
  79763. typedef uint16_t FLAC__uint16;
  79764. typedef uint32_t FLAC__uint32;
  79765. typedef uint64_t FLAC__uint64;
  79766. #endif
  79767. typedef int FLAC__bool;
  79768. typedef FLAC__uint8 FLAC__byte;
  79769. #ifdef true
  79770. #undef true
  79771. #endif
  79772. #ifdef false
  79773. #undef false
  79774. #endif
  79775. #ifndef __cplusplus
  79776. #define true 1
  79777. #define false 0
  79778. #endif
  79779. #endif
  79780. /********* End of inlined file: ordinals.h *********/
  79781. #include <stdlib.h> /* for size_t */
  79782. /** \file include/FLAC/callback.h
  79783. *
  79784. * \brief
  79785. * This module defines the structures for describing I/O callbacks
  79786. * to the other FLAC interfaces.
  79787. *
  79788. * See the detailed documentation for callbacks in the
  79789. * \link flac_callbacks callbacks \endlink module.
  79790. */
  79791. /** \defgroup flac_callbacks FLAC/callback.h: I/O callback structures
  79792. * \ingroup flac
  79793. *
  79794. * \brief
  79795. * This module defines the structures for describing I/O callbacks
  79796. * to the other FLAC interfaces.
  79797. *
  79798. * The purpose of the I/O callback functions is to create a common way
  79799. * for the metadata interfaces to handle I/O.
  79800. *
  79801. * Originally the metadata interfaces required filenames as the way of
  79802. * specifying FLAC files to operate on. This is problematic in some
  79803. * environments so there is an additional option to specify a set of
  79804. * callbacks for doing I/O on the FLAC file, instead of the filename.
  79805. *
  79806. * In addition to the callbacks, a FLAC__IOHandle type is defined as an
  79807. * opaque structure for a data source.
  79808. *
  79809. * The callback function prototypes are similar (but not identical) to the
  79810. * stdio functions fread, fwrite, fseek, ftell, feof, and fclose. If you use
  79811. * stdio streams to implement the callbacks, you can pass fread, fwrite, and
  79812. * fclose anywhere a FLAC__IOCallback_Read, FLAC__IOCallback_Write, or
  79813. * FLAC__IOCallback_Close is required, and a FILE* anywhere a FLAC__IOHandle
  79814. * is required. \warning You generally CANNOT directly use fseek or ftell
  79815. * for FLAC__IOCallback_Seek or FLAC__IOCallback_Tell since on most systems
  79816. * these use 32-bit offsets and FLAC requires 64-bit offsets to deal with
  79817. * large files. You will have to find an equivalent function (e.g. ftello),
  79818. * or write a wrapper. The same is true for feof() since this is usually
  79819. * implemented as a macro, not as a function whose address can be taken.
  79820. *
  79821. * \{
  79822. */
  79823. #ifdef __cplusplus
  79824. extern "C" {
  79825. #endif
  79826. /** This is the opaque handle type used by the callbacks. Typically
  79827. * this is a \c FILE* or address of a file descriptor.
  79828. */
  79829. typedef void* FLAC__IOHandle;
  79830. /** Signature for the read callback.
  79831. * The signature and semantics match POSIX fread() implementations
  79832. * and can generally be used interchangeably.
  79833. *
  79834. * \param ptr The address of the read buffer.
  79835. * \param size The size of the records to be read.
  79836. * \param nmemb The number of records to be read.
  79837. * \param handle The handle to the data source.
  79838. * \retval size_t
  79839. * The number of records read.
  79840. */
  79841. typedef size_t (*FLAC__IOCallback_Read) (void *ptr, size_t size, size_t nmemb, FLAC__IOHandle handle);
  79842. /** Signature for the write callback.
  79843. * The signature and semantics match POSIX fwrite() implementations
  79844. * and can generally be used interchangeably.
  79845. *
  79846. * \param ptr The address of the write buffer.
  79847. * \param size The size of the records to be written.
  79848. * \param nmemb The number of records to be written.
  79849. * \param handle The handle to the data source.
  79850. * \retval size_t
  79851. * The number of records written.
  79852. */
  79853. typedef size_t (*FLAC__IOCallback_Write) (const void *ptr, size_t size, size_t nmemb, FLAC__IOHandle handle);
  79854. /** Signature for the seek callback.
  79855. * The signature and semantics mostly match POSIX fseek() WITH ONE IMPORTANT
  79856. * EXCEPTION: the offset is a 64-bit type whereas fseek() is generally 'long'
  79857. * and 32-bits wide.
  79858. *
  79859. * \param handle The handle to the data source.
  79860. * \param offset The new position, relative to \a whence
  79861. * \param whence \c SEEK_SET, \c SEEK_CUR, or \c SEEK_END
  79862. * \retval int
  79863. * \c 0 on success, \c -1 on error.
  79864. */
  79865. typedef int (*FLAC__IOCallback_Seek) (FLAC__IOHandle handle, FLAC__int64 offset, int whence);
  79866. /** Signature for the tell callback.
  79867. * The signature and semantics mostly match POSIX ftell() WITH ONE IMPORTANT
  79868. * EXCEPTION: the offset is a 64-bit type whereas ftell() is generally 'long'
  79869. * and 32-bits wide.
  79870. *
  79871. * \param handle The handle to the data source.
  79872. * \retval FLAC__int64
  79873. * The current position on success, \c -1 on error.
  79874. */
  79875. typedef FLAC__int64 (*FLAC__IOCallback_Tell) (FLAC__IOHandle handle);
  79876. /** Signature for the EOF callback.
  79877. * The signature and semantics mostly match POSIX feof() but WATCHOUT:
  79878. * on many systems, feof() is a macro, so in this case a wrapper function
  79879. * must be provided instead.
  79880. *
  79881. * \param handle The handle to the data source.
  79882. * \retval int
  79883. * \c 0 if not at end of file, nonzero if at end of file.
  79884. */
  79885. typedef int (*FLAC__IOCallback_Eof) (FLAC__IOHandle handle);
  79886. /** Signature for the close callback.
  79887. * The signature and semantics match POSIX fclose() implementations
  79888. * and can generally be used interchangeably.
  79889. *
  79890. * \param handle The handle to the data source.
  79891. * \retval int
  79892. * \c 0 on success, \c EOF on error.
  79893. */
  79894. typedef int (*FLAC__IOCallback_Close) (FLAC__IOHandle handle);
  79895. /** A structure for holding a set of callbacks.
  79896. * Each FLAC interface that requires a FLAC__IOCallbacks structure will
  79897. * describe which of the callbacks are required. The ones that are not
  79898. * required may be set to NULL.
  79899. *
  79900. * If the seek requirement for an interface is optional, you can signify that
  79901. * a data sorce is not seekable by setting the \a seek field to \c NULL.
  79902. */
  79903. typedef struct {
  79904. FLAC__IOCallback_Read read;
  79905. FLAC__IOCallback_Write write;
  79906. FLAC__IOCallback_Seek seek;
  79907. FLAC__IOCallback_Tell tell;
  79908. FLAC__IOCallback_Eof eof;
  79909. FLAC__IOCallback_Close close;
  79910. } FLAC__IOCallbacks;
  79911. /* \} */
  79912. #ifdef __cplusplus
  79913. }
  79914. #endif
  79915. #endif
  79916. /********* End of inlined file: callback.h *********/
  79917. /********* Start of inlined file: format.h *********/
  79918. #ifndef FLAC__FORMAT_H
  79919. #define FLAC__FORMAT_H
  79920. #ifdef __cplusplus
  79921. extern "C" {
  79922. #endif
  79923. /** \file include/FLAC/format.h
  79924. *
  79925. * \brief
  79926. * This module contains structure definitions for the representation
  79927. * of FLAC format components in memory. These are the basic
  79928. * structures used by the rest of the interfaces.
  79929. *
  79930. * See the detailed documentation in the
  79931. * \link flac_format format \endlink module.
  79932. */
  79933. /** \defgroup flac_format FLAC/format.h: format components
  79934. * \ingroup flac
  79935. *
  79936. * \brief
  79937. * This module contains structure definitions for the representation
  79938. * of FLAC format components in memory. These are the basic
  79939. * structures used by the rest of the interfaces.
  79940. *
  79941. * First, you should be familiar with the
  79942. * <A HREF="../format.html">FLAC format</A>. Many of the values here
  79943. * follow directly from the specification. As a user of libFLAC, the
  79944. * interesting parts really are the structures that describe the frame
  79945. * header and metadata blocks.
  79946. *
  79947. * The format structures here are very primitive, designed to store
  79948. * information in an efficient way. Reading information from the
  79949. * structures is easy but creating or modifying them directly is
  79950. * more complex. For the most part, as a user of a library, editing
  79951. * is not necessary; however, for metadata blocks it is, so there are
  79952. * convenience functions provided in the \link flac_metadata metadata
  79953. * module \endlink to simplify the manipulation of metadata blocks.
  79954. *
  79955. * \note
  79956. * It's not the best convention, but symbols ending in _LEN are in bits
  79957. * and _LENGTH are in bytes. _LENGTH symbols are \#defines instead of
  79958. * global variables because they are usually used when declaring byte
  79959. * arrays and some compilers require compile-time knowledge of array
  79960. * sizes when declared on the stack.
  79961. *
  79962. * \{
  79963. */
  79964. /*
  79965. Most of the values described in this file are defined by the FLAC
  79966. format specification. There is nothing to tune here.
  79967. */
  79968. /** The largest legal metadata type code. */
  79969. #define FLAC__MAX_METADATA_TYPE_CODE (126u)
  79970. /** The minimum block size, in samples, permitted by the format. */
  79971. #define FLAC__MIN_BLOCK_SIZE (16u)
  79972. /** The maximum block size, in samples, permitted by the format. */
  79973. #define FLAC__MAX_BLOCK_SIZE (65535u)
  79974. /** The maximum block size, in samples, permitted by the FLAC subset for
  79975. * sample rates up to 48kHz. */
  79976. #define FLAC__SUBSET_MAX_BLOCK_SIZE_48000HZ (4608u)
  79977. /** The maximum number of channels permitted by the format. */
  79978. #define FLAC__MAX_CHANNELS (8u)
  79979. /** The minimum sample resolution permitted by the format. */
  79980. #define FLAC__MIN_BITS_PER_SAMPLE (4u)
  79981. /** The maximum sample resolution permitted by the format. */
  79982. #define FLAC__MAX_BITS_PER_SAMPLE (32u)
  79983. /** The maximum sample resolution permitted by libFLAC.
  79984. *
  79985. * \warning
  79986. * FLAC__MAX_BITS_PER_SAMPLE is the limit of the FLAC format. However,
  79987. * the reference encoder/decoder is currently limited to 24 bits because
  79988. * of prevalent 32-bit math, so make sure and use this value when
  79989. * appropriate.
  79990. */
  79991. #define FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE (24u)
  79992. /** The maximum sample rate permitted by the format. The value is
  79993. * ((2 ^ 16) - 1) * 10; see <A HREF="../format.html">FLAC format</A>
  79994. * as to why.
  79995. */
  79996. #define FLAC__MAX_SAMPLE_RATE (655350u)
  79997. /** The maximum LPC order permitted by the format. */
  79998. #define FLAC__MAX_LPC_ORDER (32u)
  79999. /** The maximum LPC order permitted by the FLAC subset for sample rates
  80000. * up to 48kHz. */
  80001. #define FLAC__SUBSET_MAX_LPC_ORDER_48000HZ (12u)
  80002. /** The minimum quantized linear predictor coefficient precision
  80003. * permitted by the format.
  80004. */
  80005. #define FLAC__MIN_QLP_COEFF_PRECISION (5u)
  80006. /** The maximum quantized linear predictor coefficient precision
  80007. * permitted by the format.
  80008. */
  80009. #define FLAC__MAX_QLP_COEFF_PRECISION (15u)
  80010. /** The maximum order of the fixed predictors permitted by the format. */
  80011. #define FLAC__MAX_FIXED_ORDER (4u)
  80012. /** The maximum Rice partition order permitted by the format. */
  80013. #define FLAC__MAX_RICE_PARTITION_ORDER (15u)
  80014. /** The maximum Rice partition order permitted by the FLAC Subset. */
  80015. #define FLAC__SUBSET_MAX_RICE_PARTITION_ORDER (8u)
  80016. /** The version string of the release, stamped onto the libraries and binaries.
  80017. *
  80018. * \note
  80019. * This does not correspond to the shared library version number, which
  80020. * is used to determine binary compatibility.
  80021. */
  80022. extern FLAC_API const char *FLAC__VERSION_STRING;
  80023. /** The vendor string inserted by the encoder into the VORBIS_COMMENT block.
  80024. * This is a NUL-terminated ASCII string; when inserted into the
  80025. * VORBIS_COMMENT the trailing null is stripped.
  80026. */
  80027. extern FLAC_API const char *FLAC__VENDOR_STRING;
  80028. /** The byte string representation of the beginning of a FLAC stream. */
  80029. extern FLAC_API const FLAC__byte FLAC__STREAM_SYNC_STRING[4]; /* = "fLaC" */
  80030. /** The 32-bit integer big-endian representation of the beginning of
  80031. * a FLAC stream.
  80032. */
  80033. extern FLAC_API const unsigned FLAC__STREAM_SYNC; /* = 0x664C6143 */
  80034. /** The length of the FLAC signature in bits. */
  80035. extern FLAC_API const unsigned FLAC__STREAM_SYNC_LEN; /* = 32 bits */
  80036. /** The length of the FLAC signature in bytes. */
  80037. #define FLAC__STREAM_SYNC_LENGTH (4u)
  80038. /*****************************************************************************
  80039. *
  80040. * Subframe structures
  80041. *
  80042. *****************************************************************************/
  80043. /*****************************************************************************/
  80044. /** An enumeration of the available entropy coding methods. */
  80045. typedef enum {
  80046. FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE = 0,
  80047. /**< Residual is coded by partitioning into contexts, each with it's own
  80048. * 4-bit Rice parameter. */
  80049. FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2 = 1
  80050. /**< Residual is coded by partitioning into contexts, each with it's own
  80051. * 5-bit Rice parameter. */
  80052. } FLAC__EntropyCodingMethodType;
  80053. /** Maps a FLAC__EntropyCodingMethodType to a C string.
  80054. *
  80055. * Using a FLAC__EntropyCodingMethodType as the index to this array will
  80056. * give the string equivalent. The contents should not be modified.
  80057. */
  80058. extern FLAC_API const char * const FLAC__EntropyCodingMethodTypeString[];
  80059. /** Contents of a Rice partitioned residual
  80060. */
  80061. typedef struct {
  80062. unsigned *parameters;
  80063. /**< The Rice parameters for each context. */
  80064. unsigned *raw_bits;
  80065. /**< Widths for escape-coded partitions. Will be non-zero for escaped
  80066. * partitions and zero for unescaped partitions.
  80067. */
  80068. unsigned capacity_by_order;
  80069. /**< The capacity of the \a parameters and \a raw_bits arrays
  80070. * specified as an order, i.e. the number of array elements
  80071. * allocated is 2 ^ \a capacity_by_order.
  80072. */
  80073. } FLAC__EntropyCodingMethod_PartitionedRiceContents;
  80074. /** Header for a Rice partitioned residual. (c.f. <A HREF="../format.html#partitioned_rice">format specification</A>)
  80075. */
  80076. typedef struct {
  80077. unsigned order;
  80078. /**< The partition order, i.e. # of contexts = 2 ^ \a order. */
  80079. const FLAC__EntropyCodingMethod_PartitionedRiceContents *contents;
  80080. /**< The context's Rice parameters and/or raw bits. */
  80081. } FLAC__EntropyCodingMethod_PartitionedRice;
  80082. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN; /**< == 4 (bits) */
  80083. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN; /**< == 4 (bits) */
  80084. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN; /**< == 5 (bits) */
  80085. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN; /**< == 5 (bits) */
  80086. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  80087. /**< == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN)-1 */
  80088. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER;
  80089. /**< == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN)-1 */
  80090. /** Header for the entropy coding method. (c.f. <A HREF="../format.html#residual">format specification</A>)
  80091. */
  80092. typedef struct {
  80093. FLAC__EntropyCodingMethodType type;
  80094. union {
  80095. FLAC__EntropyCodingMethod_PartitionedRice partitioned_rice;
  80096. } data;
  80097. } FLAC__EntropyCodingMethod;
  80098. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_TYPE_LEN; /**< == 2 (bits) */
  80099. /*****************************************************************************/
  80100. /** An enumeration of the available subframe types. */
  80101. typedef enum {
  80102. FLAC__SUBFRAME_TYPE_CONSTANT = 0, /**< constant signal */
  80103. FLAC__SUBFRAME_TYPE_VERBATIM = 1, /**< uncompressed signal */
  80104. FLAC__SUBFRAME_TYPE_FIXED = 2, /**< fixed polynomial prediction */
  80105. FLAC__SUBFRAME_TYPE_LPC = 3 /**< linear prediction */
  80106. } FLAC__SubframeType;
  80107. /** Maps a FLAC__SubframeType to a C string.
  80108. *
  80109. * Using a FLAC__SubframeType as the index to this array will
  80110. * give the string equivalent. The contents should not be modified.
  80111. */
  80112. extern FLAC_API const char * const FLAC__SubframeTypeString[];
  80113. /** CONSTANT subframe. (c.f. <A HREF="../format.html#subframe_constant">format specification</A>)
  80114. */
  80115. typedef struct {
  80116. FLAC__int32 value; /**< The constant signal value. */
  80117. } FLAC__Subframe_Constant;
  80118. /** VERBATIM subframe. (c.f. <A HREF="../format.html#subframe_verbatim">format specification</A>)
  80119. */
  80120. typedef struct {
  80121. const FLAC__int32 *data; /**< A pointer to verbatim signal. */
  80122. } FLAC__Subframe_Verbatim;
  80123. /** FIXED subframe. (c.f. <A HREF="../format.html#subframe_fixed">format specification</A>)
  80124. */
  80125. typedef struct {
  80126. FLAC__EntropyCodingMethod entropy_coding_method;
  80127. /**< The residual coding method. */
  80128. unsigned order;
  80129. /**< The polynomial order. */
  80130. FLAC__int32 warmup[FLAC__MAX_FIXED_ORDER];
  80131. /**< Warmup samples to prime the predictor, length == order. */
  80132. const FLAC__int32 *residual;
  80133. /**< The residual signal, length == (blocksize minus order) samples. */
  80134. } FLAC__Subframe_Fixed;
  80135. /** LPC subframe. (c.f. <A HREF="../format.html#subframe_lpc">format specification</A>)
  80136. */
  80137. typedef struct {
  80138. FLAC__EntropyCodingMethod entropy_coding_method;
  80139. /**< The residual coding method. */
  80140. unsigned order;
  80141. /**< The FIR order. */
  80142. unsigned qlp_coeff_precision;
  80143. /**< Quantized FIR filter coefficient precision in bits. */
  80144. int quantization_level;
  80145. /**< The qlp coeff shift needed. */
  80146. FLAC__int32 qlp_coeff[FLAC__MAX_LPC_ORDER];
  80147. /**< FIR filter coefficients. */
  80148. FLAC__int32 warmup[FLAC__MAX_LPC_ORDER];
  80149. /**< Warmup samples to prime the predictor, length == order. */
  80150. const FLAC__int32 *residual;
  80151. /**< The residual signal, length == (blocksize minus order) samples. */
  80152. } FLAC__Subframe_LPC;
  80153. extern FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN; /**< == 4 (bits) */
  80154. extern FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN; /**< == 5 (bits) */
  80155. /** FLAC subframe structure. (c.f. <A HREF="../format.html#subframe">format specification</A>)
  80156. */
  80157. typedef struct {
  80158. FLAC__SubframeType type;
  80159. union {
  80160. FLAC__Subframe_Constant constant;
  80161. FLAC__Subframe_Fixed fixed;
  80162. FLAC__Subframe_LPC lpc;
  80163. FLAC__Subframe_Verbatim verbatim;
  80164. } data;
  80165. unsigned wasted_bits;
  80166. } FLAC__Subframe;
  80167. /** == 1 (bit)
  80168. *
  80169. * This used to be a zero-padding bit (hence the name
  80170. * FLAC__SUBFRAME_ZERO_PAD_LEN) but is now a reserved bit. It still has a
  80171. * mandatory value of \c 0 but in the future may take on the value \c 0 or \c 1
  80172. * to mean something else.
  80173. */
  80174. extern FLAC_API const unsigned FLAC__SUBFRAME_ZERO_PAD_LEN;
  80175. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LEN; /**< == 6 (bits) */
  80176. extern FLAC_API const unsigned FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN; /**< == 1 (bit) */
  80177. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_CONSTANT_BYTE_ALIGNED_MASK; /**< = 0x00 */
  80178. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_VERBATIM_BYTE_ALIGNED_MASK; /**< = 0x02 */
  80179. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_FIXED_BYTE_ALIGNED_MASK; /**< = 0x10 */
  80180. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LPC_BYTE_ALIGNED_MASK; /**< = 0x40 */
  80181. /*****************************************************************************/
  80182. /*****************************************************************************
  80183. *
  80184. * Frame structures
  80185. *
  80186. *****************************************************************************/
  80187. /** An enumeration of the available channel assignments. */
  80188. typedef enum {
  80189. FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT = 0, /**< independent channels */
  80190. FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE = 1, /**< left+side stereo */
  80191. FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE = 2, /**< right+side stereo */
  80192. FLAC__CHANNEL_ASSIGNMENT_MID_SIDE = 3 /**< mid+side stereo */
  80193. } FLAC__ChannelAssignment;
  80194. /** Maps a FLAC__ChannelAssignment to a C string.
  80195. *
  80196. * Using a FLAC__ChannelAssignment as the index to this array will
  80197. * give the string equivalent. The contents should not be modified.
  80198. */
  80199. extern FLAC_API const char * const FLAC__ChannelAssignmentString[];
  80200. /** An enumeration of the possible frame numbering methods. */
  80201. typedef enum {
  80202. FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER, /**< number contains the frame number */
  80203. FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER /**< number contains the sample number of first sample in frame */
  80204. } FLAC__FrameNumberType;
  80205. /** Maps a FLAC__FrameNumberType to a C string.
  80206. *
  80207. * Using a FLAC__FrameNumberType as the index to this array will
  80208. * give the string equivalent. The contents should not be modified.
  80209. */
  80210. extern FLAC_API const char * const FLAC__FrameNumberTypeString[];
  80211. /** FLAC frame header structure. (c.f. <A HREF="../format.html#frame_header">format specification</A>)
  80212. */
  80213. typedef struct {
  80214. unsigned blocksize;
  80215. /**< The number of samples per subframe. */
  80216. unsigned sample_rate;
  80217. /**< The sample rate in Hz. */
  80218. unsigned channels;
  80219. /**< The number of channels (== number of subframes). */
  80220. FLAC__ChannelAssignment channel_assignment;
  80221. /**< The channel assignment for the frame. */
  80222. unsigned bits_per_sample;
  80223. /**< The sample resolution. */
  80224. FLAC__FrameNumberType number_type;
  80225. /**< The numbering scheme used for the frame. As a convenience, the
  80226. * decoder will always convert a frame number to a sample number because
  80227. * the rules are complex. */
  80228. union {
  80229. FLAC__uint32 frame_number;
  80230. FLAC__uint64 sample_number;
  80231. } number;
  80232. /**< The frame number or sample number of first sample in frame;
  80233. * use the \a number_type value to determine which to use. */
  80234. FLAC__uint8 crc;
  80235. /**< CRC-8 (polynomial = x^8 + x^2 + x^1 + x^0, initialized with 0)
  80236. * of the raw frame header bytes, meaning everything before the CRC byte
  80237. * including the sync code.
  80238. */
  80239. } FLAC__FrameHeader;
  80240. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC; /**< == 0x3ffe; the frame header sync code */
  80241. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC_LEN; /**< == 14 (bits) */
  80242. extern FLAC_API const unsigned FLAC__FRAME_HEADER_RESERVED_LEN; /**< == 1 (bits) */
  80243. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN; /**< == 1 (bits) */
  80244. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCK_SIZE_LEN; /**< == 4 (bits) */
  80245. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SAMPLE_RATE_LEN; /**< == 4 (bits) */
  80246. extern FLAC_API const unsigned FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN; /**< == 4 (bits) */
  80247. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN; /**< == 3 (bits) */
  80248. extern FLAC_API const unsigned FLAC__FRAME_HEADER_ZERO_PAD_LEN; /**< == 1 (bit) */
  80249. extern FLAC_API const unsigned FLAC__FRAME_HEADER_CRC_LEN; /**< == 8 (bits) */
  80250. /** FLAC frame footer structure. (c.f. <A HREF="../format.html#frame_footer">format specification</A>)
  80251. */
  80252. typedef struct {
  80253. FLAC__uint16 crc;
  80254. /**< CRC-16 (polynomial = x^16 + x^15 + x^2 + x^0, initialized with
  80255. * 0) of the bytes before the crc, back to and including the frame header
  80256. * sync code.
  80257. */
  80258. } FLAC__FrameFooter;
  80259. extern FLAC_API const unsigned FLAC__FRAME_FOOTER_CRC_LEN; /**< == 16 (bits) */
  80260. /** FLAC frame structure. (c.f. <A HREF="../format.html#frame">format specification</A>)
  80261. */
  80262. typedef struct {
  80263. FLAC__FrameHeader header;
  80264. FLAC__Subframe subframes[FLAC__MAX_CHANNELS];
  80265. FLAC__FrameFooter footer;
  80266. } FLAC__Frame;
  80267. /*****************************************************************************/
  80268. /*****************************************************************************
  80269. *
  80270. * Meta-data structures
  80271. *
  80272. *****************************************************************************/
  80273. /** An enumeration of the available metadata block types. */
  80274. typedef enum {
  80275. FLAC__METADATA_TYPE_STREAMINFO = 0,
  80276. /**< <A HREF="../format.html#metadata_block_streaminfo">STREAMINFO</A> block */
  80277. FLAC__METADATA_TYPE_PADDING = 1,
  80278. /**< <A HREF="../format.html#metadata_block_padding">PADDING</A> block */
  80279. FLAC__METADATA_TYPE_APPLICATION = 2,
  80280. /**< <A HREF="../format.html#metadata_block_application">APPLICATION</A> block */
  80281. FLAC__METADATA_TYPE_SEEKTABLE = 3,
  80282. /**< <A HREF="../format.html#metadata_block_seektable">SEEKTABLE</A> block */
  80283. FLAC__METADATA_TYPE_VORBIS_COMMENT = 4,
  80284. /**< <A HREF="../format.html#metadata_block_vorbis_comment">VORBISCOMMENT</A> block (a.k.a. FLAC tags) */
  80285. FLAC__METADATA_TYPE_CUESHEET = 5,
  80286. /**< <A HREF="../format.html#metadata_block_cuesheet">CUESHEET</A> block */
  80287. FLAC__METADATA_TYPE_PICTURE = 6,
  80288. /**< <A HREF="../format.html#metadata_block_picture">PICTURE</A> block */
  80289. FLAC__METADATA_TYPE_UNDEFINED = 7
  80290. /**< marker to denote beginning of undefined type range; this number will increase as new metadata types are added */
  80291. } FLAC__MetadataType;
  80292. /** Maps a FLAC__MetadataType to a C string.
  80293. *
  80294. * Using a FLAC__MetadataType as the index to this array will
  80295. * give the string equivalent. The contents should not be modified.
  80296. */
  80297. extern FLAC_API const char * const FLAC__MetadataTypeString[];
  80298. /** FLAC STREAMINFO structure. (c.f. <A HREF="../format.html#metadata_block_streaminfo">format specification</A>)
  80299. */
  80300. typedef struct {
  80301. unsigned min_blocksize, max_blocksize;
  80302. unsigned min_framesize, max_framesize;
  80303. unsigned sample_rate;
  80304. unsigned channels;
  80305. unsigned bits_per_sample;
  80306. FLAC__uint64 total_samples;
  80307. FLAC__byte md5sum[16];
  80308. } FLAC__StreamMetadata_StreamInfo;
  80309. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN; /**< == 16 (bits) */
  80310. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN; /**< == 16 (bits) */
  80311. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN; /**< == 24 (bits) */
  80312. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN; /**< == 24 (bits) */
  80313. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN; /**< == 20 (bits) */
  80314. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN; /**< == 3 (bits) */
  80315. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN; /**< == 5 (bits) */
  80316. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN; /**< == 36 (bits) */
  80317. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MD5SUM_LEN; /**< == 128 (bits) */
  80318. /** The total stream length of the STREAMINFO block in bytes. */
  80319. #define FLAC__STREAM_METADATA_STREAMINFO_LENGTH (34u)
  80320. /** FLAC PADDING structure. (c.f. <A HREF="../format.html#metadata_block_padding">format specification</A>)
  80321. */
  80322. typedef struct {
  80323. int dummy;
  80324. /**< Conceptually this is an empty struct since we don't store the
  80325. * padding bytes. Empty structs are not allowed by some C compilers,
  80326. * hence the dummy.
  80327. */
  80328. } FLAC__StreamMetadata_Padding;
  80329. /** FLAC APPLICATION structure. (c.f. <A HREF="../format.html#metadata_block_application">format specification</A>)
  80330. */
  80331. typedef struct {
  80332. FLAC__byte id[4];
  80333. FLAC__byte *data;
  80334. } FLAC__StreamMetadata_Application;
  80335. extern FLAC_API const unsigned FLAC__STREAM_METADATA_APPLICATION_ID_LEN; /**< == 32 (bits) */
  80336. /** SeekPoint structure used in SEEKTABLE blocks. (c.f. <A HREF="../format.html#seekpoint">format specification</A>)
  80337. */
  80338. typedef struct {
  80339. FLAC__uint64 sample_number;
  80340. /**< The sample number of the target frame. */
  80341. FLAC__uint64 stream_offset;
  80342. /**< The offset, in bytes, of the target frame with respect to
  80343. * beginning of the first frame. */
  80344. unsigned frame_samples;
  80345. /**< The number of samples in the target frame. */
  80346. } FLAC__StreamMetadata_SeekPoint;
  80347. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN; /**< == 64 (bits) */
  80348. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN; /**< == 64 (bits) */
  80349. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN; /**< == 16 (bits) */
  80350. /** The total stream length of a seek point in bytes. */
  80351. #define FLAC__STREAM_METADATA_SEEKPOINT_LENGTH (18u)
  80352. /** The value used in the \a sample_number field of
  80353. * FLAC__StreamMetadataSeekPoint used to indicate a placeholder
  80354. * point (== 0xffffffffffffffff).
  80355. */
  80356. extern FLAC_API const FLAC__uint64 FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
  80357. /** FLAC SEEKTABLE structure. (c.f. <A HREF="../format.html#metadata_block_seektable">format specification</A>)
  80358. *
  80359. * \note From the format specification:
  80360. * - The seek points must be sorted by ascending sample number.
  80361. * - Each seek point's sample number must be the first sample of the
  80362. * target frame.
  80363. * - Each seek point's sample number must be unique within the table.
  80364. * - Existence of a SEEKTABLE block implies a correct setting of
  80365. * total_samples in the stream_info block.
  80366. * - Behavior is undefined when more than one SEEKTABLE block is
  80367. * present in a stream.
  80368. */
  80369. typedef struct {
  80370. unsigned num_points;
  80371. FLAC__StreamMetadata_SeekPoint *points;
  80372. } FLAC__StreamMetadata_SeekTable;
  80373. /** Vorbis comment entry structure used in VORBIS_COMMENT blocks. (c.f. <A HREF="../format.html#metadata_block_vorbis_comment">format specification</A>)
  80374. *
  80375. * For convenience, the APIs maintain a trailing NUL character at the end of
  80376. * \a entry which is not counted toward \a length, i.e.
  80377. * \code strlen(entry) == length \endcode
  80378. */
  80379. typedef struct {
  80380. FLAC__uint32 length;
  80381. FLAC__byte *entry;
  80382. } FLAC__StreamMetadata_VorbisComment_Entry;
  80383. extern FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN; /**< == 32 (bits) */
  80384. /** FLAC VORBIS_COMMENT structure. (c.f. <A HREF="../format.html#metadata_block_vorbis_comment">format specification</A>)
  80385. */
  80386. typedef struct {
  80387. FLAC__StreamMetadata_VorbisComment_Entry vendor_string;
  80388. FLAC__uint32 num_comments;
  80389. FLAC__StreamMetadata_VorbisComment_Entry *comments;
  80390. } FLAC__StreamMetadata_VorbisComment;
  80391. extern FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN; /**< == 32 (bits) */
  80392. /** FLAC CUESHEET track index structure. (See the
  80393. * <A HREF="../format.html#cuesheet_track_index">format specification</A> for
  80394. * the full description of each field.)
  80395. */
  80396. typedef struct {
  80397. FLAC__uint64 offset;
  80398. /**< Offset in samples, relative to the track offset, of the index
  80399. * point.
  80400. */
  80401. FLAC__byte number;
  80402. /**< The index point number. */
  80403. } FLAC__StreamMetadata_CueSheet_Index;
  80404. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN; /**< == 64 (bits) */
  80405. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN; /**< == 8 (bits) */
  80406. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN; /**< == 3*8 (bits) */
  80407. /** FLAC CUESHEET track structure. (See the
  80408. * <A HREF="../format.html#cuesheet_track">format specification</A> for
  80409. * the full description of each field.)
  80410. */
  80411. typedef struct {
  80412. FLAC__uint64 offset;
  80413. /**< Track offset in samples, relative to the beginning of the FLAC audio stream. */
  80414. FLAC__byte number;
  80415. /**< The track number. */
  80416. char isrc[13];
  80417. /**< Track ISRC. This is a 12-digit alphanumeric code plus a trailing \c NUL byte */
  80418. unsigned type:1;
  80419. /**< The track type: 0 for audio, 1 for non-audio. */
  80420. unsigned pre_emphasis:1;
  80421. /**< The pre-emphasis flag: 0 for no pre-emphasis, 1 for pre-emphasis. */
  80422. FLAC__byte num_indices;
  80423. /**< The number of track index points. */
  80424. FLAC__StreamMetadata_CueSheet_Index *indices;
  80425. /**< NULL if num_indices == 0, else pointer to array of index points. */
  80426. } FLAC__StreamMetadata_CueSheet_Track;
  80427. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN; /**< == 64 (bits) */
  80428. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN; /**< == 8 (bits) */
  80429. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN; /**< == 12*8 (bits) */
  80430. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN; /**< == 1 (bit) */
  80431. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN; /**< == 1 (bit) */
  80432. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN; /**< == 6+13*8 (bits) */
  80433. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN; /**< == 8 (bits) */
  80434. /** FLAC CUESHEET structure. (See the
  80435. * <A HREF="../format.html#metadata_block_cuesheet">format specification</A>
  80436. * for the full description of each field.)
  80437. */
  80438. typedef struct {
  80439. char media_catalog_number[129];
  80440. /**< Media catalog number, in ASCII printable characters 0x20-0x7e. In
  80441. * general, the media catalog number may be 0 to 128 bytes long; any
  80442. * unused characters should be right-padded with NUL characters.
  80443. */
  80444. FLAC__uint64 lead_in;
  80445. /**< The number of lead-in samples. */
  80446. FLAC__bool is_cd;
  80447. /**< \c true if CUESHEET corresponds to a Compact Disc, else \c false. */
  80448. unsigned num_tracks;
  80449. /**< The number of tracks. */
  80450. FLAC__StreamMetadata_CueSheet_Track *tracks;
  80451. /**< NULL if num_tracks == 0, else pointer to array of tracks. */
  80452. } FLAC__StreamMetadata_CueSheet;
  80453. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN; /**< == 128*8 (bits) */
  80454. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN; /**< == 64 (bits) */
  80455. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN; /**< == 1 (bit) */
  80456. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN; /**< == 7+258*8 (bits) */
  80457. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN; /**< == 8 (bits) */
  80458. /** An enumeration of the PICTURE types (see FLAC__StreamMetadataPicture and id3 v2.4 APIC tag). */
  80459. typedef enum {
  80460. FLAC__STREAM_METADATA_PICTURE_TYPE_OTHER = 0, /**< Other */
  80461. FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD = 1, /**< 32x32 pixels 'file icon' (PNG only) */
  80462. FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON = 2, /**< Other file icon */
  80463. FLAC__STREAM_METADATA_PICTURE_TYPE_FRONT_COVER = 3, /**< Cover (front) */
  80464. FLAC__STREAM_METADATA_PICTURE_TYPE_BACK_COVER = 4, /**< Cover (back) */
  80465. FLAC__STREAM_METADATA_PICTURE_TYPE_LEAFLET_PAGE = 5, /**< Leaflet page */
  80466. FLAC__STREAM_METADATA_PICTURE_TYPE_MEDIA = 6, /**< Media (e.g. label side of CD) */
  80467. FLAC__STREAM_METADATA_PICTURE_TYPE_LEAD_ARTIST = 7, /**< Lead artist/lead performer/soloist */
  80468. FLAC__STREAM_METADATA_PICTURE_TYPE_ARTIST = 8, /**< Artist/performer */
  80469. FLAC__STREAM_METADATA_PICTURE_TYPE_CONDUCTOR = 9, /**< Conductor */
  80470. FLAC__STREAM_METADATA_PICTURE_TYPE_BAND = 10, /**< Band/Orchestra */
  80471. FLAC__STREAM_METADATA_PICTURE_TYPE_COMPOSER = 11, /**< Composer */
  80472. FLAC__STREAM_METADATA_PICTURE_TYPE_LYRICIST = 12, /**< Lyricist/text writer */
  80473. FLAC__STREAM_METADATA_PICTURE_TYPE_RECORDING_LOCATION = 13, /**< Recording Location */
  80474. FLAC__STREAM_METADATA_PICTURE_TYPE_DURING_RECORDING = 14, /**< During recording */
  80475. FLAC__STREAM_METADATA_PICTURE_TYPE_DURING_PERFORMANCE = 15, /**< During performance */
  80476. FLAC__STREAM_METADATA_PICTURE_TYPE_VIDEO_SCREEN_CAPTURE = 16, /**< Movie/video screen capture */
  80477. FLAC__STREAM_METADATA_PICTURE_TYPE_FISH = 17, /**< A bright coloured fish */
  80478. FLAC__STREAM_METADATA_PICTURE_TYPE_ILLUSTRATION = 18, /**< Illustration */
  80479. FLAC__STREAM_METADATA_PICTURE_TYPE_BAND_LOGOTYPE = 19, /**< Band/artist logotype */
  80480. FLAC__STREAM_METADATA_PICTURE_TYPE_PUBLISHER_LOGOTYPE = 20, /**< Publisher/Studio logotype */
  80481. FLAC__STREAM_METADATA_PICTURE_TYPE_UNDEFINED
  80482. } FLAC__StreamMetadata_Picture_Type;
  80483. /** Maps a FLAC__StreamMetadata_Picture_Type to a C string.
  80484. *
  80485. * Using a FLAC__StreamMetadata_Picture_Type as the index to this array
  80486. * will give the string equivalent. The contents should not be
  80487. * modified.
  80488. */
  80489. extern FLAC_API const char * const FLAC__StreamMetadata_Picture_TypeString[];
  80490. /** FLAC PICTURE structure. (See the
  80491. * <A HREF="../format.html#metadata_block_picture">format specification</A>
  80492. * for the full description of each field.)
  80493. */
  80494. typedef struct {
  80495. FLAC__StreamMetadata_Picture_Type type;
  80496. /**< The kind of picture stored. */
  80497. char *mime_type;
  80498. /**< Picture data's MIME type, in ASCII printable characters
  80499. * 0x20-0x7e, NUL terminated. For best compatibility with players,
  80500. * use picture data of MIME type \c image/jpeg or \c image/png. A
  80501. * MIME type of '-->' is also allowed, in which case the picture
  80502. * data should be a complete URL. In file storage, the MIME type is
  80503. * stored as a 32-bit length followed by the ASCII string with no NUL
  80504. * terminator, but is converted to a plain C string in this structure
  80505. * for convenience.
  80506. */
  80507. FLAC__byte *description;
  80508. /**< Picture's description in UTF-8, NUL terminated. In file storage,
  80509. * the description is stored as a 32-bit length followed by the UTF-8
  80510. * string with no NUL terminator, but is converted to a plain C string
  80511. * in this structure for convenience.
  80512. */
  80513. FLAC__uint32 width;
  80514. /**< Picture's width in pixels. */
  80515. FLAC__uint32 height;
  80516. /**< Picture's height in pixels. */
  80517. FLAC__uint32 depth;
  80518. /**< Picture's color depth in bits-per-pixel. */
  80519. FLAC__uint32 colors;
  80520. /**< For indexed palettes (like GIF), picture's number of colors (the
  80521. * number of palette entries), or \c 0 for non-indexed (i.e. 2^depth).
  80522. */
  80523. FLAC__uint32 data_length;
  80524. /**< Length of binary picture data in bytes. */
  80525. FLAC__byte *data;
  80526. /**< Binary picture data. */
  80527. } FLAC__StreamMetadata_Picture;
  80528. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_TYPE_LEN; /**< == 32 (bits) */
  80529. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN; /**< == 32 (bits) */
  80530. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN; /**< == 32 (bits) */
  80531. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN; /**< == 32 (bits) */
  80532. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN; /**< == 32 (bits) */
  80533. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN; /**< == 32 (bits) */
  80534. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_COLORS_LEN; /**< == 32 (bits) */
  80535. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN; /**< == 32 (bits) */
  80536. /** Structure that is used when a metadata block of unknown type is loaded.
  80537. * The contents are opaque. The structure is used only internally to
  80538. * correctly handle unknown metadata.
  80539. */
  80540. typedef struct {
  80541. FLAC__byte *data;
  80542. } FLAC__StreamMetadata_Unknown;
  80543. /** FLAC metadata block structure. (c.f. <A HREF="../format.html#metadata_block">format specification</A>)
  80544. */
  80545. typedef struct {
  80546. FLAC__MetadataType type;
  80547. /**< The type of the metadata block; used determine which member of the
  80548. * \a data union to dereference. If type >= FLAC__METADATA_TYPE_UNDEFINED
  80549. * then \a data.unknown must be used. */
  80550. FLAC__bool is_last;
  80551. /**< \c true if this metadata block is the last, else \a false */
  80552. unsigned length;
  80553. /**< Length, in bytes, of the block data as it appears in the stream. */
  80554. union {
  80555. FLAC__StreamMetadata_StreamInfo stream_info;
  80556. FLAC__StreamMetadata_Padding padding;
  80557. FLAC__StreamMetadata_Application application;
  80558. FLAC__StreamMetadata_SeekTable seek_table;
  80559. FLAC__StreamMetadata_VorbisComment vorbis_comment;
  80560. FLAC__StreamMetadata_CueSheet cue_sheet;
  80561. FLAC__StreamMetadata_Picture picture;
  80562. FLAC__StreamMetadata_Unknown unknown;
  80563. } data;
  80564. /**< Polymorphic block data; use the \a type value to determine which
  80565. * to use. */
  80566. } FLAC__StreamMetadata;
  80567. extern FLAC_API const unsigned FLAC__STREAM_METADATA_IS_LAST_LEN; /**< == 1 (bit) */
  80568. extern FLAC_API const unsigned FLAC__STREAM_METADATA_TYPE_LEN; /**< == 7 (bits) */
  80569. extern FLAC_API const unsigned FLAC__STREAM_METADATA_LENGTH_LEN; /**< == 24 (bits) */
  80570. /** The total stream length of a metadata block header in bytes. */
  80571. #define FLAC__STREAM_METADATA_HEADER_LENGTH (4u)
  80572. /*****************************************************************************/
  80573. /*****************************************************************************
  80574. *
  80575. * Utility functions
  80576. *
  80577. *****************************************************************************/
  80578. /** Tests that a sample rate is valid for FLAC.
  80579. *
  80580. * \param sample_rate The sample rate to test for compliance.
  80581. * \retval FLAC__bool
  80582. * \c true if the given sample rate conforms to the specification, else
  80583. * \c false.
  80584. */
  80585. FLAC_API FLAC__bool FLAC__format_sample_rate_is_valid(unsigned sample_rate);
  80586. /** Tests that a sample rate is valid for the FLAC subset. The subset rules
  80587. * for valid sample rates are slightly more complex since the rate has to
  80588. * be expressible completely in the frame header.
  80589. *
  80590. * \param sample_rate The sample rate to test for compliance.
  80591. * \retval FLAC__bool
  80592. * \c true if the given sample rate conforms to the specification for the
  80593. * subset, else \c false.
  80594. */
  80595. FLAC_API FLAC__bool FLAC__format_sample_rate_is_subset(unsigned sample_rate);
  80596. /** Check a Vorbis comment entry name to see if it conforms to the Vorbis
  80597. * comment specification.
  80598. *
  80599. * Vorbis comment names must be composed only of characters from
  80600. * [0x20-0x3C,0x3E-0x7D].
  80601. *
  80602. * \param name A NUL-terminated string to be checked.
  80603. * \assert
  80604. * \code name != NULL \endcode
  80605. * \retval FLAC__bool
  80606. * \c false if entry name is illegal, else \c true.
  80607. */
  80608. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_name_is_legal(const char *name);
  80609. /** Check a Vorbis comment entry value to see if it conforms to the Vorbis
  80610. * comment specification.
  80611. *
  80612. * Vorbis comment values must be valid UTF-8 sequences.
  80613. *
  80614. * \param value A string to be checked.
  80615. * \param length A the length of \a value in bytes. May be
  80616. * \c (unsigned)(-1) to indicate that \a value is a plain
  80617. * UTF-8 NUL-terminated string.
  80618. * \assert
  80619. * \code value != NULL \endcode
  80620. * \retval FLAC__bool
  80621. * \c false if entry name is illegal, else \c true.
  80622. */
  80623. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_value_is_legal(const FLAC__byte *value, unsigned length);
  80624. /** Check a Vorbis comment entry to see if it conforms to the Vorbis
  80625. * comment specification.
  80626. *
  80627. * Vorbis comment entries must be of the form 'name=value', and 'name' and
  80628. * 'value' must be legal according to
  80629. * FLAC__format_vorbiscomment_entry_name_is_legal() and
  80630. * FLAC__format_vorbiscomment_entry_value_is_legal() respectively.
  80631. *
  80632. * \param entry An entry to be checked.
  80633. * \param length The length of \a entry in bytes.
  80634. * \assert
  80635. * \code value != NULL \endcode
  80636. * \retval FLAC__bool
  80637. * \c false if entry name is illegal, else \c true.
  80638. */
  80639. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_is_legal(const FLAC__byte *entry, unsigned length);
  80640. /** Check a seek table to see if it conforms to the FLAC specification.
  80641. * See the format specification for limits on the contents of the
  80642. * seek table.
  80643. *
  80644. * \param seek_table A pointer to a seek table to be checked.
  80645. * \assert
  80646. * \code seek_table != NULL \endcode
  80647. * \retval FLAC__bool
  80648. * \c false if seek table is illegal, else \c true.
  80649. */
  80650. FLAC_API FLAC__bool FLAC__format_seektable_is_legal(const FLAC__StreamMetadata_SeekTable *seek_table);
  80651. /** Sort a seek table's seek points according to the format specification.
  80652. * This includes a "unique-ification" step to remove duplicates, i.e.
  80653. * seek points with identical \a sample_number values. Duplicate seek
  80654. * points are converted into placeholder points and sorted to the end of
  80655. * the table.
  80656. *
  80657. * \param seek_table A pointer to a seek table to be sorted.
  80658. * \assert
  80659. * \code seek_table != NULL \endcode
  80660. * \retval unsigned
  80661. * The number of duplicate seek points converted into placeholders.
  80662. */
  80663. FLAC_API unsigned FLAC__format_seektable_sort(FLAC__StreamMetadata_SeekTable *seek_table);
  80664. /** Check a cue sheet to see if it conforms to the FLAC specification.
  80665. * See the format specification for limits on the contents of the
  80666. * cue sheet.
  80667. *
  80668. * \param cue_sheet A pointer to an existing cue sheet to be checked.
  80669. * \param check_cd_da_subset If \c true, check CUESHEET against more
  80670. * stringent requirements for a CD-DA (audio) disc.
  80671. * \param violation Address of a pointer to a string. If there is a
  80672. * violation, a pointer to a string explanation of the
  80673. * violation will be returned here. \a violation may be
  80674. * \c NULL if you don't need the returned string. Do not
  80675. * free the returned string; it will always point to static
  80676. * data.
  80677. * \assert
  80678. * \code cue_sheet != NULL \endcode
  80679. * \retval FLAC__bool
  80680. * \c false if cue sheet is illegal, else \c true.
  80681. */
  80682. FLAC_API FLAC__bool FLAC__format_cuesheet_is_legal(const FLAC__StreamMetadata_CueSheet *cue_sheet, FLAC__bool check_cd_da_subset, const char **violation);
  80683. /** Check picture data to see if it conforms to the FLAC specification.
  80684. * See the format specification for limits on the contents of the
  80685. * PICTURE block.
  80686. *
  80687. * \param picture A pointer to existing picture data to be checked.
  80688. * \param violation Address of a pointer to a string. If there is a
  80689. * violation, a pointer to a string explanation of the
  80690. * violation will be returned here. \a violation may be
  80691. * \c NULL if you don't need the returned string. Do not
  80692. * free the returned string; it will always point to static
  80693. * data.
  80694. * \assert
  80695. * \code picture != NULL \endcode
  80696. * \retval FLAC__bool
  80697. * \c false if picture data is illegal, else \c true.
  80698. */
  80699. FLAC_API FLAC__bool FLAC__format_picture_is_legal(const FLAC__StreamMetadata_Picture *picture, const char **violation);
  80700. /* \} */
  80701. #ifdef __cplusplus
  80702. }
  80703. #endif
  80704. #endif
  80705. /********* End of inlined file: format.h *********/
  80706. /********* Start of inlined file: metadata.h *********/
  80707. #ifndef FLAC__METADATA_H
  80708. #define FLAC__METADATA_H
  80709. #include <sys/types.h> /* for off_t */
  80710. /* --------------------------------------------------------------------
  80711. (For an example of how all these routines are used, see the source
  80712. code for the unit tests in src/test_libFLAC/metadata_*.c, or
  80713. metaflac in src/metaflac/)
  80714. ------------------------------------------------------------------*/
  80715. /** \file include/FLAC/metadata.h
  80716. *
  80717. * \brief
  80718. * This module provides functions for creating and manipulating FLAC
  80719. * metadata blocks in memory, and three progressively more powerful
  80720. * interfaces for traversing and editing metadata in FLAC files.
  80721. *
  80722. * See the detailed documentation for each interface in the
  80723. * \link flac_metadata metadata \endlink module.
  80724. */
  80725. /** \defgroup flac_metadata FLAC/metadata.h: metadata interfaces
  80726. * \ingroup flac
  80727. *
  80728. * \brief
  80729. * This module provides functions for creating and manipulating FLAC
  80730. * metadata blocks in memory, and three progressively more powerful
  80731. * interfaces for traversing and editing metadata in native FLAC files.
  80732. * Note that currently only the Chain interface (level 2) supports Ogg
  80733. * FLAC files, and it is read-only i.e. no writing back changed
  80734. * metadata to file.
  80735. *
  80736. * There are three metadata interfaces of increasing complexity:
  80737. *
  80738. * Level 0:
  80739. * Read-only access to the STREAMINFO, VORBIS_COMMENT, CUESHEET, and
  80740. * PICTURE blocks.
  80741. *
  80742. * Level 1:
  80743. * Read-write access to all metadata blocks. This level is write-
  80744. * efficient in most cases (more on this below), and uses less memory
  80745. * than level 2.
  80746. *
  80747. * Level 2:
  80748. * Read-write access to all metadata blocks. This level is write-
  80749. * efficient in all cases, but uses more memory since all metadata for
  80750. * the whole file is read into memory and manipulated before writing
  80751. * out again.
  80752. *
  80753. * What do we mean by efficient? Since FLAC metadata appears at the
  80754. * beginning of the file, when writing metadata back to a FLAC file
  80755. * it is possible to grow or shrink the metadata such that the entire
  80756. * file must be rewritten. However, if the size remains the same during
  80757. * changes or PADDING blocks are utilized, only the metadata needs to be
  80758. * overwritten, which is much faster.
  80759. *
  80760. * Efficient means the whole file is rewritten at most one time, and only
  80761. * when necessary. Level 1 is not efficient only in the case that you
  80762. * cause more than one metadata block to grow or shrink beyond what can
  80763. * be accomodated by padding. In this case you should probably use level
  80764. * 2, which allows you to edit all the metadata for a file in memory and
  80765. * write it out all at once.
  80766. *
  80767. * All levels know how to skip over and not disturb an ID3v2 tag at the
  80768. * front of the file.
  80769. *
  80770. * All levels access files via their filenames. In addition, level 2
  80771. * has additional alternative read and write functions that take an I/O
  80772. * handle and callbacks, for situations where access by filename is not
  80773. * possible.
  80774. *
  80775. * In addition to the three interfaces, this module defines functions for
  80776. * creating and manipulating various metadata objects in memory. As we see
  80777. * from the Format module, FLAC metadata blocks in memory are very primitive
  80778. * structures for storing information in an efficient way. Reading
  80779. * information from the structures is easy but creating or modifying them
  80780. * directly is more complex. The metadata object routines here facilitate
  80781. * this by taking care of the consistency and memory management drudgery.
  80782. *
  80783. * Unless you will be using the level 1 or 2 interfaces to modify existing
  80784. * metadata however, you will not probably not need these.
  80785. *
  80786. * From a dependency standpoint, none of the encoders or decoders require
  80787. * the metadata module. This is so that embedded users can strip out the
  80788. * metadata module from libFLAC to reduce the size and complexity.
  80789. */
  80790. #ifdef __cplusplus
  80791. extern "C" {
  80792. #endif
  80793. /** \defgroup flac_metadata_level0 FLAC/metadata.h: metadata level 0 interface
  80794. * \ingroup flac_metadata
  80795. *
  80796. * \brief
  80797. * The level 0 interface consists of individual routines to read the
  80798. * STREAMINFO, VORBIS_COMMENT, CUESHEET, and PICTURE blocks, requiring
  80799. * only a filename.
  80800. *
  80801. * They try to skip any ID3v2 tag at the head of the file.
  80802. *
  80803. * \{
  80804. */
  80805. /** Read the STREAMINFO metadata block of the given FLAC file. This function
  80806. * will try to skip any ID3v2 tag at the head of the file.
  80807. *
  80808. * \param filename The path to the FLAC file to read.
  80809. * \param streaminfo A pointer to space for the STREAMINFO block. Since
  80810. * FLAC__StreamMetadata is a simple structure with no
  80811. * memory allocation involved, you pass the address of
  80812. * an existing structure. It need not be initialized.
  80813. * \assert
  80814. * \code filename != NULL \endcode
  80815. * \code streaminfo != NULL \endcode
  80816. * \retval FLAC__bool
  80817. * \c true if a valid STREAMINFO block was read from \a filename. Returns
  80818. * \c false if there was a memory allocation error, a file decoder error,
  80819. * or the file contained no STREAMINFO block. (A memory allocation error
  80820. * is possible because this function must set up a file decoder.)
  80821. */
  80822. FLAC_API FLAC__bool FLAC__metadata_get_streaminfo(const char *filename, FLAC__StreamMetadata *streaminfo);
  80823. /** Read the VORBIS_COMMENT metadata block of the given FLAC file. This
  80824. * function will try to skip any ID3v2 tag at the head of the file.
  80825. *
  80826. * \param filename The path to the FLAC file to read.
  80827. * \param tags The address where the returned pointer will be
  80828. * stored. The \a tags object must be deleted by
  80829. * the caller using FLAC__metadata_object_delete().
  80830. * \assert
  80831. * \code filename != NULL \endcode
  80832. * \code tags != NULL \endcode
  80833. * \retval FLAC__bool
  80834. * \c true if a valid VORBIS_COMMENT block was read from \a filename,
  80835. * and \a *tags will be set to the address of the metadata structure.
  80836. * Returns \c false if there was a memory allocation error, a file
  80837. * decoder error, or the file contained no VORBIS_COMMENT block, and
  80838. * \a *tags will be set to \c NULL.
  80839. */
  80840. FLAC_API FLAC__bool FLAC__metadata_get_tags(const char *filename, FLAC__StreamMetadata **tags);
  80841. /** Read the CUESHEET metadata block of the given FLAC file. This
  80842. * function will try to skip any ID3v2 tag at the head of the file.
  80843. *
  80844. * \param filename The path to the FLAC file to read.
  80845. * \param cuesheet The address where the returned pointer will be
  80846. * stored. The \a cuesheet object must be deleted by
  80847. * the caller using FLAC__metadata_object_delete().
  80848. * \assert
  80849. * \code filename != NULL \endcode
  80850. * \code cuesheet != NULL \endcode
  80851. * \retval FLAC__bool
  80852. * \c true if a valid CUESHEET block was read from \a filename,
  80853. * and \a *cuesheet will be set to the address of the metadata
  80854. * structure. Returns \c false if there was a memory allocation
  80855. * error, a file decoder error, or the file contained no CUESHEET
  80856. * block, and \a *cuesheet will be set to \c NULL.
  80857. */
  80858. FLAC_API FLAC__bool FLAC__metadata_get_cuesheet(const char *filename, FLAC__StreamMetadata **cuesheet);
  80859. /** Read a PICTURE metadata block of the given FLAC file. This
  80860. * function will try to skip any ID3v2 tag at the head of the file.
  80861. * Since there can be more than one PICTURE block in a file, this
  80862. * function takes a number of parameters that act as constraints to
  80863. * the search. The PICTURE block with the largest area matching all
  80864. * the constraints will be returned, or \a *picture will be set to
  80865. * \c NULL if there was no such block.
  80866. *
  80867. * \param filename The path to the FLAC file to read.
  80868. * \param picture The address where the returned pointer will be
  80869. * stored. The \a picture object must be deleted by
  80870. * the caller using FLAC__metadata_object_delete().
  80871. * \param type The desired picture type. Use \c -1 to mean
  80872. * "any type".
  80873. * \param mime_type The desired MIME type, e.g. "image/jpeg". The
  80874. * string will be matched exactly. Use \c NULL to
  80875. * mean "any MIME type".
  80876. * \param description The desired description. The string will be
  80877. * matched exactly. Use \c NULL to mean "any
  80878. * description".
  80879. * \param max_width The maximum width in pixels desired. Use
  80880. * \c (unsigned)(-1) to mean "any width".
  80881. * \param max_height The maximum height in pixels desired. Use
  80882. * \c (unsigned)(-1) to mean "any height".
  80883. * \param max_depth The maximum color depth in bits-per-pixel desired.
  80884. * Use \c (unsigned)(-1) to mean "any depth".
  80885. * \param max_colors The maximum number of colors desired. Use
  80886. * \c (unsigned)(-1) to mean "any number of colors".
  80887. * \assert
  80888. * \code filename != NULL \endcode
  80889. * \code picture != NULL \endcode
  80890. * \retval FLAC__bool
  80891. * \c true if a valid PICTURE block was read from \a filename,
  80892. * and \a *picture will be set to the address of the metadata
  80893. * structure. Returns \c false if there was a memory allocation
  80894. * error, a file decoder error, or the file contained no PICTURE
  80895. * block, and \a *picture will be set to \c NULL.
  80896. */
  80897. 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);
  80898. /* \} */
  80899. /** \defgroup flac_metadata_level1 FLAC/metadata.h: metadata level 1 interface
  80900. * \ingroup flac_metadata
  80901. *
  80902. * \brief
  80903. * The level 1 interface provides read-write access to FLAC file metadata and
  80904. * operates directly on the FLAC file.
  80905. *
  80906. * The general usage of this interface is:
  80907. *
  80908. * - Create an iterator using FLAC__metadata_simple_iterator_new()
  80909. * - Attach it to a file using FLAC__metadata_simple_iterator_init() and check
  80910. * the exit code. Call FLAC__metadata_simple_iterator_is_writable() to
  80911. * see if the file is writable, or only read access is allowed.
  80912. * - Use FLAC__metadata_simple_iterator_next() and
  80913. * FLAC__metadata_simple_iterator_prev() to traverse the blocks.
  80914. * This is does not read the actual blocks themselves.
  80915. * FLAC__metadata_simple_iterator_next() is relatively fast.
  80916. * FLAC__metadata_simple_iterator_prev() is slower since it needs to search
  80917. * forward from the front of the file.
  80918. * - Use FLAC__metadata_simple_iterator_get_block_type() or
  80919. * FLAC__metadata_simple_iterator_get_block() to access the actual data at
  80920. * the current iterator position. The returned object is yours to modify
  80921. * and free.
  80922. * - Use FLAC__metadata_simple_iterator_set_block() to write a modified block
  80923. * back. You must have write permission to the original file. Make sure to
  80924. * read the whole comment to FLAC__metadata_simple_iterator_set_block()
  80925. * below.
  80926. * - Use FLAC__metadata_simple_iterator_insert_block_after() to add new blocks.
  80927. * Use the object creation functions from
  80928. * \link flac_metadata_object here \endlink to generate new objects.
  80929. * - Use FLAC__metadata_simple_iterator_delete_block() to remove the block
  80930. * currently referred to by the iterator, or replace it with padding.
  80931. * - Destroy the iterator with FLAC__metadata_simple_iterator_delete() when
  80932. * finished.
  80933. *
  80934. * \note
  80935. * The FLAC file remains open the whole time between
  80936. * FLAC__metadata_simple_iterator_init() and
  80937. * FLAC__metadata_simple_iterator_delete(), so make sure you are not altering
  80938. * the file during this time.
  80939. *
  80940. * \note
  80941. * Do not modify the \a is_last, \a length, or \a type fields of returned
  80942. * FLAC__StreamMetadata objects. These are managed automatically.
  80943. *
  80944. * \note
  80945. * If any of the modification functions
  80946. * (FLAC__metadata_simple_iterator_set_block(),
  80947. * FLAC__metadata_simple_iterator_delete_block(),
  80948. * FLAC__metadata_simple_iterator_insert_block_after(), etc.) return \c false,
  80949. * you should delete the iterator as it may no longer be valid.
  80950. *
  80951. * \{
  80952. */
  80953. struct FLAC__Metadata_SimpleIterator;
  80954. /** The opaque structure definition for the level 1 iterator type.
  80955. * See the
  80956. * \link flac_metadata_level1 metadata level 1 module \endlink
  80957. * for a detailed description.
  80958. */
  80959. typedef struct FLAC__Metadata_SimpleIterator FLAC__Metadata_SimpleIterator;
  80960. /** Status type for FLAC__Metadata_SimpleIterator.
  80961. *
  80962. * The iterator's current status can be obtained by calling FLAC__metadata_simple_iterator_status().
  80963. */
  80964. typedef enum {
  80965. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK = 0,
  80966. /**< The iterator is in the normal OK state */
  80967. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT,
  80968. /**< The data passed into a function violated the function's usage criteria */
  80969. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ERROR_OPENING_FILE,
  80970. /**< The iterator could not open the target file */
  80971. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_A_FLAC_FILE,
  80972. /**< The iterator could not find the FLAC signature at the start of the file */
  80973. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_WRITABLE,
  80974. /**< The iterator tried to write to a file that was not writable */
  80975. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_BAD_METADATA,
  80976. /**< The iterator encountered input that does not conform to the FLAC metadata specification */
  80977. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR,
  80978. /**< The iterator encountered an error while reading the FLAC file */
  80979. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR,
  80980. /**< The iterator encountered an error while seeking in the FLAC file */
  80981. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_WRITE_ERROR,
  80982. /**< The iterator encountered an error while writing the FLAC file */
  80983. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_RENAME_ERROR,
  80984. /**< The iterator encountered an error renaming the FLAC file */
  80985. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_UNLINK_ERROR,
  80986. /**< The iterator encountered an error removing the temporary file */
  80987. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR,
  80988. /**< Memory allocation failed */
  80989. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_INTERNAL_ERROR
  80990. /**< The caller violated an assertion or an unexpected error occurred */
  80991. } FLAC__Metadata_SimpleIteratorStatus;
  80992. /** Maps a FLAC__Metadata_SimpleIteratorStatus to a C string.
  80993. *
  80994. * Using a FLAC__Metadata_SimpleIteratorStatus as the index to this array
  80995. * will give the string equivalent. The contents should not be modified.
  80996. */
  80997. extern FLAC_API const char * const FLAC__Metadata_SimpleIteratorStatusString[];
  80998. /** Create a new iterator instance.
  80999. *
  81000. * \retval FLAC__Metadata_SimpleIterator*
  81001. * \c NULL if there was an error allocating memory, else the new instance.
  81002. */
  81003. FLAC_API FLAC__Metadata_SimpleIterator *FLAC__metadata_simple_iterator_new(void);
  81004. /** Free an iterator instance. Deletes the object pointed to by \a iterator.
  81005. *
  81006. * \param iterator A pointer to an existing iterator.
  81007. * \assert
  81008. * \code iterator != NULL \endcode
  81009. */
  81010. FLAC_API void FLAC__metadata_simple_iterator_delete(FLAC__Metadata_SimpleIterator *iterator);
  81011. /** Get the current status of the iterator. Call this after a function
  81012. * returns \c false to get the reason for the error. Also resets the status
  81013. * to FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK.
  81014. *
  81015. * \param iterator A pointer to an existing iterator.
  81016. * \assert
  81017. * \code iterator != NULL \endcode
  81018. * \retval FLAC__Metadata_SimpleIteratorStatus
  81019. * The current status of the iterator.
  81020. */
  81021. FLAC_API FLAC__Metadata_SimpleIteratorStatus FLAC__metadata_simple_iterator_status(FLAC__Metadata_SimpleIterator *iterator);
  81022. /** Initialize the iterator to point to the first metadata block in the
  81023. * given FLAC file.
  81024. *
  81025. * \param iterator A pointer to an existing iterator.
  81026. * \param filename The path to the FLAC file.
  81027. * \param read_only If \c true, the FLAC file will be opened
  81028. * in read-only mode; if \c false, the FLAC
  81029. * file will be opened for edit even if no
  81030. * edits are performed.
  81031. * \param preserve_file_stats If \c true, the owner and modification
  81032. * time will be preserved even if the FLAC
  81033. * file is written to.
  81034. * \assert
  81035. * \code iterator != NULL \endcode
  81036. * \code filename != NULL \endcode
  81037. * \retval FLAC__bool
  81038. * \c false if a memory allocation error occurs, the file can't be
  81039. * opened, or another error occurs, else \c true.
  81040. */
  81041. 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);
  81042. /** Returns \c true if the FLAC file is writable. If \c false, calls to
  81043. * FLAC__metadata_simple_iterator_set_block() and
  81044. * FLAC__metadata_simple_iterator_insert_block_after() will fail.
  81045. *
  81046. * \param iterator A pointer to an existing iterator.
  81047. * \assert
  81048. * \code iterator != NULL \endcode
  81049. * \retval FLAC__bool
  81050. * See above.
  81051. */
  81052. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_is_writable(const FLAC__Metadata_SimpleIterator *iterator);
  81053. /** Moves the iterator forward one metadata block, returning \c false if
  81054. * already at the end.
  81055. *
  81056. * \param iterator A pointer to an existing initialized iterator.
  81057. * \assert
  81058. * \code iterator != NULL \endcode
  81059. * \a iterator has been successfully initialized with
  81060. * FLAC__metadata_simple_iterator_init()
  81061. * \retval FLAC__bool
  81062. * \c false if already at the last metadata block of the chain, else
  81063. * \c true.
  81064. */
  81065. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_next(FLAC__Metadata_SimpleIterator *iterator);
  81066. /** Moves the iterator backward one metadata block, returning \c false if
  81067. * already at the beginning.
  81068. *
  81069. * \param iterator A pointer to an existing initialized iterator.
  81070. * \assert
  81071. * \code iterator != NULL \endcode
  81072. * \a iterator has been successfully initialized with
  81073. * FLAC__metadata_simple_iterator_init()
  81074. * \retval FLAC__bool
  81075. * \c false if already at the first metadata block of the chain, else
  81076. * \c true.
  81077. */
  81078. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_prev(FLAC__Metadata_SimpleIterator *iterator);
  81079. /** Returns a flag telling if the current metadata block is the last.
  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 FLAC__bool
  81087. * \c true if the current metadata block is the last in the file,
  81088. * else \c false.
  81089. */
  81090. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_is_last(const FLAC__Metadata_SimpleIterator *iterator);
  81091. /** Get the offset of the metadata block at the current position. This
  81092. * avoids reading the actual block data which can save time for large
  81093. * blocks.
  81094. *
  81095. * \param iterator A pointer to an existing initialized iterator.
  81096. * \assert
  81097. * \code iterator != NULL \endcode
  81098. * \a iterator has been successfully initialized with
  81099. * FLAC__metadata_simple_iterator_init()
  81100. * \retval off_t
  81101. * The offset of the metadata block at the current iterator position.
  81102. * This is the byte offset relative to the beginning of the file of
  81103. * the current metadata block's header.
  81104. */
  81105. FLAC_API off_t FLAC__metadata_simple_iterator_get_block_offset(const FLAC__Metadata_SimpleIterator *iterator);
  81106. /** Get the type of the metadata block at the current position. This
  81107. * avoids reading the actual block data which can save time for large
  81108. * blocks.
  81109. *
  81110. * \param iterator A pointer to an existing initialized iterator.
  81111. * \assert
  81112. * \code iterator != NULL \endcode
  81113. * \a iterator has been successfully initialized with
  81114. * FLAC__metadata_simple_iterator_init()
  81115. * \retval FLAC__MetadataType
  81116. * The type of the metadata block at the current iterator position.
  81117. */
  81118. FLAC_API FLAC__MetadataType FLAC__metadata_simple_iterator_get_block_type(const FLAC__Metadata_SimpleIterator *iterator);
  81119. /** Get the length of the metadata block at the current position. This
  81120. * avoids reading the actual block data which can save time for large
  81121. * blocks.
  81122. *
  81123. * \param iterator A pointer to an existing initialized iterator.
  81124. * \assert
  81125. * \code iterator != NULL \endcode
  81126. * \a iterator has been successfully initialized with
  81127. * FLAC__metadata_simple_iterator_init()
  81128. * \retval unsigned
  81129. * The length of the metadata block at the current iterator position.
  81130. * The is same length as that in the
  81131. * <a href="http://flac.sourceforge.net/format.html#metadata_block_header">metadata block header</a>,
  81132. * i.e. the length of the metadata body that follows the header.
  81133. */
  81134. FLAC_API unsigned FLAC__metadata_simple_iterator_get_block_length(const FLAC__Metadata_SimpleIterator *iterator);
  81135. /** Get the application ID of the \c APPLICATION block at the current
  81136. * position. This avoids reading the actual block data which can save
  81137. * time for large blocks.
  81138. *
  81139. * \param iterator A pointer to an existing initialized iterator.
  81140. * \param id A pointer to a buffer of at least \c 4 bytes where
  81141. * the ID will be stored.
  81142. * \assert
  81143. * \code iterator != NULL \endcode
  81144. * \code id != NULL \endcode
  81145. * \a iterator has been successfully initialized with
  81146. * FLAC__metadata_simple_iterator_init()
  81147. * \retval FLAC__bool
  81148. * \c true if the ID was successfully read, else \c false, in which
  81149. * case you should check FLAC__metadata_simple_iterator_status() to
  81150. * find out why. If the status is
  81151. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT, then the
  81152. * current metadata block is not an \c APPLICATION block. Otherwise
  81153. * if the status is
  81154. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR or
  81155. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR, an I/O error
  81156. * occurred and the iterator can no longer be used.
  81157. */
  81158. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_get_application_id(FLAC__Metadata_SimpleIterator *iterator, FLAC__byte *id);
  81159. /** Get the metadata block at the current position. You can modify the
  81160. * block but must use FLAC__metadata_simple_iterator_set_block() to
  81161. * write it back to the FLAC file.
  81162. *
  81163. * You must call FLAC__metadata_object_delete() on the returned object
  81164. * when you are finished with it.
  81165. *
  81166. * \param iterator A pointer to an existing initialized iterator.
  81167. * \assert
  81168. * \code iterator != NULL \endcode
  81169. * \a iterator has been successfully initialized with
  81170. * FLAC__metadata_simple_iterator_init()
  81171. * \retval FLAC__StreamMetadata*
  81172. * The current metadata block, or \c NULL if there was a memory
  81173. * allocation error.
  81174. */
  81175. FLAC_API FLAC__StreamMetadata *FLAC__metadata_simple_iterator_get_block(FLAC__Metadata_SimpleIterator *iterator);
  81176. /** Write a block back to the FLAC file. This function tries to be
  81177. * as efficient as possible; how the block is actually written is
  81178. * shown by the following:
  81179. *
  81180. * Existing block is a STREAMINFO block and the new block is a
  81181. * STREAMINFO block: the new block is written in place. Make sure
  81182. * you know what you're doing when changing the values of a
  81183. * STREAMINFO block.
  81184. *
  81185. * Existing block is a STREAMINFO block and the new block is a
  81186. * not a STREAMINFO block: this is an error since the first block
  81187. * must be a STREAMINFO block. Returns \c false without altering the
  81188. * file.
  81189. *
  81190. * Existing block is not a STREAMINFO block and the new block is a
  81191. * STREAMINFO block: this is an error since there may be only one
  81192. * STREAMINFO block. Returns \c false without altering the file.
  81193. *
  81194. * Existing block and new block are the same length: the existing
  81195. * block will be replaced by the new block, written in place.
  81196. *
  81197. * Existing block is longer than new block: if use_padding is \c true,
  81198. * the existing block will be overwritten in place with the new
  81199. * block followed by a PADDING block, if possible, to make the total
  81200. * size the same as the existing block. Remember that a padding
  81201. * block requires at least four bytes so if the difference in size
  81202. * between the new block and existing block is less than that, the
  81203. * entire file will have to be rewritten, using the new block's
  81204. * exact size. If use_padding is \c false, the entire file will be
  81205. * rewritten, replacing the existing block by the new block.
  81206. *
  81207. * Existing block is shorter than new block: if use_padding is \c true,
  81208. * the function will try and expand the new block into the following
  81209. * PADDING block, if it exists and doing so won't shrink the PADDING
  81210. * block to less than 4 bytes. If there is no following PADDING
  81211. * block, or it will shrink to less than 4 bytes, or use_padding is
  81212. * \c false, the entire file is rewritten, replacing the existing block
  81213. * with the new block. Note that in this case any following PADDING
  81214. * block is preserved as is.
  81215. *
  81216. * After writing the block, the iterator will remain in the same
  81217. * place, i.e. pointing to the new block.
  81218. *
  81219. * \param iterator A pointer to an existing initialized iterator.
  81220. * \param block The block to set.
  81221. * \param use_padding See above.
  81222. * \assert
  81223. * \code iterator != NULL \endcode
  81224. * \a iterator has been successfully initialized with
  81225. * FLAC__metadata_simple_iterator_init()
  81226. * \code block != NULL \endcode
  81227. * \retval FLAC__bool
  81228. * \c true if successful, else \c false.
  81229. */
  81230. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_set_block(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, FLAC__bool use_padding);
  81231. /** This is similar to FLAC__metadata_simple_iterator_set_block()
  81232. * except that instead of writing over an existing block, it appends
  81233. * a block after the existing block. \a use_padding is again used to
  81234. * tell the function to try an expand into following padding in an
  81235. * attempt to avoid rewriting the entire file.
  81236. *
  81237. * This function will fail and return \c false if given a STREAMINFO
  81238. * block.
  81239. *
  81240. * After writing the block, the iterator will be pointing to the
  81241. * new block.
  81242. *
  81243. * \param iterator A pointer to an existing initialized iterator.
  81244. * \param block The block to set.
  81245. * \param use_padding See above.
  81246. * \assert
  81247. * \code iterator != NULL \endcode
  81248. * \a iterator has been successfully initialized with
  81249. * FLAC__metadata_simple_iterator_init()
  81250. * \code block != NULL \endcode
  81251. * \retval FLAC__bool
  81252. * \c true if successful, else \c false.
  81253. */
  81254. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_insert_block_after(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, FLAC__bool use_padding);
  81255. /** Deletes the block at the current position. This will cause the
  81256. * entire FLAC file to be rewritten, unless \a use_padding is \c true,
  81257. * in which case the block will be replaced by an equal-sized PADDING
  81258. * block. The iterator will be left pointing to the block before the
  81259. * one just deleted.
  81260. *
  81261. * You may not delete the STREAMINFO block.
  81262. *
  81263. * \param iterator A pointer to an existing initialized iterator.
  81264. * \param use_padding See above.
  81265. * \assert
  81266. * \code iterator != NULL \endcode
  81267. * \a iterator has been successfully initialized with
  81268. * FLAC__metadata_simple_iterator_init()
  81269. * \retval FLAC__bool
  81270. * \c true if successful, else \c false.
  81271. */
  81272. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_delete_block(FLAC__Metadata_SimpleIterator *iterator, FLAC__bool use_padding);
  81273. /* \} */
  81274. /** \defgroup flac_metadata_level2 FLAC/metadata.h: metadata level 2 interface
  81275. * \ingroup flac_metadata
  81276. *
  81277. * \brief
  81278. * The level 2 interface provides read-write access to FLAC file metadata;
  81279. * all metadata is read into memory, operated on in memory, and then written
  81280. * to file, which is more efficient than level 1 when editing multiple blocks.
  81281. *
  81282. * Currently Ogg FLAC is supported for read only, via
  81283. * FLAC__metadata_chain_read_ogg() but a subsequent
  81284. * FLAC__metadata_chain_write() will fail.
  81285. *
  81286. * The general usage of this interface is:
  81287. *
  81288. * - Create a new chain using FLAC__metadata_chain_new(). A chain is a
  81289. * linked list of FLAC metadata blocks.
  81290. * - Read all metadata into the the chain from a FLAC file using
  81291. * FLAC__metadata_chain_read() or FLAC__metadata_chain_read_ogg() and
  81292. * check the status.
  81293. * - Optionally, consolidate the padding using
  81294. * FLAC__metadata_chain_merge_padding() or
  81295. * FLAC__metadata_chain_sort_padding().
  81296. * - Create a new iterator using FLAC__metadata_iterator_new()
  81297. * - Initialize the iterator to point to the first element in the chain
  81298. * using FLAC__metadata_iterator_init()
  81299. * - Traverse the chain using FLAC__metadata_iterator_next and
  81300. * FLAC__metadata_iterator_prev().
  81301. * - Get a block for reading or modification using
  81302. * FLAC__metadata_iterator_get_block(). The pointer to the object
  81303. * inside the chain is returned, so the block is yours to modify.
  81304. * Changes will be reflected in the FLAC file when you write the
  81305. * chain. You can also add and delete blocks (see functions below).
  81306. * - When done, write out the chain using FLAC__metadata_chain_write().
  81307. * Make sure to read the whole comment to the function below.
  81308. * - Delete the chain using FLAC__metadata_chain_delete().
  81309. *
  81310. * \note
  81311. * Even though the FLAC file is not open while the chain is being
  81312. * manipulated, you must not alter the file externally during
  81313. * this time. The chain assumes the FLAC file will not change
  81314. * between the time of FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg()
  81315. * and FLAC__metadata_chain_write().
  81316. *
  81317. * \note
  81318. * Do not modify the is_last, length, or type fields of returned
  81319. * FLAC__StreamMetadata objects. These are managed automatically.
  81320. *
  81321. * \note
  81322. * The metadata objects returned by FLAC__metadata_iterator_get_block()
  81323. * are owned by the chain; do not FLAC__metadata_object_delete() them.
  81324. * In the same way, blocks passed to FLAC__metadata_iterator_set_block()
  81325. * become owned by the chain and they will be deleted when the chain is
  81326. * deleted.
  81327. *
  81328. * \{
  81329. */
  81330. struct FLAC__Metadata_Chain;
  81331. /** The opaque structure definition for the level 2 chain type.
  81332. */
  81333. typedef struct FLAC__Metadata_Chain FLAC__Metadata_Chain;
  81334. struct FLAC__Metadata_Iterator;
  81335. /** The opaque structure definition for the level 2 iterator type.
  81336. */
  81337. typedef struct FLAC__Metadata_Iterator FLAC__Metadata_Iterator;
  81338. typedef enum {
  81339. FLAC__METADATA_CHAIN_STATUS_OK = 0,
  81340. /**< The chain is in the normal OK state */
  81341. FLAC__METADATA_CHAIN_STATUS_ILLEGAL_INPUT,
  81342. /**< The data passed into a function violated the function's usage criteria */
  81343. FLAC__METADATA_CHAIN_STATUS_ERROR_OPENING_FILE,
  81344. /**< The chain could not open the target file */
  81345. FLAC__METADATA_CHAIN_STATUS_NOT_A_FLAC_FILE,
  81346. /**< The chain could not find the FLAC signature at the start of the file */
  81347. FLAC__METADATA_CHAIN_STATUS_NOT_WRITABLE,
  81348. /**< The chain tried to write to a file that was not writable */
  81349. FLAC__METADATA_CHAIN_STATUS_BAD_METADATA,
  81350. /**< The chain encountered input that does not conform to the FLAC metadata specification */
  81351. FLAC__METADATA_CHAIN_STATUS_READ_ERROR,
  81352. /**< The chain encountered an error while reading the FLAC file */
  81353. FLAC__METADATA_CHAIN_STATUS_SEEK_ERROR,
  81354. /**< The chain encountered an error while seeking in the FLAC file */
  81355. FLAC__METADATA_CHAIN_STATUS_WRITE_ERROR,
  81356. /**< The chain encountered an error while writing the FLAC file */
  81357. FLAC__METADATA_CHAIN_STATUS_RENAME_ERROR,
  81358. /**< The chain encountered an error renaming the FLAC file */
  81359. FLAC__METADATA_CHAIN_STATUS_UNLINK_ERROR,
  81360. /**< The chain encountered an error removing the temporary file */
  81361. FLAC__METADATA_CHAIN_STATUS_MEMORY_ALLOCATION_ERROR,
  81362. /**< Memory allocation failed */
  81363. FLAC__METADATA_CHAIN_STATUS_INTERNAL_ERROR,
  81364. /**< The caller violated an assertion or an unexpected error occurred */
  81365. FLAC__METADATA_CHAIN_STATUS_INVALID_CALLBACKS,
  81366. /**< One or more of the required callbacks was NULL */
  81367. FLAC__METADATA_CHAIN_STATUS_READ_WRITE_MISMATCH,
  81368. /**< FLAC__metadata_chain_write() was called on a chain read by
  81369. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  81370. * or
  81371. * FLAC__metadata_chain_write_with_callbacks()/FLAC__metadata_chain_write_with_callbacks_and_tempfile()
  81372. * was called on a chain read by
  81373. * FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  81374. * Matching read/write methods must always be used. */
  81375. FLAC__METADATA_CHAIN_STATUS_WRONG_WRITE_CALL
  81376. /**< FLAC__metadata_chain_write_with_callbacks() was called when the
  81377. * chain write requires a tempfile; use
  81378. * FLAC__metadata_chain_write_with_callbacks_and_tempfile() instead.
  81379. * Or, FLAC__metadata_chain_write_with_callbacks_and_tempfile() was
  81380. * called when the chain write does not require a tempfile; use
  81381. * FLAC__metadata_chain_write_with_callbacks() instead.
  81382. * Always check FLAC__metadata_chain_check_if_tempfile_needed()
  81383. * before writing via callbacks. */
  81384. } FLAC__Metadata_ChainStatus;
  81385. /** Maps a FLAC__Metadata_ChainStatus to a C string.
  81386. *
  81387. * Using a FLAC__Metadata_ChainStatus as the index to this array
  81388. * will give the string equivalent. The contents should not be modified.
  81389. */
  81390. extern FLAC_API const char * const FLAC__Metadata_ChainStatusString[];
  81391. /*********** FLAC__Metadata_Chain ***********/
  81392. /** Create a new chain instance.
  81393. *
  81394. * \retval FLAC__Metadata_Chain*
  81395. * \c NULL if there was an error allocating memory, else the new instance.
  81396. */
  81397. FLAC_API FLAC__Metadata_Chain *FLAC__metadata_chain_new(void);
  81398. /** Free a chain instance. Deletes the object pointed to by \a chain.
  81399. *
  81400. * \param chain A pointer to an existing chain.
  81401. * \assert
  81402. * \code chain != NULL \endcode
  81403. */
  81404. FLAC_API void FLAC__metadata_chain_delete(FLAC__Metadata_Chain *chain);
  81405. /** Get the current status of the chain. Call this after a function
  81406. * returns \c false to get the reason for the error. Also resets the
  81407. * status to FLAC__METADATA_CHAIN_STATUS_OK.
  81408. *
  81409. * \param chain A pointer to an existing chain.
  81410. * \assert
  81411. * \code chain != NULL \endcode
  81412. * \retval FLAC__Metadata_ChainStatus
  81413. * The current status of the chain.
  81414. */
  81415. FLAC_API FLAC__Metadata_ChainStatus FLAC__metadata_chain_status(FLAC__Metadata_Chain *chain);
  81416. /** Read all metadata from a FLAC file into the chain.
  81417. *
  81418. * \param chain A pointer to an existing chain.
  81419. * \param filename The path to the FLAC file to read.
  81420. * \assert
  81421. * \code chain != NULL \endcode
  81422. * \code filename != NULL \endcode
  81423. * \retval FLAC__bool
  81424. * \c true if a valid list of metadata blocks was read from
  81425. * \a filename, else \c false. On failure, check the status with
  81426. * FLAC__metadata_chain_status().
  81427. */
  81428. FLAC_API FLAC__bool FLAC__metadata_chain_read(FLAC__Metadata_Chain *chain, const char *filename);
  81429. /** Read all metadata from an Ogg FLAC file into the chain.
  81430. *
  81431. * \note Ogg FLAC metadata data writing is not supported yet and
  81432. * FLAC__metadata_chain_write() will fail.
  81433. *
  81434. * \param chain A pointer to an existing chain.
  81435. * \param filename The path to the Ogg FLAC file to read.
  81436. * \assert
  81437. * \code chain != NULL \endcode
  81438. * \code filename != NULL \endcode
  81439. * \retval FLAC__bool
  81440. * \c true if a valid list of metadata blocks was read from
  81441. * \a filename, else \c false. On failure, check the status with
  81442. * FLAC__metadata_chain_status().
  81443. */
  81444. FLAC_API FLAC__bool FLAC__metadata_chain_read_ogg(FLAC__Metadata_Chain *chain, const char *filename);
  81445. /** Read all metadata from a FLAC stream into the chain via I/O callbacks.
  81446. *
  81447. * The \a handle need only be open for reading, but must be seekable.
  81448. * The equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  81449. * for Windows).
  81450. *
  81451. * \param chain A pointer to an existing chain.
  81452. * \param handle The I/O handle of the FLAC stream to read. The
  81453. * handle will NOT be closed after the metadata is read;
  81454. * that is the duty of the caller.
  81455. * \param callbacks
  81456. * A set of callbacks to use for I/O. The mandatory
  81457. * callbacks are \a read, \a seek, and \a tell.
  81458. * \assert
  81459. * \code chain != NULL \endcode
  81460. * \retval FLAC__bool
  81461. * \c true if a valid list of metadata blocks was read from
  81462. * \a handle, else \c false. On failure, check the status with
  81463. * FLAC__metadata_chain_status().
  81464. */
  81465. FLAC_API FLAC__bool FLAC__metadata_chain_read_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  81466. /** Read all metadata from an Ogg FLAC stream into the chain via I/O callbacks.
  81467. *
  81468. * The \a handle need only be open for reading, but must be seekable.
  81469. * The equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  81470. * for Windows).
  81471. *
  81472. * \note Ogg FLAC metadata data writing is not supported yet and
  81473. * FLAC__metadata_chain_write() will fail.
  81474. *
  81475. * \param chain A pointer to an existing chain.
  81476. * \param handle The I/O handle of the Ogg FLAC stream to read. The
  81477. * handle will NOT be closed after the metadata is read;
  81478. * that is the duty of the caller.
  81479. * \param callbacks
  81480. * A set of callbacks to use for I/O. The mandatory
  81481. * callbacks are \a read, \a seek, and \a tell.
  81482. * \assert
  81483. * \code chain != NULL \endcode
  81484. * \retval FLAC__bool
  81485. * \c true if a valid list of metadata blocks was read from
  81486. * \a handle, else \c false. On failure, check the status with
  81487. * FLAC__metadata_chain_status().
  81488. */
  81489. FLAC_API FLAC__bool FLAC__metadata_chain_read_ogg_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  81490. /** Checks if writing the given chain would require the use of a
  81491. * temporary file, or if it could be written in place.
  81492. *
  81493. * Under certain conditions, padding can be utilized so that writing
  81494. * edited metadata back to the FLAC file does not require rewriting the
  81495. * entire file. If rewriting is required, then a temporary workfile is
  81496. * required. When writing metadata using callbacks, you must check
  81497. * this function to know whether to call
  81498. * FLAC__metadata_chain_write_with_callbacks() or
  81499. * FLAC__metadata_chain_write_with_callbacks_and_tempfile(). When
  81500. * writing with FLAC__metadata_chain_write(), the temporary file is
  81501. * handled internally.
  81502. *
  81503. * \param chain A pointer to an existing chain.
  81504. * \param use_padding
  81505. * Whether or not padding will be allowed to be used
  81506. * during the write. The value of \a use_padding given
  81507. * here must match the value later passed to
  81508. * FLAC__metadata_chain_write_with_callbacks() or
  81509. * FLAC__metadata_chain_write_with_callbacks_with_tempfile().
  81510. * \assert
  81511. * \code chain != NULL \endcode
  81512. * \retval FLAC__bool
  81513. * \c true if writing the current chain would require a tempfile, or
  81514. * \c false if metadata can be written in place.
  81515. */
  81516. FLAC_API FLAC__bool FLAC__metadata_chain_check_if_tempfile_needed(FLAC__Metadata_Chain *chain, FLAC__bool use_padding);
  81517. /** Write all metadata out to the FLAC file. This function tries to be as
  81518. * efficient as possible; how the metadata is actually written is shown by
  81519. * the following:
  81520. *
  81521. * If the current chain is the same size as the existing metadata, the new
  81522. * data is written in place.
  81523. *
  81524. * If the current chain is longer than the existing metadata, and
  81525. * \a use_padding is \c true, and the last block is a PADDING block of
  81526. * sufficient length, the function will truncate the final padding block
  81527. * so that the overall size of the metadata is the same as the existing
  81528. * metadata, and then just rewrite the metadata. Otherwise, if not all of
  81529. * the above conditions are met, the entire FLAC file must be rewritten.
  81530. * If you want to use padding this way it is a good idea to call
  81531. * FLAC__metadata_chain_sort_padding() first so that you have the maximum
  81532. * amount of padding to work with, unless you need to preserve ordering
  81533. * of the PADDING blocks for some reason.
  81534. *
  81535. * If the current chain is shorter than the existing metadata, and
  81536. * \a use_padding is \c true, and the final block is a PADDING block, the padding
  81537. * is extended to make the overall size the same as the existing data. If
  81538. * \a use_padding is \c true and the last block is not a PADDING block, a new
  81539. * PADDING block is added to the end of the new data to make it the same
  81540. * size as the existing data (if possible, see the note to
  81541. * FLAC__metadata_simple_iterator_set_block() about the four byte limit)
  81542. * and the new data is written in place. If none of the above apply or
  81543. * \a use_padding is \c false, the entire FLAC file is rewritten.
  81544. *
  81545. * If \a preserve_file_stats is \c true, the owner and modification time will
  81546. * be preserved even if the FLAC file is written.
  81547. *
  81548. * For this write function to be used, the chain must have been read with
  81549. * FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg(), not
  81550. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks().
  81551. *
  81552. * \param chain A pointer to an existing chain.
  81553. * \param use_padding See above.
  81554. * \param preserve_file_stats See above.
  81555. * \assert
  81556. * \code chain != NULL \endcode
  81557. * \retval FLAC__bool
  81558. * \c true if the write succeeded, else \c false. On failure,
  81559. * check the status with FLAC__metadata_chain_status().
  81560. */
  81561. FLAC_API FLAC__bool FLAC__metadata_chain_write(FLAC__Metadata_Chain *chain, FLAC__bool use_padding, FLAC__bool preserve_file_stats);
  81562. /** Write all metadata out to a FLAC stream via callbacks.
  81563. *
  81564. * (See FLAC__metadata_chain_write() for the details on how padding is
  81565. * used to write metadata in place if possible.)
  81566. *
  81567. * The \a handle must be open for updating and be seekable. The
  81568. * equivalent minimum stdio fopen() file mode is \c "r+" (or \c "r+b"
  81569. * for Windows).
  81570. *
  81571. * For this write function to be used, the chain must have been read with
  81572. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  81573. * not FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  81574. * Also, FLAC__metadata_chain_check_if_tempfile_needed() must have returned
  81575. * \c false.
  81576. *
  81577. * \param chain A pointer to an existing chain.
  81578. * \param use_padding See FLAC__metadata_chain_write()
  81579. * \param handle The I/O handle of the FLAC stream to write. The
  81580. * handle will NOT be closed after the metadata is
  81581. * written; that is the duty of the caller.
  81582. * \param callbacks A set of callbacks to use for I/O. The mandatory
  81583. * callbacks are \a write and \a seek.
  81584. * \assert
  81585. * \code chain != NULL \endcode
  81586. * \retval FLAC__bool
  81587. * \c true if the write succeeded, else \c false. On failure,
  81588. * check the status with FLAC__metadata_chain_status().
  81589. */
  81590. FLAC_API FLAC__bool FLAC__metadata_chain_write_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__bool use_padding, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  81591. /** Write all metadata out to a FLAC stream via callbacks.
  81592. *
  81593. * (See FLAC__metadata_chain_write() for the details on how padding is
  81594. * used to write metadata in place if possible.)
  81595. *
  81596. * This version of the write-with-callbacks function must be used when
  81597. * FLAC__metadata_chain_check_if_tempfile_needed() returns true. In
  81598. * this function, you must supply an I/O handle corresponding to the
  81599. * FLAC file to edit, and a temporary handle to which the new FLAC
  81600. * file will be written. It is the caller's job to move this temporary
  81601. * FLAC file on top of the original FLAC file to complete the metadata
  81602. * edit.
  81603. *
  81604. * The \a handle must be open for reading and be seekable. The
  81605. * equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  81606. * for Windows).
  81607. *
  81608. * The \a temp_handle must be open for writing. The
  81609. * equivalent minimum stdio fopen() file mode is \c "w" (or \c "wb"
  81610. * for Windows). It should be an empty stream, or at least positioned
  81611. * at the start-of-file (in which case it is the caller's duty to
  81612. * truncate it on return).
  81613. *
  81614. * For this write function to be used, the chain must have been read with
  81615. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  81616. * not FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  81617. * Also, FLAC__metadata_chain_check_if_tempfile_needed() must have returned
  81618. * \c true.
  81619. *
  81620. * \param chain A pointer to an existing chain.
  81621. * \param use_padding See FLAC__metadata_chain_write()
  81622. * \param handle The I/O handle of the original FLAC stream to read.
  81623. * The handle will NOT be closed after the metadata is
  81624. * written; that is the duty of the caller.
  81625. * \param callbacks A set of callbacks to use for I/O on \a handle.
  81626. * The mandatory callbacks are \a read, \a seek, and
  81627. * \a eof.
  81628. * \param temp_handle The I/O handle of the FLAC stream to write. The
  81629. * handle will NOT be closed after the metadata is
  81630. * written; that is the duty of the caller.
  81631. * \param temp_callbacks
  81632. * A set of callbacks to use for I/O on temp_handle.
  81633. * The only mandatory callback is \a write.
  81634. * \assert
  81635. * \code chain != NULL \endcode
  81636. * \retval FLAC__bool
  81637. * \c true if the write succeeded, else \c false. On failure,
  81638. * check the status with FLAC__metadata_chain_status().
  81639. */
  81640. 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);
  81641. /** Merge adjacent PADDING blocks 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_merge_padding(FLAC__Metadata_Chain *chain);
  81654. /** This function will move all PADDING blocks to the end on the metadata,
  81655. * then merge them into a single block.
  81656. *
  81657. * \note This function does not write to the FLAC file, it only
  81658. * modifies the chain.
  81659. *
  81660. * \warning Any iterator on the current chain will become invalid after this
  81661. * call. You should delete the iterator and get a new one.
  81662. *
  81663. * \param chain A pointer to an existing chain.
  81664. * \assert
  81665. * \code chain != NULL \endcode
  81666. */
  81667. FLAC_API void FLAC__metadata_chain_sort_padding(FLAC__Metadata_Chain *chain);
  81668. /*********** FLAC__Metadata_Iterator ***********/
  81669. /** Create a new iterator instance.
  81670. *
  81671. * \retval FLAC__Metadata_Iterator*
  81672. * \c NULL if there was an error allocating memory, else the new instance.
  81673. */
  81674. FLAC_API FLAC__Metadata_Iterator *FLAC__metadata_iterator_new(void);
  81675. /** Free an iterator instance. Deletes the object pointed to by \a iterator.
  81676. *
  81677. * \param iterator A pointer to an existing iterator.
  81678. * \assert
  81679. * \code iterator != NULL \endcode
  81680. */
  81681. FLAC_API void FLAC__metadata_iterator_delete(FLAC__Metadata_Iterator *iterator);
  81682. /** Initialize the iterator to point to the first metadata block in the
  81683. * given chain.
  81684. *
  81685. * \param iterator A pointer to an existing iterator.
  81686. * \param chain A pointer to an existing and initialized (read) chain.
  81687. * \assert
  81688. * \code iterator != NULL \endcode
  81689. * \code chain != NULL \endcode
  81690. */
  81691. FLAC_API void FLAC__metadata_iterator_init(FLAC__Metadata_Iterator *iterator, FLAC__Metadata_Chain *chain);
  81692. /** Moves the iterator forward one metadata block, returning \c false if
  81693. * already at the end.
  81694. *
  81695. * \param iterator A pointer to an existing initialized iterator.
  81696. * \assert
  81697. * \code iterator != NULL \endcode
  81698. * \a iterator has been successfully initialized with
  81699. * FLAC__metadata_iterator_init()
  81700. * \retval FLAC__bool
  81701. * \c false if already at the last metadata block of the chain, else
  81702. * \c true.
  81703. */
  81704. FLAC_API FLAC__bool FLAC__metadata_iterator_next(FLAC__Metadata_Iterator *iterator);
  81705. /** Moves the iterator backward one metadata block, returning \c false if
  81706. * already at the beginning.
  81707. *
  81708. * \param iterator A pointer to an existing initialized iterator.
  81709. * \assert
  81710. * \code iterator != NULL \endcode
  81711. * \a iterator has been successfully initialized with
  81712. * FLAC__metadata_iterator_init()
  81713. * \retval FLAC__bool
  81714. * \c false if already at the first metadata block of the chain, else
  81715. * \c true.
  81716. */
  81717. FLAC_API FLAC__bool FLAC__metadata_iterator_prev(FLAC__Metadata_Iterator *iterator);
  81718. /** Get the type of the metadata block at the current position.
  81719. *
  81720. * \param iterator A pointer to an existing initialized iterator.
  81721. * \assert
  81722. * \code iterator != NULL \endcode
  81723. * \a iterator has been successfully initialized with
  81724. * FLAC__metadata_iterator_init()
  81725. * \retval FLAC__MetadataType
  81726. * The type of the metadata block at the current iterator position.
  81727. */
  81728. FLAC_API FLAC__MetadataType FLAC__metadata_iterator_get_block_type(const FLAC__Metadata_Iterator *iterator);
  81729. /** Get the metadata block at the current position. You can modify
  81730. * the block in place but must write the chain before the changes
  81731. * are reflected to the FLAC file. You do not need to call
  81732. * FLAC__metadata_iterator_set_block() to reflect the changes;
  81733. * the pointer returned by FLAC__metadata_iterator_get_block()
  81734. * points directly into the chain.
  81735. *
  81736. * \warning
  81737. * Do not call FLAC__metadata_object_delete() on the returned object;
  81738. * to delete a block use FLAC__metadata_iterator_delete_block().
  81739. *
  81740. * \param iterator A pointer to an existing initialized iterator.
  81741. * \assert
  81742. * \code iterator != NULL \endcode
  81743. * \a iterator has been successfully initialized with
  81744. * FLAC__metadata_iterator_init()
  81745. * \retval FLAC__StreamMetadata*
  81746. * The current metadata block.
  81747. */
  81748. FLAC_API FLAC__StreamMetadata *FLAC__metadata_iterator_get_block(FLAC__Metadata_Iterator *iterator);
  81749. /** Set the metadata block at the current position, replacing the existing
  81750. * block. The new block passed in becomes owned by the chain and it will be
  81751. * deleted when the chain is deleted.
  81752. *
  81753. * \param iterator A pointer to an existing initialized iterator.
  81754. * \param block A pointer to a metadata block.
  81755. * \assert
  81756. * \code iterator != NULL \endcode
  81757. * \a iterator has been successfully initialized with
  81758. * FLAC__metadata_iterator_init()
  81759. * \code block != NULL \endcode
  81760. * \retval FLAC__bool
  81761. * \c false if the conditions in the above description are not met, or
  81762. * a memory allocation error occurs, otherwise \c true.
  81763. */
  81764. FLAC_API FLAC__bool FLAC__metadata_iterator_set_block(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  81765. /** Removes the current block from the chain. If \a replace_with_padding is
  81766. * \c true, the block will instead be replaced with a padding block of equal
  81767. * size. You can not delete the STREAMINFO block. The iterator will be
  81768. * left pointing to the block before the one just "deleted", even if
  81769. * \a replace_with_padding is \c true.
  81770. *
  81771. * \param iterator A pointer to an existing initialized iterator.
  81772. * \param replace_with_padding See above.
  81773. * \assert
  81774. * \code iterator != NULL \endcode
  81775. * \a iterator has been successfully initialized with
  81776. * FLAC__metadata_iterator_init()
  81777. * \retval FLAC__bool
  81778. * \c false if the conditions in the above description are not met,
  81779. * otherwise \c true.
  81780. */
  81781. FLAC_API FLAC__bool FLAC__metadata_iterator_delete_block(FLAC__Metadata_Iterator *iterator, FLAC__bool replace_with_padding);
  81782. /** Insert a new block before the current block. You cannot insert a block
  81783. * before the first STREAMINFO block. You cannot insert a STREAMINFO block
  81784. * as there can be only one, the one that already exists at the head when you
  81785. * read in a chain. The chain takes ownership of the new block and it will be
  81786. * deleted when the chain is deleted. The iterator will be left pointing to
  81787. * the new block.
  81788. *
  81789. * \param iterator A pointer to an existing initialized iterator.
  81790. * \param block A pointer to a metadata block to insert.
  81791. * \assert
  81792. * \code iterator != NULL \endcode
  81793. * \a iterator has been successfully initialized with
  81794. * FLAC__metadata_iterator_init()
  81795. * \retval FLAC__bool
  81796. * \c false if the conditions in the above description are not met, or
  81797. * a memory allocation error occurs, otherwise \c true.
  81798. */
  81799. FLAC_API FLAC__bool FLAC__metadata_iterator_insert_block_before(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  81800. /** Insert a new block after the current block. You cannot insert a STREAMINFO
  81801. * block as there can be only one, the one that already exists at the head when
  81802. * you read in a chain. The chain takes ownership of the new block and it will
  81803. * be deleted when the chain is deleted. The iterator will be left pointing to
  81804. * the new block.
  81805. *
  81806. * \param iterator A pointer to an existing initialized iterator.
  81807. * \param block A pointer to a metadata block to insert.
  81808. * \assert
  81809. * \code iterator != NULL \endcode
  81810. * \a iterator has been successfully initialized with
  81811. * FLAC__metadata_iterator_init()
  81812. * \retval FLAC__bool
  81813. * \c false if the conditions in the above description are not met, or
  81814. * a memory allocation error occurs, otherwise \c true.
  81815. */
  81816. FLAC_API FLAC__bool FLAC__metadata_iterator_insert_block_after(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  81817. /* \} */
  81818. /** \defgroup flac_metadata_object FLAC/metadata.h: metadata object methods
  81819. * \ingroup flac_metadata
  81820. *
  81821. * \brief
  81822. * This module contains methods for manipulating FLAC metadata objects.
  81823. *
  81824. * Since many are variable length we have to be careful about the memory
  81825. * management. We decree that all pointers to data in the object are
  81826. * owned by the object and memory-managed by the object.
  81827. *
  81828. * Use the FLAC__metadata_object_new() and FLAC__metadata_object_delete()
  81829. * functions to create all instances. When using the
  81830. * FLAC__metadata_object_set_*() functions to set pointers to data, set
  81831. * \a copy to \c true to have the function make it's own copy of the data, or
  81832. * to \c false to give the object ownership of your data. In the latter case
  81833. * your pointer must be freeable by free() and will be free()d when the object
  81834. * is FLAC__metadata_object_delete()d. It is legal to pass a null pointer as
  81835. * the data pointer to a FLAC__metadata_object_set_*() function as long as
  81836. * the length argument is 0 and the \a copy argument is \c false.
  81837. *
  81838. * The FLAC__metadata_object_new() and FLAC__metadata_object_clone() function
  81839. * will return \c NULL in the case of a memory allocation error, otherwise a new
  81840. * object. The FLAC__metadata_object_set_*() functions return \c false in the
  81841. * case of a memory allocation error.
  81842. *
  81843. * We don't have the convenience of C++ here, so note that the library relies
  81844. * on you to keep the types straight. In other words, if you pass, for
  81845. * example, a FLAC__StreamMetadata* that represents a STREAMINFO block to
  81846. * FLAC__metadata_object_application_set_data(), you will get an assertion
  81847. * failure.
  81848. *
  81849. * For convenience the FLAC__metadata_object_vorbiscomment_*() functions
  81850. * maintain a trailing NUL on each Vorbis comment entry. This is not counted
  81851. * toward the length or stored in the stream, but it can make working with plain
  81852. * comments (those that don't contain embedded-NULs in the value) easier.
  81853. * Entries passed into these functions have trailing NULs added if missing, and
  81854. * returned entries are guaranteed to have a trailing NUL.
  81855. *
  81856. * The FLAC__metadata_object_vorbiscomment_*() functions that take a Vorbis
  81857. * comment entry/name/value will first validate that it complies with the Vorbis
  81858. * comment specification and return false if it does not.
  81859. *
  81860. * There is no need to recalculate the length field on metadata blocks you
  81861. * have modified. They will be calculated automatically before they are
  81862. * written back to a file.
  81863. *
  81864. * \{
  81865. */
  81866. /** Create a new metadata object instance of the given type.
  81867. *
  81868. * The object will be "empty"; i.e. values and data pointers will be \c 0,
  81869. * with the exception of FLAC__METADATA_TYPE_VORBIS_COMMENT, which will have
  81870. * the vendor string set (but zero comments).
  81871. *
  81872. * Do not pass in a value greater than or equal to
  81873. * \a FLAC__METADATA_TYPE_UNDEFINED unless you really know what you're
  81874. * doing.
  81875. *
  81876. * \param type Type of object to create
  81877. * \retval FLAC__StreamMetadata*
  81878. * \c NULL if there was an error allocating memory or the type code is
  81879. * greater than FLAC__MAX_METADATA_TYPE_CODE, else the new instance.
  81880. */
  81881. FLAC_API FLAC__StreamMetadata *FLAC__metadata_object_new(FLAC__MetadataType type);
  81882. /** Create a copy of an existing metadata object.
  81883. *
  81884. * The copy is a "deep" copy, i.e. dynamically allocated data within the
  81885. * object is also copied. The caller takes ownership of the new block and
  81886. * is responsible for freeing it with FLAC__metadata_object_delete().
  81887. *
  81888. * \param object Pointer to object to copy.
  81889. * \assert
  81890. * \code object != NULL \endcode
  81891. * \retval FLAC__StreamMetadata*
  81892. * \c NULL if there was an error allocating memory, else the new instance.
  81893. */
  81894. FLAC_API FLAC__StreamMetadata *FLAC__metadata_object_clone(const FLAC__StreamMetadata *object);
  81895. /** Free a metadata object. Deletes the object pointed to by \a object.
  81896. *
  81897. * The delete is a "deep" delete, i.e. dynamically allocated data within the
  81898. * object is also deleted.
  81899. *
  81900. * \param object A pointer to an existing object.
  81901. * \assert
  81902. * \code object != NULL \endcode
  81903. */
  81904. FLAC_API void FLAC__metadata_object_delete(FLAC__StreamMetadata *object);
  81905. /** Compares two metadata objects.
  81906. *
  81907. * The compare is "deep", i.e. dynamically allocated data within the
  81908. * object is also compared.
  81909. *
  81910. * \param block1 A pointer to an existing object.
  81911. * \param block2 A pointer to an existing object.
  81912. * \assert
  81913. * \code block1 != NULL \endcode
  81914. * \code block2 != NULL \endcode
  81915. * \retval FLAC__bool
  81916. * \c true if objects are identical, else \c false.
  81917. */
  81918. FLAC_API FLAC__bool FLAC__metadata_object_is_equal(const FLAC__StreamMetadata *block1, const FLAC__StreamMetadata *block2);
  81919. /** Sets the application data of an APPLICATION block.
  81920. *
  81921. * If \a copy is \c true, a copy of the data is stored; otherwise, the object
  81922. * takes ownership of the pointer. The existing data will be freed if this
  81923. * function is successful, otherwise the original data will remain if \a copy
  81924. * is \c true and malloc() fails.
  81925. *
  81926. * \note It is safe to pass a const pointer to \a data if \a copy is \c true.
  81927. *
  81928. * \param object A pointer to an existing APPLICATION object.
  81929. * \param data A pointer to the data to set.
  81930. * \param length The length of \a data in bytes.
  81931. * \param copy See above.
  81932. * \assert
  81933. * \code object != NULL \endcode
  81934. * \code object->type == FLAC__METADATA_TYPE_APPLICATION \endcode
  81935. * \code (data != NULL && length > 0) ||
  81936. * (data == NULL && length == 0 && copy == false) \endcode
  81937. * \retval FLAC__bool
  81938. * \c false if \a copy is \c true and malloc() fails, else \c true.
  81939. */
  81940. FLAC_API FLAC__bool FLAC__metadata_object_application_set_data(FLAC__StreamMetadata *object, FLAC__byte *data, unsigned length, FLAC__bool copy);
  81941. /** Resize the seekpoint array.
  81942. *
  81943. * If the size shrinks, elements will truncated; if it grows, new placeholder
  81944. * points will be added to the end.
  81945. *
  81946. * \param object A pointer to an existing SEEKTABLE object.
  81947. * \param new_num_points The desired length of the array; may be \c 0.
  81948. * \assert
  81949. * \code object != NULL \endcode
  81950. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  81951. * \code (object->data.seek_table.points == NULL && object->data.seek_table.num_points == 0) ||
  81952. * (object->data.seek_table.points != NULL && object->data.seek_table.num_points > 0) \endcode
  81953. * \retval FLAC__bool
  81954. * \c false if memory allocation error, else \c true.
  81955. */
  81956. FLAC_API FLAC__bool FLAC__metadata_object_seektable_resize_points(FLAC__StreamMetadata *object, unsigned new_num_points);
  81957. /** Set a seekpoint in a seektable.
  81958. *
  81959. * \param object A pointer to an existing SEEKTABLE object.
  81960. * \param point_num Index into seekpoint array to set.
  81961. * \param point The point to set.
  81962. * \assert
  81963. * \code object != NULL \endcode
  81964. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  81965. * \code object->data.seek_table.num_points > point_num \endcode
  81966. */
  81967. FLAC_API void FLAC__metadata_object_seektable_set_point(FLAC__StreamMetadata *object, unsigned point_num, FLAC__StreamMetadata_SeekPoint point);
  81968. /** Insert a seekpoint into a seektable.
  81969. *
  81970. * \param object A pointer to an existing SEEKTABLE object.
  81971. * \param point_num Index into seekpoint array to set.
  81972. * \param point The point to set.
  81973. * \assert
  81974. * \code object != NULL \endcode
  81975. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  81976. * \code object->data.seek_table.num_points >= point_num \endcode
  81977. * \retval FLAC__bool
  81978. * \c false if memory allocation error, else \c true.
  81979. */
  81980. FLAC_API FLAC__bool FLAC__metadata_object_seektable_insert_point(FLAC__StreamMetadata *object, unsigned point_num, FLAC__StreamMetadata_SeekPoint point);
  81981. /** Delete a seekpoint from a seektable.
  81982. *
  81983. * \param object A pointer to an existing SEEKTABLE object.
  81984. * \param point_num Index into seekpoint array to set.
  81985. * \assert
  81986. * \code object != NULL \endcode
  81987. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  81988. * \code object->data.seek_table.num_points > point_num \endcode
  81989. * \retval FLAC__bool
  81990. * \c false if memory allocation error, else \c true.
  81991. */
  81992. FLAC_API FLAC__bool FLAC__metadata_object_seektable_delete_point(FLAC__StreamMetadata *object, unsigned point_num);
  81993. /** Check a seektable to see if it conforms to the FLAC specification.
  81994. * See the format specification for limits on the contents of the
  81995. * seektable.
  81996. *
  81997. * \param object A pointer to an existing SEEKTABLE object.
  81998. * \assert
  81999. * \code object != NULL \endcode
  82000. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  82001. * \retval FLAC__bool
  82002. * \c false if seek table is illegal, else \c true.
  82003. */
  82004. FLAC_API FLAC__bool FLAC__metadata_object_seektable_is_legal(const FLAC__StreamMetadata *object);
  82005. /** Append a number of placeholder points to the end of a seek table.
  82006. *
  82007. * \note
  82008. * As with the other ..._seektable_template_... functions, you should
  82009. * call FLAC__metadata_object_seektable_template_sort() when finished
  82010. * to make the seek table legal.
  82011. *
  82012. * \param object A pointer to an existing SEEKTABLE object.
  82013. * \param num The number of placeholder points to append.
  82014. * \assert
  82015. * \code object != NULL \endcode
  82016. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  82017. * \retval FLAC__bool
  82018. * \c false if memory allocation fails, else \c true.
  82019. */
  82020. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_placeholders(FLAC__StreamMetadata *object, unsigned num);
  82021. /** Append a specific seek point template to the end of a seek table.
  82022. *
  82023. * \note
  82024. * As with the other ..._seektable_template_... functions, you should
  82025. * call FLAC__metadata_object_seektable_template_sort() when finished
  82026. * to make the seek table legal.
  82027. *
  82028. * \param object A pointer to an existing SEEKTABLE object.
  82029. * \param sample_number The sample number of the seek point template.
  82030. * \assert
  82031. * \code object != NULL \endcode
  82032. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  82033. * \retval FLAC__bool
  82034. * \c false if memory allocation fails, else \c true.
  82035. */
  82036. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_point(FLAC__StreamMetadata *object, FLAC__uint64 sample_number);
  82037. /** Append specific seek point templates to the end of a seek table.
  82038. *
  82039. * \note
  82040. * As with the other ..._seektable_template_... functions, you should
  82041. * call FLAC__metadata_object_seektable_template_sort() when finished
  82042. * to make the seek table legal.
  82043. *
  82044. * \param object A pointer to an existing SEEKTABLE object.
  82045. * \param sample_numbers An array of sample numbers for the seek points.
  82046. * \param num The number of seek point templates to append.
  82047. * \assert
  82048. * \code object != NULL \endcode
  82049. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  82050. * \retval FLAC__bool
  82051. * \c false if memory allocation fails, else \c true.
  82052. */
  82053. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_points(FLAC__StreamMetadata *object, FLAC__uint64 sample_numbers[], unsigned num);
  82054. /** Append a set of evenly-spaced seek point templates to the end of a
  82055. * seek table.
  82056. *
  82057. * \note
  82058. * As with the other ..._seektable_template_... functions, you should
  82059. * call FLAC__metadata_object_seektable_template_sort() when finished
  82060. * to make the seek table legal.
  82061. *
  82062. * \param object A pointer to an existing SEEKTABLE object.
  82063. * \param num The number of placeholder points to append.
  82064. * \param total_samples The total number of samples to be encoded;
  82065. * the seekpoints will be spaced approximately
  82066. * \a total_samples / \a num samples apart.
  82067. * \assert
  82068. * \code object != NULL \endcode
  82069. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  82070. * \code total_samples > 0 \endcode
  82071. * \retval FLAC__bool
  82072. * \c false if memory allocation fails, else \c true.
  82073. */
  82074. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_spaced_points(FLAC__StreamMetadata *object, unsigned num, FLAC__uint64 total_samples);
  82075. /** Append a set of evenly-spaced seek point templates to the end of a
  82076. * seek table.
  82077. *
  82078. * \note
  82079. * As with the other ..._seektable_template_... functions, you should
  82080. * call FLAC__metadata_object_seektable_template_sort() when finished
  82081. * to make the seek table legal.
  82082. *
  82083. * \param object A pointer to an existing SEEKTABLE object.
  82084. * \param samples The number of samples apart to space the placeholder
  82085. * points. The first point will be at sample \c 0, the
  82086. * second at sample \a samples, then 2*\a samples, and
  82087. * so on. As long as \a samples and \a total_samples
  82088. * are greater than \c 0, there will always be at least
  82089. * one seekpoint at sample \c 0.
  82090. * \param total_samples The total number of samples to be encoded;
  82091. * the seekpoints will be spaced
  82092. * \a samples samples apart.
  82093. * \assert
  82094. * \code object != NULL \endcode
  82095. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  82096. * \code samples > 0 \endcode
  82097. * \code total_samples > 0 \endcode
  82098. * \retval FLAC__bool
  82099. * \c false if memory allocation fails, else \c true.
  82100. */
  82101. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_spaced_points_by_samples(FLAC__StreamMetadata *object, unsigned samples, FLAC__uint64 total_samples);
  82102. /** Sort a seek table's seek points according to the format specification,
  82103. * removing duplicates.
  82104. *
  82105. * \param object A pointer to a seek table to be sorted.
  82106. * \param compact If \c false, behaves like FLAC__format_seektable_sort().
  82107. * If \c true, duplicates are deleted and the seek table is
  82108. * shrunk appropriately; the number of placeholder points
  82109. * present in the seek table will be the same after the call
  82110. * as before.
  82111. * \assert
  82112. * \code object != NULL \endcode
  82113. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  82114. * \retval FLAC__bool
  82115. * \c false if realloc() fails, else \c true.
  82116. */
  82117. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_sort(FLAC__StreamMetadata *object, FLAC__bool compact);
  82118. /** Sets the vendor string in a VORBIS_COMMENT block.
  82119. *
  82120. * For convenience, a trailing NUL is added to the entry if it doesn't have
  82121. * one already.
  82122. *
  82123. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  82124. * takes ownership of the \c entry.entry pointer.
  82125. *
  82126. * \note If this function returns \c false, the caller still owns the
  82127. * pointer.
  82128. *
  82129. * \param object A pointer to an existing VORBIS_COMMENT object.
  82130. * \param entry The entry to set the vendor string to.
  82131. * \param copy See above.
  82132. * \assert
  82133. * \code object != NULL \endcode
  82134. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  82135. * \code (entry.entry != NULL && entry.length > 0) ||
  82136. * (entry.entry == NULL && entry.length == 0) \endcode
  82137. * \retval FLAC__bool
  82138. * \c false if memory allocation fails or \a entry does not comply with the
  82139. * Vorbis comment specification, else \c true.
  82140. */
  82141. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_set_vendor_string(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  82142. /** Resize the comment array.
  82143. *
  82144. * If the size shrinks, elements will truncated; if it grows, new empty
  82145. * fields will be added to the end.
  82146. *
  82147. * \param object A pointer to an existing VORBIS_COMMENT object.
  82148. * \param new_num_comments The desired length of the array; may be \c 0.
  82149. * \assert
  82150. * \code object != NULL \endcode
  82151. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  82152. * \code (object->data.vorbis_comment.comments == NULL && object->data.vorbis_comment.num_comments == 0) ||
  82153. * (object->data.vorbis_comment.comments != NULL && object->data.vorbis_comment.num_comments > 0) \endcode
  82154. * \retval FLAC__bool
  82155. * \c false if memory allocation fails, else \c true.
  82156. */
  82157. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_resize_comments(FLAC__StreamMetadata *object, unsigned new_num_comments);
  82158. /** Sets a comment in a VORBIS_COMMENT block.
  82159. *
  82160. * For convenience, a trailing NUL is added to the entry if it doesn't have
  82161. * one already.
  82162. *
  82163. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  82164. * takes ownership of the \c entry.entry pointer.
  82165. *
  82166. * \note If this function returns \c false, the caller still owns the
  82167. * pointer.
  82168. *
  82169. * \param object A pointer to an existing VORBIS_COMMENT object.
  82170. * \param comment_num Index into comment array to set.
  82171. * \param entry The entry to set the comment to.
  82172. * \param copy See above.
  82173. * \assert
  82174. * \code object != NULL \endcode
  82175. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  82176. * \code comment_num < object->data.vorbis_comment.num_comments \endcode
  82177. * \code (entry.entry != NULL && entry.length > 0) ||
  82178. * (entry.entry == NULL && entry.length == 0) \endcode
  82179. * \retval FLAC__bool
  82180. * \c false if memory allocation fails or \a entry does not comply with the
  82181. * Vorbis comment specification, else \c true.
  82182. */
  82183. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_set_comment(FLAC__StreamMetadata *object, unsigned comment_num, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  82184. /** Insert a comment in a VORBIS_COMMENT block at the given index.
  82185. *
  82186. * For convenience, a trailing NUL is added to the entry if it doesn't have
  82187. * one already.
  82188. *
  82189. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  82190. * takes ownership of the \c entry.entry pointer.
  82191. *
  82192. * \note If this function returns \c false, the caller still owns the
  82193. * pointer.
  82194. *
  82195. * \param object A pointer to an existing VORBIS_COMMENT object.
  82196. * \param comment_num The index at which to insert the comment. The comments
  82197. * at and after \a comment_num move right one position.
  82198. * To append a comment to the end, set \a comment_num to
  82199. * \c object->data.vorbis_comment.num_comments .
  82200. * \param entry The comment to insert.
  82201. * \param copy See above.
  82202. * \assert
  82203. * \code object != NULL \endcode
  82204. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  82205. * \code object->data.vorbis_comment.num_comments >= comment_num \endcode
  82206. * \code (entry.entry != NULL && entry.length > 0) ||
  82207. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  82208. * \retval FLAC__bool
  82209. * \c false if memory allocation fails or \a entry does not comply with the
  82210. * Vorbis comment specification, else \c true.
  82211. */
  82212. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_insert_comment(FLAC__StreamMetadata *object, unsigned comment_num, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  82213. /** Appends a comment to a VORBIS_COMMENT block.
  82214. *
  82215. * For convenience, a trailing NUL is added to the entry if it doesn't have
  82216. * one already.
  82217. *
  82218. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  82219. * takes ownership of the \c entry.entry pointer.
  82220. *
  82221. * \note If this function returns \c false, the caller still owns the
  82222. * pointer.
  82223. *
  82224. * \param object A pointer to an existing VORBIS_COMMENT object.
  82225. * \param entry The comment to insert.
  82226. * \param copy See above.
  82227. * \assert
  82228. * \code object != NULL \endcode
  82229. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  82230. * \code (entry.entry != NULL && entry.length > 0) ||
  82231. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  82232. * \retval FLAC__bool
  82233. * \c false if memory allocation fails or \a entry does not comply with the
  82234. * Vorbis comment specification, else \c true.
  82235. */
  82236. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_append_comment(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  82237. /** Replaces comments in a VORBIS_COMMENT block with a new one.
  82238. *
  82239. * For convenience, a trailing NUL is added to the entry if it doesn't have
  82240. * one already.
  82241. *
  82242. * Depending on the the value of \a all, either all or just the first comment
  82243. * whose field name(s) match the given entry's name will be replaced by the
  82244. * given entry. If no comments match, \a entry will simply be appended.
  82245. *
  82246. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  82247. * takes ownership of the \c entry.entry pointer.
  82248. *
  82249. * \note If this function returns \c false, the caller still owns the
  82250. * pointer.
  82251. *
  82252. * \param object A pointer to an existing VORBIS_COMMENT object.
  82253. * \param entry The comment to insert.
  82254. * \param all If \c true, all comments whose field name matches
  82255. * \a entry's field name will be removed, and \a entry will
  82256. * be inserted at the position of the first matching
  82257. * comment. If \c false, only the first comment whose
  82258. * field name matches \a entry's field name will be
  82259. * replaced with \a entry.
  82260. * \param copy See above.
  82261. * \assert
  82262. * \code object != NULL \endcode
  82263. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  82264. * \code (entry.entry != NULL && entry.length > 0) ||
  82265. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  82266. * \retval FLAC__bool
  82267. * \c false if memory allocation fails or \a entry does not comply with the
  82268. * Vorbis comment specification, else \c true.
  82269. */
  82270. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_replace_comment(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool all, FLAC__bool copy);
  82271. /** Delete a comment in a VORBIS_COMMENT block at the given index.
  82272. *
  82273. * \param object A pointer to an existing VORBIS_COMMENT object.
  82274. * \param comment_num The index of the comment to delete.
  82275. * \assert
  82276. * \code object != NULL \endcode
  82277. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  82278. * \code object->data.vorbis_comment.num_comments > comment_num \endcode
  82279. * \retval FLAC__bool
  82280. * \c false if realloc() fails, else \c true.
  82281. */
  82282. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_delete_comment(FLAC__StreamMetadata *object, unsigned comment_num);
  82283. /** Creates a Vorbis comment entry from NUL-terminated name and value strings.
  82284. *
  82285. * On return, the filled-in \a entry->entry pointer will point to malloc()ed
  82286. * memory and shall be owned by the caller. For convenience the entry will
  82287. * have a terminating NUL.
  82288. *
  82289. * \param entry A pointer to a Vorbis comment entry. The entry's
  82290. * \c entry pointer should not point to allocated
  82291. * memory as it will be overwritten.
  82292. * \param field_name The field name in ASCII, \c NUL terminated.
  82293. * \param field_value The field value in UTF-8, \c NUL terminated.
  82294. * \assert
  82295. * \code entry != NULL \endcode
  82296. * \code field_name != NULL \endcode
  82297. * \code field_value != NULL \endcode
  82298. * \retval FLAC__bool
  82299. * \c false if malloc() fails, or if \a field_name or \a field_value does
  82300. * not comply with the Vorbis comment specification, else \c true.
  82301. */
  82302. 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);
  82303. /** Splits a Vorbis comment entry into NUL-terminated name and value strings.
  82304. *
  82305. * The returned pointers to name and value will be allocated by malloc()
  82306. * and shall be owned by the caller.
  82307. *
  82308. * \param entry An existing Vorbis comment entry.
  82309. * \param field_name The address of where the returned pointer to the
  82310. * field name will be stored.
  82311. * \param field_value The address of where the returned pointer to the
  82312. * field value will be stored.
  82313. * \assert
  82314. * \code (entry.entry != NULL && entry.length > 0) \endcode
  82315. * \code memchr(entry.entry, '=', entry.length) != NULL \endcode
  82316. * \code field_name != NULL \endcode
  82317. * \code field_value != NULL \endcode
  82318. * \retval FLAC__bool
  82319. * \c false if memory allocation fails or \a entry does not comply with the
  82320. * Vorbis comment specification, else \c true.
  82321. */
  82322. 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);
  82323. /** Check if the given Vorbis comment entry's field name matches the given
  82324. * field name.
  82325. *
  82326. * \param entry An existing Vorbis comment entry.
  82327. * \param field_name The field name to check.
  82328. * \param field_name_length The length of \a field_name, not including the
  82329. * terminating \c NUL.
  82330. * \assert
  82331. * \code (entry.entry != NULL && entry.length > 0) \endcode
  82332. * \retval FLAC__bool
  82333. * \c true if the field names match, else \c false
  82334. */
  82335. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_entry_matches(const FLAC__StreamMetadata_VorbisComment_Entry entry, const char *field_name, unsigned field_name_length);
  82336. /** Find a Vorbis comment with the given field name.
  82337. *
  82338. * The search begins at entry number \a offset; use an offset of 0 to
  82339. * search from the beginning of the comment array.
  82340. *
  82341. * \param object A pointer to an existing VORBIS_COMMENT object.
  82342. * \param offset The offset into the comment array from where to start
  82343. * the search.
  82344. * \param field_name The field name of the comment to find.
  82345. * \assert
  82346. * \code object != NULL \endcode
  82347. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  82348. * \code field_name != NULL \endcode
  82349. * \retval int
  82350. * The offset in the comment array of the first comment whose field
  82351. * name matches \a field_name, or \c -1 if no match was found.
  82352. */
  82353. FLAC_API int FLAC__metadata_object_vorbiscomment_find_entry_from(const FLAC__StreamMetadata *object, unsigned offset, const char *field_name);
  82354. /** Remove first Vorbis comment matching the given field name.
  82355. *
  82356. * \param object A pointer to an existing VORBIS_COMMENT object.
  82357. * \param field_name The field name of comment to delete.
  82358. * \assert
  82359. * \code object != NULL \endcode
  82360. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  82361. * \retval int
  82362. * \c -1 for memory allocation error, \c 0 for no matching entries,
  82363. * \c 1 for one matching entry deleted.
  82364. */
  82365. FLAC_API int FLAC__metadata_object_vorbiscomment_remove_entry_matching(FLAC__StreamMetadata *object, const char *field_name);
  82366. /** Remove all Vorbis comments matching the given field name.
  82367. *
  82368. * \param object A pointer to an existing VORBIS_COMMENT object.
  82369. * \param field_name The field name of comments to delete.
  82370. * \assert
  82371. * \code object != NULL \endcode
  82372. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  82373. * \retval int
  82374. * \c -1 for memory allocation error, \c 0 for no matching entries,
  82375. * else the number of matching entries deleted.
  82376. */
  82377. FLAC_API int FLAC__metadata_object_vorbiscomment_remove_entries_matching(FLAC__StreamMetadata *object, const char *field_name);
  82378. /** Create a new CUESHEET track instance.
  82379. *
  82380. * The object will be "empty"; i.e. values and data pointers will be \c 0.
  82381. *
  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_new(void);
  82386. /** Create a copy of an existing CUESHEET track object.
  82387. *
  82388. * The copy is a "deep" copy, i.e. dynamically allocated data within the
  82389. * object is also copied. The caller takes ownership of the new object and
  82390. * is responsible for freeing it with
  82391. * FLAC__metadata_object_cuesheet_track_delete().
  82392. *
  82393. * \param object Pointer to object to copy.
  82394. * \assert
  82395. * \code object != NULL \endcode
  82396. * \retval FLAC__StreamMetadata_CueSheet_Track*
  82397. * \c NULL if there was an error allocating memory, else the new instance.
  82398. */
  82399. FLAC_API FLAC__StreamMetadata_CueSheet_Track *FLAC__metadata_object_cuesheet_track_clone(const FLAC__StreamMetadata_CueSheet_Track *object);
  82400. /** Delete a CUESHEET track object
  82401. *
  82402. * \param object A pointer to an existing CUESHEET track object.
  82403. * \assert
  82404. * \code object != NULL \endcode
  82405. */
  82406. FLAC_API void FLAC__metadata_object_cuesheet_track_delete(FLAC__StreamMetadata_CueSheet_Track *object);
  82407. /** Resize a track's index point array.
  82408. *
  82409. * If the size shrinks, elements will truncated; if it grows, new blank
  82410. * indices will be added to the end.
  82411. *
  82412. * \param object A pointer to an existing CUESHEET object.
  82413. * \param track_num The index of the track to modify. NOTE: this is not
  82414. * necessarily the same as the track's \a number field.
  82415. * \param new_num_indices The desired length of the array; may be \c 0.
  82416. * \assert
  82417. * \code object != NULL \endcode
  82418. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  82419. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  82420. * \code (object->data.cue_sheet.tracks[track_num].indices == NULL && object->data.cue_sheet.tracks[track_num].num_indices == 0) ||
  82421. * (object->data.cue_sheet.tracks[track_num].indices != NULL && object->data.cue_sheet.tracks[track_num].num_indices > 0) \endcode
  82422. * \retval FLAC__bool
  82423. * \c false if memory allocation error, else \c true.
  82424. */
  82425. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_resize_indices(FLAC__StreamMetadata *object, unsigned track_num, unsigned new_num_indices);
  82426. /** Insert an index point in a CUESHEET track at the given index.
  82427. *
  82428. * \param object A pointer to an existing CUESHEET object.
  82429. * \param track_num The index of the track to modify. NOTE: this is not
  82430. * necessarily the same as the track's \a number field.
  82431. * \param index_num The index into the track's index array at which to
  82432. * insert the index point. NOTE: this is not necessarily
  82433. * the same as the index point's \a number field. The
  82434. * indices at and after \a index_num move right one
  82435. * position. To append an index point to the end, set
  82436. * \a index_num to
  82437. * \c object->data.cue_sheet.tracks[track_num].num_indices .
  82438. * \param index The index point to insert.
  82439. * \assert
  82440. * \code object != NULL \endcode
  82441. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  82442. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  82443. * \code object->data.cue_sheet.tracks[track_num].num_indices >= index_num \endcode
  82444. * \retval FLAC__bool
  82445. * \c false if realloc() fails, else \c true.
  82446. */
  82447. 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);
  82448. /** Insert a blank index point in a CUESHEET track at the given index.
  82449. *
  82450. * A blank index point is one in which all field values are zero.
  82451. *
  82452. * \param object A pointer to an existing CUESHEET object.
  82453. * \param track_num The index of the track to modify. NOTE: this is not
  82454. * necessarily the same as the track's \a number field.
  82455. * \param index_num The index into the track's index array at which to
  82456. * insert the index point. NOTE: this is not necessarily
  82457. * the same as the index point's \a number field. The
  82458. * indices at and after \a index_num move right one
  82459. * position. To append an index point to the end, set
  82460. * \a index_num to
  82461. * \c object->data.cue_sheet.tracks[track_num].num_indices .
  82462. * \assert
  82463. * \code object != NULL \endcode
  82464. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  82465. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  82466. * \code object->data.cue_sheet.tracks[track_num].num_indices >= index_num \endcode
  82467. * \retval FLAC__bool
  82468. * \c false if realloc() fails, else \c true.
  82469. */
  82470. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_insert_blank_index(FLAC__StreamMetadata *object, unsigned track_num, unsigned index_num);
  82471. /** Delete an index point in a CUESHEET track at the given index.
  82472. *
  82473. * \param object A pointer to an existing CUESHEET object.
  82474. * \param track_num The index into the track array of the track to
  82475. * modify. NOTE: this is not necessarily the same
  82476. * as the track's \a number field.
  82477. * \param index_num The index into the track's index array of the index
  82478. * to delete. NOTE: this is not necessarily the same
  82479. * as the index's \a number field.
  82480. * \assert
  82481. * \code object != NULL \endcode
  82482. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  82483. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  82484. * \code object->data.cue_sheet.tracks[track_num].num_indices > index_num \endcode
  82485. * \retval FLAC__bool
  82486. * \c false if realloc() fails, else \c true.
  82487. */
  82488. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_delete_index(FLAC__StreamMetadata *object, unsigned track_num, unsigned index_num);
  82489. /** Resize the track array.
  82490. *
  82491. * If the size shrinks, elements will truncated; if it grows, new blank
  82492. * tracks will be added to the end.
  82493. *
  82494. * \param object A pointer to an existing CUESHEET object.
  82495. * \param new_num_tracks The desired length of the array; may be \c 0.
  82496. * \assert
  82497. * \code object != NULL \endcode
  82498. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  82499. * \code (object->data.cue_sheet.tracks == NULL && object->data.cue_sheet.num_tracks == 0) ||
  82500. * (object->data.cue_sheet.tracks != NULL && object->data.cue_sheet.num_tracks > 0) \endcode
  82501. * \retval FLAC__bool
  82502. * \c false if memory allocation error, else \c true.
  82503. */
  82504. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_resize_tracks(FLAC__StreamMetadata *object, unsigned new_num_tracks);
  82505. /** Sets a track in a CUESHEET block.
  82506. *
  82507. * If \a copy is \c true, a copy of the track is stored; otherwise, the object
  82508. * takes ownership of the \a track pointer.
  82509. *
  82510. * \param object A pointer to an existing CUESHEET object.
  82511. * \param track_num Index into track array to set. NOTE: this is not
  82512. * necessarily the same as the track's \a number field.
  82513. * \param track The track to set the track to. You may safely pass in
  82514. * a const pointer if \a copy is \c true.
  82515. * \param copy See above.
  82516. * \assert
  82517. * \code object != NULL \endcode
  82518. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  82519. * \code track_num < object->data.cue_sheet.num_tracks \endcode
  82520. * \code (track->indices != NULL && track->num_indices > 0) ||
  82521. * (track->indices == NULL && track->num_indices == 0)
  82522. * \retval FLAC__bool
  82523. * \c false if \a copy is \c true and malloc() fails, else \c true.
  82524. */
  82525. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_set_track(FLAC__StreamMetadata *object, unsigned track_num, FLAC__StreamMetadata_CueSheet_Track *track, FLAC__bool copy);
  82526. /** Insert a track in a CUESHEET block at the given index.
  82527. *
  82528. * If \a copy is \c true, a copy of the track is stored; otherwise, the object
  82529. * takes ownership of the \a track pointer.
  82530. *
  82531. * \param object A pointer to an existing CUESHEET object.
  82532. * \param track_num The index at which to insert the track. NOTE: this
  82533. * is not necessarily the same as the track's \a number
  82534. * field. The tracks at and after \a track_num move right
  82535. * one position. To append a track to the end, set
  82536. * \a track_num to \c object->data.cue_sheet.num_tracks .
  82537. * \param track The track to insert. You may safely pass in a const
  82538. * pointer if \a copy is \c true.
  82539. * \param copy See above.
  82540. * \assert
  82541. * \code object != NULL \endcode
  82542. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  82543. * \code object->data.cue_sheet.num_tracks >= track_num \endcode
  82544. * \retval FLAC__bool
  82545. * \c false if \a copy is \c true and malloc() fails, else \c true.
  82546. */
  82547. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_insert_track(FLAC__StreamMetadata *object, unsigned track_num, FLAC__StreamMetadata_CueSheet_Track *track, FLAC__bool copy);
  82548. /** Insert a blank track in a CUESHEET block at the given index.
  82549. *
  82550. * A blank track is one in which all field values are zero.
  82551. *
  82552. * \param object A pointer to an existing CUESHEET object.
  82553. * \param track_num The index at which to insert the track. NOTE: this
  82554. * is not necessarily the same as the track's \a number
  82555. * field. The tracks at and after \a track_num move right
  82556. * one position. To append a track to the end, set
  82557. * \a track_num to \c object->data.cue_sheet.num_tracks .
  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 \a copy is \c true and malloc() fails, else \c true.
  82564. */
  82565. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_insert_blank_track(FLAC__StreamMetadata *object, unsigned track_num);
  82566. /** Delete a track in a CUESHEET block at the given index.
  82567. *
  82568. * \param object A pointer to an existing CUESHEET object.
  82569. * \param track_num The index into the track array of the track to
  82570. * delete. NOTE: this is not necessarily the same
  82571. * as the track's \a number field.
  82572. * \assert
  82573. * \code object != NULL \endcode
  82574. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  82575. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  82576. * \retval FLAC__bool
  82577. * \c false if realloc() fails, else \c true.
  82578. */
  82579. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_delete_track(FLAC__StreamMetadata *object, unsigned track_num);
  82580. /** Check a cue sheet to see if it conforms to the FLAC specification.
  82581. * See the format specification for limits on the contents of the
  82582. * cue sheet.
  82583. *
  82584. * \param object A pointer to an existing CUESHEET object.
  82585. * \param check_cd_da_subset If \c true, check CUESHEET against more
  82586. * stringent requirements for a CD-DA (audio) disc.
  82587. * \param violation Address of a pointer to a string. If there is a
  82588. * violation, a pointer to a string explanation of the
  82589. * violation will be returned here. \a violation may be
  82590. * \c NULL if you don't need the returned string. Do not
  82591. * free the returned string; it will always point to static
  82592. * data.
  82593. * \assert
  82594. * \code object != NULL \endcode
  82595. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  82596. * \retval FLAC__bool
  82597. * \c false if cue sheet is illegal, else \c true.
  82598. */
  82599. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_is_legal(const FLAC__StreamMetadata *object, FLAC__bool check_cd_da_subset, const char **violation);
  82600. /** Calculate and return the CDDB/freedb ID for a cue sheet. The function
  82601. * assumes the cue sheet corresponds to a CD; the result is undefined
  82602. * if the cuesheet's is_cd bit is not set.
  82603. *
  82604. * \param object A pointer to an existing CUESHEET object.
  82605. * \assert
  82606. * \code object != NULL \endcode
  82607. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  82608. * \retval FLAC__uint32
  82609. * The unsigned integer representation of the CDDB/freedb ID
  82610. */
  82611. FLAC_API FLAC__uint32 FLAC__metadata_object_cuesheet_calculate_cddb_id(const FLAC__StreamMetadata *object);
  82612. /** Sets the MIME type of a PICTURE block.
  82613. *
  82614. * If \a copy is \c true, a copy of the string is stored; otherwise, the object
  82615. * takes ownership of the pointer. The existing string will be freed if this
  82616. * function is successful, otherwise the original string will remain if \a copy
  82617. * is \c true and malloc() fails.
  82618. *
  82619. * \note It is safe to pass a const pointer to \a mime_type if \a copy is \c true.
  82620. *
  82621. * \param object A pointer to an existing PICTURE object.
  82622. * \param mime_type A pointer to the MIME type string. The string must be
  82623. * ASCII characters 0x20-0x7e, NUL-terminated. No validation
  82624. * is done.
  82625. * \param copy See above.
  82626. * \assert
  82627. * \code object != NULL \endcode
  82628. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  82629. * \code (mime_type != NULL) \endcode
  82630. * \retval FLAC__bool
  82631. * \c false if \a copy is \c true and malloc() fails, else \c true.
  82632. */
  82633. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_mime_type(FLAC__StreamMetadata *object, char *mime_type, FLAC__bool copy);
  82634. /** Sets the description of a PICTURE block.
  82635. *
  82636. * If \a copy is \c true, a copy of the string is stored; otherwise, the object
  82637. * takes ownership of the pointer. The existing string will be freed if this
  82638. * function is successful, otherwise the original string will remain if \a copy
  82639. * is \c true and malloc() fails.
  82640. *
  82641. * \note It is safe to pass a const pointer to \a description if \a copy is \c true.
  82642. *
  82643. * \param object A pointer to an existing PICTURE object.
  82644. * \param description A pointer to the description string. The string must be
  82645. * valid UTF-8, NUL-terminated. No validation is done.
  82646. * \param copy See above.
  82647. * \assert
  82648. * \code object != NULL \endcode
  82649. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  82650. * \code (description != NULL) \endcode
  82651. * \retval FLAC__bool
  82652. * \c false if \a copy is \c true and malloc() fails, else \c true.
  82653. */
  82654. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_description(FLAC__StreamMetadata *object, FLAC__byte *description, FLAC__bool copy);
  82655. /** Sets the picture data of a PICTURE block.
  82656. *
  82657. * If \a copy is \c true, a copy of the data is stored; otherwise, the object
  82658. * takes ownership of the pointer. Also sets the \a data_length field of the
  82659. * metadata object to what is passed in as the \a length parameter. The
  82660. * existing data will be freed if this function is successful, otherwise the
  82661. * original data and data_length will remain if \a copy is \c true and
  82662. * malloc() fails.
  82663. *
  82664. * \note It is safe to pass a const pointer to \a data if \a copy is \c true.
  82665. *
  82666. * \param object A pointer to an existing PICTURE object.
  82667. * \param data A pointer to the data to set.
  82668. * \param length The length of \a data in bytes.
  82669. * \param copy See above.
  82670. * \assert
  82671. * \code object != NULL \endcode
  82672. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  82673. * \code (data != NULL && length > 0) ||
  82674. * (data == NULL && length == 0 && copy == false) \endcode
  82675. * \retval FLAC__bool
  82676. * \c false if \a copy is \c true and malloc() fails, else \c true.
  82677. */
  82678. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_data(FLAC__StreamMetadata *object, FLAC__byte *data, FLAC__uint32 length, FLAC__bool copy);
  82679. /** Check a PICTURE block to see if it conforms to the FLAC specification.
  82680. * See the format specification for limits on the contents of the
  82681. * PICTURE block.
  82682. *
  82683. * \param object A pointer to existing PICTURE block to be checked.
  82684. * \param violation Address of a pointer to a string. If there is a
  82685. * violation, a pointer to a string explanation of the
  82686. * violation will be returned here. \a violation may be
  82687. * \c NULL if you don't need the returned string. Do not
  82688. * free the returned string; it will always point to static
  82689. * data.
  82690. * \assert
  82691. * \code object != NULL \endcode
  82692. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  82693. * \retval FLAC__bool
  82694. * \c false if PICTURE block is illegal, else \c true.
  82695. */
  82696. FLAC_API FLAC__bool FLAC__metadata_object_picture_is_legal(const FLAC__StreamMetadata *object, const char **violation);
  82697. /* \} */
  82698. #ifdef __cplusplus
  82699. }
  82700. #endif
  82701. #endif
  82702. /********* End of inlined file: metadata.h *********/
  82703. /********* Start of inlined file: stream_decoder.h *********/
  82704. #ifndef FLAC__STREAM_DECODER_H
  82705. #define FLAC__STREAM_DECODER_H
  82706. #include <stdio.h> /* for FILE */
  82707. #ifdef __cplusplus
  82708. extern "C" {
  82709. #endif
  82710. /** \file include/FLAC/stream_decoder.h
  82711. *
  82712. * \brief
  82713. * This module contains the functions which implement the stream
  82714. * decoder.
  82715. *
  82716. * See the detailed documentation in the
  82717. * \link flac_stream_decoder stream decoder \endlink module.
  82718. */
  82719. /** \defgroup flac_decoder FLAC/ \*_decoder.h: decoder interfaces
  82720. * \ingroup flac
  82721. *
  82722. * \brief
  82723. * This module describes the decoder layers provided by libFLAC.
  82724. *
  82725. * The stream decoder can be used to decode complete streams either from
  82726. * the client via callbacks, or directly from a file, depending on how
  82727. * it is initialized. When decoding via callbacks, the client provides
  82728. * callbacks for reading FLAC data and writing decoded samples, and
  82729. * handling metadata and errors. If the client also supplies seek-related
  82730. * callback, the decoder function for sample-accurate seeking within the
  82731. * FLAC input is also available. When decoding from a file, the client
  82732. * needs only supply a filename or open \c FILE* and write/metadata/error
  82733. * callbacks; the rest of the callbacks are supplied internally. For more
  82734. * info see the \link flac_stream_decoder stream decoder \endlink module.
  82735. */
  82736. /** \defgroup flac_stream_decoder FLAC/stream_decoder.h: stream decoder interface
  82737. * \ingroup flac_decoder
  82738. *
  82739. * \brief
  82740. * This module contains the functions which implement the stream
  82741. * decoder.
  82742. *
  82743. * The stream decoder can decode native FLAC, and optionally Ogg FLAC
  82744. * (check FLAC_API_SUPPORTS_OGG_FLAC) streams and files.
  82745. *
  82746. * The basic usage of this decoder is as follows:
  82747. * - The program creates an instance of a decoder using
  82748. * FLAC__stream_decoder_new().
  82749. * - The program overrides the default settings using
  82750. * FLAC__stream_decoder_set_*() functions.
  82751. * - The program initializes the instance to validate the settings and
  82752. * prepare for decoding using
  82753. * - FLAC__stream_decoder_init_stream() or FLAC__stream_decoder_init_FILE()
  82754. * or FLAC__stream_decoder_init_file() for native FLAC,
  82755. * - FLAC__stream_decoder_init_ogg_stream() or FLAC__stream_decoder_init_ogg_FILE()
  82756. * or FLAC__stream_decoder_init_ogg_file() for Ogg FLAC
  82757. * - The program calls the FLAC__stream_decoder_process_*() functions
  82758. * to decode data, which subsequently calls the callbacks.
  82759. * - The program finishes the decoding with FLAC__stream_decoder_finish(),
  82760. * which flushes the input and output and resets the decoder to the
  82761. * uninitialized state.
  82762. * - The instance may be used again or deleted with
  82763. * FLAC__stream_decoder_delete().
  82764. *
  82765. * In more detail, the program will create a new instance by calling
  82766. * FLAC__stream_decoder_new(), then call FLAC__stream_decoder_set_*()
  82767. * functions to override the default decoder options, and call
  82768. * one of the FLAC__stream_decoder_init_*() functions.
  82769. *
  82770. * There are three initialization functions for native FLAC, one for
  82771. * setting up the decoder to decode FLAC data from the client via
  82772. * callbacks, and two for decoding directly from a FLAC file.
  82773. *
  82774. * For decoding via callbacks, use FLAC__stream_decoder_init_stream().
  82775. * You must also supply several callbacks for handling I/O. Some (like
  82776. * seeking) are optional, depending on the capabilities of the input.
  82777. *
  82778. * For decoding directly from a file, use FLAC__stream_decoder_init_FILE()
  82779. * or FLAC__stream_decoder_init_file(). Then you must only supply an open
  82780. * \c FILE* or filename and fewer callbacks; the decoder will handle
  82781. * the other callbacks internally.
  82782. *
  82783. * There are three similarly-named init functions for decoding from Ogg
  82784. * FLAC streams. Check \c FLAC_API_SUPPORTS_OGG_FLAC to find out if the
  82785. * library has been built with Ogg support.
  82786. *
  82787. * Once the decoder is initialized, your program will call one of several
  82788. * functions to start the decoding process:
  82789. *
  82790. * - FLAC__stream_decoder_process_single() - Tells the decoder to process at
  82791. * most one metadata block or audio frame and return, calling either the
  82792. * metadata callback or write callback, respectively, once. If the decoder
  82793. * loses sync it will return with only the error callback being called.
  82794. * - FLAC__stream_decoder_process_until_end_of_metadata() - Tells the decoder
  82795. * to process the stream from the current location and stop upon reaching
  82796. * the first audio frame. The client will get one metadata, write, or error
  82797. * callback per metadata block, audio frame, or sync error, respectively.
  82798. * - FLAC__stream_decoder_process_until_end_of_stream() - Tells the decoder
  82799. * to process the stream from the current location until the read callback
  82800. * returns FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM or
  82801. * FLAC__STREAM_DECODER_READ_STATUS_ABORT. The client will get one metadata,
  82802. * write, or error callback per metadata block, audio frame, or sync error,
  82803. * respectively.
  82804. *
  82805. * When the decoder has finished decoding (normally or through an abort),
  82806. * the instance is finished by calling FLAC__stream_decoder_finish(), which
  82807. * ensures the decoder is in the correct state and frees memory. Then the
  82808. * instance may be deleted with FLAC__stream_decoder_delete() or initialized
  82809. * again to decode another stream.
  82810. *
  82811. * Seeking is exposed through the FLAC__stream_decoder_seek_absolute() method.
  82812. * At any point after the stream decoder has been initialized, the client can
  82813. * call this function to seek to an exact sample within the stream.
  82814. * Subsequently, the first time the write callback is called it will be
  82815. * passed a (possibly partial) block starting at that sample.
  82816. *
  82817. * If the client cannot seek via the callback interface provided, but still
  82818. * has another way of seeking, it can flush the decoder using
  82819. * FLAC__stream_decoder_flush() and start feeding data from the new position
  82820. * through the read callback.
  82821. *
  82822. * The stream decoder also provides MD5 signature checking. If this is
  82823. * turned on before initialization, FLAC__stream_decoder_finish() will
  82824. * report when the decoded MD5 signature does not match the one stored
  82825. * in the STREAMINFO block. MD5 checking is automatically turned off
  82826. * (until the next FLAC__stream_decoder_reset()) if there is no signature
  82827. * in the STREAMINFO block or when a seek is attempted.
  82828. *
  82829. * The FLAC__stream_decoder_set_metadata_*() functions deserve special
  82830. * attention. By default, the decoder only calls the metadata_callback for
  82831. * the STREAMINFO block. These functions allow you to tell the decoder
  82832. * explicitly which blocks to parse and return via the metadata_callback
  82833. * and/or which to skip. Use a FLAC__stream_decoder_set_metadata_respond_all(),
  82834. * FLAC__stream_decoder_set_metadata_ignore() ... or FLAC__stream_decoder_set_metadata_ignore_all(),
  82835. * FLAC__stream_decoder_set_metadata_respond() ... sequence to exactly specify
  82836. * which blocks to return. Remember that metadata blocks can potentially
  82837. * be big (for example, cover art) so filtering out the ones you don't
  82838. * use can reduce the memory requirements of the decoder. Also note the
  82839. * special forms FLAC__stream_decoder_set_metadata_respond_application(id)
  82840. * and FLAC__stream_decoder_set_metadata_ignore_application(id) for
  82841. * filtering APPLICATION blocks based on the application ID.
  82842. *
  82843. * STREAMINFO and SEEKTABLE blocks are always parsed and used internally, but
  82844. * they still can legally be filtered from the metadata_callback.
  82845. *
  82846. * \note
  82847. * The "set" functions may only be called when the decoder is in the
  82848. * state FLAC__STREAM_DECODER_UNINITIALIZED, i.e. after
  82849. * FLAC__stream_decoder_new() or FLAC__stream_decoder_finish(), but
  82850. * before FLAC__stream_decoder_init_*(). If this is the case they will
  82851. * return \c true, otherwise \c false.
  82852. *
  82853. * \note
  82854. * FLAC__stream_decoder_finish() resets all settings to the constructor
  82855. * defaults, including the callbacks.
  82856. *
  82857. * \{
  82858. */
  82859. /** State values for a FLAC__StreamDecoder
  82860. *
  82861. * The decoder's state can be obtained by calling FLAC__stream_decoder_get_state().
  82862. */
  82863. typedef enum {
  82864. FLAC__STREAM_DECODER_SEARCH_FOR_METADATA = 0,
  82865. /**< The decoder is ready to search for metadata. */
  82866. FLAC__STREAM_DECODER_READ_METADATA,
  82867. /**< The decoder is ready to or is in the process of reading metadata. */
  82868. FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC,
  82869. /**< The decoder is ready to or is in the process of searching for the
  82870. * frame sync code.
  82871. */
  82872. FLAC__STREAM_DECODER_READ_FRAME,
  82873. /**< The decoder is ready to or is in the process of reading a frame. */
  82874. FLAC__STREAM_DECODER_END_OF_STREAM,
  82875. /**< The decoder has reached the end of the stream. */
  82876. FLAC__STREAM_DECODER_OGG_ERROR,
  82877. /**< An error occurred in the underlying Ogg layer. */
  82878. FLAC__STREAM_DECODER_SEEK_ERROR,
  82879. /**< An error occurred while seeking. The decoder must be flushed
  82880. * with FLAC__stream_decoder_flush() or reset with
  82881. * FLAC__stream_decoder_reset() before decoding can continue.
  82882. */
  82883. FLAC__STREAM_DECODER_ABORTED,
  82884. /**< The decoder was aborted by the read callback. */
  82885. FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR,
  82886. /**< An error occurred allocating memory. The decoder is in an invalid
  82887. * state and can no longer be used.
  82888. */
  82889. FLAC__STREAM_DECODER_UNINITIALIZED
  82890. /**< The decoder is in the uninitialized state; one of the
  82891. * FLAC__stream_decoder_init_*() functions must be called before samples
  82892. * can be processed.
  82893. */
  82894. } FLAC__StreamDecoderState;
  82895. /** Maps a FLAC__StreamDecoderState to a C string.
  82896. *
  82897. * Using a FLAC__StreamDecoderState as the index to this array
  82898. * will give the string equivalent. The contents should not be modified.
  82899. */
  82900. extern FLAC_API const char * const FLAC__StreamDecoderStateString[];
  82901. /** Possible return values for the FLAC__stream_decoder_init_*() functions.
  82902. */
  82903. typedef enum {
  82904. FLAC__STREAM_DECODER_INIT_STATUS_OK = 0,
  82905. /**< Initialization was successful. */
  82906. FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER,
  82907. /**< The library was not compiled with support for the given container
  82908. * format.
  82909. */
  82910. FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS,
  82911. /**< A required callback was not supplied. */
  82912. FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR,
  82913. /**< An error occurred allocating memory. */
  82914. FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE,
  82915. /**< fopen() failed in FLAC__stream_decoder_init_file() or
  82916. * FLAC__stream_decoder_init_ogg_file(). */
  82917. FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED
  82918. /**< FLAC__stream_decoder_init_*() was called when the decoder was
  82919. * already initialized, usually because
  82920. * FLAC__stream_decoder_finish() was not called.
  82921. */
  82922. } FLAC__StreamDecoderInitStatus;
  82923. /** Maps a FLAC__StreamDecoderInitStatus to a C string.
  82924. *
  82925. * Using a FLAC__StreamDecoderInitStatus as the index to this array
  82926. * will give the string equivalent. The contents should not be modified.
  82927. */
  82928. extern FLAC_API const char * const FLAC__StreamDecoderInitStatusString[];
  82929. /** Return values for the FLAC__StreamDecoder read callback.
  82930. */
  82931. typedef enum {
  82932. FLAC__STREAM_DECODER_READ_STATUS_CONTINUE,
  82933. /**< The read was OK and decoding can continue. */
  82934. FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM,
  82935. /**< The read was attempted while at the end of the stream. Note that
  82936. * the client must only return this value when the read callback was
  82937. * called when already at the end of the stream. Otherwise, if the read
  82938. * itself moves to the end of the stream, the client should still return
  82939. * the data and \c FLAC__STREAM_DECODER_READ_STATUS_CONTINUE, and then on
  82940. * the next read callback it should return
  82941. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM with a byte count
  82942. * of \c 0.
  82943. */
  82944. FLAC__STREAM_DECODER_READ_STATUS_ABORT
  82945. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  82946. } FLAC__StreamDecoderReadStatus;
  82947. /** Maps a FLAC__StreamDecoderReadStatus to a C string.
  82948. *
  82949. * Using a FLAC__StreamDecoderReadStatus as the index to this array
  82950. * will give the string equivalent. The contents should not be modified.
  82951. */
  82952. extern FLAC_API const char * const FLAC__StreamDecoderReadStatusString[];
  82953. /** Return values for the FLAC__StreamDecoder seek callback.
  82954. */
  82955. typedef enum {
  82956. FLAC__STREAM_DECODER_SEEK_STATUS_OK,
  82957. /**< The seek was OK and decoding can continue. */
  82958. FLAC__STREAM_DECODER_SEEK_STATUS_ERROR,
  82959. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  82960. FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  82961. /**< Client does not support seeking. */
  82962. } FLAC__StreamDecoderSeekStatus;
  82963. /** Maps a FLAC__StreamDecoderSeekStatus to a C string.
  82964. *
  82965. * Using a FLAC__StreamDecoderSeekStatus as the index to this array
  82966. * will give the string equivalent. The contents should not be modified.
  82967. */
  82968. extern FLAC_API const char * const FLAC__StreamDecoderSeekStatusString[];
  82969. /** Return values for the FLAC__StreamDecoder tell callback.
  82970. */
  82971. typedef enum {
  82972. FLAC__STREAM_DECODER_TELL_STATUS_OK,
  82973. /**< The tell was OK and decoding can continue. */
  82974. FLAC__STREAM_DECODER_TELL_STATUS_ERROR,
  82975. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  82976. FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  82977. /**< Client does not support telling the position. */
  82978. } FLAC__StreamDecoderTellStatus;
  82979. /** Maps a FLAC__StreamDecoderTellStatus to a C string.
  82980. *
  82981. * Using a FLAC__StreamDecoderTellStatus as the index to this array
  82982. * will give the string equivalent. The contents should not be modified.
  82983. */
  82984. extern FLAC_API const char * const FLAC__StreamDecoderTellStatusString[];
  82985. /** Return values for the FLAC__StreamDecoder length callback.
  82986. */
  82987. typedef enum {
  82988. FLAC__STREAM_DECODER_LENGTH_STATUS_OK,
  82989. /**< The length call was OK and decoding can continue. */
  82990. FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR,
  82991. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  82992. FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  82993. /**< Client does not support reporting the length. */
  82994. } FLAC__StreamDecoderLengthStatus;
  82995. /** Maps a FLAC__StreamDecoderLengthStatus to a C string.
  82996. *
  82997. * Using a FLAC__StreamDecoderLengthStatus 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__StreamDecoderLengthStatusString[];
  83001. /** Return values for the FLAC__StreamDecoder write callback.
  83002. */
  83003. typedef enum {
  83004. FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE,
  83005. /**< The write was OK and decoding can continue. */
  83006. FLAC__STREAM_DECODER_WRITE_STATUS_ABORT
  83007. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  83008. } FLAC__StreamDecoderWriteStatus;
  83009. /** Maps a FLAC__StreamDecoderWriteStatus to a C string.
  83010. *
  83011. * Using a FLAC__StreamDecoderWriteStatus as the index to this array
  83012. * will give the string equivalent. The contents should not be modified.
  83013. */
  83014. extern FLAC_API const char * const FLAC__StreamDecoderWriteStatusString[];
  83015. /** Possible values passed back to the FLAC__StreamDecoder error callback.
  83016. * \c FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC is the generic catch-
  83017. * all. The rest could be caused by bad sync (false synchronization on
  83018. * data that is not the start of a frame) or corrupted data. The error
  83019. * itself is the decoder's best guess at what happened assuming a correct
  83020. * sync. For example \c FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER
  83021. * could be caused by a correct sync on the start of a frame, but some
  83022. * data in the frame header was corrupted. Or it could be the result of
  83023. * syncing on a point the stream that looked like the starting of a frame
  83024. * but was not. \c FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM
  83025. * could be because the decoder encountered a valid frame made by a future
  83026. * version of the encoder which it cannot parse, or because of a false
  83027. * sync making it appear as though an encountered frame was generated by
  83028. * a future encoder.
  83029. */
  83030. typedef enum {
  83031. FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC,
  83032. /**< An error in the stream caused the decoder to lose synchronization. */
  83033. FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER,
  83034. /**< The decoder encountered a corrupted frame header. */
  83035. FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH,
  83036. /**< The frame's data did not match the CRC in the footer. */
  83037. FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM
  83038. /**< The decoder encountered reserved fields in use in the stream. */
  83039. } FLAC__StreamDecoderErrorStatus;
  83040. /** Maps a FLAC__StreamDecoderErrorStatus to a C string.
  83041. *
  83042. * Using a FLAC__StreamDecoderErrorStatus as the index to this array
  83043. * will give the string equivalent. The contents should not be modified.
  83044. */
  83045. extern FLAC_API const char * const FLAC__StreamDecoderErrorStatusString[];
  83046. /***********************************************************************
  83047. *
  83048. * class FLAC__StreamDecoder
  83049. *
  83050. ***********************************************************************/
  83051. struct FLAC__StreamDecoderProtected;
  83052. struct FLAC__StreamDecoderPrivate;
  83053. /** The opaque structure definition for the stream decoder type.
  83054. * See the \link flac_stream_decoder stream decoder module \endlink
  83055. * for a detailed description.
  83056. */
  83057. typedef struct {
  83058. struct FLAC__StreamDecoderProtected *protected_; /* avoid the C++ keyword 'protected' */
  83059. struct FLAC__StreamDecoderPrivate *private_; /* avoid the C++ keyword 'private' */
  83060. } FLAC__StreamDecoder;
  83061. /** Signature for the read callback.
  83062. *
  83063. * A function pointer matching this signature must be passed to
  83064. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  83065. * called when the decoder needs more input data. The address of the
  83066. * buffer to be filled is supplied, along with the number of bytes the
  83067. * buffer can hold. The callback may choose to supply less data and
  83068. * modify the byte count but must be careful not to overflow the buffer.
  83069. * The callback then returns a status code chosen from
  83070. * FLAC__StreamDecoderReadStatus.
  83071. *
  83072. * Here is an example of a read callback for stdio streams:
  83073. * \code
  83074. * FLAC__StreamDecoderReadStatus read_cb(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  83075. * {
  83076. * FILE *file = ((MyClientData*)client_data)->file;
  83077. * if(*bytes > 0) {
  83078. * *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, file);
  83079. * if(ferror(file))
  83080. * return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  83081. * else if(*bytes == 0)
  83082. * return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  83083. * else
  83084. * return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  83085. * }
  83086. * else
  83087. * return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  83088. * }
  83089. * \endcode
  83090. *
  83091. * \note In general, FLAC__StreamDecoder functions which change the
  83092. * state should not be called on the \a decoder while in the callback.
  83093. *
  83094. * \param decoder The decoder instance calling the callback.
  83095. * \param buffer A pointer to a location for the callee to store
  83096. * data to be decoded.
  83097. * \param bytes A pointer to the size of the buffer. On entry
  83098. * to the callback, it contains the maximum number
  83099. * of bytes that may be stored in \a buffer. The
  83100. * callee must set it to the actual number of bytes
  83101. * stored (0 in case of error or end-of-stream) before
  83102. * returning.
  83103. * \param client_data The callee's client data set through
  83104. * FLAC__stream_decoder_init_*().
  83105. * \retval FLAC__StreamDecoderReadStatus
  83106. * The callee's return status. Note that the callback should return
  83107. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM if and only if
  83108. * zero bytes were read and there is no more data to be read.
  83109. */
  83110. typedef FLAC__StreamDecoderReadStatus (*FLAC__StreamDecoderReadCallback)(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  83111. /** Signature for the seek callback.
  83112. *
  83113. * A function pointer matching this signature may be passed to
  83114. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  83115. * called when the decoder needs to seek the input stream. The decoder
  83116. * will pass the absolute byte offset to seek to, 0 meaning the
  83117. * beginning of the stream.
  83118. *
  83119. * Here is an example of a seek callback for stdio streams:
  83120. * \code
  83121. * FLAC__StreamDecoderSeekStatus seek_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  83122. * {
  83123. * FILE *file = ((MyClientData*)client_data)->file;
  83124. * if(file == stdin)
  83125. * return FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED;
  83126. * else if(fseeko(file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  83127. * return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR;
  83128. * else
  83129. * return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  83130. * }
  83131. * \endcode
  83132. *
  83133. * \note In general, FLAC__StreamDecoder functions which change the
  83134. * state should not be called on the \a decoder while in the callback.
  83135. *
  83136. * \param decoder The decoder instance calling the callback.
  83137. * \param absolute_byte_offset The offset from the beginning of the stream
  83138. * to seek to.
  83139. * \param client_data The callee's client data set through
  83140. * FLAC__stream_decoder_init_*().
  83141. * \retval FLAC__StreamDecoderSeekStatus
  83142. * The callee's return status.
  83143. */
  83144. typedef FLAC__StreamDecoderSeekStatus (*FLAC__StreamDecoderSeekCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  83145. /** Signature for the tell callback.
  83146. *
  83147. * A function pointer matching this signature may be passed to
  83148. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  83149. * called when the decoder wants to know the current position of the
  83150. * stream. The callback should return the byte offset from the
  83151. * beginning of the stream.
  83152. *
  83153. * Here is an example of a tell callback for stdio streams:
  83154. * \code
  83155. * FLAC__StreamDecoderTellStatus tell_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  83156. * {
  83157. * FILE *file = ((MyClientData*)client_data)->file;
  83158. * off_t pos;
  83159. * if(file == stdin)
  83160. * return FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED;
  83161. * else if((pos = ftello(file)) < 0)
  83162. * return FLAC__STREAM_DECODER_TELL_STATUS_ERROR;
  83163. * else {
  83164. * *absolute_byte_offset = (FLAC__uint64)pos;
  83165. * return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  83166. * }
  83167. * }
  83168. * \endcode
  83169. *
  83170. * \note In general, FLAC__StreamDecoder functions which change the
  83171. * state should not be called on the \a decoder while in the callback.
  83172. *
  83173. * \param decoder The decoder instance calling the callback.
  83174. * \param absolute_byte_offset A pointer to storage for the current offset
  83175. * from the beginning of the stream.
  83176. * \param client_data The callee's client data set through
  83177. * FLAC__stream_decoder_init_*().
  83178. * \retval FLAC__StreamDecoderTellStatus
  83179. * The callee's return status.
  83180. */
  83181. typedef FLAC__StreamDecoderTellStatus (*FLAC__StreamDecoderTellCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  83182. /** Signature for the length callback.
  83183. *
  83184. * A function pointer matching this signature may be passed to
  83185. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  83186. * called when the decoder wants to know the total length of the stream
  83187. * in bytes.
  83188. *
  83189. * Here is an example of a length callback for stdio streams:
  83190. * \code
  83191. * FLAC__StreamDecoderLengthStatus length_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data)
  83192. * {
  83193. * FILE *file = ((MyClientData*)client_data)->file;
  83194. * struct stat filestats;
  83195. *
  83196. * if(file == stdin)
  83197. * return FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED;
  83198. * else if(fstat(fileno(file), &filestats) != 0)
  83199. * return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR;
  83200. * else {
  83201. * *stream_length = (FLAC__uint64)filestats.st_size;
  83202. * return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  83203. * }
  83204. * }
  83205. * \endcode
  83206. *
  83207. * \note In general, FLAC__StreamDecoder functions which change the
  83208. * state should not be called on the \a decoder while in the callback.
  83209. *
  83210. * \param decoder The decoder instance calling the callback.
  83211. * \param stream_length A pointer to storage for the length of the stream
  83212. * in bytes.
  83213. * \param client_data The callee's client data set through
  83214. * FLAC__stream_decoder_init_*().
  83215. * \retval FLAC__StreamDecoderLengthStatus
  83216. * The callee's return status.
  83217. */
  83218. typedef FLAC__StreamDecoderLengthStatus (*FLAC__StreamDecoderLengthCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data);
  83219. /** Signature for the EOF callback.
  83220. *
  83221. * A function pointer matching this signature may be passed to
  83222. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  83223. * called when the decoder needs to know if the end of the stream has
  83224. * been reached.
  83225. *
  83226. * Here is an example of a EOF callback for stdio streams:
  83227. * FLAC__bool eof_cb(const FLAC__StreamDecoder *decoder, void *client_data)
  83228. * \code
  83229. * {
  83230. * FILE *file = ((MyClientData*)client_data)->file;
  83231. * return feof(file)? true : false;
  83232. * }
  83233. * \endcode
  83234. *
  83235. * \note In general, FLAC__StreamDecoder functions which change the
  83236. * state should not be called on the \a decoder while in the callback.
  83237. *
  83238. * \param decoder The decoder instance calling the callback.
  83239. * \param client_data The callee's client data set through
  83240. * FLAC__stream_decoder_init_*().
  83241. * \retval FLAC__bool
  83242. * \c true if the currently at the end of the stream, else \c false.
  83243. */
  83244. typedef FLAC__bool (*FLAC__StreamDecoderEofCallback)(const FLAC__StreamDecoder *decoder, void *client_data);
  83245. /** Signature for the write callback.
  83246. *
  83247. * A function pointer matching this signature must be passed to one of
  83248. * the FLAC__stream_decoder_init_*() functions.
  83249. * The supplied function will be called when the decoder has decoded a
  83250. * single audio frame. The decoder will pass the frame metadata as well
  83251. * as an array of pointers (one for each channel) pointing to the
  83252. * decoded audio.
  83253. *
  83254. * \note In general, FLAC__StreamDecoder functions which change the
  83255. * state should not be called on the \a decoder while in the callback.
  83256. *
  83257. * \param decoder The decoder instance calling the callback.
  83258. * \param frame The description of the decoded frame. See
  83259. * FLAC__Frame.
  83260. * \param buffer An array of pointers to decoded channels of data.
  83261. * Each pointer will point to an array of signed
  83262. * samples of length \a frame->header.blocksize.
  83263. * Channels will be ordered according to the FLAC
  83264. * specification; see the documentation for the
  83265. * <A HREF="../format.html#frame_header">frame header</A>.
  83266. * \param client_data The callee's client data set through
  83267. * FLAC__stream_decoder_init_*().
  83268. * \retval FLAC__StreamDecoderWriteStatus
  83269. * The callee's return status.
  83270. */
  83271. typedef FLAC__StreamDecoderWriteStatus (*FLAC__StreamDecoderWriteCallback)(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
  83272. /** Signature for the metadata callback.
  83273. *
  83274. * A function pointer matching this signature must be passed to one of
  83275. * the FLAC__stream_decoder_init_*() functions.
  83276. * The supplied function will be called when the decoder has decoded a
  83277. * metadata block. In a valid FLAC file there will always be one
  83278. * \c STREAMINFO block, followed by zero or more other metadata blocks.
  83279. * These will be supplied by the decoder in the same order as they
  83280. * appear in the stream and always before the first audio frame (i.e.
  83281. * write callback). The metadata block that is passed in must not be
  83282. * modified, and it doesn't live beyond the callback, so you should make
  83283. * a copy of it with FLAC__metadata_object_clone() if you will need it
  83284. * elsewhere. Since metadata blocks can potentially be large, by
  83285. * default the decoder only calls the metadata callback for the
  83286. * \c STREAMINFO block; you can instruct the decoder to pass or filter
  83287. * other blocks with FLAC__stream_decoder_set_metadata_*() calls.
  83288. *
  83289. * \note In general, FLAC__StreamDecoder functions which change the
  83290. * state should not be called on the \a decoder while in the callback.
  83291. *
  83292. * \param decoder The decoder instance calling the callback.
  83293. * \param metadata The decoded metadata block.
  83294. * \param client_data The callee's client data set through
  83295. * FLAC__stream_decoder_init_*().
  83296. */
  83297. typedef void (*FLAC__StreamDecoderMetadataCallback)(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
  83298. /** Signature for the error callback.
  83299. *
  83300. * A function pointer matching this signature must be passed to one of
  83301. * the FLAC__stream_decoder_init_*() functions.
  83302. * The supplied function will be called whenever an error occurs during
  83303. * decoding.
  83304. *
  83305. * \note In general, FLAC__StreamDecoder functions which change the
  83306. * state should not be called on the \a decoder while in the callback.
  83307. *
  83308. * \param decoder The decoder instance calling the callback.
  83309. * \param status The error encountered by the decoder.
  83310. * \param client_data The callee's client data set through
  83311. * FLAC__stream_decoder_init_*().
  83312. */
  83313. typedef void (*FLAC__StreamDecoderErrorCallback)(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
  83314. /***********************************************************************
  83315. *
  83316. * Class constructor/destructor
  83317. *
  83318. ***********************************************************************/
  83319. /** Create a new stream decoder instance. The instance is created with
  83320. * default settings; see the individual FLAC__stream_decoder_set_*()
  83321. * functions for each setting's default.
  83322. *
  83323. * \retval FLAC__StreamDecoder*
  83324. * \c NULL if there was an error allocating memory, else the new instance.
  83325. */
  83326. FLAC_API FLAC__StreamDecoder *FLAC__stream_decoder_new(void);
  83327. /** Free a decoder instance. Deletes the object pointed to by \a decoder.
  83328. *
  83329. * \param decoder A pointer to an existing decoder.
  83330. * \assert
  83331. * \code decoder != NULL \endcode
  83332. */
  83333. FLAC_API void FLAC__stream_decoder_delete(FLAC__StreamDecoder *decoder);
  83334. /***********************************************************************
  83335. *
  83336. * Public class method prototypes
  83337. *
  83338. ***********************************************************************/
  83339. /** Set the serial number for the FLAC stream within the Ogg container.
  83340. * The default behavior is to use the serial number of the first Ogg
  83341. * page. Setting a serial number here will explicitly specify which
  83342. * stream is to be decoded.
  83343. *
  83344. * \note
  83345. * This does not need to be set for native FLAC decoding.
  83346. *
  83347. * \default \c use serial number of first page
  83348. * \param decoder A decoder instance to set.
  83349. * \param serial_number See above.
  83350. * \assert
  83351. * \code decoder != NULL \endcode
  83352. * \retval FLAC__bool
  83353. * \c false if the decoder is already initialized, else \c true.
  83354. */
  83355. FLAC_API FLAC__bool FLAC__stream_decoder_set_ogg_serial_number(FLAC__StreamDecoder *decoder, long serial_number);
  83356. /** Set the "MD5 signature checking" flag. If \c true, the decoder will
  83357. * compute the MD5 signature of the unencoded audio data while decoding
  83358. * and compare it to the signature from the STREAMINFO block, if it
  83359. * exists, during FLAC__stream_decoder_finish().
  83360. *
  83361. * MD5 signature checking will be turned off (until the next
  83362. * FLAC__stream_decoder_reset()) if there is no signature in the
  83363. * STREAMINFO block or when a seek is attempted.
  83364. *
  83365. * Clients that do not use the MD5 check should leave this off to speed
  83366. * up decoding.
  83367. *
  83368. * \default \c false
  83369. * \param decoder A decoder instance to set.
  83370. * \param value Flag value (see above).
  83371. * \assert
  83372. * \code decoder != NULL \endcode
  83373. * \retval FLAC__bool
  83374. * \c false if the decoder is already initialized, else \c true.
  83375. */
  83376. FLAC_API FLAC__bool FLAC__stream_decoder_set_md5_checking(FLAC__StreamDecoder *decoder, FLAC__bool value);
  83377. /** Direct the decoder to pass on all metadata blocks of type \a type.
  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 type See above.
  83383. * \assert
  83384. * \code decoder != NULL \endcode
  83385. * \a type is valid
  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(FLAC__StreamDecoder *decoder, FLAC__MetadataType type);
  83390. /** Direct the decoder to pass on all APPLICATION metadata blocks of the
  83391. * given \a id.
  83392. *
  83393. * \default By default, only the \c STREAMINFO block is returned via the
  83394. * metadata callback.
  83395. * \param decoder A decoder instance to set.
  83396. * \param id See above.
  83397. * \assert
  83398. * \code decoder != NULL \endcode
  83399. * \code id != NULL \endcode
  83400. * \retval FLAC__bool
  83401. * \c false if the decoder is already initialized, else \c true.
  83402. */
  83403. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4]);
  83404. /** Direct the decoder to pass on all metadata blocks of any type.
  83405. *
  83406. * \default By default, only the \c STREAMINFO block is returned via the
  83407. * metadata callback.
  83408. * \param decoder A decoder instance to set.
  83409. * \assert
  83410. * \code decoder != NULL \endcode
  83411. * \retval FLAC__bool
  83412. * \c false if the decoder is already initialized, else \c true.
  83413. */
  83414. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_all(FLAC__StreamDecoder *decoder);
  83415. /** Direct the decoder to filter out all metadata blocks of type \a type.
  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 type See above.
  83421. * \assert
  83422. * \code decoder != NULL \endcode
  83423. * \a type is valid
  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(FLAC__StreamDecoder *decoder, FLAC__MetadataType type);
  83428. /** Direct the decoder to filter out all APPLICATION metadata blocks of
  83429. * the given \a id.
  83430. *
  83431. * \default By default, only the \c STREAMINFO block is returned via the
  83432. * metadata callback.
  83433. * \param decoder A decoder instance to set.
  83434. * \param id See above.
  83435. * \assert
  83436. * \code decoder != NULL \endcode
  83437. * \code id != NULL \endcode
  83438. * \retval FLAC__bool
  83439. * \c false if the decoder is already initialized, else \c true.
  83440. */
  83441. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4]);
  83442. /** Direct the decoder to filter out all metadata blocks of any type.
  83443. *
  83444. * \default By default, only the \c STREAMINFO block is returned via the
  83445. * metadata callback.
  83446. * \param decoder A decoder instance to set.
  83447. * \assert
  83448. * \code decoder != NULL \endcode
  83449. * \retval FLAC__bool
  83450. * \c false if the decoder is already initialized, else \c true.
  83451. */
  83452. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_all(FLAC__StreamDecoder *decoder);
  83453. /** Get the current decoder state.
  83454. *
  83455. * \param decoder A decoder instance to query.
  83456. * \assert
  83457. * \code decoder != NULL \endcode
  83458. * \retval FLAC__StreamDecoderState
  83459. * The current decoder state.
  83460. */
  83461. FLAC_API FLAC__StreamDecoderState FLAC__stream_decoder_get_state(const FLAC__StreamDecoder *decoder);
  83462. /** Get the current decoder state as a C string.
  83463. *
  83464. * \param decoder A decoder instance to query.
  83465. * \assert
  83466. * \code decoder != NULL \endcode
  83467. * \retval const char *
  83468. * The decoder state as a C string. Do not modify the contents.
  83469. */
  83470. FLAC_API const char *FLAC__stream_decoder_get_resolved_state_string(const FLAC__StreamDecoder *decoder);
  83471. /** Get the "MD5 signature checking" flag.
  83472. * This is the value of the setting, not whether or not the decoder is
  83473. * currently checking the MD5 (remember, it can be turned off automatically
  83474. * by a seek). When the decoder is reset the flag will be restored to the
  83475. * value returned by this function.
  83476. *
  83477. * \param decoder A decoder instance to query.
  83478. * \assert
  83479. * \code decoder != NULL \endcode
  83480. * \retval FLAC__bool
  83481. * See above.
  83482. */
  83483. FLAC_API FLAC__bool FLAC__stream_decoder_get_md5_checking(const FLAC__StreamDecoder *decoder);
  83484. /** Get the total number of samples in the stream being decoded.
  83485. * Will only be valid after decoding has started and will contain the
  83486. * value from the \c STREAMINFO block. A value of \c 0 means "unknown".
  83487. *
  83488. * \param decoder A decoder instance to query.
  83489. * \assert
  83490. * \code decoder != NULL \endcode
  83491. * \retval unsigned
  83492. * See above.
  83493. */
  83494. FLAC_API FLAC__uint64 FLAC__stream_decoder_get_total_samples(const FLAC__StreamDecoder *decoder);
  83495. /** Get the current number of channels in the stream being decoded.
  83496. * Will only be valid after decoding has started and will contain the
  83497. * value from the most recently decoded frame header.
  83498. *
  83499. * \param decoder A decoder instance to query.
  83500. * \assert
  83501. * \code decoder != NULL \endcode
  83502. * \retval unsigned
  83503. * See above.
  83504. */
  83505. FLAC_API unsigned FLAC__stream_decoder_get_channels(const FLAC__StreamDecoder *decoder);
  83506. /** Get the current channel assignment in the stream being decoded.
  83507. * Will only be valid after decoding has started and will contain the
  83508. * value from the most recently decoded frame header.
  83509. *
  83510. * \param decoder A decoder instance to query.
  83511. * \assert
  83512. * \code decoder != NULL \endcode
  83513. * \retval FLAC__ChannelAssignment
  83514. * See above.
  83515. */
  83516. FLAC_API FLAC__ChannelAssignment FLAC__stream_decoder_get_channel_assignment(const FLAC__StreamDecoder *decoder);
  83517. /** Get the current sample resolution in the stream being decoded.
  83518. * Will only be valid after decoding has started and will contain the
  83519. * value from the most recently decoded frame header.
  83520. *
  83521. * \param decoder A decoder instance to query.
  83522. * \assert
  83523. * \code decoder != NULL \endcode
  83524. * \retval unsigned
  83525. * See above.
  83526. */
  83527. FLAC_API unsigned FLAC__stream_decoder_get_bits_per_sample(const FLAC__StreamDecoder *decoder);
  83528. /** Get the current sample rate in Hz of the stream being decoded.
  83529. * Will only be valid after decoding has started and will contain the
  83530. * value from the most recently decoded frame header.
  83531. *
  83532. * \param decoder A decoder instance to query.
  83533. * \assert
  83534. * \code decoder != NULL \endcode
  83535. * \retval unsigned
  83536. * See above.
  83537. */
  83538. FLAC_API unsigned FLAC__stream_decoder_get_sample_rate(const FLAC__StreamDecoder *decoder);
  83539. /** Get the current blocksize of the stream being decoded.
  83540. * Will only be valid after decoding has started and will contain the
  83541. * value from the most recently decoded frame header.
  83542. *
  83543. * \param decoder A decoder instance to query.
  83544. * \assert
  83545. * \code decoder != NULL \endcode
  83546. * \retval unsigned
  83547. * See above.
  83548. */
  83549. FLAC_API unsigned FLAC__stream_decoder_get_blocksize(const FLAC__StreamDecoder *decoder);
  83550. /** Returns the decoder's current read position within the stream.
  83551. * The position is the byte offset from the start of the stream.
  83552. * Bytes before this position have been fully decoded. Note that
  83553. * there may still be undecoded bytes in the decoder's read FIFO.
  83554. * The returned position is correct even after a seek.
  83555. *
  83556. * \warning This function currently only works for native FLAC,
  83557. * not Ogg FLAC streams.
  83558. *
  83559. * \param decoder A decoder instance to query.
  83560. * \param position Address at which to return the desired position.
  83561. * \assert
  83562. * \code decoder != NULL \endcode
  83563. * \code position != NULL \endcode
  83564. * \retval FLAC__bool
  83565. * \c true if successful, \c false if the stream is not native FLAC,
  83566. * or there was an error from the 'tell' callback or it returned
  83567. * \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED.
  83568. */
  83569. FLAC_API FLAC__bool FLAC__stream_decoder_get_decode_position(const FLAC__StreamDecoder *decoder, FLAC__uint64 *position);
  83570. /** Initialize the decoder instance to decode native FLAC streams.
  83571. *
  83572. * This flavor of initialization sets up the decoder to decode from a
  83573. * native FLAC stream. I/O is performed via callbacks to the client.
  83574. * For decoding from a plain file via filename or open FILE*,
  83575. * FLAC__stream_decoder_init_file() and FLAC__stream_decoder_init_FILE()
  83576. * provide a simpler interface.
  83577. *
  83578. * This function should be called after FLAC__stream_decoder_new() and
  83579. * FLAC__stream_decoder_set_*() but before any of the
  83580. * FLAC__stream_decoder_process_*() functions. Will set and return the
  83581. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  83582. * if initialization succeeded.
  83583. *
  83584. * \param decoder An uninitialized decoder instance.
  83585. * \param read_callback See FLAC__StreamDecoderReadCallback. This
  83586. * pointer must not be \c NULL.
  83587. * \param seek_callback See FLAC__StreamDecoderSeekCallback. This
  83588. * pointer may be \c NULL if seeking is not
  83589. * supported. If \a seek_callback is not \c NULL then a
  83590. * \a tell_callback, \a length_callback, and \a eof_callback must also be supplied.
  83591. * Alternatively, a dummy seek callback that just
  83592. * returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  83593. * may also be supplied, all though this is slightly
  83594. * less efficient for the decoder.
  83595. * \param tell_callback See FLAC__StreamDecoderTellCallback. This
  83596. * pointer may be \c NULL if not supported by the client. If
  83597. * \a seek_callback is not \c NULL then a
  83598. * \a tell_callback must also be supplied.
  83599. * Alternatively, a dummy tell callback that just
  83600. * returns \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  83601. * may also be supplied, all though this is slightly
  83602. * less efficient for the decoder.
  83603. * \param length_callback See FLAC__StreamDecoderLengthCallback. This
  83604. * pointer may be \c NULL if not supported by the client. If
  83605. * \a seek_callback is not \c NULL then a
  83606. * \a length_callback must also be supplied.
  83607. * Alternatively, a dummy length callback that just
  83608. * returns \c FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  83609. * may also be supplied, all though this is slightly
  83610. * less efficient for the decoder.
  83611. * \param eof_callback See FLAC__StreamDecoderEofCallback. This
  83612. * pointer may be \c NULL if not supported by the client. If
  83613. * \a seek_callback is not \c NULL then a
  83614. * \a eof_callback must also be supplied.
  83615. * Alternatively, a dummy length callback that just
  83616. * returns \c false
  83617. * may also be supplied, all though this is slightly
  83618. * less efficient for the decoder.
  83619. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  83620. * pointer must not be \c NULL.
  83621. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  83622. * pointer may be \c NULL if the callback is not
  83623. * desired.
  83624. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  83625. * pointer must not be \c NULL.
  83626. * \param client_data This value will be supplied to callbacks in their
  83627. * \a client_data argument.
  83628. * \assert
  83629. * \code decoder != NULL \endcode
  83630. * \retval FLAC__StreamDecoderInitStatus
  83631. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  83632. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  83633. */
  83634. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_stream(
  83635. FLAC__StreamDecoder *decoder,
  83636. FLAC__StreamDecoderReadCallback read_callback,
  83637. FLAC__StreamDecoderSeekCallback seek_callback,
  83638. FLAC__StreamDecoderTellCallback tell_callback,
  83639. FLAC__StreamDecoderLengthCallback length_callback,
  83640. FLAC__StreamDecoderEofCallback eof_callback,
  83641. FLAC__StreamDecoderWriteCallback write_callback,
  83642. FLAC__StreamDecoderMetadataCallback metadata_callback,
  83643. FLAC__StreamDecoderErrorCallback error_callback,
  83644. void *client_data
  83645. );
  83646. /** Initialize the decoder instance to decode Ogg FLAC streams.
  83647. *
  83648. * This flavor of initialization sets up the decoder to decode from a
  83649. * FLAC stream in an Ogg container. I/O is performed via callbacks to the
  83650. * client. For decoding from a plain file via filename or open FILE*,
  83651. * FLAC__stream_decoder_init_ogg_file() and FLAC__stream_decoder_init_ogg_FILE()
  83652. * provide a simpler interface.
  83653. *
  83654. * This function should be called after FLAC__stream_decoder_new() and
  83655. * FLAC__stream_decoder_set_*() but before any of the
  83656. * FLAC__stream_decoder_process_*() functions. Will set and return the
  83657. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  83658. * if initialization succeeded.
  83659. *
  83660. * \note Support for Ogg FLAC in the library is optional. If this
  83661. * library has been built without support for Ogg FLAC, this function
  83662. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  83663. *
  83664. * \param decoder An uninitialized decoder instance.
  83665. * \param read_callback See FLAC__StreamDecoderReadCallback. This
  83666. * pointer must not be \c NULL.
  83667. * \param seek_callback See FLAC__StreamDecoderSeekCallback. This
  83668. * pointer may be \c NULL if seeking is not
  83669. * supported. If \a seek_callback is not \c NULL then a
  83670. * \a tell_callback, \a length_callback, and \a eof_callback must also be supplied.
  83671. * Alternatively, a dummy seek callback that just
  83672. * returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  83673. * may also be supplied, all though this is slightly
  83674. * less efficient for the decoder.
  83675. * \param tell_callback See FLAC__StreamDecoderTellCallback. This
  83676. * pointer may be \c NULL if not supported by the client. If
  83677. * \a seek_callback is not \c NULL then a
  83678. * \a tell_callback must also be supplied.
  83679. * Alternatively, a dummy tell callback that just
  83680. * returns \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  83681. * may also be supplied, all though this is slightly
  83682. * less efficient for the decoder.
  83683. * \param length_callback See FLAC__StreamDecoderLengthCallback. This
  83684. * pointer may be \c NULL if not supported by the client. If
  83685. * \a seek_callback is not \c NULL then a
  83686. * \a length_callback must also be supplied.
  83687. * Alternatively, a dummy length callback that just
  83688. * returns \c FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  83689. * may also be supplied, all though this is slightly
  83690. * less efficient for the decoder.
  83691. * \param eof_callback See FLAC__StreamDecoderEofCallback. This
  83692. * pointer may be \c NULL if not supported by the client. If
  83693. * \a seek_callback is not \c NULL then a
  83694. * \a eof_callback must also be supplied.
  83695. * Alternatively, a dummy length callback that just
  83696. * returns \c false
  83697. * may also be supplied, all though this is slightly
  83698. * less efficient for the decoder.
  83699. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  83700. * pointer must not be \c NULL.
  83701. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  83702. * pointer may be \c NULL if the callback is not
  83703. * desired.
  83704. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  83705. * pointer must not be \c NULL.
  83706. * \param client_data This value will be supplied to callbacks in their
  83707. * \a client_data argument.
  83708. * \assert
  83709. * \code decoder != NULL \endcode
  83710. * \retval FLAC__StreamDecoderInitStatus
  83711. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  83712. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  83713. */
  83714. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_stream(
  83715. FLAC__StreamDecoder *decoder,
  83716. FLAC__StreamDecoderReadCallback read_callback,
  83717. FLAC__StreamDecoderSeekCallback seek_callback,
  83718. FLAC__StreamDecoderTellCallback tell_callback,
  83719. FLAC__StreamDecoderLengthCallback length_callback,
  83720. FLAC__StreamDecoderEofCallback eof_callback,
  83721. FLAC__StreamDecoderWriteCallback write_callback,
  83722. FLAC__StreamDecoderMetadataCallback metadata_callback,
  83723. FLAC__StreamDecoderErrorCallback error_callback,
  83724. void *client_data
  83725. );
  83726. /** Initialize the decoder instance to decode native FLAC files.
  83727. *
  83728. * This flavor of initialization sets up the decoder to decode from a
  83729. * plain native FLAC file. For non-stdio streams, you must use
  83730. * FLAC__stream_decoder_init_stream() and provide callbacks for the I/O.
  83731. *
  83732. * This function should be called after FLAC__stream_decoder_new() and
  83733. * FLAC__stream_decoder_set_*() but before any of the
  83734. * FLAC__stream_decoder_process_*() functions. Will set and return the
  83735. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  83736. * if initialization succeeded.
  83737. *
  83738. * \param decoder An uninitialized decoder instance.
  83739. * \param file An open FLAC file. The file should have been
  83740. * opened with mode \c "rb" and rewound. The file
  83741. * becomes owned by the decoder and should not be
  83742. * manipulated by the client while decoding.
  83743. * Unless \a file is \c stdin, it will be closed
  83744. * when FLAC__stream_decoder_finish() is called.
  83745. * Note however that seeking will not work when
  83746. * decoding from \c stdout since it is not seekable.
  83747. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  83748. * pointer must not be \c NULL.
  83749. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  83750. * pointer may be \c NULL if the callback is not
  83751. * desired.
  83752. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  83753. * pointer must not be \c NULL.
  83754. * \param client_data This value will be supplied to callbacks in their
  83755. * \a client_data argument.
  83756. * \assert
  83757. * \code decoder != NULL \endcode
  83758. * \code file != NULL \endcode
  83759. * \retval FLAC__StreamDecoderInitStatus
  83760. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  83761. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  83762. */
  83763. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_FILE(
  83764. FLAC__StreamDecoder *decoder,
  83765. FILE *file,
  83766. FLAC__StreamDecoderWriteCallback write_callback,
  83767. FLAC__StreamDecoderMetadataCallback metadata_callback,
  83768. FLAC__StreamDecoderErrorCallback error_callback,
  83769. void *client_data
  83770. );
  83771. /** Initialize the decoder instance to decode Ogg FLAC files.
  83772. *
  83773. * This flavor of initialization sets up the decoder to decode from a
  83774. * plain Ogg FLAC file. For non-stdio streams, you must use
  83775. * FLAC__stream_decoder_init_ogg_stream() and provide callbacks for the I/O.
  83776. *
  83777. * This function should be called after FLAC__stream_decoder_new() and
  83778. * FLAC__stream_decoder_set_*() but before any of the
  83779. * FLAC__stream_decoder_process_*() functions. Will set and return the
  83780. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  83781. * if initialization succeeded.
  83782. *
  83783. * \note Support for Ogg FLAC in the library is optional. If this
  83784. * library has been built without support for Ogg FLAC, this function
  83785. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  83786. *
  83787. * \param decoder An uninitialized decoder instance.
  83788. * \param file An open FLAC file. The file should have been
  83789. * opened with mode \c "rb" and rewound. The file
  83790. * becomes owned by the decoder and should not be
  83791. * manipulated by the client while decoding.
  83792. * Unless \a file is \c stdin, it will be closed
  83793. * when FLAC__stream_decoder_finish() is called.
  83794. * Note however that seeking will not work when
  83795. * decoding from \c stdout since it is not seekable.
  83796. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  83797. * pointer must not be \c NULL.
  83798. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  83799. * pointer may be \c NULL if the callback is not
  83800. * desired.
  83801. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  83802. * pointer must not be \c NULL.
  83803. * \param client_data This value will be supplied to callbacks in their
  83804. * \a client_data argument.
  83805. * \assert
  83806. * \code decoder != NULL \endcode
  83807. * \code file != NULL \endcode
  83808. * \retval FLAC__StreamDecoderInitStatus
  83809. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  83810. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  83811. */
  83812. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_FILE(
  83813. FLAC__StreamDecoder *decoder,
  83814. FILE *file,
  83815. FLAC__StreamDecoderWriteCallback write_callback,
  83816. FLAC__StreamDecoderMetadataCallback metadata_callback,
  83817. FLAC__StreamDecoderErrorCallback error_callback,
  83818. void *client_data
  83819. );
  83820. /** Initialize the decoder instance to decode native FLAC files.
  83821. *
  83822. * This flavor of initialization sets up the decoder to decode from a plain
  83823. * native FLAC file. If POSIX fopen() semantics are not sufficient, (for
  83824. * example, with Unicode filenames on Windows), you must use
  83825. * FLAC__stream_decoder_init_FILE(), or FLAC__stream_decoder_init_stream()
  83826. * and provide callbacks for the I/O.
  83827. *
  83828. * This function should be called after FLAC__stream_decoder_new() and
  83829. * FLAC__stream_decoder_set_*() but before any of the
  83830. * FLAC__stream_decoder_process_*() functions. Will set and return the
  83831. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  83832. * if initialization succeeded.
  83833. *
  83834. * \param decoder An uninitialized decoder instance.
  83835. * \param filename The name of the file to decode from. The file will
  83836. * be opened with fopen(). Use \c NULL to decode from
  83837. * \c stdin. Note that \c stdin is not seekable.
  83838. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  83839. * pointer must not be \c NULL.
  83840. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  83841. * pointer may be \c NULL if the callback is not
  83842. * desired.
  83843. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  83844. * pointer must not be \c NULL.
  83845. * \param client_data This value will be supplied to callbacks in their
  83846. * \a client_data argument.
  83847. * \assert
  83848. * \code decoder != NULL \endcode
  83849. * \retval FLAC__StreamDecoderInitStatus
  83850. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  83851. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  83852. */
  83853. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_file(
  83854. FLAC__StreamDecoder *decoder,
  83855. const char *filename,
  83856. FLAC__StreamDecoderWriteCallback write_callback,
  83857. FLAC__StreamDecoderMetadataCallback metadata_callback,
  83858. FLAC__StreamDecoderErrorCallback error_callback,
  83859. void *client_data
  83860. );
  83861. /** Initialize the decoder instance to decode Ogg FLAC files.
  83862. *
  83863. * This flavor of initialization sets up the decoder to decode from a plain
  83864. * Ogg FLAC file. If POSIX fopen() semantics are not sufficient, (for
  83865. * example, with Unicode filenames on Windows), you must use
  83866. * FLAC__stream_decoder_init_ogg_FILE(), or FLAC__stream_decoder_init_ogg_stream()
  83867. * and provide callbacks for the I/O.
  83868. *
  83869. * This function should be called after FLAC__stream_decoder_new() and
  83870. * FLAC__stream_decoder_set_*() but before any of the
  83871. * FLAC__stream_decoder_process_*() functions. Will set and return the
  83872. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  83873. * if initialization succeeded.
  83874. *
  83875. * \note Support for Ogg FLAC in the library is optional. If this
  83876. * library has been built without support for Ogg FLAC, this function
  83877. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  83878. *
  83879. * \param decoder An uninitialized decoder instance.
  83880. * \param filename The name of the file to decode from. The file will
  83881. * be opened with fopen(). Use \c NULL to decode from
  83882. * \c stdin. Note that \c stdin is not seekable.
  83883. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  83884. * pointer must not be \c NULL.
  83885. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  83886. * pointer may be \c NULL if the callback is not
  83887. * desired.
  83888. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  83889. * pointer must not be \c NULL.
  83890. * \param client_data This value will be supplied to callbacks in their
  83891. * \a client_data argument.
  83892. * \assert
  83893. * \code decoder != NULL \endcode
  83894. * \retval FLAC__StreamDecoderInitStatus
  83895. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  83896. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  83897. */
  83898. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_file(
  83899. FLAC__StreamDecoder *decoder,
  83900. const char *filename,
  83901. FLAC__StreamDecoderWriteCallback write_callback,
  83902. FLAC__StreamDecoderMetadataCallback metadata_callback,
  83903. FLAC__StreamDecoderErrorCallback error_callback,
  83904. void *client_data
  83905. );
  83906. /** Finish the decoding process.
  83907. * Flushes the decoding buffer, releases resources, resets the decoder
  83908. * settings to their defaults, and returns the decoder state to
  83909. * FLAC__STREAM_DECODER_UNINITIALIZED.
  83910. *
  83911. * In the event of a prematurely-terminated decode, it is not strictly
  83912. * necessary to call this immediately before FLAC__stream_decoder_delete()
  83913. * but it is good practice to match every FLAC__stream_decoder_init_*()
  83914. * with a FLAC__stream_decoder_finish().
  83915. *
  83916. * \param decoder An uninitialized decoder instance.
  83917. * \assert
  83918. * \code decoder != NULL \endcode
  83919. * \retval FLAC__bool
  83920. * \c false if MD5 checking is on AND a STREAMINFO block was available
  83921. * AND the MD5 signature in the STREAMINFO block was non-zero AND the
  83922. * signature does not match the one computed by the decoder; else
  83923. * \c true.
  83924. */
  83925. FLAC_API FLAC__bool FLAC__stream_decoder_finish(FLAC__StreamDecoder *decoder);
  83926. /** Flush the stream input.
  83927. * The decoder's input buffer will be cleared and the state set to
  83928. * \c FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC. This will also turn
  83929. * off MD5 checking.
  83930. *
  83931. * \param decoder A decoder instance.
  83932. * \assert
  83933. * \code decoder != NULL \endcode
  83934. * \retval FLAC__bool
  83935. * \c true if successful, else \c false if a memory allocation
  83936. * error occurs (in which case the state will be set to
  83937. * \c FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR).
  83938. */
  83939. FLAC_API FLAC__bool FLAC__stream_decoder_flush(FLAC__StreamDecoder *decoder);
  83940. /** Reset the decoding process.
  83941. * The decoder's input buffer will be cleared and the state set to
  83942. * \c FLAC__STREAM_DECODER_SEARCH_FOR_METADATA. This is similar to
  83943. * FLAC__stream_decoder_finish() except that the settings are
  83944. * preserved; there is no need to call FLAC__stream_decoder_init_*()
  83945. * before decoding again. MD5 checking will be restored to its original
  83946. * setting.
  83947. *
  83948. * If the decoder is seekable, or was initialized with
  83949. * FLAC__stream_decoder_init*_FILE() or FLAC__stream_decoder_init*_file(),
  83950. * the decoder will also attempt to seek to the beginning of the file.
  83951. * If this rewind fails, this function will return \c false. It follows
  83952. * that FLAC__stream_decoder_reset() cannot be used when decoding from
  83953. * \c stdin.
  83954. *
  83955. * If the decoder was initialized with FLAC__stream_encoder_init*_stream()
  83956. * and is not seekable (i.e. no seek callback was provided or the seek
  83957. * callback returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED), it
  83958. * is the duty of the client to start feeding data from the beginning of
  83959. * the stream on the next FLAC__stream_decoder_process() or
  83960. * FLAC__stream_decoder_process_interleaved() call.
  83961. *
  83962. * \param decoder A decoder instance.
  83963. * \assert
  83964. * \code decoder != NULL \endcode
  83965. * \retval FLAC__bool
  83966. * \c true if successful, else \c false if a memory allocation occurs
  83967. * (in which case the state will be set to
  83968. * \c FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR) or a seek error
  83969. * occurs (the state will be unchanged).
  83970. */
  83971. FLAC_API FLAC__bool FLAC__stream_decoder_reset(FLAC__StreamDecoder *decoder);
  83972. /** Decode one metadata block or audio frame.
  83973. * This version instructs the decoder to decode a either a single metadata
  83974. * block or a single frame and stop, unless the callbacks return a fatal
  83975. * error or the read callback returns
  83976. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  83977. *
  83978. * As the decoder needs more input it will call the read callback.
  83979. * Depending on what was decoded, the metadata or write callback will be
  83980. * called with the decoded metadata block or audio frame.
  83981. *
  83982. * Unless there is a fatal read error or end of stream, this function
  83983. * will return once one whole frame is decoded. In other words, if the
  83984. * stream is not synchronized or points to a corrupt frame header, the
  83985. * decoder will continue to try and resync until it gets to a valid
  83986. * frame, then decode one frame, then return. If the decoder points to
  83987. * a frame whose frame CRC in the frame footer does not match the
  83988. * computed frame CRC, this function will issue a
  83989. * FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH error to the
  83990. * error callback, and return, having decoded one complete, although
  83991. * corrupt, frame. (Such corrupted frames are sent as silence of the
  83992. * correct length to the write callback.)
  83993. *
  83994. * \param decoder An initialized decoder instance.
  83995. * \assert
  83996. * \code decoder != NULL \endcode
  83997. * \retval FLAC__bool
  83998. * \c false if any fatal read, write, or memory allocation error
  83999. * occurred (meaning decoding must stop), else \c true; for more
  84000. * information about the decoder, check the decoder state with
  84001. * FLAC__stream_decoder_get_state().
  84002. */
  84003. FLAC_API FLAC__bool FLAC__stream_decoder_process_single(FLAC__StreamDecoder *decoder);
  84004. /** Decode until the end of the metadata.
  84005. * This version instructs the decoder to decode from the current position
  84006. * and continue until all the metadata has been read, or until the
  84007. * callbacks return a fatal error or the read callback returns
  84008. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  84009. *
  84010. * As the decoder needs more input it will call the read callback.
  84011. * As each metadata block is decoded, the metadata callback will be called
  84012. * with the decoded metadata.
  84013. *
  84014. * \param decoder An initialized decoder instance.
  84015. * \assert
  84016. * \code decoder != NULL \endcode
  84017. * \retval FLAC__bool
  84018. * \c false if any fatal read, write, or memory allocation error
  84019. * occurred (meaning decoding must stop), else \c true; for more
  84020. * information about the decoder, check the decoder state with
  84021. * FLAC__stream_decoder_get_state().
  84022. */
  84023. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_metadata(FLAC__StreamDecoder *decoder);
  84024. /** Decode until the end of the stream.
  84025. * This version instructs the decoder to decode from the current position
  84026. * and continue until the end of stream (the read callback returns
  84027. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM), or until the
  84028. * callbacks return a fatal error.
  84029. *
  84030. * As the decoder needs more input it will call the read callback.
  84031. * As each metadata block and frame is decoded, the metadata or write
  84032. * callback will be called with the decoded metadata or frame.
  84033. *
  84034. * \param decoder An initialized decoder instance.
  84035. * \assert
  84036. * \code decoder != NULL \endcode
  84037. * \retval FLAC__bool
  84038. * \c false if any fatal read, write, or memory allocation error
  84039. * occurred (meaning decoding must stop), else \c true; for more
  84040. * information about the decoder, check the decoder state with
  84041. * FLAC__stream_decoder_get_state().
  84042. */
  84043. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_stream(FLAC__StreamDecoder *decoder);
  84044. /** Skip one audio frame.
  84045. * This version instructs the decoder to 'skip' a single frame and stop,
  84046. * unless the callbacks return a fatal error or the read callback returns
  84047. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  84048. *
  84049. * The decoding flow is the same as what occurs when
  84050. * FLAC__stream_decoder_process_single() is called to process an audio
  84051. * frame, except that this function does not decode the parsed data into
  84052. * PCM or call the write callback. The integrity of the frame is still
  84053. * checked the same way as in the other process functions.
  84054. *
  84055. * This function will return once one whole frame is skipped, in the
  84056. * same way that FLAC__stream_decoder_process_single() will return once
  84057. * one whole frame is decoded.
  84058. *
  84059. * This function can be used in more quickly determining FLAC frame
  84060. * boundaries when decoding of the actual data is not needed, for
  84061. * example when an application is separating a FLAC stream into frames
  84062. * for editing or storing in a container. To do this, the application
  84063. * can use FLAC__stream_decoder_skip_single_frame() to quickly advance
  84064. * to the next frame, then use
  84065. * FLAC__stream_decoder_get_decode_position() to find the new frame
  84066. * boundary.
  84067. *
  84068. * This function should only be called when the stream has advanced
  84069. * past all the metadata, otherwise it will return \c false.
  84070. *
  84071. * \param decoder An initialized decoder instance not in a metadata
  84072. * state.
  84073. * \assert
  84074. * \code decoder != NULL \endcode
  84075. * \retval FLAC__bool
  84076. * \c false if any fatal read, write, or memory allocation error
  84077. * occurred (meaning decoding must stop), or if the decoder
  84078. * is in the FLAC__STREAM_DECODER_SEARCH_FOR_METADATA or
  84079. * FLAC__STREAM_DECODER_READ_METADATA state, else \c true; for more
  84080. * information about the decoder, check the decoder state with
  84081. * FLAC__stream_decoder_get_state().
  84082. */
  84083. FLAC_API FLAC__bool FLAC__stream_decoder_skip_single_frame(FLAC__StreamDecoder *decoder);
  84084. /** Flush the input and seek to an absolute sample.
  84085. * Decoding will resume at the given sample. Note that because of
  84086. * this, the next write callback may contain a partial block. The
  84087. * client must support seeking the input or this function will fail
  84088. * and return \c false. Furthermore, if the decoder state is
  84089. * \c FLAC__STREAM_DECODER_SEEK_ERROR, then the decoder must be flushed
  84090. * with FLAC__stream_decoder_flush() or reset with
  84091. * FLAC__stream_decoder_reset() before decoding can continue.
  84092. *
  84093. * \param decoder A decoder instance.
  84094. * \param sample The target sample number to seek to.
  84095. * \assert
  84096. * \code decoder != NULL \endcode
  84097. * \retval FLAC__bool
  84098. * \c true if successful, else \c false.
  84099. */
  84100. FLAC_API FLAC__bool FLAC__stream_decoder_seek_absolute(FLAC__StreamDecoder *decoder, FLAC__uint64 sample);
  84101. /* \} */
  84102. #ifdef __cplusplus
  84103. }
  84104. #endif
  84105. #endif
  84106. /********* End of inlined file: stream_decoder.h *********/
  84107. /********* Start of inlined file: stream_encoder.h *********/
  84108. #ifndef FLAC__STREAM_ENCODER_H
  84109. #define FLAC__STREAM_ENCODER_H
  84110. #include <stdio.h> /* for FILE */
  84111. #ifdef __cplusplus
  84112. extern "C" {
  84113. #endif
  84114. /** \file include/FLAC/stream_encoder.h
  84115. *
  84116. * \brief
  84117. * This module contains the functions which implement the stream
  84118. * encoder.
  84119. *
  84120. * See the detailed documentation in the
  84121. * \link flac_stream_encoder stream encoder \endlink module.
  84122. */
  84123. /** \defgroup flac_encoder FLAC/ \*_encoder.h: encoder interfaces
  84124. * \ingroup flac
  84125. *
  84126. * \brief
  84127. * This module describes the encoder layers provided by libFLAC.
  84128. *
  84129. * The stream encoder can be used to encode complete streams either to the
  84130. * client via callbacks, or directly to a file, depending on how it is
  84131. * initialized. When encoding via callbacks, the client provides a write
  84132. * callback which will be called whenever FLAC data is ready to be written.
  84133. * If the client also supplies a seek callback, the encoder will also
  84134. * automatically handle the writing back of metadata discovered while
  84135. * encoding, like stream info, seek points offsets, etc. When encoding to
  84136. * a file, the client needs only supply a filename or open \c FILE* and an
  84137. * optional progress callback for periodic notification of progress; the
  84138. * write and seek callbacks are supplied internally. For more info see the
  84139. * \link flac_stream_encoder stream encoder \endlink module.
  84140. */
  84141. /** \defgroup flac_stream_encoder FLAC/stream_encoder.h: stream encoder interface
  84142. * \ingroup flac_encoder
  84143. *
  84144. * \brief
  84145. * This module contains the functions which implement the stream
  84146. * encoder.
  84147. *
  84148. * The stream encoder can encode to native FLAC, and optionally Ogg FLAC
  84149. * (check FLAC_API_SUPPORTS_OGG_FLAC) streams and files.
  84150. *
  84151. * The basic usage of this encoder is as follows:
  84152. * - The program creates an instance of an encoder using
  84153. * FLAC__stream_encoder_new().
  84154. * - The program overrides the default settings using
  84155. * FLAC__stream_encoder_set_*() functions. At a minimum, the following
  84156. * functions should be called:
  84157. * - FLAC__stream_encoder_set_channels()
  84158. * - FLAC__stream_encoder_set_bits_per_sample()
  84159. * - FLAC__stream_encoder_set_sample_rate()
  84160. * - FLAC__stream_encoder_set_ogg_serial_number() (if encoding to Ogg FLAC)
  84161. * - FLAC__stream_encoder_set_total_samples_estimate() (if known)
  84162. * - If the application wants to control the compression level or set its own
  84163. * metadata, then the following should also be called:
  84164. * - FLAC__stream_encoder_set_compression_level()
  84165. * - FLAC__stream_encoder_set_verify()
  84166. * - FLAC__stream_encoder_set_metadata()
  84167. * - The rest of the set functions should only be called if the client needs
  84168. * exact control over how the audio is compressed; thorough understanding
  84169. * of the FLAC format is necessary to achieve good results.
  84170. * - The program initializes the instance to validate the settings and
  84171. * prepare for encoding using
  84172. * - FLAC__stream_encoder_init_stream() or FLAC__stream_encoder_init_FILE()
  84173. * or FLAC__stream_encoder_init_file() for native FLAC
  84174. * - FLAC__stream_encoder_init_ogg_stream() or FLAC__stream_encoder_init_ogg_FILE()
  84175. * or FLAC__stream_encoder_init_ogg_file() for Ogg FLAC
  84176. * - The program calls FLAC__stream_encoder_process() or
  84177. * FLAC__stream_encoder_process_interleaved() to encode data, which
  84178. * subsequently calls the callbacks when there is encoder data ready
  84179. * to be written.
  84180. * - The program finishes the encoding with FLAC__stream_encoder_finish(),
  84181. * which causes the encoder to encode any data still in its input pipe,
  84182. * update the metadata with the final encoding statistics if output
  84183. * seeking is possible, and finally reset the encoder to the
  84184. * uninitialized state.
  84185. * - The instance may be used again or deleted with
  84186. * FLAC__stream_encoder_delete().
  84187. *
  84188. * In more detail, the stream encoder functions similarly to the
  84189. * \link flac_stream_decoder stream decoder \endlink, but has fewer
  84190. * callbacks and more options. Typically the client will create a new
  84191. * instance by calling FLAC__stream_encoder_new(), then set the necessary
  84192. * parameters with FLAC__stream_encoder_set_*(), and initialize it by
  84193. * calling one of the FLAC__stream_encoder_init_*() functions.
  84194. *
  84195. * Unlike the decoders, the stream encoder has many options that can
  84196. * affect the speed and compression ratio. When setting these parameters
  84197. * you should have some basic knowledge of the format (see the
  84198. * <A HREF="../documentation.html#format">user-level documentation</A>
  84199. * or the <A HREF="../format.html">formal description</A>). The
  84200. * FLAC__stream_encoder_set_*() functions themselves do not validate the
  84201. * values as many are interdependent. The FLAC__stream_encoder_init_*()
  84202. * functions will do this, so make sure to pay attention to the state
  84203. * returned by FLAC__stream_encoder_init_*() to make sure that it is
  84204. * FLAC__STREAM_ENCODER_INIT_STATUS_OK. Any parameters that are not set
  84205. * before FLAC__stream_encoder_init_*() will take on the defaults from
  84206. * the constructor.
  84207. *
  84208. * There are three initialization functions for native FLAC, one for
  84209. * setting up the encoder to encode FLAC data to the client via
  84210. * callbacks, and two for encoding directly to a file.
  84211. *
  84212. * For encoding via callbacks, use FLAC__stream_encoder_init_stream().
  84213. * You must also supply a write callback which will be called anytime
  84214. * there is raw encoded data to write. If the client can seek the output
  84215. * it is best to also supply seek and tell callbacks, as this allows the
  84216. * encoder to go back after encoding is finished to write back
  84217. * information that was collected while encoding, like seek point offsets,
  84218. * frame sizes, etc.
  84219. *
  84220. * For encoding directly to a file, use FLAC__stream_encoder_init_FILE()
  84221. * or FLAC__stream_encoder_init_file(). Then you must only supply a
  84222. * filename or open \c FILE*; the encoder will handle all the callbacks
  84223. * internally. You may also supply a progress callback for periodic
  84224. * notification of the encoding progress.
  84225. *
  84226. * There are three similarly-named init functions for encoding to Ogg
  84227. * FLAC streams. Check \c FLAC_API_SUPPORTS_OGG_FLAC to find out if the
  84228. * library has been built with Ogg support.
  84229. *
  84230. * The call to FLAC__stream_encoder_init_*() currently will also immediately
  84231. * call the write callback several times, once with the \c fLaC signature,
  84232. * and once for each encoded metadata block. Note that for Ogg FLAC
  84233. * encoding you will usually get at least twice the number of callbacks than
  84234. * with native FLAC, one for the Ogg page header and one for the page body.
  84235. *
  84236. * After initializing the instance, the client may feed audio data to the
  84237. * encoder in one of two ways:
  84238. *
  84239. * - Channel separate, through FLAC__stream_encoder_process() - The client
  84240. * will pass an array of pointers to buffers, one for each channel, to
  84241. * the encoder, each of the same length. The samples need not be
  84242. * block-aligned, but each channel should have the same number of samples.
  84243. * - Channel interleaved, through
  84244. * FLAC__stream_encoder_process_interleaved() - The client will pass a single
  84245. * pointer to data that is channel-interleaved (i.e. channel0_sample0,
  84246. * channel1_sample0, ... , channelN_sample0, channel0_sample1, ...).
  84247. * Again, the samples need not be block-aligned but they must be
  84248. * sample-aligned, i.e. the first value should be channel0_sample0 and
  84249. * the last value channelN_sampleM.
  84250. *
  84251. * Note that for either process call, each sample in the buffers should be a
  84252. * signed integer, right-justified to the resolution set by
  84253. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the resolution
  84254. * is 16 bits per sample, the samples should all be in the range [-32768,32767].
  84255. *
  84256. * When the client is finished encoding data, it calls
  84257. * FLAC__stream_encoder_finish(), which causes the encoder to encode any
  84258. * data still in its input pipe, and call the metadata callback with the
  84259. * final encoding statistics. Then the instance may be deleted with
  84260. * FLAC__stream_encoder_delete() or initialized again to encode another
  84261. * stream.
  84262. *
  84263. * For programs that write their own metadata, but that do not know the
  84264. * actual metadata until after encoding, it is advantageous to instruct
  84265. * the encoder to write a PADDING block of the correct size, so that
  84266. * instead of rewriting the whole stream after encoding, the program can
  84267. * just overwrite the PADDING block. If only the maximum size of the
  84268. * metadata is known, the program can write a slightly larger padding
  84269. * block, then split it after encoding.
  84270. *
  84271. * Make sure you understand how lengths are calculated. All FLAC metadata
  84272. * blocks have a 4 byte header which contains the type and length. This
  84273. * length does not include the 4 bytes of the header. See the format page
  84274. * for the specification of metadata blocks and their lengths.
  84275. *
  84276. * \note
  84277. * If you are writing the FLAC data to a file via callbacks, make sure it
  84278. * is open for update (e.g. mode "w+" for stdio streams). This is because
  84279. * after the first encoding pass, the encoder will try to seek back to the
  84280. * beginning of the stream, to the STREAMINFO block, to write some data
  84281. * there. (If using FLAC__stream_encoder_init*_file() or
  84282. * FLAC__stream_encoder_init*_FILE(), the file is managed internally.)
  84283. *
  84284. * \note
  84285. * The "set" functions may only be called when the encoder is in the
  84286. * state FLAC__STREAM_ENCODER_UNINITIALIZED, i.e. after
  84287. * FLAC__stream_encoder_new() or FLAC__stream_encoder_finish(), but
  84288. * before FLAC__stream_encoder_init_*(). If this is the case they will
  84289. * return \c true, otherwise \c false.
  84290. *
  84291. * \note
  84292. * FLAC__stream_encoder_finish() resets all settings to the constructor
  84293. * defaults.
  84294. *
  84295. * \{
  84296. */
  84297. /** State values for a FLAC__StreamEncoder.
  84298. *
  84299. * The encoder's state can be obtained by calling FLAC__stream_encoder_get_state().
  84300. *
  84301. * If the encoder gets into any other state besides \c FLAC__STREAM_ENCODER_OK
  84302. * or \c FLAC__STREAM_ENCODER_UNINITIALIZED, it becomes invalid for encoding and
  84303. * must be deleted with FLAC__stream_encoder_delete().
  84304. */
  84305. typedef enum {
  84306. FLAC__STREAM_ENCODER_OK = 0,
  84307. /**< The encoder is in the normal OK state and samples can be processed. */
  84308. FLAC__STREAM_ENCODER_UNINITIALIZED,
  84309. /**< The encoder is in the uninitialized state; one of the
  84310. * FLAC__stream_encoder_init_*() functions must be called before samples
  84311. * can be processed.
  84312. */
  84313. FLAC__STREAM_ENCODER_OGG_ERROR,
  84314. /**< An error occurred in the underlying Ogg layer. */
  84315. FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR,
  84316. /**< An error occurred in the underlying verify stream decoder;
  84317. * check FLAC__stream_encoder_get_verify_decoder_state().
  84318. */
  84319. FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA,
  84320. /**< The verify decoder detected a mismatch between the original
  84321. * audio signal and the decoded audio signal.
  84322. */
  84323. FLAC__STREAM_ENCODER_CLIENT_ERROR,
  84324. /**< One of the callbacks returned a fatal error. */
  84325. FLAC__STREAM_ENCODER_IO_ERROR,
  84326. /**< An I/O error occurred while opening/reading/writing a file.
  84327. * Check \c errno.
  84328. */
  84329. FLAC__STREAM_ENCODER_FRAMING_ERROR,
  84330. /**< An error occurred while writing the stream; usually, the
  84331. * write_callback returned an error.
  84332. */
  84333. FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR
  84334. /**< Memory allocation failed. */
  84335. } FLAC__StreamEncoderState;
  84336. /** Maps a FLAC__StreamEncoderState to a C string.
  84337. *
  84338. * Using a FLAC__StreamEncoderState as the index to this array
  84339. * will give the string equivalent. The contents should not be modified.
  84340. */
  84341. extern FLAC_API const char * const FLAC__StreamEncoderStateString[];
  84342. /** Possible return values for the FLAC__stream_encoder_init_*() functions.
  84343. */
  84344. typedef enum {
  84345. FLAC__STREAM_ENCODER_INIT_STATUS_OK = 0,
  84346. /**< Initialization was successful. */
  84347. FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR,
  84348. /**< General failure to set up encoder; call FLAC__stream_encoder_get_state() for cause. */
  84349. FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER,
  84350. /**< The library was not compiled with support for the given container
  84351. * format.
  84352. */
  84353. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS,
  84354. /**< A required callback was not supplied. */
  84355. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS,
  84356. /**< The encoder has an invalid setting for number of channels. */
  84357. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE,
  84358. /**< The encoder has an invalid setting for bits-per-sample.
  84359. * FLAC supports 4-32 bps but the reference encoder currently supports
  84360. * only up to 24 bps.
  84361. */
  84362. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE,
  84363. /**< The encoder has an invalid setting for the input sample rate. */
  84364. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE,
  84365. /**< The encoder has an invalid setting for the block size. */
  84366. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER,
  84367. /**< The encoder has an invalid setting for the maximum LPC order. */
  84368. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION,
  84369. /**< The encoder has an invalid setting for the precision of the quantized linear predictor coefficients. */
  84370. FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER,
  84371. /**< The specified block size is less than the maximum LPC order. */
  84372. FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE,
  84373. /**< The encoder is bound to the <A HREF="../format.html#subset">Subset</A> but other settings violate it. */
  84374. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA,
  84375. /**< The metadata input to the encoder is invalid, in one of the following ways:
  84376. * - FLAC__stream_encoder_set_metadata() was called with a null pointer but a block count > 0
  84377. * - One of the metadata blocks contains an undefined type
  84378. * - It contains an illegal CUESHEET as checked by FLAC__format_cuesheet_is_legal()
  84379. * - It contains an illegal SEEKTABLE as checked by FLAC__format_seektable_is_legal()
  84380. * - It contains more than one SEEKTABLE block or more than one VORBIS_COMMENT block
  84381. */
  84382. FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED
  84383. /**< FLAC__stream_encoder_init_*() was called when the encoder was
  84384. * already initialized, usually because
  84385. * FLAC__stream_encoder_finish() was not called.
  84386. */
  84387. } FLAC__StreamEncoderInitStatus;
  84388. /** Maps a FLAC__StreamEncoderInitStatus to a C string.
  84389. *
  84390. * Using a FLAC__StreamEncoderInitStatus as the index to this array
  84391. * will give the string equivalent. The contents should not be modified.
  84392. */
  84393. extern FLAC_API const char * const FLAC__StreamEncoderInitStatusString[];
  84394. /** Return values for the FLAC__StreamEncoder read callback.
  84395. */
  84396. typedef enum {
  84397. FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE,
  84398. /**< The read was OK and decoding can continue. */
  84399. FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM,
  84400. /**< The read was attempted at the end of the stream. */
  84401. FLAC__STREAM_ENCODER_READ_STATUS_ABORT,
  84402. /**< An unrecoverable error occurred. */
  84403. FLAC__STREAM_ENCODER_READ_STATUS_UNSUPPORTED
  84404. /**< Client does not support reading back from the output. */
  84405. } FLAC__StreamEncoderReadStatus;
  84406. /** Maps a FLAC__StreamEncoderReadStatus to a C string.
  84407. *
  84408. * Using a FLAC__StreamEncoderReadStatus 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__StreamEncoderReadStatusString[];
  84412. /** Return values for the FLAC__StreamEncoder write callback.
  84413. */
  84414. typedef enum {
  84415. FLAC__STREAM_ENCODER_WRITE_STATUS_OK = 0,
  84416. /**< The write was OK and encoding can continue. */
  84417. FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR
  84418. /**< An unrecoverable error occurred. The encoder will return from the process call. */
  84419. } FLAC__StreamEncoderWriteStatus;
  84420. /** Maps a FLAC__StreamEncoderWriteStatus to a C string.
  84421. *
  84422. * Using a FLAC__StreamEncoderWriteStatus as the index to this array
  84423. * will give the string equivalent. The contents should not be modified.
  84424. */
  84425. extern FLAC_API const char * const FLAC__StreamEncoderWriteStatusString[];
  84426. /** Return values for the FLAC__StreamEncoder seek callback.
  84427. */
  84428. typedef enum {
  84429. FLAC__STREAM_ENCODER_SEEK_STATUS_OK,
  84430. /**< The seek was OK and encoding can continue. */
  84431. FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR,
  84432. /**< An unrecoverable error occurred. */
  84433. FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  84434. /**< Client does not support seeking. */
  84435. } FLAC__StreamEncoderSeekStatus;
  84436. /** Maps a FLAC__StreamEncoderSeekStatus to a C string.
  84437. *
  84438. * Using a FLAC__StreamEncoderSeekStatus as the index to this array
  84439. * will give the string equivalent. The contents should not be modified.
  84440. */
  84441. extern FLAC_API const char * const FLAC__StreamEncoderSeekStatusString[];
  84442. /** Return values for the FLAC__StreamEncoder tell callback.
  84443. */
  84444. typedef enum {
  84445. FLAC__STREAM_ENCODER_TELL_STATUS_OK,
  84446. /**< The tell was OK and encoding can continue. */
  84447. FLAC__STREAM_ENCODER_TELL_STATUS_ERROR,
  84448. /**< An unrecoverable error occurred. */
  84449. FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  84450. /**< Client does not support seeking. */
  84451. } FLAC__StreamEncoderTellStatus;
  84452. /** Maps a FLAC__StreamEncoderTellStatus to a C string.
  84453. *
  84454. * Using a FLAC__StreamEncoderTellStatus as the index to this array
  84455. * will give the string equivalent. The contents should not be modified.
  84456. */
  84457. extern FLAC_API const char * const FLAC__StreamEncoderTellStatusString[];
  84458. /***********************************************************************
  84459. *
  84460. * class FLAC__StreamEncoder
  84461. *
  84462. ***********************************************************************/
  84463. struct FLAC__StreamEncoderProtected;
  84464. struct FLAC__StreamEncoderPrivate;
  84465. /** The opaque structure definition for the stream encoder type.
  84466. * See the \link flac_stream_encoder stream encoder module \endlink
  84467. * for a detailed description.
  84468. */
  84469. typedef struct {
  84470. struct FLAC__StreamEncoderProtected *protected_; /* avoid the C++ keyword 'protected' */
  84471. struct FLAC__StreamEncoderPrivate *private_; /* avoid the C++ keyword 'private' */
  84472. } FLAC__StreamEncoder;
  84473. /** Signature for the read callback.
  84474. *
  84475. * A function pointer matching this signature must be passed to
  84476. * FLAC__stream_encoder_init_ogg_stream() if seeking is supported.
  84477. * The supplied function will be called when the encoder needs to read back
  84478. * encoded data. This happens during the metadata callback, when the encoder
  84479. * has to read, modify, and rewrite the metadata (e.g. seekpoints) gathered
  84480. * while encoding. The address of the buffer to be filled is supplied, along
  84481. * with the number of bytes the buffer can hold. The callback may choose to
  84482. * supply less data and modify the byte count but must be careful not to
  84483. * overflow the buffer. The callback then returns a status code chosen from
  84484. * FLAC__StreamEncoderReadStatus.
  84485. *
  84486. * Here is an example of a read callback for stdio streams:
  84487. * \code
  84488. * FLAC__StreamEncoderReadStatus read_cb(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  84489. * {
  84490. * FILE *file = ((MyClientData*)client_data)->file;
  84491. * if(*bytes > 0) {
  84492. * *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, file);
  84493. * if(ferror(file))
  84494. * return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  84495. * else if(*bytes == 0)
  84496. * return FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM;
  84497. * else
  84498. * return FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE;
  84499. * }
  84500. * else
  84501. * return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  84502. * }
  84503. * \endcode
  84504. *
  84505. * \note In general, FLAC__StreamEncoder functions which change the
  84506. * state should not be called on the \a encoder while in the callback.
  84507. *
  84508. * \param encoder The encoder instance calling the callback.
  84509. * \param buffer A pointer to a location for the callee to store
  84510. * data to be encoded.
  84511. * \param bytes A pointer to the size of the buffer. On entry
  84512. * to the callback, it contains the maximum number
  84513. * of bytes that may be stored in \a buffer. The
  84514. * callee must set it to the actual number of bytes
  84515. * stored (0 in case of error or end-of-stream) before
  84516. * returning.
  84517. * \param client_data The callee's client data set through
  84518. * FLAC__stream_encoder_set_client_data().
  84519. * \retval FLAC__StreamEncoderReadStatus
  84520. * The callee's return status.
  84521. */
  84522. typedef FLAC__StreamEncoderReadStatus (*FLAC__StreamEncoderReadCallback)(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  84523. /** Signature for the write callback.
  84524. *
  84525. * A function pointer matching this signature must be passed to
  84526. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  84527. * by the encoder anytime there is raw encoded data ready to write. It may
  84528. * include metadata mixed with encoded audio frames and the data is not
  84529. * guaranteed to be aligned on frame or metadata block boundaries.
  84530. *
  84531. * The only duty of the callback is to write out the \a bytes worth of data
  84532. * in \a buffer to the current position in the output stream. The arguments
  84533. * \a samples and \a current_frame are purely informational. If \a samples
  84534. * is greater than \c 0, then \a current_frame will hold the current frame
  84535. * number that is being written; otherwise it indicates that the write
  84536. * callback is being called to write metadata.
  84537. *
  84538. * \note
  84539. * Unlike when writing to native FLAC, when writing to Ogg FLAC the
  84540. * write callback will be called twice when writing each audio
  84541. * frame; once for the page header, and once for the page body.
  84542. * When writing the page header, the \a samples argument to the
  84543. * write callback will be \c 0.
  84544. *
  84545. * \note In general, FLAC__StreamEncoder functions which change the
  84546. * state should not be called on the \a encoder while in the callback.
  84547. *
  84548. * \param encoder The encoder instance calling the callback.
  84549. * \param buffer An array of encoded data of length \a bytes.
  84550. * \param bytes The byte length of \a buffer.
  84551. * \param samples The number of samples encoded by \a buffer.
  84552. * \c 0 has a special meaning; see above.
  84553. * \param current_frame The number of the current frame being encoded.
  84554. * \param client_data The callee's client data set through
  84555. * FLAC__stream_encoder_init_*().
  84556. * \retval FLAC__StreamEncoderWriteStatus
  84557. * The callee's return status.
  84558. */
  84559. typedef FLAC__StreamEncoderWriteStatus (*FLAC__StreamEncoderWriteCallback)(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data);
  84560. /** Signature for the seek callback.
  84561. *
  84562. * A function pointer matching this signature may be passed to
  84563. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  84564. * when the encoder needs to seek the output stream. The encoder will pass
  84565. * the absolute byte offset to seek to, 0 meaning the beginning of the stream.
  84566. *
  84567. * Here is an example of a seek callback for stdio streams:
  84568. * \code
  84569. * FLAC__StreamEncoderSeekStatus seek_cb(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  84570. * {
  84571. * FILE *file = ((MyClientData*)client_data)->file;
  84572. * if(file == stdin)
  84573. * return FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED;
  84574. * else if(fseeko(file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  84575. * return FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR;
  84576. * else
  84577. * return FLAC__STREAM_ENCODER_SEEK_STATUS_OK;
  84578. * }
  84579. * \endcode
  84580. *
  84581. * \note In general, FLAC__StreamEncoder functions which change the
  84582. * state should not be called on the \a encoder while in the callback.
  84583. *
  84584. * \param encoder The encoder instance calling the callback.
  84585. * \param absolute_byte_offset The offset from the beginning of the stream
  84586. * to seek to.
  84587. * \param client_data The callee's client data set through
  84588. * FLAC__stream_encoder_init_*().
  84589. * \retval FLAC__StreamEncoderSeekStatus
  84590. * The callee's return status.
  84591. */
  84592. typedef FLAC__StreamEncoderSeekStatus (*FLAC__StreamEncoderSeekCallback)(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  84593. /** Signature for the tell callback.
  84594. *
  84595. * A function pointer matching this signature may be passed to
  84596. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  84597. * when the encoder needs to know the current position of the output stream.
  84598. *
  84599. * \warning
  84600. * The callback must return the true current byte offset of the output to
  84601. * which the encoder is writing. If you are buffering the output, make
  84602. * sure and take this into account. If you are writing directly to a
  84603. * FILE* from your write callback, ftell() is sufficient. If you are
  84604. * writing directly to a file descriptor from your write callback, you
  84605. * can use lseek(fd, SEEK_CUR, 0). The encoder may later seek back to
  84606. * these points to rewrite metadata after encoding.
  84607. *
  84608. * Here is an example of a tell callback for stdio streams:
  84609. * \code
  84610. * FLAC__StreamEncoderTellStatus tell_cb(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  84611. * {
  84612. * FILE *file = ((MyClientData*)client_data)->file;
  84613. * off_t pos;
  84614. * if(file == stdin)
  84615. * return FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED;
  84616. * else if((pos = ftello(file)) < 0)
  84617. * return FLAC__STREAM_ENCODER_TELL_STATUS_ERROR;
  84618. * else {
  84619. * *absolute_byte_offset = (FLAC__uint64)pos;
  84620. * return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  84621. * }
  84622. * }
  84623. * \endcode
  84624. *
  84625. * \note In general, FLAC__StreamEncoder functions which change the
  84626. * state should not be called on the \a encoder while in the callback.
  84627. *
  84628. * \param encoder The encoder instance calling the callback.
  84629. * \param absolute_byte_offset The address at which to store the current
  84630. * position of the output.
  84631. * \param client_data The callee's client data set through
  84632. * FLAC__stream_encoder_init_*().
  84633. * \retval FLAC__StreamEncoderTellStatus
  84634. * The callee's return status.
  84635. */
  84636. typedef FLAC__StreamEncoderTellStatus (*FLAC__StreamEncoderTellCallback)(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  84637. /** Signature for the metadata callback.
  84638. *
  84639. * A function pointer matching this signature may be passed to
  84640. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  84641. * once at the end of encoding with the populated STREAMINFO structure. This
  84642. * is so the client can seek back to the beginning of the file and write the
  84643. * STREAMINFO block with the correct statistics after encoding (like
  84644. * minimum/maximum frame size and total samples).
  84645. *
  84646. * \note In general, FLAC__StreamEncoder functions which change the
  84647. * state should not be called on the \a encoder while in the callback.
  84648. *
  84649. * \param encoder The encoder instance calling the callback.
  84650. * \param metadata The final populated STREAMINFO block.
  84651. * \param client_data The callee's client data set through
  84652. * FLAC__stream_encoder_init_*().
  84653. */
  84654. typedef void (*FLAC__StreamEncoderMetadataCallback)(const FLAC__StreamEncoder *encoder, const FLAC__StreamMetadata *metadata, void *client_data);
  84655. /** Signature for the progress callback.
  84656. *
  84657. * A function pointer matching this signature may be passed to
  84658. * FLAC__stream_encoder_init*_file() or FLAC__stream_encoder_init*_FILE().
  84659. * The supplied function will be called when the encoder has finished
  84660. * writing a frame. The \c total_frames_estimate argument to the
  84661. * callback will be based on the value from
  84662. * FLAC__stream_encoder_set_total_samples_estimate().
  84663. *
  84664. * \note In general, FLAC__StreamEncoder functions which change the
  84665. * state should not be called on the \a encoder while in the callback.
  84666. *
  84667. * \param encoder The encoder instance calling the callback.
  84668. * \param bytes_written Bytes written so far.
  84669. * \param samples_written Samples written so far.
  84670. * \param frames_written Frames written so far.
  84671. * \param total_frames_estimate The estimate of the total number of
  84672. * frames to be written.
  84673. * \param client_data The callee's client data set through
  84674. * FLAC__stream_encoder_init_*().
  84675. */
  84676. 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);
  84677. /***********************************************************************
  84678. *
  84679. * Class constructor/destructor
  84680. *
  84681. ***********************************************************************/
  84682. /** Create a new stream encoder instance. The instance is created with
  84683. * default settings; see the individual FLAC__stream_encoder_set_*()
  84684. * functions for each setting's default.
  84685. *
  84686. * \retval FLAC__StreamEncoder*
  84687. * \c NULL if there was an error allocating memory, else the new instance.
  84688. */
  84689. FLAC_API FLAC__StreamEncoder *FLAC__stream_encoder_new(void);
  84690. /** Free an encoder instance. Deletes the object pointed to by \a encoder.
  84691. *
  84692. * \param encoder A pointer to an existing encoder.
  84693. * \assert
  84694. * \code encoder != NULL \endcode
  84695. */
  84696. FLAC_API void FLAC__stream_encoder_delete(FLAC__StreamEncoder *encoder);
  84697. /***********************************************************************
  84698. *
  84699. * Public class method prototypes
  84700. *
  84701. ***********************************************************************/
  84702. /** Set the serial number for the FLAC stream to use in the Ogg container.
  84703. *
  84704. * \note
  84705. * This does not need to be set for native FLAC encoding.
  84706. *
  84707. * \note
  84708. * It is recommended to set a serial number explicitly as the default of '0'
  84709. * may collide with other streams.
  84710. *
  84711. * \default \c 0
  84712. * \param encoder An encoder instance to set.
  84713. * \param serial_number See above.
  84714. * \assert
  84715. * \code encoder != NULL \endcode
  84716. * \retval FLAC__bool
  84717. * \c false if the encoder is already initialized, else \c true.
  84718. */
  84719. FLAC_API FLAC__bool FLAC__stream_encoder_set_ogg_serial_number(FLAC__StreamEncoder *encoder, long serial_number);
  84720. /** Set the "verify" flag. If \c true, the encoder will verify it's own
  84721. * encoded output by feeding it through an internal decoder and comparing
  84722. * the original signal against the decoded signal. If a mismatch occurs,
  84723. * the process call will return \c false. Note that this will slow the
  84724. * encoding process by the extra time required for decoding and comparison.
  84725. *
  84726. * \default \c false
  84727. * \param encoder An encoder instance to set.
  84728. * \param value Flag value (see above).
  84729. * \assert
  84730. * \code encoder != NULL \endcode
  84731. * \retval FLAC__bool
  84732. * \c false if the encoder is already initialized, else \c true.
  84733. */
  84734. FLAC_API FLAC__bool FLAC__stream_encoder_set_verify(FLAC__StreamEncoder *encoder, FLAC__bool value);
  84735. /** Set the <A HREF="../format.html#subset">Subset</A> flag. If \c true,
  84736. * the encoder will comply with the Subset and will check the
  84737. * settings during FLAC__stream_encoder_init_*() to see if all settings
  84738. * comply. If \c false, the settings may take advantage of the full
  84739. * range that the format allows.
  84740. *
  84741. * Make sure you know what it entails before setting this to \c false.
  84742. *
  84743. * \default \c true
  84744. * \param encoder An encoder instance to set.
  84745. * \param value Flag value (see above).
  84746. * \assert
  84747. * \code encoder != NULL \endcode
  84748. * \retval FLAC__bool
  84749. * \c false if the encoder is already initialized, else \c true.
  84750. */
  84751. FLAC_API FLAC__bool FLAC__stream_encoder_set_streamable_subset(FLAC__StreamEncoder *encoder, FLAC__bool value);
  84752. /** Set the number of channels to be encoded.
  84753. *
  84754. * \default \c 2
  84755. * \param encoder An encoder instance to set.
  84756. * \param value See above.
  84757. * \assert
  84758. * \code encoder != NULL \endcode
  84759. * \retval FLAC__bool
  84760. * \c false if the encoder is already initialized, else \c true.
  84761. */
  84762. FLAC_API FLAC__bool FLAC__stream_encoder_set_channels(FLAC__StreamEncoder *encoder, unsigned value);
  84763. /** Set the sample resolution of the input to be encoded.
  84764. *
  84765. * \warning
  84766. * Do not feed the encoder data that is wider than the value you
  84767. * set here or you will generate an invalid stream.
  84768. *
  84769. * \default \c 16
  84770. * \param encoder An encoder instance to set.
  84771. * \param value See above.
  84772. * \assert
  84773. * \code encoder != NULL \endcode
  84774. * \retval FLAC__bool
  84775. * \c false if the encoder is already initialized, else \c true.
  84776. */
  84777. FLAC_API FLAC__bool FLAC__stream_encoder_set_bits_per_sample(FLAC__StreamEncoder *encoder, unsigned value);
  84778. /** Set the sample rate (in Hz) of the input to be encoded.
  84779. *
  84780. * \default \c 44100
  84781. * \param encoder An encoder instance to set.
  84782. * \param value See above.
  84783. * \assert
  84784. * \code encoder != NULL \endcode
  84785. * \retval FLAC__bool
  84786. * \c false if the encoder is already initialized, else \c true.
  84787. */
  84788. FLAC_API FLAC__bool FLAC__stream_encoder_set_sample_rate(FLAC__StreamEncoder *encoder, unsigned value);
  84789. /** Set the compression level
  84790. *
  84791. * The compression level is roughly proportional to the amount of effort
  84792. * the encoder expends to compress the file. A higher level usually
  84793. * means more computation but higher compression. The default level is
  84794. * suitable for most applications.
  84795. *
  84796. * Currently the levels range from \c 0 (fastest, least compression) to
  84797. * \c 8 (slowest, most compression). A value larger than \c 8 will be
  84798. * treated as \c 8.
  84799. *
  84800. * This function automatically calls the following other \c _set_
  84801. * functions with appropriate values, so the client does not need to
  84802. * unless it specifically wants to override them:
  84803. * - FLAC__stream_encoder_set_do_mid_side_stereo()
  84804. * - FLAC__stream_encoder_set_loose_mid_side_stereo()
  84805. * - FLAC__stream_encoder_set_apodization()
  84806. * - FLAC__stream_encoder_set_max_lpc_order()
  84807. * - FLAC__stream_encoder_set_qlp_coeff_precision()
  84808. * - FLAC__stream_encoder_set_do_qlp_coeff_prec_search()
  84809. * - FLAC__stream_encoder_set_do_escape_coding()
  84810. * - FLAC__stream_encoder_set_do_exhaustive_model_search()
  84811. * - FLAC__stream_encoder_set_min_residual_partition_order()
  84812. * - FLAC__stream_encoder_set_max_residual_partition_order()
  84813. * - FLAC__stream_encoder_set_rice_parameter_search_dist()
  84814. *
  84815. * The actual values set for each level are:
  84816. * <table>
  84817. * <tr>
  84818. * <td><b>level</b><td>
  84819. * <td>do mid-side stereo<td>
  84820. * <td>loose mid-side stereo<td>
  84821. * <td>apodization<td>
  84822. * <td>max lpc order<td>
  84823. * <td>qlp coeff precision<td>
  84824. * <td>qlp coeff prec search<td>
  84825. * <td>escape coding<td>
  84826. * <td>exhaustive model search<td>
  84827. * <td>min residual partition order<td>
  84828. * <td>max residual partition order<td>
  84829. * <td>rice parameter search dist<td>
  84830. * </tr>
  84831. * <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>
  84832. * <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>
  84833. * <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>
  84834. * <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>
  84835. * <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>
  84836. * <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>
  84837. * <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>
  84838. * <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>
  84839. * <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>
  84840. * </table>
  84841. *
  84842. * \default \c 5
  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_compression_level(FLAC__StreamEncoder *encoder, unsigned value);
  84851. /** Set the blocksize to use while encoding.
  84852. *
  84853. * The number of samples to use per frame. Use \c 0 to let the encoder
  84854. * estimate a blocksize; this is usually best.
  84855. *
  84856. * \default \c 0
  84857. * \param encoder An encoder instance to set.
  84858. * \param value See above.
  84859. * \assert
  84860. * \code encoder != NULL \endcode
  84861. * \retval FLAC__bool
  84862. * \c false if the encoder is already initialized, else \c true.
  84863. */
  84864. FLAC_API FLAC__bool FLAC__stream_encoder_set_blocksize(FLAC__StreamEncoder *encoder, unsigned value);
  84865. /** Set to \c true to enable mid-side encoding on stereo input. The
  84866. * number of channels must be 2 for this to have any effect. Set to
  84867. * \c false to use only independent channel coding.
  84868. *
  84869. * \default \c false
  84870. * \param encoder An encoder instance to set.
  84871. * \param value Flag value (see above).
  84872. * \assert
  84873. * \code encoder != NULL \endcode
  84874. * \retval FLAC__bool
  84875. * \c false if the encoder is already initialized, else \c true.
  84876. */
  84877. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value);
  84878. /** Set to \c true to enable adaptive switching between mid-side and
  84879. * left-right encoding on stereo input. Set to \c false to use
  84880. * exhaustive searching. Setting this to \c true requires
  84881. * FLAC__stream_encoder_set_do_mid_side_stereo() to also be set to
  84882. * \c true in order to have any effect.
  84883. *
  84884. * \default \c false
  84885. * \param encoder An encoder instance to set.
  84886. * \param value Flag value (see above).
  84887. * \assert
  84888. * \code encoder != NULL \endcode
  84889. * \retval FLAC__bool
  84890. * \c false if the encoder is already initialized, else \c true.
  84891. */
  84892. FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value);
  84893. /** Sets the apodization function(s) the encoder will use when windowing
  84894. * audio data for LPC analysis.
  84895. *
  84896. * The \a specification is a plain ASCII string which specifies exactly
  84897. * which functions to use. There may be more than one (up to 32),
  84898. * separated by \c ';' characters. Some functions take one or more
  84899. * comma-separated arguments in parentheses.
  84900. *
  84901. * The available functions are \c bartlett, \c bartlett_hann,
  84902. * \c blackman, \c blackman_harris_4term_92db, \c connes, \c flattop,
  84903. * \c gauss(STDDEV), \c hamming, \c hann, \c kaiser_bessel, \c nuttall,
  84904. * \c rectangle, \c triangle, \c tukey(P), \c welch.
  84905. *
  84906. * For \c gauss(STDDEV), STDDEV specifies the standard deviation
  84907. * (0<STDDEV<=0.5).
  84908. *
  84909. * For \c tukey(P), P specifies the fraction of the window that is
  84910. * tapered (0<=P<=1). P=0 corresponds to \c rectangle and P=1
  84911. * corresponds to \c hann.
  84912. *
  84913. * Example specifications are \c "blackman" or
  84914. * \c "hann;triangle;tukey(0.5);tukey(0.25);tukey(0.125)"
  84915. *
  84916. * Any function that is specified erroneously is silently dropped. Up
  84917. * to 32 functions are kept, the rest are dropped. If the specification
  84918. * is empty the encoder defaults to \c "tukey(0.5)".
  84919. *
  84920. * When more than one function is specified, then for every subframe the
  84921. * encoder will try each of them separately and choose the window that
  84922. * results in the smallest compressed subframe.
  84923. *
  84924. * Note that each function specified causes the encoder to occupy a
  84925. * floating point array in which to store the window.
  84926. *
  84927. * \default \c "tukey(0.5)"
  84928. * \param encoder An encoder instance to set.
  84929. * \param specification See above.
  84930. * \assert
  84931. * \code encoder != NULL \endcode
  84932. * \code specification != NULL \endcode
  84933. * \retval FLAC__bool
  84934. * \c false if the encoder is already initialized, else \c true.
  84935. */
  84936. FLAC_API FLAC__bool FLAC__stream_encoder_set_apodization(FLAC__StreamEncoder *encoder, const char *specification);
  84937. /** Set the maximum LPC order, or \c 0 to use only the fixed predictors.
  84938. *
  84939. * \default \c 0
  84940. * \param encoder An encoder instance to set.
  84941. * \param value See above.
  84942. * \assert
  84943. * \code encoder != NULL \endcode
  84944. * \retval FLAC__bool
  84945. * \c false if the encoder is already initialized, else \c true.
  84946. */
  84947. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_lpc_order(FLAC__StreamEncoder *encoder, unsigned value);
  84948. /** Set the precision, in bits, of the quantized linear predictor
  84949. * coefficients, or \c 0 to let the encoder select it based on the
  84950. * blocksize.
  84951. *
  84952. * \note
  84953. * In the current implementation, qlp_coeff_precision + bits_per_sample must
  84954. * be less than 32.
  84955. *
  84956. * \default \c 0
  84957. * \param encoder An encoder instance to set.
  84958. * \param value See above.
  84959. * \assert
  84960. * \code encoder != NULL \endcode
  84961. * \retval FLAC__bool
  84962. * \c false if the encoder is already initialized, else \c true.
  84963. */
  84964. FLAC_API FLAC__bool FLAC__stream_encoder_set_qlp_coeff_precision(FLAC__StreamEncoder *encoder, unsigned value);
  84965. /** Set to \c false to use only the specified quantized linear predictor
  84966. * coefficient precision, or \c true to search neighboring precision
  84967. * values and use the best one.
  84968. *
  84969. * \default \c false
  84970. * \param encoder An encoder instance to set.
  84971. * \param value See above.
  84972. * \assert
  84973. * \code encoder != NULL \endcode
  84974. * \retval FLAC__bool
  84975. * \c false if the encoder is already initialized, else \c true.
  84976. */
  84977. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_qlp_coeff_prec_search(FLAC__StreamEncoder *encoder, FLAC__bool value);
  84978. /** Deprecated. Setting this value has no effect.
  84979. *
  84980. * \default \c false
  84981. * \param encoder An encoder instance to set.
  84982. * \param value See above.
  84983. * \assert
  84984. * \code encoder != NULL \endcode
  84985. * \retval FLAC__bool
  84986. * \c false if the encoder is already initialized, else \c true.
  84987. */
  84988. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_escape_coding(FLAC__StreamEncoder *encoder, FLAC__bool value);
  84989. /** Set to \c false to let the encoder estimate the best model order
  84990. * based on the residual signal energy, or \c true to force the
  84991. * encoder to evaluate all order models and select the best.
  84992. *
  84993. * \default \c false
  84994. * \param encoder An encoder instance to set.
  84995. * \param value See above.
  84996. * \assert
  84997. * \code encoder != NULL \endcode
  84998. * \retval FLAC__bool
  84999. * \c false if the encoder is already initialized, else \c true.
  85000. */
  85001. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_exhaustive_model_search(FLAC__StreamEncoder *encoder, FLAC__bool value);
  85002. /** Set the minimum partition order to search when coding the residual.
  85003. * This is used in tandem with
  85004. * FLAC__stream_encoder_set_max_residual_partition_order().
  85005. *
  85006. * The partition order determines the context size in the residual.
  85007. * The context size will be approximately <tt>blocksize / (2 ^ order)</tt>.
  85008. *
  85009. * Set both min and max values to \c 0 to force a single context,
  85010. * whose Rice parameter is based on the residual signal variance.
  85011. * Otherwise, set a min and max order, and the encoder will search
  85012. * all orders, using the mean of each context for its Rice parameter,
  85013. * and use the best.
  85014. *
  85015. * \default \c 0
  85016. * \param encoder An encoder instance to set.
  85017. * \param value See above.
  85018. * \assert
  85019. * \code encoder != NULL \endcode
  85020. * \retval FLAC__bool
  85021. * \c false if the encoder is already initialized, else \c true.
  85022. */
  85023. FLAC_API FLAC__bool FLAC__stream_encoder_set_min_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value);
  85024. /** Set the maximum partition order to search when coding the residual.
  85025. * This is used in tandem with
  85026. * FLAC__stream_encoder_set_min_residual_partition_order().
  85027. *
  85028. * The partition order determines the context size in the residual.
  85029. * The context size will be approximately <tt>blocksize / (2 ^ order)</tt>.
  85030. *
  85031. * Set both min and max values to \c 0 to force a single context,
  85032. * whose Rice parameter is based on the residual signal variance.
  85033. * Otherwise, set a min and max order, and the encoder will search
  85034. * all orders, using the mean of each context for its Rice parameter,
  85035. * and use the best.
  85036. *
  85037. * \default \c 0
  85038. * \param encoder An encoder instance to set.
  85039. * \param value See above.
  85040. * \assert
  85041. * \code encoder != NULL \endcode
  85042. * \retval FLAC__bool
  85043. * \c false if the encoder is already initialized, else \c true.
  85044. */
  85045. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value);
  85046. /** Deprecated. Setting this value has no effect.
  85047. *
  85048. * \default \c 0
  85049. * \param encoder An encoder instance to set.
  85050. * \param value See above.
  85051. * \assert
  85052. * \code encoder != NULL \endcode
  85053. * \retval FLAC__bool
  85054. * \c false if the encoder is already initialized, else \c true.
  85055. */
  85056. FLAC_API FLAC__bool FLAC__stream_encoder_set_rice_parameter_search_dist(FLAC__StreamEncoder *encoder, unsigned value);
  85057. /** Set an estimate of the total samples that will be encoded.
  85058. * This is merely an estimate and may be set to \c 0 if unknown.
  85059. * This value will be written to the STREAMINFO block before encoding,
  85060. * and can remove the need for the caller to rewrite the value later
  85061. * if the value is known before encoding.
  85062. *
  85063. * \default \c 0
  85064. * \param encoder An encoder instance to set.
  85065. * \param value See above.
  85066. * \assert
  85067. * \code encoder != NULL \endcode
  85068. * \retval FLAC__bool
  85069. * \c false if the encoder is already initialized, else \c true.
  85070. */
  85071. FLAC_API FLAC__bool FLAC__stream_encoder_set_total_samples_estimate(FLAC__StreamEncoder *encoder, FLAC__uint64 value);
  85072. /** Set the metadata blocks to be emitted to the stream before encoding.
  85073. * A value of \c NULL, \c 0 implies no metadata; otherwise, supply an
  85074. * array of pointers to metadata blocks. The array is non-const since
  85075. * the encoder may need to change the \a is_last flag inside them, and
  85076. * in some cases update seek point offsets. Otherwise, the encoder will
  85077. * not modify or free the blocks. It is up to the caller to free the
  85078. * metadata blocks after encoding finishes.
  85079. *
  85080. * \note
  85081. * The encoder stores only copies of the pointers in the \a metadata array;
  85082. * the metadata blocks themselves must survive at least until after
  85083. * FLAC__stream_encoder_finish() returns. Do not free the blocks until then.
  85084. *
  85085. * \note
  85086. * The STREAMINFO block is always written and no STREAMINFO block may
  85087. * occur in the supplied array.
  85088. *
  85089. * \note
  85090. * By default the encoder does not create a SEEKTABLE. If one is supplied
  85091. * in the \a metadata array, but the client has specified that it does not
  85092. * support seeking, then the SEEKTABLE will be written verbatim. However
  85093. * by itself this is not very useful as the client will not know the stream
  85094. * offsets for the seekpoints ahead of time. In order to get a proper
  85095. * seektable the client must support seeking. See next note.
  85096. *
  85097. * \note
  85098. * SEEKTABLE blocks are handled specially. Since you will not know
  85099. * the values for the seek point stream offsets, you should pass in
  85100. * a SEEKTABLE 'template', that is, a SEEKTABLE object with the
  85101. * required sample numbers (or placeholder points), with \c 0 for the
  85102. * \a frame_samples and \a stream_offset fields for each point. If the
  85103. * client has specified that it supports seeking by providing a seek
  85104. * callback to FLAC__stream_encoder_init_stream() or both seek AND read
  85105. * callback to FLAC__stream_encoder_init_ogg_stream() (or by using
  85106. * FLAC__stream_encoder_init*_file() or FLAC__stream_encoder_init*_FILE()),
  85107. * then while it is encoding the encoder will fill the stream offsets in
  85108. * for you and when encoding is finished, it will seek back and write the
  85109. * real values into the SEEKTABLE block in the stream. There are helper
  85110. * routines for manipulating seektable template blocks; see metadata.h:
  85111. * FLAC__metadata_object_seektable_template_*(). If the client does
  85112. * not support seeking, the SEEKTABLE will have inaccurate offsets which
  85113. * will slow down or remove the ability to seek in the FLAC stream.
  85114. *
  85115. * \note
  85116. * The encoder instance \b will modify the first \c SEEKTABLE block
  85117. * as it transforms the template to a valid seektable while encoding,
  85118. * but it is still up to the caller to free all metadata blocks after
  85119. * encoding.
  85120. *
  85121. * \note
  85122. * A VORBIS_COMMENT block may be supplied. The vendor string in it
  85123. * will be ignored. libFLAC will use it's own vendor string. libFLAC
  85124. * will not modify the passed-in VORBIS_COMMENT's vendor string, it
  85125. * will simply write it's own into the stream. If no VORBIS_COMMENT
  85126. * block is present in the \a metadata array, libFLAC will write an
  85127. * empty one, containing only the vendor string.
  85128. *
  85129. * \note The Ogg FLAC mapping requires that the VORBIS_COMMENT block be
  85130. * the second metadata block of the stream. The encoder already supplies
  85131. * the STREAMINFO block automatically. If \a metadata does not contain a
  85132. * VORBIS_COMMENT block, the encoder will supply that too. Otherwise, if
  85133. * \a metadata does contain a VORBIS_COMMENT block and it is not the
  85134. * first, the init function will reorder \a metadata by moving the
  85135. * VORBIS_COMMENT block to the front; the relative ordering of the other
  85136. * blocks will remain as they were.
  85137. *
  85138. * \note The Ogg FLAC mapping limits the number of metadata blocks per
  85139. * stream to \c 65535. If \a num_blocks exceeds this the function will
  85140. * return \c false.
  85141. *
  85142. * \default \c NULL, 0
  85143. * \param encoder An encoder instance to set.
  85144. * \param metadata See above.
  85145. * \param num_blocks See above.
  85146. * \assert
  85147. * \code encoder != NULL \endcode
  85148. * \retval FLAC__bool
  85149. * \c false if the encoder is already initialized, else \c true.
  85150. * \c false if the encoder is already initialized, or if
  85151. * \a num_blocks > 65535 if encoding to Ogg FLAC, else \c true.
  85152. */
  85153. FLAC_API FLAC__bool FLAC__stream_encoder_set_metadata(FLAC__StreamEncoder *encoder, FLAC__StreamMetadata **metadata, unsigned num_blocks);
  85154. /** Get the current encoder state.
  85155. *
  85156. * \param encoder An encoder instance to query.
  85157. * \assert
  85158. * \code encoder != NULL \endcode
  85159. * \retval FLAC__StreamEncoderState
  85160. * The current encoder state.
  85161. */
  85162. FLAC_API FLAC__StreamEncoderState FLAC__stream_encoder_get_state(const FLAC__StreamEncoder *encoder);
  85163. /** Get the state of the verify stream decoder.
  85164. * Useful when the stream encoder state is
  85165. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR.
  85166. *
  85167. * \param encoder An encoder instance to query.
  85168. * \assert
  85169. * \code encoder != NULL \endcode
  85170. * \retval FLAC__StreamDecoderState
  85171. * The verify stream decoder state.
  85172. */
  85173. FLAC_API FLAC__StreamDecoderState FLAC__stream_encoder_get_verify_decoder_state(const FLAC__StreamEncoder *encoder);
  85174. /** Get the current encoder state as a C string.
  85175. * This version automatically resolves
  85176. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR by getting the
  85177. * verify decoder's state.
  85178. *
  85179. * \param encoder A encoder instance to query.
  85180. * \assert
  85181. * \code encoder != NULL \endcode
  85182. * \retval const char *
  85183. * The encoder state as a C string. Do not modify the contents.
  85184. */
  85185. FLAC_API const char *FLAC__stream_encoder_get_resolved_state_string(const FLAC__StreamEncoder *encoder);
  85186. /** Get relevant values about the nature of a verify decoder error.
  85187. * Useful when the stream encoder state is
  85188. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR. The arguments should
  85189. * be addresses in which the stats will be returned, or NULL if value
  85190. * is not desired.
  85191. *
  85192. * \param encoder An encoder instance to query.
  85193. * \param absolute_sample The absolute sample number of the mismatch.
  85194. * \param frame_number The number of the frame in which the mismatch occurred.
  85195. * \param channel The channel in which the mismatch occurred.
  85196. * \param sample The number of the sample (relative to the frame) in
  85197. * which the mismatch occurred.
  85198. * \param expected The expected value for the sample in question.
  85199. * \param got The actual value returned by the decoder.
  85200. * \assert
  85201. * \code encoder != NULL \endcode
  85202. */
  85203. 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);
  85204. /** Get the "verify" flag.
  85205. *
  85206. * \param encoder An encoder instance to query.
  85207. * \assert
  85208. * \code encoder != NULL \endcode
  85209. * \retval FLAC__bool
  85210. * See FLAC__stream_encoder_set_verify().
  85211. */
  85212. FLAC_API FLAC__bool FLAC__stream_encoder_get_verify(const FLAC__StreamEncoder *encoder);
  85213. /** Get the <A HREF="../format.html#subset>Subset</A> flag.
  85214. *
  85215. * \param encoder An encoder instance to query.
  85216. * \assert
  85217. * \code encoder != NULL \endcode
  85218. * \retval FLAC__bool
  85219. * See FLAC__stream_encoder_set_streamable_subset().
  85220. */
  85221. FLAC_API FLAC__bool FLAC__stream_encoder_get_streamable_subset(const FLAC__StreamEncoder *encoder);
  85222. /** Get the number of input channels being processed.
  85223. *
  85224. * \param encoder An encoder instance to query.
  85225. * \assert
  85226. * \code encoder != NULL \endcode
  85227. * \retval unsigned
  85228. * See FLAC__stream_encoder_set_channels().
  85229. */
  85230. FLAC_API unsigned FLAC__stream_encoder_get_channels(const FLAC__StreamEncoder *encoder);
  85231. /** Get the input sample resolution setting.
  85232. *
  85233. * \param encoder An encoder instance to query.
  85234. * \assert
  85235. * \code encoder != NULL \endcode
  85236. * \retval unsigned
  85237. * See FLAC__stream_encoder_set_bits_per_sample().
  85238. */
  85239. FLAC_API unsigned FLAC__stream_encoder_get_bits_per_sample(const FLAC__StreamEncoder *encoder);
  85240. /** Get the input sample rate setting.
  85241. *
  85242. * \param encoder An encoder instance to query.
  85243. * \assert
  85244. * \code encoder != NULL \endcode
  85245. * \retval unsigned
  85246. * See FLAC__stream_encoder_set_sample_rate().
  85247. */
  85248. FLAC_API unsigned FLAC__stream_encoder_get_sample_rate(const FLAC__StreamEncoder *encoder);
  85249. /** Get the blocksize setting.
  85250. *
  85251. * \param encoder An encoder instance to query.
  85252. * \assert
  85253. * \code encoder != NULL \endcode
  85254. * \retval unsigned
  85255. * See FLAC__stream_encoder_set_blocksize().
  85256. */
  85257. FLAC_API unsigned FLAC__stream_encoder_get_blocksize(const FLAC__StreamEncoder *encoder);
  85258. /** Get the "mid/side stereo coding" flag.
  85259. *
  85260. * \param encoder An encoder instance to query.
  85261. * \assert
  85262. * \code encoder != NULL \endcode
  85263. * \retval FLAC__bool
  85264. * See FLAC__stream_encoder_get_do_mid_side_stereo().
  85265. */
  85266. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_mid_side_stereo(const FLAC__StreamEncoder *encoder);
  85267. /** Get the "adaptive mid/side switching" flag.
  85268. *
  85269. * \param encoder An encoder instance to query.
  85270. * \assert
  85271. * \code encoder != NULL \endcode
  85272. * \retval FLAC__bool
  85273. * See FLAC__stream_encoder_set_loose_mid_side_stereo().
  85274. */
  85275. FLAC_API FLAC__bool FLAC__stream_encoder_get_loose_mid_side_stereo(const FLAC__StreamEncoder *encoder);
  85276. /** Get the maximum LPC order setting.
  85277. *
  85278. * \param encoder An encoder instance to query.
  85279. * \assert
  85280. * \code encoder != NULL \endcode
  85281. * \retval unsigned
  85282. * See FLAC__stream_encoder_set_max_lpc_order().
  85283. */
  85284. FLAC_API unsigned FLAC__stream_encoder_get_max_lpc_order(const FLAC__StreamEncoder *encoder);
  85285. /** Get the quantized linear predictor coefficient precision setting.
  85286. *
  85287. * \param encoder An encoder instance to query.
  85288. * \assert
  85289. * \code encoder != NULL \endcode
  85290. * \retval unsigned
  85291. * See FLAC__stream_encoder_set_qlp_coeff_precision().
  85292. */
  85293. FLAC_API unsigned FLAC__stream_encoder_get_qlp_coeff_precision(const FLAC__StreamEncoder *encoder);
  85294. /** Get the qlp coefficient precision search flag.
  85295. *
  85296. * \param encoder An encoder instance to query.
  85297. * \assert
  85298. * \code encoder != NULL \endcode
  85299. * \retval FLAC__bool
  85300. * See FLAC__stream_encoder_set_do_qlp_coeff_prec_search().
  85301. */
  85302. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_qlp_coeff_prec_search(const FLAC__StreamEncoder *encoder);
  85303. /** Get the "escape coding" flag.
  85304. *
  85305. * \param encoder An encoder instance to query.
  85306. * \assert
  85307. * \code encoder != NULL \endcode
  85308. * \retval FLAC__bool
  85309. * See FLAC__stream_encoder_set_do_escape_coding().
  85310. */
  85311. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_escape_coding(const FLAC__StreamEncoder *encoder);
  85312. /** Get the exhaustive model search flag.
  85313. *
  85314. * \param encoder An encoder instance to query.
  85315. * \assert
  85316. * \code encoder != NULL \endcode
  85317. * \retval FLAC__bool
  85318. * See FLAC__stream_encoder_set_do_exhaustive_model_search().
  85319. */
  85320. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_exhaustive_model_search(const FLAC__StreamEncoder *encoder);
  85321. /** Get the minimum residual partition order setting.
  85322. *
  85323. * \param encoder An encoder instance to query.
  85324. * \assert
  85325. * \code encoder != NULL \endcode
  85326. * \retval unsigned
  85327. * See FLAC__stream_encoder_set_min_residual_partition_order().
  85328. */
  85329. FLAC_API unsigned FLAC__stream_encoder_get_min_residual_partition_order(const FLAC__StreamEncoder *encoder);
  85330. /** Get maximum residual partition order setting.
  85331. *
  85332. * \param encoder An encoder instance to query.
  85333. * \assert
  85334. * \code encoder != NULL \endcode
  85335. * \retval unsigned
  85336. * See FLAC__stream_encoder_set_max_residual_partition_order().
  85337. */
  85338. FLAC_API unsigned FLAC__stream_encoder_get_max_residual_partition_order(const FLAC__StreamEncoder *encoder);
  85339. /** Get the Rice parameter search distance setting.
  85340. *
  85341. * \param encoder An encoder instance to query.
  85342. * \assert
  85343. * \code encoder != NULL \endcode
  85344. * \retval unsigned
  85345. * See FLAC__stream_encoder_set_rice_parameter_search_dist().
  85346. */
  85347. FLAC_API unsigned FLAC__stream_encoder_get_rice_parameter_search_dist(const FLAC__StreamEncoder *encoder);
  85348. /** Get the previously set estimate of the total samples to be encoded.
  85349. * The encoder merely mimics back the value given to
  85350. * FLAC__stream_encoder_set_total_samples_estimate() since it has no
  85351. * other way of knowing how many samples the client will encode.
  85352. *
  85353. * \param encoder An encoder instance to set.
  85354. * \assert
  85355. * \code encoder != NULL \endcode
  85356. * \retval FLAC__uint64
  85357. * See FLAC__stream_encoder_get_total_samples_estimate().
  85358. */
  85359. FLAC_API FLAC__uint64 FLAC__stream_encoder_get_total_samples_estimate(const FLAC__StreamEncoder *encoder);
  85360. /** Initialize the encoder instance to encode native FLAC streams.
  85361. *
  85362. * This flavor of initialization sets up the encoder to encode to a
  85363. * native FLAC stream. I/O is performed via callbacks to the client.
  85364. * For encoding to a plain file via filename or open \c FILE*,
  85365. * FLAC__stream_encoder_init_file() and FLAC__stream_encoder_init_FILE()
  85366. * provide a simpler interface.
  85367. *
  85368. * This function should be called after FLAC__stream_encoder_new() and
  85369. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  85370. * or FLAC__stream_encoder_process_interleaved().
  85371. * initialization succeeded.
  85372. *
  85373. * The call to FLAC__stream_encoder_init_stream() currently will also
  85374. * immediately call the write callback several times, once with the \c fLaC
  85375. * signature, and once for each encoded metadata block.
  85376. *
  85377. * \param encoder An uninitialized encoder instance.
  85378. * \param write_callback See FLAC__StreamEncoderWriteCallback. This
  85379. * pointer must not be \c NULL.
  85380. * \param seek_callback See FLAC__StreamEncoderSeekCallback. This
  85381. * pointer may be \c NULL if seeking is not
  85382. * supported. The encoder uses seeking to go back
  85383. * and write some some stream statistics to the
  85384. * STREAMINFO block; this is recommended but not
  85385. * necessary to create a valid FLAC stream. If
  85386. * \a seek_callback is not \c NULL then a
  85387. * \a tell_callback must also be supplied.
  85388. * Alternatively, a dummy seek callback that just
  85389. * returns \c FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  85390. * may also be supplied, all though this is slightly
  85391. * less efficient for the encoder.
  85392. * \param tell_callback See FLAC__StreamEncoderTellCallback. This
  85393. * pointer may be \c NULL if seeking is not
  85394. * supported. If \a seek_callback is \c NULL then
  85395. * this argument will be ignored. If
  85396. * \a seek_callback is not \c NULL then a
  85397. * \a tell_callback must also be supplied.
  85398. * Alternatively, a dummy tell callback that just
  85399. * returns \c FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  85400. * may also be supplied, all though this is slightly
  85401. * less efficient for the encoder.
  85402. * \param metadata_callback See FLAC__StreamEncoderMetadataCallback. This
  85403. * pointer may be \c NULL if the callback is not
  85404. * desired. If the client provides a seek callback,
  85405. * this function is not necessary as the encoder
  85406. * will automatically seek back and update the
  85407. * STREAMINFO block. It may also be \c NULL if the
  85408. * client does not support seeking, since it will
  85409. * have no way of going back to update the
  85410. * STREAMINFO. However the client can still supply
  85411. * a callback if it would like to know the details
  85412. * from the STREAMINFO.
  85413. * \param client_data This value will be supplied to callbacks in their
  85414. * \a client_data argument.
  85415. * \assert
  85416. * \code encoder != NULL \endcode
  85417. * \retval FLAC__StreamEncoderInitStatus
  85418. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  85419. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  85420. */
  85421. 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);
  85422. /** Initialize the encoder instance to encode Ogg FLAC streams.
  85423. *
  85424. * This flavor of initialization sets up the encoder to encode to a FLAC
  85425. * stream in an Ogg container. I/O is performed via callbacks to the
  85426. * client. For encoding to a plain file via filename or open \c FILE*,
  85427. * FLAC__stream_encoder_init_ogg_file() and FLAC__stream_encoder_init_ogg_FILE()
  85428. * provide a simpler interface.
  85429. *
  85430. * This function should be called after FLAC__stream_encoder_new() and
  85431. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  85432. * or FLAC__stream_encoder_process_interleaved().
  85433. * initialization succeeded.
  85434. *
  85435. * The call to FLAC__stream_encoder_init_ogg_stream() currently will also
  85436. * immediately call the write callback several times to write the metadata
  85437. * packets.
  85438. *
  85439. * \param encoder An uninitialized encoder instance.
  85440. * \param read_callback See FLAC__StreamEncoderReadCallback. This
  85441. * pointer must not be \c NULL if \a seek_callback
  85442. * is non-NULL since they are both needed to be
  85443. * able to write data back to the Ogg FLAC stream
  85444. * in the post-encode phase.
  85445. * \param write_callback See FLAC__StreamEncoderWriteCallback. This
  85446. * pointer must not be \c NULL.
  85447. * \param seek_callback See FLAC__StreamEncoderSeekCallback. This
  85448. * pointer may be \c NULL if seeking is not
  85449. * supported. The encoder uses seeking to go back
  85450. * and write some some stream statistics to the
  85451. * STREAMINFO block; this is recommended but not
  85452. * necessary to create a valid FLAC stream. If
  85453. * \a seek_callback is not \c NULL then a
  85454. * \a tell_callback must also be supplied.
  85455. * Alternatively, a dummy seek callback that just
  85456. * returns \c FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  85457. * may also be supplied, all though this is slightly
  85458. * less efficient for the encoder.
  85459. * \param tell_callback See FLAC__StreamEncoderTellCallback. This
  85460. * pointer may be \c NULL if seeking is not
  85461. * supported. If \a seek_callback is \c NULL then
  85462. * this argument will be ignored. If
  85463. * \a seek_callback is not \c NULL then a
  85464. * \a tell_callback must also be supplied.
  85465. * Alternatively, a dummy tell callback that just
  85466. * returns \c FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  85467. * may also be supplied, all though this is slightly
  85468. * less efficient for the encoder.
  85469. * \param metadata_callback See FLAC__StreamEncoderMetadataCallback. This
  85470. * pointer may be \c NULL if the callback is not
  85471. * desired. If the client provides a seek callback,
  85472. * this function is not necessary as the encoder
  85473. * will automatically seek back and update the
  85474. * STREAMINFO block. It may also be \c NULL if the
  85475. * client does not support seeking, since it will
  85476. * have no way of going back to update the
  85477. * STREAMINFO. However the client can still supply
  85478. * a callback if it would like to know the details
  85479. * from the STREAMINFO.
  85480. * \param client_data This value will be supplied to callbacks in their
  85481. * \a client_data argument.
  85482. * \assert
  85483. * \code encoder != NULL \endcode
  85484. * \retval FLAC__StreamEncoderInitStatus
  85485. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  85486. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  85487. */
  85488. 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);
  85489. /** Initialize the encoder instance to encode native FLAC files.
  85490. *
  85491. * This flavor of initialization sets up the encoder to encode to a
  85492. * plain native FLAC file. For non-stdio streams, you must use
  85493. * FLAC__stream_encoder_init_stream() and provide callbacks for the I/O.
  85494. *
  85495. * This function should be called after FLAC__stream_encoder_new() and
  85496. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  85497. * or FLAC__stream_encoder_process_interleaved().
  85498. * initialization succeeded.
  85499. *
  85500. * \param encoder An uninitialized encoder instance.
  85501. * \param file An open file. The file should have been opened
  85502. * with mode \c "w+b" and rewound. The file
  85503. * becomes owned by the encoder and should not be
  85504. * manipulated by the client while encoding.
  85505. * Unless \a file is \c stdout, it will be closed
  85506. * when FLAC__stream_encoder_finish() is called.
  85507. * Note however that a proper SEEKTABLE cannot be
  85508. * created when encoding to \c stdout since it is
  85509. * not seekable.
  85510. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  85511. * pointer may be \c NULL if the callback is not
  85512. * desired.
  85513. * \param client_data This value will be supplied to callbacks in their
  85514. * \a client_data argument.
  85515. * \assert
  85516. * \code encoder != NULL \endcode
  85517. * \code file != NULL \endcode
  85518. * \retval FLAC__StreamEncoderInitStatus
  85519. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  85520. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  85521. */
  85522. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_FILE(FLAC__StreamEncoder *encoder, FILE *file, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  85523. /** Initialize the encoder instance to encode Ogg FLAC files.
  85524. *
  85525. * This flavor of initialization sets up the encoder to encode to a
  85526. * plain Ogg FLAC file. For non-stdio streams, you must use
  85527. * FLAC__stream_encoder_init_ogg_stream() and provide callbacks for the I/O.
  85528. *
  85529. * This function should be called after FLAC__stream_encoder_new() and
  85530. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  85531. * or FLAC__stream_encoder_process_interleaved().
  85532. * initialization succeeded.
  85533. *
  85534. * \param encoder An uninitialized encoder instance.
  85535. * \param file An open file. The file should have been opened
  85536. * with mode \c "w+b" and rewound. The file
  85537. * becomes owned by the encoder and should not be
  85538. * manipulated by the client while encoding.
  85539. * Unless \a file is \c stdout, it will be closed
  85540. * when FLAC__stream_encoder_finish() is called.
  85541. * Note however that a proper SEEKTABLE cannot be
  85542. * created when encoding to \c stdout since it is
  85543. * not seekable.
  85544. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  85545. * pointer may be \c NULL if the callback is not
  85546. * desired.
  85547. * \param client_data This value will be supplied to callbacks in their
  85548. * \a client_data argument.
  85549. * \assert
  85550. * \code encoder != NULL \endcode
  85551. * \code file != NULL \endcode
  85552. * \retval FLAC__StreamEncoderInitStatus
  85553. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  85554. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  85555. */
  85556. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_FILE(FLAC__StreamEncoder *encoder, FILE *file, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  85557. /** Initialize the encoder instance to encode native FLAC files.
  85558. *
  85559. * This flavor of initialization sets up the encoder to encode to a plain
  85560. * FLAC file. If POSIX fopen() semantics are not sufficient (for example,
  85561. * with Unicode filenames on Windows), you must use
  85562. * FLAC__stream_encoder_init_FILE(), or FLAC__stream_encoder_init_stream()
  85563. * and provide callbacks for the I/O.
  85564. *
  85565. * This function should be called after FLAC__stream_encoder_new() and
  85566. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  85567. * or FLAC__stream_encoder_process_interleaved().
  85568. * initialization succeeded.
  85569. *
  85570. * \param encoder An uninitialized encoder instance.
  85571. * \param filename The name of the file to encode to. The file will
  85572. * be opened with fopen(). Use \c NULL to encode to
  85573. * \c stdout. Note however that a proper SEEKTABLE
  85574. * cannot be created when encoding to \c stdout since
  85575. * it is not seekable.
  85576. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  85577. * pointer may be \c NULL if the callback is not
  85578. * desired.
  85579. * \param client_data This value will be supplied to callbacks in their
  85580. * \a client_data argument.
  85581. * \assert
  85582. * \code encoder != NULL \endcode
  85583. * \retval FLAC__StreamEncoderInitStatus
  85584. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  85585. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  85586. */
  85587. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_file(FLAC__StreamEncoder *encoder, const char *filename, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  85588. /** Initialize the encoder instance to encode Ogg FLAC files.
  85589. *
  85590. * This flavor of initialization sets up the encoder to encode to a plain
  85591. * Ogg FLAC file. If POSIX fopen() semantics are not sufficient (for example,
  85592. * with Unicode filenames on Windows), you must use
  85593. * FLAC__stream_encoder_init_ogg_FILE(), or FLAC__stream_encoder_init_ogg_stream()
  85594. * and provide callbacks for the I/O.
  85595. *
  85596. * This function should be called after FLAC__stream_encoder_new() and
  85597. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  85598. * or FLAC__stream_encoder_process_interleaved().
  85599. * initialization succeeded.
  85600. *
  85601. * \param encoder An uninitialized encoder instance.
  85602. * \param filename The name of the file to encode to. The file will
  85603. * be opened with fopen(). Use \c NULL to encode to
  85604. * \c stdout. Note however that a proper SEEKTABLE
  85605. * cannot be created when encoding to \c stdout since
  85606. * it is not seekable.
  85607. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  85608. * pointer may be \c NULL if the callback is not
  85609. * desired.
  85610. * \param client_data This value will be supplied to callbacks in their
  85611. * \a client_data argument.
  85612. * \assert
  85613. * \code encoder != NULL \endcode
  85614. * \retval FLAC__StreamEncoderInitStatus
  85615. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  85616. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  85617. */
  85618. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_file(FLAC__StreamEncoder *encoder, const char *filename, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  85619. /** Finish the encoding process.
  85620. * Flushes the encoding buffer, releases resources, resets the encoder
  85621. * settings to their defaults, and returns the encoder state to
  85622. * FLAC__STREAM_ENCODER_UNINITIALIZED. Note that this can generate
  85623. * one or more write callbacks before returning, and will generate
  85624. * a metadata callback.
  85625. *
  85626. * Note that in the course of processing the last frame, errors can
  85627. * occur, so the caller should be sure to check the return value to
  85628. * ensure the file was encoded properly.
  85629. *
  85630. * In the event of a prematurely-terminated encode, it is not strictly
  85631. * necessary to call this immediately before FLAC__stream_encoder_delete()
  85632. * but it is good practice to match every FLAC__stream_encoder_init_*()
  85633. * with a FLAC__stream_encoder_finish().
  85634. *
  85635. * \param encoder An uninitialized encoder instance.
  85636. * \assert
  85637. * \code encoder != NULL \endcode
  85638. * \retval FLAC__bool
  85639. * \c false if an error occurred processing the last frame; or if verify
  85640. * mode is set (see FLAC__stream_encoder_set_verify()), there was a
  85641. * verify mismatch; else \c true. If \c false, caller should check the
  85642. * state with FLAC__stream_encoder_get_state() for more information
  85643. * about the error.
  85644. */
  85645. FLAC_API FLAC__bool FLAC__stream_encoder_finish(FLAC__StreamEncoder *encoder);
  85646. /** Submit data for encoding.
  85647. * This version allows you to supply the input data via an array of
  85648. * pointers, each pointer pointing to an array of \a samples samples
  85649. * representing one channel. The samples need not be block-aligned,
  85650. * but each channel should have the same number of samples. Each sample
  85651. * should be a signed integer, right-justified to the resolution set by
  85652. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the
  85653. * resolution is 16 bits per sample, the samples should all be in the
  85654. * range [-32768,32767].
  85655. *
  85656. * For applications where channel order is important, channels must
  85657. * follow the order as described in the
  85658. * <A HREF="../format.html#frame_header">frame header</A>.
  85659. *
  85660. * \param encoder An initialized encoder instance in the OK state.
  85661. * \param buffer An array of pointers to each channel's signal.
  85662. * \param samples The number of samples in one channel.
  85663. * \assert
  85664. * \code encoder != NULL \endcode
  85665. * \code FLAC__stream_encoder_get_state(encoder) == FLAC__STREAM_ENCODER_OK \endcode
  85666. * \retval FLAC__bool
  85667. * \c true if successful, else \c false; in this case, check the
  85668. * encoder state with FLAC__stream_encoder_get_state() to see what
  85669. * went wrong.
  85670. */
  85671. FLAC_API FLAC__bool FLAC__stream_encoder_process(FLAC__StreamEncoder *encoder, const FLAC__int32 * const buffer[], unsigned samples);
  85672. /** Submit data for encoding.
  85673. * This version allows you to supply the input data where the channels
  85674. * are interleaved into a single array (i.e. channel0_sample0,
  85675. * channel1_sample0, ... , channelN_sample0, channel0_sample1, ...).
  85676. * The samples need not be block-aligned but they must be
  85677. * sample-aligned, i.e. the first value should be channel0_sample0
  85678. * and the last value channelN_sampleM. Each sample should be a signed
  85679. * integer, right-justified to the resolution set by
  85680. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the
  85681. * resolution is 16 bits per sample, the samples should all be in the
  85682. * range [-32768,32767].
  85683. *
  85684. * For applications where channel order is important, channels must
  85685. * follow the order as described in the
  85686. * <A HREF="../format.html#frame_header">frame header</A>.
  85687. *
  85688. * \param encoder An initialized encoder instance in the OK state.
  85689. * \param buffer An array of channel-interleaved data (see above).
  85690. * \param samples The number of samples in one channel, the same as for
  85691. * FLAC__stream_encoder_process(). For example, if
  85692. * encoding two channels, \c 1000 \a samples corresponds
  85693. * to a \a buffer of 2000 values.
  85694. * \assert
  85695. * \code encoder != NULL \endcode
  85696. * \code FLAC__stream_encoder_get_state(encoder) == FLAC__STREAM_ENCODER_OK \endcode
  85697. * \retval FLAC__bool
  85698. * \c true if successful, else \c false; in this case, check the
  85699. * encoder state with FLAC__stream_encoder_get_state() to see what
  85700. * went wrong.
  85701. */
  85702. FLAC_API FLAC__bool FLAC__stream_encoder_process_interleaved(FLAC__StreamEncoder *encoder, const FLAC__int32 buffer[], unsigned samples);
  85703. /* \} */
  85704. #ifdef __cplusplus
  85705. }
  85706. #endif
  85707. #endif
  85708. /********* End of inlined file: stream_encoder.h *********/
  85709. #ifdef _MSC_VER
  85710. /* OPT: an MSVC built-in would be better */
  85711. static _inline FLAC__uint32 local_swap32_(FLAC__uint32 x)
  85712. {
  85713. x = ((x<<8)&0xFF00FF00) | ((x>>8)&0x00FF00FF);
  85714. return (x>>16) | (x<<16);
  85715. }
  85716. #endif
  85717. #if defined(_MSC_VER) && defined(_X86_)
  85718. /* OPT: an MSVC built-in would be better */
  85719. static void local_swap32_block_(FLAC__uint32 *start, FLAC__uint32 len)
  85720. {
  85721. __asm {
  85722. mov edx, start
  85723. mov ecx, len
  85724. test ecx, ecx
  85725. loop1:
  85726. jz done1
  85727. mov eax, [edx]
  85728. bswap eax
  85729. mov [edx], eax
  85730. add edx, 4
  85731. dec ecx
  85732. jmp short loop1
  85733. done1:
  85734. }
  85735. }
  85736. #endif
  85737. /** \mainpage
  85738. *
  85739. * \section intro Introduction
  85740. *
  85741. * This is the documentation for the FLAC C and C++ APIs. It is
  85742. * highly interconnected; this introduction should give you a top
  85743. * level idea of the structure and how to find the information you
  85744. * need. As a prerequisite you should have at least a basic
  85745. * knowledge of the FLAC format, documented
  85746. * <A HREF="../format.html">here</A>.
  85747. *
  85748. * \section c_api FLAC C API
  85749. *
  85750. * The FLAC C API is the interface to libFLAC, a set of structures
  85751. * describing the components of FLAC streams, and functions for
  85752. * encoding and decoding streams, as well as manipulating FLAC
  85753. * metadata in files. The public include files will be installed
  85754. * in your include area (for example /usr/include/FLAC/...).
  85755. *
  85756. * By writing a little code and linking against libFLAC, it is
  85757. * relatively easy to add FLAC support to another program. The
  85758. * library is licensed under <A HREF="../license.html">Xiph's BSD license</A>.
  85759. * Complete source code of libFLAC as well as the command-line
  85760. * encoder and plugins is available and is a useful source of
  85761. * examples.
  85762. *
  85763. * Aside from encoders and decoders, libFLAC provides a powerful
  85764. * metadata interface for manipulating metadata in FLAC files. It
  85765. * allows the user to add, delete, and modify FLAC metadata blocks
  85766. * and it can automatically take advantage of PADDING blocks to avoid
  85767. * rewriting the entire FLAC file when changing the size of the
  85768. * metadata.
  85769. *
  85770. * libFLAC usually only requires the standard C library and C math
  85771. * library. In particular, threading is not used so there is no
  85772. * dependency on a thread library. However, libFLAC does not use
  85773. * global variables and should be thread-safe.
  85774. *
  85775. * libFLAC also supports encoding to and decoding from Ogg FLAC.
  85776. * However the metadata editing interfaces currently have limited
  85777. * read-only support for Ogg FLAC files.
  85778. *
  85779. * \section cpp_api FLAC C++ API
  85780. *
  85781. * The FLAC C++ API is a set of classes that encapsulate the
  85782. * structures and functions in libFLAC. They provide slightly more
  85783. * functionality with respect to metadata but are otherwise
  85784. * equivalent. For the most part, they share the same usage as
  85785. * their counterparts in libFLAC, and the FLAC C API documentation
  85786. * can be used as a supplement. The public include files
  85787. * for the C++ API will be installed in your include area (for
  85788. * example /usr/include/FLAC++/...).
  85789. *
  85790. * libFLAC++ is also licensed under
  85791. * <A HREF="../license.html">Xiph's BSD license</A>.
  85792. *
  85793. * \section getting_started Getting Started
  85794. *
  85795. * A good starting point for learning the API is to browse through
  85796. * the <A HREF="modules.html">modules</A>. Modules are logical
  85797. * groupings of related functions or classes, which correspond roughly
  85798. * to header files or sections of header files. Each module includes a
  85799. * detailed description of the general usage of its functions or
  85800. * classes.
  85801. *
  85802. * From there you can go on to look at the documentation of
  85803. * individual functions. You can see different views of the individual
  85804. * functions through the links in top bar across this page.
  85805. *
  85806. * If you prefer a more hands-on approach, you can jump right to some
  85807. * <A HREF="../documentation_example_code.html">example code</A>.
  85808. *
  85809. * \section porting_guide Porting Guide
  85810. *
  85811. * Starting with FLAC 1.1.3 a \link porting Porting Guide \endlink
  85812. * has been introduced which gives detailed instructions on how to
  85813. * port your code to newer versions of FLAC.
  85814. *
  85815. * \section embedded_developers Embedded Developers
  85816. *
  85817. * libFLAC has grown larger over time as more functionality has been
  85818. * included, but much of it may be unnecessary for a particular embedded
  85819. * implementation. Unused parts may be pruned by some simple editing of
  85820. * src/libFLAC/Makefile.am. In general, the decoders, encoders, and
  85821. * metadata interface are all independent from each other.
  85822. *
  85823. * It is easiest to just describe the dependencies:
  85824. *
  85825. * - All modules depend on the \link flac_format Format \endlink module.
  85826. * - The decoders and encoders depend on the bitbuffer.
  85827. * - The decoder is independent of the encoder. The encoder uses the
  85828. * decoder because of the verify feature, but this can be removed if
  85829. * not needed.
  85830. * - Parts of the metadata interface require the stream decoder (but not
  85831. * the encoder).
  85832. * - Ogg support is selectable through the compile time macro
  85833. * \c FLAC__HAS_OGG.
  85834. *
  85835. * For example, if your application only requires the stream decoder, no
  85836. * encoder, and no metadata interface, you can remove the stream encoder
  85837. * and the metadata interface, which will greatly reduce the size of the
  85838. * library.
  85839. *
  85840. * Also, there are several places in the libFLAC code with comments marked
  85841. * with "OPT:" where a #define can be changed to enable code that might be
  85842. * faster on a specific platform. Experimenting with these can yield faster
  85843. * binaries.
  85844. */
  85845. /** \defgroup porting Porting Guide for New Versions
  85846. *
  85847. * This module describes differences in the library interfaces from
  85848. * version to version. It assists in the porting of code that uses
  85849. * the libraries to newer versions of FLAC.
  85850. *
  85851. * One simple facility for making porting easier that has been added
  85852. * in FLAC 1.1.3 is a set of \c #defines in \c export.h of each
  85853. * library's includes (e.g. \c include/FLAC/export.h). The
  85854. * \c #defines mirror the libraries'
  85855. * <A HREF="http://www.gnu.org/software/libtool/manual.html#Libtool-versioning">libtool version numbers</A>,
  85856. * e.g. in libFLAC there are \c FLAC_API_VERSION_CURRENT,
  85857. * \c FLAC_API_VERSION_REVISION, and \c FLAC_API_VERSION_AGE.
  85858. * These can be used to support multiple versions of an API during the
  85859. * transition phase, e.g.
  85860. *
  85861. * \code
  85862. * #if !defined(FLAC_API_VERSION_CURRENT) || FLAC_API_VERSION_CURRENT <= 7
  85863. * legacy code
  85864. * #else
  85865. * new code
  85866. * #endif
  85867. * \endcode
  85868. *
  85869. * The the source will work for multiple versions and the legacy code can
  85870. * easily be removed when the transition is complete.
  85871. *
  85872. * Another available symbol is FLAC_API_SUPPORTS_OGG_FLAC (defined in
  85873. * include/FLAC/export.h), which can be used to determine whether or not
  85874. * the library has been compiled with support for Ogg FLAC. This is
  85875. * simpler than trying to call an Ogg init function and catching the
  85876. * error.
  85877. */
  85878. /** \defgroup porting_1_1_2_to_1_1_3 Porting from FLAC 1.1.2 to 1.1.3
  85879. * \ingroup porting
  85880. *
  85881. * \brief
  85882. * This module describes porting from FLAC 1.1.2 to FLAC 1.1.3.
  85883. *
  85884. * The main change between the APIs in 1.1.2 and 1.1.3 is that they have
  85885. * been simplified. First, libOggFLAC has been merged into libFLAC and
  85886. * libOggFLAC++ has been merged into libFLAC++. Second, both the three
  85887. * decoding layers and three encoding layers have been merged into a
  85888. * single stream decoder and stream encoder. That is, the functionality
  85889. * of FLAC__SeekableStreamDecoder and FLAC__FileDecoder has been merged
  85890. * into FLAC__StreamDecoder, and FLAC__SeekableStreamEncoder and
  85891. * FLAC__FileEncoder into FLAC__StreamEncoder. Only the
  85892. * FLAC__StreamDecoder and FLAC__StreamEncoder remain. What this means
  85893. * is there is now a single API that can be used to encode or decode
  85894. * streams to/from native FLAC or Ogg FLAC and the single API can work
  85895. * on both seekable and non-seekable streams.
  85896. *
  85897. * Instead of creating an encoder or decoder of a certain layer, now the
  85898. * client will always create a FLAC__StreamEncoder or
  85899. * FLAC__StreamDecoder. The old layers are now differentiated by the
  85900. * initialization function. For example, for the decoder,
  85901. * FLAC__stream_decoder_init() has been replaced by
  85902. * FLAC__stream_decoder_init_stream(). This init function takes
  85903. * callbacks for the I/O, and the seeking callbacks are optional. This
  85904. * allows the client to use the same object for seekable and
  85905. * non-seekable streams. For decoding a FLAC file directly, the client
  85906. * can use FLAC__stream_decoder_init_file() and pass just a filename
  85907. * and fewer callbacks; most of the other callbacks are supplied
  85908. * internally. For situations where fopen()ing by filename is not
  85909. * possible (e.g. Unicode filenames on Windows) the client can instead
  85910. * open the file itself and supply the FILE* to
  85911. * FLAC__stream_decoder_init_FILE(). The init functions now returns a
  85912. * FLAC__StreamDecoderInitStatus instead of FLAC__StreamDecoderState.
  85913. * Since the callbacks and client data are now passed to the init
  85914. * function, the FLAC__stream_decoder_set_*_callback() functions and
  85915. * FLAC__stream_decoder_set_client_data() are no longer needed. The
  85916. * rest of the calls to the decoder are the same as before.
  85917. *
  85918. * There are counterpart init functions for Ogg FLAC, e.g.
  85919. * FLAC__stream_decoder_init_ogg_stream(). All the rest of the calls
  85920. * and callbacks are the same as for native FLAC.
  85921. *
  85922. * As an example, in FLAC 1.1.2 a seekable stream decoder would have
  85923. * been set up like so:
  85924. *
  85925. * \code
  85926. * FLAC__SeekableStreamDecoder *decoder = FLAC__seekable_stream_decoder_new();
  85927. * if(decoder == NULL) do_something;
  85928. * FLAC__seekable_stream_decoder_set_md5_checking(decoder, true);
  85929. * [... other settings ...]
  85930. * FLAC__seekable_stream_decoder_set_read_callback(decoder, my_read_callback);
  85931. * FLAC__seekable_stream_decoder_set_seek_callback(decoder, my_seek_callback);
  85932. * FLAC__seekable_stream_decoder_set_tell_callback(decoder, my_tell_callback);
  85933. * FLAC__seekable_stream_decoder_set_length_callback(decoder, my_length_callback);
  85934. * FLAC__seekable_stream_decoder_set_eof_callback(decoder, my_eof_callback);
  85935. * FLAC__seekable_stream_decoder_set_write_callback(decoder, my_write_callback);
  85936. * FLAC__seekable_stream_decoder_set_metadata_callback(decoder, my_metadata_callback);
  85937. * FLAC__seekable_stream_decoder_set_error_callback(decoder, my_error_callback);
  85938. * FLAC__seekable_stream_decoder_set_client_data(decoder, my_client_data);
  85939. * if(FLAC__seekable_stream_decoder_init(decoder) != FLAC__SEEKABLE_STREAM_DECODER_OK) do_something;
  85940. * \endcode
  85941. *
  85942. * In FLAC 1.1.3 it is like this:
  85943. *
  85944. * \code
  85945. * FLAC__StreamDecoder *decoder = FLAC__stream_decoder_new();
  85946. * if(decoder == NULL) do_something;
  85947. * FLAC__stream_decoder_set_md5_checking(decoder, true);
  85948. * [... other settings ...]
  85949. * if(FLAC__stream_decoder_init_stream(
  85950. * decoder,
  85951. * my_read_callback,
  85952. * my_seek_callback, // or NULL
  85953. * my_tell_callback, // or NULL
  85954. * my_length_callback, // or NULL
  85955. * my_eof_callback, // or NULL
  85956. * my_write_callback,
  85957. * my_metadata_callback, // or NULL
  85958. * my_error_callback,
  85959. * my_client_data
  85960. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  85961. * \endcode
  85962. *
  85963. * or you could do;
  85964. *
  85965. * \code
  85966. * [...]
  85967. * FILE *file = fopen("somefile.flac","rb");
  85968. * if(file == NULL) do_somthing;
  85969. * if(FLAC__stream_decoder_init_FILE(
  85970. * decoder,
  85971. * file,
  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. * or just:
  85980. *
  85981. * \code
  85982. * [...]
  85983. * if(FLAC__stream_decoder_init_file(
  85984. * decoder,
  85985. * "somefile.flac",
  85986. * my_write_callback,
  85987. * my_metadata_callback, // or NULL
  85988. * my_error_callback,
  85989. * my_client_data
  85990. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  85991. * \endcode
  85992. *
  85993. * Another small change to the decoder is in how it handles unparseable
  85994. * streams. Before, when the decoder found an unparseable stream
  85995. * (reserved for when the decoder encounters a stream from a future
  85996. * encoder that it can't parse), it changed the state to
  85997. * \c FLAC__STREAM_DECODER_UNPARSEABLE_STREAM. Now the decoder instead
  85998. * drops sync and calls the error callback with a new error code
  85999. * \c FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM. This is
  86000. * more robust. If your error callback does not discriminate on the the
  86001. * error state, your code does not need to be changed.
  86002. *
  86003. * The encoder now has a new setting:
  86004. * FLAC__stream_encoder_set_apodization(). This is for setting the
  86005. * method used to window the data before LPC analysis. You only need to
  86006. * add a call to this function if the default is not suitable. There
  86007. * are also two new convenience functions that may be useful:
  86008. * FLAC__metadata_object_cuesheet_calculate_cddb_id() and
  86009. * FLAC__metadata_get_cuesheet().
  86010. *
  86011. * The \a bytes parameter to FLAC__StreamDecoderReadCallback,
  86012. * FLAC__StreamEncoderReadCallback, and FLAC__StreamEncoderWriteCallback
  86013. * is now \c size_t instead of \c unsigned.
  86014. */
  86015. /** \defgroup porting_1_1_3_to_1_1_4 Porting from FLAC 1.1.3 to 1.1.4
  86016. * \ingroup porting
  86017. *
  86018. * \brief
  86019. * This module describes porting from FLAC 1.1.3 to FLAC 1.1.4.
  86020. *
  86021. * There were no changes to any of the interfaces from 1.1.3 to 1.1.4.
  86022. * There was a slight change in the implementation of
  86023. * FLAC__stream_encoder_set_metadata(); the function now makes a copy
  86024. * of the \a metadata array of pointers so the client no longer needs
  86025. * to maintain it after the call. The objects themselves that are
  86026. * pointed to by the array are still not copied though and must be
  86027. * maintained until the call to FLAC__stream_encoder_finish().
  86028. */
  86029. /** \defgroup porting_1_1_4_to_1_2_0 Porting from FLAC 1.1.4 to 1.2.0
  86030. * \ingroup porting
  86031. *
  86032. * \brief
  86033. * This module describes porting from FLAC 1.1.4 to FLAC 1.2.0.
  86034. *
  86035. * There were only very minor changes to the interfaces from 1.1.4 to 1.2.0.
  86036. * In libFLAC, \c FLAC__format_sample_rate_is_subset() was added.
  86037. * In libFLAC++, \c FLAC::Decoder::Stream::get_decode_position() was added.
  86038. *
  86039. * Finally, value of the constant \c FLAC__FRAME_HEADER_RESERVED_LEN
  86040. * has changed to reflect the conversion of one of the reserved bits
  86041. * into active use. It used to be \c 2 and now is \c 1. However the
  86042. * FLAC frame header length has not changed, so to skip the proper
  86043. * number of bits, use \c FLAC__FRAME_HEADER_RESERVED_LEN +
  86044. * \c FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN
  86045. */
  86046. /** \defgroup flac FLAC C API
  86047. *
  86048. * The FLAC C API is the interface to libFLAC, a set of structures
  86049. * describing the components of FLAC streams, and functions for
  86050. * encoding and decoding streams, as well as manipulating FLAC
  86051. * metadata in files.
  86052. *
  86053. * You should start with the format components as all other modules
  86054. * are dependent on it.
  86055. */
  86056. #endif
  86057. /********* End of inlined file: all.h *********/
  86058. /********* Start of inlined file: bitmath.c *********/
  86059. /********* Start of inlined file: juce_FlacHeader.h *********/
  86060. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  86061. // tasks..
  86062. #define VERSION "1.2.1"
  86063. #define FLAC__NO_DLL 1
  86064. #ifdef _MSC_VER
  86065. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  86066. #endif
  86067. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  86068. #define FLAC__SYS_DARWIN 1
  86069. #endif
  86070. /********* End of inlined file: juce_FlacHeader.h *********/
  86071. #if JUCE_USE_FLAC
  86072. #if HAVE_CONFIG_H
  86073. # include <config.h>
  86074. #endif
  86075. /********* Start of inlined file: bitmath.h *********/
  86076. #ifndef FLAC__PRIVATE__BITMATH_H
  86077. #define FLAC__PRIVATE__BITMATH_H
  86078. unsigned FLAC__bitmath_ilog2(FLAC__uint32 v);
  86079. unsigned FLAC__bitmath_ilog2_wide(FLAC__uint64 v);
  86080. unsigned FLAC__bitmath_silog2(int v);
  86081. unsigned FLAC__bitmath_silog2_wide(FLAC__int64 v);
  86082. #endif
  86083. /********* End of inlined file: bitmath.h *********/
  86084. /* An example of what FLAC__bitmath_ilog2() computes:
  86085. *
  86086. * ilog2( 0) = assertion failure
  86087. * ilog2( 1) = 0
  86088. * ilog2( 2) = 1
  86089. * ilog2( 3) = 1
  86090. * ilog2( 4) = 2
  86091. * ilog2( 5) = 2
  86092. * ilog2( 6) = 2
  86093. * ilog2( 7) = 2
  86094. * ilog2( 8) = 3
  86095. * ilog2( 9) = 3
  86096. * ilog2(10) = 3
  86097. * ilog2(11) = 3
  86098. * ilog2(12) = 3
  86099. * ilog2(13) = 3
  86100. * ilog2(14) = 3
  86101. * ilog2(15) = 3
  86102. * ilog2(16) = 4
  86103. * ilog2(17) = 4
  86104. * ilog2(18) = 4
  86105. */
  86106. unsigned FLAC__bitmath_ilog2(FLAC__uint32 v)
  86107. {
  86108. unsigned l = 0;
  86109. FLAC__ASSERT(v > 0);
  86110. while(v >>= 1)
  86111. l++;
  86112. return l;
  86113. }
  86114. unsigned FLAC__bitmath_ilog2_wide(FLAC__uint64 v)
  86115. {
  86116. unsigned l = 0;
  86117. FLAC__ASSERT(v > 0);
  86118. while(v >>= 1)
  86119. l++;
  86120. return l;
  86121. }
  86122. /* An example of what FLAC__bitmath_silog2() computes:
  86123. *
  86124. * silog2(-10) = 5
  86125. * silog2(- 9) = 5
  86126. * silog2(- 8) = 4
  86127. * silog2(- 7) = 4
  86128. * silog2(- 6) = 4
  86129. * silog2(- 5) = 4
  86130. * silog2(- 4) = 3
  86131. * silog2(- 3) = 3
  86132. * silog2(- 2) = 2
  86133. * silog2(- 1) = 2
  86134. * silog2( 0) = 0
  86135. * silog2( 1) = 2
  86136. * silog2( 2) = 3
  86137. * silog2( 3) = 3
  86138. * silog2( 4) = 4
  86139. * silog2( 5) = 4
  86140. * silog2( 6) = 4
  86141. * silog2( 7) = 4
  86142. * silog2( 8) = 5
  86143. * silog2( 9) = 5
  86144. * silog2( 10) = 5
  86145. */
  86146. unsigned FLAC__bitmath_silog2(int v)
  86147. {
  86148. while(1) {
  86149. if(v == 0) {
  86150. return 0;
  86151. }
  86152. else if(v > 0) {
  86153. unsigned l = 0;
  86154. while(v) {
  86155. l++;
  86156. v >>= 1;
  86157. }
  86158. return l+1;
  86159. }
  86160. else if(v == -1) {
  86161. return 2;
  86162. }
  86163. else {
  86164. v++;
  86165. v = -v;
  86166. }
  86167. }
  86168. }
  86169. unsigned FLAC__bitmath_silog2_wide(FLAC__int64 v)
  86170. {
  86171. while(1) {
  86172. if(v == 0) {
  86173. return 0;
  86174. }
  86175. else if(v > 0) {
  86176. unsigned l = 0;
  86177. while(v) {
  86178. l++;
  86179. v >>= 1;
  86180. }
  86181. return l+1;
  86182. }
  86183. else if(v == -1) {
  86184. return 2;
  86185. }
  86186. else {
  86187. v++;
  86188. v = -v;
  86189. }
  86190. }
  86191. }
  86192. #endif
  86193. /********* End of inlined file: bitmath.c *********/
  86194. /********* Start of inlined file: bitreader.c *********/
  86195. /********* Start of inlined file: juce_FlacHeader.h *********/
  86196. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  86197. // tasks..
  86198. #define VERSION "1.2.1"
  86199. #define FLAC__NO_DLL 1
  86200. #ifdef _MSC_VER
  86201. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  86202. #endif
  86203. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  86204. #define FLAC__SYS_DARWIN 1
  86205. #endif
  86206. /********* End of inlined file: juce_FlacHeader.h *********/
  86207. #if JUCE_USE_FLAC
  86208. #if HAVE_CONFIG_H
  86209. # include <config.h>
  86210. #endif
  86211. #include <stdlib.h> /* for malloc() */
  86212. #include <string.h> /* for memcpy(), memset() */
  86213. #ifdef _MSC_VER
  86214. #include <winsock.h> /* for ntohl() */
  86215. #elif defined FLAC__SYS_DARWIN
  86216. #include <machine/endian.h> /* for ntohl() */
  86217. #elif defined __MINGW32__
  86218. #include <winsock.h> /* for ntohl() */
  86219. #else
  86220. #include <netinet/in.h> /* for ntohl() */
  86221. #endif
  86222. /********* Start of inlined file: bitreader.h *********/
  86223. #ifndef FLAC__PRIVATE__BITREADER_H
  86224. #define FLAC__PRIVATE__BITREADER_H
  86225. #include <stdio.h> /* for FILE */
  86226. /********* Start of inlined file: cpu.h *********/
  86227. #ifndef FLAC__PRIVATE__CPU_H
  86228. #define FLAC__PRIVATE__CPU_H
  86229. #ifdef HAVE_CONFIG_H
  86230. #include <config.h>
  86231. #endif
  86232. typedef enum {
  86233. FLAC__CPUINFO_TYPE_IA32,
  86234. FLAC__CPUINFO_TYPE_PPC,
  86235. FLAC__CPUINFO_TYPE_UNKNOWN
  86236. } FLAC__CPUInfo_Type;
  86237. typedef struct {
  86238. FLAC__bool cpuid;
  86239. FLAC__bool bswap;
  86240. FLAC__bool cmov;
  86241. FLAC__bool mmx;
  86242. FLAC__bool fxsr;
  86243. FLAC__bool sse;
  86244. FLAC__bool sse2;
  86245. FLAC__bool sse3;
  86246. FLAC__bool ssse3;
  86247. FLAC__bool _3dnow;
  86248. FLAC__bool ext3dnow;
  86249. FLAC__bool extmmx;
  86250. } FLAC__CPUInfo_IA32;
  86251. typedef struct {
  86252. FLAC__bool altivec;
  86253. FLAC__bool ppc64;
  86254. } FLAC__CPUInfo_PPC;
  86255. typedef struct {
  86256. FLAC__bool use_asm;
  86257. FLAC__CPUInfo_Type type;
  86258. union {
  86259. FLAC__CPUInfo_IA32 ia32;
  86260. FLAC__CPUInfo_PPC ppc;
  86261. } data;
  86262. } FLAC__CPUInfo;
  86263. void FLAC__cpu_info(FLAC__CPUInfo *info);
  86264. #ifndef FLAC__NO_ASM
  86265. #ifdef FLAC__CPU_IA32
  86266. #ifdef FLAC__HAS_NASM
  86267. FLAC__uint32 FLAC__cpu_have_cpuid_asm_ia32(void);
  86268. void FLAC__cpu_info_asm_ia32(FLAC__uint32 *flags_edx, FLAC__uint32 *flags_ecx);
  86269. FLAC__uint32 FLAC__cpu_info_extended_amd_asm_ia32(void);
  86270. #endif
  86271. #endif
  86272. #endif
  86273. #endif
  86274. /********* End of inlined file: cpu.h *********/
  86275. /*
  86276. * opaque structure definition
  86277. */
  86278. struct FLAC__BitReader;
  86279. typedef struct FLAC__BitReader FLAC__BitReader;
  86280. typedef FLAC__bool (*FLAC__BitReaderReadCallback)(FLAC__byte buffer[], size_t *bytes, void *client_data);
  86281. /*
  86282. * construction, deletion, initialization, etc functions
  86283. */
  86284. FLAC__BitReader *FLAC__bitreader_new(void);
  86285. void FLAC__bitreader_delete(FLAC__BitReader *br);
  86286. FLAC__bool FLAC__bitreader_init(FLAC__BitReader *br, FLAC__CPUInfo cpu, FLAC__BitReaderReadCallback rcb, void *cd);
  86287. void FLAC__bitreader_free(FLAC__BitReader *br); /* does not 'free(br)' */
  86288. FLAC__bool FLAC__bitreader_clear(FLAC__BitReader *br);
  86289. void FLAC__bitreader_dump(const FLAC__BitReader *br, FILE *out);
  86290. /*
  86291. * CRC functions
  86292. */
  86293. void FLAC__bitreader_reset_read_crc16(FLAC__BitReader *br, FLAC__uint16 seed);
  86294. FLAC__uint16 FLAC__bitreader_get_read_crc16(FLAC__BitReader *br);
  86295. /*
  86296. * info functions
  86297. */
  86298. FLAC__bool FLAC__bitreader_is_consumed_byte_aligned(const FLAC__BitReader *br);
  86299. unsigned FLAC__bitreader_bits_left_for_byte_alignment(const FLAC__BitReader *br);
  86300. unsigned FLAC__bitreader_get_input_bits_unconsumed(const FLAC__BitReader *br);
  86301. /*
  86302. * read functions
  86303. */
  86304. FLAC__bool FLAC__bitreader_read_raw_uint32(FLAC__BitReader *br, FLAC__uint32 *val, unsigned bits);
  86305. FLAC__bool FLAC__bitreader_read_raw_int32(FLAC__BitReader *br, FLAC__int32 *val, unsigned bits);
  86306. FLAC__bool FLAC__bitreader_read_raw_uint64(FLAC__BitReader *br, FLAC__uint64 *val, unsigned bits);
  86307. FLAC__bool FLAC__bitreader_read_uint32_little_endian(FLAC__BitReader *br, FLAC__uint32 *val); /*only for bits=32*/
  86308. FLAC__bool FLAC__bitreader_skip_bits_no_crc(FLAC__BitReader *br, unsigned bits); /* WATCHOUT: does not CRC the skipped data! */ /*@@@@ add to unit tests */
  86309. FLAC__bool FLAC__bitreader_skip_byte_block_aligned_no_crc(FLAC__BitReader *br, unsigned nvals); /* WATCHOUT: does not CRC the read data! */
  86310. 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! */
  86311. FLAC__bool FLAC__bitreader_read_unary_unsigned(FLAC__BitReader *br, unsigned *val);
  86312. FLAC__bool FLAC__bitreader_read_rice_signed(FLAC__BitReader *br, int *val, unsigned parameter);
  86313. FLAC__bool FLAC__bitreader_read_rice_signed_block(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter);
  86314. #ifndef FLAC__NO_ASM
  86315. # ifdef FLAC__CPU_IA32
  86316. # ifdef FLAC__HAS_NASM
  86317. FLAC__bool FLAC__bitreader_read_rice_signed_block_asm_ia32_bswap(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter);
  86318. # endif
  86319. # endif
  86320. #endif
  86321. #if 0 /* UNUSED */
  86322. FLAC__bool FLAC__bitreader_read_golomb_signed(FLAC__BitReader *br, int *val, unsigned parameter);
  86323. FLAC__bool FLAC__bitreader_read_golomb_unsigned(FLAC__BitReader *br, unsigned *val, unsigned parameter);
  86324. #endif
  86325. FLAC__bool FLAC__bitreader_read_utf8_uint32(FLAC__BitReader *br, FLAC__uint32 *val, FLAC__byte *raw, unsigned *rawlen);
  86326. FLAC__bool FLAC__bitreader_read_utf8_uint64(FLAC__BitReader *br, FLAC__uint64 *val, FLAC__byte *raw, unsigned *rawlen);
  86327. FLAC__bool bitreader_read_from_client_(FLAC__BitReader *br);
  86328. #endif
  86329. /********* End of inlined file: bitreader.h *********/
  86330. /********* Start of inlined file: crc.h *********/
  86331. #ifndef FLAC__PRIVATE__CRC_H
  86332. #define FLAC__PRIVATE__CRC_H
  86333. /* 8 bit CRC generator, MSB shifted first
  86334. ** polynomial = x^8 + x^2 + x^1 + x^0
  86335. ** init = 0
  86336. */
  86337. extern FLAC__byte const FLAC__crc8_table[256];
  86338. #define FLAC__CRC8_UPDATE(data, crc) (crc) = FLAC__crc8_table[(crc) ^ (data)];
  86339. void FLAC__crc8_update(const FLAC__byte data, FLAC__uint8 *crc);
  86340. void FLAC__crc8_update_block(const FLAC__byte *data, unsigned len, FLAC__uint8 *crc);
  86341. FLAC__uint8 FLAC__crc8(const FLAC__byte *data, unsigned len);
  86342. /* 16 bit CRC generator, MSB shifted first
  86343. ** polynomial = x^16 + x^15 + x^2 + x^0
  86344. ** init = 0
  86345. */
  86346. extern unsigned FLAC__crc16_table[256];
  86347. #define FLAC__CRC16_UPDATE(data, crc) (((((crc)<<8) & 0xffff) ^ FLAC__crc16_table[((crc)>>8) ^ (data)]))
  86348. /* this alternate may be faster on some systems/compilers */
  86349. #if 0
  86350. #define FLAC__CRC16_UPDATE(data, crc) ((((crc)<<8) ^ FLAC__crc16_table[((crc)>>8) ^ (data)]) & 0xffff)
  86351. #endif
  86352. unsigned FLAC__crc16(const FLAC__byte *data, unsigned len);
  86353. #endif
  86354. /********* End of inlined file: crc.h *********/
  86355. /* Things should be fastest when this matches the machine word size */
  86356. /* WATCHOUT: if you change this you must also change the following #defines down to COUNT_ZERO_MSBS below to match */
  86357. /* WATCHOUT: there are a few places where the code will not work unless brword is >= 32 bits wide */
  86358. /* also, some sections currently only have fast versions for 4 or 8 bytes per word */
  86359. typedef FLAC__uint32 brword;
  86360. #define FLAC__BYTES_PER_WORD 4
  86361. #define FLAC__BITS_PER_WORD 32
  86362. #define FLAC__WORD_ALL_ONES ((FLAC__uint32)0xffffffff)
  86363. /* SWAP_BE_WORD_TO_HOST swaps bytes in a brword (which is always big-endian) if necessary to match host byte order */
  86364. #if WORDS_BIGENDIAN
  86365. #define SWAP_BE_WORD_TO_HOST(x) (x)
  86366. #else
  86367. #if defined (_MSC_VER) && defined (_X86_)
  86368. #define SWAP_BE_WORD_TO_HOST(x) local_swap32_(x)
  86369. #else
  86370. #define SWAP_BE_WORD_TO_HOST(x) ntohl(x)
  86371. #endif
  86372. #endif
  86373. /* counts the # of zero MSBs in a word */
  86374. #define COUNT_ZERO_MSBS(word) ( \
  86375. (word) <= 0xffff ? \
  86376. ( (word) <= 0xff? byte_to_unary_table[word] + 24 : byte_to_unary_table[(word) >> 8] + 16 ) : \
  86377. ( (word) <= 0xffffff? byte_to_unary_table[word >> 16] + 8 : byte_to_unary_table[(word) >> 24] ) \
  86378. )
  86379. /* this alternate might be slightly faster on some systems/compilers: */
  86380. #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])) )
  86381. /*
  86382. * This should be at least twice as large as the largest number of words
  86383. * required to represent any 'number' (in any encoding) you are going to
  86384. * read. With FLAC this is on the order of maybe a few hundred bits.
  86385. * If the buffer is smaller than that, the decoder won't be able to read
  86386. * in a whole number that is in a variable length encoding (e.g. Rice).
  86387. * But to be practical it should be at least 1K bytes.
  86388. *
  86389. * Increase this number to decrease the number of read callbacks, at the
  86390. * expense of using more memory. Or decrease for the reverse effect,
  86391. * keeping in mind the limit from the first paragraph. The optimal size
  86392. * also depends on the CPU cache size and other factors; some twiddling
  86393. * may be necessary to squeeze out the best performance.
  86394. */
  86395. static const unsigned FLAC__BITREADER_DEFAULT_CAPACITY = 65536u / FLAC__BITS_PER_WORD; /* in words */
  86396. static const unsigned char byte_to_unary_table[] = {
  86397. 8, 7, 6, 6, 5, 5, 5, 5, 4, 4, 4, 4, 4, 4, 4, 4,
  86398. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  86399. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  86400. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  86401. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  86402. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  86403. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  86404. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  86405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  86406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  86407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  86408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  86409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  86410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  86411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  86412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
  86413. };
  86414. #ifdef min
  86415. #undef min
  86416. #endif
  86417. #define min(x,y) ((x)<(y)?(x):(y))
  86418. #ifdef max
  86419. #undef max
  86420. #endif
  86421. #define max(x,y) ((x)>(y)?(x):(y))
  86422. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  86423. #ifdef _MSC_VER
  86424. #define FLAC__U64L(x) x
  86425. #else
  86426. #define FLAC__U64L(x) x##LLU
  86427. #endif
  86428. #ifndef FLaC__INLINE
  86429. #define FLaC__INLINE
  86430. #endif
  86431. /* WATCHOUT: assembly routines rely on the order in which these fields are declared */
  86432. struct FLAC__BitReader {
  86433. /* any partially-consumed word at the head will stay right-justified as bits are consumed from the left */
  86434. /* any incomplete word at the tail will be left-justified, and bytes from the read callback are added on the right */
  86435. brword *buffer;
  86436. unsigned capacity; /* in words */
  86437. unsigned words; /* # of completed words in buffer */
  86438. unsigned bytes; /* # of bytes in incomplete word at buffer[words] */
  86439. unsigned consumed_words; /* #words ... */
  86440. unsigned consumed_bits; /* ... + (#bits of head word) already consumed from the front of buffer */
  86441. unsigned read_crc16; /* the running frame CRC */
  86442. unsigned crc16_align; /* the number of bits in the current consumed word that should not be CRC'd */
  86443. FLAC__BitReaderReadCallback read_callback;
  86444. void *client_data;
  86445. FLAC__CPUInfo cpu_info;
  86446. };
  86447. static FLaC__INLINE void crc16_update_word_(FLAC__BitReader *br, brword word)
  86448. {
  86449. register unsigned crc = br->read_crc16;
  86450. #if FLAC__BYTES_PER_WORD == 4
  86451. switch(br->crc16_align) {
  86452. case 0: crc = FLAC__CRC16_UPDATE((unsigned)(word >> 24), crc);
  86453. case 8: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 16) & 0xff), crc);
  86454. case 16: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 8) & 0xff), crc);
  86455. case 24: br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)(word & 0xff), crc);
  86456. }
  86457. #elif FLAC__BYTES_PER_WORD == 8
  86458. switch(br->crc16_align) {
  86459. case 0: crc = FLAC__CRC16_UPDATE((unsigned)(word >> 56), crc);
  86460. case 8: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 48) & 0xff), crc);
  86461. case 16: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 40) & 0xff), crc);
  86462. case 24: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 32) & 0xff), crc);
  86463. case 32: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 24) & 0xff), crc);
  86464. case 40: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 16) & 0xff), crc);
  86465. case 48: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 8) & 0xff), crc);
  86466. case 56: br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)(word & 0xff), crc);
  86467. }
  86468. #else
  86469. for( ; br->crc16_align < FLAC__BITS_PER_WORD; br->crc16_align += 8)
  86470. crc = FLAC__CRC16_UPDATE((unsigned)((word >> (FLAC__BITS_PER_WORD-8-br->crc16_align)) & 0xff), crc);
  86471. br->read_crc16 = crc;
  86472. #endif
  86473. br->crc16_align = 0;
  86474. }
  86475. /* would be static except it needs to be called by asm routines */
  86476. FLAC__bool bitreader_read_from_client_(FLAC__BitReader *br)
  86477. {
  86478. unsigned start, end;
  86479. size_t bytes;
  86480. FLAC__byte *target;
  86481. /* first shift the unconsumed buffer data toward the front as much as possible */
  86482. if(br->consumed_words > 0) {
  86483. start = br->consumed_words;
  86484. end = br->words + (br->bytes? 1:0);
  86485. memmove(br->buffer, br->buffer+start, FLAC__BYTES_PER_WORD * (end - start));
  86486. br->words -= start;
  86487. br->consumed_words = 0;
  86488. }
  86489. /*
  86490. * set the target for reading, taking into account word alignment and endianness
  86491. */
  86492. bytes = (br->capacity - br->words) * FLAC__BYTES_PER_WORD - br->bytes;
  86493. if(bytes == 0)
  86494. return false; /* no space left, buffer is too small; see note for FLAC__BITREADER_DEFAULT_CAPACITY */
  86495. target = ((FLAC__byte*)(br->buffer+br->words)) + br->bytes;
  86496. /* before reading, if the existing reader looks like this (say brword is 32 bits wide)
  86497. * bitstream : 11 22 33 44 55 br->words=1 br->bytes=1 (partial tail word is left-justified)
  86498. * buffer[BE]: 11 22 33 44 55 ?? ?? ?? (shown layed out as bytes sequentially in memory)
  86499. * buffer[LE]: 44 33 22 11 ?? ?? ?? 55 (?? being don't-care)
  86500. * ^^-------target, bytes=3
  86501. * on LE machines, have to byteswap the odd tail word so nothing is
  86502. * overwritten:
  86503. */
  86504. #if WORDS_BIGENDIAN
  86505. #else
  86506. if(br->bytes)
  86507. br->buffer[br->words] = SWAP_BE_WORD_TO_HOST(br->buffer[br->words]);
  86508. #endif
  86509. /* now it looks like:
  86510. * bitstream : 11 22 33 44 55 br->words=1 br->bytes=1
  86511. * buffer[BE]: 11 22 33 44 55 ?? ?? ??
  86512. * buffer[LE]: 44 33 22 11 55 ?? ?? ??
  86513. * ^^-------target, bytes=3
  86514. */
  86515. /* read in the data; note that the callback may return a smaller number of bytes */
  86516. if(!br->read_callback(target, &bytes, br->client_data))
  86517. return false;
  86518. /* after reading bytes 66 77 88 99 AA BB CC DD EE FF from the client:
  86519. * bitstream : 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF
  86520. * buffer[BE]: 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF ??
  86521. * buffer[LE]: 44 33 22 11 55 66 77 88 99 AA BB CC DD EE FF ??
  86522. * now have to byteswap on LE machines:
  86523. */
  86524. #if WORDS_BIGENDIAN
  86525. #else
  86526. end = (br->words*FLAC__BYTES_PER_WORD + br->bytes + bytes + (FLAC__BYTES_PER_WORD-1)) / FLAC__BYTES_PER_WORD;
  86527. # if defined(_MSC_VER) && defined (_X86_) && (FLAC__BYTES_PER_WORD == 4)
  86528. if(br->cpu_info.type == FLAC__CPUINFO_TYPE_IA32 && br->cpu_info.data.ia32.bswap) {
  86529. start = br->words;
  86530. local_swap32_block_(br->buffer + start, end - start);
  86531. }
  86532. else
  86533. # endif
  86534. for(start = br->words; start < end; start++)
  86535. br->buffer[start] = SWAP_BE_WORD_TO_HOST(br->buffer[start]);
  86536. #endif
  86537. /* now it looks like:
  86538. * bitstream : 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF
  86539. * buffer[BE]: 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF ??
  86540. * buffer[LE]: 44 33 22 11 88 77 66 55 CC BB AA 99 ?? FF EE DD
  86541. * finally we'll update the reader values:
  86542. */
  86543. end = br->words*FLAC__BYTES_PER_WORD + br->bytes + bytes;
  86544. br->words = end / FLAC__BYTES_PER_WORD;
  86545. br->bytes = end % FLAC__BYTES_PER_WORD;
  86546. return true;
  86547. }
  86548. /***********************************************************************
  86549. *
  86550. * Class constructor/destructor
  86551. *
  86552. ***********************************************************************/
  86553. FLAC__BitReader *FLAC__bitreader_new(void)
  86554. {
  86555. FLAC__BitReader *br = (FLAC__BitReader*)calloc(1, sizeof(FLAC__BitReader));
  86556. /* calloc() implies:
  86557. memset(br, 0, sizeof(FLAC__BitReader));
  86558. br->buffer = 0;
  86559. br->capacity = 0;
  86560. br->words = br->bytes = 0;
  86561. br->consumed_words = br->consumed_bits = 0;
  86562. br->read_callback = 0;
  86563. br->client_data = 0;
  86564. */
  86565. return br;
  86566. }
  86567. void FLAC__bitreader_delete(FLAC__BitReader *br)
  86568. {
  86569. FLAC__ASSERT(0 != br);
  86570. FLAC__bitreader_free(br);
  86571. free(br);
  86572. }
  86573. /***********************************************************************
  86574. *
  86575. * Public class methods
  86576. *
  86577. ***********************************************************************/
  86578. FLAC__bool FLAC__bitreader_init(FLAC__BitReader *br, FLAC__CPUInfo cpu, FLAC__BitReaderReadCallback rcb, void *cd)
  86579. {
  86580. FLAC__ASSERT(0 != br);
  86581. br->words = br->bytes = 0;
  86582. br->consumed_words = br->consumed_bits = 0;
  86583. br->capacity = FLAC__BITREADER_DEFAULT_CAPACITY;
  86584. br->buffer = (brword*)malloc(sizeof(brword) * br->capacity);
  86585. if(br->buffer == 0)
  86586. return false;
  86587. br->read_callback = rcb;
  86588. br->client_data = cd;
  86589. br->cpu_info = cpu;
  86590. return true;
  86591. }
  86592. void FLAC__bitreader_free(FLAC__BitReader *br)
  86593. {
  86594. FLAC__ASSERT(0 != br);
  86595. if(0 != br->buffer)
  86596. free(br->buffer);
  86597. br->buffer = 0;
  86598. br->capacity = 0;
  86599. br->words = br->bytes = 0;
  86600. br->consumed_words = br->consumed_bits = 0;
  86601. br->read_callback = 0;
  86602. br->client_data = 0;
  86603. }
  86604. FLAC__bool FLAC__bitreader_clear(FLAC__BitReader *br)
  86605. {
  86606. br->words = br->bytes = 0;
  86607. br->consumed_words = br->consumed_bits = 0;
  86608. return true;
  86609. }
  86610. void FLAC__bitreader_dump(const FLAC__BitReader *br, FILE *out)
  86611. {
  86612. unsigned i, j;
  86613. if(br == 0) {
  86614. fprintf(out, "bitreader is NULL\n");
  86615. }
  86616. else {
  86617. 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);
  86618. for(i = 0; i < br->words; i++) {
  86619. fprintf(out, "%08X: ", i);
  86620. for(j = 0; j < FLAC__BITS_PER_WORD; j++)
  86621. if(i < br->consumed_words || (i == br->consumed_words && j < br->consumed_bits))
  86622. fprintf(out, ".");
  86623. else
  86624. fprintf(out, "%01u", br->buffer[i] & (1 << (FLAC__BITS_PER_WORD-j-1)) ? 1:0);
  86625. fprintf(out, "\n");
  86626. }
  86627. if(br->bytes > 0) {
  86628. fprintf(out, "%08X: ", i);
  86629. for(j = 0; j < br->bytes*8; j++)
  86630. if(i < br->consumed_words || (i == br->consumed_words && j < br->consumed_bits))
  86631. fprintf(out, ".");
  86632. else
  86633. fprintf(out, "%01u", br->buffer[i] & (1 << (br->bytes*8-j-1)) ? 1:0);
  86634. fprintf(out, "\n");
  86635. }
  86636. }
  86637. }
  86638. void FLAC__bitreader_reset_read_crc16(FLAC__BitReader *br, FLAC__uint16 seed)
  86639. {
  86640. FLAC__ASSERT(0 != br);
  86641. FLAC__ASSERT(0 != br->buffer);
  86642. FLAC__ASSERT((br->consumed_bits & 7) == 0);
  86643. br->read_crc16 = (unsigned)seed;
  86644. br->crc16_align = br->consumed_bits;
  86645. }
  86646. FLAC__uint16 FLAC__bitreader_get_read_crc16(FLAC__BitReader *br)
  86647. {
  86648. FLAC__ASSERT(0 != br);
  86649. FLAC__ASSERT(0 != br->buffer);
  86650. FLAC__ASSERT((br->consumed_bits & 7) == 0);
  86651. FLAC__ASSERT(br->crc16_align <= br->consumed_bits);
  86652. /* CRC any tail bytes in a partially-consumed word */
  86653. if(br->consumed_bits) {
  86654. const brword tail = br->buffer[br->consumed_words];
  86655. for( ; br->crc16_align < br->consumed_bits; br->crc16_align += 8)
  86656. br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)((tail >> (FLAC__BITS_PER_WORD-8-br->crc16_align)) & 0xff), br->read_crc16);
  86657. }
  86658. return br->read_crc16;
  86659. }
  86660. FLaC__INLINE FLAC__bool FLAC__bitreader_is_consumed_byte_aligned(const FLAC__BitReader *br)
  86661. {
  86662. return ((br->consumed_bits & 7) == 0);
  86663. }
  86664. FLaC__INLINE unsigned FLAC__bitreader_bits_left_for_byte_alignment(const FLAC__BitReader *br)
  86665. {
  86666. return 8 - (br->consumed_bits & 7);
  86667. }
  86668. FLaC__INLINE unsigned FLAC__bitreader_get_input_bits_unconsumed(const FLAC__BitReader *br)
  86669. {
  86670. return (br->words-br->consumed_words)*FLAC__BITS_PER_WORD + br->bytes*8 - br->consumed_bits;
  86671. }
  86672. FLaC__INLINE FLAC__bool FLAC__bitreader_read_raw_uint32(FLAC__BitReader *br, FLAC__uint32 *val, unsigned bits)
  86673. {
  86674. FLAC__ASSERT(0 != br);
  86675. FLAC__ASSERT(0 != br->buffer);
  86676. FLAC__ASSERT(bits <= 32);
  86677. FLAC__ASSERT((br->capacity*FLAC__BITS_PER_WORD) * 2 >= bits);
  86678. FLAC__ASSERT(br->consumed_words <= br->words);
  86679. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  86680. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  86681. if(bits == 0) { /* OPT: investigate if this can ever happen, maybe change to assertion */
  86682. *val = 0;
  86683. return true;
  86684. }
  86685. while((br->words-br->consumed_words)*FLAC__BITS_PER_WORD + br->bytes*8 - br->consumed_bits < bits) {
  86686. if(!bitreader_read_from_client_(br))
  86687. return false;
  86688. }
  86689. if(br->consumed_words < br->words) { /* if we've not consumed up to a partial tail word... */
  86690. /* OPT: taking out the consumed_bits==0 "else" case below might make things faster if less code allows the compiler to inline this function */
  86691. if(br->consumed_bits) {
  86692. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  86693. const unsigned n = FLAC__BITS_PER_WORD - br->consumed_bits;
  86694. const brword word = br->buffer[br->consumed_words];
  86695. if(bits < n) {
  86696. *val = (word & (FLAC__WORD_ALL_ONES >> br->consumed_bits)) >> (n-bits);
  86697. br->consumed_bits += bits;
  86698. return true;
  86699. }
  86700. *val = word & (FLAC__WORD_ALL_ONES >> br->consumed_bits);
  86701. bits -= n;
  86702. crc16_update_word_(br, word);
  86703. br->consumed_words++;
  86704. br->consumed_bits = 0;
  86705. 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 */
  86706. *val <<= bits;
  86707. *val |= (br->buffer[br->consumed_words] >> (FLAC__BITS_PER_WORD-bits));
  86708. br->consumed_bits = bits;
  86709. }
  86710. return true;
  86711. }
  86712. else {
  86713. const brword word = br->buffer[br->consumed_words];
  86714. if(bits < FLAC__BITS_PER_WORD) {
  86715. *val = word >> (FLAC__BITS_PER_WORD-bits);
  86716. br->consumed_bits = bits;
  86717. return true;
  86718. }
  86719. /* at this point 'bits' must be == FLAC__BITS_PER_WORD; because of previous assertions, it can't be larger */
  86720. *val = word;
  86721. crc16_update_word_(br, word);
  86722. br->consumed_words++;
  86723. return true;
  86724. }
  86725. }
  86726. else {
  86727. /* in this case we're starting our read at a partial tail word;
  86728. * the reader has guaranteed that we have at least 'bits' bits
  86729. * available to read, which makes this case simpler.
  86730. */
  86731. /* OPT: taking out the consumed_bits==0 "else" case below might make things faster if less code allows the compiler to inline this function */
  86732. if(br->consumed_bits) {
  86733. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  86734. FLAC__ASSERT(br->consumed_bits + bits <= br->bytes*8);
  86735. *val = (br->buffer[br->consumed_words] & (FLAC__WORD_ALL_ONES >> br->consumed_bits)) >> (FLAC__BITS_PER_WORD-br->consumed_bits-bits);
  86736. br->consumed_bits += bits;
  86737. return true;
  86738. }
  86739. else {
  86740. *val = br->buffer[br->consumed_words] >> (FLAC__BITS_PER_WORD-bits);
  86741. br->consumed_bits += bits;
  86742. return true;
  86743. }
  86744. }
  86745. }
  86746. FLAC__bool FLAC__bitreader_read_raw_int32(FLAC__BitReader *br, FLAC__int32 *val, unsigned bits)
  86747. {
  86748. /* OPT: inline raw uint32 code here, or make into a macro if possible in the .h file */
  86749. if(!FLAC__bitreader_read_raw_uint32(br, (FLAC__uint32*)val, bits))
  86750. return false;
  86751. /* sign-extend: */
  86752. *val <<= (32-bits);
  86753. *val >>= (32-bits);
  86754. return true;
  86755. }
  86756. FLAC__bool FLAC__bitreader_read_raw_uint64(FLAC__BitReader *br, FLAC__uint64 *val, unsigned bits)
  86757. {
  86758. FLAC__uint32 hi, lo;
  86759. if(bits > 32) {
  86760. if(!FLAC__bitreader_read_raw_uint32(br, &hi, bits-32))
  86761. return false;
  86762. if(!FLAC__bitreader_read_raw_uint32(br, &lo, 32))
  86763. return false;
  86764. *val = hi;
  86765. *val <<= 32;
  86766. *val |= lo;
  86767. }
  86768. else {
  86769. if(!FLAC__bitreader_read_raw_uint32(br, &lo, bits))
  86770. return false;
  86771. *val = lo;
  86772. }
  86773. return true;
  86774. }
  86775. FLaC__INLINE FLAC__bool FLAC__bitreader_read_uint32_little_endian(FLAC__BitReader *br, FLAC__uint32 *val)
  86776. {
  86777. FLAC__uint32 x8, x32 = 0;
  86778. /* this doesn't need to be that fast as currently it is only used for vorbis comments */
  86779. if(!FLAC__bitreader_read_raw_uint32(br, &x32, 8))
  86780. return false;
  86781. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  86782. return false;
  86783. x32 |= (x8 << 8);
  86784. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  86785. return false;
  86786. x32 |= (x8 << 16);
  86787. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  86788. return false;
  86789. x32 |= (x8 << 24);
  86790. *val = x32;
  86791. return true;
  86792. }
  86793. FLAC__bool FLAC__bitreader_skip_bits_no_crc(FLAC__BitReader *br, unsigned bits)
  86794. {
  86795. /*
  86796. * OPT: a faster implementation is possible but probably not that useful
  86797. * since this is only called a couple of times in the metadata readers.
  86798. */
  86799. FLAC__ASSERT(0 != br);
  86800. FLAC__ASSERT(0 != br->buffer);
  86801. if(bits > 0) {
  86802. const unsigned n = br->consumed_bits & 7;
  86803. unsigned m;
  86804. FLAC__uint32 x;
  86805. if(n != 0) {
  86806. m = min(8-n, bits);
  86807. if(!FLAC__bitreader_read_raw_uint32(br, &x, m))
  86808. return false;
  86809. bits -= m;
  86810. }
  86811. m = bits / 8;
  86812. if(m > 0) {
  86813. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(br, m))
  86814. return false;
  86815. bits %= 8;
  86816. }
  86817. if(bits > 0) {
  86818. if(!FLAC__bitreader_read_raw_uint32(br, &x, bits))
  86819. return false;
  86820. }
  86821. }
  86822. return true;
  86823. }
  86824. FLAC__bool FLAC__bitreader_skip_byte_block_aligned_no_crc(FLAC__BitReader *br, unsigned nvals)
  86825. {
  86826. FLAC__uint32 x;
  86827. FLAC__ASSERT(0 != br);
  86828. FLAC__ASSERT(0 != br->buffer);
  86829. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(br));
  86830. /* step 1: skip over partial head word to get word aligned */
  86831. while(nvals && br->consumed_bits) { /* i.e. run until we read 'nvals' bytes or we hit the end of the head word */
  86832. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  86833. return false;
  86834. nvals--;
  86835. }
  86836. if(0 == nvals)
  86837. return true;
  86838. /* step 2: skip whole words in chunks */
  86839. while(nvals >= FLAC__BYTES_PER_WORD) {
  86840. if(br->consumed_words < br->words) {
  86841. br->consumed_words++;
  86842. nvals -= FLAC__BYTES_PER_WORD;
  86843. }
  86844. else if(!bitreader_read_from_client_(br))
  86845. return false;
  86846. }
  86847. /* step 3: skip any remainder from partial tail bytes */
  86848. while(nvals) {
  86849. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  86850. return false;
  86851. nvals--;
  86852. }
  86853. return true;
  86854. }
  86855. FLAC__bool FLAC__bitreader_read_byte_block_aligned_no_crc(FLAC__BitReader *br, FLAC__byte *val, unsigned nvals)
  86856. {
  86857. FLAC__uint32 x;
  86858. FLAC__ASSERT(0 != br);
  86859. FLAC__ASSERT(0 != br->buffer);
  86860. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(br));
  86861. /* step 1: read from partial head word to get word aligned */
  86862. while(nvals && br->consumed_bits) { /* i.e. run until we read 'nvals' bytes or we hit the end of the head word */
  86863. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  86864. return false;
  86865. *val++ = (FLAC__byte)x;
  86866. nvals--;
  86867. }
  86868. if(0 == nvals)
  86869. return true;
  86870. /* step 2: read whole words in chunks */
  86871. while(nvals >= FLAC__BYTES_PER_WORD) {
  86872. if(br->consumed_words < br->words) {
  86873. const brword word = br->buffer[br->consumed_words++];
  86874. #if FLAC__BYTES_PER_WORD == 4
  86875. val[0] = (FLAC__byte)(word >> 24);
  86876. val[1] = (FLAC__byte)(word >> 16);
  86877. val[2] = (FLAC__byte)(word >> 8);
  86878. val[3] = (FLAC__byte)word;
  86879. #elif FLAC__BYTES_PER_WORD == 8
  86880. val[0] = (FLAC__byte)(word >> 56);
  86881. val[1] = (FLAC__byte)(word >> 48);
  86882. val[2] = (FLAC__byte)(word >> 40);
  86883. val[3] = (FLAC__byte)(word >> 32);
  86884. val[4] = (FLAC__byte)(word >> 24);
  86885. val[5] = (FLAC__byte)(word >> 16);
  86886. val[6] = (FLAC__byte)(word >> 8);
  86887. val[7] = (FLAC__byte)word;
  86888. #else
  86889. for(x = 0; x < FLAC__BYTES_PER_WORD; x++)
  86890. val[x] = (FLAC__byte)(word >> (8*(FLAC__BYTES_PER_WORD-x-1)));
  86891. #endif
  86892. val += FLAC__BYTES_PER_WORD;
  86893. nvals -= FLAC__BYTES_PER_WORD;
  86894. }
  86895. else if(!bitreader_read_from_client_(br))
  86896. return false;
  86897. }
  86898. /* step 3: read any remainder from partial tail bytes */
  86899. while(nvals) {
  86900. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  86901. return false;
  86902. *val++ = (FLAC__byte)x;
  86903. nvals--;
  86904. }
  86905. return true;
  86906. }
  86907. FLaC__INLINE FLAC__bool FLAC__bitreader_read_unary_unsigned(FLAC__BitReader *br, unsigned *val)
  86908. #if 0 /* slow but readable version */
  86909. {
  86910. unsigned bit;
  86911. FLAC__ASSERT(0 != br);
  86912. FLAC__ASSERT(0 != br->buffer);
  86913. *val = 0;
  86914. while(1) {
  86915. if(!FLAC__bitreader_read_bit(br, &bit))
  86916. return false;
  86917. if(bit)
  86918. break;
  86919. else
  86920. *val++;
  86921. }
  86922. return true;
  86923. }
  86924. #else
  86925. {
  86926. unsigned i;
  86927. FLAC__ASSERT(0 != br);
  86928. FLAC__ASSERT(0 != br->buffer);
  86929. *val = 0;
  86930. while(1) {
  86931. while(br->consumed_words < br->words) { /* if we've not consumed up to a partial tail word... */
  86932. brword b = br->buffer[br->consumed_words] << br->consumed_bits;
  86933. if(b) {
  86934. i = COUNT_ZERO_MSBS(b);
  86935. *val += i;
  86936. i++;
  86937. br->consumed_bits += i;
  86938. if(br->consumed_bits >= FLAC__BITS_PER_WORD) { /* faster way of testing if(br->consumed_bits == FLAC__BITS_PER_WORD) */
  86939. crc16_update_word_(br, br->buffer[br->consumed_words]);
  86940. br->consumed_words++;
  86941. br->consumed_bits = 0;
  86942. }
  86943. return true;
  86944. }
  86945. else {
  86946. *val += FLAC__BITS_PER_WORD - br->consumed_bits;
  86947. crc16_update_word_(br, br->buffer[br->consumed_words]);
  86948. br->consumed_words++;
  86949. br->consumed_bits = 0;
  86950. /* didn't find stop bit yet, have to keep going... */
  86951. }
  86952. }
  86953. /* at this point we've eaten up all the whole words; have to try
  86954. * reading through any tail bytes before calling the read callback.
  86955. * this is a repeat of the above logic adjusted for the fact we
  86956. * don't have a whole word. note though if the client is feeding
  86957. * us data a byte at a time (unlikely), br->consumed_bits may not
  86958. * be zero.
  86959. */
  86960. if(br->bytes) {
  86961. const unsigned end = br->bytes * 8;
  86962. brword b = (br->buffer[br->consumed_words] & (FLAC__WORD_ALL_ONES << (FLAC__BITS_PER_WORD-end))) << br->consumed_bits;
  86963. if(b) {
  86964. i = COUNT_ZERO_MSBS(b);
  86965. *val += i;
  86966. i++;
  86967. br->consumed_bits += i;
  86968. FLAC__ASSERT(br->consumed_bits < FLAC__BITS_PER_WORD);
  86969. return true;
  86970. }
  86971. else {
  86972. *val += end - br->consumed_bits;
  86973. br->consumed_bits += end;
  86974. FLAC__ASSERT(br->consumed_bits < FLAC__BITS_PER_WORD);
  86975. /* didn't find stop bit yet, have to keep going... */
  86976. }
  86977. }
  86978. if(!bitreader_read_from_client_(br))
  86979. return false;
  86980. }
  86981. }
  86982. #endif
  86983. FLAC__bool FLAC__bitreader_read_rice_signed(FLAC__BitReader *br, int *val, unsigned parameter)
  86984. {
  86985. FLAC__uint32 lsbs = 0, msbs = 0;
  86986. unsigned uval;
  86987. FLAC__ASSERT(0 != br);
  86988. FLAC__ASSERT(0 != br->buffer);
  86989. FLAC__ASSERT(parameter <= 31);
  86990. /* read the unary MSBs and end bit */
  86991. if(!FLAC__bitreader_read_unary_unsigned(br, (unsigned int*) &msbs))
  86992. return false;
  86993. /* read the binary LSBs */
  86994. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, parameter))
  86995. return false;
  86996. /* compose the value */
  86997. uval = (msbs << parameter) | lsbs;
  86998. if(uval & 1)
  86999. *val = -((int)(uval >> 1)) - 1;
  87000. else
  87001. *val = (int)(uval >> 1);
  87002. return true;
  87003. }
  87004. /* this is by far the most heavily used reader call. it ain't pretty but it's fast */
  87005. /* a lot of the logic is copied, then adapted, from FLAC__bitreader_read_unary_unsigned() and FLAC__bitreader_read_raw_uint32() */
  87006. FLAC__bool FLAC__bitreader_read_rice_signed_block(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter)
  87007. /* OPT: possibly faster version for use with MSVC */
  87008. #ifdef _MSC_VER
  87009. {
  87010. unsigned i;
  87011. unsigned uval = 0;
  87012. unsigned bits; /* the # of binary LSBs left to read to finish a rice codeword */
  87013. /* try and get br->consumed_words and br->consumed_bits into register;
  87014. * must remember to flush them back to *br before calling other
  87015. * bitwriter functions that use them, and before returning */
  87016. register unsigned cwords;
  87017. register unsigned cbits;
  87018. FLAC__ASSERT(0 != br);
  87019. FLAC__ASSERT(0 != br->buffer);
  87020. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  87021. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  87022. FLAC__ASSERT(parameter < 32);
  87023. /* 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 */
  87024. if(nvals == 0)
  87025. return true;
  87026. cbits = br->consumed_bits;
  87027. cwords = br->consumed_words;
  87028. while(1) {
  87029. /* read unary part */
  87030. while(1) {
  87031. while(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  87032. brword b = br->buffer[cwords] << cbits;
  87033. if(b) {
  87034. #if 0 /* slower, probably due to bad register allocation... */ && defined FLAC__CPU_IA32 && !defined FLAC__NO_ASM && FLAC__BITS_PER_WORD == 32
  87035. __asm {
  87036. bsr eax, b
  87037. not eax
  87038. and eax, 31
  87039. mov i, eax
  87040. }
  87041. #else
  87042. i = COUNT_ZERO_MSBS(b);
  87043. #endif
  87044. uval += i;
  87045. bits = parameter;
  87046. i++;
  87047. cbits += i;
  87048. if(cbits == FLAC__BITS_PER_WORD) {
  87049. crc16_update_word_(br, br->buffer[cwords]);
  87050. cwords++;
  87051. cbits = 0;
  87052. }
  87053. goto break1;
  87054. }
  87055. else {
  87056. uval += FLAC__BITS_PER_WORD - cbits;
  87057. crc16_update_word_(br, br->buffer[cwords]);
  87058. cwords++;
  87059. cbits = 0;
  87060. /* didn't find stop bit yet, have to keep going... */
  87061. }
  87062. }
  87063. /* at this point we've eaten up all the whole words; have to try
  87064. * reading through any tail bytes before calling the read callback.
  87065. * this is a repeat of the above logic adjusted for the fact we
  87066. * don't have a whole word. note though if the client is feeding
  87067. * us data a byte at a time (unlikely), br->consumed_bits may not
  87068. * be zero.
  87069. */
  87070. if(br->bytes) {
  87071. const unsigned end = br->bytes * 8;
  87072. brword b = (br->buffer[cwords] & (FLAC__WORD_ALL_ONES << (FLAC__BITS_PER_WORD-end))) << cbits;
  87073. if(b) {
  87074. i = COUNT_ZERO_MSBS(b);
  87075. uval += i;
  87076. bits = parameter;
  87077. i++;
  87078. cbits += i;
  87079. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  87080. goto break1;
  87081. }
  87082. else {
  87083. uval += end - cbits;
  87084. cbits += end;
  87085. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  87086. /* didn't find stop bit yet, have to keep going... */
  87087. }
  87088. }
  87089. /* flush registers and read; bitreader_read_from_client_() does
  87090. * not touch br->consumed_bits at all but we still need to set
  87091. * it in case it fails and we have to return false.
  87092. */
  87093. br->consumed_bits = cbits;
  87094. br->consumed_words = cwords;
  87095. if(!bitreader_read_from_client_(br))
  87096. return false;
  87097. cwords = br->consumed_words;
  87098. }
  87099. break1:
  87100. /* read binary part */
  87101. FLAC__ASSERT(cwords <= br->words);
  87102. if(bits) {
  87103. while((br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits < bits) {
  87104. /* flush registers and read; bitreader_read_from_client_() does
  87105. * not touch br->consumed_bits at all but we still need to set
  87106. * it in case it fails and we have to return false.
  87107. */
  87108. br->consumed_bits = cbits;
  87109. br->consumed_words = cwords;
  87110. if(!bitreader_read_from_client_(br))
  87111. return false;
  87112. cwords = br->consumed_words;
  87113. }
  87114. if(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  87115. if(cbits) {
  87116. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  87117. const unsigned n = FLAC__BITS_PER_WORD - cbits;
  87118. const brword word = br->buffer[cwords];
  87119. if(bits < n) {
  87120. uval <<= bits;
  87121. uval |= (word & (FLAC__WORD_ALL_ONES >> cbits)) >> (n-bits);
  87122. cbits += bits;
  87123. goto break2;
  87124. }
  87125. uval <<= n;
  87126. uval |= word & (FLAC__WORD_ALL_ONES >> cbits);
  87127. bits -= n;
  87128. crc16_update_word_(br, word);
  87129. cwords++;
  87130. cbits = 0;
  87131. 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 */
  87132. uval <<= bits;
  87133. uval |= (br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits));
  87134. cbits = bits;
  87135. }
  87136. goto break2;
  87137. }
  87138. else {
  87139. FLAC__ASSERT(bits < FLAC__BITS_PER_WORD);
  87140. uval <<= bits;
  87141. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits);
  87142. cbits = bits;
  87143. goto break2;
  87144. }
  87145. }
  87146. else {
  87147. /* in this case we're starting our read at a partial tail word;
  87148. * the reader has guaranteed that we have at least 'bits' bits
  87149. * available to read, which makes this case simpler.
  87150. */
  87151. uval <<= bits;
  87152. if(cbits) {
  87153. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  87154. FLAC__ASSERT(cbits + bits <= br->bytes*8);
  87155. uval |= (br->buffer[cwords] & (FLAC__WORD_ALL_ONES >> cbits)) >> (FLAC__BITS_PER_WORD-cbits-bits);
  87156. cbits += bits;
  87157. goto break2;
  87158. }
  87159. else {
  87160. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits);
  87161. cbits += bits;
  87162. goto break2;
  87163. }
  87164. }
  87165. }
  87166. break2:
  87167. /* compose the value */
  87168. *vals = (int)(uval >> 1 ^ -(int)(uval & 1));
  87169. /* are we done? */
  87170. --nvals;
  87171. if(nvals == 0) {
  87172. br->consumed_bits = cbits;
  87173. br->consumed_words = cwords;
  87174. return true;
  87175. }
  87176. uval = 0;
  87177. ++vals;
  87178. }
  87179. }
  87180. #else
  87181. {
  87182. unsigned i;
  87183. unsigned uval = 0;
  87184. /* try and get br->consumed_words and br->consumed_bits into register;
  87185. * must remember to flush them back to *br before calling other
  87186. * bitwriter functions that use them, and before returning */
  87187. register unsigned cwords;
  87188. register unsigned cbits;
  87189. unsigned ucbits; /* keep track of the number of unconsumed bits in the buffer */
  87190. FLAC__ASSERT(0 != br);
  87191. FLAC__ASSERT(0 != br->buffer);
  87192. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  87193. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  87194. FLAC__ASSERT(parameter < 32);
  87195. /* 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 */
  87196. if(nvals == 0)
  87197. return true;
  87198. cbits = br->consumed_bits;
  87199. cwords = br->consumed_words;
  87200. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits;
  87201. while(1) {
  87202. /* read unary part */
  87203. while(1) {
  87204. while(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  87205. brword b = br->buffer[cwords] << cbits;
  87206. if(b) {
  87207. #if 0 /* is not discernably faster... */ && defined FLAC__CPU_IA32 && !defined FLAC__NO_ASM && FLAC__BITS_PER_WORD == 32 && defined __GNUC__
  87208. asm volatile (
  87209. "bsrl %1, %0;"
  87210. "notl %0;"
  87211. "andl $31, %0;"
  87212. : "=r"(i)
  87213. : "r"(b)
  87214. );
  87215. #else
  87216. i = COUNT_ZERO_MSBS(b);
  87217. #endif
  87218. uval += i;
  87219. cbits += i;
  87220. cbits++; /* skip over stop bit */
  87221. if(cbits >= FLAC__BITS_PER_WORD) { /* faster way of testing if(cbits == FLAC__BITS_PER_WORD) */
  87222. crc16_update_word_(br, br->buffer[cwords]);
  87223. cwords++;
  87224. cbits = 0;
  87225. }
  87226. goto break1;
  87227. }
  87228. else {
  87229. uval += FLAC__BITS_PER_WORD - cbits;
  87230. crc16_update_word_(br, br->buffer[cwords]);
  87231. cwords++;
  87232. cbits = 0;
  87233. /* didn't find stop bit yet, have to keep going... */
  87234. }
  87235. }
  87236. /* at this point we've eaten up all the whole words; have to try
  87237. * reading through any tail bytes before calling the read callback.
  87238. * this is a repeat of the above logic adjusted for the fact we
  87239. * don't have a whole word. note though if the client is feeding
  87240. * us data a byte at a time (unlikely), br->consumed_bits may not
  87241. * be zero.
  87242. */
  87243. if(br->bytes) {
  87244. const unsigned end = br->bytes * 8;
  87245. brword b = (br->buffer[cwords] & ~(FLAC__WORD_ALL_ONES >> end)) << cbits;
  87246. if(b) {
  87247. i = COUNT_ZERO_MSBS(b);
  87248. uval += i;
  87249. cbits += i;
  87250. cbits++; /* skip over stop bit */
  87251. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  87252. goto break1;
  87253. }
  87254. else {
  87255. uval += end - cbits;
  87256. cbits += end;
  87257. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  87258. /* didn't find stop bit yet, have to keep going... */
  87259. }
  87260. }
  87261. /* flush registers and read; bitreader_read_from_client_() does
  87262. * not touch br->consumed_bits at all but we still need to set
  87263. * it in case it fails and we have to return false.
  87264. */
  87265. br->consumed_bits = cbits;
  87266. br->consumed_words = cwords;
  87267. if(!bitreader_read_from_client_(br))
  87268. return false;
  87269. cwords = br->consumed_words;
  87270. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits + uval;
  87271. /* + uval to offset our count by the # of unary bits already
  87272. * consumed before the read, because we will add these back
  87273. * in all at once at break1
  87274. */
  87275. }
  87276. break1:
  87277. ucbits -= uval;
  87278. ucbits--; /* account for stop bit */
  87279. /* read binary part */
  87280. FLAC__ASSERT(cwords <= br->words);
  87281. if(parameter) {
  87282. while(ucbits < parameter) {
  87283. /* flush registers and read; bitreader_read_from_client_() does
  87284. * not touch br->consumed_bits at all but we still need to set
  87285. * it in case it fails and we have to return false.
  87286. */
  87287. br->consumed_bits = cbits;
  87288. br->consumed_words = cwords;
  87289. if(!bitreader_read_from_client_(br))
  87290. return false;
  87291. cwords = br->consumed_words;
  87292. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits;
  87293. }
  87294. if(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  87295. if(cbits) {
  87296. /* this also works when consumed_bits==0, it's just slower than necessary for that case */
  87297. const unsigned n = FLAC__BITS_PER_WORD - cbits;
  87298. const brword word = br->buffer[cwords];
  87299. if(parameter < n) {
  87300. uval <<= parameter;
  87301. uval |= (word & (FLAC__WORD_ALL_ONES >> cbits)) >> (n-parameter);
  87302. cbits += parameter;
  87303. }
  87304. else {
  87305. uval <<= n;
  87306. uval |= word & (FLAC__WORD_ALL_ONES >> cbits);
  87307. crc16_update_word_(br, word);
  87308. cwords++;
  87309. cbits = parameter - n;
  87310. 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 */
  87311. uval <<= cbits;
  87312. uval |= (br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits));
  87313. }
  87314. }
  87315. }
  87316. else {
  87317. cbits = parameter;
  87318. uval <<= parameter;
  87319. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits);
  87320. }
  87321. }
  87322. else {
  87323. /* in this case we're starting our read at a partial tail word;
  87324. * the reader has guaranteed that we have at least 'parameter'
  87325. * bits available to read, which makes this case simpler.
  87326. */
  87327. uval <<= parameter;
  87328. if(cbits) {
  87329. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  87330. FLAC__ASSERT(cbits + parameter <= br->bytes*8);
  87331. uval |= (br->buffer[cwords] & (FLAC__WORD_ALL_ONES >> cbits)) >> (FLAC__BITS_PER_WORD-cbits-parameter);
  87332. cbits += parameter;
  87333. }
  87334. else {
  87335. cbits = parameter;
  87336. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits);
  87337. }
  87338. }
  87339. }
  87340. ucbits -= parameter;
  87341. /* compose the value */
  87342. *vals = (int)(uval >> 1 ^ -(int)(uval & 1));
  87343. /* are we done? */
  87344. --nvals;
  87345. if(nvals == 0) {
  87346. br->consumed_bits = cbits;
  87347. br->consumed_words = cwords;
  87348. return true;
  87349. }
  87350. uval = 0;
  87351. ++vals;
  87352. }
  87353. }
  87354. #endif
  87355. #if 0 /* UNUSED */
  87356. FLAC__bool FLAC__bitreader_read_golomb_signed(FLAC__BitReader *br, int *val, unsigned parameter)
  87357. {
  87358. FLAC__uint32 lsbs = 0, msbs = 0;
  87359. unsigned bit, uval, k;
  87360. FLAC__ASSERT(0 != br);
  87361. FLAC__ASSERT(0 != br->buffer);
  87362. k = FLAC__bitmath_ilog2(parameter);
  87363. /* read the unary MSBs and end bit */
  87364. if(!FLAC__bitreader_read_unary_unsigned(br, &msbs))
  87365. return false;
  87366. /* read the binary LSBs */
  87367. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, k))
  87368. return false;
  87369. if(parameter == 1u<<k) {
  87370. /* compose the value */
  87371. uval = (msbs << k) | lsbs;
  87372. }
  87373. else {
  87374. unsigned d = (1 << (k+1)) - parameter;
  87375. if(lsbs >= d) {
  87376. if(!FLAC__bitreader_read_bit(br, &bit))
  87377. return false;
  87378. lsbs <<= 1;
  87379. lsbs |= bit;
  87380. lsbs -= d;
  87381. }
  87382. /* compose the value */
  87383. uval = msbs * parameter + lsbs;
  87384. }
  87385. /* unfold unsigned to signed */
  87386. if(uval & 1)
  87387. *val = -((int)(uval >> 1)) - 1;
  87388. else
  87389. *val = (int)(uval >> 1);
  87390. return true;
  87391. }
  87392. FLAC__bool FLAC__bitreader_read_golomb_unsigned(FLAC__BitReader *br, unsigned *val, unsigned parameter)
  87393. {
  87394. FLAC__uint32 lsbs, msbs = 0;
  87395. unsigned bit, k;
  87396. FLAC__ASSERT(0 != br);
  87397. FLAC__ASSERT(0 != br->buffer);
  87398. k = FLAC__bitmath_ilog2(parameter);
  87399. /* read the unary MSBs and end bit */
  87400. if(!FLAC__bitreader_read_unary_unsigned(br, &msbs))
  87401. return false;
  87402. /* read the binary LSBs */
  87403. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, k))
  87404. return false;
  87405. if(parameter == 1u<<k) {
  87406. /* compose the value */
  87407. *val = (msbs << k) | lsbs;
  87408. }
  87409. else {
  87410. unsigned d = (1 << (k+1)) - parameter;
  87411. if(lsbs >= d) {
  87412. if(!FLAC__bitreader_read_bit(br, &bit))
  87413. return false;
  87414. lsbs <<= 1;
  87415. lsbs |= bit;
  87416. lsbs -= d;
  87417. }
  87418. /* compose the value */
  87419. *val = msbs * parameter + lsbs;
  87420. }
  87421. return true;
  87422. }
  87423. #endif /* UNUSED */
  87424. /* on return, if *val == 0xffffffff then the utf-8 sequence was invalid, but the return value will be true */
  87425. FLAC__bool FLAC__bitreader_read_utf8_uint32(FLAC__BitReader *br, FLAC__uint32 *val, FLAC__byte *raw, unsigned *rawlen)
  87426. {
  87427. FLAC__uint32 v = 0;
  87428. FLAC__uint32 x;
  87429. unsigned i;
  87430. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  87431. return false;
  87432. if(raw)
  87433. raw[(*rawlen)++] = (FLAC__byte)x;
  87434. if(!(x & 0x80)) { /* 0xxxxxxx */
  87435. v = x;
  87436. i = 0;
  87437. }
  87438. else if(x & 0xC0 && !(x & 0x20)) { /* 110xxxxx */
  87439. v = x & 0x1F;
  87440. i = 1;
  87441. }
  87442. else if(x & 0xE0 && !(x & 0x10)) { /* 1110xxxx */
  87443. v = x & 0x0F;
  87444. i = 2;
  87445. }
  87446. else if(x & 0xF0 && !(x & 0x08)) { /* 11110xxx */
  87447. v = x & 0x07;
  87448. i = 3;
  87449. }
  87450. else if(x & 0xF8 && !(x & 0x04)) { /* 111110xx */
  87451. v = x & 0x03;
  87452. i = 4;
  87453. }
  87454. else if(x & 0xFC && !(x & 0x02)) { /* 1111110x */
  87455. v = x & 0x01;
  87456. i = 5;
  87457. }
  87458. else {
  87459. *val = 0xffffffff;
  87460. return true;
  87461. }
  87462. for( ; i; i--) {
  87463. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  87464. return false;
  87465. if(raw)
  87466. raw[(*rawlen)++] = (FLAC__byte)x;
  87467. if(!(x & 0x80) || (x & 0x40)) { /* 10xxxxxx */
  87468. *val = 0xffffffff;
  87469. return true;
  87470. }
  87471. v <<= 6;
  87472. v |= (x & 0x3F);
  87473. }
  87474. *val = v;
  87475. return true;
  87476. }
  87477. /* on return, if *val == 0xffffffffffffffff then the utf-8 sequence was invalid, but the return value will be true */
  87478. FLAC__bool FLAC__bitreader_read_utf8_uint64(FLAC__BitReader *br, FLAC__uint64 *val, FLAC__byte *raw, unsigned *rawlen)
  87479. {
  87480. FLAC__uint64 v = 0;
  87481. FLAC__uint32 x;
  87482. unsigned i;
  87483. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  87484. return false;
  87485. if(raw)
  87486. raw[(*rawlen)++] = (FLAC__byte)x;
  87487. if(!(x & 0x80)) { /* 0xxxxxxx */
  87488. v = x;
  87489. i = 0;
  87490. }
  87491. else if(x & 0xC0 && !(x & 0x20)) { /* 110xxxxx */
  87492. v = x & 0x1F;
  87493. i = 1;
  87494. }
  87495. else if(x & 0xE0 && !(x & 0x10)) { /* 1110xxxx */
  87496. v = x & 0x0F;
  87497. i = 2;
  87498. }
  87499. else if(x & 0xF0 && !(x & 0x08)) { /* 11110xxx */
  87500. v = x & 0x07;
  87501. i = 3;
  87502. }
  87503. else if(x & 0xF8 && !(x & 0x04)) { /* 111110xx */
  87504. v = x & 0x03;
  87505. i = 4;
  87506. }
  87507. else if(x & 0xFC && !(x & 0x02)) { /* 1111110x */
  87508. v = x & 0x01;
  87509. i = 5;
  87510. }
  87511. else if(x & 0xFE && !(x & 0x01)) { /* 11111110 */
  87512. v = 0;
  87513. i = 6;
  87514. }
  87515. else {
  87516. *val = FLAC__U64L(0xffffffffffffffff);
  87517. return true;
  87518. }
  87519. for( ; i; i--) {
  87520. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  87521. return false;
  87522. if(raw)
  87523. raw[(*rawlen)++] = (FLAC__byte)x;
  87524. if(!(x & 0x80) || (x & 0x40)) { /* 10xxxxxx */
  87525. *val = FLAC__U64L(0xffffffffffffffff);
  87526. return true;
  87527. }
  87528. v <<= 6;
  87529. v |= (x & 0x3F);
  87530. }
  87531. *val = v;
  87532. return true;
  87533. }
  87534. #endif
  87535. /********* End of inlined file: bitreader.c *********/
  87536. /********* Start of inlined file: bitwriter.c *********/
  87537. /********* Start of inlined file: juce_FlacHeader.h *********/
  87538. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  87539. // tasks..
  87540. #define VERSION "1.2.1"
  87541. #define FLAC__NO_DLL 1
  87542. #ifdef _MSC_VER
  87543. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  87544. #endif
  87545. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  87546. #define FLAC__SYS_DARWIN 1
  87547. #endif
  87548. /********* End of inlined file: juce_FlacHeader.h *********/
  87549. #if JUCE_USE_FLAC
  87550. #if HAVE_CONFIG_H
  87551. # include <config.h>
  87552. #endif
  87553. #include <stdlib.h> /* for malloc() */
  87554. #include <string.h> /* for memcpy(), memset() */
  87555. #ifdef _MSC_VER
  87556. #include <winsock.h> /* for ntohl() */
  87557. #elif defined FLAC__SYS_DARWIN
  87558. #include <machine/endian.h> /* for ntohl() */
  87559. #elif defined __MINGW32__
  87560. #include <winsock.h> /* for ntohl() */
  87561. #else
  87562. #include <netinet/in.h> /* for ntohl() */
  87563. #endif
  87564. #if 0 /* UNUSED */
  87565. #endif
  87566. /********* Start of inlined file: bitwriter.h *********/
  87567. #ifndef FLAC__PRIVATE__BITWRITER_H
  87568. #define FLAC__PRIVATE__BITWRITER_H
  87569. #include <stdio.h> /* for FILE */
  87570. /*
  87571. * opaque structure definition
  87572. */
  87573. struct FLAC__BitWriter;
  87574. typedef struct FLAC__BitWriter FLAC__BitWriter;
  87575. /*
  87576. * construction, deletion, initialization, etc functions
  87577. */
  87578. FLAC__BitWriter *FLAC__bitwriter_new(void);
  87579. void FLAC__bitwriter_delete(FLAC__BitWriter *bw);
  87580. FLAC__bool FLAC__bitwriter_init(FLAC__BitWriter *bw);
  87581. void FLAC__bitwriter_free(FLAC__BitWriter *bw); /* does not 'free(buffer)' */
  87582. void FLAC__bitwriter_clear(FLAC__BitWriter *bw);
  87583. void FLAC__bitwriter_dump(const FLAC__BitWriter *bw, FILE *out);
  87584. /*
  87585. * CRC functions
  87586. *
  87587. * non-const *bw because they have to cal FLAC__bitwriter_get_buffer()
  87588. */
  87589. FLAC__bool FLAC__bitwriter_get_write_crc16(FLAC__BitWriter *bw, FLAC__uint16 *crc);
  87590. FLAC__bool FLAC__bitwriter_get_write_crc8(FLAC__BitWriter *bw, FLAC__byte *crc);
  87591. /*
  87592. * info functions
  87593. */
  87594. FLAC__bool FLAC__bitwriter_is_byte_aligned(const FLAC__BitWriter *bw);
  87595. unsigned FLAC__bitwriter_get_input_bits_unconsumed(const FLAC__BitWriter *bw); /* can be called anytime, returns total # of bits unconsumed */
  87596. /*
  87597. * direct buffer access
  87598. *
  87599. * there may be no calls on the bitwriter between get and release.
  87600. * the bitwriter continues to own the returned buffer.
  87601. * before get, bitwriter MUST be byte aligned: check with FLAC__bitwriter_is_byte_aligned()
  87602. */
  87603. FLAC__bool FLAC__bitwriter_get_buffer(FLAC__BitWriter *bw, const FLAC__byte **buffer, size_t *bytes);
  87604. void FLAC__bitwriter_release_buffer(FLAC__BitWriter *bw);
  87605. /*
  87606. * write functions
  87607. */
  87608. FLAC__bool FLAC__bitwriter_write_zeroes(FLAC__BitWriter *bw, unsigned bits);
  87609. FLAC__bool FLAC__bitwriter_write_raw_uint32(FLAC__BitWriter *bw, FLAC__uint32 val, unsigned bits);
  87610. FLAC__bool FLAC__bitwriter_write_raw_int32(FLAC__BitWriter *bw, FLAC__int32 val, unsigned bits);
  87611. FLAC__bool FLAC__bitwriter_write_raw_uint64(FLAC__BitWriter *bw, FLAC__uint64 val, unsigned bits);
  87612. FLAC__bool FLAC__bitwriter_write_raw_uint32_little_endian(FLAC__BitWriter *bw, FLAC__uint32 val); /*only for bits=32*/
  87613. FLAC__bool FLAC__bitwriter_write_byte_block(FLAC__BitWriter *bw, const FLAC__byte vals[], unsigned nvals);
  87614. FLAC__bool FLAC__bitwriter_write_unary_unsigned(FLAC__BitWriter *bw, unsigned val);
  87615. unsigned FLAC__bitwriter_rice_bits(FLAC__int32 val, unsigned parameter);
  87616. #if 0 /* UNUSED */
  87617. unsigned FLAC__bitwriter_golomb_bits_signed(int val, unsigned parameter);
  87618. unsigned FLAC__bitwriter_golomb_bits_unsigned(unsigned val, unsigned parameter);
  87619. #endif
  87620. FLAC__bool FLAC__bitwriter_write_rice_signed(FLAC__BitWriter *bw, FLAC__int32 val, unsigned parameter);
  87621. FLAC__bool FLAC__bitwriter_write_rice_signed_block(FLAC__BitWriter *bw, const FLAC__int32 *vals, unsigned nvals, unsigned parameter);
  87622. #if 0 /* UNUSED */
  87623. FLAC__bool FLAC__bitwriter_write_golomb_signed(FLAC__BitWriter *bw, int val, unsigned parameter);
  87624. FLAC__bool FLAC__bitwriter_write_golomb_unsigned(FLAC__BitWriter *bw, unsigned val, unsigned parameter);
  87625. #endif
  87626. FLAC__bool FLAC__bitwriter_write_utf8_uint32(FLAC__BitWriter *bw, FLAC__uint32 val);
  87627. FLAC__bool FLAC__bitwriter_write_utf8_uint64(FLAC__BitWriter *bw, FLAC__uint64 val);
  87628. FLAC__bool FLAC__bitwriter_zero_pad_to_byte_boundary(FLAC__BitWriter *bw);
  87629. #endif
  87630. /********* End of inlined file: bitwriter.h *********/
  87631. /********* Start of inlined file: alloc.h *********/
  87632. #ifndef FLAC__SHARE__ALLOC_H
  87633. #define FLAC__SHARE__ALLOC_H
  87634. #if HAVE_CONFIG_H
  87635. # include <config.h>
  87636. #endif
  87637. /* WATCHOUT: for c++ you may have to #define __STDC_LIMIT_MACROS 1 real early
  87638. * before #including this file, otherwise SIZE_MAX might not be defined
  87639. */
  87640. #include <limits.h> /* for SIZE_MAX */
  87641. #if !defined _MSC_VER && !defined __MINGW32__ && !defined __EMX__
  87642. #include <stdint.h> /* for SIZE_MAX in case limits.h didn't get it */
  87643. #endif
  87644. #include <stdlib.h> /* for size_t, malloc(), etc */
  87645. #ifndef SIZE_MAX
  87646. # ifndef SIZE_T_MAX
  87647. # ifdef _MSC_VER
  87648. # define SIZE_T_MAX UINT_MAX
  87649. # else
  87650. # error
  87651. # endif
  87652. # endif
  87653. # define SIZE_MAX SIZE_T_MAX
  87654. #endif
  87655. #ifndef FLaC__INLINE
  87656. #define FLaC__INLINE
  87657. #endif
  87658. /* avoid malloc()ing 0 bytes, see:
  87659. * https://www.securecoding.cert.org/confluence/display/seccode/MEM04-A.+Do+not+make+assumptions+about+the+result+of+allocating+0+bytes?focusedCommentId=5407003
  87660. */
  87661. static FLaC__INLINE void *safe_malloc_(size_t size)
  87662. {
  87663. /* malloc(0) is undefined; FLAC src convention is to always allocate */
  87664. if(!size)
  87665. size++;
  87666. return malloc(size);
  87667. }
  87668. static FLaC__INLINE void *safe_calloc_(size_t nmemb, size_t size)
  87669. {
  87670. if(!nmemb || !size)
  87671. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  87672. return calloc(nmemb, size);
  87673. }
  87674. /*@@@@ there's probably a better way to prevent overflows when allocating untrusted sums but this works for now */
  87675. static FLaC__INLINE void *safe_malloc_add_2op_(size_t size1, size_t size2)
  87676. {
  87677. size2 += size1;
  87678. if(size2 < size1)
  87679. return 0;
  87680. return safe_malloc_(size2);
  87681. }
  87682. static FLaC__INLINE void *safe_malloc_add_3op_(size_t size1, size_t size2, size_t size3)
  87683. {
  87684. size2 += size1;
  87685. if(size2 < size1)
  87686. return 0;
  87687. size3 += size2;
  87688. if(size3 < size2)
  87689. return 0;
  87690. return safe_malloc_(size3);
  87691. }
  87692. static FLaC__INLINE void *safe_malloc_add_4op_(size_t size1, size_t size2, size_t size3, size_t size4)
  87693. {
  87694. size2 += size1;
  87695. if(size2 < size1)
  87696. return 0;
  87697. size3 += size2;
  87698. if(size3 < size2)
  87699. return 0;
  87700. size4 += size3;
  87701. if(size4 < size3)
  87702. return 0;
  87703. return safe_malloc_(size4);
  87704. }
  87705. static FLaC__INLINE void *safe_malloc_mul_2op_(size_t size1, size_t size2)
  87706. #if 0
  87707. needs support for cases where sizeof(size_t) != 4
  87708. {
  87709. /* could be faster #ifdef'ing off SIZEOF_SIZE_T */
  87710. if(sizeof(size_t) == 4) {
  87711. if ((double)size1 * (double)size2 < 4294967296.0)
  87712. return malloc(size1*size2);
  87713. }
  87714. return 0;
  87715. }
  87716. #else
  87717. /* better? */
  87718. {
  87719. if(!size1 || !size2)
  87720. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  87721. if(size1 > SIZE_MAX / size2)
  87722. return 0;
  87723. return malloc(size1*size2);
  87724. }
  87725. #endif
  87726. static FLaC__INLINE void *safe_malloc_mul_3op_(size_t size1, size_t size2, size_t size3)
  87727. {
  87728. if(!size1 || !size2 || !size3)
  87729. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  87730. if(size1 > SIZE_MAX / size2)
  87731. return 0;
  87732. size1 *= size2;
  87733. if(size1 > SIZE_MAX / size3)
  87734. return 0;
  87735. return malloc(size1*size3);
  87736. }
  87737. /* size1*size2 + size3 */
  87738. static FLaC__INLINE void *safe_malloc_mul2add_(size_t size1, size_t size2, size_t size3)
  87739. {
  87740. if(!size1 || !size2)
  87741. return safe_malloc_(size3);
  87742. if(size1 > SIZE_MAX / size2)
  87743. return 0;
  87744. return safe_malloc_add_2op_(size1*size2, size3);
  87745. }
  87746. /* size1 * (size2 + size3) */
  87747. static FLaC__INLINE void *safe_malloc_muladd2_(size_t size1, size_t size2, size_t size3)
  87748. {
  87749. if(!size1 || (!size2 && !size3))
  87750. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  87751. size2 += size3;
  87752. if(size2 < size3)
  87753. return 0;
  87754. return safe_malloc_mul_2op_(size1, size2);
  87755. }
  87756. static FLaC__INLINE void *safe_realloc_add_2op_(void *ptr, size_t size1, size_t size2)
  87757. {
  87758. size2 += size1;
  87759. if(size2 < size1)
  87760. return 0;
  87761. return realloc(ptr, size2);
  87762. }
  87763. static FLaC__INLINE void *safe_realloc_add_3op_(void *ptr, size_t size1, size_t size2, size_t size3)
  87764. {
  87765. size2 += size1;
  87766. if(size2 < size1)
  87767. return 0;
  87768. size3 += size2;
  87769. if(size3 < size2)
  87770. return 0;
  87771. return realloc(ptr, size3);
  87772. }
  87773. static FLaC__INLINE void *safe_realloc_add_4op_(void *ptr, size_t size1, size_t size2, size_t size3, size_t size4)
  87774. {
  87775. size2 += size1;
  87776. if(size2 < size1)
  87777. return 0;
  87778. size3 += size2;
  87779. if(size3 < size2)
  87780. return 0;
  87781. size4 += size3;
  87782. if(size4 < size3)
  87783. return 0;
  87784. return realloc(ptr, size4);
  87785. }
  87786. static FLaC__INLINE void *safe_realloc_mul_2op_(void *ptr, size_t size1, size_t size2)
  87787. {
  87788. if(!size1 || !size2)
  87789. return realloc(ptr, 0); /* preserve POSIX realloc(ptr, 0) semantics */
  87790. if(size1 > SIZE_MAX / size2)
  87791. return 0;
  87792. return realloc(ptr, size1*size2);
  87793. }
  87794. /* size1 * (size2 + size3) */
  87795. static FLaC__INLINE void *safe_realloc_muladd2_(void *ptr, size_t size1, size_t size2, size_t size3)
  87796. {
  87797. if(!size1 || (!size2 && !size3))
  87798. return realloc(ptr, 0); /* preserve POSIX realloc(ptr, 0) semantics */
  87799. size2 += size3;
  87800. if(size2 < size3)
  87801. return 0;
  87802. return safe_realloc_mul_2op_(ptr, size1, size2);
  87803. }
  87804. #endif
  87805. /********* End of inlined file: alloc.h *********/
  87806. /* Things should be fastest when this matches the machine word size */
  87807. /* WATCHOUT: if you change this you must also change the following #defines down to SWAP_BE_WORD_TO_HOST below to match */
  87808. /* WATCHOUT: there are a few places where the code will not work unless bwword is >= 32 bits wide */
  87809. typedef FLAC__uint32 bwword;
  87810. #define FLAC__BYTES_PER_WORD 4
  87811. #define FLAC__BITS_PER_WORD 32
  87812. #define FLAC__WORD_ALL_ONES ((FLAC__uint32)0xffffffff)
  87813. /* SWAP_BE_WORD_TO_HOST swaps bytes in a bwword (which is always big-endian) if necessary to match host byte order */
  87814. #if WORDS_BIGENDIAN
  87815. #define SWAP_BE_WORD_TO_HOST(x) (x)
  87816. #else
  87817. #ifdef _MSC_VER
  87818. #define SWAP_BE_WORD_TO_HOST(x) local_swap32_(x)
  87819. #else
  87820. #define SWAP_BE_WORD_TO_HOST(x) ntohl(x)
  87821. #endif
  87822. #endif
  87823. /*
  87824. * The default capacity here doesn't matter too much. The buffer always grows
  87825. * to hold whatever is written to it. Usually the encoder will stop adding at
  87826. * a frame or metadata block, then write that out and clear the buffer for the
  87827. * next one.
  87828. */
  87829. static const unsigned FLAC__BITWRITER_DEFAULT_CAPACITY = 32768u / sizeof(bwword); /* size in words */
  87830. /* When growing, increment 4K at a time */
  87831. static const unsigned FLAC__BITWRITER_DEFAULT_INCREMENT = 4096u / sizeof(bwword); /* size in words */
  87832. #define FLAC__WORDS_TO_BITS(words) ((words) * FLAC__BITS_PER_WORD)
  87833. #define FLAC__TOTAL_BITS(bw) (FLAC__WORDS_TO_BITS((bw)->words) + (bw)->bits)
  87834. #ifdef min
  87835. #undef min
  87836. #endif
  87837. #define min(x,y) ((x)<(y)?(x):(y))
  87838. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  87839. #ifdef _MSC_VER
  87840. #define FLAC__U64L(x) x
  87841. #else
  87842. #define FLAC__U64L(x) x##LLU
  87843. #endif
  87844. #ifndef FLaC__INLINE
  87845. #define FLaC__INLINE
  87846. #endif
  87847. struct FLAC__BitWriter {
  87848. bwword *buffer;
  87849. bwword accum; /* accumulator; bits are right-justified; when full, accum is appended to buffer */
  87850. unsigned capacity; /* capacity of buffer in words */
  87851. unsigned words; /* # of complete words in buffer */
  87852. unsigned bits; /* # of used bits in accum */
  87853. };
  87854. /* * WATCHOUT: The current implementation only grows the buffer. */
  87855. static FLAC__bool bitwriter_grow_(FLAC__BitWriter *bw, unsigned bits_to_add)
  87856. {
  87857. unsigned new_capacity;
  87858. bwword *new_buffer;
  87859. FLAC__ASSERT(0 != bw);
  87860. FLAC__ASSERT(0 != bw->buffer);
  87861. /* calculate total words needed to store 'bits_to_add' additional bits */
  87862. new_capacity = bw->words + ((bw->bits + bits_to_add + FLAC__BITS_PER_WORD - 1) / FLAC__BITS_PER_WORD);
  87863. /* it's possible (due to pessimism in the growth estimation that
  87864. * leads to this call) that we don't actually need to grow
  87865. */
  87866. if(bw->capacity >= new_capacity)
  87867. return true;
  87868. /* round up capacity increase to the nearest FLAC__BITWRITER_DEFAULT_INCREMENT */
  87869. if((new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT)
  87870. new_capacity += FLAC__BITWRITER_DEFAULT_INCREMENT - ((new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT);
  87871. /* make sure we got everything right */
  87872. FLAC__ASSERT(0 == (new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT);
  87873. FLAC__ASSERT(new_capacity > bw->capacity);
  87874. FLAC__ASSERT(new_capacity >= bw->words + ((bw->bits + bits_to_add + FLAC__BITS_PER_WORD - 1) / FLAC__BITS_PER_WORD));
  87875. new_buffer = (bwword*)safe_realloc_mul_2op_(bw->buffer, sizeof(bwword), /*times*/new_capacity);
  87876. if(new_buffer == 0)
  87877. return false;
  87878. bw->buffer = new_buffer;
  87879. bw->capacity = new_capacity;
  87880. return true;
  87881. }
  87882. /***********************************************************************
  87883. *
  87884. * Class constructor/destructor
  87885. *
  87886. ***********************************************************************/
  87887. FLAC__BitWriter *FLAC__bitwriter_new(void)
  87888. {
  87889. FLAC__BitWriter *bw = (FLAC__BitWriter*)calloc(1, sizeof(FLAC__BitWriter));
  87890. /* note that calloc() sets all members to 0 for us */
  87891. return bw;
  87892. }
  87893. void FLAC__bitwriter_delete(FLAC__BitWriter *bw)
  87894. {
  87895. FLAC__ASSERT(0 != bw);
  87896. FLAC__bitwriter_free(bw);
  87897. free(bw);
  87898. }
  87899. /***********************************************************************
  87900. *
  87901. * Public class methods
  87902. *
  87903. ***********************************************************************/
  87904. FLAC__bool FLAC__bitwriter_init(FLAC__BitWriter *bw)
  87905. {
  87906. FLAC__ASSERT(0 != bw);
  87907. bw->words = bw->bits = 0;
  87908. bw->capacity = FLAC__BITWRITER_DEFAULT_CAPACITY;
  87909. bw->buffer = (bwword*)malloc(sizeof(bwword) * bw->capacity);
  87910. if(bw->buffer == 0)
  87911. return false;
  87912. return true;
  87913. }
  87914. void FLAC__bitwriter_free(FLAC__BitWriter *bw)
  87915. {
  87916. FLAC__ASSERT(0 != bw);
  87917. if(0 != bw->buffer)
  87918. free(bw->buffer);
  87919. bw->buffer = 0;
  87920. bw->capacity = 0;
  87921. bw->words = bw->bits = 0;
  87922. }
  87923. void FLAC__bitwriter_clear(FLAC__BitWriter *bw)
  87924. {
  87925. bw->words = bw->bits = 0;
  87926. }
  87927. void FLAC__bitwriter_dump(const FLAC__BitWriter *bw, FILE *out)
  87928. {
  87929. unsigned i, j;
  87930. if(bw == 0) {
  87931. fprintf(out, "bitwriter is NULL\n");
  87932. }
  87933. else {
  87934. fprintf(out, "bitwriter: capacity=%u words=%u bits=%u total_bits=%u\n", bw->capacity, bw->words, bw->bits, FLAC__TOTAL_BITS(bw));
  87935. for(i = 0; i < bw->words; i++) {
  87936. fprintf(out, "%08X: ", i);
  87937. for(j = 0; j < FLAC__BITS_PER_WORD; j++)
  87938. fprintf(out, "%01u", bw->buffer[i] & (1 << (FLAC__BITS_PER_WORD-j-1)) ? 1:0);
  87939. fprintf(out, "\n");
  87940. }
  87941. if(bw->bits > 0) {
  87942. fprintf(out, "%08X: ", i);
  87943. for(j = 0; j < bw->bits; j++)
  87944. fprintf(out, "%01u", bw->accum & (1 << (bw->bits-j-1)) ? 1:0);
  87945. fprintf(out, "\n");
  87946. }
  87947. }
  87948. }
  87949. FLAC__bool FLAC__bitwriter_get_write_crc16(FLAC__BitWriter *bw, FLAC__uint16 *crc)
  87950. {
  87951. const FLAC__byte *buffer;
  87952. size_t bytes;
  87953. FLAC__ASSERT((bw->bits & 7) == 0); /* assert that we're byte-aligned */
  87954. if(!FLAC__bitwriter_get_buffer(bw, &buffer, &bytes))
  87955. return false;
  87956. *crc = (FLAC__uint16)FLAC__crc16(buffer, bytes);
  87957. FLAC__bitwriter_release_buffer(bw);
  87958. return true;
  87959. }
  87960. FLAC__bool FLAC__bitwriter_get_write_crc8(FLAC__BitWriter *bw, FLAC__byte *crc)
  87961. {
  87962. const FLAC__byte *buffer;
  87963. size_t bytes;
  87964. FLAC__ASSERT((bw->bits & 7) == 0); /* assert that we're byte-aligned */
  87965. if(!FLAC__bitwriter_get_buffer(bw, &buffer, &bytes))
  87966. return false;
  87967. *crc = FLAC__crc8(buffer, bytes);
  87968. FLAC__bitwriter_release_buffer(bw);
  87969. return true;
  87970. }
  87971. FLAC__bool FLAC__bitwriter_is_byte_aligned(const FLAC__BitWriter *bw)
  87972. {
  87973. return ((bw->bits & 7) == 0);
  87974. }
  87975. unsigned FLAC__bitwriter_get_input_bits_unconsumed(const FLAC__BitWriter *bw)
  87976. {
  87977. return FLAC__TOTAL_BITS(bw);
  87978. }
  87979. FLAC__bool FLAC__bitwriter_get_buffer(FLAC__BitWriter *bw, const FLAC__byte **buffer, size_t *bytes)
  87980. {
  87981. FLAC__ASSERT((bw->bits & 7) == 0);
  87982. /* double protection */
  87983. if(bw->bits & 7)
  87984. return false;
  87985. /* if we have bits in the accumulator we have to flush those to the buffer first */
  87986. if(bw->bits) {
  87987. FLAC__ASSERT(bw->words <= bw->capacity);
  87988. if(bw->words == bw->capacity && !bitwriter_grow_(bw, FLAC__BITS_PER_WORD))
  87989. return false;
  87990. /* append bits as complete word to buffer, but don't change bw->accum or bw->bits */
  87991. bw->buffer[bw->words] = SWAP_BE_WORD_TO_HOST(bw->accum << (FLAC__BITS_PER_WORD-bw->bits));
  87992. }
  87993. /* now we can just return what we have */
  87994. *buffer = (FLAC__byte*)bw->buffer;
  87995. *bytes = (FLAC__BYTES_PER_WORD * bw->words) + (bw->bits >> 3);
  87996. return true;
  87997. }
  87998. void FLAC__bitwriter_release_buffer(FLAC__BitWriter *bw)
  87999. {
  88000. /* nothing to do. in the future, strict checking of a 'writer-is-in-
  88001. * get-mode' flag could be added everywhere and then cleared here
  88002. */
  88003. (void)bw;
  88004. }
  88005. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_zeroes(FLAC__BitWriter *bw, unsigned bits)
  88006. {
  88007. unsigned n;
  88008. FLAC__ASSERT(0 != bw);
  88009. FLAC__ASSERT(0 != bw->buffer);
  88010. if(bits == 0)
  88011. return true;
  88012. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+bits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  88013. if(bw->capacity <= bw->words + bits && !bitwriter_grow_(bw, bits))
  88014. return false;
  88015. /* first part gets to word alignment */
  88016. if(bw->bits) {
  88017. n = min(FLAC__BITS_PER_WORD - bw->bits, bits);
  88018. bw->accum <<= n;
  88019. bits -= n;
  88020. bw->bits += n;
  88021. if(bw->bits == FLAC__BITS_PER_WORD) {
  88022. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  88023. bw->bits = 0;
  88024. }
  88025. else
  88026. return true;
  88027. }
  88028. /* do whole words */
  88029. while(bits >= FLAC__BITS_PER_WORD) {
  88030. bw->buffer[bw->words++] = 0;
  88031. bits -= FLAC__BITS_PER_WORD;
  88032. }
  88033. /* do any leftovers */
  88034. if(bits > 0) {
  88035. bw->accum = 0;
  88036. bw->bits = bits;
  88037. }
  88038. return true;
  88039. }
  88040. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint32(FLAC__BitWriter *bw, FLAC__uint32 val, unsigned bits)
  88041. {
  88042. register unsigned left;
  88043. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  88044. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  88045. FLAC__ASSERT(0 != bw);
  88046. FLAC__ASSERT(0 != bw->buffer);
  88047. FLAC__ASSERT(bits <= 32);
  88048. if(bits == 0)
  88049. return true;
  88050. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+bits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  88051. if(bw->capacity <= bw->words + bits && !bitwriter_grow_(bw, bits))
  88052. return false;
  88053. left = FLAC__BITS_PER_WORD - bw->bits;
  88054. if(bits < left) {
  88055. bw->accum <<= bits;
  88056. bw->accum |= val;
  88057. bw->bits += bits;
  88058. }
  88059. 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 */
  88060. bw->accum <<= left;
  88061. bw->accum |= val >> (bw->bits = bits - left);
  88062. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  88063. bw->accum = val;
  88064. }
  88065. else {
  88066. bw->accum = val;
  88067. bw->bits = 0;
  88068. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(val);
  88069. }
  88070. return true;
  88071. }
  88072. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_int32(FLAC__BitWriter *bw, FLAC__int32 val, unsigned bits)
  88073. {
  88074. /* zero-out unused bits */
  88075. if(bits < 32)
  88076. val &= (~(0xffffffff << bits));
  88077. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, bits);
  88078. }
  88079. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint64(FLAC__BitWriter *bw, FLAC__uint64 val, unsigned bits)
  88080. {
  88081. /* this could be a little faster but it's not used for much */
  88082. if(bits > 32) {
  88083. return
  88084. FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)(val>>32), bits-32) &&
  88085. FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, 32);
  88086. }
  88087. else
  88088. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, bits);
  88089. }
  88090. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint32_little_endian(FLAC__BitWriter *bw, FLAC__uint32 val)
  88091. {
  88092. /* this doesn't need to be that fast as currently it is only used for vorbis comments */
  88093. if(!FLAC__bitwriter_write_raw_uint32(bw, val & 0xff, 8))
  88094. return false;
  88095. if(!FLAC__bitwriter_write_raw_uint32(bw, (val>>8) & 0xff, 8))
  88096. return false;
  88097. if(!FLAC__bitwriter_write_raw_uint32(bw, (val>>16) & 0xff, 8))
  88098. return false;
  88099. if(!FLAC__bitwriter_write_raw_uint32(bw, val>>24, 8))
  88100. return false;
  88101. return true;
  88102. }
  88103. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_byte_block(FLAC__BitWriter *bw, const FLAC__byte vals[], unsigned nvals)
  88104. {
  88105. unsigned i;
  88106. /* this could be faster but currently we don't need it to be since it's only used for writing metadata */
  88107. for(i = 0; i < nvals; i++) {
  88108. if(!FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)(vals[i]), 8))
  88109. return false;
  88110. }
  88111. return true;
  88112. }
  88113. FLAC__bool FLAC__bitwriter_write_unary_unsigned(FLAC__BitWriter *bw, unsigned val)
  88114. {
  88115. if(val < 32)
  88116. return FLAC__bitwriter_write_raw_uint32(bw, 1, ++val);
  88117. else
  88118. return
  88119. FLAC__bitwriter_write_zeroes(bw, val) &&
  88120. FLAC__bitwriter_write_raw_uint32(bw, 1, 1);
  88121. }
  88122. unsigned FLAC__bitwriter_rice_bits(FLAC__int32 val, unsigned parameter)
  88123. {
  88124. FLAC__uint32 uval;
  88125. FLAC__ASSERT(parameter < sizeof(unsigned)*8);
  88126. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  88127. uval = (val<<1) ^ (val>>31);
  88128. return 1 + parameter + (uval >> parameter);
  88129. }
  88130. #if 0 /* UNUSED */
  88131. unsigned FLAC__bitwriter_golomb_bits_signed(int val, unsigned parameter)
  88132. {
  88133. unsigned bits, msbs, uval;
  88134. unsigned k;
  88135. FLAC__ASSERT(parameter > 0);
  88136. /* fold signed to unsigned */
  88137. if(val < 0)
  88138. uval = (unsigned)(((-(++val)) << 1) + 1);
  88139. else
  88140. uval = (unsigned)(val << 1);
  88141. k = FLAC__bitmath_ilog2(parameter);
  88142. if(parameter == 1u<<k) {
  88143. FLAC__ASSERT(k <= 30);
  88144. msbs = uval >> k;
  88145. bits = 1 + k + msbs;
  88146. }
  88147. else {
  88148. unsigned q, r, d;
  88149. d = (1 << (k+1)) - parameter;
  88150. q = uval / parameter;
  88151. r = uval - (q * parameter);
  88152. bits = 1 + q + k;
  88153. if(r >= d)
  88154. bits++;
  88155. }
  88156. return bits;
  88157. }
  88158. unsigned FLAC__bitwriter_golomb_bits_unsigned(unsigned uval, unsigned parameter)
  88159. {
  88160. unsigned bits, msbs;
  88161. unsigned k;
  88162. FLAC__ASSERT(parameter > 0);
  88163. k = FLAC__bitmath_ilog2(parameter);
  88164. if(parameter == 1u<<k) {
  88165. FLAC__ASSERT(k <= 30);
  88166. msbs = uval >> k;
  88167. bits = 1 + k + msbs;
  88168. }
  88169. else {
  88170. unsigned q, r, d;
  88171. d = (1 << (k+1)) - parameter;
  88172. q = uval / parameter;
  88173. r = uval - (q * parameter);
  88174. bits = 1 + q + k;
  88175. if(r >= d)
  88176. bits++;
  88177. }
  88178. return bits;
  88179. }
  88180. #endif /* UNUSED */
  88181. FLAC__bool FLAC__bitwriter_write_rice_signed(FLAC__BitWriter *bw, FLAC__int32 val, unsigned parameter)
  88182. {
  88183. unsigned total_bits, interesting_bits, msbs;
  88184. FLAC__uint32 uval, pattern;
  88185. FLAC__ASSERT(0 != bw);
  88186. FLAC__ASSERT(0 != bw->buffer);
  88187. FLAC__ASSERT(parameter < 8*sizeof(uval));
  88188. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  88189. uval = (val<<1) ^ (val>>31);
  88190. msbs = uval >> parameter;
  88191. interesting_bits = 1 + parameter;
  88192. total_bits = interesting_bits + msbs;
  88193. pattern = 1 << parameter; /* the unary end bit */
  88194. pattern |= (uval & ((1<<parameter)-1)); /* the binary LSBs */
  88195. if(total_bits <= 32)
  88196. return FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits);
  88197. else
  88198. return
  88199. FLAC__bitwriter_write_zeroes(bw, msbs) && /* write the unary MSBs */
  88200. FLAC__bitwriter_write_raw_uint32(bw, pattern, interesting_bits); /* write the unary end bit and binary LSBs */
  88201. }
  88202. FLAC__bool FLAC__bitwriter_write_rice_signed_block(FLAC__BitWriter *bw, const FLAC__int32 *vals, unsigned nvals, unsigned parameter)
  88203. {
  88204. const FLAC__uint32 mask1 = FLAC__WORD_ALL_ONES << parameter; /* we val|=mask1 to set the stop bit above it... */
  88205. const FLAC__uint32 mask2 = FLAC__WORD_ALL_ONES >> (31-parameter); /* ...then mask off the bits above the stop bit with val&=mask2*/
  88206. FLAC__uint32 uval;
  88207. unsigned left;
  88208. const unsigned lsbits = 1 + parameter;
  88209. unsigned msbits;
  88210. FLAC__ASSERT(0 != bw);
  88211. FLAC__ASSERT(0 != bw->buffer);
  88212. FLAC__ASSERT(parameter < 8*sizeof(bwword)-1);
  88213. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  88214. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  88215. while(nvals) {
  88216. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  88217. uval = (*vals<<1) ^ (*vals>>31);
  88218. msbits = uval >> parameter;
  88219. #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) */
  88220. if(bw->bits && bw->bits + msbits + lsbits <= FLAC__BITS_PER_WORD) { /* i.e. if the whole thing fits in the current bwword */
  88221. /* ^^^ if bw->bits is 0 then we may have filled the buffer and have no free bwword to work in */
  88222. bw->bits = bw->bits + msbits + lsbits;
  88223. uval |= mask1; /* set stop bit */
  88224. uval &= mask2; /* mask off unused top bits */
  88225. /* NOT: bw->accum <<= msbits + lsbits because msbits+lsbits could be 32, then the shift would be a NOP */
  88226. bw->accum <<= msbits;
  88227. bw->accum <<= lsbits;
  88228. bw->accum |= uval;
  88229. if(bw->bits == FLAC__BITS_PER_WORD) {
  88230. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  88231. bw->bits = 0;
  88232. /* burying the capacity check down here means we have to grow the buffer a little if there are more vals to do */
  88233. if(bw->capacity <= bw->words && nvals > 1 && !bitwriter_grow_(bw, 1)) {
  88234. FLAC__ASSERT(bw->capacity == bw->words);
  88235. return false;
  88236. }
  88237. }
  88238. }
  88239. else {
  88240. #elif 1 /*@@@@@@ OPT: try this version with MSVC6 to see if better, not much difference for gcc-4 */
  88241. if(bw->bits && bw->bits + msbits + lsbits < FLAC__BITS_PER_WORD) { /* i.e. if the whole thing fits in the current bwword */
  88242. /* ^^^ if bw->bits is 0 then we may have filled the buffer and have no free bwword to work in */
  88243. bw->bits = bw->bits + msbits + lsbits;
  88244. uval |= mask1; /* set stop bit */
  88245. uval &= mask2; /* mask off unused top bits */
  88246. bw->accum <<= msbits + lsbits;
  88247. bw->accum |= uval;
  88248. }
  88249. else {
  88250. #endif
  88251. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+msbits+lsbits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  88252. /* OPT: pessimism may cause flurry of false calls to grow_ which eat up all savings before it */
  88253. if(bw->capacity <= bw->words + bw->bits + msbits + 1/*lsbits always fit in 1 bwword*/ && !bitwriter_grow_(bw, msbits+lsbits))
  88254. return false;
  88255. if(msbits) {
  88256. /* first part gets to word alignment */
  88257. if(bw->bits) {
  88258. left = FLAC__BITS_PER_WORD - bw->bits;
  88259. if(msbits < left) {
  88260. bw->accum <<= msbits;
  88261. bw->bits += msbits;
  88262. goto break1;
  88263. }
  88264. else {
  88265. bw->accum <<= left;
  88266. msbits -= left;
  88267. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  88268. bw->bits = 0;
  88269. }
  88270. }
  88271. /* do whole words */
  88272. while(msbits >= FLAC__BITS_PER_WORD) {
  88273. bw->buffer[bw->words++] = 0;
  88274. msbits -= FLAC__BITS_PER_WORD;
  88275. }
  88276. /* do any leftovers */
  88277. if(msbits > 0) {
  88278. bw->accum = 0;
  88279. bw->bits = msbits;
  88280. }
  88281. }
  88282. break1:
  88283. uval |= mask1; /* set stop bit */
  88284. uval &= mask2; /* mask off unused top bits */
  88285. left = FLAC__BITS_PER_WORD - bw->bits;
  88286. if(lsbits < left) {
  88287. bw->accum <<= lsbits;
  88288. bw->accum |= uval;
  88289. bw->bits += lsbits;
  88290. }
  88291. else {
  88292. /* if bw->bits == 0, left==FLAC__BITS_PER_WORD which will always
  88293. * be > lsbits (because of previous assertions) so it would have
  88294. * triggered the (lsbits<left) case above.
  88295. */
  88296. FLAC__ASSERT(bw->bits);
  88297. FLAC__ASSERT(left < FLAC__BITS_PER_WORD);
  88298. bw->accum <<= left;
  88299. bw->accum |= uval >> (bw->bits = lsbits - left);
  88300. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  88301. bw->accum = uval;
  88302. }
  88303. #if 1
  88304. }
  88305. #endif
  88306. vals++;
  88307. nvals--;
  88308. }
  88309. return true;
  88310. }
  88311. #if 0 /* UNUSED */
  88312. FLAC__bool FLAC__bitwriter_write_golomb_signed(FLAC__BitWriter *bw, int val, unsigned parameter)
  88313. {
  88314. unsigned total_bits, msbs, uval;
  88315. unsigned k;
  88316. FLAC__ASSERT(0 != bw);
  88317. FLAC__ASSERT(0 != bw->buffer);
  88318. FLAC__ASSERT(parameter > 0);
  88319. /* fold signed to unsigned */
  88320. if(val < 0)
  88321. uval = (unsigned)(((-(++val)) << 1) + 1);
  88322. else
  88323. uval = (unsigned)(val << 1);
  88324. k = FLAC__bitmath_ilog2(parameter);
  88325. if(parameter == 1u<<k) {
  88326. unsigned pattern;
  88327. FLAC__ASSERT(k <= 30);
  88328. msbs = uval >> k;
  88329. total_bits = 1 + k + msbs;
  88330. pattern = 1 << k; /* the unary end bit */
  88331. pattern |= (uval & ((1u<<k)-1)); /* the binary LSBs */
  88332. if(total_bits <= 32) {
  88333. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits))
  88334. return false;
  88335. }
  88336. else {
  88337. /* write the unary MSBs */
  88338. if(!FLAC__bitwriter_write_zeroes(bw, msbs))
  88339. return false;
  88340. /* write the unary end bit and binary LSBs */
  88341. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, k+1))
  88342. return false;
  88343. }
  88344. }
  88345. else {
  88346. unsigned q, r, d;
  88347. d = (1 << (k+1)) - parameter;
  88348. q = uval / parameter;
  88349. r = uval - (q * parameter);
  88350. /* write the unary MSBs */
  88351. if(!FLAC__bitwriter_write_zeroes(bw, q))
  88352. return false;
  88353. /* write the unary end bit */
  88354. if(!FLAC__bitwriter_write_raw_uint32(bw, 1, 1))
  88355. return false;
  88356. /* write the binary LSBs */
  88357. if(r >= d) {
  88358. if(!FLAC__bitwriter_write_raw_uint32(bw, r+d, k+1))
  88359. return false;
  88360. }
  88361. else {
  88362. if(!FLAC__bitwriter_write_raw_uint32(bw, r, k))
  88363. return false;
  88364. }
  88365. }
  88366. return true;
  88367. }
  88368. FLAC__bool FLAC__bitwriter_write_golomb_unsigned(FLAC__BitWriter *bw, unsigned uval, unsigned parameter)
  88369. {
  88370. unsigned total_bits, msbs;
  88371. unsigned k;
  88372. FLAC__ASSERT(0 != bw);
  88373. FLAC__ASSERT(0 != bw->buffer);
  88374. FLAC__ASSERT(parameter > 0);
  88375. k = FLAC__bitmath_ilog2(parameter);
  88376. if(parameter == 1u<<k) {
  88377. unsigned pattern;
  88378. FLAC__ASSERT(k <= 30);
  88379. msbs = uval >> k;
  88380. total_bits = 1 + k + msbs;
  88381. pattern = 1 << k; /* the unary end bit */
  88382. pattern |= (uval & ((1u<<k)-1)); /* the binary LSBs */
  88383. if(total_bits <= 32) {
  88384. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits))
  88385. return false;
  88386. }
  88387. else {
  88388. /* write the unary MSBs */
  88389. if(!FLAC__bitwriter_write_zeroes(bw, msbs))
  88390. return false;
  88391. /* write the unary end bit and binary LSBs */
  88392. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, k+1))
  88393. return false;
  88394. }
  88395. }
  88396. else {
  88397. unsigned q, r, d;
  88398. d = (1 << (k+1)) - parameter;
  88399. q = uval / parameter;
  88400. r = uval - (q * parameter);
  88401. /* write the unary MSBs */
  88402. if(!FLAC__bitwriter_write_zeroes(bw, q))
  88403. return false;
  88404. /* write the unary end bit */
  88405. if(!FLAC__bitwriter_write_raw_uint32(bw, 1, 1))
  88406. return false;
  88407. /* write the binary LSBs */
  88408. if(r >= d) {
  88409. if(!FLAC__bitwriter_write_raw_uint32(bw, r+d, k+1))
  88410. return false;
  88411. }
  88412. else {
  88413. if(!FLAC__bitwriter_write_raw_uint32(bw, r, k))
  88414. return false;
  88415. }
  88416. }
  88417. return true;
  88418. }
  88419. #endif /* UNUSED */
  88420. FLAC__bool FLAC__bitwriter_write_utf8_uint32(FLAC__BitWriter *bw, FLAC__uint32 val)
  88421. {
  88422. FLAC__bool ok = 1;
  88423. FLAC__ASSERT(0 != bw);
  88424. FLAC__ASSERT(0 != bw->buffer);
  88425. FLAC__ASSERT(!(val & 0x80000000)); /* this version only handles 31 bits */
  88426. if(val < 0x80) {
  88427. return FLAC__bitwriter_write_raw_uint32(bw, val, 8);
  88428. }
  88429. else if(val < 0x800) {
  88430. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xC0 | (val>>6), 8);
  88431. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  88432. }
  88433. else if(val < 0x10000) {
  88434. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xE0 | (val>>12), 8);
  88435. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  88436. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  88437. }
  88438. else if(val < 0x200000) {
  88439. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF0 | (val>>18), 8);
  88440. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  88441. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  88442. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  88443. }
  88444. else if(val < 0x4000000) {
  88445. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF8 | (val>>24), 8);
  88446. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>18)&0x3F), 8);
  88447. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  88448. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  88449. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  88450. }
  88451. else {
  88452. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFC | (val>>30), 8);
  88453. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>24)&0x3F), 8);
  88454. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>18)&0x3F), 8);
  88455. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  88456. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  88457. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  88458. }
  88459. return ok;
  88460. }
  88461. FLAC__bool FLAC__bitwriter_write_utf8_uint64(FLAC__BitWriter *bw, FLAC__uint64 val)
  88462. {
  88463. FLAC__bool ok = 1;
  88464. FLAC__ASSERT(0 != bw);
  88465. FLAC__ASSERT(0 != bw->buffer);
  88466. FLAC__ASSERT(!(val & FLAC__U64L(0xFFFFFFF000000000))); /* this version only handles 36 bits */
  88467. if(val < 0x80) {
  88468. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, 8);
  88469. }
  88470. else if(val < 0x800) {
  88471. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xC0 | (FLAC__uint32)(val>>6), 8);
  88472. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  88473. }
  88474. else if(val < 0x10000) {
  88475. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xE0 | (FLAC__uint32)(val>>12), 8);
  88476. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  88477. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  88478. }
  88479. else if(val < 0x200000) {
  88480. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF0 | (FLAC__uint32)(val>>18), 8);
  88481. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  88482. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  88483. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  88484. }
  88485. else if(val < 0x4000000) {
  88486. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF8 | (FLAC__uint32)(val>>24), 8);
  88487. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  88488. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  88489. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  88490. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  88491. }
  88492. else if(val < 0x80000000) {
  88493. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFC | (FLAC__uint32)(val>>30), 8);
  88494. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>24)&0x3F), 8);
  88495. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  88496. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  88497. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  88498. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  88499. }
  88500. else {
  88501. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFE, 8);
  88502. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>30)&0x3F), 8);
  88503. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>24)&0x3F), 8);
  88504. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  88505. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  88506. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  88507. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  88508. }
  88509. return ok;
  88510. }
  88511. FLAC__bool FLAC__bitwriter_zero_pad_to_byte_boundary(FLAC__BitWriter *bw)
  88512. {
  88513. /* 0-pad to byte boundary */
  88514. if(bw->bits & 7u)
  88515. return FLAC__bitwriter_write_zeroes(bw, 8 - (bw->bits & 7u));
  88516. else
  88517. return true;
  88518. }
  88519. #endif
  88520. /********* End of inlined file: bitwriter.c *********/
  88521. /********* Start of inlined file: cpu.c *********/
  88522. /********* Start of inlined file: juce_FlacHeader.h *********/
  88523. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  88524. // tasks..
  88525. #define VERSION "1.2.1"
  88526. #define FLAC__NO_DLL 1
  88527. #ifdef _MSC_VER
  88528. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  88529. #endif
  88530. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  88531. #define FLAC__SYS_DARWIN 1
  88532. #endif
  88533. /********* End of inlined file: juce_FlacHeader.h *********/
  88534. #if JUCE_USE_FLAC
  88535. #if HAVE_CONFIG_H
  88536. # include <config.h>
  88537. #endif
  88538. #include <stdlib.h>
  88539. #include <stdio.h>
  88540. #if defined FLAC__CPU_IA32
  88541. # include <signal.h>
  88542. #elif defined FLAC__CPU_PPC
  88543. # if !defined FLAC__NO_ASM
  88544. # if defined FLAC__SYS_DARWIN
  88545. # include <sys/sysctl.h>
  88546. # include <mach/mach.h>
  88547. # include <mach/mach_host.h>
  88548. # include <mach/host_info.h>
  88549. # include <mach/machine.h>
  88550. # ifndef CPU_SUBTYPE_POWERPC_970
  88551. # define CPU_SUBTYPE_POWERPC_970 ((cpu_subtype_t) 100)
  88552. # endif
  88553. # else /* FLAC__SYS_DARWIN */
  88554. # include <signal.h>
  88555. # include <setjmp.h>
  88556. static sigjmp_buf jmpbuf;
  88557. static volatile sig_atomic_t canjump = 0;
  88558. static void sigill_handler (int sig)
  88559. {
  88560. if (!canjump) {
  88561. signal (sig, SIG_DFL);
  88562. raise (sig);
  88563. }
  88564. canjump = 0;
  88565. siglongjmp (jmpbuf, 1);
  88566. }
  88567. # endif /* FLAC__SYS_DARWIN */
  88568. # endif /* FLAC__NO_ASM */
  88569. #endif /* FLAC__CPU_PPC */
  88570. #if defined (__NetBSD__) || defined(__OpenBSD__)
  88571. #include <sys/param.h>
  88572. #include <sys/sysctl.h>
  88573. #include <machine/cpu.h>
  88574. #endif
  88575. #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
  88576. #include <sys/types.h>
  88577. #include <sys/sysctl.h>
  88578. #endif
  88579. #if defined(__APPLE__)
  88580. /* how to get sysctlbyname()? */
  88581. #endif
  88582. /* these are flags in EDX of CPUID AX=00000001 */
  88583. static const unsigned FLAC__CPUINFO_IA32_CPUID_CMOV = 0x00008000;
  88584. static const unsigned FLAC__CPUINFO_IA32_CPUID_MMX = 0x00800000;
  88585. static const unsigned FLAC__CPUINFO_IA32_CPUID_FXSR = 0x01000000;
  88586. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE = 0x02000000;
  88587. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE2 = 0x04000000;
  88588. /* these are flags in ECX of CPUID AX=00000001 */
  88589. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE3 = 0x00000001;
  88590. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSSE3 = 0x00000200;
  88591. /* these are flags in EDX of CPUID AX=80000001 */
  88592. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_3DNOW = 0x80000000;
  88593. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXT3DNOW = 0x40000000;
  88594. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXTMMX = 0x00400000;
  88595. /*
  88596. * Extra stuff needed for detection of OS support for SSE on IA-32
  88597. */
  88598. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM && !defined FLAC__NO_SSE_OS && !defined FLAC__SSE_OS
  88599. # if defined(__linux__)
  88600. /*
  88601. * If the OS doesn't support SSE, we will get here with a SIGILL. We
  88602. * modify the return address to jump over the offending SSE instruction
  88603. * and also the operation following it that indicates the instruction
  88604. * executed successfully. In this way we use no global variables and
  88605. * stay thread-safe.
  88606. *
  88607. * 3 + 3 + 6:
  88608. * 3 bytes for "xorps xmm0,xmm0"
  88609. * 3 bytes for estimate of how long the follwing "inc var" instruction is
  88610. * 6 bytes extra in case our estimate is wrong
  88611. * 12 bytes puts us in the NOP "landing zone"
  88612. */
  88613. # undef USE_OBSOLETE_SIGCONTEXT_FLAVOR /* #define this to use the older signal handler method */
  88614. # ifdef USE_OBSOLETE_SIGCONTEXT_FLAVOR
  88615. static void sigill_handler_sse_os(int signal, struct sigcontext sc)
  88616. {
  88617. (void)signal;
  88618. sc.eip += 3 + 3 + 6;
  88619. }
  88620. # else
  88621. # include <sys/ucontext.h>
  88622. static void sigill_handler_sse_os(int signal, siginfo_t *si, void *uc)
  88623. {
  88624. (void)signal, (void)si;
  88625. ((ucontext_t*)uc)->uc_mcontext.gregs[14/*REG_EIP*/] += 3 + 3 + 6;
  88626. }
  88627. # endif
  88628. # elif defined(_MSC_VER)
  88629. # include <windows.h>
  88630. # undef USE_TRY_CATCH_FLAVOR /* #define this to use the try/catch method for catching illegal opcode exception */
  88631. # ifdef USE_TRY_CATCH_FLAVOR
  88632. # else
  88633. LONG CALLBACK sigill_handler_sse_os(EXCEPTION_POINTERS *ep)
  88634. {
  88635. if(ep->ExceptionRecord->ExceptionCode == EXCEPTION_ILLEGAL_INSTRUCTION) {
  88636. ep->ContextRecord->Eip += 3 + 3 + 6;
  88637. return EXCEPTION_CONTINUE_EXECUTION;
  88638. }
  88639. return EXCEPTION_CONTINUE_SEARCH;
  88640. }
  88641. # endif
  88642. # endif
  88643. #endif
  88644. void FLAC__cpu_info(FLAC__CPUInfo *info)
  88645. {
  88646. /*
  88647. * IA32-specific
  88648. */
  88649. #ifdef FLAC__CPU_IA32
  88650. info->type = FLAC__CPUINFO_TYPE_IA32;
  88651. #if !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  88652. info->use_asm = true; /* we assume a minimum of 80386 with FLAC__CPU_IA32 */
  88653. info->data.ia32.cpuid = FLAC__cpu_have_cpuid_asm_ia32()? true : false;
  88654. info->data.ia32.bswap = info->data.ia32.cpuid; /* CPUID => BSWAP since it came after */
  88655. info->data.ia32.cmov = false;
  88656. info->data.ia32.mmx = false;
  88657. info->data.ia32.fxsr = false;
  88658. info->data.ia32.sse = false;
  88659. info->data.ia32.sse2 = false;
  88660. info->data.ia32.sse3 = false;
  88661. info->data.ia32.ssse3 = false;
  88662. info->data.ia32._3dnow = false;
  88663. info->data.ia32.ext3dnow = false;
  88664. info->data.ia32.extmmx = false;
  88665. if(info->data.ia32.cpuid) {
  88666. /* http://www.sandpile.org/ia32/cpuid.htm */
  88667. FLAC__uint32 flags_edx, flags_ecx;
  88668. FLAC__cpu_info_asm_ia32(&flags_edx, &flags_ecx);
  88669. info->data.ia32.cmov = (flags_edx & FLAC__CPUINFO_IA32_CPUID_CMOV )? true : false;
  88670. info->data.ia32.mmx = (flags_edx & FLAC__CPUINFO_IA32_CPUID_MMX )? true : false;
  88671. info->data.ia32.fxsr = (flags_edx & FLAC__CPUINFO_IA32_CPUID_FXSR )? true : false;
  88672. info->data.ia32.sse = (flags_edx & FLAC__CPUINFO_IA32_CPUID_SSE )? true : false;
  88673. info->data.ia32.sse2 = (flags_edx & FLAC__CPUINFO_IA32_CPUID_SSE2 )? true : false;
  88674. info->data.ia32.sse3 = (flags_ecx & FLAC__CPUINFO_IA32_CPUID_SSE3 )? true : false;
  88675. info->data.ia32.ssse3 = (flags_ecx & FLAC__CPUINFO_IA32_CPUID_SSSE3)? true : false;
  88676. #ifdef FLAC__USE_3DNOW
  88677. flags_edx = FLAC__cpu_info_extended_amd_asm_ia32();
  88678. info->data.ia32._3dnow = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_3DNOW )? true : false;
  88679. info->data.ia32.ext3dnow = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXT3DNOW)? true : false;
  88680. info->data.ia32.extmmx = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXTMMX )? true : false;
  88681. #else
  88682. info->data.ia32._3dnow = info->data.ia32.ext3dnow = info->data.ia32.extmmx = false;
  88683. #endif
  88684. #ifdef DEBUG
  88685. fprintf(stderr, "CPU info (IA-32):\n");
  88686. fprintf(stderr, " CPUID ...... %c\n", info->data.ia32.cpuid ? 'Y' : 'n');
  88687. fprintf(stderr, " BSWAP ...... %c\n", info->data.ia32.bswap ? 'Y' : 'n');
  88688. fprintf(stderr, " CMOV ....... %c\n", info->data.ia32.cmov ? 'Y' : 'n');
  88689. fprintf(stderr, " MMX ........ %c\n", info->data.ia32.mmx ? 'Y' : 'n');
  88690. fprintf(stderr, " FXSR ....... %c\n", info->data.ia32.fxsr ? 'Y' : 'n');
  88691. fprintf(stderr, " SSE ........ %c\n", info->data.ia32.sse ? 'Y' : 'n');
  88692. fprintf(stderr, " SSE2 ....... %c\n", info->data.ia32.sse2 ? 'Y' : 'n');
  88693. fprintf(stderr, " SSE3 ....... %c\n", info->data.ia32.sse3 ? 'Y' : 'n');
  88694. fprintf(stderr, " SSSE3 ...... %c\n", info->data.ia32.ssse3 ? 'Y' : 'n');
  88695. fprintf(stderr, " 3DNow! ..... %c\n", info->data.ia32._3dnow ? 'Y' : 'n');
  88696. fprintf(stderr, " 3DNow!-ext . %c\n", info->data.ia32.ext3dnow? 'Y' : 'n');
  88697. fprintf(stderr, " 3DNow!-MMX . %c\n", info->data.ia32.extmmx ? 'Y' : 'n');
  88698. #endif
  88699. /*
  88700. * now have to check for OS support of SSE/SSE2
  88701. */
  88702. if(info->data.ia32.fxsr || info->data.ia32.sse || info->data.ia32.sse2) {
  88703. #if defined FLAC__NO_SSE_OS
  88704. /* assume user knows better than us; turn it off */
  88705. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  88706. #elif defined FLAC__SSE_OS
  88707. /* assume user knows better than us; leave as detected above */
  88708. #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__) || defined(__APPLE__)
  88709. int sse = 0;
  88710. size_t len;
  88711. /* at least one of these must work: */
  88712. len = sizeof(sse); sse = sse || (sysctlbyname("hw.instruction_sse", &sse, &len, NULL, 0) == 0 && sse);
  88713. len = sizeof(sse); sse = sse || (sysctlbyname("hw.optional.sse" , &sse, &len, NULL, 0) == 0 && sse); /* __APPLE__ ? */
  88714. if(!sse)
  88715. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  88716. #elif defined(__NetBSD__) || defined (__OpenBSD__)
  88717. # if __NetBSD_Version__ >= 105250000 || (defined __OpenBSD__)
  88718. int val = 0, mib[2] = { CTL_MACHDEP, CPU_SSE };
  88719. size_t len = sizeof(val);
  88720. if(sysctl(mib, 2, &val, &len, NULL, 0) < 0 || !val)
  88721. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  88722. else { /* double-check SSE2 */
  88723. mib[1] = CPU_SSE2;
  88724. len = sizeof(val);
  88725. if(sysctl(mib, 2, &val, &len, NULL, 0) < 0 || !val)
  88726. info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  88727. }
  88728. # else
  88729. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  88730. # endif
  88731. #elif defined(__linux__)
  88732. int sse = 0;
  88733. struct sigaction sigill_save;
  88734. #ifdef USE_OBSOLETE_SIGCONTEXT_FLAVOR
  88735. if(0 == sigaction(SIGILL, NULL, &sigill_save) && signal(SIGILL, (void (*)(int))sigill_handler_sse_os) != SIG_ERR)
  88736. #else
  88737. struct sigaction sigill_sse;
  88738. sigill_sse.sa_sigaction = sigill_handler_sse_os;
  88739. __sigemptyset(&sigill_sse.sa_mask);
  88740. 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 */
  88741. if(0 == sigaction(SIGILL, &sigill_sse, &sigill_save))
  88742. #endif
  88743. {
  88744. /* http://www.ibiblio.org/gferg/ldp/GCC-Inline-Assembly-HOWTO.html */
  88745. /* see sigill_handler_sse_os() for an explanation of the following: */
  88746. asm volatile (
  88747. "xorl %0,%0\n\t" /* for some reason, still need to do this to clear 'sse' var */
  88748. "xorps %%xmm0,%%xmm0\n\t" /* will cause SIGILL if unsupported by OS */
  88749. "incl %0\n\t" /* SIGILL handler will jump over this */
  88750. /* landing zone */
  88751. "nop\n\t" /* SIGILL jump lands here if "inc" is 9 bytes */
  88752. "nop\n\t"
  88753. "nop\n\t"
  88754. "nop\n\t"
  88755. "nop\n\t"
  88756. "nop\n\t"
  88757. "nop\n\t" /* SIGILL jump lands here if "inc" is 3 bytes (expected) */
  88758. "nop\n\t"
  88759. "nop" /* SIGILL jump lands here if "inc" is 1 byte */
  88760. : "=r"(sse)
  88761. : "r"(sse)
  88762. );
  88763. sigaction(SIGILL, &sigill_save, NULL);
  88764. }
  88765. if(!sse)
  88766. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  88767. #elif defined(_MSC_VER)
  88768. # ifdef USE_TRY_CATCH_FLAVOR
  88769. _try {
  88770. __asm {
  88771. # if _MSC_VER <= 1200
  88772. /* VC6 assembler doesn't know SSE, have to emit bytecode instead */
  88773. _emit 0x0F
  88774. _emit 0x57
  88775. _emit 0xC0
  88776. # else
  88777. xorps xmm0,xmm0
  88778. # endif
  88779. }
  88780. }
  88781. _except(EXCEPTION_EXECUTE_HANDLER) {
  88782. if (_exception_code() == STATUS_ILLEGAL_INSTRUCTION)
  88783. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  88784. }
  88785. # else
  88786. int sse = 0;
  88787. LPTOP_LEVEL_EXCEPTION_FILTER save = SetUnhandledExceptionFilter(sigill_handler_sse_os);
  88788. /* see GCC version above for explanation */
  88789. /* http://msdn2.microsoft.com/en-us/library/4ks26t93.aspx */
  88790. /* http://www.codeproject.com/cpp/gccasm.asp */
  88791. /* http://www.hick.org/~mmiller/msvc_inline_asm.html */
  88792. __asm {
  88793. # if _MSC_VER <= 1200
  88794. /* VC6 assembler doesn't know SSE, have to emit bytecode instead */
  88795. _emit 0x0F
  88796. _emit 0x57
  88797. _emit 0xC0
  88798. # else
  88799. xorps xmm0,xmm0
  88800. # endif
  88801. inc sse
  88802. nop
  88803. nop
  88804. nop
  88805. nop
  88806. nop
  88807. nop
  88808. nop
  88809. nop
  88810. nop
  88811. }
  88812. SetUnhandledExceptionFilter(save);
  88813. if(!sse)
  88814. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  88815. # endif
  88816. #else
  88817. /* no way to test, disable to be safe */
  88818. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  88819. #endif
  88820. #ifdef DEBUG
  88821. fprintf(stderr, " SSE OS sup . %c\n", info->data.ia32.sse ? 'Y' : 'n');
  88822. #endif
  88823. }
  88824. }
  88825. #else
  88826. info->use_asm = false;
  88827. #endif
  88828. /*
  88829. * PPC-specific
  88830. */
  88831. #elif defined FLAC__CPU_PPC
  88832. info->type = FLAC__CPUINFO_TYPE_PPC;
  88833. # if !defined FLAC__NO_ASM
  88834. info->use_asm = true;
  88835. # ifdef FLAC__USE_ALTIVEC
  88836. # if defined FLAC__SYS_DARWIN
  88837. {
  88838. int val = 0, mib[2] = { CTL_HW, HW_VECTORUNIT };
  88839. size_t len = sizeof(val);
  88840. info->data.ppc.altivec = !(sysctl(mib, 2, &val, &len, NULL, 0) || !val);
  88841. }
  88842. {
  88843. host_basic_info_data_t hostInfo;
  88844. mach_msg_type_number_t infoCount;
  88845. infoCount = HOST_BASIC_INFO_COUNT;
  88846. host_info(mach_host_self(), HOST_BASIC_INFO, (host_info_t)&hostInfo, &infoCount);
  88847. info->data.ppc.ppc64 = (hostInfo.cpu_type == CPU_TYPE_POWERPC) && (hostInfo.cpu_subtype == CPU_SUBTYPE_POWERPC_970);
  88848. }
  88849. # else /* FLAC__USE_ALTIVEC && !FLAC__SYS_DARWIN */
  88850. {
  88851. /* no Darwin, do it the brute-force way */
  88852. /* @@@@@@ this is not thread-safe; replace with SSE OS method above or remove */
  88853. info->data.ppc.altivec = 0;
  88854. info->data.ppc.ppc64 = 0;
  88855. signal (SIGILL, sigill_handler);
  88856. canjump = 0;
  88857. if (!sigsetjmp (jmpbuf, 1)) {
  88858. canjump = 1;
  88859. asm volatile (
  88860. "mtspr 256, %0\n\t"
  88861. "vand %%v0, %%v0, %%v0"
  88862. :
  88863. : "r" (-1)
  88864. );
  88865. info->data.ppc.altivec = 1;
  88866. }
  88867. canjump = 0;
  88868. if (!sigsetjmp (jmpbuf, 1)) {
  88869. int x = 0;
  88870. canjump = 1;
  88871. /* PPC64 hardware implements the cntlzd instruction */
  88872. asm volatile ("cntlzd %0, %1" : "=r" (x) : "r" (x) );
  88873. info->data.ppc.ppc64 = 1;
  88874. }
  88875. signal (SIGILL, SIG_DFL); /*@@@@@@ should save and restore old signal */
  88876. }
  88877. # endif
  88878. # else /* !FLAC__USE_ALTIVEC */
  88879. info->data.ppc.altivec = 0;
  88880. info->data.ppc.ppc64 = 0;
  88881. # endif
  88882. # else
  88883. info->use_asm = false;
  88884. # endif
  88885. /*
  88886. * unknown CPI
  88887. */
  88888. #else
  88889. info->type = FLAC__CPUINFO_TYPE_UNKNOWN;
  88890. info->use_asm = false;
  88891. #endif
  88892. }
  88893. #endif
  88894. /********* End of inlined file: cpu.c *********/
  88895. /********* Start of inlined file: crc.c *********/
  88896. /********* Start of inlined file: juce_FlacHeader.h *********/
  88897. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  88898. // tasks..
  88899. #define VERSION "1.2.1"
  88900. #define FLAC__NO_DLL 1
  88901. #ifdef _MSC_VER
  88902. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  88903. #endif
  88904. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  88905. #define FLAC__SYS_DARWIN 1
  88906. #endif
  88907. /********* End of inlined file: juce_FlacHeader.h *********/
  88908. #if JUCE_USE_FLAC
  88909. #if HAVE_CONFIG_H
  88910. # include <config.h>
  88911. #endif
  88912. /* CRC-8, poly = x^8 + x^2 + x^1 + x^0, init = 0 */
  88913. FLAC__byte const FLAC__crc8_table[256] = {
  88914. 0x00, 0x07, 0x0E, 0x09, 0x1C, 0x1B, 0x12, 0x15,
  88915. 0x38, 0x3F, 0x36, 0x31, 0x24, 0x23, 0x2A, 0x2D,
  88916. 0x70, 0x77, 0x7E, 0x79, 0x6C, 0x6B, 0x62, 0x65,
  88917. 0x48, 0x4F, 0x46, 0x41, 0x54, 0x53, 0x5A, 0x5D,
  88918. 0xE0, 0xE7, 0xEE, 0xE9, 0xFC, 0xFB, 0xF2, 0xF5,
  88919. 0xD8, 0xDF, 0xD6, 0xD1, 0xC4, 0xC3, 0xCA, 0xCD,
  88920. 0x90, 0x97, 0x9E, 0x99, 0x8C, 0x8B, 0x82, 0x85,
  88921. 0xA8, 0xAF, 0xA6, 0xA1, 0xB4, 0xB3, 0xBA, 0xBD,
  88922. 0xC7, 0xC0, 0xC9, 0xCE, 0xDB, 0xDC, 0xD5, 0xD2,
  88923. 0xFF, 0xF8, 0xF1, 0xF6, 0xE3, 0xE4, 0xED, 0xEA,
  88924. 0xB7, 0xB0, 0xB9, 0xBE, 0xAB, 0xAC, 0xA5, 0xA2,
  88925. 0x8F, 0x88, 0x81, 0x86, 0x93, 0x94, 0x9D, 0x9A,
  88926. 0x27, 0x20, 0x29, 0x2E, 0x3B, 0x3C, 0x35, 0x32,
  88927. 0x1F, 0x18, 0x11, 0x16, 0x03, 0x04, 0x0D, 0x0A,
  88928. 0x57, 0x50, 0x59, 0x5E, 0x4B, 0x4C, 0x45, 0x42,
  88929. 0x6F, 0x68, 0x61, 0x66, 0x73, 0x74, 0x7D, 0x7A,
  88930. 0x89, 0x8E, 0x87, 0x80, 0x95, 0x92, 0x9B, 0x9C,
  88931. 0xB1, 0xB6, 0xBF, 0xB8, 0xAD, 0xAA, 0xA3, 0xA4,
  88932. 0xF9, 0xFE, 0xF7, 0xF0, 0xE5, 0xE2, 0xEB, 0xEC,
  88933. 0xC1, 0xC6, 0xCF, 0xC8, 0xDD, 0xDA, 0xD3, 0xD4,
  88934. 0x69, 0x6E, 0x67, 0x60, 0x75, 0x72, 0x7B, 0x7C,
  88935. 0x51, 0x56, 0x5F, 0x58, 0x4D, 0x4A, 0x43, 0x44,
  88936. 0x19, 0x1E, 0x17, 0x10, 0x05, 0x02, 0x0B, 0x0C,
  88937. 0x21, 0x26, 0x2F, 0x28, 0x3D, 0x3A, 0x33, 0x34,
  88938. 0x4E, 0x49, 0x40, 0x47, 0x52, 0x55, 0x5C, 0x5B,
  88939. 0x76, 0x71, 0x78, 0x7F, 0x6A, 0x6D, 0x64, 0x63,
  88940. 0x3E, 0x39, 0x30, 0x37, 0x22, 0x25, 0x2C, 0x2B,
  88941. 0x06, 0x01, 0x08, 0x0F, 0x1A, 0x1D, 0x14, 0x13,
  88942. 0xAE, 0xA9, 0xA0, 0xA7, 0xB2, 0xB5, 0xBC, 0xBB,
  88943. 0x96, 0x91, 0x98, 0x9F, 0x8A, 0x8D, 0x84, 0x83,
  88944. 0xDE, 0xD9, 0xD0, 0xD7, 0xC2, 0xC5, 0xCC, 0xCB,
  88945. 0xE6, 0xE1, 0xE8, 0xEF, 0xFA, 0xFD, 0xF4, 0xF3
  88946. };
  88947. /* CRC-16, poly = x^16 + x^15 + x^2 + x^0, init = 0 */
  88948. unsigned FLAC__crc16_table[256] = {
  88949. 0x0000, 0x8005, 0x800f, 0x000a, 0x801b, 0x001e, 0x0014, 0x8011,
  88950. 0x8033, 0x0036, 0x003c, 0x8039, 0x0028, 0x802d, 0x8027, 0x0022,
  88951. 0x8063, 0x0066, 0x006c, 0x8069, 0x0078, 0x807d, 0x8077, 0x0072,
  88952. 0x0050, 0x8055, 0x805f, 0x005a, 0x804b, 0x004e, 0x0044, 0x8041,
  88953. 0x80c3, 0x00c6, 0x00cc, 0x80c9, 0x00d8, 0x80dd, 0x80d7, 0x00d2,
  88954. 0x00f0, 0x80f5, 0x80ff, 0x00fa, 0x80eb, 0x00ee, 0x00e4, 0x80e1,
  88955. 0x00a0, 0x80a5, 0x80af, 0x00aa, 0x80bb, 0x00be, 0x00b4, 0x80b1,
  88956. 0x8093, 0x0096, 0x009c, 0x8099, 0x0088, 0x808d, 0x8087, 0x0082,
  88957. 0x8183, 0x0186, 0x018c, 0x8189, 0x0198, 0x819d, 0x8197, 0x0192,
  88958. 0x01b0, 0x81b5, 0x81bf, 0x01ba, 0x81ab, 0x01ae, 0x01a4, 0x81a1,
  88959. 0x01e0, 0x81e5, 0x81ef, 0x01ea, 0x81fb, 0x01fe, 0x01f4, 0x81f1,
  88960. 0x81d3, 0x01d6, 0x01dc, 0x81d9, 0x01c8, 0x81cd, 0x81c7, 0x01c2,
  88961. 0x0140, 0x8145, 0x814f, 0x014a, 0x815b, 0x015e, 0x0154, 0x8151,
  88962. 0x8173, 0x0176, 0x017c, 0x8179, 0x0168, 0x816d, 0x8167, 0x0162,
  88963. 0x8123, 0x0126, 0x012c, 0x8129, 0x0138, 0x813d, 0x8137, 0x0132,
  88964. 0x0110, 0x8115, 0x811f, 0x011a, 0x810b, 0x010e, 0x0104, 0x8101,
  88965. 0x8303, 0x0306, 0x030c, 0x8309, 0x0318, 0x831d, 0x8317, 0x0312,
  88966. 0x0330, 0x8335, 0x833f, 0x033a, 0x832b, 0x032e, 0x0324, 0x8321,
  88967. 0x0360, 0x8365, 0x836f, 0x036a, 0x837b, 0x037e, 0x0374, 0x8371,
  88968. 0x8353, 0x0356, 0x035c, 0x8359, 0x0348, 0x834d, 0x8347, 0x0342,
  88969. 0x03c0, 0x83c5, 0x83cf, 0x03ca, 0x83db, 0x03de, 0x03d4, 0x83d1,
  88970. 0x83f3, 0x03f6, 0x03fc, 0x83f9, 0x03e8, 0x83ed, 0x83e7, 0x03e2,
  88971. 0x83a3, 0x03a6, 0x03ac, 0x83a9, 0x03b8, 0x83bd, 0x83b7, 0x03b2,
  88972. 0x0390, 0x8395, 0x839f, 0x039a, 0x838b, 0x038e, 0x0384, 0x8381,
  88973. 0x0280, 0x8285, 0x828f, 0x028a, 0x829b, 0x029e, 0x0294, 0x8291,
  88974. 0x82b3, 0x02b6, 0x02bc, 0x82b9, 0x02a8, 0x82ad, 0x82a7, 0x02a2,
  88975. 0x82e3, 0x02e6, 0x02ec, 0x82e9, 0x02f8, 0x82fd, 0x82f7, 0x02f2,
  88976. 0x02d0, 0x82d5, 0x82df, 0x02da, 0x82cb, 0x02ce, 0x02c4, 0x82c1,
  88977. 0x8243, 0x0246, 0x024c, 0x8249, 0x0258, 0x825d, 0x8257, 0x0252,
  88978. 0x0270, 0x8275, 0x827f, 0x027a, 0x826b, 0x026e, 0x0264, 0x8261,
  88979. 0x0220, 0x8225, 0x822f, 0x022a, 0x823b, 0x023e, 0x0234, 0x8231,
  88980. 0x8213, 0x0216, 0x021c, 0x8219, 0x0208, 0x820d, 0x8207, 0x0202
  88981. };
  88982. void FLAC__crc8_update(const FLAC__byte data, FLAC__uint8 *crc)
  88983. {
  88984. *crc = FLAC__crc8_table[*crc ^ data];
  88985. }
  88986. void FLAC__crc8_update_block(const FLAC__byte *data, unsigned len, FLAC__uint8 *crc)
  88987. {
  88988. while(len--)
  88989. *crc = FLAC__crc8_table[*crc ^ *data++];
  88990. }
  88991. FLAC__uint8 FLAC__crc8(const FLAC__byte *data, unsigned len)
  88992. {
  88993. FLAC__uint8 crc = 0;
  88994. while(len--)
  88995. crc = FLAC__crc8_table[crc ^ *data++];
  88996. return crc;
  88997. }
  88998. unsigned FLAC__crc16(const FLAC__byte *data, unsigned len)
  88999. {
  89000. unsigned crc = 0;
  89001. while(len--)
  89002. crc = ((crc<<8) ^ FLAC__crc16_table[(crc>>8) ^ *data++]) & 0xffff;
  89003. return crc;
  89004. }
  89005. #endif
  89006. /********* End of inlined file: crc.c *********/
  89007. /********* Start of inlined file: fixed.c *********/
  89008. /********* Start of inlined file: juce_FlacHeader.h *********/
  89009. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  89010. // tasks..
  89011. #define VERSION "1.2.1"
  89012. #define FLAC__NO_DLL 1
  89013. #ifdef _MSC_VER
  89014. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  89015. #endif
  89016. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  89017. #define FLAC__SYS_DARWIN 1
  89018. #endif
  89019. /********* End of inlined file: juce_FlacHeader.h *********/
  89020. #if JUCE_USE_FLAC
  89021. #if HAVE_CONFIG_H
  89022. # include <config.h>
  89023. #endif
  89024. #include <math.h>
  89025. #include <string.h>
  89026. /********* Start of inlined file: fixed.h *********/
  89027. #ifndef FLAC__PRIVATE__FIXED_H
  89028. #define FLAC__PRIVATE__FIXED_H
  89029. #ifdef HAVE_CONFIG_H
  89030. #include <config.h>
  89031. #endif
  89032. /********* Start of inlined file: float.h *********/
  89033. #ifndef FLAC__PRIVATE__FLOAT_H
  89034. #define FLAC__PRIVATE__FLOAT_H
  89035. #ifdef HAVE_CONFIG_H
  89036. #include <config.h>
  89037. #endif
  89038. /*
  89039. * These typedefs make it easier to ensure that integer versions of
  89040. * the library really only contain integer operations. All the code
  89041. * in libFLAC should use FLAC__float and FLAC__double in place of
  89042. * float and double, and be protected by checks of the macro
  89043. * FLAC__INTEGER_ONLY_LIBRARY.
  89044. *
  89045. * FLAC__real is the basic floating point type used in LPC analysis.
  89046. */
  89047. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  89048. typedef double FLAC__double;
  89049. typedef float FLAC__float;
  89050. /*
  89051. * WATCHOUT: changing FLAC__real will change the signatures of many
  89052. * functions that have assembly language equivalents and break them.
  89053. */
  89054. typedef float FLAC__real;
  89055. #else
  89056. /*
  89057. * The convention for FLAC__fixedpoint is to use the upper 16 bits
  89058. * for the integer part and lower 16 bits for the fractional part.
  89059. */
  89060. typedef FLAC__int32 FLAC__fixedpoint;
  89061. extern const FLAC__fixedpoint FLAC__FP_ZERO;
  89062. extern const FLAC__fixedpoint FLAC__FP_ONE_HALF;
  89063. extern const FLAC__fixedpoint FLAC__FP_ONE;
  89064. extern const FLAC__fixedpoint FLAC__FP_LN2;
  89065. extern const FLAC__fixedpoint FLAC__FP_E;
  89066. #define FLAC__fixedpoint_trunc(x) ((x)>>16)
  89067. #define FLAC__fixedpoint_mul(x, y) ( (FLAC__fixedpoint) ( ((FLAC__int64)(x)*(FLAC__int64)(y)) >> 16 ) )
  89068. #define FLAC__fixedpoint_div(x, y) ( (FLAC__fixedpoint) ( ( ((FLAC__int64)(x)<<32) / (FLAC__int64)(y) ) >> 16 ) )
  89069. /*
  89070. * FLAC__fixedpoint_log2()
  89071. * --------------------------------------------------------------------
  89072. * Returns the base-2 logarithm of the fixed-point number 'x' using an
  89073. * algorithm by Knuth for x >= 1.0
  89074. *
  89075. * 'fracbits' is the number of fractional bits of 'x'. 'fracbits' must
  89076. * be < 32 and evenly divisible by 4 (0 is OK but not very precise).
  89077. *
  89078. * 'precision' roughly limits the number of iterations that are done;
  89079. * use (unsigned)(-1) for maximum precision.
  89080. *
  89081. * If 'x' is less than one -- that is, x < (1<<fracbits) -- then this
  89082. * function will punt and return 0.
  89083. *
  89084. * The return value will also have 'fracbits' fractional bits.
  89085. */
  89086. FLAC__uint32 FLAC__fixedpoint_log2(FLAC__uint32 x, unsigned fracbits, unsigned precision);
  89087. #endif
  89088. #endif
  89089. /********* End of inlined file: float.h *********/
  89090. /********* Start of inlined file: format.h *********/
  89091. #ifndef FLAC__PRIVATE__FORMAT_H
  89092. #define FLAC__PRIVATE__FORMAT_H
  89093. unsigned FLAC__format_get_max_rice_partition_order(unsigned blocksize, unsigned predictor_order);
  89094. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize(unsigned blocksize);
  89095. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(unsigned limit, unsigned blocksize, unsigned predictor_order);
  89096. void FLAC__format_entropy_coding_method_partitioned_rice_contents_init(FLAC__EntropyCodingMethod_PartitionedRiceContents *object);
  89097. void FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(FLAC__EntropyCodingMethod_PartitionedRiceContents *object);
  89098. FLAC__bool FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(FLAC__EntropyCodingMethod_PartitionedRiceContents *object, unsigned max_partition_order);
  89099. #endif
  89100. /********* End of inlined file: format.h *********/
  89101. /*
  89102. * FLAC__fixed_compute_best_predictor()
  89103. * --------------------------------------------------------------------
  89104. * Compute the best fixed predictor and the expected bits-per-sample
  89105. * of the residual signal for each order. The _wide() version uses
  89106. * 64-bit integers which is statistically necessary when bits-per-
  89107. * sample + log2(blocksize) > 30
  89108. *
  89109. * IN data[0,data_len-1]
  89110. * IN data_len
  89111. * OUT residual_bits_per_sample[0,FLAC__MAX_FIXED_ORDER]
  89112. */
  89113. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  89114. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  89115. # ifndef FLAC__NO_ASM
  89116. # ifdef FLAC__CPU_IA32
  89117. # ifdef FLAC__HAS_NASM
  89118. 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]);
  89119. # endif
  89120. # endif
  89121. # endif
  89122. 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]);
  89123. #else
  89124. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  89125. 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]);
  89126. #endif
  89127. /*
  89128. * FLAC__fixed_compute_residual()
  89129. * --------------------------------------------------------------------
  89130. * Compute the residual signal obtained from sutracting the predicted
  89131. * signal from the original.
  89132. *
  89133. * IN data[-order,data_len-1] original signal (NOTE THE INDICES!)
  89134. * IN data_len length of original signal
  89135. * IN order <= FLAC__MAX_FIXED_ORDER fixed-predictor order
  89136. * OUT residual[0,data_len-1] residual signal
  89137. */
  89138. void FLAC__fixed_compute_residual(const FLAC__int32 data[], unsigned data_len, unsigned order, FLAC__int32 residual[]);
  89139. /*
  89140. * FLAC__fixed_restore_signal()
  89141. * --------------------------------------------------------------------
  89142. * Restore the original signal by summing the residual and the
  89143. * predictor.
  89144. *
  89145. * IN residual[0,data_len-1] residual signal
  89146. * IN data_len length of original signal
  89147. * IN order <= FLAC__MAX_FIXED_ORDER fixed-predictor order
  89148. * *** IMPORTANT: the caller must pass in the historical samples:
  89149. * IN data[-order,-1] previously-reconstructed historical samples
  89150. * OUT data[0,data_len-1] original signal
  89151. */
  89152. void FLAC__fixed_restore_signal(const FLAC__int32 residual[], unsigned data_len, unsigned order, FLAC__int32 data[]);
  89153. #endif
  89154. /********* End of inlined file: fixed.h *********/
  89155. #ifndef M_LN2
  89156. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  89157. #define M_LN2 0.69314718055994530942
  89158. #endif
  89159. #ifdef min
  89160. #undef min
  89161. #endif
  89162. #define min(x,y) ((x) < (y)? (x) : (y))
  89163. #ifdef local_abs
  89164. #undef local_abs
  89165. #endif
  89166. #define local_abs(x) ((unsigned)((x)<0? -(x) : (x)))
  89167. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  89168. /* rbps stands for residual bits per sample
  89169. *
  89170. * (ln(2) * err)
  89171. * rbps = log (-----------)
  89172. * 2 ( n )
  89173. */
  89174. static FLAC__fixedpoint local__compute_rbps_integerized(FLAC__uint32 err, FLAC__uint32 n)
  89175. {
  89176. FLAC__uint32 rbps;
  89177. unsigned bits; /* the number of bits required to represent a number */
  89178. int fracbits; /* the number of bits of rbps that comprise the fractional part */
  89179. FLAC__ASSERT(sizeof(rbps) == sizeof(FLAC__fixedpoint));
  89180. FLAC__ASSERT(err > 0);
  89181. FLAC__ASSERT(n > 0);
  89182. FLAC__ASSERT(n <= FLAC__MAX_BLOCK_SIZE);
  89183. if(err <= n)
  89184. return 0;
  89185. /*
  89186. * The above two things tell us 1) n fits in 16 bits; 2) err/n > 1.
  89187. * These allow us later to know we won't lose too much precision in the
  89188. * fixed-point division (err<<fracbits)/n.
  89189. */
  89190. fracbits = (8*sizeof(err)) - (FLAC__bitmath_ilog2(err)+1);
  89191. err <<= fracbits;
  89192. err /= n;
  89193. /* err now holds err/n with fracbits fractional bits */
  89194. /*
  89195. * Whittle err down to 16 bits max. 16 significant bits is enough for
  89196. * our purposes.
  89197. */
  89198. FLAC__ASSERT(err > 0);
  89199. bits = FLAC__bitmath_ilog2(err)+1;
  89200. if(bits > 16) {
  89201. err >>= (bits-16);
  89202. fracbits -= (bits-16);
  89203. }
  89204. rbps = (FLAC__uint32)err;
  89205. /* Multiply by fixed-point version of ln(2), with 16 fractional bits */
  89206. rbps *= FLAC__FP_LN2;
  89207. fracbits += 16;
  89208. FLAC__ASSERT(fracbits >= 0);
  89209. /* FLAC__fixedpoint_log2 requires fracbits%4 to be 0 */
  89210. {
  89211. const int f = fracbits & 3;
  89212. if(f) {
  89213. rbps >>= f;
  89214. fracbits -= f;
  89215. }
  89216. }
  89217. rbps = FLAC__fixedpoint_log2(rbps, fracbits, (unsigned)(-1));
  89218. if(rbps == 0)
  89219. return 0;
  89220. /*
  89221. * The return value must have 16 fractional bits. Since the whole part
  89222. * of the base-2 log of a 32 bit number must fit in 5 bits, and fracbits
  89223. * must be >= -3, these assertion allows us to be able to shift rbps
  89224. * left if necessary to get 16 fracbits without losing any bits of the
  89225. * whole part of rbps.
  89226. *
  89227. * There is a slight chance due to accumulated error that the whole part
  89228. * will require 6 bits, so we use 6 in the assertion. Really though as
  89229. * long as it fits in 13 bits (32 - (16 - (-3))) we are fine.
  89230. */
  89231. FLAC__ASSERT((int)FLAC__bitmath_ilog2(rbps)+1 <= fracbits + 6);
  89232. FLAC__ASSERT(fracbits >= -3);
  89233. /* now shift the decimal point into place */
  89234. if(fracbits < 16)
  89235. return rbps << (16-fracbits);
  89236. else if(fracbits > 16)
  89237. return rbps >> (fracbits-16);
  89238. else
  89239. return rbps;
  89240. }
  89241. static FLAC__fixedpoint local__compute_rbps_wide_integerized(FLAC__uint64 err, FLAC__uint32 n)
  89242. {
  89243. FLAC__uint32 rbps;
  89244. unsigned bits; /* the number of bits required to represent a number */
  89245. int fracbits; /* the number of bits of rbps that comprise the fractional part */
  89246. FLAC__ASSERT(sizeof(rbps) == sizeof(FLAC__fixedpoint));
  89247. FLAC__ASSERT(err > 0);
  89248. FLAC__ASSERT(n > 0);
  89249. FLAC__ASSERT(n <= FLAC__MAX_BLOCK_SIZE);
  89250. if(err <= n)
  89251. return 0;
  89252. /*
  89253. * The above two things tell us 1) n fits in 16 bits; 2) err/n > 1.
  89254. * These allow us later to know we won't lose too much precision in the
  89255. * fixed-point division (err<<fracbits)/n.
  89256. */
  89257. fracbits = (8*sizeof(err)) - (FLAC__bitmath_ilog2_wide(err)+1);
  89258. err <<= fracbits;
  89259. err /= n;
  89260. /* err now holds err/n with fracbits fractional bits */
  89261. /*
  89262. * Whittle err down to 16 bits max. 16 significant bits is enough for
  89263. * our purposes.
  89264. */
  89265. FLAC__ASSERT(err > 0);
  89266. bits = FLAC__bitmath_ilog2_wide(err)+1;
  89267. if(bits > 16) {
  89268. err >>= (bits-16);
  89269. fracbits -= (bits-16);
  89270. }
  89271. rbps = (FLAC__uint32)err;
  89272. /* Multiply by fixed-point version of ln(2), with 16 fractional bits */
  89273. rbps *= FLAC__FP_LN2;
  89274. fracbits += 16;
  89275. FLAC__ASSERT(fracbits >= 0);
  89276. /* FLAC__fixedpoint_log2 requires fracbits%4 to be 0 */
  89277. {
  89278. const int f = fracbits & 3;
  89279. if(f) {
  89280. rbps >>= f;
  89281. fracbits -= f;
  89282. }
  89283. }
  89284. rbps = FLAC__fixedpoint_log2(rbps, fracbits, (unsigned)(-1));
  89285. if(rbps == 0)
  89286. return 0;
  89287. /*
  89288. * The return value must have 16 fractional bits. Since the whole part
  89289. * of the base-2 log of a 32 bit number must fit in 5 bits, and fracbits
  89290. * must be >= -3, these assertion allows us to be able to shift rbps
  89291. * left if necessary to get 16 fracbits without losing any bits of the
  89292. * whole part of rbps.
  89293. *
  89294. * There is a slight chance due to accumulated error that the whole part
  89295. * will require 6 bits, so we use 6 in the assertion. Really though as
  89296. * long as it fits in 13 bits (32 - (16 - (-3))) we are fine.
  89297. */
  89298. FLAC__ASSERT((int)FLAC__bitmath_ilog2(rbps)+1 <= fracbits + 6);
  89299. FLAC__ASSERT(fracbits >= -3);
  89300. /* now shift the decimal point into place */
  89301. if(fracbits < 16)
  89302. return rbps << (16-fracbits);
  89303. else if(fracbits > 16)
  89304. return rbps >> (fracbits-16);
  89305. else
  89306. return rbps;
  89307. }
  89308. #endif
  89309. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  89310. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1])
  89311. #else
  89312. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1])
  89313. #endif
  89314. {
  89315. FLAC__int32 last_error_0 = data[-1];
  89316. FLAC__int32 last_error_1 = data[-1] - data[-2];
  89317. FLAC__int32 last_error_2 = last_error_1 - (data[-2] - data[-3]);
  89318. FLAC__int32 last_error_3 = last_error_2 - (data[-2] - 2*data[-3] + data[-4]);
  89319. FLAC__int32 error, save;
  89320. FLAC__uint32 total_error_0 = 0, total_error_1 = 0, total_error_2 = 0, total_error_3 = 0, total_error_4 = 0;
  89321. unsigned i, order;
  89322. for(i = 0; i < data_len; i++) {
  89323. error = data[i] ; total_error_0 += local_abs(error); save = error;
  89324. error -= last_error_0; total_error_1 += local_abs(error); last_error_0 = save; save = error;
  89325. error -= last_error_1; total_error_2 += local_abs(error); last_error_1 = save; save = error;
  89326. error -= last_error_2; total_error_3 += local_abs(error); last_error_2 = save; save = error;
  89327. error -= last_error_3; total_error_4 += local_abs(error); last_error_3 = save;
  89328. }
  89329. if(total_error_0 < min(min(min(total_error_1, total_error_2), total_error_3), total_error_4))
  89330. order = 0;
  89331. else if(total_error_1 < min(min(total_error_2, total_error_3), total_error_4))
  89332. order = 1;
  89333. else if(total_error_2 < min(total_error_3, total_error_4))
  89334. order = 2;
  89335. else if(total_error_3 < total_error_4)
  89336. order = 3;
  89337. else
  89338. order = 4;
  89339. /* Estimate the expected number of bits per residual signal sample. */
  89340. /* 'total_error*' is linearly related to the variance of the residual */
  89341. /* signal, so we use it directly to compute E(|x|) */
  89342. FLAC__ASSERT(data_len > 0 || total_error_0 == 0);
  89343. FLAC__ASSERT(data_len > 0 || total_error_1 == 0);
  89344. FLAC__ASSERT(data_len > 0 || total_error_2 == 0);
  89345. FLAC__ASSERT(data_len > 0 || total_error_3 == 0);
  89346. FLAC__ASSERT(data_len > 0 || total_error_4 == 0);
  89347. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  89348. 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);
  89349. 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);
  89350. 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);
  89351. 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);
  89352. 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);
  89353. #else
  89354. residual_bits_per_sample[0] = (total_error_0 > 0) ? local__compute_rbps_integerized(total_error_0, data_len) : 0;
  89355. residual_bits_per_sample[1] = (total_error_1 > 0) ? local__compute_rbps_integerized(total_error_1, data_len) : 0;
  89356. residual_bits_per_sample[2] = (total_error_2 > 0) ? local__compute_rbps_integerized(total_error_2, data_len) : 0;
  89357. residual_bits_per_sample[3] = (total_error_3 > 0) ? local__compute_rbps_integerized(total_error_3, data_len) : 0;
  89358. residual_bits_per_sample[4] = (total_error_4 > 0) ? local__compute_rbps_integerized(total_error_4, data_len) : 0;
  89359. #endif
  89360. return order;
  89361. }
  89362. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  89363. 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])
  89364. #else
  89365. 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])
  89366. #endif
  89367. {
  89368. FLAC__int32 last_error_0 = data[-1];
  89369. FLAC__int32 last_error_1 = data[-1] - data[-2];
  89370. FLAC__int32 last_error_2 = last_error_1 - (data[-2] - data[-3]);
  89371. FLAC__int32 last_error_3 = last_error_2 - (data[-2] - 2*data[-3] + data[-4]);
  89372. FLAC__int32 error, save;
  89373. /* total_error_* are 64-bits to avoid overflow when encoding
  89374. * erratic signals when the bits-per-sample and blocksize are
  89375. * large.
  89376. */
  89377. FLAC__uint64 total_error_0 = 0, total_error_1 = 0, total_error_2 = 0, total_error_3 = 0, total_error_4 = 0;
  89378. unsigned i, order;
  89379. for(i = 0; i < data_len; i++) {
  89380. error = data[i] ; total_error_0 += local_abs(error); save = error;
  89381. error -= last_error_0; total_error_1 += local_abs(error); last_error_0 = save; save = error;
  89382. error -= last_error_1; total_error_2 += local_abs(error); last_error_1 = save; save = error;
  89383. error -= last_error_2; total_error_3 += local_abs(error); last_error_2 = save; save = error;
  89384. error -= last_error_3; total_error_4 += local_abs(error); last_error_3 = save;
  89385. }
  89386. if(total_error_0 < min(min(min(total_error_1, total_error_2), total_error_3), total_error_4))
  89387. order = 0;
  89388. else if(total_error_1 < min(min(total_error_2, total_error_3), total_error_4))
  89389. order = 1;
  89390. else if(total_error_2 < min(total_error_3, total_error_4))
  89391. order = 2;
  89392. else if(total_error_3 < total_error_4)
  89393. order = 3;
  89394. else
  89395. order = 4;
  89396. /* Estimate the expected number of bits per residual signal sample. */
  89397. /* 'total_error*' is linearly related to the variance of the residual */
  89398. /* signal, so we use it directly to compute E(|x|) */
  89399. FLAC__ASSERT(data_len > 0 || total_error_0 == 0);
  89400. FLAC__ASSERT(data_len > 0 || total_error_1 == 0);
  89401. FLAC__ASSERT(data_len > 0 || total_error_2 == 0);
  89402. FLAC__ASSERT(data_len > 0 || total_error_3 == 0);
  89403. FLAC__ASSERT(data_len > 0 || total_error_4 == 0);
  89404. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  89405. #if defined _MSC_VER || defined __MINGW32__
  89406. /* with MSVC you have to spoon feed it the casting */
  89407. 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);
  89408. 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);
  89409. 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);
  89410. 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);
  89411. 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);
  89412. #else
  89413. 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);
  89414. 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);
  89415. 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);
  89416. 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);
  89417. 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);
  89418. #endif
  89419. #else
  89420. residual_bits_per_sample[0] = (total_error_0 > 0) ? local__compute_rbps_wide_integerized(total_error_0, data_len) : 0;
  89421. residual_bits_per_sample[1] = (total_error_1 > 0) ? local__compute_rbps_wide_integerized(total_error_1, data_len) : 0;
  89422. residual_bits_per_sample[2] = (total_error_2 > 0) ? local__compute_rbps_wide_integerized(total_error_2, data_len) : 0;
  89423. residual_bits_per_sample[3] = (total_error_3 > 0) ? local__compute_rbps_wide_integerized(total_error_3, data_len) : 0;
  89424. residual_bits_per_sample[4] = (total_error_4 > 0) ? local__compute_rbps_wide_integerized(total_error_4, data_len) : 0;
  89425. #endif
  89426. return order;
  89427. }
  89428. void FLAC__fixed_compute_residual(const FLAC__int32 data[], unsigned data_len, unsigned order, FLAC__int32 residual[])
  89429. {
  89430. const int idata_len = (int)data_len;
  89431. int i;
  89432. switch(order) {
  89433. case 0:
  89434. FLAC__ASSERT(sizeof(residual[0]) == sizeof(data[0]));
  89435. memcpy(residual, data, sizeof(residual[0])*data_len);
  89436. break;
  89437. case 1:
  89438. for(i = 0; i < idata_len; i++)
  89439. residual[i] = data[i] - data[i-1];
  89440. break;
  89441. case 2:
  89442. for(i = 0; i < idata_len; i++)
  89443. #if 1 /* OPT: may be faster with some compilers on some systems */
  89444. residual[i] = data[i] - (data[i-1] << 1) + data[i-2];
  89445. #else
  89446. residual[i] = data[i] - 2*data[i-1] + data[i-2];
  89447. #endif
  89448. break;
  89449. case 3:
  89450. for(i = 0; i < idata_len; i++)
  89451. #if 1 /* OPT: may be faster with some compilers on some systems */
  89452. residual[i] = data[i] - (((data[i-1]-data[i-2])<<1) + (data[i-1]-data[i-2])) - data[i-3];
  89453. #else
  89454. residual[i] = data[i] - 3*data[i-1] + 3*data[i-2] - data[i-3];
  89455. #endif
  89456. break;
  89457. case 4:
  89458. for(i = 0; i < idata_len; i++)
  89459. #if 1 /* OPT: may be faster with some compilers on some systems */
  89460. residual[i] = data[i] - ((data[i-1]+data[i-3])<<2) + ((data[i-2]<<2) + (data[i-2]<<1)) + data[i-4];
  89461. #else
  89462. residual[i] = data[i] - 4*data[i-1] + 6*data[i-2] - 4*data[i-3] + data[i-4];
  89463. #endif
  89464. break;
  89465. default:
  89466. FLAC__ASSERT(0);
  89467. }
  89468. }
  89469. void FLAC__fixed_restore_signal(const FLAC__int32 residual[], unsigned data_len, unsigned order, FLAC__int32 data[])
  89470. {
  89471. int i, idata_len = (int)data_len;
  89472. switch(order) {
  89473. case 0:
  89474. FLAC__ASSERT(sizeof(residual[0]) == sizeof(data[0]));
  89475. memcpy(data, residual, sizeof(residual[0])*data_len);
  89476. break;
  89477. case 1:
  89478. for(i = 0; i < idata_len; i++)
  89479. data[i] = residual[i] + data[i-1];
  89480. break;
  89481. case 2:
  89482. for(i = 0; i < idata_len; i++)
  89483. #if 1 /* OPT: may be faster with some compilers on some systems */
  89484. data[i] = residual[i] + (data[i-1]<<1) - data[i-2];
  89485. #else
  89486. data[i] = residual[i] + 2*data[i-1] - data[i-2];
  89487. #endif
  89488. break;
  89489. case 3:
  89490. for(i = 0; i < idata_len; i++)
  89491. #if 1 /* OPT: may be faster with some compilers on some systems */
  89492. data[i] = residual[i] + (((data[i-1]-data[i-2])<<1) + (data[i-1]-data[i-2])) + data[i-3];
  89493. #else
  89494. data[i] = residual[i] + 3*data[i-1] - 3*data[i-2] + data[i-3];
  89495. #endif
  89496. break;
  89497. case 4:
  89498. for(i = 0; i < idata_len; i++)
  89499. #if 1 /* OPT: may be faster with some compilers on some systems */
  89500. data[i] = residual[i] + ((data[i-1]+data[i-3])<<2) - ((data[i-2]<<2) + (data[i-2]<<1)) - data[i-4];
  89501. #else
  89502. data[i] = residual[i] + 4*data[i-1] - 6*data[i-2] + 4*data[i-3] - data[i-4];
  89503. #endif
  89504. break;
  89505. default:
  89506. FLAC__ASSERT(0);
  89507. }
  89508. }
  89509. #endif
  89510. /********* End of inlined file: fixed.c *********/
  89511. /********* Start of inlined file: float.c *********/
  89512. /********* Start of inlined file: juce_FlacHeader.h *********/
  89513. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  89514. // tasks..
  89515. #define VERSION "1.2.1"
  89516. #define FLAC__NO_DLL 1
  89517. #ifdef _MSC_VER
  89518. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  89519. #endif
  89520. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  89521. #define FLAC__SYS_DARWIN 1
  89522. #endif
  89523. /********* End of inlined file: juce_FlacHeader.h *********/
  89524. #if JUCE_USE_FLAC
  89525. #if HAVE_CONFIG_H
  89526. # include <config.h>
  89527. #endif
  89528. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  89529. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  89530. #ifdef _MSC_VER
  89531. #define FLAC__U64L(x) x
  89532. #else
  89533. #define FLAC__U64L(x) x##LLU
  89534. #endif
  89535. const FLAC__fixedpoint FLAC__FP_ZERO = 0;
  89536. const FLAC__fixedpoint FLAC__FP_ONE_HALF = 0x00008000;
  89537. const FLAC__fixedpoint FLAC__FP_ONE = 0x00010000;
  89538. const FLAC__fixedpoint FLAC__FP_LN2 = 45426;
  89539. const FLAC__fixedpoint FLAC__FP_E = 178145;
  89540. /* Lookup tables for Knuth's logarithm algorithm */
  89541. #define LOG2_LOOKUP_PRECISION 16
  89542. static const FLAC__uint32 log2_lookup[][LOG2_LOOKUP_PRECISION] = {
  89543. {
  89544. /*
  89545. * 0 fraction bits
  89546. */
  89547. /* undefined */ 0x00000000,
  89548. /* lg(2/1) = */ 0x00000001,
  89549. /* lg(4/3) = */ 0x00000000,
  89550. /* lg(8/7) = */ 0x00000000,
  89551. /* lg(16/15) = */ 0x00000000,
  89552. /* lg(32/31) = */ 0x00000000,
  89553. /* lg(64/63) = */ 0x00000000,
  89554. /* lg(128/127) = */ 0x00000000,
  89555. /* lg(256/255) = */ 0x00000000,
  89556. /* lg(512/511) = */ 0x00000000,
  89557. /* lg(1024/1023) = */ 0x00000000,
  89558. /* lg(2048/2047) = */ 0x00000000,
  89559. /* lg(4096/4095) = */ 0x00000000,
  89560. /* lg(8192/8191) = */ 0x00000000,
  89561. /* lg(16384/16383) = */ 0x00000000,
  89562. /* lg(32768/32767) = */ 0x00000000
  89563. },
  89564. {
  89565. /*
  89566. * 4 fraction bits
  89567. */
  89568. /* undefined */ 0x00000000,
  89569. /* lg(2/1) = */ 0x00000010,
  89570. /* lg(4/3) = */ 0x00000007,
  89571. /* lg(8/7) = */ 0x00000003,
  89572. /* lg(16/15) = */ 0x00000001,
  89573. /* lg(32/31) = */ 0x00000001,
  89574. /* lg(64/63) = */ 0x00000000,
  89575. /* lg(128/127) = */ 0x00000000,
  89576. /* lg(256/255) = */ 0x00000000,
  89577. /* lg(512/511) = */ 0x00000000,
  89578. /* lg(1024/1023) = */ 0x00000000,
  89579. /* lg(2048/2047) = */ 0x00000000,
  89580. /* lg(4096/4095) = */ 0x00000000,
  89581. /* lg(8192/8191) = */ 0x00000000,
  89582. /* lg(16384/16383) = */ 0x00000000,
  89583. /* lg(32768/32767) = */ 0x00000000
  89584. },
  89585. {
  89586. /*
  89587. * 8 fraction bits
  89588. */
  89589. /* undefined */ 0x00000000,
  89590. /* lg(2/1) = */ 0x00000100,
  89591. /* lg(4/3) = */ 0x0000006a,
  89592. /* lg(8/7) = */ 0x00000031,
  89593. /* lg(16/15) = */ 0x00000018,
  89594. /* lg(32/31) = */ 0x0000000c,
  89595. /* lg(64/63) = */ 0x00000006,
  89596. /* lg(128/127) = */ 0x00000003,
  89597. /* lg(256/255) = */ 0x00000001,
  89598. /* lg(512/511) = */ 0x00000001,
  89599. /* lg(1024/1023) = */ 0x00000000,
  89600. /* lg(2048/2047) = */ 0x00000000,
  89601. /* lg(4096/4095) = */ 0x00000000,
  89602. /* lg(8192/8191) = */ 0x00000000,
  89603. /* lg(16384/16383) = */ 0x00000000,
  89604. /* lg(32768/32767) = */ 0x00000000
  89605. },
  89606. {
  89607. /*
  89608. * 12 fraction bits
  89609. */
  89610. /* undefined */ 0x00000000,
  89611. /* lg(2/1) = */ 0x00001000,
  89612. /* lg(4/3) = */ 0x000006a4,
  89613. /* lg(8/7) = */ 0x00000315,
  89614. /* lg(16/15) = */ 0x0000017d,
  89615. /* lg(32/31) = */ 0x000000bc,
  89616. /* lg(64/63) = */ 0x0000005d,
  89617. /* lg(128/127) = */ 0x0000002e,
  89618. /* lg(256/255) = */ 0x00000017,
  89619. /* lg(512/511) = */ 0x0000000c,
  89620. /* lg(1024/1023) = */ 0x00000006,
  89621. /* lg(2048/2047) = */ 0x00000003,
  89622. /* lg(4096/4095) = */ 0x00000001,
  89623. /* lg(8192/8191) = */ 0x00000001,
  89624. /* lg(16384/16383) = */ 0x00000000,
  89625. /* lg(32768/32767) = */ 0x00000000
  89626. },
  89627. {
  89628. /*
  89629. * 16 fraction bits
  89630. */
  89631. /* undefined */ 0x00000000,
  89632. /* lg(2/1) = */ 0x00010000,
  89633. /* lg(4/3) = */ 0x00006a40,
  89634. /* lg(8/7) = */ 0x00003151,
  89635. /* lg(16/15) = */ 0x000017d6,
  89636. /* lg(32/31) = */ 0x00000bba,
  89637. /* lg(64/63) = */ 0x000005d1,
  89638. /* lg(128/127) = */ 0x000002e6,
  89639. /* lg(256/255) = */ 0x00000172,
  89640. /* lg(512/511) = */ 0x000000b9,
  89641. /* lg(1024/1023) = */ 0x0000005c,
  89642. /* lg(2048/2047) = */ 0x0000002e,
  89643. /* lg(4096/4095) = */ 0x00000017,
  89644. /* lg(8192/8191) = */ 0x0000000c,
  89645. /* lg(16384/16383) = */ 0x00000006,
  89646. /* lg(32768/32767) = */ 0x00000003
  89647. },
  89648. {
  89649. /*
  89650. * 20 fraction bits
  89651. */
  89652. /* undefined */ 0x00000000,
  89653. /* lg(2/1) = */ 0x00100000,
  89654. /* lg(4/3) = */ 0x0006a3fe,
  89655. /* lg(8/7) = */ 0x00031513,
  89656. /* lg(16/15) = */ 0x00017d60,
  89657. /* lg(32/31) = */ 0x0000bb9d,
  89658. /* lg(64/63) = */ 0x00005d10,
  89659. /* lg(128/127) = */ 0x00002e59,
  89660. /* lg(256/255) = */ 0x00001721,
  89661. /* lg(512/511) = */ 0x00000b8e,
  89662. /* lg(1024/1023) = */ 0x000005c6,
  89663. /* lg(2048/2047) = */ 0x000002e3,
  89664. /* lg(4096/4095) = */ 0x00000171,
  89665. /* lg(8192/8191) = */ 0x000000b9,
  89666. /* lg(16384/16383) = */ 0x0000005c,
  89667. /* lg(32768/32767) = */ 0x0000002e
  89668. },
  89669. {
  89670. /*
  89671. * 24 fraction bits
  89672. */
  89673. /* undefined */ 0x00000000,
  89674. /* lg(2/1) = */ 0x01000000,
  89675. /* lg(4/3) = */ 0x006a3fe6,
  89676. /* lg(8/7) = */ 0x00315130,
  89677. /* lg(16/15) = */ 0x0017d605,
  89678. /* lg(32/31) = */ 0x000bb9ca,
  89679. /* lg(64/63) = */ 0x0005d0fc,
  89680. /* lg(128/127) = */ 0x0002e58f,
  89681. /* lg(256/255) = */ 0x0001720e,
  89682. /* lg(512/511) = */ 0x0000b8d8,
  89683. /* lg(1024/1023) = */ 0x00005c61,
  89684. /* lg(2048/2047) = */ 0x00002e2d,
  89685. /* lg(4096/4095) = */ 0x00001716,
  89686. /* lg(8192/8191) = */ 0x00000b8b,
  89687. /* lg(16384/16383) = */ 0x000005c5,
  89688. /* lg(32768/32767) = */ 0x000002e3
  89689. },
  89690. {
  89691. /*
  89692. * 28 fraction bits
  89693. */
  89694. /* undefined */ 0x00000000,
  89695. /* lg(2/1) = */ 0x10000000,
  89696. /* lg(4/3) = */ 0x06a3fe5c,
  89697. /* lg(8/7) = */ 0x03151301,
  89698. /* lg(16/15) = */ 0x017d6049,
  89699. /* lg(32/31) = */ 0x00bb9ca6,
  89700. /* lg(64/63) = */ 0x005d0fba,
  89701. /* lg(128/127) = */ 0x002e58f7,
  89702. /* lg(256/255) = */ 0x001720da,
  89703. /* lg(512/511) = */ 0x000b8d87,
  89704. /* lg(1024/1023) = */ 0x0005c60b,
  89705. /* lg(2048/2047) = */ 0x0002e2d7,
  89706. /* lg(4096/4095) = */ 0x00017160,
  89707. /* lg(8192/8191) = */ 0x0000b8ad,
  89708. /* lg(16384/16383) = */ 0x00005c56,
  89709. /* lg(32768/32767) = */ 0x00002e2b
  89710. }
  89711. };
  89712. #if 0
  89713. static const FLAC__uint64 log2_lookup_wide[] = {
  89714. {
  89715. /*
  89716. * 32 fraction bits
  89717. */
  89718. /* undefined */ 0x00000000,
  89719. /* lg(2/1) = */ FLAC__U64L(0x100000000),
  89720. /* lg(4/3) = */ FLAC__U64L(0x6a3fe5c6),
  89721. /* lg(8/7) = */ FLAC__U64L(0x31513015),
  89722. /* lg(16/15) = */ FLAC__U64L(0x17d60497),
  89723. /* lg(32/31) = */ FLAC__U64L(0x0bb9ca65),
  89724. /* lg(64/63) = */ FLAC__U64L(0x05d0fba2),
  89725. /* lg(128/127) = */ FLAC__U64L(0x02e58f74),
  89726. /* lg(256/255) = */ FLAC__U64L(0x01720d9c),
  89727. /* lg(512/511) = */ FLAC__U64L(0x00b8d875),
  89728. /* lg(1024/1023) = */ FLAC__U64L(0x005c60aa),
  89729. /* lg(2048/2047) = */ FLAC__U64L(0x002e2d72),
  89730. /* lg(4096/4095) = */ FLAC__U64L(0x00171600),
  89731. /* lg(8192/8191) = */ FLAC__U64L(0x000b8ad2),
  89732. /* lg(16384/16383) = */ FLAC__U64L(0x0005c55d),
  89733. /* lg(32768/32767) = */ FLAC__U64L(0x0002e2ac)
  89734. },
  89735. {
  89736. /*
  89737. * 48 fraction bits
  89738. */
  89739. /* undefined */ 0x00000000,
  89740. /* lg(2/1) = */ FLAC__U64L(0x1000000000000),
  89741. /* lg(4/3) = */ FLAC__U64L(0x6a3fe5c60429),
  89742. /* lg(8/7) = */ FLAC__U64L(0x315130157f7a),
  89743. /* lg(16/15) = */ FLAC__U64L(0x17d60496cfbb),
  89744. /* lg(32/31) = */ FLAC__U64L(0xbb9ca64ecac),
  89745. /* lg(64/63) = */ FLAC__U64L(0x5d0fba187cd),
  89746. /* lg(128/127) = */ FLAC__U64L(0x2e58f7441ee),
  89747. /* lg(256/255) = */ FLAC__U64L(0x1720d9c06a8),
  89748. /* lg(512/511) = */ FLAC__U64L(0xb8d8752173),
  89749. /* lg(1024/1023) = */ FLAC__U64L(0x5c60aa252e),
  89750. /* lg(2048/2047) = */ FLAC__U64L(0x2e2d71b0d8),
  89751. /* lg(4096/4095) = */ FLAC__U64L(0x1716001719),
  89752. /* lg(8192/8191) = */ FLAC__U64L(0xb8ad1de1b),
  89753. /* lg(16384/16383) = */ FLAC__U64L(0x5c55d640d),
  89754. /* lg(32768/32767) = */ FLAC__U64L(0x2e2abcf52)
  89755. }
  89756. };
  89757. #endif
  89758. FLAC__uint32 FLAC__fixedpoint_log2(FLAC__uint32 x, unsigned fracbits, unsigned precision)
  89759. {
  89760. const FLAC__uint32 ONE = (1u << fracbits);
  89761. const FLAC__uint32 *table = log2_lookup[fracbits >> 2];
  89762. FLAC__ASSERT(fracbits < 32);
  89763. FLAC__ASSERT((fracbits & 0x3) == 0);
  89764. if(x < ONE)
  89765. return 0;
  89766. if(precision > LOG2_LOOKUP_PRECISION)
  89767. precision = LOG2_LOOKUP_PRECISION;
  89768. /* Knuth's algorithm for computing logarithms, optimized for base-2 with lookup tables */
  89769. {
  89770. FLAC__uint32 y = 0;
  89771. FLAC__uint32 z = x >> 1, k = 1;
  89772. while (x > ONE && k < precision) {
  89773. if (x - z >= ONE) {
  89774. x -= z;
  89775. z = x >> k;
  89776. y += table[k];
  89777. }
  89778. else {
  89779. z >>= 1;
  89780. k++;
  89781. }
  89782. }
  89783. return y;
  89784. }
  89785. }
  89786. #endif /* defined FLAC__INTEGER_ONLY_LIBRARY */
  89787. #endif
  89788. /********* End of inlined file: float.c *********/
  89789. /********* Start of inlined file: format.c *********/
  89790. /********* Start of inlined file: juce_FlacHeader.h *********/
  89791. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  89792. // tasks..
  89793. #define VERSION "1.2.1"
  89794. #define FLAC__NO_DLL 1
  89795. #ifdef _MSC_VER
  89796. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  89797. #endif
  89798. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  89799. #define FLAC__SYS_DARWIN 1
  89800. #endif
  89801. /********* End of inlined file: juce_FlacHeader.h *********/
  89802. #if JUCE_USE_FLAC
  89803. #if HAVE_CONFIG_H
  89804. # include <config.h>
  89805. #endif
  89806. #include <stdio.h>
  89807. #include <stdlib.h> /* for qsort() */
  89808. #include <string.h> /* for memset() */
  89809. #ifndef FLaC__INLINE
  89810. #define FLaC__INLINE
  89811. #endif
  89812. #ifdef min
  89813. #undef min
  89814. #endif
  89815. #define min(a,b) ((a)<(b)?(a):(b))
  89816. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  89817. #ifdef _MSC_VER
  89818. #define FLAC__U64L(x) x
  89819. #else
  89820. #define FLAC__U64L(x) x##LLU
  89821. #endif
  89822. /* VERSION should come from configure */
  89823. FLAC_API const char *FLAC__VERSION_STRING = VERSION
  89824. ;
  89825. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINW32__
  89826. /* yet one more hack because of MSVC6: */
  89827. FLAC_API const char *FLAC__VENDOR_STRING = "reference libFLAC 1.2.1 20070917";
  89828. #else
  89829. FLAC_API const char *FLAC__VENDOR_STRING = "reference libFLAC " VERSION " 20070917";
  89830. #endif
  89831. FLAC_API const FLAC__byte FLAC__STREAM_SYNC_STRING[4] = { 'f','L','a','C' };
  89832. FLAC_API const unsigned FLAC__STREAM_SYNC = 0x664C6143;
  89833. FLAC_API const unsigned FLAC__STREAM_SYNC_LEN = 32; /* bits */
  89834. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN = 16; /* bits */
  89835. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN = 16; /* bits */
  89836. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN = 24; /* bits */
  89837. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN = 24; /* bits */
  89838. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN = 20; /* bits */
  89839. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN = 3; /* bits */
  89840. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN = 5; /* bits */
  89841. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN = 36; /* bits */
  89842. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MD5SUM_LEN = 128; /* bits */
  89843. FLAC_API const unsigned FLAC__STREAM_METADATA_APPLICATION_ID_LEN = 32; /* bits */
  89844. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN = 64; /* bits */
  89845. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN = 64; /* bits */
  89846. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN = 16; /* bits */
  89847. FLAC_API const FLAC__uint64 FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER = FLAC__U64L(0xffffffffffffffff);
  89848. FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN = 32; /* bits */
  89849. FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN = 32; /* bits */
  89850. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN = 64; /* bits */
  89851. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN = 8; /* bits */
  89852. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN = 3*8; /* bits */
  89853. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN = 64; /* bits */
  89854. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN = 8; /* bits */
  89855. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN = 12*8; /* bits */
  89856. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN = 1; /* bit */
  89857. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN = 1; /* bit */
  89858. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN = 6+13*8; /* bits */
  89859. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN = 8; /* bits */
  89860. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN = 128*8; /* bits */
  89861. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN = 64; /* bits */
  89862. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN = 1; /* bit */
  89863. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN = 7+258*8; /* bits */
  89864. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN = 8; /* bits */
  89865. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_TYPE_LEN = 32; /* bits */
  89866. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN = 32; /* bits */
  89867. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN = 32; /* bits */
  89868. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN = 32; /* bits */
  89869. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN = 32; /* bits */
  89870. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN = 32; /* bits */
  89871. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_COLORS_LEN = 32; /* bits */
  89872. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN = 32; /* bits */
  89873. FLAC_API const unsigned FLAC__STREAM_METADATA_IS_LAST_LEN = 1; /* bits */
  89874. FLAC_API const unsigned FLAC__STREAM_METADATA_TYPE_LEN = 7; /* bits */
  89875. FLAC_API const unsigned FLAC__STREAM_METADATA_LENGTH_LEN = 24; /* bits */
  89876. FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC = 0x3ffe;
  89877. FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC_LEN = 14; /* bits */
  89878. FLAC_API const unsigned FLAC__FRAME_HEADER_RESERVED_LEN = 1; /* bits */
  89879. FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN = 1; /* bits */
  89880. FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCK_SIZE_LEN = 4; /* bits */
  89881. FLAC_API const unsigned FLAC__FRAME_HEADER_SAMPLE_RATE_LEN = 4; /* bits */
  89882. FLAC_API const unsigned FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN = 4; /* bits */
  89883. FLAC_API const unsigned FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN = 3; /* bits */
  89884. FLAC_API const unsigned FLAC__FRAME_HEADER_ZERO_PAD_LEN = 1; /* bits */
  89885. FLAC_API const unsigned FLAC__FRAME_HEADER_CRC_LEN = 8; /* bits */
  89886. FLAC_API const unsigned FLAC__FRAME_FOOTER_CRC_LEN = 16; /* bits */
  89887. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_TYPE_LEN = 2; /* bits */
  89888. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN = 4; /* bits */
  89889. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN = 4; /* bits */
  89890. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN = 5; /* bits */
  89891. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN = 5; /* bits */
  89892. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER = 15; /* == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN)-1 */
  89893. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER = 31; /* == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN)-1 */
  89894. FLAC_API const char * const FLAC__EntropyCodingMethodTypeString[] = {
  89895. "PARTITIONED_RICE",
  89896. "PARTITIONED_RICE2"
  89897. };
  89898. FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN = 4; /* bits */
  89899. FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN = 5; /* bits */
  89900. FLAC_API const unsigned FLAC__SUBFRAME_ZERO_PAD_LEN = 1; /* bits */
  89901. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LEN = 6; /* bits */
  89902. FLAC_API const unsigned FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN = 1; /* bits */
  89903. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_CONSTANT_BYTE_ALIGNED_MASK = 0x00;
  89904. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_VERBATIM_BYTE_ALIGNED_MASK = 0x02;
  89905. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_FIXED_BYTE_ALIGNED_MASK = 0x10;
  89906. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LPC_BYTE_ALIGNED_MASK = 0x40;
  89907. FLAC_API const char * const FLAC__SubframeTypeString[] = {
  89908. "CONSTANT",
  89909. "VERBATIM",
  89910. "FIXED",
  89911. "LPC"
  89912. };
  89913. FLAC_API const char * const FLAC__ChannelAssignmentString[] = {
  89914. "INDEPENDENT",
  89915. "LEFT_SIDE",
  89916. "RIGHT_SIDE",
  89917. "MID_SIDE"
  89918. };
  89919. FLAC_API const char * const FLAC__FrameNumberTypeString[] = {
  89920. "FRAME_NUMBER_TYPE_FRAME_NUMBER",
  89921. "FRAME_NUMBER_TYPE_SAMPLE_NUMBER"
  89922. };
  89923. FLAC_API const char * const FLAC__MetadataTypeString[] = {
  89924. "STREAMINFO",
  89925. "PADDING",
  89926. "APPLICATION",
  89927. "SEEKTABLE",
  89928. "VORBIS_COMMENT",
  89929. "CUESHEET",
  89930. "PICTURE"
  89931. };
  89932. FLAC_API const char * const FLAC__StreamMetadata_Picture_TypeString[] = {
  89933. "Other",
  89934. "32x32 pixels 'file icon' (PNG only)",
  89935. "Other file icon",
  89936. "Cover (front)",
  89937. "Cover (back)",
  89938. "Leaflet page",
  89939. "Media (e.g. label side of CD)",
  89940. "Lead artist/lead performer/soloist",
  89941. "Artist/performer",
  89942. "Conductor",
  89943. "Band/Orchestra",
  89944. "Composer",
  89945. "Lyricist/text writer",
  89946. "Recording Location",
  89947. "During recording",
  89948. "During performance",
  89949. "Movie/video screen capture",
  89950. "A bright coloured fish",
  89951. "Illustration",
  89952. "Band/artist logotype",
  89953. "Publisher/Studio logotype"
  89954. };
  89955. FLAC_API FLAC__bool FLAC__format_sample_rate_is_valid(unsigned sample_rate)
  89956. {
  89957. if(sample_rate == 0 || sample_rate > FLAC__MAX_SAMPLE_RATE) {
  89958. return false;
  89959. }
  89960. else
  89961. return true;
  89962. }
  89963. FLAC_API FLAC__bool FLAC__format_sample_rate_is_subset(unsigned sample_rate)
  89964. {
  89965. if(
  89966. !FLAC__format_sample_rate_is_valid(sample_rate) ||
  89967. (
  89968. sample_rate >= (1u << 16) &&
  89969. !(sample_rate % 1000 == 0 || sample_rate % 10 == 0)
  89970. )
  89971. ) {
  89972. return false;
  89973. }
  89974. else
  89975. return true;
  89976. }
  89977. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  89978. FLAC_API FLAC__bool FLAC__format_seektable_is_legal(const FLAC__StreamMetadata_SeekTable *seek_table)
  89979. {
  89980. unsigned i;
  89981. FLAC__uint64 prev_sample_number = 0;
  89982. FLAC__bool got_prev = false;
  89983. FLAC__ASSERT(0 != seek_table);
  89984. for(i = 0; i < seek_table->num_points; i++) {
  89985. if(got_prev) {
  89986. if(
  89987. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  89988. seek_table->points[i].sample_number <= prev_sample_number
  89989. )
  89990. return false;
  89991. }
  89992. prev_sample_number = seek_table->points[i].sample_number;
  89993. got_prev = true;
  89994. }
  89995. return true;
  89996. }
  89997. /* used as the sort predicate for qsort() */
  89998. static int seekpoint_compare_(const FLAC__StreamMetadata_SeekPoint *l, const FLAC__StreamMetadata_SeekPoint *r)
  89999. {
  90000. /* we don't just 'return l->sample_number - r->sample_number' since the result (FLAC__int64) might overflow an 'int' */
  90001. if(l->sample_number == r->sample_number)
  90002. return 0;
  90003. else if(l->sample_number < r->sample_number)
  90004. return -1;
  90005. else
  90006. return 1;
  90007. }
  90008. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  90009. FLAC_API unsigned FLAC__format_seektable_sort(FLAC__StreamMetadata_SeekTable *seek_table)
  90010. {
  90011. unsigned i, j;
  90012. FLAC__bool first;
  90013. FLAC__ASSERT(0 != seek_table);
  90014. /* sort the seekpoints */
  90015. qsort(seek_table->points, seek_table->num_points, sizeof(FLAC__StreamMetadata_SeekPoint), (int (*)(const void *, const void *))seekpoint_compare_);
  90016. /* uniquify the seekpoints */
  90017. first = true;
  90018. for(i = j = 0; i < seek_table->num_points; i++) {
  90019. if(seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER) {
  90020. if(!first) {
  90021. if(seek_table->points[i].sample_number == seek_table->points[j-1].sample_number)
  90022. continue;
  90023. }
  90024. }
  90025. first = false;
  90026. seek_table->points[j++] = seek_table->points[i];
  90027. }
  90028. for(i = j; i < seek_table->num_points; i++) {
  90029. seek_table->points[i].sample_number = FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
  90030. seek_table->points[i].stream_offset = 0;
  90031. seek_table->points[i].frame_samples = 0;
  90032. }
  90033. return j;
  90034. }
  90035. /*
  90036. * also disallows non-shortest-form encodings, c.f.
  90037. * http://www.unicode.org/versions/corrigendum1.html
  90038. * and a more clear explanation at the end of this section:
  90039. * http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  90040. */
  90041. static FLaC__INLINE unsigned utf8len_(const FLAC__byte *utf8)
  90042. {
  90043. FLAC__ASSERT(0 != utf8);
  90044. if ((utf8[0] & 0x80) == 0) {
  90045. return 1;
  90046. }
  90047. else if ((utf8[0] & 0xE0) == 0xC0 && (utf8[1] & 0xC0) == 0x80) {
  90048. if ((utf8[0] & 0xFE) == 0xC0) /* overlong sequence check */
  90049. return 0;
  90050. return 2;
  90051. }
  90052. else if ((utf8[0] & 0xF0) == 0xE0 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80) {
  90053. if (utf8[0] == 0xE0 && (utf8[1] & 0xE0) == 0x80) /* overlong sequence check */
  90054. return 0;
  90055. /* illegal surrogates check (U+D800...U+DFFF and U+FFFE...U+FFFF) */
  90056. if (utf8[0] == 0xED && (utf8[1] & 0xE0) == 0xA0) /* D800-DFFF */
  90057. return 0;
  90058. if (utf8[0] == 0xEF && utf8[1] == 0xBF && (utf8[2] & 0xFE) == 0xBE) /* FFFE-FFFF */
  90059. return 0;
  90060. return 3;
  90061. }
  90062. else if ((utf8[0] & 0xF8) == 0xF0 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80 && (utf8[3] & 0xC0) == 0x80) {
  90063. if (utf8[0] == 0xF0 && (utf8[1] & 0xF0) == 0x80) /* overlong sequence check */
  90064. return 0;
  90065. return 4;
  90066. }
  90067. else if ((utf8[0] & 0xFC) == 0xF8 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80 && (utf8[3] & 0xC0) == 0x80 && (utf8[4] & 0xC0) == 0x80) {
  90068. if (utf8[0] == 0xF8 && (utf8[1] & 0xF8) == 0x80) /* overlong sequence check */
  90069. return 0;
  90070. return 5;
  90071. }
  90072. 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) {
  90073. if (utf8[0] == 0xFC && (utf8[1] & 0xFC) == 0x80) /* overlong sequence check */
  90074. return 0;
  90075. return 6;
  90076. }
  90077. else {
  90078. return 0;
  90079. }
  90080. }
  90081. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_name_is_legal(const char *name)
  90082. {
  90083. char c;
  90084. for(c = *name; c; c = *(++name))
  90085. if(c < 0x20 || c == 0x3d || c > 0x7d)
  90086. return false;
  90087. return true;
  90088. }
  90089. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_value_is_legal(const FLAC__byte *value, unsigned length)
  90090. {
  90091. if(length == (unsigned)(-1)) {
  90092. while(*value) {
  90093. unsigned n = utf8len_(value);
  90094. if(n == 0)
  90095. return false;
  90096. value += n;
  90097. }
  90098. }
  90099. else {
  90100. const FLAC__byte *end = value + length;
  90101. while(value < end) {
  90102. unsigned n = utf8len_(value);
  90103. if(n == 0)
  90104. return false;
  90105. value += n;
  90106. }
  90107. if(value != end)
  90108. return false;
  90109. }
  90110. return true;
  90111. }
  90112. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_is_legal(const FLAC__byte *entry, unsigned length)
  90113. {
  90114. const FLAC__byte *s, *end;
  90115. for(s = entry, end = s + length; s < end && *s != '='; s++) {
  90116. if(*s < 0x20 || *s > 0x7D)
  90117. return false;
  90118. }
  90119. if(s == end)
  90120. return false;
  90121. s++; /* skip '=' */
  90122. while(s < end) {
  90123. unsigned n = utf8len_(s);
  90124. if(n == 0)
  90125. return false;
  90126. s += n;
  90127. }
  90128. if(s != end)
  90129. return false;
  90130. return true;
  90131. }
  90132. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  90133. FLAC_API FLAC__bool FLAC__format_cuesheet_is_legal(const FLAC__StreamMetadata_CueSheet *cue_sheet, FLAC__bool check_cd_da_subset, const char **violation)
  90134. {
  90135. unsigned i, j;
  90136. if(check_cd_da_subset) {
  90137. if(cue_sheet->lead_in < 2 * 44100) {
  90138. if(violation) *violation = "CD-DA cue sheet must have a lead-in length of at least 2 seconds";
  90139. return false;
  90140. }
  90141. if(cue_sheet->lead_in % 588 != 0) {
  90142. if(violation) *violation = "CD-DA cue sheet lead-in length must be evenly divisible by 588 samples";
  90143. return false;
  90144. }
  90145. }
  90146. if(cue_sheet->num_tracks == 0) {
  90147. if(violation) *violation = "cue sheet must have at least one track (the lead-out)";
  90148. return false;
  90149. }
  90150. if(check_cd_da_subset && cue_sheet->tracks[cue_sheet->num_tracks-1].number != 170) {
  90151. if(violation) *violation = "CD-DA cue sheet must have a lead-out track number 170 (0xAA)";
  90152. return false;
  90153. }
  90154. for(i = 0; i < cue_sheet->num_tracks; i++) {
  90155. if(cue_sheet->tracks[i].number == 0) {
  90156. if(violation) *violation = "cue sheet may not have a track number 0";
  90157. return false;
  90158. }
  90159. if(check_cd_da_subset) {
  90160. if(!((cue_sheet->tracks[i].number >= 1 && cue_sheet->tracks[i].number <= 99) || cue_sheet->tracks[i].number == 170)) {
  90161. if(violation) *violation = "CD-DA cue sheet track number must be 1-99 or 170";
  90162. return false;
  90163. }
  90164. }
  90165. if(check_cd_da_subset && cue_sheet->tracks[i].offset % 588 != 0) {
  90166. if(violation) {
  90167. if(i == cue_sheet->num_tracks-1) /* the lead-out track... */
  90168. *violation = "CD-DA cue sheet lead-out offset must be evenly divisible by 588 samples";
  90169. else
  90170. *violation = "CD-DA cue sheet track offset must be evenly divisible by 588 samples";
  90171. }
  90172. return false;
  90173. }
  90174. if(i < cue_sheet->num_tracks - 1) {
  90175. if(cue_sheet->tracks[i].num_indices == 0) {
  90176. if(violation) *violation = "cue sheet track must have at least one index point";
  90177. return false;
  90178. }
  90179. if(cue_sheet->tracks[i].indices[0].number > 1) {
  90180. if(violation) *violation = "cue sheet track's first index number must be 0 or 1";
  90181. return false;
  90182. }
  90183. }
  90184. for(j = 0; j < cue_sheet->tracks[i].num_indices; j++) {
  90185. if(check_cd_da_subset && cue_sheet->tracks[i].indices[j].offset % 588 != 0) {
  90186. if(violation) *violation = "CD-DA cue sheet track index offset must be evenly divisible by 588 samples";
  90187. return false;
  90188. }
  90189. if(j > 0) {
  90190. if(cue_sheet->tracks[i].indices[j].number != cue_sheet->tracks[i].indices[j-1].number + 1) {
  90191. if(violation) *violation = "cue sheet track index numbers must increase by 1";
  90192. return false;
  90193. }
  90194. }
  90195. }
  90196. }
  90197. return true;
  90198. }
  90199. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  90200. FLAC_API FLAC__bool FLAC__format_picture_is_legal(const FLAC__StreamMetadata_Picture *picture, const char **violation)
  90201. {
  90202. char *p;
  90203. FLAC__byte *b;
  90204. for(p = picture->mime_type; *p; p++) {
  90205. if(*p < 0x20 || *p > 0x7e) {
  90206. if(violation) *violation = "MIME type string must contain only printable ASCII characters (0x20-0x7e)";
  90207. return false;
  90208. }
  90209. }
  90210. for(b = picture->description; *b; ) {
  90211. unsigned n = utf8len_(b);
  90212. if(n == 0) {
  90213. if(violation) *violation = "description string must be valid UTF-8";
  90214. return false;
  90215. }
  90216. b += n;
  90217. }
  90218. return true;
  90219. }
  90220. /*
  90221. * These routines are private to libFLAC
  90222. */
  90223. unsigned FLAC__format_get_max_rice_partition_order(unsigned blocksize, unsigned predictor_order)
  90224. {
  90225. return
  90226. FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(
  90227. FLAC__format_get_max_rice_partition_order_from_blocksize(blocksize),
  90228. blocksize,
  90229. predictor_order
  90230. );
  90231. }
  90232. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize(unsigned blocksize)
  90233. {
  90234. unsigned max_rice_partition_order = 0;
  90235. while(!(blocksize & 1)) {
  90236. max_rice_partition_order++;
  90237. blocksize >>= 1;
  90238. }
  90239. return min(FLAC__MAX_RICE_PARTITION_ORDER, max_rice_partition_order);
  90240. }
  90241. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(unsigned limit, unsigned blocksize, unsigned predictor_order)
  90242. {
  90243. unsigned max_rice_partition_order = limit;
  90244. while(max_rice_partition_order > 0 && (blocksize >> max_rice_partition_order) <= predictor_order)
  90245. max_rice_partition_order--;
  90246. FLAC__ASSERT(
  90247. (max_rice_partition_order == 0 && blocksize >= predictor_order) ||
  90248. (max_rice_partition_order > 0 && blocksize >> max_rice_partition_order > predictor_order)
  90249. );
  90250. return max_rice_partition_order;
  90251. }
  90252. void FLAC__format_entropy_coding_method_partitioned_rice_contents_init(FLAC__EntropyCodingMethod_PartitionedRiceContents *object)
  90253. {
  90254. FLAC__ASSERT(0 != object);
  90255. object->parameters = 0;
  90256. object->raw_bits = 0;
  90257. object->capacity_by_order = 0;
  90258. }
  90259. void FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(FLAC__EntropyCodingMethod_PartitionedRiceContents *object)
  90260. {
  90261. FLAC__ASSERT(0 != object);
  90262. if(0 != object->parameters)
  90263. free(object->parameters);
  90264. if(0 != object->raw_bits)
  90265. free(object->raw_bits);
  90266. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(object);
  90267. }
  90268. FLAC__bool FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(FLAC__EntropyCodingMethod_PartitionedRiceContents *object, unsigned max_partition_order)
  90269. {
  90270. FLAC__ASSERT(0 != object);
  90271. FLAC__ASSERT(object->capacity_by_order > 0 || (0 == object->parameters && 0 == object->raw_bits));
  90272. if(object->capacity_by_order < max_partition_order) {
  90273. if(0 == (object->parameters = (unsigned*)realloc(object->parameters, sizeof(unsigned)*(1 << max_partition_order))))
  90274. return false;
  90275. if(0 == (object->raw_bits = (unsigned*)realloc(object->raw_bits, sizeof(unsigned)*(1 << max_partition_order))))
  90276. return false;
  90277. memset(object->raw_bits, 0, sizeof(unsigned)*(1 << max_partition_order));
  90278. object->capacity_by_order = max_partition_order;
  90279. }
  90280. return true;
  90281. }
  90282. #endif
  90283. /********* End of inlined file: format.c *********/
  90284. /********* Start of inlined file: lpc_flac.c *********/
  90285. /********* Start of inlined file: juce_FlacHeader.h *********/
  90286. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  90287. // tasks..
  90288. #define VERSION "1.2.1"
  90289. #define FLAC__NO_DLL 1
  90290. #ifdef _MSC_VER
  90291. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  90292. #endif
  90293. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  90294. #define FLAC__SYS_DARWIN 1
  90295. #endif
  90296. /********* End of inlined file: juce_FlacHeader.h *********/
  90297. #if JUCE_USE_FLAC
  90298. #if HAVE_CONFIG_H
  90299. # include <config.h>
  90300. #endif
  90301. #include <math.h>
  90302. /********* Start of inlined file: lpc.h *********/
  90303. #ifndef FLAC__PRIVATE__LPC_H
  90304. #define FLAC__PRIVATE__LPC_H
  90305. #ifdef HAVE_CONFIG_H
  90306. #include <config.h>
  90307. #endif
  90308. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  90309. /*
  90310. * FLAC__lpc_window_data()
  90311. * --------------------------------------------------------------------
  90312. * Applies the given window to the data.
  90313. * OPT: asm implementation
  90314. *
  90315. * IN in[0,data_len-1]
  90316. * IN window[0,data_len-1]
  90317. * OUT out[0,lag-1]
  90318. * IN data_len
  90319. */
  90320. void FLAC__lpc_window_data(const FLAC__int32 in[], const FLAC__real window[], FLAC__real out[], unsigned data_len);
  90321. /*
  90322. * FLAC__lpc_compute_autocorrelation()
  90323. * --------------------------------------------------------------------
  90324. * Compute the autocorrelation for lags between 0 and lag-1.
  90325. * Assumes data[] outside of [0,data_len-1] == 0.
  90326. * Asserts that lag > 0.
  90327. *
  90328. * IN data[0,data_len-1]
  90329. * IN data_len
  90330. * IN 0 < lag <= data_len
  90331. * OUT autoc[0,lag-1]
  90332. */
  90333. void FLAC__lpc_compute_autocorrelation(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  90334. #ifndef FLAC__NO_ASM
  90335. # ifdef FLAC__CPU_IA32
  90336. # ifdef FLAC__HAS_NASM
  90337. void FLAC__lpc_compute_autocorrelation_asm_ia32(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  90338. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_4(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  90339. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_8(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  90340. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_12(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  90341. void FLAC__lpc_compute_autocorrelation_asm_ia32_3dnow(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  90342. # endif
  90343. # endif
  90344. #endif
  90345. /*
  90346. * FLAC__lpc_compute_lp_coefficients()
  90347. * --------------------------------------------------------------------
  90348. * Computes LP coefficients for orders 1..max_order.
  90349. * Do not call if autoc[0] == 0.0. This means the signal is zero
  90350. * and there is no point in calculating a predictor.
  90351. *
  90352. * IN autoc[0,max_order] autocorrelation values
  90353. * IN 0 < max_order <= FLAC__MAX_LPC_ORDER max LP order to compute
  90354. * OUT lp_coeff[0,max_order-1][0,max_order-1] LP coefficients for each order
  90355. * *** IMPORTANT:
  90356. * *** lp_coeff[0,max_order-1][max_order,FLAC__MAX_LPC_ORDER-1] are untouched
  90357. * OUT error[0,max_order-1] error for each order (more
  90358. * specifically, the variance of
  90359. * the error signal times # of
  90360. * samples in the signal)
  90361. *
  90362. * Example: if max_order is 9, the LP coefficients for order 9 will be
  90363. * in lp_coeff[8][0,8], the LP coefficients for order 8 will be
  90364. * in lp_coeff[7][0,7], etc.
  90365. */
  90366. void FLAC__lpc_compute_lp_coefficients(const FLAC__real autoc[], unsigned *max_order, FLAC__real lp_coeff[][FLAC__MAX_LPC_ORDER], FLAC__double error[]);
  90367. /*
  90368. * FLAC__lpc_quantize_coefficients()
  90369. * --------------------------------------------------------------------
  90370. * Quantizes the LP coefficients. NOTE: precision + bits_per_sample
  90371. * must be less than 32 (sizeof(FLAC__int32)*8).
  90372. *
  90373. * IN lp_coeff[0,order-1] LP coefficients
  90374. * IN order LP order
  90375. * IN FLAC__MIN_QLP_COEFF_PRECISION < precision
  90376. * desired precision (in bits, including sign
  90377. * bit) of largest coefficient
  90378. * OUT qlp_coeff[0,order-1] quantized coefficients
  90379. * OUT shift # of bits to shift right to get approximated
  90380. * LP coefficients. NOTE: could be negative.
  90381. * RETURN 0 => quantization OK
  90382. * 1 => coefficients require too much shifting for *shift to
  90383. * fit in the LPC subframe header. 'shift' is unset.
  90384. * 2 => coefficients are all zero, which is bad. 'shift' is
  90385. * unset.
  90386. */
  90387. int FLAC__lpc_quantize_coefficients(const FLAC__real lp_coeff[], unsigned order, unsigned precision, FLAC__int32 qlp_coeff[], int *shift);
  90388. /*
  90389. * FLAC__lpc_compute_residual_from_qlp_coefficients()
  90390. * --------------------------------------------------------------------
  90391. * Compute the residual signal obtained from sutracting the predicted
  90392. * signal from the original.
  90393. *
  90394. * IN data[-order,data_len-1] original signal (NOTE THE INDICES!)
  90395. * IN data_len length of original signal
  90396. * IN qlp_coeff[0,order-1] quantized LP coefficients
  90397. * IN order > 0 LP order
  90398. * IN lp_quantization quantization of LP coefficients in bits
  90399. * OUT residual[0,data_len-1] residual signal
  90400. */
  90401. 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[]);
  90402. 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[]);
  90403. #ifndef FLAC__NO_ASM
  90404. # ifdef FLAC__CPU_IA32
  90405. # ifdef FLAC__HAS_NASM
  90406. 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[]);
  90407. 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[]);
  90408. # endif
  90409. # endif
  90410. #endif
  90411. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  90412. /*
  90413. * FLAC__lpc_restore_signal()
  90414. * --------------------------------------------------------------------
  90415. * Restore the original signal by summing the residual and the
  90416. * predictor.
  90417. *
  90418. * IN residual[0,data_len-1] residual signal
  90419. * IN data_len length of original signal
  90420. * IN qlp_coeff[0,order-1] quantized LP coefficients
  90421. * IN order > 0 LP order
  90422. * IN lp_quantization quantization of LP coefficients in bits
  90423. * *** IMPORTANT: the caller must pass in the historical samples:
  90424. * IN data[-order,-1] previously-reconstructed historical samples
  90425. * OUT data[0,data_len-1] original signal
  90426. */
  90427. 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[]);
  90428. 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[]);
  90429. #ifndef FLAC__NO_ASM
  90430. # ifdef FLAC__CPU_IA32
  90431. # ifdef FLAC__HAS_NASM
  90432. 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[]);
  90433. 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[]);
  90434. # endif /* FLAC__HAS_NASM */
  90435. # elif defined FLAC__CPU_PPC
  90436. 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[]);
  90437. 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[]);
  90438. # endif/* FLAC__CPU_IA32 || FLAC__CPU_PPC */
  90439. #endif /* FLAC__NO_ASM */
  90440. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  90441. /*
  90442. * FLAC__lpc_compute_expected_bits_per_residual_sample()
  90443. * --------------------------------------------------------------------
  90444. * Compute the expected number of bits per residual signal sample
  90445. * based on the LP error (which is related to the residual variance).
  90446. *
  90447. * IN lpc_error >= 0.0 error returned from calculating LP coefficients
  90448. * IN total_samples > 0 # of samples in residual signal
  90449. * RETURN expected bits per sample
  90450. */
  90451. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample(FLAC__double lpc_error, unsigned total_samples);
  90452. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(FLAC__double lpc_error, FLAC__double error_scale);
  90453. /*
  90454. * FLAC__lpc_compute_best_order()
  90455. * --------------------------------------------------------------------
  90456. * Compute the best order from the array of signal errors returned
  90457. * during coefficient computation.
  90458. *
  90459. * IN lpc_error[0,max_order-1] >= 0.0 error returned from calculating LP coefficients
  90460. * IN max_order > 0 max LP order
  90461. * IN total_samples > 0 # of samples in residual signal
  90462. * IN overhead_bits_per_order # of bits overhead for each increased LP order
  90463. * (includes warmup sample size and quantized LP coefficient)
  90464. * RETURN [1,max_order] best order
  90465. */
  90466. unsigned FLAC__lpc_compute_best_order(const FLAC__double lpc_error[], unsigned max_order, unsigned total_samples, unsigned overhead_bits_per_order);
  90467. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  90468. #endif
  90469. /********* End of inlined file: lpc.h *********/
  90470. #if defined DEBUG || defined FLAC__OVERFLOW_DETECT || defined FLAC__OVERFLOW_DETECT_VERBOSE
  90471. #include <stdio.h>
  90472. #endif
  90473. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  90474. #ifndef M_LN2
  90475. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  90476. #define M_LN2 0.69314718055994530942
  90477. #endif
  90478. /* OPT: #undef'ing this may improve the speed on some architectures */
  90479. #define FLAC__LPC_UNROLLED_FILTER_LOOPS
  90480. void FLAC__lpc_window_data(const FLAC__int32 in[], const FLAC__real window[], FLAC__real out[], unsigned data_len)
  90481. {
  90482. unsigned i;
  90483. for(i = 0; i < data_len; i++)
  90484. out[i] = in[i] * window[i];
  90485. }
  90486. void FLAC__lpc_compute_autocorrelation(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[])
  90487. {
  90488. /* a readable, but slower, version */
  90489. #if 0
  90490. FLAC__real d;
  90491. unsigned i;
  90492. FLAC__ASSERT(lag > 0);
  90493. FLAC__ASSERT(lag <= data_len);
  90494. /*
  90495. * Technically we should subtract the mean first like so:
  90496. * for(i = 0; i < data_len; i++)
  90497. * data[i] -= mean;
  90498. * but it appears not to make enough of a difference to matter, and
  90499. * most signals are already closely centered around zero
  90500. */
  90501. while(lag--) {
  90502. for(i = lag, d = 0.0; i < data_len; i++)
  90503. d += data[i] * data[i - lag];
  90504. autoc[lag] = d;
  90505. }
  90506. #endif
  90507. /*
  90508. * this version tends to run faster because of better data locality
  90509. * ('data_len' is usually much larger than 'lag')
  90510. */
  90511. FLAC__real d;
  90512. unsigned sample, coeff;
  90513. const unsigned limit = data_len - lag;
  90514. FLAC__ASSERT(lag > 0);
  90515. FLAC__ASSERT(lag <= data_len);
  90516. for(coeff = 0; coeff < lag; coeff++)
  90517. autoc[coeff] = 0.0;
  90518. for(sample = 0; sample <= limit; sample++) {
  90519. d = data[sample];
  90520. for(coeff = 0; coeff < lag; coeff++)
  90521. autoc[coeff] += d * data[sample+coeff];
  90522. }
  90523. for(; sample < data_len; sample++) {
  90524. d = data[sample];
  90525. for(coeff = 0; coeff < data_len - sample; coeff++)
  90526. autoc[coeff] += d * data[sample+coeff];
  90527. }
  90528. }
  90529. void FLAC__lpc_compute_lp_coefficients(const FLAC__real autoc[], unsigned *max_order, FLAC__real lp_coeff[][FLAC__MAX_LPC_ORDER], FLAC__double error[])
  90530. {
  90531. unsigned i, j;
  90532. FLAC__double r, err, ref[FLAC__MAX_LPC_ORDER], lpc[FLAC__MAX_LPC_ORDER];
  90533. FLAC__ASSERT(0 != max_order);
  90534. FLAC__ASSERT(0 < *max_order);
  90535. FLAC__ASSERT(*max_order <= FLAC__MAX_LPC_ORDER);
  90536. FLAC__ASSERT(autoc[0] != 0.0);
  90537. err = autoc[0];
  90538. for(i = 0; i < *max_order; i++) {
  90539. /* Sum up this iteration's reflection coefficient. */
  90540. r = -autoc[i+1];
  90541. for(j = 0; j < i; j++)
  90542. r -= lpc[j] * autoc[i-j];
  90543. ref[i] = (r/=err);
  90544. /* Update LPC coefficients and total error. */
  90545. lpc[i]=r;
  90546. for(j = 0; j < (i>>1); j++) {
  90547. FLAC__double tmp = lpc[j];
  90548. lpc[j] += r * lpc[i-1-j];
  90549. lpc[i-1-j] += r * tmp;
  90550. }
  90551. if(i & 1)
  90552. lpc[j] += lpc[j] * r;
  90553. err *= (1.0 - r * r);
  90554. /* save this order */
  90555. for(j = 0; j <= i; j++)
  90556. lp_coeff[i][j] = (FLAC__real)(-lpc[j]); /* negate FIR filter coeff to get predictor coeff */
  90557. error[i] = err;
  90558. /* see SF bug #1601812 http://sourceforge.net/tracker/index.php?func=detail&aid=1601812&group_id=13478&atid=113478 */
  90559. if(err == 0.0) {
  90560. *max_order = i+1;
  90561. return;
  90562. }
  90563. }
  90564. }
  90565. int FLAC__lpc_quantize_coefficients(const FLAC__real lp_coeff[], unsigned order, unsigned precision, FLAC__int32 qlp_coeff[], int *shift)
  90566. {
  90567. unsigned i;
  90568. FLAC__double cmax;
  90569. FLAC__int32 qmax, qmin;
  90570. FLAC__ASSERT(precision > 0);
  90571. FLAC__ASSERT(precision >= FLAC__MIN_QLP_COEFF_PRECISION);
  90572. /* drop one bit for the sign; from here on out we consider only |lp_coeff[i]| */
  90573. precision--;
  90574. qmax = 1 << precision;
  90575. qmin = -qmax;
  90576. qmax--;
  90577. /* calc cmax = max( |lp_coeff[i]| ) */
  90578. cmax = 0.0;
  90579. for(i = 0; i < order; i++) {
  90580. const FLAC__double d = fabs(lp_coeff[i]);
  90581. if(d > cmax)
  90582. cmax = d;
  90583. }
  90584. if(cmax <= 0.0) {
  90585. /* => coefficients are all 0, which means our constant-detect didn't work */
  90586. return 2;
  90587. }
  90588. else {
  90589. const int max_shiftlimit = (1 << (FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN-1)) - 1;
  90590. const int min_shiftlimit = -max_shiftlimit - 1;
  90591. int log2cmax;
  90592. (void)frexp(cmax, &log2cmax);
  90593. log2cmax--;
  90594. *shift = (int)precision - log2cmax - 1;
  90595. if(*shift > max_shiftlimit)
  90596. *shift = max_shiftlimit;
  90597. else if(*shift < min_shiftlimit)
  90598. return 1;
  90599. }
  90600. if(*shift >= 0) {
  90601. FLAC__double error = 0.0;
  90602. FLAC__int32 q;
  90603. for(i = 0; i < order; i++) {
  90604. error += lp_coeff[i] * (1 << *shift);
  90605. #if 1 /* unfortunately lround() is C99 */
  90606. if(error >= 0.0)
  90607. q = (FLAC__int32)(error + 0.5);
  90608. else
  90609. q = (FLAC__int32)(error - 0.5);
  90610. #else
  90611. q = lround(error);
  90612. #endif
  90613. #ifdef FLAC__OVERFLOW_DETECT
  90614. if(q > qmax+1) /* we expect q==qmax+1 occasionally due to rounding */
  90615. 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]);
  90616. else if(q < qmin)
  90617. 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]);
  90618. #endif
  90619. if(q > qmax)
  90620. q = qmax;
  90621. else if(q < qmin)
  90622. q = qmin;
  90623. error -= q;
  90624. qlp_coeff[i] = q;
  90625. }
  90626. }
  90627. /* negative shift is very rare but due to design flaw, negative shift is
  90628. * a NOP in the decoder, so it must be handled specially by scaling down
  90629. * coeffs
  90630. */
  90631. else {
  90632. const int nshift = -(*shift);
  90633. FLAC__double error = 0.0;
  90634. FLAC__int32 q;
  90635. #ifdef DEBUG
  90636. fprintf(stderr,"FLAC__lpc_quantize_coefficients: negative shift=%d order=%u cmax=%f\n", *shift, order, cmax);
  90637. #endif
  90638. for(i = 0; i < order; i++) {
  90639. error += lp_coeff[i] / (1 << nshift);
  90640. #if 1 /* unfortunately lround() is C99 */
  90641. if(error >= 0.0)
  90642. q = (FLAC__int32)(error + 0.5);
  90643. else
  90644. q = (FLAC__int32)(error - 0.5);
  90645. #else
  90646. q = lround(error);
  90647. #endif
  90648. #ifdef FLAC__OVERFLOW_DETECT
  90649. if(q > qmax+1) /* we expect q==qmax+1 occasionally due to rounding */
  90650. 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]);
  90651. else if(q < qmin)
  90652. 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]);
  90653. #endif
  90654. if(q > qmax)
  90655. q = qmax;
  90656. else if(q < qmin)
  90657. q = qmin;
  90658. error -= q;
  90659. qlp_coeff[i] = q;
  90660. }
  90661. *shift = 0;
  90662. }
  90663. return 0;
  90664. }
  90665. 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[])
  90666. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  90667. {
  90668. FLAC__int64 sumo;
  90669. unsigned i, j;
  90670. FLAC__int32 sum;
  90671. const FLAC__int32 *history;
  90672. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  90673. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  90674. for(i=0;i<order;i++)
  90675. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  90676. fprintf(stderr,"\n");
  90677. #endif
  90678. FLAC__ASSERT(order > 0);
  90679. for(i = 0; i < data_len; i++) {
  90680. sumo = 0;
  90681. sum = 0;
  90682. history = data;
  90683. for(j = 0; j < order; j++) {
  90684. sum += qlp_coeff[j] * (*(--history));
  90685. sumo += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*history);
  90686. #if defined _MSC_VER
  90687. if(sumo > 2147483647I64 || sumo < -2147483648I64)
  90688. 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);
  90689. #else
  90690. if(sumo > 2147483647ll || sumo < -2147483648ll)
  90691. 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);
  90692. #endif
  90693. }
  90694. *(residual++) = *(data++) - (sum >> lp_quantization);
  90695. }
  90696. /* Here's a slower but clearer version:
  90697. for(i = 0; i < data_len; i++) {
  90698. sum = 0;
  90699. for(j = 0; j < order; j++)
  90700. sum += qlp_coeff[j] * data[i-j-1];
  90701. residual[i] = data[i] - (sum >> lp_quantization);
  90702. }
  90703. */
  90704. }
  90705. #else /* fully unrolled version for normal use */
  90706. {
  90707. int i;
  90708. FLAC__int32 sum;
  90709. FLAC__ASSERT(order > 0);
  90710. FLAC__ASSERT(order <= 32);
  90711. /*
  90712. * We do unique versions up to 12th order since that's the subset limit.
  90713. * Also they are roughly ordered to match frequency of occurrence to
  90714. * minimize branching.
  90715. */
  90716. if(order <= 12) {
  90717. if(order > 8) {
  90718. if(order > 10) {
  90719. if(order == 12) {
  90720. for(i = 0; i < (int)data_len; i++) {
  90721. sum = 0;
  90722. sum += qlp_coeff[11] * data[i-12];
  90723. sum += qlp_coeff[10] * data[i-11];
  90724. sum += qlp_coeff[9] * data[i-10];
  90725. sum += qlp_coeff[8] * data[i-9];
  90726. sum += qlp_coeff[7] * data[i-8];
  90727. sum += qlp_coeff[6] * data[i-7];
  90728. sum += qlp_coeff[5] * data[i-6];
  90729. sum += qlp_coeff[4] * data[i-5];
  90730. sum += qlp_coeff[3] * data[i-4];
  90731. sum += qlp_coeff[2] * data[i-3];
  90732. sum += qlp_coeff[1] * data[i-2];
  90733. sum += qlp_coeff[0] * data[i-1];
  90734. residual[i] = data[i] - (sum >> lp_quantization);
  90735. }
  90736. }
  90737. else { /* order == 11 */
  90738. for(i = 0; i < (int)data_len; i++) {
  90739. sum = 0;
  90740. sum += qlp_coeff[10] * data[i-11];
  90741. sum += qlp_coeff[9] * data[i-10];
  90742. sum += qlp_coeff[8] * data[i-9];
  90743. sum += qlp_coeff[7] * data[i-8];
  90744. sum += qlp_coeff[6] * data[i-7];
  90745. sum += qlp_coeff[5] * data[i-6];
  90746. sum += qlp_coeff[4] * data[i-5];
  90747. sum += qlp_coeff[3] * data[i-4];
  90748. sum += qlp_coeff[2] * data[i-3];
  90749. sum += qlp_coeff[1] * data[i-2];
  90750. sum += qlp_coeff[0] * data[i-1];
  90751. residual[i] = data[i] - (sum >> lp_quantization);
  90752. }
  90753. }
  90754. }
  90755. else {
  90756. if(order == 10) {
  90757. for(i = 0; i < (int)data_len; i++) {
  90758. sum = 0;
  90759. sum += qlp_coeff[9] * data[i-10];
  90760. sum += qlp_coeff[8] * data[i-9];
  90761. sum += qlp_coeff[7] * data[i-8];
  90762. sum += qlp_coeff[6] * data[i-7];
  90763. sum += qlp_coeff[5] * data[i-6];
  90764. sum += qlp_coeff[4] * data[i-5];
  90765. sum += qlp_coeff[3] * data[i-4];
  90766. sum += qlp_coeff[2] * data[i-3];
  90767. sum += qlp_coeff[1] * data[i-2];
  90768. sum += qlp_coeff[0] * data[i-1];
  90769. residual[i] = data[i] - (sum >> lp_quantization);
  90770. }
  90771. }
  90772. else { /* order == 9 */
  90773. for(i = 0; i < (int)data_len; i++) {
  90774. sum = 0;
  90775. sum += qlp_coeff[8] * data[i-9];
  90776. sum += qlp_coeff[7] * data[i-8];
  90777. sum += qlp_coeff[6] * data[i-7];
  90778. sum += qlp_coeff[5] * data[i-6];
  90779. sum += qlp_coeff[4] * data[i-5];
  90780. sum += qlp_coeff[3] * data[i-4];
  90781. sum += qlp_coeff[2] * data[i-3];
  90782. sum += qlp_coeff[1] * data[i-2];
  90783. sum += qlp_coeff[0] * data[i-1];
  90784. residual[i] = data[i] - (sum >> lp_quantization);
  90785. }
  90786. }
  90787. }
  90788. }
  90789. else if(order > 4) {
  90790. if(order > 6) {
  90791. if(order == 8) {
  90792. for(i = 0; i < (int)data_len; i++) {
  90793. sum = 0;
  90794. sum += qlp_coeff[7] * data[i-8];
  90795. sum += qlp_coeff[6] * data[i-7];
  90796. sum += qlp_coeff[5] * data[i-6];
  90797. sum += qlp_coeff[4] * data[i-5];
  90798. sum += qlp_coeff[3] * data[i-4];
  90799. sum += qlp_coeff[2] * data[i-3];
  90800. sum += qlp_coeff[1] * data[i-2];
  90801. sum += qlp_coeff[0] * data[i-1];
  90802. residual[i] = data[i] - (sum >> lp_quantization);
  90803. }
  90804. }
  90805. else { /* order == 7 */
  90806. for(i = 0; i < (int)data_len; i++) {
  90807. sum = 0;
  90808. sum += qlp_coeff[6] * data[i-7];
  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. }
  90819. else {
  90820. if(order == 6) {
  90821. for(i = 0; i < (int)data_len; i++) {
  90822. sum = 0;
  90823. sum += qlp_coeff[5] * data[i-6];
  90824. sum += qlp_coeff[4] * data[i-5];
  90825. sum += qlp_coeff[3] * data[i-4];
  90826. sum += qlp_coeff[2] * data[i-3];
  90827. sum += qlp_coeff[1] * data[i-2];
  90828. sum += qlp_coeff[0] * data[i-1];
  90829. residual[i] = data[i] - (sum >> lp_quantization);
  90830. }
  90831. }
  90832. else { /* order == 5 */
  90833. for(i = 0; i < (int)data_len; i++) {
  90834. sum = 0;
  90835. sum += qlp_coeff[4] * data[i-5];
  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. }
  90844. }
  90845. else {
  90846. if(order > 2) {
  90847. if(order == 4) {
  90848. for(i = 0; i < (int)data_len; i++) {
  90849. sum = 0;
  90850. sum += qlp_coeff[3] * data[i-4];
  90851. sum += qlp_coeff[2] * data[i-3];
  90852. sum += qlp_coeff[1] * data[i-2];
  90853. sum += qlp_coeff[0] * data[i-1];
  90854. residual[i] = data[i] - (sum >> lp_quantization);
  90855. }
  90856. }
  90857. else { /* order == 3 */
  90858. for(i = 0; i < (int)data_len; i++) {
  90859. sum = 0;
  90860. sum += qlp_coeff[2] * data[i-3];
  90861. sum += qlp_coeff[1] * data[i-2];
  90862. sum += qlp_coeff[0] * data[i-1];
  90863. residual[i] = data[i] - (sum >> lp_quantization);
  90864. }
  90865. }
  90866. }
  90867. else {
  90868. if(order == 2) {
  90869. for(i = 0; i < (int)data_len; i++) {
  90870. sum = 0;
  90871. sum += qlp_coeff[1] * data[i-2];
  90872. sum += qlp_coeff[0] * data[i-1];
  90873. residual[i] = data[i] - (sum >> lp_quantization);
  90874. }
  90875. }
  90876. else { /* order == 1 */
  90877. for(i = 0; i < (int)data_len; i++)
  90878. residual[i] = data[i] - ((qlp_coeff[0] * data[i-1]) >> lp_quantization);
  90879. }
  90880. }
  90881. }
  90882. }
  90883. else { /* order > 12 */
  90884. for(i = 0; i < (int)data_len; i++) {
  90885. sum = 0;
  90886. switch(order) {
  90887. case 32: sum += qlp_coeff[31] * data[i-32];
  90888. case 31: sum += qlp_coeff[30] * data[i-31];
  90889. case 30: sum += qlp_coeff[29] * data[i-30];
  90890. case 29: sum += qlp_coeff[28] * data[i-29];
  90891. case 28: sum += qlp_coeff[27] * data[i-28];
  90892. case 27: sum += qlp_coeff[26] * data[i-27];
  90893. case 26: sum += qlp_coeff[25] * data[i-26];
  90894. case 25: sum += qlp_coeff[24] * data[i-25];
  90895. case 24: sum += qlp_coeff[23] * data[i-24];
  90896. case 23: sum += qlp_coeff[22] * data[i-23];
  90897. case 22: sum += qlp_coeff[21] * data[i-22];
  90898. case 21: sum += qlp_coeff[20] * data[i-21];
  90899. case 20: sum += qlp_coeff[19] * data[i-20];
  90900. case 19: sum += qlp_coeff[18] * data[i-19];
  90901. case 18: sum += qlp_coeff[17] * data[i-18];
  90902. case 17: sum += qlp_coeff[16] * data[i-17];
  90903. case 16: sum += qlp_coeff[15] * data[i-16];
  90904. case 15: sum += qlp_coeff[14] * data[i-15];
  90905. case 14: sum += qlp_coeff[13] * data[i-14];
  90906. case 13: sum += qlp_coeff[12] * data[i-13];
  90907. sum += qlp_coeff[11] * data[i-12];
  90908. sum += qlp_coeff[10] * data[i-11];
  90909. sum += qlp_coeff[ 9] * data[i-10];
  90910. sum += qlp_coeff[ 8] * data[i- 9];
  90911. sum += qlp_coeff[ 7] * data[i- 8];
  90912. sum += qlp_coeff[ 6] * data[i- 7];
  90913. sum += qlp_coeff[ 5] * data[i- 6];
  90914. sum += qlp_coeff[ 4] * data[i- 5];
  90915. sum += qlp_coeff[ 3] * data[i- 4];
  90916. sum += qlp_coeff[ 2] * data[i- 3];
  90917. sum += qlp_coeff[ 1] * data[i- 2];
  90918. sum += qlp_coeff[ 0] * data[i- 1];
  90919. }
  90920. residual[i] = data[i] - (sum >> lp_quantization);
  90921. }
  90922. }
  90923. }
  90924. #endif
  90925. 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[])
  90926. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  90927. {
  90928. unsigned i, j;
  90929. FLAC__int64 sum;
  90930. const FLAC__int32 *history;
  90931. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  90932. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  90933. for(i=0;i<order;i++)
  90934. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  90935. fprintf(stderr,"\n");
  90936. #endif
  90937. FLAC__ASSERT(order > 0);
  90938. for(i = 0; i < data_len; i++) {
  90939. sum = 0;
  90940. history = data;
  90941. for(j = 0; j < order; j++)
  90942. sum += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*(--history));
  90943. if(FLAC__bitmath_silog2_wide(sum >> lp_quantization) > 32) {
  90944. #if defined _MSC_VER
  90945. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: OVERFLOW, i=%u, sum=%I64d\n", i, sum >> lp_quantization);
  90946. #else
  90947. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: OVERFLOW, i=%u, sum=%lld\n", i, (long long)(sum >> lp_quantization));
  90948. #endif
  90949. break;
  90950. }
  90951. if(FLAC__bitmath_silog2_wide((FLAC__int64)(*data) - (sum >> lp_quantization)) > 32) {
  90952. #if defined _MSC_VER
  90953. 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));
  90954. #else
  90955. 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)));
  90956. #endif
  90957. break;
  90958. }
  90959. *(residual++) = *(data++) - (FLAC__int32)(sum >> lp_quantization);
  90960. }
  90961. }
  90962. #else /* fully unrolled version for normal use */
  90963. {
  90964. int i;
  90965. FLAC__int64 sum;
  90966. FLAC__ASSERT(order > 0);
  90967. FLAC__ASSERT(order <= 32);
  90968. /*
  90969. * We do unique versions up to 12th order since that's the subset limit.
  90970. * Also they are roughly ordered to match frequency of occurrence to
  90971. * minimize branching.
  90972. */
  90973. if(order <= 12) {
  90974. if(order > 8) {
  90975. if(order > 10) {
  90976. if(order == 12) {
  90977. for(i = 0; i < (int)data_len; i++) {
  90978. sum = 0;
  90979. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  90980. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  90981. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  90982. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  90983. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  90984. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  90985. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  90986. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  90987. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  90988. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  90989. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  90990. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  90991. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  90992. }
  90993. }
  90994. else { /* order == 11 */
  90995. for(i = 0; i < (int)data_len; i++) {
  90996. sum = 0;
  90997. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  90998. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  90999. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  91000. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  91001. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  91002. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  91003. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  91004. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  91005. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  91006. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  91007. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  91008. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  91009. }
  91010. }
  91011. }
  91012. else {
  91013. if(order == 10) {
  91014. for(i = 0; i < (int)data_len; i++) {
  91015. sum = 0;
  91016. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  91017. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  91018. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  91019. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  91020. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  91021. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  91022. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  91023. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  91024. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  91025. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  91026. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  91027. }
  91028. }
  91029. else { /* order == 9 */
  91030. for(i = 0; i < (int)data_len; i++) {
  91031. sum = 0;
  91032. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  91033. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  91034. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  91035. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  91036. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  91037. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  91038. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  91039. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  91040. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  91041. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  91042. }
  91043. }
  91044. }
  91045. }
  91046. else if(order > 4) {
  91047. if(order > 6) {
  91048. if(order == 8) {
  91049. for(i = 0; i < (int)data_len; i++) {
  91050. sum = 0;
  91051. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  91052. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  91053. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  91054. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  91055. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  91056. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  91057. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  91058. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  91059. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  91060. }
  91061. }
  91062. else { /* order == 7 */
  91063. for(i = 0; i < (int)data_len; i++) {
  91064. sum = 0;
  91065. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  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. }
  91076. else {
  91077. if(order == 6) {
  91078. for(i = 0; i < (int)data_len; i++) {
  91079. sum = 0;
  91080. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  91081. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  91082. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  91083. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  91084. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  91085. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  91086. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  91087. }
  91088. }
  91089. else { /* order == 5 */
  91090. for(i = 0; i < (int)data_len; i++) {
  91091. sum = 0;
  91092. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  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. }
  91101. }
  91102. else {
  91103. if(order > 2) {
  91104. if(order == 4) {
  91105. for(i = 0; i < (int)data_len; i++) {
  91106. sum = 0;
  91107. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  91108. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  91109. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  91110. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  91111. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  91112. }
  91113. }
  91114. else { /* order == 3 */
  91115. for(i = 0; i < (int)data_len; i++) {
  91116. sum = 0;
  91117. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  91118. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  91119. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  91120. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  91121. }
  91122. }
  91123. }
  91124. else {
  91125. if(order == 2) {
  91126. for(i = 0; i < (int)data_len; i++) {
  91127. sum = 0;
  91128. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  91129. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  91130. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  91131. }
  91132. }
  91133. else { /* order == 1 */
  91134. for(i = 0; i < (int)data_len; i++)
  91135. residual[i] = data[i] - (FLAC__int32)((qlp_coeff[0] * (FLAC__int64)data[i-1]) >> lp_quantization);
  91136. }
  91137. }
  91138. }
  91139. }
  91140. else { /* order > 12 */
  91141. for(i = 0; i < (int)data_len; i++) {
  91142. sum = 0;
  91143. switch(order) {
  91144. case 32: sum += qlp_coeff[31] * (FLAC__int64)data[i-32];
  91145. case 31: sum += qlp_coeff[30] * (FLAC__int64)data[i-31];
  91146. case 30: sum += qlp_coeff[29] * (FLAC__int64)data[i-30];
  91147. case 29: sum += qlp_coeff[28] * (FLAC__int64)data[i-29];
  91148. case 28: sum += qlp_coeff[27] * (FLAC__int64)data[i-28];
  91149. case 27: sum += qlp_coeff[26] * (FLAC__int64)data[i-27];
  91150. case 26: sum += qlp_coeff[25] * (FLAC__int64)data[i-26];
  91151. case 25: sum += qlp_coeff[24] * (FLAC__int64)data[i-25];
  91152. case 24: sum += qlp_coeff[23] * (FLAC__int64)data[i-24];
  91153. case 23: sum += qlp_coeff[22] * (FLAC__int64)data[i-23];
  91154. case 22: sum += qlp_coeff[21] * (FLAC__int64)data[i-22];
  91155. case 21: sum += qlp_coeff[20] * (FLAC__int64)data[i-21];
  91156. case 20: sum += qlp_coeff[19] * (FLAC__int64)data[i-20];
  91157. case 19: sum += qlp_coeff[18] * (FLAC__int64)data[i-19];
  91158. case 18: sum += qlp_coeff[17] * (FLAC__int64)data[i-18];
  91159. case 17: sum += qlp_coeff[16] * (FLAC__int64)data[i-17];
  91160. case 16: sum += qlp_coeff[15] * (FLAC__int64)data[i-16];
  91161. case 15: sum += qlp_coeff[14] * (FLAC__int64)data[i-15];
  91162. case 14: sum += qlp_coeff[13] * (FLAC__int64)data[i-14];
  91163. case 13: sum += qlp_coeff[12] * (FLAC__int64)data[i-13];
  91164. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  91165. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  91166. sum += qlp_coeff[ 9] * (FLAC__int64)data[i-10];
  91167. sum += qlp_coeff[ 8] * (FLAC__int64)data[i- 9];
  91168. sum += qlp_coeff[ 7] * (FLAC__int64)data[i- 8];
  91169. sum += qlp_coeff[ 6] * (FLAC__int64)data[i- 7];
  91170. sum += qlp_coeff[ 5] * (FLAC__int64)data[i- 6];
  91171. sum += qlp_coeff[ 4] * (FLAC__int64)data[i- 5];
  91172. sum += qlp_coeff[ 3] * (FLAC__int64)data[i- 4];
  91173. sum += qlp_coeff[ 2] * (FLAC__int64)data[i- 3];
  91174. sum += qlp_coeff[ 1] * (FLAC__int64)data[i- 2];
  91175. sum += qlp_coeff[ 0] * (FLAC__int64)data[i- 1];
  91176. }
  91177. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  91178. }
  91179. }
  91180. }
  91181. #endif
  91182. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  91183. 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[])
  91184. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  91185. {
  91186. FLAC__int64 sumo;
  91187. unsigned i, j;
  91188. FLAC__int32 sum;
  91189. const FLAC__int32 *r = residual, *history;
  91190. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  91191. fprintf(stderr,"FLAC__lpc_restore_signal: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  91192. for(i=0;i<order;i++)
  91193. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  91194. fprintf(stderr,"\n");
  91195. #endif
  91196. FLAC__ASSERT(order > 0);
  91197. for(i = 0; i < data_len; i++) {
  91198. sumo = 0;
  91199. sum = 0;
  91200. history = data;
  91201. for(j = 0; j < order; j++) {
  91202. sum += qlp_coeff[j] * (*(--history));
  91203. sumo += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*history);
  91204. #if defined _MSC_VER
  91205. if(sumo > 2147483647I64 || sumo < -2147483648I64)
  91206. 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);
  91207. #else
  91208. if(sumo > 2147483647ll || sumo < -2147483648ll)
  91209. 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);
  91210. #endif
  91211. }
  91212. *(data++) = *(r++) + (sum >> lp_quantization);
  91213. }
  91214. /* Here's a slower but clearer version:
  91215. for(i = 0; i < data_len; i++) {
  91216. sum = 0;
  91217. for(j = 0; j < order; j++)
  91218. sum += qlp_coeff[j] * data[i-j-1];
  91219. data[i] = residual[i] + (sum >> lp_quantization);
  91220. }
  91221. */
  91222. }
  91223. #else /* fully unrolled version for normal use */
  91224. {
  91225. int i;
  91226. FLAC__int32 sum;
  91227. FLAC__ASSERT(order > 0);
  91228. FLAC__ASSERT(order <= 32);
  91229. /*
  91230. * We do unique versions up to 12th order since that's the subset limit.
  91231. * Also they are roughly ordered to match frequency of occurrence to
  91232. * minimize branching.
  91233. */
  91234. if(order <= 12) {
  91235. if(order > 8) {
  91236. if(order > 10) {
  91237. if(order == 12) {
  91238. for(i = 0; i < (int)data_len; i++) {
  91239. sum = 0;
  91240. sum += qlp_coeff[11] * data[i-12];
  91241. sum += qlp_coeff[10] * data[i-11];
  91242. sum += qlp_coeff[9] * data[i-10];
  91243. sum += qlp_coeff[8] * data[i-9];
  91244. sum += qlp_coeff[7] * data[i-8];
  91245. sum += qlp_coeff[6] * data[i-7];
  91246. sum += qlp_coeff[5] * data[i-6];
  91247. sum += qlp_coeff[4] * data[i-5];
  91248. sum += qlp_coeff[3] * data[i-4];
  91249. sum += qlp_coeff[2] * data[i-3];
  91250. sum += qlp_coeff[1] * data[i-2];
  91251. sum += qlp_coeff[0] * data[i-1];
  91252. data[i] = residual[i] + (sum >> lp_quantization);
  91253. }
  91254. }
  91255. else { /* order == 11 */
  91256. for(i = 0; i < (int)data_len; i++) {
  91257. sum = 0;
  91258. sum += qlp_coeff[10] * data[i-11];
  91259. sum += qlp_coeff[9] * data[i-10];
  91260. sum += qlp_coeff[8] * data[i-9];
  91261. sum += qlp_coeff[7] * data[i-8];
  91262. sum += qlp_coeff[6] * data[i-7];
  91263. sum += qlp_coeff[5] * data[i-6];
  91264. sum += qlp_coeff[4] * data[i-5];
  91265. sum += qlp_coeff[3] * data[i-4];
  91266. sum += qlp_coeff[2] * data[i-3];
  91267. sum += qlp_coeff[1] * data[i-2];
  91268. sum += qlp_coeff[0] * data[i-1];
  91269. data[i] = residual[i] + (sum >> lp_quantization);
  91270. }
  91271. }
  91272. }
  91273. else {
  91274. if(order == 10) {
  91275. for(i = 0; i < (int)data_len; i++) {
  91276. sum = 0;
  91277. sum += qlp_coeff[9] * data[i-10];
  91278. sum += qlp_coeff[8] * data[i-9];
  91279. sum += qlp_coeff[7] * data[i-8];
  91280. sum += qlp_coeff[6] * data[i-7];
  91281. sum += qlp_coeff[5] * data[i-6];
  91282. sum += qlp_coeff[4] * data[i-5];
  91283. sum += qlp_coeff[3] * data[i-4];
  91284. sum += qlp_coeff[2] * data[i-3];
  91285. sum += qlp_coeff[1] * data[i-2];
  91286. sum += qlp_coeff[0] * data[i-1];
  91287. data[i] = residual[i] + (sum >> lp_quantization);
  91288. }
  91289. }
  91290. else { /* order == 9 */
  91291. for(i = 0; i < (int)data_len; i++) {
  91292. sum = 0;
  91293. sum += qlp_coeff[8] * data[i-9];
  91294. sum += qlp_coeff[7] * data[i-8];
  91295. sum += qlp_coeff[6] * data[i-7];
  91296. sum += qlp_coeff[5] * data[i-6];
  91297. sum += qlp_coeff[4] * data[i-5];
  91298. sum += qlp_coeff[3] * data[i-4];
  91299. sum += qlp_coeff[2] * data[i-3];
  91300. sum += qlp_coeff[1] * data[i-2];
  91301. sum += qlp_coeff[0] * data[i-1];
  91302. data[i] = residual[i] + (sum >> lp_quantization);
  91303. }
  91304. }
  91305. }
  91306. }
  91307. else if(order > 4) {
  91308. if(order > 6) {
  91309. if(order == 8) {
  91310. for(i = 0; i < (int)data_len; i++) {
  91311. sum = 0;
  91312. sum += qlp_coeff[7] * data[i-8];
  91313. sum += qlp_coeff[6] * data[i-7];
  91314. sum += qlp_coeff[5] * data[i-6];
  91315. sum += qlp_coeff[4] * data[i-5];
  91316. sum += qlp_coeff[3] * data[i-4];
  91317. sum += qlp_coeff[2] * data[i-3];
  91318. sum += qlp_coeff[1] * data[i-2];
  91319. sum += qlp_coeff[0] * data[i-1];
  91320. data[i] = residual[i] + (sum >> lp_quantization);
  91321. }
  91322. }
  91323. else { /* order == 7 */
  91324. for(i = 0; i < (int)data_len; i++) {
  91325. sum = 0;
  91326. sum += qlp_coeff[6] * data[i-7];
  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. }
  91337. else {
  91338. if(order == 6) {
  91339. for(i = 0; i < (int)data_len; i++) {
  91340. sum = 0;
  91341. sum += qlp_coeff[5] * data[i-6];
  91342. sum += qlp_coeff[4] * data[i-5];
  91343. sum += qlp_coeff[3] * data[i-4];
  91344. sum += qlp_coeff[2] * data[i-3];
  91345. sum += qlp_coeff[1] * data[i-2];
  91346. sum += qlp_coeff[0] * data[i-1];
  91347. data[i] = residual[i] + (sum >> lp_quantization);
  91348. }
  91349. }
  91350. else { /* order == 5 */
  91351. for(i = 0; i < (int)data_len; i++) {
  91352. sum = 0;
  91353. sum += qlp_coeff[4] * data[i-5];
  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. }
  91362. }
  91363. else {
  91364. if(order > 2) {
  91365. if(order == 4) {
  91366. for(i = 0; i < (int)data_len; i++) {
  91367. sum = 0;
  91368. sum += qlp_coeff[3] * data[i-4];
  91369. sum += qlp_coeff[2] * data[i-3];
  91370. sum += qlp_coeff[1] * data[i-2];
  91371. sum += qlp_coeff[0] * data[i-1];
  91372. data[i] = residual[i] + (sum >> lp_quantization);
  91373. }
  91374. }
  91375. else { /* order == 3 */
  91376. for(i = 0; i < (int)data_len; i++) {
  91377. sum = 0;
  91378. sum += qlp_coeff[2] * data[i-3];
  91379. sum += qlp_coeff[1] * data[i-2];
  91380. sum += qlp_coeff[0] * data[i-1];
  91381. data[i] = residual[i] + (sum >> lp_quantization);
  91382. }
  91383. }
  91384. }
  91385. else {
  91386. if(order == 2) {
  91387. for(i = 0; i < (int)data_len; i++) {
  91388. sum = 0;
  91389. sum += qlp_coeff[1] * data[i-2];
  91390. sum += qlp_coeff[0] * data[i-1];
  91391. data[i] = residual[i] + (sum >> lp_quantization);
  91392. }
  91393. }
  91394. else { /* order == 1 */
  91395. for(i = 0; i < (int)data_len; i++)
  91396. data[i] = residual[i] + ((qlp_coeff[0] * data[i-1]) >> lp_quantization);
  91397. }
  91398. }
  91399. }
  91400. }
  91401. else { /* order > 12 */
  91402. for(i = 0; i < (int)data_len; i++) {
  91403. sum = 0;
  91404. switch(order) {
  91405. case 32: sum += qlp_coeff[31] * data[i-32];
  91406. case 31: sum += qlp_coeff[30] * data[i-31];
  91407. case 30: sum += qlp_coeff[29] * data[i-30];
  91408. case 29: sum += qlp_coeff[28] * data[i-29];
  91409. case 28: sum += qlp_coeff[27] * data[i-28];
  91410. case 27: sum += qlp_coeff[26] * data[i-27];
  91411. case 26: sum += qlp_coeff[25] * data[i-26];
  91412. case 25: sum += qlp_coeff[24] * data[i-25];
  91413. case 24: sum += qlp_coeff[23] * data[i-24];
  91414. case 23: sum += qlp_coeff[22] * data[i-23];
  91415. case 22: sum += qlp_coeff[21] * data[i-22];
  91416. case 21: sum += qlp_coeff[20] * data[i-21];
  91417. case 20: sum += qlp_coeff[19] * data[i-20];
  91418. case 19: sum += qlp_coeff[18] * data[i-19];
  91419. case 18: sum += qlp_coeff[17] * data[i-18];
  91420. case 17: sum += qlp_coeff[16] * data[i-17];
  91421. case 16: sum += qlp_coeff[15] * data[i-16];
  91422. case 15: sum += qlp_coeff[14] * data[i-15];
  91423. case 14: sum += qlp_coeff[13] * data[i-14];
  91424. case 13: sum += qlp_coeff[12] * data[i-13];
  91425. sum += qlp_coeff[11] * data[i-12];
  91426. sum += qlp_coeff[10] * data[i-11];
  91427. sum += qlp_coeff[ 9] * data[i-10];
  91428. sum += qlp_coeff[ 8] * data[i- 9];
  91429. sum += qlp_coeff[ 7] * data[i- 8];
  91430. sum += qlp_coeff[ 6] * data[i- 7];
  91431. sum += qlp_coeff[ 5] * data[i- 6];
  91432. sum += qlp_coeff[ 4] * data[i- 5];
  91433. sum += qlp_coeff[ 3] * data[i- 4];
  91434. sum += qlp_coeff[ 2] * data[i- 3];
  91435. sum += qlp_coeff[ 1] * data[i- 2];
  91436. sum += qlp_coeff[ 0] * data[i- 1];
  91437. }
  91438. data[i] = residual[i] + (sum >> lp_quantization);
  91439. }
  91440. }
  91441. }
  91442. #endif
  91443. 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[])
  91444. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  91445. {
  91446. unsigned i, j;
  91447. FLAC__int64 sum;
  91448. const FLAC__int32 *r = residual, *history;
  91449. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  91450. fprintf(stderr,"FLAC__lpc_restore_signal_wide: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  91451. for(i=0;i<order;i++)
  91452. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  91453. fprintf(stderr,"\n");
  91454. #endif
  91455. FLAC__ASSERT(order > 0);
  91456. for(i = 0; i < data_len; i++) {
  91457. sum = 0;
  91458. history = data;
  91459. for(j = 0; j < order; j++)
  91460. sum += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*(--history));
  91461. if(FLAC__bitmath_silog2_wide(sum >> lp_quantization) > 32) {
  91462. #ifdef _MSC_VER
  91463. fprintf(stderr,"FLAC__lpc_restore_signal_wide: OVERFLOW, i=%u, sum=%I64d\n", i, sum >> lp_quantization);
  91464. #else
  91465. fprintf(stderr,"FLAC__lpc_restore_signal_wide: OVERFLOW, i=%u, sum=%lld\n", i, (long long)(sum >> lp_quantization));
  91466. #endif
  91467. break;
  91468. }
  91469. if(FLAC__bitmath_silog2_wide((FLAC__int64)(*r) + (sum >> lp_quantization)) > 32) {
  91470. #ifdef _MSC_VER
  91471. 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));
  91472. #else
  91473. 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)));
  91474. #endif
  91475. break;
  91476. }
  91477. *(data++) = *(r++) + (FLAC__int32)(sum >> lp_quantization);
  91478. }
  91479. }
  91480. #else /* fully unrolled version for normal use */
  91481. {
  91482. int i;
  91483. FLAC__int64 sum;
  91484. FLAC__ASSERT(order > 0);
  91485. FLAC__ASSERT(order <= 32);
  91486. /*
  91487. * We do unique versions up to 12th order since that's the subset limit.
  91488. * Also they are roughly ordered to match frequency of occurrence to
  91489. * minimize branching.
  91490. */
  91491. if(order <= 12) {
  91492. if(order > 8) {
  91493. if(order > 10) {
  91494. if(order == 12) {
  91495. for(i = 0; i < (int)data_len; i++) {
  91496. sum = 0;
  91497. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  91498. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  91499. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  91500. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  91501. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  91502. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  91503. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  91504. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  91505. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  91506. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  91507. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  91508. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  91509. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  91510. }
  91511. }
  91512. else { /* order == 11 */
  91513. for(i = 0; i < (int)data_len; i++) {
  91514. sum = 0;
  91515. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  91516. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  91517. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  91518. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  91519. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  91520. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  91521. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  91522. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  91523. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  91524. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  91525. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  91526. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  91527. }
  91528. }
  91529. }
  91530. else {
  91531. if(order == 10) {
  91532. for(i = 0; i < (int)data_len; i++) {
  91533. sum = 0;
  91534. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  91535. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  91536. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  91537. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  91538. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  91539. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  91540. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  91541. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  91542. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  91543. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  91544. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  91545. }
  91546. }
  91547. else { /* order == 9 */
  91548. for(i = 0; i < (int)data_len; i++) {
  91549. sum = 0;
  91550. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  91551. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  91552. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  91553. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  91554. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  91555. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  91556. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  91557. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  91558. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  91559. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  91560. }
  91561. }
  91562. }
  91563. }
  91564. else if(order > 4) {
  91565. if(order > 6) {
  91566. if(order == 8) {
  91567. for(i = 0; i < (int)data_len; i++) {
  91568. sum = 0;
  91569. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  91570. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  91571. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  91572. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  91573. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  91574. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  91575. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  91576. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  91577. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  91578. }
  91579. }
  91580. else { /* order == 7 */
  91581. for(i = 0; i < (int)data_len; i++) {
  91582. sum = 0;
  91583. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  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. }
  91594. else {
  91595. if(order == 6) {
  91596. for(i = 0; i < (int)data_len; i++) {
  91597. sum = 0;
  91598. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  91599. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  91600. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  91601. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  91602. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  91603. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  91604. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  91605. }
  91606. }
  91607. else { /* order == 5 */
  91608. for(i = 0; i < (int)data_len; i++) {
  91609. sum = 0;
  91610. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  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. }
  91619. }
  91620. else {
  91621. if(order > 2) {
  91622. if(order == 4) {
  91623. for(i = 0; i < (int)data_len; i++) {
  91624. sum = 0;
  91625. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  91626. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  91627. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  91628. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  91629. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  91630. }
  91631. }
  91632. else { /* order == 3 */
  91633. for(i = 0; i < (int)data_len; i++) {
  91634. sum = 0;
  91635. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  91636. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  91637. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  91638. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  91639. }
  91640. }
  91641. }
  91642. else {
  91643. if(order == 2) {
  91644. for(i = 0; i < (int)data_len; i++) {
  91645. sum = 0;
  91646. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  91647. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  91648. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  91649. }
  91650. }
  91651. else { /* order == 1 */
  91652. for(i = 0; i < (int)data_len; i++)
  91653. data[i] = residual[i] + (FLAC__int32)((qlp_coeff[0] * (FLAC__int64)data[i-1]) >> lp_quantization);
  91654. }
  91655. }
  91656. }
  91657. }
  91658. else { /* order > 12 */
  91659. for(i = 0; i < (int)data_len; i++) {
  91660. sum = 0;
  91661. switch(order) {
  91662. case 32: sum += qlp_coeff[31] * (FLAC__int64)data[i-32];
  91663. case 31: sum += qlp_coeff[30] * (FLAC__int64)data[i-31];
  91664. case 30: sum += qlp_coeff[29] * (FLAC__int64)data[i-30];
  91665. case 29: sum += qlp_coeff[28] * (FLAC__int64)data[i-29];
  91666. case 28: sum += qlp_coeff[27] * (FLAC__int64)data[i-28];
  91667. case 27: sum += qlp_coeff[26] * (FLAC__int64)data[i-27];
  91668. case 26: sum += qlp_coeff[25] * (FLAC__int64)data[i-26];
  91669. case 25: sum += qlp_coeff[24] * (FLAC__int64)data[i-25];
  91670. case 24: sum += qlp_coeff[23] * (FLAC__int64)data[i-24];
  91671. case 23: sum += qlp_coeff[22] * (FLAC__int64)data[i-23];
  91672. case 22: sum += qlp_coeff[21] * (FLAC__int64)data[i-22];
  91673. case 21: sum += qlp_coeff[20] * (FLAC__int64)data[i-21];
  91674. case 20: sum += qlp_coeff[19] * (FLAC__int64)data[i-20];
  91675. case 19: sum += qlp_coeff[18] * (FLAC__int64)data[i-19];
  91676. case 18: sum += qlp_coeff[17] * (FLAC__int64)data[i-18];
  91677. case 17: sum += qlp_coeff[16] * (FLAC__int64)data[i-17];
  91678. case 16: sum += qlp_coeff[15] * (FLAC__int64)data[i-16];
  91679. case 15: sum += qlp_coeff[14] * (FLAC__int64)data[i-15];
  91680. case 14: sum += qlp_coeff[13] * (FLAC__int64)data[i-14];
  91681. case 13: sum += qlp_coeff[12] * (FLAC__int64)data[i-13];
  91682. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  91683. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  91684. sum += qlp_coeff[ 9] * (FLAC__int64)data[i-10];
  91685. sum += qlp_coeff[ 8] * (FLAC__int64)data[i- 9];
  91686. sum += qlp_coeff[ 7] * (FLAC__int64)data[i- 8];
  91687. sum += qlp_coeff[ 6] * (FLAC__int64)data[i- 7];
  91688. sum += qlp_coeff[ 5] * (FLAC__int64)data[i- 6];
  91689. sum += qlp_coeff[ 4] * (FLAC__int64)data[i- 5];
  91690. sum += qlp_coeff[ 3] * (FLAC__int64)data[i- 4];
  91691. sum += qlp_coeff[ 2] * (FLAC__int64)data[i- 3];
  91692. sum += qlp_coeff[ 1] * (FLAC__int64)data[i- 2];
  91693. sum += qlp_coeff[ 0] * (FLAC__int64)data[i- 1];
  91694. }
  91695. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  91696. }
  91697. }
  91698. }
  91699. #endif
  91700. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  91701. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample(FLAC__double lpc_error, unsigned total_samples)
  91702. {
  91703. FLAC__double error_scale;
  91704. FLAC__ASSERT(total_samples > 0);
  91705. error_scale = 0.5 * M_LN2 * M_LN2 / (FLAC__double)total_samples;
  91706. return FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(lpc_error, error_scale);
  91707. }
  91708. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(FLAC__double lpc_error, FLAC__double error_scale)
  91709. {
  91710. if(lpc_error > 0.0) {
  91711. FLAC__double bps = (FLAC__double)0.5 * log(error_scale * lpc_error) / M_LN2;
  91712. if(bps >= 0.0)
  91713. return bps;
  91714. else
  91715. return 0.0;
  91716. }
  91717. else if(lpc_error < 0.0) { /* error should not be negative but can happen due to inadequate floating-point resolution */
  91718. return 1e32;
  91719. }
  91720. else {
  91721. return 0.0;
  91722. }
  91723. }
  91724. unsigned FLAC__lpc_compute_best_order(const FLAC__double lpc_error[], unsigned max_order, unsigned total_samples, unsigned overhead_bits_per_order)
  91725. {
  91726. 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 */
  91727. FLAC__double bits, best_bits, error_scale;
  91728. FLAC__ASSERT(max_order > 0);
  91729. FLAC__ASSERT(total_samples > 0);
  91730. error_scale = 0.5 * M_LN2 * M_LN2 / (FLAC__double)total_samples;
  91731. best_index = 0;
  91732. best_bits = (unsigned)(-1);
  91733. for(index = 0, order = 1; index < max_order; index++, order++) {
  91734. 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);
  91735. if(bits < best_bits) {
  91736. best_index = index;
  91737. best_bits = bits;
  91738. }
  91739. }
  91740. return best_index+1; /* +1 since index of lpc_error[] is order-1 */
  91741. }
  91742. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  91743. #endif
  91744. /********* End of inlined file: lpc_flac.c *********/
  91745. /********* Start of inlined file: md5.c *********/
  91746. /********* Start of inlined file: juce_FlacHeader.h *********/
  91747. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  91748. // tasks..
  91749. #define VERSION "1.2.1"
  91750. #define FLAC__NO_DLL 1
  91751. #ifdef _MSC_VER
  91752. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  91753. #endif
  91754. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  91755. #define FLAC__SYS_DARWIN 1
  91756. #endif
  91757. /********* End of inlined file: juce_FlacHeader.h *********/
  91758. #if JUCE_USE_FLAC
  91759. #if HAVE_CONFIG_H
  91760. # include <config.h>
  91761. #endif
  91762. #include <stdlib.h> /* for malloc() */
  91763. #include <string.h> /* for memcpy() */
  91764. /********* Start of inlined file: md5.h *********/
  91765. #ifndef FLAC__PRIVATE__MD5_H
  91766. #define FLAC__PRIVATE__MD5_H
  91767. /*
  91768. * This is the header file for the MD5 message-digest algorithm.
  91769. * The algorithm is due to Ron Rivest. This code was
  91770. * written by Colin Plumb in 1993, no copyright is claimed.
  91771. * This code is in the public domain; do with it what you wish.
  91772. *
  91773. * Equivalent code is available from RSA Data Security, Inc.
  91774. * This code has been tested against that, and is equivalent,
  91775. * except that you don't need to include two pages of legalese
  91776. * with every copy.
  91777. *
  91778. * To compute the message digest of a chunk of bytes, declare an
  91779. * MD5Context structure, pass it to MD5Init, call MD5Update as
  91780. * needed on buffers full of bytes, and then call MD5Final, which
  91781. * will fill a supplied 16-byte array with the digest.
  91782. *
  91783. * Changed so as no longer to depend on Colin Plumb's `usual.h'
  91784. * header definitions; now uses stuff from dpkg's config.h
  91785. * - Ian Jackson <ijackson@nyx.cs.du.edu>.
  91786. * Still in the public domain.
  91787. *
  91788. * Josh Coalson: made some changes to integrate with libFLAC.
  91789. * Still in the public domain, with no warranty.
  91790. */
  91791. typedef struct {
  91792. FLAC__uint32 in[16];
  91793. FLAC__uint32 buf[4];
  91794. FLAC__uint32 bytes[2];
  91795. FLAC__byte *internal_buf;
  91796. size_t capacity;
  91797. } FLAC__MD5Context;
  91798. void FLAC__MD5Init(FLAC__MD5Context *context);
  91799. void FLAC__MD5Final(FLAC__byte digest[16], FLAC__MD5Context *context);
  91800. FLAC__bool FLAC__MD5Accumulate(FLAC__MD5Context *ctx, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample);
  91801. #endif
  91802. /********* End of inlined file: md5.h *********/
  91803. #ifndef FLaC__INLINE
  91804. #define FLaC__INLINE
  91805. #endif
  91806. /*
  91807. * This code implements the MD5 message-digest algorithm.
  91808. * The algorithm is due to Ron Rivest. This code was
  91809. * written by Colin Plumb in 1993, no copyright is claimed.
  91810. * This code is in the public domain; do with it what you wish.
  91811. *
  91812. * Equivalent code is available from RSA Data Security, Inc.
  91813. * This code has been tested against that, and is equivalent,
  91814. * except that you don't need to include two pages of legalese
  91815. * with every copy.
  91816. *
  91817. * To compute the message digest of a chunk of bytes, declare an
  91818. * MD5Context structure, pass it to MD5Init, call MD5Update as
  91819. * needed on buffers full of bytes, and then call MD5Final, which
  91820. * will fill a supplied 16-byte array with the digest.
  91821. *
  91822. * Changed so as no longer to depend on Colin Plumb's `usual.h' header
  91823. * definitions; now uses stuff from dpkg's config.h.
  91824. * - Ian Jackson <ijackson@nyx.cs.du.edu>.
  91825. * Still in the public domain.
  91826. *
  91827. * Josh Coalson: made some changes to integrate with libFLAC.
  91828. * Still in the public domain.
  91829. */
  91830. /* The four core functions - F1 is optimized somewhat */
  91831. /* #define F1(x, y, z) (x & y | ~x & z) */
  91832. #define F1(x, y, z) (z ^ (x & (y ^ z)))
  91833. #define F2(x, y, z) F1(z, x, y)
  91834. #define F3(x, y, z) (x ^ y ^ z)
  91835. #define F4(x, y, z) (y ^ (x | ~z))
  91836. /* This is the central step in the MD5 algorithm. */
  91837. #define MD5STEP(f,w,x,y,z,in,s) \
  91838. (w += f(x,y,z) + in, w = (w<<s | w>>(32-s)) + x)
  91839. /*
  91840. * The core of the MD5 algorithm, this alters an existing MD5 hash to
  91841. * reflect the addition of 16 longwords of new data. MD5Update blocks
  91842. * the data and converts bytes into longwords for this routine.
  91843. */
  91844. static void FLAC__MD5Transform(FLAC__uint32 buf[4], FLAC__uint32 const in[16])
  91845. {
  91846. register FLAC__uint32 a, b, c, d;
  91847. a = buf[0];
  91848. b = buf[1];
  91849. c = buf[2];
  91850. d = buf[3];
  91851. MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7);
  91852. MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12);
  91853. MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17);
  91854. MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22);
  91855. MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7);
  91856. MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12);
  91857. MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17);
  91858. MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22);
  91859. MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7);
  91860. MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12);
  91861. MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17);
  91862. MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22);
  91863. MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7);
  91864. MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12);
  91865. MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17);
  91866. MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22);
  91867. MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5);
  91868. MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9);
  91869. MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14);
  91870. MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20);
  91871. MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5);
  91872. MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9);
  91873. MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14);
  91874. MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20);
  91875. MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5);
  91876. MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9);
  91877. MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14);
  91878. MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20);
  91879. MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5);
  91880. MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9);
  91881. MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14);
  91882. MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);
  91883. MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4);
  91884. MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11);
  91885. MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16);
  91886. MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23);
  91887. MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4);
  91888. MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11);
  91889. MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16);
  91890. MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23);
  91891. MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4);
  91892. MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11);
  91893. MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16);
  91894. MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23);
  91895. MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4);
  91896. MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11);
  91897. MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);
  91898. MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23);
  91899. MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6);
  91900. MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10);
  91901. MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15);
  91902. MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21);
  91903. MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6);
  91904. MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10);
  91905. MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15);
  91906. MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21);
  91907. MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6);
  91908. MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);
  91909. MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15);
  91910. MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21);
  91911. MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6);
  91912. MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10);
  91913. MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15);
  91914. MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21);
  91915. buf[0] += a;
  91916. buf[1] += b;
  91917. buf[2] += c;
  91918. buf[3] += d;
  91919. }
  91920. #if WORDS_BIGENDIAN
  91921. //@@@@@@ OPT: use bswap/intrinsics
  91922. static void byteSwap(FLAC__uint32 *buf, unsigned words)
  91923. {
  91924. register FLAC__uint32 x;
  91925. do {
  91926. x = *buf;
  91927. x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff);
  91928. *buf++ = (x >> 16) | (x << 16);
  91929. } while (--words);
  91930. }
  91931. static void byteSwapX16(FLAC__uint32 *buf)
  91932. {
  91933. register FLAC__uint32 x;
  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. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  91937. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  91938. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  91939. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  91940. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  91941. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  91942. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  91943. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  91944. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  91945. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  91946. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  91947. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  91948. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  91949. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf = (x >> 16) | (x << 16);
  91950. }
  91951. #else
  91952. #define byteSwap(buf, words)
  91953. #define byteSwapX16(buf)
  91954. #endif
  91955. /*
  91956. * Update context to reflect the concatenation of another buffer full
  91957. * of bytes.
  91958. */
  91959. static void FLAC__MD5Update(FLAC__MD5Context *ctx, FLAC__byte const *buf, unsigned len)
  91960. {
  91961. FLAC__uint32 t;
  91962. /* Update byte count */
  91963. t = ctx->bytes[0];
  91964. if ((ctx->bytes[0] = t + len) < t)
  91965. ctx->bytes[1]++; /* Carry from low to high */
  91966. t = 64 - (t & 0x3f); /* Space available in ctx->in (at least 1) */
  91967. if (t > len) {
  91968. memcpy((FLAC__byte *)ctx->in + 64 - t, buf, len);
  91969. return;
  91970. }
  91971. /* First chunk is an odd size */
  91972. memcpy((FLAC__byte *)ctx->in + 64 - t, buf, t);
  91973. byteSwapX16(ctx->in);
  91974. FLAC__MD5Transform(ctx->buf, ctx->in);
  91975. buf += t;
  91976. len -= t;
  91977. /* Process data in 64-byte chunks */
  91978. while (len >= 64) {
  91979. memcpy(ctx->in, buf, 64);
  91980. byteSwapX16(ctx->in);
  91981. FLAC__MD5Transform(ctx->buf, ctx->in);
  91982. buf += 64;
  91983. len -= 64;
  91984. }
  91985. /* Handle any remaining bytes of data. */
  91986. memcpy(ctx->in, buf, len);
  91987. }
  91988. /*
  91989. * Start MD5 accumulation. Set bit count to 0 and buffer to mysterious
  91990. * initialization constants.
  91991. */
  91992. void FLAC__MD5Init(FLAC__MD5Context *ctx)
  91993. {
  91994. ctx->buf[0] = 0x67452301;
  91995. ctx->buf[1] = 0xefcdab89;
  91996. ctx->buf[2] = 0x98badcfe;
  91997. ctx->buf[3] = 0x10325476;
  91998. ctx->bytes[0] = 0;
  91999. ctx->bytes[1] = 0;
  92000. ctx->internal_buf = 0;
  92001. ctx->capacity = 0;
  92002. }
  92003. /*
  92004. * Final wrapup - pad to 64-byte boundary with the bit pattern
  92005. * 1 0* (64-bit count of bits processed, MSB-first)
  92006. */
  92007. void FLAC__MD5Final(FLAC__byte digest[16], FLAC__MD5Context *ctx)
  92008. {
  92009. int count = ctx->bytes[0] & 0x3f; /* Number of bytes in ctx->in */
  92010. FLAC__byte *p = (FLAC__byte *)ctx->in + count;
  92011. /* Set the first char of padding to 0x80. There is always room. */
  92012. *p++ = 0x80;
  92013. /* Bytes of padding needed to make 56 bytes (-8..55) */
  92014. count = 56 - 1 - count;
  92015. if (count < 0) { /* Padding forces an extra block */
  92016. memset(p, 0, count + 8);
  92017. byteSwapX16(ctx->in);
  92018. FLAC__MD5Transform(ctx->buf, ctx->in);
  92019. p = (FLAC__byte *)ctx->in;
  92020. count = 56;
  92021. }
  92022. memset(p, 0, count);
  92023. byteSwap(ctx->in, 14);
  92024. /* Append length in bits and transform */
  92025. ctx->in[14] = ctx->bytes[0] << 3;
  92026. ctx->in[15] = ctx->bytes[1] << 3 | ctx->bytes[0] >> 29;
  92027. FLAC__MD5Transform(ctx->buf, ctx->in);
  92028. byteSwap(ctx->buf, 4);
  92029. memcpy(digest, ctx->buf, 16);
  92030. memset(ctx, 0, sizeof(ctx)); /* In case it's sensitive */
  92031. if(0 != ctx->internal_buf) {
  92032. free(ctx->internal_buf);
  92033. ctx->internal_buf = 0;
  92034. ctx->capacity = 0;
  92035. }
  92036. }
  92037. /*
  92038. * Convert the incoming audio signal to a byte stream
  92039. */
  92040. static void format_input_(FLAC__byte *buf, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample)
  92041. {
  92042. unsigned channel, sample;
  92043. register FLAC__int32 a_word;
  92044. register FLAC__byte *buf_ = buf;
  92045. #if WORDS_BIGENDIAN
  92046. #else
  92047. if(channels == 2 && bytes_per_sample == 2) {
  92048. FLAC__int16 *buf1_ = ((FLAC__int16*)buf_) + 1;
  92049. memcpy(buf_, signal[0], sizeof(FLAC__int32) * samples);
  92050. for(sample = 0; sample < samples; sample++, buf1_+=2)
  92051. *buf1_ = (FLAC__int16)signal[1][sample];
  92052. }
  92053. else if(channels == 1 && bytes_per_sample == 2) {
  92054. FLAC__int16 *buf1_ = (FLAC__int16*)buf_;
  92055. for(sample = 0; sample < samples; sample++)
  92056. *buf1_++ = (FLAC__int16)signal[0][sample];
  92057. }
  92058. else
  92059. #endif
  92060. if(bytes_per_sample == 2) {
  92061. if(channels == 2) {
  92062. for(sample = 0; sample < samples; sample++) {
  92063. a_word = signal[0][sample];
  92064. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  92065. *buf_++ = (FLAC__byte)a_word;
  92066. a_word = signal[1][sample];
  92067. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  92068. *buf_++ = (FLAC__byte)a_word;
  92069. }
  92070. }
  92071. else if(channels == 1) {
  92072. for(sample = 0; sample < samples; sample++) {
  92073. a_word = signal[0][sample];
  92074. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  92075. *buf_++ = (FLAC__byte)a_word;
  92076. }
  92077. }
  92078. else {
  92079. for(sample = 0; sample < samples; sample++) {
  92080. for(channel = 0; channel < channels; channel++) {
  92081. a_word = signal[channel][sample];
  92082. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  92083. *buf_++ = (FLAC__byte)a_word;
  92084. }
  92085. }
  92086. }
  92087. }
  92088. else if(bytes_per_sample == 3) {
  92089. if(channels == 2) {
  92090. for(sample = 0; sample < samples; sample++) {
  92091. a_word = signal[0][sample];
  92092. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  92093. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  92094. *buf_++ = (FLAC__byte)a_word;
  92095. a_word = signal[1][sample];
  92096. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  92097. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  92098. *buf_++ = (FLAC__byte)a_word;
  92099. }
  92100. }
  92101. else if(channels == 1) {
  92102. for(sample = 0; sample < samples; sample++) {
  92103. a_word = signal[0][sample];
  92104. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  92105. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  92106. *buf_++ = (FLAC__byte)a_word;
  92107. }
  92108. }
  92109. else {
  92110. for(sample = 0; sample < samples; sample++) {
  92111. for(channel = 0; channel < channels; channel++) {
  92112. a_word = signal[channel][sample];
  92113. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  92114. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  92115. *buf_++ = (FLAC__byte)a_word;
  92116. }
  92117. }
  92118. }
  92119. }
  92120. else if(bytes_per_sample == 1) {
  92121. if(channels == 2) {
  92122. for(sample = 0; sample < samples; sample++) {
  92123. a_word = signal[0][sample];
  92124. *buf_++ = (FLAC__byte)a_word;
  92125. a_word = signal[1][sample];
  92126. *buf_++ = (FLAC__byte)a_word;
  92127. }
  92128. }
  92129. else if(channels == 1) {
  92130. for(sample = 0; sample < samples; sample++) {
  92131. a_word = signal[0][sample];
  92132. *buf_++ = (FLAC__byte)a_word;
  92133. }
  92134. }
  92135. else {
  92136. for(sample = 0; sample < samples; sample++) {
  92137. for(channel = 0; channel < channels; channel++) {
  92138. a_word = signal[channel][sample];
  92139. *buf_++ = (FLAC__byte)a_word;
  92140. }
  92141. }
  92142. }
  92143. }
  92144. else { /* bytes_per_sample == 4, maybe optimize more later */
  92145. for(sample = 0; sample < samples; sample++) {
  92146. for(channel = 0; channel < channels; channel++) {
  92147. a_word = signal[channel][sample];
  92148. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  92149. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  92150. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  92151. *buf_++ = (FLAC__byte)a_word;
  92152. }
  92153. }
  92154. }
  92155. }
  92156. /*
  92157. * Convert the incoming audio signal to a byte stream and FLAC__MD5Update it.
  92158. */
  92159. FLAC__bool FLAC__MD5Accumulate(FLAC__MD5Context *ctx, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample)
  92160. {
  92161. const size_t bytes_needed = (size_t)channels * (size_t)samples * (size_t)bytes_per_sample;
  92162. /* overflow check */
  92163. if((size_t)channels > SIZE_MAX / (size_t)bytes_per_sample)
  92164. return false;
  92165. if((size_t)channels * (size_t)bytes_per_sample > SIZE_MAX / (size_t)samples)
  92166. return false;
  92167. if(ctx->capacity < bytes_needed) {
  92168. FLAC__byte *tmp = (FLAC__byte*)realloc(ctx->internal_buf, bytes_needed);
  92169. if(0 == tmp) {
  92170. free(ctx->internal_buf);
  92171. if(0 == (ctx->internal_buf = (FLAC__byte*)safe_malloc_(bytes_needed)))
  92172. return false;
  92173. }
  92174. ctx->internal_buf = tmp;
  92175. ctx->capacity = bytes_needed;
  92176. }
  92177. format_input_(ctx->internal_buf, signal, channels, samples, bytes_per_sample);
  92178. FLAC__MD5Update(ctx, ctx->internal_buf, bytes_needed);
  92179. return true;
  92180. }
  92181. #endif
  92182. /********* End of inlined file: md5.c *********/
  92183. /********* Start of inlined file: memory.c *********/
  92184. /********* Start of inlined file: juce_FlacHeader.h *********/
  92185. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  92186. // tasks..
  92187. #define VERSION "1.2.1"
  92188. #define FLAC__NO_DLL 1
  92189. #ifdef _MSC_VER
  92190. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  92191. #endif
  92192. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  92193. #define FLAC__SYS_DARWIN 1
  92194. #endif
  92195. /********* End of inlined file: juce_FlacHeader.h *********/
  92196. #if JUCE_USE_FLAC
  92197. #if HAVE_CONFIG_H
  92198. # include <config.h>
  92199. #endif
  92200. /********* Start of inlined file: memory.h *********/
  92201. #ifndef FLAC__PRIVATE__MEMORY_H
  92202. #define FLAC__PRIVATE__MEMORY_H
  92203. #ifdef HAVE_CONFIG_H
  92204. #include <config.h>
  92205. #endif
  92206. #include <stdlib.h> /* for size_t */
  92207. /* Returns the unaligned address returned by malloc.
  92208. * Use free() on this address to deallocate.
  92209. */
  92210. void *FLAC__memory_alloc_aligned(size_t bytes, void **aligned_address);
  92211. FLAC__bool FLAC__memory_alloc_aligned_int32_array(unsigned elements, FLAC__int32 **unaligned_pointer, FLAC__int32 **aligned_pointer);
  92212. FLAC__bool FLAC__memory_alloc_aligned_uint32_array(unsigned elements, FLAC__uint32 **unaligned_pointer, FLAC__uint32 **aligned_pointer);
  92213. FLAC__bool FLAC__memory_alloc_aligned_uint64_array(unsigned elements, FLAC__uint64 **unaligned_pointer, FLAC__uint64 **aligned_pointer);
  92214. FLAC__bool FLAC__memory_alloc_aligned_unsigned_array(unsigned elements, unsigned **unaligned_pointer, unsigned **aligned_pointer);
  92215. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  92216. FLAC__bool FLAC__memory_alloc_aligned_real_array(unsigned elements, FLAC__real **unaligned_pointer, FLAC__real **aligned_pointer);
  92217. #endif
  92218. #endif
  92219. /********* End of inlined file: memory.h *********/
  92220. void *FLAC__memory_alloc_aligned(size_t bytes, void **aligned_address)
  92221. {
  92222. void *x;
  92223. FLAC__ASSERT(0 != aligned_address);
  92224. #ifdef FLAC__ALIGN_MALLOC_DATA
  92225. /* align on 32-byte (256-bit) boundary */
  92226. x = safe_malloc_add_2op_(bytes, /*+*/31);
  92227. #ifdef SIZEOF_VOIDP
  92228. #if SIZEOF_VOIDP == 4
  92229. /* could do *aligned_address = x + ((unsigned) (32 - (((unsigned)x) & 31))) & 31; */
  92230. *aligned_address = (void*)(((unsigned)x + 31) & -32);
  92231. #elif SIZEOF_VOIDP == 8
  92232. *aligned_address = (void*)(((FLAC__uint64)x + 31) & (FLAC__uint64)(-((FLAC__int64)32)));
  92233. #else
  92234. # error Unsupported sizeof(void*)
  92235. #endif
  92236. #else
  92237. /* there's got to be a better way to do this right for all archs */
  92238. if(sizeof(void*) == sizeof(unsigned))
  92239. *aligned_address = (void*)(((unsigned)x + 31) & -32);
  92240. else if(sizeof(void*) == sizeof(FLAC__uint64))
  92241. *aligned_address = (void*)(((FLAC__uint64)x + 31) & (FLAC__uint64)(-((FLAC__int64)32)));
  92242. else
  92243. return 0;
  92244. #endif
  92245. #else
  92246. x = safe_malloc_(bytes);
  92247. *aligned_address = x;
  92248. #endif
  92249. return x;
  92250. }
  92251. FLAC__bool FLAC__memory_alloc_aligned_int32_array(unsigned elements, FLAC__int32 **unaligned_pointer, FLAC__int32 **aligned_pointer)
  92252. {
  92253. FLAC__int32 *pu; /* unaligned pointer */
  92254. union { /* union needed to comply with C99 pointer aliasing rules */
  92255. FLAC__int32 *pa; /* aligned pointer */
  92256. void *pv; /* aligned pointer alias */
  92257. } u;
  92258. FLAC__ASSERT(elements > 0);
  92259. FLAC__ASSERT(0 != unaligned_pointer);
  92260. FLAC__ASSERT(0 != aligned_pointer);
  92261. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  92262. if((size_t)elements > SIZE_MAX / sizeof(*pu)) /* overflow check */
  92263. return false;
  92264. pu = (FLAC__int32*)FLAC__memory_alloc_aligned(sizeof(*pu) * (size_t)elements, &u.pv);
  92265. if(0 == pu) {
  92266. return false;
  92267. }
  92268. else {
  92269. if(*unaligned_pointer != 0)
  92270. free(*unaligned_pointer);
  92271. *unaligned_pointer = pu;
  92272. *aligned_pointer = u.pa;
  92273. return true;
  92274. }
  92275. }
  92276. FLAC__bool FLAC__memory_alloc_aligned_uint32_array(unsigned elements, FLAC__uint32 **unaligned_pointer, FLAC__uint32 **aligned_pointer)
  92277. {
  92278. FLAC__uint32 *pu; /* unaligned pointer */
  92279. union { /* union needed to comply with C99 pointer aliasing rules */
  92280. FLAC__uint32 *pa; /* aligned pointer */
  92281. void *pv; /* aligned pointer alias */
  92282. } u;
  92283. FLAC__ASSERT(elements > 0);
  92284. FLAC__ASSERT(0 != unaligned_pointer);
  92285. FLAC__ASSERT(0 != aligned_pointer);
  92286. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  92287. if((size_t)elements > SIZE_MAX / sizeof(*pu)) /* overflow check */
  92288. return false;
  92289. pu = (FLAC__uint32*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  92290. if(0 == pu) {
  92291. return false;
  92292. }
  92293. else {
  92294. if(*unaligned_pointer != 0)
  92295. free(*unaligned_pointer);
  92296. *unaligned_pointer = pu;
  92297. *aligned_pointer = u.pa;
  92298. return true;
  92299. }
  92300. }
  92301. FLAC__bool FLAC__memory_alloc_aligned_uint64_array(unsigned elements, FLAC__uint64 **unaligned_pointer, FLAC__uint64 **aligned_pointer)
  92302. {
  92303. FLAC__uint64 *pu; /* unaligned pointer */
  92304. union { /* union needed to comply with C99 pointer aliasing rules */
  92305. FLAC__uint64 *pa; /* aligned pointer */
  92306. void *pv; /* aligned pointer alias */
  92307. } u;
  92308. FLAC__ASSERT(elements > 0);
  92309. FLAC__ASSERT(0 != unaligned_pointer);
  92310. FLAC__ASSERT(0 != aligned_pointer);
  92311. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  92312. if((size_t)elements > SIZE_MAX / sizeof(*pu)) /* overflow check */
  92313. return false;
  92314. pu = (FLAC__uint64*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  92315. if(0 == pu) {
  92316. return false;
  92317. }
  92318. else {
  92319. if(*unaligned_pointer != 0)
  92320. free(*unaligned_pointer);
  92321. *unaligned_pointer = pu;
  92322. *aligned_pointer = u.pa;
  92323. return true;
  92324. }
  92325. }
  92326. FLAC__bool FLAC__memory_alloc_aligned_unsigned_array(unsigned elements, unsigned **unaligned_pointer, unsigned **aligned_pointer)
  92327. {
  92328. unsigned *pu; /* unaligned pointer */
  92329. union { /* union needed to comply with C99 pointer aliasing rules */
  92330. unsigned *pa; /* aligned pointer */
  92331. void *pv; /* aligned pointer alias */
  92332. } u;
  92333. FLAC__ASSERT(elements > 0);
  92334. FLAC__ASSERT(0 != unaligned_pointer);
  92335. FLAC__ASSERT(0 != aligned_pointer);
  92336. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  92337. if((size_t)elements > SIZE_MAX / sizeof(*pu)) /* overflow check */
  92338. return false;
  92339. pu = (unsigned*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  92340. if(0 == pu) {
  92341. return false;
  92342. }
  92343. else {
  92344. if(*unaligned_pointer != 0)
  92345. free(*unaligned_pointer);
  92346. *unaligned_pointer = pu;
  92347. *aligned_pointer = u.pa;
  92348. return true;
  92349. }
  92350. }
  92351. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  92352. FLAC__bool FLAC__memory_alloc_aligned_real_array(unsigned elements, FLAC__real **unaligned_pointer, FLAC__real **aligned_pointer)
  92353. {
  92354. FLAC__real *pu; /* unaligned pointer */
  92355. union { /* union needed to comply with C99 pointer aliasing rules */
  92356. FLAC__real *pa; /* aligned pointer */
  92357. void *pv; /* aligned pointer alias */
  92358. } u;
  92359. FLAC__ASSERT(elements > 0);
  92360. FLAC__ASSERT(0 != unaligned_pointer);
  92361. FLAC__ASSERT(0 != aligned_pointer);
  92362. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  92363. if((size_t)elements > SIZE_MAX / sizeof(*pu)) /* overflow check */
  92364. return false;
  92365. pu = (FLAC__real*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  92366. if(0 == pu) {
  92367. return false;
  92368. }
  92369. else {
  92370. if(*unaligned_pointer != 0)
  92371. free(*unaligned_pointer);
  92372. *unaligned_pointer = pu;
  92373. *aligned_pointer = u.pa;
  92374. return true;
  92375. }
  92376. }
  92377. #endif
  92378. #endif
  92379. /********* End of inlined file: memory.c *********/
  92380. /********* Start of inlined file: stream_decoder.c *********/
  92381. /********* Start of inlined file: juce_FlacHeader.h *********/
  92382. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  92383. // tasks..
  92384. #define VERSION "1.2.1"
  92385. #define FLAC__NO_DLL 1
  92386. #ifdef _MSC_VER
  92387. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  92388. #endif
  92389. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  92390. #define FLAC__SYS_DARWIN 1
  92391. #endif
  92392. /********* End of inlined file: juce_FlacHeader.h *********/
  92393. #if JUCE_USE_FLAC
  92394. #if HAVE_CONFIG_H
  92395. # include <config.h>
  92396. #endif
  92397. #if defined _MSC_VER || defined __MINGW32__
  92398. #include <io.h> /* for _setmode() */
  92399. #include <fcntl.h> /* for _O_BINARY */
  92400. #endif
  92401. #if defined __CYGWIN__ || defined __EMX__
  92402. #include <io.h> /* for setmode(), O_BINARY */
  92403. #include <fcntl.h> /* for _O_BINARY */
  92404. #endif
  92405. #include <stdio.h>
  92406. #include <stdlib.h> /* for malloc() */
  92407. #include <string.h> /* for memset/memcpy() */
  92408. #include <sys/stat.h> /* for stat() */
  92409. #include <sys/types.h> /* for off_t */
  92410. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINGW32__
  92411. #if _MSC_VER <= 1600 || defined __BORLANDC__ /* @@@ [2G limit] */
  92412. #define fseeko fseek
  92413. #define ftello ftell
  92414. #endif
  92415. #endif
  92416. /********* Start of inlined file: stream_decoder.h *********/
  92417. #ifndef FLAC__PROTECTED__STREAM_DECODER_H
  92418. #define FLAC__PROTECTED__STREAM_DECODER_H
  92419. #if FLAC__HAS_OGG
  92420. #include "include/private/ogg_decoder_aspect.h"
  92421. #endif
  92422. typedef struct FLAC__StreamDecoderProtected {
  92423. FLAC__StreamDecoderState state;
  92424. unsigned channels;
  92425. FLAC__ChannelAssignment channel_assignment;
  92426. unsigned bits_per_sample;
  92427. unsigned sample_rate; /* in Hz */
  92428. unsigned blocksize; /* in samples (per channel) */
  92429. FLAC__bool md5_checking; /* if true, generate MD5 signature of decoded data and compare against signature in the STREAMINFO metadata block */
  92430. #if FLAC__HAS_OGG
  92431. FLAC__OggDecoderAspect ogg_decoder_aspect;
  92432. #endif
  92433. } FLAC__StreamDecoderProtected;
  92434. /*
  92435. * return the number of input bytes consumed
  92436. */
  92437. unsigned FLAC__stream_decoder_get_input_bytes_unconsumed(const FLAC__StreamDecoder *decoder);
  92438. #endif
  92439. /********* End of inlined file: stream_decoder.h *********/
  92440. #ifdef max
  92441. #undef max
  92442. #endif
  92443. #define max(a,b) ((a)>(b)?(a):(b))
  92444. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  92445. #ifdef _MSC_VER
  92446. #define FLAC__U64L(x) x
  92447. #else
  92448. #define FLAC__U64L(x) x##LLU
  92449. #endif
  92450. /* technically this should be in an "export.c" but this is convenient enough */
  92451. FLAC_API int FLAC_API_SUPPORTS_OGG_FLAC =
  92452. #if FLAC__HAS_OGG
  92453. 1
  92454. #else
  92455. 0
  92456. #endif
  92457. ;
  92458. /***********************************************************************
  92459. *
  92460. * Private static data
  92461. *
  92462. ***********************************************************************/
  92463. static FLAC__byte ID3V2_TAG_[3] = { 'I', 'D', '3' };
  92464. /***********************************************************************
  92465. *
  92466. * Private class method prototypes
  92467. *
  92468. ***********************************************************************/
  92469. static void set_defaults_dec(FLAC__StreamDecoder *decoder);
  92470. static FILE *get_binary_stdin_(void);
  92471. static FLAC__bool allocate_output_(FLAC__StreamDecoder *decoder, unsigned size, unsigned channels);
  92472. static FLAC__bool has_id_filtered_(FLAC__StreamDecoder *decoder, FLAC__byte *id);
  92473. static FLAC__bool find_metadata_(FLAC__StreamDecoder *decoder);
  92474. static FLAC__bool read_metadata_(FLAC__StreamDecoder *decoder);
  92475. static FLAC__bool read_metadata_streaminfo_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length);
  92476. static FLAC__bool read_metadata_seektable_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length);
  92477. static FLAC__bool read_metadata_vorbiscomment_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_VorbisComment *obj);
  92478. static FLAC__bool read_metadata_cuesheet_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_CueSheet *obj);
  92479. static FLAC__bool read_metadata_picture_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_Picture *obj);
  92480. static FLAC__bool skip_id3v2_tag_(FLAC__StreamDecoder *decoder);
  92481. static FLAC__bool frame_sync_(FLAC__StreamDecoder *decoder);
  92482. static FLAC__bool read_frame_(FLAC__StreamDecoder *decoder, FLAC__bool *got_a_frame, FLAC__bool do_full_decode);
  92483. static FLAC__bool read_frame_header_(FLAC__StreamDecoder *decoder);
  92484. static FLAC__bool read_subframe_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  92485. static FLAC__bool read_subframe_constant_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  92486. static FLAC__bool read_subframe_fixed_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode);
  92487. static FLAC__bool read_subframe_lpc_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode);
  92488. static FLAC__bool read_subframe_verbatim_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  92489. 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);
  92490. static FLAC__bool read_zero_padding_(FLAC__StreamDecoder *decoder);
  92491. static FLAC__bool read_callback_(FLAC__byte buffer[], size_t *bytes, void *client_data);
  92492. #if FLAC__HAS_OGG
  92493. static FLAC__StreamDecoderReadStatus read_callback_ogg_aspect_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes);
  92494. static FLAC__OggDecoderAspectReadStatus read_callback_proxy_(const void *void_decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  92495. #endif
  92496. static FLAC__StreamDecoderWriteStatus write_audio_frame_to_client_(FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[]);
  92497. static void send_error_to_client_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status);
  92498. static FLAC__bool seek_to_absolute_sample_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample);
  92499. #if FLAC__HAS_OGG
  92500. static FLAC__bool seek_to_absolute_sample_ogg_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample);
  92501. #endif
  92502. static FLAC__StreamDecoderReadStatus file_read_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  92503. static FLAC__StreamDecoderSeekStatus file_seek_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  92504. static FLAC__StreamDecoderTellStatus file_tell_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  92505. static FLAC__StreamDecoderLengthStatus file_length_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data);
  92506. static FLAC__bool file_eof_callback_(const FLAC__StreamDecoder *decoder, void *client_data);
  92507. /***********************************************************************
  92508. *
  92509. * Private class data
  92510. *
  92511. ***********************************************************************/
  92512. typedef struct FLAC__StreamDecoderPrivate {
  92513. #if FLAC__HAS_OGG
  92514. FLAC__bool is_ogg;
  92515. #endif
  92516. FLAC__StreamDecoderReadCallback read_callback;
  92517. FLAC__StreamDecoderSeekCallback seek_callback;
  92518. FLAC__StreamDecoderTellCallback tell_callback;
  92519. FLAC__StreamDecoderLengthCallback length_callback;
  92520. FLAC__StreamDecoderEofCallback eof_callback;
  92521. FLAC__StreamDecoderWriteCallback write_callback;
  92522. FLAC__StreamDecoderMetadataCallback metadata_callback;
  92523. FLAC__StreamDecoderErrorCallback error_callback;
  92524. /* generic 32-bit datapath: */
  92525. 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[]);
  92526. /* generic 64-bit datapath: */
  92527. 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[]);
  92528. /* for use when the signal is <= 16 bits-per-sample, or <= 15 bits-per-sample on a side channel (which requires 1 extra bit): */
  92529. 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[]);
  92530. /* 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: */
  92531. 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[]);
  92532. FLAC__bool (*local_bitreader_read_rice_signed_block)(FLAC__BitReader *br, int* vals, unsigned nvals, unsigned parameter);
  92533. void *client_data;
  92534. FILE *file; /* only used if FLAC__stream_decoder_init_file()/FLAC__stream_decoder_init_file() called, else NULL */
  92535. FLAC__BitReader *input;
  92536. FLAC__int32 *output[FLAC__MAX_CHANNELS];
  92537. FLAC__int32 *residual[FLAC__MAX_CHANNELS]; /* WATCHOUT: these are the aligned pointers; the real pointers that should be free()'d are residual_unaligned[] below */
  92538. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents[FLAC__MAX_CHANNELS];
  92539. unsigned output_capacity, output_channels;
  92540. FLAC__uint32 fixed_block_size, next_fixed_block_size;
  92541. FLAC__uint64 samples_decoded;
  92542. FLAC__bool has_stream_info, has_seek_table;
  92543. FLAC__StreamMetadata stream_info;
  92544. FLAC__StreamMetadata seek_table;
  92545. FLAC__bool metadata_filter[128]; /* MAGIC number 128 == total number of metadata block types == 1 << 7 */
  92546. FLAC__byte *metadata_filter_ids;
  92547. size_t metadata_filter_ids_count, metadata_filter_ids_capacity; /* units for both are IDs, not bytes */
  92548. FLAC__Frame frame;
  92549. FLAC__bool cached; /* true if there is a byte in lookahead */
  92550. FLAC__CPUInfo cpuinfo;
  92551. FLAC__byte header_warmup[2]; /* contains the sync code and reserved bits */
  92552. FLAC__byte lookahead; /* temp storage when we need to look ahead one byte in the stream */
  92553. /* unaligned (original) pointers to allocated data */
  92554. FLAC__int32 *residual_unaligned[FLAC__MAX_CHANNELS];
  92555. 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 */
  92556. FLAC__bool internal_reset_hack; /* used only during init() so we can call reset to set up the decoder without rewinding the input */
  92557. FLAC__bool is_seeking;
  92558. FLAC__MD5Context md5context;
  92559. FLAC__byte computed_md5sum[16]; /* this is the sum we computed from the decoded data */
  92560. /* (the rest of these are only used for seeking) */
  92561. FLAC__Frame last_frame; /* holds the info of the last frame we seeked to */
  92562. FLAC__uint64 first_frame_offset; /* hint to the seek routine of where in the stream the first audio frame starts */
  92563. FLAC__uint64 target_sample;
  92564. unsigned unparseable_frame_count; /* used to tell whether we're decoding a future version of FLAC or just got a bad sync */
  92565. #if FLAC__HAS_OGG
  92566. FLAC__bool got_a_frame; /* hack needed in Ogg FLAC seek routine to check when process_single() actually writes a frame */
  92567. #endif
  92568. } FLAC__StreamDecoderPrivate;
  92569. /***********************************************************************
  92570. *
  92571. * Public static class data
  92572. *
  92573. ***********************************************************************/
  92574. FLAC_API const char * const FLAC__StreamDecoderStateString[] = {
  92575. "FLAC__STREAM_DECODER_SEARCH_FOR_METADATA",
  92576. "FLAC__STREAM_DECODER_READ_METADATA",
  92577. "FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC",
  92578. "FLAC__STREAM_DECODER_READ_FRAME",
  92579. "FLAC__STREAM_DECODER_END_OF_STREAM",
  92580. "FLAC__STREAM_DECODER_OGG_ERROR",
  92581. "FLAC__STREAM_DECODER_SEEK_ERROR",
  92582. "FLAC__STREAM_DECODER_ABORTED",
  92583. "FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR",
  92584. "FLAC__STREAM_DECODER_UNINITIALIZED"
  92585. };
  92586. FLAC_API const char * const FLAC__StreamDecoderInitStatusString[] = {
  92587. "FLAC__STREAM_DECODER_INIT_STATUS_OK",
  92588. "FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER",
  92589. "FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS",
  92590. "FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR",
  92591. "FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE",
  92592. "FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED"
  92593. };
  92594. FLAC_API const char * const FLAC__StreamDecoderReadStatusString[] = {
  92595. "FLAC__STREAM_DECODER_READ_STATUS_CONTINUE",
  92596. "FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM",
  92597. "FLAC__STREAM_DECODER_READ_STATUS_ABORT"
  92598. };
  92599. FLAC_API const char * const FLAC__StreamDecoderSeekStatusString[] = {
  92600. "FLAC__STREAM_DECODER_SEEK_STATUS_OK",
  92601. "FLAC__STREAM_DECODER_SEEK_STATUS_ERROR",
  92602. "FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED"
  92603. };
  92604. FLAC_API const char * const FLAC__StreamDecoderTellStatusString[] = {
  92605. "FLAC__STREAM_DECODER_TELL_STATUS_OK",
  92606. "FLAC__STREAM_DECODER_TELL_STATUS_ERROR",
  92607. "FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED"
  92608. };
  92609. FLAC_API const char * const FLAC__StreamDecoderLengthStatusString[] = {
  92610. "FLAC__STREAM_DECODER_LENGTH_STATUS_OK",
  92611. "FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR",
  92612. "FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED"
  92613. };
  92614. FLAC_API const char * const FLAC__StreamDecoderWriteStatusString[] = {
  92615. "FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE",
  92616. "FLAC__STREAM_DECODER_WRITE_STATUS_ABORT"
  92617. };
  92618. FLAC_API const char * const FLAC__StreamDecoderErrorStatusString[] = {
  92619. "FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC",
  92620. "FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER",
  92621. "FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH",
  92622. "FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM"
  92623. };
  92624. /***********************************************************************
  92625. *
  92626. * Class constructor/destructor
  92627. *
  92628. ***********************************************************************/
  92629. FLAC_API FLAC__StreamDecoder *FLAC__stream_decoder_new(void)
  92630. {
  92631. FLAC__StreamDecoder *decoder;
  92632. unsigned i;
  92633. FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
  92634. decoder = (FLAC__StreamDecoder*)calloc(1, sizeof(FLAC__StreamDecoder));
  92635. if(decoder == 0) {
  92636. return 0;
  92637. }
  92638. decoder->protected_ = (FLAC__StreamDecoderProtected*)calloc(1, sizeof(FLAC__StreamDecoderProtected));
  92639. if(decoder->protected_ == 0) {
  92640. free(decoder);
  92641. return 0;
  92642. }
  92643. decoder->private_ = (FLAC__StreamDecoderPrivate*)calloc(1, sizeof(FLAC__StreamDecoderPrivate));
  92644. if(decoder->private_ == 0) {
  92645. free(decoder->protected_);
  92646. free(decoder);
  92647. return 0;
  92648. }
  92649. decoder->private_->input = FLAC__bitreader_new();
  92650. if(decoder->private_->input == 0) {
  92651. free(decoder->private_);
  92652. free(decoder->protected_);
  92653. free(decoder);
  92654. return 0;
  92655. }
  92656. decoder->private_->metadata_filter_ids_capacity = 16;
  92657. if(0 == (decoder->private_->metadata_filter_ids = (FLAC__byte*)malloc((FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8) * decoder->private_->metadata_filter_ids_capacity))) {
  92658. FLAC__bitreader_delete(decoder->private_->input);
  92659. free(decoder->private_);
  92660. free(decoder->protected_);
  92661. free(decoder);
  92662. return 0;
  92663. }
  92664. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  92665. decoder->private_->output[i] = 0;
  92666. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  92667. }
  92668. decoder->private_->output_capacity = 0;
  92669. decoder->private_->output_channels = 0;
  92670. decoder->private_->has_seek_table = false;
  92671. for(i = 0; i < FLAC__MAX_CHANNELS; i++)
  92672. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&decoder->private_->partitioned_rice_contents[i]);
  92673. decoder->private_->file = 0;
  92674. set_defaults_dec(decoder);
  92675. decoder->protected_->state = FLAC__STREAM_DECODER_UNINITIALIZED;
  92676. return decoder;
  92677. }
  92678. FLAC_API void FLAC__stream_decoder_delete(FLAC__StreamDecoder *decoder)
  92679. {
  92680. unsigned i;
  92681. FLAC__ASSERT(0 != decoder);
  92682. FLAC__ASSERT(0 != decoder->protected_);
  92683. FLAC__ASSERT(0 != decoder->private_);
  92684. FLAC__ASSERT(0 != decoder->private_->input);
  92685. (void)FLAC__stream_decoder_finish(decoder);
  92686. if(0 != decoder->private_->metadata_filter_ids)
  92687. free(decoder->private_->metadata_filter_ids);
  92688. FLAC__bitreader_delete(decoder->private_->input);
  92689. for(i = 0; i < FLAC__MAX_CHANNELS; i++)
  92690. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&decoder->private_->partitioned_rice_contents[i]);
  92691. free(decoder->private_);
  92692. free(decoder->protected_);
  92693. free(decoder);
  92694. }
  92695. /***********************************************************************
  92696. *
  92697. * Public class methods
  92698. *
  92699. ***********************************************************************/
  92700. static FLAC__StreamDecoderInitStatus init_stream_internal_dec(
  92701. FLAC__StreamDecoder *decoder,
  92702. FLAC__StreamDecoderReadCallback read_callback,
  92703. FLAC__StreamDecoderSeekCallback seek_callback,
  92704. FLAC__StreamDecoderTellCallback tell_callback,
  92705. FLAC__StreamDecoderLengthCallback length_callback,
  92706. FLAC__StreamDecoderEofCallback eof_callback,
  92707. FLAC__StreamDecoderWriteCallback write_callback,
  92708. FLAC__StreamDecoderMetadataCallback metadata_callback,
  92709. FLAC__StreamDecoderErrorCallback error_callback,
  92710. void *client_data,
  92711. FLAC__bool is_ogg
  92712. )
  92713. {
  92714. FLAC__ASSERT(0 != decoder);
  92715. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  92716. return FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED;
  92717. #if !FLAC__HAS_OGG
  92718. if(is_ogg)
  92719. return FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER;
  92720. #endif
  92721. if(
  92722. 0 == read_callback ||
  92723. 0 == write_callback ||
  92724. 0 == error_callback ||
  92725. (seek_callback && (0 == tell_callback || 0 == length_callback || 0 == eof_callback))
  92726. )
  92727. return FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS;
  92728. #if FLAC__HAS_OGG
  92729. decoder->private_->is_ogg = is_ogg;
  92730. if(is_ogg && !FLAC__ogg_decoder_aspect_init(&decoder->protected_->ogg_decoder_aspect))
  92731. return decoder->protected_->state = FLAC__STREAM_DECODER_OGG_ERROR;
  92732. #endif
  92733. /*
  92734. * get the CPU info and set the function pointers
  92735. */
  92736. FLAC__cpu_info(&decoder->private_->cpuinfo);
  92737. /* first default to the non-asm routines */
  92738. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal;
  92739. decoder->private_->local_lpc_restore_signal_64bit = FLAC__lpc_restore_signal_wide;
  92740. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal;
  92741. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal;
  92742. decoder->private_->local_bitreader_read_rice_signed_block = FLAC__bitreader_read_rice_signed_block;
  92743. /* now override with asm where appropriate */
  92744. #ifndef FLAC__NO_ASM
  92745. if(decoder->private_->cpuinfo.use_asm) {
  92746. #ifdef FLAC__CPU_IA32
  92747. FLAC__ASSERT(decoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32);
  92748. #ifdef FLAC__HAS_NASM
  92749. #if 1 /*@@@@@@ OPT: not clearly faster, needs more testing */
  92750. if(decoder->private_->cpuinfo.data.ia32.bswap)
  92751. decoder->private_->local_bitreader_read_rice_signed_block = FLAC__bitreader_read_rice_signed_block_asm_ia32_bswap;
  92752. #endif
  92753. if(decoder->private_->cpuinfo.data.ia32.mmx) {
  92754. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal_asm_ia32;
  92755. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ia32_mmx;
  92756. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ia32_mmx;
  92757. }
  92758. else {
  92759. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal_asm_ia32;
  92760. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ia32;
  92761. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ia32;
  92762. }
  92763. #endif
  92764. #elif defined FLAC__CPU_PPC
  92765. FLAC__ASSERT(decoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_PPC);
  92766. if(decoder->private_->cpuinfo.data.ppc.altivec) {
  92767. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ppc_altivec_16;
  92768. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ppc_altivec_16_order8;
  92769. }
  92770. #endif
  92771. }
  92772. #endif
  92773. /* from here on, errors are fatal */
  92774. if(!FLAC__bitreader_init(decoder->private_->input, decoder->private_->cpuinfo, read_callback_, decoder)) {
  92775. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  92776. return FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR;
  92777. }
  92778. decoder->private_->read_callback = read_callback;
  92779. decoder->private_->seek_callback = seek_callback;
  92780. decoder->private_->tell_callback = tell_callback;
  92781. decoder->private_->length_callback = length_callback;
  92782. decoder->private_->eof_callback = eof_callback;
  92783. decoder->private_->write_callback = write_callback;
  92784. decoder->private_->metadata_callback = metadata_callback;
  92785. decoder->private_->error_callback = error_callback;
  92786. decoder->private_->client_data = client_data;
  92787. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size = 0;
  92788. decoder->private_->samples_decoded = 0;
  92789. decoder->private_->has_stream_info = false;
  92790. decoder->private_->cached = false;
  92791. decoder->private_->do_md5_checking = decoder->protected_->md5_checking;
  92792. decoder->private_->is_seeking = false;
  92793. decoder->private_->internal_reset_hack = true; /* so the following reset does not try to rewind the input */
  92794. if(!FLAC__stream_decoder_reset(decoder)) {
  92795. /* above call sets the state for us */
  92796. return FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR;
  92797. }
  92798. return FLAC__STREAM_DECODER_INIT_STATUS_OK;
  92799. }
  92800. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_stream(
  92801. FLAC__StreamDecoder *decoder,
  92802. FLAC__StreamDecoderReadCallback read_callback,
  92803. FLAC__StreamDecoderSeekCallback seek_callback,
  92804. FLAC__StreamDecoderTellCallback tell_callback,
  92805. FLAC__StreamDecoderLengthCallback length_callback,
  92806. FLAC__StreamDecoderEofCallback eof_callback,
  92807. FLAC__StreamDecoderWriteCallback write_callback,
  92808. FLAC__StreamDecoderMetadataCallback metadata_callback,
  92809. FLAC__StreamDecoderErrorCallback error_callback,
  92810. void *client_data
  92811. )
  92812. {
  92813. return init_stream_internal_dec(
  92814. decoder,
  92815. read_callback,
  92816. seek_callback,
  92817. tell_callback,
  92818. length_callback,
  92819. eof_callback,
  92820. write_callback,
  92821. metadata_callback,
  92822. error_callback,
  92823. client_data,
  92824. /*is_ogg=*/false
  92825. );
  92826. }
  92827. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_stream(
  92828. FLAC__StreamDecoder *decoder,
  92829. FLAC__StreamDecoderReadCallback read_callback,
  92830. FLAC__StreamDecoderSeekCallback seek_callback,
  92831. FLAC__StreamDecoderTellCallback tell_callback,
  92832. FLAC__StreamDecoderLengthCallback length_callback,
  92833. FLAC__StreamDecoderEofCallback eof_callback,
  92834. FLAC__StreamDecoderWriteCallback write_callback,
  92835. FLAC__StreamDecoderMetadataCallback metadata_callback,
  92836. FLAC__StreamDecoderErrorCallback error_callback,
  92837. void *client_data
  92838. )
  92839. {
  92840. return init_stream_internal_dec(
  92841. decoder,
  92842. read_callback,
  92843. seek_callback,
  92844. tell_callback,
  92845. length_callback,
  92846. eof_callback,
  92847. write_callback,
  92848. metadata_callback,
  92849. error_callback,
  92850. client_data,
  92851. /*is_ogg=*/true
  92852. );
  92853. }
  92854. static FLAC__StreamDecoderInitStatus init_FILE_internal_(
  92855. FLAC__StreamDecoder *decoder,
  92856. FILE *file,
  92857. FLAC__StreamDecoderWriteCallback write_callback,
  92858. FLAC__StreamDecoderMetadataCallback metadata_callback,
  92859. FLAC__StreamDecoderErrorCallback error_callback,
  92860. void *client_data,
  92861. FLAC__bool is_ogg
  92862. )
  92863. {
  92864. FLAC__ASSERT(0 != decoder);
  92865. FLAC__ASSERT(0 != file);
  92866. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  92867. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED);
  92868. if(0 == write_callback || 0 == error_callback)
  92869. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS);
  92870. /*
  92871. * To make sure that our file does not go unclosed after an error, we
  92872. * must assign the FILE pointer before any further error can occur in
  92873. * this routine.
  92874. */
  92875. if(file == stdin)
  92876. file = get_binary_stdin_(); /* just to be safe */
  92877. decoder->private_->file = file;
  92878. return init_stream_internal_dec(
  92879. decoder,
  92880. file_read_callback_dec,
  92881. decoder->private_->file == stdin? 0: file_seek_callback_dec,
  92882. decoder->private_->file == stdin? 0: file_tell_callback_dec,
  92883. decoder->private_->file == stdin? 0: file_length_callback_,
  92884. file_eof_callback_,
  92885. write_callback,
  92886. metadata_callback,
  92887. error_callback,
  92888. client_data,
  92889. is_ogg
  92890. );
  92891. }
  92892. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_FILE(
  92893. FLAC__StreamDecoder *decoder,
  92894. FILE *file,
  92895. FLAC__StreamDecoderWriteCallback write_callback,
  92896. FLAC__StreamDecoderMetadataCallback metadata_callback,
  92897. FLAC__StreamDecoderErrorCallback error_callback,
  92898. void *client_data
  92899. )
  92900. {
  92901. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/false);
  92902. }
  92903. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_FILE(
  92904. FLAC__StreamDecoder *decoder,
  92905. FILE *file,
  92906. FLAC__StreamDecoderWriteCallback write_callback,
  92907. FLAC__StreamDecoderMetadataCallback metadata_callback,
  92908. FLAC__StreamDecoderErrorCallback error_callback,
  92909. void *client_data
  92910. )
  92911. {
  92912. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/true);
  92913. }
  92914. static FLAC__StreamDecoderInitStatus init_file_internal_(
  92915. FLAC__StreamDecoder *decoder,
  92916. const char *filename,
  92917. FLAC__StreamDecoderWriteCallback write_callback,
  92918. FLAC__StreamDecoderMetadataCallback metadata_callback,
  92919. FLAC__StreamDecoderErrorCallback error_callback,
  92920. void *client_data,
  92921. FLAC__bool is_ogg
  92922. )
  92923. {
  92924. FILE *file;
  92925. FLAC__ASSERT(0 != decoder);
  92926. /*
  92927. * To make sure that our file does not go unclosed after an error, we
  92928. * have to do the same entrance checks here that are later performed
  92929. * in FLAC__stream_decoder_init_FILE() before the FILE* is assigned.
  92930. */
  92931. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  92932. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED);
  92933. if(0 == write_callback || 0 == error_callback)
  92934. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS);
  92935. file = filename? fopen(filename, "rb") : stdin;
  92936. if(0 == file)
  92937. return FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE;
  92938. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, is_ogg);
  92939. }
  92940. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_file(
  92941. FLAC__StreamDecoder *decoder,
  92942. const char *filename,
  92943. FLAC__StreamDecoderWriteCallback write_callback,
  92944. FLAC__StreamDecoderMetadataCallback metadata_callback,
  92945. FLAC__StreamDecoderErrorCallback error_callback,
  92946. void *client_data
  92947. )
  92948. {
  92949. return init_file_internal_(decoder, filename, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/false);
  92950. }
  92951. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_file(
  92952. FLAC__StreamDecoder *decoder,
  92953. const char *filename,
  92954. FLAC__StreamDecoderWriteCallback write_callback,
  92955. FLAC__StreamDecoderMetadataCallback metadata_callback,
  92956. FLAC__StreamDecoderErrorCallback error_callback,
  92957. void *client_data
  92958. )
  92959. {
  92960. return init_file_internal_(decoder, filename, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/true);
  92961. }
  92962. FLAC_API FLAC__bool FLAC__stream_decoder_finish(FLAC__StreamDecoder *decoder)
  92963. {
  92964. FLAC__bool md5_failed = false;
  92965. unsigned i;
  92966. FLAC__ASSERT(0 != decoder);
  92967. FLAC__ASSERT(0 != decoder->private_);
  92968. FLAC__ASSERT(0 != decoder->protected_);
  92969. if(decoder->protected_->state == FLAC__STREAM_DECODER_UNINITIALIZED)
  92970. return true;
  92971. /* see the comment in FLAC__seekable_stream_decoder_reset() as to why we
  92972. * always call FLAC__MD5Final()
  92973. */
  92974. FLAC__MD5Final(decoder->private_->computed_md5sum, &decoder->private_->md5context);
  92975. if(decoder->private_->has_seek_table && 0 != decoder->private_->seek_table.data.seek_table.points) {
  92976. free(decoder->private_->seek_table.data.seek_table.points);
  92977. decoder->private_->seek_table.data.seek_table.points = 0;
  92978. decoder->private_->has_seek_table = false;
  92979. }
  92980. FLAC__bitreader_free(decoder->private_->input);
  92981. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  92982. /* WATCHOUT:
  92983. * FLAC__lpc_restore_signal_asm_ia32_mmx() requires that the
  92984. * output arrays have a buffer of up to 3 zeroes in front
  92985. * (at negative indices) for alignment purposes; we use 4
  92986. * to keep the data well-aligned.
  92987. */
  92988. if(0 != decoder->private_->output[i]) {
  92989. free(decoder->private_->output[i]-4);
  92990. decoder->private_->output[i] = 0;
  92991. }
  92992. if(0 != decoder->private_->residual_unaligned[i]) {
  92993. free(decoder->private_->residual_unaligned[i]);
  92994. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  92995. }
  92996. }
  92997. decoder->private_->output_capacity = 0;
  92998. decoder->private_->output_channels = 0;
  92999. #if FLAC__HAS_OGG
  93000. if(decoder->private_->is_ogg)
  93001. FLAC__ogg_decoder_aspect_finish(&decoder->protected_->ogg_decoder_aspect);
  93002. #endif
  93003. if(0 != decoder->private_->file) {
  93004. if(decoder->private_->file != stdin)
  93005. fclose(decoder->private_->file);
  93006. decoder->private_->file = 0;
  93007. }
  93008. if(decoder->private_->do_md5_checking) {
  93009. if(memcmp(decoder->private_->stream_info.data.stream_info.md5sum, decoder->private_->computed_md5sum, 16))
  93010. md5_failed = true;
  93011. }
  93012. decoder->private_->is_seeking = false;
  93013. set_defaults_dec(decoder);
  93014. decoder->protected_->state = FLAC__STREAM_DECODER_UNINITIALIZED;
  93015. return !md5_failed;
  93016. }
  93017. FLAC_API FLAC__bool FLAC__stream_decoder_set_ogg_serial_number(FLAC__StreamDecoder *decoder, long value)
  93018. {
  93019. FLAC__ASSERT(0 != decoder);
  93020. FLAC__ASSERT(0 != decoder->private_);
  93021. FLAC__ASSERT(0 != decoder->protected_);
  93022. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  93023. return false;
  93024. #if FLAC__HAS_OGG
  93025. /* can't check decoder->private_->is_ogg since that's not set until init time */
  93026. FLAC__ogg_decoder_aspect_set_serial_number(&decoder->protected_->ogg_decoder_aspect, value);
  93027. return true;
  93028. #else
  93029. (void)value;
  93030. return false;
  93031. #endif
  93032. }
  93033. FLAC_API FLAC__bool FLAC__stream_decoder_set_md5_checking(FLAC__StreamDecoder *decoder, FLAC__bool value)
  93034. {
  93035. FLAC__ASSERT(0 != decoder);
  93036. FLAC__ASSERT(0 != decoder->protected_);
  93037. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  93038. return false;
  93039. decoder->protected_->md5_checking = value;
  93040. return true;
  93041. }
  93042. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond(FLAC__StreamDecoder *decoder, FLAC__MetadataType type)
  93043. {
  93044. FLAC__ASSERT(0 != decoder);
  93045. FLAC__ASSERT(0 != decoder->private_);
  93046. FLAC__ASSERT(0 != decoder->protected_);
  93047. FLAC__ASSERT((unsigned)type <= FLAC__MAX_METADATA_TYPE_CODE);
  93048. /* double protection */
  93049. if((unsigned)type > FLAC__MAX_METADATA_TYPE_CODE)
  93050. return false;
  93051. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  93052. return false;
  93053. decoder->private_->metadata_filter[type] = true;
  93054. if(type == FLAC__METADATA_TYPE_APPLICATION)
  93055. decoder->private_->metadata_filter_ids_count = 0;
  93056. return true;
  93057. }
  93058. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4])
  93059. {
  93060. FLAC__ASSERT(0 != decoder);
  93061. FLAC__ASSERT(0 != decoder->private_);
  93062. FLAC__ASSERT(0 != decoder->protected_);
  93063. FLAC__ASSERT(0 != id);
  93064. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  93065. return false;
  93066. if(decoder->private_->metadata_filter[FLAC__METADATA_TYPE_APPLICATION])
  93067. return true;
  93068. FLAC__ASSERT(0 != decoder->private_->metadata_filter_ids);
  93069. if(decoder->private_->metadata_filter_ids_count == decoder->private_->metadata_filter_ids_capacity) {
  93070. 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))) {
  93071. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  93072. return false;
  93073. }
  93074. decoder->private_->metadata_filter_ids_capacity *= 2;
  93075. }
  93076. 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));
  93077. decoder->private_->metadata_filter_ids_count++;
  93078. return true;
  93079. }
  93080. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_all(FLAC__StreamDecoder *decoder)
  93081. {
  93082. unsigned i;
  93083. FLAC__ASSERT(0 != decoder);
  93084. FLAC__ASSERT(0 != decoder->private_);
  93085. FLAC__ASSERT(0 != decoder->protected_);
  93086. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  93087. return false;
  93088. for(i = 0; i < sizeof(decoder->private_->metadata_filter) / sizeof(decoder->private_->metadata_filter[0]); i++)
  93089. decoder->private_->metadata_filter[i] = true;
  93090. decoder->private_->metadata_filter_ids_count = 0;
  93091. return true;
  93092. }
  93093. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore(FLAC__StreamDecoder *decoder, FLAC__MetadataType type)
  93094. {
  93095. FLAC__ASSERT(0 != decoder);
  93096. FLAC__ASSERT(0 != decoder->private_);
  93097. FLAC__ASSERT(0 != decoder->protected_);
  93098. FLAC__ASSERT((unsigned)type <= FLAC__MAX_METADATA_TYPE_CODE);
  93099. /* double protection */
  93100. if((unsigned)type > FLAC__MAX_METADATA_TYPE_CODE)
  93101. return false;
  93102. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  93103. return false;
  93104. decoder->private_->metadata_filter[type] = false;
  93105. if(type == FLAC__METADATA_TYPE_APPLICATION)
  93106. decoder->private_->metadata_filter_ids_count = 0;
  93107. return true;
  93108. }
  93109. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4])
  93110. {
  93111. FLAC__ASSERT(0 != decoder);
  93112. FLAC__ASSERT(0 != decoder->private_);
  93113. FLAC__ASSERT(0 != decoder->protected_);
  93114. FLAC__ASSERT(0 != id);
  93115. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  93116. return false;
  93117. if(!decoder->private_->metadata_filter[FLAC__METADATA_TYPE_APPLICATION])
  93118. return true;
  93119. FLAC__ASSERT(0 != decoder->private_->metadata_filter_ids);
  93120. if(decoder->private_->metadata_filter_ids_count == decoder->private_->metadata_filter_ids_capacity) {
  93121. 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))) {
  93122. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  93123. return false;
  93124. }
  93125. decoder->private_->metadata_filter_ids_capacity *= 2;
  93126. }
  93127. 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));
  93128. decoder->private_->metadata_filter_ids_count++;
  93129. return true;
  93130. }
  93131. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_all(FLAC__StreamDecoder *decoder)
  93132. {
  93133. FLAC__ASSERT(0 != decoder);
  93134. FLAC__ASSERT(0 != decoder->private_);
  93135. FLAC__ASSERT(0 != decoder->protected_);
  93136. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  93137. return false;
  93138. memset(decoder->private_->metadata_filter, 0, sizeof(decoder->private_->metadata_filter));
  93139. decoder->private_->metadata_filter_ids_count = 0;
  93140. return true;
  93141. }
  93142. FLAC_API FLAC__StreamDecoderState FLAC__stream_decoder_get_state(const FLAC__StreamDecoder *decoder)
  93143. {
  93144. FLAC__ASSERT(0 != decoder);
  93145. FLAC__ASSERT(0 != decoder->protected_);
  93146. return decoder->protected_->state;
  93147. }
  93148. FLAC_API const char *FLAC__stream_decoder_get_resolved_state_string(const FLAC__StreamDecoder *decoder)
  93149. {
  93150. return FLAC__StreamDecoderStateString[decoder->protected_->state];
  93151. }
  93152. FLAC_API FLAC__bool FLAC__stream_decoder_get_md5_checking(const FLAC__StreamDecoder *decoder)
  93153. {
  93154. FLAC__ASSERT(0 != decoder);
  93155. FLAC__ASSERT(0 != decoder->protected_);
  93156. return decoder->protected_->md5_checking;
  93157. }
  93158. FLAC_API FLAC__uint64 FLAC__stream_decoder_get_total_samples(const FLAC__StreamDecoder *decoder)
  93159. {
  93160. FLAC__ASSERT(0 != decoder);
  93161. FLAC__ASSERT(0 != decoder->protected_);
  93162. return decoder->private_->has_stream_info? decoder->private_->stream_info.data.stream_info.total_samples : 0;
  93163. }
  93164. FLAC_API unsigned FLAC__stream_decoder_get_channels(const FLAC__StreamDecoder *decoder)
  93165. {
  93166. FLAC__ASSERT(0 != decoder);
  93167. FLAC__ASSERT(0 != decoder->protected_);
  93168. return decoder->protected_->channels;
  93169. }
  93170. FLAC_API FLAC__ChannelAssignment FLAC__stream_decoder_get_channel_assignment(const FLAC__StreamDecoder *decoder)
  93171. {
  93172. FLAC__ASSERT(0 != decoder);
  93173. FLAC__ASSERT(0 != decoder->protected_);
  93174. return decoder->protected_->channel_assignment;
  93175. }
  93176. FLAC_API unsigned FLAC__stream_decoder_get_bits_per_sample(const FLAC__StreamDecoder *decoder)
  93177. {
  93178. FLAC__ASSERT(0 != decoder);
  93179. FLAC__ASSERT(0 != decoder->protected_);
  93180. return decoder->protected_->bits_per_sample;
  93181. }
  93182. FLAC_API unsigned FLAC__stream_decoder_get_sample_rate(const FLAC__StreamDecoder *decoder)
  93183. {
  93184. FLAC__ASSERT(0 != decoder);
  93185. FLAC__ASSERT(0 != decoder->protected_);
  93186. return decoder->protected_->sample_rate;
  93187. }
  93188. FLAC_API unsigned FLAC__stream_decoder_get_blocksize(const FLAC__StreamDecoder *decoder)
  93189. {
  93190. FLAC__ASSERT(0 != decoder);
  93191. FLAC__ASSERT(0 != decoder->protected_);
  93192. return decoder->protected_->blocksize;
  93193. }
  93194. FLAC_API FLAC__bool FLAC__stream_decoder_get_decode_position(const FLAC__StreamDecoder *decoder, FLAC__uint64 *position)
  93195. {
  93196. FLAC__ASSERT(0 != decoder);
  93197. FLAC__ASSERT(0 != decoder->private_);
  93198. FLAC__ASSERT(0 != position);
  93199. #if FLAC__HAS_OGG
  93200. if(decoder->private_->is_ogg)
  93201. return false;
  93202. #endif
  93203. if(0 == decoder->private_->tell_callback)
  93204. return false;
  93205. if(decoder->private_->tell_callback(decoder, position, decoder->private_->client_data) != FLAC__STREAM_DECODER_TELL_STATUS_OK)
  93206. return false;
  93207. /* should never happen since all FLAC frames and metadata blocks are byte aligned, but check just in case */
  93208. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input))
  93209. return false;
  93210. FLAC__ASSERT(*position >= FLAC__stream_decoder_get_input_bytes_unconsumed(decoder));
  93211. *position -= FLAC__stream_decoder_get_input_bytes_unconsumed(decoder);
  93212. return true;
  93213. }
  93214. FLAC_API FLAC__bool FLAC__stream_decoder_flush(FLAC__StreamDecoder *decoder)
  93215. {
  93216. FLAC__ASSERT(0 != decoder);
  93217. FLAC__ASSERT(0 != decoder->private_);
  93218. FLAC__ASSERT(0 != decoder->protected_);
  93219. decoder->private_->samples_decoded = 0;
  93220. decoder->private_->do_md5_checking = false;
  93221. #if FLAC__HAS_OGG
  93222. if(decoder->private_->is_ogg)
  93223. FLAC__ogg_decoder_aspect_flush(&decoder->protected_->ogg_decoder_aspect);
  93224. #endif
  93225. if(!FLAC__bitreader_clear(decoder->private_->input)) {
  93226. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  93227. return false;
  93228. }
  93229. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  93230. return true;
  93231. }
  93232. FLAC_API FLAC__bool FLAC__stream_decoder_reset(FLAC__StreamDecoder *decoder)
  93233. {
  93234. FLAC__ASSERT(0 != decoder);
  93235. FLAC__ASSERT(0 != decoder->private_);
  93236. FLAC__ASSERT(0 != decoder->protected_);
  93237. if(!FLAC__stream_decoder_flush(decoder)) {
  93238. /* above call sets the state for us */
  93239. return false;
  93240. }
  93241. #if FLAC__HAS_OGG
  93242. /*@@@ could go in !internal_reset_hack block below */
  93243. if(decoder->private_->is_ogg)
  93244. FLAC__ogg_decoder_aspect_reset(&decoder->protected_->ogg_decoder_aspect);
  93245. #endif
  93246. /* Rewind if necessary. If FLAC__stream_decoder_init() is calling us,
  93247. * (internal_reset_hack) don't try to rewind since we are already at
  93248. * the beginning of the stream and don't want to fail if the input is
  93249. * not seekable.
  93250. */
  93251. if(!decoder->private_->internal_reset_hack) {
  93252. if(decoder->private_->file == stdin)
  93253. return false; /* can't rewind stdin, reset fails */
  93254. if(decoder->private_->seek_callback && decoder->private_->seek_callback(decoder, 0, decoder->private_->client_data) == FLAC__STREAM_DECODER_SEEK_STATUS_ERROR)
  93255. return false; /* seekable and seek fails, reset fails */
  93256. }
  93257. else
  93258. decoder->private_->internal_reset_hack = false;
  93259. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_METADATA;
  93260. decoder->private_->has_stream_info = false;
  93261. if(decoder->private_->has_seek_table && 0 != decoder->private_->seek_table.data.seek_table.points) {
  93262. free(decoder->private_->seek_table.data.seek_table.points);
  93263. decoder->private_->seek_table.data.seek_table.points = 0;
  93264. decoder->private_->has_seek_table = false;
  93265. }
  93266. decoder->private_->do_md5_checking = decoder->protected_->md5_checking;
  93267. /*
  93268. * This goes in reset() and not flush() because according to the spec, a
  93269. * fixed-blocksize stream must stay that way through the whole stream.
  93270. */
  93271. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size = 0;
  93272. /* We initialize the FLAC__MD5Context even though we may never use it. This
  93273. * is because md5 checking may be turned on to start and then turned off if
  93274. * a seek occurs. So we init the context here and finalize it in
  93275. * FLAC__stream_decoder_finish() to make sure things are always cleaned up
  93276. * properly.
  93277. */
  93278. FLAC__MD5Init(&decoder->private_->md5context);
  93279. decoder->private_->first_frame_offset = 0;
  93280. decoder->private_->unparseable_frame_count = 0;
  93281. return true;
  93282. }
  93283. FLAC_API FLAC__bool FLAC__stream_decoder_process_single(FLAC__StreamDecoder *decoder)
  93284. {
  93285. FLAC__bool got_a_frame;
  93286. FLAC__ASSERT(0 != decoder);
  93287. FLAC__ASSERT(0 != decoder->protected_);
  93288. while(1) {
  93289. switch(decoder->protected_->state) {
  93290. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  93291. if(!find_metadata_(decoder))
  93292. return false; /* above function sets the status for us */
  93293. break;
  93294. case FLAC__STREAM_DECODER_READ_METADATA:
  93295. if(!read_metadata_(decoder))
  93296. return false; /* above function sets the status for us */
  93297. else
  93298. return true;
  93299. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  93300. if(!frame_sync_(decoder))
  93301. return true; /* above function sets the status for us */
  93302. break;
  93303. case FLAC__STREAM_DECODER_READ_FRAME:
  93304. if(!read_frame_(decoder, &got_a_frame, /*do_full_decode=*/true))
  93305. return false; /* above function sets the status for us */
  93306. if(got_a_frame)
  93307. return true; /* above function sets the status for us */
  93308. break;
  93309. case FLAC__STREAM_DECODER_END_OF_STREAM:
  93310. case FLAC__STREAM_DECODER_ABORTED:
  93311. return true;
  93312. default:
  93313. FLAC__ASSERT(0);
  93314. return false;
  93315. }
  93316. }
  93317. }
  93318. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_metadata(FLAC__StreamDecoder *decoder)
  93319. {
  93320. FLAC__ASSERT(0 != decoder);
  93321. FLAC__ASSERT(0 != decoder->protected_);
  93322. while(1) {
  93323. switch(decoder->protected_->state) {
  93324. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  93325. if(!find_metadata_(decoder))
  93326. return false; /* above function sets the status for us */
  93327. break;
  93328. case FLAC__STREAM_DECODER_READ_METADATA:
  93329. if(!read_metadata_(decoder))
  93330. return false; /* above function sets the status for us */
  93331. break;
  93332. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  93333. case FLAC__STREAM_DECODER_READ_FRAME:
  93334. case FLAC__STREAM_DECODER_END_OF_STREAM:
  93335. case FLAC__STREAM_DECODER_ABORTED:
  93336. return true;
  93337. default:
  93338. FLAC__ASSERT(0);
  93339. return false;
  93340. }
  93341. }
  93342. }
  93343. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_stream(FLAC__StreamDecoder *decoder)
  93344. {
  93345. FLAC__bool dummy;
  93346. FLAC__ASSERT(0 != decoder);
  93347. FLAC__ASSERT(0 != decoder->protected_);
  93348. while(1) {
  93349. switch(decoder->protected_->state) {
  93350. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  93351. if(!find_metadata_(decoder))
  93352. return false; /* above function sets the status for us */
  93353. break;
  93354. case FLAC__STREAM_DECODER_READ_METADATA:
  93355. if(!read_metadata_(decoder))
  93356. return false; /* above function sets the status for us */
  93357. break;
  93358. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  93359. if(!frame_sync_(decoder))
  93360. return true; /* above function sets the status for us */
  93361. break;
  93362. case FLAC__STREAM_DECODER_READ_FRAME:
  93363. if(!read_frame_(decoder, &dummy, /*do_full_decode=*/true))
  93364. return false; /* above function sets the status for us */
  93365. break;
  93366. case FLAC__STREAM_DECODER_END_OF_STREAM:
  93367. case FLAC__STREAM_DECODER_ABORTED:
  93368. return true;
  93369. default:
  93370. FLAC__ASSERT(0);
  93371. return false;
  93372. }
  93373. }
  93374. }
  93375. FLAC_API FLAC__bool FLAC__stream_decoder_skip_single_frame(FLAC__StreamDecoder *decoder)
  93376. {
  93377. FLAC__bool got_a_frame;
  93378. FLAC__ASSERT(0 != decoder);
  93379. FLAC__ASSERT(0 != decoder->protected_);
  93380. while(1) {
  93381. switch(decoder->protected_->state) {
  93382. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  93383. case FLAC__STREAM_DECODER_READ_METADATA:
  93384. return false; /* above function sets the status for us */
  93385. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  93386. if(!frame_sync_(decoder))
  93387. return true; /* above function sets the status for us */
  93388. break;
  93389. case FLAC__STREAM_DECODER_READ_FRAME:
  93390. if(!read_frame_(decoder, &got_a_frame, /*do_full_decode=*/false))
  93391. return false; /* above function sets the status for us */
  93392. if(got_a_frame)
  93393. return true; /* above function sets the status for us */
  93394. break;
  93395. case FLAC__STREAM_DECODER_END_OF_STREAM:
  93396. case FLAC__STREAM_DECODER_ABORTED:
  93397. return true;
  93398. default:
  93399. FLAC__ASSERT(0);
  93400. return false;
  93401. }
  93402. }
  93403. }
  93404. FLAC_API FLAC__bool FLAC__stream_decoder_seek_absolute(FLAC__StreamDecoder *decoder, FLAC__uint64 sample)
  93405. {
  93406. FLAC__uint64 length;
  93407. FLAC__ASSERT(0 != decoder);
  93408. if(
  93409. decoder->protected_->state != FLAC__STREAM_DECODER_SEARCH_FOR_METADATA &&
  93410. decoder->protected_->state != FLAC__STREAM_DECODER_READ_METADATA &&
  93411. decoder->protected_->state != FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC &&
  93412. decoder->protected_->state != FLAC__STREAM_DECODER_READ_FRAME &&
  93413. decoder->protected_->state != FLAC__STREAM_DECODER_END_OF_STREAM
  93414. )
  93415. return false;
  93416. if(0 == decoder->private_->seek_callback)
  93417. return false;
  93418. FLAC__ASSERT(decoder->private_->seek_callback);
  93419. FLAC__ASSERT(decoder->private_->tell_callback);
  93420. FLAC__ASSERT(decoder->private_->length_callback);
  93421. FLAC__ASSERT(decoder->private_->eof_callback);
  93422. if(FLAC__stream_decoder_get_total_samples(decoder) > 0 && sample >= FLAC__stream_decoder_get_total_samples(decoder))
  93423. return false;
  93424. decoder->private_->is_seeking = true;
  93425. /* turn off md5 checking if a seek is attempted */
  93426. decoder->private_->do_md5_checking = false;
  93427. /* 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) */
  93428. if(decoder->private_->length_callback(decoder, &length, decoder->private_->client_data) != FLAC__STREAM_DECODER_LENGTH_STATUS_OK) {
  93429. decoder->private_->is_seeking = false;
  93430. return false;
  93431. }
  93432. /* if we haven't finished processing the metadata yet, do that so we have the STREAMINFO, SEEK_TABLE, and first_frame_offset */
  93433. if(
  93434. decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_METADATA ||
  93435. decoder->protected_->state == FLAC__STREAM_DECODER_READ_METADATA
  93436. ) {
  93437. if(!FLAC__stream_decoder_process_until_end_of_metadata(decoder)) {
  93438. /* above call sets the state for us */
  93439. decoder->private_->is_seeking = false;
  93440. return false;
  93441. }
  93442. /* check this again in case we didn't know total_samples the first time */
  93443. if(FLAC__stream_decoder_get_total_samples(decoder) > 0 && sample >= FLAC__stream_decoder_get_total_samples(decoder)) {
  93444. decoder->private_->is_seeking = false;
  93445. return false;
  93446. }
  93447. }
  93448. {
  93449. const FLAC__bool ok =
  93450. #if FLAC__HAS_OGG
  93451. decoder->private_->is_ogg?
  93452. seek_to_absolute_sample_ogg_(decoder, length, sample) :
  93453. #endif
  93454. seek_to_absolute_sample_(decoder, length, sample)
  93455. ;
  93456. decoder->private_->is_seeking = false;
  93457. return ok;
  93458. }
  93459. }
  93460. /***********************************************************************
  93461. *
  93462. * Protected class methods
  93463. *
  93464. ***********************************************************************/
  93465. unsigned FLAC__stream_decoder_get_input_bytes_unconsumed(const FLAC__StreamDecoder *decoder)
  93466. {
  93467. FLAC__ASSERT(0 != decoder);
  93468. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  93469. FLAC__ASSERT(!(FLAC__bitreader_get_input_bits_unconsumed(decoder->private_->input) & 7));
  93470. return FLAC__bitreader_get_input_bits_unconsumed(decoder->private_->input) / 8;
  93471. }
  93472. /***********************************************************************
  93473. *
  93474. * Private class methods
  93475. *
  93476. ***********************************************************************/
  93477. void set_defaults_dec(FLAC__StreamDecoder *decoder)
  93478. {
  93479. #if FLAC__HAS_OGG
  93480. decoder->private_->is_ogg = false;
  93481. #endif
  93482. decoder->private_->read_callback = 0;
  93483. decoder->private_->seek_callback = 0;
  93484. decoder->private_->tell_callback = 0;
  93485. decoder->private_->length_callback = 0;
  93486. decoder->private_->eof_callback = 0;
  93487. decoder->private_->write_callback = 0;
  93488. decoder->private_->metadata_callback = 0;
  93489. decoder->private_->error_callback = 0;
  93490. decoder->private_->client_data = 0;
  93491. memset(decoder->private_->metadata_filter, 0, sizeof(decoder->private_->metadata_filter));
  93492. decoder->private_->metadata_filter[FLAC__METADATA_TYPE_STREAMINFO] = true;
  93493. decoder->private_->metadata_filter_ids_count = 0;
  93494. decoder->protected_->md5_checking = false;
  93495. #if FLAC__HAS_OGG
  93496. FLAC__ogg_decoder_aspect_set_defaults(&decoder->protected_->ogg_decoder_aspect);
  93497. #endif
  93498. }
  93499. /*
  93500. * This will forcibly set stdin to binary mode (for OSes that require it)
  93501. */
  93502. FILE *get_binary_stdin_(void)
  93503. {
  93504. /* if something breaks here it is probably due to the presence or
  93505. * absence of an underscore before the identifiers 'setmode',
  93506. * 'fileno', and/or 'O_BINARY'; check your system header files.
  93507. */
  93508. #if defined _MSC_VER || defined __MINGW32__
  93509. _setmode(_fileno(stdin), _O_BINARY);
  93510. #elif defined __CYGWIN__
  93511. /* almost certainly not needed for any modern Cygwin, but let's be safe... */
  93512. setmode(_fileno(stdin), _O_BINARY);
  93513. #elif defined __EMX__
  93514. setmode(fileno(stdin), O_BINARY);
  93515. #endif
  93516. return stdin;
  93517. }
  93518. FLAC__bool allocate_output_(FLAC__StreamDecoder *decoder, unsigned size, unsigned channels)
  93519. {
  93520. unsigned i;
  93521. FLAC__int32 *tmp;
  93522. if(size <= decoder->private_->output_capacity && channels <= decoder->private_->output_channels)
  93523. return true;
  93524. /* simply using realloc() is not practical because the number of channels may change mid-stream */
  93525. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  93526. if(0 != decoder->private_->output[i]) {
  93527. free(decoder->private_->output[i]-4);
  93528. decoder->private_->output[i] = 0;
  93529. }
  93530. if(0 != decoder->private_->residual_unaligned[i]) {
  93531. free(decoder->private_->residual_unaligned[i]);
  93532. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  93533. }
  93534. }
  93535. for(i = 0; i < channels; i++) {
  93536. /* WATCHOUT:
  93537. * FLAC__lpc_restore_signal_asm_ia32_mmx() requires that the
  93538. * output arrays have a buffer of up to 3 zeroes in front
  93539. * (at negative indices) for alignment purposes; we use 4
  93540. * to keep the data well-aligned.
  93541. */
  93542. tmp = (FLAC__int32*)safe_malloc_muladd2_(sizeof(FLAC__int32), /*times (*/size, /*+*/4/*)*/);
  93543. if(tmp == 0) {
  93544. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  93545. return false;
  93546. }
  93547. memset(tmp, 0, sizeof(FLAC__int32)*4);
  93548. decoder->private_->output[i] = tmp + 4;
  93549. /* WATCHOUT:
  93550. * minimum of quadword alignment for PPC vector optimizations is REQUIRED:
  93551. */
  93552. if(!FLAC__memory_alloc_aligned_int32_array(size, &decoder->private_->residual_unaligned[i], &decoder->private_->residual[i])) {
  93553. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  93554. return false;
  93555. }
  93556. }
  93557. decoder->private_->output_capacity = size;
  93558. decoder->private_->output_channels = channels;
  93559. return true;
  93560. }
  93561. FLAC__bool has_id_filtered_(FLAC__StreamDecoder *decoder, FLAC__byte *id)
  93562. {
  93563. size_t i;
  93564. FLAC__ASSERT(0 != decoder);
  93565. FLAC__ASSERT(0 != decoder->private_);
  93566. for(i = 0; i < decoder->private_->metadata_filter_ids_count; i++)
  93567. if(0 == memcmp(decoder->private_->metadata_filter_ids + i * (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8), id, (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8)))
  93568. return true;
  93569. return false;
  93570. }
  93571. FLAC__bool find_metadata_(FLAC__StreamDecoder *decoder)
  93572. {
  93573. FLAC__uint32 x;
  93574. unsigned i, id_;
  93575. FLAC__bool first = true;
  93576. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  93577. for(i = id_ = 0; i < 4; ) {
  93578. if(decoder->private_->cached) {
  93579. x = (FLAC__uint32)decoder->private_->lookahead;
  93580. decoder->private_->cached = false;
  93581. }
  93582. else {
  93583. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  93584. return false; /* read_callback_ sets the state for us */
  93585. }
  93586. if(x == FLAC__STREAM_SYNC_STRING[i]) {
  93587. first = true;
  93588. i++;
  93589. id_ = 0;
  93590. continue;
  93591. }
  93592. if(x == ID3V2_TAG_[id_]) {
  93593. id_++;
  93594. i = 0;
  93595. if(id_ == 3) {
  93596. if(!skip_id3v2_tag_(decoder))
  93597. return false; /* skip_id3v2_tag_ sets the state for us */
  93598. }
  93599. continue;
  93600. }
  93601. id_ = 0;
  93602. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  93603. decoder->private_->header_warmup[0] = (FLAC__byte)x;
  93604. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  93605. return false; /* read_callback_ sets the state for us */
  93606. /* 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 */
  93607. /* else we have to check if the second byte is the end of a sync code */
  93608. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  93609. decoder->private_->lookahead = (FLAC__byte)x;
  93610. decoder->private_->cached = true;
  93611. }
  93612. else if(x >> 2 == 0x3e) { /* MAGIC NUMBER for the last 6 sync bits */
  93613. decoder->private_->header_warmup[1] = (FLAC__byte)x;
  93614. decoder->protected_->state = FLAC__STREAM_DECODER_READ_FRAME;
  93615. return true;
  93616. }
  93617. }
  93618. i = 0;
  93619. if(first) {
  93620. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  93621. first = false;
  93622. }
  93623. }
  93624. decoder->protected_->state = FLAC__STREAM_DECODER_READ_METADATA;
  93625. return true;
  93626. }
  93627. FLAC__bool read_metadata_(FLAC__StreamDecoder *decoder)
  93628. {
  93629. FLAC__bool is_last;
  93630. FLAC__uint32 i, x, type, length;
  93631. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  93632. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_IS_LAST_LEN))
  93633. return false; /* read_callback_ sets the state for us */
  93634. is_last = x? true : false;
  93635. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &type, FLAC__STREAM_METADATA_TYPE_LEN))
  93636. return false; /* read_callback_ sets the state for us */
  93637. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &length, FLAC__STREAM_METADATA_LENGTH_LEN))
  93638. return false; /* read_callback_ sets the state for us */
  93639. if(type == FLAC__METADATA_TYPE_STREAMINFO) {
  93640. if(!read_metadata_streaminfo_(decoder, is_last, length))
  93641. return false;
  93642. decoder->private_->has_stream_info = true;
  93643. 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))
  93644. decoder->private_->do_md5_checking = false;
  93645. if(!decoder->private_->is_seeking && decoder->private_->metadata_filter[FLAC__METADATA_TYPE_STREAMINFO] && decoder->private_->metadata_callback)
  93646. decoder->private_->metadata_callback(decoder, &decoder->private_->stream_info, decoder->private_->client_data);
  93647. }
  93648. else if(type == FLAC__METADATA_TYPE_SEEKTABLE) {
  93649. if(!read_metadata_seektable_(decoder, is_last, length))
  93650. return false;
  93651. decoder->private_->has_seek_table = true;
  93652. if(!decoder->private_->is_seeking && decoder->private_->metadata_filter[FLAC__METADATA_TYPE_SEEKTABLE] && decoder->private_->metadata_callback)
  93653. decoder->private_->metadata_callback(decoder, &decoder->private_->seek_table, decoder->private_->client_data);
  93654. }
  93655. else {
  93656. FLAC__bool skip_it = !decoder->private_->metadata_filter[type];
  93657. unsigned real_length = length;
  93658. FLAC__StreamMetadata block;
  93659. block.is_last = is_last;
  93660. block.type = (FLAC__MetadataType)type;
  93661. block.length = length;
  93662. if(type == FLAC__METADATA_TYPE_APPLICATION) {
  93663. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.application.id, FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8))
  93664. return false; /* read_callback_ sets the state for us */
  93665. if(real_length < FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8) { /* underflow check */
  93666. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;/*@@@@@@ maybe wrong error? need to resync?*/
  93667. return false;
  93668. }
  93669. real_length -= FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8;
  93670. if(decoder->private_->metadata_filter_ids_count > 0 && has_id_filtered_(decoder, block.data.application.id))
  93671. skip_it = !skip_it;
  93672. }
  93673. if(skip_it) {
  93674. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, real_length))
  93675. return false; /* read_callback_ sets the state for us */
  93676. }
  93677. else {
  93678. switch(type) {
  93679. case FLAC__METADATA_TYPE_PADDING:
  93680. /* skip the padding bytes */
  93681. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, real_length))
  93682. return false; /* read_callback_ sets the state for us */
  93683. break;
  93684. case FLAC__METADATA_TYPE_APPLICATION:
  93685. /* remember, we read the ID already */
  93686. if(real_length > 0) {
  93687. if(0 == (block.data.application.data = (FLAC__byte*)malloc(real_length))) {
  93688. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  93689. return false;
  93690. }
  93691. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.application.data, real_length))
  93692. return false; /* read_callback_ sets the state for us */
  93693. }
  93694. else
  93695. block.data.application.data = 0;
  93696. break;
  93697. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  93698. if(!read_metadata_vorbiscomment_(decoder, &block.data.vorbis_comment))
  93699. return false;
  93700. break;
  93701. case FLAC__METADATA_TYPE_CUESHEET:
  93702. if(!read_metadata_cuesheet_(decoder, &block.data.cue_sheet))
  93703. return false;
  93704. break;
  93705. case FLAC__METADATA_TYPE_PICTURE:
  93706. if(!read_metadata_picture_(decoder, &block.data.picture))
  93707. return false;
  93708. break;
  93709. case FLAC__METADATA_TYPE_STREAMINFO:
  93710. case FLAC__METADATA_TYPE_SEEKTABLE:
  93711. FLAC__ASSERT(0);
  93712. break;
  93713. default:
  93714. if(real_length > 0) {
  93715. if(0 == (block.data.unknown.data = (FLAC__byte*)malloc(real_length))) {
  93716. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  93717. return false;
  93718. }
  93719. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.unknown.data, real_length))
  93720. return false; /* read_callback_ sets the state for us */
  93721. }
  93722. else
  93723. block.data.unknown.data = 0;
  93724. break;
  93725. }
  93726. if(!decoder->private_->is_seeking && decoder->private_->metadata_callback)
  93727. decoder->private_->metadata_callback(decoder, &block, decoder->private_->client_data);
  93728. /* now we have to free any malloc()ed data in the block */
  93729. switch(type) {
  93730. case FLAC__METADATA_TYPE_PADDING:
  93731. break;
  93732. case FLAC__METADATA_TYPE_APPLICATION:
  93733. if(0 != block.data.application.data)
  93734. free(block.data.application.data);
  93735. break;
  93736. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  93737. if(0 != block.data.vorbis_comment.vendor_string.entry)
  93738. free(block.data.vorbis_comment.vendor_string.entry);
  93739. if(block.data.vorbis_comment.num_comments > 0)
  93740. for(i = 0; i < block.data.vorbis_comment.num_comments; i++)
  93741. if(0 != block.data.vorbis_comment.comments[i].entry)
  93742. free(block.data.vorbis_comment.comments[i].entry);
  93743. if(0 != block.data.vorbis_comment.comments)
  93744. free(block.data.vorbis_comment.comments);
  93745. break;
  93746. case FLAC__METADATA_TYPE_CUESHEET:
  93747. if(block.data.cue_sheet.num_tracks > 0)
  93748. for(i = 0; i < block.data.cue_sheet.num_tracks; i++)
  93749. if(0 != block.data.cue_sheet.tracks[i].indices)
  93750. free(block.data.cue_sheet.tracks[i].indices);
  93751. if(0 != block.data.cue_sheet.tracks)
  93752. free(block.data.cue_sheet.tracks);
  93753. break;
  93754. case FLAC__METADATA_TYPE_PICTURE:
  93755. if(0 != block.data.picture.mime_type)
  93756. free(block.data.picture.mime_type);
  93757. if(0 != block.data.picture.description)
  93758. free(block.data.picture.description);
  93759. if(0 != block.data.picture.data)
  93760. free(block.data.picture.data);
  93761. break;
  93762. case FLAC__METADATA_TYPE_STREAMINFO:
  93763. case FLAC__METADATA_TYPE_SEEKTABLE:
  93764. FLAC__ASSERT(0);
  93765. default:
  93766. if(0 != block.data.unknown.data)
  93767. free(block.data.unknown.data);
  93768. break;
  93769. }
  93770. }
  93771. }
  93772. if(is_last) {
  93773. /* if this fails, it's OK, it's just a hint for the seek routine */
  93774. if(!FLAC__stream_decoder_get_decode_position(decoder, &decoder->private_->first_frame_offset))
  93775. decoder->private_->first_frame_offset = 0;
  93776. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  93777. }
  93778. return true;
  93779. }
  93780. FLAC__bool read_metadata_streaminfo_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length)
  93781. {
  93782. FLAC__uint32 x;
  93783. unsigned bits, used_bits = 0;
  93784. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  93785. decoder->private_->stream_info.type = FLAC__METADATA_TYPE_STREAMINFO;
  93786. decoder->private_->stream_info.is_last = is_last;
  93787. decoder->private_->stream_info.length = length;
  93788. bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN;
  93789. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, bits))
  93790. return false; /* read_callback_ sets the state for us */
  93791. decoder->private_->stream_info.data.stream_info.min_blocksize = x;
  93792. used_bits += bits;
  93793. bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN;
  93794. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN))
  93795. return false; /* read_callback_ sets the state for us */
  93796. decoder->private_->stream_info.data.stream_info.max_blocksize = x;
  93797. used_bits += bits;
  93798. bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN;
  93799. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN))
  93800. return false; /* read_callback_ sets the state for us */
  93801. decoder->private_->stream_info.data.stream_info.min_framesize = x;
  93802. used_bits += bits;
  93803. bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN;
  93804. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN))
  93805. return false; /* read_callback_ sets the state for us */
  93806. decoder->private_->stream_info.data.stream_info.max_framesize = x;
  93807. used_bits += bits;
  93808. bits = FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN;
  93809. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN))
  93810. return false; /* read_callback_ sets the state for us */
  93811. decoder->private_->stream_info.data.stream_info.sample_rate = x;
  93812. used_bits += bits;
  93813. bits = FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN;
  93814. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN))
  93815. return false; /* read_callback_ sets the state for us */
  93816. decoder->private_->stream_info.data.stream_info.channels = x+1;
  93817. used_bits += bits;
  93818. bits = FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN;
  93819. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN))
  93820. return false; /* read_callback_ sets the state for us */
  93821. decoder->private_->stream_info.data.stream_info.bits_per_sample = x+1;
  93822. used_bits += bits;
  93823. bits = FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN;
  93824. 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))
  93825. return false; /* read_callback_ sets the state for us */
  93826. used_bits += bits;
  93827. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, decoder->private_->stream_info.data.stream_info.md5sum, 16))
  93828. return false; /* read_callback_ sets the state for us */
  93829. used_bits += 16*8;
  93830. /* skip the rest of the block */
  93831. FLAC__ASSERT(used_bits % 8 == 0);
  93832. length -= (used_bits / 8);
  93833. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, length))
  93834. return false; /* read_callback_ sets the state for us */
  93835. return true;
  93836. }
  93837. FLAC__bool read_metadata_seektable_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length)
  93838. {
  93839. FLAC__uint32 i, x;
  93840. FLAC__uint64 xx;
  93841. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  93842. decoder->private_->seek_table.type = FLAC__METADATA_TYPE_SEEKTABLE;
  93843. decoder->private_->seek_table.is_last = is_last;
  93844. decoder->private_->seek_table.length = length;
  93845. decoder->private_->seek_table.data.seek_table.num_points = length / FLAC__STREAM_METADATA_SEEKPOINT_LENGTH;
  93846. /* use realloc since we may pass through here several times (e.g. after seeking) */
  93847. 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)))) {
  93848. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  93849. return false;
  93850. }
  93851. for(i = 0; i < decoder->private_->seek_table.data.seek_table.num_points; i++) {
  93852. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &xx, FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN))
  93853. return false; /* read_callback_ sets the state for us */
  93854. decoder->private_->seek_table.data.seek_table.points[i].sample_number = xx;
  93855. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &xx, FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN))
  93856. return false; /* read_callback_ sets the state for us */
  93857. decoder->private_->seek_table.data.seek_table.points[i].stream_offset = xx;
  93858. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN))
  93859. return false; /* read_callback_ sets the state for us */
  93860. decoder->private_->seek_table.data.seek_table.points[i].frame_samples = x;
  93861. }
  93862. length -= (decoder->private_->seek_table.data.seek_table.num_points * FLAC__STREAM_METADATA_SEEKPOINT_LENGTH);
  93863. /* if there is a partial point left, skip over it */
  93864. if(length > 0) {
  93865. /*@@@ do a send_error_to_client_() here? there's an argument for either way */
  93866. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, length))
  93867. return false; /* read_callback_ sets the state for us */
  93868. }
  93869. return true;
  93870. }
  93871. FLAC__bool read_metadata_vorbiscomment_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_VorbisComment *obj)
  93872. {
  93873. FLAC__uint32 i;
  93874. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  93875. /* read vendor string */
  93876. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32);
  93877. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->vendor_string.length))
  93878. return false; /* read_callback_ sets the state for us */
  93879. if(obj->vendor_string.length > 0) {
  93880. if(0 == (obj->vendor_string.entry = (FLAC__byte*)safe_malloc_add_2op_(obj->vendor_string.length, /*+*/1))) {
  93881. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  93882. return false;
  93883. }
  93884. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->vendor_string.entry, obj->vendor_string.length))
  93885. return false; /* read_callback_ sets the state for us */
  93886. obj->vendor_string.entry[obj->vendor_string.length] = '\0';
  93887. }
  93888. else
  93889. obj->vendor_string.entry = 0;
  93890. /* read num comments */
  93891. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN == 32);
  93892. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->num_comments))
  93893. return false; /* read_callback_ sets the state for us */
  93894. /* read comments */
  93895. if(obj->num_comments > 0) {
  93896. if(0 == (obj->comments = (FLAC__StreamMetadata_VorbisComment_Entry*)safe_malloc_mul_2op_(obj->num_comments, /*times*/sizeof(FLAC__StreamMetadata_VorbisComment_Entry)))) {
  93897. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  93898. return false;
  93899. }
  93900. for(i = 0; i < obj->num_comments; i++) {
  93901. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32);
  93902. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->comments[i].length))
  93903. return false; /* read_callback_ sets the state for us */
  93904. if(obj->comments[i].length > 0) {
  93905. if(0 == (obj->comments[i].entry = (FLAC__byte*)safe_malloc_add_2op_(obj->comments[i].length, /*+*/1))) {
  93906. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  93907. return false;
  93908. }
  93909. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->comments[i].entry, obj->comments[i].length))
  93910. return false; /* read_callback_ sets the state for us */
  93911. obj->comments[i].entry[obj->comments[i].length] = '\0';
  93912. }
  93913. else
  93914. obj->comments[i].entry = 0;
  93915. }
  93916. }
  93917. else {
  93918. obj->comments = 0;
  93919. }
  93920. return true;
  93921. }
  93922. FLAC__bool read_metadata_cuesheet_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_CueSheet *obj)
  93923. {
  93924. FLAC__uint32 i, j, x;
  93925. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  93926. memset(obj, 0, sizeof(FLAC__StreamMetadata_CueSheet));
  93927. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN % 8 == 0);
  93928. 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))
  93929. return false; /* read_callback_ sets the state for us */
  93930. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &obj->lead_in, FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN))
  93931. return false; /* read_callback_ sets the state for us */
  93932. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN))
  93933. return false; /* read_callback_ sets the state for us */
  93934. obj->is_cd = x? true : false;
  93935. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN))
  93936. return false; /* read_callback_ sets the state for us */
  93937. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN))
  93938. return false; /* read_callback_ sets the state for us */
  93939. obj->num_tracks = x;
  93940. if(obj->num_tracks > 0) {
  93941. if(0 == (obj->tracks = (FLAC__StreamMetadata_CueSheet_Track*)safe_calloc_(obj->num_tracks, sizeof(FLAC__StreamMetadata_CueSheet_Track)))) {
  93942. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  93943. return false;
  93944. }
  93945. for(i = 0; i < obj->num_tracks; i++) {
  93946. FLAC__StreamMetadata_CueSheet_Track *track = &obj->tracks[i];
  93947. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &track->offset, FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_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_NUMBER_LEN))
  93950. return false; /* read_callback_ sets the state for us */
  93951. track->number = (FLAC__byte)x;
  93952. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN % 8 == 0);
  93953. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)track->isrc, FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN/8))
  93954. return false; /* read_callback_ sets the state for us */
  93955. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN))
  93956. return false; /* read_callback_ sets the state for us */
  93957. track->type = x;
  93958. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN))
  93959. return false; /* read_callback_ sets the state for us */
  93960. track->pre_emphasis = x;
  93961. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN))
  93962. return false; /* read_callback_ sets the state for us */
  93963. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN))
  93964. return false; /* read_callback_ sets the state for us */
  93965. track->num_indices = (FLAC__byte)x;
  93966. if(track->num_indices > 0) {
  93967. if(0 == (track->indices = (FLAC__StreamMetadata_CueSheet_Index*)safe_calloc_(track->num_indices, sizeof(FLAC__StreamMetadata_CueSheet_Index)))) {
  93968. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  93969. return false;
  93970. }
  93971. for(j = 0; j < track->num_indices; j++) {
  93972. FLAC__StreamMetadata_CueSheet_Index *index = &track->indices[j];
  93973. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &index->offset, FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN))
  93974. return false; /* read_callback_ sets the state for us */
  93975. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN))
  93976. return false; /* read_callback_ sets the state for us */
  93977. index->number = (FLAC__byte)x;
  93978. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN))
  93979. return false; /* read_callback_ sets the state for us */
  93980. }
  93981. }
  93982. }
  93983. }
  93984. return true;
  93985. }
  93986. FLAC__bool read_metadata_picture_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_Picture *obj)
  93987. {
  93988. FLAC__uint32 x;
  93989. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  93990. /* read type */
  93991. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_TYPE_LEN))
  93992. return false; /* read_callback_ sets the state for us */
  93993. obj->type = (FLAC__StreamMetadata_Picture_Type) x;
  93994. /* read MIME type */
  93995. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN))
  93996. return false; /* read_callback_ sets the state for us */
  93997. if(0 == (obj->mime_type = (char*)safe_malloc_add_2op_(x, /*+*/1))) {
  93998. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  93999. return false;
  94000. }
  94001. if(x > 0) {
  94002. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)obj->mime_type, x))
  94003. return false; /* read_callback_ sets the state for us */
  94004. }
  94005. obj->mime_type[x] = '\0';
  94006. /* read description */
  94007. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN))
  94008. return false; /* read_callback_ sets the state for us */
  94009. if(0 == (obj->description = (FLAC__byte*)safe_malloc_add_2op_(x, /*+*/1))) {
  94010. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  94011. return false;
  94012. }
  94013. if(x > 0) {
  94014. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->description, x))
  94015. return false; /* read_callback_ sets the state for us */
  94016. }
  94017. obj->description[x] = '\0';
  94018. /* read width */
  94019. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->width, FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN))
  94020. return false; /* read_callback_ sets the state for us */
  94021. /* read height */
  94022. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->height, FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN))
  94023. return false; /* read_callback_ sets the state for us */
  94024. /* read depth */
  94025. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->depth, FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN))
  94026. return false; /* read_callback_ sets the state for us */
  94027. /* read colors */
  94028. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->colors, FLAC__STREAM_METADATA_PICTURE_COLORS_LEN))
  94029. return false; /* read_callback_ sets the state for us */
  94030. /* read data */
  94031. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &(obj->data_length), FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN))
  94032. return false; /* read_callback_ sets the state for us */
  94033. if(0 == (obj->data = (FLAC__byte*)safe_malloc_(obj->data_length))) {
  94034. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  94035. return false;
  94036. }
  94037. if(obj->data_length > 0) {
  94038. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->data, obj->data_length))
  94039. return false; /* read_callback_ sets the state for us */
  94040. }
  94041. return true;
  94042. }
  94043. FLAC__bool skip_id3v2_tag_(FLAC__StreamDecoder *decoder)
  94044. {
  94045. FLAC__uint32 x;
  94046. unsigned i, skip;
  94047. /* skip the version and flags bytes */
  94048. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 24))
  94049. return false; /* read_callback_ sets the state for us */
  94050. /* get the size (in bytes) to skip */
  94051. skip = 0;
  94052. for(i = 0; i < 4; i++) {
  94053. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  94054. return false; /* read_callback_ sets the state for us */
  94055. skip <<= 7;
  94056. skip |= (x & 0x7f);
  94057. }
  94058. /* skip the rest of the tag */
  94059. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, skip))
  94060. return false; /* read_callback_ sets the state for us */
  94061. return true;
  94062. }
  94063. FLAC__bool frame_sync_(FLAC__StreamDecoder *decoder)
  94064. {
  94065. FLAC__uint32 x;
  94066. FLAC__bool first = true;
  94067. /* If we know the total number of samples in the stream, stop if we've read that many. */
  94068. /* This will stop us, for example, from wasting time trying to sync on an ID3V1 tag. */
  94069. if(FLAC__stream_decoder_get_total_samples(decoder) > 0) {
  94070. if(decoder->private_->samples_decoded >= FLAC__stream_decoder_get_total_samples(decoder)) {
  94071. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  94072. return true;
  94073. }
  94074. }
  94075. /* make sure we're byte aligned */
  94076. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input)) {
  94077. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__bitreader_bits_left_for_byte_alignment(decoder->private_->input)))
  94078. return false; /* read_callback_ sets the state for us */
  94079. }
  94080. while(1) {
  94081. if(decoder->private_->cached) {
  94082. x = (FLAC__uint32)decoder->private_->lookahead;
  94083. decoder->private_->cached = false;
  94084. }
  94085. else {
  94086. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  94087. return false; /* read_callback_ sets the state for us */
  94088. }
  94089. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  94090. decoder->private_->header_warmup[0] = (FLAC__byte)x;
  94091. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  94092. return false; /* read_callback_ sets the state for us */
  94093. /* 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 */
  94094. /* else we have to check if the second byte is the end of a sync code */
  94095. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  94096. decoder->private_->lookahead = (FLAC__byte)x;
  94097. decoder->private_->cached = true;
  94098. }
  94099. else if(x >> 2 == 0x3e) { /* MAGIC NUMBER for the last 6 sync bits */
  94100. decoder->private_->header_warmup[1] = (FLAC__byte)x;
  94101. decoder->protected_->state = FLAC__STREAM_DECODER_READ_FRAME;
  94102. return true;
  94103. }
  94104. }
  94105. if(first) {
  94106. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  94107. first = false;
  94108. }
  94109. }
  94110. return true;
  94111. }
  94112. FLAC__bool read_frame_(FLAC__StreamDecoder *decoder, FLAC__bool *got_a_frame, FLAC__bool do_full_decode)
  94113. {
  94114. unsigned channel;
  94115. unsigned i;
  94116. FLAC__int32 mid, side;
  94117. unsigned frame_crc; /* the one we calculate from the input stream */
  94118. FLAC__uint32 x;
  94119. *got_a_frame = false;
  94120. /* init the CRC */
  94121. frame_crc = 0;
  94122. frame_crc = FLAC__CRC16_UPDATE(decoder->private_->header_warmup[0], frame_crc);
  94123. frame_crc = FLAC__CRC16_UPDATE(decoder->private_->header_warmup[1], frame_crc);
  94124. FLAC__bitreader_reset_read_crc16(decoder->private_->input, (FLAC__uint16)frame_crc);
  94125. if(!read_frame_header_(decoder))
  94126. return false;
  94127. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means we didn't sync on a valid header */
  94128. return true;
  94129. if(!allocate_output_(decoder, decoder->private_->frame.header.blocksize, decoder->private_->frame.header.channels))
  94130. return false;
  94131. for(channel = 0; channel < decoder->private_->frame.header.channels; channel++) {
  94132. /*
  94133. * first figure the correct bits-per-sample of the subframe
  94134. */
  94135. unsigned bps = decoder->private_->frame.header.bits_per_sample;
  94136. switch(decoder->private_->frame.header.channel_assignment) {
  94137. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  94138. /* no adjustment needed */
  94139. break;
  94140. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  94141. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  94142. if(channel == 1)
  94143. bps++;
  94144. break;
  94145. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  94146. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  94147. if(channel == 0)
  94148. bps++;
  94149. break;
  94150. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  94151. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  94152. if(channel == 1)
  94153. bps++;
  94154. break;
  94155. default:
  94156. FLAC__ASSERT(0);
  94157. }
  94158. /*
  94159. * now read it
  94160. */
  94161. if(!read_subframe_(decoder, channel, bps, do_full_decode))
  94162. return false;
  94163. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  94164. return true;
  94165. }
  94166. if(!read_zero_padding_(decoder))
  94167. return false;
  94168. 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) */
  94169. return true;
  94170. /*
  94171. * Read the frame CRC-16 from the footer and check
  94172. */
  94173. frame_crc = FLAC__bitreader_get_read_crc16(decoder->private_->input);
  94174. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__FRAME_FOOTER_CRC_LEN))
  94175. return false; /* read_callback_ sets the state for us */
  94176. if(frame_crc == x) {
  94177. if(do_full_decode) {
  94178. /* Undo any special channel coding */
  94179. switch(decoder->private_->frame.header.channel_assignment) {
  94180. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  94181. /* do nothing */
  94182. break;
  94183. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  94184. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  94185. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  94186. decoder->private_->output[1][i] = decoder->private_->output[0][i] - decoder->private_->output[1][i];
  94187. break;
  94188. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  94189. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  94190. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  94191. decoder->private_->output[0][i] += decoder->private_->output[1][i];
  94192. break;
  94193. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  94194. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  94195. for(i = 0; i < decoder->private_->frame.header.blocksize; i++) {
  94196. #if 1
  94197. mid = decoder->private_->output[0][i];
  94198. side = decoder->private_->output[1][i];
  94199. mid <<= 1;
  94200. mid |= (side & 1); /* i.e. if 'side' is odd... */
  94201. decoder->private_->output[0][i] = (mid + side) >> 1;
  94202. decoder->private_->output[1][i] = (mid - side) >> 1;
  94203. #else
  94204. /* OPT: without 'side' temp variable */
  94205. mid = (decoder->private_->output[0][i] << 1) | (decoder->private_->output[1][i] & 1); /* i.e. if 'side' is odd... */
  94206. decoder->private_->output[0][i] = (mid + decoder->private_->output[1][i]) >> 1;
  94207. decoder->private_->output[1][i] = (mid - decoder->private_->output[1][i]) >> 1;
  94208. #endif
  94209. }
  94210. break;
  94211. default:
  94212. FLAC__ASSERT(0);
  94213. break;
  94214. }
  94215. }
  94216. }
  94217. else {
  94218. /* Bad frame, emit error and zero the output signal */
  94219. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH);
  94220. if(do_full_decode) {
  94221. for(channel = 0; channel < decoder->private_->frame.header.channels; channel++) {
  94222. memset(decoder->private_->output[channel], 0, sizeof(FLAC__int32) * decoder->private_->frame.header.blocksize);
  94223. }
  94224. }
  94225. }
  94226. *got_a_frame = true;
  94227. /* we wait to update fixed_block_size until here, when we're sure we've got a proper frame and hence a correct blocksize */
  94228. if(decoder->private_->next_fixed_block_size)
  94229. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size;
  94230. /* put the latest values into the public section of the decoder instance */
  94231. decoder->protected_->channels = decoder->private_->frame.header.channels;
  94232. decoder->protected_->channel_assignment = decoder->private_->frame.header.channel_assignment;
  94233. decoder->protected_->bits_per_sample = decoder->private_->frame.header.bits_per_sample;
  94234. decoder->protected_->sample_rate = decoder->private_->frame.header.sample_rate;
  94235. decoder->protected_->blocksize = decoder->private_->frame.header.blocksize;
  94236. FLAC__ASSERT(decoder->private_->frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  94237. decoder->private_->samples_decoded = decoder->private_->frame.header.number.sample_number + decoder->private_->frame.header.blocksize;
  94238. /* write it */
  94239. if(do_full_decode) {
  94240. if(write_audio_frame_to_client_(decoder, &decoder->private_->frame, (const FLAC__int32 * const *)decoder->private_->output) != FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE)
  94241. return false;
  94242. }
  94243. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  94244. return true;
  94245. }
  94246. FLAC__bool read_frame_header_(FLAC__StreamDecoder *decoder)
  94247. {
  94248. FLAC__uint32 x;
  94249. FLAC__uint64 xx;
  94250. unsigned i, blocksize_hint = 0, sample_rate_hint = 0;
  94251. FLAC__byte crc8, raw_header[16]; /* MAGIC NUMBER based on the maximum frame header size, including CRC */
  94252. unsigned raw_header_len;
  94253. FLAC__bool is_unparseable = false;
  94254. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  94255. /* init the raw header with the saved bits from synchronization */
  94256. raw_header[0] = decoder->private_->header_warmup[0];
  94257. raw_header[1] = decoder->private_->header_warmup[1];
  94258. raw_header_len = 2;
  94259. /* check to make sure that reserved bit is 0 */
  94260. if(raw_header[1] & 0x02) /* MAGIC NUMBER */
  94261. is_unparseable = true;
  94262. /*
  94263. * Note that along the way as we read the header, we look for a sync
  94264. * code inside. If we find one it would indicate that our original
  94265. * sync was bad since there cannot be a sync code in a valid header.
  94266. *
  94267. * Three kinds of things can go wrong when reading the frame header:
  94268. * 1) We may have sync'ed incorrectly and not landed on a frame header.
  94269. * If we don't find a sync code, it can end up looking like we read
  94270. * a valid but unparseable header, until getting to the frame header
  94271. * CRC. Even then we could get a false positive on the CRC.
  94272. * 2) We may have sync'ed correctly but on an unparseable frame (from a
  94273. * future encoder).
  94274. * 3) We may be on a damaged frame which appears valid but unparseable.
  94275. *
  94276. * For all these reasons, we try and read a complete frame header as
  94277. * long as it seems valid, even if unparseable, up until the frame
  94278. * header CRC.
  94279. */
  94280. /*
  94281. * read in the raw header as bytes so we can CRC it, and parse it on the way
  94282. */
  94283. for(i = 0; i < 2; i++) {
  94284. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  94285. return false; /* read_callback_ sets the state for us */
  94286. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  94287. /* if we get here it means our original sync was erroneous since the sync code cannot appear in the header */
  94288. decoder->private_->lookahead = (FLAC__byte)x;
  94289. decoder->private_->cached = true;
  94290. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  94291. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  94292. return true;
  94293. }
  94294. raw_header[raw_header_len++] = (FLAC__byte)x;
  94295. }
  94296. switch(x = raw_header[2] >> 4) {
  94297. case 0:
  94298. is_unparseable = true;
  94299. break;
  94300. case 1:
  94301. decoder->private_->frame.header.blocksize = 192;
  94302. break;
  94303. case 2:
  94304. case 3:
  94305. case 4:
  94306. case 5:
  94307. decoder->private_->frame.header.blocksize = 576 << (x-2);
  94308. break;
  94309. case 6:
  94310. case 7:
  94311. blocksize_hint = x;
  94312. break;
  94313. case 8:
  94314. case 9:
  94315. case 10:
  94316. case 11:
  94317. case 12:
  94318. case 13:
  94319. case 14:
  94320. case 15:
  94321. decoder->private_->frame.header.blocksize = 256 << (x-8);
  94322. break;
  94323. default:
  94324. FLAC__ASSERT(0);
  94325. break;
  94326. }
  94327. switch(x = raw_header[2] & 0x0f) {
  94328. case 0:
  94329. if(decoder->private_->has_stream_info)
  94330. decoder->private_->frame.header.sample_rate = decoder->private_->stream_info.data.stream_info.sample_rate;
  94331. else
  94332. is_unparseable = true;
  94333. break;
  94334. case 1:
  94335. decoder->private_->frame.header.sample_rate = 88200;
  94336. break;
  94337. case 2:
  94338. decoder->private_->frame.header.sample_rate = 176400;
  94339. break;
  94340. case 3:
  94341. decoder->private_->frame.header.sample_rate = 192000;
  94342. break;
  94343. case 4:
  94344. decoder->private_->frame.header.sample_rate = 8000;
  94345. break;
  94346. case 5:
  94347. decoder->private_->frame.header.sample_rate = 16000;
  94348. break;
  94349. case 6:
  94350. decoder->private_->frame.header.sample_rate = 22050;
  94351. break;
  94352. case 7:
  94353. decoder->private_->frame.header.sample_rate = 24000;
  94354. break;
  94355. case 8:
  94356. decoder->private_->frame.header.sample_rate = 32000;
  94357. break;
  94358. case 9:
  94359. decoder->private_->frame.header.sample_rate = 44100;
  94360. break;
  94361. case 10:
  94362. decoder->private_->frame.header.sample_rate = 48000;
  94363. break;
  94364. case 11:
  94365. decoder->private_->frame.header.sample_rate = 96000;
  94366. break;
  94367. case 12:
  94368. case 13:
  94369. case 14:
  94370. sample_rate_hint = x;
  94371. break;
  94372. case 15:
  94373. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  94374. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  94375. return true;
  94376. default:
  94377. FLAC__ASSERT(0);
  94378. }
  94379. x = (unsigned)(raw_header[3] >> 4);
  94380. if(x & 8) {
  94381. decoder->private_->frame.header.channels = 2;
  94382. switch(x & 7) {
  94383. case 0:
  94384. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE;
  94385. break;
  94386. case 1:
  94387. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE;
  94388. break;
  94389. case 2:
  94390. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_MID_SIDE;
  94391. break;
  94392. default:
  94393. is_unparseable = true;
  94394. break;
  94395. }
  94396. }
  94397. else {
  94398. decoder->private_->frame.header.channels = (unsigned)x + 1;
  94399. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
  94400. }
  94401. switch(x = (unsigned)(raw_header[3] & 0x0e) >> 1) {
  94402. case 0:
  94403. if(decoder->private_->has_stream_info)
  94404. decoder->private_->frame.header.bits_per_sample = decoder->private_->stream_info.data.stream_info.bits_per_sample;
  94405. else
  94406. is_unparseable = true;
  94407. break;
  94408. case 1:
  94409. decoder->private_->frame.header.bits_per_sample = 8;
  94410. break;
  94411. case 2:
  94412. decoder->private_->frame.header.bits_per_sample = 12;
  94413. break;
  94414. case 4:
  94415. decoder->private_->frame.header.bits_per_sample = 16;
  94416. break;
  94417. case 5:
  94418. decoder->private_->frame.header.bits_per_sample = 20;
  94419. break;
  94420. case 6:
  94421. decoder->private_->frame.header.bits_per_sample = 24;
  94422. break;
  94423. case 3:
  94424. case 7:
  94425. is_unparseable = true;
  94426. break;
  94427. default:
  94428. FLAC__ASSERT(0);
  94429. break;
  94430. }
  94431. /* check to make sure that reserved bit is 0 */
  94432. if(raw_header[3] & 0x01) /* MAGIC NUMBER */
  94433. is_unparseable = true;
  94434. /* read the frame's starting sample number (or frame number as the case may be) */
  94435. if(
  94436. raw_header[1] & 0x01 ||
  94437. /*@@@ 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 */
  94438. (decoder->private_->has_stream_info && decoder->private_->stream_info.data.stream_info.min_blocksize != decoder->private_->stream_info.data.stream_info.max_blocksize)
  94439. ) { /* variable blocksize */
  94440. if(!FLAC__bitreader_read_utf8_uint64(decoder->private_->input, &xx, raw_header, &raw_header_len))
  94441. return false; /* read_callback_ sets the state for us */
  94442. if(xx == FLAC__U64L(0xffffffffffffffff)) { /* i.e. non-UTF8 code... */
  94443. decoder->private_->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */
  94444. decoder->private_->cached = true;
  94445. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  94446. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  94447. return true;
  94448. }
  94449. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER;
  94450. decoder->private_->frame.header.number.sample_number = xx;
  94451. }
  94452. else { /* fixed blocksize */
  94453. if(!FLAC__bitreader_read_utf8_uint32(decoder->private_->input, &x, raw_header, &raw_header_len))
  94454. return false; /* read_callback_ sets the state for us */
  94455. if(x == 0xffffffff) { /* i.e. non-UTF8 code... */
  94456. decoder->private_->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */
  94457. decoder->private_->cached = true;
  94458. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  94459. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  94460. return true;
  94461. }
  94462. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER;
  94463. decoder->private_->frame.header.number.frame_number = x;
  94464. }
  94465. if(blocksize_hint) {
  94466. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  94467. return false; /* read_callback_ sets the state for us */
  94468. raw_header[raw_header_len++] = (FLAC__byte)x;
  94469. if(blocksize_hint == 7) {
  94470. FLAC__uint32 _x;
  94471. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &_x, 8))
  94472. return false; /* read_callback_ sets the state for us */
  94473. raw_header[raw_header_len++] = (FLAC__byte)_x;
  94474. x = (x << 8) | _x;
  94475. }
  94476. decoder->private_->frame.header.blocksize = x+1;
  94477. }
  94478. if(sample_rate_hint) {
  94479. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  94480. return false; /* read_callback_ sets the state for us */
  94481. raw_header[raw_header_len++] = (FLAC__byte)x;
  94482. if(sample_rate_hint != 12) {
  94483. FLAC__uint32 _x;
  94484. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &_x, 8))
  94485. return false; /* read_callback_ sets the state for us */
  94486. raw_header[raw_header_len++] = (FLAC__byte)_x;
  94487. x = (x << 8) | _x;
  94488. }
  94489. if(sample_rate_hint == 12)
  94490. decoder->private_->frame.header.sample_rate = x*1000;
  94491. else if(sample_rate_hint == 13)
  94492. decoder->private_->frame.header.sample_rate = x;
  94493. else
  94494. decoder->private_->frame.header.sample_rate = x*10;
  94495. }
  94496. /* read the CRC-8 byte */
  94497. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  94498. return false; /* read_callback_ sets the state for us */
  94499. crc8 = (FLAC__byte)x;
  94500. if(FLAC__crc8(raw_header, raw_header_len) != crc8) {
  94501. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  94502. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  94503. return true;
  94504. }
  94505. /* calculate the sample number from the frame number if needed */
  94506. decoder->private_->next_fixed_block_size = 0;
  94507. if(decoder->private_->frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER) {
  94508. x = decoder->private_->frame.header.number.frame_number;
  94509. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER;
  94510. if(decoder->private_->fixed_block_size)
  94511. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->fixed_block_size * (FLAC__uint64)x;
  94512. else if(decoder->private_->has_stream_info) {
  94513. if(decoder->private_->stream_info.data.stream_info.min_blocksize == decoder->private_->stream_info.data.stream_info.max_blocksize) {
  94514. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->stream_info.data.stream_info.min_blocksize * (FLAC__uint64)x;
  94515. decoder->private_->next_fixed_block_size = decoder->private_->stream_info.data.stream_info.max_blocksize;
  94516. }
  94517. else
  94518. is_unparseable = true;
  94519. }
  94520. else if(x == 0) {
  94521. decoder->private_->frame.header.number.sample_number = 0;
  94522. decoder->private_->next_fixed_block_size = decoder->private_->frame.header.blocksize;
  94523. }
  94524. else {
  94525. /* can only get here if the stream has invalid frame numbering and no STREAMINFO, so assume it's not the last (possibly short) frame */
  94526. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->frame.header.blocksize * (FLAC__uint64)x;
  94527. }
  94528. }
  94529. if(is_unparseable) {
  94530. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  94531. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  94532. return true;
  94533. }
  94534. return true;
  94535. }
  94536. FLAC__bool read_subframe_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  94537. {
  94538. FLAC__uint32 x;
  94539. FLAC__bool wasted_bits;
  94540. unsigned i;
  94541. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8)) /* MAGIC NUMBER */
  94542. return false; /* read_callback_ sets the state for us */
  94543. wasted_bits = (x & 1);
  94544. x &= 0xfe;
  94545. if(wasted_bits) {
  94546. unsigned u;
  94547. if(!FLAC__bitreader_read_unary_unsigned(decoder->private_->input, &u))
  94548. return false; /* read_callback_ sets the state for us */
  94549. decoder->private_->frame.subframes[channel].wasted_bits = u+1;
  94550. bps -= decoder->private_->frame.subframes[channel].wasted_bits;
  94551. }
  94552. else
  94553. decoder->private_->frame.subframes[channel].wasted_bits = 0;
  94554. /*
  94555. * Lots of magic numbers here
  94556. */
  94557. if(x & 0x80) {
  94558. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  94559. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  94560. return true;
  94561. }
  94562. else if(x == 0) {
  94563. if(!read_subframe_constant_(decoder, channel, bps, do_full_decode))
  94564. return false;
  94565. }
  94566. else if(x == 2) {
  94567. if(!read_subframe_verbatim_(decoder, channel, bps, do_full_decode))
  94568. return false;
  94569. }
  94570. else if(x < 16) {
  94571. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  94572. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  94573. return true;
  94574. }
  94575. else if(x <= 24) {
  94576. if(!read_subframe_fixed_(decoder, channel, bps, (x>>1)&7, do_full_decode))
  94577. return false;
  94578. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  94579. return true;
  94580. }
  94581. else if(x < 64) {
  94582. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  94583. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  94584. return true;
  94585. }
  94586. else {
  94587. if(!read_subframe_lpc_(decoder, channel, bps, ((x>>1)&31)+1, do_full_decode))
  94588. return false;
  94589. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  94590. return true;
  94591. }
  94592. if(wasted_bits && do_full_decode) {
  94593. x = decoder->private_->frame.subframes[channel].wasted_bits;
  94594. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  94595. decoder->private_->output[channel][i] <<= x;
  94596. }
  94597. return true;
  94598. }
  94599. FLAC__bool read_subframe_constant_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  94600. {
  94601. FLAC__Subframe_Constant *subframe = &decoder->private_->frame.subframes[channel].data.constant;
  94602. FLAC__int32 x;
  94603. unsigned i;
  94604. FLAC__int32 *output = decoder->private_->output[channel];
  94605. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_CONSTANT;
  94606. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &x, bps))
  94607. return false; /* read_callback_ sets the state for us */
  94608. subframe->value = x;
  94609. /* decode the subframe */
  94610. if(do_full_decode) {
  94611. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  94612. output[i] = x;
  94613. }
  94614. return true;
  94615. }
  94616. FLAC__bool read_subframe_fixed_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode)
  94617. {
  94618. FLAC__Subframe_Fixed *subframe = &decoder->private_->frame.subframes[channel].data.fixed;
  94619. FLAC__int32 i32;
  94620. FLAC__uint32 u32;
  94621. unsigned u;
  94622. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_FIXED;
  94623. subframe->residual = decoder->private_->residual[channel];
  94624. subframe->order = order;
  94625. /* read warm-up samples */
  94626. for(u = 0; u < order; u++) {
  94627. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, bps))
  94628. return false; /* read_callback_ sets the state for us */
  94629. subframe->warmup[u] = i32;
  94630. }
  94631. /* read entropy coding method info */
  94632. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  94633. return false; /* read_callback_ sets the state for us */
  94634. subframe->entropy_coding_method.type = (FLAC__EntropyCodingMethodType)u32;
  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(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  94639. return false; /* read_callback_ sets the state for us */
  94640. subframe->entropy_coding_method.data.partitioned_rice.order = u32;
  94641. subframe->entropy_coding_method.data.partitioned_rice.contents = &decoder->private_->partitioned_rice_contents[channel];
  94642. break;
  94643. default:
  94644. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  94645. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  94646. return true;
  94647. }
  94648. /* read residual */
  94649. switch(subframe->entropy_coding_method.type) {
  94650. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  94651. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  94652. 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))
  94653. return false;
  94654. break;
  94655. default:
  94656. FLAC__ASSERT(0);
  94657. }
  94658. /* decode the subframe */
  94659. if(do_full_decode) {
  94660. memcpy(decoder->private_->output[channel], subframe->warmup, sizeof(FLAC__int32) * order);
  94661. FLAC__fixed_restore_signal(decoder->private_->residual[channel], decoder->private_->frame.header.blocksize-order, order, decoder->private_->output[channel]+order);
  94662. }
  94663. return true;
  94664. }
  94665. FLAC__bool read_subframe_lpc_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode)
  94666. {
  94667. FLAC__Subframe_LPC *subframe = &decoder->private_->frame.subframes[channel].data.lpc;
  94668. FLAC__int32 i32;
  94669. FLAC__uint32 u32;
  94670. unsigned u;
  94671. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_LPC;
  94672. subframe->residual = decoder->private_->residual[channel];
  94673. subframe->order = order;
  94674. /* read warm-up samples */
  94675. for(u = 0; u < order; u++) {
  94676. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, bps))
  94677. return false; /* read_callback_ sets the state for us */
  94678. subframe->warmup[u] = i32;
  94679. }
  94680. /* read qlp coeff precision */
  94681. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN))
  94682. return false; /* read_callback_ sets the state for us */
  94683. if(u32 == (1u << FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN) - 1) {
  94684. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  94685. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  94686. return true;
  94687. }
  94688. subframe->qlp_coeff_precision = u32+1;
  94689. /* read qlp shift */
  94690. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN))
  94691. return false; /* read_callback_ sets the state for us */
  94692. subframe->quantization_level = i32;
  94693. /* read quantized lp coefficiencts */
  94694. for(u = 0; u < order; u++) {
  94695. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, subframe->qlp_coeff_precision))
  94696. return false; /* read_callback_ sets the state for us */
  94697. subframe->qlp_coeff[u] = i32;
  94698. }
  94699. /* read entropy coding method info */
  94700. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  94701. return false; /* read_callback_ sets the state for us */
  94702. subframe->entropy_coding_method.type = (FLAC__EntropyCodingMethodType)u32;
  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(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  94707. return false; /* read_callback_ sets the state for us */
  94708. subframe->entropy_coding_method.data.partitioned_rice.order = u32;
  94709. subframe->entropy_coding_method.data.partitioned_rice.contents = &decoder->private_->partitioned_rice_contents[channel];
  94710. break;
  94711. default:
  94712. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  94713. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  94714. return true;
  94715. }
  94716. /* read residual */
  94717. switch(subframe->entropy_coding_method.type) {
  94718. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  94719. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  94720. 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))
  94721. return false;
  94722. break;
  94723. default:
  94724. FLAC__ASSERT(0);
  94725. }
  94726. /* decode the subframe */
  94727. if(do_full_decode) {
  94728. memcpy(decoder->private_->output[channel], subframe->warmup, sizeof(FLAC__int32) * order);
  94729. /*@@@@@@ technically not pessimistic enough, should be more like
  94730. if( (FLAC__uint64)order * ((((FLAC__uint64)1)<<bps)-1) * ((1<<subframe->qlp_coeff_precision)-1) < (((FLAC__uint64)-1) << 32) )
  94731. */
  94732. if(bps + subframe->qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
  94733. if(bps <= 16 && subframe->qlp_coeff_precision <= 16) {
  94734. if(order <= 8)
  94735. 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);
  94736. else
  94737. 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);
  94738. }
  94739. else
  94740. 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);
  94741. else
  94742. 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);
  94743. }
  94744. return true;
  94745. }
  94746. FLAC__bool read_subframe_verbatim_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  94747. {
  94748. FLAC__Subframe_Verbatim *subframe = &decoder->private_->frame.subframes[channel].data.verbatim;
  94749. FLAC__int32 x, *residual = decoder->private_->residual[channel];
  94750. unsigned i;
  94751. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_VERBATIM;
  94752. subframe->data = residual;
  94753. for(i = 0; i < decoder->private_->frame.header.blocksize; i++) {
  94754. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &x, bps))
  94755. return false; /* read_callback_ sets the state for us */
  94756. residual[i] = x;
  94757. }
  94758. /* decode the subframe */
  94759. if(do_full_decode)
  94760. memcpy(decoder->private_->output[channel], subframe->data, sizeof(FLAC__int32) * decoder->private_->frame.header.blocksize);
  94761. return true;
  94762. }
  94763. 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)
  94764. {
  94765. FLAC__uint32 rice_parameter;
  94766. int i;
  94767. unsigned partition, sample, u;
  94768. const unsigned partitions = 1u << partition_order;
  94769. const unsigned partition_samples = partition_order > 0? decoder->private_->frame.header.blocksize >> partition_order : decoder->private_->frame.header.blocksize - predictor_order;
  94770. const unsigned plen = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
  94771. const unsigned pesc = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  94772. /* sanity checks */
  94773. if(partition_order == 0) {
  94774. if(decoder->private_->frame.header.blocksize < predictor_order) {
  94775. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  94776. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  94777. return true;
  94778. }
  94779. }
  94780. else {
  94781. if(partition_samples < predictor_order) {
  94782. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  94783. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  94784. return true;
  94785. }
  94786. }
  94787. if(!FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order))) {
  94788. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  94789. return false;
  94790. }
  94791. sample = 0;
  94792. for(partition = 0; partition < partitions; partition++) {
  94793. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &rice_parameter, plen))
  94794. return false; /* read_callback_ sets the state for us */
  94795. partitioned_rice_contents->parameters[partition] = rice_parameter;
  94796. if(rice_parameter < pesc) {
  94797. partitioned_rice_contents->raw_bits[partition] = 0;
  94798. u = (partition_order == 0 || partition > 0)? partition_samples : partition_samples - predictor_order;
  94799. if(!decoder->private_->local_bitreader_read_rice_signed_block(decoder->private_->input, (int*) residual + sample, u, rice_parameter))
  94800. return false; /* read_callback_ sets the state for us */
  94801. sample += u;
  94802. }
  94803. else {
  94804. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  94805. return false; /* read_callback_ sets the state for us */
  94806. partitioned_rice_contents->raw_bits[partition] = rice_parameter;
  94807. for(u = (partition_order == 0 || partition > 0)? 0 : predictor_order; u < partition_samples; u++, sample++) {
  94808. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, (FLAC__int32*) &i, rice_parameter))
  94809. return false; /* read_callback_ sets the state for us */
  94810. residual[sample] = i;
  94811. }
  94812. }
  94813. }
  94814. return true;
  94815. }
  94816. FLAC__bool read_zero_padding_(FLAC__StreamDecoder *decoder)
  94817. {
  94818. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input)) {
  94819. FLAC__uint32 zero = 0;
  94820. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &zero, FLAC__bitreader_bits_left_for_byte_alignment(decoder->private_->input)))
  94821. return false; /* read_callback_ sets the state for us */
  94822. if(zero != 0) {
  94823. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  94824. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  94825. }
  94826. }
  94827. return true;
  94828. }
  94829. FLAC__bool read_callback_(FLAC__byte buffer[], size_t *bytes, void *client_data)
  94830. {
  94831. FLAC__StreamDecoder *decoder = (FLAC__StreamDecoder *)client_data;
  94832. if(
  94833. #if FLAC__HAS_OGG
  94834. /* see [1] HACK NOTE below for why we don't call the eof_callback when decoding Ogg FLAC */
  94835. !decoder->private_->is_ogg &&
  94836. #endif
  94837. decoder->private_->eof_callback && decoder->private_->eof_callback(decoder, decoder->private_->client_data)
  94838. ) {
  94839. *bytes = 0;
  94840. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  94841. return false;
  94842. }
  94843. else if(*bytes > 0) {
  94844. /* While seeking, it is possible for our seek to land in the
  94845. * middle of audio data that looks exactly like a frame header
  94846. * from a future version of an encoder. When that happens, our
  94847. * error callback will get an
  94848. * FLAC__STREAM_DECODER_UNPARSEABLE_STREAM and increment its
  94849. * unparseable_frame_count. But there is a remote possibility
  94850. * that it is properly synced at such a "future-codec frame",
  94851. * so to make sure, we wait to see many "unparseable" errors in
  94852. * a row before bailing out.
  94853. */
  94854. if(decoder->private_->is_seeking && decoder->private_->unparseable_frame_count > 20) {
  94855. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  94856. return false;
  94857. }
  94858. else {
  94859. const FLAC__StreamDecoderReadStatus status =
  94860. #if FLAC__HAS_OGG
  94861. decoder->private_->is_ogg?
  94862. read_callback_ogg_aspect_(decoder, buffer, bytes) :
  94863. #endif
  94864. decoder->private_->read_callback(decoder, buffer, bytes, decoder->private_->client_data)
  94865. ;
  94866. if(status == FLAC__STREAM_DECODER_READ_STATUS_ABORT) {
  94867. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  94868. return false;
  94869. }
  94870. else if(*bytes == 0) {
  94871. if(
  94872. status == FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM ||
  94873. (
  94874. #if FLAC__HAS_OGG
  94875. /* see [1] HACK NOTE below for why we don't call the eof_callback when decoding Ogg FLAC */
  94876. !decoder->private_->is_ogg &&
  94877. #endif
  94878. decoder->private_->eof_callback && decoder->private_->eof_callback(decoder, decoder->private_->client_data)
  94879. )
  94880. ) {
  94881. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  94882. return false;
  94883. }
  94884. else
  94885. return true;
  94886. }
  94887. else
  94888. return true;
  94889. }
  94890. }
  94891. else {
  94892. /* abort to avoid a deadlock */
  94893. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  94894. return false;
  94895. }
  94896. /* [1] @@@ HACK NOTE: The end-of-stream checking has to be hacked around
  94897. * for Ogg FLAC. This is because the ogg decoder aspect can lose sync
  94898. * and at the same time hit the end of the stream (for example, seeking
  94899. * to a point that is after the beginning of the last Ogg page). There
  94900. * is no way to report an Ogg sync loss through the callbacks (see note
  94901. * in read_callback_ogg_aspect_()) so it returns CONTINUE with *bytes==0.
  94902. * So to keep the decoder from stopping at this point we gate the call
  94903. * to the eof_callback and let the Ogg decoder aspect set the
  94904. * end-of-stream state when it is needed.
  94905. */
  94906. }
  94907. #if FLAC__HAS_OGG
  94908. FLAC__StreamDecoderReadStatus read_callback_ogg_aspect_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes)
  94909. {
  94910. switch(FLAC__ogg_decoder_aspect_read_callback_wrapper(&decoder->protected_->ogg_decoder_aspect, buffer, bytes, read_callback_proxy_, decoder, decoder->private_->client_data)) {
  94911. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_OK:
  94912. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  94913. /* we don't really have a way to handle lost sync via read
  94914. * callback so we'll let it pass and let the underlying
  94915. * FLAC decoder catch the error
  94916. */
  94917. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_LOST_SYNC:
  94918. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  94919. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_END_OF_STREAM:
  94920. return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  94921. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_NOT_FLAC:
  94922. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_UNSUPPORTED_MAPPING_VERSION:
  94923. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT:
  94924. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_ERROR:
  94925. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_MEMORY_ALLOCATION_ERROR:
  94926. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  94927. default:
  94928. FLAC__ASSERT(0);
  94929. /* double protection */
  94930. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  94931. }
  94932. }
  94933. FLAC__OggDecoderAspectReadStatus read_callback_proxy_(const void *void_decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  94934. {
  94935. FLAC__StreamDecoder *decoder = (FLAC__StreamDecoder*)void_decoder;
  94936. switch(decoder->private_->read_callback(decoder, buffer, bytes, client_data)) {
  94937. case FLAC__STREAM_DECODER_READ_STATUS_CONTINUE:
  94938. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_OK;
  94939. case FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM:
  94940. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_END_OF_STREAM;
  94941. case FLAC__STREAM_DECODER_READ_STATUS_ABORT:
  94942. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT;
  94943. default:
  94944. /* double protection: */
  94945. FLAC__ASSERT(0);
  94946. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT;
  94947. }
  94948. }
  94949. #endif
  94950. FLAC__StreamDecoderWriteStatus write_audio_frame_to_client_(FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[])
  94951. {
  94952. if(decoder->private_->is_seeking) {
  94953. FLAC__uint64 this_frame_sample = frame->header.number.sample_number;
  94954. FLAC__uint64 next_frame_sample = this_frame_sample + (FLAC__uint64)frame->header.blocksize;
  94955. FLAC__uint64 target_sample = decoder->private_->target_sample;
  94956. FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  94957. #if FLAC__HAS_OGG
  94958. decoder->private_->got_a_frame = true;
  94959. #endif
  94960. decoder->private_->last_frame = *frame; /* save the frame */
  94961. if(this_frame_sample <= target_sample && target_sample < next_frame_sample) { /* we hit our target frame */
  94962. unsigned delta = (unsigned)(target_sample - this_frame_sample);
  94963. /* kick out of seek mode */
  94964. decoder->private_->is_seeking = false;
  94965. /* shift out the samples before target_sample */
  94966. if(delta > 0) {
  94967. unsigned channel;
  94968. const FLAC__int32 *newbuffer[FLAC__MAX_CHANNELS];
  94969. for(channel = 0; channel < frame->header.channels; channel++)
  94970. newbuffer[channel] = buffer[channel] + delta;
  94971. decoder->private_->last_frame.header.blocksize -= delta;
  94972. decoder->private_->last_frame.header.number.sample_number += (FLAC__uint64)delta;
  94973. /* write the relevant samples */
  94974. return decoder->private_->write_callback(decoder, &decoder->private_->last_frame, newbuffer, decoder->private_->client_data);
  94975. }
  94976. else {
  94977. /* write the relevant samples */
  94978. return decoder->private_->write_callback(decoder, frame, buffer, decoder->private_->client_data);
  94979. }
  94980. }
  94981. else {
  94982. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  94983. }
  94984. }
  94985. else {
  94986. /*
  94987. * If we never got STREAMINFO, turn off MD5 checking to save
  94988. * cycles since we don't have a sum to compare to anyway
  94989. */
  94990. if(!decoder->private_->has_stream_info)
  94991. decoder->private_->do_md5_checking = false;
  94992. if(decoder->private_->do_md5_checking) {
  94993. if(!FLAC__MD5Accumulate(&decoder->private_->md5context, buffer, frame->header.channels, frame->header.blocksize, (frame->header.bits_per_sample+7) / 8))
  94994. return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
  94995. }
  94996. return decoder->private_->write_callback(decoder, frame, buffer, decoder->private_->client_data);
  94997. }
  94998. }
  94999. void send_error_to_client_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status)
  95000. {
  95001. if(!decoder->private_->is_seeking)
  95002. decoder->private_->error_callback(decoder, status, decoder->private_->client_data);
  95003. else if(status == FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM)
  95004. decoder->private_->unparseable_frame_count++;
  95005. }
  95006. FLAC__bool seek_to_absolute_sample_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample)
  95007. {
  95008. FLAC__uint64 first_frame_offset = decoder->private_->first_frame_offset, lower_bound, upper_bound, lower_bound_sample, upper_bound_sample, this_frame_sample;
  95009. FLAC__int64 pos = -1;
  95010. int i;
  95011. unsigned approx_bytes_per_frame;
  95012. FLAC__bool first_seek = true;
  95013. const FLAC__uint64 total_samples = FLAC__stream_decoder_get_total_samples(decoder);
  95014. const unsigned min_blocksize = decoder->private_->stream_info.data.stream_info.min_blocksize;
  95015. const unsigned max_blocksize = decoder->private_->stream_info.data.stream_info.max_blocksize;
  95016. const unsigned max_framesize = decoder->private_->stream_info.data.stream_info.max_framesize;
  95017. const unsigned min_framesize = decoder->private_->stream_info.data.stream_info.min_framesize;
  95018. /* take these from the current frame in case they've changed mid-stream */
  95019. unsigned channels = FLAC__stream_decoder_get_channels(decoder);
  95020. unsigned bps = FLAC__stream_decoder_get_bits_per_sample(decoder);
  95021. const FLAC__StreamMetadata_SeekTable *seek_table = decoder->private_->has_seek_table? &decoder->private_->seek_table.data.seek_table : 0;
  95022. /* use values from stream info if we didn't decode a frame */
  95023. if(channels == 0)
  95024. channels = decoder->private_->stream_info.data.stream_info.channels;
  95025. if(bps == 0)
  95026. bps = decoder->private_->stream_info.data.stream_info.bits_per_sample;
  95027. /* we are just guessing here */
  95028. if(max_framesize > 0)
  95029. approx_bytes_per_frame = (max_framesize + min_framesize) / 2 + 1;
  95030. /*
  95031. * Check if it's a known fixed-blocksize stream. Note that though
  95032. * the spec doesn't allow zeroes in the STREAMINFO block, we may
  95033. * never get a STREAMINFO block when decoding so the value of
  95034. * min_blocksize might be zero.
  95035. */
  95036. else if(min_blocksize == max_blocksize && min_blocksize > 0) {
  95037. /* note there are no () around 'bps/8' to keep precision up since it's an integer calulation */
  95038. approx_bytes_per_frame = min_blocksize * channels * bps/8 + 64;
  95039. }
  95040. else
  95041. approx_bytes_per_frame = 4096 * channels * bps/8 + 64;
  95042. /*
  95043. * First, we set an upper and lower bound on where in the
  95044. * stream we will search. For now we assume the worst case
  95045. * scenario, which is our best guess at the beginning of
  95046. * the first frame and end of the stream.
  95047. */
  95048. lower_bound = first_frame_offset;
  95049. lower_bound_sample = 0;
  95050. upper_bound = stream_length;
  95051. upper_bound_sample = total_samples > 0 ? total_samples : target_sample /*estimate it*/;
  95052. /*
  95053. * Now we refine the bounds if we have a seektable with
  95054. * suitable points. Note that according to the spec they
  95055. * must be ordered by ascending sample number.
  95056. *
  95057. * Note: to protect against invalid seek tables we will ignore points
  95058. * that have frame_samples==0 or sample_number>=total_samples
  95059. */
  95060. if(seek_table) {
  95061. FLAC__uint64 new_lower_bound = lower_bound;
  95062. FLAC__uint64 new_upper_bound = upper_bound;
  95063. FLAC__uint64 new_lower_bound_sample = lower_bound_sample;
  95064. FLAC__uint64 new_upper_bound_sample = upper_bound_sample;
  95065. /* find the closest seek point <= target_sample, if it exists */
  95066. for(i = (int)seek_table->num_points - 1; i >= 0; 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 >= 0) { /* i.e. we found a suitable seek point... */
  95076. new_lower_bound = first_frame_offset + seek_table->points[i].stream_offset;
  95077. new_lower_bound_sample = seek_table->points[i].sample_number;
  95078. }
  95079. /* find the closest seek point > target_sample, if it exists */
  95080. for(i = 0; i < (int)seek_table->num_points; i++) {
  95081. if(
  95082. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  95083. seek_table->points[i].frame_samples > 0 && /* defense against bad seekpoints */
  95084. (total_samples <= 0 || seek_table->points[i].sample_number < total_samples) && /* defense against bad seekpoints */
  95085. seek_table->points[i].sample_number > target_sample
  95086. )
  95087. break;
  95088. }
  95089. if(i < (int)seek_table->num_points) { /* i.e. we found a suitable seek point... */
  95090. new_upper_bound = first_frame_offset + seek_table->points[i].stream_offset;
  95091. new_upper_bound_sample = seek_table->points[i].sample_number;
  95092. }
  95093. /* final protection against unsorted seek tables; keep original values if bogus */
  95094. if(new_upper_bound >= new_lower_bound) {
  95095. lower_bound = new_lower_bound;
  95096. upper_bound = new_upper_bound;
  95097. lower_bound_sample = new_lower_bound_sample;
  95098. upper_bound_sample = new_upper_bound_sample;
  95099. }
  95100. }
  95101. FLAC__ASSERT(upper_bound_sample >= lower_bound_sample);
  95102. /* there are 2 insidious ways that the following equality occurs, which
  95103. * we need to fix:
  95104. * 1) total_samples is 0 (unknown) and target_sample is 0
  95105. * 2) total_samples is 0 (unknown) and target_sample happens to be
  95106. * exactly equal to the last seek point in the seek table; this
  95107. * means there is no seek point above it, and upper_bound_samples
  95108. * remains equal to the estimate (of target_samples) we made above
  95109. * in either case it does not hurt to move upper_bound_sample up by 1
  95110. */
  95111. if(upper_bound_sample == lower_bound_sample)
  95112. upper_bound_sample++;
  95113. decoder->private_->target_sample = target_sample;
  95114. while(1) {
  95115. /* check if the bounds are still ok */
  95116. if (lower_bound_sample >= upper_bound_sample || lower_bound > upper_bound) {
  95117. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  95118. return false;
  95119. }
  95120. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95121. #if defined _MSC_VER || defined __MINGW32__
  95122. /* with VC++ you have to spoon feed it the casting */
  95123. 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;
  95124. #else
  95125. 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;
  95126. #endif
  95127. #else
  95128. /* a little less accurate: */
  95129. if(upper_bound - lower_bound < 0xffffffff)
  95130. 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;
  95131. else /* @@@ WATCHOUT, ~2TB limit */
  95132. 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;
  95133. #endif
  95134. if(pos >= (FLAC__int64)upper_bound)
  95135. pos = (FLAC__int64)upper_bound - 1;
  95136. if(pos < (FLAC__int64)lower_bound)
  95137. pos = (FLAC__int64)lower_bound;
  95138. if(decoder->private_->seek_callback(decoder, (FLAC__uint64)pos, decoder->private_->client_data) != FLAC__STREAM_DECODER_SEEK_STATUS_OK) {
  95139. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  95140. return false;
  95141. }
  95142. if(!FLAC__stream_decoder_flush(decoder)) {
  95143. /* above call sets the state for us */
  95144. return false;
  95145. }
  95146. /* Now we need to get a frame. First we need to reset our
  95147. * unparseable_frame_count; if we get too many unparseable
  95148. * frames in a row, the read callback will return
  95149. * FLAC__STREAM_DECODER_READ_STATUS_ABORT, causing
  95150. * FLAC__stream_decoder_process_single() to return false.
  95151. */
  95152. decoder->private_->unparseable_frame_count = 0;
  95153. if(!FLAC__stream_decoder_process_single(decoder)) {
  95154. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  95155. return false;
  95156. }
  95157. /* our write callback will change the state when it gets to the target frame */
  95158. /* 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 */
  95159. #if 0
  95160. /*@@@@@@ used to be the following; not clear if the check for end of stream is needed anymore */
  95161. if(decoder->protected_->state != FLAC__SEEKABLE_STREAM_DECODER_SEEKING && decoder->protected_->state != FLAC__STREAM_DECODER_END_OF_STREAM)
  95162. break;
  95163. #endif
  95164. if(!decoder->private_->is_seeking)
  95165. break;
  95166. FLAC__ASSERT(decoder->private_->last_frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  95167. this_frame_sample = decoder->private_->last_frame.header.number.sample_number;
  95168. if (0 == decoder->private_->samples_decoded || (this_frame_sample + decoder->private_->last_frame.header.blocksize >= upper_bound_sample && !first_seek)) {
  95169. if (pos == (FLAC__int64)lower_bound) {
  95170. /* can't move back any more than the first frame, something is fatally wrong */
  95171. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  95172. return false;
  95173. }
  95174. /* our last move backwards wasn't big enough, try again */
  95175. approx_bytes_per_frame = approx_bytes_per_frame? approx_bytes_per_frame * 2 : 16;
  95176. continue;
  95177. }
  95178. /* allow one seek over upper bound, so we can get a correct upper_bound_sample for streams with unknown total_samples */
  95179. first_seek = false;
  95180. /* make sure we are not seeking in corrupted stream */
  95181. if (this_frame_sample < lower_bound_sample) {
  95182. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  95183. return false;
  95184. }
  95185. /* we need to narrow the search */
  95186. if(target_sample < this_frame_sample) {
  95187. upper_bound_sample = this_frame_sample + decoder->private_->last_frame.header.blocksize;
  95188. /*@@@@@@ what will decode position be if at end of stream? */
  95189. if(!FLAC__stream_decoder_get_decode_position(decoder, &upper_bound)) {
  95190. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  95191. return false;
  95192. }
  95193. approx_bytes_per_frame = (unsigned)(2 * (upper_bound - pos) / 3 + 16);
  95194. }
  95195. else { /* target_sample >= this_frame_sample + this frame's blocksize */
  95196. lower_bound_sample = this_frame_sample + decoder->private_->last_frame.header.blocksize;
  95197. if(!FLAC__stream_decoder_get_decode_position(decoder, &lower_bound)) {
  95198. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  95199. return false;
  95200. }
  95201. approx_bytes_per_frame = (unsigned)(2 * (lower_bound - pos) / 3 + 16);
  95202. }
  95203. }
  95204. return true;
  95205. }
  95206. #if FLAC__HAS_OGG
  95207. FLAC__bool seek_to_absolute_sample_ogg_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample)
  95208. {
  95209. FLAC__uint64 left_pos = 0, right_pos = stream_length;
  95210. FLAC__uint64 left_sample = 0, right_sample = FLAC__stream_decoder_get_total_samples(decoder);
  95211. FLAC__uint64 this_frame_sample = (FLAC__uint64)0 - 1;
  95212. FLAC__uint64 pos = 0; /* only initialized to avoid compiler warning */
  95213. FLAC__bool did_a_seek;
  95214. unsigned iteration = 0;
  95215. /* In the first iterations, we will calculate the target byte position
  95216. * by the distance from the target sample to left_sample and
  95217. * right_sample (let's call it "proportional search"). After that, we
  95218. * will switch to binary search.
  95219. */
  95220. unsigned BINARY_SEARCH_AFTER_ITERATION = 2;
  95221. /* We will switch to a linear search once our current sample is less
  95222. * than this number of samples ahead of the target sample
  95223. */
  95224. static const FLAC__uint64 LINEAR_SEARCH_WITHIN_SAMPLES = FLAC__MAX_BLOCK_SIZE * 2;
  95225. /* If the total number of samples is unknown, use a large value, and
  95226. * force binary search immediately.
  95227. */
  95228. if(right_sample == 0) {
  95229. right_sample = (FLAC__uint64)(-1);
  95230. BINARY_SEARCH_AFTER_ITERATION = 0;
  95231. }
  95232. decoder->private_->target_sample = target_sample;
  95233. for( ; ; iteration++) {
  95234. if (iteration == 0 || this_frame_sample > target_sample || target_sample - this_frame_sample > LINEAR_SEARCH_WITHIN_SAMPLES) {
  95235. if (iteration >= BINARY_SEARCH_AFTER_ITERATION) {
  95236. pos = (right_pos + left_pos) / 2;
  95237. }
  95238. else {
  95239. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95240. #if defined _MSC_VER || defined __MINGW32__
  95241. /* with MSVC you have to spoon feed it the casting */
  95242. 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));
  95243. #else
  95244. pos = (FLAC__uint64)((FLAC__double)(target_sample - left_sample) / (FLAC__double)(right_sample - left_sample) * (FLAC__double)(right_pos - left_pos));
  95245. #endif
  95246. #else
  95247. /* a little less accurate: */
  95248. if ((target_sample-left_sample <= 0xffffffff) && (right_pos-left_pos <= 0xffffffff))
  95249. pos = (FLAC__int64)(((target_sample-left_sample) * (right_pos-left_pos)) / (right_sample-left_sample));
  95250. else /* @@@ WATCHOUT, ~2TB limit */
  95251. pos = (FLAC__int64)((((target_sample-left_sample)>>8) * ((right_pos-left_pos)>>8)) / ((right_sample-left_sample)>>16));
  95252. #endif
  95253. /* @@@ TODO: might want to limit pos to some distance
  95254. * before EOF, to make sure we land before the last frame,
  95255. * thereby getting a this_frame_sample and so having a better
  95256. * estimate.
  95257. */
  95258. }
  95259. /* physical seek */
  95260. if(decoder->private_->seek_callback((FLAC__StreamDecoder*)decoder, (FLAC__uint64)pos, decoder->private_->client_data) != FLAC__STREAM_DECODER_SEEK_STATUS_OK) {
  95261. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  95262. return false;
  95263. }
  95264. if(!FLAC__stream_decoder_flush(decoder)) {
  95265. /* above call sets the state for us */
  95266. return false;
  95267. }
  95268. did_a_seek = true;
  95269. }
  95270. else
  95271. did_a_seek = false;
  95272. decoder->private_->got_a_frame = false;
  95273. if(!FLAC__stream_decoder_process_single(decoder)) {
  95274. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  95275. return false;
  95276. }
  95277. if(!decoder->private_->got_a_frame) {
  95278. if(did_a_seek) {
  95279. /* this can happen if we seek to a point after the last frame; we drop
  95280. * to binary search right away in this case to avoid any wasted
  95281. * iterations of proportional search.
  95282. */
  95283. right_pos = pos;
  95284. BINARY_SEARCH_AFTER_ITERATION = 0;
  95285. }
  95286. else {
  95287. /* this can probably only happen if total_samples is unknown and the
  95288. * target_sample is past the end of the stream
  95289. */
  95290. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  95291. return false;
  95292. }
  95293. }
  95294. /* our write callback will change the state when it gets to the target frame */
  95295. else if(!decoder->private_->is_seeking) {
  95296. break;
  95297. }
  95298. else {
  95299. this_frame_sample = decoder->private_->last_frame.header.number.sample_number;
  95300. FLAC__ASSERT(decoder->private_->last_frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  95301. if (did_a_seek) {
  95302. if (this_frame_sample <= target_sample) {
  95303. /* The 'equal' case should not happen, since
  95304. * FLAC__stream_decoder_process_single()
  95305. * should recognize that it has hit the
  95306. * target sample and we would exit through
  95307. * the 'break' above.
  95308. */
  95309. FLAC__ASSERT(this_frame_sample != target_sample);
  95310. left_sample = this_frame_sample;
  95311. /* sanity check to avoid infinite loop */
  95312. if (left_pos == pos) {
  95313. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  95314. return false;
  95315. }
  95316. left_pos = pos;
  95317. }
  95318. else if(this_frame_sample > target_sample) {
  95319. right_sample = this_frame_sample;
  95320. /* sanity check to avoid infinite loop */
  95321. if (right_pos == pos) {
  95322. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  95323. return false;
  95324. }
  95325. right_pos = pos;
  95326. }
  95327. }
  95328. }
  95329. }
  95330. return true;
  95331. }
  95332. #endif
  95333. FLAC__StreamDecoderReadStatus file_read_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  95334. {
  95335. (void)client_data;
  95336. if(*bytes > 0) {
  95337. *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, decoder->private_->file);
  95338. if(ferror(decoder->private_->file))
  95339. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  95340. else if(*bytes == 0)
  95341. return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  95342. else
  95343. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  95344. }
  95345. else
  95346. return FLAC__STREAM_DECODER_READ_STATUS_ABORT; /* abort to avoid a deadlock */
  95347. }
  95348. FLAC__StreamDecoderSeekStatus file_seek_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  95349. {
  95350. (void)client_data;
  95351. if(decoder->private_->file == stdin)
  95352. return FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED;
  95353. else if(fseeko(decoder->private_->file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  95354. return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR;
  95355. else
  95356. return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  95357. }
  95358. FLAC__StreamDecoderTellStatus file_tell_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  95359. {
  95360. off_t pos;
  95361. (void)client_data;
  95362. if(decoder->private_->file == stdin)
  95363. return FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED;
  95364. else if((pos = ftello(decoder->private_->file)) < 0)
  95365. return FLAC__STREAM_DECODER_TELL_STATUS_ERROR;
  95366. else {
  95367. *absolute_byte_offset = (FLAC__uint64)pos;
  95368. return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  95369. }
  95370. }
  95371. FLAC__StreamDecoderLengthStatus file_length_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data)
  95372. {
  95373. struct stat filestats;
  95374. (void)client_data;
  95375. if(decoder->private_->file == stdin)
  95376. return FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED;
  95377. else if(fstat(fileno(decoder->private_->file), &filestats) != 0)
  95378. return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR;
  95379. else {
  95380. *stream_length = (FLAC__uint64)filestats.st_size;
  95381. return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  95382. }
  95383. }
  95384. FLAC__bool file_eof_callback_(const FLAC__StreamDecoder *decoder, void *client_data)
  95385. {
  95386. (void)client_data;
  95387. return feof(decoder->private_->file)? true : false;
  95388. }
  95389. #endif
  95390. /********* End of inlined file: stream_decoder.c *********/
  95391. /********* Start of inlined file: stream_encoder.c *********/
  95392. /********* Start of inlined file: juce_FlacHeader.h *********/
  95393. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  95394. // tasks..
  95395. #define VERSION "1.2.1"
  95396. #define FLAC__NO_DLL 1
  95397. #ifdef _MSC_VER
  95398. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  95399. #endif
  95400. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  95401. #define FLAC__SYS_DARWIN 1
  95402. #endif
  95403. /********* End of inlined file: juce_FlacHeader.h *********/
  95404. #if JUCE_USE_FLAC
  95405. #if HAVE_CONFIG_H
  95406. # include <config.h>
  95407. #endif
  95408. #if defined _MSC_VER || defined __MINGW32__
  95409. #include <io.h> /* for _setmode() */
  95410. #include <fcntl.h> /* for _O_BINARY */
  95411. #endif
  95412. #if defined __CYGWIN__ || defined __EMX__
  95413. #include <io.h> /* for setmode(), O_BINARY */
  95414. #include <fcntl.h> /* for _O_BINARY */
  95415. #endif
  95416. #include <limits.h>
  95417. #include <stdio.h>
  95418. #include <stdlib.h> /* for malloc() */
  95419. #include <string.h> /* for memcpy() */
  95420. #include <sys/types.h> /* for off_t */
  95421. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINGW32__
  95422. #if _MSC_VER <= 1600 || defined __BORLANDC__ /* @@@ [2G limit] */
  95423. #define fseeko fseek
  95424. #define ftello ftell
  95425. #endif
  95426. #endif
  95427. /********* Start of inlined file: stream_encoder.h *********/
  95428. #ifndef FLAC__PROTECTED__STREAM_ENCODER_H
  95429. #define FLAC__PROTECTED__STREAM_ENCODER_H
  95430. #if FLAC__HAS_OGG
  95431. #include "private/ogg_encoder_aspect.h"
  95432. #endif
  95433. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95434. #define FLAC__MAX_APODIZATION_FUNCTIONS 32
  95435. typedef enum {
  95436. FLAC__APODIZATION_BARTLETT,
  95437. FLAC__APODIZATION_BARTLETT_HANN,
  95438. FLAC__APODIZATION_BLACKMAN,
  95439. FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE,
  95440. FLAC__APODIZATION_CONNES,
  95441. FLAC__APODIZATION_FLATTOP,
  95442. FLAC__APODIZATION_GAUSS,
  95443. FLAC__APODIZATION_HAMMING,
  95444. FLAC__APODIZATION_HANN,
  95445. FLAC__APODIZATION_KAISER_BESSEL,
  95446. FLAC__APODIZATION_NUTTALL,
  95447. FLAC__APODIZATION_RECTANGLE,
  95448. FLAC__APODIZATION_TRIANGLE,
  95449. FLAC__APODIZATION_TUKEY,
  95450. FLAC__APODIZATION_WELCH
  95451. } FLAC__ApodizationFunction;
  95452. typedef struct {
  95453. FLAC__ApodizationFunction type;
  95454. union {
  95455. struct {
  95456. FLAC__real stddev;
  95457. } gauss;
  95458. struct {
  95459. FLAC__real p;
  95460. } tukey;
  95461. } parameters;
  95462. } FLAC__ApodizationSpecification;
  95463. #endif // #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95464. typedef struct FLAC__StreamEncoderProtected {
  95465. FLAC__StreamEncoderState state;
  95466. FLAC__bool verify;
  95467. FLAC__bool streamable_subset;
  95468. FLAC__bool do_md5;
  95469. FLAC__bool do_mid_side_stereo;
  95470. FLAC__bool loose_mid_side_stereo;
  95471. unsigned channels;
  95472. unsigned bits_per_sample;
  95473. unsigned sample_rate;
  95474. unsigned blocksize;
  95475. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95476. unsigned num_apodizations;
  95477. FLAC__ApodizationSpecification apodizations[FLAC__MAX_APODIZATION_FUNCTIONS];
  95478. #endif
  95479. unsigned max_lpc_order;
  95480. unsigned qlp_coeff_precision;
  95481. FLAC__bool do_qlp_coeff_prec_search;
  95482. FLAC__bool do_exhaustive_model_search;
  95483. FLAC__bool do_escape_coding;
  95484. unsigned min_residual_partition_order;
  95485. unsigned max_residual_partition_order;
  95486. unsigned rice_parameter_search_dist;
  95487. FLAC__uint64 total_samples_estimate;
  95488. FLAC__StreamMetadata **metadata;
  95489. unsigned num_metadata_blocks;
  95490. FLAC__uint64 streaminfo_offset, seektable_offset, audio_offset;
  95491. #if FLAC__HAS_OGG
  95492. FLAC__OggEncoderAspect ogg_encoder_aspect;
  95493. #endif
  95494. } FLAC__StreamEncoderProtected;
  95495. #endif
  95496. /********* End of inlined file: stream_encoder.h *********/
  95497. #if FLAC__HAS_OGG
  95498. #include "include/private/ogg_helper.h"
  95499. #include "include/private/ogg_mapping.h"
  95500. #endif
  95501. /********* Start of inlined file: stream_encoder_framing.h *********/
  95502. #ifndef FLAC__PRIVATE__STREAM_ENCODER_FRAMING_H
  95503. #define FLAC__PRIVATE__STREAM_ENCODER_FRAMING_H
  95504. FLAC__bool FLAC__add_metadata_block(const FLAC__StreamMetadata *metadata, FLAC__BitWriter *bw);
  95505. FLAC__bool FLAC__frame_add_header(const FLAC__FrameHeader *header, FLAC__BitWriter *bw);
  95506. FLAC__bool FLAC__subframe_add_constant(const FLAC__Subframe_Constant *subframe, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  95507. FLAC__bool FLAC__subframe_add_fixed(const FLAC__Subframe_Fixed *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  95508. FLAC__bool FLAC__subframe_add_lpc(const FLAC__Subframe_LPC *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  95509. FLAC__bool FLAC__subframe_add_verbatim(const FLAC__Subframe_Verbatim *subframe, unsigned samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  95510. #endif
  95511. /********* End of inlined file: stream_encoder_framing.h *********/
  95512. /********* Start of inlined file: window.h *********/
  95513. #ifndef FLAC__PRIVATE__WINDOW_H
  95514. #define FLAC__PRIVATE__WINDOW_H
  95515. #ifdef HAVE_CONFIG_H
  95516. #include <config.h>
  95517. #endif
  95518. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95519. /*
  95520. * FLAC__window_*()
  95521. * --------------------------------------------------------------------
  95522. * Calculates window coefficients according to different apodization
  95523. * functions.
  95524. *
  95525. * OUT window[0,L-1]
  95526. * IN L (number of points in window)
  95527. */
  95528. void FLAC__window_bartlett(FLAC__real *window, const FLAC__int32 L);
  95529. void FLAC__window_bartlett_hann(FLAC__real *window, const FLAC__int32 L);
  95530. void FLAC__window_blackman(FLAC__real *window, const FLAC__int32 L);
  95531. void FLAC__window_blackman_harris_4term_92db_sidelobe(FLAC__real *window, const FLAC__int32 L);
  95532. void FLAC__window_connes(FLAC__real *window, const FLAC__int32 L);
  95533. void FLAC__window_flattop(FLAC__real *window, const FLAC__int32 L);
  95534. void FLAC__window_gauss(FLAC__real *window, const FLAC__int32 L, const FLAC__real stddev); /* 0.0 < stddev <= 0.5 */
  95535. void FLAC__window_hamming(FLAC__real *window, const FLAC__int32 L);
  95536. void FLAC__window_hann(FLAC__real *window, const FLAC__int32 L);
  95537. void FLAC__window_kaiser_bessel(FLAC__real *window, const FLAC__int32 L);
  95538. void FLAC__window_nuttall(FLAC__real *window, const FLAC__int32 L);
  95539. void FLAC__window_rectangle(FLAC__real *window, const FLAC__int32 L);
  95540. void FLAC__window_triangle(FLAC__real *window, const FLAC__int32 L);
  95541. void FLAC__window_tukey(FLAC__real *window, const FLAC__int32 L, const FLAC__real p);
  95542. void FLAC__window_welch(FLAC__real *window, const FLAC__int32 L);
  95543. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  95544. #endif
  95545. /********* End of inlined file: window.h *********/
  95546. #ifndef FLaC__INLINE
  95547. #define FLaC__INLINE
  95548. #endif
  95549. #ifdef min
  95550. #undef min
  95551. #endif
  95552. #define min(x,y) ((x)<(y)?(x):(y))
  95553. #ifdef max
  95554. #undef max
  95555. #endif
  95556. #define max(x,y) ((x)>(y)?(x):(y))
  95557. /* Exact Rice codeword length calculation is off by default. The simple
  95558. * (and fast) estimation (of how many bits a residual value will be
  95559. * encoded with) in this encoder is very good, almost always yielding
  95560. * compression within 0.1% of exact calculation.
  95561. */
  95562. #undef EXACT_RICE_BITS_CALCULATION
  95563. /* Rice parameter searching is off by default. The simple (and fast)
  95564. * parameter estimation in this encoder is very good, almost always
  95565. * yielding compression within 0.1% of the optimal parameters.
  95566. */
  95567. #undef ENABLE_RICE_PARAMETER_SEARCH
  95568. typedef struct {
  95569. FLAC__int32 *data[FLAC__MAX_CHANNELS];
  95570. unsigned size; /* of each data[] in samples */
  95571. unsigned tail;
  95572. } verify_input_fifo;
  95573. typedef struct {
  95574. const FLAC__byte *data;
  95575. unsigned capacity;
  95576. unsigned bytes;
  95577. } verify_output;
  95578. typedef enum {
  95579. ENCODER_IN_MAGIC = 0,
  95580. ENCODER_IN_METADATA = 1,
  95581. ENCODER_IN_AUDIO = 2
  95582. } EncoderStateHint;
  95583. static struct CompressionLevels {
  95584. FLAC__bool do_mid_side_stereo;
  95585. FLAC__bool loose_mid_side_stereo;
  95586. unsigned max_lpc_order;
  95587. unsigned qlp_coeff_precision;
  95588. FLAC__bool do_qlp_coeff_prec_search;
  95589. FLAC__bool do_escape_coding;
  95590. FLAC__bool do_exhaustive_model_search;
  95591. unsigned min_residual_partition_order;
  95592. unsigned max_residual_partition_order;
  95593. unsigned rice_parameter_search_dist;
  95594. } compression_levels_[] = {
  95595. { false, false, 0, 0, false, false, false, 0, 3, 0 },
  95596. { true , true , 0, 0, false, false, false, 0, 3, 0 },
  95597. { true , false, 0, 0, false, false, false, 0, 3, 0 },
  95598. { false, false, 6, 0, false, false, false, 0, 4, 0 },
  95599. { true , true , 8, 0, false, false, false, 0, 4, 0 },
  95600. { true , false, 8, 0, false, false, false, 0, 5, 0 },
  95601. { true , false, 8, 0, false, false, false, 0, 6, 0 },
  95602. { true , false, 8, 0, false, false, true , 0, 6, 0 },
  95603. { true , false, 12, 0, false, false, true , 0, 6, 0 }
  95604. };
  95605. /***********************************************************************
  95606. *
  95607. * Private class method prototypes
  95608. *
  95609. ***********************************************************************/
  95610. static void set_defaults_enc(FLAC__StreamEncoder *encoder);
  95611. static void free_(FLAC__StreamEncoder *encoder);
  95612. static FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize);
  95613. static FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block);
  95614. static FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block);
  95615. static void update_metadata_(const FLAC__StreamEncoder *encoder);
  95616. #if FLAC__HAS_OGG
  95617. static void update_ogg_metadata_(FLAC__StreamEncoder *encoder);
  95618. #endif
  95619. static FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block);
  95620. static FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block);
  95621. static FLAC__bool process_subframe_(
  95622. FLAC__StreamEncoder *encoder,
  95623. unsigned min_partition_order,
  95624. unsigned max_partition_order,
  95625. const FLAC__FrameHeader *frame_header,
  95626. unsigned subframe_bps,
  95627. const FLAC__int32 integer_signal[],
  95628. FLAC__Subframe *subframe[2],
  95629. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
  95630. FLAC__int32 *residual[2],
  95631. unsigned *best_subframe,
  95632. unsigned *best_bits
  95633. );
  95634. static FLAC__bool add_subframe_(
  95635. FLAC__StreamEncoder *encoder,
  95636. unsigned blocksize,
  95637. unsigned subframe_bps,
  95638. const FLAC__Subframe *subframe,
  95639. FLAC__BitWriter *frame
  95640. );
  95641. static unsigned evaluate_constant_subframe_(
  95642. FLAC__StreamEncoder *encoder,
  95643. const FLAC__int32 signal,
  95644. unsigned blocksize,
  95645. unsigned subframe_bps,
  95646. FLAC__Subframe *subframe
  95647. );
  95648. static unsigned evaluate_fixed_subframe_(
  95649. FLAC__StreamEncoder *encoder,
  95650. const FLAC__int32 signal[],
  95651. FLAC__int32 residual[],
  95652. FLAC__uint64 abs_residual_partition_sums[],
  95653. unsigned raw_bits_per_partition[],
  95654. unsigned blocksize,
  95655. unsigned subframe_bps,
  95656. unsigned order,
  95657. unsigned rice_parameter,
  95658. unsigned rice_parameter_limit,
  95659. unsigned min_partition_order,
  95660. unsigned max_partition_order,
  95661. FLAC__bool do_escape_coding,
  95662. unsigned rice_parameter_search_dist,
  95663. FLAC__Subframe *subframe,
  95664. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  95665. );
  95666. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95667. static unsigned evaluate_lpc_subframe_(
  95668. FLAC__StreamEncoder *encoder,
  95669. const FLAC__int32 signal[],
  95670. FLAC__int32 residual[],
  95671. FLAC__uint64 abs_residual_partition_sums[],
  95672. unsigned raw_bits_per_partition[],
  95673. const FLAC__real lp_coeff[],
  95674. unsigned blocksize,
  95675. unsigned subframe_bps,
  95676. unsigned order,
  95677. unsigned qlp_coeff_precision,
  95678. unsigned rice_parameter,
  95679. unsigned rice_parameter_limit,
  95680. unsigned min_partition_order,
  95681. unsigned max_partition_order,
  95682. FLAC__bool do_escape_coding,
  95683. unsigned rice_parameter_search_dist,
  95684. FLAC__Subframe *subframe,
  95685. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  95686. );
  95687. #endif
  95688. static unsigned evaluate_verbatim_subframe_(
  95689. FLAC__StreamEncoder *encoder,
  95690. const FLAC__int32 signal[],
  95691. unsigned blocksize,
  95692. unsigned subframe_bps,
  95693. FLAC__Subframe *subframe
  95694. );
  95695. static unsigned find_best_partition_order_(
  95696. struct FLAC__StreamEncoderPrivate *private_,
  95697. const FLAC__int32 residual[],
  95698. FLAC__uint64 abs_residual_partition_sums[],
  95699. unsigned raw_bits_per_partition[],
  95700. unsigned residual_samples,
  95701. unsigned predictor_order,
  95702. unsigned rice_parameter,
  95703. unsigned rice_parameter_limit,
  95704. unsigned min_partition_order,
  95705. unsigned max_partition_order,
  95706. unsigned bps,
  95707. FLAC__bool do_escape_coding,
  95708. unsigned rice_parameter_search_dist,
  95709. FLAC__EntropyCodingMethod *best_ecm
  95710. );
  95711. static void precompute_partition_info_sums_(
  95712. const FLAC__int32 residual[],
  95713. FLAC__uint64 abs_residual_partition_sums[],
  95714. unsigned residual_samples,
  95715. unsigned predictor_order,
  95716. unsigned min_partition_order,
  95717. unsigned max_partition_order,
  95718. unsigned bps
  95719. );
  95720. static void precompute_partition_info_escapes_(
  95721. const FLAC__int32 residual[],
  95722. unsigned raw_bits_per_partition[],
  95723. unsigned residual_samples,
  95724. unsigned predictor_order,
  95725. unsigned min_partition_order,
  95726. unsigned max_partition_order
  95727. );
  95728. static FLAC__bool set_partitioned_rice_(
  95729. #ifdef EXACT_RICE_BITS_CALCULATION
  95730. const FLAC__int32 residual[],
  95731. #endif
  95732. const FLAC__uint64 abs_residual_partition_sums[],
  95733. const unsigned raw_bits_per_partition[],
  95734. const unsigned residual_samples,
  95735. const unsigned predictor_order,
  95736. const unsigned suggested_rice_parameter,
  95737. const unsigned rice_parameter_limit,
  95738. const unsigned rice_parameter_search_dist,
  95739. const unsigned partition_order,
  95740. const FLAC__bool search_for_escapes,
  95741. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
  95742. unsigned *bits
  95743. );
  95744. static unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples);
  95745. /* verify-related routines: */
  95746. static void append_to_verify_fifo_(
  95747. verify_input_fifo *fifo,
  95748. const FLAC__int32 * const input[],
  95749. unsigned input_offset,
  95750. unsigned channels,
  95751. unsigned wide_samples
  95752. );
  95753. static void append_to_verify_fifo_interleaved_(
  95754. verify_input_fifo *fifo,
  95755. const FLAC__int32 input[],
  95756. unsigned input_offset,
  95757. unsigned channels,
  95758. unsigned wide_samples
  95759. );
  95760. static FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  95761. static FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
  95762. static void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
  95763. static void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
  95764. static FLAC__StreamEncoderReadStatus file_read_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  95765. static FLAC__StreamEncoderSeekStatus file_seek_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  95766. static FLAC__StreamEncoderTellStatus file_tell_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  95767. 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);
  95768. static FILE *get_binary_stdout_(void);
  95769. /***********************************************************************
  95770. *
  95771. * Private class data
  95772. *
  95773. ***********************************************************************/
  95774. typedef struct FLAC__StreamEncoderPrivate {
  95775. unsigned input_capacity; /* current size (in samples) of the signal and residual buffers */
  95776. FLAC__int32 *integer_signal[FLAC__MAX_CHANNELS]; /* the integer version of the input signal */
  95777. FLAC__int32 *integer_signal_mid_side[2]; /* the integer version of the mid-side input signal (stereo only) */
  95778. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95779. FLAC__real *real_signal[FLAC__MAX_CHANNELS]; /* (@@@ currently unused) the floating-point version of the input signal */
  95780. FLAC__real *real_signal_mid_side[2]; /* (@@@ currently unused) the floating-point version of the mid-side input signal (stereo only) */
  95781. FLAC__real *window[FLAC__MAX_APODIZATION_FUNCTIONS]; /* the pre-computed floating-point window for each apodization function */
  95782. FLAC__real *windowed_signal; /* the integer_signal[] * current window[] */
  95783. #endif
  95784. unsigned subframe_bps[FLAC__MAX_CHANNELS]; /* the effective bits per sample of the input signal (stream bps - wasted bits) */
  95785. unsigned subframe_bps_mid_side[2]; /* the effective bits per sample of the mid-side input signal (stream bps - wasted bits + 0/1) */
  95786. FLAC__int32 *residual_workspace[FLAC__MAX_CHANNELS][2]; /* each channel has a candidate and best workspace where the subframe residual signals will be stored */
  95787. FLAC__int32 *residual_workspace_mid_side[2][2];
  95788. FLAC__Subframe subframe_workspace[FLAC__MAX_CHANNELS][2];
  95789. FLAC__Subframe subframe_workspace_mid_side[2][2];
  95790. FLAC__Subframe *subframe_workspace_ptr[FLAC__MAX_CHANNELS][2];
  95791. FLAC__Subframe *subframe_workspace_ptr_mid_side[2][2];
  95792. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace[FLAC__MAX_CHANNELS][2];
  95793. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace_mid_side[FLAC__MAX_CHANNELS][2];
  95794. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr[FLAC__MAX_CHANNELS][2];
  95795. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr_mid_side[FLAC__MAX_CHANNELS][2];
  95796. unsigned best_subframe[FLAC__MAX_CHANNELS]; /* index (0 or 1) into 2nd dimension of the above workspaces */
  95797. unsigned best_subframe_mid_side[2];
  95798. unsigned best_subframe_bits[FLAC__MAX_CHANNELS]; /* size in bits of the best subframe for each channel */
  95799. unsigned best_subframe_bits_mid_side[2];
  95800. FLAC__uint64 *abs_residual_partition_sums; /* workspace where the sum of abs(candidate residual) for each partition is stored */
  95801. unsigned *raw_bits_per_partition; /* workspace where the sum of silog2(candidate residual) for each partition is stored */
  95802. FLAC__BitWriter *frame; /* the current frame being worked on */
  95803. unsigned loose_mid_side_stereo_frames; /* rounded number of frames the encoder will use before trying both independent and mid/side frames again */
  95804. unsigned loose_mid_side_stereo_frame_count; /* number of frames using the current channel assignment */
  95805. FLAC__ChannelAssignment last_channel_assignment;
  95806. FLAC__StreamMetadata streaminfo; /* scratchpad for STREAMINFO as it is built */
  95807. FLAC__StreamMetadata_SeekTable *seek_table; /* pointer into encoder->protected_->metadata_ where the seek table is */
  95808. unsigned current_sample_number;
  95809. unsigned current_frame_number;
  95810. FLAC__MD5Context md5context;
  95811. FLAC__CPUInfo cpuinfo;
  95812. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95813. unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  95814. #else
  95815. unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  95816. #endif
  95817. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95818. void (*local_lpc_compute_autocorrelation)(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  95819. 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[]);
  95820. 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[]);
  95821. 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[]);
  95822. #endif
  95823. FLAC__bool use_wide_by_block; /* use slow 64-bit versions of some functions because of the block size */
  95824. FLAC__bool use_wide_by_partition; /* use slow 64-bit versions of some functions because of the min partition order and blocksize */
  95825. FLAC__bool use_wide_by_order; /* use slow 64-bit versions of some functions because of the lpc order */
  95826. FLAC__bool disable_constant_subframes;
  95827. FLAC__bool disable_fixed_subframes;
  95828. FLAC__bool disable_verbatim_subframes;
  95829. #if FLAC__HAS_OGG
  95830. FLAC__bool is_ogg;
  95831. #endif
  95832. FLAC__StreamEncoderReadCallback read_callback; /* currently only needed for Ogg FLAC */
  95833. FLAC__StreamEncoderSeekCallback seek_callback;
  95834. FLAC__StreamEncoderTellCallback tell_callback;
  95835. FLAC__StreamEncoderWriteCallback write_callback;
  95836. FLAC__StreamEncoderMetadataCallback metadata_callback;
  95837. FLAC__StreamEncoderProgressCallback progress_callback;
  95838. void *client_data;
  95839. unsigned first_seekpoint_to_check;
  95840. FILE *file; /* only used when encoding to a file */
  95841. FLAC__uint64 bytes_written;
  95842. FLAC__uint64 samples_written;
  95843. unsigned frames_written;
  95844. unsigned total_frames_estimate;
  95845. /* unaligned (original) pointers to allocated data */
  95846. FLAC__int32 *integer_signal_unaligned[FLAC__MAX_CHANNELS];
  95847. FLAC__int32 *integer_signal_mid_side_unaligned[2];
  95848. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95849. FLAC__real *real_signal_unaligned[FLAC__MAX_CHANNELS]; /* (@@@ currently unused) */
  95850. FLAC__real *real_signal_mid_side_unaligned[2]; /* (@@@ currently unused) */
  95851. FLAC__real *window_unaligned[FLAC__MAX_APODIZATION_FUNCTIONS];
  95852. FLAC__real *windowed_signal_unaligned;
  95853. #endif
  95854. FLAC__int32 *residual_workspace_unaligned[FLAC__MAX_CHANNELS][2];
  95855. FLAC__int32 *residual_workspace_mid_side_unaligned[2][2];
  95856. FLAC__uint64 *abs_residual_partition_sums_unaligned;
  95857. unsigned *raw_bits_per_partition_unaligned;
  95858. /*
  95859. * These fields have been moved here from private function local
  95860. * declarations merely to save stack space during encoding.
  95861. */
  95862. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95863. FLAC__real lp_coeff[FLAC__MAX_LPC_ORDER][FLAC__MAX_LPC_ORDER]; /* from process_subframe_() */
  95864. #endif
  95865. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_extra[2]; /* from find_best_partition_order_() */
  95866. /*
  95867. * The data for the verify section
  95868. */
  95869. struct {
  95870. FLAC__StreamDecoder *decoder;
  95871. EncoderStateHint state_hint;
  95872. FLAC__bool needs_magic_hack;
  95873. verify_input_fifo input_fifo;
  95874. verify_output output;
  95875. struct {
  95876. FLAC__uint64 absolute_sample;
  95877. unsigned frame_number;
  95878. unsigned channel;
  95879. unsigned sample;
  95880. FLAC__int32 expected;
  95881. FLAC__int32 got;
  95882. } error_stats;
  95883. } verify;
  95884. FLAC__bool is_being_deleted; /* if true, call to ..._finish() from ..._delete() will not call the callbacks */
  95885. } FLAC__StreamEncoderPrivate;
  95886. /***********************************************************************
  95887. *
  95888. * Public static class data
  95889. *
  95890. ***********************************************************************/
  95891. FLAC_API const char * const FLAC__StreamEncoderStateString[] = {
  95892. "FLAC__STREAM_ENCODER_OK",
  95893. "FLAC__STREAM_ENCODER_UNINITIALIZED",
  95894. "FLAC__STREAM_ENCODER_OGG_ERROR",
  95895. "FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR",
  95896. "FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA",
  95897. "FLAC__STREAM_ENCODER_CLIENT_ERROR",
  95898. "FLAC__STREAM_ENCODER_IO_ERROR",
  95899. "FLAC__STREAM_ENCODER_FRAMING_ERROR",
  95900. "FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR"
  95901. };
  95902. FLAC_API const char * const FLAC__StreamEncoderInitStatusString[] = {
  95903. "FLAC__STREAM_ENCODER_INIT_STATUS_OK",
  95904. "FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR",
  95905. "FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER",
  95906. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS",
  95907. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS",
  95908. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE",
  95909. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE",
  95910. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE",
  95911. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER",
  95912. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION",
  95913. "FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER",
  95914. "FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE",
  95915. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA",
  95916. "FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED"
  95917. };
  95918. FLAC_API const char * const FLAC__treamEncoderReadStatusString[] = {
  95919. "FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE",
  95920. "FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM",
  95921. "FLAC__STREAM_ENCODER_READ_STATUS_ABORT",
  95922. "FLAC__STREAM_ENCODER_READ_STATUS_UNSUPPORTED"
  95923. };
  95924. FLAC_API const char * const FLAC__StreamEncoderWriteStatusString[] = {
  95925. "FLAC__STREAM_ENCODER_WRITE_STATUS_OK",
  95926. "FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR"
  95927. };
  95928. FLAC_API const char * const FLAC__StreamEncoderSeekStatusString[] = {
  95929. "FLAC__STREAM_ENCODER_SEEK_STATUS_OK",
  95930. "FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR",
  95931. "FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED"
  95932. };
  95933. FLAC_API const char * const FLAC__StreamEncoderTellStatusString[] = {
  95934. "FLAC__STREAM_ENCODER_TELL_STATUS_OK",
  95935. "FLAC__STREAM_ENCODER_TELL_STATUS_ERROR",
  95936. "FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED"
  95937. };
  95938. /* Number of samples that will be overread to watch for end of stream. By
  95939. * 'overread', we mean that the FLAC__stream_encoder_process*() calls will
  95940. * always try to read blocksize+1 samples before encoding a block, so that
  95941. * even if the stream has a total sample count that is an integral multiple
  95942. * of the blocksize, we will still notice when we are encoding the last
  95943. * block. This is needed, for example, to correctly set the end-of-stream
  95944. * marker in Ogg FLAC.
  95945. *
  95946. * WATCHOUT: some parts of the code assert that OVERREAD_ == 1 and there's
  95947. * not really any reason to change it.
  95948. */
  95949. static const unsigned OVERREAD_ = 1;
  95950. /***********************************************************************
  95951. *
  95952. * Class constructor/destructor
  95953. *
  95954. */
  95955. FLAC_API FLAC__StreamEncoder *FLAC__stream_encoder_new(void)
  95956. {
  95957. FLAC__StreamEncoder *encoder;
  95958. unsigned i;
  95959. FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
  95960. encoder = (FLAC__StreamEncoder*)calloc(1, sizeof(FLAC__StreamEncoder));
  95961. if(encoder == 0) {
  95962. return 0;
  95963. }
  95964. encoder->protected_ = (FLAC__StreamEncoderProtected*)calloc(1, sizeof(FLAC__StreamEncoderProtected));
  95965. if(encoder->protected_ == 0) {
  95966. free(encoder);
  95967. return 0;
  95968. }
  95969. encoder->private_ = (FLAC__StreamEncoderPrivate*)calloc(1, sizeof(FLAC__StreamEncoderPrivate));
  95970. if(encoder->private_ == 0) {
  95971. free(encoder->protected_);
  95972. free(encoder);
  95973. return 0;
  95974. }
  95975. encoder->private_->frame = FLAC__bitwriter_new();
  95976. if(encoder->private_->frame == 0) {
  95977. free(encoder->private_);
  95978. free(encoder->protected_);
  95979. free(encoder);
  95980. return 0;
  95981. }
  95982. encoder->private_->file = 0;
  95983. set_defaults_enc(encoder);
  95984. encoder->private_->is_being_deleted = false;
  95985. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  95986. encoder->private_->subframe_workspace_ptr[i][0] = &encoder->private_->subframe_workspace[i][0];
  95987. encoder->private_->subframe_workspace_ptr[i][1] = &encoder->private_->subframe_workspace[i][1];
  95988. }
  95989. for(i = 0; i < 2; i++) {
  95990. encoder->private_->subframe_workspace_ptr_mid_side[i][0] = &encoder->private_->subframe_workspace_mid_side[i][0];
  95991. encoder->private_->subframe_workspace_ptr_mid_side[i][1] = &encoder->private_->subframe_workspace_mid_side[i][1];
  95992. }
  95993. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  95994. encoder->private_->partitioned_rice_contents_workspace_ptr[i][0] = &encoder->private_->partitioned_rice_contents_workspace[i][0];
  95995. encoder->private_->partitioned_rice_contents_workspace_ptr[i][1] = &encoder->private_->partitioned_rice_contents_workspace[i][1];
  95996. }
  95997. for(i = 0; i < 2; i++) {
  95998. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][0] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0];
  95999. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][1] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1];
  96000. }
  96001. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  96002. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
  96003. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
  96004. }
  96005. for(i = 0; i < 2; i++) {
  96006. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
  96007. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
  96008. }
  96009. for(i = 0; i < 2; i++)
  96010. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_extra[i]);
  96011. encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
  96012. return encoder;
  96013. }
  96014. FLAC_API void FLAC__stream_encoder_delete(FLAC__StreamEncoder *encoder)
  96015. {
  96016. unsigned i;
  96017. FLAC__ASSERT(0 != encoder);
  96018. FLAC__ASSERT(0 != encoder->protected_);
  96019. FLAC__ASSERT(0 != encoder->private_);
  96020. FLAC__ASSERT(0 != encoder->private_->frame);
  96021. encoder->private_->is_being_deleted = true;
  96022. (void)FLAC__stream_encoder_finish(encoder);
  96023. if(0 != encoder->private_->verify.decoder)
  96024. FLAC__stream_decoder_delete(encoder->private_->verify.decoder);
  96025. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  96026. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
  96027. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
  96028. }
  96029. for(i = 0; i < 2; i++) {
  96030. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
  96031. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
  96032. }
  96033. for(i = 0; i < 2; i++)
  96034. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_extra[i]);
  96035. FLAC__bitwriter_delete(encoder->private_->frame);
  96036. free(encoder->private_);
  96037. free(encoder->protected_);
  96038. free(encoder);
  96039. }
  96040. /***********************************************************************
  96041. *
  96042. * Public class methods
  96043. *
  96044. ***********************************************************************/
  96045. static FLAC__StreamEncoderInitStatus init_stream_internal_enc(
  96046. FLAC__StreamEncoder *encoder,
  96047. FLAC__StreamEncoderReadCallback read_callback,
  96048. FLAC__StreamEncoderWriteCallback write_callback,
  96049. FLAC__StreamEncoderSeekCallback seek_callback,
  96050. FLAC__StreamEncoderTellCallback tell_callback,
  96051. FLAC__StreamEncoderMetadataCallback metadata_callback,
  96052. void *client_data,
  96053. FLAC__bool is_ogg
  96054. )
  96055. {
  96056. unsigned i;
  96057. FLAC__bool metadata_has_seektable, metadata_has_vorbis_comment, metadata_picture_has_type1, metadata_picture_has_type2;
  96058. FLAC__ASSERT(0 != encoder);
  96059. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  96060. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  96061. #if !FLAC__HAS_OGG
  96062. if(is_ogg)
  96063. return FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER;
  96064. #endif
  96065. if(0 == write_callback || (seek_callback && 0 == tell_callback))
  96066. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS;
  96067. if(encoder->protected_->channels == 0 || encoder->protected_->channels > FLAC__MAX_CHANNELS)
  96068. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS;
  96069. if(encoder->protected_->channels != 2) {
  96070. encoder->protected_->do_mid_side_stereo = false;
  96071. encoder->protected_->loose_mid_side_stereo = false;
  96072. }
  96073. else if(!encoder->protected_->do_mid_side_stereo)
  96074. encoder->protected_->loose_mid_side_stereo = false;
  96075. if(encoder->protected_->bits_per_sample >= 32)
  96076. encoder->protected_->do_mid_side_stereo = false; /* since we currenty do 32-bit math, the side channel would have 33 bps and overflow */
  96077. if(encoder->protected_->bits_per_sample < FLAC__MIN_BITS_PER_SAMPLE || encoder->protected_->bits_per_sample > FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE)
  96078. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE;
  96079. if(!FLAC__format_sample_rate_is_valid(encoder->protected_->sample_rate))
  96080. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE;
  96081. if(encoder->protected_->blocksize == 0) {
  96082. if(encoder->protected_->max_lpc_order == 0)
  96083. encoder->protected_->blocksize = 1152;
  96084. else
  96085. encoder->protected_->blocksize = 4096;
  96086. }
  96087. if(encoder->protected_->blocksize < FLAC__MIN_BLOCK_SIZE || encoder->protected_->blocksize > FLAC__MAX_BLOCK_SIZE)
  96088. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE;
  96089. if(encoder->protected_->max_lpc_order > FLAC__MAX_LPC_ORDER)
  96090. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER;
  96091. if(encoder->protected_->blocksize < encoder->protected_->max_lpc_order)
  96092. return FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER;
  96093. if(encoder->protected_->qlp_coeff_precision == 0) {
  96094. if(encoder->protected_->bits_per_sample < 16) {
  96095. /* @@@ need some data about how to set this here w.r.t. blocksize and sample rate */
  96096. /* @@@ until then we'll make a guess */
  96097. encoder->protected_->qlp_coeff_precision = max(FLAC__MIN_QLP_COEFF_PRECISION, 2 + encoder->protected_->bits_per_sample / 2);
  96098. }
  96099. else if(encoder->protected_->bits_per_sample == 16) {
  96100. if(encoder->protected_->blocksize <= 192)
  96101. encoder->protected_->qlp_coeff_precision = 7;
  96102. else if(encoder->protected_->blocksize <= 384)
  96103. encoder->protected_->qlp_coeff_precision = 8;
  96104. else if(encoder->protected_->blocksize <= 576)
  96105. encoder->protected_->qlp_coeff_precision = 9;
  96106. else if(encoder->protected_->blocksize <= 1152)
  96107. encoder->protected_->qlp_coeff_precision = 10;
  96108. else if(encoder->protected_->blocksize <= 2304)
  96109. encoder->protected_->qlp_coeff_precision = 11;
  96110. else if(encoder->protected_->blocksize <= 4608)
  96111. encoder->protected_->qlp_coeff_precision = 12;
  96112. else
  96113. encoder->protected_->qlp_coeff_precision = 13;
  96114. }
  96115. else {
  96116. if(encoder->protected_->blocksize <= 384)
  96117. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-2;
  96118. else if(encoder->protected_->blocksize <= 1152)
  96119. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-1;
  96120. else
  96121. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
  96122. }
  96123. FLAC__ASSERT(encoder->protected_->qlp_coeff_precision <= FLAC__MAX_QLP_COEFF_PRECISION);
  96124. }
  96125. else if(encoder->protected_->qlp_coeff_precision < FLAC__MIN_QLP_COEFF_PRECISION || encoder->protected_->qlp_coeff_precision > FLAC__MAX_QLP_COEFF_PRECISION)
  96126. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION;
  96127. if(encoder->protected_->streamable_subset) {
  96128. if(
  96129. encoder->protected_->blocksize != 192 &&
  96130. encoder->protected_->blocksize != 576 &&
  96131. encoder->protected_->blocksize != 1152 &&
  96132. encoder->protected_->blocksize != 2304 &&
  96133. encoder->protected_->blocksize != 4608 &&
  96134. encoder->protected_->blocksize != 256 &&
  96135. encoder->protected_->blocksize != 512 &&
  96136. encoder->protected_->blocksize != 1024 &&
  96137. encoder->protected_->blocksize != 2048 &&
  96138. encoder->protected_->blocksize != 4096 &&
  96139. encoder->protected_->blocksize != 8192 &&
  96140. encoder->protected_->blocksize != 16384
  96141. )
  96142. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  96143. if(!FLAC__format_sample_rate_is_subset(encoder->protected_->sample_rate))
  96144. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  96145. if(
  96146. encoder->protected_->bits_per_sample != 8 &&
  96147. encoder->protected_->bits_per_sample != 12 &&
  96148. encoder->protected_->bits_per_sample != 16 &&
  96149. encoder->protected_->bits_per_sample != 20 &&
  96150. encoder->protected_->bits_per_sample != 24
  96151. )
  96152. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  96153. if(encoder->protected_->max_residual_partition_order > FLAC__SUBSET_MAX_RICE_PARTITION_ORDER)
  96154. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  96155. if(
  96156. encoder->protected_->sample_rate <= 48000 &&
  96157. (
  96158. encoder->protected_->blocksize > FLAC__SUBSET_MAX_BLOCK_SIZE_48000HZ ||
  96159. encoder->protected_->max_lpc_order > FLAC__SUBSET_MAX_LPC_ORDER_48000HZ
  96160. )
  96161. ) {
  96162. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  96163. }
  96164. }
  96165. if(encoder->protected_->max_residual_partition_order >= (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  96166. encoder->protected_->max_residual_partition_order = (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN) - 1;
  96167. if(encoder->protected_->min_residual_partition_order >= encoder->protected_->max_residual_partition_order)
  96168. encoder->protected_->min_residual_partition_order = encoder->protected_->max_residual_partition_order;
  96169. #if FLAC__HAS_OGG
  96170. /* reorder metadata if necessary to ensure that any VORBIS_COMMENT is the first, according to the mapping spec */
  96171. if(is_ogg && 0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 1) {
  96172. unsigned i;
  96173. for(i = 1; i < encoder->protected_->num_metadata_blocks; i++) {
  96174. if(0 != encoder->protected_->metadata[i] && encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  96175. FLAC__StreamMetadata *vc = encoder->protected_->metadata[i];
  96176. for( ; i > 0; i--)
  96177. encoder->protected_->metadata[i] = encoder->protected_->metadata[i-1];
  96178. encoder->protected_->metadata[0] = vc;
  96179. break;
  96180. }
  96181. }
  96182. }
  96183. #endif
  96184. /* keep track of any SEEKTABLE block */
  96185. if(0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0) {
  96186. unsigned i;
  96187. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  96188. if(0 != encoder->protected_->metadata[i] && encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_SEEKTABLE) {
  96189. encoder->private_->seek_table = &encoder->protected_->metadata[i]->data.seek_table;
  96190. break; /* take only the first one */
  96191. }
  96192. }
  96193. }
  96194. /* validate metadata */
  96195. if(0 == encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0)
  96196. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  96197. metadata_has_seektable = false;
  96198. metadata_has_vorbis_comment = false;
  96199. metadata_picture_has_type1 = false;
  96200. metadata_picture_has_type2 = false;
  96201. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  96202. const FLAC__StreamMetadata *m = encoder->protected_->metadata[i];
  96203. if(m->type == FLAC__METADATA_TYPE_STREAMINFO)
  96204. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  96205. else if(m->type == FLAC__METADATA_TYPE_SEEKTABLE) {
  96206. if(metadata_has_seektable) /* only one is allowed */
  96207. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  96208. metadata_has_seektable = true;
  96209. if(!FLAC__format_seektable_is_legal(&m->data.seek_table))
  96210. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  96211. }
  96212. else if(m->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  96213. if(metadata_has_vorbis_comment) /* only one is allowed */
  96214. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  96215. metadata_has_vorbis_comment = true;
  96216. }
  96217. else if(m->type == FLAC__METADATA_TYPE_CUESHEET) {
  96218. if(!FLAC__format_cuesheet_is_legal(&m->data.cue_sheet, m->data.cue_sheet.is_cd, /*violation=*/0))
  96219. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  96220. }
  96221. else if(m->type == FLAC__METADATA_TYPE_PICTURE) {
  96222. if(!FLAC__format_picture_is_legal(&m->data.picture, /*violation=*/0))
  96223. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  96224. if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD) {
  96225. if(metadata_picture_has_type1) /* there should only be 1 per stream */
  96226. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  96227. metadata_picture_has_type1 = true;
  96228. /* standard icon must be 32x32 pixel PNG */
  96229. if(
  96230. m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD &&
  96231. (
  96232. (strcmp(m->data.picture.mime_type, "image/png") && strcmp(m->data.picture.mime_type, "-->")) ||
  96233. m->data.picture.width != 32 ||
  96234. m->data.picture.height != 32
  96235. )
  96236. )
  96237. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  96238. }
  96239. else if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON) {
  96240. if(metadata_picture_has_type2) /* there should only be 1 per stream */
  96241. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  96242. metadata_picture_has_type2 = true;
  96243. }
  96244. }
  96245. }
  96246. encoder->private_->input_capacity = 0;
  96247. for(i = 0; i < encoder->protected_->channels; i++) {
  96248. encoder->private_->integer_signal_unaligned[i] = encoder->private_->integer_signal[i] = 0;
  96249. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96250. encoder->private_->real_signal_unaligned[i] = encoder->private_->real_signal[i] = 0;
  96251. #endif
  96252. }
  96253. for(i = 0; i < 2; i++) {
  96254. encoder->private_->integer_signal_mid_side_unaligned[i] = encoder->private_->integer_signal_mid_side[i] = 0;
  96255. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96256. encoder->private_->real_signal_mid_side_unaligned[i] = encoder->private_->real_signal_mid_side[i] = 0;
  96257. #endif
  96258. }
  96259. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96260. for(i = 0; i < encoder->protected_->num_apodizations; i++)
  96261. encoder->private_->window_unaligned[i] = encoder->private_->window[i] = 0;
  96262. encoder->private_->windowed_signal_unaligned = encoder->private_->windowed_signal = 0;
  96263. #endif
  96264. for(i = 0; i < encoder->protected_->channels; i++) {
  96265. encoder->private_->residual_workspace_unaligned[i][0] = encoder->private_->residual_workspace[i][0] = 0;
  96266. encoder->private_->residual_workspace_unaligned[i][1] = encoder->private_->residual_workspace[i][1] = 0;
  96267. encoder->private_->best_subframe[i] = 0;
  96268. }
  96269. for(i = 0; i < 2; i++) {
  96270. encoder->private_->residual_workspace_mid_side_unaligned[i][0] = encoder->private_->residual_workspace_mid_side[i][0] = 0;
  96271. encoder->private_->residual_workspace_mid_side_unaligned[i][1] = encoder->private_->residual_workspace_mid_side[i][1] = 0;
  96272. encoder->private_->best_subframe_mid_side[i] = 0;
  96273. }
  96274. encoder->private_->abs_residual_partition_sums_unaligned = encoder->private_->abs_residual_partition_sums = 0;
  96275. encoder->private_->raw_bits_per_partition_unaligned = encoder->private_->raw_bits_per_partition = 0;
  96276. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96277. encoder->private_->loose_mid_side_stereo_frames = (unsigned)((FLAC__double)encoder->protected_->sample_rate * 0.4 / (FLAC__double)encoder->protected_->blocksize + 0.5);
  96278. #else
  96279. /* 26214 is the approximate fixed-point equivalent to 0.4 (0.4 * 2^16) */
  96280. /* sample rate can be up to 655350 Hz, and thus use 20 bits, so we do the multiply&divide by hand */
  96281. FLAC__ASSERT(FLAC__MAX_SAMPLE_RATE <= 655350);
  96282. FLAC__ASSERT(FLAC__MAX_BLOCK_SIZE <= 65535);
  96283. FLAC__ASSERT(encoder->protected_->sample_rate <= 655350);
  96284. FLAC__ASSERT(encoder->protected_->blocksize <= 65535);
  96285. 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);
  96286. #endif
  96287. if(encoder->private_->loose_mid_side_stereo_frames == 0)
  96288. encoder->private_->loose_mid_side_stereo_frames = 1;
  96289. encoder->private_->loose_mid_side_stereo_frame_count = 0;
  96290. encoder->private_->current_sample_number = 0;
  96291. encoder->private_->current_frame_number = 0;
  96292. encoder->private_->use_wide_by_block = (encoder->protected_->bits_per_sample + FLAC__bitmath_ilog2(encoder->protected_->blocksize)+1 > 30);
  96293. 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? */
  96294. encoder->private_->use_wide_by_partition = (false); /*@@@ need to set this */
  96295. /*
  96296. * get the CPU info and set the function pointers
  96297. */
  96298. FLAC__cpu_info(&encoder->private_->cpuinfo);
  96299. /* first default to the non-asm routines */
  96300. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96301. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation;
  96302. #endif
  96303. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor;
  96304. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96305. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients;
  96306. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit = FLAC__lpc_compute_residual_from_qlp_coefficients_wide;
  96307. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients;
  96308. #endif
  96309. /* now override with asm where appropriate */
  96310. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96311. # ifndef FLAC__NO_ASM
  96312. if(encoder->private_->cpuinfo.use_asm) {
  96313. # ifdef FLAC__CPU_IA32
  96314. FLAC__ASSERT(encoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32);
  96315. # ifdef FLAC__HAS_NASM
  96316. if(encoder->private_->cpuinfo.data.ia32.sse) {
  96317. if(encoder->protected_->max_lpc_order < 4)
  96318. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_4;
  96319. else if(encoder->protected_->max_lpc_order < 8)
  96320. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_8;
  96321. else if(encoder->protected_->max_lpc_order < 12)
  96322. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_12;
  96323. else
  96324. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
  96325. }
  96326. else if(encoder->private_->cpuinfo.data.ia32._3dnow)
  96327. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_3dnow;
  96328. else
  96329. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
  96330. if(encoder->private_->cpuinfo.data.ia32.mmx) {
  96331. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  96332. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx;
  96333. }
  96334. else {
  96335. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  96336. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  96337. }
  96338. if(encoder->private_->cpuinfo.data.ia32.mmx && encoder->private_->cpuinfo.data.ia32.cmov)
  96339. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_asm_ia32_mmx_cmov;
  96340. # endif /* FLAC__HAS_NASM */
  96341. # endif /* FLAC__CPU_IA32 */
  96342. }
  96343. # endif /* !FLAC__NO_ASM */
  96344. #endif /* !FLAC__INTEGER_ONLY_LIBRARY */
  96345. /* finally override based on wide-ness if necessary */
  96346. if(encoder->private_->use_wide_by_block) {
  96347. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_wide;
  96348. }
  96349. /* set state to OK; from here on, errors are fatal and we'll override the state then */
  96350. encoder->protected_->state = FLAC__STREAM_ENCODER_OK;
  96351. #if FLAC__HAS_OGG
  96352. encoder->private_->is_ogg = is_ogg;
  96353. if(is_ogg && !FLAC__ogg_encoder_aspect_init(&encoder->protected_->ogg_encoder_aspect)) {
  96354. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  96355. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  96356. }
  96357. #endif
  96358. encoder->private_->read_callback = read_callback;
  96359. encoder->private_->write_callback = write_callback;
  96360. encoder->private_->seek_callback = seek_callback;
  96361. encoder->private_->tell_callback = tell_callback;
  96362. encoder->private_->metadata_callback = metadata_callback;
  96363. encoder->private_->client_data = client_data;
  96364. if(!resize_buffers_(encoder, encoder->protected_->blocksize)) {
  96365. /* the above function sets the state for us in case of an error */
  96366. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  96367. }
  96368. if(!FLAC__bitwriter_init(encoder->private_->frame)) {
  96369. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  96370. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  96371. }
  96372. /*
  96373. * Set up the verify stuff if necessary
  96374. */
  96375. if(encoder->protected_->verify) {
  96376. /*
  96377. * First, set up the fifo which will hold the
  96378. * original signal to compare against
  96379. */
  96380. encoder->private_->verify.input_fifo.size = encoder->protected_->blocksize+OVERREAD_;
  96381. for(i = 0; i < encoder->protected_->channels; i++) {
  96382. 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))) {
  96383. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  96384. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  96385. }
  96386. }
  96387. encoder->private_->verify.input_fifo.tail = 0;
  96388. /*
  96389. * Now set up a stream decoder for verification
  96390. */
  96391. encoder->private_->verify.decoder = FLAC__stream_decoder_new();
  96392. if(0 == encoder->private_->verify.decoder) {
  96393. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  96394. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  96395. }
  96396. 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) {
  96397. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  96398. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  96399. }
  96400. }
  96401. encoder->private_->verify.error_stats.absolute_sample = 0;
  96402. encoder->private_->verify.error_stats.frame_number = 0;
  96403. encoder->private_->verify.error_stats.channel = 0;
  96404. encoder->private_->verify.error_stats.sample = 0;
  96405. encoder->private_->verify.error_stats.expected = 0;
  96406. encoder->private_->verify.error_stats.got = 0;
  96407. /*
  96408. * These must be done before we write any metadata, because that
  96409. * calls the write_callback, which uses these values.
  96410. */
  96411. encoder->private_->first_seekpoint_to_check = 0;
  96412. encoder->private_->samples_written = 0;
  96413. encoder->protected_->streaminfo_offset = 0;
  96414. encoder->protected_->seektable_offset = 0;
  96415. encoder->protected_->audio_offset = 0;
  96416. /*
  96417. * write the stream header
  96418. */
  96419. if(encoder->protected_->verify)
  96420. encoder->private_->verify.state_hint = ENCODER_IN_MAGIC;
  96421. if(!FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, FLAC__STREAM_SYNC, FLAC__STREAM_SYNC_LEN)) {
  96422. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  96423. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  96424. }
  96425. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  96426. /* the above function sets the state for us in case of an error */
  96427. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  96428. }
  96429. /*
  96430. * write the STREAMINFO metadata block
  96431. */
  96432. if(encoder->protected_->verify)
  96433. encoder->private_->verify.state_hint = ENCODER_IN_METADATA;
  96434. encoder->private_->streaminfo.type = FLAC__METADATA_TYPE_STREAMINFO;
  96435. encoder->private_->streaminfo.is_last = false; /* we will have at a minimum a VORBIS_COMMENT afterwards */
  96436. encoder->private_->streaminfo.length = FLAC__STREAM_METADATA_STREAMINFO_LENGTH;
  96437. encoder->private_->streaminfo.data.stream_info.min_blocksize = encoder->protected_->blocksize; /* this encoder uses the same blocksize for the whole stream */
  96438. encoder->private_->streaminfo.data.stream_info.max_blocksize = encoder->protected_->blocksize;
  96439. encoder->private_->streaminfo.data.stream_info.min_framesize = 0; /* we don't know this yet; have to fill it in later */
  96440. encoder->private_->streaminfo.data.stream_info.max_framesize = 0; /* we don't know this yet; have to fill it in later */
  96441. encoder->private_->streaminfo.data.stream_info.sample_rate = encoder->protected_->sample_rate;
  96442. encoder->private_->streaminfo.data.stream_info.channels = encoder->protected_->channels;
  96443. encoder->private_->streaminfo.data.stream_info.bits_per_sample = encoder->protected_->bits_per_sample;
  96444. encoder->private_->streaminfo.data.stream_info.total_samples = encoder->protected_->total_samples_estimate; /* we will replace this later with the real total */
  96445. memset(encoder->private_->streaminfo.data.stream_info.md5sum, 0, 16); /* we don't know this yet; have to fill it in later */
  96446. if(encoder->protected_->do_md5)
  96447. FLAC__MD5Init(&encoder->private_->md5context);
  96448. if(!FLAC__add_metadata_block(&encoder->private_->streaminfo, encoder->private_->frame)) {
  96449. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  96450. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  96451. }
  96452. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  96453. /* the above function sets the state for us in case of an error */
  96454. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  96455. }
  96456. /*
  96457. * Now that the STREAMINFO block is written, we can init this to an
  96458. * absurdly-high value...
  96459. */
  96460. encoder->private_->streaminfo.data.stream_info.min_framesize = (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN) - 1;
  96461. /* ... and clear this to 0 */
  96462. encoder->private_->streaminfo.data.stream_info.total_samples = 0;
  96463. /*
  96464. * Check to see if the supplied metadata contains a VORBIS_COMMENT;
  96465. * if not, we will write an empty one (FLAC__add_metadata_block()
  96466. * automatically supplies the vendor string).
  96467. *
  96468. * WATCHOUT: the Ogg FLAC mapping requires us to write this block after
  96469. * the STREAMINFO. (In the case that metadata_has_vorbis_comment is
  96470. * true it will have already insured that the metadata list is properly
  96471. * ordered.)
  96472. */
  96473. if(!metadata_has_vorbis_comment) {
  96474. FLAC__StreamMetadata vorbis_comment;
  96475. vorbis_comment.type = FLAC__METADATA_TYPE_VORBIS_COMMENT;
  96476. vorbis_comment.is_last = (encoder->protected_->num_metadata_blocks == 0);
  96477. vorbis_comment.length = 4 + 4; /* MAGIC NUMBER */
  96478. vorbis_comment.data.vorbis_comment.vendor_string.length = 0;
  96479. vorbis_comment.data.vorbis_comment.vendor_string.entry = 0;
  96480. vorbis_comment.data.vorbis_comment.num_comments = 0;
  96481. vorbis_comment.data.vorbis_comment.comments = 0;
  96482. if(!FLAC__add_metadata_block(&vorbis_comment, 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. /*
  96492. * write the user's metadata blocks
  96493. */
  96494. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  96495. encoder->protected_->metadata[i]->is_last = (i == encoder->protected_->num_metadata_blocks - 1);
  96496. if(!FLAC__add_metadata_block(encoder->protected_->metadata[i], encoder->private_->frame)) {
  96497. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  96498. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  96499. }
  96500. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  96501. /* the above function sets the state for us in case of an error */
  96502. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  96503. }
  96504. }
  96505. /* now that all the metadata is written, we save the stream offset */
  96506. 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 */
  96507. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  96508. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  96509. }
  96510. if(encoder->protected_->verify)
  96511. encoder->private_->verify.state_hint = ENCODER_IN_AUDIO;
  96512. return FLAC__STREAM_ENCODER_INIT_STATUS_OK;
  96513. }
  96514. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_stream(
  96515. FLAC__StreamEncoder *encoder,
  96516. FLAC__StreamEncoderWriteCallback write_callback,
  96517. FLAC__StreamEncoderSeekCallback seek_callback,
  96518. FLAC__StreamEncoderTellCallback tell_callback,
  96519. FLAC__StreamEncoderMetadataCallback metadata_callback,
  96520. void *client_data
  96521. )
  96522. {
  96523. return init_stream_internal_enc(
  96524. encoder,
  96525. /*read_callback=*/0,
  96526. write_callback,
  96527. seek_callback,
  96528. tell_callback,
  96529. metadata_callback,
  96530. client_data,
  96531. /*is_ogg=*/false
  96532. );
  96533. }
  96534. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_stream(
  96535. FLAC__StreamEncoder *encoder,
  96536. FLAC__StreamEncoderReadCallback read_callback,
  96537. FLAC__StreamEncoderWriteCallback write_callback,
  96538. FLAC__StreamEncoderSeekCallback seek_callback,
  96539. FLAC__StreamEncoderTellCallback tell_callback,
  96540. FLAC__StreamEncoderMetadataCallback metadata_callback,
  96541. void *client_data
  96542. )
  96543. {
  96544. return init_stream_internal_enc(
  96545. encoder,
  96546. read_callback,
  96547. write_callback,
  96548. seek_callback,
  96549. tell_callback,
  96550. metadata_callback,
  96551. client_data,
  96552. /*is_ogg=*/true
  96553. );
  96554. }
  96555. static FLAC__StreamEncoderInitStatus init_FILE_internal_enc(
  96556. FLAC__StreamEncoder *encoder,
  96557. FILE *file,
  96558. FLAC__StreamEncoderProgressCallback progress_callback,
  96559. void *client_data,
  96560. FLAC__bool is_ogg
  96561. )
  96562. {
  96563. FLAC__StreamEncoderInitStatus init_status;
  96564. FLAC__ASSERT(0 != encoder);
  96565. FLAC__ASSERT(0 != file);
  96566. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  96567. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  96568. /* double protection */
  96569. if(file == 0) {
  96570. encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
  96571. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  96572. }
  96573. /*
  96574. * To make sure that our file does not go unclosed after an error, we
  96575. * must assign the FILE pointer before any further error can occur in
  96576. * this routine.
  96577. */
  96578. if(file == stdout)
  96579. file = get_binary_stdout_(); /* just to be safe */
  96580. encoder->private_->file = file;
  96581. encoder->private_->progress_callback = progress_callback;
  96582. encoder->private_->bytes_written = 0;
  96583. encoder->private_->samples_written = 0;
  96584. encoder->private_->frames_written = 0;
  96585. init_status = init_stream_internal_enc(
  96586. encoder,
  96587. encoder->private_->file == stdout? 0 : is_ogg? file_read_callback_enc : 0,
  96588. file_write_callback_,
  96589. encoder->private_->file == stdout? 0 : file_seek_callback_enc,
  96590. encoder->private_->file == stdout? 0 : file_tell_callback_enc,
  96591. /*metadata_callback=*/0,
  96592. client_data,
  96593. is_ogg
  96594. );
  96595. if(init_status != FLAC__STREAM_ENCODER_INIT_STATUS_OK) {
  96596. /* the above function sets the state for us in case of an error */
  96597. return init_status;
  96598. }
  96599. {
  96600. unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
  96601. FLAC__ASSERT(blocksize != 0);
  96602. encoder->private_->total_frames_estimate = (unsigned)((FLAC__stream_encoder_get_total_samples_estimate(encoder) + blocksize - 1) / blocksize);
  96603. }
  96604. return init_status;
  96605. }
  96606. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_FILE(
  96607. FLAC__StreamEncoder *encoder,
  96608. FILE *file,
  96609. FLAC__StreamEncoderProgressCallback progress_callback,
  96610. void *client_data
  96611. )
  96612. {
  96613. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, /*is_ogg=*/false);
  96614. }
  96615. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_FILE(
  96616. FLAC__StreamEncoder *encoder,
  96617. FILE *file,
  96618. FLAC__StreamEncoderProgressCallback progress_callback,
  96619. void *client_data
  96620. )
  96621. {
  96622. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, /*is_ogg=*/true);
  96623. }
  96624. static FLAC__StreamEncoderInitStatus init_file_internal_enc(
  96625. FLAC__StreamEncoder *encoder,
  96626. const char *filename,
  96627. FLAC__StreamEncoderProgressCallback progress_callback,
  96628. void *client_data,
  96629. FLAC__bool is_ogg
  96630. )
  96631. {
  96632. FILE *file;
  96633. FLAC__ASSERT(0 != encoder);
  96634. /*
  96635. * To make sure that our file does not go unclosed after an error, we
  96636. * have to do the same entrance checks here that are later performed
  96637. * in FLAC__stream_encoder_init_FILE() before the FILE* is assigned.
  96638. */
  96639. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  96640. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  96641. file = filename? fopen(filename, "w+b") : stdout;
  96642. if(file == 0) {
  96643. encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
  96644. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  96645. }
  96646. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, is_ogg);
  96647. }
  96648. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_file(
  96649. FLAC__StreamEncoder *encoder,
  96650. const char *filename,
  96651. FLAC__StreamEncoderProgressCallback progress_callback,
  96652. void *client_data
  96653. )
  96654. {
  96655. return init_file_internal_enc(encoder, filename, progress_callback, client_data, /*is_ogg=*/false);
  96656. }
  96657. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_file(
  96658. FLAC__StreamEncoder *encoder,
  96659. const char *filename,
  96660. FLAC__StreamEncoderProgressCallback progress_callback,
  96661. void *client_data
  96662. )
  96663. {
  96664. return init_file_internal_enc(encoder, filename, progress_callback, client_data, /*is_ogg=*/true);
  96665. }
  96666. FLAC_API FLAC__bool FLAC__stream_encoder_finish(FLAC__StreamEncoder *encoder)
  96667. {
  96668. FLAC__bool error = false;
  96669. FLAC__ASSERT(0 != encoder);
  96670. FLAC__ASSERT(0 != encoder->private_);
  96671. FLAC__ASSERT(0 != encoder->protected_);
  96672. if(encoder->protected_->state == FLAC__STREAM_ENCODER_UNINITIALIZED)
  96673. return true;
  96674. if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK && !encoder->private_->is_being_deleted) {
  96675. if(encoder->private_->current_sample_number != 0) {
  96676. const FLAC__bool is_fractional_block = encoder->protected_->blocksize != encoder->private_->current_sample_number;
  96677. encoder->protected_->blocksize = encoder->private_->current_sample_number;
  96678. if(!process_frame_(encoder, is_fractional_block, /*is_last_block=*/true))
  96679. error = true;
  96680. }
  96681. }
  96682. if(encoder->protected_->do_md5)
  96683. FLAC__MD5Final(encoder->private_->streaminfo.data.stream_info.md5sum, &encoder->private_->md5context);
  96684. if(!encoder->private_->is_being_deleted) {
  96685. if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK) {
  96686. if(encoder->private_->seek_callback) {
  96687. #if FLAC__HAS_OGG
  96688. if(encoder->private_->is_ogg)
  96689. update_ogg_metadata_(encoder);
  96690. else
  96691. #endif
  96692. update_metadata_(encoder);
  96693. /* check if an error occurred while updating metadata */
  96694. if(encoder->protected_->state != FLAC__STREAM_ENCODER_OK)
  96695. error = true;
  96696. }
  96697. if(encoder->private_->metadata_callback)
  96698. encoder->private_->metadata_callback(encoder, &encoder->private_->streaminfo, encoder->private_->client_data);
  96699. }
  96700. if(encoder->protected_->verify && 0 != encoder->private_->verify.decoder && !FLAC__stream_decoder_finish(encoder->private_->verify.decoder)) {
  96701. if(!error)
  96702. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
  96703. error = true;
  96704. }
  96705. }
  96706. if(0 != encoder->private_->file) {
  96707. if(encoder->private_->file != stdout)
  96708. fclose(encoder->private_->file);
  96709. encoder->private_->file = 0;
  96710. }
  96711. #if FLAC__HAS_OGG
  96712. if(encoder->private_->is_ogg)
  96713. FLAC__ogg_encoder_aspect_finish(&encoder->protected_->ogg_encoder_aspect);
  96714. #endif
  96715. free_(encoder);
  96716. set_defaults_enc(encoder);
  96717. if(!error)
  96718. encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
  96719. return !error;
  96720. }
  96721. FLAC_API FLAC__bool FLAC__stream_encoder_set_ogg_serial_number(FLAC__StreamEncoder *encoder, long value)
  96722. {
  96723. FLAC__ASSERT(0 != encoder);
  96724. FLAC__ASSERT(0 != encoder->private_);
  96725. FLAC__ASSERT(0 != encoder->protected_);
  96726. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  96727. return false;
  96728. #if FLAC__HAS_OGG
  96729. /* can't check encoder->private_->is_ogg since that's not set until init time */
  96730. FLAC__ogg_encoder_aspect_set_serial_number(&encoder->protected_->ogg_encoder_aspect, value);
  96731. return true;
  96732. #else
  96733. (void)value;
  96734. return false;
  96735. #endif
  96736. }
  96737. FLAC_API FLAC__bool FLAC__stream_encoder_set_verify(FLAC__StreamEncoder *encoder, FLAC__bool value)
  96738. {
  96739. FLAC__ASSERT(0 != encoder);
  96740. FLAC__ASSERT(0 != encoder->private_);
  96741. FLAC__ASSERT(0 != encoder->protected_);
  96742. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  96743. return false;
  96744. #ifndef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
  96745. encoder->protected_->verify = value;
  96746. #endif
  96747. return true;
  96748. }
  96749. FLAC_API FLAC__bool FLAC__stream_encoder_set_streamable_subset(FLAC__StreamEncoder *encoder, FLAC__bool value)
  96750. {
  96751. FLAC__ASSERT(0 != encoder);
  96752. FLAC__ASSERT(0 != encoder->private_);
  96753. FLAC__ASSERT(0 != encoder->protected_);
  96754. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  96755. return false;
  96756. encoder->protected_->streamable_subset = value;
  96757. return true;
  96758. }
  96759. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_md5(FLAC__StreamEncoder *encoder, FLAC__bool value)
  96760. {
  96761. FLAC__ASSERT(0 != encoder);
  96762. FLAC__ASSERT(0 != encoder->private_);
  96763. FLAC__ASSERT(0 != encoder->protected_);
  96764. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  96765. return false;
  96766. encoder->protected_->do_md5 = value;
  96767. return true;
  96768. }
  96769. FLAC_API FLAC__bool FLAC__stream_encoder_set_channels(FLAC__StreamEncoder *encoder, unsigned value)
  96770. {
  96771. FLAC__ASSERT(0 != encoder);
  96772. FLAC__ASSERT(0 != encoder->private_);
  96773. FLAC__ASSERT(0 != encoder->protected_);
  96774. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  96775. return false;
  96776. encoder->protected_->channels = value;
  96777. return true;
  96778. }
  96779. FLAC_API FLAC__bool FLAC__stream_encoder_set_bits_per_sample(FLAC__StreamEncoder *encoder, unsigned value)
  96780. {
  96781. FLAC__ASSERT(0 != encoder);
  96782. FLAC__ASSERT(0 != encoder->private_);
  96783. FLAC__ASSERT(0 != encoder->protected_);
  96784. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  96785. return false;
  96786. encoder->protected_->bits_per_sample = value;
  96787. return true;
  96788. }
  96789. FLAC_API FLAC__bool FLAC__stream_encoder_set_sample_rate(FLAC__StreamEncoder *encoder, unsigned value)
  96790. {
  96791. FLAC__ASSERT(0 != encoder);
  96792. FLAC__ASSERT(0 != encoder->private_);
  96793. FLAC__ASSERT(0 != encoder->protected_);
  96794. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  96795. return false;
  96796. encoder->protected_->sample_rate = value;
  96797. return true;
  96798. }
  96799. FLAC_API FLAC__bool FLAC__stream_encoder_set_compression_level(FLAC__StreamEncoder *encoder, unsigned value)
  96800. {
  96801. FLAC__bool ok = true;
  96802. FLAC__ASSERT(0 != encoder);
  96803. FLAC__ASSERT(0 != encoder->private_);
  96804. FLAC__ASSERT(0 != encoder->protected_);
  96805. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  96806. return false;
  96807. if(value >= sizeof(compression_levels_)/sizeof(compression_levels_[0]))
  96808. value = sizeof(compression_levels_)/sizeof(compression_levels_[0]) - 1;
  96809. ok &= FLAC__stream_encoder_set_do_mid_side_stereo (encoder, compression_levels_[value].do_mid_side_stereo);
  96810. ok &= FLAC__stream_encoder_set_loose_mid_side_stereo (encoder, compression_levels_[value].loose_mid_side_stereo);
  96811. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96812. #if 0
  96813. /* was: */
  96814. ok &= FLAC__stream_encoder_set_apodization (encoder, compression_levels_[value].apodization);
  96815. /* but it's too hard to specify the string in a locale-specific way */
  96816. #else
  96817. encoder->protected_->num_apodizations = 1;
  96818. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  96819. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  96820. #endif
  96821. #endif
  96822. ok &= FLAC__stream_encoder_set_max_lpc_order (encoder, compression_levels_[value].max_lpc_order);
  96823. ok &= FLAC__stream_encoder_set_qlp_coeff_precision (encoder, compression_levels_[value].qlp_coeff_precision);
  96824. ok &= FLAC__stream_encoder_set_do_qlp_coeff_prec_search (encoder, compression_levels_[value].do_qlp_coeff_prec_search);
  96825. ok &= FLAC__stream_encoder_set_do_escape_coding (encoder, compression_levels_[value].do_escape_coding);
  96826. ok &= FLAC__stream_encoder_set_do_exhaustive_model_search (encoder, compression_levels_[value].do_exhaustive_model_search);
  96827. ok &= FLAC__stream_encoder_set_min_residual_partition_order(encoder, compression_levels_[value].min_residual_partition_order);
  96828. ok &= FLAC__stream_encoder_set_max_residual_partition_order(encoder, compression_levels_[value].max_residual_partition_order);
  96829. ok &= FLAC__stream_encoder_set_rice_parameter_search_dist (encoder, compression_levels_[value].rice_parameter_search_dist);
  96830. return ok;
  96831. }
  96832. FLAC_API FLAC__bool FLAC__stream_encoder_set_blocksize(FLAC__StreamEncoder *encoder, unsigned value)
  96833. {
  96834. FLAC__ASSERT(0 != encoder);
  96835. FLAC__ASSERT(0 != encoder->private_);
  96836. FLAC__ASSERT(0 != encoder->protected_);
  96837. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  96838. return false;
  96839. encoder->protected_->blocksize = value;
  96840. return true;
  96841. }
  96842. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
  96843. {
  96844. FLAC__ASSERT(0 != encoder);
  96845. FLAC__ASSERT(0 != encoder->private_);
  96846. FLAC__ASSERT(0 != encoder->protected_);
  96847. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  96848. return false;
  96849. encoder->protected_->do_mid_side_stereo = value;
  96850. return true;
  96851. }
  96852. FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
  96853. {
  96854. FLAC__ASSERT(0 != encoder);
  96855. FLAC__ASSERT(0 != encoder->private_);
  96856. FLAC__ASSERT(0 != encoder->protected_);
  96857. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  96858. return false;
  96859. encoder->protected_->loose_mid_side_stereo = value;
  96860. return true;
  96861. }
  96862. /*@@@@add to tests*/
  96863. FLAC_API FLAC__bool FLAC__stream_encoder_set_apodization(FLAC__StreamEncoder *encoder, const char *specification)
  96864. {
  96865. FLAC__ASSERT(0 != encoder);
  96866. FLAC__ASSERT(0 != encoder->private_);
  96867. FLAC__ASSERT(0 != encoder->protected_);
  96868. FLAC__ASSERT(0 != specification);
  96869. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  96870. return false;
  96871. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  96872. (void)specification; /* silently ignore since we haven't integerized; will always use a rectangular window */
  96873. #else
  96874. encoder->protected_->num_apodizations = 0;
  96875. while(1) {
  96876. const char *s = strchr(specification, ';');
  96877. const size_t n = s? (size_t)(s - specification) : strlen(specification);
  96878. if (n==8 && 0 == strncmp("bartlett" , specification, n))
  96879. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT;
  96880. else if(n==13 && 0 == strncmp("bartlett_hann", specification, n))
  96881. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT_HANN;
  96882. else if(n==8 && 0 == strncmp("blackman" , specification, n))
  96883. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN;
  96884. else if(n==26 && 0 == strncmp("blackman_harris_4term_92db", specification, n))
  96885. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE;
  96886. else if(n==6 && 0 == strncmp("connes" , specification, n))
  96887. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_CONNES;
  96888. else if(n==7 && 0 == strncmp("flattop" , specification, n))
  96889. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_FLATTOP;
  96890. else if(n>7 && 0 == strncmp("gauss(" , specification, 6)) {
  96891. FLAC__real stddev = (FLAC__real)strtod(specification+6, 0);
  96892. if (stddev > 0.0 && stddev <= 0.5) {
  96893. encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.gauss.stddev = stddev;
  96894. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_GAUSS;
  96895. }
  96896. }
  96897. else if(n==7 && 0 == strncmp("hamming" , specification, n))
  96898. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HAMMING;
  96899. else if(n==4 && 0 == strncmp("hann" , specification, n))
  96900. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HANN;
  96901. else if(n==13 && 0 == strncmp("kaiser_bessel", specification, n))
  96902. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_KAISER_BESSEL;
  96903. else if(n==7 && 0 == strncmp("nuttall" , specification, n))
  96904. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_NUTTALL;
  96905. else if(n==9 && 0 == strncmp("rectangle" , specification, n))
  96906. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_RECTANGLE;
  96907. else if(n==8 && 0 == strncmp("triangle" , specification, n))
  96908. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TRIANGLE;
  96909. else if(n>7 && 0 == strncmp("tukey(" , specification, 6)) {
  96910. FLAC__real p = (FLAC__real)strtod(specification+6, 0);
  96911. if (p >= 0.0 && p <= 1.0) {
  96912. encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.tukey.p = p;
  96913. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TUKEY;
  96914. }
  96915. }
  96916. else if(n==5 && 0 == strncmp("welch" , specification, n))
  96917. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_WELCH;
  96918. if (encoder->protected_->num_apodizations == 32)
  96919. break;
  96920. if (s)
  96921. specification = s+1;
  96922. else
  96923. break;
  96924. }
  96925. if(encoder->protected_->num_apodizations == 0) {
  96926. encoder->protected_->num_apodizations = 1;
  96927. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  96928. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  96929. }
  96930. #endif
  96931. return true;
  96932. }
  96933. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_lpc_order(FLAC__StreamEncoder *encoder, unsigned value)
  96934. {
  96935. FLAC__ASSERT(0 != encoder);
  96936. FLAC__ASSERT(0 != encoder->private_);
  96937. FLAC__ASSERT(0 != encoder->protected_);
  96938. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  96939. return false;
  96940. encoder->protected_->max_lpc_order = value;
  96941. return true;
  96942. }
  96943. FLAC_API FLAC__bool FLAC__stream_encoder_set_qlp_coeff_precision(FLAC__StreamEncoder *encoder, unsigned value)
  96944. {
  96945. FLAC__ASSERT(0 != encoder);
  96946. FLAC__ASSERT(0 != encoder->private_);
  96947. FLAC__ASSERT(0 != encoder->protected_);
  96948. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  96949. return false;
  96950. encoder->protected_->qlp_coeff_precision = value;
  96951. return true;
  96952. }
  96953. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_qlp_coeff_prec_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
  96954. {
  96955. FLAC__ASSERT(0 != encoder);
  96956. FLAC__ASSERT(0 != encoder->private_);
  96957. FLAC__ASSERT(0 != encoder->protected_);
  96958. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  96959. return false;
  96960. encoder->protected_->do_qlp_coeff_prec_search = value;
  96961. return true;
  96962. }
  96963. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_escape_coding(FLAC__StreamEncoder *encoder, FLAC__bool value)
  96964. {
  96965. FLAC__ASSERT(0 != encoder);
  96966. FLAC__ASSERT(0 != encoder->private_);
  96967. FLAC__ASSERT(0 != encoder->protected_);
  96968. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  96969. return false;
  96970. #if 0
  96971. /*@@@ deprecated: */
  96972. encoder->protected_->do_escape_coding = value;
  96973. #else
  96974. (void)value;
  96975. #endif
  96976. return true;
  96977. }
  96978. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_exhaustive_model_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
  96979. {
  96980. FLAC__ASSERT(0 != encoder);
  96981. FLAC__ASSERT(0 != encoder->private_);
  96982. FLAC__ASSERT(0 != encoder->protected_);
  96983. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  96984. return false;
  96985. encoder->protected_->do_exhaustive_model_search = value;
  96986. return true;
  96987. }
  96988. FLAC_API FLAC__bool FLAC__stream_encoder_set_min_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
  96989. {
  96990. FLAC__ASSERT(0 != encoder);
  96991. FLAC__ASSERT(0 != encoder->private_);
  96992. FLAC__ASSERT(0 != encoder->protected_);
  96993. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  96994. return false;
  96995. encoder->protected_->min_residual_partition_order = value;
  96996. return true;
  96997. }
  96998. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
  96999. {
  97000. FLAC__ASSERT(0 != encoder);
  97001. FLAC__ASSERT(0 != encoder->private_);
  97002. FLAC__ASSERT(0 != encoder->protected_);
  97003. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  97004. return false;
  97005. encoder->protected_->max_residual_partition_order = value;
  97006. return true;
  97007. }
  97008. FLAC_API FLAC__bool FLAC__stream_encoder_set_rice_parameter_search_dist(FLAC__StreamEncoder *encoder, unsigned value)
  97009. {
  97010. FLAC__ASSERT(0 != encoder);
  97011. FLAC__ASSERT(0 != encoder->private_);
  97012. FLAC__ASSERT(0 != encoder->protected_);
  97013. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  97014. return false;
  97015. #if 0
  97016. /*@@@ deprecated: */
  97017. encoder->protected_->rice_parameter_search_dist = value;
  97018. #else
  97019. (void)value;
  97020. #endif
  97021. return true;
  97022. }
  97023. FLAC_API FLAC__bool FLAC__stream_encoder_set_total_samples_estimate(FLAC__StreamEncoder *encoder, FLAC__uint64 value)
  97024. {
  97025. FLAC__ASSERT(0 != encoder);
  97026. FLAC__ASSERT(0 != encoder->private_);
  97027. FLAC__ASSERT(0 != encoder->protected_);
  97028. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  97029. return false;
  97030. encoder->protected_->total_samples_estimate = value;
  97031. return true;
  97032. }
  97033. FLAC_API FLAC__bool FLAC__stream_encoder_set_metadata(FLAC__StreamEncoder *encoder, FLAC__StreamMetadata **metadata, unsigned num_blocks)
  97034. {
  97035. FLAC__ASSERT(0 != encoder);
  97036. FLAC__ASSERT(0 != encoder->private_);
  97037. FLAC__ASSERT(0 != encoder->protected_);
  97038. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  97039. return false;
  97040. if(0 == metadata)
  97041. num_blocks = 0;
  97042. if(0 == num_blocks)
  97043. metadata = 0;
  97044. /* realloc() does not do exactly what we want so... */
  97045. if(encoder->protected_->metadata) {
  97046. free(encoder->protected_->metadata);
  97047. encoder->protected_->metadata = 0;
  97048. encoder->protected_->num_metadata_blocks = 0;
  97049. }
  97050. if(num_blocks) {
  97051. FLAC__StreamMetadata **m;
  97052. if(0 == (m = (FLAC__StreamMetadata**)safe_malloc_mul_2op_(sizeof(m[0]), /*times*/num_blocks)))
  97053. return false;
  97054. memcpy(m, metadata, sizeof(m[0]) * num_blocks);
  97055. encoder->protected_->metadata = m;
  97056. encoder->protected_->num_metadata_blocks = num_blocks;
  97057. }
  97058. #if FLAC__HAS_OGG
  97059. if(!FLAC__ogg_encoder_aspect_set_num_metadata(&encoder->protected_->ogg_encoder_aspect, num_blocks))
  97060. return false;
  97061. #endif
  97062. return true;
  97063. }
  97064. /*
  97065. * These three functions are not static, but not publically exposed in
  97066. * include/FLAC/ either. They are used by the test suite.
  97067. */
  97068. FLAC_API FLAC__bool FLAC__stream_encoder_disable_constant_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  97069. {
  97070. FLAC__ASSERT(0 != encoder);
  97071. FLAC__ASSERT(0 != encoder->private_);
  97072. FLAC__ASSERT(0 != encoder->protected_);
  97073. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  97074. return false;
  97075. encoder->private_->disable_constant_subframes = value;
  97076. return true;
  97077. }
  97078. FLAC_API FLAC__bool FLAC__stream_encoder_disable_fixed_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  97079. {
  97080. FLAC__ASSERT(0 != encoder);
  97081. FLAC__ASSERT(0 != encoder->private_);
  97082. FLAC__ASSERT(0 != encoder->protected_);
  97083. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  97084. return false;
  97085. encoder->private_->disable_fixed_subframes = value;
  97086. return true;
  97087. }
  97088. FLAC_API FLAC__bool FLAC__stream_encoder_disable_verbatim_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  97089. {
  97090. FLAC__ASSERT(0 != encoder);
  97091. FLAC__ASSERT(0 != encoder->private_);
  97092. FLAC__ASSERT(0 != encoder->protected_);
  97093. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  97094. return false;
  97095. encoder->private_->disable_verbatim_subframes = value;
  97096. return true;
  97097. }
  97098. FLAC_API FLAC__StreamEncoderState FLAC__stream_encoder_get_state(const FLAC__StreamEncoder *encoder)
  97099. {
  97100. FLAC__ASSERT(0 != encoder);
  97101. FLAC__ASSERT(0 != encoder->private_);
  97102. FLAC__ASSERT(0 != encoder->protected_);
  97103. return encoder->protected_->state;
  97104. }
  97105. FLAC_API FLAC__StreamDecoderState FLAC__stream_encoder_get_verify_decoder_state(const FLAC__StreamEncoder *encoder)
  97106. {
  97107. FLAC__ASSERT(0 != encoder);
  97108. FLAC__ASSERT(0 != encoder->private_);
  97109. FLAC__ASSERT(0 != encoder->protected_);
  97110. if(encoder->protected_->verify)
  97111. return FLAC__stream_decoder_get_state(encoder->private_->verify.decoder);
  97112. else
  97113. return FLAC__STREAM_DECODER_UNINITIALIZED;
  97114. }
  97115. FLAC_API const char *FLAC__stream_encoder_get_resolved_state_string(const FLAC__StreamEncoder *encoder)
  97116. {
  97117. FLAC__ASSERT(0 != encoder);
  97118. FLAC__ASSERT(0 != encoder->private_);
  97119. FLAC__ASSERT(0 != encoder->protected_);
  97120. if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR)
  97121. return FLAC__StreamEncoderStateString[encoder->protected_->state];
  97122. else
  97123. return FLAC__stream_decoder_get_resolved_state_string(encoder->private_->verify.decoder);
  97124. }
  97125. 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)
  97126. {
  97127. FLAC__ASSERT(0 != encoder);
  97128. FLAC__ASSERT(0 != encoder->private_);
  97129. FLAC__ASSERT(0 != encoder->protected_);
  97130. if(0 != absolute_sample)
  97131. *absolute_sample = encoder->private_->verify.error_stats.absolute_sample;
  97132. if(0 != frame_number)
  97133. *frame_number = encoder->private_->verify.error_stats.frame_number;
  97134. if(0 != channel)
  97135. *channel = encoder->private_->verify.error_stats.channel;
  97136. if(0 != sample)
  97137. *sample = encoder->private_->verify.error_stats.sample;
  97138. if(0 != expected)
  97139. *expected = encoder->private_->verify.error_stats.expected;
  97140. if(0 != got)
  97141. *got = encoder->private_->verify.error_stats.got;
  97142. }
  97143. FLAC_API FLAC__bool FLAC__stream_encoder_get_verify(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_->verify;
  97149. }
  97150. FLAC_API FLAC__bool FLAC__stream_encoder_get_streamable_subset(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_->streamable_subset;
  97156. }
  97157. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_md5(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_->do_md5;
  97163. }
  97164. FLAC_API unsigned FLAC__stream_encoder_get_channels(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_->channels;
  97170. }
  97171. FLAC_API unsigned FLAC__stream_encoder_get_bits_per_sample(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_->bits_per_sample;
  97177. }
  97178. FLAC_API unsigned FLAC__stream_encoder_get_sample_rate(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_->sample_rate;
  97184. }
  97185. FLAC_API unsigned FLAC__stream_encoder_get_blocksize(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_->blocksize;
  97191. }
  97192. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_mid_side_stereo(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_->do_mid_side_stereo;
  97198. }
  97199. FLAC_API FLAC__bool FLAC__stream_encoder_get_loose_mid_side_stereo(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_->loose_mid_side_stereo;
  97205. }
  97206. FLAC_API unsigned FLAC__stream_encoder_get_max_lpc_order(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_->max_lpc_order;
  97212. }
  97213. FLAC_API unsigned FLAC__stream_encoder_get_qlp_coeff_precision(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_->qlp_coeff_precision;
  97219. }
  97220. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_qlp_coeff_prec_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_qlp_coeff_prec_search;
  97226. }
  97227. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_escape_coding(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_->do_escape_coding;
  97233. }
  97234. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_exhaustive_model_search(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_->do_exhaustive_model_search;
  97240. }
  97241. FLAC_API unsigned FLAC__stream_encoder_get_min_residual_partition_order(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_->min_residual_partition_order;
  97247. }
  97248. FLAC_API unsigned FLAC__stream_encoder_get_max_residual_partition_order(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_->max_residual_partition_order;
  97254. }
  97255. FLAC_API unsigned FLAC__stream_encoder_get_rice_parameter_search_dist(const FLAC__StreamEncoder *encoder)
  97256. {
  97257. FLAC__ASSERT(0 != encoder);
  97258. FLAC__ASSERT(0 != encoder->private_);
  97259. FLAC__ASSERT(0 != encoder->protected_);
  97260. return encoder->protected_->rice_parameter_search_dist;
  97261. }
  97262. FLAC_API FLAC__uint64 FLAC__stream_encoder_get_total_samples_estimate(const FLAC__StreamEncoder *encoder)
  97263. {
  97264. FLAC__ASSERT(0 != encoder);
  97265. FLAC__ASSERT(0 != encoder->private_);
  97266. FLAC__ASSERT(0 != encoder->protected_);
  97267. return encoder->protected_->total_samples_estimate;
  97268. }
  97269. FLAC_API FLAC__bool FLAC__stream_encoder_process(FLAC__StreamEncoder *encoder, const FLAC__int32 * const buffer[], unsigned samples)
  97270. {
  97271. unsigned i, j = 0, channel;
  97272. const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
  97273. FLAC__ASSERT(0 != encoder);
  97274. FLAC__ASSERT(0 != encoder->private_);
  97275. FLAC__ASSERT(0 != encoder->protected_);
  97276. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  97277. do {
  97278. const unsigned n = min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j);
  97279. if(encoder->protected_->verify)
  97280. append_to_verify_fifo_(&encoder->private_->verify.input_fifo, buffer, j, channels, n);
  97281. for(channel = 0; channel < channels; channel++)
  97282. memcpy(&encoder->private_->integer_signal[channel][encoder->private_->current_sample_number], &buffer[channel][j], sizeof(buffer[channel][0]) * n);
  97283. if(encoder->protected_->do_mid_side_stereo) {
  97284. FLAC__ASSERT(channels == 2);
  97285. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  97286. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  97287. encoder->private_->integer_signal_mid_side[1][i] = buffer[0][j] - buffer[1][j];
  97288. 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' ! */
  97289. }
  97290. }
  97291. else
  97292. j += n;
  97293. encoder->private_->current_sample_number += n;
  97294. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  97295. if(encoder->private_->current_sample_number > blocksize) {
  97296. FLAC__ASSERT(encoder->private_->current_sample_number == blocksize+OVERREAD_);
  97297. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  97298. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  97299. return false;
  97300. /* move unprocessed overread samples to beginnings of arrays */
  97301. for(channel = 0; channel < channels; channel++)
  97302. encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
  97303. if(encoder->protected_->do_mid_side_stereo) {
  97304. encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
  97305. encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
  97306. }
  97307. encoder->private_->current_sample_number = 1;
  97308. }
  97309. } while(j < samples);
  97310. return true;
  97311. }
  97312. FLAC_API FLAC__bool FLAC__stream_encoder_process_interleaved(FLAC__StreamEncoder *encoder, const FLAC__int32 buffer[], unsigned samples)
  97313. {
  97314. unsigned i, j, k, channel;
  97315. FLAC__int32 x, mid, side;
  97316. const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
  97317. FLAC__ASSERT(0 != encoder);
  97318. FLAC__ASSERT(0 != encoder->private_);
  97319. FLAC__ASSERT(0 != encoder->protected_);
  97320. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  97321. j = k = 0;
  97322. /*
  97323. * we have several flavors of the same basic loop, optimized for
  97324. * different conditions:
  97325. */
  97326. if(encoder->protected_->do_mid_side_stereo && channels == 2) {
  97327. /*
  97328. * stereo coding: unroll channel loop
  97329. */
  97330. do {
  97331. if(encoder->protected_->verify)
  97332. append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
  97333. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  97334. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  97335. encoder->private_->integer_signal[0][i] = mid = side = buffer[k++];
  97336. x = buffer[k++];
  97337. encoder->private_->integer_signal[1][i] = x;
  97338. mid += x;
  97339. side -= x;
  97340. mid >>= 1; /* NOTE: not the same as 'mid = (left + right) / 2' ! */
  97341. encoder->private_->integer_signal_mid_side[1][i] = side;
  97342. encoder->private_->integer_signal_mid_side[0][i] = mid;
  97343. }
  97344. encoder->private_->current_sample_number = i;
  97345. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  97346. if(i > blocksize) {
  97347. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  97348. return false;
  97349. /* move unprocessed overread samples to beginnings of arrays */
  97350. FLAC__ASSERT(i == blocksize+OVERREAD_);
  97351. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  97352. encoder->private_->integer_signal[0][0] = encoder->private_->integer_signal[0][blocksize];
  97353. encoder->private_->integer_signal[1][0] = encoder->private_->integer_signal[1][blocksize];
  97354. encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
  97355. encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
  97356. encoder->private_->current_sample_number = 1;
  97357. }
  97358. } while(j < samples);
  97359. }
  97360. else {
  97361. /*
  97362. * independent channel coding: buffer each channel in inner loop
  97363. */
  97364. do {
  97365. if(encoder->protected_->verify)
  97366. append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
  97367. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  97368. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  97369. for(channel = 0; channel < channels; channel++)
  97370. encoder->private_->integer_signal[channel][i] = buffer[k++];
  97371. }
  97372. encoder->private_->current_sample_number = i;
  97373. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  97374. if(i > blocksize) {
  97375. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  97376. return false;
  97377. /* move unprocessed overread samples to beginnings of arrays */
  97378. FLAC__ASSERT(i == blocksize+OVERREAD_);
  97379. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  97380. for(channel = 0; channel < channels; channel++)
  97381. encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
  97382. encoder->private_->current_sample_number = 1;
  97383. }
  97384. } while(j < samples);
  97385. }
  97386. return true;
  97387. }
  97388. /***********************************************************************
  97389. *
  97390. * Private class methods
  97391. *
  97392. ***********************************************************************/
  97393. void set_defaults_enc(FLAC__StreamEncoder *encoder)
  97394. {
  97395. FLAC__ASSERT(0 != encoder);
  97396. #ifdef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
  97397. encoder->protected_->verify = true;
  97398. #else
  97399. encoder->protected_->verify = false;
  97400. #endif
  97401. encoder->protected_->streamable_subset = true;
  97402. encoder->protected_->do_md5 = true;
  97403. encoder->protected_->do_mid_side_stereo = false;
  97404. encoder->protected_->loose_mid_side_stereo = false;
  97405. encoder->protected_->channels = 2;
  97406. encoder->protected_->bits_per_sample = 16;
  97407. encoder->protected_->sample_rate = 44100;
  97408. encoder->protected_->blocksize = 0;
  97409. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97410. encoder->protected_->num_apodizations = 1;
  97411. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  97412. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  97413. #endif
  97414. encoder->protected_->max_lpc_order = 0;
  97415. encoder->protected_->qlp_coeff_precision = 0;
  97416. encoder->protected_->do_qlp_coeff_prec_search = false;
  97417. encoder->protected_->do_exhaustive_model_search = false;
  97418. encoder->protected_->do_escape_coding = false;
  97419. encoder->protected_->min_residual_partition_order = 0;
  97420. encoder->protected_->max_residual_partition_order = 0;
  97421. encoder->protected_->rice_parameter_search_dist = 0;
  97422. encoder->protected_->total_samples_estimate = 0;
  97423. encoder->protected_->metadata = 0;
  97424. encoder->protected_->num_metadata_blocks = 0;
  97425. encoder->private_->seek_table = 0;
  97426. encoder->private_->disable_constant_subframes = false;
  97427. encoder->private_->disable_fixed_subframes = false;
  97428. encoder->private_->disable_verbatim_subframes = false;
  97429. #if FLAC__HAS_OGG
  97430. encoder->private_->is_ogg = false;
  97431. #endif
  97432. encoder->private_->read_callback = 0;
  97433. encoder->private_->write_callback = 0;
  97434. encoder->private_->seek_callback = 0;
  97435. encoder->private_->tell_callback = 0;
  97436. encoder->private_->metadata_callback = 0;
  97437. encoder->private_->progress_callback = 0;
  97438. encoder->private_->client_data = 0;
  97439. #if FLAC__HAS_OGG
  97440. FLAC__ogg_encoder_aspect_set_defaults(&encoder->protected_->ogg_encoder_aspect);
  97441. #endif
  97442. }
  97443. void free_(FLAC__StreamEncoder *encoder)
  97444. {
  97445. unsigned i, channel;
  97446. FLAC__ASSERT(0 != encoder);
  97447. if(encoder->protected_->metadata) {
  97448. free(encoder->protected_->metadata);
  97449. encoder->protected_->metadata = 0;
  97450. encoder->protected_->num_metadata_blocks = 0;
  97451. }
  97452. for(i = 0; i < encoder->protected_->channels; i++) {
  97453. if(0 != encoder->private_->integer_signal_unaligned[i]) {
  97454. free(encoder->private_->integer_signal_unaligned[i]);
  97455. encoder->private_->integer_signal_unaligned[i] = 0;
  97456. }
  97457. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97458. if(0 != encoder->private_->real_signal_unaligned[i]) {
  97459. free(encoder->private_->real_signal_unaligned[i]);
  97460. encoder->private_->real_signal_unaligned[i] = 0;
  97461. }
  97462. #endif
  97463. }
  97464. for(i = 0; i < 2; i++) {
  97465. if(0 != encoder->private_->integer_signal_mid_side_unaligned[i]) {
  97466. free(encoder->private_->integer_signal_mid_side_unaligned[i]);
  97467. encoder->private_->integer_signal_mid_side_unaligned[i] = 0;
  97468. }
  97469. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97470. if(0 != encoder->private_->real_signal_mid_side_unaligned[i]) {
  97471. free(encoder->private_->real_signal_mid_side_unaligned[i]);
  97472. encoder->private_->real_signal_mid_side_unaligned[i] = 0;
  97473. }
  97474. #endif
  97475. }
  97476. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97477. for(i = 0; i < encoder->protected_->num_apodizations; i++) {
  97478. if(0 != encoder->private_->window_unaligned[i]) {
  97479. free(encoder->private_->window_unaligned[i]);
  97480. encoder->private_->window_unaligned[i] = 0;
  97481. }
  97482. }
  97483. if(0 != encoder->private_->windowed_signal_unaligned) {
  97484. free(encoder->private_->windowed_signal_unaligned);
  97485. encoder->private_->windowed_signal_unaligned = 0;
  97486. }
  97487. #endif
  97488. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  97489. for(i = 0; i < 2; i++) {
  97490. if(0 != encoder->private_->residual_workspace_unaligned[channel][i]) {
  97491. free(encoder->private_->residual_workspace_unaligned[channel][i]);
  97492. encoder->private_->residual_workspace_unaligned[channel][i] = 0;
  97493. }
  97494. }
  97495. }
  97496. for(channel = 0; channel < 2; channel++) {
  97497. for(i = 0; i < 2; i++) {
  97498. if(0 != encoder->private_->residual_workspace_mid_side_unaligned[channel][i]) {
  97499. free(encoder->private_->residual_workspace_mid_side_unaligned[channel][i]);
  97500. encoder->private_->residual_workspace_mid_side_unaligned[channel][i] = 0;
  97501. }
  97502. }
  97503. }
  97504. if(0 != encoder->private_->abs_residual_partition_sums_unaligned) {
  97505. free(encoder->private_->abs_residual_partition_sums_unaligned);
  97506. encoder->private_->abs_residual_partition_sums_unaligned = 0;
  97507. }
  97508. if(0 != encoder->private_->raw_bits_per_partition_unaligned) {
  97509. free(encoder->private_->raw_bits_per_partition_unaligned);
  97510. encoder->private_->raw_bits_per_partition_unaligned = 0;
  97511. }
  97512. if(encoder->protected_->verify) {
  97513. for(i = 0; i < encoder->protected_->channels; i++) {
  97514. if(0 != encoder->private_->verify.input_fifo.data[i]) {
  97515. free(encoder->private_->verify.input_fifo.data[i]);
  97516. encoder->private_->verify.input_fifo.data[i] = 0;
  97517. }
  97518. }
  97519. }
  97520. FLAC__bitwriter_free(encoder->private_->frame);
  97521. }
  97522. FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize)
  97523. {
  97524. FLAC__bool ok;
  97525. unsigned i, channel;
  97526. FLAC__ASSERT(new_blocksize > 0);
  97527. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  97528. FLAC__ASSERT(encoder->private_->current_sample_number == 0);
  97529. /* To avoid excessive malloc'ing, we only grow the buffer; no shrinking. */
  97530. if(new_blocksize <= encoder->private_->input_capacity)
  97531. return true;
  97532. ok = true;
  97533. /* WATCHOUT: FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx()
  97534. * requires that the input arrays (in our case the integer signals)
  97535. * have a buffer of up to 3 zeroes in front (at negative indices) for
  97536. * alignment purposes; we use 4 in front to keep the data well-aligned.
  97537. */
  97538. for(i = 0; ok && i < encoder->protected_->channels; i++) {
  97539. ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize+4+OVERREAD_, &encoder->private_->integer_signal_unaligned[i], &encoder->private_->integer_signal[i]);
  97540. memset(encoder->private_->integer_signal[i], 0, sizeof(FLAC__int32)*4);
  97541. encoder->private_->integer_signal[i] += 4;
  97542. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97543. #if 0 /* @@@ currently unused */
  97544. if(encoder->protected_->max_lpc_order > 0)
  97545. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize+OVERREAD_, &encoder->private_->real_signal_unaligned[i], &encoder->private_->real_signal[i]);
  97546. #endif
  97547. #endif
  97548. }
  97549. for(i = 0; ok && i < 2; i++) {
  97550. 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]);
  97551. memset(encoder->private_->integer_signal_mid_side[i], 0, sizeof(FLAC__int32)*4);
  97552. encoder->private_->integer_signal_mid_side[i] += 4;
  97553. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97554. #if 0 /* @@@ currently unused */
  97555. if(encoder->protected_->max_lpc_order > 0)
  97556. 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]);
  97557. #endif
  97558. #endif
  97559. }
  97560. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97561. if(ok && encoder->protected_->max_lpc_order > 0) {
  97562. for(i = 0; ok && i < encoder->protected_->num_apodizations; i++)
  97563. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->window_unaligned[i], &encoder->private_->window[i]);
  97564. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->windowed_signal_unaligned, &encoder->private_->windowed_signal);
  97565. }
  97566. #endif
  97567. for(channel = 0; ok && channel < encoder->protected_->channels; channel++) {
  97568. for(i = 0; ok && i < 2; i++) {
  97569. ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize, &encoder->private_->residual_workspace_unaligned[channel][i], &encoder->private_->residual_workspace[channel][i]);
  97570. }
  97571. }
  97572. for(channel = 0; ok && channel < 2; channel++) {
  97573. for(i = 0; ok && i < 2; i++) {
  97574. 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]);
  97575. }
  97576. }
  97577. /* the *2 is an approximation to the series 1 + 1/2 + 1/4 + ... that sums tree occupies in a flat array */
  97578. /*@@@ 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) */
  97579. ok = ok && FLAC__memory_alloc_aligned_uint64_array(new_blocksize * 2, &encoder->private_->abs_residual_partition_sums_unaligned, &encoder->private_->abs_residual_partition_sums);
  97580. if(encoder->protected_->do_escape_coding)
  97581. ok = ok && FLAC__memory_alloc_aligned_unsigned_array(new_blocksize * 2, &encoder->private_->raw_bits_per_partition_unaligned, &encoder->private_->raw_bits_per_partition);
  97582. /* now adjust the windows if the blocksize has changed */
  97583. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97584. if(ok && new_blocksize != encoder->private_->input_capacity && encoder->protected_->max_lpc_order > 0) {
  97585. for(i = 0; ok && i < encoder->protected_->num_apodizations; i++) {
  97586. switch(encoder->protected_->apodizations[i].type) {
  97587. case FLAC__APODIZATION_BARTLETT:
  97588. FLAC__window_bartlett(encoder->private_->window[i], new_blocksize);
  97589. break;
  97590. case FLAC__APODIZATION_BARTLETT_HANN:
  97591. FLAC__window_bartlett_hann(encoder->private_->window[i], new_blocksize);
  97592. break;
  97593. case FLAC__APODIZATION_BLACKMAN:
  97594. FLAC__window_blackman(encoder->private_->window[i], new_blocksize);
  97595. break;
  97596. case FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE:
  97597. FLAC__window_blackman_harris_4term_92db_sidelobe(encoder->private_->window[i], new_blocksize);
  97598. break;
  97599. case FLAC__APODIZATION_CONNES:
  97600. FLAC__window_connes(encoder->private_->window[i], new_blocksize);
  97601. break;
  97602. case FLAC__APODIZATION_FLATTOP:
  97603. FLAC__window_flattop(encoder->private_->window[i], new_blocksize);
  97604. break;
  97605. case FLAC__APODIZATION_GAUSS:
  97606. FLAC__window_gauss(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.gauss.stddev);
  97607. break;
  97608. case FLAC__APODIZATION_HAMMING:
  97609. FLAC__window_hamming(encoder->private_->window[i], new_blocksize);
  97610. break;
  97611. case FLAC__APODIZATION_HANN:
  97612. FLAC__window_hann(encoder->private_->window[i], new_blocksize);
  97613. break;
  97614. case FLAC__APODIZATION_KAISER_BESSEL:
  97615. FLAC__window_kaiser_bessel(encoder->private_->window[i], new_blocksize);
  97616. break;
  97617. case FLAC__APODIZATION_NUTTALL:
  97618. FLAC__window_nuttall(encoder->private_->window[i], new_blocksize);
  97619. break;
  97620. case FLAC__APODIZATION_RECTANGLE:
  97621. FLAC__window_rectangle(encoder->private_->window[i], new_blocksize);
  97622. break;
  97623. case FLAC__APODIZATION_TRIANGLE:
  97624. FLAC__window_triangle(encoder->private_->window[i], new_blocksize);
  97625. break;
  97626. case FLAC__APODIZATION_TUKEY:
  97627. FLAC__window_tukey(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.tukey.p);
  97628. break;
  97629. case FLAC__APODIZATION_WELCH:
  97630. FLAC__window_welch(encoder->private_->window[i], new_blocksize);
  97631. break;
  97632. default:
  97633. FLAC__ASSERT(0);
  97634. /* double protection */
  97635. FLAC__window_hann(encoder->private_->window[i], new_blocksize);
  97636. break;
  97637. }
  97638. }
  97639. }
  97640. #endif
  97641. if(ok)
  97642. encoder->private_->input_capacity = new_blocksize;
  97643. else
  97644. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  97645. return ok;
  97646. }
  97647. FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block)
  97648. {
  97649. const FLAC__byte *buffer;
  97650. size_t bytes;
  97651. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
  97652. if(!FLAC__bitwriter_get_buffer(encoder->private_->frame, &buffer, &bytes)) {
  97653. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  97654. return false;
  97655. }
  97656. if(encoder->protected_->verify) {
  97657. encoder->private_->verify.output.data = buffer;
  97658. encoder->private_->verify.output.bytes = bytes;
  97659. if(encoder->private_->verify.state_hint == ENCODER_IN_MAGIC) {
  97660. encoder->private_->verify.needs_magic_hack = true;
  97661. }
  97662. else {
  97663. if(!FLAC__stream_decoder_process_single(encoder->private_->verify.decoder)) {
  97664. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  97665. FLAC__bitwriter_clear(encoder->private_->frame);
  97666. if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA)
  97667. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  97668. return false;
  97669. }
  97670. }
  97671. }
  97672. if(write_frame_(encoder, buffer, bytes, samples, is_last_block) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  97673. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  97674. FLAC__bitwriter_clear(encoder->private_->frame);
  97675. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  97676. return false;
  97677. }
  97678. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  97679. FLAC__bitwriter_clear(encoder->private_->frame);
  97680. if(samples > 0) {
  97681. encoder->private_->streaminfo.data.stream_info.min_framesize = min(bytes, encoder->private_->streaminfo.data.stream_info.min_framesize);
  97682. encoder->private_->streaminfo.data.stream_info.max_framesize = max(bytes, encoder->private_->streaminfo.data.stream_info.max_framesize);
  97683. }
  97684. return true;
  97685. }
  97686. FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block)
  97687. {
  97688. FLAC__StreamEncoderWriteStatus status;
  97689. FLAC__uint64 output_position = 0;
  97690. /* FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED just means we didn't get the offset; no error */
  97691. if(encoder->private_->tell_callback && encoder->private_->tell_callback(encoder, &output_position, encoder->private_->client_data) == FLAC__STREAM_ENCODER_TELL_STATUS_ERROR) {
  97692. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  97693. return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  97694. }
  97695. /*
  97696. * Watch for the STREAMINFO block and first SEEKTABLE block to go by and store their offsets.
  97697. */
  97698. if(samples == 0) {
  97699. FLAC__MetadataType type = (FLAC__MetadataType) (buffer[0] & 0x7f);
  97700. if(type == FLAC__METADATA_TYPE_STREAMINFO)
  97701. encoder->protected_->streaminfo_offset = output_position;
  97702. else if(type == FLAC__METADATA_TYPE_SEEKTABLE && encoder->protected_->seektable_offset == 0)
  97703. encoder->protected_->seektable_offset = output_position;
  97704. }
  97705. /*
  97706. * Mark the current seek point if hit (if audio_offset == 0 that
  97707. * means we're still writing metadata and haven't hit the first
  97708. * frame yet)
  97709. */
  97710. if(0 != encoder->private_->seek_table && encoder->protected_->audio_offset > 0 && encoder->private_->seek_table->num_points > 0) {
  97711. const unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
  97712. const FLAC__uint64 frame_first_sample = encoder->private_->samples_written;
  97713. const FLAC__uint64 frame_last_sample = frame_first_sample + (FLAC__uint64)blocksize - 1;
  97714. FLAC__uint64 test_sample;
  97715. unsigned i;
  97716. for(i = encoder->private_->first_seekpoint_to_check; i < encoder->private_->seek_table->num_points; i++) {
  97717. test_sample = encoder->private_->seek_table->points[i].sample_number;
  97718. if(test_sample > frame_last_sample) {
  97719. break;
  97720. }
  97721. else if(test_sample >= frame_first_sample) {
  97722. encoder->private_->seek_table->points[i].sample_number = frame_first_sample;
  97723. encoder->private_->seek_table->points[i].stream_offset = output_position - encoder->protected_->audio_offset;
  97724. encoder->private_->seek_table->points[i].frame_samples = blocksize;
  97725. encoder->private_->first_seekpoint_to_check++;
  97726. /* DO NOT: "break;" and here's why:
  97727. * The seektable template may contain more than one target
  97728. * sample for any given frame; we will keep looping, generating
  97729. * duplicate seekpoints for them, and we'll clean it up later,
  97730. * just before writing the seektable back to the metadata.
  97731. */
  97732. }
  97733. else {
  97734. encoder->private_->first_seekpoint_to_check++;
  97735. }
  97736. }
  97737. }
  97738. #if FLAC__HAS_OGG
  97739. if(encoder->private_->is_ogg) {
  97740. status = FLAC__ogg_encoder_aspect_write_callback_wrapper(
  97741. &encoder->protected_->ogg_encoder_aspect,
  97742. buffer,
  97743. bytes,
  97744. samples,
  97745. encoder->private_->current_frame_number,
  97746. is_last_block,
  97747. (FLAC__OggEncoderAspectWriteCallbackProxy)encoder->private_->write_callback,
  97748. encoder,
  97749. encoder->private_->client_data
  97750. );
  97751. }
  97752. else
  97753. #endif
  97754. status = encoder->private_->write_callback(encoder, buffer, bytes, samples, encoder->private_->current_frame_number, encoder->private_->client_data);
  97755. if(status == FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  97756. encoder->private_->bytes_written += bytes;
  97757. encoder->private_->samples_written += samples;
  97758. /* we keep a high watermark on the number of frames written because
  97759. * when the encoder goes back to write metadata, 'current_frame'
  97760. * will drop back to 0.
  97761. */
  97762. encoder->private_->frames_written = max(encoder->private_->frames_written, encoder->private_->current_frame_number+1);
  97763. }
  97764. else
  97765. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  97766. return status;
  97767. }
  97768. /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks. */
  97769. void update_metadata_(const FLAC__StreamEncoder *encoder)
  97770. {
  97771. FLAC__byte b[max(6, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
  97772. const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
  97773. const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
  97774. const unsigned min_framesize = metadata->data.stream_info.min_framesize;
  97775. const unsigned max_framesize = metadata->data.stream_info.max_framesize;
  97776. const unsigned bps = metadata->data.stream_info.bits_per_sample;
  97777. FLAC__StreamEncoderSeekStatus seek_status;
  97778. FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
  97779. /* All this is based on intimate knowledge of the stream header
  97780. * layout, but a change to the header format that would break this
  97781. * would also break all streams encoded in the previous format.
  97782. */
  97783. /*
  97784. * Write MD5 signature
  97785. */
  97786. {
  97787. const unsigned md5_offset =
  97788. FLAC__STREAM_METADATA_HEADER_LENGTH +
  97789. (
  97790. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  97791. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  97792. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  97793. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  97794. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  97795. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  97796. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
  97797. FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
  97798. ) / 8;
  97799. if((seek_status = encoder->private_->seek_callback(encoder, encoder->protected_->streaminfo_offset + md5_offset, encoder->private_->client_data)) != FLAC__STREAM_ENCODER_SEEK_STATUS_OK) {
  97800. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  97801. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  97802. return;
  97803. }
  97804. if(encoder->private_->write_callback(encoder, metadata->data.stream_info.md5sum, 16, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  97805. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  97806. return;
  97807. }
  97808. }
  97809. /*
  97810. * Write total samples
  97811. */
  97812. {
  97813. const unsigned total_samples_byte_offset =
  97814. FLAC__STREAM_METADATA_HEADER_LENGTH +
  97815. (
  97816. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  97817. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  97818. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  97819. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  97820. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  97821. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  97822. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
  97823. - 4
  97824. ) / 8;
  97825. b[0] = ((FLAC__byte)(bps-1) << 4) | (FLAC__byte)((samples >> 32) & 0x0F);
  97826. b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
  97827. b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
  97828. b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
  97829. b[4] = (FLAC__byte)(samples & 0xFF);
  97830. 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) {
  97831. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  97832. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  97833. return;
  97834. }
  97835. if(encoder->private_->write_callback(encoder, b, 5, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  97836. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  97837. return;
  97838. }
  97839. }
  97840. /*
  97841. * Write min/max framesize
  97842. */
  97843. {
  97844. const unsigned min_framesize_offset =
  97845. FLAC__STREAM_METADATA_HEADER_LENGTH +
  97846. (
  97847. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  97848. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
  97849. ) / 8;
  97850. b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
  97851. b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
  97852. b[2] = (FLAC__byte)(min_framesize & 0xFF);
  97853. b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
  97854. b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
  97855. b[5] = (FLAC__byte)(max_framesize & 0xFF);
  97856. 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) {
  97857. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  97858. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  97859. return;
  97860. }
  97861. if(encoder->private_->write_callback(encoder, b, 6, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  97862. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  97863. return;
  97864. }
  97865. }
  97866. /*
  97867. * Write seektable
  97868. */
  97869. if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
  97870. unsigned i;
  97871. FLAC__format_seektable_sort(encoder->private_->seek_table);
  97872. FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
  97873. 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) {
  97874. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  97875. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  97876. return;
  97877. }
  97878. for(i = 0; i < encoder->private_->seek_table->num_points; i++) {
  97879. FLAC__uint64 xx;
  97880. unsigned x;
  97881. xx = encoder->private_->seek_table->points[i].sample_number;
  97882. b[7] = (FLAC__byte)xx; xx >>= 8;
  97883. b[6] = (FLAC__byte)xx; xx >>= 8;
  97884. b[5] = (FLAC__byte)xx; xx >>= 8;
  97885. b[4] = (FLAC__byte)xx; xx >>= 8;
  97886. b[3] = (FLAC__byte)xx; xx >>= 8;
  97887. b[2] = (FLAC__byte)xx; xx >>= 8;
  97888. b[1] = (FLAC__byte)xx; xx >>= 8;
  97889. b[0] = (FLAC__byte)xx; xx >>= 8;
  97890. xx = encoder->private_->seek_table->points[i].stream_offset;
  97891. b[15] = (FLAC__byte)xx; xx >>= 8;
  97892. b[14] = (FLAC__byte)xx; xx >>= 8;
  97893. b[13] = (FLAC__byte)xx; xx >>= 8;
  97894. b[12] = (FLAC__byte)xx; xx >>= 8;
  97895. b[11] = (FLAC__byte)xx; xx >>= 8;
  97896. b[10] = (FLAC__byte)xx; xx >>= 8;
  97897. b[9] = (FLAC__byte)xx; xx >>= 8;
  97898. b[8] = (FLAC__byte)xx; xx >>= 8;
  97899. x = encoder->private_->seek_table->points[i].frame_samples;
  97900. b[17] = (FLAC__byte)x; x >>= 8;
  97901. b[16] = (FLAC__byte)x; x >>= 8;
  97902. if(encoder->private_->write_callback(encoder, b, 18, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  97903. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  97904. return;
  97905. }
  97906. }
  97907. }
  97908. }
  97909. #if FLAC__HAS_OGG
  97910. /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks. */
  97911. void update_ogg_metadata_(FLAC__StreamEncoder *encoder)
  97912. {
  97913. /* the # of bytes in the 1st packet that precede the STREAMINFO */
  97914. static const unsigned FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH =
  97915. FLAC__OGG_MAPPING_PACKET_TYPE_LENGTH +
  97916. FLAC__OGG_MAPPING_MAGIC_LENGTH +
  97917. FLAC__OGG_MAPPING_VERSION_MAJOR_LENGTH +
  97918. FLAC__OGG_MAPPING_VERSION_MINOR_LENGTH +
  97919. FLAC__OGG_MAPPING_NUM_HEADERS_LENGTH +
  97920. FLAC__STREAM_SYNC_LENGTH
  97921. ;
  97922. FLAC__byte b[max(6, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
  97923. const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
  97924. const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
  97925. const unsigned min_framesize = metadata->data.stream_info.min_framesize;
  97926. const unsigned max_framesize = metadata->data.stream_info.max_framesize;
  97927. ogg_page page;
  97928. FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
  97929. FLAC__ASSERT(0 != encoder->private_->seek_callback);
  97930. /* Pre-check that client supports seeking, since we don't want the
  97931. * ogg_helper code to ever have to deal with this condition.
  97932. */
  97933. if(encoder->private_->seek_callback(encoder, 0, encoder->private_->client_data) == FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED)
  97934. return;
  97935. /* All this is based on intimate knowledge of the stream header
  97936. * layout, but a change to the header format that would break this
  97937. * would also break all streams encoded in the previous format.
  97938. */
  97939. /**
  97940. ** Write STREAMINFO stats
  97941. **/
  97942. simple_ogg_page__init(&page);
  97943. if(!simple_ogg_page__get_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
  97944. simple_ogg_page__clear(&page);
  97945. return; /* state already set */
  97946. }
  97947. /*
  97948. * Write MD5 signature
  97949. */
  97950. {
  97951. const unsigned md5_offset =
  97952. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  97953. FLAC__STREAM_METADATA_HEADER_LENGTH +
  97954. (
  97955. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  97956. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  97957. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  97958. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  97959. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  97960. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  97961. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
  97962. FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
  97963. ) / 8;
  97964. if(md5_offset + 16 > (unsigned)page.body_len) {
  97965. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  97966. simple_ogg_page__clear(&page);
  97967. return;
  97968. }
  97969. memcpy(page.body + md5_offset, metadata->data.stream_info.md5sum, 16);
  97970. }
  97971. /*
  97972. * Write total samples
  97973. */
  97974. {
  97975. const unsigned total_samples_byte_offset =
  97976. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  97977. FLAC__STREAM_METADATA_HEADER_LENGTH +
  97978. (
  97979. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  97980. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  97981. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  97982. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  97983. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  97984. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  97985. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
  97986. - 4
  97987. ) / 8;
  97988. if(total_samples_byte_offset + 5 > (unsigned)page.body_len) {
  97989. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  97990. simple_ogg_page__clear(&page);
  97991. return;
  97992. }
  97993. b[0] = (FLAC__byte)page.body[total_samples_byte_offset] & 0xF0;
  97994. b[0] |= (FLAC__byte)((samples >> 32) & 0x0F);
  97995. b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
  97996. b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
  97997. b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
  97998. b[4] = (FLAC__byte)(samples & 0xFF);
  97999. memcpy(page.body + total_samples_byte_offset, b, 5);
  98000. }
  98001. /*
  98002. * Write min/max framesize
  98003. */
  98004. {
  98005. const unsigned min_framesize_offset =
  98006. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  98007. FLAC__STREAM_METADATA_HEADER_LENGTH +
  98008. (
  98009. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  98010. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
  98011. ) / 8;
  98012. if(min_framesize_offset + 6 > (unsigned)page.body_len) {
  98013. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  98014. simple_ogg_page__clear(&page);
  98015. return;
  98016. }
  98017. b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
  98018. b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
  98019. b[2] = (FLAC__byte)(min_framesize & 0xFF);
  98020. b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
  98021. b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
  98022. b[5] = (FLAC__byte)(max_framesize & 0xFF);
  98023. memcpy(page.body + min_framesize_offset, b, 6);
  98024. }
  98025. if(!simple_ogg_page__set_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
  98026. simple_ogg_page__clear(&page);
  98027. return; /* state already set */
  98028. }
  98029. simple_ogg_page__clear(&page);
  98030. /*
  98031. * Write seektable
  98032. */
  98033. if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
  98034. unsigned i;
  98035. FLAC__byte *p;
  98036. FLAC__format_seektable_sort(encoder->private_->seek_table);
  98037. FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
  98038. simple_ogg_page__init(&page);
  98039. if(!simple_ogg_page__get_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
  98040. simple_ogg_page__clear(&page);
  98041. return; /* state already set */
  98042. }
  98043. if((FLAC__STREAM_METADATA_HEADER_LENGTH + 18*encoder->private_->seek_table->num_points) != (unsigned)page.body_len) {
  98044. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  98045. simple_ogg_page__clear(&page);
  98046. return;
  98047. }
  98048. for(i = 0, p = page.body + FLAC__STREAM_METADATA_HEADER_LENGTH; i < encoder->private_->seek_table->num_points; i++, p += 18) {
  98049. FLAC__uint64 xx;
  98050. unsigned x;
  98051. xx = encoder->private_->seek_table->points[i].sample_number;
  98052. b[7] = (FLAC__byte)xx; xx >>= 8;
  98053. b[6] = (FLAC__byte)xx; xx >>= 8;
  98054. b[5] = (FLAC__byte)xx; xx >>= 8;
  98055. b[4] = (FLAC__byte)xx; xx >>= 8;
  98056. b[3] = (FLAC__byte)xx; xx >>= 8;
  98057. b[2] = (FLAC__byte)xx; xx >>= 8;
  98058. b[1] = (FLAC__byte)xx; xx >>= 8;
  98059. b[0] = (FLAC__byte)xx; xx >>= 8;
  98060. xx = encoder->private_->seek_table->points[i].stream_offset;
  98061. b[15] = (FLAC__byte)xx; xx >>= 8;
  98062. b[14] = (FLAC__byte)xx; xx >>= 8;
  98063. b[13] = (FLAC__byte)xx; xx >>= 8;
  98064. b[12] = (FLAC__byte)xx; xx >>= 8;
  98065. b[11] = (FLAC__byte)xx; xx >>= 8;
  98066. b[10] = (FLAC__byte)xx; xx >>= 8;
  98067. b[9] = (FLAC__byte)xx; xx >>= 8;
  98068. b[8] = (FLAC__byte)xx; xx >>= 8;
  98069. x = encoder->private_->seek_table->points[i].frame_samples;
  98070. b[17] = (FLAC__byte)x; x >>= 8;
  98071. b[16] = (FLAC__byte)x; x >>= 8;
  98072. memcpy(p, b, 18);
  98073. }
  98074. if(!simple_ogg_page__set_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
  98075. simple_ogg_page__clear(&page);
  98076. return; /* state already set */
  98077. }
  98078. simple_ogg_page__clear(&page);
  98079. }
  98080. }
  98081. #endif
  98082. FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block)
  98083. {
  98084. FLAC__uint16 crc;
  98085. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  98086. /*
  98087. * Accumulate raw signal to the MD5 signature
  98088. */
  98089. 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)) {
  98090. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  98091. return false;
  98092. }
  98093. /*
  98094. * Process the frame header and subframes into the frame bitbuffer
  98095. */
  98096. if(!process_subframes_(encoder, is_fractional_block)) {
  98097. /* the above function sets the state for us in case of an error */
  98098. return false;
  98099. }
  98100. /*
  98101. * Zero-pad the frame to a byte_boundary
  98102. */
  98103. if(!FLAC__bitwriter_zero_pad_to_byte_boundary(encoder->private_->frame)) {
  98104. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  98105. return false;
  98106. }
  98107. /*
  98108. * CRC-16 the whole thing
  98109. */
  98110. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
  98111. if(
  98112. !FLAC__bitwriter_get_write_crc16(encoder->private_->frame, &crc) ||
  98113. !FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, crc, FLAC__FRAME_FOOTER_CRC_LEN)
  98114. ) {
  98115. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  98116. return false;
  98117. }
  98118. /*
  98119. * Write it
  98120. */
  98121. if(!write_bitbuffer_(encoder, encoder->protected_->blocksize, is_last_block)) {
  98122. /* the above function sets the state for us in case of an error */
  98123. return false;
  98124. }
  98125. /*
  98126. * Get ready for the next frame
  98127. */
  98128. encoder->private_->current_sample_number = 0;
  98129. encoder->private_->current_frame_number++;
  98130. encoder->private_->streaminfo.data.stream_info.total_samples += (FLAC__uint64)encoder->protected_->blocksize;
  98131. return true;
  98132. }
  98133. FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block)
  98134. {
  98135. FLAC__FrameHeader frame_header;
  98136. unsigned channel, min_partition_order = encoder->protected_->min_residual_partition_order, max_partition_order;
  98137. FLAC__bool do_independent, do_mid_side;
  98138. /*
  98139. * Calculate the min,max Rice partition orders
  98140. */
  98141. if(is_fractional_block) {
  98142. max_partition_order = 0;
  98143. }
  98144. else {
  98145. max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize(encoder->protected_->blocksize);
  98146. max_partition_order = min(max_partition_order, encoder->protected_->max_residual_partition_order);
  98147. }
  98148. min_partition_order = min(min_partition_order, max_partition_order);
  98149. /*
  98150. * Setup the frame
  98151. */
  98152. frame_header.blocksize = encoder->protected_->blocksize;
  98153. frame_header.sample_rate = encoder->protected_->sample_rate;
  98154. frame_header.channels = encoder->protected_->channels;
  98155. frame_header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT; /* the default unless the encoder determines otherwise */
  98156. frame_header.bits_per_sample = encoder->protected_->bits_per_sample;
  98157. frame_header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER;
  98158. frame_header.number.frame_number = encoder->private_->current_frame_number;
  98159. /*
  98160. * Figure out what channel assignments to try
  98161. */
  98162. if(encoder->protected_->do_mid_side_stereo) {
  98163. if(encoder->protected_->loose_mid_side_stereo) {
  98164. if(encoder->private_->loose_mid_side_stereo_frame_count == 0) {
  98165. do_independent = true;
  98166. do_mid_side = true;
  98167. }
  98168. else {
  98169. do_independent = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT);
  98170. do_mid_side = !do_independent;
  98171. }
  98172. }
  98173. else {
  98174. do_independent = true;
  98175. do_mid_side = true;
  98176. }
  98177. }
  98178. else {
  98179. do_independent = true;
  98180. do_mid_side = false;
  98181. }
  98182. FLAC__ASSERT(do_independent || do_mid_side);
  98183. /*
  98184. * Check for wasted bits; set effective bps for each subframe
  98185. */
  98186. if(do_independent) {
  98187. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  98188. const unsigned w = get_wasted_bits_(encoder->private_->integer_signal[channel], encoder->protected_->blocksize);
  98189. encoder->private_->subframe_workspace[channel][0].wasted_bits = encoder->private_->subframe_workspace[channel][1].wasted_bits = w;
  98190. encoder->private_->subframe_bps[channel] = encoder->protected_->bits_per_sample - w;
  98191. }
  98192. }
  98193. if(do_mid_side) {
  98194. FLAC__ASSERT(encoder->protected_->channels == 2);
  98195. for(channel = 0; channel < 2; channel++) {
  98196. const unsigned w = get_wasted_bits_(encoder->private_->integer_signal_mid_side[channel], encoder->protected_->blocksize);
  98197. encoder->private_->subframe_workspace_mid_side[channel][0].wasted_bits = encoder->private_->subframe_workspace_mid_side[channel][1].wasted_bits = w;
  98198. encoder->private_->subframe_bps_mid_side[channel] = encoder->protected_->bits_per_sample - w + (channel==0? 0:1);
  98199. }
  98200. }
  98201. /*
  98202. * First do a normal encoding pass of each independent channel
  98203. */
  98204. if(do_independent) {
  98205. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  98206. if(!
  98207. process_subframe_(
  98208. encoder,
  98209. min_partition_order,
  98210. max_partition_order,
  98211. &frame_header,
  98212. encoder->private_->subframe_bps[channel],
  98213. encoder->private_->integer_signal[channel],
  98214. encoder->private_->subframe_workspace_ptr[channel],
  98215. encoder->private_->partitioned_rice_contents_workspace_ptr[channel],
  98216. encoder->private_->residual_workspace[channel],
  98217. encoder->private_->best_subframe+channel,
  98218. encoder->private_->best_subframe_bits+channel
  98219. )
  98220. )
  98221. return false;
  98222. }
  98223. }
  98224. /*
  98225. * Now do mid and side channels if requested
  98226. */
  98227. if(do_mid_side) {
  98228. FLAC__ASSERT(encoder->protected_->channels == 2);
  98229. for(channel = 0; channel < 2; channel++) {
  98230. if(!
  98231. process_subframe_(
  98232. encoder,
  98233. min_partition_order,
  98234. max_partition_order,
  98235. &frame_header,
  98236. encoder->private_->subframe_bps_mid_side[channel],
  98237. encoder->private_->integer_signal_mid_side[channel],
  98238. encoder->private_->subframe_workspace_ptr_mid_side[channel],
  98239. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[channel],
  98240. encoder->private_->residual_workspace_mid_side[channel],
  98241. encoder->private_->best_subframe_mid_side+channel,
  98242. encoder->private_->best_subframe_bits_mid_side+channel
  98243. )
  98244. )
  98245. return false;
  98246. }
  98247. }
  98248. /*
  98249. * Compose the frame bitbuffer
  98250. */
  98251. if(do_mid_side) {
  98252. unsigned left_bps = 0, right_bps = 0; /* initialized only to prevent superfluous compiler warning */
  98253. FLAC__Subframe *left_subframe = 0, *right_subframe = 0; /* initialized only to prevent superfluous compiler warning */
  98254. FLAC__ChannelAssignment channel_assignment;
  98255. FLAC__ASSERT(encoder->protected_->channels == 2);
  98256. if(encoder->protected_->loose_mid_side_stereo && encoder->private_->loose_mid_side_stereo_frame_count > 0) {
  98257. channel_assignment = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT? FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT : FLAC__CHANNEL_ASSIGNMENT_MID_SIDE);
  98258. }
  98259. else {
  98260. unsigned bits[4]; /* WATCHOUT - indexed by FLAC__ChannelAssignment */
  98261. unsigned min_bits;
  98262. int ca;
  98263. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT == 0);
  98264. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE == 1);
  98265. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE == 2);
  98266. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_MID_SIDE == 3);
  98267. FLAC__ASSERT(do_independent && do_mid_side);
  98268. /* We have to figure out which channel assignent results in the smallest frame */
  98269. bits[FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT] = encoder->private_->best_subframe_bits [0] + encoder->private_->best_subframe_bits [1];
  98270. bits[FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE ] = encoder->private_->best_subframe_bits [0] + encoder->private_->best_subframe_bits_mid_side[1];
  98271. bits[FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE ] = encoder->private_->best_subframe_bits [1] + encoder->private_->best_subframe_bits_mid_side[1];
  98272. bits[FLAC__CHANNEL_ASSIGNMENT_MID_SIDE ] = encoder->private_->best_subframe_bits_mid_side[0] + encoder->private_->best_subframe_bits_mid_side[1];
  98273. channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
  98274. min_bits = bits[channel_assignment];
  98275. for(ca = 1; ca <= 3; ca++) {
  98276. if(bits[ca] < min_bits) {
  98277. min_bits = bits[ca];
  98278. channel_assignment = (FLAC__ChannelAssignment)ca;
  98279. }
  98280. }
  98281. }
  98282. frame_header.channel_assignment = channel_assignment;
  98283. if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
  98284. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  98285. return false;
  98286. }
  98287. switch(channel_assignment) {
  98288. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  98289. left_subframe = &encoder->private_->subframe_workspace [0][encoder->private_->best_subframe [0]];
  98290. right_subframe = &encoder->private_->subframe_workspace [1][encoder->private_->best_subframe [1]];
  98291. break;
  98292. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  98293. left_subframe = &encoder->private_->subframe_workspace [0][encoder->private_->best_subframe [0]];
  98294. right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  98295. break;
  98296. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  98297. left_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  98298. right_subframe = &encoder->private_->subframe_workspace [1][encoder->private_->best_subframe [1]];
  98299. break;
  98300. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  98301. left_subframe = &encoder->private_->subframe_workspace_mid_side[0][encoder->private_->best_subframe_mid_side[0]];
  98302. right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  98303. break;
  98304. default:
  98305. FLAC__ASSERT(0);
  98306. }
  98307. switch(channel_assignment) {
  98308. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  98309. left_bps = encoder->private_->subframe_bps [0];
  98310. right_bps = encoder->private_->subframe_bps [1];
  98311. break;
  98312. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  98313. left_bps = encoder->private_->subframe_bps [0];
  98314. right_bps = encoder->private_->subframe_bps_mid_side[1];
  98315. break;
  98316. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  98317. left_bps = encoder->private_->subframe_bps_mid_side[1];
  98318. right_bps = encoder->private_->subframe_bps [1];
  98319. break;
  98320. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  98321. left_bps = encoder->private_->subframe_bps_mid_side[0];
  98322. right_bps = encoder->private_->subframe_bps_mid_side[1];
  98323. break;
  98324. default:
  98325. FLAC__ASSERT(0);
  98326. }
  98327. /* note that encoder_add_subframe_ sets the state for us in case of an error */
  98328. if(!add_subframe_(encoder, frame_header.blocksize, left_bps , left_subframe , encoder->private_->frame))
  98329. return false;
  98330. if(!add_subframe_(encoder, frame_header.blocksize, right_bps, right_subframe, encoder->private_->frame))
  98331. return false;
  98332. }
  98333. else {
  98334. if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
  98335. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  98336. return false;
  98337. }
  98338. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  98339. 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)) {
  98340. /* the above function sets the state for us in case of an error */
  98341. return false;
  98342. }
  98343. }
  98344. }
  98345. if(encoder->protected_->loose_mid_side_stereo) {
  98346. encoder->private_->loose_mid_side_stereo_frame_count++;
  98347. if(encoder->private_->loose_mid_side_stereo_frame_count >= encoder->private_->loose_mid_side_stereo_frames)
  98348. encoder->private_->loose_mid_side_stereo_frame_count = 0;
  98349. }
  98350. encoder->private_->last_channel_assignment = frame_header.channel_assignment;
  98351. return true;
  98352. }
  98353. FLAC__bool process_subframe_(
  98354. FLAC__StreamEncoder *encoder,
  98355. unsigned min_partition_order,
  98356. unsigned max_partition_order,
  98357. const FLAC__FrameHeader *frame_header,
  98358. unsigned subframe_bps,
  98359. const FLAC__int32 integer_signal[],
  98360. FLAC__Subframe *subframe[2],
  98361. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
  98362. FLAC__int32 *residual[2],
  98363. unsigned *best_subframe,
  98364. unsigned *best_bits
  98365. )
  98366. {
  98367. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98368. FLAC__float fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
  98369. #else
  98370. FLAC__fixedpoint fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
  98371. #endif
  98372. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98373. FLAC__double lpc_residual_bits_per_sample;
  98374. 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 */
  98375. FLAC__double lpc_error[FLAC__MAX_LPC_ORDER];
  98376. unsigned min_lpc_order, max_lpc_order, lpc_order;
  98377. unsigned min_qlp_coeff_precision, max_qlp_coeff_precision, qlp_coeff_precision;
  98378. #endif
  98379. unsigned min_fixed_order, max_fixed_order, guess_fixed_order, fixed_order;
  98380. unsigned rice_parameter;
  98381. unsigned _candidate_bits, _best_bits;
  98382. unsigned _best_subframe;
  98383. /* only use RICE2 partitions if stream bps > 16 */
  98384. 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;
  98385. FLAC__ASSERT(frame_header->blocksize > 0);
  98386. /* verbatim subframe is the baseline against which we measure other compressed subframes */
  98387. _best_subframe = 0;
  98388. if(encoder->private_->disable_verbatim_subframes && frame_header->blocksize >= FLAC__MAX_FIXED_ORDER)
  98389. _best_bits = UINT_MAX;
  98390. else
  98391. _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
  98392. if(frame_header->blocksize >= FLAC__MAX_FIXED_ORDER) {
  98393. unsigned signal_is_constant = false;
  98394. 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);
  98395. /* check for constant subframe */
  98396. if(
  98397. !encoder->private_->disable_constant_subframes &&
  98398. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98399. fixed_residual_bits_per_sample[1] == 0.0
  98400. #else
  98401. fixed_residual_bits_per_sample[1] == FLAC__FP_ZERO
  98402. #endif
  98403. ) {
  98404. /* the above means it's possible all samples are the same value; now double-check it: */
  98405. unsigned i;
  98406. signal_is_constant = true;
  98407. for(i = 1; i < frame_header->blocksize; i++) {
  98408. if(integer_signal[0] != integer_signal[i]) {
  98409. signal_is_constant = false;
  98410. break;
  98411. }
  98412. }
  98413. }
  98414. if(signal_is_constant) {
  98415. _candidate_bits = evaluate_constant_subframe_(encoder, integer_signal[0], frame_header->blocksize, subframe_bps, subframe[!_best_subframe]);
  98416. if(_candidate_bits < _best_bits) {
  98417. _best_subframe = !_best_subframe;
  98418. _best_bits = _candidate_bits;
  98419. }
  98420. }
  98421. else {
  98422. if(!encoder->private_->disable_fixed_subframes || (encoder->protected_->max_lpc_order == 0 && _best_bits == UINT_MAX)) {
  98423. /* encode fixed */
  98424. if(encoder->protected_->do_exhaustive_model_search) {
  98425. min_fixed_order = 0;
  98426. max_fixed_order = FLAC__MAX_FIXED_ORDER;
  98427. }
  98428. else {
  98429. min_fixed_order = max_fixed_order = guess_fixed_order;
  98430. }
  98431. if(max_fixed_order >= frame_header->blocksize)
  98432. max_fixed_order = frame_header->blocksize - 1;
  98433. for(fixed_order = min_fixed_order; fixed_order <= max_fixed_order; fixed_order++) {
  98434. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98435. if(fixed_residual_bits_per_sample[fixed_order] >= (FLAC__float)subframe_bps)
  98436. continue; /* don't even try */
  98437. 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 */
  98438. #else
  98439. if(FLAC__fixedpoint_trunc(fixed_residual_bits_per_sample[fixed_order]) >= (int)subframe_bps)
  98440. continue; /* don't even try */
  98441. 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 */
  98442. #endif
  98443. rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
  98444. if(rice_parameter >= rice_parameter_limit) {
  98445. #ifdef DEBUG_VERBOSE
  98446. fprintf(stderr, "clipping rice_parameter (%u -> %u) @0\n", rice_parameter, rice_parameter_limit - 1);
  98447. #endif
  98448. rice_parameter = rice_parameter_limit - 1;
  98449. }
  98450. _candidate_bits =
  98451. evaluate_fixed_subframe_(
  98452. encoder,
  98453. integer_signal,
  98454. residual[!_best_subframe],
  98455. encoder->private_->abs_residual_partition_sums,
  98456. encoder->private_->raw_bits_per_partition,
  98457. frame_header->blocksize,
  98458. subframe_bps,
  98459. fixed_order,
  98460. rice_parameter,
  98461. rice_parameter_limit,
  98462. min_partition_order,
  98463. max_partition_order,
  98464. encoder->protected_->do_escape_coding,
  98465. encoder->protected_->rice_parameter_search_dist,
  98466. subframe[!_best_subframe],
  98467. partitioned_rice_contents[!_best_subframe]
  98468. );
  98469. if(_candidate_bits < _best_bits) {
  98470. _best_subframe = !_best_subframe;
  98471. _best_bits = _candidate_bits;
  98472. }
  98473. }
  98474. }
  98475. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98476. /* encode lpc */
  98477. if(encoder->protected_->max_lpc_order > 0) {
  98478. if(encoder->protected_->max_lpc_order >= frame_header->blocksize)
  98479. max_lpc_order = frame_header->blocksize-1;
  98480. else
  98481. max_lpc_order = encoder->protected_->max_lpc_order;
  98482. if(max_lpc_order > 0) {
  98483. unsigned a;
  98484. for (a = 0; a < encoder->protected_->num_apodizations; a++) {
  98485. FLAC__lpc_window_data(integer_signal, encoder->private_->window[a], encoder->private_->windowed_signal, frame_header->blocksize);
  98486. encoder->private_->local_lpc_compute_autocorrelation(encoder->private_->windowed_signal, frame_header->blocksize, max_lpc_order+1, autoc);
  98487. /* if autoc[0] == 0.0, the signal is constant and we usually won't get here, but it can happen */
  98488. if(autoc[0] != 0.0) {
  98489. FLAC__lpc_compute_lp_coefficients(autoc, &max_lpc_order, encoder->private_->lp_coeff, lpc_error);
  98490. if(encoder->protected_->do_exhaustive_model_search) {
  98491. min_lpc_order = 1;
  98492. }
  98493. else {
  98494. const unsigned guess_lpc_order =
  98495. FLAC__lpc_compute_best_order(
  98496. lpc_error,
  98497. max_lpc_order,
  98498. frame_header->blocksize,
  98499. subframe_bps + (
  98500. encoder->protected_->do_qlp_coeff_prec_search?
  98501. FLAC__MIN_QLP_COEFF_PRECISION : /* have to guess; use the min possible size to avoid accidentally favoring lower orders */
  98502. encoder->protected_->qlp_coeff_precision
  98503. )
  98504. );
  98505. min_lpc_order = max_lpc_order = guess_lpc_order;
  98506. }
  98507. if(max_lpc_order >= frame_header->blocksize)
  98508. max_lpc_order = frame_header->blocksize - 1;
  98509. for(lpc_order = min_lpc_order; lpc_order <= max_lpc_order; lpc_order++) {
  98510. lpc_residual_bits_per_sample = FLAC__lpc_compute_expected_bits_per_residual_sample(lpc_error[lpc_order-1], frame_header->blocksize-lpc_order);
  98511. if(lpc_residual_bits_per_sample >= (FLAC__double)subframe_bps)
  98512. continue; /* don't even try */
  98513. rice_parameter = (lpc_residual_bits_per_sample > 0.0)? (unsigned)(lpc_residual_bits_per_sample+0.5) : 0; /* 0.5 is for rounding */
  98514. rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
  98515. if(rice_parameter >= rice_parameter_limit) {
  98516. #ifdef DEBUG_VERBOSE
  98517. fprintf(stderr, "clipping rice_parameter (%u -> %u) @1\n", rice_parameter, rice_parameter_limit - 1);
  98518. #endif
  98519. rice_parameter = rice_parameter_limit - 1;
  98520. }
  98521. if(encoder->protected_->do_qlp_coeff_prec_search) {
  98522. min_qlp_coeff_precision = FLAC__MIN_QLP_COEFF_PRECISION;
  98523. /* try to ensure a 32-bit datapath throughout for 16bps(+1bps for side channel) or less */
  98524. if(subframe_bps <= 17) {
  98525. max_qlp_coeff_precision = min(32 - subframe_bps - lpc_order, FLAC__MAX_QLP_COEFF_PRECISION);
  98526. max_qlp_coeff_precision = max(max_qlp_coeff_precision, min_qlp_coeff_precision);
  98527. }
  98528. else
  98529. max_qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
  98530. }
  98531. else {
  98532. min_qlp_coeff_precision = max_qlp_coeff_precision = encoder->protected_->qlp_coeff_precision;
  98533. }
  98534. for(qlp_coeff_precision = min_qlp_coeff_precision; qlp_coeff_precision <= max_qlp_coeff_precision; qlp_coeff_precision++) {
  98535. _candidate_bits =
  98536. evaluate_lpc_subframe_(
  98537. encoder,
  98538. integer_signal,
  98539. residual[!_best_subframe],
  98540. encoder->private_->abs_residual_partition_sums,
  98541. encoder->private_->raw_bits_per_partition,
  98542. encoder->private_->lp_coeff[lpc_order-1],
  98543. frame_header->blocksize,
  98544. subframe_bps,
  98545. lpc_order,
  98546. qlp_coeff_precision,
  98547. rice_parameter,
  98548. rice_parameter_limit,
  98549. min_partition_order,
  98550. max_partition_order,
  98551. encoder->protected_->do_escape_coding,
  98552. encoder->protected_->rice_parameter_search_dist,
  98553. subframe[!_best_subframe],
  98554. partitioned_rice_contents[!_best_subframe]
  98555. );
  98556. if(_candidate_bits > 0) { /* if == 0, there was a problem quantizing the lpcoeffs */
  98557. if(_candidate_bits < _best_bits) {
  98558. _best_subframe = !_best_subframe;
  98559. _best_bits = _candidate_bits;
  98560. }
  98561. }
  98562. }
  98563. }
  98564. }
  98565. }
  98566. }
  98567. }
  98568. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  98569. }
  98570. }
  98571. /* under rare circumstances this can happen when all but lpc subframe types are disabled: */
  98572. if(_best_bits == UINT_MAX) {
  98573. FLAC__ASSERT(_best_subframe == 0);
  98574. _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
  98575. }
  98576. *best_subframe = _best_subframe;
  98577. *best_bits = _best_bits;
  98578. return true;
  98579. }
  98580. FLAC__bool add_subframe_(
  98581. FLAC__StreamEncoder *encoder,
  98582. unsigned blocksize,
  98583. unsigned subframe_bps,
  98584. const FLAC__Subframe *subframe,
  98585. FLAC__BitWriter *frame
  98586. )
  98587. {
  98588. switch(subframe->type) {
  98589. case FLAC__SUBFRAME_TYPE_CONSTANT:
  98590. if(!FLAC__subframe_add_constant(&(subframe->data.constant), subframe_bps, subframe->wasted_bits, frame)) {
  98591. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  98592. return false;
  98593. }
  98594. break;
  98595. case FLAC__SUBFRAME_TYPE_FIXED:
  98596. if(!FLAC__subframe_add_fixed(&(subframe->data.fixed), blocksize - subframe->data.fixed.order, subframe_bps, subframe->wasted_bits, frame)) {
  98597. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  98598. return false;
  98599. }
  98600. break;
  98601. case FLAC__SUBFRAME_TYPE_LPC:
  98602. if(!FLAC__subframe_add_lpc(&(subframe->data.lpc), blocksize - subframe->data.lpc.order, subframe_bps, subframe->wasted_bits, frame)) {
  98603. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  98604. return false;
  98605. }
  98606. break;
  98607. case FLAC__SUBFRAME_TYPE_VERBATIM:
  98608. if(!FLAC__subframe_add_verbatim(&(subframe->data.verbatim), blocksize, subframe_bps, subframe->wasted_bits, frame)) {
  98609. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  98610. return false;
  98611. }
  98612. break;
  98613. default:
  98614. FLAC__ASSERT(0);
  98615. }
  98616. return true;
  98617. }
  98618. #define SPOTCHECK_ESTIMATE 0
  98619. #if SPOTCHECK_ESTIMATE
  98620. static void spotcheck_subframe_estimate_(
  98621. FLAC__StreamEncoder *encoder,
  98622. unsigned blocksize,
  98623. unsigned subframe_bps,
  98624. const FLAC__Subframe *subframe,
  98625. unsigned estimate
  98626. )
  98627. {
  98628. FLAC__bool ret;
  98629. FLAC__BitWriter *frame = FLAC__bitwriter_new();
  98630. if(frame == 0) {
  98631. fprintf(stderr, "EST: can't allocate frame\n");
  98632. return;
  98633. }
  98634. if(!FLAC__bitwriter_init(frame)) {
  98635. fprintf(stderr, "EST: can't init frame\n");
  98636. return;
  98637. }
  98638. ret = add_subframe_(encoder, blocksize, subframe_bps, subframe, frame);
  98639. FLAC__ASSERT(ret);
  98640. {
  98641. const unsigned actual = FLAC__bitwriter_get_input_bits_unconsumed(frame);
  98642. if(estimate != actual)
  98643. 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);
  98644. }
  98645. FLAC__bitwriter_delete(frame);
  98646. }
  98647. #endif
  98648. unsigned evaluate_constant_subframe_(
  98649. FLAC__StreamEncoder *encoder,
  98650. const FLAC__int32 signal,
  98651. unsigned blocksize,
  98652. unsigned subframe_bps,
  98653. FLAC__Subframe *subframe
  98654. )
  98655. {
  98656. unsigned estimate;
  98657. subframe->type = FLAC__SUBFRAME_TYPE_CONSTANT;
  98658. subframe->data.constant.value = signal;
  98659. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + subframe_bps;
  98660. #if SPOTCHECK_ESTIMATE
  98661. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  98662. #else
  98663. (void)encoder, (void)blocksize;
  98664. #endif
  98665. return estimate;
  98666. }
  98667. unsigned evaluate_fixed_subframe_(
  98668. FLAC__StreamEncoder *encoder,
  98669. const FLAC__int32 signal[],
  98670. FLAC__int32 residual[],
  98671. FLAC__uint64 abs_residual_partition_sums[],
  98672. unsigned raw_bits_per_partition[],
  98673. unsigned blocksize,
  98674. unsigned subframe_bps,
  98675. unsigned order,
  98676. unsigned rice_parameter,
  98677. unsigned rice_parameter_limit,
  98678. unsigned min_partition_order,
  98679. unsigned max_partition_order,
  98680. FLAC__bool do_escape_coding,
  98681. unsigned rice_parameter_search_dist,
  98682. FLAC__Subframe *subframe,
  98683. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  98684. )
  98685. {
  98686. unsigned i, residual_bits, estimate;
  98687. const unsigned residual_samples = blocksize - order;
  98688. FLAC__fixed_compute_residual(signal+order, residual_samples, order, residual);
  98689. subframe->type = FLAC__SUBFRAME_TYPE_FIXED;
  98690. subframe->data.fixed.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
  98691. subframe->data.fixed.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
  98692. subframe->data.fixed.residual = residual;
  98693. residual_bits =
  98694. find_best_partition_order_(
  98695. encoder->private_,
  98696. residual,
  98697. abs_residual_partition_sums,
  98698. raw_bits_per_partition,
  98699. residual_samples,
  98700. order,
  98701. rice_parameter,
  98702. rice_parameter_limit,
  98703. min_partition_order,
  98704. max_partition_order,
  98705. subframe_bps,
  98706. do_escape_coding,
  98707. rice_parameter_search_dist,
  98708. &subframe->data.fixed.entropy_coding_method
  98709. );
  98710. subframe->data.fixed.order = order;
  98711. for(i = 0; i < order; i++)
  98712. subframe->data.fixed.warmup[i] = signal[i];
  98713. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (order * subframe_bps) + residual_bits;
  98714. #if SPOTCHECK_ESTIMATE
  98715. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  98716. #endif
  98717. return estimate;
  98718. }
  98719. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98720. unsigned evaluate_lpc_subframe_(
  98721. FLAC__StreamEncoder *encoder,
  98722. const FLAC__int32 signal[],
  98723. FLAC__int32 residual[],
  98724. FLAC__uint64 abs_residual_partition_sums[],
  98725. unsigned raw_bits_per_partition[],
  98726. const FLAC__real lp_coeff[],
  98727. unsigned blocksize,
  98728. unsigned subframe_bps,
  98729. unsigned order,
  98730. unsigned qlp_coeff_precision,
  98731. unsigned rice_parameter,
  98732. unsigned rice_parameter_limit,
  98733. unsigned min_partition_order,
  98734. unsigned max_partition_order,
  98735. FLAC__bool do_escape_coding,
  98736. unsigned rice_parameter_search_dist,
  98737. FLAC__Subframe *subframe,
  98738. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  98739. )
  98740. {
  98741. FLAC__int32 qlp_coeff[FLAC__MAX_LPC_ORDER];
  98742. unsigned i, residual_bits, estimate;
  98743. int quantization, ret;
  98744. const unsigned residual_samples = blocksize - order;
  98745. /* try to keep qlp coeff precision such that only 32-bit math is required for decode of <=16bps streams */
  98746. if(subframe_bps <= 16) {
  98747. FLAC__ASSERT(order > 0);
  98748. FLAC__ASSERT(order <= FLAC__MAX_LPC_ORDER);
  98749. qlp_coeff_precision = min(qlp_coeff_precision, 32 - subframe_bps - FLAC__bitmath_ilog2(order));
  98750. }
  98751. ret = FLAC__lpc_quantize_coefficients(lp_coeff, order, qlp_coeff_precision, qlp_coeff, &quantization);
  98752. if(ret != 0)
  98753. return 0; /* this is a hack to indicate to the caller that we can't do lp at this order on this subframe */
  98754. if(subframe_bps + qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
  98755. if(subframe_bps <= 16 && qlp_coeff_precision <= 16)
  98756. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  98757. else
  98758. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  98759. else
  98760. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  98761. subframe->type = FLAC__SUBFRAME_TYPE_LPC;
  98762. subframe->data.lpc.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
  98763. subframe->data.lpc.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
  98764. subframe->data.lpc.residual = residual;
  98765. residual_bits =
  98766. find_best_partition_order_(
  98767. encoder->private_,
  98768. residual,
  98769. abs_residual_partition_sums,
  98770. raw_bits_per_partition,
  98771. residual_samples,
  98772. order,
  98773. rice_parameter,
  98774. rice_parameter_limit,
  98775. min_partition_order,
  98776. max_partition_order,
  98777. subframe_bps,
  98778. do_escape_coding,
  98779. rice_parameter_search_dist,
  98780. &subframe->data.lpc.entropy_coding_method
  98781. );
  98782. subframe->data.lpc.order = order;
  98783. subframe->data.lpc.qlp_coeff_precision = qlp_coeff_precision;
  98784. subframe->data.lpc.quantization_level = quantization;
  98785. memcpy(subframe->data.lpc.qlp_coeff, qlp_coeff, sizeof(FLAC__int32)*FLAC__MAX_LPC_ORDER);
  98786. for(i = 0; i < order; i++)
  98787. subframe->data.lpc.warmup[i] = signal[i];
  98788. 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;
  98789. #if SPOTCHECK_ESTIMATE
  98790. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  98791. #endif
  98792. return estimate;
  98793. }
  98794. #endif
  98795. unsigned evaluate_verbatim_subframe_(
  98796. FLAC__StreamEncoder *encoder,
  98797. const FLAC__int32 signal[],
  98798. unsigned blocksize,
  98799. unsigned subframe_bps,
  98800. FLAC__Subframe *subframe
  98801. )
  98802. {
  98803. unsigned estimate;
  98804. subframe->type = FLAC__SUBFRAME_TYPE_VERBATIM;
  98805. subframe->data.verbatim.data = signal;
  98806. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (blocksize * subframe_bps);
  98807. #if SPOTCHECK_ESTIMATE
  98808. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  98809. #else
  98810. (void)encoder;
  98811. #endif
  98812. return estimate;
  98813. }
  98814. unsigned find_best_partition_order_(
  98815. FLAC__StreamEncoderPrivate *private_,
  98816. const FLAC__int32 residual[],
  98817. FLAC__uint64 abs_residual_partition_sums[],
  98818. unsigned raw_bits_per_partition[],
  98819. unsigned residual_samples,
  98820. unsigned predictor_order,
  98821. unsigned rice_parameter,
  98822. unsigned rice_parameter_limit,
  98823. unsigned min_partition_order,
  98824. unsigned max_partition_order,
  98825. unsigned bps,
  98826. FLAC__bool do_escape_coding,
  98827. unsigned rice_parameter_search_dist,
  98828. FLAC__EntropyCodingMethod *best_ecm
  98829. )
  98830. {
  98831. unsigned residual_bits, best_residual_bits = 0;
  98832. unsigned best_parameters_index = 0;
  98833. unsigned best_partition_order = 0;
  98834. const unsigned blocksize = residual_samples + predictor_order;
  98835. max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(max_partition_order, blocksize, predictor_order);
  98836. min_partition_order = min(min_partition_order, max_partition_order);
  98837. precompute_partition_info_sums_(residual, abs_residual_partition_sums, residual_samples, predictor_order, min_partition_order, max_partition_order, bps);
  98838. if(do_escape_coding)
  98839. precompute_partition_info_escapes_(residual, raw_bits_per_partition, residual_samples, predictor_order, min_partition_order, max_partition_order);
  98840. {
  98841. int partition_order;
  98842. unsigned sum;
  98843. for(partition_order = (int)max_partition_order, sum = 0; partition_order >= (int)min_partition_order; partition_order--) {
  98844. if(!
  98845. set_partitioned_rice_(
  98846. #ifdef EXACT_RICE_BITS_CALCULATION
  98847. residual,
  98848. #endif
  98849. abs_residual_partition_sums+sum,
  98850. raw_bits_per_partition+sum,
  98851. residual_samples,
  98852. predictor_order,
  98853. rice_parameter,
  98854. rice_parameter_limit,
  98855. rice_parameter_search_dist,
  98856. (unsigned)partition_order,
  98857. do_escape_coding,
  98858. &private_->partitioned_rice_contents_extra[!best_parameters_index],
  98859. &residual_bits
  98860. )
  98861. )
  98862. {
  98863. FLAC__ASSERT(best_residual_bits != 0);
  98864. break;
  98865. }
  98866. sum += 1u << partition_order;
  98867. if(best_residual_bits == 0 || residual_bits < best_residual_bits) {
  98868. best_residual_bits = residual_bits;
  98869. best_parameters_index = !best_parameters_index;
  98870. best_partition_order = partition_order;
  98871. }
  98872. }
  98873. }
  98874. best_ecm->data.partitioned_rice.order = best_partition_order;
  98875. {
  98876. /*
  98877. * We are allowed to de-const the pointer based on our special
  98878. * knowledge; it is const to the outside world.
  98879. */
  98880. FLAC__EntropyCodingMethod_PartitionedRiceContents* prc = (FLAC__EntropyCodingMethod_PartitionedRiceContents*)best_ecm->data.partitioned_rice.contents;
  98881. unsigned partition;
  98882. /* save best parameters and raw_bits */
  98883. FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(prc, max(6, best_partition_order));
  98884. memcpy(prc->parameters, private_->partitioned_rice_contents_extra[best_parameters_index].parameters, sizeof(unsigned)*(1<<(best_partition_order)));
  98885. if(do_escape_coding)
  98886. memcpy(prc->raw_bits, private_->partitioned_rice_contents_extra[best_parameters_index].raw_bits, sizeof(unsigned)*(1<<(best_partition_order)));
  98887. /*
  98888. * Now need to check if the type should be changed to
  98889. * FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2 based on the
  98890. * size of the rice parameters.
  98891. */
  98892. for(partition = 0; partition < (1u<<best_partition_order); partition++) {
  98893. if(prc->parameters[partition] >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
  98894. best_ecm->type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2;
  98895. break;
  98896. }
  98897. }
  98898. }
  98899. return best_residual_bits;
  98900. }
  98901. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  98902. extern void precompute_partition_info_sums_32bit_asm_ia32_(
  98903. const FLAC__int32 residual[],
  98904. FLAC__uint64 abs_residual_partition_sums[],
  98905. unsigned blocksize,
  98906. unsigned predictor_order,
  98907. unsigned min_partition_order,
  98908. unsigned max_partition_order
  98909. );
  98910. #endif
  98911. void precompute_partition_info_sums_(
  98912. const FLAC__int32 residual[],
  98913. FLAC__uint64 abs_residual_partition_sums[],
  98914. unsigned residual_samples,
  98915. unsigned predictor_order,
  98916. unsigned min_partition_order,
  98917. unsigned max_partition_order,
  98918. unsigned bps
  98919. )
  98920. {
  98921. const unsigned default_partition_samples = (residual_samples + predictor_order) >> max_partition_order;
  98922. unsigned partitions = 1u << max_partition_order;
  98923. FLAC__ASSERT(default_partition_samples > predictor_order);
  98924. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  98925. /* slightly pessimistic but still catches all common cases */
  98926. /* WATCHOUT: "+ bps" is an assumption that the average residual magnitude will not be more than "bps" bits */
  98927. if(FLAC__bitmath_ilog2(default_partition_samples) + bps < 32) {
  98928. precompute_partition_info_sums_32bit_asm_ia32_(residual, abs_residual_partition_sums, residual_samples + predictor_order, predictor_order, min_partition_order, max_partition_order);
  98929. return;
  98930. }
  98931. #endif
  98932. /* first do max_partition_order */
  98933. {
  98934. unsigned partition, residual_sample, end = (unsigned)(-(int)predictor_order);
  98935. /* slightly pessimistic but still catches all common cases */
  98936. /* WATCHOUT: "+ bps" is an assumption that the average residual magnitude will not be more than "bps" bits */
  98937. if(FLAC__bitmath_ilog2(default_partition_samples) + bps < 32) {
  98938. FLAC__uint32 abs_residual_partition_sum;
  98939. for(partition = residual_sample = 0; partition < partitions; partition++) {
  98940. end += default_partition_samples;
  98941. abs_residual_partition_sum = 0;
  98942. for( ; residual_sample < end; residual_sample++)
  98943. abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */
  98944. abs_residual_partition_sums[partition] = abs_residual_partition_sum;
  98945. }
  98946. }
  98947. else { /* have to pessimistically use 64 bits for accumulator */
  98948. FLAC__uint64 abs_residual_partition_sum;
  98949. for(partition = residual_sample = 0; partition < partitions; partition++) {
  98950. end += default_partition_samples;
  98951. abs_residual_partition_sum = 0;
  98952. for( ; residual_sample < end; residual_sample++)
  98953. abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */
  98954. abs_residual_partition_sums[partition] = abs_residual_partition_sum;
  98955. }
  98956. }
  98957. }
  98958. /* now merge partitions for lower orders */
  98959. {
  98960. unsigned from_partition = 0, to_partition = partitions;
  98961. int partition_order;
  98962. for(partition_order = (int)max_partition_order - 1; partition_order >= (int)min_partition_order; partition_order--) {
  98963. unsigned i;
  98964. partitions >>= 1;
  98965. for(i = 0; i < partitions; i++) {
  98966. abs_residual_partition_sums[to_partition++] =
  98967. abs_residual_partition_sums[from_partition ] +
  98968. abs_residual_partition_sums[from_partition+1];
  98969. from_partition += 2;
  98970. }
  98971. }
  98972. }
  98973. }
  98974. void precompute_partition_info_escapes_(
  98975. const FLAC__int32 residual[],
  98976. unsigned raw_bits_per_partition[],
  98977. unsigned residual_samples,
  98978. unsigned predictor_order,
  98979. unsigned min_partition_order,
  98980. unsigned max_partition_order
  98981. )
  98982. {
  98983. int partition_order;
  98984. unsigned from_partition, to_partition = 0;
  98985. const unsigned blocksize = residual_samples + predictor_order;
  98986. /* first do max_partition_order */
  98987. for(partition_order = (int)max_partition_order; partition_order >= 0; partition_order--) {
  98988. FLAC__int32 r;
  98989. FLAC__uint32 rmax;
  98990. unsigned partition, partition_sample, partition_samples, residual_sample;
  98991. const unsigned partitions = 1u << partition_order;
  98992. const unsigned default_partition_samples = blocksize >> partition_order;
  98993. FLAC__ASSERT(default_partition_samples > predictor_order);
  98994. for(partition = residual_sample = 0; partition < partitions; partition++) {
  98995. partition_samples = default_partition_samples;
  98996. if(partition == 0)
  98997. partition_samples -= predictor_order;
  98998. rmax = 0;
  98999. for(partition_sample = 0; partition_sample < partition_samples; partition_sample++) {
  99000. r = residual[residual_sample++];
  99001. /* OPT: maybe faster: rmax |= r ^ (r>>31) */
  99002. if(r < 0)
  99003. rmax |= ~r;
  99004. else
  99005. rmax |= r;
  99006. }
  99007. /* now we know all residual values are in the range [-rmax-1,rmax] */
  99008. raw_bits_per_partition[partition] = rmax? FLAC__bitmath_ilog2(rmax) + 2 : 1;
  99009. }
  99010. to_partition = partitions;
  99011. break; /*@@@ yuck, should remove the 'for' loop instead */
  99012. }
  99013. /* now merge partitions for lower orders */
  99014. for(from_partition = 0, --partition_order; partition_order >= (int)min_partition_order; partition_order--) {
  99015. unsigned m;
  99016. unsigned i;
  99017. const unsigned partitions = 1u << partition_order;
  99018. for(i = 0; i < partitions; i++) {
  99019. m = raw_bits_per_partition[from_partition];
  99020. from_partition++;
  99021. raw_bits_per_partition[to_partition] = max(m, raw_bits_per_partition[from_partition]);
  99022. from_partition++;
  99023. to_partition++;
  99024. }
  99025. }
  99026. }
  99027. #ifdef EXACT_RICE_BITS_CALCULATION
  99028. static FLaC__INLINE unsigned count_rice_bits_in_partition_(
  99029. const unsigned rice_parameter,
  99030. const unsigned partition_samples,
  99031. const FLAC__int32 *residual
  99032. )
  99033. {
  99034. unsigned i, partition_bits =
  99035. 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 */
  99036. (1+rice_parameter) * partition_samples /* 1 for unary stop bit + rice_parameter for the binary portion */
  99037. ;
  99038. for(i = 0; i < partition_samples; i++)
  99039. partition_bits += ( (FLAC__uint32)((residual[i]<<1)^(residual[i]>>31)) >> rice_parameter );
  99040. return partition_bits;
  99041. }
  99042. #else
  99043. static FLaC__INLINE unsigned count_rice_bits_in_partition_(
  99044. const unsigned rice_parameter,
  99045. const unsigned partition_samples,
  99046. const FLAC__uint64 abs_residual_partition_sum
  99047. )
  99048. {
  99049. return
  99050. 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 */
  99051. (1+rice_parameter) * partition_samples + /* 1 for unary stop bit + rice_parameter for the binary portion */
  99052. (
  99053. rice_parameter?
  99054. (unsigned)(abs_residual_partition_sum >> (rice_parameter-1)) /* rice_parameter-1 because the real coder sign-folds instead of using a sign bit */
  99055. : (unsigned)(abs_residual_partition_sum << 1) /* can't shift by negative number, so reverse */
  99056. )
  99057. - (partition_samples >> 1)
  99058. /* -(partition_samples>>1) to subtract out extra contributions to the abs_residual_partition_sum.
  99059. * The actual number of bits used is closer to the sum(for all i in the partition) of abs(residual[i])>>(rice_parameter-1)
  99060. * By using the abs_residual_partition sum, we also add in bits in the LSBs that would normally be shifted out.
  99061. * So the subtraction term tries to guess how many extra bits were contributed.
  99062. * If the LSBs are randomly distributed, this should average to 0.5 extra bits per sample.
  99063. */
  99064. ;
  99065. }
  99066. #endif
  99067. FLAC__bool set_partitioned_rice_(
  99068. #ifdef EXACT_RICE_BITS_CALCULATION
  99069. const FLAC__int32 residual[],
  99070. #endif
  99071. const FLAC__uint64 abs_residual_partition_sums[],
  99072. const unsigned raw_bits_per_partition[],
  99073. const unsigned residual_samples,
  99074. const unsigned predictor_order,
  99075. const unsigned suggested_rice_parameter,
  99076. const unsigned rice_parameter_limit,
  99077. const unsigned rice_parameter_search_dist,
  99078. const unsigned partition_order,
  99079. const FLAC__bool search_for_escapes,
  99080. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
  99081. unsigned *bits
  99082. )
  99083. {
  99084. unsigned rice_parameter, partition_bits;
  99085. unsigned best_partition_bits, best_rice_parameter = 0;
  99086. unsigned bits_ = FLAC__ENTROPY_CODING_METHOD_TYPE_LEN + FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN;
  99087. unsigned *parameters, *raw_bits;
  99088. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  99089. unsigned min_rice_parameter, max_rice_parameter;
  99090. #else
  99091. (void)rice_parameter_search_dist;
  99092. #endif
  99093. FLAC__ASSERT(suggested_rice_parameter < FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER);
  99094. FLAC__ASSERT(rice_parameter_limit <= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER);
  99095. FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order));
  99096. parameters = partitioned_rice_contents->parameters;
  99097. raw_bits = partitioned_rice_contents->raw_bits;
  99098. if(partition_order == 0) {
  99099. best_partition_bits = (unsigned)(-1);
  99100. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  99101. if(rice_parameter_search_dist) {
  99102. if(suggested_rice_parameter < rice_parameter_search_dist)
  99103. min_rice_parameter = 0;
  99104. else
  99105. min_rice_parameter = suggested_rice_parameter - rice_parameter_search_dist;
  99106. max_rice_parameter = suggested_rice_parameter + rice_parameter_search_dist;
  99107. if(max_rice_parameter >= rice_parameter_limit) {
  99108. #ifdef DEBUG_VERBOSE
  99109. fprintf(stderr, "clipping rice_parameter (%u -> %u) @5\n", max_rice_parameter, rice_parameter_limit - 1);
  99110. #endif
  99111. max_rice_parameter = rice_parameter_limit - 1;
  99112. }
  99113. }
  99114. else
  99115. min_rice_parameter = max_rice_parameter = suggested_rice_parameter;
  99116. for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
  99117. #else
  99118. rice_parameter = suggested_rice_parameter;
  99119. #endif
  99120. #ifdef EXACT_RICE_BITS_CALCULATION
  99121. partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, residual);
  99122. #else
  99123. partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, abs_residual_partition_sums[0]);
  99124. #endif
  99125. if(partition_bits < best_partition_bits) {
  99126. best_rice_parameter = rice_parameter;
  99127. best_partition_bits = partition_bits;
  99128. }
  99129. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  99130. }
  99131. #endif
  99132. if(search_for_escapes) {
  99133. 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;
  99134. if(partition_bits <= best_partition_bits) {
  99135. raw_bits[0] = raw_bits_per_partition[0];
  99136. best_rice_parameter = 0; /* will be converted to appropriate escape parameter later */
  99137. best_partition_bits = partition_bits;
  99138. }
  99139. else
  99140. raw_bits[0] = 0;
  99141. }
  99142. parameters[0] = best_rice_parameter;
  99143. bits_ += best_partition_bits;
  99144. }
  99145. else {
  99146. unsigned partition, residual_sample;
  99147. unsigned partition_samples;
  99148. FLAC__uint64 mean, k;
  99149. const unsigned partitions = 1u << partition_order;
  99150. for(partition = residual_sample = 0; partition < partitions; partition++) {
  99151. partition_samples = (residual_samples+predictor_order) >> partition_order;
  99152. if(partition == 0) {
  99153. if(partition_samples <= predictor_order)
  99154. return false;
  99155. else
  99156. partition_samples -= predictor_order;
  99157. }
  99158. mean = abs_residual_partition_sums[partition];
  99159. /* we are basically calculating the size in bits of the
  99160. * average residual magnitude in the partition:
  99161. * rice_parameter = floor(log2(mean/partition_samples))
  99162. * 'mean' is not a good name for the variable, it is
  99163. * actually the sum of magnitudes of all residual values
  99164. * in the partition, so the actual mean is
  99165. * mean/partition_samples
  99166. */
  99167. for(rice_parameter = 0, k = partition_samples; k < mean; rice_parameter++, k <<= 1)
  99168. ;
  99169. if(rice_parameter >= rice_parameter_limit) {
  99170. #ifdef DEBUG_VERBOSE
  99171. fprintf(stderr, "clipping rice_parameter (%u -> %u) @6\n", rice_parameter, rice_parameter_limit - 1);
  99172. #endif
  99173. rice_parameter = rice_parameter_limit - 1;
  99174. }
  99175. best_partition_bits = (unsigned)(-1);
  99176. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  99177. if(rice_parameter_search_dist) {
  99178. if(rice_parameter < rice_parameter_search_dist)
  99179. min_rice_parameter = 0;
  99180. else
  99181. min_rice_parameter = rice_parameter - rice_parameter_search_dist;
  99182. max_rice_parameter = rice_parameter + rice_parameter_search_dist;
  99183. if(max_rice_parameter >= rice_parameter_limit) {
  99184. #ifdef DEBUG_VERBOSE
  99185. fprintf(stderr, "clipping rice_parameter (%u -> %u) @7\n", max_rice_parameter, rice_parameter_limit - 1);
  99186. #endif
  99187. max_rice_parameter = rice_parameter_limit - 1;
  99188. }
  99189. }
  99190. else
  99191. min_rice_parameter = max_rice_parameter = rice_parameter;
  99192. for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
  99193. #endif
  99194. #ifdef EXACT_RICE_BITS_CALCULATION
  99195. partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, residual+residual_sample);
  99196. #else
  99197. partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, abs_residual_partition_sums[partition]);
  99198. #endif
  99199. if(partition_bits < best_partition_bits) {
  99200. best_rice_parameter = rice_parameter;
  99201. best_partition_bits = partition_bits;
  99202. }
  99203. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  99204. }
  99205. #endif
  99206. if(search_for_escapes) {
  99207. 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;
  99208. if(partition_bits <= best_partition_bits) {
  99209. raw_bits[partition] = raw_bits_per_partition[partition];
  99210. best_rice_parameter = 0; /* will be converted to appropriate escape parameter later */
  99211. best_partition_bits = partition_bits;
  99212. }
  99213. else
  99214. raw_bits[partition] = 0;
  99215. }
  99216. parameters[partition] = best_rice_parameter;
  99217. bits_ += best_partition_bits;
  99218. residual_sample += partition_samples;
  99219. }
  99220. }
  99221. *bits = bits_;
  99222. return true;
  99223. }
  99224. unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples)
  99225. {
  99226. unsigned i, shift;
  99227. FLAC__int32 x = 0;
  99228. for(i = 0; i < samples && !(x&1); i++)
  99229. x |= signal[i];
  99230. if(x == 0) {
  99231. shift = 0;
  99232. }
  99233. else {
  99234. for(shift = 0; !(x&1); shift++)
  99235. x >>= 1;
  99236. }
  99237. if(shift > 0) {
  99238. for(i = 0; i < samples; i++)
  99239. signal[i] >>= shift;
  99240. }
  99241. return shift;
  99242. }
  99243. void append_to_verify_fifo_(verify_input_fifo *fifo, const FLAC__int32 * const input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
  99244. {
  99245. unsigned channel;
  99246. for(channel = 0; channel < channels; channel++)
  99247. memcpy(&fifo->data[channel][fifo->tail], &input[channel][input_offset], sizeof(FLAC__int32) * wide_samples);
  99248. fifo->tail += wide_samples;
  99249. FLAC__ASSERT(fifo->tail <= fifo->size);
  99250. }
  99251. void append_to_verify_fifo_interleaved_(verify_input_fifo *fifo, const FLAC__int32 input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
  99252. {
  99253. unsigned channel;
  99254. unsigned sample, wide_sample;
  99255. unsigned tail = fifo->tail;
  99256. sample = input_offset * channels;
  99257. for(wide_sample = 0; wide_sample < wide_samples; wide_sample++) {
  99258. for(channel = 0; channel < channels; channel++)
  99259. fifo->data[channel][tail] = input[sample++];
  99260. tail++;
  99261. }
  99262. fifo->tail = tail;
  99263. FLAC__ASSERT(fifo->tail <= fifo->size);
  99264. }
  99265. FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  99266. {
  99267. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
  99268. const size_t encoded_bytes = encoder->private_->verify.output.bytes;
  99269. (void)decoder;
  99270. if(encoder->private_->verify.needs_magic_hack) {
  99271. FLAC__ASSERT(*bytes >= FLAC__STREAM_SYNC_LENGTH);
  99272. *bytes = FLAC__STREAM_SYNC_LENGTH;
  99273. memcpy(buffer, FLAC__STREAM_SYNC_STRING, *bytes);
  99274. encoder->private_->verify.needs_magic_hack = false;
  99275. }
  99276. else {
  99277. if(encoded_bytes == 0) {
  99278. /*
  99279. * If we get here, a FIFO underflow has occurred,
  99280. * which means there is a bug somewhere.
  99281. */
  99282. FLAC__ASSERT(0);
  99283. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  99284. }
  99285. else if(encoded_bytes < *bytes)
  99286. *bytes = encoded_bytes;
  99287. memcpy(buffer, encoder->private_->verify.output.data, *bytes);
  99288. encoder->private_->verify.output.data += *bytes;
  99289. encoder->private_->verify.output.bytes -= *bytes;
  99290. }
  99291. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  99292. }
  99293. FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data)
  99294. {
  99295. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder *)client_data;
  99296. unsigned channel;
  99297. const unsigned channels = frame->header.channels;
  99298. const unsigned blocksize = frame->header.blocksize;
  99299. const unsigned bytes_per_block = sizeof(FLAC__int32) * blocksize;
  99300. (void)decoder;
  99301. for(channel = 0; channel < channels; channel++) {
  99302. if(0 != memcmp(buffer[channel], encoder->private_->verify.input_fifo.data[channel], bytes_per_block)) {
  99303. unsigned i, sample = 0;
  99304. FLAC__int32 expect = 0, got = 0;
  99305. for(i = 0; i < blocksize; i++) {
  99306. if(buffer[channel][i] != encoder->private_->verify.input_fifo.data[channel][i]) {
  99307. sample = i;
  99308. expect = (FLAC__int32)encoder->private_->verify.input_fifo.data[channel][i];
  99309. got = (FLAC__int32)buffer[channel][i];
  99310. break;
  99311. }
  99312. }
  99313. FLAC__ASSERT(i < blocksize);
  99314. FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  99315. encoder->private_->verify.error_stats.absolute_sample = frame->header.number.sample_number + sample;
  99316. encoder->private_->verify.error_stats.frame_number = (unsigned)(frame->header.number.sample_number / blocksize);
  99317. encoder->private_->verify.error_stats.channel = channel;
  99318. encoder->private_->verify.error_stats.sample = sample;
  99319. encoder->private_->verify.error_stats.expected = expect;
  99320. encoder->private_->verify.error_stats.got = got;
  99321. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
  99322. return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
  99323. }
  99324. }
  99325. /* dequeue the frame from the fifo */
  99326. encoder->private_->verify.input_fifo.tail -= blocksize;
  99327. FLAC__ASSERT(encoder->private_->verify.input_fifo.tail <= OVERREAD_);
  99328. for(channel = 0; channel < channels; channel++)
  99329. 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]));
  99330. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  99331. }
  99332. void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
  99333. {
  99334. (void)decoder, (void)metadata, (void)client_data;
  99335. }
  99336. void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
  99337. {
  99338. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
  99339. (void)decoder, (void)status;
  99340. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  99341. }
  99342. FLAC__StreamEncoderReadStatus file_read_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  99343. {
  99344. (void)client_data;
  99345. *bytes = fread(buffer, 1, *bytes, encoder->private_->file);
  99346. if (*bytes == 0) {
  99347. if (feof(encoder->private_->file))
  99348. return FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM;
  99349. else if (ferror(encoder->private_->file))
  99350. return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  99351. }
  99352. return FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE;
  99353. }
  99354. FLAC__StreamEncoderSeekStatus file_seek_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  99355. {
  99356. (void)client_data;
  99357. if(fseeko(encoder->private_->file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  99358. return FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR;
  99359. else
  99360. return FLAC__STREAM_ENCODER_SEEK_STATUS_OK;
  99361. }
  99362. FLAC__StreamEncoderTellStatus file_tell_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  99363. {
  99364. off_t offset;
  99365. (void)client_data;
  99366. offset = ftello(encoder->private_->file);
  99367. if(offset < 0) {
  99368. return FLAC__STREAM_ENCODER_TELL_STATUS_ERROR;
  99369. }
  99370. else {
  99371. *absolute_byte_offset = (FLAC__uint64)offset;
  99372. return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  99373. }
  99374. }
  99375. #ifdef FLAC__VALGRIND_TESTING
  99376. static size_t local__fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream)
  99377. {
  99378. size_t ret = fwrite(ptr, size, nmemb, stream);
  99379. if(!ferror(stream))
  99380. fflush(stream);
  99381. return ret;
  99382. }
  99383. #else
  99384. #define local__fwrite fwrite
  99385. #endif
  99386. FLAC__StreamEncoderWriteStatus file_write_callback_(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data)
  99387. {
  99388. (void)client_data, (void)current_frame;
  99389. if(local__fwrite(buffer, sizeof(FLAC__byte), bytes, encoder->private_->file) == bytes) {
  99390. FLAC__bool call_it = 0 != encoder->private_->progress_callback && (
  99391. #if FLAC__HAS_OGG
  99392. /* We would like to be able to use 'samples > 0' in the
  99393. * clause here but currently because of the nature of our
  99394. * Ogg writing implementation, 'samples' is always 0 (see
  99395. * ogg_encoder_aspect.c). The downside is extra progress
  99396. * callbacks.
  99397. */
  99398. encoder->private_->is_ogg? true :
  99399. #endif
  99400. samples > 0
  99401. );
  99402. if(call_it) {
  99403. /* NOTE: We have to add +bytes, +samples, and +1 to the stats
  99404. * because at this point in the callback chain, the stats
  99405. * have not been updated. Only after we return and control
  99406. * gets back to write_frame_() are the stats updated
  99407. */
  99408. 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);
  99409. }
  99410. return FLAC__STREAM_ENCODER_WRITE_STATUS_OK;
  99411. }
  99412. else
  99413. return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  99414. }
  99415. /*
  99416. * This will forcibly set stdout to binary mode (for OSes that require it)
  99417. */
  99418. FILE *get_binary_stdout_(void)
  99419. {
  99420. /* if something breaks here it is probably due to the presence or
  99421. * absence of an underscore before the identifiers 'setmode',
  99422. * 'fileno', and/or 'O_BINARY'; check your system header files.
  99423. */
  99424. #if defined _MSC_VER || defined __MINGW32__
  99425. _setmode(_fileno(stdout), _O_BINARY);
  99426. #elif defined __CYGWIN__
  99427. /* almost certainly not needed for any modern Cygwin, but let's be safe... */
  99428. setmode(_fileno(stdout), _O_BINARY);
  99429. #elif defined __EMX__
  99430. setmode(fileno(stdout), O_BINARY);
  99431. #endif
  99432. return stdout;
  99433. }
  99434. #endif
  99435. /********* End of inlined file: stream_encoder.c *********/
  99436. /********* Start of inlined file: stream_encoder_framing.c *********/
  99437. /********* Start of inlined file: juce_FlacHeader.h *********/
  99438. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  99439. // tasks..
  99440. #define VERSION "1.2.1"
  99441. #define FLAC__NO_DLL 1
  99442. #ifdef _MSC_VER
  99443. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  99444. #endif
  99445. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  99446. #define FLAC__SYS_DARWIN 1
  99447. #endif
  99448. /********* End of inlined file: juce_FlacHeader.h *********/
  99449. #if JUCE_USE_FLAC
  99450. #if HAVE_CONFIG_H
  99451. # include <config.h>
  99452. #endif
  99453. #include <stdio.h>
  99454. #include <string.h> /* for strlen() */
  99455. #ifdef max
  99456. #undef max
  99457. #endif
  99458. #define max(x,y) ((x)>(y)?(x):(y))
  99459. static FLAC__bool add_entropy_coding_method_(FLAC__BitWriter *bw, const FLAC__EntropyCodingMethod *method);
  99460. 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);
  99461. FLAC__bool FLAC__add_metadata_block(const FLAC__StreamMetadata *metadata, FLAC__BitWriter *bw)
  99462. {
  99463. unsigned i, j;
  99464. const unsigned vendor_string_length = (unsigned)strlen(FLAC__VENDOR_STRING);
  99465. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->is_last, FLAC__STREAM_METADATA_IS_LAST_LEN))
  99466. return false;
  99467. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->type, FLAC__STREAM_METADATA_TYPE_LEN))
  99468. return false;
  99469. /*
  99470. * First, for VORBIS_COMMENTs, adjust the length to reflect our vendor string
  99471. */
  99472. i = metadata->length;
  99473. if(metadata->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  99474. FLAC__ASSERT(metadata->data.vorbis_comment.vendor_string.length == 0 || 0 != metadata->data.vorbis_comment.vendor_string.entry);
  99475. i -= metadata->data.vorbis_comment.vendor_string.length;
  99476. i += vendor_string_length;
  99477. }
  99478. FLAC__ASSERT(i < (1u << FLAC__STREAM_METADATA_LENGTH_LEN));
  99479. if(!FLAC__bitwriter_write_raw_uint32(bw, i, FLAC__STREAM_METADATA_LENGTH_LEN))
  99480. return false;
  99481. switch(metadata->type) {
  99482. case FLAC__METADATA_TYPE_STREAMINFO:
  99483. FLAC__ASSERT(metadata->data.stream_info.min_blocksize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN));
  99484. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.min_blocksize, FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN))
  99485. return false;
  99486. FLAC__ASSERT(metadata->data.stream_info.max_blocksize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN));
  99487. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.max_blocksize, FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN))
  99488. return false;
  99489. FLAC__ASSERT(metadata->data.stream_info.min_framesize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN));
  99490. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.min_framesize, FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN))
  99491. return false;
  99492. FLAC__ASSERT(metadata->data.stream_info.max_framesize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN));
  99493. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.max_framesize, FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN))
  99494. return false;
  99495. FLAC__ASSERT(FLAC__format_sample_rate_is_valid(metadata->data.stream_info.sample_rate));
  99496. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.sample_rate, FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN))
  99497. return false;
  99498. FLAC__ASSERT(metadata->data.stream_info.channels > 0);
  99499. FLAC__ASSERT(metadata->data.stream_info.channels <= (1u << FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN));
  99500. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.channels-1, FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN))
  99501. return false;
  99502. FLAC__ASSERT(metadata->data.stream_info.bits_per_sample > 0);
  99503. FLAC__ASSERT(metadata->data.stream_info.bits_per_sample <= (1u << FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN));
  99504. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.bits_per_sample-1, FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN))
  99505. return false;
  99506. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.stream_info.total_samples, FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN))
  99507. return false;
  99508. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.stream_info.md5sum, 16))
  99509. return false;
  99510. break;
  99511. case FLAC__METADATA_TYPE_PADDING:
  99512. if(!FLAC__bitwriter_write_zeroes(bw, metadata->length * 8))
  99513. return false;
  99514. break;
  99515. case FLAC__METADATA_TYPE_APPLICATION:
  99516. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.application.id, FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8))
  99517. return false;
  99518. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.application.data, metadata->length - (FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8)))
  99519. return false;
  99520. break;
  99521. case FLAC__METADATA_TYPE_SEEKTABLE:
  99522. for(i = 0; i < metadata->data.seek_table.num_points; i++) {
  99523. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.seek_table.points[i].sample_number, FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN))
  99524. return false;
  99525. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.seek_table.points[i].stream_offset, FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN))
  99526. return false;
  99527. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.seek_table.points[i].frame_samples, FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN))
  99528. return false;
  99529. }
  99530. break;
  99531. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  99532. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, vendor_string_length))
  99533. return false;
  99534. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)FLAC__VENDOR_STRING, vendor_string_length))
  99535. return false;
  99536. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, metadata->data.vorbis_comment.num_comments))
  99537. return false;
  99538. for(i = 0; i < metadata->data.vorbis_comment.num_comments; i++) {
  99539. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, metadata->data.vorbis_comment.comments[i].length))
  99540. return false;
  99541. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.vorbis_comment.comments[i].entry, metadata->data.vorbis_comment.comments[i].length))
  99542. return false;
  99543. }
  99544. break;
  99545. case FLAC__METADATA_TYPE_CUESHEET:
  99546. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN % 8 == 0);
  99547. 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))
  99548. return false;
  99549. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.cue_sheet.lead_in, FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN))
  99550. return false;
  99551. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.cue_sheet.is_cd? 1 : 0, FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN))
  99552. return false;
  99553. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN))
  99554. return false;
  99555. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.cue_sheet.num_tracks, FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN))
  99556. return false;
  99557. for(i = 0; i < metadata->data.cue_sheet.num_tracks; i++) {
  99558. const FLAC__StreamMetadata_CueSheet_Track *track = metadata->data.cue_sheet.tracks + i;
  99559. if(!FLAC__bitwriter_write_raw_uint64(bw, track->offset, FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN))
  99560. return false;
  99561. if(!FLAC__bitwriter_write_raw_uint32(bw, track->number, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN))
  99562. return false;
  99563. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN % 8 == 0);
  99564. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)track->isrc, FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN/8))
  99565. return false;
  99566. if(!FLAC__bitwriter_write_raw_uint32(bw, track->type, FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN))
  99567. return false;
  99568. if(!FLAC__bitwriter_write_raw_uint32(bw, track->pre_emphasis, FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN))
  99569. return false;
  99570. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN))
  99571. return false;
  99572. if(!FLAC__bitwriter_write_raw_uint32(bw, track->num_indices, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN))
  99573. return false;
  99574. for(j = 0; j < track->num_indices; j++) {
  99575. const FLAC__StreamMetadata_CueSheet_Index *index = track->indices + j;
  99576. if(!FLAC__bitwriter_write_raw_uint64(bw, index->offset, FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN))
  99577. return false;
  99578. if(!FLAC__bitwriter_write_raw_uint32(bw, index->number, FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN))
  99579. return false;
  99580. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN))
  99581. return false;
  99582. }
  99583. }
  99584. break;
  99585. case FLAC__METADATA_TYPE_PICTURE:
  99586. {
  99587. size_t len;
  99588. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.type, FLAC__STREAM_METADATA_PICTURE_TYPE_LEN))
  99589. return false;
  99590. len = strlen(metadata->data.picture.mime_type);
  99591. if(!FLAC__bitwriter_write_raw_uint32(bw, len, FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN))
  99592. return false;
  99593. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)metadata->data.picture.mime_type, len))
  99594. return false;
  99595. len = strlen((const char *)metadata->data.picture.description);
  99596. if(!FLAC__bitwriter_write_raw_uint32(bw, len, FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN))
  99597. return false;
  99598. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.picture.description, len))
  99599. return false;
  99600. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.width, FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN))
  99601. return false;
  99602. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.height, FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN))
  99603. return false;
  99604. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.depth, FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN))
  99605. return false;
  99606. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.colors, FLAC__STREAM_METADATA_PICTURE_COLORS_LEN))
  99607. return false;
  99608. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.data_length, FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN))
  99609. return false;
  99610. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.picture.data, metadata->data.picture.data_length))
  99611. return false;
  99612. }
  99613. break;
  99614. default:
  99615. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.unknown.data, metadata->length))
  99616. return false;
  99617. break;
  99618. }
  99619. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(bw));
  99620. return true;
  99621. }
  99622. FLAC__bool FLAC__frame_add_header(const FLAC__FrameHeader *header, FLAC__BitWriter *bw)
  99623. {
  99624. unsigned u, blocksize_hint, sample_rate_hint;
  99625. FLAC__byte crc;
  99626. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(bw));
  99627. if(!FLAC__bitwriter_write_raw_uint32(bw, FLAC__FRAME_HEADER_SYNC, FLAC__FRAME_HEADER_SYNC_LEN))
  99628. return false;
  99629. if(!FLAC__bitwriter_write_raw_uint32(bw, 0, FLAC__FRAME_HEADER_RESERVED_LEN))
  99630. return false;
  99631. if(!FLAC__bitwriter_write_raw_uint32(bw, (header->number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER)? 0 : 1, FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN))
  99632. return false;
  99633. FLAC__ASSERT(header->blocksize > 0 && header->blocksize <= FLAC__MAX_BLOCK_SIZE);
  99634. /* when this assertion holds true, any legal blocksize can be expressed in the frame header */
  99635. FLAC__ASSERT(FLAC__MAX_BLOCK_SIZE <= 65535u);
  99636. blocksize_hint = 0;
  99637. switch(header->blocksize) {
  99638. case 192: u = 1; break;
  99639. case 576: u = 2; break;
  99640. case 1152: u = 3; break;
  99641. case 2304: u = 4; break;
  99642. case 4608: u = 5; break;
  99643. case 256: u = 8; break;
  99644. case 512: u = 9; break;
  99645. case 1024: u = 10; break;
  99646. case 2048: u = 11; break;
  99647. case 4096: u = 12; break;
  99648. case 8192: u = 13; break;
  99649. case 16384: u = 14; break;
  99650. case 32768: u = 15; break;
  99651. default:
  99652. if(header->blocksize <= 0x100)
  99653. blocksize_hint = u = 6;
  99654. else
  99655. blocksize_hint = u = 7;
  99656. break;
  99657. }
  99658. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_BLOCK_SIZE_LEN))
  99659. return false;
  99660. FLAC__ASSERT(FLAC__format_sample_rate_is_valid(header->sample_rate));
  99661. sample_rate_hint = 0;
  99662. switch(header->sample_rate) {
  99663. case 88200: u = 1; break;
  99664. case 176400: u = 2; break;
  99665. case 192000: u = 3; break;
  99666. case 8000: u = 4; break;
  99667. case 16000: u = 5; break;
  99668. case 22050: u = 6; break;
  99669. case 24000: u = 7; break;
  99670. case 32000: u = 8; break;
  99671. case 44100: u = 9; break;
  99672. case 48000: u = 10; break;
  99673. case 96000: u = 11; break;
  99674. default:
  99675. if(header->sample_rate <= 255000 && header->sample_rate % 1000 == 0)
  99676. sample_rate_hint = u = 12;
  99677. else if(header->sample_rate % 10 == 0)
  99678. sample_rate_hint = u = 14;
  99679. else if(header->sample_rate <= 0xffff)
  99680. sample_rate_hint = u = 13;
  99681. else
  99682. u = 0;
  99683. break;
  99684. }
  99685. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_SAMPLE_RATE_LEN))
  99686. return false;
  99687. FLAC__ASSERT(header->channels > 0 && header->channels <= (1u << FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN) && header->channels <= FLAC__MAX_CHANNELS);
  99688. switch(header->channel_assignment) {
  99689. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  99690. u = header->channels - 1;
  99691. break;
  99692. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  99693. FLAC__ASSERT(header->channels == 2);
  99694. u = 8;
  99695. break;
  99696. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  99697. FLAC__ASSERT(header->channels == 2);
  99698. u = 9;
  99699. break;
  99700. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  99701. FLAC__ASSERT(header->channels == 2);
  99702. u = 10;
  99703. break;
  99704. default:
  99705. FLAC__ASSERT(0);
  99706. }
  99707. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN))
  99708. return false;
  99709. FLAC__ASSERT(header->bits_per_sample > 0 && header->bits_per_sample <= (1u << FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN));
  99710. switch(header->bits_per_sample) {
  99711. case 8 : u = 1; break;
  99712. case 12: u = 2; break;
  99713. case 16: u = 4; break;
  99714. case 20: u = 5; break;
  99715. case 24: u = 6; break;
  99716. default: u = 0; break;
  99717. }
  99718. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN))
  99719. return false;
  99720. if(!FLAC__bitwriter_write_raw_uint32(bw, 0, FLAC__FRAME_HEADER_ZERO_PAD_LEN))
  99721. return false;
  99722. if(header->number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER) {
  99723. if(!FLAC__bitwriter_write_utf8_uint32(bw, header->number.frame_number))
  99724. return false;
  99725. }
  99726. else {
  99727. if(!FLAC__bitwriter_write_utf8_uint64(bw, header->number.sample_number))
  99728. return false;
  99729. }
  99730. if(blocksize_hint)
  99731. if(!FLAC__bitwriter_write_raw_uint32(bw, header->blocksize-1, (blocksize_hint==6)? 8:16))
  99732. return false;
  99733. switch(sample_rate_hint) {
  99734. case 12:
  99735. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate / 1000, 8))
  99736. return false;
  99737. break;
  99738. case 13:
  99739. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate, 16))
  99740. return false;
  99741. break;
  99742. case 14:
  99743. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate / 10, 16))
  99744. return false;
  99745. break;
  99746. }
  99747. /* write the CRC */
  99748. if(!FLAC__bitwriter_get_write_crc8(bw, &crc))
  99749. return false;
  99750. if(!FLAC__bitwriter_write_raw_uint32(bw, crc, FLAC__FRAME_HEADER_CRC_LEN))
  99751. return false;
  99752. return true;
  99753. }
  99754. FLAC__bool FLAC__subframe_add_constant(const FLAC__Subframe_Constant *subframe, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  99755. {
  99756. FLAC__bool ok;
  99757. ok =
  99758. 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) &&
  99759. (wasted_bits? FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1) : true) &&
  99760. FLAC__bitwriter_write_raw_int32(bw, subframe->value, subframe_bps)
  99761. ;
  99762. return ok;
  99763. }
  99764. FLAC__bool FLAC__subframe_add_fixed(const FLAC__Subframe_Fixed *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  99765. {
  99766. unsigned i;
  99767. 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))
  99768. return false;
  99769. if(wasted_bits)
  99770. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  99771. return false;
  99772. for(i = 0; i < subframe->order; i++)
  99773. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->warmup[i], subframe_bps))
  99774. return false;
  99775. if(!add_entropy_coding_method_(bw, &subframe->entropy_coding_method))
  99776. return false;
  99777. switch(subframe->entropy_coding_method.type) {
  99778. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  99779. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  99780. if(!add_residual_partitioned_rice_(
  99781. bw,
  99782. subframe->residual,
  99783. residual_samples,
  99784. subframe->order,
  99785. subframe->entropy_coding_method.data.partitioned_rice.contents->parameters,
  99786. subframe->entropy_coding_method.data.partitioned_rice.contents->raw_bits,
  99787. subframe->entropy_coding_method.data.partitioned_rice.order,
  99788. /*is_extended=*/subframe->entropy_coding_method.type == FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2
  99789. ))
  99790. return false;
  99791. break;
  99792. default:
  99793. FLAC__ASSERT(0);
  99794. }
  99795. return true;
  99796. }
  99797. FLAC__bool FLAC__subframe_add_lpc(const FLAC__Subframe_LPC *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  99798. {
  99799. unsigned i;
  99800. 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))
  99801. return false;
  99802. if(wasted_bits)
  99803. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  99804. return false;
  99805. for(i = 0; i < subframe->order; i++)
  99806. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->warmup[i], subframe_bps))
  99807. return false;
  99808. if(!FLAC__bitwriter_write_raw_uint32(bw, subframe->qlp_coeff_precision-1, FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN))
  99809. return false;
  99810. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->quantization_level, FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN))
  99811. return false;
  99812. for(i = 0; i < subframe->order; i++)
  99813. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->qlp_coeff[i], subframe->qlp_coeff_precision))
  99814. return false;
  99815. if(!add_entropy_coding_method_(bw, &subframe->entropy_coding_method))
  99816. return false;
  99817. switch(subframe->entropy_coding_method.type) {
  99818. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  99819. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  99820. if(!add_residual_partitioned_rice_(
  99821. bw,
  99822. subframe->residual,
  99823. residual_samples,
  99824. subframe->order,
  99825. subframe->entropy_coding_method.data.partitioned_rice.contents->parameters,
  99826. subframe->entropy_coding_method.data.partitioned_rice.contents->raw_bits,
  99827. subframe->entropy_coding_method.data.partitioned_rice.order,
  99828. /*is_extended=*/subframe->entropy_coding_method.type == FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2
  99829. ))
  99830. return false;
  99831. break;
  99832. default:
  99833. FLAC__ASSERT(0);
  99834. }
  99835. return true;
  99836. }
  99837. FLAC__bool FLAC__subframe_add_verbatim(const FLAC__Subframe_Verbatim *subframe, unsigned samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  99838. {
  99839. unsigned i;
  99840. const FLAC__int32 *signal = subframe->data;
  99841. 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))
  99842. return false;
  99843. if(wasted_bits)
  99844. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  99845. return false;
  99846. for(i = 0; i < samples; i++)
  99847. if(!FLAC__bitwriter_write_raw_int32(bw, signal[i], subframe_bps))
  99848. return false;
  99849. return true;
  99850. }
  99851. FLAC__bool add_entropy_coding_method_(FLAC__BitWriter *bw, const FLAC__EntropyCodingMethod *method)
  99852. {
  99853. if(!FLAC__bitwriter_write_raw_uint32(bw, method->type, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  99854. return false;
  99855. switch(method->type) {
  99856. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  99857. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  99858. if(!FLAC__bitwriter_write_raw_uint32(bw, method->data.partitioned_rice.order, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  99859. return false;
  99860. break;
  99861. default:
  99862. FLAC__ASSERT(0);
  99863. }
  99864. return true;
  99865. }
  99866. 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)
  99867. {
  99868. const unsigned plen = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
  99869. const unsigned pesc = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  99870. if(partition_order == 0) {
  99871. unsigned i;
  99872. if(raw_bits[0] == 0) {
  99873. if(!FLAC__bitwriter_write_raw_uint32(bw, rice_parameters[0], plen))
  99874. return false;
  99875. if(!FLAC__bitwriter_write_rice_signed_block(bw, residual, residual_samples, rice_parameters[0]))
  99876. return false;
  99877. }
  99878. else {
  99879. FLAC__ASSERT(rice_parameters[0] == 0);
  99880. if(!FLAC__bitwriter_write_raw_uint32(bw, pesc, plen))
  99881. return false;
  99882. if(!FLAC__bitwriter_write_raw_uint32(bw, raw_bits[0], FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  99883. return false;
  99884. for(i = 0; i < residual_samples; i++) {
  99885. if(!FLAC__bitwriter_write_raw_int32(bw, residual[i], raw_bits[0]))
  99886. return false;
  99887. }
  99888. }
  99889. return true;
  99890. }
  99891. else {
  99892. unsigned i, j, k = 0, k_last = 0;
  99893. unsigned partition_samples;
  99894. const unsigned default_partition_samples = (residual_samples+predictor_order) >> partition_order;
  99895. for(i = 0; i < (1u<<partition_order); i++) {
  99896. partition_samples = default_partition_samples;
  99897. if(i == 0)
  99898. partition_samples -= predictor_order;
  99899. k += partition_samples;
  99900. if(raw_bits[i] == 0) {
  99901. if(!FLAC__bitwriter_write_raw_uint32(bw, rice_parameters[i], plen))
  99902. return false;
  99903. if(!FLAC__bitwriter_write_rice_signed_block(bw, residual+k_last, k-k_last, rice_parameters[i]))
  99904. return false;
  99905. }
  99906. else {
  99907. if(!FLAC__bitwriter_write_raw_uint32(bw, pesc, plen))
  99908. return false;
  99909. if(!FLAC__bitwriter_write_raw_uint32(bw, raw_bits[i], FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  99910. return false;
  99911. for(j = k_last; j < k; j++) {
  99912. if(!FLAC__bitwriter_write_raw_int32(bw, residual[j], raw_bits[i]))
  99913. return false;
  99914. }
  99915. }
  99916. k_last = k;
  99917. }
  99918. return true;
  99919. }
  99920. }
  99921. #endif
  99922. /********* End of inlined file: stream_encoder_framing.c *********/
  99923. /********* Start of inlined file: window_flac.c *********/
  99924. /********* Start of inlined file: juce_FlacHeader.h *********/
  99925. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  99926. // tasks..
  99927. #define VERSION "1.2.1"
  99928. #define FLAC__NO_DLL 1
  99929. #ifdef _MSC_VER
  99930. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  99931. #endif
  99932. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  99933. #define FLAC__SYS_DARWIN 1
  99934. #endif
  99935. /********* End of inlined file: juce_FlacHeader.h *********/
  99936. #if JUCE_USE_FLAC
  99937. #if HAVE_CONFIG_H
  99938. # include <config.h>
  99939. #endif
  99940. #include <math.h>
  99941. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99942. #ifndef M_PI
  99943. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  99944. #define M_PI 3.14159265358979323846
  99945. #endif
  99946. void FLAC__window_bartlett(FLAC__real *window, const FLAC__int32 L)
  99947. {
  99948. const FLAC__int32 N = L - 1;
  99949. FLAC__int32 n;
  99950. if (L & 1) {
  99951. for (n = 0; n <= N/2; n++)
  99952. window[n] = 2.0f * n / (float)N;
  99953. for (; n <= N; n++)
  99954. window[n] = 2.0f - 2.0f * n / (float)N;
  99955. }
  99956. else {
  99957. for (n = 0; n <= L/2-1; n++)
  99958. window[n] = 2.0f * n / (float)N;
  99959. for (; n <= N; n++)
  99960. window[n] = 2.0f - 2.0f * (N-n) / (float)N;
  99961. }
  99962. }
  99963. void FLAC__window_bartlett_hann(FLAC__real *window, const FLAC__int32 L)
  99964. {
  99965. const FLAC__int32 N = L - 1;
  99966. FLAC__int32 n;
  99967. for (n = 0; n < L; n++)
  99968. 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)));
  99969. }
  99970. void FLAC__window_blackman(FLAC__real *window, const FLAC__int32 L)
  99971. {
  99972. const FLAC__int32 N = L - 1;
  99973. FLAC__int32 n;
  99974. for (n = 0; n < L; n++)
  99975. window[n] = (FLAC__real)(0.42f - 0.5f * cos(2.0f * M_PI * n / N) + 0.08f * cos(4.0f * M_PI * n / N));
  99976. }
  99977. /* 4-term -92dB side-lobe */
  99978. void FLAC__window_blackman_harris_4term_92db_sidelobe(FLAC__real *window, const FLAC__int32 L)
  99979. {
  99980. const FLAC__int32 N = L - 1;
  99981. FLAC__int32 n;
  99982. for (n = 0; n <= N; n++)
  99983. 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));
  99984. }
  99985. void FLAC__window_connes(FLAC__real *window, const FLAC__int32 L)
  99986. {
  99987. const FLAC__int32 N = L - 1;
  99988. const double N2 = (double)N / 2.;
  99989. FLAC__int32 n;
  99990. for (n = 0; n <= N; n++) {
  99991. double k = ((double)n - N2) / N2;
  99992. k = 1.0f - k * k;
  99993. window[n] = (FLAC__real)(k * k);
  99994. }
  99995. }
  99996. void FLAC__window_flattop(FLAC__real *window, const FLAC__int32 L)
  99997. {
  99998. const FLAC__int32 N = L - 1;
  99999. FLAC__int32 n;
  100000. for (n = 0; n < L; n++)
  100001. 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));
  100002. }
  100003. void FLAC__window_gauss(FLAC__real *window, const FLAC__int32 L, const FLAC__real stddev)
  100004. {
  100005. const FLAC__int32 N = L - 1;
  100006. const double N2 = (double)N / 2.;
  100007. FLAC__int32 n;
  100008. for (n = 0; n <= N; n++) {
  100009. const double k = ((double)n - N2) / (stddev * N2);
  100010. window[n] = (FLAC__real)exp(-0.5f * k * k);
  100011. }
  100012. }
  100013. void FLAC__window_hamming(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.54f - 0.46f * cos(2.0f * M_PI * n / N));
  100019. }
  100020. void FLAC__window_hann(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.5f - 0.5f * cos(2.0f * M_PI * n / N));
  100026. }
  100027. void FLAC__window_kaiser_bessel(FLAC__real *window, const FLAC__int32 L)
  100028. {
  100029. const FLAC__int32 N = L - 1;
  100030. FLAC__int32 n;
  100031. for (n = 0; n < L; n++)
  100032. 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));
  100033. }
  100034. void FLAC__window_nuttall(FLAC__real *window, const FLAC__int32 L)
  100035. {
  100036. const FLAC__int32 N = L - 1;
  100037. FLAC__int32 n;
  100038. for (n = 0; n < L; n++)
  100039. 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));
  100040. }
  100041. void FLAC__window_rectangle(FLAC__real *window, const FLAC__int32 L)
  100042. {
  100043. FLAC__int32 n;
  100044. for (n = 0; n < L; n++)
  100045. window[n] = 1.0f;
  100046. }
  100047. void FLAC__window_triangle(FLAC__real *window, const FLAC__int32 L)
  100048. {
  100049. FLAC__int32 n;
  100050. if (L & 1) {
  100051. for (n = 1; n <= L+1/2; n++)
  100052. window[n-1] = 2.0f * n / ((float)L + 1.0f);
  100053. for (; n <= L; n++)
  100054. window[n-1] = - (float)(2 * (L - n + 1)) / ((float)L + 1.0f);
  100055. }
  100056. else {
  100057. for (n = 1; n <= L/2; n++)
  100058. window[n-1] = 2.0f * n / (float)L;
  100059. for (; n <= L; n++)
  100060. window[n-1] = ((float)(2 * (L - n)) + 1.0f) / (float)L;
  100061. }
  100062. }
  100063. void FLAC__window_tukey(FLAC__real *window, const FLAC__int32 L, const FLAC__real p)
  100064. {
  100065. if (p <= 0.0)
  100066. FLAC__window_rectangle(window, L);
  100067. else if (p >= 1.0)
  100068. FLAC__window_hann(window, L);
  100069. else {
  100070. const FLAC__int32 Np = (FLAC__int32)(p / 2.0f * L) - 1;
  100071. FLAC__int32 n;
  100072. /* start with rectangle... */
  100073. FLAC__window_rectangle(window, L);
  100074. /* ...replace ends with hann */
  100075. if (Np > 0) {
  100076. for (n = 0; n <= Np; n++) {
  100077. window[n] = (FLAC__real)(0.5f - 0.5f * cos(M_PI * n / Np));
  100078. window[L-Np-1+n] = (FLAC__real)(0.5f - 0.5f * cos(M_PI * (n+Np) / Np));
  100079. }
  100080. }
  100081. }
  100082. }
  100083. void FLAC__window_welch(FLAC__real *window, const FLAC__int32 L)
  100084. {
  100085. const FLAC__int32 N = L - 1;
  100086. const double N2 = (double)N / 2.;
  100087. FLAC__int32 n;
  100088. for (n = 0; n <= N; n++) {
  100089. const double k = ((double)n - N2) / N2;
  100090. window[n] = (FLAC__real)(1.0f - k * k);
  100091. }
  100092. }
  100093. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  100094. #endif
  100095. /********* End of inlined file: window_flac.c *********/
  100096. }
  100097. #ifdef _MSC_VER
  100098. #pragma warning (pop)
  100099. #endif
  100100. BEGIN_JUCE_NAMESPACE
  100101. using namespace FlacNamespace;
  100102. #define flacFormatName TRANS("FLAC file")
  100103. static const tchar* const flacExtensions[] = { T(".flac"), 0 };
  100104. class FlacReader : public AudioFormatReader
  100105. {
  100106. FLAC__StreamDecoder* decoder;
  100107. AudioSampleBuffer reservoir;
  100108. int reservoirStart, samplesInReservoir;
  100109. bool ok, scanningForLength;
  100110. public:
  100111. FlacReader (InputStream* const in)
  100112. : AudioFormatReader (in, flacFormatName),
  100113. reservoir (2, 0),
  100114. reservoirStart (0),
  100115. samplesInReservoir (0),
  100116. scanningForLength (false)
  100117. {
  100118. using namespace FlacNamespace;
  100119. lengthInSamples = 0;
  100120. decoder = FLAC__stream_decoder_new();
  100121. ok = FLAC__stream_decoder_init_stream (decoder,
  100122. readCallback_, seekCallback_, tellCallback_, lengthCallback_,
  100123. eofCallback_, writeCallback_, metadataCallback_, errorCallback_,
  100124. (void*) this) == FLAC__STREAM_DECODER_INIT_STATUS_OK;
  100125. if (ok)
  100126. {
  100127. FLAC__stream_decoder_process_until_end_of_metadata (decoder);
  100128. if (lengthInSamples == 0 && sampleRate > 0)
  100129. {
  100130. // the length hasn't been stored in the metadata, so we'll need to
  100131. // work it out the length the hard way, by scanning the whole file..
  100132. scanningForLength = true;
  100133. FLAC__stream_decoder_process_until_end_of_stream (decoder);
  100134. scanningForLength = false;
  100135. const int64 tempLength = lengthInSamples;
  100136. FLAC__stream_decoder_reset (decoder);
  100137. FLAC__stream_decoder_process_until_end_of_metadata (decoder);
  100138. lengthInSamples = tempLength;
  100139. }
  100140. }
  100141. }
  100142. ~FlacReader()
  100143. {
  100144. FLAC__stream_decoder_delete (decoder);
  100145. }
  100146. void useMetadata (const FLAC__StreamMetadata_StreamInfo& info)
  100147. {
  100148. sampleRate = info.sample_rate;
  100149. bitsPerSample = info.bits_per_sample;
  100150. lengthInSamples = (unsigned int) info.total_samples;
  100151. numChannels = info.channels;
  100152. reservoir.setSize (numChannels, 2 * info.max_blocksize, false, false, true);
  100153. }
  100154. // returns the number of samples read
  100155. bool read (int** destSamples,
  100156. int64 startSampleInFile,
  100157. int numSamples)
  100158. {
  100159. using namespace FlacNamespace;
  100160. if (! ok)
  100161. return false;
  100162. int offset = 0;
  100163. if (startSampleInFile < 0)
  100164. {
  100165. const int num = (int) jmin ((int64) numSamples, -startSampleInFile);
  100166. int n = 0;
  100167. while (destSamples[n] != 0)
  100168. {
  100169. zeromem (destSamples[n], sizeof (int) * num);
  100170. ++n;
  100171. }
  100172. offset += num;
  100173. startSampleInFile += num;
  100174. numSamples -= num;
  100175. }
  100176. while (numSamples > 0)
  100177. {
  100178. if (startSampleInFile >= reservoirStart
  100179. && startSampleInFile < reservoirStart + samplesInReservoir)
  100180. {
  100181. const int num = (int) jmin ((int64) numSamples,
  100182. reservoirStart + samplesInReservoir - startSampleInFile);
  100183. jassert (num > 0);
  100184. int n = 0;
  100185. while (destSamples[n] != 0)
  100186. {
  100187. memcpy (destSamples[n] + offset,
  100188. reservoir.getSampleData (n, (int) (startSampleInFile - reservoirStart)),
  100189. sizeof (int) * num);
  100190. ++n;
  100191. }
  100192. offset += num;
  100193. startSampleInFile += num;
  100194. numSamples -= num;
  100195. }
  100196. else
  100197. {
  100198. if (startSampleInFile < reservoirStart
  100199. || startSampleInFile > reservoirStart + jmax (samplesInReservoir, 511))
  100200. {
  100201. if (startSampleInFile >= (int) lengthInSamples)
  100202. {
  100203. samplesInReservoir = 0;
  100204. break;
  100205. }
  100206. // had some problems with flac crashing if the read pos is aligned more
  100207. // accurately than this. Probably fixed in newer versions of the library, though.
  100208. reservoirStart = (int) (startSampleInFile & ~511);
  100209. FLAC__stream_decoder_seek_absolute (decoder, (FLAC__uint64) reservoirStart);
  100210. }
  100211. else
  100212. {
  100213. reservoirStart += samplesInReservoir;
  100214. }
  100215. samplesInReservoir = 0;
  100216. FLAC__stream_decoder_process_single (decoder);
  100217. if (samplesInReservoir == 0)
  100218. break;
  100219. }
  100220. }
  100221. if (numSamples > 0)
  100222. {
  100223. int n = 0;
  100224. while (destSamples[n] != 0)
  100225. {
  100226. zeromem (destSamples[n] + offset, sizeof (int) * numSamples);
  100227. ++n;
  100228. }
  100229. }
  100230. return true;
  100231. }
  100232. void useSamples (const FLAC__int32* const buffer[], int numSamples)
  100233. {
  100234. if (scanningForLength)
  100235. {
  100236. lengthInSamples += numSamples;
  100237. }
  100238. else
  100239. {
  100240. if (numSamples > reservoir.getNumSamples())
  100241. reservoir.setSize (numChannels, numSamples, false, false, true);
  100242. const int bitsToShift = 32 - bitsPerSample;
  100243. for (int i = 0; i < (int) numChannels; ++i)
  100244. {
  100245. const FLAC__int32* src = buffer[i];
  100246. int n = i;
  100247. while (src == 0 && n > 0)
  100248. src = buffer [--n];
  100249. if (src != 0)
  100250. {
  100251. int* dest = (int*) reservoir.getSampleData(i);
  100252. for (int j = 0; j < numSamples; ++j)
  100253. dest[j] = src[j] << bitsToShift;
  100254. }
  100255. }
  100256. samplesInReservoir = numSamples;
  100257. }
  100258. }
  100259. static FLAC__StreamDecoderReadStatus readCallback_ (const FLAC__StreamDecoder*, FLAC__byte buffer[], size_t* bytes, void* client_data)
  100260. {
  100261. *bytes = (unsigned int) ((const FlacReader*) client_data)->input->read (buffer, (int) *bytes);
  100262. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  100263. }
  100264. static FLAC__StreamDecoderSeekStatus seekCallback_ (const FLAC__StreamDecoder*, FLAC__uint64 absolute_byte_offset, void* client_data)
  100265. {
  100266. ((const FlacReader*) client_data)->input->setPosition ((int) absolute_byte_offset);
  100267. return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  100268. }
  100269. static FLAC__StreamDecoderTellStatus tellCallback_ (const FLAC__StreamDecoder*, FLAC__uint64* absolute_byte_offset, void* client_data)
  100270. {
  100271. *absolute_byte_offset = ((const FlacReader*) client_data)->input->getPosition();
  100272. return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  100273. }
  100274. static FLAC__StreamDecoderLengthStatus lengthCallback_ (const FLAC__StreamDecoder*, FLAC__uint64* stream_length, void* client_data)
  100275. {
  100276. *stream_length = ((const FlacReader*) client_data)->input->getTotalLength();
  100277. return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  100278. }
  100279. static FLAC__bool eofCallback_ (const FLAC__StreamDecoder*, void* client_data)
  100280. {
  100281. return ((const FlacReader*) client_data)->input->isExhausted();
  100282. }
  100283. static FLAC__StreamDecoderWriteStatus writeCallback_ (const FLAC__StreamDecoder*,
  100284. const FLAC__Frame* frame,
  100285. const FLAC__int32* const buffer[],
  100286. void* client_data)
  100287. {
  100288. ((FlacReader*) client_data)->useSamples (buffer, frame->header.blocksize);
  100289. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  100290. }
  100291. static void metadataCallback_ (const FLAC__StreamDecoder*,
  100292. const FLAC__StreamMetadata* metadata,
  100293. void* client_data)
  100294. {
  100295. ((FlacReader*) client_data)->useMetadata (metadata->data.stream_info);
  100296. }
  100297. static void errorCallback_ (const FLAC__StreamDecoder*, FLAC__StreamDecoderErrorStatus, void*)
  100298. {
  100299. }
  100300. juce_UseDebuggingNewOperator
  100301. };
  100302. class FlacWriter : public AudioFormatWriter
  100303. {
  100304. FLAC__StreamEncoder* encoder;
  100305. MemoryBlock temp;
  100306. public:
  100307. bool ok;
  100308. FlacWriter (OutputStream* const out,
  100309. const double sampleRate,
  100310. const int numChannels,
  100311. const int bitsPerSample_)
  100312. : AudioFormatWriter (out, flacFormatName,
  100313. sampleRate,
  100314. numChannels,
  100315. bitsPerSample_)
  100316. {
  100317. using namespace FlacNamespace;
  100318. encoder = FLAC__stream_encoder_new();
  100319. FLAC__stream_encoder_set_do_mid_side_stereo (encoder, numChannels == 2);
  100320. FLAC__stream_encoder_set_loose_mid_side_stereo (encoder, numChannels == 2);
  100321. FLAC__stream_encoder_set_channels (encoder, numChannels);
  100322. FLAC__stream_encoder_set_bits_per_sample (encoder, jmin (24, bitsPerSample));
  100323. FLAC__stream_encoder_set_sample_rate (encoder, (unsigned int) sampleRate);
  100324. FLAC__stream_encoder_set_blocksize (encoder, 2048);
  100325. FLAC__stream_encoder_set_do_escape_coding (encoder, true);
  100326. ok = FLAC__stream_encoder_init_stream (encoder,
  100327. encodeWriteCallback, encodeSeekCallback,
  100328. encodeTellCallback, encodeMetadataCallback,
  100329. (void*) this) == FLAC__STREAM_ENCODER_INIT_STATUS_OK;
  100330. }
  100331. ~FlacWriter()
  100332. {
  100333. if (ok)
  100334. {
  100335. FLAC__stream_encoder_finish (encoder);
  100336. output->flush();
  100337. }
  100338. else
  100339. {
  100340. output = 0; // to stop the base class deleting this, as it needs to be returned
  100341. // to the caller of createWriter()
  100342. }
  100343. FLAC__stream_encoder_delete (encoder);
  100344. }
  100345. bool write (const int** samplesToWrite, int numSamples)
  100346. {
  100347. if (! ok)
  100348. return false;
  100349. int* buf[3];
  100350. const int bitsToShift = 32 - bitsPerSample;
  100351. if (bitsToShift > 0)
  100352. {
  100353. const int numChannels = (samplesToWrite[1] == 0) ? 1 : 2;
  100354. temp.setSize (sizeof (int) * numSamples * numChannels);
  100355. buf[0] = (int*) temp.getData();
  100356. buf[1] = buf[0] + numSamples;
  100357. buf[2] = 0;
  100358. for (int i = numChannels; --i >= 0;)
  100359. {
  100360. if (samplesToWrite[i] != 0)
  100361. {
  100362. for (int j = 0; j < numSamples; ++j)
  100363. buf [i][j] = (samplesToWrite [i][j] >> bitsToShift);
  100364. }
  100365. }
  100366. samplesToWrite = (const int**) buf;
  100367. }
  100368. return FLAC__stream_encoder_process (encoder,
  100369. (const FLAC__int32**) samplesToWrite,
  100370. numSamples) != 0;
  100371. }
  100372. bool writeData (const void* const data, const int size) const
  100373. {
  100374. return output->write (data, size);
  100375. }
  100376. static void packUint32 (FLAC__uint32 val, FLAC__byte* b, const int bytes)
  100377. {
  100378. b += bytes;
  100379. for (int i = 0; i < bytes; ++i)
  100380. {
  100381. *(--b) = (FLAC__byte) (val & 0xff);
  100382. val >>= 8;
  100383. }
  100384. }
  100385. void writeMetaData (const FLAC__StreamMetadata* metadata)
  100386. {
  100387. using namespace FlacNamespace;
  100388. const FLAC__StreamMetadata_StreamInfo& info = metadata->data.stream_info;
  100389. unsigned char buffer [FLAC__STREAM_METADATA_STREAMINFO_LENGTH];
  100390. const unsigned int channelsMinus1 = info.channels - 1;
  100391. const unsigned int bitsMinus1 = info.bits_per_sample - 1;
  100392. packUint32 (info.min_blocksize, buffer, 2);
  100393. packUint32 (info.max_blocksize, buffer + 2, 2);
  100394. packUint32 (info.min_framesize, buffer + 4, 3);
  100395. packUint32 (info.max_framesize, buffer + 7, 3);
  100396. buffer[10] = (uint8) ((info.sample_rate >> 12) & 0xff);
  100397. buffer[11] = (uint8) ((info.sample_rate >> 4) & 0xff);
  100398. buffer[12] = (uint8) (((info.sample_rate & 0x0f) << 4) | (channelsMinus1 << 1) | (bitsMinus1 >> 4));
  100399. buffer[13] = (FLAC__byte) (((bitsMinus1 & 0x0f) << 4) | (unsigned int) ((info.total_samples >> 32) & 0x0f));
  100400. packUint32 ((FLAC__uint32) info.total_samples, buffer + 14, 4);
  100401. memcpy (buffer + 18, info.md5sum, 16);
  100402. const bool ok = output->setPosition (4);
  100403. (void) ok;
  100404. // if this fails, you've given it an output stream that can't seek! It needs
  100405. // to be able to seek back to write the header
  100406. jassert (ok);
  100407. output->writeIntBigEndian (FLAC__STREAM_METADATA_STREAMINFO_LENGTH);
  100408. output->write (buffer, FLAC__STREAM_METADATA_STREAMINFO_LENGTH);
  100409. }
  100410. static FLAC__StreamEncoderWriteStatus encodeWriteCallback (const FLAC__StreamEncoder*,
  100411. const FLAC__byte buffer[],
  100412. size_t bytes,
  100413. unsigned int /*samples*/,
  100414. unsigned int /*current_frame*/,
  100415. void* client_data)
  100416. {
  100417. using namespace FlacNamespace;
  100418. return ((FlacWriter*) client_data)->writeData (buffer, (int) bytes)
  100419. ? FLAC__STREAM_ENCODER_WRITE_STATUS_OK
  100420. : FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  100421. }
  100422. static FLAC__StreamEncoderSeekStatus encodeSeekCallback (const FLAC__StreamEncoder*, FLAC__uint64, void*)
  100423. {
  100424. return FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED;
  100425. }
  100426. static FLAC__StreamEncoderTellStatus encodeTellCallback (const FLAC__StreamEncoder*, FLAC__uint64*, void*)
  100427. {
  100428. return FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED;
  100429. }
  100430. static void encodeMetadataCallback (const FLAC__StreamEncoder*,
  100431. const FLAC__StreamMetadata* metadata,
  100432. void* client_data)
  100433. {
  100434. ((FlacWriter*) client_data)->writeMetaData (metadata);
  100435. }
  100436. juce_UseDebuggingNewOperator
  100437. };
  100438. FlacAudioFormat::FlacAudioFormat()
  100439. : AudioFormat (flacFormatName, (const tchar**) flacExtensions)
  100440. {
  100441. }
  100442. FlacAudioFormat::~FlacAudioFormat()
  100443. {
  100444. }
  100445. const Array <int> FlacAudioFormat::getPossibleSampleRates()
  100446. {
  100447. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 0 };
  100448. return Array <int> (rates);
  100449. }
  100450. const Array <int> FlacAudioFormat::getPossibleBitDepths()
  100451. {
  100452. const int depths[] = { 16, 24, 0 };
  100453. return Array <int> (depths);
  100454. }
  100455. bool FlacAudioFormat::canDoStereo()
  100456. {
  100457. return true;
  100458. }
  100459. bool FlacAudioFormat::canDoMono()
  100460. {
  100461. return true;
  100462. }
  100463. bool FlacAudioFormat::isCompressed()
  100464. {
  100465. return true;
  100466. }
  100467. AudioFormatReader* FlacAudioFormat::createReaderFor (InputStream* in,
  100468. const bool deleteStreamIfOpeningFails)
  100469. {
  100470. FlacReader* r = new FlacReader (in);
  100471. if (r->sampleRate == 0)
  100472. {
  100473. if (! deleteStreamIfOpeningFails)
  100474. r->input = 0;
  100475. deleteAndZero (r);
  100476. }
  100477. return r;
  100478. }
  100479. AudioFormatWriter* FlacAudioFormat::createWriterFor (OutputStream* out,
  100480. double sampleRate,
  100481. unsigned int numberOfChannels,
  100482. int bitsPerSample,
  100483. const StringPairArray& /*metadataValues*/,
  100484. int /*qualityOptionIndex*/)
  100485. {
  100486. if (getPossibleBitDepths().contains (bitsPerSample))
  100487. {
  100488. FlacWriter* w = new FlacWriter (out,
  100489. sampleRate,
  100490. numberOfChannels,
  100491. bitsPerSample);
  100492. if (! w->ok)
  100493. deleteAndZero (w);
  100494. return w;
  100495. }
  100496. return 0;
  100497. }
  100498. END_JUCE_NAMESPACE
  100499. #endif
  100500. /********* End of inlined file: juce_FlacAudioFormat.cpp *********/
  100501. /********* Start of inlined file: juce_OggVorbisAudioFormat.cpp *********/
  100502. #if JUCE_USE_OGGVORBIS
  100503. #if JUCE_MAC
  100504. #define __MACOSX__ 1
  100505. #endif
  100506. namespace OggVorbisNamespace
  100507. {
  100508. /********* Start of inlined file: vorbisenc.h *********/
  100509. #ifndef _OV_ENC_H_
  100510. #define _OV_ENC_H_
  100511. #ifdef __cplusplus
  100512. extern "C"
  100513. {
  100514. #endif /* __cplusplus */
  100515. /********* Start of inlined file: codec.h *********/
  100516. #ifndef _vorbis_codec_h_
  100517. #define _vorbis_codec_h_
  100518. #ifdef __cplusplus
  100519. extern "C"
  100520. {
  100521. #endif /* __cplusplus */
  100522. /********* Start of inlined file: ogg.h *********/
  100523. #ifndef _OGG_H
  100524. #define _OGG_H
  100525. #ifdef __cplusplus
  100526. extern "C" {
  100527. #endif
  100528. /********* Start of inlined file: os_types.h *********/
  100529. #ifndef _OS_TYPES_H
  100530. #define _OS_TYPES_H
  100531. /* make it easy on the folks that want to compile the libs with a
  100532. different malloc than stdlib */
  100533. #define _ogg_malloc malloc
  100534. #define _ogg_calloc calloc
  100535. #define _ogg_realloc realloc
  100536. #define _ogg_free free
  100537. #if defined(_WIN32)
  100538. # if defined(__CYGWIN__)
  100539. # include <_G_config.h>
  100540. typedef _G_int64_t ogg_int64_t;
  100541. typedef _G_int32_t ogg_int32_t;
  100542. typedef _G_uint32_t ogg_uint32_t;
  100543. typedef _G_int16_t ogg_int16_t;
  100544. typedef _G_uint16_t ogg_uint16_t;
  100545. # elif defined(__MINGW32__)
  100546. typedef short ogg_int16_t;
  100547. typedef unsigned short ogg_uint16_t;
  100548. typedef int ogg_int32_t;
  100549. typedef unsigned int ogg_uint32_t;
  100550. typedef long long ogg_int64_t;
  100551. typedef unsigned long long ogg_uint64_t;
  100552. # elif defined(__MWERKS__)
  100553. typedef long long ogg_int64_t;
  100554. typedef int ogg_int32_t;
  100555. typedef unsigned int ogg_uint32_t;
  100556. typedef short ogg_int16_t;
  100557. typedef unsigned short ogg_uint16_t;
  100558. # else
  100559. /* MSVC/Borland */
  100560. typedef __int64 ogg_int64_t;
  100561. typedef __int32 ogg_int32_t;
  100562. typedef unsigned __int32 ogg_uint32_t;
  100563. typedef __int16 ogg_int16_t;
  100564. typedef unsigned __int16 ogg_uint16_t;
  100565. # endif
  100566. #elif defined(__MACOS__)
  100567. # include <sys/types.h>
  100568. typedef SInt16 ogg_int16_t;
  100569. typedef UInt16 ogg_uint16_t;
  100570. typedef SInt32 ogg_int32_t;
  100571. typedef UInt32 ogg_uint32_t;
  100572. typedef SInt64 ogg_int64_t;
  100573. #elif defined(__MACOSX__) /* MacOS X Framework build */
  100574. # include <sys/types.h>
  100575. typedef int16_t ogg_int16_t;
  100576. typedef u_int16_t ogg_uint16_t;
  100577. typedef int32_t ogg_int32_t;
  100578. typedef u_int32_t ogg_uint32_t;
  100579. typedef int64_t ogg_int64_t;
  100580. #elif defined(__BEOS__)
  100581. /* Be */
  100582. # include <inttypes.h>
  100583. typedef int16_t ogg_int16_t;
  100584. typedef u_int16_t ogg_uint16_t;
  100585. typedef int32_t ogg_int32_t;
  100586. typedef u_int32_t ogg_uint32_t;
  100587. typedef int64_t ogg_int64_t;
  100588. #elif defined (__EMX__)
  100589. /* OS/2 GCC */
  100590. typedef short ogg_int16_t;
  100591. typedef unsigned short ogg_uint16_t;
  100592. typedef int ogg_int32_t;
  100593. typedef unsigned int ogg_uint32_t;
  100594. typedef long long ogg_int64_t;
  100595. #elif defined (DJGPP)
  100596. /* DJGPP */
  100597. typedef short ogg_int16_t;
  100598. typedef int ogg_int32_t;
  100599. typedef unsigned int ogg_uint32_t;
  100600. typedef long long ogg_int64_t;
  100601. #elif defined(R5900)
  100602. /* PS2 EE */
  100603. typedef long ogg_int64_t;
  100604. typedef int ogg_int32_t;
  100605. typedef unsigned ogg_uint32_t;
  100606. typedef short ogg_int16_t;
  100607. #elif defined(__SYMBIAN32__)
  100608. /* Symbian GCC */
  100609. typedef signed short ogg_int16_t;
  100610. typedef unsigned short ogg_uint16_t;
  100611. typedef signed int ogg_int32_t;
  100612. typedef unsigned int ogg_uint32_t;
  100613. typedef long long int ogg_int64_t;
  100614. #else
  100615. # include <sys/types.h>
  100616. /********* Start of inlined file: config_types.h *********/
  100617. #ifndef __CONFIG_TYPES_H__
  100618. #define __CONFIG_TYPES_H__
  100619. typedef int16_t ogg_int16_t;
  100620. typedef unsigned short ogg_uint16_t;
  100621. typedef int32_t ogg_int32_t;
  100622. typedef unsigned int ogg_uint32_t;
  100623. typedef int64_t ogg_int64_t;
  100624. #endif
  100625. /********* End of inlined file: config_types.h *********/
  100626. #endif
  100627. #endif /* _OS_TYPES_H */
  100628. /********* End of inlined file: os_types.h *********/
  100629. typedef struct {
  100630. long endbyte;
  100631. int endbit;
  100632. unsigned char *buffer;
  100633. unsigned char *ptr;
  100634. long storage;
  100635. } oggpack_buffer;
  100636. /* ogg_page is used to encapsulate the data in one Ogg bitstream page *****/
  100637. typedef struct {
  100638. unsigned char *header;
  100639. long header_len;
  100640. unsigned char *body;
  100641. long body_len;
  100642. } ogg_page;
  100643. ogg_uint32_t bitreverse(ogg_uint32_t x){
  100644. x= ((x>>16)&0x0000ffffUL) | ((x<<16)&0xffff0000UL);
  100645. x= ((x>> 8)&0x00ff00ffUL) | ((x<< 8)&0xff00ff00UL);
  100646. x= ((x>> 4)&0x0f0f0f0fUL) | ((x<< 4)&0xf0f0f0f0UL);
  100647. x= ((x>> 2)&0x33333333UL) | ((x<< 2)&0xccccccccUL);
  100648. return((x>> 1)&0x55555555UL) | ((x<< 1)&0xaaaaaaaaUL);
  100649. }
  100650. /* ogg_stream_state contains the current encode/decode state of a logical
  100651. Ogg bitstream **********************************************************/
  100652. typedef struct {
  100653. unsigned char *body_data; /* bytes from packet bodies */
  100654. long body_storage; /* storage elements allocated */
  100655. long body_fill; /* elements stored; fill mark */
  100656. long body_returned; /* elements of fill returned */
  100657. int *lacing_vals; /* The values that will go to the segment table */
  100658. ogg_int64_t *granule_vals; /* granulepos values for headers. Not compact
  100659. this way, but it is simple coupled to the
  100660. lacing fifo */
  100661. long lacing_storage;
  100662. long lacing_fill;
  100663. long lacing_packet;
  100664. long lacing_returned;
  100665. unsigned char header[282]; /* working space for header encode */
  100666. int header_fill;
  100667. int e_o_s; /* set when we have buffered the last packet in the
  100668. logical bitstream */
  100669. int b_o_s; /* set after we've written the initial page
  100670. of a logical bitstream */
  100671. long serialno;
  100672. long pageno;
  100673. ogg_int64_t packetno; /* sequence number for decode; the framing
  100674. knows where there's a hole in the data,
  100675. but we need coupling so that the codec
  100676. (which is in a seperate abstraction
  100677. layer) also knows about the gap */
  100678. ogg_int64_t granulepos;
  100679. } ogg_stream_state;
  100680. /* ogg_packet is used to encapsulate the data and metadata belonging
  100681. to a single raw Ogg/Vorbis packet *************************************/
  100682. typedef struct {
  100683. unsigned char *packet;
  100684. long bytes;
  100685. long b_o_s;
  100686. long e_o_s;
  100687. ogg_int64_t granulepos;
  100688. ogg_int64_t packetno; /* sequence number for decode; the framing
  100689. knows where there's a hole in the data,
  100690. but we need coupling so that the codec
  100691. (which is in a seperate abstraction
  100692. layer) also knows about the gap */
  100693. } ogg_packet;
  100694. typedef struct {
  100695. unsigned char *data;
  100696. int storage;
  100697. int fill;
  100698. int returned;
  100699. int unsynced;
  100700. int headerbytes;
  100701. int bodybytes;
  100702. } ogg_sync_state;
  100703. /* Ogg BITSTREAM PRIMITIVES: bitstream ************************/
  100704. extern void oggpack_writeinit(oggpack_buffer *b);
  100705. extern void oggpack_writetrunc(oggpack_buffer *b,long bits);
  100706. extern void oggpack_writealign(oggpack_buffer *b);
  100707. extern void oggpack_writecopy(oggpack_buffer *b,void *source,long bits);
  100708. extern void oggpack_reset(oggpack_buffer *b);
  100709. extern void oggpack_writeclear(oggpack_buffer *b);
  100710. extern void oggpack_readinit(oggpack_buffer *b,unsigned char *buf,int bytes);
  100711. extern void oggpack_write(oggpack_buffer *b,unsigned long value,int bits);
  100712. extern long oggpack_look(oggpack_buffer *b,int bits);
  100713. extern long oggpack_look1(oggpack_buffer *b);
  100714. extern void oggpack_adv(oggpack_buffer *b,int bits);
  100715. extern void oggpack_adv1(oggpack_buffer *b);
  100716. extern long oggpack_read(oggpack_buffer *b,int bits);
  100717. extern long oggpack_read1(oggpack_buffer *b);
  100718. extern long oggpack_bytes(oggpack_buffer *b);
  100719. extern long oggpack_bits(oggpack_buffer *b);
  100720. extern unsigned char *oggpack_get_buffer(oggpack_buffer *b);
  100721. extern void oggpackB_writeinit(oggpack_buffer *b);
  100722. extern void oggpackB_writetrunc(oggpack_buffer *b,long bits);
  100723. extern void oggpackB_writealign(oggpack_buffer *b);
  100724. extern void oggpackB_writecopy(oggpack_buffer *b,void *source,long bits);
  100725. extern void oggpackB_reset(oggpack_buffer *b);
  100726. extern void oggpackB_writeclear(oggpack_buffer *b);
  100727. extern void oggpackB_readinit(oggpack_buffer *b,unsigned char *buf,int bytes);
  100728. extern void oggpackB_write(oggpack_buffer *b,unsigned long value,int bits);
  100729. extern long oggpackB_look(oggpack_buffer *b,int bits);
  100730. extern long oggpackB_look1(oggpack_buffer *b);
  100731. extern void oggpackB_adv(oggpack_buffer *b,int bits);
  100732. extern void oggpackB_adv1(oggpack_buffer *b);
  100733. extern long oggpackB_read(oggpack_buffer *b,int bits);
  100734. extern long oggpackB_read1(oggpack_buffer *b);
  100735. extern long oggpackB_bytes(oggpack_buffer *b);
  100736. extern long oggpackB_bits(oggpack_buffer *b);
  100737. extern unsigned char *oggpackB_get_buffer(oggpack_buffer *b);
  100738. /* Ogg BITSTREAM PRIMITIVES: encoding **************************/
  100739. extern int ogg_stream_packetin(ogg_stream_state *os, ogg_packet *op);
  100740. extern int ogg_stream_pageout(ogg_stream_state *os, ogg_page *og);
  100741. extern int ogg_stream_flush(ogg_stream_state *os, ogg_page *og);
  100742. /* Ogg BITSTREAM PRIMITIVES: decoding **************************/
  100743. extern int ogg_sync_init(ogg_sync_state *oy);
  100744. extern int ogg_sync_clear(ogg_sync_state *oy);
  100745. extern int ogg_sync_reset(ogg_sync_state *oy);
  100746. extern int ogg_sync_destroy(ogg_sync_state *oy);
  100747. extern char *ogg_sync_buffer(ogg_sync_state *oy, long size);
  100748. extern int ogg_sync_wrote(ogg_sync_state *oy, long bytes);
  100749. extern long ogg_sync_pageseek(ogg_sync_state *oy,ogg_page *og);
  100750. extern int ogg_sync_pageout(ogg_sync_state *oy, ogg_page *og);
  100751. extern int ogg_stream_pagein(ogg_stream_state *os, ogg_page *og);
  100752. extern int ogg_stream_packetout(ogg_stream_state *os,ogg_packet *op);
  100753. extern int ogg_stream_packetpeek(ogg_stream_state *os,ogg_packet *op);
  100754. /* Ogg BITSTREAM PRIMITIVES: general ***************************/
  100755. extern int ogg_stream_init(ogg_stream_state *os,int serialno);
  100756. extern int ogg_stream_clear(ogg_stream_state *os);
  100757. extern int ogg_stream_reset(ogg_stream_state *os);
  100758. extern int ogg_stream_reset_serialno(ogg_stream_state *os,int serialno);
  100759. extern int ogg_stream_destroy(ogg_stream_state *os);
  100760. extern int ogg_stream_eos(ogg_stream_state *os);
  100761. extern void ogg_page_checksum_set(ogg_page *og);
  100762. extern int ogg_page_version(ogg_page *og);
  100763. extern int ogg_page_continued(ogg_page *og);
  100764. extern int ogg_page_bos(ogg_page *og);
  100765. extern int ogg_page_eos(ogg_page *og);
  100766. extern ogg_int64_t ogg_page_granulepos(ogg_page *og);
  100767. extern int ogg_page_serialno(ogg_page *og);
  100768. extern long ogg_page_pageno(ogg_page *og);
  100769. extern int ogg_page_packets(ogg_page *og);
  100770. extern void ogg_packet_clear(ogg_packet *op);
  100771. #ifdef __cplusplus
  100772. }
  100773. #endif
  100774. #endif /* _OGG_H */
  100775. /********* End of inlined file: ogg.h *********/
  100776. typedef struct vorbis_info{
  100777. int version;
  100778. int channels;
  100779. long rate;
  100780. /* The below bitrate declarations are *hints*.
  100781. Combinations of the three values carry the following implications:
  100782. all three set to the same value:
  100783. implies a fixed rate bitstream
  100784. only nominal set:
  100785. implies a VBR stream that averages the nominal bitrate. No hard
  100786. upper/lower limit
  100787. upper and or lower set:
  100788. implies a VBR bitstream that obeys the bitrate limits. nominal
  100789. may also be set to give a nominal rate.
  100790. none set:
  100791. the coder does not care to speculate.
  100792. */
  100793. long bitrate_upper;
  100794. long bitrate_nominal;
  100795. long bitrate_lower;
  100796. long bitrate_window;
  100797. void *codec_setup;
  100798. } vorbis_info;
  100799. /* vorbis_dsp_state buffers the current vorbis audio
  100800. analysis/synthesis state. The DSP state belongs to a specific
  100801. logical bitstream ****************************************************/
  100802. typedef struct vorbis_dsp_state{
  100803. int analysisp;
  100804. vorbis_info *vi;
  100805. float **pcm;
  100806. float **pcmret;
  100807. int pcm_storage;
  100808. int pcm_current;
  100809. int pcm_returned;
  100810. int preextrapolate;
  100811. int eofflag;
  100812. long lW;
  100813. long W;
  100814. long nW;
  100815. long centerW;
  100816. ogg_int64_t granulepos;
  100817. ogg_int64_t sequence;
  100818. ogg_int64_t glue_bits;
  100819. ogg_int64_t time_bits;
  100820. ogg_int64_t floor_bits;
  100821. ogg_int64_t res_bits;
  100822. void *backend_state;
  100823. } vorbis_dsp_state;
  100824. typedef struct vorbis_block{
  100825. /* necessary stream state for linking to the framing abstraction */
  100826. float **pcm; /* this is a pointer into local storage */
  100827. oggpack_buffer opb;
  100828. long lW;
  100829. long W;
  100830. long nW;
  100831. int pcmend;
  100832. int mode;
  100833. int eofflag;
  100834. ogg_int64_t granulepos;
  100835. ogg_int64_t sequence;
  100836. vorbis_dsp_state *vd; /* For read-only access of configuration */
  100837. /* local storage to avoid remallocing; it's up to the mapping to
  100838. structure it */
  100839. void *localstore;
  100840. long localtop;
  100841. long localalloc;
  100842. long totaluse;
  100843. struct alloc_chain *reap;
  100844. /* bitmetrics for the frame */
  100845. long glue_bits;
  100846. long time_bits;
  100847. long floor_bits;
  100848. long res_bits;
  100849. void *internal;
  100850. } vorbis_block;
  100851. /* vorbis_block is a single block of data to be processed as part of
  100852. the analysis/synthesis stream; it belongs to a specific logical
  100853. bitstream, but is independant from other vorbis_blocks belonging to
  100854. that logical bitstream. *************************************************/
  100855. struct alloc_chain{
  100856. void *ptr;
  100857. struct alloc_chain *next;
  100858. };
  100859. /* vorbis_info contains all the setup information specific to the
  100860. specific compression/decompression mode in progress (eg,
  100861. psychoacoustic settings, channel setup, options, codebook
  100862. etc). vorbis_info and substructures are in backends.h.
  100863. *********************************************************************/
  100864. /* the comments are not part of vorbis_info so that vorbis_info can be
  100865. static storage */
  100866. typedef struct vorbis_comment{
  100867. /* unlimited user comment fields. libvorbis writes 'libvorbis'
  100868. whatever vendor is set to in encode */
  100869. char **user_comments;
  100870. int *comment_lengths;
  100871. int comments;
  100872. char *vendor;
  100873. } vorbis_comment;
  100874. /* libvorbis encodes in two abstraction layers; first we perform DSP
  100875. and produce a packet (see docs/analysis.txt). The packet is then
  100876. coded into a framed OggSquish bitstream by the second layer (see
  100877. docs/framing.txt). Decode is the reverse process; we sync/frame
  100878. the bitstream and extract individual packets, then decode the
  100879. packet back into PCM audio.
  100880. The extra framing/packetizing is used in streaming formats, such as
  100881. files. Over the net (such as with UDP), the framing and
  100882. packetization aren't necessary as they're provided by the transport
  100883. and the streaming layer is not used */
  100884. /* Vorbis PRIMITIVES: general ***************************************/
  100885. extern void vorbis_info_init(vorbis_info *vi);
  100886. extern void vorbis_info_clear(vorbis_info *vi);
  100887. extern int vorbis_info_blocksize(vorbis_info *vi,int zo);
  100888. extern void vorbis_comment_init(vorbis_comment *vc);
  100889. extern void vorbis_comment_add(vorbis_comment *vc, char *comment);
  100890. extern void vorbis_comment_add_tag(vorbis_comment *vc,
  100891. char *tag, char *contents);
  100892. extern char *vorbis_comment_query(vorbis_comment *vc, char *tag, int count);
  100893. extern int vorbis_comment_query_count(vorbis_comment *vc, char *tag);
  100894. extern void vorbis_comment_clear(vorbis_comment *vc);
  100895. extern int vorbis_block_init(vorbis_dsp_state *v, vorbis_block *vb);
  100896. extern int vorbis_block_clear(vorbis_block *vb);
  100897. extern void vorbis_dsp_clear(vorbis_dsp_state *v);
  100898. extern double vorbis_granule_time(vorbis_dsp_state *v,
  100899. ogg_int64_t granulepos);
  100900. /* Vorbis PRIMITIVES: analysis/DSP layer ****************************/
  100901. extern int vorbis_analysis_init(vorbis_dsp_state *v,vorbis_info *vi);
  100902. extern int vorbis_commentheader_out(vorbis_comment *vc, ogg_packet *op);
  100903. extern int vorbis_analysis_headerout(vorbis_dsp_state *v,
  100904. vorbis_comment *vc,
  100905. ogg_packet *op,
  100906. ogg_packet *op_comm,
  100907. ogg_packet *op_code);
  100908. extern float **vorbis_analysis_buffer(vorbis_dsp_state *v,int vals);
  100909. extern int vorbis_analysis_wrote(vorbis_dsp_state *v,int vals);
  100910. extern int vorbis_analysis_blockout(vorbis_dsp_state *v,vorbis_block *vb);
  100911. extern int vorbis_analysis(vorbis_block *vb,ogg_packet *op);
  100912. extern int vorbis_bitrate_addblock(vorbis_block *vb);
  100913. extern int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd,
  100914. ogg_packet *op);
  100915. /* Vorbis PRIMITIVES: synthesis layer *******************************/
  100916. extern int vorbis_synthesis_headerin(vorbis_info *vi,vorbis_comment *vc,
  100917. ogg_packet *op);
  100918. extern int vorbis_synthesis_init(vorbis_dsp_state *v,vorbis_info *vi);
  100919. extern int vorbis_synthesis_restart(vorbis_dsp_state *v);
  100920. extern int vorbis_synthesis(vorbis_block *vb,ogg_packet *op);
  100921. extern int vorbis_synthesis_trackonly(vorbis_block *vb,ogg_packet *op);
  100922. extern int vorbis_synthesis_blockin(vorbis_dsp_state *v,vorbis_block *vb);
  100923. extern int vorbis_synthesis_pcmout(vorbis_dsp_state *v,float ***pcm);
  100924. extern int vorbis_synthesis_lapout(vorbis_dsp_state *v,float ***pcm);
  100925. extern int vorbis_synthesis_read(vorbis_dsp_state *v,int samples);
  100926. extern long vorbis_packet_blocksize(vorbis_info *vi,ogg_packet *op);
  100927. extern int vorbis_synthesis_halfrate(vorbis_info *v,int flag);
  100928. extern int vorbis_synthesis_halfrate_p(vorbis_info *v);
  100929. /* Vorbis ERRORS and return codes ***********************************/
  100930. #define OV_FALSE -1
  100931. #define OV_EOF -2
  100932. #define OV_HOLE -3
  100933. #define OV_EREAD -128
  100934. #define OV_EFAULT -129
  100935. #define OV_EIMPL -130
  100936. #define OV_EINVAL -131
  100937. #define OV_ENOTVORBIS -132
  100938. #define OV_EBADHEADER -133
  100939. #define OV_EVERSION -134
  100940. #define OV_ENOTAUDIO -135
  100941. #define OV_EBADPACKET -136
  100942. #define OV_EBADLINK -137
  100943. #define OV_ENOSEEK -138
  100944. #ifdef __cplusplus
  100945. }
  100946. #endif /* __cplusplus */
  100947. #endif
  100948. /********* End of inlined file: codec.h *********/
  100949. extern int vorbis_encode_init(vorbis_info *vi,
  100950. long channels,
  100951. long rate,
  100952. long max_bitrate,
  100953. long nominal_bitrate,
  100954. long min_bitrate);
  100955. extern int vorbis_encode_setup_managed(vorbis_info *vi,
  100956. long channels,
  100957. long rate,
  100958. long max_bitrate,
  100959. long nominal_bitrate,
  100960. long min_bitrate);
  100961. extern int vorbis_encode_setup_vbr(vorbis_info *vi,
  100962. long channels,
  100963. long rate,
  100964. float quality /* quality level from 0. (lo) to 1. (hi) */
  100965. );
  100966. extern int vorbis_encode_init_vbr(vorbis_info *vi,
  100967. long channels,
  100968. long rate,
  100969. float base_quality /* quality level from 0. (lo) to 1. (hi) */
  100970. );
  100971. extern int vorbis_encode_setup_init(vorbis_info *vi);
  100972. extern int vorbis_encode_ctl(vorbis_info *vi,int number,void *arg);
  100973. /* deprecated rate management supported only for compatability */
  100974. #define OV_ECTL_RATEMANAGE_GET 0x10
  100975. #define OV_ECTL_RATEMANAGE_SET 0x11
  100976. #define OV_ECTL_RATEMANAGE_AVG 0x12
  100977. #define OV_ECTL_RATEMANAGE_HARD 0x13
  100978. struct ovectl_ratemanage_arg {
  100979. int management_active;
  100980. long bitrate_hard_min;
  100981. long bitrate_hard_max;
  100982. double bitrate_hard_window;
  100983. long bitrate_av_lo;
  100984. long bitrate_av_hi;
  100985. double bitrate_av_window;
  100986. double bitrate_av_window_center;
  100987. };
  100988. /* new rate setup */
  100989. #define OV_ECTL_RATEMANAGE2_GET 0x14
  100990. #define OV_ECTL_RATEMANAGE2_SET 0x15
  100991. struct ovectl_ratemanage2_arg {
  100992. int management_active;
  100993. long bitrate_limit_min_kbps;
  100994. long bitrate_limit_max_kbps;
  100995. long bitrate_limit_reservoir_bits;
  100996. double bitrate_limit_reservoir_bias;
  100997. long bitrate_average_kbps;
  100998. double bitrate_average_damping;
  100999. };
  101000. #define OV_ECTL_LOWPASS_GET 0x20
  101001. #define OV_ECTL_LOWPASS_SET 0x21
  101002. #define OV_ECTL_IBLOCK_GET 0x30
  101003. #define OV_ECTL_IBLOCK_SET 0x31
  101004. #ifdef __cplusplus
  101005. }
  101006. #endif /* __cplusplus */
  101007. #endif
  101008. /********* End of inlined file: vorbisenc.h *********/
  101009. /********* Start of inlined file: vorbisfile.h *********/
  101010. #ifndef _OV_FILE_H_
  101011. #define _OV_FILE_H_
  101012. #ifdef __cplusplus
  101013. extern "C"
  101014. {
  101015. #endif /* __cplusplus */
  101016. #include <stdio.h>
  101017. /* The function prototypes for the callbacks are basically the same as for
  101018. * the stdio functions fread, fseek, fclose, ftell.
  101019. * The one difference is that the FILE * arguments have been replaced with
  101020. * a void * - this is to be used as a pointer to whatever internal data these
  101021. * functions might need. In the stdio case, it's just a FILE * cast to a void *
  101022. *
  101023. * If you use other functions, check the docs for these functions and return
  101024. * the right values. For seek_func(), you *MUST* return -1 if the stream is
  101025. * unseekable
  101026. */
  101027. typedef struct {
  101028. size_t (*read_func) (void *ptr, size_t size, size_t nmemb, void *datasource);
  101029. int (*seek_func) (void *datasource, ogg_int64_t offset, int whence);
  101030. int (*close_func) (void *datasource);
  101031. long (*tell_func) (void *datasource);
  101032. } ov_callbacks;
  101033. #define NOTOPEN 0
  101034. #define PARTOPEN 1
  101035. #define OPENED 2
  101036. #define STREAMSET 3
  101037. #define INITSET 4
  101038. typedef struct OggVorbis_File {
  101039. void *datasource; /* Pointer to a FILE *, etc. */
  101040. int seekable;
  101041. ogg_int64_t offset;
  101042. ogg_int64_t end;
  101043. ogg_sync_state oy;
  101044. /* If the FILE handle isn't seekable (eg, a pipe), only the current
  101045. stream appears */
  101046. int links;
  101047. ogg_int64_t *offsets;
  101048. ogg_int64_t *dataoffsets;
  101049. long *serialnos;
  101050. ogg_int64_t *pcmlengths; /* overloaded to maintain binary
  101051. compatability; x2 size, stores both
  101052. beginning and end values */
  101053. vorbis_info *vi;
  101054. vorbis_comment *vc;
  101055. /* Decoding working state local storage */
  101056. ogg_int64_t pcm_offset;
  101057. int ready_state;
  101058. long current_serialno;
  101059. int current_link;
  101060. double bittrack;
  101061. double samptrack;
  101062. ogg_stream_state os; /* take physical pages, weld into a logical
  101063. stream of packets */
  101064. vorbis_dsp_state vd; /* central working state for the packet->PCM decoder */
  101065. vorbis_block vb; /* local working space for packet->PCM decode */
  101066. ov_callbacks callbacks;
  101067. } OggVorbis_File;
  101068. extern int ov_clear(OggVorbis_File *vf);
  101069. extern int ov_open(FILE *f,OggVorbis_File *vf,char *initial,long ibytes);
  101070. extern int ov_open_callbacks(void *datasource, OggVorbis_File *vf,
  101071. char *initial, long ibytes, ov_callbacks callbacks);
  101072. extern int ov_test(FILE *f,OggVorbis_File *vf,char *initial,long ibytes);
  101073. extern int ov_test_callbacks(void *datasource, OggVorbis_File *vf,
  101074. char *initial, long ibytes, ov_callbacks callbacks);
  101075. extern int ov_test_open(OggVorbis_File *vf);
  101076. extern long ov_bitrate(OggVorbis_File *vf,int i);
  101077. extern long ov_bitrate_instant(OggVorbis_File *vf);
  101078. extern long ov_streams(OggVorbis_File *vf);
  101079. extern long ov_seekable(OggVorbis_File *vf);
  101080. extern long ov_serialnumber(OggVorbis_File *vf,int i);
  101081. extern ogg_int64_t ov_raw_total(OggVorbis_File *vf,int i);
  101082. extern ogg_int64_t ov_pcm_total(OggVorbis_File *vf,int i);
  101083. extern double ov_time_total(OggVorbis_File *vf,int i);
  101084. extern int ov_raw_seek(OggVorbis_File *vf,ogg_int64_t pos);
  101085. extern int ov_pcm_seek(OggVorbis_File *vf,ogg_int64_t pos);
  101086. extern int ov_pcm_seek_page(OggVorbis_File *vf,ogg_int64_t pos);
  101087. extern int ov_time_seek(OggVorbis_File *vf,double pos);
  101088. extern int ov_time_seek_page(OggVorbis_File *vf,double pos);
  101089. extern int ov_raw_seek_lap(OggVorbis_File *vf,ogg_int64_t pos);
  101090. extern int ov_pcm_seek_lap(OggVorbis_File *vf,ogg_int64_t pos);
  101091. extern int ov_pcm_seek_page_lap(OggVorbis_File *vf,ogg_int64_t pos);
  101092. extern int ov_time_seek_lap(OggVorbis_File *vf,double pos);
  101093. extern int ov_time_seek_page_lap(OggVorbis_File *vf,double pos);
  101094. extern ogg_int64_t ov_raw_tell(OggVorbis_File *vf);
  101095. extern ogg_int64_t ov_pcm_tell(OggVorbis_File *vf);
  101096. extern double ov_time_tell(OggVorbis_File *vf);
  101097. extern vorbis_info *ov_info(OggVorbis_File *vf,int link);
  101098. extern vorbis_comment *ov_comment(OggVorbis_File *vf,int link);
  101099. extern long ov_read_float(OggVorbis_File *vf,float ***pcm_channels,int samples,
  101100. int *bitstream);
  101101. extern long ov_read(OggVorbis_File *vf,char *buffer,int length,
  101102. int bigendianp,int word,int sgned,int *bitstream);
  101103. extern int ov_crosslap(OggVorbis_File *vf1,OggVorbis_File *vf2);
  101104. extern int ov_halfrate(OggVorbis_File *vf,int flag);
  101105. extern int ov_halfrate_p(OggVorbis_File *vf);
  101106. #ifdef __cplusplus
  101107. }
  101108. #endif /* __cplusplus */
  101109. #endif
  101110. /********* End of inlined file: vorbisfile.h *********/
  101111. /********* Start of inlined file: bitwise.c *********/
  101112. /* We're 'LSb' endian; if we write a word but read individual bits,
  101113. then we'll read the lsb first */
  101114. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  101115. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  101116. // tasks..
  101117. #ifdef _MSC_VER
  101118. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  101119. #endif
  101120. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  101121. #if JUCE_USE_OGGVORBIS
  101122. #include <string.h>
  101123. #include <stdlib.h>
  101124. #define BUFFER_INCREMENT 256
  101125. static const unsigned long mask[]=
  101126. {0x00000000,0x00000001,0x00000003,0x00000007,0x0000000f,
  101127. 0x0000001f,0x0000003f,0x0000007f,0x000000ff,0x000001ff,
  101128. 0x000003ff,0x000007ff,0x00000fff,0x00001fff,0x00003fff,
  101129. 0x00007fff,0x0000ffff,0x0001ffff,0x0003ffff,0x0007ffff,
  101130. 0x000fffff,0x001fffff,0x003fffff,0x007fffff,0x00ffffff,
  101131. 0x01ffffff,0x03ffffff,0x07ffffff,0x0fffffff,0x1fffffff,
  101132. 0x3fffffff,0x7fffffff,0xffffffff };
  101133. static const unsigned int mask8B[]=
  101134. {0x00,0x80,0xc0,0xe0,0xf0,0xf8,0xfc,0xfe,0xff};
  101135. void oggpack_writeinit(oggpack_buffer *b){
  101136. memset(b,0,sizeof(*b));
  101137. b->ptr=b->buffer=(unsigned char*) _ogg_malloc(BUFFER_INCREMENT);
  101138. b->buffer[0]='\0';
  101139. b->storage=BUFFER_INCREMENT;
  101140. }
  101141. void oggpackB_writeinit(oggpack_buffer *b){
  101142. oggpack_writeinit(b);
  101143. }
  101144. void oggpack_writetrunc(oggpack_buffer *b,long bits){
  101145. long bytes=bits>>3;
  101146. bits-=bytes*8;
  101147. b->ptr=b->buffer+bytes;
  101148. b->endbit=bits;
  101149. b->endbyte=bytes;
  101150. *b->ptr&=mask[bits];
  101151. }
  101152. void oggpackB_writetrunc(oggpack_buffer *b,long bits){
  101153. long bytes=bits>>3;
  101154. bits-=bytes*8;
  101155. b->ptr=b->buffer+bytes;
  101156. b->endbit=bits;
  101157. b->endbyte=bytes;
  101158. *b->ptr&=mask8B[bits];
  101159. }
  101160. /* Takes only up to 32 bits. */
  101161. void oggpack_write(oggpack_buffer *b,unsigned long value,int bits){
  101162. if(b->endbyte+4>=b->storage){
  101163. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage+BUFFER_INCREMENT);
  101164. b->storage+=BUFFER_INCREMENT;
  101165. b->ptr=b->buffer+b->endbyte;
  101166. }
  101167. value&=mask[bits];
  101168. bits+=b->endbit;
  101169. b->ptr[0]|=value<<b->endbit;
  101170. if(bits>=8){
  101171. b->ptr[1]=(unsigned char)(value>>(8-b->endbit));
  101172. if(bits>=16){
  101173. b->ptr[2]=(unsigned char)(value>>(16-b->endbit));
  101174. if(bits>=24){
  101175. b->ptr[3]=(unsigned char)(value>>(24-b->endbit));
  101176. if(bits>=32){
  101177. if(b->endbit)
  101178. b->ptr[4]=(unsigned char)(value>>(32-b->endbit));
  101179. else
  101180. b->ptr[4]=0;
  101181. }
  101182. }
  101183. }
  101184. }
  101185. b->endbyte+=bits/8;
  101186. b->ptr+=bits/8;
  101187. b->endbit=bits&7;
  101188. }
  101189. /* Takes only up to 32 bits. */
  101190. void oggpackB_write(oggpack_buffer *b,unsigned long value,int bits){
  101191. if(b->endbyte+4>=b->storage){
  101192. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage+BUFFER_INCREMENT);
  101193. b->storage+=BUFFER_INCREMENT;
  101194. b->ptr=b->buffer+b->endbyte;
  101195. }
  101196. value=(value&mask[bits])<<(32-bits);
  101197. bits+=b->endbit;
  101198. b->ptr[0]|=value>>(24+b->endbit);
  101199. if(bits>=8){
  101200. b->ptr[1]=(unsigned char)(value>>(16+b->endbit));
  101201. if(bits>=16){
  101202. b->ptr[2]=(unsigned char)(value>>(8+b->endbit));
  101203. if(bits>=24){
  101204. b->ptr[3]=(unsigned char)(value>>(b->endbit));
  101205. if(bits>=32){
  101206. if(b->endbit)
  101207. b->ptr[4]=(unsigned char)(value<<(8-b->endbit));
  101208. else
  101209. b->ptr[4]=0;
  101210. }
  101211. }
  101212. }
  101213. }
  101214. b->endbyte+=bits/8;
  101215. b->ptr+=bits/8;
  101216. b->endbit=bits&7;
  101217. }
  101218. void oggpack_writealign(oggpack_buffer *b){
  101219. int bits=8-b->endbit;
  101220. if(bits<8)
  101221. oggpack_write(b,0,bits);
  101222. }
  101223. void oggpackB_writealign(oggpack_buffer *b){
  101224. int bits=8-b->endbit;
  101225. if(bits<8)
  101226. oggpackB_write(b,0,bits);
  101227. }
  101228. static void oggpack_writecopy_helper(oggpack_buffer *b,
  101229. void *source,
  101230. long bits,
  101231. void (*w)(oggpack_buffer *,
  101232. unsigned long,
  101233. int),
  101234. int msb){
  101235. unsigned char *ptr=(unsigned char *)source;
  101236. long bytes=bits/8;
  101237. bits-=bytes*8;
  101238. if(b->endbit){
  101239. int i;
  101240. /* unaligned copy. Do it the hard way. */
  101241. for(i=0;i<bytes;i++)
  101242. w(b,(unsigned long)(ptr[i]),8);
  101243. }else{
  101244. /* aligned block copy */
  101245. if(b->endbyte+bytes+1>=b->storage){
  101246. b->storage=b->endbyte+bytes+BUFFER_INCREMENT;
  101247. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage);
  101248. b->ptr=b->buffer+b->endbyte;
  101249. }
  101250. memmove(b->ptr,source,bytes);
  101251. b->ptr+=bytes;
  101252. b->endbyte+=bytes;
  101253. *b->ptr=0;
  101254. }
  101255. if(bits){
  101256. if(msb)
  101257. w(b,(unsigned long)(ptr[bytes]>>(8-bits)),bits);
  101258. else
  101259. w(b,(unsigned long)(ptr[bytes]),bits);
  101260. }
  101261. }
  101262. void oggpack_writecopy(oggpack_buffer *b,void *source,long bits){
  101263. oggpack_writecopy_helper(b,source,bits,oggpack_write,0);
  101264. }
  101265. void oggpackB_writecopy(oggpack_buffer *b,void *source,long bits){
  101266. oggpack_writecopy_helper(b,source,bits,oggpackB_write,1);
  101267. }
  101268. void oggpack_reset(oggpack_buffer *b){
  101269. b->ptr=b->buffer;
  101270. b->buffer[0]=0;
  101271. b->endbit=b->endbyte=0;
  101272. }
  101273. void oggpackB_reset(oggpack_buffer *b){
  101274. oggpack_reset(b);
  101275. }
  101276. void oggpack_writeclear(oggpack_buffer *b){
  101277. _ogg_free(b->buffer);
  101278. memset(b,0,sizeof(*b));
  101279. }
  101280. void oggpackB_writeclear(oggpack_buffer *b){
  101281. oggpack_writeclear(b);
  101282. }
  101283. void oggpack_readinit(oggpack_buffer *b,unsigned char *buf,int bytes){
  101284. memset(b,0,sizeof(*b));
  101285. b->buffer=b->ptr=buf;
  101286. b->storage=bytes;
  101287. }
  101288. void oggpackB_readinit(oggpack_buffer *b,unsigned char *buf,int bytes){
  101289. oggpack_readinit(b,buf,bytes);
  101290. }
  101291. /* Read in bits without advancing the bitptr; bits <= 32 */
  101292. long oggpack_look(oggpack_buffer *b,int bits){
  101293. unsigned long ret;
  101294. unsigned long m=mask[bits];
  101295. bits+=b->endbit;
  101296. if(b->endbyte+4>=b->storage){
  101297. /* not the main path */
  101298. if(b->endbyte*8+bits>b->storage*8)return(-1);
  101299. }
  101300. ret=b->ptr[0]>>b->endbit;
  101301. if(bits>8){
  101302. ret|=b->ptr[1]<<(8-b->endbit);
  101303. if(bits>16){
  101304. ret|=b->ptr[2]<<(16-b->endbit);
  101305. if(bits>24){
  101306. ret|=b->ptr[3]<<(24-b->endbit);
  101307. if(bits>32 && b->endbit)
  101308. ret|=b->ptr[4]<<(32-b->endbit);
  101309. }
  101310. }
  101311. }
  101312. return(m&ret);
  101313. }
  101314. /* Read in bits without advancing the bitptr; bits <= 32 */
  101315. long oggpackB_look(oggpack_buffer *b,int bits){
  101316. unsigned long ret;
  101317. int m=32-bits;
  101318. bits+=b->endbit;
  101319. if(b->endbyte+4>=b->storage){
  101320. /* not the main path */
  101321. if(b->endbyte*8+bits>b->storage*8)return(-1);
  101322. }
  101323. ret=b->ptr[0]<<(24+b->endbit);
  101324. if(bits>8){
  101325. ret|=b->ptr[1]<<(16+b->endbit);
  101326. if(bits>16){
  101327. ret|=b->ptr[2]<<(8+b->endbit);
  101328. if(bits>24){
  101329. ret|=b->ptr[3]<<(b->endbit);
  101330. if(bits>32 && b->endbit)
  101331. ret|=b->ptr[4]>>(8-b->endbit);
  101332. }
  101333. }
  101334. }
  101335. return ((ret&0xffffffff)>>(m>>1))>>((m+1)>>1);
  101336. }
  101337. long oggpack_look1(oggpack_buffer *b){
  101338. if(b->endbyte>=b->storage)return(-1);
  101339. return((b->ptr[0]>>b->endbit)&1);
  101340. }
  101341. long oggpackB_look1(oggpack_buffer *b){
  101342. if(b->endbyte>=b->storage)return(-1);
  101343. return((b->ptr[0]>>(7-b->endbit))&1);
  101344. }
  101345. void oggpack_adv(oggpack_buffer *b,int bits){
  101346. bits+=b->endbit;
  101347. b->ptr+=bits/8;
  101348. b->endbyte+=bits/8;
  101349. b->endbit=bits&7;
  101350. }
  101351. void oggpackB_adv(oggpack_buffer *b,int bits){
  101352. oggpack_adv(b,bits);
  101353. }
  101354. void oggpack_adv1(oggpack_buffer *b){
  101355. if(++(b->endbit)>7){
  101356. b->endbit=0;
  101357. b->ptr++;
  101358. b->endbyte++;
  101359. }
  101360. }
  101361. void oggpackB_adv1(oggpack_buffer *b){
  101362. oggpack_adv1(b);
  101363. }
  101364. /* bits <= 32 */
  101365. long oggpack_read(oggpack_buffer *b,int bits){
  101366. long ret;
  101367. unsigned long m=mask[bits];
  101368. bits+=b->endbit;
  101369. if(b->endbyte+4>=b->storage){
  101370. /* not the main path */
  101371. ret=-1L;
  101372. if(b->endbyte*8+bits>b->storage*8)goto overflow;
  101373. }
  101374. ret=b->ptr[0]>>b->endbit;
  101375. if(bits>8){
  101376. ret|=b->ptr[1]<<(8-b->endbit);
  101377. if(bits>16){
  101378. ret|=b->ptr[2]<<(16-b->endbit);
  101379. if(bits>24){
  101380. ret|=b->ptr[3]<<(24-b->endbit);
  101381. if(bits>32 && b->endbit){
  101382. ret|=b->ptr[4]<<(32-b->endbit);
  101383. }
  101384. }
  101385. }
  101386. }
  101387. ret&=m;
  101388. overflow:
  101389. b->ptr+=bits/8;
  101390. b->endbyte+=bits/8;
  101391. b->endbit=bits&7;
  101392. return(ret);
  101393. }
  101394. /* bits <= 32 */
  101395. long oggpackB_read(oggpack_buffer *b,int bits){
  101396. long ret;
  101397. long m=32-bits;
  101398. bits+=b->endbit;
  101399. if(b->endbyte+4>=b->storage){
  101400. /* not the main path */
  101401. ret=-1L;
  101402. if(b->endbyte*8+bits>b->storage*8)goto overflow;
  101403. }
  101404. ret=b->ptr[0]<<(24+b->endbit);
  101405. if(bits>8){
  101406. ret|=b->ptr[1]<<(16+b->endbit);
  101407. if(bits>16){
  101408. ret|=b->ptr[2]<<(8+b->endbit);
  101409. if(bits>24){
  101410. ret|=b->ptr[3]<<(b->endbit);
  101411. if(bits>32 && b->endbit)
  101412. ret|=b->ptr[4]>>(8-b->endbit);
  101413. }
  101414. }
  101415. }
  101416. ret=((ret&0xffffffffUL)>>(m>>1))>>((m+1)>>1);
  101417. overflow:
  101418. b->ptr+=bits/8;
  101419. b->endbyte+=bits/8;
  101420. b->endbit=bits&7;
  101421. return(ret);
  101422. }
  101423. long oggpack_read1(oggpack_buffer *b){
  101424. long ret;
  101425. if(b->endbyte>=b->storage){
  101426. /* not the main path */
  101427. ret=-1L;
  101428. goto overflow;
  101429. }
  101430. ret=(b->ptr[0]>>b->endbit)&1;
  101431. overflow:
  101432. b->endbit++;
  101433. if(b->endbit>7){
  101434. b->endbit=0;
  101435. b->ptr++;
  101436. b->endbyte++;
  101437. }
  101438. return(ret);
  101439. }
  101440. long oggpackB_read1(oggpack_buffer *b){
  101441. long ret;
  101442. if(b->endbyte>=b->storage){
  101443. /* not the main path */
  101444. ret=-1L;
  101445. goto overflow;
  101446. }
  101447. ret=(b->ptr[0]>>(7-b->endbit))&1;
  101448. overflow:
  101449. b->endbit++;
  101450. if(b->endbit>7){
  101451. b->endbit=0;
  101452. b->ptr++;
  101453. b->endbyte++;
  101454. }
  101455. return(ret);
  101456. }
  101457. long oggpack_bytes(oggpack_buffer *b){
  101458. return(b->endbyte+(b->endbit+7)/8);
  101459. }
  101460. long oggpack_bits(oggpack_buffer *b){
  101461. return(b->endbyte*8+b->endbit);
  101462. }
  101463. long oggpackB_bytes(oggpack_buffer *b){
  101464. return oggpack_bytes(b);
  101465. }
  101466. long oggpackB_bits(oggpack_buffer *b){
  101467. return oggpack_bits(b);
  101468. }
  101469. unsigned char *oggpack_get_buffer(oggpack_buffer *b){
  101470. return(b->buffer);
  101471. }
  101472. unsigned char *oggpackB_get_buffer(oggpack_buffer *b){
  101473. return oggpack_get_buffer(b);
  101474. }
  101475. /* Self test of the bitwise routines; everything else is based on
  101476. them, so they damned well better be solid. */
  101477. #ifdef _V_SELFTEST
  101478. #include <stdio.h>
  101479. static int ilog(unsigned int v){
  101480. int ret=0;
  101481. while(v){
  101482. ret++;
  101483. v>>=1;
  101484. }
  101485. return(ret);
  101486. }
  101487. oggpack_buffer o;
  101488. oggpack_buffer r;
  101489. void report(char *in){
  101490. fprintf(stderr,"%s",in);
  101491. exit(1);
  101492. }
  101493. void cliptest(unsigned long *b,int vals,int bits,int *comp,int compsize){
  101494. long bytes,i;
  101495. unsigned char *buffer;
  101496. oggpack_reset(&o);
  101497. for(i=0;i<vals;i++)
  101498. oggpack_write(&o,b[i],bits?bits:ilog(b[i]));
  101499. buffer=oggpack_get_buffer(&o);
  101500. bytes=oggpack_bytes(&o);
  101501. if(bytes!=compsize)report("wrong number of bytes!\n");
  101502. for(i=0;i<bytes;i++)if(buffer[i]!=comp[i]){
  101503. for(i=0;i<bytes;i++)fprintf(stderr,"%x %x\n",(int)buffer[i],(int)comp[i]);
  101504. report("wrote incorrect value!\n");
  101505. }
  101506. oggpack_readinit(&r,buffer,bytes);
  101507. for(i=0;i<vals;i++){
  101508. int tbit=bits?bits:ilog(b[i]);
  101509. if(oggpack_look(&r,tbit)==-1)
  101510. report("out of data!\n");
  101511. if(oggpack_look(&r,tbit)!=(b[i]&mask[tbit]))
  101512. report("looked at incorrect value!\n");
  101513. if(tbit==1)
  101514. if(oggpack_look1(&r)!=(b[i]&mask[tbit]))
  101515. report("looked at single bit incorrect value!\n");
  101516. if(tbit==1){
  101517. if(oggpack_read1(&r)!=(b[i]&mask[tbit]))
  101518. report("read incorrect single bit value!\n");
  101519. }else{
  101520. if(oggpack_read(&r,tbit)!=(b[i]&mask[tbit]))
  101521. report("read incorrect value!\n");
  101522. }
  101523. }
  101524. if(oggpack_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  101525. }
  101526. void cliptestB(unsigned long *b,int vals,int bits,int *comp,int compsize){
  101527. long bytes,i;
  101528. unsigned char *buffer;
  101529. oggpackB_reset(&o);
  101530. for(i=0;i<vals;i++)
  101531. oggpackB_write(&o,b[i],bits?bits:ilog(b[i]));
  101532. buffer=oggpackB_get_buffer(&o);
  101533. bytes=oggpackB_bytes(&o);
  101534. if(bytes!=compsize)report("wrong number of bytes!\n");
  101535. for(i=0;i<bytes;i++)if(buffer[i]!=comp[i]){
  101536. for(i=0;i<bytes;i++)fprintf(stderr,"%x %x\n",(int)buffer[i],(int)comp[i]);
  101537. report("wrote incorrect value!\n");
  101538. }
  101539. oggpackB_readinit(&r,buffer,bytes);
  101540. for(i=0;i<vals;i++){
  101541. int tbit=bits?bits:ilog(b[i]);
  101542. if(oggpackB_look(&r,tbit)==-1)
  101543. report("out of data!\n");
  101544. if(oggpackB_look(&r,tbit)!=(b[i]&mask[tbit]))
  101545. report("looked at incorrect value!\n");
  101546. if(tbit==1)
  101547. if(oggpackB_look1(&r)!=(b[i]&mask[tbit]))
  101548. report("looked at single bit incorrect value!\n");
  101549. if(tbit==1){
  101550. if(oggpackB_read1(&r)!=(b[i]&mask[tbit]))
  101551. report("read incorrect single bit value!\n");
  101552. }else{
  101553. if(oggpackB_read(&r,tbit)!=(b[i]&mask[tbit]))
  101554. report("read incorrect value!\n");
  101555. }
  101556. }
  101557. if(oggpackB_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  101558. }
  101559. int main(void){
  101560. unsigned char *buffer;
  101561. long bytes,i;
  101562. static unsigned long testbuffer1[]=
  101563. {18,12,103948,4325,543,76,432,52,3,65,4,56,32,42,34,21,1,23,32,546,456,7,
  101564. 567,56,8,8,55,3,52,342,341,4,265,7,67,86,2199,21,7,1,5,1,4};
  101565. int test1size=43;
  101566. static unsigned long testbuffer2[]=
  101567. {216531625L,1237861823,56732452,131,3212421,12325343,34547562,12313212,
  101568. 1233432,534,5,346435231,14436467,7869299,76326614,167548585,
  101569. 85525151,0,12321,1,349528352};
  101570. int test2size=21;
  101571. static unsigned long testbuffer3[]=
  101572. {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,
  101573. 0,1,30,1,1,1,0,0,1,0,0,0,12,0,11,0,1,0,0,1};
  101574. int test3size=56;
  101575. static unsigned long large[]=
  101576. {2136531625L,2137861823,56732452,131,3212421,12325343,34547562,12313212,
  101577. 1233432,534,5,2146435231,14436467,7869299,76326614,167548585,
  101578. 85525151,0,12321,1,2146528352};
  101579. int onesize=33;
  101580. static int one[33]={146,25,44,151,195,15,153,176,233,131,196,65,85,172,47,40,
  101581. 34,242,223,136,35,222,211,86,171,50,225,135,214,75,172,
  101582. 223,4};
  101583. static int oneB[33]={150,101,131,33,203,15,204,216,105,193,156,65,84,85,222,
  101584. 8,139,145,227,126,34,55,244,171,85,100,39,195,173,18,
  101585. 245,251,128};
  101586. int twosize=6;
  101587. static int two[6]={61,255,255,251,231,29};
  101588. static int twoB[6]={247,63,255,253,249,120};
  101589. int threesize=54;
  101590. static int three[54]={169,2,232,252,91,132,156,36,89,13,123,176,144,32,254,
  101591. 142,224,85,59,121,144,79,124,23,67,90,90,216,79,23,83,
  101592. 58,135,196,61,55,129,183,54,101,100,170,37,127,126,10,
  101593. 100,52,4,14,18,86,77,1};
  101594. static int threeB[54]={206,128,42,153,57,8,183,251,13,89,36,30,32,144,183,
  101595. 130,59,240,121,59,85,223,19,228,180,134,33,107,74,98,
  101596. 233,253,196,135,63,2,110,114,50,155,90,127,37,170,104,
  101597. 200,20,254,4,58,106,176,144,0};
  101598. int foursize=38;
  101599. static int four[38]={18,6,163,252,97,194,104,131,32,1,7,82,137,42,129,11,72,
  101600. 132,60,220,112,8,196,109,64,179,86,9,137,195,208,122,169,
  101601. 28,2,133,0,1};
  101602. static int fourB[38]={36,48,102,83,243,24,52,7,4,35,132,10,145,21,2,93,2,41,
  101603. 1,219,184,16,33,184,54,149,170,132,18,30,29,98,229,67,
  101604. 129,10,4,32};
  101605. int fivesize=45;
  101606. static int five[45]={169,2,126,139,144,172,30,4,80,72,240,59,130,218,73,62,
  101607. 241,24,210,44,4,20,0,248,116,49,135,100,110,130,181,169,
  101608. 84,75,159,2,1,0,132,192,8,0,0,18,22};
  101609. static int fiveB[45]={1,84,145,111,245,100,128,8,56,36,40,71,126,78,213,226,
  101610. 124,105,12,0,133,128,0,162,233,242,67,152,77,205,77,
  101611. 172,150,169,129,79,128,0,6,4,32,0,27,9,0};
  101612. int sixsize=7;
  101613. static int six[7]={17,177,170,242,169,19,148};
  101614. static int sixB[7]={136,141,85,79,149,200,41};
  101615. /* Test read/write together */
  101616. /* Later we test against pregenerated bitstreams */
  101617. oggpack_writeinit(&o);
  101618. fprintf(stderr,"\nSmall preclipped packing (LSb): ");
  101619. cliptest(testbuffer1,test1size,0,one,onesize);
  101620. fprintf(stderr,"ok.");
  101621. fprintf(stderr,"\nNull bit call (LSb): ");
  101622. cliptest(testbuffer3,test3size,0,two,twosize);
  101623. fprintf(stderr,"ok.");
  101624. fprintf(stderr,"\nLarge preclipped packing (LSb): ");
  101625. cliptest(testbuffer2,test2size,0,three,threesize);
  101626. fprintf(stderr,"ok.");
  101627. fprintf(stderr,"\n32 bit preclipped packing (LSb): ");
  101628. oggpack_reset(&o);
  101629. for(i=0;i<test2size;i++)
  101630. oggpack_write(&o,large[i],32);
  101631. buffer=oggpack_get_buffer(&o);
  101632. bytes=oggpack_bytes(&o);
  101633. oggpack_readinit(&r,buffer,bytes);
  101634. for(i=0;i<test2size;i++){
  101635. if(oggpack_look(&r,32)==-1)report("out of data. failed!");
  101636. if(oggpack_look(&r,32)!=large[i]){
  101637. fprintf(stderr,"%ld != %ld (%lx!=%lx):",oggpack_look(&r,32),large[i],
  101638. oggpack_look(&r,32),large[i]);
  101639. report("read incorrect value!\n");
  101640. }
  101641. oggpack_adv(&r,32);
  101642. }
  101643. if(oggpack_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  101644. fprintf(stderr,"ok.");
  101645. fprintf(stderr,"\nSmall unclipped packing (LSb): ");
  101646. cliptest(testbuffer1,test1size,7,four,foursize);
  101647. fprintf(stderr,"ok.");
  101648. fprintf(stderr,"\nLarge unclipped packing (LSb): ");
  101649. cliptest(testbuffer2,test2size,17,five,fivesize);
  101650. fprintf(stderr,"ok.");
  101651. fprintf(stderr,"\nSingle bit unclipped packing (LSb): ");
  101652. cliptest(testbuffer3,test3size,1,six,sixsize);
  101653. fprintf(stderr,"ok.");
  101654. fprintf(stderr,"\nTesting read past end (LSb): ");
  101655. oggpack_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  101656. for(i=0;i<64;i++){
  101657. if(oggpack_read(&r,1)!=0){
  101658. fprintf(stderr,"failed; got -1 prematurely.\n");
  101659. exit(1);
  101660. }
  101661. }
  101662. if(oggpack_look(&r,1)!=-1 ||
  101663. oggpack_read(&r,1)!=-1){
  101664. fprintf(stderr,"failed; read past end without -1.\n");
  101665. exit(1);
  101666. }
  101667. oggpack_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  101668. if(oggpack_read(&r,30)!=0 || oggpack_read(&r,16)!=0){
  101669. fprintf(stderr,"failed 2; got -1 prematurely.\n");
  101670. exit(1);
  101671. }
  101672. if(oggpack_look(&r,18)!=0 ||
  101673. oggpack_look(&r,18)!=0){
  101674. fprintf(stderr,"failed 3; got -1 prematurely.\n");
  101675. exit(1);
  101676. }
  101677. if(oggpack_look(&r,19)!=-1 ||
  101678. oggpack_look(&r,19)!=-1){
  101679. fprintf(stderr,"failed; read past end without -1.\n");
  101680. exit(1);
  101681. }
  101682. if(oggpack_look(&r,32)!=-1 ||
  101683. oggpack_look(&r,32)!=-1){
  101684. fprintf(stderr,"failed; read past end without -1.\n");
  101685. exit(1);
  101686. }
  101687. oggpack_writeclear(&o);
  101688. fprintf(stderr,"ok.\n");
  101689. /********** lazy, cut-n-paste retest with MSb packing ***********/
  101690. /* Test read/write together */
  101691. /* Later we test against pregenerated bitstreams */
  101692. oggpackB_writeinit(&o);
  101693. fprintf(stderr,"\nSmall preclipped packing (MSb): ");
  101694. cliptestB(testbuffer1,test1size,0,oneB,onesize);
  101695. fprintf(stderr,"ok.");
  101696. fprintf(stderr,"\nNull bit call (MSb): ");
  101697. cliptestB(testbuffer3,test3size,0,twoB,twosize);
  101698. fprintf(stderr,"ok.");
  101699. fprintf(stderr,"\nLarge preclipped packing (MSb): ");
  101700. cliptestB(testbuffer2,test2size,0,threeB,threesize);
  101701. fprintf(stderr,"ok.");
  101702. fprintf(stderr,"\n32 bit preclipped packing (MSb): ");
  101703. oggpackB_reset(&o);
  101704. for(i=0;i<test2size;i++)
  101705. oggpackB_write(&o,large[i],32);
  101706. buffer=oggpackB_get_buffer(&o);
  101707. bytes=oggpackB_bytes(&o);
  101708. oggpackB_readinit(&r,buffer,bytes);
  101709. for(i=0;i<test2size;i++){
  101710. if(oggpackB_look(&r,32)==-1)report("out of data. failed!");
  101711. if(oggpackB_look(&r,32)!=large[i]){
  101712. fprintf(stderr,"%ld != %ld (%lx!=%lx):",oggpackB_look(&r,32),large[i],
  101713. oggpackB_look(&r,32),large[i]);
  101714. report("read incorrect value!\n");
  101715. }
  101716. oggpackB_adv(&r,32);
  101717. }
  101718. if(oggpackB_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  101719. fprintf(stderr,"ok.");
  101720. fprintf(stderr,"\nSmall unclipped packing (MSb): ");
  101721. cliptestB(testbuffer1,test1size,7,fourB,foursize);
  101722. fprintf(stderr,"ok.");
  101723. fprintf(stderr,"\nLarge unclipped packing (MSb): ");
  101724. cliptestB(testbuffer2,test2size,17,fiveB,fivesize);
  101725. fprintf(stderr,"ok.");
  101726. fprintf(stderr,"\nSingle bit unclipped packing (MSb): ");
  101727. cliptestB(testbuffer3,test3size,1,sixB,sixsize);
  101728. fprintf(stderr,"ok.");
  101729. fprintf(stderr,"\nTesting read past end (MSb): ");
  101730. oggpackB_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  101731. for(i=0;i<64;i++){
  101732. if(oggpackB_read(&r,1)!=0){
  101733. fprintf(stderr,"failed; got -1 prematurely.\n");
  101734. exit(1);
  101735. }
  101736. }
  101737. if(oggpackB_look(&r,1)!=-1 ||
  101738. oggpackB_read(&r,1)!=-1){
  101739. fprintf(stderr,"failed; read past end without -1.\n");
  101740. exit(1);
  101741. }
  101742. oggpackB_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  101743. if(oggpackB_read(&r,30)!=0 || oggpackB_read(&r,16)!=0){
  101744. fprintf(stderr,"failed 2; got -1 prematurely.\n");
  101745. exit(1);
  101746. }
  101747. if(oggpackB_look(&r,18)!=0 ||
  101748. oggpackB_look(&r,18)!=0){
  101749. fprintf(stderr,"failed 3; got -1 prematurely.\n");
  101750. exit(1);
  101751. }
  101752. if(oggpackB_look(&r,19)!=-1 ||
  101753. oggpackB_look(&r,19)!=-1){
  101754. fprintf(stderr,"failed; read past end without -1.\n");
  101755. exit(1);
  101756. }
  101757. if(oggpackB_look(&r,32)!=-1 ||
  101758. oggpackB_look(&r,32)!=-1){
  101759. fprintf(stderr,"failed; read past end without -1.\n");
  101760. exit(1);
  101761. }
  101762. oggpackB_writeclear(&o);
  101763. fprintf(stderr,"ok.\n\n");
  101764. return(0);
  101765. }
  101766. #endif /* _V_SELFTEST */
  101767. #undef BUFFER_INCREMENT
  101768. #endif
  101769. /********* End of inlined file: bitwise.c *********/
  101770. /********* Start of inlined file: framing.c *********/
  101771. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  101772. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  101773. // tasks..
  101774. #ifdef _MSC_VER
  101775. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  101776. #endif
  101777. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  101778. #if JUCE_USE_OGGVORBIS
  101779. #include <stdlib.h>
  101780. #include <string.h>
  101781. /* A complete description of Ogg framing exists in docs/framing.html */
  101782. int ogg_page_version(ogg_page *og){
  101783. return((int)(og->header[4]));
  101784. }
  101785. int ogg_page_continued(ogg_page *og){
  101786. return((int)(og->header[5]&0x01));
  101787. }
  101788. int ogg_page_bos(ogg_page *og){
  101789. return((int)(og->header[5]&0x02));
  101790. }
  101791. int ogg_page_eos(ogg_page *og){
  101792. return((int)(og->header[5]&0x04));
  101793. }
  101794. ogg_int64_t ogg_page_granulepos(ogg_page *og){
  101795. unsigned char *page=og->header;
  101796. ogg_int64_t granulepos=page[13]&(0xff);
  101797. granulepos= (granulepos<<8)|(page[12]&0xff);
  101798. granulepos= (granulepos<<8)|(page[11]&0xff);
  101799. granulepos= (granulepos<<8)|(page[10]&0xff);
  101800. granulepos= (granulepos<<8)|(page[9]&0xff);
  101801. granulepos= (granulepos<<8)|(page[8]&0xff);
  101802. granulepos= (granulepos<<8)|(page[7]&0xff);
  101803. granulepos= (granulepos<<8)|(page[6]&0xff);
  101804. return(granulepos);
  101805. }
  101806. int ogg_page_serialno(ogg_page *og){
  101807. return(og->header[14] |
  101808. (og->header[15]<<8) |
  101809. (og->header[16]<<16) |
  101810. (og->header[17]<<24));
  101811. }
  101812. long ogg_page_pageno(ogg_page *og){
  101813. return(og->header[18] |
  101814. (og->header[19]<<8) |
  101815. (og->header[20]<<16) |
  101816. (og->header[21]<<24));
  101817. }
  101818. /* returns the number of packets that are completed on this page (if
  101819. the leading packet is begun on a previous page, but ends on this
  101820. page, it's counted */
  101821. /* NOTE:
  101822. If a page consists of a packet begun on a previous page, and a new
  101823. packet begun (but not completed) on this page, the return will be:
  101824. ogg_page_packets(page) ==1,
  101825. ogg_page_continued(page) !=0
  101826. If a page happens to be a single packet that was begun on a
  101827. previous page, and spans to the next page (in the case of a three or
  101828. more page packet), the return will be:
  101829. ogg_page_packets(page) ==0,
  101830. ogg_page_continued(page) !=0
  101831. */
  101832. int ogg_page_packets(ogg_page *og){
  101833. int i,n=og->header[26],count=0;
  101834. for(i=0;i<n;i++)
  101835. if(og->header[27+i]<255)count++;
  101836. return(count);
  101837. }
  101838. #if 0
  101839. /* helper to initialize lookup for direct-table CRC (illustrative; we
  101840. use the static init below) */
  101841. static ogg_uint32_t _ogg_crc_entry(unsigned long index){
  101842. int i;
  101843. unsigned long r;
  101844. r = index << 24;
  101845. for (i=0; i<8; i++)
  101846. if (r & 0x80000000UL)
  101847. r = (r << 1) ^ 0x04c11db7; /* The same as the ethernet generator
  101848. polynomial, although we use an
  101849. unreflected alg and an init/final
  101850. of 0, not 0xffffffff */
  101851. else
  101852. r<<=1;
  101853. return (r & 0xffffffffUL);
  101854. }
  101855. #endif
  101856. static const ogg_uint32_t crc_lookup[256]={
  101857. 0x00000000,0x04c11db7,0x09823b6e,0x0d4326d9,
  101858. 0x130476dc,0x17c56b6b,0x1a864db2,0x1e475005,
  101859. 0x2608edb8,0x22c9f00f,0x2f8ad6d6,0x2b4bcb61,
  101860. 0x350c9b64,0x31cd86d3,0x3c8ea00a,0x384fbdbd,
  101861. 0x4c11db70,0x48d0c6c7,0x4593e01e,0x4152fda9,
  101862. 0x5f15adac,0x5bd4b01b,0x569796c2,0x52568b75,
  101863. 0x6a1936c8,0x6ed82b7f,0x639b0da6,0x675a1011,
  101864. 0x791d4014,0x7ddc5da3,0x709f7b7a,0x745e66cd,
  101865. 0x9823b6e0,0x9ce2ab57,0x91a18d8e,0x95609039,
  101866. 0x8b27c03c,0x8fe6dd8b,0x82a5fb52,0x8664e6e5,
  101867. 0xbe2b5b58,0xbaea46ef,0xb7a96036,0xb3687d81,
  101868. 0xad2f2d84,0xa9ee3033,0xa4ad16ea,0xa06c0b5d,
  101869. 0xd4326d90,0xd0f37027,0xddb056fe,0xd9714b49,
  101870. 0xc7361b4c,0xc3f706fb,0xceb42022,0xca753d95,
  101871. 0xf23a8028,0xf6fb9d9f,0xfbb8bb46,0xff79a6f1,
  101872. 0xe13ef6f4,0xe5ffeb43,0xe8bccd9a,0xec7dd02d,
  101873. 0x34867077,0x30476dc0,0x3d044b19,0x39c556ae,
  101874. 0x278206ab,0x23431b1c,0x2e003dc5,0x2ac12072,
  101875. 0x128e9dcf,0x164f8078,0x1b0ca6a1,0x1fcdbb16,
  101876. 0x018aeb13,0x054bf6a4,0x0808d07d,0x0cc9cdca,
  101877. 0x7897ab07,0x7c56b6b0,0x71159069,0x75d48dde,
  101878. 0x6b93dddb,0x6f52c06c,0x6211e6b5,0x66d0fb02,
  101879. 0x5e9f46bf,0x5a5e5b08,0x571d7dd1,0x53dc6066,
  101880. 0x4d9b3063,0x495a2dd4,0x44190b0d,0x40d816ba,
  101881. 0xaca5c697,0xa864db20,0xa527fdf9,0xa1e6e04e,
  101882. 0xbfa1b04b,0xbb60adfc,0xb6238b25,0xb2e29692,
  101883. 0x8aad2b2f,0x8e6c3698,0x832f1041,0x87ee0df6,
  101884. 0x99a95df3,0x9d684044,0x902b669d,0x94ea7b2a,
  101885. 0xe0b41de7,0xe4750050,0xe9362689,0xedf73b3e,
  101886. 0xf3b06b3b,0xf771768c,0xfa325055,0xfef34de2,
  101887. 0xc6bcf05f,0xc27dede8,0xcf3ecb31,0xcbffd686,
  101888. 0xd5b88683,0xd1799b34,0xdc3abded,0xd8fba05a,
  101889. 0x690ce0ee,0x6dcdfd59,0x608edb80,0x644fc637,
  101890. 0x7a089632,0x7ec98b85,0x738aad5c,0x774bb0eb,
  101891. 0x4f040d56,0x4bc510e1,0x46863638,0x42472b8f,
  101892. 0x5c007b8a,0x58c1663d,0x558240e4,0x51435d53,
  101893. 0x251d3b9e,0x21dc2629,0x2c9f00f0,0x285e1d47,
  101894. 0x36194d42,0x32d850f5,0x3f9b762c,0x3b5a6b9b,
  101895. 0x0315d626,0x07d4cb91,0x0a97ed48,0x0e56f0ff,
  101896. 0x1011a0fa,0x14d0bd4d,0x19939b94,0x1d528623,
  101897. 0xf12f560e,0xf5ee4bb9,0xf8ad6d60,0xfc6c70d7,
  101898. 0xe22b20d2,0xe6ea3d65,0xeba91bbc,0xef68060b,
  101899. 0xd727bbb6,0xd3e6a601,0xdea580d8,0xda649d6f,
  101900. 0xc423cd6a,0xc0e2d0dd,0xcda1f604,0xc960ebb3,
  101901. 0xbd3e8d7e,0xb9ff90c9,0xb4bcb610,0xb07daba7,
  101902. 0xae3afba2,0xaafbe615,0xa7b8c0cc,0xa379dd7b,
  101903. 0x9b3660c6,0x9ff77d71,0x92b45ba8,0x9675461f,
  101904. 0x8832161a,0x8cf30bad,0x81b02d74,0x857130c3,
  101905. 0x5d8a9099,0x594b8d2e,0x5408abf7,0x50c9b640,
  101906. 0x4e8ee645,0x4a4ffbf2,0x470cdd2b,0x43cdc09c,
  101907. 0x7b827d21,0x7f436096,0x7200464f,0x76c15bf8,
  101908. 0x68860bfd,0x6c47164a,0x61043093,0x65c52d24,
  101909. 0x119b4be9,0x155a565e,0x18197087,0x1cd86d30,
  101910. 0x029f3d35,0x065e2082,0x0b1d065b,0x0fdc1bec,
  101911. 0x3793a651,0x3352bbe6,0x3e119d3f,0x3ad08088,
  101912. 0x2497d08d,0x2056cd3a,0x2d15ebe3,0x29d4f654,
  101913. 0xc5a92679,0xc1683bce,0xcc2b1d17,0xc8ea00a0,
  101914. 0xd6ad50a5,0xd26c4d12,0xdf2f6bcb,0xdbee767c,
  101915. 0xe3a1cbc1,0xe760d676,0xea23f0af,0xeee2ed18,
  101916. 0xf0a5bd1d,0xf464a0aa,0xf9278673,0xfde69bc4,
  101917. 0x89b8fd09,0x8d79e0be,0x803ac667,0x84fbdbd0,
  101918. 0x9abc8bd5,0x9e7d9662,0x933eb0bb,0x97ffad0c,
  101919. 0xafb010b1,0xab710d06,0xa6322bdf,0xa2f33668,
  101920. 0xbcb4666d,0xb8757bda,0xb5365d03,0xb1f740b4};
  101921. /* init the encode/decode logical stream state */
  101922. int ogg_stream_init(ogg_stream_state *os,int serialno){
  101923. if(os){
  101924. memset(os,0,sizeof(*os));
  101925. os->body_storage=16*1024;
  101926. os->body_data=(unsigned char*) _ogg_malloc(os->body_storage*sizeof(*os->body_data));
  101927. os->lacing_storage=1024;
  101928. os->lacing_vals=(int*) _ogg_malloc(os->lacing_storage*sizeof(*os->lacing_vals));
  101929. os->granule_vals=(ogg_int64_t*) _ogg_malloc(os->lacing_storage*sizeof(*os->granule_vals));
  101930. os->serialno=serialno;
  101931. return(0);
  101932. }
  101933. return(-1);
  101934. }
  101935. /* _clear does not free os, only the non-flat storage within */
  101936. int ogg_stream_clear(ogg_stream_state *os){
  101937. if(os){
  101938. if(os->body_data)_ogg_free(os->body_data);
  101939. if(os->lacing_vals)_ogg_free(os->lacing_vals);
  101940. if(os->granule_vals)_ogg_free(os->granule_vals);
  101941. memset(os,0,sizeof(*os));
  101942. }
  101943. return(0);
  101944. }
  101945. int ogg_stream_destroy(ogg_stream_state *os){
  101946. if(os){
  101947. ogg_stream_clear(os);
  101948. _ogg_free(os);
  101949. }
  101950. return(0);
  101951. }
  101952. /* Helpers for ogg_stream_encode; this keeps the structure and
  101953. what's happening fairly clear */
  101954. static void _os_body_expand(ogg_stream_state *os,int needed){
  101955. if(os->body_storage<=os->body_fill+needed){
  101956. os->body_storage+=(needed+1024);
  101957. os->body_data=(unsigned char*) _ogg_realloc(os->body_data,os->body_storage*sizeof(*os->body_data));
  101958. }
  101959. }
  101960. static void _os_lacing_expand(ogg_stream_state *os,int needed){
  101961. if(os->lacing_storage<=os->lacing_fill+needed){
  101962. os->lacing_storage+=(needed+32);
  101963. os->lacing_vals=(int*)_ogg_realloc(os->lacing_vals,os->lacing_storage*sizeof(*os->lacing_vals));
  101964. os->granule_vals=(ogg_int64_t*)_ogg_realloc(os->granule_vals,os->lacing_storage*sizeof(*os->granule_vals));
  101965. }
  101966. }
  101967. /* checksum the page */
  101968. /* Direct table CRC; note that this will be faster in the future if we
  101969. perform the checksum silmultaneously with other copies */
  101970. void ogg_page_checksum_set(ogg_page *og){
  101971. if(og){
  101972. ogg_uint32_t crc_reg=0;
  101973. int i;
  101974. /* safety; needed for API behavior, but not framing code */
  101975. og->header[22]=0;
  101976. og->header[23]=0;
  101977. og->header[24]=0;
  101978. og->header[25]=0;
  101979. for(i=0;i<og->header_len;i++)
  101980. crc_reg=(crc_reg<<8)^crc_lookup[((crc_reg >> 24)&0xff)^og->header[i]];
  101981. for(i=0;i<og->body_len;i++)
  101982. crc_reg=(crc_reg<<8)^crc_lookup[((crc_reg >> 24)&0xff)^og->body[i]];
  101983. og->header[22]=(unsigned char)(crc_reg&0xff);
  101984. og->header[23]=(unsigned char)((crc_reg>>8)&0xff);
  101985. og->header[24]=(unsigned char)((crc_reg>>16)&0xff);
  101986. og->header[25]=(unsigned char)((crc_reg>>24)&0xff);
  101987. }
  101988. }
  101989. /* submit data to the internal buffer of the framing engine */
  101990. int ogg_stream_packetin(ogg_stream_state *os,ogg_packet *op){
  101991. int lacing_vals=op->bytes/255+1,i;
  101992. if(os->body_returned){
  101993. /* advance packet data according to the body_returned pointer. We
  101994. had to keep it around to return a pointer into the buffer last
  101995. call */
  101996. os->body_fill-=os->body_returned;
  101997. if(os->body_fill)
  101998. memmove(os->body_data,os->body_data+os->body_returned,
  101999. os->body_fill);
  102000. os->body_returned=0;
  102001. }
  102002. /* make sure we have the buffer storage */
  102003. _os_body_expand(os,op->bytes);
  102004. _os_lacing_expand(os,lacing_vals);
  102005. /* Copy in the submitted packet. Yes, the copy is a waste; this is
  102006. the liability of overly clean abstraction for the time being. It
  102007. will actually be fairly easy to eliminate the extra copy in the
  102008. future */
  102009. memcpy(os->body_data+os->body_fill,op->packet,op->bytes);
  102010. os->body_fill+=op->bytes;
  102011. /* Store lacing vals for this packet */
  102012. for(i=0;i<lacing_vals-1;i++){
  102013. os->lacing_vals[os->lacing_fill+i]=255;
  102014. os->granule_vals[os->lacing_fill+i]=os->granulepos;
  102015. }
  102016. os->lacing_vals[os->lacing_fill+i]=(op->bytes)%255;
  102017. os->granulepos=os->granule_vals[os->lacing_fill+i]=op->granulepos;
  102018. /* flag the first segment as the beginning of the packet */
  102019. os->lacing_vals[os->lacing_fill]|= 0x100;
  102020. os->lacing_fill+=lacing_vals;
  102021. /* for the sake of completeness */
  102022. os->packetno++;
  102023. if(op->e_o_s)os->e_o_s=1;
  102024. return(0);
  102025. }
  102026. /* This will flush remaining packets into a page (returning nonzero),
  102027. even if there is not enough data to trigger a flush normally
  102028. (undersized page). If there are no packets or partial packets to
  102029. flush, ogg_stream_flush returns 0. Note that ogg_stream_flush will
  102030. try to flush a normal sized page like ogg_stream_pageout; a call to
  102031. ogg_stream_flush does not guarantee that all packets have flushed.
  102032. Only a return value of 0 from ogg_stream_flush indicates all packet
  102033. data is flushed into pages.
  102034. since ogg_stream_flush will flush the last page in a stream even if
  102035. it's undersized, you almost certainly want to use ogg_stream_pageout
  102036. (and *not* ogg_stream_flush) unless you specifically need to flush
  102037. an page regardless of size in the middle of a stream. */
  102038. int ogg_stream_flush(ogg_stream_state *os,ogg_page *og){
  102039. int i;
  102040. int vals=0;
  102041. int maxvals=(os->lacing_fill>255?255:os->lacing_fill);
  102042. int bytes=0;
  102043. long acc=0;
  102044. ogg_int64_t granule_pos=-1;
  102045. if(maxvals==0)return(0);
  102046. /* construct a page */
  102047. /* decide how many segments to include */
  102048. /* If this is the initial header case, the first page must only include
  102049. the initial header packet */
  102050. if(os->b_o_s==0){ /* 'initial header page' case */
  102051. granule_pos=0;
  102052. for(vals=0;vals<maxvals;vals++){
  102053. if((os->lacing_vals[vals]&0x0ff)<255){
  102054. vals++;
  102055. break;
  102056. }
  102057. }
  102058. }else{
  102059. for(vals=0;vals<maxvals;vals++){
  102060. if(acc>4096)break;
  102061. acc+=os->lacing_vals[vals]&0x0ff;
  102062. if((os->lacing_vals[vals]&0xff)<255)
  102063. granule_pos=os->granule_vals[vals];
  102064. }
  102065. }
  102066. /* construct the header in temp storage */
  102067. memcpy(os->header,"OggS",4);
  102068. /* stream structure version */
  102069. os->header[4]=0x00;
  102070. /* continued packet flag? */
  102071. os->header[5]=0x00;
  102072. if((os->lacing_vals[0]&0x100)==0)os->header[5]|=0x01;
  102073. /* first page flag? */
  102074. if(os->b_o_s==0)os->header[5]|=0x02;
  102075. /* last page flag? */
  102076. if(os->e_o_s && os->lacing_fill==vals)os->header[5]|=0x04;
  102077. os->b_o_s=1;
  102078. /* 64 bits of PCM position */
  102079. for(i=6;i<14;i++){
  102080. os->header[i]=(unsigned char)(granule_pos&0xff);
  102081. granule_pos>>=8;
  102082. }
  102083. /* 32 bits of stream serial number */
  102084. {
  102085. long serialno=os->serialno;
  102086. for(i=14;i<18;i++){
  102087. os->header[i]=(unsigned char)(serialno&0xff);
  102088. serialno>>=8;
  102089. }
  102090. }
  102091. /* 32 bits of page counter (we have both counter and page header
  102092. because this val can roll over) */
  102093. if(os->pageno==-1)os->pageno=0; /* because someone called
  102094. stream_reset; this would be a
  102095. strange thing to do in an
  102096. encode stream, but it has
  102097. plausible uses */
  102098. {
  102099. long pageno=os->pageno++;
  102100. for(i=18;i<22;i++){
  102101. os->header[i]=(unsigned char)(pageno&0xff);
  102102. pageno>>=8;
  102103. }
  102104. }
  102105. /* zero for computation; filled in later */
  102106. os->header[22]=0;
  102107. os->header[23]=0;
  102108. os->header[24]=0;
  102109. os->header[25]=0;
  102110. /* segment table */
  102111. os->header[26]=(unsigned char)(vals&0xff);
  102112. for(i=0;i<vals;i++)
  102113. bytes+=os->header[i+27]=(unsigned char)(os->lacing_vals[i]&0xff);
  102114. /* set pointers in the ogg_page struct */
  102115. og->header=os->header;
  102116. og->header_len=os->header_fill=vals+27;
  102117. og->body=os->body_data+os->body_returned;
  102118. og->body_len=bytes;
  102119. /* advance the lacing data and set the body_returned pointer */
  102120. os->lacing_fill-=vals;
  102121. memmove(os->lacing_vals,os->lacing_vals+vals,os->lacing_fill*sizeof(*os->lacing_vals));
  102122. memmove(os->granule_vals,os->granule_vals+vals,os->lacing_fill*sizeof(*os->granule_vals));
  102123. os->body_returned+=bytes;
  102124. /* calculate the checksum */
  102125. ogg_page_checksum_set(og);
  102126. /* done */
  102127. return(1);
  102128. }
  102129. /* This constructs pages from buffered packet segments. The pointers
  102130. returned are to static buffers; do not free. The returned buffers are
  102131. good only until the next call (using the same ogg_stream_state) */
  102132. int ogg_stream_pageout(ogg_stream_state *os, ogg_page *og){
  102133. if((os->e_o_s&&os->lacing_fill) || /* 'were done, now flush' case */
  102134. os->body_fill-os->body_returned > 4096 ||/* 'page nominal size' case */
  102135. os->lacing_fill>=255 || /* 'segment table full' case */
  102136. (os->lacing_fill&&!os->b_o_s)){ /* 'initial header page' case */
  102137. return(ogg_stream_flush(os,og));
  102138. }
  102139. /* not enough data to construct a page and not end of stream */
  102140. return(0);
  102141. }
  102142. int ogg_stream_eos(ogg_stream_state *os){
  102143. return os->e_o_s;
  102144. }
  102145. /* DECODING PRIMITIVES: packet streaming layer **********************/
  102146. /* This has two layers to place more of the multi-serialno and paging
  102147. control in the application's hands. First, we expose a data buffer
  102148. using ogg_sync_buffer(). The app either copies into the
  102149. buffer, or passes it directly to read(), etc. We then call
  102150. ogg_sync_wrote() to tell how many bytes we just added.
  102151. Pages are returned (pointers into the buffer in ogg_sync_state)
  102152. by ogg_sync_pageout(). The page is then submitted to
  102153. ogg_stream_pagein() along with the appropriate
  102154. ogg_stream_state* (ie, matching serialno). We then get raw
  102155. packets out calling ogg_stream_packetout() with a
  102156. ogg_stream_state. */
  102157. /* initialize the struct to a known state */
  102158. int ogg_sync_init(ogg_sync_state *oy){
  102159. if(oy){
  102160. memset(oy,0,sizeof(*oy));
  102161. }
  102162. return(0);
  102163. }
  102164. /* clear non-flat storage within */
  102165. int ogg_sync_clear(ogg_sync_state *oy){
  102166. if(oy){
  102167. if(oy->data)_ogg_free(oy->data);
  102168. ogg_sync_init(oy);
  102169. }
  102170. return(0);
  102171. }
  102172. int ogg_sync_destroy(ogg_sync_state *oy){
  102173. if(oy){
  102174. ogg_sync_clear(oy);
  102175. _ogg_free(oy);
  102176. }
  102177. return(0);
  102178. }
  102179. char *ogg_sync_buffer(ogg_sync_state *oy, long size){
  102180. /* first, clear out any space that has been previously returned */
  102181. if(oy->returned){
  102182. oy->fill-=oy->returned;
  102183. if(oy->fill>0)
  102184. memmove(oy->data,oy->data+oy->returned,oy->fill);
  102185. oy->returned=0;
  102186. }
  102187. if(size>oy->storage-oy->fill){
  102188. /* We need to extend the internal buffer */
  102189. long newsize=size+oy->fill+4096; /* an extra page to be nice */
  102190. if(oy->data)
  102191. oy->data=(unsigned char*) _ogg_realloc(oy->data,newsize);
  102192. else
  102193. oy->data=(unsigned char*) _ogg_malloc(newsize);
  102194. oy->storage=newsize;
  102195. }
  102196. /* expose a segment at least as large as requested at the fill mark */
  102197. return((char *)oy->data+oy->fill);
  102198. }
  102199. int ogg_sync_wrote(ogg_sync_state *oy, long bytes){
  102200. if(oy->fill+bytes>oy->storage)return(-1);
  102201. oy->fill+=bytes;
  102202. return(0);
  102203. }
  102204. /* sync the stream. This is meant to be useful for finding page
  102205. boundaries.
  102206. return values for this:
  102207. -n) skipped n bytes
  102208. 0) page not ready; more data (no bytes skipped)
  102209. n) page synced at current location; page length n bytes
  102210. */
  102211. long ogg_sync_pageseek(ogg_sync_state *oy,ogg_page *og){
  102212. unsigned char *page=oy->data+oy->returned;
  102213. unsigned char *next;
  102214. long bytes=oy->fill-oy->returned;
  102215. if(oy->headerbytes==0){
  102216. int headerbytes,i;
  102217. if(bytes<27)return(0); /* not enough for a header */
  102218. /* verify capture pattern */
  102219. if(memcmp(page,"OggS",4))goto sync_fail;
  102220. headerbytes=page[26]+27;
  102221. if(bytes<headerbytes)return(0); /* not enough for header + seg table */
  102222. /* count up body length in the segment table */
  102223. for(i=0;i<page[26];i++)
  102224. oy->bodybytes+=page[27+i];
  102225. oy->headerbytes=headerbytes;
  102226. }
  102227. if(oy->bodybytes+oy->headerbytes>bytes)return(0);
  102228. /* The whole test page is buffered. Verify the checksum */
  102229. {
  102230. /* Grab the checksum bytes, set the header field to zero */
  102231. char chksum[4];
  102232. ogg_page log;
  102233. memcpy(chksum,page+22,4);
  102234. memset(page+22,0,4);
  102235. /* set up a temp page struct and recompute the checksum */
  102236. log.header=page;
  102237. log.header_len=oy->headerbytes;
  102238. log.body=page+oy->headerbytes;
  102239. log.body_len=oy->bodybytes;
  102240. ogg_page_checksum_set(&log);
  102241. /* Compare */
  102242. if(memcmp(chksum,page+22,4)){
  102243. /* D'oh. Mismatch! Corrupt page (or miscapture and not a page
  102244. at all) */
  102245. /* replace the computed checksum with the one actually read in */
  102246. memcpy(page+22,chksum,4);
  102247. /* Bad checksum. Lose sync */
  102248. goto sync_fail;
  102249. }
  102250. }
  102251. /* yes, have a whole page all ready to go */
  102252. {
  102253. unsigned char *page=oy->data+oy->returned;
  102254. long bytes;
  102255. if(og){
  102256. og->header=page;
  102257. og->header_len=oy->headerbytes;
  102258. og->body=page+oy->headerbytes;
  102259. og->body_len=oy->bodybytes;
  102260. }
  102261. oy->unsynced=0;
  102262. oy->returned+=(bytes=oy->headerbytes+oy->bodybytes);
  102263. oy->headerbytes=0;
  102264. oy->bodybytes=0;
  102265. return(bytes);
  102266. }
  102267. sync_fail:
  102268. oy->headerbytes=0;
  102269. oy->bodybytes=0;
  102270. /* search for possible capture */
  102271. next=(unsigned char*)memchr(page+1,'O',bytes-1);
  102272. if(!next)
  102273. next=oy->data+oy->fill;
  102274. oy->returned=next-oy->data;
  102275. return(-(next-page));
  102276. }
  102277. /* sync the stream and get a page. Keep trying until we find a page.
  102278. Supress 'sync errors' after reporting the first.
  102279. return values:
  102280. -1) recapture (hole in data)
  102281. 0) need more data
  102282. 1) page returned
  102283. Returns pointers into buffered data; invalidated by next call to
  102284. _stream, _clear, _init, or _buffer */
  102285. int ogg_sync_pageout(ogg_sync_state *oy, ogg_page *og){
  102286. /* all we need to do is verify a page at the head of the stream
  102287. buffer. If it doesn't verify, we look for the next potential
  102288. frame */
  102289. for(;;){
  102290. long ret=ogg_sync_pageseek(oy,og);
  102291. if(ret>0){
  102292. /* have a page */
  102293. return(1);
  102294. }
  102295. if(ret==0){
  102296. /* need more data */
  102297. return(0);
  102298. }
  102299. /* head did not start a synced page... skipped some bytes */
  102300. if(!oy->unsynced){
  102301. oy->unsynced=1;
  102302. return(-1);
  102303. }
  102304. /* loop. keep looking */
  102305. }
  102306. }
  102307. /* add the incoming page to the stream state; we decompose the page
  102308. into packet segments here as well. */
  102309. int ogg_stream_pagein(ogg_stream_state *os, ogg_page *og){
  102310. unsigned char *header=og->header;
  102311. unsigned char *body=og->body;
  102312. long bodysize=og->body_len;
  102313. int segptr=0;
  102314. int version=ogg_page_version(og);
  102315. int continued=ogg_page_continued(og);
  102316. int bos=ogg_page_bos(og);
  102317. int eos=ogg_page_eos(og);
  102318. ogg_int64_t granulepos=ogg_page_granulepos(og);
  102319. int serialno=ogg_page_serialno(og);
  102320. long pageno=ogg_page_pageno(og);
  102321. int segments=header[26];
  102322. /* clean up 'returned data' */
  102323. {
  102324. long lr=os->lacing_returned;
  102325. long br=os->body_returned;
  102326. /* body data */
  102327. if(br){
  102328. os->body_fill-=br;
  102329. if(os->body_fill)
  102330. memmove(os->body_data,os->body_data+br,os->body_fill);
  102331. os->body_returned=0;
  102332. }
  102333. if(lr){
  102334. /* segment table */
  102335. if(os->lacing_fill-lr){
  102336. memmove(os->lacing_vals,os->lacing_vals+lr,
  102337. (os->lacing_fill-lr)*sizeof(*os->lacing_vals));
  102338. memmove(os->granule_vals,os->granule_vals+lr,
  102339. (os->lacing_fill-lr)*sizeof(*os->granule_vals));
  102340. }
  102341. os->lacing_fill-=lr;
  102342. os->lacing_packet-=lr;
  102343. os->lacing_returned=0;
  102344. }
  102345. }
  102346. /* check the serial number */
  102347. if(serialno!=os->serialno)return(-1);
  102348. if(version>0)return(-1);
  102349. _os_lacing_expand(os,segments+1);
  102350. /* are we in sequence? */
  102351. if(pageno!=os->pageno){
  102352. int i;
  102353. /* unroll previous partial packet (if any) */
  102354. for(i=os->lacing_packet;i<os->lacing_fill;i++)
  102355. os->body_fill-=os->lacing_vals[i]&0xff;
  102356. os->lacing_fill=os->lacing_packet;
  102357. /* make a note of dropped data in segment table */
  102358. if(os->pageno!=-1){
  102359. os->lacing_vals[os->lacing_fill++]=0x400;
  102360. os->lacing_packet++;
  102361. }
  102362. }
  102363. /* are we a 'continued packet' page? If so, we may need to skip
  102364. some segments */
  102365. if(continued){
  102366. if(os->lacing_fill<1 ||
  102367. os->lacing_vals[os->lacing_fill-1]==0x400){
  102368. bos=0;
  102369. for(;segptr<segments;segptr++){
  102370. int val=header[27+segptr];
  102371. body+=val;
  102372. bodysize-=val;
  102373. if(val<255){
  102374. segptr++;
  102375. break;
  102376. }
  102377. }
  102378. }
  102379. }
  102380. if(bodysize){
  102381. _os_body_expand(os,bodysize);
  102382. memcpy(os->body_data+os->body_fill,body,bodysize);
  102383. os->body_fill+=bodysize;
  102384. }
  102385. {
  102386. int saved=-1;
  102387. while(segptr<segments){
  102388. int val=header[27+segptr];
  102389. os->lacing_vals[os->lacing_fill]=val;
  102390. os->granule_vals[os->lacing_fill]=-1;
  102391. if(bos){
  102392. os->lacing_vals[os->lacing_fill]|=0x100;
  102393. bos=0;
  102394. }
  102395. if(val<255)saved=os->lacing_fill;
  102396. os->lacing_fill++;
  102397. segptr++;
  102398. if(val<255)os->lacing_packet=os->lacing_fill;
  102399. }
  102400. /* set the granulepos on the last granuleval of the last full packet */
  102401. if(saved!=-1){
  102402. os->granule_vals[saved]=granulepos;
  102403. }
  102404. }
  102405. if(eos){
  102406. os->e_o_s=1;
  102407. if(os->lacing_fill>0)
  102408. os->lacing_vals[os->lacing_fill-1]|=0x200;
  102409. }
  102410. os->pageno=pageno+1;
  102411. return(0);
  102412. }
  102413. /* clear things to an initial state. Good to call, eg, before seeking */
  102414. int ogg_sync_reset(ogg_sync_state *oy){
  102415. oy->fill=0;
  102416. oy->returned=0;
  102417. oy->unsynced=0;
  102418. oy->headerbytes=0;
  102419. oy->bodybytes=0;
  102420. return(0);
  102421. }
  102422. int ogg_stream_reset(ogg_stream_state *os){
  102423. os->body_fill=0;
  102424. os->body_returned=0;
  102425. os->lacing_fill=0;
  102426. os->lacing_packet=0;
  102427. os->lacing_returned=0;
  102428. os->header_fill=0;
  102429. os->e_o_s=0;
  102430. os->b_o_s=0;
  102431. os->pageno=-1;
  102432. os->packetno=0;
  102433. os->granulepos=0;
  102434. return(0);
  102435. }
  102436. int ogg_stream_reset_serialno(ogg_stream_state *os,int serialno){
  102437. ogg_stream_reset(os);
  102438. os->serialno=serialno;
  102439. return(0);
  102440. }
  102441. static int _packetout(ogg_stream_state *os,ogg_packet *op,int adv){
  102442. /* The last part of decode. We have the stream broken into packet
  102443. segments. Now we need to group them into packets (or return the
  102444. out of sync markers) */
  102445. int ptr=os->lacing_returned;
  102446. if(os->lacing_packet<=ptr)return(0);
  102447. if(os->lacing_vals[ptr]&0x400){
  102448. /* we need to tell the codec there's a gap; it might need to
  102449. handle previous packet dependencies. */
  102450. os->lacing_returned++;
  102451. os->packetno++;
  102452. return(-1);
  102453. }
  102454. if(!op && !adv)return(1); /* just using peek as an inexpensive way
  102455. to ask if there's a whole packet
  102456. waiting */
  102457. /* Gather the whole packet. We'll have no holes or a partial packet */
  102458. {
  102459. int size=os->lacing_vals[ptr]&0xff;
  102460. int bytes=size;
  102461. int eos=os->lacing_vals[ptr]&0x200; /* last packet of the stream? */
  102462. int bos=os->lacing_vals[ptr]&0x100; /* first packet of the stream? */
  102463. while(size==255){
  102464. int val=os->lacing_vals[++ptr];
  102465. size=val&0xff;
  102466. if(val&0x200)eos=0x200;
  102467. bytes+=size;
  102468. }
  102469. if(op){
  102470. op->e_o_s=eos;
  102471. op->b_o_s=bos;
  102472. op->packet=os->body_data+os->body_returned;
  102473. op->packetno=os->packetno;
  102474. op->granulepos=os->granule_vals[ptr];
  102475. op->bytes=bytes;
  102476. }
  102477. if(adv){
  102478. os->body_returned+=bytes;
  102479. os->lacing_returned=ptr+1;
  102480. os->packetno++;
  102481. }
  102482. }
  102483. return(1);
  102484. }
  102485. int ogg_stream_packetout(ogg_stream_state *os,ogg_packet *op){
  102486. return _packetout(os,op,1);
  102487. }
  102488. int ogg_stream_packetpeek(ogg_stream_state *os,ogg_packet *op){
  102489. return _packetout(os,op,0);
  102490. }
  102491. void ogg_packet_clear(ogg_packet *op) {
  102492. _ogg_free(op->packet);
  102493. memset(op, 0, sizeof(*op));
  102494. }
  102495. #ifdef _V_SELFTEST
  102496. #include <stdio.h>
  102497. ogg_stream_state os_en, os_de;
  102498. ogg_sync_state oy;
  102499. void checkpacket(ogg_packet *op,int len, int no, int pos){
  102500. long j;
  102501. static int sequence=0;
  102502. static int lastno=0;
  102503. if(op->bytes!=len){
  102504. fprintf(stderr,"incorrect packet length!\n");
  102505. exit(1);
  102506. }
  102507. if(op->granulepos!=pos){
  102508. fprintf(stderr,"incorrect packet position!\n");
  102509. exit(1);
  102510. }
  102511. /* packet number just follows sequence/gap; adjust the input number
  102512. for that */
  102513. if(no==0){
  102514. sequence=0;
  102515. }else{
  102516. sequence++;
  102517. if(no>lastno+1)
  102518. sequence++;
  102519. }
  102520. lastno=no;
  102521. if(op->packetno!=sequence){
  102522. fprintf(stderr,"incorrect packet sequence %ld != %d\n",
  102523. (long)(op->packetno),sequence);
  102524. exit(1);
  102525. }
  102526. /* Test data */
  102527. for(j=0;j<op->bytes;j++)
  102528. if(op->packet[j]!=((j+no)&0xff)){
  102529. fprintf(stderr,"body data mismatch (1) at pos %ld: %x!=%lx!\n\n",
  102530. j,op->packet[j],(j+no)&0xff);
  102531. exit(1);
  102532. }
  102533. }
  102534. void check_page(unsigned char *data,const int *header,ogg_page *og){
  102535. long j;
  102536. /* Test data */
  102537. for(j=0;j<og->body_len;j++)
  102538. if(og->body[j]!=data[j]){
  102539. fprintf(stderr,"body data mismatch (2) at pos %ld: %x!=%x!\n\n",
  102540. j,data[j],og->body[j]);
  102541. exit(1);
  102542. }
  102543. /* Test header */
  102544. for(j=0;j<og->header_len;j++){
  102545. if(og->header[j]!=header[j]){
  102546. fprintf(stderr,"header content mismatch at pos %ld:\n",j);
  102547. for(j=0;j<header[26]+27;j++)
  102548. fprintf(stderr," (%ld)%02x:%02x",j,header[j],og->header[j]);
  102549. fprintf(stderr,"\n");
  102550. exit(1);
  102551. }
  102552. }
  102553. if(og->header_len!=header[26]+27){
  102554. fprintf(stderr,"header length incorrect! (%ld!=%d)\n",
  102555. og->header_len,header[26]+27);
  102556. exit(1);
  102557. }
  102558. }
  102559. void print_header(ogg_page *og){
  102560. int j;
  102561. fprintf(stderr,"\nHEADER:\n");
  102562. fprintf(stderr," capture: %c %c %c %c version: %d flags: %x\n",
  102563. og->header[0],og->header[1],og->header[2],og->header[3],
  102564. (int)og->header[4],(int)og->header[5]);
  102565. fprintf(stderr," granulepos: %d serialno: %d pageno: %ld\n",
  102566. (og->header[9]<<24)|(og->header[8]<<16)|
  102567. (og->header[7]<<8)|og->header[6],
  102568. (og->header[17]<<24)|(og->header[16]<<16)|
  102569. (og->header[15]<<8)|og->header[14],
  102570. ((long)(og->header[21])<<24)|(og->header[20]<<16)|
  102571. (og->header[19]<<8)|og->header[18]);
  102572. fprintf(stderr," checksum: %02x:%02x:%02x:%02x\n segments: %d (",
  102573. (int)og->header[22],(int)og->header[23],
  102574. (int)og->header[24],(int)og->header[25],
  102575. (int)og->header[26]);
  102576. for(j=27;j<og->header_len;j++)
  102577. fprintf(stderr,"%d ",(int)og->header[j]);
  102578. fprintf(stderr,")\n\n");
  102579. }
  102580. void copy_page(ogg_page *og){
  102581. unsigned char *temp=_ogg_malloc(og->header_len);
  102582. memcpy(temp,og->header,og->header_len);
  102583. og->header=temp;
  102584. temp=_ogg_malloc(og->body_len);
  102585. memcpy(temp,og->body,og->body_len);
  102586. og->body=temp;
  102587. }
  102588. void free_page(ogg_page *og){
  102589. _ogg_free (og->header);
  102590. _ogg_free (og->body);
  102591. }
  102592. void error(void){
  102593. fprintf(stderr,"error!\n");
  102594. exit(1);
  102595. }
  102596. /* 17 only */
  102597. const int head1_0[] = {0x4f,0x67,0x67,0x53,0,0x06,
  102598. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  102599. 0x01,0x02,0x03,0x04,0,0,0,0,
  102600. 0x15,0xed,0xec,0x91,
  102601. 1,
  102602. 17};
  102603. /* 17, 254, 255, 256, 500, 510, 600 byte, pad */
  102604. const int head1_1[] = {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. 0x59,0x10,0x6c,0x2c,
  102608. 1,
  102609. 17};
  102610. const int head2_1[] = {0x4f,0x67,0x67,0x53,0,0x04,
  102611. 0x07,0x18,0x00,0x00,0x00,0x00,0x00,0x00,
  102612. 0x01,0x02,0x03,0x04,1,0,0,0,
  102613. 0x89,0x33,0x85,0xce,
  102614. 13,
  102615. 254,255,0,255,1,255,245,255,255,0,
  102616. 255,255,90};
  102617. /* nil packets; beginning,middle,end */
  102618. const int head1_2[] = {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. 0xff,0x7b,0x23,0x17,
  102622. 1,
  102623. 0};
  102624. const int head2_2[] = {0x4f,0x67,0x67,0x53,0,0x04,
  102625. 0x07,0x28,0x00,0x00,0x00,0x00,0x00,0x00,
  102626. 0x01,0x02,0x03,0x04,1,0,0,0,
  102627. 0x5c,0x3f,0x66,0xcb,
  102628. 17,
  102629. 17,254,255,0,0,255,1,0,255,245,255,255,0,
  102630. 255,255,90,0};
  102631. /* large initial packet */
  102632. const int head1_3[] = {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. 0x01,0x27,0x31,0xaa,
  102636. 18,
  102637. 255,255,255,255,255,255,255,255,
  102638. 255,255,255,255,255,255,255,255,255,10};
  102639. const int head2_3[] = {0x4f,0x67,0x67,0x53,0,0x04,
  102640. 0x07,0x08,0x00,0x00,0x00,0x00,0x00,0x00,
  102641. 0x01,0x02,0x03,0x04,1,0,0,0,
  102642. 0x7f,0x4e,0x8a,0xd2,
  102643. 4,
  102644. 255,4,255,0};
  102645. /* continuing packet test */
  102646. const int head1_4[] = {0x4f,0x67,0x67,0x53,0,0x02,
  102647. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  102648. 0x01,0x02,0x03,0x04,0,0,0,0,
  102649. 0xff,0x7b,0x23,0x17,
  102650. 1,
  102651. 0};
  102652. const int head2_4[] = {0x4f,0x67,0x67,0x53,0,0x00,
  102653. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  102654. 0x01,0x02,0x03,0x04,1,0,0,0,
  102655. 0x54,0x05,0x51,0xc8,
  102656. 17,
  102657. 255,255,255,255,255,255,255,255,
  102658. 255,255,255,255,255,255,255,255,255};
  102659. const int head3_4[] = {0x4f,0x67,0x67,0x53,0,0x05,
  102660. 0x07,0x0c,0x00,0x00,0x00,0x00,0x00,0x00,
  102661. 0x01,0x02,0x03,0x04,2,0,0,0,
  102662. 0xc8,0xc3,0xcb,0xed,
  102663. 5,
  102664. 10,255,4,255,0};
  102665. /* page with the 255 segment limit */
  102666. const int head1_5[] = {0x4f,0x67,0x67,0x53,0,0x02,
  102667. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  102668. 0x01,0x02,0x03,0x04,0,0,0,0,
  102669. 0xff,0x7b,0x23,0x17,
  102670. 1,
  102671. 0};
  102672. const int head2_5[] = {0x4f,0x67,0x67,0x53,0,0x00,
  102673. 0x07,0xfc,0x03,0x00,0x00,0x00,0x00,0x00,
  102674. 0x01,0x02,0x03,0x04,1,0,0,0,
  102675. 0xed,0x2a,0x2e,0xa7,
  102676. 255,
  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,10,
  102695. 10,10,10,10,10,10,10,10,
  102696. 10,10,10,10,10,10,10,10,
  102697. 10,10,10,10,10,10,10,10,
  102698. 10,10,10,10,10,10,10,10,
  102699. 10,10,10,10,10,10,10,10,
  102700. 10,10,10,10,10,10,10,10,
  102701. 10,10,10,10,10,10,10,10,
  102702. 10,10,10,10,10,10,10,10,
  102703. 10,10,10,10,10,10,10,10,
  102704. 10,10,10,10,10,10,10,10,
  102705. 10,10,10,10,10,10,10,10,
  102706. 10,10,10,10,10,10,10,10,
  102707. 10,10,10,10,10,10,10,10,
  102708. 10,10,10,10,10,10,10};
  102709. const int head3_5[] = {0x4f,0x67,0x67,0x53,0,0x04,
  102710. 0x07,0x00,0x04,0x00,0x00,0x00,0x00,0x00,
  102711. 0x01,0x02,0x03,0x04,2,0,0,0,
  102712. 0x6c,0x3b,0x82,0x3d,
  102713. 1,
  102714. 50};
  102715. /* packet that overspans over an entire page */
  102716. const int head1_6[] = {0x4f,0x67,0x67,0x53,0,0x02,
  102717. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  102718. 0x01,0x02,0x03,0x04,0,0,0,0,
  102719. 0xff,0x7b,0x23,0x17,
  102720. 1,
  102721. 0};
  102722. const int head2_6[] = {0x4f,0x67,0x67,0x53,0,0x00,
  102723. 0x07,0x04,0x00,0x00,0x00,0x00,0x00,0x00,
  102724. 0x01,0x02,0x03,0x04,1,0,0,0,
  102725. 0x3c,0xd9,0x4d,0x3f,
  102726. 17,
  102727. 100,255,255,255,255,255,255,255,255,
  102728. 255,255,255,255,255,255,255,255};
  102729. const int head3_6[] = {0x4f,0x67,0x67,0x53,0,0x01,
  102730. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  102731. 0x01,0x02,0x03,0x04,2,0,0,0,
  102732. 0x01,0xd2,0xe5,0xe5,
  102733. 17,
  102734. 255,255,255,255,255,255,255,255,
  102735. 255,255,255,255,255,255,255,255,255};
  102736. const int head4_6[] = {0x4f,0x67,0x67,0x53,0,0x05,
  102737. 0x07,0x10,0x00,0x00,0x00,0x00,0x00,0x00,
  102738. 0x01,0x02,0x03,0x04,3,0,0,0,
  102739. 0xef,0xdd,0x88,0xde,
  102740. 7,
  102741. 255,255,75,255,4,255,0};
  102742. /* packet that overspans over an entire page */
  102743. const int head1_7[] = {0x4f,0x67,0x67,0x53,0,0x02,
  102744. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  102745. 0x01,0x02,0x03,0x04,0,0,0,0,
  102746. 0xff,0x7b,0x23,0x17,
  102747. 1,
  102748. 0};
  102749. const int head2_7[] = {0x4f,0x67,0x67,0x53,0,0x00,
  102750. 0x07,0x04,0x00,0x00,0x00,0x00,0x00,0x00,
  102751. 0x01,0x02,0x03,0x04,1,0,0,0,
  102752. 0x3c,0xd9,0x4d,0x3f,
  102753. 17,
  102754. 100,255,255,255,255,255,255,255,255,
  102755. 255,255,255,255,255,255,255,255};
  102756. const int head3_7[] = {0x4f,0x67,0x67,0x53,0,0x05,
  102757. 0x07,0x08,0x00,0x00,0x00,0x00,0x00,0x00,
  102758. 0x01,0x02,0x03,0x04,2,0,0,0,
  102759. 0xd4,0xe0,0x60,0xe5,
  102760. 1,0};
  102761. void test_pack(const int *pl, const int **headers, int byteskip,
  102762. int pageskip, int packetskip){
  102763. unsigned char *data=_ogg_malloc(1024*1024); /* for scripted test cases only */
  102764. long inptr=0;
  102765. long outptr=0;
  102766. long deptr=0;
  102767. long depacket=0;
  102768. long granule_pos=7,pageno=0;
  102769. int i,j,packets,pageout=pageskip;
  102770. int eosflag=0;
  102771. int bosflag=0;
  102772. int byteskipcount=0;
  102773. ogg_stream_reset(&os_en);
  102774. ogg_stream_reset(&os_de);
  102775. ogg_sync_reset(&oy);
  102776. for(packets=0;packets<packetskip;packets++)
  102777. depacket+=pl[packets];
  102778. for(packets=0;;packets++)if(pl[packets]==-1)break;
  102779. for(i=0;i<packets;i++){
  102780. /* construct a test packet */
  102781. ogg_packet op;
  102782. int len=pl[i];
  102783. op.packet=data+inptr;
  102784. op.bytes=len;
  102785. op.e_o_s=(pl[i+1]<0?1:0);
  102786. op.granulepos=granule_pos;
  102787. granule_pos+=1024;
  102788. for(j=0;j<len;j++)data[inptr++]=i+j;
  102789. /* submit the test packet */
  102790. ogg_stream_packetin(&os_en,&op);
  102791. /* retrieve any finished pages */
  102792. {
  102793. ogg_page og;
  102794. while(ogg_stream_pageout(&os_en,&og)){
  102795. /* We have a page. Check it carefully */
  102796. fprintf(stderr,"%ld, ",pageno);
  102797. if(headers[pageno]==NULL){
  102798. fprintf(stderr,"coded too many pages!\n");
  102799. exit(1);
  102800. }
  102801. check_page(data+outptr,headers[pageno],&og);
  102802. outptr+=og.body_len;
  102803. pageno++;
  102804. if(pageskip){
  102805. bosflag=1;
  102806. pageskip--;
  102807. deptr+=og.body_len;
  102808. }
  102809. /* have a complete page; submit it to sync/decode */
  102810. {
  102811. ogg_page og_de;
  102812. ogg_packet op_de,op_de2;
  102813. char *buf=ogg_sync_buffer(&oy,og.header_len+og.body_len);
  102814. char *next=buf;
  102815. byteskipcount+=og.header_len;
  102816. if(byteskipcount>byteskip){
  102817. memcpy(next,og.header,byteskipcount-byteskip);
  102818. next+=byteskipcount-byteskip;
  102819. byteskipcount=byteskip;
  102820. }
  102821. byteskipcount+=og.body_len;
  102822. if(byteskipcount>byteskip){
  102823. memcpy(next,og.body,byteskipcount-byteskip);
  102824. next+=byteskipcount-byteskip;
  102825. byteskipcount=byteskip;
  102826. }
  102827. ogg_sync_wrote(&oy,next-buf);
  102828. while(1){
  102829. int ret=ogg_sync_pageout(&oy,&og_de);
  102830. if(ret==0)break;
  102831. if(ret<0)continue;
  102832. /* got a page. Happy happy. Verify that it's good. */
  102833. fprintf(stderr,"(%ld), ",pageout);
  102834. check_page(data+deptr,headers[pageout],&og_de);
  102835. deptr+=og_de.body_len;
  102836. pageout++;
  102837. /* submit it to deconstitution */
  102838. ogg_stream_pagein(&os_de,&og_de);
  102839. /* packets out? */
  102840. while(ogg_stream_packetpeek(&os_de,&op_de2)>0){
  102841. ogg_stream_packetpeek(&os_de,NULL);
  102842. ogg_stream_packetout(&os_de,&op_de); /* just catching them all */
  102843. /* verify peek and out match */
  102844. if(memcmp(&op_de,&op_de2,sizeof(op_de))){
  102845. fprintf(stderr,"packetout != packetpeek! pos=%ld\n",
  102846. depacket);
  102847. exit(1);
  102848. }
  102849. /* verify the packet! */
  102850. /* check data */
  102851. if(memcmp(data+depacket,op_de.packet,op_de.bytes)){
  102852. fprintf(stderr,"packet data mismatch in decode! pos=%ld\n",
  102853. depacket);
  102854. exit(1);
  102855. }
  102856. /* check bos flag */
  102857. if(bosflag==0 && op_de.b_o_s==0){
  102858. fprintf(stderr,"b_o_s flag not set on packet!\n");
  102859. exit(1);
  102860. }
  102861. if(bosflag && op_de.b_o_s){
  102862. fprintf(stderr,"b_o_s flag incorrectly set on packet!\n");
  102863. exit(1);
  102864. }
  102865. bosflag=1;
  102866. depacket+=op_de.bytes;
  102867. /* check eos flag */
  102868. if(eosflag){
  102869. fprintf(stderr,"Multiple decoded packets with eos flag!\n");
  102870. exit(1);
  102871. }
  102872. if(op_de.e_o_s)eosflag=1;
  102873. /* check granulepos flag */
  102874. if(op_de.granulepos!=-1){
  102875. fprintf(stderr," granule:%ld ",(long)op_de.granulepos);
  102876. }
  102877. }
  102878. }
  102879. }
  102880. }
  102881. }
  102882. }
  102883. _ogg_free(data);
  102884. if(headers[pageno]!=NULL){
  102885. fprintf(stderr,"did not write last page!\n");
  102886. exit(1);
  102887. }
  102888. if(headers[pageout]!=NULL){
  102889. fprintf(stderr,"did not decode last page!\n");
  102890. exit(1);
  102891. }
  102892. if(inptr!=outptr){
  102893. fprintf(stderr,"encoded page data incomplete!\n");
  102894. exit(1);
  102895. }
  102896. if(inptr!=deptr){
  102897. fprintf(stderr,"decoded page data incomplete!\n");
  102898. exit(1);
  102899. }
  102900. if(inptr!=depacket){
  102901. fprintf(stderr,"decoded packet data incomplete!\n");
  102902. exit(1);
  102903. }
  102904. if(!eosflag){
  102905. fprintf(stderr,"Never got a packet with EOS set!\n");
  102906. exit(1);
  102907. }
  102908. fprintf(stderr,"ok.\n");
  102909. }
  102910. int main(void){
  102911. ogg_stream_init(&os_en,0x04030201);
  102912. ogg_stream_init(&os_de,0x04030201);
  102913. ogg_sync_init(&oy);
  102914. /* Exercise each code path in the framing code. Also verify that
  102915. the checksums are working. */
  102916. {
  102917. /* 17 only */
  102918. const int packets[]={17, -1};
  102919. const int *headret[]={head1_0,NULL};
  102920. fprintf(stderr,"testing single page encoding... ");
  102921. test_pack(packets,headret,0,0,0);
  102922. }
  102923. {
  102924. /* 17, 254, 255, 256, 500, 510, 600 byte, pad */
  102925. const int packets[]={17, 254, 255, 256, 500, 510, 600, -1};
  102926. const int *headret[]={head1_1,head2_1,NULL};
  102927. fprintf(stderr,"testing basic page encoding... ");
  102928. test_pack(packets,headret,0,0,0);
  102929. }
  102930. {
  102931. /* nil packets; beginning,middle,end */
  102932. const int packets[]={0,17, 254, 255, 0, 256, 0, 500, 510, 600, 0, -1};
  102933. const int *headret[]={head1_2,head2_2,NULL};
  102934. fprintf(stderr,"testing basic nil packets... ");
  102935. test_pack(packets,headret,0,0,0);
  102936. }
  102937. {
  102938. /* large initial packet */
  102939. const int packets[]={4345,259,255,-1};
  102940. const int *headret[]={head1_3,head2_3,NULL};
  102941. fprintf(stderr,"testing initial-packet lacing > 4k... ");
  102942. test_pack(packets,headret,0,0,0);
  102943. }
  102944. {
  102945. /* continuing packet test */
  102946. const int packets[]={0,4345,259,255,-1};
  102947. const int *headret[]={head1_4,head2_4,head3_4,NULL};
  102948. fprintf(stderr,"testing single packet page span... ");
  102949. test_pack(packets,headret,0,0,0);
  102950. }
  102951. /* page with the 255 segment limit */
  102952. {
  102953. const int packets[]={0,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,10,
  102971. 10,10,10,10,10,10,10,10,
  102972. 10,10,10,10,10,10,10,10,
  102973. 10,10,10,10,10,10,10,10,
  102974. 10,10,10,10,10,10,10,10,
  102975. 10,10,10,10,10,10,10,10,
  102976. 10,10,10,10,10,10,10,10,
  102977. 10,10,10,10,10,10,10,10,
  102978. 10,10,10,10,10,10,10,10,
  102979. 10,10,10,10,10,10,10,10,
  102980. 10,10,10,10,10,10,10,10,
  102981. 10,10,10,10,10,10,10,10,
  102982. 10,10,10,10,10,10,10,10,
  102983. 10,10,10,10,10,10,10,10,
  102984. 10,10,10,10,10,10,10,50,-1};
  102985. const int *headret[]={head1_5,head2_5,head3_5,NULL};
  102986. fprintf(stderr,"testing max packet segments... ");
  102987. test_pack(packets,headret,0,0,0);
  102988. }
  102989. {
  102990. /* packet that overspans over an entire page */
  102991. const int packets[]={0,100,9000,259,255,-1};
  102992. const int *headret[]={head1_6,head2_6,head3_6,head4_6,NULL};
  102993. fprintf(stderr,"testing very large packets... ");
  102994. test_pack(packets,headret,0,0,0);
  102995. }
  102996. {
  102997. /* test for the libogg 1.1.1 resync in large continuation bug
  102998. found by Josh Coalson) */
  102999. const int packets[]={0,100,9000,259,255,-1};
  103000. const int *headret[]={head1_6,head2_6,head3_6,head4_6,NULL};
  103001. fprintf(stderr,"testing continuation resync in very large packets... ");
  103002. test_pack(packets,headret,100,2,3);
  103003. }
  103004. {
  103005. /* term only page. why not? */
  103006. const int packets[]={0,100,4080,-1};
  103007. const int *headret[]={head1_7,head2_7,head3_7,NULL};
  103008. fprintf(stderr,"testing zero data page (1 nil packet)... ");
  103009. test_pack(packets,headret,0,0,0);
  103010. }
  103011. {
  103012. /* build a bunch of pages for testing */
  103013. unsigned char *data=_ogg_malloc(1024*1024);
  103014. int pl[]={0,100,4079,2956,2057,76,34,912,0,234,1000,1000,1000,300,-1};
  103015. int inptr=0,i,j;
  103016. ogg_page og[5];
  103017. ogg_stream_reset(&os_en);
  103018. for(i=0;pl[i]!=-1;i++){
  103019. ogg_packet op;
  103020. int len=pl[i];
  103021. op.packet=data+inptr;
  103022. op.bytes=len;
  103023. op.e_o_s=(pl[i+1]<0?1:0);
  103024. op.granulepos=(i+1)*1000;
  103025. for(j=0;j<len;j++)data[inptr++]=i+j;
  103026. ogg_stream_packetin(&os_en,&op);
  103027. }
  103028. _ogg_free(data);
  103029. /* retrieve finished pages */
  103030. for(i=0;i<5;i++){
  103031. if(ogg_stream_pageout(&os_en,&og[i])==0){
  103032. fprintf(stderr,"Too few pages output building sync tests!\n");
  103033. exit(1);
  103034. }
  103035. copy_page(&og[i]);
  103036. }
  103037. /* Test lost pages on pagein/packetout: no rollback */
  103038. {
  103039. ogg_page temp;
  103040. ogg_packet test;
  103041. fprintf(stderr,"Testing loss of pages... ");
  103042. ogg_sync_reset(&oy);
  103043. ogg_stream_reset(&os_de);
  103044. for(i=0;i<5;i++){
  103045. memcpy(ogg_sync_buffer(&oy,og[i].header_len),og[i].header,
  103046. og[i].header_len);
  103047. ogg_sync_wrote(&oy,og[i].header_len);
  103048. memcpy(ogg_sync_buffer(&oy,og[i].body_len),og[i].body,og[i].body_len);
  103049. ogg_sync_wrote(&oy,og[i].body_len);
  103050. }
  103051. ogg_sync_pageout(&oy,&temp);
  103052. ogg_stream_pagein(&os_de,&temp);
  103053. ogg_sync_pageout(&oy,&temp);
  103054. ogg_stream_pagein(&os_de,&temp);
  103055. ogg_sync_pageout(&oy,&temp);
  103056. /* skip */
  103057. ogg_sync_pageout(&oy,&temp);
  103058. ogg_stream_pagein(&os_de,&temp);
  103059. /* do we get the expected results/packets? */
  103060. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  103061. checkpacket(&test,0,0,0);
  103062. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  103063. checkpacket(&test,100,1,-1);
  103064. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  103065. checkpacket(&test,4079,2,3000);
  103066. if(ogg_stream_packetout(&os_de,&test)!=-1){
  103067. fprintf(stderr,"Error: loss of page did not return error\n");
  103068. exit(1);
  103069. }
  103070. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  103071. checkpacket(&test,76,5,-1);
  103072. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  103073. checkpacket(&test,34,6,-1);
  103074. fprintf(stderr,"ok.\n");
  103075. }
  103076. /* Test lost pages on pagein/packetout: rollback with continuation */
  103077. {
  103078. ogg_page temp;
  103079. ogg_packet test;
  103080. fprintf(stderr,"Testing loss of pages (rollback required)... ");
  103081. ogg_sync_reset(&oy);
  103082. ogg_stream_reset(&os_de);
  103083. for(i=0;i<5;i++){
  103084. memcpy(ogg_sync_buffer(&oy,og[i].header_len),og[i].header,
  103085. og[i].header_len);
  103086. ogg_sync_wrote(&oy,og[i].header_len);
  103087. memcpy(ogg_sync_buffer(&oy,og[i].body_len),og[i].body,og[i].body_len);
  103088. ogg_sync_wrote(&oy,og[i].body_len);
  103089. }
  103090. ogg_sync_pageout(&oy,&temp);
  103091. ogg_stream_pagein(&os_de,&temp);
  103092. ogg_sync_pageout(&oy,&temp);
  103093. ogg_stream_pagein(&os_de,&temp);
  103094. ogg_sync_pageout(&oy,&temp);
  103095. ogg_stream_pagein(&os_de,&temp);
  103096. ogg_sync_pageout(&oy,&temp);
  103097. /* skip */
  103098. ogg_sync_pageout(&oy,&temp);
  103099. ogg_stream_pagein(&os_de,&temp);
  103100. /* do we get the expected results/packets? */
  103101. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  103102. checkpacket(&test,0,0,0);
  103103. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  103104. checkpacket(&test,100,1,-1);
  103105. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  103106. checkpacket(&test,4079,2,3000);
  103107. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  103108. checkpacket(&test,2956,3,4000);
  103109. if(ogg_stream_packetout(&os_de,&test)!=-1){
  103110. fprintf(stderr,"Error: loss of page did not return error\n");
  103111. exit(1);
  103112. }
  103113. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  103114. checkpacket(&test,300,13,14000);
  103115. fprintf(stderr,"ok.\n");
  103116. }
  103117. /* the rest only test sync */
  103118. {
  103119. ogg_page og_de;
  103120. /* Test fractional page inputs: incomplete capture */
  103121. fprintf(stderr,"Testing sync on partial inputs... ");
  103122. ogg_sync_reset(&oy);
  103123. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  103124. 3);
  103125. ogg_sync_wrote(&oy,3);
  103126. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  103127. /* Test fractional page inputs: incomplete fixed header */
  103128. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+3,
  103129. 20);
  103130. ogg_sync_wrote(&oy,20);
  103131. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  103132. /* Test fractional page inputs: incomplete header */
  103133. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+23,
  103134. 5);
  103135. ogg_sync_wrote(&oy,5);
  103136. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  103137. /* Test fractional page inputs: incomplete body */
  103138. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+28,
  103139. og[1].header_len-28);
  103140. ogg_sync_wrote(&oy,og[1].header_len-28);
  103141. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  103142. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,1000);
  103143. ogg_sync_wrote(&oy,1000);
  103144. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  103145. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body+1000,
  103146. og[1].body_len-1000);
  103147. ogg_sync_wrote(&oy,og[1].body_len-1000);
  103148. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  103149. fprintf(stderr,"ok.\n");
  103150. }
  103151. /* Test fractional page inputs: page + incomplete capture */
  103152. {
  103153. ogg_page og_de;
  103154. fprintf(stderr,"Testing sync on 1+partial inputs... ");
  103155. ogg_sync_reset(&oy);
  103156. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  103157. og[1].header_len);
  103158. ogg_sync_wrote(&oy,og[1].header_len);
  103159. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  103160. og[1].body_len);
  103161. ogg_sync_wrote(&oy,og[1].body_len);
  103162. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  103163. 20);
  103164. ogg_sync_wrote(&oy,20);
  103165. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  103166. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  103167. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+20,
  103168. og[1].header_len-20);
  103169. ogg_sync_wrote(&oy,og[1].header_len-20);
  103170. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  103171. og[1].body_len);
  103172. ogg_sync_wrote(&oy,og[1].body_len);
  103173. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  103174. fprintf(stderr,"ok.\n");
  103175. }
  103176. /* Test recapture: garbage + page */
  103177. {
  103178. ogg_page og_de;
  103179. fprintf(stderr,"Testing search for capture... ");
  103180. ogg_sync_reset(&oy);
  103181. /* 'garbage' */
  103182. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  103183. og[1].body_len);
  103184. ogg_sync_wrote(&oy,og[1].body_len);
  103185. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  103186. og[1].header_len);
  103187. ogg_sync_wrote(&oy,og[1].header_len);
  103188. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  103189. og[1].body_len);
  103190. ogg_sync_wrote(&oy,og[1].body_len);
  103191. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  103192. 20);
  103193. ogg_sync_wrote(&oy,20);
  103194. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  103195. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  103196. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  103197. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header+20,
  103198. og[2].header_len-20);
  103199. ogg_sync_wrote(&oy,og[2].header_len-20);
  103200. memcpy(ogg_sync_buffer(&oy,og[2].body_len),og[2].body,
  103201. og[2].body_len);
  103202. ogg_sync_wrote(&oy,og[2].body_len);
  103203. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  103204. fprintf(stderr,"ok.\n");
  103205. }
  103206. /* Test recapture: page + garbage + page */
  103207. {
  103208. ogg_page og_de;
  103209. fprintf(stderr,"Testing recapture... ");
  103210. ogg_sync_reset(&oy);
  103211. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  103212. og[1].header_len);
  103213. ogg_sync_wrote(&oy,og[1].header_len);
  103214. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  103215. og[1].body_len);
  103216. ogg_sync_wrote(&oy,og[1].body_len);
  103217. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  103218. og[2].header_len);
  103219. ogg_sync_wrote(&oy,og[2].header_len);
  103220. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  103221. og[2].header_len);
  103222. ogg_sync_wrote(&oy,og[2].header_len);
  103223. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  103224. memcpy(ogg_sync_buffer(&oy,og[2].body_len),og[2].body,
  103225. og[2].body_len-5);
  103226. ogg_sync_wrote(&oy,og[2].body_len-5);
  103227. memcpy(ogg_sync_buffer(&oy,og[3].header_len),og[3].header,
  103228. og[3].header_len);
  103229. ogg_sync_wrote(&oy,og[3].header_len);
  103230. memcpy(ogg_sync_buffer(&oy,og[3].body_len),og[3].body,
  103231. og[3].body_len);
  103232. ogg_sync_wrote(&oy,og[3].body_len);
  103233. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  103234. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  103235. fprintf(stderr,"ok.\n");
  103236. }
  103237. /* Free page data that was previously copied */
  103238. {
  103239. for(i=0;i<5;i++){
  103240. free_page(&og[i]);
  103241. }
  103242. }
  103243. }
  103244. return(0);
  103245. }
  103246. #endif
  103247. #endif
  103248. /********* End of inlined file: framing.c *********/
  103249. /********* Start of inlined file: analysis.c *********/
  103250. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  103251. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  103252. // tasks..
  103253. #ifdef _MSC_VER
  103254. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  103255. #endif
  103256. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  103257. #if JUCE_USE_OGGVORBIS
  103258. #include <stdio.h>
  103259. #include <string.h>
  103260. #include <math.h>
  103261. /********* Start of inlined file: codec_internal.h *********/
  103262. #ifndef _V_CODECI_H_
  103263. #define _V_CODECI_H_
  103264. /********* Start of inlined file: envelope.h *********/
  103265. #ifndef _V_ENVELOPE_
  103266. #define _V_ENVELOPE_
  103267. /********* Start of inlined file: mdct.h *********/
  103268. #ifndef _OGG_mdct_H_
  103269. #define _OGG_mdct_H_
  103270. /*#define MDCT_INTEGERIZED <- be warned there could be some hurt left here*/
  103271. #ifdef MDCT_INTEGERIZED
  103272. #define DATA_TYPE int
  103273. #define REG_TYPE register int
  103274. #define TRIGBITS 14
  103275. #define cPI3_8 6270
  103276. #define cPI2_8 11585
  103277. #define cPI1_8 15137
  103278. #define FLOAT_CONV(x) ((int)((x)*(1<<TRIGBITS)+.5))
  103279. #define MULT_NORM(x) ((x)>>TRIGBITS)
  103280. #define HALVE(x) ((x)>>1)
  103281. #else
  103282. #define DATA_TYPE float
  103283. #define REG_TYPE float
  103284. #define cPI3_8 .38268343236508977175F
  103285. #define cPI2_8 .70710678118654752441F
  103286. #define cPI1_8 .92387953251128675613F
  103287. #define FLOAT_CONV(x) (x)
  103288. #define MULT_NORM(x) (x)
  103289. #define HALVE(x) ((x)*.5f)
  103290. #endif
  103291. typedef struct {
  103292. int n;
  103293. int log2n;
  103294. DATA_TYPE *trig;
  103295. int *bitrev;
  103296. DATA_TYPE scale;
  103297. } mdct_lookup;
  103298. extern void mdct_init(mdct_lookup *lookup,int n);
  103299. extern void mdct_clear(mdct_lookup *l);
  103300. extern void mdct_forward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out);
  103301. extern void mdct_backward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out);
  103302. #endif
  103303. /********* End of inlined file: mdct.h *********/
  103304. #define VE_PRE 16
  103305. #define VE_WIN 4
  103306. #define VE_POST 2
  103307. #define VE_AMP (VE_PRE+VE_POST-1)
  103308. #define VE_BANDS 7
  103309. #define VE_NEARDC 15
  103310. #define VE_MINSTRETCH 2 /* a bit less than short block */
  103311. #define VE_MAXSTRETCH 12 /* one-third full block */
  103312. typedef struct {
  103313. float ampbuf[VE_AMP];
  103314. int ampptr;
  103315. float nearDC[VE_NEARDC];
  103316. float nearDC_acc;
  103317. float nearDC_partialacc;
  103318. int nearptr;
  103319. } envelope_filter_state;
  103320. typedef struct {
  103321. int begin;
  103322. int end;
  103323. float *window;
  103324. float total;
  103325. } envelope_band;
  103326. typedef struct {
  103327. int ch;
  103328. int winlength;
  103329. int searchstep;
  103330. float minenergy;
  103331. mdct_lookup mdct;
  103332. float *mdct_win;
  103333. envelope_band band[VE_BANDS];
  103334. envelope_filter_state *filter;
  103335. int stretch;
  103336. int *mark;
  103337. long storage;
  103338. long current;
  103339. long curmark;
  103340. long cursor;
  103341. } envelope_lookup;
  103342. extern void _ve_envelope_init(envelope_lookup *e,vorbis_info *vi);
  103343. extern void _ve_envelope_clear(envelope_lookup *e);
  103344. extern long _ve_envelope_search(vorbis_dsp_state *v);
  103345. extern void _ve_envelope_shift(envelope_lookup *e,long shift);
  103346. extern int _ve_envelope_mark(vorbis_dsp_state *v);
  103347. #endif
  103348. /********* End of inlined file: envelope.h *********/
  103349. /********* Start of inlined file: codebook.h *********/
  103350. #ifndef _V_CODEBOOK_H_
  103351. #define _V_CODEBOOK_H_
  103352. /* This structure encapsulates huffman and VQ style encoding books; it
  103353. doesn't do anything specific to either.
  103354. valuelist/quantlist are nonNULL (and q_* significant) only if
  103355. there's entry->value mapping to be done.
  103356. If encode-side mapping must be done (and thus the entry needs to be
  103357. hunted), the auxiliary encode pointer will point to a decision
  103358. tree. This is true of both VQ and huffman, but is mostly useful
  103359. with VQ.
  103360. */
  103361. typedef struct static_codebook{
  103362. long dim; /* codebook dimensions (elements per vector) */
  103363. long entries; /* codebook entries */
  103364. long *lengthlist; /* codeword lengths in bits */
  103365. /* mapping ***************************************************************/
  103366. int maptype; /* 0=none
  103367. 1=implicitly populated values from map column
  103368. 2=listed arbitrary values */
  103369. /* The below does a linear, single monotonic sequence mapping. */
  103370. long q_min; /* packed 32 bit float; quant value 0 maps to minval */
  103371. long q_delta; /* packed 32 bit float; val 1 - val 0 == delta */
  103372. int q_quant; /* bits: 0 < quant <= 16 */
  103373. int q_sequencep; /* bitflag */
  103374. long *quantlist; /* map == 1: (int)(entries^(1/dim)) element column map
  103375. map == 2: list of dim*entries quantized entry vals
  103376. */
  103377. /* encode helpers ********************************************************/
  103378. struct encode_aux_nearestmatch *nearest_tree;
  103379. struct encode_aux_threshmatch *thresh_tree;
  103380. struct encode_aux_pigeonhole *pigeon_tree;
  103381. int allocedp;
  103382. } static_codebook;
  103383. /* this structures an arbitrary trained book to quickly find the
  103384. nearest cell match */
  103385. typedef struct encode_aux_nearestmatch{
  103386. /* pre-calculated partitioning tree */
  103387. long *ptr0;
  103388. long *ptr1;
  103389. long *p; /* decision points (each is an entry) */
  103390. long *q; /* decision points (each is an entry) */
  103391. long aux; /* number of tree entries */
  103392. long alloc;
  103393. } encode_aux_nearestmatch;
  103394. /* assumes a maptype of 1; encode side only, so that's OK */
  103395. typedef struct encode_aux_threshmatch{
  103396. float *quantthresh;
  103397. long *quantmap;
  103398. int quantvals;
  103399. int threshvals;
  103400. } encode_aux_threshmatch;
  103401. typedef struct encode_aux_pigeonhole{
  103402. float min;
  103403. float del;
  103404. int mapentries;
  103405. int quantvals;
  103406. long *pigeonmap;
  103407. long fittotal;
  103408. long *fitlist;
  103409. long *fitmap;
  103410. long *fitlength;
  103411. } encode_aux_pigeonhole;
  103412. typedef struct codebook{
  103413. long dim; /* codebook dimensions (elements per vector) */
  103414. long entries; /* codebook entries */
  103415. long used_entries; /* populated codebook entries */
  103416. const static_codebook *c;
  103417. /* for encode, the below are entry-ordered, fully populated */
  103418. /* for decode, the below are ordered by bitreversed codeword and only
  103419. used entries are populated */
  103420. float *valuelist; /* list of dim*entries actual entry values */
  103421. ogg_uint32_t *codelist; /* list of bitstream codewords for each entry */
  103422. int *dec_index; /* only used if sparseness collapsed */
  103423. char *dec_codelengths;
  103424. ogg_uint32_t *dec_firsttable;
  103425. int dec_firsttablen;
  103426. int dec_maxlength;
  103427. } codebook;
  103428. extern void vorbis_staticbook_clear(static_codebook *b);
  103429. extern void vorbis_staticbook_destroy(static_codebook *b);
  103430. extern int vorbis_book_init_encode(codebook *dest,const static_codebook *source);
  103431. extern int vorbis_book_init_decode(codebook *dest,const static_codebook *source);
  103432. extern void vorbis_book_clear(codebook *b);
  103433. extern float *_book_unquantize(const static_codebook *b,int n,int *map);
  103434. extern float *_book_logdist(const static_codebook *b,float *vals);
  103435. extern float _float32_unpack(long val);
  103436. extern long _float32_pack(float val);
  103437. extern int _best(codebook *book, float *a, int step);
  103438. extern int _ilog(unsigned int v);
  103439. extern long _book_maptype1_quantvals(const static_codebook *b);
  103440. extern int vorbis_book_besterror(codebook *book,float *a,int step,int addmul);
  103441. extern long vorbis_book_codeword(codebook *book,int entry);
  103442. extern long vorbis_book_codelen(codebook *book,int entry);
  103443. extern int vorbis_staticbook_pack(const static_codebook *c,oggpack_buffer *b);
  103444. extern int vorbis_staticbook_unpack(oggpack_buffer *b,static_codebook *c);
  103445. extern int vorbis_book_encode(codebook *book, int a, oggpack_buffer *b);
  103446. extern int vorbis_book_errorv(codebook *book, float *a);
  103447. extern int vorbis_book_encodev(codebook *book, int best,float *a,
  103448. oggpack_buffer *b);
  103449. extern long vorbis_book_decode(codebook *book, oggpack_buffer *b);
  103450. extern long vorbis_book_decodevs_add(codebook *book, float *a,
  103451. oggpack_buffer *b,int n);
  103452. extern long vorbis_book_decodev_set(codebook *book, float *a,
  103453. oggpack_buffer *b,int n);
  103454. extern long vorbis_book_decodev_add(codebook *book, float *a,
  103455. oggpack_buffer *b,int n);
  103456. extern long vorbis_book_decodevv_add(codebook *book, float **a,
  103457. long off,int ch,
  103458. oggpack_buffer *b,int n);
  103459. #endif
  103460. /********* End of inlined file: codebook.h *********/
  103461. #define BLOCKTYPE_IMPULSE 0
  103462. #define BLOCKTYPE_PADDING 1
  103463. #define BLOCKTYPE_TRANSITION 0
  103464. #define BLOCKTYPE_LONG 1
  103465. #define PACKETBLOBS 15
  103466. typedef struct vorbis_block_internal{
  103467. float **pcmdelay; /* this is a pointer into local storage */
  103468. float ampmax;
  103469. int blocktype;
  103470. oggpack_buffer *packetblob[PACKETBLOBS]; /* initialized, must be freed;
  103471. blob [PACKETBLOBS/2] points to
  103472. the oggpack_buffer in the
  103473. main vorbis_block */
  103474. } vorbis_block_internal;
  103475. typedef void vorbis_look_floor;
  103476. typedef void vorbis_look_residue;
  103477. typedef void vorbis_look_transform;
  103478. /* mode ************************************************************/
  103479. typedef struct {
  103480. int blockflag;
  103481. int windowtype;
  103482. int transformtype;
  103483. int mapping;
  103484. } vorbis_info_mode;
  103485. typedef void vorbis_info_floor;
  103486. typedef void vorbis_info_residue;
  103487. typedef void vorbis_info_mapping;
  103488. /********* Start of inlined file: psy.h *********/
  103489. #ifndef _V_PSY_H_
  103490. #define _V_PSY_H_
  103491. /********* Start of inlined file: smallft.h *********/
  103492. #ifndef _V_SMFT_H_
  103493. #define _V_SMFT_H_
  103494. typedef struct {
  103495. int n;
  103496. float *trigcache;
  103497. int *splitcache;
  103498. } drft_lookup;
  103499. extern void drft_forward(drft_lookup *l,float *data);
  103500. extern void drft_backward(drft_lookup *l,float *data);
  103501. extern void drft_init(drft_lookup *l,int n);
  103502. extern void drft_clear(drft_lookup *l);
  103503. #endif
  103504. /********* End of inlined file: smallft.h *********/
  103505. /********* Start of inlined file: backends.h *********/
  103506. /* this is exposed up here because we need it for static modes.
  103507. Lookups for each backend aren't exposed because there's no reason
  103508. to do so */
  103509. #ifndef _vorbis_backend_h_
  103510. #define _vorbis_backend_h_
  103511. /* this would all be simpler/shorter with templates, but.... */
  103512. /* Floor backend generic *****************************************/
  103513. typedef struct{
  103514. void (*pack) (vorbis_info_floor *,oggpack_buffer *);
  103515. vorbis_info_floor *(*unpack)(vorbis_info *,oggpack_buffer *);
  103516. vorbis_look_floor *(*look) (vorbis_dsp_state *,vorbis_info_floor *);
  103517. void (*free_info) (vorbis_info_floor *);
  103518. void (*free_look) (vorbis_look_floor *);
  103519. void *(*inverse1) (struct vorbis_block *,vorbis_look_floor *);
  103520. int (*inverse2) (struct vorbis_block *,vorbis_look_floor *,
  103521. void *buffer,float *);
  103522. } vorbis_func_floor;
  103523. typedef struct{
  103524. int order;
  103525. long rate;
  103526. long barkmap;
  103527. int ampbits;
  103528. int ampdB;
  103529. int numbooks; /* <= 16 */
  103530. int books[16];
  103531. float lessthan; /* encode-only config setting hacks for libvorbis */
  103532. float greaterthan; /* encode-only config setting hacks for libvorbis */
  103533. } vorbis_info_floor0;
  103534. #define VIF_POSIT 63
  103535. #define VIF_CLASS 16
  103536. #define VIF_PARTS 31
  103537. typedef struct{
  103538. int partitions; /* 0 to 31 */
  103539. int partitionclass[VIF_PARTS]; /* 0 to 15 */
  103540. int class_dim[VIF_CLASS]; /* 1 to 8 */
  103541. int class_subs[VIF_CLASS]; /* 0,1,2,3 (bits: 1<<n poss) */
  103542. int class_book[VIF_CLASS]; /* subs ^ dim entries */
  103543. int class_subbook[VIF_CLASS][8]; /* [VIF_CLASS][subs] */
  103544. int mult; /* 1 2 3 or 4 */
  103545. int postlist[VIF_POSIT+2]; /* first two implicit */
  103546. /* encode side analysis parameters */
  103547. float maxover;
  103548. float maxunder;
  103549. float maxerr;
  103550. float twofitweight;
  103551. float twofitatten;
  103552. int n;
  103553. } vorbis_info_floor1;
  103554. /* Residue backend generic *****************************************/
  103555. typedef struct{
  103556. void (*pack) (vorbis_info_residue *,oggpack_buffer *);
  103557. vorbis_info_residue *(*unpack)(vorbis_info *,oggpack_buffer *);
  103558. vorbis_look_residue *(*look) (vorbis_dsp_state *,
  103559. vorbis_info_residue *);
  103560. void (*free_info) (vorbis_info_residue *);
  103561. void (*free_look) (vorbis_look_residue *);
  103562. long **(*classx) (struct vorbis_block *,vorbis_look_residue *,
  103563. float **,int *,int);
  103564. int (*forward) (oggpack_buffer *,struct vorbis_block *,
  103565. vorbis_look_residue *,
  103566. float **,float **,int *,int,long **);
  103567. int (*inverse) (struct vorbis_block *,vorbis_look_residue *,
  103568. float **,int *,int);
  103569. } vorbis_func_residue;
  103570. typedef struct vorbis_info_residue0{
  103571. /* block-partitioned VQ coded straight residue */
  103572. long begin;
  103573. long end;
  103574. /* first stage (lossless partitioning) */
  103575. int grouping; /* group n vectors per partition */
  103576. int partitions; /* possible codebooks for a partition */
  103577. int groupbook; /* huffbook for partitioning */
  103578. int secondstages[64]; /* expanded out to pointers in lookup */
  103579. int booklist[256]; /* list of second stage books */
  103580. float classmetric1[64];
  103581. float classmetric2[64];
  103582. } vorbis_info_residue0;
  103583. /* Mapping backend generic *****************************************/
  103584. typedef struct{
  103585. void (*pack) (vorbis_info *,vorbis_info_mapping *,
  103586. oggpack_buffer *);
  103587. vorbis_info_mapping *(*unpack)(vorbis_info *,oggpack_buffer *);
  103588. void (*free_info) (vorbis_info_mapping *);
  103589. int (*forward) (struct vorbis_block *vb);
  103590. int (*inverse) (struct vorbis_block *vb,vorbis_info_mapping *);
  103591. } vorbis_func_mapping;
  103592. typedef struct vorbis_info_mapping0{
  103593. int submaps; /* <= 16 */
  103594. int chmuxlist[256]; /* up to 256 channels in a Vorbis stream */
  103595. int floorsubmap[16]; /* [mux] submap to floors */
  103596. int residuesubmap[16]; /* [mux] submap to residue */
  103597. int coupling_steps;
  103598. int coupling_mag[256];
  103599. int coupling_ang[256];
  103600. } vorbis_info_mapping0;
  103601. #endif
  103602. /********* End of inlined file: backends.h *********/
  103603. #ifndef EHMER_MAX
  103604. #define EHMER_MAX 56
  103605. #endif
  103606. /* psychoacoustic setup ********************************************/
  103607. #define P_BANDS 17 /* 62Hz to 16kHz */
  103608. #define P_LEVELS 8 /* 30dB to 100dB */
  103609. #define P_LEVEL_0 30. /* 30 dB */
  103610. #define P_NOISECURVES 3
  103611. #define NOISE_COMPAND_LEVELS 40
  103612. typedef struct vorbis_info_psy{
  103613. int blockflag;
  103614. float ath_adjatt;
  103615. float ath_maxatt;
  103616. float tone_masteratt[P_NOISECURVES];
  103617. float tone_centerboost;
  103618. float tone_decay;
  103619. float tone_abs_limit;
  103620. float toneatt[P_BANDS];
  103621. int noisemaskp;
  103622. float noisemaxsupp;
  103623. float noisewindowlo;
  103624. float noisewindowhi;
  103625. int noisewindowlomin;
  103626. int noisewindowhimin;
  103627. int noisewindowfixed;
  103628. float noiseoff[P_NOISECURVES][P_BANDS];
  103629. float noisecompand[NOISE_COMPAND_LEVELS];
  103630. float max_curve_dB;
  103631. int normal_channel_p;
  103632. int normal_point_p;
  103633. int normal_start;
  103634. int normal_partition;
  103635. double normal_thresh;
  103636. } vorbis_info_psy;
  103637. typedef struct{
  103638. int eighth_octave_lines;
  103639. /* for block long/short tuning; encode only */
  103640. float preecho_thresh[VE_BANDS];
  103641. float postecho_thresh[VE_BANDS];
  103642. float stretch_penalty;
  103643. float preecho_minenergy;
  103644. float ampmax_att_per_sec;
  103645. /* channel coupling config */
  103646. int coupling_pkHz[PACKETBLOBS];
  103647. int coupling_pointlimit[2][PACKETBLOBS];
  103648. int coupling_prepointamp[PACKETBLOBS];
  103649. int coupling_postpointamp[PACKETBLOBS];
  103650. int sliding_lowpass[2][PACKETBLOBS];
  103651. } vorbis_info_psy_global;
  103652. typedef struct {
  103653. float ampmax;
  103654. int channels;
  103655. vorbis_info_psy_global *gi;
  103656. int coupling_pointlimit[2][P_NOISECURVES];
  103657. } vorbis_look_psy_global;
  103658. typedef struct {
  103659. int n;
  103660. struct vorbis_info_psy *vi;
  103661. float ***tonecurves;
  103662. float **noiseoffset;
  103663. float *ath;
  103664. long *octave; /* in n.ocshift format */
  103665. long *bark;
  103666. long firstoc;
  103667. long shiftoc;
  103668. int eighth_octave_lines; /* power of two, please */
  103669. int total_octave_lines;
  103670. long rate; /* cache it */
  103671. float m_val; /* Masking compensation value */
  103672. } vorbis_look_psy;
  103673. extern void _vp_psy_init(vorbis_look_psy *p,vorbis_info_psy *vi,
  103674. vorbis_info_psy_global *gi,int n,long rate);
  103675. extern void _vp_psy_clear(vorbis_look_psy *p);
  103676. extern void *_vi_psy_dup(void *source);
  103677. extern void _vi_psy_free(vorbis_info_psy *i);
  103678. extern vorbis_info_psy *_vi_psy_copy(vorbis_info_psy *i);
  103679. extern void _vp_remove_floor(vorbis_look_psy *p,
  103680. float *mdct,
  103681. int *icodedflr,
  103682. float *residue,
  103683. int sliding_lowpass);
  103684. extern void _vp_noisemask(vorbis_look_psy *p,
  103685. float *logmdct,
  103686. float *logmask);
  103687. extern void _vp_tonemask(vorbis_look_psy *p,
  103688. float *logfft,
  103689. float *logmask,
  103690. float global_specmax,
  103691. float local_specmax);
  103692. extern void _vp_offset_and_mix(vorbis_look_psy *p,
  103693. float *noise,
  103694. float *tone,
  103695. int offset_select,
  103696. float *logmask,
  103697. float *mdct,
  103698. float *logmdct);
  103699. extern float _vp_ampmax_decay(float amp,vorbis_dsp_state *vd);
  103700. extern float **_vp_quantize_couple_memo(vorbis_block *vb,
  103701. vorbis_info_psy_global *g,
  103702. vorbis_look_psy *p,
  103703. vorbis_info_mapping0 *vi,
  103704. float **mdct);
  103705. extern void _vp_couple(int blobno,
  103706. vorbis_info_psy_global *g,
  103707. vorbis_look_psy *p,
  103708. vorbis_info_mapping0 *vi,
  103709. float **res,
  103710. float **mag_memo,
  103711. int **mag_sort,
  103712. int **ifloor,
  103713. int *nonzero,
  103714. int sliding_lowpass);
  103715. extern void _vp_noise_normalize(vorbis_look_psy *p,
  103716. float *in,float *out,int *sortedindex);
  103717. extern void _vp_noise_normalize_sort(vorbis_look_psy *p,
  103718. float *magnitudes,int *sortedindex);
  103719. extern int **_vp_quantize_couple_sort(vorbis_block *vb,
  103720. vorbis_look_psy *p,
  103721. vorbis_info_mapping0 *vi,
  103722. float **mags);
  103723. extern void hf_reduction(vorbis_info_psy_global *g,
  103724. vorbis_look_psy *p,
  103725. vorbis_info_mapping0 *vi,
  103726. float **mdct);
  103727. #endif
  103728. /********* End of inlined file: psy.h *********/
  103729. /********* Start of inlined file: bitrate.h *********/
  103730. #ifndef _V_BITRATE_H_
  103731. #define _V_BITRATE_H_
  103732. /********* Start of inlined file: os.h *********/
  103733. #ifndef _OS_H
  103734. #define _OS_H
  103735. /********************************************************************
  103736. * *
  103737. * THIS FILE IS PART OF THE OggVorbis SOFTWARE CODEC SOURCE CODE. *
  103738. * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS *
  103739. * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE *
  103740. * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. *
  103741. * *
  103742. * THE OggVorbis SOURCE CODE IS (C) COPYRIGHT 1994-2002 *
  103743. * by the XIPHOPHORUS Company http://www.xiph.org/ *
  103744. * *
  103745. ********************************************************************
  103746. function: #ifdef jail to whip a few platforms into the UNIX ideal.
  103747. last mod: $Id: os.h,v 1.1 2007/06/07 17:49:18 jules_rms Exp $
  103748. ********************************************************************/
  103749. #ifdef HAVE_CONFIG_H
  103750. #include "config.h"
  103751. #endif
  103752. #include <math.h>
  103753. /********* Start of inlined file: misc.h *********/
  103754. #ifndef _V_RANDOM_H_
  103755. #define _V_RANDOM_H_
  103756. extern int analysis_noisy;
  103757. extern void *_vorbis_block_alloc(vorbis_block *vb,long bytes);
  103758. extern void _vorbis_block_ripcord(vorbis_block *vb);
  103759. extern void _analysis_output(char *base,int i,float *v,int n,int bark,int dB,
  103760. ogg_int64_t off);
  103761. #ifdef DEBUG_MALLOC
  103762. #define _VDBG_GRAPHFILE "malloc.m"
  103763. extern void *_VDBG_malloc(void *ptr,long bytes,char *file,long line);
  103764. extern void _VDBG_free(void *ptr,char *file,long line);
  103765. #ifndef MISC_C
  103766. #undef _ogg_malloc
  103767. #undef _ogg_calloc
  103768. #undef _ogg_realloc
  103769. #undef _ogg_free
  103770. #define _ogg_malloc(x) _VDBG_malloc(NULL,(x),__FILE__,__LINE__)
  103771. #define _ogg_calloc(x,y) _VDBG_malloc(NULL,(x)*(y),__FILE__,__LINE__)
  103772. #define _ogg_realloc(x,y) _VDBG_malloc((x),(y),__FILE__,__LINE__)
  103773. #define _ogg_free(x) _VDBG_free((x),__FILE__,__LINE__)
  103774. #endif
  103775. #endif
  103776. #endif
  103777. /********* End of inlined file: misc.h *********/
  103778. #ifndef _V_IFDEFJAIL_H_
  103779. # define _V_IFDEFJAIL_H_
  103780. # ifdef __GNUC__
  103781. # define STIN static __inline__
  103782. # elif _WIN32
  103783. # define STIN static __inline
  103784. # else
  103785. # define STIN static
  103786. # endif
  103787. #ifdef DJGPP
  103788. # define rint(x) (floor((x)+0.5f))
  103789. #endif
  103790. #ifndef M_PI
  103791. # define M_PI (3.1415926536f)
  103792. #endif
  103793. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  103794. # include <malloc.h>
  103795. # define rint(x) (floor((x)+0.5f))
  103796. # define NO_FLOAT_MATH_LIB
  103797. # define FAST_HYPOT(a, b) sqrt((a)*(a) + (b)*(b))
  103798. #endif
  103799. #if defined(__SYMBIAN32__) && defined(__WINS__)
  103800. void *_alloca(size_t size);
  103801. # define alloca _alloca
  103802. #endif
  103803. #ifndef FAST_HYPOT
  103804. # define FAST_HYPOT hypot
  103805. #endif
  103806. #endif
  103807. #ifdef HAVE_ALLOCA_H
  103808. # include <alloca.h>
  103809. #endif
  103810. #ifdef USE_MEMORY_H
  103811. # include <memory.h>
  103812. #endif
  103813. #ifndef min
  103814. # define min(x,y) ((x)>(y)?(y):(x))
  103815. #endif
  103816. #ifndef max
  103817. # define max(x,y) ((x)<(y)?(y):(x))
  103818. #endif
  103819. #if defined(__i386__) && defined(__GNUC__) && !defined(__BEOS__)
  103820. # define VORBIS_FPU_CONTROL
  103821. /* both GCC and MSVC are kinda stupid about rounding/casting to int.
  103822. Because of encapsulation constraints (GCC can't see inside the asm
  103823. block and so we end up doing stupid things like a store/load that
  103824. is collectively a noop), we do it this way */
  103825. /* we must set up the fpu before this works!! */
  103826. typedef ogg_int16_t vorbis_fpu_control;
  103827. static inline void vorbis_fpu_setround(vorbis_fpu_control *fpu){
  103828. ogg_int16_t ret;
  103829. ogg_int16_t temp;
  103830. __asm__ __volatile__("fnstcw %0\n\t"
  103831. "movw %0,%%dx\n\t"
  103832. "orw $62463,%%dx\n\t"
  103833. "movw %%dx,%1\n\t"
  103834. "fldcw %1\n\t":"=m"(ret):"m"(temp): "dx");
  103835. *fpu=ret;
  103836. }
  103837. static inline void vorbis_fpu_restore(vorbis_fpu_control fpu){
  103838. __asm__ __volatile__("fldcw %0":: "m"(fpu));
  103839. }
  103840. /* assumes the FPU is in round mode! */
  103841. static inline int vorbis_ftoi(double f){ /* yes, double! Otherwise,
  103842. we get extra fst/fld to
  103843. truncate precision */
  103844. int i;
  103845. __asm__("fistl %0": "=m"(i) : "t"(f));
  103846. return(i);
  103847. }
  103848. #endif
  103849. #if defined(_WIN32) && defined(_X86_) && !defined(__GNUC__) && !defined(__BORLANDC__)
  103850. # define VORBIS_FPU_CONTROL
  103851. typedef ogg_int16_t vorbis_fpu_control;
  103852. static __inline int vorbis_ftoi(double f){
  103853. int i;
  103854. __asm{
  103855. fld f
  103856. fistp i
  103857. }
  103858. return i;
  103859. }
  103860. static __inline void vorbis_fpu_setround(vorbis_fpu_control *fpu){
  103861. }
  103862. static __inline void vorbis_fpu_restore(vorbis_fpu_control fpu){
  103863. }
  103864. #endif
  103865. #ifndef VORBIS_FPU_CONTROL
  103866. typedef int vorbis_fpu_control;
  103867. static int vorbis_ftoi(double f){
  103868. return (int)(f+.5);
  103869. }
  103870. /* We don't have special code for this compiler/arch, so do it the slow way */
  103871. # define vorbis_fpu_setround(vorbis_fpu_control) {}
  103872. # define vorbis_fpu_restore(vorbis_fpu_control) {}
  103873. #endif
  103874. #endif /* _OS_H */
  103875. /********* End of inlined file: os.h *********/
  103876. /* encode side bitrate tracking */
  103877. typedef struct bitrate_manager_state {
  103878. int managed;
  103879. long avg_reservoir;
  103880. long minmax_reservoir;
  103881. long avg_bitsper;
  103882. long min_bitsper;
  103883. long max_bitsper;
  103884. long short_per_long;
  103885. double avgfloat;
  103886. vorbis_block *vb;
  103887. int choice;
  103888. } bitrate_manager_state;
  103889. typedef struct bitrate_manager_info{
  103890. long avg_rate;
  103891. long min_rate;
  103892. long max_rate;
  103893. long reservoir_bits;
  103894. double reservoir_bias;
  103895. double slew_damp;
  103896. } bitrate_manager_info;
  103897. extern void vorbis_bitrate_init(vorbis_info *vi,bitrate_manager_state *bs);
  103898. extern void vorbis_bitrate_clear(bitrate_manager_state *bs);
  103899. extern int vorbis_bitrate_managed(vorbis_block *vb);
  103900. extern int vorbis_bitrate_addblock(vorbis_block *vb);
  103901. extern int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd, ogg_packet *op);
  103902. #endif
  103903. /********* End of inlined file: bitrate.h *********/
  103904. static int ilog(unsigned int v){
  103905. int ret=0;
  103906. while(v){
  103907. ret++;
  103908. v>>=1;
  103909. }
  103910. return(ret);
  103911. }
  103912. static int ilog2(unsigned int v){
  103913. int ret=0;
  103914. if(v)--v;
  103915. while(v){
  103916. ret++;
  103917. v>>=1;
  103918. }
  103919. return(ret);
  103920. }
  103921. typedef struct private_state {
  103922. /* local lookup storage */
  103923. envelope_lookup *ve; /* envelope lookup */
  103924. int window[2];
  103925. vorbis_look_transform **transform[2]; /* block, type */
  103926. drft_lookup fft_look[2];
  103927. int modebits;
  103928. vorbis_look_floor **flr;
  103929. vorbis_look_residue **residue;
  103930. vorbis_look_psy *psy;
  103931. vorbis_look_psy_global *psy_g_look;
  103932. /* local storage, only used on the encoding side. This way the
  103933. application does not need to worry about freeing some packets'
  103934. memory and not others'; packet storage is always tracked.
  103935. Cleared next call to a _dsp_ function */
  103936. unsigned char *header;
  103937. unsigned char *header1;
  103938. unsigned char *header2;
  103939. bitrate_manager_state bms;
  103940. ogg_int64_t sample_count;
  103941. } private_state;
  103942. /* codec_setup_info contains all the setup information specific to the
  103943. specific compression/decompression mode in progress (eg,
  103944. psychoacoustic settings, channel setup, options, codebook
  103945. etc).
  103946. *********************************************************************/
  103947. /********* Start of inlined file: highlevel.h *********/
  103948. typedef struct highlevel_byblocktype {
  103949. double tone_mask_setting;
  103950. double tone_peaklimit_setting;
  103951. double noise_bias_setting;
  103952. double noise_compand_setting;
  103953. } highlevel_byblocktype;
  103954. typedef struct highlevel_encode_setup {
  103955. void *setup;
  103956. int set_in_stone;
  103957. double base_setting;
  103958. double long_setting;
  103959. double short_setting;
  103960. double impulse_noisetune;
  103961. int managed;
  103962. long bitrate_min;
  103963. long bitrate_av;
  103964. double bitrate_av_damp;
  103965. long bitrate_max;
  103966. long bitrate_reservoir;
  103967. double bitrate_reservoir_bias;
  103968. int impulse_block_p;
  103969. int noise_normalize_p;
  103970. double stereo_point_setting;
  103971. double lowpass_kHz;
  103972. double ath_floating_dB;
  103973. double ath_absolute_dB;
  103974. double amplitude_track_dBpersec;
  103975. double trigger_setting;
  103976. highlevel_byblocktype block[4]; /* padding, impulse, transition, long */
  103977. } highlevel_encode_setup;
  103978. /********* End of inlined file: highlevel.h *********/
  103979. typedef struct codec_setup_info {
  103980. /* Vorbis supports only short and long blocks, but allows the
  103981. encoder to choose the sizes */
  103982. long blocksizes[2];
  103983. /* modes are the primary means of supporting on-the-fly different
  103984. blocksizes, different channel mappings (LR or M/A),
  103985. different residue backends, etc. Each mode consists of a
  103986. blocksize flag and a mapping (along with the mapping setup */
  103987. int modes;
  103988. int maps;
  103989. int floors;
  103990. int residues;
  103991. int books;
  103992. int psys; /* encode only */
  103993. vorbis_info_mode *mode_param[64];
  103994. int map_type[64];
  103995. vorbis_info_mapping *map_param[64];
  103996. int floor_type[64];
  103997. vorbis_info_floor *floor_param[64];
  103998. int residue_type[64];
  103999. vorbis_info_residue *residue_param[64];
  104000. static_codebook *book_param[256];
  104001. codebook *fullbooks;
  104002. vorbis_info_psy *psy_param[4]; /* encode only */
  104003. vorbis_info_psy_global psy_g_param;
  104004. bitrate_manager_info bi;
  104005. highlevel_encode_setup hi; /* used only by vorbisenc.c. It's a
  104006. highly redundant structure, but
  104007. improves clarity of program flow. */
  104008. int halfrate_flag; /* painless downsample for decode */
  104009. } codec_setup_info;
  104010. extern vorbis_look_psy_global *_vp_global_look(vorbis_info *vi);
  104011. extern void _vp_global_free(vorbis_look_psy_global *look);
  104012. #endif
  104013. /********* End of inlined file: codec_internal.h *********/
  104014. /********* Start of inlined file: registry.h *********/
  104015. #ifndef _V_REG_H_
  104016. #define _V_REG_H_
  104017. #define VI_TRANSFORMB 1
  104018. #define VI_WINDOWB 1
  104019. #define VI_TIMEB 1
  104020. #define VI_FLOORB 2
  104021. #define VI_RESB 3
  104022. #define VI_MAPB 1
  104023. extern vorbis_func_floor *_floor_P[];
  104024. extern vorbis_func_residue *_residue_P[];
  104025. extern vorbis_func_mapping *_mapping_P[];
  104026. #endif
  104027. /********* End of inlined file: registry.h *********/
  104028. /********* Start of inlined file: scales.h *********/
  104029. #ifndef _V_SCALES_H_
  104030. #define _V_SCALES_H_
  104031. #include <math.h>
  104032. /* 20log10(x) */
  104033. #define VORBIS_IEEE_FLOAT32 1
  104034. #ifdef VORBIS_IEEE_FLOAT32
  104035. static float unitnorm(float x){
  104036. union {
  104037. ogg_uint32_t i;
  104038. float f;
  104039. } ix;
  104040. ix.f = x;
  104041. ix.i = (ix.i & 0x80000000U) | (0x3f800000U);
  104042. return ix.f;
  104043. }
  104044. /* Segher was off (too high) by ~ .3 decibel. Center the conversion correctly. */
  104045. static float todB(const float *x){
  104046. union {
  104047. ogg_uint32_t i;
  104048. float f;
  104049. } ix;
  104050. ix.f = *x;
  104051. ix.i = ix.i&0x7fffffff;
  104052. return (float)(ix.i * 7.17711438e-7f -764.6161886f);
  104053. }
  104054. #define todB_nn(x) todB(x)
  104055. #else
  104056. static float unitnorm(float x){
  104057. if(x<0)return(-1.f);
  104058. return(1.f);
  104059. }
  104060. #define todB(x) (*(x)==0?-400.f:log(*(x)**(x))*4.34294480f)
  104061. #define todB_nn(x) (*(x)==0.f?-400.f:log(*(x))*8.6858896f)
  104062. #endif
  104063. #define fromdB(x) (exp((x)*.11512925f))
  104064. /* The bark scale equations are approximations, since the original
  104065. table was somewhat hand rolled. The below are chosen to have the
  104066. best possible fit to the rolled tables, thus their somewhat odd
  104067. appearance (these are more accurate and over a longer range than
  104068. the oft-quoted bark equations found in the texts I have). The
  104069. approximations are valid from 0 - 30kHz (nyquist) or so.
  104070. all f in Hz, z in Bark */
  104071. #define toBARK(n) (13.1f*atan(.00074f*(n))+2.24f*atan((n)*(n)*1.85e-8f)+1e-4f*(n))
  104072. #define fromBARK(z) (102.f*(z)-2.f*pow(z,2.f)+.4f*pow(z,3.f)+pow(1.46f,z)-1.f)
  104073. #define toMEL(n) (log(1.f+(n)*.001f)*1442.695f)
  104074. #define fromMEL(m) (1000.f*exp((m)/1442.695f)-1000.f)
  104075. /* Frequency to octave. We arbitrarily declare 63.5 Hz to be octave
  104076. 0.0 */
  104077. #define toOC(n) (log(n)*1.442695f-5.965784f)
  104078. #define fromOC(o) (exp(((o)+5.965784f)*.693147f))
  104079. #endif
  104080. /********* End of inlined file: scales.h *********/
  104081. int analysis_noisy=1;
  104082. /* decides between modes, dispatches to the appropriate mapping. */
  104083. int vorbis_analysis(vorbis_block *vb, ogg_packet *op){
  104084. int ret,i;
  104085. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  104086. vb->glue_bits=0;
  104087. vb->time_bits=0;
  104088. vb->floor_bits=0;
  104089. vb->res_bits=0;
  104090. /* first things first. Make sure encode is ready */
  104091. for(i=0;i<PACKETBLOBS;i++)
  104092. oggpack_reset(vbi->packetblob[i]);
  104093. /* we only have one mapping type (0), and we let the mapping code
  104094. itself figure out what soft mode to use. This allows easier
  104095. bitrate management */
  104096. if((ret=_mapping_P[0]->forward(vb)))
  104097. return(ret);
  104098. if(op){
  104099. if(vorbis_bitrate_managed(vb))
  104100. /* The app is using a bitmanaged mode... but not using the
  104101. bitrate management interface. */
  104102. return(OV_EINVAL);
  104103. op->packet=oggpack_get_buffer(&vb->opb);
  104104. op->bytes=oggpack_bytes(&vb->opb);
  104105. op->b_o_s=0;
  104106. op->e_o_s=vb->eofflag;
  104107. op->granulepos=vb->granulepos;
  104108. op->packetno=vb->sequence; /* for sake of completeness */
  104109. }
  104110. return(0);
  104111. }
  104112. /* there was no great place to put this.... */
  104113. void _analysis_output_always(char *base,int i,float *v,int n,int bark,int dB,ogg_int64_t off){
  104114. int j;
  104115. FILE *of;
  104116. char buffer[80];
  104117. /* if(i==5870){*/
  104118. sprintf(buffer,"%s_%d.m",base,i);
  104119. of=fopen(buffer,"w");
  104120. if(!of)perror("failed to open data dump file");
  104121. for(j=0;j<n;j++){
  104122. if(bark){
  104123. float b=toBARK((4000.f*j/n)+.25);
  104124. fprintf(of,"%f ",b);
  104125. }else
  104126. if(off!=0)
  104127. fprintf(of,"%f ",(double)(j+off)/8000.);
  104128. else
  104129. fprintf(of,"%f ",(double)j);
  104130. if(dB){
  104131. float val;
  104132. if(v[j]==0.)
  104133. val=-140.;
  104134. else
  104135. val=todB(v+j);
  104136. fprintf(of,"%f\n",val);
  104137. }else{
  104138. fprintf(of,"%f\n",v[j]);
  104139. }
  104140. }
  104141. fclose(of);
  104142. /* } */
  104143. }
  104144. void _analysis_output(char *base,int i,float *v,int n,int bark,int dB,
  104145. ogg_int64_t off){
  104146. if(analysis_noisy)_analysis_output_always(base,i,v,n,bark,dB,off);
  104147. }
  104148. #endif
  104149. /********* End of inlined file: analysis.c *********/
  104150. /********* Start of inlined file: bitrate.c *********/
  104151. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  104152. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  104153. // tasks..
  104154. #ifdef _MSC_VER
  104155. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  104156. #endif
  104157. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  104158. #if JUCE_USE_OGGVORBIS
  104159. #include <stdlib.h>
  104160. #include <string.h>
  104161. #include <math.h>
  104162. /* compute bitrate tracking setup */
  104163. void vorbis_bitrate_init(vorbis_info *vi,bitrate_manager_state *bm){
  104164. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  104165. bitrate_manager_info *bi=&ci->bi;
  104166. memset(bm,0,sizeof(*bm));
  104167. if(bi && (bi->reservoir_bits>0)){
  104168. long ratesamples=vi->rate;
  104169. int halfsamples=ci->blocksizes[0]>>1;
  104170. bm->short_per_long=ci->blocksizes[1]/ci->blocksizes[0];
  104171. bm->managed=1;
  104172. bm->avg_bitsper= rint(1.*bi->avg_rate*halfsamples/ratesamples);
  104173. bm->min_bitsper= rint(1.*bi->min_rate*halfsamples/ratesamples);
  104174. bm->max_bitsper= rint(1.*bi->max_rate*halfsamples/ratesamples);
  104175. bm->avgfloat=PACKETBLOBS/2;
  104176. /* not a necessary fix, but one that leads to a more balanced
  104177. typical initialization */
  104178. {
  104179. long desired_fill=bi->reservoir_bits*bi->reservoir_bias;
  104180. bm->minmax_reservoir=desired_fill;
  104181. bm->avg_reservoir=desired_fill;
  104182. }
  104183. }
  104184. }
  104185. void vorbis_bitrate_clear(bitrate_manager_state *bm){
  104186. memset(bm,0,sizeof(*bm));
  104187. return;
  104188. }
  104189. int vorbis_bitrate_managed(vorbis_block *vb){
  104190. vorbis_dsp_state *vd=vb->vd;
  104191. private_state *b=(private_state*)vd->backend_state;
  104192. bitrate_manager_state *bm=&b->bms;
  104193. if(bm && bm->managed)return(1);
  104194. return(0);
  104195. }
  104196. /* finish taking in the block we just processed */
  104197. int vorbis_bitrate_addblock(vorbis_block *vb){
  104198. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  104199. vorbis_dsp_state *vd=vb->vd;
  104200. private_state *b=(private_state*)vd->backend_state;
  104201. bitrate_manager_state *bm=&b->bms;
  104202. vorbis_info *vi=vd->vi;
  104203. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  104204. bitrate_manager_info *bi=&ci->bi;
  104205. int choice=rint(bm->avgfloat);
  104206. long this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  104207. long min_target_bits=(vb->W?bm->min_bitsper*bm->short_per_long:bm->min_bitsper);
  104208. long max_target_bits=(vb->W?bm->max_bitsper*bm->short_per_long:bm->max_bitsper);
  104209. int samples=ci->blocksizes[vb->W]>>1;
  104210. long desired_fill=bi->reservoir_bits*bi->reservoir_bias;
  104211. if(!bm->managed){
  104212. /* not a bitrate managed stream, but for API simplicity, we'll
  104213. buffer the packet to keep the code path clean */
  104214. if(bm->vb)return(-1); /* one has been submitted without
  104215. being claimed */
  104216. bm->vb=vb;
  104217. return(0);
  104218. }
  104219. bm->vb=vb;
  104220. /* look ahead for avg floater */
  104221. if(bm->avg_bitsper>0){
  104222. double slew=0.;
  104223. long avg_target_bits=(vb->W?bm->avg_bitsper*bm->short_per_long:bm->avg_bitsper);
  104224. double slewlimit= 15./bi->slew_damp;
  104225. /* choosing a new floater:
  104226. if we're over target, we slew down
  104227. if we're under target, we slew up
  104228. choose slew as follows: look through packetblobs of this frame
  104229. and set slew as the first in the appropriate direction that
  104230. gives us the slew we want. This may mean no slew if delta is
  104231. already favorable.
  104232. Then limit slew to slew max */
  104233. if(bm->avg_reservoir+(this_bits-avg_target_bits)>desired_fill){
  104234. while(choice>0 && this_bits>avg_target_bits &&
  104235. bm->avg_reservoir+(this_bits-avg_target_bits)>desired_fill){
  104236. choice--;
  104237. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  104238. }
  104239. }else if(bm->avg_reservoir+(this_bits-avg_target_bits)<desired_fill){
  104240. while(choice+1<PACKETBLOBS && this_bits<avg_target_bits &&
  104241. bm->avg_reservoir+(this_bits-avg_target_bits)<desired_fill){
  104242. choice++;
  104243. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  104244. }
  104245. }
  104246. slew=rint(choice-bm->avgfloat)/samples*vi->rate;
  104247. if(slew<-slewlimit)slew=-slewlimit;
  104248. if(slew>slewlimit)slew=slewlimit;
  104249. choice=rint(bm->avgfloat+= slew/vi->rate*samples);
  104250. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  104251. }
  104252. /* enforce min(if used) on the current floater (if used) */
  104253. if(bm->min_bitsper>0){
  104254. /* do we need to force the bitrate up? */
  104255. if(this_bits<min_target_bits){
  104256. while(bm->minmax_reservoir-(min_target_bits-this_bits)<0){
  104257. choice++;
  104258. if(choice>=PACKETBLOBS)break;
  104259. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  104260. }
  104261. }
  104262. }
  104263. /* enforce max (if used) on the current floater (if used) */
  104264. if(bm->max_bitsper>0){
  104265. /* do we need to force the bitrate down? */
  104266. if(this_bits>max_target_bits){
  104267. while(bm->minmax_reservoir+(this_bits-max_target_bits)>bi->reservoir_bits){
  104268. choice--;
  104269. if(choice<0)break;
  104270. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  104271. }
  104272. }
  104273. }
  104274. /* Choice of packetblobs now made based on floater, and min/max
  104275. requirements. Now boundary check extreme choices */
  104276. if(choice<0){
  104277. /* choosing a smaller packetblob is insufficient to trim bitrate.
  104278. frame will need to be truncated */
  104279. long maxsize=(max_target_bits+(bi->reservoir_bits-bm->minmax_reservoir))/8;
  104280. bm->choice=choice=0;
  104281. if(oggpack_bytes(vbi->packetblob[choice])>maxsize){
  104282. oggpack_writetrunc(vbi->packetblob[choice],maxsize*8);
  104283. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  104284. }
  104285. }else{
  104286. long minsize=(min_target_bits-bm->minmax_reservoir+7)/8;
  104287. if(choice>=PACKETBLOBS)
  104288. choice=PACKETBLOBS-1;
  104289. bm->choice=choice;
  104290. /* prop up bitrate according to demand. pad this frame out with zeroes */
  104291. minsize-=oggpack_bytes(vbi->packetblob[choice]);
  104292. while(minsize-->0)oggpack_write(vbi->packetblob[choice],0,8);
  104293. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  104294. }
  104295. /* now we have the final packet and the final packet size. Update statistics */
  104296. /* min and max reservoir */
  104297. if(bm->min_bitsper>0 || bm->max_bitsper>0){
  104298. if(max_target_bits>0 && this_bits>max_target_bits){
  104299. bm->minmax_reservoir+=(this_bits-max_target_bits);
  104300. }else if(min_target_bits>0 && this_bits<min_target_bits){
  104301. bm->minmax_reservoir+=(this_bits-min_target_bits);
  104302. }else{
  104303. /* inbetween; we want to take reservoir toward but not past desired_fill */
  104304. if(bm->minmax_reservoir>desired_fill){
  104305. if(max_target_bits>0){ /* logical bulletproofing against initialization state */
  104306. bm->minmax_reservoir+=(this_bits-max_target_bits);
  104307. if(bm->minmax_reservoir<desired_fill)bm->minmax_reservoir=desired_fill;
  104308. }else{
  104309. bm->minmax_reservoir=desired_fill;
  104310. }
  104311. }else{
  104312. if(min_target_bits>0){ /* logical bulletproofing against initialization state */
  104313. bm->minmax_reservoir+=(this_bits-min_target_bits);
  104314. if(bm->minmax_reservoir>desired_fill)bm->minmax_reservoir=desired_fill;
  104315. }else{
  104316. bm->minmax_reservoir=desired_fill;
  104317. }
  104318. }
  104319. }
  104320. }
  104321. /* avg reservoir */
  104322. if(bm->avg_bitsper>0){
  104323. long avg_target_bits=(vb->W?bm->avg_bitsper*bm->short_per_long:bm->avg_bitsper);
  104324. bm->avg_reservoir+=this_bits-avg_target_bits;
  104325. }
  104326. return(0);
  104327. }
  104328. int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd,ogg_packet *op){
  104329. private_state *b=(private_state*)vd->backend_state;
  104330. bitrate_manager_state *bm=&b->bms;
  104331. vorbis_block *vb=bm->vb;
  104332. int choice=PACKETBLOBS/2;
  104333. if(!vb)return 0;
  104334. if(op){
  104335. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  104336. if(vorbis_bitrate_managed(vb))
  104337. choice=bm->choice;
  104338. op->packet=oggpack_get_buffer(vbi->packetblob[choice]);
  104339. op->bytes=oggpack_bytes(vbi->packetblob[choice]);
  104340. op->b_o_s=0;
  104341. op->e_o_s=vb->eofflag;
  104342. op->granulepos=vb->granulepos;
  104343. op->packetno=vb->sequence; /* for sake of completeness */
  104344. }
  104345. bm->vb=0;
  104346. return(1);
  104347. }
  104348. #endif
  104349. /********* End of inlined file: bitrate.c *********/
  104350. /********* Start of inlined file: block.c *********/
  104351. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  104352. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  104353. // tasks..
  104354. #ifdef _MSC_VER
  104355. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  104356. #endif
  104357. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  104358. #if JUCE_USE_OGGVORBIS
  104359. #include <stdio.h>
  104360. #include <stdlib.h>
  104361. #include <string.h>
  104362. /********* Start of inlined file: window.h *********/
  104363. #ifndef _V_WINDOW_
  104364. #define _V_WINDOW_
  104365. extern float *_vorbis_window_get(int n);
  104366. extern void _vorbis_apply_window(float *d,int *winno,long *blocksizes,
  104367. int lW,int W,int nW);
  104368. #endif
  104369. /********* End of inlined file: window.h *********/
  104370. /********* Start of inlined file: lpc.h *********/
  104371. #ifndef _V_LPC_H_
  104372. #define _V_LPC_H_
  104373. /* simple linear scale LPC code */
  104374. extern float vorbis_lpc_from_data(float *data,float *lpc,int n,int m);
  104375. extern void vorbis_lpc_predict(float *coeff,float *prime,int m,
  104376. float *data,long n);
  104377. #endif
  104378. /********* End of inlined file: lpc.h *********/
  104379. /* pcm accumulator examples (not exhaustive):
  104380. <-------------- lW ---------------->
  104381. <--------------- W ---------------->
  104382. : .....|..... _______________ |
  104383. : .''' | '''_--- | |\ |
  104384. :.....''' |_____--- '''......| | \_______|
  104385. :.................|__________________|_______|__|______|
  104386. |<------ Sl ------>| > Sr < |endW
  104387. |beginSl |endSl | |endSr
  104388. |beginW |endlW |beginSr
  104389. |< lW >|
  104390. <--------------- W ---------------->
  104391. | | .. ______________ |
  104392. | | ' `/ | ---_ |
  104393. |___.'___/`. | ---_____|
  104394. |_______|__|_______|_________________|
  104395. | >|Sl|< |<------ Sr ----->|endW
  104396. | | |endSl |beginSr |endSr
  104397. |beginW | |endlW
  104398. mult[0] |beginSl mult[n]
  104399. <-------------- lW ----------------->
  104400. |<--W-->|
  104401. : .............. ___ | |
  104402. : .''' |`/ \ | |
  104403. :.....''' |/`....\|...|
  104404. :.........................|___|___|___|
  104405. |Sl |Sr |endW
  104406. | | |endSr
  104407. | |beginSr
  104408. | |endSl
  104409. |beginSl
  104410. |beginW
  104411. */
  104412. /* block abstraction setup *********************************************/
  104413. #ifndef WORD_ALIGN
  104414. #define WORD_ALIGN 8
  104415. #endif
  104416. int vorbis_block_init(vorbis_dsp_state *v, vorbis_block *vb){
  104417. int i;
  104418. memset(vb,0,sizeof(*vb));
  104419. vb->vd=v;
  104420. vb->localalloc=0;
  104421. vb->localstore=NULL;
  104422. if(v->analysisp){
  104423. vorbis_block_internal *vbi=(vorbis_block_internal*)
  104424. (vb->internal=(vorbis_block_internal*)_ogg_calloc(1,sizeof(vorbis_block_internal)));
  104425. vbi->ampmax=-9999;
  104426. for(i=0;i<PACKETBLOBS;i++){
  104427. if(i==PACKETBLOBS/2){
  104428. vbi->packetblob[i]=&vb->opb;
  104429. }else{
  104430. vbi->packetblob[i]=
  104431. (oggpack_buffer*) _ogg_calloc(1,sizeof(oggpack_buffer));
  104432. }
  104433. oggpack_writeinit(vbi->packetblob[i]);
  104434. }
  104435. }
  104436. return(0);
  104437. }
  104438. void *_vorbis_block_alloc(vorbis_block *vb,long bytes){
  104439. bytes=(bytes+(WORD_ALIGN-1)) & ~(WORD_ALIGN-1);
  104440. if(bytes+vb->localtop>vb->localalloc){
  104441. /* can't just _ogg_realloc... there are outstanding pointers */
  104442. if(vb->localstore){
  104443. struct alloc_chain *link=(struct alloc_chain*)_ogg_malloc(sizeof(*link));
  104444. vb->totaluse+=vb->localtop;
  104445. link->next=vb->reap;
  104446. link->ptr=vb->localstore;
  104447. vb->reap=link;
  104448. }
  104449. /* highly conservative */
  104450. vb->localalloc=bytes;
  104451. vb->localstore=_ogg_malloc(vb->localalloc);
  104452. vb->localtop=0;
  104453. }
  104454. {
  104455. void *ret=(void *)(((char *)vb->localstore)+vb->localtop);
  104456. vb->localtop+=bytes;
  104457. return ret;
  104458. }
  104459. }
  104460. /* reap the chain, pull the ripcord */
  104461. void _vorbis_block_ripcord(vorbis_block *vb){
  104462. /* reap the chain */
  104463. struct alloc_chain *reap=vb->reap;
  104464. while(reap){
  104465. struct alloc_chain *next=reap->next;
  104466. _ogg_free(reap->ptr);
  104467. memset(reap,0,sizeof(*reap));
  104468. _ogg_free(reap);
  104469. reap=next;
  104470. }
  104471. /* consolidate storage */
  104472. if(vb->totaluse){
  104473. vb->localstore=_ogg_realloc(vb->localstore,vb->totaluse+vb->localalloc);
  104474. vb->localalloc+=vb->totaluse;
  104475. vb->totaluse=0;
  104476. }
  104477. /* pull the ripcord */
  104478. vb->localtop=0;
  104479. vb->reap=NULL;
  104480. }
  104481. int vorbis_block_clear(vorbis_block *vb){
  104482. int i;
  104483. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  104484. _vorbis_block_ripcord(vb);
  104485. if(vb->localstore)_ogg_free(vb->localstore);
  104486. if(vbi){
  104487. for(i=0;i<PACKETBLOBS;i++){
  104488. oggpack_writeclear(vbi->packetblob[i]);
  104489. if(i!=PACKETBLOBS/2)_ogg_free(vbi->packetblob[i]);
  104490. }
  104491. _ogg_free(vbi);
  104492. }
  104493. memset(vb,0,sizeof(*vb));
  104494. return(0);
  104495. }
  104496. /* Analysis side code, but directly related to blocking. Thus it's
  104497. here and not in analysis.c (which is for analysis transforms only).
  104498. The init is here because some of it is shared */
  104499. static int _vds_shared_init(vorbis_dsp_state *v,vorbis_info *vi,int encp){
  104500. int i;
  104501. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  104502. private_state *b=NULL;
  104503. int hs;
  104504. if(ci==NULL) return 1;
  104505. hs=ci->halfrate_flag;
  104506. memset(v,0,sizeof(*v));
  104507. b=(private_state*) (v->backend_state=(private_state*)_ogg_calloc(1,sizeof(*b)));
  104508. v->vi=vi;
  104509. b->modebits=ilog2(ci->modes);
  104510. b->transform[0]=(vorbis_look_transform**)_ogg_calloc(VI_TRANSFORMB,sizeof(*b->transform[0]));
  104511. b->transform[1]=(vorbis_look_transform**)_ogg_calloc(VI_TRANSFORMB,sizeof(*b->transform[1]));
  104512. /* MDCT is tranform 0 */
  104513. b->transform[0][0]=_ogg_calloc(1,sizeof(mdct_lookup));
  104514. b->transform[1][0]=_ogg_calloc(1,sizeof(mdct_lookup));
  104515. mdct_init((mdct_lookup*)b->transform[0][0],ci->blocksizes[0]>>hs);
  104516. mdct_init((mdct_lookup*)b->transform[1][0],ci->blocksizes[1]>>hs);
  104517. /* Vorbis I uses only window type 0 */
  104518. b->window[0]=ilog2(ci->blocksizes[0])-6;
  104519. b->window[1]=ilog2(ci->blocksizes[1])-6;
  104520. if(encp){ /* encode/decode differ here */
  104521. /* analysis always needs an fft */
  104522. drft_init(&b->fft_look[0],ci->blocksizes[0]);
  104523. drft_init(&b->fft_look[1],ci->blocksizes[1]);
  104524. /* finish the codebooks */
  104525. if(!ci->fullbooks){
  104526. ci->fullbooks=(codebook*) _ogg_calloc(ci->books,sizeof(*ci->fullbooks));
  104527. for(i=0;i<ci->books;i++)
  104528. vorbis_book_init_encode(ci->fullbooks+i,ci->book_param[i]);
  104529. }
  104530. b->psy=(vorbis_look_psy*)_ogg_calloc(ci->psys,sizeof(*b->psy));
  104531. for(i=0;i<ci->psys;i++){
  104532. _vp_psy_init(b->psy+i,
  104533. ci->psy_param[i],
  104534. &ci->psy_g_param,
  104535. ci->blocksizes[ci->psy_param[i]->blockflag]/2,
  104536. vi->rate);
  104537. }
  104538. v->analysisp=1;
  104539. }else{
  104540. /* finish the codebooks */
  104541. if(!ci->fullbooks){
  104542. ci->fullbooks=(codebook*) _ogg_calloc(ci->books,sizeof(*ci->fullbooks));
  104543. for(i=0;i<ci->books;i++){
  104544. vorbis_book_init_decode(ci->fullbooks+i,ci->book_param[i]);
  104545. /* decode codebooks are now standalone after init */
  104546. vorbis_staticbook_destroy(ci->book_param[i]);
  104547. ci->book_param[i]=NULL;
  104548. }
  104549. }
  104550. }
  104551. /* initialize the storage vectors. blocksize[1] is small for encode,
  104552. but the correct size for decode */
  104553. v->pcm_storage=ci->blocksizes[1];
  104554. v->pcm=(float**)_ogg_malloc(vi->channels*sizeof(*v->pcm));
  104555. v->pcmret=(float**)_ogg_malloc(vi->channels*sizeof(*v->pcmret));
  104556. {
  104557. int i;
  104558. for(i=0;i<vi->channels;i++)
  104559. v->pcm[i]=(float*)_ogg_calloc(v->pcm_storage,sizeof(*v->pcm[i]));
  104560. }
  104561. /* all 1 (large block) or 0 (small block) */
  104562. /* explicitly set for the sake of clarity */
  104563. v->lW=0; /* previous window size */
  104564. v->W=0; /* current window size */
  104565. /* all vector indexes */
  104566. v->centerW=ci->blocksizes[1]/2;
  104567. v->pcm_current=v->centerW;
  104568. /* initialize all the backend lookups */
  104569. b->flr=(vorbis_look_floor**)_ogg_calloc(ci->floors,sizeof(*b->flr));
  104570. b->residue=(vorbis_look_residue**)_ogg_calloc(ci->residues,sizeof(*b->residue));
  104571. for(i=0;i<ci->floors;i++)
  104572. b->flr[i]=_floor_P[ci->floor_type[i]]->
  104573. look(v,ci->floor_param[i]);
  104574. for(i=0;i<ci->residues;i++)
  104575. b->residue[i]=_residue_P[ci->residue_type[i]]->
  104576. look(v,ci->residue_param[i]);
  104577. return 0;
  104578. }
  104579. /* arbitrary settings and spec-mandated numbers get filled in here */
  104580. int vorbis_analysis_init(vorbis_dsp_state *v,vorbis_info *vi){
  104581. private_state *b=NULL;
  104582. if(_vds_shared_init(v,vi,1))return 1;
  104583. b=(private_state*)v->backend_state;
  104584. b->psy_g_look=_vp_global_look(vi);
  104585. /* Initialize the envelope state storage */
  104586. b->ve=(envelope_lookup*)_ogg_calloc(1,sizeof(*b->ve));
  104587. _ve_envelope_init(b->ve,vi);
  104588. vorbis_bitrate_init(vi,&b->bms);
  104589. /* compressed audio packets start after the headers
  104590. with sequence number 3 */
  104591. v->sequence=3;
  104592. return(0);
  104593. }
  104594. void vorbis_dsp_clear(vorbis_dsp_state *v){
  104595. int i;
  104596. if(v){
  104597. vorbis_info *vi=v->vi;
  104598. codec_setup_info *ci=(codec_setup_info*)(vi?vi->codec_setup:NULL);
  104599. private_state *b=(private_state*)v->backend_state;
  104600. if(b){
  104601. if(b->ve){
  104602. _ve_envelope_clear(b->ve);
  104603. _ogg_free(b->ve);
  104604. }
  104605. if(b->transform[0]){
  104606. mdct_clear((mdct_lookup*) b->transform[0][0]);
  104607. _ogg_free(b->transform[0][0]);
  104608. _ogg_free(b->transform[0]);
  104609. }
  104610. if(b->transform[1]){
  104611. mdct_clear((mdct_lookup*) b->transform[1][0]);
  104612. _ogg_free(b->transform[1][0]);
  104613. _ogg_free(b->transform[1]);
  104614. }
  104615. if(b->flr){
  104616. for(i=0;i<ci->floors;i++)
  104617. _floor_P[ci->floor_type[i]]->
  104618. free_look(b->flr[i]);
  104619. _ogg_free(b->flr);
  104620. }
  104621. if(b->residue){
  104622. for(i=0;i<ci->residues;i++)
  104623. _residue_P[ci->residue_type[i]]->
  104624. free_look(b->residue[i]);
  104625. _ogg_free(b->residue);
  104626. }
  104627. if(b->psy){
  104628. for(i=0;i<ci->psys;i++)
  104629. _vp_psy_clear(b->psy+i);
  104630. _ogg_free(b->psy);
  104631. }
  104632. if(b->psy_g_look)_vp_global_free(b->psy_g_look);
  104633. vorbis_bitrate_clear(&b->bms);
  104634. drft_clear(&b->fft_look[0]);
  104635. drft_clear(&b->fft_look[1]);
  104636. }
  104637. if(v->pcm){
  104638. for(i=0;i<vi->channels;i++)
  104639. if(v->pcm[i])_ogg_free(v->pcm[i]);
  104640. _ogg_free(v->pcm);
  104641. if(v->pcmret)_ogg_free(v->pcmret);
  104642. }
  104643. if(b){
  104644. /* free header, header1, header2 */
  104645. if(b->header)_ogg_free(b->header);
  104646. if(b->header1)_ogg_free(b->header1);
  104647. if(b->header2)_ogg_free(b->header2);
  104648. _ogg_free(b);
  104649. }
  104650. memset(v,0,sizeof(*v));
  104651. }
  104652. }
  104653. float **vorbis_analysis_buffer(vorbis_dsp_state *v, int vals){
  104654. int i;
  104655. vorbis_info *vi=v->vi;
  104656. private_state *b=(private_state*)v->backend_state;
  104657. /* free header, header1, header2 */
  104658. if(b->header)_ogg_free(b->header);b->header=NULL;
  104659. if(b->header1)_ogg_free(b->header1);b->header1=NULL;
  104660. if(b->header2)_ogg_free(b->header2);b->header2=NULL;
  104661. /* Do we have enough storage space for the requested buffer? If not,
  104662. expand the PCM (and envelope) storage */
  104663. if(v->pcm_current+vals>=v->pcm_storage){
  104664. v->pcm_storage=v->pcm_current+vals*2;
  104665. for(i=0;i<vi->channels;i++){
  104666. v->pcm[i]=(float*)_ogg_realloc(v->pcm[i],v->pcm_storage*sizeof(*v->pcm[i]));
  104667. }
  104668. }
  104669. for(i=0;i<vi->channels;i++)
  104670. v->pcmret[i]=v->pcm[i]+v->pcm_current;
  104671. return(v->pcmret);
  104672. }
  104673. static void _preextrapolate_helper(vorbis_dsp_state *v){
  104674. int i;
  104675. int order=32;
  104676. float *lpc=(float*)alloca(order*sizeof(*lpc));
  104677. float *work=(float*)alloca(v->pcm_current*sizeof(*work));
  104678. long j;
  104679. v->preextrapolate=1;
  104680. if(v->pcm_current-v->centerW>order*2){ /* safety */
  104681. for(i=0;i<v->vi->channels;i++){
  104682. /* need to run the extrapolation in reverse! */
  104683. for(j=0;j<v->pcm_current;j++)
  104684. work[j]=v->pcm[i][v->pcm_current-j-1];
  104685. /* prime as above */
  104686. vorbis_lpc_from_data(work,lpc,v->pcm_current-v->centerW,order);
  104687. /* run the predictor filter */
  104688. vorbis_lpc_predict(lpc,work+v->pcm_current-v->centerW-order,
  104689. order,
  104690. work+v->pcm_current-v->centerW,
  104691. v->centerW);
  104692. for(j=0;j<v->pcm_current;j++)
  104693. v->pcm[i][v->pcm_current-j-1]=work[j];
  104694. }
  104695. }
  104696. }
  104697. /* call with val<=0 to set eof */
  104698. int vorbis_analysis_wrote(vorbis_dsp_state *v, int vals){
  104699. vorbis_info *vi=v->vi;
  104700. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  104701. if(vals<=0){
  104702. int order=32;
  104703. int i;
  104704. float *lpc=(float*) alloca(order*sizeof(*lpc));
  104705. /* if it wasn't done earlier (very short sample) */
  104706. if(!v->preextrapolate)
  104707. _preextrapolate_helper(v);
  104708. /* We're encoding the end of the stream. Just make sure we have
  104709. [at least] a few full blocks of zeroes at the end. */
  104710. /* actually, we don't want zeroes; that could drop a large
  104711. amplitude off a cliff, creating spread spectrum noise that will
  104712. suck to encode. Extrapolate for the sake of cleanliness. */
  104713. vorbis_analysis_buffer(v,ci->blocksizes[1]*3);
  104714. v->eofflag=v->pcm_current;
  104715. v->pcm_current+=ci->blocksizes[1]*3;
  104716. for(i=0;i<vi->channels;i++){
  104717. if(v->eofflag>order*2){
  104718. /* extrapolate with LPC to fill in */
  104719. long n;
  104720. /* make a predictor filter */
  104721. n=v->eofflag;
  104722. if(n>ci->blocksizes[1])n=ci->blocksizes[1];
  104723. vorbis_lpc_from_data(v->pcm[i]+v->eofflag-n,lpc,n,order);
  104724. /* run the predictor filter */
  104725. vorbis_lpc_predict(lpc,v->pcm[i]+v->eofflag-order,order,
  104726. v->pcm[i]+v->eofflag,v->pcm_current-v->eofflag);
  104727. }else{
  104728. /* not enough data to extrapolate (unlikely to happen due to
  104729. guarding the overlap, but bulletproof in case that
  104730. assumtion goes away). zeroes will do. */
  104731. memset(v->pcm[i]+v->eofflag,0,
  104732. (v->pcm_current-v->eofflag)*sizeof(*v->pcm[i]));
  104733. }
  104734. }
  104735. }else{
  104736. if(v->pcm_current+vals>v->pcm_storage)
  104737. return(OV_EINVAL);
  104738. v->pcm_current+=vals;
  104739. /* we may want to reverse extrapolate the beginning of a stream
  104740. too... in case we're beginning on a cliff! */
  104741. /* clumsy, but simple. It only runs once, so simple is good. */
  104742. if(!v->preextrapolate && v->pcm_current-v->centerW>ci->blocksizes[1])
  104743. _preextrapolate_helper(v);
  104744. }
  104745. return(0);
  104746. }
  104747. /* do the deltas, envelope shaping, pre-echo and determine the size of
  104748. the next block on which to continue analysis */
  104749. int vorbis_analysis_blockout(vorbis_dsp_state *v,vorbis_block *vb){
  104750. int i;
  104751. vorbis_info *vi=v->vi;
  104752. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  104753. private_state *b=(private_state*)v->backend_state;
  104754. vorbis_look_psy_global *g=b->psy_g_look;
  104755. long beginW=v->centerW-ci->blocksizes[v->W]/2,centerNext;
  104756. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  104757. /* check to see if we're started... */
  104758. if(!v->preextrapolate)return(0);
  104759. /* check to see if we're done... */
  104760. if(v->eofflag==-1)return(0);
  104761. /* By our invariant, we have lW, W and centerW set. Search for
  104762. the next boundary so we can determine nW (the next window size)
  104763. which lets us compute the shape of the current block's window */
  104764. /* we do an envelope search even on a single blocksize; we may still
  104765. be throwing more bits at impulses, and envelope search handles
  104766. marking impulses too. */
  104767. {
  104768. long bp=_ve_envelope_search(v);
  104769. if(bp==-1){
  104770. if(v->eofflag==0)return(0); /* not enough data currently to search for a
  104771. full long block */
  104772. v->nW=0;
  104773. }else{
  104774. if(ci->blocksizes[0]==ci->blocksizes[1])
  104775. v->nW=0;
  104776. else
  104777. v->nW=bp;
  104778. }
  104779. }
  104780. centerNext=v->centerW+ci->blocksizes[v->W]/4+ci->blocksizes[v->nW]/4;
  104781. {
  104782. /* center of next block + next block maximum right side. */
  104783. long blockbound=centerNext+ci->blocksizes[v->nW]/2;
  104784. if(v->pcm_current<blockbound)return(0); /* not enough data yet;
  104785. although this check is
  104786. less strict that the
  104787. _ve_envelope_search,
  104788. the search is not run
  104789. if we only use one
  104790. block size */
  104791. }
  104792. /* fill in the block. Note that for a short window, lW and nW are *short*
  104793. regardless of actual settings in the stream */
  104794. _vorbis_block_ripcord(vb);
  104795. vb->lW=v->lW;
  104796. vb->W=v->W;
  104797. vb->nW=v->nW;
  104798. if(v->W){
  104799. if(!v->lW || !v->nW){
  104800. vbi->blocktype=BLOCKTYPE_TRANSITION;
  104801. /*fprintf(stderr,"-");*/
  104802. }else{
  104803. vbi->blocktype=BLOCKTYPE_LONG;
  104804. /*fprintf(stderr,"_");*/
  104805. }
  104806. }else{
  104807. if(_ve_envelope_mark(v)){
  104808. vbi->blocktype=BLOCKTYPE_IMPULSE;
  104809. /*fprintf(stderr,"|");*/
  104810. }else{
  104811. vbi->blocktype=BLOCKTYPE_PADDING;
  104812. /*fprintf(stderr,".");*/
  104813. }
  104814. }
  104815. vb->vd=v;
  104816. vb->sequence=v->sequence++;
  104817. vb->granulepos=v->granulepos;
  104818. vb->pcmend=ci->blocksizes[v->W];
  104819. /* copy the vectors; this uses the local storage in vb */
  104820. /* this tracks 'strongest peak' for later psychoacoustics */
  104821. /* moved to the global psy state; clean this mess up */
  104822. if(vbi->ampmax>g->ampmax)g->ampmax=vbi->ampmax;
  104823. g->ampmax=_vp_ampmax_decay(g->ampmax,v);
  104824. vbi->ampmax=g->ampmax;
  104825. vb->pcm=(float**)_vorbis_block_alloc(vb,sizeof(*vb->pcm)*vi->channels);
  104826. vbi->pcmdelay=(float**)_vorbis_block_alloc(vb,sizeof(*vbi->pcmdelay)*vi->channels);
  104827. for(i=0;i<vi->channels;i++){
  104828. vbi->pcmdelay[i]=
  104829. (float*) _vorbis_block_alloc(vb,(vb->pcmend+beginW)*sizeof(*vbi->pcmdelay[i]));
  104830. memcpy(vbi->pcmdelay[i],v->pcm[i],(vb->pcmend+beginW)*sizeof(*vbi->pcmdelay[i]));
  104831. vb->pcm[i]=vbi->pcmdelay[i]+beginW;
  104832. /* before we added the delay
  104833. vb->pcm[i]=_vorbis_block_alloc(vb,vb->pcmend*sizeof(*vb->pcm[i]));
  104834. memcpy(vb->pcm[i],v->pcm[i]+beginW,ci->blocksizes[v->W]*sizeof(*vb->pcm[i]));
  104835. */
  104836. }
  104837. /* handle eof detection: eof==0 means that we've not yet received EOF
  104838. eof>0 marks the last 'real' sample in pcm[]
  104839. eof<0 'no more to do'; doesn't get here */
  104840. if(v->eofflag){
  104841. if(v->centerW>=v->eofflag){
  104842. v->eofflag=-1;
  104843. vb->eofflag=1;
  104844. return(1);
  104845. }
  104846. }
  104847. /* advance storage vectors and clean up */
  104848. {
  104849. int new_centerNext=ci->blocksizes[1]/2;
  104850. int movementW=centerNext-new_centerNext;
  104851. if(movementW>0){
  104852. _ve_envelope_shift(b->ve,movementW);
  104853. v->pcm_current-=movementW;
  104854. for(i=0;i<vi->channels;i++)
  104855. memmove(v->pcm[i],v->pcm[i]+movementW,
  104856. v->pcm_current*sizeof(*v->pcm[i]));
  104857. v->lW=v->W;
  104858. v->W=v->nW;
  104859. v->centerW=new_centerNext;
  104860. if(v->eofflag){
  104861. v->eofflag-=movementW;
  104862. if(v->eofflag<=0)v->eofflag=-1;
  104863. /* do not add padding to end of stream! */
  104864. if(v->centerW>=v->eofflag){
  104865. v->granulepos+=movementW-(v->centerW-v->eofflag);
  104866. }else{
  104867. v->granulepos+=movementW;
  104868. }
  104869. }else{
  104870. v->granulepos+=movementW;
  104871. }
  104872. }
  104873. }
  104874. /* done */
  104875. return(1);
  104876. }
  104877. int vorbis_synthesis_restart(vorbis_dsp_state *v){
  104878. vorbis_info *vi=v->vi;
  104879. codec_setup_info *ci;
  104880. int hs;
  104881. if(!v->backend_state)return -1;
  104882. if(!vi)return -1;
  104883. ci=(codec_setup_info*) vi->codec_setup;
  104884. if(!ci)return -1;
  104885. hs=ci->halfrate_flag;
  104886. v->centerW=ci->blocksizes[1]>>(hs+1);
  104887. v->pcm_current=v->centerW>>hs;
  104888. v->pcm_returned=-1;
  104889. v->granulepos=-1;
  104890. v->sequence=-1;
  104891. v->eofflag=0;
  104892. ((private_state *)(v->backend_state))->sample_count=-1;
  104893. return(0);
  104894. }
  104895. int vorbis_synthesis_init(vorbis_dsp_state *v,vorbis_info *vi){
  104896. if(_vds_shared_init(v,vi,0)) return 1;
  104897. vorbis_synthesis_restart(v);
  104898. return 0;
  104899. }
  104900. /* Unlike in analysis, the window is only partially applied for each
  104901. block. The time domain envelope is not yet handled at the point of
  104902. calling (as it relies on the previous block). */
  104903. int vorbis_synthesis_blockin(vorbis_dsp_state *v,vorbis_block *vb){
  104904. vorbis_info *vi=v->vi;
  104905. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  104906. private_state *b=(private_state*)v->backend_state;
  104907. int hs=ci->halfrate_flag;
  104908. int i,j;
  104909. if(!vb)return(OV_EINVAL);
  104910. if(v->pcm_current>v->pcm_returned && v->pcm_returned!=-1)return(OV_EINVAL);
  104911. v->lW=v->W;
  104912. v->W=vb->W;
  104913. v->nW=-1;
  104914. if((v->sequence==-1)||
  104915. (v->sequence+1 != vb->sequence)){
  104916. v->granulepos=-1; /* out of sequence; lose count */
  104917. b->sample_count=-1;
  104918. }
  104919. v->sequence=vb->sequence;
  104920. if(vb->pcm){ /* no pcm to process if vorbis_synthesis_trackonly
  104921. was called on block */
  104922. int n=ci->blocksizes[v->W]>>(hs+1);
  104923. int n0=ci->blocksizes[0]>>(hs+1);
  104924. int n1=ci->blocksizes[1]>>(hs+1);
  104925. int thisCenter;
  104926. int prevCenter;
  104927. v->glue_bits+=vb->glue_bits;
  104928. v->time_bits+=vb->time_bits;
  104929. v->floor_bits+=vb->floor_bits;
  104930. v->res_bits+=vb->res_bits;
  104931. if(v->centerW){
  104932. thisCenter=n1;
  104933. prevCenter=0;
  104934. }else{
  104935. thisCenter=0;
  104936. prevCenter=n1;
  104937. }
  104938. /* v->pcm is now used like a two-stage double buffer. We don't want
  104939. to have to constantly shift *or* adjust memory usage. Don't
  104940. accept a new block until the old is shifted out */
  104941. for(j=0;j<vi->channels;j++){
  104942. /* the overlap/add section */
  104943. if(v->lW){
  104944. if(v->W){
  104945. /* large/large */
  104946. float *w=_vorbis_window_get(b->window[1]-hs);
  104947. float *pcm=v->pcm[j]+prevCenter;
  104948. float *p=vb->pcm[j];
  104949. for(i=0;i<n1;i++)
  104950. pcm[i]=pcm[i]*w[n1-i-1] + p[i]*w[i];
  104951. }else{
  104952. /* large/small */
  104953. float *w=_vorbis_window_get(b->window[0]-hs);
  104954. float *pcm=v->pcm[j]+prevCenter+n1/2-n0/2;
  104955. float *p=vb->pcm[j];
  104956. for(i=0;i<n0;i++)
  104957. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  104958. }
  104959. }else{
  104960. if(v->W){
  104961. /* small/large */
  104962. float *w=_vorbis_window_get(b->window[0]-hs);
  104963. float *pcm=v->pcm[j]+prevCenter;
  104964. float *p=vb->pcm[j]+n1/2-n0/2;
  104965. for(i=0;i<n0;i++)
  104966. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  104967. for(;i<n1/2+n0/2;i++)
  104968. pcm[i]=p[i];
  104969. }else{
  104970. /* small/small */
  104971. float *w=_vorbis_window_get(b->window[0]-hs);
  104972. float *pcm=v->pcm[j]+prevCenter;
  104973. float *p=vb->pcm[j];
  104974. for(i=0;i<n0;i++)
  104975. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  104976. }
  104977. }
  104978. /* the copy section */
  104979. {
  104980. float *pcm=v->pcm[j]+thisCenter;
  104981. float *p=vb->pcm[j]+n;
  104982. for(i=0;i<n;i++)
  104983. pcm[i]=p[i];
  104984. }
  104985. }
  104986. if(v->centerW)
  104987. v->centerW=0;
  104988. else
  104989. v->centerW=n1;
  104990. /* deal with initial packet state; we do this using the explicit
  104991. pcm_returned==-1 flag otherwise we're sensitive to first block
  104992. being short or long */
  104993. if(v->pcm_returned==-1){
  104994. v->pcm_returned=thisCenter;
  104995. v->pcm_current=thisCenter;
  104996. }else{
  104997. v->pcm_returned=prevCenter;
  104998. v->pcm_current=prevCenter+
  104999. ((ci->blocksizes[v->lW]/4+
  105000. ci->blocksizes[v->W]/4)>>hs);
  105001. }
  105002. }
  105003. /* track the frame number... This is for convenience, but also
  105004. making sure our last packet doesn't end with added padding. If
  105005. the last packet is partial, the number of samples we'll have to
  105006. return will be past the vb->granulepos.
  105007. This is not foolproof! It will be confused if we begin
  105008. decoding at the last page after a seek or hole. In that case,
  105009. we don't have a starting point to judge where the last frame
  105010. is. For this reason, vorbisfile will always try to make sure
  105011. it reads the last two marked pages in proper sequence */
  105012. if(b->sample_count==-1){
  105013. b->sample_count=0;
  105014. }else{
  105015. b->sample_count+=ci->blocksizes[v->lW]/4+ci->blocksizes[v->W]/4;
  105016. }
  105017. if(v->granulepos==-1){
  105018. if(vb->granulepos!=-1){ /* only set if we have a position to set to */
  105019. v->granulepos=vb->granulepos;
  105020. /* is this a short page? */
  105021. if(b->sample_count>v->granulepos){
  105022. /* corner case; if this is both the first and last audio page,
  105023. then spec says the end is cut, not beginning */
  105024. if(vb->eofflag){
  105025. /* trim the end */
  105026. /* no preceeding granulepos; assume we started at zero (we'd
  105027. have to in a short single-page stream) */
  105028. /* granulepos could be -1 due to a seek, but that would result
  105029. in a long count, not short count */
  105030. v->pcm_current-=(b->sample_count-v->granulepos)>>hs;
  105031. }else{
  105032. /* trim the beginning */
  105033. v->pcm_returned+=(b->sample_count-v->granulepos)>>hs;
  105034. if(v->pcm_returned>v->pcm_current)
  105035. v->pcm_returned=v->pcm_current;
  105036. }
  105037. }
  105038. }
  105039. }else{
  105040. v->granulepos+=ci->blocksizes[v->lW]/4+ci->blocksizes[v->W]/4;
  105041. if(vb->granulepos!=-1 && v->granulepos!=vb->granulepos){
  105042. if(v->granulepos>vb->granulepos){
  105043. long extra=v->granulepos-vb->granulepos;
  105044. if(extra)
  105045. if(vb->eofflag){
  105046. /* partial last frame. Strip the extra samples off */
  105047. v->pcm_current-=extra>>hs;
  105048. } /* else {Shouldn't happen *unless* the bitstream is out of
  105049. spec. Either way, believe the bitstream } */
  105050. } /* else {Shouldn't happen *unless* the bitstream is out of
  105051. spec. Either way, believe the bitstream } */
  105052. v->granulepos=vb->granulepos;
  105053. }
  105054. }
  105055. /* Update, cleanup */
  105056. if(vb->eofflag)v->eofflag=1;
  105057. return(0);
  105058. }
  105059. /* pcm==NULL indicates we just want the pending samples, no more */
  105060. int vorbis_synthesis_pcmout(vorbis_dsp_state *v,float ***pcm){
  105061. vorbis_info *vi=v->vi;
  105062. if(v->pcm_returned>-1 && v->pcm_returned<v->pcm_current){
  105063. if(pcm){
  105064. int i;
  105065. for(i=0;i<vi->channels;i++)
  105066. v->pcmret[i]=v->pcm[i]+v->pcm_returned;
  105067. *pcm=v->pcmret;
  105068. }
  105069. return(v->pcm_current-v->pcm_returned);
  105070. }
  105071. return(0);
  105072. }
  105073. int vorbis_synthesis_read(vorbis_dsp_state *v,int n){
  105074. if(n && v->pcm_returned+n>v->pcm_current)return(OV_EINVAL);
  105075. v->pcm_returned+=n;
  105076. return(0);
  105077. }
  105078. /* intended for use with a specific vorbisfile feature; we want access
  105079. to the [usually synthetic/postextrapolated] buffer and lapping at
  105080. the end of a decode cycle, specifically, a half-short-block worth.
  105081. This funtion works like pcmout above, except it will also expose
  105082. this implicit buffer data not normally decoded. */
  105083. int vorbis_synthesis_lapout(vorbis_dsp_state *v,float ***pcm){
  105084. vorbis_info *vi=v->vi;
  105085. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  105086. int hs=ci->halfrate_flag;
  105087. int n=ci->blocksizes[v->W]>>(hs+1);
  105088. int n0=ci->blocksizes[0]>>(hs+1);
  105089. int n1=ci->blocksizes[1]>>(hs+1);
  105090. int i,j;
  105091. if(v->pcm_returned<0)return 0;
  105092. /* our returned data ends at pcm_returned; because the synthesis pcm
  105093. buffer is a two-fragment ring, that means our data block may be
  105094. fragmented by buffering, wrapping or a short block not filling
  105095. out a buffer. To simplify things, we unfragment if it's at all
  105096. possibly needed. Otherwise, we'd need to call lapout more than
  105097. once as well as hold additional dsp state. Opt for
  105098. simplicity. */
  105099. /* centerW was advanced by blockin; it would be the center of the
  105100. *next* block */
  105101. if(v->centerW==n1){
  105102. /* the data buffer wraps; swap the halves */
  105103. /* slow, sure, small */
  105104. for(j=0;j<vi->channels;j++){
  105105. float *p=v->pcm[j];
  105106. for(i=0;i<n1;i++){
  105107. float temp=p[i];
  105108. p[i]=p[i+n1];
  105109. p[i+n1]=temp;
  105110. }
  105111. }
  105112. v->pcm_current-=n1;
  105113. v->pcm_returned-=n1;
  105114. v->centerW=0;
  105115. }
  105116. /* solidify buffer into contiguous space */
  105117. if((v->lW^v->W)==1){
  105118. /* long/short or short/long */
  105119. for(j=0;j<vi->channels;j++){
  105120. float *s=v->pcm[j];
  105121. float *d=v->pcm[j]+(n1-n0)/2;
  105122. for(i=(n1+n0)/2-1;i>=0;--i)
  105123. d[i]=s[i];
  105124. }
  105125. v->pcm_returned+=(n1-n0)/2;
  105126. v->pcm_current+=(n1-n0)/2;
  105127. }else{
  105128. if(v->lW==0){
  105129. /* short/short */
  105130. for(j=0;j<vi->channels;j++){
  105131. float *s=v->pcm[j];
  105132. float *d=v->pcm[j]+n1-n0;
  105133. for(i=n0-1;i>=0;--i)
  105134. d[i]=s[i];
  105135. }
  105136. v->pcm_returned+=n1-n0;
  105137. v->pcm_current+=n1-n0;
  105138. }
  105139. }
  105140. if(pcm){
  105141. int i;
  105142. for(i=0;i<vi->channels;i++)
  105143. v->pcmret[i]=v->pcm[i]+v->pcm_returned;
  105144. *pcm=v->pcmret;
  105145. }
  105146. return(n1+n-v->pcm_returned);
  105147. }
  105148. float *vorbis_window(vorbis_dsp_state *v,int W){
  105149. vorbis_info *vi=v->vi;
  105150. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  105151. int hs=ci->halfrate_flag;
  105152. private_state *b=(private_state*)v->backend_state;
  105153. if(b->window[W]-1<0)return NULL;
  105154. return _vorbis_window_get(b->window[W]-hs);
  105155. }
  105156. #endif
  105157. /********* End of inlined file: block.c *********/
  105158. /********* Start of inlined file: codebook.c *********/
  105159. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  105160. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  105161. // tasks..
  105162. #ifdef _MSC_VER
  105163. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  105164. #endif
  105165. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  105166. #if JUCE_USE_OGGVORBIS
  105167. #include <stdlib.h>
  105168. #include <string.h>
  105169. #include <math.h>
  105170. /* packs the given codebook into the bitstream **************************/
  105171. int vorbis_staticbook_pack(const static_codebook *c,oggpack_buffer *opb){
  105172. long i,j;
  105173. int ordered=0;
  105174. /* first the basic parameters */
  105175. oggpack_write(opb,0x564342,24);
  105176. oggpack_write(opb,c->dim,16);
  105177. oggpack_write(opb,c->entries,24);
  105178. /* pack the codewords. There are two packings; length ordered and
  105179. length random. Decide between the two now. */
  105180. for(i=1;i<c->entries;i++)
  105181. if(c->lengthlist[i-1]==0 || c->lengthlist[i]<c->lengthlist[i-1])break;
  105182. if(i==c->entries)ordered=1;
  105183. if(ordered){
  105184. /* length ordered. We only need to say how many codewords of
  105185. each length. The actual codewords are generated
  105186. deterministically */
  105187. long count=0;
  105188. oggpack_write(opb,1,1); /* ordered */
  105189. oggpack_write(opb,c->lengthlist[0]-1,5); /* 1 to 32 */
  105190. for(i=1;i<c->entries;i++){
  105191. long thisx=c->lengthlist[i];
  105192. long last=c->lengthlist[i-1];
  105193. if(thisx>last){
  105194. for(j=last;j<thisx;j++){
  105195. oggpack_write(opb,i-count,_ilog(c->entries-count));
  105196. count=i;
  105197. }
  105198. }
  105199. }
  105200. oggpack_write(opb,i-count,_ilog(c->entries-count));
  105201. }else{
  105202. /* length random. Again, we don't code the codeword itself, just
  105203. the length. This time, though, we have to encode each length */
  105204. oggpack_write(opb,0,1); /* unordered */
  105205. /* algortihmic mapping has use for 'unused entries', which we tag
  105206. here. The algorithmic mapping happens as usual, but the unused
  105207. entry has no codeword. */
  105208. for(i=0;i<c->entries;i++)
  105209. if(c->lengthlist[i]==0)break;
  105210. if(i==c->entries){
  105211. oggpack_write(opb,0,1); /* no unused entries */
  105212. for(i=0;i<c->entries;i++)
  105213. oggpack_write(opb,c->lengthlist[i]-1,5);
  105214. }else{
  105215. oggpack_write(opb,1,1); /* we have unused entries; thus we tag */
  105216. for(i=0;i<c->entries;i++){
  105217. if(c->lengthlist[i]==0){
  105218. oggpack_write(opb,0,1);
  105219. }else{
  105220. oggpack_write(opb,1,1);
  105221. oggpack_write(opb,c->lengthlist[i]-1,5);
  105222. }
  105223. }
  105224. }
  105225. }
  105226. /* is the entry number the desired return value, or do we have a
  105227. mapping? If we have a mapping, what type? */
  105228. oggpack_write(opb,c->maptype,4);
  105229. switch(c->maptype){
  105230. case 0:
  105231. /* no mapping */
  105232. break;
  105233. case 1:case 2:
  105234. /* implicitly populated value mapping */
  105235. /* explicitly populated value mapping */
  105236. if(!c->quantlist){
  105237. /* no quantlist? error */
  105238. return(-1);
  105239. }
  105240. /* values that define the dequantization */
  105241. oggpack_write(opb,c->q_min,32);
  105242. oggpack_write(opb,c->q_delta,32);
  105243. oggpack_write(opb,c->q_quant-1,4);
  105244. oggpack_write(opb,c->q_sequencep,1);
  105245. {
  105246. int quantvals;
  105247. switch(c->maptype){
  105248. case 1:
  105249. /* a single column of (c->entries/c->dim) quantized values for
  105250. building a full value list algorithmically (square lattice) */
  105251. quantvals=_book_maptype1_quantvals(c);
  105252. break;
  105253. case 2:
  105254. /* every value (c->entries*c->dim total) specified explicitly */
  105255. quantvals=c->entries*c->dim;
  105256. break;
  105257. default: /* NOT_REACHABLE */
  105258. quantvals=-1;
  105259. }
  105260. /* quantized values */
  105261. for(i=0;i<quantvals;i++)
  105262. oggpack_write(opb,labs(c->quantlist[i]),c->q_quant);
  105263. }
  105264. break;
  105265. default:
  105266. /* error case; we don't have any other map types now */
  105267. return(-1);
  105268. }
  105269. return(0);
  105270. }
  105271. /* unpacks a codebook from the packet buffer into the codebook struct,
  105272. readies the codebook auxiliary structures for decode *************/
  105273. int vorbis_staticbook_unpack(oggpack_buffer *opb,static_codebook *s){
  105274. long i,j;
  105275. memset(s,0,sizeof(*s));
  105276. s->allocedp=1;
  105277. /* make sure alignment is correct */
  105278. if(oggpack_read(opb,24)!=0x564342)goto _eofout;
  105279. /* first the basic parameters */
  105280. s->dim=oggpack_read(opb,16);
  105281. s->entries=oggpack_read(opb,24);
  105282. if(s->entries==-1)goto _eofout;
  105283. /* codeword ordering.... length ordered or unordered? */
  105284. switch((int)oggpack_read(opb,1)){
  105285. case 0:
  105286. /* unordered */
  105287. s->lengthlist=(long*)_ogg_malloc(sizeof(*s->lengthlist)*s->entries);
  105288. /* allocated but unused entries? */
  105289. if(oggpack_read(opb,1)){
  105290. /* yes, unused entries */
  105291. for(i=0;i<s->entries;i++){
  105292. if(oggpack_read(opb,1)){
  105293. long num=oggpack_read(opb,5);
  105294. if(num==-1)goto _eofout;
  105295. s->lengthlist[i]=num+1;
  105296. }else
  105297. s->lengthlist[i]=0;
  105298. }
  105299. }else{
  105300. /* all entries used; no tagging */
  105301. for(i=0;i<s->entries;i++){
  105302. long num=oggpack_read(opb,5);
  105303. if(num==-1)goto _eofout;
  105304. s->lengthlist[i]=num+1;
  105305. }
  105306. }
  105307. break;
  105308. case 1:
  105309. /* ordered */
  105310. {
  105311. long length=oggpack_read(opb,5)+1;
  105312. s->lengthlist=(long*)_ogg_malloc(sizeof(*s->lengthlist)*s->entries);
  105313. for(i=0;i<s->entries;){
  105314. long num=oggpack_read(opb,_ilog(s->entries-i));
  105315. if(num==-1)goto _eofout;
  105316. for(j=0;j<num && i<s->entries;j++,i++)
  105317. s->lengthlist[i]=length;
  105318. length++;
  105319. }
  105320. }
  105321. break;
  105322. default:
  105323. /* EOF */
  105324. return(-1);
  105325. }
  105326. /* Do we have a mapping to unpack? */
  105327. switch((s->maptype=oggpack_read(opb,4))){
  105328. case 0:
  105329. /* no mapping */
  105330. break;
  105331. case 1: case 2:
  105332. /* implicitly populated value mapping */
  105333. /* explicitly populated value mapping */
  105334. s->q_min=oggpack_read(opb,32);
  105335. s->q_delta=oggpack_read(opb,32);
  105336. s->q_quant=oggpack_read(opb,4)+1;
  105337. s->q_sequencep=oggpack_read(opb,1);
  105338. {
  105339. int quantvals=0;
  105340. switch(s->maptype){
  105341. case 1:
  105342. quantvals=_book_maptype1_quantvals(s);
  105343. break;
  105344. case 2:
  105345. quantvals=s->entries*s->dim;
  105346. break;
  105347. }
  105348. /* quantized values */
  105349. s->quantlist=(long*)_ogg_malloc(sizeof(*s->quantlist)*quantvals);
  105350. for(i=0;i<quantvals;i++)
  105351. s->quantlist[i]=oggpack_read(opb,s->q_quant);
  105352. if(quantvals&&s->quantlist[quantvals-1]==-1)goto _eofout;
  105353. }
  105354. break;
  105355. default:
  105356. goto _errout;
  105357. }
  105358. /* all set */
  105359. return(0);
  105360. _errout:
  105361. _eofout:
  105362. vorbis_staticbook_clear(s);
  105363. return(-1);
  105364. }
  105365. /* returns the number of bits ************************************************/
  105366. int vorbis_book_encode(codebook *book, int a, oggpack_buffer *b){
  105367. oggpack_write(b,book->codelist[a],book->c->lengthlist[a]);
  105368. return(book->c->lengthlist[a]);
  105369. }
  105370. /* One the encode side, our vector writers are each designed for a
  105371. specific purpose, and the encoder is not flexible without modification:
  105372. The LSP vector coder uses a single stage nearest-match with no
  105373. interleave, so no step and no error return. This is specced by floor0
  105374. and doesn't change.
  105375. Residue0 encoding interleaves, uses multiple stages, and each stage
  105376. peels of a specific amount of resolution from a lattice (thus we want
  105377. to match by threshold, not nearest match). Residue doesn't *have* to
  105378. be encoded that way, but to change it, one will need to add more
  105379. infrastructure on the encode side (decode side is specced and simpler) */
  105380. /* floor0 LSP (single stage, non interleaved, nearest match) */
  105381. /* returns entry number and *modifies a* to the quantization value *****/
  105382. int vorbis_book_errorv(codebook *book,float *a){
  105383. int dim=book->dim,k;
  105384. int best=_best(book,a,1);
  105385. for(k=0;k<dim;k++)
  105386. a[k]=(book->valuelist+best*dim)[k];
  105387. return(best);
  105388. }
  105389. /* returns the number of bits and *modifies a* to the quantization value *****/
  105390. int vorbis_book_encodev(codebook *book,int best,float *a,oggpack_buffer *b){
  105391. int k,dim=book->dim;
  105392. for(k=0;k<dim;k++)
  105393. a[k]=(book->valuelist+best*dim)[k];
  105394. return(vorbis_book_encode(book,best,b));
  105395. }
  105396. /* the 'eliminate the decode tree' optimization actually requires the
  105397. codewords to be MSb first, not LSb. This is an annoying inelegancy
  105398. (and one of the first places where carefully thought out design
  105399. turned out to be wrong; Vorbis II and future Ogg codecs should go
  105400. to an MSb bitpacker), but not actually the huge hit it appears to
  105401. be. The first-stage decode table catches most words so that
  105402. bitreverse is not in the main execution path. */
  105403. STIN long decode_packed_entry_number(codebook *book, oggpack_buffer *b){
  105404. int read=book->dec_maxlength;
  105405. long lo,hi;
  105406. long lok = oggpack_look(b,book->dec_firsttablen);
  105407. if (lok >= 0) {
  105408. long entry = book->dec_firsttable[lok];
  105409. if(entry&0x80000000UL){
  105410. lo=(entry>>15)&0x7fff;
  105411. hi=book->used_entries-(entry&0x7fff);
  105412. }else{
  105413. oggpack_adv(b, book->dec_codelengths[entry-1]);
  105414. return(entry-1);
  105415. }
  105416. }else{
  105417. lo=0;
  105418. hi=book->used_entries;
  105419. }
  105420. lok = oggpack_look(b, read);
  105421. while(lok<0 && read>1)
  105422. lok = oggpack_look(b, --read);
  105423. if(lok<0)return -1;
  105424. /* bisect search for the codeword in the ordered list */
  105425. {
  105426. ogg_uint32_t testword=bitreverse((ogg_uint32_t)lok);
  105427. while(hi-lo>1){
  105428. long p=(hi-lo)>>1;
  105429. long test=book->codelist[lo+p]>testword;
  105430. lo+=p&(test-1);
  105431. hi-=p&(-test);
  105432. }
  105433. if(book->dec_codelengths[lo]<=read){
  105434. oggpack_adv(b, book->dec_codelengths[lo]);
  105435. return(lo);
  105436. }
  105437. }
  105438. oggpack_adv(b, read);
  105439. return(-1);
  105440. }
  105441. /* Decode side is specced and easier, because we don't need to find
  105442. matches using different criteria; we simply read and map. There are
  105443. two things we need to do 'depending':
  105444. We may need to support interleave. We don't really, but it's
  105445. convenient to do it here rather than rebuild the vector later.
  105446. Cascades may be additive or multiplicitive; this is not inherent in
  105447. the codebook, but set in the code using the codebook. Like
  105448. interleaving, it's easiest to do it here.
  105449. addmul==0 -> declarative (set the value)
  105450. addmul==1 -> additive
  105451. addmul==2 -> multiplicitive */
  105452. /* returns the [original, not compacted] entry number or -1 on eof *********/
  105453. long vorbis_book_decode(codebook *book, oggpack_buffer *b){
  105454. long packed_entry=decode_packed_entry_number(book,b);
  105455. if(packed_entry>=0)
  105456. return(book->dec_index[packed_entry]);
  105457. /* if there's no dec_index, the codebook unpacking isn't collapsed */
  105458. return(packed_entry);
  105459. }
  105460. /* returns 0 on OK or -1 on eof *************************************/
  105461. long vorbis_book_decodevs_add(codebook *book,float *a,oggpack_buffer *b,int n){
  105462. int step=n/book->dim;
  105463. long *entry = (long*)alloca(sizeof(*entry)*step);
  105464. float **t = (float**)alloca(sizeof(*t)*step);
  105465. int i,j,o;
  105466. for (i = 0; i < step; i++) {
  105467. entry[i]=decode_packed_entry_number(book,b);
  105468. if(entry[i]==-1)return(-1);
  105469. t[i] = book->valuelist+entry[i]*book->dim;
  105470. }
  105471. for(i=0,o=0;i<book->dim;i++,o+=step)
  105472. for (j=0;j<step;j++)
  105473. a[o+j]+=t[j][i];
  105474. return(0);
  105475. }
  105476. long vorbis_book_decodev_add(codebook *book,float *a,oggpack_buffer *b,int n){
  105477. int i,j,entry;
  105478. float *t;
  105479. if(book->dim>8){
  105480. for(i=0;i<n;){
  105481. entry = decode_packed_entry_number(book,b);
  105482. if(entry==-1)return(-1);
  105483. t = book->valuelist+entry*book->dim;
  105484. for (j=0;j<book->dim;)
  105485. a[i++]+=t[j++];
  105486. }
  105487. }else{
  105488. for(i=0;i<n;){
  105489. entry = decode_packed_entry_number(book,b);
  105490. if(entry==-1)return(-1);
  105491. t = book->valuelist+entry*book->dim;
  105492. j=0;
  105493. switch((int)book->dim){
  105494. case 8:
  105495. a[i++]+=t[j++];
  105496. case 7:
  105497. a[i++]+=t[j++];
  105498. case 6:
  105499. a[i++]+=t[j++];
  105500. case 5:
  105501. a[i++]+=t[j++];
  105502. case 4:
  105503. a[i++]+=t[j++];
  105504. case 3:
  105505. a[i++]+=t[j++];
  105506. case 2:
  105507. a[i++]+=t[j++];
  105508. case 1:
  105509. a[i++]+=t[j++];
  105510. case 0:
  105511. break;
  105512. }
  105513. }
  105514. }
  105515. return(0);
  105516. }
  105517. long vorbis_book_decodev_set(codebook *book,float *a,oggpack_buffer *b,int n){
  105518. int i,j,entry;
  105519. float *t;
  105520. for(i=0;i<n;){
  105521. entry = decode_packed_entry_number(book,b);
  105522. if(entry==-1)return(-1);
  105523. t = book->valuelist+entry*book->dim;
  105524. for (j=0;j<book->dim;)
  105525. a[i++]=t[j++];
  105526. }
  105527. return(0);
  105528. }
  105529. long vorbis_book_decodevv_add(codebook *book,float **a,long offset,int ch,
  105530. oggpack_buffer *b,int n){
  105531. long i,j,entry;
  105532. int chptr=0;
  105533. for(i=offset/ch;i<(offset+n)/ch;){
  105534. entry = decode_packed_entry_number(book,b);
  105535. if(entry==-1)return(-1);
  105536. {
  105537. const float *t = book->valuelist+entry*book->dim;
  105538. for (j=0;j<book->dim;j++){
  105539. a[chptr++][i]+=t[j];
  105540. if(chptr==ch){
  105541. chptr=0;
  105542. i++;
  105543. }
  105544. }
  105545. }
  105546. }
  105547. return(0);
  105548. }
  105549. #ifdef _V_SELFTEST
  105550. /* Simple enough; pack a few candidate codebooks, unpack them. Code a
  105551. number of vectors through (keeping track of the quantized values),
  105552. and decode using the unpacked book. quantized version of in should
  105553. exactly equal out */
  105554. #include <stdio.h>
  105555. #include "vorbis/book/lsp20_0.vqh"
  105556. #include "vorbis/book/res0a_13.vqh"
  105557. #define TESTSIZE 40
  105558. float test1[TESTSIZE]={
  105559. 0.105939f,
  105560. 0.215373f,
  105561. 0.429117f,
  105562. 0.587974f,
  105563. 0.181173f,
  105564. 0.296583f,
  105565. 0.515707f,
  105566. 0.715261f,
  105567. 0.162327f,
  105568. 0.263834f,
  105569. 0.342876f,
  105570. 0.406025f,
  105571. 0.103571f,
  105572. 0.223561f,
  105573. 0.368513f,
  105574. 0.540313f,
  105575. 0.136672f,
  105576. 0.395882f,
  105577. 0.587183f,
  105578. 0.652476f,
  105579. 0.114338f,
  105580. 0.417300f,
  105581. 0.525486f,
  105582. 0.698679f,
  105583. 0.147492f,
  105584. 0.324481f,
  105585. 0.643089f,
  105586. 0.757582f,
  105587. 0.139556f,
  105588. 0.215795f,
  105589. 0.324559f,
  105590. 0.399387f,
  105591. 0.120236f,
  105592. 0.267420f,
  105593. 0.446940f,
  105594. 0.608760f,
  105595. 0.115587f,
  105596. 0.287234f,
  105597. 0.571081f,
  105598. 0.708603f,
  105599. };
  105600. float test3[TESTSIZE]={
  105601. 0,1,-2,3,4,-5,6,7,8,9,
  105602. 8,-2,7,-1,4,6,8,3,1,-9,
  105603. 10,11,12,13,14,15,26,17,18,19,
  105604. 30,-25,-30,-1,-5,-32,4,3,-2,0};
  105605. static_codebook *testlist[]={&_vq_book_lsp20_0,
  105606. &_vq_book_res0a_13,NULL};
  105607. float *testvec[]={test1,test3};
  105608. int main(){
  105609. oggpack_buffer write;
  105610. oggpack_buffer read;
  105611. long ptr=0,i;
  105612. oggpack_writeinit(&write);
  105613. fprintf(stderr,"Testing codebook abstraction...:\n");
  105614. while(testlist[ptr]){
  105615. codebook c;
  105616. static_codebook s;
  105617. float *qv=alloca(sizeof(*qv)*TESTSIZE);
  105618. float *iv=alloca(sizeof(*iv)*TESTSIZE);
  105619. memcpy(qv,testvec[ptr],sizeof(*qv)*TESTSIZE);
  105620. memset(iv,0,sizeof(*iv)*TESTSIZE);
  105621. fprintf(stderr,"\tpacking/coding %ld... ",ptr);
  105622. /* pack the codebook, write the testvector */
  105623. oggpack_reset(&write);
  105624. vorbis_book_init_encode(&c,testlist[ptr]); /* get it into memory
  105625. we can write */
  105626. vorbis_staticbook_pack(testlist[ptr],&write);
  105627. fprintf(stderr,"Codebook size %ld bytes... ",oggpack_bytes(&write));
  105628. for(i=0;i<TESTSIZE;i+=c.dim){
  105629. int best=_best(&c,qv+i,1);
  105630. vorbis_book_encodev(&c,best,qv+i,&write);
  105631. }
  105632. vorbis_book_clear(&c);
  105633. fprintf(stderr,"OK.\n");
  105634. fprintf(stderr,"\tunpacking/decoding %ld... ",ptr);
  105635. /* transfer the write data to a read buffer and unpack/read */
  105636. oggpack_readinit(&read,oggpack_get_buffer(&write),oggpack_bytes(&write));
  105637. if(vorbis_staticbook_unpack(&read,&s)){
  105638. fprintf(stderr,"Error unpacking codebook.\n");
  105639. exit(1);
  105640. }
  105641. if(vorbis_book_init_decode(&c,&s)){
  105642. fprintf(stderr,"Error initializing codebook.\n");
  105643. exit(1);
  105644. }
  105645. for(i=0;i<TESTSIZE;i+=c.dim)
  105646. if(vorbis_book_decodev_set(&c,iv+i,&read,c.dim)==-1){
  105647. fprintf(stderr,"Error reading codebook test data (EOP).\n");
  105648. exit(1);
  105649. }
  105650. for(i=0;i<TESTSIZE;i++)
  105651. if(fabs(qv[i]-iv[i])>.000001){
  105652. fprintf(stderr,"read (%g) != written (%g) at position (%ld)\n",
  105653. iv[i],qv[i],i);
  105654. exit(1);
  105655. }
  105656. fprintf(stderr,"OK\n");
  105657. ptr++;
  105658. }
  105659. /* The above is the trivial stuff; now try unquantizing a log scale codebook */
  105660. exit(0);
  105661. }
  105662. #endif
  105663. #endif
  105664. /********* End of inlined file: codebook.c *********/
  105665. /********* Start of inlined file: envelope.c *********/
  105666. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  105667. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  105668. // tasks..
  105669. #ifdef _MSC_VER
  105670. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  105671. #endif
  105672. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  105673. #if JUCE_USE_OGGVORBIS
  105674. #include <stdlib.h>
  105675. #include <string.h>
  105676. #include <stdio.h>
  105677. #include <math.h>
  105678. void _ve_envelope_init(envelope_lookup *e,vorbis_info *vi){
  105679. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  105680. vorbis_info_psy_global *gi=&ci->psy_g_param;
  105681. int ch=vi->channels;
  105682. int i,j;
  105683. int n=e->winlength=128;
  105684. e->searchstep=64; /* not random */
  105685. e->minenergy=gi->preecho_minenergy;
  105686. e->ch=ch;
  105687. e->storage=128;
  105688. e->cursor=ci->blocksizes[1]/2;
  105689. e->mdct_win=(float*)_ogg_calloc(n,sizeof(*e->mdct_win));
  105690. mdct_init(&e->mdct,n);
  105691. for(i=0;i<n;i++){
  105692. e->mdct_win[i]=sin(i/(n-1.)*M_PI);
  105693. e->mdct_win[i]*=e->mdct_win[i];
  105694. }
  105695. /* magic follows */
  105696. e->band[0].begin=2; e->band[0].end=4;
  105697. e->band[1].begin=4; e->band[1].end=5;
  105698. e->band[2].begin=6; e->band[2].end=6;
  105699. e->band[3].begin=9; e->band[3].end=8;
  105700. e->band[4].begin=13; e->band[4].end=8;
  105701. e->band[5].begin=17; e->band[5].end=8;
  105702. e->band[6].begin=22; e->band[6].end=8;
  105703. for(j=0;j<VE_BANDS;j++){
  105704. n=e->band[j].end;
  105705. e->band[j].window=(float*)_ogg_malloc(n*sizeof(*e->band[0].window));
  105706. for(i=0;i<n;i++){
  105707. e->band[j].window[i]=sin((i+.5)/n*M_PI);
  105708. e->band[j].total+=e->band[j].window[i];
  105709. }
  105710. e->band[j].total=1./e->band[j].total;
  105711. }
  105712. e->filter=(envelope_filter_state*)_ogg_calloc(VE_BANDS*ch,sizeof(*e->filter));
  105713. e->mark=(int*)_ogg_calloc(e->storage,sizeof(*e->mark));
  105714. }
  105715. void _ve_envelope_clear(envelope_lookup *e){
  105716. int i;
  105717. mdct_clear(&e->mdct);
  105718. for(i=0;i<VE_BANDS;i++)
  105719. _ogg_free(e->band[i].window);
  105720. _ogg_free(e->mdct_win);
  105721. _ogg_free(e->filter);
  105722. _ogg_free(e->mark);
  105723. memset(e,0,sizeof(*e));
  105724. }
  105725. /* fairly straight threshhold-by-band based until we find something
  105726. that works better and isn't patented. */
  105727. static int _ve_amp(envelope_lookup *ve,
  105728. vorbis_info_psy_global *gi,
  105729. float *data,
  105730. envelope_band *bands,
  105731. envelope_filter_state *filters,
  105732. long pos){
  105733. long n=ve->winlength;
  105734. int ret=0;
  105735. long i,j;
  105736. float decay;
  105737. /* we want to have a 'minimum bar' for energy, else we're just
  105738. basing blocks on quantization noise that outweighs the signal
  105739. itself (for low power signals) */
  105740. float minV=ve->minenergy;
  105741. float *vec=(float*) alloca(n*sizeof(*vec));
  105742. /* stretch is used to gradually lengthen the number of windows
  105743. considered prevoius-to-potential-trigger */
  105744. int stretch=max(VE_MINSTRETCH,ve->stretch/2);
  105745. float penalty=gi->stretch_penalty-(ve->stretch/2-VE_MINSTRETCH);
  105746. if(penalty<0.f)penalty=0.f;
  105747. if(penalty>gi->stretch_penalty)penalty=gi->stretch_penalty;
  105748. /*_analysis_output_always("lpcm",seq2,data,n,0,0,
  105749. totalshift+pos*ve->searchstep);*/
  105750. /* window and transform */
  105751. for(i=0;i<n;i++)
  105752. vec[i]=data[i]*ve->mdct_win[i];
  105753. mdct_forward(&ve->mdct,vec,vec);
  105754. /*_analysis_output_always("mdct",seq2,vec,n/2,0,1,0); */
  105755. /* near-DC spreading function; this has nothing to do with
  105756. psychoacoustics, just sidelobe leakage and window size */
  105757. {
  105758. float temp=vec[0]*vec[0]+.7*vec[1]*vec[1]+.2*vec[2]*vec[2];
  105759. int ptr=filters->nearptr;
  105760. /* the accumulation is regularly refreshed from scratch to avoid
  105761. floating point creep */
  105762. if(ptr==0){
  105763. decay=filters->nearDC_acc=filters->nearDC_partialacc+temp;
  105764. filters->nearDC_partialacc=temp;
  105765. }else{
  105766. decay=filters->nearDC_acc+=temp;
  105767. filters->nearDC_partialacc+=temp;
  105768. }
  105769. filters->nearDC_acc-=filters->nearDC[ptr];
  105770. filters->nearDC[ptr]=temp;
  105771. decay*=(1./(VE_NEARDC+1));
  105772. filters->nearptr++;
  105773. if(filters->nearptr>=VE_NEARDC)filters->nearptr=0;
  105774. decay=todB(&decay)*.5-15.f;
  105775. }
  105776. /* perform spreading and limiting, also smooth the spectrum. yes,
  105777. the MDCT results in all real coefficients, but it still *behaves*
  105778. like real/imaginary pairs */
  105779. for(i=0;i<n/2;i+=2){
  105780. float val=vec[i]*vec[i]+vec[i+1]*vec[i+1];
  105781. val=todB(&val)*.5f;
  105782. if(val<decay)val=decay;
  105783. if(val<minV)val=minV;
  105784. vec[i>>1]=val;
  105785. decay-=8.;
  105786. }
  105787. /*_analysis_output_always("spread",seq2++,vec,n/4,0,0,0);*/
  105788. /* perform preecho/postecho triggering by band */
  105789. for(j=0;j<VE_BANDS;j++){
  105790. float acc=0.;
  105791. float valmax,valmin;
  105792. /* accumulate amplitude */
  105793. for(i=0;i<bands[j].end;i++)
  105794. acc+=vec[i+bands[j].begin]*bands[j].window[i];
  105795. acc*=bands[j].total;
  105796. /* convert amplitude to delta */
  105797. {
  105798. int p,thisx=filters[j].ampptr;
  105799. float postmax,postmin,premax=-99999.f,premin=99999.f;
  105800. p=thisx;
  105801. p--;
  105802. if(p<0)p+=VE_AMP;
  105803. postmax=max(acc,filters[j].ampbuf[p]);
  105804. postmin=min(acc,filters[j].ampbuf[p]);
  105805. for(i=0;i<stretch;i++){
  105806. p--;
  105807. if(p<0)p+=VE_AMP;
  105808. premax=max(premax,filters[j].ampbuf[p]);
  105809. premin=min(premin,filters[j].ampbuf[p]);
  105810. }
  105811. valmin=postmin-premin;
  105812. valmax=postmax-premax;
  105813. /*filters[j].markers[pos]=valmax;*/
  105814. filters[j].ampbuf[thisx]=acc;
  105815. filters[j].ampptr++;
  105816. if(filters[j].ampptr>=VE_AMP)filters[j].ampptr=0;
  105817. }
  105818. /* look at min/max, decide trigger */
  105819. if(valmax>gi->preecho_thresh[j]+penalty){
  105820. ret|=1;
  105821. ret|=4;
  105822. }
  105823. if(valmin<gi->postecho_thresh[j]-penalty)ret|=2;
  105824. }
  105825. return(ret);
  105826. }
  105827. #if 0
  105828. static int seq=0;
  105829. static ogg_int64_t totalshift=-1024;
  105830. #endif
  105831. long _ve_envelope_search(vorbis_dsp_state *v){
  105832. vorbis_info *vi=v->vi;
  105833. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  105834. vorbis_info_psy_global *gi=&ci->psy_g_param;
  105835. envelope_lookup *ve=((private_state *)(v->backend_state))->ve;
  105836. long i,j;
  105837. int first=ve->current/ve->searchstep;
  105838. int last=v->pcm_current/ve->searchstep-VE_WIN;
  105839. if(first<0)first=0;
  105840. /* make sure we have enough storage to match the PCM */
  105841. if(last+VE_WIN+VE_POST>ve->storage){
  105842. ve->storage=last+VE_WIN+VE_POST; /* be sure */
  105843. ve->mark=(int*)_ogg_realloc(ve->mark,ve->storage*sizeof(*ve->mark));
  105844. }
  105845. for(j=first;j<last;j++){
  105846. int ret=0;
  105847. ve->stretch++;
  105848. if(ve->stretch>VE_MAXSTRETCH*2)
  105849. ve->stretch=VE_MAXSTRETCH*2;
  105850. for(i=0;i<ve->ch;i++){
  105851. float *pcm=v->pcm[i]+ve->searchstep*(j);
  105852. ret|=_ve_amp(ve,gi,pcm,ve->band,ve->filter+i*VE_BANDS,j);
  105853. }
  105854. ve->mark[j+VE_POST]=0;
  105855. if(ret&1){
  105856. ve->mark[j]=1;
  105857. ve->mark[j+1]=1;
  105858. }
  105859. if(ret&2){
  105860. ve->mark[j]=1;
  105861. if(j>0)ve->mark[j-1]=1;
  105862. }
  105863. if(ret&4)ve->stretch=-1;
  105864. }
  105865. ve->current=last*ve->searchstep;
  105866. {
  105867. long centerW=v->centerW;
  105868. long testW=
  105869. centerW+
  105870. ci->blocksizes[v->W]/4+
  105871. ci->blocksizes[1]/2+
  105872. ci->blocksizes[0]/4;
  105873. j=ve->cursor;
  105874. while(j<ve->current-(ve->searchstep)){/* account for postecho
  105875. working back one window */
  105876. if(j>=testW)return(1);
  105877. ve->cursor=j;
  105878. if(ve->mark[j/ve->searchstep]){
  105879. if(j>centerW){
  105880. #if 0
  105881. if(j>ve->curmark){
  105882. float *marker=alloca(v->pcm_current*sizeof(*marker));
  105883. int l,m;
  105884. memset(marker,0,sizeof(*marker)*v->pcm_current);
  105885. fprintf(stderr,"mark! seq=%d, cursor:%fs time:%fs\n",
  105886. seq,
  105887. (totalshift+ve->cursor)/44100.,
  105888. (totalshift+j)/44100.);
  105889. _analysis_output_always("pcmL",seq,v->pcm[0],v->pcm_current,0,0,totalshift);
  105890. _analysis_output_always("pcmR",seq,v->pcm[1],v->pcm_current,0,0,totalshift);
  105891. _analysis_output_always("markL",seq,v->pcm[0],j,0,0,totalshift);
  105892. _analysis_output_always("markR",seq,v->pcm[1],j,0,0,totalshift);
  105893. for(m=0;m<VE_BANDS;m++){
  105894. char buf[80];
  105895. sprintf(buf,"delL%d",m);
  105896. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->filter[m].markers[l]*.1;
  105897. _analysis_output_always(buf,seq,marker,v->pcm_current,0,0,totalshift);
  105898. }
  105899. for(m=0;m<VE_BANDS;m++){
  105900. char buf[80];
  105901. sprintf(buf,"delR%d",m);
  105902. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->filter[m+VE_BANDS].markers[l]*.1;
  105903. _analysis_output_always(buf,seq,marker,v->pcm_current,0,0,totalshift);
  105904. }
  105905. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->mark[l]*.4;
  105906. _analysis_output_always("mark",seq,marker,v->pcm_current,0,0,totalshift);
  105907. seq++;
  105908. }
  105909. #endif
  105910. ve->curmark=j;
  105911. if(j>=testW)return(1);
  105912. return(0);
  105913. }
  105914. }
  105915. j+=ve->searchstep;
  105916. }
  105917. }
  105918. return(-1);
  105919. }
  105920. int _ve_envelope_mark(vorbis_dsp_state *v){
  105921. envelope_lookup *ve=((private_state *)(v->backend_state))->ve;
  105922. vorbis_info *vi=v->vi;
  105923. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  105924. long centerW=v->centerW;
  105925. long beginW=centerW-ci->blocksizes[v->W]/4;
  105926. long endW=centerW+ci->blocksizes[v->W]/4;
  105927. if(v->W){
  105928. beginW-=ci->blocksizes[v->lW]/4;
  105929. endW+=ci->blocksizes[v->nW]/4;
  105930. }else{
  105931. beginW-=ci->blocksizes[0]/4;
  105932. endW+=ci->blocksizes[0]/4;
  105933. }
  105934. if(ve->curmark>=beginW && ve->curmark<endW)return(1);
  105935. {
  105936. long first=beginW/ve->searchstep;
  105937. long last=endW/ve->searchstep;
  105938. long i;
  105939. for(i=first;i<last;i++)
  105940. if(ve->mark[i])return(1);
  105941. }
  105942. return(0);
  105943. }
  105944. void _ve_envelope_shift(envelope_lookup *e,long shift){
  105945. int smallsize=e->current/e->searchstep+VE_POST; /* adjust for placing marks
  105946. ahead of ve->current */
  105947. int smallshift=shift/e->searchstep;
  105948. memmove(e->mark,e->mark+smallshift,(smallsize-smallshift)*sizeof(*e->mark));
  105949. #if 0
  105950. for(i=0;i<VE_BANDS*e->ch;i++)
  105951. memmove(e->filter[i].markers,
  105952. e->filter[i].markers+smallshift,
  105953. (1024-smallshift)*sizeof(*(*e->filter).markers));
  105954. totalshift+=shift;
  105955. #endif
  105956. e->current-=shift;
  105957. if(e->curmark>=0)
  105958. e->curmark-=shift;
  105959. e->cursor-=shift;
  105960. }
  105961. #endif
  105962. /********* End of inlined file: envelope.c *********/
  105963. /********* Start of inlined file: floor0.c *********/
  105964. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  105965. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  105966. // tasks..
  105967. #ifdef _MSC_VER
  105968. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  105969. #endif
  105970. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  105971. #if JUCE_USE_OGGVORBIS
  105972. #include <stdlib.h>
  105973. #include <string.h>
  105974. #include <math.h>
  105975. /********* Start of inlined file: lsp.h *********/
  105976. #ifndef _V_LSP_H_
  105977. #define _V_LSP_H_
  105978. extern int vorbis_lpc_to_lsp(float *lpc,float *lsp,int m);
  105979. extern void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,
  105980. float *lsp,int m,
  105981. float amp,float ampoffset);
  105982. #endif
  105983. /********* End of inlined file: lsp.h *********/
  105984. #include <stdio.h>
  105985. typedef struct {
  105986. int ln;
  105987. int m;
  105988. int **linearmap;
  105989. int n[2];
  105990. vorbis_info_floor0 *vi;
  105991. long bits;
  105992. long frames;
  105993. } vorbis_look_floor0;
  105994. /***********************************************/
  105995. static void floor0_free_info(vorbis_info_floor *i){
  105996. vorbis_info_floor0 *info=(vorbis_info_floor0 *)i;
  105997. if(info){
  105998. memset(info,0,sizeof(*info));
  105999. _ogg_free(info);
  106000. }
  106001. }
  106002. static void floor0_free_look(vorbis_look_floor *i){
  106003. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  106004. if(look){
  106005. if(look->linearmap){
  106006. if(look->linearmap[0])_ogg_free(look->linearmap[0]);
  106007. if(look->linearmap[1])_ogg_free(look->linearmap[1]);
  106008. _ogg_free(look->linearmap);
  106009. }
  106010. memset(look,0,sizeof(*look));
  106011. _ogg_free(look);
  106012. }
  106013. }
  106014. static vorbis_info_floor *floor0_unpack (vorbis_info *vi,oggpack_buffer *opb){
  106015. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  106016. int j;
  106017. vorbis_info_floor0 *info=(vorbis_info_floor0*)_ogg_malloc(sizeof(*info));
  106018. info->order=oggpack_read(opb,8);
  106019. info->rate=oggpack_read(opb,16);
  106020. info->barkmap=oggpack_read(opb,16);
  106021. info->ampbits=oggpack_read(opb,6);
  106022. info->ampdB=oggpack_read(opb,8);
  106023. info->numbooks=oggpack_read(opb,4)+1;
  106024. if(info->order<1)goto err_out;
  106025. if(info->rate<1)goto err_out;
  106026. if(info->barkmap<1)goto err_out;
  106027. if(info->numbooks<1)goto err_out;
  106028. for(j=0;j<info->numbooks;j++){
  106029. info->books[j]=oggpack_read(opb,8);
  106030. if(info->books[j]<0 || info->books[j]>=ci->books)goto err_out;
  106031. }
  106032. return(info);
  106033. err_out:
  106034. floor0_free_info(info);
  106035. return(NULL);
  106036. }
  106037. /* initialize Bark scale and normalization lookups. We could do this
  106038. with static tables, but Vorbis allows a number of possible
  106039. combinations, so it's best to do it computationally.
  106040. The below is authoritative in terms of defining scale mapping.
  106041. Note that the scale depends on the sampling rate as well as the
  106042. linear block and mapping sizes */
  106043. static void floor0_map_lazy_init(vorbis_block *vb,
  106044. vorbis_info_floor *infoX,
  106045. vorbis_look_floor0 *look){
  106046. if(!look->linearmap[vb->W]){
  106047. vorbis_dsp_state *vd=vb->vd;
  106048. vorbis_info *vi=vd->vi;
  106049. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  106050. vorbis_info_floor0 *info=(vorbis_info_floor0 *)infoX;
  106051. int W=vb->W;
  106052. int n=ci->blocksizes[W]/2,j;
  106053. /* we choose a scaling constant so that:
  106054. floor(bark(rate/2-1)*C)=mapped-1
  106055. floor(bark(rate/2)*C)=mapped */
  106056. float scale=look->ln/toBARK(info->rate/2.f);
  106057. /* the mapping from a linear scale to a smaller bark scale is
  106058. straightforward. We do *not* make sure that the linear mapping
  106059. does not skip bark-scale bins; the decoder simply skips them and
  106060. the encoder may do what it wishes in filling them. They're
  106061. necessary in some mapping combinations to keep the scale spacing
  106062. accurate */
  106063. look->linearmap[W]=(int*)_ogg_malloc((n+1)*sizeof(**look->linearmap));
  106064. for(j=0;j<n;j++){
  106065. int val=floor( toBARK((info->rate/2.f)/n*j)
  106066. *scale); /* bark numbers represent band edges */
  106067. if(val>=look->ln)val=look->ln-1; /* guard against the approximation */
  106068. look->linearmap[W][j]=val;
  106069. }
  106070. look->linearmap[W][j]=-1;
  106071. look->n[W]=n;
  106072. }
  106073. }
  106074. static vorbis_look_floor *floor0_look(vorbis_dsp_state *vd,
  106075. vorbis_info_floor *i){
  106076. vorbis_info_floor0 *info=(vorbis_info_floor0*)i;
  106077. vorbis_look_floor0 *look=(vorbis_look_floor0*)_ogg_calloc(1,sizeof(*look));
  106078. look->m=info->order;
  106079. look->ln=info->barkmap;
  106080. look->vi=info;
  106081. look->linearmap=(int**)_ogg_calloc(2,sizeof(*look->linearmap));
  106082. return look;
  106083. }
  106084. static void *floor0_inverse1(vorbis_block *vb,vorbis_look_floor *i){
  106085. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  106086. vorbis_info_floor0 *info=look->vi;
  106087. int j,k;
  106088. int ampraw=oggpack_read(&vb->opb,info->ampbits);
  106089. if(ampraw>0){ /* also handles the -1 out of data case */
  106090. long maxval=(1<<info->ampbits)-1;
  106091. float amp=(float)ampraw/maxval*info->ampdB;
  106092. int booknum=oggpack_read(&vb->opb,_ilog(info->numbooks));
  106093. if(booknum!=-1 && booknum<info->numbooks){ /* be paranoid */
  106094. codec_setup_info *ci=(codec_setup_info *)vb->vd->vi->codec_setup;
  106095. codebook *b=ci->fullbooks+info->books[booknum];
  106096. float last=0.f;
  106097. /* the additional b->dim is a guard against any possible stack
  106098. smash; b->dim is provably more than we can overflow the
  106099. vector */
  106100. float *lsp=(float*)_vorbis_block_alloc(vb,sizeof(*lsp)*(look->m+b->dim+1));
  106101. for(j=0;j<look->m;j+=b->dim)
  106102. if(vorbis_book_decodev_set(b,lsp+j,&vb->opb,b->dim)==-1)goto eop;
  106103. for(j=0;j<look->m;){
  106104. for(k=0;k<b->dim;k++,j++)lsp[j]+=last;
  106105. last=lsp[j-1];
  106106. }
  106107. lsp[look->m]=amp;
  106108. return(lsp);
  106109. }
  106110. }
  106111. eop:
  106112. return(NULL);
  106113. }
  106114. static int floor0_inverse2(vorbis_block *vb,vorbis_look_floor *i,
  106115. void *memo,float *out){
  106116. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  106117. vorbis_info_floor0 *info=look->vi;
  106118. floor0_map_lazy_init(vb,info,look);
  106119. if(memo){
  106120. float *lsp=(float *)memo;
  106121. float amp=lsp[look->m];
  106122. /* take the coefficients back to a spectral envelope curve */
  106123. vorbis_lsp_to_curve(out,
  106124. look->linearmap[vb->W],
  106125. look->n[vb->W],
  106126. look->ln,
  106127. lsp,look->m,amp,(float)info->ampdB);
  106128. return(1);
  106129. }
  106130. memset(out,0,sizeof(*out)*look->n[vb->W]);
  106131. return(0);
  106132. }
  106133. /* export hooks */
  106134. vorbis_func_floor floor0_exportbundle={
  106135. NULL,&floor0_unpack,&floor0_look,&floor0_free_info,
  106136. &floor0_free_look,&floor0_inverse1,&floor0_inverse2
  106137. };
  106138. #endif
  106139. /********* End of inlined file: floor0.c *********/
  106140. /********* Start of inlined file: floor1.c *********/
  106141. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  106142. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  106143. // tasks..
  106144. #ifdef _MSC_VER
  106145. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  106146. #endif
  106147. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  106148. #if JUCE_USE_OGGVORBIS
  106149. #include <stdlib.h>
  106150. #include <string.h>
  106151. #include <math.h>
  106152. #include <stdio.h>
  106153. #define floor1_rangedB 140 /* floor 1 fixed at -140dB to 0dB range */
  106154. typedef struct {
  106155. int sorted_index[VIF_POSIT+2];
  106156. int forward_index[VIF_POSIT+2];
  106157. int reverse_index[VIF_POSIT+2];
  106158. int hineighbor[VIF_POSIT];
  106159. int loneighbor[VIF_POSIT];
  106160. int posts;
  106161. int n;
  106162. int quant_q;
  106163. vorbis_info_floor1 *vi;
  106164. long phrasebits;
  106165. long postbits;
  106166. long frames;
  106167. } vorbis_look_floor1;
  106168. typedef struct lsfit_acc{
  106169. long x0;
  106170. long x1;
  106171. long xa;
  106172. long ya;
  106173. long x2a;
  106174. long y2a;
  106175. long xya;
  106176. long an;
  106177. } lsfit_acc;
  106178. /***********************************************/
  106179. static void floor1_free_info(vorbis_info_floor *i){
  106180. vorbis_info_floor1 *info=(vorbis_info_floor1 *)i;
  106181. if(info){
  106182. memset(info,0,sizeof(*info));
  106183. _ogg_free(info);
  106184. }
  106185. }
  106186. static void floor1_free_look(vorbis_look_floor *i){
  106187. vorbis_look_floor1 *look=(vorbis_look_floor1 *)i;
  106188. if(look){
  106189. /*fprintf(stderr,"floor 1 bit usage %f:%f (%f total)\n",
  106190. (float)look->phrasebits/look->frames,
  106191. (float)look->postbits/look->frames,
  106192. (float)(look->postbits+look->phrasebits)/look->frames);*/
  106193. memset(look,0,sizeof(*look));
  106194. _ogg_free(look);
  106195. }
  106196. }
  106197. static void floor1_pack (vorbis_info_floor *i,oggpack_buffer *opb){
  106198. vorbis_info_floor1 *info=(vorbis_info_floor1 *)i;
  106199. int j,k;
  106200. int count=0;
  106201. int rangebits;
  106202. int maxposit=info->postlist[1];
  106203. int maxclass=-1;
  106204. /* save out partitions */
  106205. oggpack_write(opb,info->partitions,5); /* only 0 to 31 legal */
  106206. for(j=0;j<info->partitions;j++){
  106207. oggpack_write(opb,info->partitionclass[j],4); /* only 0 to 15 legal */
  106208. if(maxclass<info->partitionclass[j])maxclass=info->partitionclass[j];
  106209. }
  106210. /* save out partition classes */
  106211. for(j=0;j<maxclass+1;j++){
  106212. oggpack_write(opb,info->class_dim[j]-1,3); /* 1 to 8 */
  106213. oggpack_write(opb,info->class_subs[j],2); /* 0 to 3 */
  106214. if(info->class_subs[j])oggpack_write(opb,info->class_book[j],8);
  106215. for(k=0;k<(1<<info->class_subs[j]);k++)
  106216. oggpack_write(opb,info->class_subbook[j][k]+1,8);
  106217. }
  106218. /* save out the post list */
  106219. oggpack_write(opb,info->mult-1,2); /* only 1,2,3,4 legal now */
  106220. oggpack_write(opb,ilog2(maxposit),4);
  106221. rangebits=ilog2(maxposit);
  106222. for(j=0,k=0;j<info->partitions;j++){
  106223. count+=info->class_dim[info->partitionclass[j]];
  106224. for(;k<count;k++)
  106225. oggpack_write(opb,info->postlist[k+2],rangebits);
  106226. }
  106227. }
  106228. static vorbis_info_floor *floor1_unpack (vorbis_info *vi,oggpack_buffer *opb){
  106229. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  106230. int j,k,count=0,maxclass=-1,rangebits;
  106231. vorbis_info_floor1 *info=(vorbis_info_floor1*)_ogg_calloc(1,sizeof(*info));
  106232. /* read partitions */
  106233. info->partitions=oggpack_read(opb,5); /* only 0 to 31 legal */
  106234. for(j=0;j<info->partitions;j++){
  106235. info->partitionclass[j]=oggpack_read(opb,4); /* only 0 to 15 legal */
  106236. if(maxclass<info->partitionclass[j])maxclass=info->partitionclass[j];
  106237. }
  106238. /* read partition classes */
  106239. for(j=0;j<maxclass+1;j++){
  106240. info->class_dim[j]=oggpack_read(opb,3)+1; /* 1 to 8 */
  106241. info->class_subs[j]=oggpack_read(opb,2); /* 0,1,2,3 bits */
  106242. if(info->class_subs[j]<0)
  106243. goto err_out;
  106244. if(info->class_subs[j])info->class_book[j]=oggpack_read(opb,8);
  106245. if(info->class_book[j]<0 || info->class_book[j]>=ci->books)
  106246. goto err_out;
  106247. for(k=0;k<(1<<info->class_subs[j]);k++){
  106248. info->class_subbook[j][k]=oggpack_read(opb,8)-1;
  106249. if(info->class_subbook[j][k]<-1 || info->class_subbook[j][k]>=ci->books)
  106250. goto err_out;
  106251. }
  106252. }
  106253. /* read the post list */
  106254. info->mult=oggpack_read(opb,2)+1; /* only 1,2,3,4 legal now */
  106255. rangebits=oggpack_read(opb,4);
  106256. for(j=0,k=0;j<info->partitions;j++){
  106257. count+=info->class_dim[info->partitionclass[j]];
  106258. for(;k<count;k++){
  106259. int t=info->postlist[k+2]=oggpack_read(opb,rangebits);
  106260. if(t<0 || t>=(1<<rangebits))
  106261. goto err_out;
  106262. }
  106263. }
  106264. info->postlist[0]=0;
  106265. info->postlist[1]=1<<rangebits;
  106266. return(info);
  106267. err_out:
  106268. floor1_free_info(info);
  106269. return(NULL);
  106270. }
  106271. static int icomp(const void *a,const void *b){
  106272. return(**(int **)a-**(int **)b);
  106273. }
  106274. static vorbis_look_floor *floor1_look(vorbis_dsp_state *vd,
  106275. vorbis_info_floor *in){
  106276. int *sortpointer[VIF_POSIT+2];
  106277. vorbis_info_floor1 *info=(vorbis_info_floor1*)in;
  106278. vorbis_look_floor1 *look=(vorbis_look_floor1*)_ogg_calloc(1,sizeof(*look));
  106279. int i,j,n=0;
  106280. look->vi=info;
  106281. look->n=info->postlist[1];
  106282. /* we drop each position value in-between already decoded values,
  106283. and use linear interpolation to predict each new value past the
  106284. edges. The positions are read in the order of the position
  106285. list... we precompute the bounding positions in the lookup. Of
  106286. course, the neighbors can change (if a position is declined), but
  106287. this is an initial mapping */
  106288. for(i=0;i<info->partitions;i++)n+=info->class_dim[info->partitionclass[i]];
  106289. n+=2;
  106290. look->posts=n;
  106291. /* also store a sorted position index */
  106292. for(i=0;i<n;i++)sortpointer[i]=info->postlist+i;
  106293. qsort(sortpointer,n,sizeof(*sortpointer),icomp);
  106294. /* points from sort order back to range number */
  106295. for(i=0;i<n;i++)look->forward_index[i]=sortpointer[i]-info->postlist;
  106296. /* points from range order to sorted position */
  106297. for(i=0;i<n;i++)look->reverse_index[look->forward_index[i]]=i;
  106298. /* we actually need the post values too */
  106299. for(i=0;i<n;i++)look->sorted_index[i]=info->postlist[look->forward_index[i]];
  106300. /* quantize values to multiplier spec */
  106301. switch(info->mult){
  106302. case 1: /* 1024 -> 256 */
  106303. look->quant_q=256;
  106304. break;
  106305. case 2: /* 1024 -> 128 */
  106306. look->quant_q=128;
  106307. break;
  106308. case 3: /* 1024 -> 86 */
  106309. look->quant_q=86;
  106310. break;
  106311. case 4: /* 1024 -> 64 */
  106312. look->quant_q=64;
  106313. break;
  106314. }
  106315. /* discover our neighbors for decode where we don't use fit flags
  106316. (that would push the neighbors outward) */
  106317. for(i=0;i<n-2;i++){
  106318. int lo=0;
  106319. int hi=1;
  106320. int lx=0;
  106321. int hx=look->n;
  106322. int currentx=info->postlist[i+2];
  106323. for(j=0;j<i+2;j++){
  106324. int x=info->postlist[j];
  106325. if(x>lx && x<currentx){
  106326. lo=j;
  106327. lx=x;
  106328. }
  106329. if(x<hx && x>currentx){
  106330. hi=j;
  106331. hx=x;
  106332. }
  106333. }
  106334. look->loneighbor[i]=lo;
  106335. look->hineighbor[i]=hi;
  106336. }
  106337. return(look);
  106338. }
  106339. static int render_point(int x0,int x1,int y0,int y1,int x){
  106340. y0&=0x7fff; /* mask off flag */
  106341. y1&=0x7fff;
  106342. {
  106343. int dy=y1-y0;
  106344. int adx=x1-x0;
  106345. int ady=abs(dy);
  106346. int err=ady*(x-x0);
  106347. int off=err/adx;
  106348. if(dy<0)return(y0-off);
  106349. return(y0+off);
  106350. }
  106351. }
  106352. static int vorbis_dBquant(const float *x){
  106353. int i= *x*7.3142857f+1023.5f;
  106354. if(i>1023)return(1023);
  106355. if(i<0)return(0);
  106356. return i;
  106357. }
  106358. static float FLOOR1_fromdB_LOOKUP[256]={
  106359. 1.0649863e-07F, 1.1341951e-07F, 1.2079015e-07F, 1.2863978e-07F,
  106360. 1.3699951e-07F, 1.4590251e-07F, 1.5538408e-07F, 1.6548181e-07F,
  106361. 1.7623575e-07F, 1.8768855e-07F, 1.9988561e-07F, 2.128753e-07F,
  106362. 2.2670913e-07F, 2.4144197e-07F, 2.5713223e-07F, 2.7384213e-07F,
  106363. 2.9163793e-07F, 3.1059021e-07F, 3.3077411e-07F, 3.5226968e-07F,
  106364. 3.7516214e-07F, 3.9954229e-07F, 4.2550680e-07F, 4.5315863e-07F,
  106365. 4.8260743e-07F, 5.1396998e-07F, 5.4737065e-07F, 5.8294187e-07F,
  106366. 6.2082472e-07F, 6.6116941e-07F, 7.0413592e-07F, 7.4989464e-07F,
  106367. 7.9862701e-07F, 8.5052630e-07F, 9.0579828e-07F, 9.6466216e-07F,
  106368. 1.0273513e-06F, 1.0941144e-06F, 1.1652161e-06F, 1.2409384e-06F,
  106369. 1.3215816e-06F, 1.4074654e-06F, 1.4989305e-06F, 1.5963394e-06F,
  106370. 1.7000785e-06F, 1.8105592e-06F, 1.9282195e-06F, 2.0535261e-06F,
  106371. 2.1869758e-06F, 2.3290978e-06F, 2.4804557e-06F, 2.6416497e-06F,
  106372. 2.8133190e-06F, 2.9961443e-06F, 3.1908506e-06F, 3.3982101e-06F,
  106373. 3.6190449e-06F, 3.8542308e-06F, 4.1047004e-06F, 4.3714470e-06F,
  106374. 4.6555282e-06F, 4.9580707e-06F, 5.2802740e-06F, 5.6234160e-06F,
  106375. 5.9888572e-06F, 6.3780469e-06F, 6.7925283e-06F, 7.2339451e-06F,
  106376. 7.7040476e-06F, 8.2047000e-06F, 8.7378876e-06F, 9.3057248e-06F,
  106377. 9.9104632e-06F, 1.0554501e-05F, 1.1240392e-05F, 1.1970856e-05F,
  106378. 1.2748789e-05F, 1.3577278e-05F, 1.4459606e-05F, 1.5399272e-05F,
  106379. 1.6400004e-05F, 1.7465768e-05F, 1.8600792e-05F, 1.9809576e-05F,
  106380. 2.1096914e-05F, 2.2467911e-05F, 2.3928002e-05F, 2.5482978e-05F,
  106381. 2.7139006e-05F, 2.8902651e-05F, 3.0780908e-05F, 3.2781225e-05F,
  106382. 3.4911534e-05F, 3.7180282e-05F, 3.9596466e-05F, 4.2169667e-05F,
  106383. 4.4910090e-05F, 4.7828601e-05F, 5.0936773e-05F, 5.4246931e-05F,
  106384. 5.7772202e-05F, 6.1526565e-05F, 6.5524908e-05F, 6.9783085e-05F,
  106385. 7.4317983e-05F, 7.9147585e-05F, 8.4291040e-05F, 8.9768747e-05F,
  106386. 9.5602426e-05F, 0.00010181521F, 0.00010843174F, 0.00011547824F,
  106387. 0.00012298267F, 0.00013097477F, 0.00013948625F, 0.00014855085F,
  106388. 0.00015820453F, 0.00016848555F, 0.00017943469F, 0.00019109536F,
  106389. 0.00020351382F, 0.00021673929F, 0.00023082423F, 0.00024582449F,
  106390. 0.00026179955F, 0.00027881276F, 0.00029693158F, 0.00031622787F,
  106391. 0.00033677814F, 0.00035866388F, 0.00038197188F, 0.00040679456F,
  106392. 0.00043323036F, 0.00046138411F, 0.00049136745F, 0.00052329927F,
  106393. 0.00055730621F, 0.00059352311F, 0.00063209358F, 0.00067317058F,
  106394. 0.00071691700F, 0.00076350630F, 0.00081312324F, 0.00086596457F,
  106395. 0.00092223983F, 0.00098217216F, 0.0010459992F, 0.0011139742F,
  106396. 0.0011863665F, 0.0012634633F, 0.0013455702F, 0.0014330129F,
  106397. 0.0015261382F, 0.0016253153F, 0.0017309374F, 0.0018434235F,
  106398. 0.0019632195F, 0.0020908006F, 0.0022266726F, 0.0023713743F,
  106399. 0.0025254795F, 0.0026895994F, 0.0028643847F, 0.0030505286F,
  106400. 0.0032487691F, 0.0034598925F, 0.0036847358F, 0.0039241906F,
  106401. 0.0041792066F, 0.0044507950F, 0.0047400328F, 0.0050480668F,
  106402. 0.0053761186F, 0.0057254891F, 0.0060975636F, 0.0064938176F,
  106403. 0.0069158225F, 0.0073652516F, 0.0078438871F, 0.0083536271F,
  106404. 0.0088964928F, 0.009474637F, 0.010090352F, 0.010746080F,
  106405. 0.011444421F, 0.012188144F, 0.012980198F, 0.013823725F,
  106406. 0.014722068F, 0.015678791F, 0.016697687F, 0.017782797F,
  106407. 0.018938423F, 0.020169149F, 0.021479854F, 0.022875735F,
  106408. 0.024362330F, 0.025945531F, 0.027631618F, 0.029427276F,
  106409. 0.031339626F, 0.033376252F, 0.035545228F, 0.037855157F,
  106410. 0.040315199F, 0.042935108F, 0.045725273F, 0.048696758F,
  106411. 0.051861348F, 0.055231591F, 0.058820850F, 0.062643361F,
  106412. 0.066714279F, 0.071049749F, 0.075666962F, 0.080584227F,
  106413. 0.085821044F, 0.091398179F, 0.097337747F, 0.10366330F,
  106414. 0.11039993F, 0.11757434F, 0.12521498F, 0.13335215F,
  106415. 0.14201813F, 0.15124727F, 0.16107617F, 0.17154380F,
  106416. 0.18269168F, 0.19456402F, 0.20720788F, 0.22067342F,
  106417. 0.23501402F, 0.25028656F, 0.26655159F, 0.28387361F,
  106418. 0.30232132F, 0.32196786F, 0.34289114F, 0.36517414F,
  106419. 0.38890521F, 0.41417847F, 0.44109412F, 0.46975890F,
  106420. 0.50028648F, 0.53279791F, 0.56742212F, 0.60429640F,
  106421. 0.64356699F, 0.68538959F, 0.72993007F, 0.77736504F,
  106422. 0.82788260F, 0.88168307F, 0.9389798F, 1.F,
  106423. };
  106424. static void render_line(int x0,int x1,int y0,int y1,float *d){
  106425. int dy=y1-y0;
  106426. int adx=x1-x0;
  106427. int ady=abs(dy);
  106428. int base=dy/adx;
  106429. int sy=(dy<0?base-1:base+1);
  106430. int x=x0;
  106431. int y=y0;
  106432. int err=0;
  106433. ady-=abs(base*adx);
  106434. d[x]*=FLOOR1_fromdB_LOOKUP[y];
  106435. while(++x<x1){
  106436. err=err+ady;
  106437. if(err>=adx){
  106438. err-=adx;
  106439. y+=sy;
  106440. }else{
  106441. y+=base;
  106442. }
  106443. d[x]*=FLOOR1_fromdB_LOOKUP[y];
  106444. }
  106445. }
  106446. static void render_line0(int x0,int x1,int y0,int y1,int *d){
  106447. int dy=y1-y0;
  106448. int adx=x1-x0;
  106449. int ady=abs(dy);
  106450. int base=dy/adx;
  106451. int sy=(dy<0?base-1:base+1);
  106452. int x=x0;
  106453. int y=y0;
  106454. int err=0;
  106455. ady-=abs(base*adx);
  106456. d[x]=y;
  106457. while(++x<x1){
  106458. err=err+ady;
  106459. if(err>=adx){
  106460. err-=adx;
  106461. y+=sy;
  106462. }else{
  106463. y+=base;
  106464. }
  106465. d[x]=y;
  106466. }
  106467. }
  106468. /* the floor has already been filtered to only include relevant sections */
  106469. static int accumulate_fit(const float *flr,const float *mdct,
  106470. int x0, int x1,lsfit_acc *a,
  106471. int n,vorbis_info_floor1 *info){
  106472. long i;
  106473. 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;
  106474. memset(a,0,sizeof(*a));
  106475. a->x0=x0;
  106476. a->x1=x1;
  106477. if(x1>=n)x1=n-1;
  106478. for(i=x0;i<=x1;i++){
  106479. int quantized=vorbis_dBquant(flr+i);
  106480. if(quantized){
  106481. if(mdct[i]+info->twofitatten>=flr[i]){
  106482. xa += i;
  106483. ya += quantized;
  106484. x2a += i*i;
  106485. y2a += quantized*quantized;
  106486. xya += i*quantized;
  106487. na++;
  106488. }else{
  106489. xb += i;
  106490. yb += quantized;
  106491. x2b += i*i;
  106492. y2b += quantized*quantized;
  106493. xyb += i*quantized;
  106494. nb++;
  106495. }
  106496. }
  106497. }
  106498. xb+=xa;
  106499. yb+=ya;
  106500. x2b+=x2a;
  106501. y2b+=y2a;
  106502. xyb+=xya;
  106503. nb+=na;
  106504. /* weight toward the actually used frequencies if we meet the threshhold */
  106505. {
  106506. int weight=nb*info->twofitweight/(na+1);
  106507. a->xa=xa*weight+xb;
  106508. a->ya=ya*weight+yb;
  106509. a->x2a=x2a*weight+x2b;
  106510. a->y2a=y2a*weight+y2b;
  106511. a->xya=xya*weight+xyb;
  106512. a->an=na*weight+nb;
  106513. }
  106514. return(na);
  106515. }
  106516. static void fit_line(lsfit_acc *a,int fits,int *y0,int *y1){
  106517. long x=0,y=0,x2=0,y2=0,xy=0,an=0,i;
  106518. long x0=a[0].x0;
  106519. long x1=a[fits-1].x1;
  106520. for(i=0;i<fits;i++){
  106521. x+=a[i].xa;
  106522. y+=a[i].ya;
  106523. x2+=a[i].x2a;
  106524. y2+=a[i].y2a;
  106525. xy+=a[i].xya;
  106526. an+=a[i].an;
  106527. }
  106528. if(*y0>=0){
  106529. x+= x0;
  106530. y+= *y0;
  106531. x2+= x0 * x0;
  106532. y2+= *y0 * *y0;
  106533. xy+= *y0 * x0;
  106534. an++;
  106535. }
  106536. if(*y1>=0){
  106537. x+= x1;
  106538. y+= *y1;
  106539. x2+= x1 * x1;
  106540. y2+= *y1 * *y1;
  106541. xy+= *y1 * x1;
  106542. an++;
  106543. }
  106544. if(an){
  106545. /* need 64 bit multiplies, which C doesn't give portably as int */
  106546. double fx=x;
  106547. double fy=y;
  106548. double fx2=x2;
  106549. double fxy=xy;
  106550. double denom=1./(an*fx2-fx*fx);
  106551. double a=(fy*fx2-fxy*fx)*denom;
  106552. double b=(an*fxy-fx*fy)*denom;
  106553. *y0=rint(a+b*x0);
  106554. *y1=rint(a+b*x1);
  106555. /* limit to our range! */
  106556. if(*y0>1023)*y0=1023;
  106557. if(*y1>1023)*y1=1023;
  106558. if(*y0<0)*y0=0;
  106559. if(*y1<0)*y1=0;
  106560. }else{
  106561. *y0=0;
  106562. *y1=0;
  106563. }
  106564. }
  106565. /*static void fit_line_point(lsfit_acc *a,int fits,int *y0,int *y1){
  106566. long y=0;
  106567. int i;
  106568. for(i=0;i<fits && y==0;i++)
  106569. y+=a[i].ya;
  106570. *y0=*y1=y;
  106571. }*/
  106572. static int inspect_error(int x0,int x1,int y0,int y1,const float *mask,
  106573. const float *mdct,
  106574. vorbis_info_floor1 *info){
  106575. int dy=y1-y0;
  106576. int adx=x1-x0;
  106577. int ady=abs(dy);
  106578. int base=dy/adx;
  106579. int sy=(dy<0?base-1:base+1);
  106580. int x=x0;
  106581. int y=y0;
  106582. int err=0;
  106583. int val=vorbis_dBquant(mask+x);
  106584. int mse=0;
  106585. int n=0;
  106586. ady-=abs(base*adx);
  106587. mse=(y-val);
  106588. mse*=mse;
  106589. n++;
  106590. if(mdct[x]+info->twofitatten>=mask[x]){
  106591. if(y+info->maxover<val)return(1);
  106592. if(y-info->maxunder>val)return(1);
  106593. }
  106594. while(++x<x1){
  106595. err=err+ady;
  106596. if(err>=adx){
  106597. err-=adx;
  106598. y+=sy;
  106599. }else{
  106600. y+=base;
  106601. }
  106602. val=vorbis_dBquant(mask+x);
  106603. mse+=((y-val)*(y-val));
  106604. n++;
  106605. if(mdct[x]+info->twofitatten>=mask[x]){
  106606. if(val){
  106607. if(y+info->maxover<val)return(1);
  106608. if(y-info->maxunder>val)return(1);
  106609. }
  106610. }
  106611. }
  106612. if(info->maxover*info->maxover/n>info->maxerr)return(0);
  106613. if(info->maxunder*info->maxunder/n>info->maxerr)return(0);
  106614. if(mse/n>info->maxerr)return(1);
  106615. return(0);
  106616. }
  106617. static int post_Y(int *A,int *B,int pos){
  106618. if(A[pos]<0)
  106619. return B[pos];
  106620. if(B[pos]<0)
  106621. return A[pos];
  106622. return (A[pos]+B[pos])>>1;
  106623. }
  106624. int *floor1_fit(vorbis_block *vb,void *look_,
  106625. const float *logmdct, /* in */
  106626. const float *logmask){
  106627. long i,j;
  106628. vorbis_look_floor1 *look = (vorbis_look_floor1*) look_;
  106629. vorbis_info_floor1 *info=look->vi;
  106630. long n=look->n;
  106631. long posts=look->posts;
  106632. long nonzero=0;
  106633. lsfit_acc fits[VIF_POSIT+1];
  106634. int fit_valueA[VIF_POSIT+2]; /* index by range list position */
  106635. int fit_valueB[VIF_POSIT+2]; /* index by range list position */
  106636. int loneighbor[VIF_POSIT+2]; /* sorted index of range list position (+2) */
  106637. int hineighbor[VIF_POSIT+2];
  106638. int *output=NULL;
  106639. int memo[VIF_POSIT+2];
  106640. for(i=0;i<posts;i++)fit_valueA[i]=-200; /* mark all unused */
  106641. for(i=0;i<posts;i++)fit_valueB[i]=-200; /* mark all unused */
  106642. for(i=0;i<posts;i++)loneighbor[i]=0; /* 0 for the implicit 0 post */
  106643. for(i=0;i<posts;i++)hineighbor[i]=1; /* 1 for the implicit post at n */
  106644. for(i=0;i<posts;i++)memo[i]=-1; /* no neighbor yet */
  106645. /* quantize the relevant floor points and collect them into line fit
  106646. structures (one per minimal division) at the same time */
  106647. if(posts==0){
  106648. nonzero+=accumulate_fit(logmask,logmdct,0,n,fits,n,info);
  106649. }else{
  106650. for(i=0;i<posts-1;i++)
  106651. nonzero+=accumulate_fit(logmask,logmdct,look->sorted_index[i],
  106652. look->sorted_index[i+1],fits+i,
  106653. n,info);
  106654. }
  106655. if(nonzero){
  106656. /* start by fitting the implicit base case.... */
  106657. int y0=-200;
  106658. int y1=-200;
  106659. fit_line(fits,posts-1,&y0,&y1);
  106660. fit_valueA[0]=y0;
  106661. fit_valueB[0]=y0;
  106662. fit_valueB[1]=y1;
  106663. fit_valueA[1]=y1;
  106664. /* Non degenerate case */
  106665. /* start progressive splitting. This is a greedy, non-optimal
  106666. algorithm, but simple and close enough to the best
  106667. answer. */
  106668. for(i=2;i<posts;i++){
  106669. int sortpos=look->reverse_index[i];
  106670. int ln=loneighbor[sortpos];
  106671. int hn=hineighbor[sortpos];
  106672. /* eliminate repeat searches of a particular range with a memo */
  106673. if(memo[ln]!=hn){
  106674. /* haven't performed this error search yet */
  106675. int lsortpos=look->reverse_index[ln];
  106676. int hsortpos=look->reverse_index[hn];
  106677. memo[ln]=hn;
  106678. {
  106679. /* A note: we want to bound/minimize *local*, not global, error */
  106680. int lx=info->postlist[ln];
  106681. int hx=info->postlist[hn];
  106682. int ly=post_Y(fit_valueA,fit_valueB,ln);
  106683. int hy=post_Y(fit_valueA,fit_valueB,hn);
  106684. if(ly==-1 || hy==-1){
  106685. exit(1);
  106686. }
  106687. if(inspect_error(lx,hx,ly,hy,logmask,logmdct,info)){
  106688. /* outside error bounds/begin search area. Split it. */
  106689. int ly0=-200;
  106690. int ly1=-200;
  106691. int hy0=-200;
  106692. int hy1=-200;
  106693. fit_line(fits+lsortpos,sortpos-lsortpos,&ly0,&ly1);
  106694. fit_line(fits+sortpos,hsortpos-sortpos,&hy0,&hy1);
  106695. /* store new edge values */
  106696. fit_valueB[ln]=ly0;
  106697. if(ln==0)fit_valueA[ln]=ly0;
  106698. fit_valueA[i]=ly1;
  106699. fit_valueB[i]=hy0;
  106700. fit_valueA[hn]=hy1;
  106701. if(hn==1)fit_valueB[hn]=hy1;
  106702. if(ly1>=0 || hy0>=0){
  106703. /* store new neighbor values */
  106704. for(j=sortpos-1;j>=0;j--)
  106705. if(hineighbor[j]==hn)
  106706. hineighbor[j]=i;
  106707. else
  106708. break;
  106709. for(j=sortpos+1;j<posts;j++)
  106710. if(loneighbor[j]==ln)
  106711. loneighbor[j]=i;
  106712. else
  106713. break;
  106714. }
  106715. }else{
  106716. fit_valueA[i]=-200;
  106717. fit_valueB[i]=-200;
  106718. }
  106719. }
  106720. }
  106721. }
  106722. output=(int*)_vorbis_block_alloc(vb,sizeof(*output)*posts);
  106723. output[0]=post_Y(fit_valueA,fit_valueB,0);
  106724. output[1]=post_Y(fit_valueA,fit_valueB,1);
  106725. /* fill in posts marked as not using a fit; we will zero
  106726. back out to 'unused' when encoding them so long as curve
  106727. interpolation doesn't force them into use */
  106728. for(i=2;i<posts;i++){
  106729. int ln=look->loneighbor[i-2];
  106730. int hn=look->hineighbor[i-2];
  106731. int x0=info->postlist[ln];
  106732. int x1=info->postlist[hn];
  106733. int y0=output[ln];
  106734. int y1=output[hn];
  106735. int predicted=render_point(x0,x1,y0,y1,info->postlist[i]);
  106736. int vx=post_Y(fit_valueA,fit_valueB,i);
  106737. if(vx>=0 && predicted!=vx){
  106738. output[i]=vx;
  106739. }else{
  106740. output[i]= predicted|0x8000;
  106741. }
  106742. }
  106743. }
  106744. return(output);
  106745. }
  106746. int *floor1_interpolate_fit(vorbis_block *vb,void *look_,
  106747. int *A,int *B,
  106748. int del){
  106749. long i;
  106750. vorbis_look_floor1* look = (vorbis_look_floor1*) look_;
  106751. long posts=look->posts;
  106752. int *output=NULL;
  106753. if(A && B){
  106754. output=(int*)_vorbis_block_alloc(vb,sizeof(*output)*posts);
  106755. for(i=0;i<posts;i++){
  106756. output[i]=((65536-del)*(A[i]&0x7fff)+del*(B[i]&0x7fff)+32768)>>16;
  106757. if(A[i]&0x8000 && B[i]&0x8000)output[i]|=0x8000;
  106758. }
  106759. }
  106760. return(output);
  106761. }
  106762. int floor1_encode(oggpack_buffer *opb,vorbis_block *vb,
  106763. void*look_,
  106764. int *post,int *ilogmask){
  106765. long i,j;
  106766. vorbis_look_floor1 *look = (vorbis_look_floor1 *) look_;
  106767. vorbis_info_floor1 *info=look->vi;
  106768. long posts=look->posts;
  106769. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  106770. int out[VIF_POSIT+2];
  106771. static_codebook **sbooks=ci->book_param;
  106772. codebook *books=ci->fullbooks;
  106773. static long seq=0;
  106774. /* quantize values to multiplier spec */
  106775. if(post){
  106776. for(i=0;i<posts;i++){
  106777. int val=post[i]&0x7fff;
  106778. switch(info->mult){
  106779. case 1: /* 1024 -> 256 */
  106780. val>>=2;
  106781. break;
  106782. case 2: /* 1024 -> 128 */
  106783. val>>=3;
  106784. break;
  106785. case 3: /* 1024 -> 86 */
  106786. val/=12;
  106787. break;
  106788. case 4: /* 1024 -> 64 */
  106789. val>>=4;
  106790. break;
  106791. }
  106792. post[i]=val | (post[i]&0x8000);
  106793. }
  106794. out[0]=post[0];
  106795. out[1]=post[1];
  106796. /* find prediction values for each post and subtract them */
  106797. for(i=2;i<posts;i++){
  106798. int ln=look->loneighbor[i-2];
  106799. int hn=look->hineighbor[i-2];
  106800. int x0=info->postlist[ln];
  106801. int x1=info->postlist[hn];
  106802. int y0=post[ln];
  106803. int y1=post[hn];
  106804. int predicted=render_point(x0,x1,y0,y1,info->postlist[i]);
  106805. if((post[i]&0x8000) || (predicted==post[i])){
  106806. post[i]=predicted|0x8000; /* in case there was roundoff jitter
  106807. in interpolation */
  106808. out[i]=0;
  106809. }else{
  106810. int headroom=(look->quant_q-predicted<predicted?
  106811. look->quant_q-predicted:predicted);
  106812. int val=post[i]-predicted;
  106813. /* at this point the 'deviation' value is in the range +/- max
  106814. range, but the real, unique range can always be mapped to
  106815. only [0-maxrange). So we want to wrap the deviation into
  106816. this limited range, but do it in the way that least screws
  106817. an essentially gaussian probability distribution. */
  106818. if(val<0)
  106819. if(val<-headroom)
  106820. val=headroom-val-1;
  106821. else
  106822. val=-1-(val<<1);
  106823. else
  106824. if(val>=headroom)
  106825. val= val+headroom;
  106826. else
  106827. val<<=1;
  106828. out[i]=val;
  106829. post[ln]&=0x7fff;
  106830. post[hn]&=0x7fff;
  106831. }
  106832. }
  106833. /* we have everything we need. pack it out */
  106834. /* mark nontrivial floor */
  106835. oggpack_write(opb,1,1);
  106836. /* beginning/end post */
  106837. look->frames++;
  106838. look->postbits+=ilog(look->quant_q-1)*2;
  106839. oggpack_write(opb,out[0],ilog(look->quant_q-1));
  106840. oggpack_write(opb,out[1],ilog(look->quant_q-1));
  106841. /* partition by partition */
  106842. for(i=0,j=2;i<info->partitions;i++){
  106843. int classx=info->partitionclass[i];
  106844. int cdim=info->class_dim[classx];
  106845. int csubbits=info->class_subs[classx];
  106846. int csub=1<<csubbits;
  106847. int bookas[8]={0,0,0,0,0,0,0,0};
  106848. int cval=0;
  106849. int cshift=0;
  106850. int k,l;
  106851. /* generate the partition's first stage cascade value */
  106852. if(csubbits){
  106853. int maxval[8];
  106854. for(k=0;k<csub;k++){
  106855. int booknum=info->class_subbook[classx][k];
  106856. if(booknum<0){
  106857. maxval[k]=1;
  106858. }else{
  106859. maxval[k]=sbooks[info->class_subbook[classx][k]]->entries;
  106860. }
  106861. }
  106862. for(k=0;k<cdim;k++){
  106863. for(l=0;l<csub;l++){
  106864. int val=out[j+k];
  106865. if(val<maxval[l]){
  106866. bookas[k]=l;
  106867. break;
  106868. }
  106869. }
  106870. cval|= bookas[k]<<cshift;
  106871. cshift+=csubbits;
  106872. }
  106873. /* write it */
  106874. look->phrasebits+=
  106875. vorbis_book_encode(books+info->class_book[classx],cval,opb);
  106876. #ifdef TRAIN_FLOOR1
  106877. {
  106878. FILE *of;
  106879. char buffer[80];
  106880. sprintf(buffer,"line_%dx%ld_class%d.vqd",
  106881. vb->pcmend/2,posts-2,class);
  106882. of=fopen(buffer,"a");
  106883. fprintf(of,"%d\n",cval);
  106884. fclose(of);
  106885. }
  106886. #endif
  106887. }
  106888. /* write post values */
  106889. for(k=0;k<cdim;k++){
  106890. int book=info->class_subbook[classx][bookas[k]];
  106891. if(book>=0){
  106892. /* hack to allow training with 'bad' books */
  106893. if(out[j+k]<(books+book)->entries)
  106894. look->postbits+=vorbis_book_encode(books+book,
  106895. out[j+k],opb);
  106896. /*else
  106897. fprintf(stderr,"+!");*/
  106898. #ifdef TRAIN_FLOOR1
  106899. {
  106900. FILE *of;
  106901. char buffer[80];
  106902. sprintf(buffer,"line_%dx%ld_%dsub%d.vqd",
  106903. vb->pcmend/2,posts-2,class,bookas[k]);
  106904. of=fopen(buffer,"a");
  106905. fprintf(of,"%d\n",out[j+k]);
  106906. fclose(of);
  106907. }
  106908. #endif
  106909. }
  106910. }
  106911. j+=cdim;
  106912. }
  106913. {
  106914. /* generate quantized floor equivalent to what we'd unpack in decode */
  106915. /* render the lines */
  106916. int hx=0;
  106917. int lx=0;
  106918. int ly=post[0]*info->mult;
  106919. for(j=1;j<look->posts;j++){
  106920. int current=look->forward_index[j];
  106921. int hy=post[current]&0x7fff;
  106922. if(hy==post[current]){
  106923. hy*=info->mult;
  106924. hx=info->postlist[current];
  106925. render_line0(lx,hx,ly,hy,ilogmask);
  106926. lx=hx;
  106927. ly=hy;
  106928. }
  106929. }
  106930. for(j=hx;j<vb->pcmend/2;j++)ilogmask[j]=ly; /* be certain */
  106931. seq++;
  106932. return(1);
  106933. }
  106934. }else{
  106935. oggpack_write(opb,0,1);
  106936. memset(ilogmask,0,vb->pcmend/2*sizeof(*ilogmask));
  106937. seq++;
  106938. return(0);
  106939. }
  106940. }
  106941. static void *floor1_inverse1(vorbis_block *vb,vorbis_look_floor *in){
  106942. vorbis_look_floor1 *look=(vorbis_look_floor1 *)in;
  106943. vorbis_info_floor1 *info=look->vi;
  106944. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  106945. int i,j,k;
  106946. codebook *books=ci->fullbooks;
  106947. /* unpack wrapped/predicted values from stream */
  106948. if(oggpack_read(&vb->opb,1)==1){
  106949. int *fit_value=(int*)_vorbis_block_alloc(vb,(look->posts)*sizeof(*fit_value));
  106950. fit_value[0]=oggpack_read(&vb->opb,ilog(look->quant_q-1));
  106951. fit_value[1]=oggpack_read(&vb->opb,ilog(look->quant_q-1));
  106952. /* partition by partition */
  106953. for(i=0,j=2;i<info->partitions;i++){
  106954. int classx=info->partitionclass[i];
  106955. int cdim=info->class_dim[classx];
  106956. int csubbits=info->class_subs[classx];
  106957. int csub=1<<csubbits;
  106958. int cval=0;
  106959. /* decode the partition's first stage cascade value */
  106960. if(csubbits){
  106961. cval=vorbis_book_decode(books+info->class_book[classx],&vb->opb);
  106962. if(cval==-1)goto eop;
  106963. }
  106964. for(k=0;k<cdim;k++){
  106965. int book=info->class_subbook[classx][cval&(csub-1)];
  106966. cval>>=csubbits;
  106967. if(book>=0){
  106968. if((fit_value[j+k]=vorbis_book_decode(books+book,&vb->opb))==-1)
  106969. goto eop;
  106970. }else{
  106971. fit_value[j+k]=0;
  106972. }
  106973. }
  106974. j+=cdim;
  106975. }
  106976. /* unwrap positive values and reconsitute via linear interpolation */
  106977. for(i=2;i<look->posts;i++){
  106978. int predicted=render_point(info->postlist[look->loneighbor[i-2]],
  106979. info->postlist[look->hineighbor[i-2]],
  106980. fit_value[look->loneighbor[i-2]],
  106981. fit_value[look->hineighbor[i-2]],
  106982. info->postlist[i]);
  106983. int hiroom=look->quant_q-predicted;
  106984. int loroom=predicted;
  106985. int room=(hiroom<loroom?hiroom:loroom)<<1;
  106986. int val=fit_value[i];
  106987. if(val){
  106988. if(val>=room){
  106989. if(hiroom>loroom){
  106990. val = val-loroom;
  106991. }else{
  106992. val = -1-(val-hiroom);
  106993. }
  106994. }else{
  106995. if(val&1){
  106996. val= -((val+1)>>1);
  106997. }else{
  106998. val>>=1;
  106999. }
  107000. }
  107001. fit_value[i]=val+predicted;
  107002. fit_value[look->loneighbor[i-2]]&=0x7fff;
  107003. fit_value[look->hineighbor[i-2]]&=0x7fff;
  107004. }else{
  107005. fit_value[i]=predicted|0x8000;
  107006. }
  107007. }
  107008. return(fit_value);
  107009. }
  107010. eop:
  107011. return(NULL);
  107012. }
  107013. static int floor1_inverse2(vorbis_block *vb,vorbis_look_floor *in,void *memo,
  107014. float *out){
  107015. vorbis_look_floor1 *look=(vorbis_look_floor1 *)in;
  107016. vorbis_info_floor1 *info=look->vi;
  107017. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  107018. int n=ci->blocksizes[vb->W]/2;
  107019. int j;
  107020. if(memo){
  107021. /* render the lines */
  107022. int *fit_value=(int *)memo;
  107023. int hx=0;
  107024. int lx=0;
  107025. int ly=fit_value[0]*info->mult;
  107026. for(j=1;j<look->posts;j++){
  107027. int current=look->forward_index[j];
  107028. int hy=fit_value[current]&0x7fff;
  107029. if(hy==fit_value[current]){
  107030. hy*=info->mult;
  107031. hx=info->postlist[current];
  107032. render_line(lx,hx,ly,hy,out);
  107033. lx=hx;
  107034. ly=hy;
  107035. }
  107036. }
  107037. for(j=hx;j<n;j++)out[j]*=FLOOR1_fromdB_LOOKUP[ly]; /* be certain */
  107038. return(1);
  107039. }
  107040. memset(out,0,sizeof(*out)*n);
  107041. return(0);
  107042. }
  107043. /* export hooks */
  107044. vorbis_func_floor floor1_exportbundle={
  107045. &floor1_pack,&floor1_unpack,&floor1_look,&floor1_free_info,
  107046. &floor1_free_look,&floor1_inverse1,&floor1_inverse2
  107047. };
  107048. #endif
  107049. /********* End of inlined file: floor1.c *********/
  107050. /********* Start of inlined file: info.c *********/
  107051. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  107052. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  107053. // tasks..
  107054. #ifdef _MSC_VER
  107055. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  107056. #endif
  107057. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  107058. #if JUCE_USE_OGGVORBIS
  107059. /* general handling of the header and the vorbis_info structure (and
  107060. substructures) */
  107061. #include <stdlib.h>
  107062. #include <string.h>
  107063. #include <ctype.h>
  107064. static void _v_writestring(oggpack_buffer *o,char *s, int bytes){
  107065. while(bytes--){
  107066. oggpack_write(o,*s++,8);
  107067. }
  107068. }
  107069. static void _v_readstring(oggpack_buffer *o,char *buf,int bytes){
  107070. while(bytes--){
  107071. *buf++=oggpack_read(o,8);
  107072. }
  107073. }
  107074. void vorbis_comment_init(vorbis_comment *vc){
  107075. memset(vc,0,sizeof(*vc));
  107076. }
  107077. void vorbis_comment_add(vorbis_comment *vc,char *comment){
  107078. vc->user_comments=(char**)_ogg_realloc(vc->user_comments,
  107079. (vc->comments+2)*sizeof(*vc->user_comments));
  107080. vc->comment_lengths=(int*)_ogg_realloc(vc->comment_lengths,
  107081. (vc->comments+2)*sizeof(*vc->comment_lengths));
  107082. vc->comment_lengths[vc->comments]=strlen(comment);
  107083. vc->user_comments[vc->comments]=(char*)_ogg_malloc(vc->comment_lengths[vc->comments]+1);
  107084. strcpy(vc->user_comments[vc->comments], comment);
  107085. vc->comments++;
  107086. vc->user_comments[vc->comments]=NULL;
  107087. }
  107088. void vorbis_comment_add_tag(vorbis_comment *vc, char *tag, char *contents){
  107089. char *comment=(char*)alloca(strlen(tag)+strlen(contents)+2); /* +2 for = and \0 */
  107090. strcpy(comment, tag);
  107091. strcat(comment, "=");
  107092. strcat(comment, contents);
  107093. vorbis_comment_add(vc, comment);
  107094. }
  107095. /* This is more or less the same as strncasecmp - but that doesn't exist
  107096. * everywhere, and this is a fairly trivial function, so we include it */
  107097. static int tagcompare(const char *s1, const char *s2, int n){
  107098. int c=0;
  107099. while(c < n){
  107100. if(toupper(s1[c]) != toupper(s2[c]))
  107101. return !0;
  107102. c++;
  107103. }
  107104. return 0;
  107105. }
  107106. char *vorbis_comment_query(vorbis_comment *vc, char *tag, int count){
  107107. long i;
  107108. int found = 0;
  107109. int taglen = strlen(tag)+1; /* +1 for the = we append */
  107110. char *fulltag = (char*)alloca(taglen+ 1);
  107111. strcpy(fulltag, tag);
  107112. strcat(fulltag, "=");
  107113. for(i=0;i<vc->comments;i++){
  107114. if(!tagcompare(vc->user_comments[i], fulltag, taglen)){
  107115. if(count == found)
  107116. /* We return a pointer to the data, not a copy */
  107117. return vc->user_comments[i] + taglen;
  107118. else
  107119. found++;
  107120. }
  107121. }
  107122. return NULL; /* didn't find anything */
  107123. }
  107124. int vorbis_comment_query_count(vorbis_comment *vc, char *tag){
  107125. int i,count=0;
  107126. int taglen = strlen(tag)+1; /* +1 for the = we append */
  107127. char *fulltag = (char*)alloca(taglen+1);
  107128. strcpy(fulltag,tag);
  107129. strcat(fulltag, "=");
  107130. for(i=0;i<vc->comments;i++){
  107131. if(!tagcompare(vc->user_comments[i], fulltag, taglen))
  107132. count++;
  107133. }
  107134. return count;
  107135. }
  107136. void vorbis_comment_clear(vorbis_comment *vc){
  107137. if(vc){
  107138. long i;
  107139. for(i=0;i<vc->comments;i++)
  107140. if(vc->user_comments[i])_ogg_free(vc->user_comments[i]);
  107141. if(vc->user_comments)_ogg_free(vc->user_comments);
  107142. if(vc->comment_lengths)_ogg_free(vc->comment_lengths);
  107143. if(vc->vendor)_ogg_free(vc->vendor);
  107144. }
  107145. memset(vc,0,sizeof(*vc));
  107146. }
  107147. /* blocksize 0 is guaranteed to be short, 1 is guarantted to be long.
  107148. They may be equal, but short will never ge greater than long */
  107149. int vorbis_info_blocksize(vorbis_info *vi,int zo){
  107150. codec_setup_info *ci = (codec_setup_info*)vi->codec_setup;
  107151. return ci ? ci->blocksizes[zo] : -1;
  107152. }
  107153. /* used by synthesis, which has a full, alloced vi */
  107154. void vorbis_info_init(vorbis_info *vi){
  107155. memset(vi,0,sizeof(*vi));
  107156. vi->codec_setup=_ogg_calloc(1,sizeof(codec_setup_info));
  107157. }
  107158. void vorbis_info_clear(vorbis_info *vi){
  107159. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  107160. int i;
  107161. if(ci){
  107162. for(i=0;i<ci->modes;i++)
  107163. if(ci->mode_param[i])_ogg_free(ci->mode_param[i]);
  107164. for(i=0;i<ci->maps;i++) /* unpack does the range checking */
  107165. _mapping_P[ci->map_type[i]]->free_info(ci->map_param[i]);
  107166. for(i=0;i<ci->floors;i++) /* unpack does the range checking */
  107167. _floor_P[ci->floor_type[i]]->free_info(ci->floor_param[i]);
  107168. for(i=0;i<ci->residues;i++) /* unpack does the range checking */
  107169. _residue_P[ci->residue_type[i]]->free_info(ci->residue_param[i]);
  107170. for(i=0;i<ci->books;i++){
  107171. if(ci->book_param[i]){
  107172. /* knows if the book was not alloced */
  107173. vorbis_staticbook_destroy(ci->book_param[i]);
  107174. }
  107175. if(ci->fullbooks)
  107176. vorbis_book_clear(ci->fullbooks+i);
  107177. }
  107178. if(ci->fullbooks)
  107179. _ogg_free(ci->fullbooks);
  107180. for(i=0;i<ci->psys;i++)
  107181. _vi_psy_free(ci->psy_param[i]);
  107182. _ogg_free(ci);
  107183. }
  107184. memset(vi,0,sizeof(*vi));
  107185. }
  107186. /* Header packing/unpacking ********************************************/
  107187. static int _vorbis_unpack_info(vorbis_info *vi,oggpack_buffer *opb){
  107188. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  107189. if(!ci)return(OV_EFAULT);
  107190. vi->version=oggpack_read(opb,32);
  107191. if(vi->version!=0)return(OV_EVERSION);
  107192. vi->channels=oggpack_read(opb,8);
  107193. vi->rate=oggpack_read(opb,32);
  107194. vi->bitrate_upper=oggpack_read(opb,32);
  107195. vi->bitrate_nominal=oggpack_read(opb,32);
  107196. vi->bitrate_lower=oggpack_read(opb,32);
  107197. ci->blocksizes[0]=1<<oggpack_read(opb,4);
  107198. ci->blocksizes[1]=1<<oggpack_read(opb,4);
  107199. if(vi->rate<1)goto err_out;
  107200. if(vi->channels<1)goto err_out;
  107201. if(ci->blocksizes[0]<8)goto err_out;
  107202. if(ci->blocksizes[1]<ci->blocksizes[0])goto err_out;
  107203. if(oggpack_read(opb,1)!=1)goto err_out; /* EOP check */
  107204. return(0);
  107205. err_out:
  107206. vorbis_info_clear(vi);
  107207. return(OV_EBADHEADER);
  107208. }
  107209. static int _vorbis_unpack_comment(vorbis_comment *vc,oggpack_buffer *opb){
  107210. int i;
  107211. int vendorlen=oggpack_read(opb,32);
  107212. if(vendorlen<0)goto err_out;
  107213. vc->vendor=(char*)_ogg_calloc(vendorlen+1,1);
  107214. _v_readstring(opb,vc->vendor,vendorlen);
  107215. vc->comments=oggpack_read(opb,32);
  107216. if(vc->comments<0)goto err_out;
  107217. vc->user_comments=(char**)_ogg_calloc(vc->comments+1,sizeof(*vc->user_comments));
  107218. vc->comment_lengths=(int*)_ogg_calloc(vc->comments+1, sizeof(*vc->comment_lengths));
  107219. for(i=0;i<vc->comments;i++){
  107220. int len=oggpack_read(opb,32);
  107221. if(len<0)goto err_out;
  107222. vc->comment_lengths[i]=len;
  107223. vc->user_comments[i]=(char*)_ogg_calloc(len+1,1);
  107224. _v_readstring(opb,vc->user_comments[i],len);
  107225. }
  107226. if(oggpack_read(opb,1)!=1)goto err_out; /* EOP check */
  107227. return(0);
  107228. err_out:
  107229. vorbis_comment_clear(vc);
  107230. return(OV_EBADHEADER);
  107231. }
  107232. /* all of the real encoding details are here. The modes, books,
  107233. everything */
  107234. static int _vorbis_unpack_books(vorbis_info *vi,oggpack_buffer *opb){
  107235. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  107236. int i;
  107237. if(!ci)return(OV_EFAULT);
  107238. /* codebooks */
  107239. ci->books=oggpack_read(opb,8)+1;
  107240. /*ci->book_param=_ogg_calloc(ci->books,sizeof(*ci->book_param));*/
  107241. for(i=0;i<ci->books;i++){
  107242. ci->book_param[i]=(static_codebook*)_ogg_calloc(1,sizeof(*ci->book_param[i]));
  107243. if(vorbis_staticbook_unpack(opb,ci->book_param[i]))goto err_out;
  107244. }
  107245. /* time backend settings; hooks are unused */
  107246. {
  107247. int times=oggpack_read(opb,6)+1;
  107248. for(i=0;i<times;i++){
  107249. int test=oggpack_read(opb,16);
  107250. if(test<0 || test>=VI_TIMEB)goto err_out;
  107251. }
  107252. }
  107253. /* floor backend settings */
  107254. ci->floors=oggpack_read(opb,6)+1;
  107255. /*ci->floor_type=_ogg_malloc(ci->floors*sizeof(*ci->floor_type));*/
  107256. /*ci->floor_param=_ogg_calloc(ci->floors,sizeof(void *));*/
  107257. for(i=0;i<ci->floors;i++){
  107258. ci->floor_type[i]=oggpack_read(opb,16);
  107259. if(ci->floor_type[i]<0 || ci->floor_type[i]>=VI_FLOORB)goto err_out;
  107260. ci->floor_param[i]=_floor_P[ci->floor_type[i]]->unpack(vi,opb);
  107261. if(!ci->floor_param[i])goto err_out;
  107262. }
  107263. /* residue backend settings */
  107264. ci->residues=oggpack_read(opb,6)+1;
  107265. /*ci->residue_type=_ogg_malloc(ci->residues*sizeof(*ci->residue_type));*/
  107266. /*ci->residue_param=_ogg_calloc(ci->residues,sizeof(void *));*/
  107267. for(i=0;i<ci->residues;i++){
  107268. ci->residue_type[i]=oggpack_read(opb,16);
  107269. if(ci->residue_type[i]<0 || ci->residue_type[i]>=VI_RESB)goto err_out;
  107270. ci->residue_param[i]=_residue_P[ci->residue_type[i]]->unpack(vi,opb);
  107271. if(!ci->residue_param[i])goto err_out;
  107272. }
  107273. /* map backend settings */
  107274. ci->maps=oggpack_read(opb,6)+1;
  107275. /*ci->map_type=_ogg_malloc(ci->maps*sizeof(*ci->map_type));*/
  107276. /*ci->map_param=_ogg_calloc(ci->maps,sizeof(void *));*/
  107277. for(i=0;i<ci->maps;i++){
  107278. ci->map_type[i]=oggpack_read(opb,16);
  107279. if(ci->map_type[i]<0 || ci->map_type[i]>=VI_MAPB)goto err_out;
  107280. ci->map_param[i]=_mapping_P[ci->map_type[i]]->unpack(vi,opb);
  107281. if(!ci->map_param[i])goto err_out;
  107282. }
  107283. /* mode settings */
  107284. ci->modes=oggpack_read(opb,6)+1;
  107285. /*vi->mode_param=_ogg_calloc(vi->modes,sizeof(void *));*/
  107286. for(i=0;i<ci->modes;i++){
  107287. ci->mode_param[i]=(vorbis_info_mode*)_ogg_calloc(1,sizeof(*ci->mode_param[i]));
  107288. ci->mode_param[i]->blockflag=oggpack_read(opb,1);
  107289. ci->mode_param[i]->windowtype=oggpack_read(opb,16);
  107290. ci->mode_param[i]->transformtype=oggpack_read(opb,16);
  107291. ci->mode_param[i]->mapping=oggpack_read(opb,8);
  107292. if(ci->mode_param[i]->windowtype>=VI_WINDOWB)goto err_out;
  107293. if(ci->mode_param[i]->transformtype>=VI_WINDOWB)goto err_out;
  107294. if(ci->mode_param[i]->mapping>=ci->maps)goto err_out;
  107295. }
  107296. if(oggpack_read(opb,1)!=1)goto err_out; /* top level EOP check */
  107297. return(0);
  107298. err_out:
  107299. vorbis_info_clear(vi);
  107300. return(OV_EBADHEADER);
  107301. }
  107302. /* The Vorbis header is in three packets; the initial small packet in
  107303. the first page that identifies basic parameters, a second packet
  107304. with bitstream comments and a third packet that holds the
  107305. codebook. */
  107306. int vorbis_synthesis_headerin(vorbis_info *vi,vorbis_comment *vc,ogg_packet *op){
  107307. oggpack_buffer opb;
  107308. if(op){
  107309. oggpack_readinit(&opb,op->packet,op->bytes);
  107310. /* Which of the three types of header is this? */
  107311. /* Also verify header-ness, vorbis */
  107312. {
  107313. char buffer[6];
  107314. int packtype=oggpack_read(&opb,8);
  107315. memset(buffer,0,6);
  107316. _v_readstring(&opb,buffer,6);
  107317. if(memcmp(buffer,"vorbis",6)){
  107318. /* not a vorbis header */
  107319. return(OV_ENOTVORBIS);
  107320. }
  107321. switch(packtype){
  107322. case 0x01: /* least significant *bit* is read first */
  107323. if(!op->b_o_s){
  107324. /* Not the initial packet */
  107325. return(OV_EBADHEADER);
  107326. }
  107327. if(vi->rate!=0){
  107328. /* previously initialized info header */
  107329. return(OV_EBADHEADER);
  107330. }
  107331. return(_vorbis_unpack_info(vi,&opb));
  107332. case 0x03: /* least significant *bit* is read first */
  107333. if(vi->rate==0){
  107334. /* um... we didn't get the initial header */
  107335. return(OV_EBADHEADER);
  107336. }
  107337. return(_vorbis_unpack_comment(vc,&opb));
  107338. case 0x05: /* least significant *bit* is read first */
  107339. if(vi->rate==0 || vc->vendor==NULL){
  107340. /* um... we didn;t get the initial header or comments yet */
  107341. return(OV_EBADHEADER);
  107342. }
  107343. return(_vorbis_unpack_books(vi,&opb));
  107344. default:
  107345. /* Not a valid vorbis header type */
  107346. return(OV_EBADHEADER);
  107347. break;
  107348. }
  107349. }
  107350. }
  107351. return(OV_EBADHEADER);
  107352. }
  107353. /* pack side **********************************************************/
  107354. static int _vorbis_pack_info(oggpack_buffer *opb,vorbis_info *vi){
  107355. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  107356. if(!ci)return(OV_EFAULT);
  107357. /* preamble */
  107358. oggpack_write(opb,0x01,8);
  107359. _v_writestring(opb,"vorbis", 6);
  107360. /* basic information about the stream */
  107361. oggpack_write(opb,0x00,32);
  107362. oggpack_write(opb,vi->channels,8);
  107363. oggpack_write(opb,vi->rate,32);
  107364. oggpack_write(opb,vi->bitrate_upper,32);
  107365. oggpack_write(opb,vi->bitrate_nominal,32);
  107366. oggpack_write(opb,vi->bitrate_lower,32);
  107367. oggpack_write(opb,ilog2(ci->blocksizes[0]),4);
  107368. oggpack_write(opb,ilog2(ci->blocksizes[1]),4);
  107369. oggpack_write(opb,1,1);
  107370. return(0);
  107371. }
  107372. static int _vorbis_pack_comment(oggpack_buffer *opb,vorbis_comment *vc){
  107373. char temp[]="Xiph.Org libVorbis I 20050304";
  107374. int bytes = strlen(temp);
  107375. /* preamble */
  107376. oggpack_write(opb,0x03,8);
  107377. _v_writestring(opb,"vorbis", 6);
  107378. /* vendor */
  107379. oggpack_write(opb,bytes,32);
  107380. _v_writestring(opb,temp, bytes);
  107381. /* comments */
  107382. oggpack_write(opb,vc->comments,32);
  107383. if(vc->comments){
  107384. int i;
  107385. for(i=0;i<vc->comments;i++){
  107386. if(vc->user_comments[i]){
  107387. oggpack_write(opb,vc->comment_lengths[i],32);
  107388. _v_writestring(opb,vc->user_comments[i], vc->comment_lengths[i]);
  107389. }else{
  107390. oggpack_write(opb,0,32);
  107391. }
  107392. }
  107393. }
  107394. oggpack_write(opb,1,1);
  107395. return(0);
  107396. }
  107397. static int _vorbis_pack_books(oggpack_buffer *opb,vorbis_info *vi){
  107398. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  107399. int i;
  107400. if(!ci)return(OV_EFAULT);
  107401. oggpack_write(opb,0x05,8);
  107402. _v_writestring(opb,"vorbis", 6);
  107403. /* books */
  107404. oggpack_write(opb,ci->books-1,8);
  107405. for(i=0;i<ci->books;i++)
  107406. if(vorbis_staticbook_pack(ci->book_param[i],opb))goto err_out;
  107407. /* times; hook placeholders */
  107408. oggpack_write(opb,0,6);
  107409. oggpack_write(opb,0,16);
  107410. /* floors */
  107411. oggpack_write(opb,ci->floors-1,6);
  107412. for(i=0;i<ci->floors;i++){
  107413. oggpack_write(opb,ci->floor_type[i],16);
  107414. if(_floor_P[ci->floor_type[i]]->pack)
  107415. _floor_P[ci->floor_type[i]]->pack(ci->floor_param[i],opb);
  107416. else
  107417. goto err_out;
  107418. }
  107419. /* residues */
  107420. oggpack_write(opb,ci->residues-1,6);
  107421. for(i=0;i<ci->residues;i++){
  107422. oggpack_write(opb,ci->residue_type[i],16);
  107423. _residue_P[ci->residue_type[i]]->pack(ci->residue_param[i],opb);
  107424. }
  107425. /* maps */
  107426. oggpack_write(opb,ci->maps-1,6);
  107427. for(i=0;i<ci->maps;i++){
  107428. oggpack_write(opb,ci->map_type[i],16);
  107429. _mapping_P[ci->map_type[i]]->pack(vi,ci->map_param[i],opb);
  107430. }
  107431. /* modes */
  107432. oggpack_write(opb,ci->modes-1,6);
  107433. for(i=0;i<ci->modes;i++){
  107434. oggpack_write(opb,ci->mode_param[i]->blockflag,1);
  107435. oggpack_write(opb,ci->mode_param[i]->windowtype,16);
  107436. oggpack_write(opb,ci->mode_param[i]->transformtype,16);
  107437. oggpack_write(opb,ci->mode_param[i]->mapping,8);
  107438. }
  107439. oggpack_write(opb,1,1);
  107440. return(0);
  107441. err_out:
  107442. return(-1);
  107443. }
  107444. int vorbis_commentheader_out(vorbis_comment *vc,
  107445. ogg_packet *op){
  107446. oggpack_buffer opb;
  107447. oggpack_writeinit(&opb);
  107448. if(_vorbis_pack_comment(&opb,vc)) return OV_EIMPL;
  107449. op->packet = (unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  107450. memcpy(op->packet, opb.buffer, oggpack_bytes(&opb));
  107451. op->bytes=oggpack_bytes(&opb);
  107452. op->b_o_s=0;
  107453. op->e_o_s=0;
  107454. op->granulepos=0;
  107455. op->packetno=1;
  107456. return 0;
  107457. }
  107458. int vorbis_analysis_headerout(vorbis_dsp_state *v,
  107459. vorbis_comment *vc,
  107460. ogg_packet *op,
  107461. ogg_packet *op_comm,
  107462. ogg_packet *op_code){
  107463. int ret=OV_EIMPL;
  107464. vorbis_info *vi=v->vi;
  107465. oggpack_buffer opb;
  107466. private_state *b=(private_state*)v->backend_state;
  107467. if(!b){
  107468. ret=OV_EFAULT;
  107469. goto err_out;
  107470. }
  107471. /* first header packet **********************************************/
  107472. oggpack_writeinit(&opb);
  107473. if(_vorbis_pack_info(&opb,vi))goto err_out;
  107474. /* build the packet */
  107475. if(b->header)_ogg_free(b->header);
  107476. b->header=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  107477. memcpy(b->header,opb.buffer,oggpack_bytes(&opb));
  107478. op->packet=b->header;
  107479. op->bytes=oggpack_bytes(&opb);
  107480. op->b_o_s=1;
  107481. op->e_o_s=0;
  107482. op->granulepos=0;
  107483. op->packetno=0;
  107484. /* second header packet (comments) **********************************/
  107485. oggpack_reset(&opb);
  107486. if(_vorbis_pack_comment(&opb,vc))goto err_out;
  107487. if(b->header1)_ogg_free(b->header1);
  107488. b->header1=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  107489. memcpy(b->header1,opb.buffer,oggpack_bytes(&opb));
  107490. op_comm->packet=b->header1;
  107491. op_comm->bytes=oggpack_bytes(&opb);
  107492. op_comm->b_o_s=0;
  107493. op_comm->e_o_s=0;
  107494. op_comm->granulepos=0;
  107495. op_comm->packetno=1;
  107496. /* third header packet (modes/codebooks) ****************************/
  107497. oggpack_reset(&opb);
  107498. if(_vorbis_pack_books(&opb,vi))goto err_out;
  107499. if(b->header2)_ogg_free(b->header2);
  107500. b->header2=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  107501. memcpy(b->header2,opb.buffer,oggpack_bytes(&opb));
  107502. op_code->packet=b->header2;
  107503. op_code->bytes=oggpack_bytes(&opb);
  107504. op_code->b_o_s=0;
  107505. op_code->e_o_s=0;
  107506. op_code->granulepos=0;
  107507. op_code->packetno=2;
  107508. oggpack_writeclear(&opb);
  107509. return(0);
  107510. err_out:
  107511. oggpack_writeclear(&opb);
  107512. memset(op,0,sizeof(*op));
  107513. memset(op_comm,0,sizeof(*op_comm));
  107514. memset(op_code,0,sizeof(*op_code));
  107515. if(b->header)_ogg_free(b->header);
  107516. if(b->header1)_ogg_free(b->header1);
  107517. if(b->header2)_ogg_free(b->header2);
  107518. b->header=NULL;
  107519. b->header1=NULL;
  107520. b->header2=NULL;
  107521. return(ret);
  107522. }
  107523. double vorbis_granule_time(vorbis_dsp_state *v,ogg_int64_t granulepos){
  107524. if(granulepos>=0)
  107525. return((double)granulepos/v->vi->rate);
  107526. return(-1);
  107527. }
  107528. #endif
  107529. /********* End of inlined file: info.c *********/
  107530. /********* Start of inlined file: lpc.c *********/
  107531. /* Some of these routines (autocorrelator, LPC coefficient estimator)
  107532. are derived from code written by Jutta Degener and Carsten Bormann;
  107533. thus we include their copyright below. The entirety of this file
  107534. is freely redistributable on the condition that both of these
  107535. copyright notices are preserved without modification. */
  107536. /* Preserved Copyright: *********************************************/
  107537. /* Copyright 1992, 1993, 1994 by Jutta Degener and Carsten Bormann,
  107538. Technische Universita"t Berlin
  107539. Any use of this software is permitted provided that this notice is not
  107540. removed and that neither the authors nor the Technische Universita"t
  107541. Berlin are deemed to have made any representations as to the
  107542. suitability of this software for any purpose nor are held responsible
  107543. for any defects of this software. THERE IS ABSOLUTELY NO WARRANTY FOR
  107544. THIS SOFTWARE.
  107545. As a matter of courtesy, the authors request to be informed about uses
  107546. this software has found, about bugs in this software, and about any
  107547. improvements that may be of general interest.
  107548. Berlin, 28.11.1994
  107549. Jutta Degener
  107550. Carsten Bormann
  107551. *********************************************************************/
  107552. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  107553. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  107554. // tasks..
  107555. #ifdef _MSC_VER
  107556. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  107557. #endif
  107558. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  107559. #if JUCE_USE_OGGVORBIS
  107560. #include <stdlib.h>
  107561. #include <string.h>
  107562. #include <math.h>
  107563. /* Autocorrelation LPC coeff generation algorithm invented by
  107564. N. Levinson in 1947, modified by J. Durbin in 1959. */
  107565. /* Input : n elements of time doamin data
  107566. Output: m lpc coefficients, excitation energy */
  107567. float vorbis_lpc_from_data(float *data,float *lpci,int n,int m){
  107568. double *aut=(double*)alloca(sizeof(*aut)*(m+1));
  107569. double *lpc=(double*)alloca(sizeof(*lpc)*(m));
  107570. double error;
  107571. int i,j;
  107572. /* autocorrelation, p+1 lag coefficients */
  107573. j=m+1;
  107574. while(j--){
  107575. double d=0; /* double needed for accumulator depth */
  107576. for(i=j;i<n;i++)d+=(double)data[i]*data[i-j];
  107577. aut[j]=d;
  107578. }
  107579. /* Generate lpc coefficients from autocorr values */
  107580. error=aut[0];
  107581. for(i=0;i<m;i++){
  107582. double r= -aut[i+1];
  107583. if(error==0){
  107584. memset(lpci,0,m*sizeof(*lpci));
  107585. return 0;
  107586. }
  107587. /* Sum up this iteration's reflection coefficient; note that in
  107588. Vorbis we don't save it. If anyone wants to recycle this code
  107589. and needs reflection coefficients, save the results of 'r' from
  107590. each iteration. */
  107591. for(j=0;j<i;j++)r-=lpc[j]*aut[i-j];
  107592. r/=error;
  107593. /* Update LPC coefficients and total error */
  107594. lpc[i]=r;
  107595. for(j=0;j<i/2;j++){
  107596. double tmp=lpc[j];
  107597. lpc[j]+=r*lpc[i-1-j];
  107598. lpc[i-1-j]+=r*tmp;
  107599. }
  107600. if(i%2)lpc[j]+=lpc[j]*r;
  107601. error*=1.f-r*r;
  107602. }
  107603. for(j=0;j<m;j++)lpci[j]=(float)lpc[j];
  107604. /* we need the error value to know how big an impulse to hit the
  107605. filter with later */
  107606. return error;
  107607. }
  107608. void vorbis_lpc_predict(float *coeff,float *prime,int m,
  107609. float *data,long n){
  107610. /* in: coeff[0...m-1] LPC coefficients
  107611. prime[0...m-1] initial values (allocated size of n+m-1)
  107612. out: data[0...n-1] data samples */
  107613. long i,j,o,p;
  107614. float y;
  107615. float *work=(float*)alloca(sizeof(*work)*(m+n));
  107616. if(!prime)
  107617. for(i=0;i<m;i++)
  107618. work[i]=0.f;
  107619. else
  107620. for(i=0;i<m;i++)
  107621. work[i]=prime[i];
  107622. for(i=0;i<n;i++){
  107623. y=0;
  107624. o=i;
  107625. p=m;
  107626. for(j=0;j<m;j++)
  107627. y-=work[o++]*coeff[--p];
  107628. data[i]=work[o]=y;
  107629. }
  107630. }
  107631. #endif
  107632. /********* End of inlined file: lpc.c *********/
  107633. /********* Start of inlined file: lsp.c *********/
  107634. /* Note that the lpc-lsp conversion finds the roots of polynomial with
  107635. an iterative root polisher (CACM algorithm 283). It *is* possible
  107636. to confuse this algorithm into not converging; that should only
  107637. happen with absurdly closely spaced roots (very sharp peaks in the
  107638. LPC f response) which in turn should be impossible in our use of
  107639. the code. If this *does* happen anyway, it's a bug in the floor
  107640. finder; find the cause of the confusion (probably a single bin
  107641. spike or accidental near-float-limit resolution problems) and
  107642. correct it. */
  107643. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  107644. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  107645. // tasks..
  107646. #ifdef _MSC_VER
  107647. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  107648. #endif
  107649. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  107650. #if JUCE_USE_OGGVORBIS
  107651. #include <math.h>
  107652. #include <string.h>
  107653. #include <stdlib.h>
  107654. /********* Start of inlined file: lookup.h *********/
  107655. #ifndef _V_LOOKUP_H_
  107656. #ifdef FLOAT_LOOKUP
  107657. extern float vorbis_coslook(float a);
  107658. extern float vorbis_invsqlook(float a);
  107659. extern float vorbis_invsq2explook(int a);
  107660. extern float vorbis_fromdBlook(float a);
  107661. #endif
  107662. #ifdef INT_LOOKUP
  107663. extern long vorbis_invsqlook_i(long a,long e);
  107664. extern long vorbis_coslook_i(long a);
  107665. extern float vorbis_fromdBlook_i(long a);
  107666. #endif
  107667. #endif
  107668. /********* End of inlined file: lookup.h *********/
  107669. /* three possible LSP to f curve functions; the exact computation
  107670. (float), a lookup based float implementation, and an integer
  107671. implementation. The float lookup is likely the optimal choice on
  107672. any machine with an FPU. The integer implementation is *not* fixed
  107673. point (due to the need for a large dynamic range and thus a
  107674. seperately tracked exponent) and thus much more complex than the
  107675. relatively simple float implementations. It's mostly for future
  107676. work on a fully fixed point implementation for processors like the
  107677. ARM family. */
  107678. /* undefine both for the 'old' but more precise implementation */
  107679. #define FLOAT_LOOKUP
  107680. #undef INT_LOOKUP
  107681. #ifdef FLOAT_LOOKUP
  107682. /********* Start of inlined file: lookup.c *********/
  107683. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  107684. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  107685. // tasks..
  107686. #ifdef _MSC_VER
  107687. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  107688. #endif
  107689. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  107690. #if JUCE_USE_OGGVORBIS
  107691. #include <math.h>
  107692. /********* Start of inlined file: lookup.h *********/
  107693. #ifndef _V_LOOKUP_H_
  107694. #ifdef FLOAT_LOOKUP
  107695. extern float vorbis_coslook(float a);
  107696. extern float vorbis_invsqlook(float a);
  107697. extern float vorbis_invsq2explook(int a);
  107698. extern float vorbis_fromdBlook(float a);
  107699. #endif
  107700. #ifdef INT_LOOKUP
  107701. extern long vorbis_invsqlook_i(long a,long e);
  107702. extern long vorbis_coslook_i(long a);
  107703. extern float vorbis_fromdBlook_i(long a);
  107704. #endif
  107705. #endif
  107706. /********* End of inlined file: lookup.h *********/
  107707. /********* Start of inlined file: lookup_data.h *********/
  107708. #ifndef _V_LOOKUP_DATA_H_
  107709. #ifdef FLOAT_LOOKUP
  107710. #define COS_LOOKUP_SZ 128
  107711. static float COS_LOOKUP[COS_LOOKUP_SZ+1]={
  107712. +1.0000000000000f,+0.9996988186962f,+0.9987954562052f,+0.9972904566787f,
  107713. +0.9951847266722f,+0.9924795345987f,+0.9891765099648f,+0.9852776423889f,
  107714. +0.9807852804032f,+0.9757021300385f,+0.9700312531945f,+0.9637760657954f,
  107715. +0.9569403357322f,+0.9495281805930f,+0.9415440651830f,+0.9329927988347f,
  107716. +0.9238795325113f,+0.9142097557035f,+0.9039892931234f,+0.8932243011955f,
  107717. +0.8819212643484f,+0.8700869911087f,+0.8577286100003f,+0.8448535652497f,
  107718. +0.8314696123025f,+0.8175848131516f,+0.8032075314806f,+0.7883464276266f,
  107719. +0.7730104533627f,+0.7572088465065f,+0.7409511253550f,+0.7242470829515f,
  107720. +0.7071067811865f,+0.6895405447371f,+0.6715589548470f,+0.6531728429538f,
  107721. +0.6343932841636f,+0.6152315905806f,+0.5956993044924f,+0.5758081914178f,
  107722. +0.5555702330196f,+0.5349976198871f,+0.5141027441932f,+0.4928981922298f,
  107723. +0.4713967368260f,+0.4496113296546f,+0.4275550934303f,+0.4052413140050f,
  107724. +0.3826834323651f,+0.3598950365350f,+0.3368898533922f,+0.3136817403989f,
  107725. +0.2902846772545f,+0.2667127574749f,+0.2429801799033f,+0.2191012401569f,
  107726. +0.1950903220161f,+0.1709618887603f,+0.1467304744554f,+0.1224106751992f,
  107727. +0.0980171403296f,+0.0735645635997f,+0.0490676743274f,+0.0245412285229f,
  107728. +0.0000000000000f,-0.0245412285229f,-0.0490676743274f,-0.0735645635997f,
  107729. -0.0980171403296f,-0.1224106751992f,-0.1467304744554f,-0.1709618887603f,
  107730. -0.1950903220161f,-0.2191012401569f,-0.2429801799033f,-0.2667127574749f,
  107731. -0.2902846772545f,-0.3136817403989f,-0.3368898533922f,-0.3598950365350f,
  107732. -0.3826834323651f,-0.4052413140050f,-0.4275550934303f,-0.4496113296546f,
  107733. -0.4713967368260f,-0.4928981922298f,-0.5141027441932f,-0.5349976198871f,
  107734. -0.5555702330196f,-0.5758081914178f,-0.5956993044924f,-0.6152315905806f,
  107735. -0.6343932841636f,-0.6531728429538f,-0.6715589548470f,-0.6895405447371f,
  107736. -0.7071067811865f,-0.7242470829515f,-0.7409511253550f,-0.7572088465065f,
  107737. -0.7730104533627f,-0.7883464276266f,-0.8032075314806f,-0.8175848131516f,
  107738. -0.8314696123025f,-0.8448535652497f,-0.8577286100003f,-0.8700869911087f,
  107739. -0.8819212643484f,-0.8932243011955f,-0.9039892931234f,-0.9142097557035f,
  107740. -0.9238795325113f,-0.9329927988347f,-0.9415440651830f,-0.9495281805930f,
  107741. -0.9569403357322f,-0.9637760657954f,-0.9700312531945f,-0.9757021300385f,
  107742. -0.9807852804032f,-0.9852776423889f,-0.9891765099648f,-0.9924795345987f,
  107743. -0.9951847266722f,-0.9972904566787f,-0.9987954562052f,-0.9996988186962f,
  107744. -1.0000000000000f,
  107745. };
  107746. #define INVSQ_LOOKUP_SZ 32
  107747. static float INVSQ_LOOKUP[INVSQ_LOOKUP_SZ+1]={
  107748. 1.414213562373f,1.392621247646f,1.371988681140f,1.352246807566f,
  107749. 1.333333333333f,1.315191898443f,1.297771369046f,1.281025230441f,
  107750. 1.264911064067f,1.249390095109f,1.234426799697f,1.219988562661f,
  107751. 1.206045378311f,1.192569588000f,1.179535649239f,1.166919931983f,
  107752. 1.154700538379f,1.142857142857f,1.131370849898f,1.120224067222f,
  107753. 1.109400392450f,1.098884511590f,1.088662107904f,1.078719779941f,
  107754. 1.069044967650f,1.059625885652f,1.050451462878f,1.041511287847f,
  107755. 1.032795558989f,1.024295039463f,1.016001016002f,1.007905261358f,
  107756. 1.000000000000f,
  107757. };
  107758. #define INVSQ2EXP_LOOKUP_MIN (-32)
  107759. #define INVSQ2EXP_LOOKUP_MAX 32
  107760. static float INVSQ2EXP_LOOKUP[INVSQ2EXP_LOOKUP_MAX-\
  107761. INVSQ2EXP_LOOKUP_MIN+1]={
  107762. 65536.f, 46340.95001f, 32768.f, 23170.47501f,
  107763. 16384.f, 11585.2375f, 8192.f, 5792.618751f,
  107764. 4096.f, 2896.309376f, 2048.f, 1448.154688f,
  107765. 1024.f, 724.0773439f, 512.f, 362.038672f,
  107766. 256.f, 181.019336f, 128.f, 90.50966799f,
  107767. 64.f, 45.254834f, 32.f, 22.627417f,
  107768. 16.f, 11.3137085f, 8.f, 5.656854249f,
  107769. 4.f, 2.828427125f, 2.f, 1.414213562f,
  107770. 1.f, 0.7071067812f, 0.5f, 0.3535533906f,
  107771. 0.25f, 0.1767766953f, 0.125f, 0.08838834765f,
  107772. 0.0625f, 0.04419417382f, 0.03125f, 0.02209708691f,
  107773. 0.015625f, 0.01104854346f, 0.0078125f, 0.005524271728f,
  107774. 0.00390625f, 0.002762135864f, 0.001953125f, 0.001381067932f,
  107775. 0.0009765625f, 0.000690533966f, 0.00048828125f, 0.000345266983f,
  107776. 0.000244140625f,0.0001726334915f,0.0001220703125f,8.631674575e-05f,
  107777. 6.103515625e-05f,4.315837288e-05f,3.051757812e-05f,2.157918644e-05f,
  107778. 1.525878906e-05f,
  107779. };
  107780. #endif
  107781. #define FROMdB_LOOKUP_SZ 35
  107782. #define FROMdB2_LOOKUP_SZ 32
  107783. #define FROMdB_SHIFT 5
  107784. #define FROMdB2_SHIFT 3
  107785. #define FROMdB2_MASK 31
  107786. static float FROMdB_LOOKUP[FROMdB_LOOKUP_SZ]={
  107787. 1.f, 0.6309573445f, 0.3981071706f, 0.2511886432f,
  107788. 0.1584893192f, 0.1f, 0.06309573445f, 0.03981071706f,
  107789. 0.02511886432f, 0.01584893192f, 0.01f, 0.006309573445f,
  107790. 0.003981071706f, 0.002511886432f, 0.001584893192f, 0.001f,
  107791. 0.0006309573445f,0.0003981071706f,0.0002511886432f,0.0001584893192f,
  107792. 0.0001f,6.309573445e-05f,3.981071706e-05f,2.511886432e-05f,
  107793. 1.584893192e-05f, 1e-05f,6.309573445e-06f,3.981071706e-06f,
  107794. 2.511886432e-06f,1.584893192e-06f, 1e-06f,6.309573445e-07f,
  107795. 3.981071706e-07f,2.511886432e-07f,1.584893192e-07f,
  107796. };
  107797. static float FROMdB2_LOOKUP[FROMdB2_LOOKUP_SZ]={
  107798. 0.9928302478f, 0.9786445908f, 0.9646616199f, 0.9508784391f,
  107799. 0.9372921937f, 0.92390007f, 0.9106992942f, 0.8976871324f,
  107800. 0.8848608897f, 0.8722179097f, 0.8597555737f, 0.8474713009f,
  107801. 0.835362547f, 0.8234268041f, 0.8116616003f, 0.8000644989f,
  107802. 0.7886330981f, 0.7773650302f, 0.7662579617f, 0.755309592f,
  107803. 0.7445176537f, 0.7338799116f, 0.7233941627f, 0.7130582353f,
  107804. 0.7028699885f, 0.6928273125f, 0.6829281272f, 0.6731703824f,
  107805. 0.6635520573f, 0.6540711597f, 0.6447257262f, 0.6355138211f,
  107806. };
  107807. #ifdef INT_LOOKUP
  107808. #define INVSQ_LOOKUP_I_SHIFT 10
  107809. #define INVSQ_LOOKUP_I_MASK 1023
  107810. static long INVSQ_LOOKUP_I[64+1]={
  107811. 92682l, 91966l, 91267l, 90583l,
  107812. 89915l, 89261l, 88621l, 87995l,
  107813. 87381l, 86781l, 86192l, 85616l,
  107814. 85051l, 84497l, 83953l, 83420l,
  107815. 82897l, 82384l, 81880l, 81385l,
  107816. 80899l, 80422l, 79953l, 79492l,
  107817. 79039l, 78594l, 78156l, 77726l,
  107818. 77302l, 76885l, 76475l, 76072l,
  107819. 75674l, 75283l, 74898l, 74519l,
  107820. 74146l, 73778l, 73415l, 73058l,
  107821. 72706l, 72359l, 72016l, 71679l,
  107822. 71347l, 71019l, 70695l, 70376l,
  107823. 70061l, 69750l, 69444l, 69141l,
  107824. 68842l, 68548l, 68256l, 67969l,
  107825. 67685l, 67405l, 67128l, 66855l,
  107826. 66585l, 66318l, 66054l, 65794l,
  107827. 65536l,
  107828. };
  107829. #define COS_LOOKUP_I_SHIFT 9
  107830. #define COS_LOOKUP_I_MASK 511
  107831. #define COS_LOOKUP_I_SZ 128
  107832. static long COS_LOOKUP_I[COS_LOOKUP_I_SZ+1]={
  107833. 16384l, 16379l, 16364l, 16340l,
  107834. 16305l, 16261l, 16207l, 16143l,
  107835. 16069l, 15986l, 15893l, 15791l,
  107836. 15679l, 15557l, 15426l, 15286l,
  107837. 15137l, 14978l, 14811l, 14635l,
  107838. 14449l, 14256l, 14053l, 13842l,
  107839. 13623l, 13395l, 13160l, 12916l,
  107840. 12665l, 12406l, 12140l, 11866l,
  107841. 11585l, 11297l, 11003l, 10702l,
  107842. 10394l, 10080l, 9760l, 9434l,
  107843. 9102l, 8765l, 8423l, 8076l,
  107844. 7723l, 7366l, 7005l, 6639l,
  107845. 6270l, 5897l, 5520l, 5139l,
  107846. 4756l, 4370l, 3981l, 3590l,
  107847. 3196l, 2801l, 2404l, 2006l,
  107848. 1606l, 1205l, 804l, 402l,
  107849. 0l, -401l, -803l, -1204l,
  107850. -1605l, -2005l, -2403l, -2800l,
  107851. -3195l, -3589l, -3980l, -4369l,
  107852. -4755l, -5138l, -5519l, -5896l,
  107853. -6269l, -6638l, -7004l, -7365l,
  107854. -7722l, -8075l, -8422l, -8764l,
  107855. -9101l, -9433l, -9759l, -10079l,
  107856. -10393l, -10701l, -11002l, -11296l,
  107857. -11584l, -11865l, -12139l, -12405l,
  107858. -12664l, -12915l, -13159l, -13394l,
  107859. -13622l, -13841l, -14052l, -14255l,
  107860. -14448l, -14634l, -14810l, -14977l,
  107861. -15136l, -15285l, -15425l, -15556l,
  107862. -15678l, -15790l, -15892l, -15985l,
  107863. -16068l, -16142l, -16206l, -16260l,
  107864. -16304l, -16339l, -16363l, -16378l,
  107865. -16383l,
  107866. };
  107867. #endif
  107868. #endif
  107869. /********* End of inlined file: lookup_data.h *********/
  107870. #ifdef FLOAT_LOOKUP
  107871. /* interpolated lookup based cos function, domain 0 to PI only */
  107872. float vorbis_coslook(float a){
  107873. double d=a*(.31830989*(float)COS_LOOKUP_SZ);
  107874. int i=vorbis_ftoi(d-.5);
  107875. return COS_LOOKUP[i]+ (d-i)*(COS_LOOKUP[i+1]-COS_LOOKUP[i]);
  107876. }
  107877. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  107878. float vorbis_invsqlook(float a){
  107879. double d=a*(2.f*(float)INVSQ_LOOKUP_SZ)-(float)INVSQ_LOOKUP_SZ;
  107880. int i=vorbis_ftoi(d-.5f);
  107881. return INVSQ_LOOKUP[i]+ (d-i)*(INVSQ_LOOKUP[i+1]-INVSQ_LOOKUP[i]);
  107882. }
  107883. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  107884. float vorbis_invsq2explook(int a){
  107885. return INVSQ2EXP_LOOKUP[a-INVSQ2EXP_LOOKUP_MIN];
  107886. }
  107887. #include <stdio.h>
  107888. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  107889. float vorbis_fromdBlook(float a){
  107890. int i=vorbis_ftoi(a*((float)(-(1<<FROMdB2_SHIFT)))-.5f);
  107891. return (i<0)?1.f:
  107892. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  107893. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  107894. }
  107895. #endif
  107896. #ifdef INT_LOOKUP
  107897. /* interpolated 1./sqrt(p) where .5 <= a < 1. (.100000... to .111111...) in
  107898. 16.16 format
  107899. returns in m.8 format */
  107900. long vorbis_invsqlook_i(long a,long e){
  107901. long i=(a&0x7fff)>>(INVSQ_LOOKUP_I_SHIFT-1);
  107902. long d=(a&INVSQ_LOOKUP_I_MASK)<<(16-INVSQ_LOOKUP_I_SHIFT); /* 0.16 */
  107903. long val=INVSQ_LOOKUP_I[i]- /* 1.16 */
  107904. (((INVSQ_LOOKUP_I[i]-INVSQ_LOOKUP_I[i+1])* /* 0.16 */
  107905. d)>>16); /* result 1.16 */
  107906. e+=32;
  107907. if(e&1)val=(val*5792)>>13; /* multiply val by 1/sqrt(2) */
  107908. e=(e>>1)-8;
  107909. return(val>>e);
  107910. }
  107911. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  107912. /* a is in n.12 format */
  107913. float vorbis_fromdBlook_i(long a){
  107914. int i=(-a)>>(12-FROMdB2_SHIFT);
  107915. return (i<0)?1.f:
  107916. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  107917. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  107918. }
  107919. /* interpolated lookup based cos function, domain 0 to PI only */
  107920. /* a is in 0.16 format, where 0==0, 2^^16-1==PI, return 0.14 */
  107921. long vorbis_coslook_i(long a){
  107922. int i=a>>COS_LOOKUP_I_SHIFT;
  107923. int d=a&COS_LOOKUP_I_MASK;
  107924. return COS_LOOKUP_I[i]- ((d*(COS_LOOKUP_I[i]-COS_LOOKUP_I[i+1]))>>
  107925. COS_LOOKUP_I_SHIFT);
  107926. }
  107927. #endif
  107928. #endif
  107929. /********* End of inlined file: lookup.c *********/
  107930. /* catch this in the build system; we #include for
  107931. compilers (like gcc) that can't inline across
  107932. modules */
  107933. /* side effect: changes *lsp to cosines of lsp */
  107934. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  107935. float amp,float ampoffset){
  107936. int i;
  107937. float wdel=M_PI/ln;
  107938. vorbis_fpu_control fpu;
  107939. (void) fpu; // to avoid an unused variable warning
  107940. vorbis_fpu_setround(&fpu);
  107941. for(i=0;i<m;i++)lsp[i]=vorbis_coslook(lsp[i]);
  107942. i=0;
  107943. while(i<n){
  107944. int k=map[i];
  107945. int qexp;
  107946. float p=.7071067812f;
  107947. float q=.7071067812f;
  107948. float w=vorbis_coslook(wdel*k);
  107949. float *ftmp=lsp;
  107950. int c=m>>1;
  107951. do{
  107952. q*=ftmp[0]-w;
  107953. p*=ftmp[1]-w;
  107954. ftmp+=2;
  107955. }while(--c);
  107956. if(m&1){
  107957. /* odd order filter; slightly assymetric */
  107958. /* the last coefficient */
  107959. q*=ftmp[0]-w;
  107960. q*=q;
  107961. p*=p*(1.f-w*w);
  107962. }else{
  107963. /* even order filter; still symmetric */
  107964. q*=q*(1.f+w);
  107965. p*=p*(1.f-w);
  107966. }
  107967. q=frexp(p+q,&qexp);
  107968. q=vorbis_fromdBlook(amp*
  107969. vorbis_invsqlook(q)*
  107970. vorbis_invsq2explook(qexp+m)-
  107971. ampoffset);
  107972. do{
  107973. curve[i++]*=q;
  107974. }while(map[i]==k);
  107975. }
  107976. vorbis_fpu_restore(fpu);
  107977. }
  107978. #else
  107979. #ifdef INT_LOOKUP
  107980. /********* Start of inlined file: lookup.c *********/
  107981. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  107982. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  107983. // tasks..
  107984. #ifdef _MSC_VER
  107985. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  107986. #endif
  107987. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  107988. #if JUCE_USE_OGGVORBIS
  107989. #include <math.h>
  107990. /********* Start of inlined file: lookup.h *********/
  107991. #ifndef _V_LOOKUP_H_
  107992. #ifdef FLOAT_LOOKUP
  107993. extern float vorbis_coslook(float a);
  107994. extern float vorbis_invsqlook(float a);
  107995. extern float vorbis_invsq2explook(int a);
  107996. extern float vorbis_fromdBlook(float a);
  107997. #endif
  107998. #ifdef INT_LOOKUP
  107999. extern long vorbis_invsqlook_i(long a,long e);
  108000. extern long vorbis_coslook_i(long a);
  108001. extern float vorbis_fromdBlook_i(long a);
  108002. #endif
  108003. #endif
  108004. /********* End of inlined file: lookup.h *********/
  108005. /********* Start of inlined file: lookup_data.h *********/
  108006. #ifndef _V_LOOKUP_DATA_H_
  108007. #ifdef FLOAT_LOOKUP
  108008. #define COS_LOOKUP_SZ 128
  108009. static float COS_LOOKUP[COS_LOOKUP_SZ+1]={
  108010. +1.0000000000000f,+0.9996988186962f,+0.9987954562052f,+0.9972904566787f,
  108011. +0.9951847266722f,+0.9924795345987f,+0.9891765099648f,+0.9852776423889f,
  108012. +0.9807852804032f,+0.9757021300385f,+0.9700312531945f,+0.9637760657954f,
  108013. +0.9569403357322f,+0.9495281805930f,+0.9415440651830f,+0.9329927988347f,
  108014. +0.9238795325113f,+0.9142097557035f,+0.9039892931234f,+0.8932243011955f,
  108015. +0.8819212643484f,+0.8700869911087f,+0.8577286100003f,+0.8448535652497f,
  108016. +0.8314696123025f,+0.8175848131516f,+0.8032075314806f,+0.7883464276266f,
  108017. +0.7730104533627f,+0.7572088465065f,+0.7409511253550f,+0.7242470829515f,
  108018. +0.7071067811865f,+0.6895405447371f,+0.6715589548470f,+0.6531728429538f,
  108019. +0.6343932841636f,+0.6152315905806f,+0.5956993044924f,+0.5758081914178f,
  108020. +0.5555702330196f,+0.5349976198871f,+0.5141027441932f,+0.4928981922298f,
  108021. +0.4713967368260f,+0.4496113296546f,+0.4275550934303f,+0.4052413140050f,
  108022. +0.3826834323651f,+0.3598950365350f,+0.3368898533922f,+0.3136817403989f,
  108023. +0.2902846772545f,+0.2667127574749f,+0.2429801799033f,+0.2191012401569f,
  108024. +0.1950903220161f,+0.1709618887603f,+0.1467304744554f,+0.1224106751992f,
  108025. +0.0980171403296f,+0.0735645635997f,+0.0490676743274f,+0.0245412285229f,
  108026. +0.0000000000000f,-0.0245412285229f,-0.0490676743274f,-0.0735645635997f,
  108027. -0.0980171403296f,-0.1224106751992f,-0.1467304744554f,-0.1709618887603f,
  108028. -0.1950903220161f,-0.2191012401569f,-0.2429801799033f,-0.2667127574749f,
  108029. -0.2902846772545f,-0.3136817403989f,-0.3368898533922f,-0.3598950365350f,
  108030. -0.3826834323651f,-0.4052413140050f,-0.4275550934303f,-0.4496113296546f,
  108031. -0.4713967368260f,-0.4928981922298f,-0.5141027441932f,-0.5349976198871f,
  108032. -0.5555702330196f,-0.5758081914178f,-0.5956993044924f,-0.6152315905806f,
  108033. -0.6343932841636f,-0.6531728429538f,-0.6715589548470f,-0.6895405447371f,
  108034. -0.7071067811865f,-0.7242470829515f,-0.7409511253550f,-0.7572088465065f,
  108035. -0.7730104533627f,-0.7883464276266f,-0.8032075314806f,-0.8175848131516f,
  108036. -0.8314696123025f,-0.8448535652497f,-0.8577286100003f,-0.8700869911087f,
  108037. -0.8819212643484f,-0.8932243011955f,-0.9039892931234f,-0.9142097557035f,
  108038. -0.9238795325113f,-0.9329927988347f,-0.9415440651830f,-0.9495281805930f,
  108039. -0.9569403357322f,-0.9637760657954f,-0.9700312531945f,-0.9757021300385f,
  108040. -0.9807852804032f,-0.9852776423889f,-0.9891765099648f,-0.9924795345987f,
  108041. -0.9951847266722f,-0.9972904566787f,-0.9987954562052f,-0.9996988186962f,
  108042. -1.0000000000000f,
  108043. };
  108044. #define INVSQ_LOOKUP_SZ 32
  108045. static float INVSQ_LOOKUP[INVSQ_LOOKUP_SZ+1]={
  108046. 1.414213562373f,1.392621247646f,1.371988681140f,1.352246807566f,
  108047. 1.333333333333f,1.315191898443f,1.297771369046f,1.281025230441f,
  108048. 1.264911064067f,1.249390095109f,1.234426799697f,1.219988562661f,
  108049. 1.206045378311f,1.192569588000f,1.179535649239f,1.166919931983f,
  108050. 1.154700538379f,1.142857142857f,1.131370849898f,1.120224067222f,
  108051. 1.109400392450f,1.098884511590f,1.088662107904f,1.078719779941f,
  108052. 1.069044967650f,1.059625885652f,1.050451462878f,1.041511287847f,
  108053. 1.032795558989f,1.024295039463f,1.016001016002f,1.007905261358f,
  108054. 1.000000000000f,
  108055. };
  108056. #define INVSQ2EXP_LOOKUP_MIN (-32)
  108057. #define INVSQ2EXP_LOOKUP_MAX 32
  108058. static float INVSQ2EXP_LOOKUP[INVSQ2EXP_LOOKUP_MAX-\
  108059. INVSQ2EXP_LOOKUP_MIN+1]={
  108060. 65536.f, 46340.95001f, 32768.f, 23170.47501f,
  108061. 16384.f, 11585.2375f, 8192.f, 5792.618751f,
  108062. 4096.f, 2896.309376f, 2048.f, 1448.154688f,
  108063. 1024.f, 724.0773439f, 512.f, 362.038672f,
  108064. 256.f, 181.019336f, 128.f, 90.50966799f,
  108065. 64.f, 45.254834f, 32.f, 22.627417f,
  108066. 16.f, 11.3137085f, 8.f, 5.656854249f,
  108067. 4.f, 2.828427125f, 2.f, 1.414213562f,
  108068. 1.f, 0.7071067812f, 0.5f, 0.3535533906f,
  108069. 0.25f, 0.1767766953f, 0.125f, 0.08838834765f,
  108070. 0.0625f, 0.04419417382f, 0.03125f, 0.02209708691f,
  108071. 0.015625f, 0.01104854346f, 0.0078125f, 0.005524271728f,
  108072. 0.00390625f, 0.002762135864f, 0.001953125f, 0.001381067932f,
  108073. 0.0009765625f, 0.000690533966f, 0.00048828125f, 0.000345266983f,
  108074. 0.000244140625f,0.0001726334915f,0.0001220703125f,8.631674575e-05f,
  108075. 6.103515625e-05f,4.315837288e-05f,3.051757812e-05f,2.157918644e-05f,
  108076. 1.525878906e-05f,
  108077. };
  108078. #endif
  108079. #define FROMdB_LOOKUP_SZ 35
  108080. #define FROMdB2_LOOKUP_SZ 32
  108081. #define FROMdB_SHIFT 5
  108082. #define FROMdB2_SHIFT 3
  108083. #define FROMdB2_MASK 31
  108084. static float FROMdB_LOOKUP[FROMdB_LOOKUP_SZ]={
  108085. 1.f, 0.6309573445f, 0.3981071706f, 0.2511886432f,
  108086. 0.1584893192f, 0.1f, 0.06309573445f, 0.03981071706f,
  108087. 0.02511886432f, 0.01584893192f, 0.01f, 0.006309573445f,
  108088. 0.003981071706f, 0.002511886432f, 0.001584893192f, 0.001f,
  108089. 0.0006309573445f,0.0003981071706f,0.0002511886432f,0.0001584893192f,
  108090. 0.0001f,6.309573445e-05f,3.981071706e-05f,2.511886432e-05f,
  108091. 1.584893192e-05f, 1e-05f,6.309573445e-06f,3.981071706e-06f,
  108092. 2.511886432e-06f,1.584893192e-06f, 1e-06f,6.309573445e-07f,
  108093. 3.981071706e-07f,2.511886432e-07f,1.584893192e-07f,
  108094. };
  108095. static float FROMdB2_LOOKUP[FROMdB2_LOOKUP_SZ]={
  108096. 0.9928302478f, 0.9786445908f, 0.9646616199f, 0.9508784391f,
  108097. 0.9372921937f, 0.92390007f, 0.9106992942f, 0.8976871324f,
  108098. 0.8848608897f, 0.8722179097f, 0.8597555737f, 0.8474713009f,
  108099. 0.835362547f, 0.8234268041f, 0.8116616003f, 0.8000644989f,
  108100. 0.7886330981f, 0.7773650302f, 0.7662579617f, 0.755309592f,
  108101. 0.7445176537f, 0.7338799116f, 0.7233941627f, 0.7130582353f,
  108102. 0.7028699885f, 0.6928273125f, 0.6829281272f, 0.6731703824f,
  108103. 0.6635520573f, 0.6540711597f, 0.6447257262f, 0.6355138211f,
  108104. };
  108105. #ifdef INT_LOOKUP
  108106. #define INVSQ_LOOKUP_I_SHIFT 10
  108107. #define INVSQ_LOOKUP_I_MASK 1023
  108108. static long INVSQ_LOOKUP_I[64+1]={
  108109. 92682l, 91966l, 91267l, 90583l,
  108110. 89915l, 89261l, 88621l, 87995l,
  108111. 87381l, 86781l, 86192l, 85616l,
  108112. 85051l, 84497l, 83953l, 83420l,
  108113. 82897l, 82384l, 81880l, 81385l,
  108114. 80899l, 80422l, 79953l, 79492l,
  108115. 79039l, 78594l, 78156l, 77726l,
  108116. 77302l, 76885l, 76475l, 76072l,
  108117. 75674l, 75283l, 74898l, 74519l,
  108118. 74146l, 73778l, 73415l, 73058l,
  108119. 72706l, 72359l, 72016l, 71679l,
  108120. 71347l, 71019l, 70695l, 70376l,
  108121. 70061l, 69750l, 69444l, 69141l,
  108122. 68842l, 68548l, 68256l, 67969l,
  108123. 67685l, 67405l, 67128l, 66855l,
  108124. 66585l, 66318l, 66054l, 65794l,
  108125. 65536l,
  108126. };
  108127. #define COS_LOOKUP_I_SHIFT 9
  108128. #define COS_LOOKUP_I_MASK 511
  108129. #define COS_LOOKUP_I_SZ 128
  108130. static long COS_LOOKUP_I[COS_LOOKUP_I_SZ+1]={
  108131. 16384l, 16379l, 16364l, 16340l,
  108132. 16305l, 16261l, 16207l, 16143l,
  108133. 16069l, 15986l, 15893l, 15791l,
  108134. 15679l, 15557l, 15426l, 15286l,
  108135. 15137l, 14978l, 14811l, 14635l,
  108136. 14449l, 14256l, 14053l, 13842l,
  108137. 13623l, 13395l, 13160l, 12916l,
  108138. 12665l, 12406l, 12140l, 11866l,
  108139. 11585l, 11297l, 11003l, 10702l,
  108140. 10394l, 10080l, 9760l, 9434l,
  108141. 9102l, 8765l, 8423l, 8076l,
  108142. 7723l, 7366l, 7005l, 6639l,
  108143. 6270l, 5897l, 5520l, 5139l,
  108144. 4756l, 4370l, 3981l, 3590l,
  108145. 3196l, 2801l, 2404l, 2006l,
  108146. 1606l, 1205l, 804l, 402l,
  108147. 0l, -401l, -803l, -1204l,
  108148. -1605l, -2005l, -2403l, -2800l,
  108149. -3195l, -3589l, -3980l, -4369l,
  108150. -4755l, -5138l, -5519l, -5896l,
  108151. -6269l, -6638l, -7004l, -7365l,
  108152. -7722l, -8075l, -8422l, -8764l,
  108153. -9101l, -9433l, -9759l, -10079l,
  108154. -10393l, -10701l, -11002l, -11296l,
  108155. -11584l, -11865l, -12139l, -12405l,
  108156. -12664l, -12915l, -13159l, -13394l,
  108157. -13622l, -13841l, -14052l, -14255l,
  108158. -14448l, -14634l, -14810l, -14977l,
  108159. -15136l, -15285l, -15425l, -15556l,
  108160. -15678l, -15790l, -15892l, -15985l,
  108161. -16068l, -16142l, -16206l, -16260l,
  108162. -16304l, -16339l, -16363l, -16378l,
  108163. -16383l,
  108164. };
  108165. #endif
  108166. #endif
  108167. /********* End of inlined file: lookup_data.h *********/
  108168. #ifdef FLOAT_LOOKUP
  108169. /* interpolated lookup based cos function, domain 0 to PI only */
  108170. float vorbis_coslook(float a){
  108171. double d=a*(.31830989*(float)COS_LOOKUP_SZ);
  108172. int i=vorbis_ftoi(d-.5);
  108173. return COS_LOOKUP[i]+ (d-i)*(COS_LOOKUP[i+1]-COS_LOOKUP[i]);
  108174. }
  108175. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  108176. float vorbis_invsqlook(float a){
  108177. double d=a*(2.f*(float)INVSQ_LOOKUP_SZ)-(float)INVSQ_LOOKUP_SZ;
  108178. int i=vorbis_ftoi(d-.5f);
  108179. return INVSQ_LOOKUP[i]+ (d-i)*(INVSQ_LOOKUP[i+1]-INVSQ_LOOKUP[i]);
  108180. }
  108181. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  108182. float vorbis_invsq2explook(int a){
  108183. return INVSQ2EXP_LOOKUP[a-INVSQ2EXP_LOOKUP_MIN];
  108184. }
  108185. #include <stdio.h>
  108186. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  108187. float vorbis_fromdBlook(float a){
  108188. int i=vorbis_ftoi(a*((float)(-(1<<FROMdB2_SHIFT)))-.5f);
  108189. return (i<0)?1.f:
  108190. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  108191. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  108192. }
  108193. #endif
  108194. #ifdef INT_LOOKUP
  108195. /* interpolated 1./sqrt(p) where .5 <= a < 1. (.100000... to .111111...) in
  108196. 16.16 format
  108197. returns in m.8 format */
  108198. long vorbis_invsqlook_i(long a,long e){
  108199. long i=(a&0x7fff)>>(INVSQ_LOOKUP_I_SHIFT-1);
  108200. long d=(a&INVSQ_LOOKUP_I_MASK)<<(16-INVSQ_LOOKUP_I_SHIFT); /* 0.16 */
  108201. long val=INVSQ_LOOKUP_I[i]- /* 1.16 */
  108202. (((INVSQ_LOOKUP_I[i]-INVSQ_LOOKUP_I[i+1])* /* 0.16 */
  108203. d)>>16); /* result 1.16 */
  108204. e+=32;
  108205. if(e&1)val=(val*5792)>>13; /* multiply val by 1/sqrt(2) */
  108206. e=(e>>1)-8;
  108207. return(val>>e);
  108208. }
  108209. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  108210. /* a is in n.12 format */
  108211. float vorbis_fromdBlook_i(long a){
  108212. int i=(-a)>>(12-FROMdB2_SHIFT);
  108213. return (i<0)?1.f:
  108214. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  108215. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  108216. }
  108217. /* interpolated lookup based cos function, domain 0 to PI only */
  108218. /* a is in 0.16 format, where 0==0, 2^^16-1==PI, return 0.14 */
  108219. long vorbis_coslook_i(long a){
  108220. int i=a>>COS_LOOKUP_I_SHIFT;
  108221. int d=a&COS_LOOKUP_I_MASK;
  108222. return COS_LOOKUP_I[i]- ((d*(COS_LOOKUP_I[i]-COS_LOOKUP_I[i+1]))>>
  108223. COS_LOOKUP_I_SHIFT);
  108224. }
  108225. #endif
  108226. #endif
  108227. /********* End of inlined file: lookup.c *********/
  108228. /* catch this in the build system; we #include for
  108229. compilers (like gcc) that can't inline across
  108230. modules */
  108231. static int MLOOP_1[64]={
  108232. 0,10,11,11, 12,12,12,12, 13,13,13,13, 13,13,13,13,
  108233. 14,14,14,14, 14,14,14,14, 14,14,14,14, 14,14,14,14,
  108234. 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
  108235. 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
  108236. };
  108237. static int MLOOP_2[64]={
  108238. 0,4,5,5, 6,6,6,6, 7,7,7,7, 7,7,7,7,
  108239. 8,8,8,8, 8,8,8,8, 8,8,8,8, 8,8,8,8,
  108240. 9,9,9,9, 9,9,9,9, 9,9,9,9, 9,9,9,9,
  108241. 9,9,9,9, 9,9,9,9, 9,9,9,9, 9,9,9,9,
  108242. };
  108243. static int MLOOP_3[8]={0,1,2,2,3,3,3,3};
  108244. /* side effect: changes *lsp to cosines of lsp */
  108245. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  108246. float amp,float ampoffset){
  108247. /* 0 <= m < 256 */
  108248. /* set up for using all int later */
  108249. int i;
  108250. int ampoffseti=rint(ampoffset*4096.f);
  108251. int ampi=rint(amp*16.f);
  108252. long *ilsp=alloca(m*sizeof(*ilsp));
  108253. for(i=0;i<m;i++)ilsp[i]=vorbis_coslook_i(lsp[i]/M_PI*65536.f+.5f);
  108254. i=0;
  108255. while(i<n){
  108256. int j,k=map[i];
  108257. unsigned long pi=46341; /* 2**-.5 in 0.16 */
  108258. unsigned long qi=46341;
  108259. int qexp=0,shift;
  108260. long wi=vorbis_coslook_i(k*65536/ln);
  108261. qi*=labs(ilsp[0]-wi);
  108262. pi*=labs(ilsp[1]-wi);
  108263. for(j=3;j<m;j+=2){
  108264. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  108265. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  108266. shift=MLOOP_3[(pi|qi)>>16];
  108267. qi=(qi>>shift)*labs(ilsp[j-1]-wi);
  108268. pi=(pi>>shift)*labs(ilsp[j]-wi);
  108269. qexp+=shift;
  108270. }
  108271. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  108272. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  108273. shift=MLOOP_3[(pi|qi)>>16];
  108274. /* pi,qi normalized collectively, both tracked using qexp */
  108275. if(m&1){
  108276. /* odd order filter; slightly assymetric */
  108277. /* the last coefficient */
  108278. qi=(qi>>shift)*labs(ilsp[j-1]-wi);
  108279. pi=(pi>>shift)<<14;
  108280. qexp+=shift;
  108281. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  108282. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  108283. shift=MLOOP_3[(pi|qi)>>16];
  108284. pi>>=shift;
  108285. qi>>=shift;
  108286. qexp+=shift-14*((m+1)>>1);
  108287. pi=((pi*pi)>>16);
  108288. qi=((qi*qi)>>16);
  108289. qexp=qexp*2+m;
  108290. pi*=(1<<14)-((wi*wi)>>14);
  108291. qi+=pi>>14;
  108292. }else{
  108293. /* even order filter; still symmetric */
  108294. /* p*=p(1-w), q*=q(1+w), let normalization drift because it isn't
  108295. worth tracking step by step */
  108296. pi>>=shift;
  108297. qi>>=shift;
  108298. qexp+=shift-7*m;
  108299. pi=((pi*pi)>>16);
  108300. qi=((qi*qi)>>16);
  108301. qexp=qexp*2+m;
  108302. pi*=(1<<14)-wi;
  108303. qi*=(1<<14)+wi;
  108304. qi=(qi+pi)>>14;
  108305. }
  108306. /* we've let the normalization drift because it wasn't important;
  108307. however, for the lookup, things must be normalized again. We
  108308. need at most one right shift or a number of left shifts */
  108309. if(qi&0xffff0000){ /* checks for 1.xxxxxxxxxxxxxxxx */
  108310. qi>>=1; qexp++;
  108311. }else
  108312. while(qi && !(qi&0x8000)){ /* checks for 0.0xxxxxxxxxxxxxxx or less*/
  108313. qi<<=1; qexp--;
  108314. }
  108315. amp=vorbis_fromdBlook_i(ampi* /* n.4 */
  108316. vorbis_invsqlook_i(qi,qexp)-
  108317. /* m.8, m+n<=8 */
  108318. ampoffseti); /* 8.12[0] */
  108319. curve[i]*=amp;
  108320. while(map[++i]==k)curve[i]*=amp;
  108321. }
  108322. }
  108323. #else
  108324. /* old, nonoptimized but simple version for any poor sap who needs to
  108325. figure out what the hell this code does, or wants the other
  108326. fraction of a dB precision */
  108327. /* side effect: changes *lsp to cosines of lsp */
  108328. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  108329. float amp,float ampoffset){
  108330. int i;
  108331. float wdel=M_PI/ln;
  108332. for(i=0;i<m;i++)lsp[i]=2.f*cos(lsp[i]);
  108333. i=0;
  108334. while(i<n){
  108335. int j,k=map[i];
  108336. float p=.5f;
  108337. float q=.5f;
  108338. float w=2.f*cos(wdel*k);
  108339. for(j=1;j<m;j+=2){
  108340. q *= w-lsp[j-1];
  108341. p *= w-lsp[j];
  108342. }
  108343. if(j==m){
  108344. /* odd order filter; slightly assymetric */
  108345. /* the last coefficient */
  108346. q*=w-lsp[j-1];
  108347. p*=p*(4.f-w*w);
  108348. q*=q;
  108349. }else{
  108350. /* even order filter; still symmetric */
  108351. p*=p*(2.f-w);
  108352. q*=q*(2.f+w);
  108353. }
  108354. q=fromdB(amp/sqrt(p+q)-ampoffset);
  108355. curve[i]*=q;
  108356. while(map[++i]==k)curve[i]*=q;
  108357. }
  108358. }
  108359. #endif
  108360. #endif
  108361. static void cheby(float *g, int ord) {
  108362. int i, j;
  108363. g[0] *= .5f;
  108364. for(i=2; i<= ord; i++) {
  108365. for(j=ord; j >= i; j--) {
  108366. g[j-2] -= g[j];
  108367. g[j] += g[j];
  108368. }
  108369. }
  108370. }
  108371. static int comp(const void *a,const void *b){
  108372. return (*(float *)a<*(float *)b)-(*(float *)a>*(float *)b);
  108373. }
  108374. /* Newton-Raphson-Maehly actually functioned as a decent root finder,
  108375. but there are root sets for which it gets into limit cycles
  108376. (exacerbated by zero suppression) and fails. We can't afford to
  108377. fail, even if the failure is 1 in 100,000,000, so we now use
  108378. Laguerre and later polish with Newton-Raphson (which can then
  108379. afford to fail) */
  108380. #define EPSILON 10e-7
  108381. static int Laguerre_With_Deflation(float *a,int ord,float *r){
  108382. int i,m;
  108383. double lastdelta=0.f;
  108384. double *defl=(double*)alloca(sizeof(*defl)*(ord+1));
  108385. for(i=0;i<=ord;i++)defl[i]=a[i];
  108386. for(m=ord;m>0;m--){
  108387. double newx=0.f,delta;
  108388. /* iterate a root */
  108389. while(1){
  108390. double p=defl[m],pp=0.f,ppp=0.f,denom;
  108391. /* eval the polynomial and its first two derivatives */
  108392. for(i=m;i>0;i--){
  108393. ppp = newx*ppp + pp;
  108394. pp = newx*pp + p;
  108395. p = newx*p + defl[i-1];
  108396. }
  108397. /* Laguerre's method */
  108398. denom=(m-1) * ((m-1)*pp*pp - m*p*ppp);
  108399. if(denom<0)
  108400. return(-1); /* complex root! The LPC generator handed us a bad filter */
  108401. if(pp>0){
  108402. denom = pp + sqrt(denom);
  108403. if(denom<EPSILON)denom=EPSILON;
  108404. }else{
  108405. denom = pp - sqrt(denom);
  108406. if(denom>-(EPSILON))denom=-(EPSILON);
  108407. }
  108408. delta = m*p/denom;
  108409. newx -= delta;
  108410. if(delta<0.f)delta*=-1;
  108411. if(fabs(delta/newx)<10e-12)break;
  108412. lastdelta=delta;
  108413. }
  108414. r[m-1]=newx;
  108415. /* forward deflation */
  108416. for(i=m;i>0;i--)
  108417. defl[i-1]+=newx*defl[i];
  108418. defl++;
  108419. }
  108420. return(0);
  108421. }
  108422. /* for spit-and-polish only */
  108423. static int Newton_Raphson(float *a,int ord,float *r){
  108424. int i, k, count=0;
  108425. double error=1.f;
  108426. double *root=(double*)alloca(ord*sizeof(*root));
  108427. for(i=0; i<ord;i++) root[i] = r[i];
  108428. while(error>1e-20){
  108429. error=0;
  108430. for(i=0; i<ord; i++) { /* Update each point. */
  108431. double pp=0.,delta;
  108432. double rooti=root[i];
  108433. double p=a[ord];
  108434. for(k=ord-1; k>= 0; k--) {
  108435. pp= pp* rooti + p;
  108436. p = p * rooti + a[k];
  108437. }
  108438. delta = p/pp;
  108439. root[i] -= delta;
  108440. error+= delta*delta;
  108441. }
  108442. if(count>40)return(-1);
  108443. count++;
  108444. }
  108445. /* Replaced the original bubble sort with a real sort. With your
  108446. help, we can eliminate the bubble sort in our lifetime. --Monty */
  108447. for(i=0; i<ord;i++) r[i] = root[i];
  108448. return(0);
  108449. }
  108450. /* Convert lpc coefficients to lsp coefficients */
  108451. int vorbis_lpc_to_lsp(float *lpc,float *lsp,int m){
  108452. int order2=(m+1)>>1;
  108453. int g1_order,g2_order;
  108454. float *g1=(float*)alloca(sizeof(*g1)*(order2+1));
  108455. float *g2=(float*)alloca(sizeof(*g2)*(order2+1));
  108456. float *g1r=(float*)alloca(sizeof(*g1r)*(order2+1));
  108457. float *g2r=(float*)alloca(sizeof(*g2r)*(order2+1));
  108458. int i;
  108459. /* even and odd are slightly different base cases */
  108460. g1_order=(m+1)>>1;
  108461. g2_order=(m) >>1;
  108462. /* Compute the lengths of the x polynomials. */
  108463. /* Compute the first half of K & R F1 & F2 polynomials. */
  108464. /* Compute half of the symmetric and antisymmetric polynomials. */
  108465. /* Remove the roots at +1 and -1. */
  108466. g1[g1_order] = 1.f;
  108467. for(i=1;i<=g1_order;i++) g1[g1_order-i] = lpc[i-1]+lpc[m-i];
  108468. g2[g2_order] = 1.f;
  108469. for(i=1;i<=g2_order;i++) g2[g2_order-i] = lpc[i-1]-lpc[m-i];
  108470. if(g1_order>g2_order){
  108471. for(i=2; i<=g2_order;i++) g2[g2_order-i] += g2[g2_order-i+2];
  108472. }else{
  108473. for(i=1; i<=g1_order;i++) g1[g1_order-i] -= g1[g1_order-i+1];
  108474. for(i=1; i<=g2_order;i++) g2[g2_order-i] += g2[g2_order-i+1];
  108475. }
  108476. /* Convert into polynomials in cos(alpha) */
  108477. cheby(g1,g1_order);
  108478. cheby(g2,g2_order);
  108479. /* Find the roots of the 2 even polynomials.*/
  108480. if(Laguerre_With_Deflation(g1,g1_order,g1r) ||
  108481. Laguerre_With_Deflation(g2,g2_order,g2r))
  108482. return(-1);
  108483. Newton_Raphson(g1,g1_order,g1r); /* if it fails, it leaves g1r alone */
  108484. Newton_Raphson(g2,g2_order,g2r); /* if it fails, it leaves g2r alone */
  108485. qsort(g1r,g1_order,sizeof(*g1r),comp);
  108486. qsort(g2r,g2_order,sizeof(*g2r),comp);
  108487. for(i=0;i<g1_order;i++)
  108488. lsp[i*2] = acos(g1r[i]);
  108489. for(i=0;i<g2_order;i++)
  108490. lsp[i*2+1] = acos(g2r[i]);
  108491. return(0);
  108492. }
  108493. #endif
  108494. /********* End of inlined file: lsp.c *********/
  108495. /********* Start of inlined file: mapping0.c *********/
  108496. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  108497. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  108498. // tasks..
  108499. #ifdef _MSC_VER
  108500. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  108501. #endif
  108502. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  108503. #if JUCE_USE_OGGVORBIS
  108504. #include <stdlib.h>
  108505. #include <stdio.h>
  108506. #include <string.h>
  108507. #include <math.h>
  108508. /* simplistic, wasteful way of doing this (unique lookup for each
  108509. mode/submapping); there should be a central repository for
  108510. identical lookups. That will require minor work, so I'm putting it
  108511. off as low priority.
  108512. Why a lookup for each backend in a given mode? Because the
  108513. blocksize is set by the mode, and low backend lookups may require
  108514. parameters from other areas of the mode/mapping */
  108515. static void mapping0_free_info(vorbis_info_mapping *i){
  108516. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)i;
  108517. if(info){
  108518. memset(info,0,sizeof(*info));
  108519. _ogg_free(info);
  108520. }
  108521. }
  108522. static int ilog3(unsigned int v){
  108523. int ret=0;
  108524. if(v)--v;
  108525. while(v){
  108526. ret++;
  108527. v>>=1;
  108528. }
  108529. return(ret);
  108530. }
  108531. static void mapping0_pack(vorbis_info *vi,vorbis_info_mapping *vm,
  108532. oggpack_buffer *opb){
  108533. int i;
  108534. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)vm;
  108535. /* another 'we meant to do it this way' hack... up to beta 4, we
  108536. packed 4 binary zeros here to signify one submapping in use. We
  108537. now redefine that to mean four bitflags that indicate use of
  108538. deeper features; bit0:submappings, bit1:coupling,
  108539. bit2,3:reserved. This is backward compatable with all actual uses
  108540. of the beta code. */
  108541. if(info->submaps>1){
  108542. oggpack_write(opb,1,1);
  108543. oggpack_write(opb,info->submaps-1,4);
  108544. }else
  108545. oggpack_write(opb,0,1);
  108546. if(info->coupling_steps>0){
  108547. oggpack_write(opb,1,1);
  108548. oggpack_write(opb,info->coupling_steps-1,8);
  108549. for(i=0;i<info->coupling_steps;i++){
  108550. oggpack_write(opb,info->coupling_mag[i],ilog3(vi->channels));
  108551. oggpack_write(opb,info->coupling_ang[i],ilog3(vi->channels));
  108552. }
  108553. }else
  108554. oggpack_write(opb,0,1);
  108555. oggpack_write(opb,0,2); /* 2,3:reserved */
  108556. /* we don't write the channel submappings if we only have one... */
  108557. if(info->submaps>1){
  108558. for(i=0;i<vi->channels;i++)
  108559. oggpack_write(opb,info->chmuxlist[i],4);
  108560. }
  108561. for(i=0;i<info->submaps;i++){
  108562. oggpack_write(opb,0,8); /* time submap unused */
  108563. oggpack_write(opb,info->floorsubmap[i],8);
  108564. oggpack_write(opb,info->residuesubmap[i],8);
  108565. }
  108566. }
  108567. /* also responsible for range checking */
  108568. static vorbis_info_mapping *mapping0_unpack(vorbis_info *vi,oggpack_buffer *opb){
  108569. int i;
  108570. vorbis_info_mapping0 *info=(vorbis_info_mapping0*)_ogg_calloc(1,sizeof(*info));
  108571. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  108572. memset(info,0,sizeof(*info));
  108573. if(oggpack_read(opb,1))
  108574. info->submaps=oggpack_read(opb,4)+1;
  108575. else
  108576. info->submaps=1;
  108577. if(oggpack_read(opb,1)){
  108578. info->coupling_steps=oggpack_read(opb,8)+1;
  108579. for(i=0;i<info->coupling_steps;i++){
  108580. int testM=info->coupling_mag[i]=oggpack_read(opb,ilog3(vi->channels));
  108581. int testA=info->coupling_ang[i]=oggpack_read(opb,ilog3(vi->channels));
  108582. if(testM<0 ||
  108583. testA<0 ||
  108584. testM==testA ||
  108585. testM>=vi->channels ||
  108586. testA>=vi->channels) goto err_out;
  108587. }
  108588. }
  108589. if(oggpack_read(opb,2)>0)goto err_out; /* 2,3:reserved */
  108590. if(info->submaps>1){
  108591. for(i=0;i<vi->channels;i++){
  108592. info->chmuxlist[i]=oggpack_read(opb,4);
  108593. if(info->chmuxlist[i]>=info->submaps)goto err_out;
  108594. }
  108595. }
  108596. for(i=0;i<info->submaps;i++){
  108597. oggpack_read(opb,8); /* time submap unused */
  108598. info->floorsubmap[i]=oggpack_read(opb,8);
  108599. if(info->floorsubmap[i]>=ci->floors)goto err_out;
  108600. info->residuesubmap[i]=oggpack_read(opb,8);
  108601. if(info->residuesubmap[i]>=ci->residues)goto err_out;
  108602. }
  108603. return info;
  108604. err_out:
  108605. mapping0_free_info(info);
  108606. return(NULL);
  108607. }
  108608. #if 0
  108609. static long seq=0;
  108610. static ogg_int64_t total=0;
  108611. static float FLOOR1_fromdB_LOOKUP[256]={
  108612. 1.0649863e-07F, 1.1341951e-07F, 1.2079015e-07F, 1.2863978e-07F,
  108613. 1.3699951e-07F, 1.4590251e-07F, 1.5538408e-07F, 1.6548181e-07F,
  108614. 1.7623575e-07F, 1.8768855e-07F, 1.9988561e-07F, 2.128753e-07F,
  108615. 2.2670913e-07F, 2.4144197e-07F, 2.5713223e-07F, 2.7384213e-07F,
  108616. 2.9163793e-07F, 3.1059021e-07F, 3.3077411e-07F, 3.5226968e-07F,
  108617. 3.7516214e-07F, 3.9954229e-07F, 4.2550680e-07F, 4.5315863e-07F,
  108618. 4.8260743e-07F, 5.1396998e-07F, 5.4737065e-07F, 5.8294187e-07F,
  108619. 6.2082472e-07F, 6.6116941e-07F, 7.0413592e-07F, 7.4989464e-07F,
  108620. 7.9862701e-07F, 8.5052630e-07F, 9.0579828e-07F, 9.6466216e-07F,
  108621. 1.0273513e-06F, 1.0941144e-06F, 1.1652161e-06F, 1.2409384e-06F,
  108622. 1.3215816e-06F, 1.4074654e-06F, 1.4989305e-06F, 1.5963394e-06F,
  108623. 1.7000785e-06F, 1.8105592e-06F, 1.9282195e-06F, 2.0535261e-06F,
  108624. 2.1869758e-06F, 2.3290978e-06F, 2.4804557e-06F, 2.6416497e-06F,
  108625. 2.8133190e-06F, 2.9961443e-06F, 3.1908506e-06F, 3.3982101e-06F,
  108626. 3.6190449e-06F, 3.8542308e-06F, 4.1047004e-06F, 4.3714470e-06F,
  108627. 4.6555282e-06F, 4.9580707e-06F, 5.2802740e-06F, 5.6234160e-06F,
  108628. 5.9888572e-06F, 6.3780469e-06F, 6.7925283e-06F, 7.2339451e-06F,
  108629. 7.7040476e-06F, 8.2047000e-06F, 8.7378876e-06F, 9.3057248e-06F,
  108630. 9.9104632e-06F, 1.0554501e-05F, 1.1240392e-05F, 1.1970856e-05F,
  108631. 1.2748789e-05F, 1.3577278e-05F, 1.4459606e-05F, 1.5399272e-05F,
  108632. 1.6400004e-05F, 1.7465768e-05F, 1.8600792e-05F, 1.9809576e-05F,
  108633. 2.1096914e-05F, 2.2467911e-05F, 2.3928002e-05F, 2.5482978e-05F,
  108634. 2.7139006e-05F, 2.8902651e-05F, 3.0780908e-05F, 3.2781225e-05F,
  108635. 3.4911534e-05F, 3.7180282e-05F, 3.9596466e-05F, 4.2169667e-05F,
  108636. 4.4910090e-05F, 4.7828601e-05F, 5.0936773e-05F, 5.4246931e-05F,
  108637. 5.7772202e-05F, 6.1526565e-05F, 6.5524908e-05F, 6.9783085e-05F,
  108638. 7.4317983e-05F, 7.9147585e-05F, 8.4291040e-05F, 8.9768747e-05F,
  108639. 9.5602426e-05F, 0.00010181521F, 0.00010843174F, 0.00011547824F,
  108640. 0.00012298267F, 0.00013097477F, 0.00013948625F, 0.00014855085F,
  108641. 0.00015820453F, 0.00016848555F, 0.00017943469F, 0.00019109536F,
  108642. 0.00020351382F, 0.00021673929F, 0.00023082423F, 0.00024582449F,
  108643. 0.00026179955F, 0.00027881276F, 0.00029693158F, 0.00031622787F,
  108644. 0.00033677814F, 0.00035866388F, 0.00038197188F, 0.00040679456F,
  108645. 0.00043323036F, 0.00046138411F, 0.00049136745F, 0.00052329927F,
  108646. 0.00055730621F, 0.00059352311F, 0.00063209358F, 0.00067317058F,
  108647. 0.00071691700F, 0.00076350630F, 0.00081312324F, 0.00086596457F,
  108648. 0.00092223983F, 0.00098217216F, 0.0010459992F, 0.0011139742F,
  108649. 0.0011863665F, 0.0012634633F, 0.0013455702F, 0.0014330129F,
  108650. 0.0015261382F, 0.0016253153F, 0.0017309374F, 0.0018434235F,
  108651. 0.0019632195F, 0.0020908006F, 0.0022266726F, 0.0023713743F,
  108652. 0.0025254795F, 0.0026895994F, 0.0028643847F, 0.0030505286F,
  108653. 0.0032487691F, 0.0034598925F, 0.0036847358F, 0.0039241906F,
  108654. 0.0041792066F, 0.0044507950F, 0.0047400328F, 0.0050480668F,
  108655. 0.0053761186F, 0.0057254891F, 0.0060975636F, 0.0064938176F,
  108656. 0.0069158225F, 0.0073652516F, 0.0078438871F, 0.0083536271F,
  108657. 0.0088964928F, 0.009474637F, 0.010090352F, 0.010746080F,
  108658. 0.011444421F, 0.012188144F, 0.012980198F, 0.013823725F,
  108659. 0.014722068F, 0.015678791F, 0.016697687F, 0.017782797F,
  108660. 0.018938423F, 0.020169149F, 0.021479854F, 0.022875735F,
  108661. 0.024362330F, 0.025945531F, 0.027631618F, 0.029427276F,
  108662. 0.031339626F, 0.033376252F, 0.035545228F, 0.037855157F,
  108663. 0.040315199F, 0.042935108F, 0.045725273F, 0.048696758F,
  108664. 0.051861348F, 0.055231591F, 0.058820850F, 0.062643361F,
  108665. 0.066714279F, 0.071049749F, 0.075666962F, 0.080584227F,
  108666. 0.085821044F, 0.091398179F, 0.097337747F, 0.10366330F,
  108667. 0.11039993F, 0.11757434F, 0.12521498F, 0.13335215F,
  108668. 0.14201813F, 0.15124727F, 0.16107617F, 0.17154380F,
  108669. 0.18269168F, 0.19456402F, 0.20720788F, 0.22067342F,
  108670. 0.23501402F, 0.25028656F, 0.26655159F, 0.28387361F,
  108671. 0.30232132F, 0.32196786F, 0.34289114F, 0.36517414F,
  108672. 0.38890521F, 0.41417847F, 0.44109412F, 0.46975890F,
  108673. 0.50028648F, 0.53279791F, 0.56742212F, 0.60429640F,
  108674. 0.64356699F, 0.68538959F, 0.72993007F, 0.77736504F,
  108675. 0.82788260F, 0.88168307F, 0.9389798F, 1.F,
  108676. };
  108677. #endif
  108678. extern int *floor1_fit(vorbis_block *vb,void *look,
  108679. const float *logmdct, /* in */
  108680. const float *logmask);
  108681. extern int *floor1_interpolate_fit(vorbis_block *vb,void *look,
  108682. int *A,int *B,
  108683. int del);
  108684. extern int floor1_encode(oggpack_buffer *opb,vorbis_block *vb,
  108685. void*look,
  108686. int *post,int *ilogmask);
  108687. static int mapping0_forward(vorbis_block *vb){
  108688. vorbis_dsp_state *vd=vb->vd;
  108689. vorbis_info *vi=vd->vi;
  108690. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  108691. private_state *b=(private_state*)vb->vd->backend_state;
  108692. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  108693. int n=vb->pcmend;
  108694. int i,j,k;
  108695. int *nonzero = (int*) alloca(sizeof(*nonzero)*vi->channels);
  108696. float **gmdct = (float**) _vorbis_block_alloc(vb,vi->channels*sizeof(*gmdct));
  108697. int **ilogmaskch= (int**) _vorbis_block_alloc(vb,vi->channels*sizeof(*ilogmaskch));
  108698. int ***floor_posts = (int***) _vorbis_block_alloc(vb,vi->channels*sizeof(*floor_posts));
  108699. float global_ampmax=vbi->ampmax;
  108700. float *local_ampmax=(float*)alloca(sizeof(*local_ampmax)*vi->channels);
  108701. int blocktype=vbi->blocktype;
  108702. int modenumber=vb->W;
  108703. vorbis_info_mapping0 *info=(vorbis_info_mapping0*)ci->map_param[modenumber];
  108704. vorbis_look_psy *psy_look=
  108705. b->psy+blocktype+(vb->W?2:0);
  108706. vb->mode=modenumber;
  108707. for(i=0;i<vi->channels;i++){
  108708. float scale=4.f/n;
  108709. float scale_dB;
  108710. float *pcm =vb->pcm[i];
  108711. float *logfft =pcm;
  108712. gmdct[i]=(float*)_vorbis_block_alloc(vb,n/2*sizeof(**gmdct));
  108713. scale_dB=todB(&scale) + .345; /* + .345 is a hack; the original
  108714. todB estimation used on IEEE 754
  108715. compliant machines had a bug that
  108716. returned dB values about a third
  108717. of a decibel too high. The bug
  108718. was harmless because tunings
  108719. implicitly took that into
  108720. account. However, fixing the bug
  108721. in the estimator requires
  108722. changing all the tunings as well.
  108723. For now, it's easier to sync
  108724. things back up here, and
  108725. recalibrate the tunings in the
  108726. next major model upgrade. */
  108727. #if 0
  108728. if(vi->channels==2)
  108729. if(i==0)
  108730. _analysis_output("pcmL",seq,pcm,n,0,0,total-n/2);
  108731. else
  108732. _analysis_output("pcmR",seq,pcm,n,0,0,total-n/2);
  108733. #endif
  108734. /* window the PCM data */
  108735. _vorbis_apply_window(pcm,b->window,ci->blocksizes,vb->lW,vb->W,vb->nW);
  108736. #if 0
  108737. if(vi->channels==2)
  108738. if(i==0)
  108739. _analysis_output("windowedL",seq,pcm,n,0,0,total-n/2);
  108740. else
  108741. _analysis_output("windowedR",seq,pcm,n,0,0,total-n/2);
  108742. #endif
  108743. /* transform the PCM data */
  108744. /* only MDCT right now.... */
  108745. mdct_forward((mdct_lookup*) b->transform[vb->W][0],pcm,gmdct[i]);
  108746. /* FFT yields more accurate tonal estimation (not phase sensitive) */
  108747. drft_forward(&b->fft_look[vb->W],pcm);
  108748. logfft[0]=scale_dB+todB(pcm) + .345; /* + .345 is a hack; the
  108749. original todB estimation used on
  108750. IEEE 754 compliant machines had a
  108751. bug that returned dB values about
  108752. a third of a decibel too high.
  108753. The bug was harmless because
  108754. tunings implicitly took that into
  108755. account. However, fixing the bug
  108756. in the estimator requires
  108757. changing all the tunings as well.
  108758. For now, it's easier to sync
  108759. things back up here, and
  108760. recalibrate the tunings in the
  108761. next major model upgrade. */
  108762. local_ampmax[i]=logfft[0];
  108763. for(j=1;j<n-1;j+=2){
  108764. float temp=pcm[j]*pcm[j]+pcm[j+1]*pcm[j+1];
  108765. temp=logfft[(j+1)>>1]=scale_dB+.5f*todB(&temp) + .345; /* +
  108766. .345 is a hack; the original todB
  108767. estimation used on IEEE 754
  108768. compliant machines had a bug that
  108769. returned dB values about a third
  108770. of a decibel too high. The bug
  108771. was harmless because tunings
  108772. implicitly took that into
  108773. account. However, fixing the bug
  108774. in the estimator requires
  108775. changing all the tunings as well.
  108776. For now, it's easier to sync
  108777. things back up here, and
  108778. recalibrate the tunings in the
  108779. next major model upgrade. */
  108780. if(temp>local_ampmax[i])local_ampmax[i]=temp;
  108781. }
  108782. if(local_ampmax[i]>0.f)local_ampmax[i]=0.f;
  108783. if(local_ampmax[i]>global_ampmax)global_ampmax=local_ampmax[i];
  108784. #if 0
  108785. if(vi->channels==2){
  108786. if(i==0){
  108787. _analysis_output("fftL",seq,logfft,n/2,1,0,0);
  108788. }else{
  108789. _analysis_output("fftR",seq,logfft,n/2,1,0,0);
  108790. }
  108791. }
  108792. #endif
  108793. }
  108794. {
  108795. float *noise = (float*) _vorbis_block_alloc(vb,n/2*sizeof(*noise));
  108796. float *tone = (float*) _vorbis_block_alloc(vb,n/2*sizeof(*tone));
  108797. for(i=0;i<vi->channels;i++){
  108798. /* the encoder setup assumes that all the modes used by any
  108799. specific bitrate tweaking use the same floor */
  108800. int submap=info->chmuxlist[i];
  108801. /* the following makes things clearer to *me* anyway */
  108802. float *mdct =gmdct[i];
  108803. float *logfft =vb->pcm[i];
  108804. float *logmdct =logfft+n/2;
  108805. float *logmask =logfft;
  108806. vb->mode=modenumber;
  108807. floor_posts[i]=(int**) _vorbis_block_alloc(vb,PACKETBLOBS*sizeof(**floor_posts));
  108808. memset(floor_posts[i],0,sizeof(**floor_posts)*PACKETBLOBS);
  108809. for(j=0;j<n/2;j++)
  108810. logmdct[j]=todB(mdct+j) + .345; /* + .345 is a hack; the original
  108811. todB estimation used on IEEE 754
  108812. compliant machines had a bug that
  108813. returned dB values about a third
  108814. of a decibel too high. The bug
  108815. was harmless because tunings
  108816. implicitly took that into
  108817. account. However, fixing the bug
  108818. in the estimator requires
  108819. changing all the tunings as well.
  108820. For now, it's easier to sync
  108821. things back up here, and
  108822. recalibrate the tunings in the
  108823. next major model upgrade. */
  108824. #if 0
  108825. if(vi->channels==2){
  108826. if(i==0)
  108827. _analysis_output("mdctL",seq,logmdct,n/2,1,0,0);
  108828. else
  108829. _analysis_output("mdctR",seq,logmdct,n/2,1,0,0);
  108830. }else{
  108831. _analysis_output("mdct",seq,logmdct,n/2,1,0,0);
  108832. }
  108833. #endif
  108834. /* first step; noise masking. Not only does 'noise masking'
  108835. give us curves from which we can decide how much resolution
  108836. to give noise parts of the spectrum, it also implicitly hands
  108837. us a tonality estimate (the larger the value in the
  108838. 'noise_depth' vector, the more tonal that area is) */
  108839. _vp_noisemask(psy_look,
  108840. logmdct,
  108841. noise); /* noise does not have by-frequency offset
  108842. bias applied yet */
  108843. #if 0
  108844. if(vi->channels==2){
  108845. if(i==0)
  108846. _analysis_output("noiseL",seq,noise,n/2,1,0,0);
  108847. else
  108848. _analysis_output("noiseR",seq,noise,n/2,1,0,0);
  108849. }
  108850. #endif
  108851. /* second step: 'all the other crap'; all the stuff that isn't
  108852. computed/fit for bitrate management goes in the second psy
  108853. vector. This includes tone masking, peak limiting and ATH */
  108854. _vp_tonemask(psy_look,
  108855. logfft,
  108856. tone,
  108857. global_ampmax,
  108858. local_ampmax[i]);
  108859. #if 0
  108860. if(vi->channels==2){
  108861. if(i==0)
  108862. _analysis_output("toneL",seq,tone,n/2,1,0,0);
  108863. else
  108864. _analysis_output("toneR",seq,tone,n/2,1,0,0);
  108865. }
  108866. #endif
  108867. /* third step; we offset the noise vectors, overlay tone
  108868. masking. We then do a floor1-specific line fit. If we're
  108869. performing bitrate management, the line fit is performed
  108870. multiple times for up/down tweakage on demand. */
  108871. #if 0
  108872. {
  108873. float aotuv[psy_look->n];
  108874. #endif
  108875. _vp_offset_and_mix(psy_look,
  108876. noise,
  108877. tone,
  108878. 1,
  108879. logmask,
  108880. mdct,
  108881. logmdct);
  108882. #if 0
  108883. if(vi->channels==2){
  108884. if(i==0)
  108885. _analysis_output("aotuvM1_L",seq,aotuv,psy_look->n,1,1,0);
  108886. else
  108887. _analysis_output("aotuvM1_R",seq,aotuv,psy_look->n,1,1,0);
  108888. }
  108889. }
  108890. #endif
  108891. #if 0
  108892. if(vi->channels==2){
  108893. if(i==0)
  108894. _analysis_output("mask1L",seq,logmask,n/2,1,0,0);
  108895. else
  108896. _analysis_output("mask1R",seq,logmask,n/2,1,0,0);
  108897. }
  108898. #endif
  108899. /* this algorithm is hardwired to floor 1 for now; abort out if
  108900. we're *not* floor1. This won't happen unless someone has
  108901. broken the encode setup lib. Guard it anyway. */
  108902. if(ci->floor_type[info->floorsubmap[submap]]!=1)return(-1);
  108903. floor_posts[i][PACKETBLOBS/2]=
  108904. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  108905. logmdct,
  108906. logmask);
  108907. /* are we managing bitrate? If so, perform two more fits for
  108908. later rate tweaking (fits represent hi/lo) */
  108909. if(vorbis_bitrate_managed(vb) && floor_posts[i][PACKETBLOBS/2]){
  108910. /* higher rate by way of lower noise curve */
  108911. _vp_offset_and_mix(psy_look,
  108912. noise,
  108913. tone,
  108914. 2,
  108915. logmask,
  108916. mdct,
  108917. logmdct);
  108918. #if 0
  108919. if(vi->channels==2){
  108920. if(i==0)
  108921. _analysis_output("mask2L",seq,logmask,n/2,1,0,0);
  108922. else
  108923. _analysis_output("mask2R",seq,logmask,n/2,1,0,0);
  108924. }
  108925. #endif
  108926. floor_posts[i][PACKETBLOBS-1]=
  108927. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  108928. logmdct,
  108929. logmask);
  108930. /* lower rate by way of higher noise curve */
  108931. _vp_offset_and_mix(psy_look,
  108932. noise,
  108933. tone,
  108934. 0,
  108935. logmask,
  108936. mdct,
  108937. logmdct);
  108938. #if 0
  108939. if(vi->channels==2)
  108940. if(i==0)
  108941. _analysis_output("mask0L",seq,logmask,n/2,1,0,0);
  108942. else
  108943. _analysis_output("mask0R",seq,logmask,n/2,1,0,0);
  108944. #endif
  108945. floor_posts[i][0]=
  108946. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  108947. logmdct,
  108948. logmask);
  108949. /* we also interpolate a range of intermediate curves for
  108950. intermediate rates */
  108951. for(k=1;k<PACKETBLOBS/2;k++)
  108952. floor_posts[i][k]=
  108953. floor1_interpolate_fit(vb,b->flr[info->floorsubmap[submap]],
  108954. floor_posts[i][0],
  108955. floor_posts[i][PACKETBLOBS/2],
  108956. k*65536/(PACKETBLOBS/2));
  108957. for(k=PACKETBLOBS/2+1;k<PACKETBLOBS-1;k++)
  108958. floor_posts[i][k]=
  108959. floor1_interpolate_fit(vb,b->flr[info->floorsubmap[submap]],
  108960. floor_posts[i][PACKETBLOBS/2],
  108961. floor_posts[i][PACKETBLOBS-1],
  108962. (k-PACKETBLOBS/2)*65536/(PACKETBLOBS/2));
  108963. }
  108964. }
  108965. }
  108966. vbi->ampmax=global_ampmax;
  108967. /*
  108968. the next phases are performed once for vbr-only and PACKETBLOB
  108969. times for bitrate managed modes.
  108970. 1) encode actual mode being used
  108971. 2) encode the floor for each channel, compute coded mask curve/res
  108972. 3) normalize and couple.
  108973. 4) encode residue
  108974. 5) save packet bytes to the packetblob vector
  108975. */
  108976. /* iterate over the many masking curve fits we've created */
  108977. {
  108978. float **res_bundle=(float**) alloca(sizeof(*res_bundle)*vi->channels);
  108979. float **couple_bundle=(float**) alloca(sizeof(*couple_bundle)*vi->channels);
  108980. int *zerobundle=(int*) alloca(sizeof(*zerobundle)*vi->channels);
  108981. int **sortindex=(int**) alloca(sizeof(*sortindex)*vi->channels);
  108982. float **mag_memo;
  108983. int **mag_sort;
  108984. if(info->coupling_steps){
  108985. mag_memo=_vp_quantize_couple_memo(vb,
  108986. &ci->psy_g_param,
  108987. psy_look,
  108988. info,
  108989. gmdct);
  108990. mag_sort=_vp_quantize_couple_sort(vb,
  108991. psy_look,
  108992. info,
  108993. mag_memo);
  108994. hf_reduction(&ci->psy_g_param,
  108995. psy_look,
  108996. info,
  108997. mag_memo);
  108998. }
  108999. memset(sortindex,0,sizeof(*sortindex)*vi->channels);
  109000. if(psy_look->vi->normal_channel_p){
  109001. for(i=0;i<vi->channels;i++){
  109002. float *mdct =gmdct[i];
  109003. sortindex[i]=(int*) alloca(sizeof(**sortindex)*n/2);
  109004. _vp_noise_normalize_sort(psy_look,mdct,sortindex[i]);
  109005. }
  109006. }
  109007. for(k=(vorbis_bitrate_managed(vb)?0:PACKETBLOBS/2);
  109008. k<=(vorbis_bitrate_managed(vb)?PACKETBLOBS-1:PACKETBLOBS/2);
  109009. k++){
  109010. oggpack_buffer *opb=vbi->packetblob[k];
  109011. /* start out our new packet blob with packet type and mode */
  109012. /* Encode the packet type */
  109013. oggpack_write(opb,0,1);
  109014. /* Encode the modenumber */
  109015. /* Encode frame mode, pre,post windowsize, then dispatch */
  109016. oggpack_write(opb,modenumber,b->modebits);
  109017. if(vb->W){
  109018. oggpack_write(opb,vb->lW,1);
  109019. oggpack_write(opb,vb->nW,1);
  109020. }
  109021. /* encode floor, compute masking curve, sep out residue */
  109022. for(i=0;i<vi->channels;i++){
  109023. int submap=info->chmuxlist[i];
  109024. float *mdct =gmdct[i];
  109025. float *res =vb->pcm[i];
  109026. int *ilogmask=ilogmaskch[i]=
  109027. (int*) _vorbis_block_alloc(vb,n/2*sizeof(**gmdct));
  109028. nonzero[i]=floor1_encode(opb,vb,b->flr[info->floorsubmap[submap]],
  109029. floor_posts[i][k],
  109030. ilogmask);
  109031. #if 0
  109032. {
  109033. char buf[80];
  109034. sprintf(buf,"maskI%c%d",i?'R':'L',k);
  109035. float work[n/2];
  109036. for(j=0;j<n/2;j++)
  109037. work[j]=FLOOR1_fromdB_LOOKUP[ilogmask[j]];
  109038. _analysis_output(buf,seq,work,n/2,1,1,0);
  109039. }
  109040. #endif
  109041. _vp_remove_floor(psy_look,
  109042. mdct,
  109043. ilogmask,
  109044. res,
  109045. ci->psy_g_param.sliding_lowpass[vb->W][k]);
  109046. _vp_noise_normalize(psy_look,res,res+n/2,sortindex[i]);
  109047. #if 0
  109048. {
  109049. char buf[80];
  109050. float work[n/2];
  109051. for(j=0;j<n/2;j++)
  109052. work[j]=FLOOR1_fromdB_LOOKUP[ilogmask[j]]*(res+n/2)[j];
  109053. sprintf(buf,"resI%c%d",i?'R':'L',k);
  109054. _analysis_output(buf,seq,work,n/2,1,1,0);
  109055. }
  109056. #endif
  109057. }
  109058. /* our iteration is now based on masking curve, not prequant and
  109059. coupling. Only one prequant/coupling step */
  109060. /* quantize/couple */
  109061. /* incomplete implementation that assumes the tree is all depth
  109062. one, or no tree at all */
  109063. if(info->coupling_steps){
  109064. _vp_couple(k,
  109065. &ci->psy_g_param,
  109066. psy_look,
  109067. info,
  109068. vb->pcm,
  109069. mag_memo,
  109070. mag_sort,
  109071. ilogmaskch,
  109072. nonzero,
  109073. ci->psy_g_param.sliding_lowpass[vb->W][k]);
  109074. }
  109075. /* classify and encode by submap */
  109076. for(i=0;i<info->submaps;i++){
  109077. int ch_in_bundle=0;
  109078. long **classifications;
  109079. int resnum=info->residuesubmap[i];
  109080. for(j=0;j<vi->channels;j++){
  109081. if(info->chmuxlist[j]==i){
  109082. zerobundle[ch_in_bundle]=0;
  109083. if(nonzero[j])zerobundle[ch_in_bundle]=1;
  109084. res_bundle[ch_in_bundle]=vb->pcm[j];
  109085. couple_bundle[ch_in_bundle++]=vb->pcm[j]+n/2;
  109086. }
  109087. }
  109088. classifications=_residue_P[ci->residue_type[resnum]]->
  109089. classx(vb,b->residue[resnum],couple_bundle,zerobundle,ch_in_bundle);
  109090. _residue_P[ci->residue_type[resnum]]->
  109091. forward(opb,vb,b->residue[resnum],
  109092. couple_bundle,NULL,zerobundle,ch_in_bundle,classifications);
  109093. }
  109094. /* ok, done encoding. Next protopacket. */
  109095. }
  109096. }
  109097. #if 0
  109098. seq++;
  109099. total+=ci->blocksizes[vb->W]/4+ci->blocksizes[vb->nW]/4;
  109100. #endif
  109101. return(0);
  109102. }
  109103. static int mapping0_inverse(vorbis_block *vb,vorbis_info_mapping *l){
  109104. vorbis_dsp_state *vd=vb->vd;
  109105. vorbis_info *vi=vd->vi;
  109106. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  109107. private_state *b=(private_state*)vd->backend_state;
  109108. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)l;
  109109. int i,j;
  109110. long n=vb->pcmend=ci->blocksizes[vb->W];
  109111. float **pcmbundle=(float**) alloca(sizeof(*pcmbundle)*vi->channels);
  109112. int *zerobundle=(int*) alloca(sizeof(*zerobundle)*vi->channels);
  109113. int *nonzero =(int*) alloca(sizeof(*nonzero)*vi->channels);
  109114. void **floormemo=(void**) alloca(sizeof(*floormemo)*vi->channels);
  109115. /* recover the spectral envelope; store it in the PCM vector for now */
  109116. for(i=0;i<vi->channels;i++){
  109117. int submap=info->chmuxlist[i];
  109118. floormemo[i]=_floor_P[ci->floor_type[info->floorsubmap[submap]]]->
  109119. inverse1(vb,b->flr[info->floorsubmap[submap]]);
  109120. if(floormemo[i])
  109121. nonzero[i]=1;
  109122. else
  109123. nonzero[i]=0;
  109124. memset(vb->pcm[i],0,sizeof(*vb->pcm[i])*n/2);
  109125. }
  109126. /* channel coupling can 'dirty' the nonzero listing */
  109127. for(i=0;i<info->coupling_steps;i++){
  109128. if(nonzero[info->coupling_mag[i]] ||
  109129. nonzero[info->coupling_ang[i]]){
  109130. nonzero[info->coupling_mag[i]]=1;
  109131. nonzero[info->coupling_ang[i]]=1;
  109132. }
  109133. }
  109134. /* recover the residue into our working vectors */
  109135. for(i=0;i<info->submaps;i++){
  109136. int ch_in_bundle=0;
  109137. for(j=0;j<vi->channels;j++){
  109138. if(info->chmuxlist[j]==i){
  109139. if(nonzero[j])
  109140. zerobundle[ch_in_bundle]=1;
  109141. else
  109142. zerobundle[ch_in_bundle]=0;
  109143. pcmbundle[ch_in_bundle++]=vb->pcm[j];
  109144. }
  109145. }
  109146. _residue_P[ci->residue_type[info->residuesubmap[i]]]->
  109147. inverse(vb,b->residue[info->residuesubmap[i]],
  109148. pcmbundle,zerobundle,ch_in_bundle);
  109149. }
  109150. /* channel coupling */
  109151. for(i=info->coupling_steps-1;i>=0;i--){
  109152. float *pcmM=vb->pcm[info->coupling_mag[i]];
  109153. float *pcmA=vb->pcm[info->coupling_ang[i]];
  109154. for(j=0;j<n/2;j++){
  109155. float mag=pcmM[j];
  109156. float ang=pcmA[j];
  109157. if(mag>0)
  109158. if(ang>0){
  109159. pcmM[j]=mag;
  109160. pcmA[j]=mag-ang;
  109161. }else{
  109162. pcmA[j]=mag;
  109163. pcmM[j]=mag+ang;
  109164. }
  109165. else
  109166. if(ang>0){
  109167. pcmM[j]=mag;
  109168. pcmA[j]=mag+ang;
  109169. }else{
  109170. pcmA[j]=mag;
  109171. pcmM[j]=mag-ang;
  109172. }
  109173. }
  109174. }
  109175. /* compute and apply spectral envelope */
  109176. for(i=0;i<vi->channels;i++){
  109177. float *pcm=vb->pcm[i];
  109178. int submap=info->chmuxlist[i];
  109179. _floor_P[ci->floor_type[info->floorsubmap[submap]]]->
  109180. inverse2(vb,b->flr[info->floorsubmap[submap]],
  109181. floormemo[i],pcm);
  109182. }
  109183. /* transform the PCM data; takes PCM vector, vb; modifies PCM vector */
  109184. /* only MDCT right now.... */
  109185. for(i=0;i<vi->channels;i++){
  109186. float *pcm=vb->pcm[i];
  109187. mdct_backward((mdct_lookup*) b->transform[vb->W][0],pcm,pcm);
  109188. }
  109189. /* all done! */
  109190. return(0);
  109191. }
  109192. /* export hooks */
  109193. vorbis_func_mapping mapping0_exportbundle={
  109194. &mapping0_pack,
  109195. &mapping0_unpack,
  109196. &mapping0_free_info,
  109197. &mapping0_forward,
  109198. &mapping0_inverse
  109199. };
  109200. #endif
  109201. /********* End of inlined file: mapping0.c *********/
  109202. /********* Start of inlined file: mdct.c *********/
  109203. /* this can also be run as an integer transform by uncommenting a
  109204. define in mdct.h; the integerization is a first pass and although
  109205. it's likely stable for Vorbis, the dynamic range is constrained and
  109206. roundoff isn't done (so it's noisy). Consider it functional, but
  109207. only a starting point. There's no point on a machine with an FPU */
  109208. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  109209. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  109210. // tasks..
  109211. #ifdef _MSC_VER
  109212. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  109213. #endif
  109214. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  109215. #if JUCE_USE_OGGVORBIS
  109216. #include <stdio.h>
  109217. #include <stdlib.h>
  109218. #include <string.h>
  109219. #include <math.h>
  109220. /* build lookups for trig functions; also pre-figure scaling and
  109221. some window function algebra. */
  109222. void mdct_init(mdct_lookup *lookup,int n){
  109223. int *bitrev=(int*) _ogg_malloc(sizeof(*bitrev)*(n/4));
  109224. DATA_TYPE *T=(DATA_TYPE*) _ogg_malloc(sizeof(*T)*(n+n/4));
  109225. int i;
  109226. int n2=n>>1;
  109227. int log2n=lookup->log2n=rint(log((float)n)/log(2.f));
  109228. lookup->n=n;
  109229. lookup->trig=T;
  109230. lookup->bitrev=bitrev;
  109231. /* trig lookups... */
  109232. for(i=0;i<n/4;i++){
  109233. T[i*2]=FLOAT_CONV(cos((M_PI/n)*(4*i)));
  109234. T[i*2+1]=FLOAT_CONV(-sin((M_PI/n)*(4*i)));
  109235. T[n2+i*2]=FLOAT_CONV(cos((M_PI/(2*n))*(2*i+1)));
  109236. T[n2+i*2+1]=FLOAT_CONV(sin((M_PI/(2*n))*(2*i+1)));
  109237. }
  109238. for(i=0;i<n/8;i++){
  109239. T[n+i*2]=FLOAT_CONV(cos((M_PI/n)*(4*i+2))*.5);
  109240. T[n+i*2+1]=FLOAT_CONV(-sin((M_PI/n)*(4*i+2))*.5);
  109241. }
  109242. /* bitreverse lookup... */
  109243. {
  109244. int mask=(1<<(log2n-1))-1,i,j;
  109245. int msb=1<<(log2n-2);
  109246. for(i=0;i<n/8;i++){
  109247. int acc=0;
  109248. for(j=0;msb>>j;j++)
  109249. if((msb>>j)&i)acc|=1<<j;
  109250. bitrev[i*2]=((~acc)&mask)-1;
  109251. bitrev[i*2+1]=acc;
  109252. }
  109253. }
  109254. lookup->scale=FLOAT_CONV(4.f/n);
  109255. }
  109256. /* 8 point butterfly (in place, 4 register) */
  109257. STIN void mdct_butterfly_8(DATA_TYPE *x){
  109258. REG_TYPE r0 = x[6] + x[2];
  109259. REG_TYPE r1 = x[6] - x[2];
  109260. REG_TYPE r2 = x[4] + x[0];
  109261. REG_TYPE r3 = x[4] - x[0];
  109262. x[6] = r0 + r2;
  109263. x[4] = r0 - r2;
  109264. r0 = x[5] - x[1];
  109265. r2 = x[7] - x[3];
  109266. x[0] = r1 + r0;
  109267. x[2] = r1 - r0;
  109268. r0 = x[5] + x[1];
  109269. r1 = x[7] + x[3];
  109270. x[3] = r2 + r3;
  109271. x[1] = r2 - r3;
  109272. x[7] = r1 + r0;
  109273. x[5] = r1 - r0;
  109274. }
  109275. /* 16 point butterfly (in place, 4 register) */
  109276. STIN void mdct_butterfly_16(DATA_TYPE *x){
  109277. REG_TYPE r0 = x[1] - x[9];
  109278. REG_TYPE r1 = x[0] - x[8];
  109279. x[8] += x[0];
  109280. x[9] += x[1];
  109281. x[0] = MULT_NORM((r0 + r1) * cPI2_8);
  109282. x[1] = MULT_NORM((r0 - r1) * cPI2_8);
  109283. r0 = x[3] - x[11];
  109284. r1 = x[10] - x[2];
  109285. x[10] += x[2];
  109286. x[11] += x[3];
  109287. x[2] = r0;
  109288. x[3] = r1;
  109289. r0 = x[12] - x[4];
  109290. r1 = x[13] - x[5];
  109291. x[12] += x[4];
  109292. x[13] += x[5];
  109293. x[4] = MULT_NORM((r0 - r1) * cPI2_8);
  109294. x[5] = MULT_NORM((r0 + r1) * cPI2_8);
  109295. r0 = x[14] - x[6];
  109296. r1 = x[15] - x[7];
  109297. x[14] += x[6];
  109298. x[15] += x[7];
  109299. x[6] = r0;
  109300. x[7] = r1;
  109301. mdct_butterfly_8(x);
  109302. mdct_butterfly_8(x+8);
  109303. }
  109304. /* 32 point butterfly (in place, 4 register) */
  109305. STIN void mdct_butterfly_32(DATA_TYPE *x){
  109306. REG_TYPE r0 = x[30] - x[14];
  109307. REG_TYPE r1 = x[31] - x[15];
  109308. x[30] += x[14];
  109309. x[31] += x[15];
  109310. x[14] = r0;
  109311. x[15] = r1;
  109312. r0 = x[28] - x[12];
  109313. r1 = x[29] - x[13];
  109314. x[28] += x[12];
  109315. x[29] += x[13];
  109316. x[12] = MULT_NORM( r0 * cPI1_8 - r1 * cPI3_8 );
  109317. x[13] = MULT_NORM( r0 * cPI3_8 + r1 * cPI1_8 );
  109318. r0 = x[26] - x[10];
  109319. r1 = x[27] - x[11];
  109320. x[26] += x[10];
  109321. x[27] += x[11];
  109322. x[10] = MULT_NORM(( r0 - r1 ) * cPI2_8);
  109323. x[11] = MULT_NORM(( r0 + r1 ) * cPI2_8);
  109324. r0 = x[24] - x[8];
  109325. r1 = x[25] - x[9];
  109326. x[24] += x[8];
  109327. x[25] += x[9];
  109328. x[8] = MULT_NORM( r0 * cPI3_8 - r1 * cPI1_8 );
  109329. x[9] = MULT_NORM( r1 * cPI3_8 + r0 * cPI1_8 );
  109330. r0 = x[22] - x[6];
  109331. r1 = x[7] - x[23];
  109332. x[22] += x[6];
  109333. x[23] += x[7];
  109334. x[6] = r1;
  109335. x[7] = r0;
  109336. r0 = x[4] - x[20];
  109337. r1 = x[5] - x[21];
  109338. x[20] += x[4];
  109339. x[21] += x[5];
  109340. x[4] = MULT_NORM( r1 * cPI1_8 + r0 * cPI3_8 );
  109341. x[5] = MULT_NORM( r1 * cPI3_8 - r0 * cPI1_8 );
  109342. r0 = x[2] - x[18];
  109343. r1 = x[3] - x[19];
  109344. x[18] += x[2];
  109345. x[19] += x[3];
  109346. x[2] = MULT_NORM(( r1 + r0 ) * cPI2_8);
  109347. x[3] = MULT_NORM(( r1 - r0 ) * cPI2_8);
  109348. r0 = x[0] - x[16];
  109349. r1 = x[1] - x[17];
  109350. x[16] += x[0];
  109351. x[17] += x[1];
  109352. x[0] = MULT_NORM( r1 * cPI3_8 + r0 * cPI1_8 );
  109353. x[1] = MULT_NORM( r1 * cPI1_8 - r0 * cPI3_8 );
  109354. mdct_butterfly_16(x);
  109355. mdct_butterfly_16(x+16);
  109356. }
  109357. /* N point first stage butterfly (in place, 2 register) */
  109358. STIN void mdct_butterfly_first(DATA_TYPE *T,
  109359. DATA_TYPE *x,
  109360. int points){
  109361. DATA_TYPE *x1 = x + points - 8;
  109362. DATA_TYPE *x2 = x + (points>>1) - 8;
  109363. REG_TYPE r0;
  109364. REG_TYPE r1;
  109365. do{
  109366. r0 = x1[6] - x2[6];
  109367. r1 = x1[7] - x2[7];
  109368. x1[6] += x2[6];
  109369. x1[7] += x2[7];
  109370. x2[6] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  109371. x2[7] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  109372. r0 = x1[4] - x2[4];
  109373. r1 = x1[5] - x2[5];
  109374. x1[4] += x2[4];
  109375. x1[5] += x2[5];
  109376. x2[4] = MULT_NORM(r1 * T[5] + r0 * T[4]);
  109377. x2[5] = MULT_NORM(r1 * T[4] - r0 * T[5]);
  109378. r0 = x1[2] - x2[2];
  109379. r1 = x1[3] - x2[3];
  109380. x1[2] += x2[2];
  109381. x1[3] += x2[3];
  109382. x2[2] = MULT_NORM(r1 * T[9] + r0 * T[8]);
  109383. x2[3] = MULT_NORM(r1 * T[8] - r0 * T[9]);
  109384. r0 = x1[0] - x2[0];
  109385. r1 = x1[1] - x2[1];
  109386. x1[0] += x2[0];
  109387. x1[1] += x2[1];
  109388. x2[0] = MULT_NORM(r1 * T[13] + r0 * T[12]);
  109389. x2[1] = MULT_NORM(r1 * T[12] - r0 * T[13]);
  109390. x1-=8;
  109391. x2-=8;
  109392. T+=16;
  109393. }while(x2>=x);
  109394. }
  109395. /* N/stage point generic N stage butterfly (in place, 2 register) */
  109396. STIN void mdct_butterfly_generic(DATA_TYPE *T,
  109397. DATA_TYPE *x,
  109398. int points,
  109399. int trigint){
  109400. DATA_TYPE *x1 = x + points - 8;
  109401. DATA_TYPE *x2 = x + (points>>1) - 8;
  109402. REG_TYPE r0;
  109403. REG_TYPE r1;
  109404. do{
  109405. r0 = x1[6] - x2[6];
  109406. r1 = x1[7] - x2[7];
  109407. x1[6] += x2[6];
  109408. x1[7] += x2[7];
  109409. x2[6] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  109410. x2[7] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  109411. T+=trigint;
  109412. r0 = x1[4] - x2[4];
  109413. r1 = x1[5] - x2[5];
  109414. x1[4] += x2[4];
  109415. x1[5] += x2[5];
  109416. x2[4] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  109417. x2[5] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  109418. T+=trigint;
  109419. r0 = x1[2] - x2[2];
  109420. r1 = x1[3] - x2[3];
  109421. x1[2] += x2[2];
  109422. x1[3] += x2[3];
  109423. x2[2] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  109424. x2[3] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  109425. T+=trigint;
  109426. r0 = x1[0] - x2[0];
  109427. r1 = x1[1] - x2[1];
  109428. x1[0] += x2[0];
  109429. x1[1] += x2[1];
  109430. x2[0] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  109431. x2[1] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  109432. T+=trigint;
  109433. x1-=8;
  109434. x2-=8;
  109435. }while(x2>=x);
  109436. }
  109437. STIN void mdct_butterflies(mdct_lookup *init,
  109438. DATA_TYPE *x,
  109439. int points){
  109440. DATA_TYPE *T=init->trig;
  109441. int stages=init->log2n-5;
  109442. int i,j;
  109443. if(--stages>0){
  109444. mdct_butterfly_first(T,x,points);
  109445. }
  109446. for(i=1;--stages>0;i++){
  109447. for(j=0;j<(1<<i);j++)
  109448. mdct_butterfly_generic(T,x+(points>>i)*j,points>>i,4<<i);
  109449. }
  109450. for(j=0;j<points;j+=32)
  109451. mdct_butterfly_32(x+j);
  109452. }
  109453. void mdct_clear(mdct_lookup *l){
  109454. if(l){
  109455. if(l->trig)_ogg_free(l->trig);
  109456. if(l->bitrev)_ogg_free(l->bitrev);
  109457. memset(l,0,sizeof(*l));
  109458. }
  109459. }
  109460. STIN void mdct_bitreverse(mdct_lookup *init,
  109461. DATA_TYPE *x){
  109462. int n = init->n;
  109463. int *bit = init->bitrev;
  109464. DATA_TYPE *w0 = x;
  109465. DATA_TYPE *w1 = x = w0+(n>>1);
  109466. DATA_TYPE *T = init->trig+n;
  109467. do{
  109468. DATA_TYPE *x0 = x+bit[0];
  109469. DATA_TYPE *x1 = x+bit[1];
  109470. REG_TYPE r0 = x0[1] - x1[1];
  109471. REG_TYPE r1 = x0[0] + x1[0];
  109472. REG_TYPE r2 = MULT_NORM(r1 * T[0] + r0 * T[1]);
  109473. REG_TYPE r3 = MULT_NORM(r1 * T[1] - r0 * T[0]);
  109474. w1 -= 4;
  109475. r0 = HALVE(x0[1] + x1[1]);
  109476. r1 = HALVE(x0[0] - x1[0]);
  109477. w0[0] = r0 + r2;
  109478. w1[2] = r0 - r2;
  109479. w0[1] = r1 + r3;
  109480. w1[3] = r3 - r1;
  109481. x0 = x+bit[2];
  109482. x1 = x+bit[3];
  109483. r0 = x0[1] - x1[1];
  109484. r1 = x0[0] + x1[0];
  109485. r2 = MULT_NORM(r1 * T[2] + r0 * T[3]);
  109486. r3 = MULT_NORM(r1 * T[3] - r0 * T[2]);
  109487. r0 = HALVE(x0[1] + x1[1]);
  109488. r1 = HALVE(x0[0] - x1[0]);
  109489. w0[2] = r0 + r2;
  109490. w1[0] = r0 - r2;
  109491. w0[3] = r1 + r3;
  109492. w1[1] = r3 - r1;
  109493. T += 4;
  109494. bit += 4;
  109495. w0 += 4;
  109496. }while(w0<w1);
  109497. }
  109498. void mdct_backward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out){
  109499. int n=init->n;
  109500. int n2=n>>1;
  109501. int n4=n>>2;
  109502. /* rotate */
  109503. DATA_TYPE *iX = in+n2-7;
  109504. DATA_TYPE *oX = out+n2+n4;
  109505. DATA_TYPE *T = init->trig+n4;
  109506. do{
  109507. oX -= 4;
  109508. oX[0] = MULT_NORM(-iX[2] * T[3] - iX[0] * T[2]);
  109509. oX[1] = MULT_NORM (iX[0] * T[3] - iX[2] * T[2]);
  109510. oX[2] = MULT_NORM(-iX[6] * T[1] - iX[4] * T[0]);
  109511. oX[3] = MULT_NORM (iX[4] * T[1] - iX[6] * T[0]);
  109512. iX -= 8;
  109513. T += 4;
  109514. }while(iX>=in);
  109515. iX = in+n2-8;
  109516. oX = out+n2+n4;
  109517. T = init->trig+n4;
  109518. do{
  109519. T -= 4;
  109520. oX[0] = MULT_NORM (iX[4] * T[3] + iX[6] * T[2]);
  109521. oX[1] = MULT_NORM (iX[4] * T[2] - iX[6] * T[3]);
  109522. oX[2] = MULT_NORM (iX[0] * T[1] + iX[2] * T[0]);
  109523. oX[3] = MULT_NORM (iX[0] * T[0] - iX[2] * T[1]);
  109524. iX -= 8;
  109525. oX += 4;
  109526. }while(iX>=in);
  109527. mdct_butterflies(init,out+n2,n2);
  109528. mdct_bitreverse(init,out);
  109529. /* roatate + window */
  109530. {
  109531. DATA_TYPE *oX1=out+n2+n4;
  109532. DATA_TYPE *oX2=out+n2+n4;
  109533. DATA_TYPE *iX =out;
  109534. T =init->trig+n2;
  109535. do{
  109536. oX1-=4;
  109537. oX1[3] = MULT_NORM (iX[0] * T[1] - iX[1] * T[0]);
  109538. oX2[0] = -MULT_NORM (iX[0] * T[0] + iX[1] * T[1]);
  109539. oX1[2] = MULT_NORM (iX[2] * T[3] - iX[3] * T[2]);
  109540. oX2[1] = -MULT_NORM (iX[2] * T[2] + iX[3] * T[3]);
  109541. oX1[1] = MULT_NORM (iX[4] * T[5] - iX[5] * T[4]);
  109542. oX2[2] = -MULT_NORM (iX[4] * T[4] + iX[5] * T[5]);
  109543. oX1[0] = MULT_NORM (iX[6] * T[7] - iX[7] * T[6]);
  109544. oX2[3] = -MULT_NORM (iX[6] * T[6] + iX[7] * T[7]);
  109545. oX2+=4;
  109546. iX += 8;
  109547. T += 8;
  109548. }while(iX<oX1);
  109549. iX=out+n2+n4;
  109550. oX1=out+n4;
  109551. oX2=oX1;
  109552. do{
  109553. oX1-=4;
  109554. iX-=4;
  109555. oX2[0] = -(oX1[3] = iX[3]);
  109556. oX2[1] = -(oX1[2] = iX[2]);
  109557. oX2[2] = -(oX1[1] = iX[1]);
  109558. oX2[3] = -(oX1[0] = iX[0]);
  109559. oX2+=4;
  109560. }while(oX2<iX);
  109561. iX=out+n2+n4;
  109562. oX1=out+n2+n4;
  109563. oX2=out+n2;
  109564. do{
  109565. oX1-=4;
  109566. oX1[0]= iX[3];
  109567. oX1[1]= iX[2];
  109568. oX1[2]= iX[1];
  109569. oX1[3]= iX[0];
  109570. iX+=4;
  109571. }while(oX1>oX2);
  109572. }
  109573. }
  109574. void mdct_forward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out){
  109575. int n=init->n;
  109576. int n2=n>>1;
  109577. int n4=n>>2;
  109578. int n8=n>>3;
  109579. DATA_TYPE *w=(DATA_TYPE*) alloca(n*sizeof(*w)); /* forward needs working space */
  109580. DATA_TYPE *w2=w+n2;
  109581. /* rotate */
  109582. /* window + rotate + step 1 */
  109583. REG_TYPE r0;
  109584. REG_TYPE r1;
  109585. DATA_TYPE *x0=in+n2+n4;
  109586. DATA_TYPE *x1=x0+1;
  109587. DATA_TYPE *T=init->trig+n2;
  109588. int i=0;
  109589. for(i=0;i<n8;i+=2){
  109590. x0 -=4;
  109591. T-=2;
  109592. r0= x0[2] + x1[0];
  109593. r1= x0[0] + x1[2];
  109594. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  109595. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  109596. x1 +=4;
  109597. }
  109598. x1=in+1;
  109599. for(;i<n2-n8;i+=2){
  109600. T-=2;
  109601. x0 -=4;
  109602. r0= x0[2] - x1[0];
  109603. r1= x0[0] - x1[2];
  109604. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  109605. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  109606. x1 +=4;
  109607. }
  109608. x0=in+n;
  109609. for(;i<n2;i+=2){
  109610. T-=2;
  109611. x0 -=4;
  109612. r0= -x0[2] - x1[0];
  109613. r1= -x0[0] - x1[2];
  109614. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  109615. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  109616. x1 +=4;
  109617. }
  109618. mdct_butterflies(init,w+n2,n2);
  109619. mdct_bitreverse(init,w);
  109620. /* roatate + window */
  109621. T=init->trig+n2;
  109622. x0=out+n2;
  109623. for(i=0;i<n4;i++){
  109624. x0--;
  109625. out[i] =MULT_NORM((w[0]*T[0]+w[1]*T[1])*init->scale);
  109626. x0[0] =MULT_NORM((w[0]*T[1]-w[1]*T[0])*init->scale);
  109627. w+=2;
  109628. T+=2;
  109629. }
  109630. }
  109631. #endif
  109632. /********* End of inlined file: mdct.c *********/
  109633. /********* Start of inlined file: psy.c *********/
  109634. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  109635. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  109636. // tasks..
  109637. #ifdef _MSC_VER
  109638. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  109639. #endif
  109640. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  109641. #if JUCE_USE_OGGVORBIS
  109642. #include <stdlib.h>
  109643. #include <math.h>
  109644. #include <string.h>
  109645. /********* Start of inlined file: masking.h *********/
  109646. #ifndef _V_MASKING_H_
  109647. #define _V_MASKING_H_
  109648. /* more detailed ATH; the bass if flat to save stressing the floor
  109649. overly for only a bin or two of savings. */
  109650. #define MAX_ATH 88
  109651. static float ATH[]={
  109652. /*15*/ -51, -52, -53, -54, -55, -56, -57, -58,
  109653. /*31*/ -59, -60, -61, -62, -63, -64, -65, -66,
  109654. /*63*/ -67, -68, -69, -70, -71, -72, -73, -74,
  109655. /*125*/ -75, -76, -77, -78, -80, -81, -82, -83,
  109656. /*250*/ -84, -85, -86, -87, -88, -88, -89, -89,
  109657. /*500*/ -90, -91, -91, -92, -93, -94, -95, -96,
  109658. /*1k*/ -96, -97, -98, -98, -99, -99,-100,-100,
  109659. /*2k*/ -101,-102,-103,-104,-106,-107,-107,-107,
  109660. /*4k*/ -107,-105,-103,-102,-101, -99, -98, -96,
  109661. /*8k*/ -95, -95, -96, -97, -96, -95, -93, -90,
  109662. /*16k*/ -80, -70, -50, -40, -30, -30, -30, -30
  109663. };
  109664. /* The tone masking curves from Ehmer's and Fielder's papers have been
  109665. replaced by an empirically collected data set. The previously
  109666. published values were, far too often, simply on crack. */
  109667. #define EHMER_OFFSET 16
  109668. #define EHMER_MAX 56
  109669. /* masking tones from -50 to 0dB, 62.5 through 16kHz at half octaves
  109670. test tones from -2 octaves to +5 octaves sampled at eighth octaves */
  109671. /* (Vorbis 0dB, the loudest possible tone, is assumed to be ~100dB SPL
  109672. for collection of these curves) */
  109673. static float tonemasks[P_BANDS][6][EHMER_MAX]={
  109674. /* 62.5 Hz */
  109675. {{ -60, -60, -60, -60, -60, -60, -60, -60,
  109676. -60, -60, -60, -60, -62, -62, -65, -73,
  109677. -69, -68, -68, -67, -70, -70, -72, -74,
  109678. -75, -79, -79, -80, -83, -88, -93, -100,
  109679. -110, -999, -999, -999, -999, -999, -999, -999,
  109680. -999, -999, -999, -999, -999, -999, -999, -999,
  109681. -999, -999, -999, -999, -999, -999, -999, -999},
  109682. { -48, -48, -48, -48, -48, -48, -48, -48,
  109683. -48, -48, -48, -48, -48, -53, -61, -66,
  109684. -66, -68, -67, -70, -76, -76, -72, -73,
  109685. -75, -76, -78, -79, -83, -88, -93, -100,
  109686. -110, -999, -999, -999, -999, -999, -999, -999,
  109687. -999, -999, -999, -999, -999, -999, -999, -999,
  109688. -999, -999, -999, -999, -999, -999, -999, -999},
  109689. { -37, -37, -37, -37, -37, -37, -37, -37,
  109690. -38, -40, -42, -46, -48, -53, -55, -62,
  109691. -65, -58, -56, -56, -61, -60, -65, -67,
  109692. -69, -71, -77, -77, -78, -80, -82, -84,
  109693. -88, -93, -98, -106, -112, -999, -999, -999,
  109694. -999, -999, -999, -999, -999, -999, -999, -999,
  109695. -999, -999, -999, -999, -999, -999, -999, -999},
  109696. { -25, -25, -25, -25, -25, -25, -25, -25,
  109697. -25, -26, -27, -29, -32, -38, -48, -52,
  109698. -52, -50, -48, -48, -51, -52, -54, -60,
  109699. -67, -67, -66, -68, -69, -73, -73, -76,
  109700. -80, -81, -81, -85, -85, -86, -88, -93,
  109701. -100, -110, -999, -999, -999, -999, -999, -999,
  109702. -999, -999, -999, -999, -999, -999, -999, -999},
  109703. { -16, -16, -16, -16, -16, -16, -16, -16,
  109704. -17, -19, -20, -22, -26, -28, -31, -40,
  109705. -47, -39, -39, -40, -42, -43, -47, -51,
  109706. -57, -52, -55, -55, -60, -58, -62, -63,
  109707. -70, -67, -69, -72, -73, -77, -80, -82,
  109708. -83, -87, -90, -94, -98, -104, -115, -999,
  109709. -999, -999, -999, -999, -999, -999, -999, -999},
  109710. { -8, -8, -8, -8, -8, -8, -8, -8,
  109711. -8, -8, -10, -11, -15, -19, -25, -30,
  109712. -34, -31, -30, -31, -29, -32, -35, -42,
  109713. -48, -42, -44, -46, -50, -50, -51, -52,
  109714. -59, -54, -55, -55, -58, -62, -63, -66,
  109715. -72, -73, -76, -75, -78, -80, -80, -81,
  109716. -84, -88, -90, -94, -98, -101, -106, -110}},
  109717. /* 88Hz */
  109718. {{ -66, -66, -66, -66, -66, -66, -66, -66,
  109719. -66, -66, -66, -66, -66, -67, -67, -67,
  109720. -76, -72, -71, -74, -76, -76, -75, -78,
  109721. -79, -79, -81, -83, -86, -89, -93, -97,
  109722. -100, -105, -110, -999, -999, -999, -999, -999,
  109723. -999, -999, -999, -999, -999, -999, -999, -999,
  109724. -999, -999, -999, -999, -999, -999, -999, -999},
  109725. { -47, -47, -47, -47, -47, -47, -47, -47,
  109726. -47, -47, -47, -48, -51, -55, -59, -66,
  109727. -66, -66, -67, -66, -68, -69, -70, -74,
  109728. -79, -77, -77, -78, -80, -81, -82, -84,
  109729. -86, -88, -91, -95, -100, -108, -116, -999,
  109730. -999, -999, -999, -999, -999, -999, -999, -999,
  109731. -999, -999, -999, -999, -999, -999, -999, -999},
  109732. { -36, -36, -36, -36, -36, -36, -36, -36,
  109733. -36, -37, -37, -41, -44, -48, -51, -58,
  109734. -62, -60, -57, -59, -59, -60, -63, -65,
  109735. -72, -71, -70, -72, -74, -77, -76, -78,
  109736. -81, -81, -80, -83, -86, -91, -96, -100,
  109737. -105, -110, -999, -999, -999, -999, -999, -999,
  109738. -999, -999, -999, -999, -999, -999, -999, -999},
  109739. { -28, -28, -28, -28, -28, -28, -28, -28,
  109740. -28, -30, -32, -32, -33, -35, -41, -49,
  109741. -50, -49, -47, -48, -48, -52, -51, -57,
  109742. -65, -61, -59, -61, -64, -69, -70, -74,
  109743. -77, -77, -78, -81, -84, -85, -87, -90,
  109744. -92, -96, -100, -107, -112, -999, -999, -999,
  109745. -999, -999, -999, -999, -999, -999, -999, -999},
  109746. { -19, -19, -19, -19, -19, -19, -19, -19,
  109747. -20, -21, -23, -27, -30, -35, -36, -41,
  109748. -46, -44, -42, -40, -41, -41, -43, -48,
  109749. -55, -53, -52, -53, -56, -59, -58, -60,
  109750. -67, -66, -69, -71, -72, -75, -79, -81,
  109751. -84, -87, -90, -93, -97, -101, -107, -114,
  109752. -999, -999, -999, -999, -999, -999, -999, -999},
  109753. { -9, -9, -9, -9, -9, -9, -9, -9,
  109754. -11, -12, -12, -15, -16, -20, -23, -30,
  109755. -37, -34, -33, -34, -31, -32, -32, -38,
  109756. -47, -44, -41, -40, -47, -49, -46, -46,
  109757. -58, -50, -50, -54, -58, -62, -64, -67,
  109758. -67, -70, -72, -76, -79, -83, -87, -91,
  109759. -96, -100, -104, -110, -999, -999, -999, -999}},
  109760. /* 125 Hz */
  109761. {{ -62, -62, -62, -62, -62, -62, -62, -62,
  109762. -62, -62, -63, -64, -66, -67, -66, -68,
  109763. -75, -72, -76, -75, -76, -78, -79, -82,
  109764. -84, -85, -90, -94, -101, -110, -999, -999,
  109765. -999, -999, -999, -999, -999, -999, -999, -999,
  109766. -999, -999, -999, -999, -999, -999, -999, -999,
  109767. -999, -999, -999, -999, -999, -999, -999, -999},
  109768. { -59, -59, -59, -59, -59, -59, -59, -59,
  109769. -59, -59, -59, -60, -60, -61, -63, -66,
  109770. -71, -68, -70, -70, -71, -72, -72, -75,
  109771. -81, -78, -79, -82, -83, -86, -90, -97,
  109772. -103, -113, -999, -999, -999, -999, -999, -999,
  109773. -999, -999, -999, -999, -999, -999, -999, -999,
  109774. -999, -999, -999, -999, -999, -999, -999, -999},
  109775. { -53, -53, -53, -53, -53, -53, -53, -53,
  109776. -53, -54, -55, -57, -56, -57, -55, -61,
  109777. -65, -60, -60, -62, -63, -63, -66, -68,
  109778. -74, -73, -75, -75, -78, -80, -80, -82,
  109779. -85, -90, -96, -101, -108, -999, -999, -999,
  109780. -999, -999, -999, -999, -999, -999, -999, -999,
  109781. -999, -999, -999, -999, -999, -999, -999, -999},
  109782. { -46, -46, -46, -46, -46, -46, -46, -46,
  109783. -46, -46, -47, -47, -47, -47, -48, -51,
  109784. -57, -51, -49, -50, -51, -53, -54, -59,
  109785. -66, -60, -62, -67, -67, -70, -72, -75,
  109786. -76, -78, -81, -85, -88, -94, -97, -104,
  109787. -112, -999, -999, -999, -999, -999, -999, -999,
  109788. -999, -999, -999, -999, -999, -999, -999, -999},
  109789. { -36, -36, -36, -36, -36, -36, -36, -36,
  109790. -39, -41, -42, -42, -39, -38, -41, -43,
  109791. -52, -44, -40, -39, -37, -37, -40, -47,
  109792. -54, -50, -48, -50, -55, -61, -59, -62,
  109793. -66, -66, -66, -69, -69, -73, -74, -74,
  109794. -75, -77, -79, -82, -87, -91, -95, -100,
  109795. -108, -115, -999, -999, -999, -999, -999, -999},
  109796. { -28, -26, -24, -22, -20, -20, -23, -29,
  109797. -30, -31, -28, -27, -28, -28, -28, -35,
  109798. -40, -33, -32, -29, -30, -30, -30, -37,
  109799. -45, -41, -37, -38, -45, -47, -47, -48,
  109800. -53, -49, -48, -50, -49, -49, -51, -52,
  109801. -58, -56, -57, -56, -60, -61, -62, -70,
  109802. -72, -74, -78, -83, -88, -93, -100, -106}},
  109803. /* 177 Hz */
  109804. {{-999, -999, -999, -999, -999, -999, -999, -999,
  109805. -999, -110, -105, -100, -95, -91, -87, -83,
  109806. -80, -78, -76, -78, -78, -81, -83, -85,
  109807. -86, -85, -86, -87, -90, -97, -107, -999,
  109808. -999, -999, -999, -999, -999, -999, -999, -999,
  109809. -999, -999, -999, -999, -999, -999, -999, -999,
  109810. -999, -999, -999, -999, -999, -999, -999, -999},
  109811. {-999, -999, -999, -110, -105, -100, -95, -90,
  109812. -85, -81, -77, -73, -70, -67, -67, -68,
  109813. -75, -73, -70, -69, -70, -72, -75, -79,
  109814. -84, -83, -84, -86, -88, -89, -89, -93,
  109815. -98, -105, -112, -999, -999, -999, -999, -999,
  109816. -999, -999, -999, -999, -999, -999, -999, -999,
  109817. -999, -999, -999, -999, -999, -999, -999, -999},
  109818. {-105, -100, -95, -90, -85, -80, -76, -71,
  109819. -68, -68, -65, -63, -63, -62, -62, -64,
  109820. -65, -64, -61, -62, -63, -64, -66, -68,
  109821. -73, -73, -74, -75, -76, -81, -83, -85,
  109822. -88, -89, -92, -95, -100, -108, -999, -999,
  109823. -999, -999, -999, -999, -999, -999, -999, -999,
  109824. -999, -999, -999, -999, -999, -999, -999, -999},
  109825. { -80, -75, -71, -68, -65, -63, -62, -61,
  109826. -61, -61, -61, -59, -56, -57, -53, -50,
  109827. -58, -52, -50, -50, -52, -53, -54, -58,
  109828. -67, -63, -67, -68, -72, -75, -78, -80,
  109829. -81, -81, -82, -85, -89, -90, -93, -97,
  109830. -101, -107, -114, -999, -999, -999, -999, -999,
  109831. -999, -999, -999, -999, -999, -999, -999, -999},
  109832. { -65, -61, -59, -57, -56, -55, -55, -56,
  109833. -56, -57, -55, -53, -52, -47, -44, -44,
  109834. -50, -44, -41, -39, -39, -42, -40, -46,
  109835. -51, -49, -50, -53, -54, -63, -60, -61,
  109836. -62, -66, -66, -66, -70, -73, -74, -75,
  109837. -76, -75, -79, -85, -89, -91, -96, -102,
  109838. -110, -999, -999, -999, -999, -999, -999, -999},
  109839. { -52, -50, -49, -49, -48, -48, -48, -49,
  109840. -50, -50, -49, -46, -43, -39, -35, -33,
  109841. -38, -36, -32, -29, -32, -32, -32, -35,
  109842. -44, -39, -38, -38, -46, -50, -45, -46,
  109843. -53, -50, -50, -50, -54, -54, -53, -53,
  109844. -56, -57, -59, -66, -70, -72, -74, -79,
  109845. -83, -85, -90, -97, -114, -999, -999, -999}},
  109846. /* 250 Hz */
  109847. {{-999, -999, -999, -999, -999, -999, -110, -105,
  109848. -100, -95, -90, -86, -80, -75, -75, -79,
  109849. -80, -79, -80, -81, -82, -88, -95, -103,
  109850. -110, -999, -999, -999, -999, -999, -999, -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, -999, -108, -103, -98, -93,
  109855. -88, -83, -79, -78, -75, -71, -67, -68,
  109856. -73, -73, -72, -73, -75, -77, -80, -82,
  109857. -88, -93, -100, -107, -114, -999, -999, -999,
  109858. -999, -999, -999, -999, -999, -999, -999, -999,
  109859. -999, -999, -999, -999, -999, -999, -999, -999,
  109860. -999, -999, -999, -999, -999, -999, -999, -999},
  109861. {-999, -999, -999, -110, -105, -101, -96, -90,
  109862. -86, -81, -77, -73, -69, -66, -61, -62,
  109863. -66, -64, -62, -65, -66, -70, -72, -76,
  109864. -81, -80, -84, -90, -95, -102, -110, -999,
  109865. -999, -999, -999, -999, -999, -999, -999, -999,
  109866. -999, -999, -999, -999, -999, -999, -999, -999,
  109867. -999, -999, -999, -999, -999, -999, -999, -999},
  109868. {-999, -999, -999, -107, -103, -97, -92, -88,
  109869. -83, -79, -74, -70, -66, -59, -53, -58,
  109870. -62, -55, -54, -54, -54, -58, -61, -62,
  109871. -72, -70, -72, -75, -78, -80, -81, -80,
  109872. -83, -83, -88, -93, -100, -107, -115, -999,
  109873. -999, -999, -999, -999, -999, -999, -999, -999,
  109874. -999, -999, -999, -999, -999, -999, -999, -999},
  109875. {-999, -999, -999, -105, -100, -95, -90, -85,
  109876. -80, -75, -70, -66, -62, -56, -48, -44,
  109877. -48, -46, -46, -43, -46, -48, -48, -51,
  109878. -58, -58, -59, -60, -62, -62, -61, -61,
  109879. -65, -64, -65, -68, -70, -74, -75, -78,
  109880. -81, -86, -95, -110, -999, -999, -999, -999,
  109881. -999, -999, -999, -999, -999, -999, -999, -999},
  109882. {-999, -999, -105, -100, -95, -90, -85, -80,
  109883. -75, -70, -65, -61, -55, -49, -39, -33,
  109884. -40, -35, -32, -38, -40, -33, -35, -37,
  109885. -46, -41, -45, -44, -46, -42, -45, -46,
  109886. -52, -50, -50, -50, -54, -54, -55, -57,
  109887. -62, -64, -66, -68, -70, -76, -81, -90,
  109888. -100, -110, -999, -999, -999, -999, -999, -999}},
  109889. /* 354 hz */
  109890. {{-999, -999, -999, -999, -999, -999, -999, -999,
  109891. -105, -98, -90, -85, -82, -83, -80, -78,
  109892. -84, -79, -80, -83, -87, -89, -91, -93,
  109893. -99, -106, -117, -999, -999, -999, -999, -999,
  109894. -999, -999, -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. -105, -98, -90, -85, -80, -75, -70, -68,
  109899. -74, -72, -74, -77, -80, -82, -85, -87,
  109900. -92, -89, -91, -95, -100, -106, -112, -999,
  109901. -999, -999, -999, -999, -999, -999, -999, -999,
  109902. -999, -999, -999, -999, -999, -999, -999, -999,
  109903. -999, -999, -999, -999, -999, -999, -999, -999},
  109904. {-999, -999, -999, -999, -999, -999, -999, -999,
  109905. -105, -98, -90, -83, -75, -71, -63, -64,
  109906. -67, -62, -64, -67, -70, -73, -77, -81,
  109907. -84, -83, -85, -89, -90, -93, -98, -104,
  109908. -109, -114, -999, -999, -999, -999, -999, -999,
  109909. -999, -999, -999, -999, -999, -999, -999, -999,
  109910. -999, -999, -999, -999, -999, -999, -999, -999},
  109911. {-999, -999, -999, -999, -999, -999, -999, -999,
  109912. -103, -96, -88, -81, -75, -68, -58, -54,
  109913. -56, -54, -56, -56, -58, -60, -63, -66,
  109914. -74, -69, -72, -72, -75, -74, -77, -81,
  109915. -81, -82, -84, -87, -93, -96, -99, -104,
  109916. -110, -999, -999, -999, -999, -999, -999, -999,
  109917. -999, -999, -999, -999, -999, -999, -999, -999},
  109918. {-999, -999, -999, -999, -999, -108, -102, -96,
  109919. -91, -85, -80, -74, -68, -60, -51, -46,
  109920. -48, -46, -43, -45, -47, -47, -49, -48,
  109921. -56, -53, -55, -58, -57, -63, -58, -60,
  109922. -66, -64, -67, -70, -70, -74, -77, -84,
  109923. -86, -89, -91, -93, -94, -101, -109, -118,
  109924. -999, -999, -999, -999, -999, -999, -999, -999},
  109925. {-999, -999, -999, -108, -103, -98, -93, -88,
  109926. -83, -78, -73, -68, -60, -53, -44, -35,
  109927. -38, -38, -34, -34, -36, -40, -41, -44,
  109928. -51, -45, -46, -47, -46, -54, -50, -49,
  109929. -50, -50, -50, -51, -54, -57, -58, -60,
  109930. -66, -66, -66, -64, -65, -68, -77, -82,
  109931. -87, -95, -110, -999, -999, -999, -999, -999}},
  109932. /* 500 Hz */
  109933. {{-999, -999, -999, -999, -999, -999, -999, -999,
  109934. -107, -102, -97, -92, -87, -83, -78, -75,
  109935. -82, -79, -83, -85, -89, -92, -95, -98,
  109936. -101, -105, -109, -113, -999, -999, -999, -999,
  109937. -999, -999, -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, -999, -999, -106,
  109941. -100, -95, -90, -86, -81, -78, -74, -69,
  109942. -74, -74, -76, -79, -83, -84, -86, -89,
  109943. -92, -97, -93, -100, -103, -107, -110, -999,
  109944. -999, -999, -999, -999, -999, -999, -999, -999,
  109945. -999, -999, -999, -999, -999, -999, -999, -999,
  109946. -999, -999, -999, -999, -999, -999, -999, -999},
  109947. {-999, -999, -999, -999, -999, -999, -106, -100,
  109948. -95, -90, -87, -83, -80, -75, -69, -60,
  109949. -66, -66, -68, -70, -74, -78, -79, -81,
  109950. -81, -83, -84, -87, -93, -96, -99, -103,
  109951. -107, -110, -999, -999, -999, -999, -999, -999,
  109952. -999, -999, -999, -999, -999, -999, -999, -999,
  109953. -999, -999, -999, -999, -999, -999, -999, -999},
  109954. {-999, -999, -999, -999, -999, -108, -103, -98,
  109955. -93, -89, -85, -82, -78, -71, -62, -55,
  109956. -58, -58, -54, -54, -55, -59, -61, -62,
  109957. -70, -66, -66, -67, -70, -72, -75, -78,
  109958. -84, -84, -84, -88, -91, -90, -95, -98,
  109959. -102, -103, -106, -110, -999, -999, -999, -999,
  109960. -999, -999, -999, -999, -999, -999, -999, -999},
  109961. {-999, -999, -999, -999, -108, -103, -98, -94,
  109962. -90, -87, -82, -79, -73, -67, -58, -47,
  109963. -50, -45, -41, -45, -48, -44, -44, -49,
  109964. -54, -51, -48, -47, -49, -50, -51, -57,
  109965. -58, -60, -63, -69, -70, -69, -71, -74,
  109966. -78, -82, -90, -95, -101, -105, -110, -999,
  109967. -999, -999, -999, -999, -999, -999, -999, -999},
  109968. {-999, -999, -999, -105, -101, -97, -93, -90,
  109969. -85, -80, -77, -72, -65, -56, -48, -37,
  109970. -40, -36, -34, -40, -50, -47, -38, -41,
  109971. -47, -38, -35, -39, -38, -43, -40, -45,
  109972. -50, -45, -44, -47, -50, -55, -48, -48,
  109973. -52, -66, -70, -76, -82, -90, -97, -105,
  109974. -110, -999, -999, -999, -999, -999, -999, -999}},
  109975. /* 707 Hz */
  109976. {{-999, -999, -999, -999, -999, -999, -999, -999,
  109977. -999, -108, -103, -98, -93, -86, -79, -76,
  109978. -83, -81, -85, -87, -89, -93, -98, -102,
  109979. -107, -112, -999, -999, -999, -999, -999, -999,
  109980. -999, -999, -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. -999, -108, -103, -98, -93, -86, -79, -71,
  109985. -77, -74, -77, -79, -81, -84, -85, -90,
  109986. -92, -93, -92, -98, -101, -108, -112, -999,
  109987. -999, -999, -999, -999, -999, -999, -999, -999,
  109988. -999, -999, -999, -999, -999, -999, -999, -999,
  109989. -999, -999, -999, -999, -999, -999, -999, -999},
  109990. {-999, -999, -999, -999, -999, -999, -999, -999,
  109991. -108, -103, -98, -93, -87, -78, -68, -65,
  109992. -66, -62, -65, -67, -70, -73, -75, -78,
  109993. -82, -82, -83, -84, -91, -93, -98, -102,
  109994. -106, -110, -999, -999, -999, -999, -999, -999,
  109995. -999, -999, -999, -999, -999, -999, -999, -999,
  109996. -999, -999, -999, -999, -999, -999, -999, -999},
  109997. {-999, -999, -999, -999, -999, -999, -999, -999,
  109998. -105, -100, -95, -90, -82, -74, -62, -57,
  109999. -58, -56, -51, -52, -52, -54, -54, -58,
  110000. -66, -59, -60, -63, -66, -69, -73, -79,
  110001. -83, -84, -80, -81, -81, -82, -88, -92,
  110002. -98, -105, -113, -999, -999, -999, -999, -999,
  110003. -999, -999, -999, -999, -999, -999, -999, -999},
  110004. {-999, -999, -999, -999, -999, -999, -999, -107,
  110005. -102, -97, -92, -84, -79, -69, -57, -47,
  110006. -52, -47, -44, -45, -50, -52, -42, -42,
  110007. -53, -43, -43, -48, -51, -56, -55, -52,
  110008. -57, -59, -61, -62, -67, -71, -78, -83,
  110009. -86, -94, -98, -103, -110, -999, -999, -999,
  110010. -999, -999, -999, -999, -999, -999, -999, -999},
  110011. {-999, -999, -999, -999, -999, -999, -105, -100,
  110012. -95, -90, -84, -78, -70, -61, -51, -41,
  110013. -40, -38, -40, -46, -52, -51, -41, -40,
  110014. -46, -40, -38, -38, -41, -46, -41, -46,
  110015. -47, -43, -43, -45, -41, -45, -56, -67,
  110016. -68, -83, -87, -90, -95, -102, -107, -113,
  110017. -999, -999, -999, -999, -999, -999, -999, -999}},
  110018. /* 1000 Hz */
  110019. {{-999, -999, -999, -999, -999, -999, -999, -999,
  110020. -999, -109, -105, -101, -96, -91, -84, -77,
  110021. -82, -82, -85, -89, -94, -100, -106, -110,
  110022. -999, -999, -999, -999, -999, -999, -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, -999,
  110027. -999, -106, -103, -98, -92, -85, -80, -71,
  110028. -75, -72, -76, -80, -84, -86, -89, -93,
  110029. -100, -107, -113, -999, -999, -999, -999, -999,
  110030. -999, -999, -999, -999, -999, -999, -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, -999, -107,
  110034. -104, -101, -97, -92, -88, -84, -80, -64,
  110035. -66, -63, -64, -66, -69, -73, -77, -83,
  110036. -83, -86, -91, -98, -104, -111, -999, -999,
  110037. -999, -999, -999, -999, -999, -999, -999, -999,
  110038. -999, -999, -999, -999, -999, -999, -999, -999,
  110039. -999, -999, -999, -999, -999, -999, -999, -999},
  110040. {-999, -999, -999, -999, -999, -999, -999, -107,
  110041. -104, -101, -97, -92, -90, -84, -74, -57,
  110042. -58, -52, -55, -54, -50, -52, -50, -52,
  110043. -63, -62, -69, -76, -77, -78, -78, -79,
  110044. -82, -88, -94, -100, -106, -111, -999, -999,
  110045. -999, -999, -999, -999, -999, -999, -999, -999,
  110046. -999, -999, -999, -999, -999, -999, -999, -999},
  110047. {-999, -999, -999, -999, -999, -999, -106, -102,
  110048. -98, -95, -90, -85, -83, -78, -70, -50,
  110049. -50, -41, -44, -49, -47, -50, -50, -44,
  110050. -55, -46, -47, -48, -48, -54, -49, -49,
  110051. -58, -62, -71, -81, -87, -92, -97, -102,
  110052. -108, -114, -999, -999, -999, -999, -999, -999,
  110053. -999, -999, -999, -999, -999, -999, -999, -999},
  110054. {-999, -999, -999, -999, -999, -999, -106, -102,
  110055. -98, -95, -90, -85, -83, -78, -70, -45,
  110056. -43, -41, -47, -50, -51, -50, -49, -45,
  110057. -47, -41, -44, -41, -39, -43, -38, -37,
  110058. -40, -41, -44, -50, -58, -65, -73, -79,
  110059. -85, -92, -97, -101, -105, -109, -113, -999,
  110060. -999, -999, -999, -999, -999, -999, -999, -999}},
  110061. /* 1414 Hz */
  110062. {{-999, -999, -999, -999, -999, -999, -999, -999,
  110063. -999, -999, -999, -107, -100, -95, -87, -81,
  110064. -85, -83, -88, -93, -100, -107, -114, -999,
  110065. -999, -999, -999, -999, -999, -999, -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, -107, -101, -95, -88, -83, -76,
  110071. -73, -72, -79, -84, -90, -95, -100, -105,
  110072. -110, -115, -999, -999, -999, -999, -999, -999,
  110073. -999, -999, -999, -999, -999, -999, -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, -999,
  110077. -999, -999, -104, -98, -92, -87, -81, -70,
  110078. -65, -62, -67, -71, -74, -80, -85, -91,
  110079. -95, -99, -103, -108, -111, -114, -999, -999,
  110080. -999, -999, -999, -999, -999, -999, -999, -999,
  110081. -999, -999, -999, -999, -999, -999, -999, -999,
  110082. -999, -999, -999, -999, -999, -999, -999, -999},
  110083. {-999, -999, -999, -999, -999, -999, -999, -999,
  110084. -999, -999, -103, -97, -90, -85, -76, -60,
  110085. -56, -54, -60, -62, -61, -56, -63, -65,
  110086. -73, -74, -77, -75, -78, -81, -86, -87,
  110087. -88, -91, -94, -98, -103, -110, -999, -999,
  110088. -999, -999, -999, -999, -999, -999, -999, -999,
  110089. -999, -999, -999, -999, -999, -999, -999, -999},
  110090. {-999, -999, -999, -999, -999, -999, -999, -105,
  110091. -100, -97, -92, -86, -81, -79, -70, -57,
  110092. -51, -47, -51, -58, -60, -56, -53, -50,
  110093. -58, -52, -50, -50, -53, -55, -64, -69,
  110094. -71, -85, -82, -78, -81, -85, -95, -102,
  110095. -112, -999, -999, -999, -999, -999, -999, -999,
  110096. -999, -999, -999, -999, -999, -999, -999, -999},
  110097. {-999, -999, -999, -999, -999, -999, -999, -105,
  110098. -100, -97, -92, -85, -83, -79, -72, -49,
  110099. -40, -43, -43, -54, -56, -51, -50, -40,
  110100. -43, -38, -36, -35, -37, -38, -37, -44,
  110101. -54, -60, -57, -60, -70, -75, -84, -92,
  110102. -103, -112, -999, -999, -999, -999, -999, -999,
  110103. -999, -999, -999, -999, -999, -999, -999, -999}},
  110104. /* 2000 Hz */
  110105. {{-999, -999, -999, -999, -999, -999, -999, -999,
  110106. -999, -999, -999, -110, -102, -95, -89, -82,
  110107. -83, -84, -90, -92, -99, -107, -113, -999,
  110108. -999, -999, -999, -999, -999, -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, -999, -107, -101, -95, -89, -83, -72,
  110114. -74, -78, -85, -88, -88, -90, -92, -98,
  110115. -105, -111, -999, -999, -999, -999, -999, -999,
  110116. -999, -999, -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, -109, -103, -97, -93, -87, -81, -70,
  110121. -70, -67, -75, -73, -76, -79, -81, -83,
  110122. -88, -89, -97, -103, -110, -999, -999, -999,
  110123. -999, -999, -999, -999, -999, -999, -999, -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, -107, -100, -94, -88, -83, -75, -63,
  110128. -59, -59, -63, -66, -60, -62, -67, -67,
  110129. -77, -76, -81, -88, -86, -92, -96, -102,
  110130. -109, -116, -999, -999, -999, -999, -999, -999,
  110131. -999, -999, -999, -999, -999, -999, -999, -999,
  110132. -999, -999, -999, -999, -999, -999, -999, -999},
  110133. {-999, -999, -999, -999, -999, -999, -999, -999,
  110134. -999, -105, -98, -92, -86, -81, -73, -56,
  110135. -52, -47, -55, -60, -58, -52, -51, -45,
  110136. -49, -50, -53, -54, -61, -71, -70, -69,
  110137. -78, -79, -87, -90, -96, -104, -112, -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, -103, -96, -90, -86, -78, -70, -51,
  110142. -42, -47, -48, -55, -54, -54, -53, -42,
  110143. -35, -28, -33, -38, -37, -44, -47, -49,
  110144. -54, -63, -68, -78, -82, -89, -94, -99,
  110145. -104, -109, -114, -999, -999, -999, -999, -999,
  110146. -999, -999, -999, -999, -999, -999, -999, -999}},
  110147. /* 2828 Hz */
  110148. {{-999, -999, -999, -999, -999, -999, -999, -999,
  110149. -999, -999, -999, -999, -110, -100, -90, -79,
  110150. -85, -81, -82, -82, -89, -94, -99, -103,
  110151. -109, -115, -999, -999, -999, -999, -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, -999, -105, -97, -85, -72,
  110157. -74, -70, -70, -70, -76, -85, -91, -93,
  110158. -97, -103, -109, -115, -999, -999, -999, -999,
  110159. -999, -999, -999, -999, -999, -999, -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, -999, -112, -93, -81, -68,
  110164. -62, -60, -60, -57, -63, -70, -77, -82,
  110165. -90, -93, -98, -104, -109, -113, -999, -999,
  110166. -999, -999, -999, -999, -999, -999, -999, -999,
  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, -999, -113, -100, -93, -84, -63,
  110171. -58, -48, -53, -54, -52, -52, -57, -64,
  110172. -66, -76, -83, -81, -85, -85, -90, -95,
  110173. -98, -101, -103, -106, -108, -111, -999, -999,
  110174. -999, -999, -999, -999, -999, -999, -999, -999,
  110175. -999, -999, -999, -999, -999, -999, -999, -999},
  110176. {-999, -999, -999, -999, -999, -999, -999, -999,
  110177. -999, -999, -999, -105, -95, -86, -74, -53,
  110178. -50, -38, -43, -49, -43, -42, -39, -39,
  110179. -46, -52, -57, -56, -72, -69, -74, -81,
  110180. -87, -92, -94, -97, -99, -102, -105, -108,
  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, -108, -99, -90, -76, -66, -45,
  110185. -43, -41, -44, -47, -43, -47, -40, -30,
  110186. -31, -31, -39, -33, -40, -41, -43, -53,
  110187. -59, -70, -73, -77, -79, -82, -84, -87,
  110188. -999, -999, -999, -999, -999, -999, -999, -999,
  110189. -999, -999, -999, -999, -999, -999, -999, -999}},
  110190. /* 4000 Hz */
  110191. {{-999, -999, -999, -999, -999, -999, -999, -999,
  110192. -999, -999, -999, -999, -999, -110, -91, -76,
  110193. -75, -85, -93, -98, -104, -110, -999, -999,
  110194. -999, -999, -999, -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, -999, -110, -91, -70,
  110200. -70, -75, -86, -89, -94, -98, -101, -106,
  110201. -110, -999, -999, -999, -999, -999, -999, -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, -60,
  110207. -65, -64, -74, -83, -88, -91, -95, -99,
  110208. -103, -107, -110, -999, -999, -999, -999, -999,
  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, -999, -110, -95, -80, -58,
  110214. -55, -49, -66, -68, -71, -78, -78, -80,
  110215. -88, -85, -89, -97, -100, -105, -110, -999,
  110216. -999, -999, -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. {-999, -999, -999, -999, -999, -999, -999, -999,
  110220. -999, -999, -999, -999, -110, -95, -80, -53,
  110221. -52, -41, -59, -59, -49, -58, -56, -63,
  110222. -86, -79, -90, -93, -98, -103, -107, -112,
  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, -110, -97, -91, -73, -45,
  110228. -40, -33, -53, -61, -49, -54, -50, -50,
  110229. -60, -52, -67, -74, -81, -92, -96, -100,
  110230. -105, -110, -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. /* 5657 Hz */
  110234. {{-999, -999, -999, -999, -999, -999, -999, -999,
  110235. -999, -999, -999, -113, -106, -99, -92, -77,
  110236. -80, -88, -97, -106, -115, -999, -999, -999,
  110237. -999, -999, -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, -116, -109, -102, -95, -89, -74,
  110243. -72, -88, -87, -95, -102, -109, -116, -999,
  110244. -999, -999, -999, -999, -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, -116, -109, -102, -95, -89, -75,
  110250. -66, -74, -77, -78, -86, -87, -90, -96,
  110251. -105, -115, -999, -999, -999, -999, -999, -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, -999, -115, -108, -101, -94, -88, -66,
  110257. -56, -61, -70, -65, -78, -72, -83, -84,
  110258. -93, -98, -105, -110, -999, -999, -999, -999,
  110259. -999, -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. {-999, -999, -999, -999, -999, -999, -999, -999,
  110263. -999, -999, -110, -105, -95, -89, -82, -57,
  110264. -52, -52, -59, -56, -59, -58, -69, -67,
  110265. -88, -82, -82, -89, -94, -100, -108, -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, -110, -101, -96, -90, -83, -77, -54,
  110271. -43, -38, -50, -48, -52, -48, -42, -42,
  110272. -51, -52, -53, -59, -65, -71, -78, -85,
  110273. -95, -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. /* 8000 Hz */
  110277. {{-999, -999, -999, -999, -999, -999, -999, -999,
  110278. -999, -999, -999, -999, -120, -105, -86, -68,
  110279. -78, -79, -90, -100, -110, -999, -999, -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, -999, -120, -105, -86, -66,
  110286. -73, -77, -88, -96, -105, -115, -999, -999,
  110287. -999, -999, -999, -999, -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, -120, -105, -92, -80, -61,
  110293. -64, -68, -80, -87, -92, -100, -110, -999,
  110294. -999, -999, -999, -999, -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, -120, -104, -91, -79, -52,
  110300. -60, -54, -64, -69, -77, -80, -82, -84,
  110301. -85, -87, -88, -90, -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. {-999, -999, -999, -999, -999, -999, -999, -999,
  110306. -999, -999, -999, -118, -100, -87, -77, -49,
  110307. -50, -44, -58, -61, -61, -67, -65, -62,
  110308. -62, -62, -65, -68, -999, -999, -999, -999,
  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, -115, -98, -84, -62, -49,
  110314. -44, -38, -46, -49, -49, -46, -39, -37,
  110315. -39, -40, -42, -43, -999, -999, -999, -999,
  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. /* 11314 Hz */
  110320. {{-999, -999, -999, -999, -999, -999, -999, -999,
  110321. -999, -999, -999, -999, -999, -110, -88, -74,
  110322. -77, -82, -82, -85, -90, -94, -99, -104,
  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, -88, -66,
  110329. -70, -81, -80, -81, -84, -88, -91, -93,
  110330. -999, -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, -999, -110, -88, -61,
  110336. -63, -70, -71, -74, -77, -80, -83, -85,
  110337. -999, -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, -999, -110, -86, -62,
  110343. -63, -62, -62, -58, -52, -50, -50, -52,
  110344. -54, -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. {-999, -999, -999, -999, -999, -999, -999, -999,
  110349. -999, -999, -999, -999, -118, -108, -84, -53,
  110350. -50, -50, -50, -55, -47, -45, -40, -40,
  110351. -40, -999, -999, -999, -999, -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, -118, -100, -73, -43,
  110357. -37, -42, -43, -53, -38, -37, -35, -35,
  110358. -38, -999, -999, -999, -999, -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. /* 16000 Hz */
  110363. {{-999, -999, -999, -999, -999, -999, -999, -999,
  110364. -999, -999, -999, -110, -100, -91, -84, -74,
  110365. -80, -80, -80, -80, -80, -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, -91, -84, -74,
  110372. -68, -68, -68, -68, -68, -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, -78, -70,
  110379. -60, -45, -30, -21, -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, -87, -78, -67,
  110386. -48, -38, -29, -21, -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. {-999, -999, -999, -999, -999, -999, -999, -999,
  110392. -999, -999, -999, -110, -100, -86, -69, -56,
  110393. -45, -35, -33, -29, -999, -999, -999, -999,
  110394. -999, -999, -999, -999, -999, -999, -999, -999,
  110395. -999, -999, -999, -999, -999, -999, -999, -999,
  110396. -999, -999, -999, -999, -999, -999, -999, -999,
  110397. -999, -999, -999, -999, -999, -999, -999, -999},
  110398. {-999, -999, -999, -999, -999, -999, -999, -999,
  110399. -999, -999, -999, -110, -100, -83, -71, -48,
  110400. -27, -38, -37, -34, -999, -999, -999, -999,
  110401. -999, -999, -999, -999, -999, -999, -999, -999,
  110402. -999, -999, -999, -999, -999, -999, -999, -999,
  110403. -999, -999, -999, -999, -999, -999, -999, -999,
  110404. -999, -999, -999, -999, -999, -999, -999, -999}}
  110405. };
  110406. #endif
  110407. /********* End of inlined file: masking.h *********/
  110408. #define NEGINF -9999.f
  110409. static double stereo_threshholds[]={0.0, .5, 1.0, 1.5, 2.5, 4.5, 8.5, 16.5, 9e10};
  110410. static double stereo_threshholds_limited[]={0.0, .5, 1.0, 1.5, 2.0, 2.5, 4.5, 8.5, 9e10};
  110411. vorbis_look_psy_global *_vp_global_look(vorbis_info *vi){
  110412. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  110413. vorbis_info_psy_global *gi=&ci->psy_g_param;
  110414. vorbis_look_psy_global *look=(vorbis_look_psy_global*)_ogg_calloc(1,sizeof(*look));
  110415. look->channels=vi->channels;
  110416. look->ampmax=-9999.;
  110417. look->gi=gi;
  110418. return(look);
  110419. }
  110420. void _vp_global_free(vorbis_look_psy_global *look){
  110421. if(look){
  110422. memset(look,0,sizeof(*look));
  110423. _ogg_free(look);
  110424. }
  110425. }
  110426. void _vi_gpsy_free(vorbis_info_psy_global *i){
  110427. if(i){
  110428. memset(i,0,sizeof(*i));
  110429. _ogg_free(i);
  110430. }
  110431. }
  110432. void _vi_psy_free(vorbis_info_psy *i){
  110433. if(i){
  110434. memset(i,0,sizeof(*i));
  110435. _ogg_free(i);
  110436. }
  110437. }
  110438. static void min_curve(float *c,
  110439. float *c2){
  110440. int i;
  110441. for(i=0;i<EHMER_MAX;i++)if(c2[i]<c[i])c[i]=c2[i];
  110442. }
  110443. static void max_curve(float *c,
  110444. float *c2){
  110445. int i;
  110446. for(i=0;i<EHMER_MAX;i++)if(c2[i]>c[i])c[i]=c2[i];
  110447. }
  110448. static void attenuate_curve(float *c,float att){
  110449. int i;
  110450. for(i=0;i<EHMER_MAX;i++)
  110451. c[i]+=att;
  110452. }
  110453. static float ***setup_tone_curves(float curveatt_dB[P_BANDS],float binHz,int n,
  110454. float center_boost, float center_decay_rate){
  110455. int i,j,k,m;
  110456. float ath[EHMER_MAX];
  110457. float workc[P_BANDS][P_LEVELS][EHMER_MAX];
  110458. float athc[P_LEVELS][EHMER_MAX];
  110459. float *brute_buffer=(float*) alloca(n*sizeof(*brute_buffer));
  110460. float ***ret=(float***) _ogg_malloc(sizeof(*ret)*P_BANDS);
  110461. memset(workc,0,sizeof(workc));
  110462. for(i=0;i<P_BANDS;i++){
  110463. /* we add back in the ATH to avoid low level curves falling off to
  110464. -infinity and unnecessarily cutting off high level curves in the
  110465. curve limiting (last step). */
  110466. /* A half-band's settings must be valid over the whole band, and
  110467. it's better to mask too little than too much */
  110468. int ath_offset=i*4;
  110469. for(j=0;j<EHMER_MAX;j++){
  110470. float min=999.;
  110471. for(k=0;k<4;k++)
  110472. if(j+k+ath_offset<MAX_ATH){
  110473. if(min>ATH[j+k+ath_offset])min=ATH[j+k+ath_offset];
  110474. }else{
  110475. if(min>ATH[MAX_ATH-1])min=ATH[MAX_ATH-1];
  110476. }
  110477. ath[j]=min;
  110478. }
  110479. /* copy curves into working space, replicate the 50dB curve to 30
  110480. and 40, replicate the 100dB curve to 110 */
  110481. for(j=0;j<6;j++)
  110482. memcpy(workc[i][j+2],tonemasks[i][j],EHMER_MAX*sizeof(*tonemasks[i][j]));
  110483. memcpy(workc[i][0],tonemasks[i][0],EHMER_MAX*sizeof(*tonemasks[i][0]));
  110484. memcpy(workc[i][1],tonemasks[i][0],EHMER_MAX*sizeof(*tonemasks[i][0]));
  110485. /* apply centered curve boost/decay */
  110486. for(j=0;j<P_LEVELS;j++){
  110487. for(k=0;k<EHMER_MAX;k++){
  110488. float adj=center_boost+abs(EHMER_OFFSET-k)*center_decay_rate;
  110489. if(adj<0. && center_boost>0)adj=0.;
  110490. if(adj>0. && center_boost<0)adj=0.;
  110491. workc[i][j][k]+=adj;
  110492. }
  110493. }
  110494. /* normalize curves so the driving amplitude is 0dB */
  110495. /* make temp curves with the ATH overlayed */
  110496. for(j=0;j<P_LEVELS;j++){
  110497. attenuate_curve(workc[i][j],curveatt_dB[i]+100.-(j<2?2:j)*10.-P_LEVEL_0);
  110498. memcpy(athc[j],ath,EHMER_MAX*sizeof(**athc));
  110499. attenuate_curve(athc[j],+100.-j*10.f-P_LEVEL_0);
  110500. max_curve(athc[j],workc[i][j]);
  110501. }
  110502. /* Now limit the louder curves.
  110503. the idea is this: We don't know what the playback attenuation
  110504. will be; 0dB SL moves every time the user twiddles the volume
  110505. knob. So that means we have to use a single 'most pessimal' curve
  110506. for all masking amplitudes, right? Wrong. The *loudest* sound
  110507. can be in (we assume) a range of ...+100dB] SL. However, sounds
  110508. 20dB down will be in a range ...+80], 40dB down is from ...+60],
  110509. etc... */
  110510. for(j=1;j<P_LEVELS;j++){
  110511. min_curve(athc[j],athc[j-1]);
  110512. min_curve(workc[i][j],athc[j]);
  110513. }
  110514. }
  110515. for(i=0;i<P_BANDS;i++){
  110516. int hi_curve,lo_curve,bin;
  110517. ret[i]=(float**)_ogg_malloc(sizeof(**ret)*P_LEVELS);
  110518. /* low frequency curves are measured with greater resolution than
  110519. the MDCT/FFT will actually give us; we want the curve applied
  110520. to the tone data to be pessimistic and thus apply the minimum
  110521. masking possible for a given bin. That means that a single bin
  110522. could span more than one octave and that the curve will be a
  110523. composite of multiple octaves. It also may mean that a single
  110524. bin may span > an eighth of an octave and that the eighth
  110525. octave values may also be composited. */
  110526. /* which octave curves will we be compositing? */
  110527. bin=floor(fromOC(i*.5)/binHz);
  110528. lo_curve= ceil(toOC(bin*binHz+1)*2);
  110529. hi_curve= floor(toOC((bin+1)*binHz)*2);
  110530. if(lo_curve>i)lo_curve=i;
  110531. if(lo_curve<0)lo_curve=0;
  110532. if(hi_curve>=P_BANDS)hi_curve=P_BANDS-1;
  110533. for(m=0;m<P_LEVELS;m++){
  110534. ret[i][m]=(float*)_ogg_malloc(sizeof(***ret)*(EHMER_MAX+2));
  110535. for(j=0;j<n;j++)brute_buffer[j]=999.;
  110536. /* render the curve into bins, then pull values back into curve.
  110537. The point is that any inherent subsampling aliasing results in
  110538. a safe minimum */
  110539. for(k=lo_curve;k<=hi_curve;k++){
  110540. int l=0;
  110541. for(j=0;j<EHMER_MAX;j++){
  110542. int lo_bin= fromOC(j*.125+k*.5-2.0625)/binHz;
  110543. int hi_bin= fromOC(j*.125+k*.5-1.9375)/binHz+1;
  110544. if(lo_bin<0)lo_bin=0;
  110545. if(lo_bin>n)lo_bin=n;
  110546. if(lo_bin<l)l=lo_bin;
  110547. if(hi_bin<0)hi_bin=0;
  110548. if(hi_bin>n)hi_bin=n;
  110549. for(;l<hi_bin && l<n;l++)
  110550. if(brute_buffer[l]>workc[k][m][j])
  110551. brute_buffer[l]=workc[k][m][j];
  110552. }
  110553. for(;l<n;l++)
  110554. if(brute_buffer[l]>workc[k][m][EHMER_MAX-1])
  110555. brute_buffer[l]=workc[k][m][EHMER_MAX-1];
  110556. }
  110557. /* be equally paranoid about being valid up to next half ocatve */
  110558. if(i+1<P_BANDS){
  110559. int l=0;
  110560. k=i+1;
  110561. for(j=0;j<EHMER_MAX;j++){
  110562. int lo_bin= fromOC(j*.125+i*.5-2.0625)/binHz;
  110563. int hi_bin= fromOC(j*.125+i*.5-1.9375)/binHz+1;
  110564. if(lo_bin<0)lo_bin=0;
  110565. if(lo_bin>n)lo_bin=n;
  110566. if(lo_bin<l)l=lo_bin;
  110567. if(hi_bin<0)hi_bin=0;
  110568. if(hi_bin>n)hi_bin=n;
  110569. for(;l<hi_bin && l<n;l++)
  110570. if(brute_buffer[l]>workc[k][m][j])
  110571. brute_buffer[l]=workc[k][m][j];
  110572. }
  110573. for(;l<n;l++)
  110574. if(brute_buffer[l]>workc[k][m][EHMER_MAX-1])
  110575. brute_buffer[l]=workc[k][m][EHMER_MAX-1];
  110576. }
  110577. for(j=0;j<EHMER_MAX;j++){
  110578. int bin=fromOC(j*.125+i*.5-2.)/binHz;
  110579. if(bin<0){
  110580. ret[i][m][j+2]=-999.;
  110581. }else{
  110582. if(bin>=n){
  110583. ret[i][m][j+2]=-999.;
  110584. }else{
  110585. ret[i][m][j+2]=brute_buffer[bin];
  110586. }
  110587. }
  110588. }
  110589. /* add fenceposts */
  110590. for(j=0;j<EHMER_OFFSET;j++)
  110591. if(ret[i][m][j+2]>-200.f)break;
  110592. ret[i][m][0]=j;
  110593. for(j=EHMER_MAX-1;j>EHMER_OFFSET+1;j--)
  110594. if(ret[i][m][j+2]>-200.f)
  110595. break;
  110596. ret[i][m][1]=j;
  110597. }
  110598. }
  110599. return(ret);
  110600. }
  110601. void _vp_psy_init(vorbis_look_psy *p,vorbis_info_psy *vi,
  110602. vorbis_info_psy_global *gi,int n,long rate){
  110603. long i,j,lo=-99,hi=1;
  110604. long maxoc;
  110605. memset(p,0,sizeof(*p));
  110606. p->eighth_octave_lines=gi->eighth_octave_lines;
  110607. p->shiftoc=rint(log(gi->eighth_octave_lines*8.f)/log(2.f))-1;
  110608. p->firstoc=toOC(.25f*rate*.5/n)*(1<<(p->shiftoc+1))-gi->eighth_octave_lines;
  110609. maxoc=toOC((n+.25f)*rate*.5/n)*(1<<(p->shiftoc+1))+.5f;
  110610. p->total_octave_lines=maxoc-p->firstoc+1;
  110611. p->ath=(float*)_ogg_malloc(n*sizeof(*p->ath));
  110612. p->octave=(long*)_ogg_malloc(n*sizeof(*p->octave));
  110613. p->bark=(long*)_ogg_malloc(n*sizeof(*p->bark));
  110614. p->vi=vi;
  110615. p->n=n;
  110616. p->rate=rate;
  110617. /* AoTuV HF weighting */
  110618. p->m_val = 1.;
  110619. if(rate < 26000) p->m_val = 0;
  110620. else if(rate < 38000) p->m_val = .94; /* 32kHz */
  110621. else if(rate > 46000) p->m_val = 1.275; /* 48kHz */
  110622. /* set up the lookups for a given blocksize and sample rate */
  110623. for(i=0,j=0;i<MAX_ATH-1;i++){
  110624. int endpos=rint(fromOC((i+1)*.125-2.)*2*n/rate);
  110625. float base=ATH[i];
  110626. if(j<endpos){
  110627. float delta=(ATH[i+1]-base)/(endpos-j);
  110628. for(;j<endpos && j<n;j++){
  110629. p->ath[j]=base+100.;
  110630. base+=delta;
  110631. }
  110632. }
  110633. }
  110634. for(i=0;i<n;i++){
  110635. float bark=toBARK(rate/(2*n)*i);
  110636. for(;lo+vi->noisewindowlomin<i &&
  110637. toBARK(rate/(2*n)*lo)<(bark-vi->noisewindowlo);lo++);
  110638. for(;hi<=n && (hi<i+vi->noisewindowhimin ||
  110639. toBARK(rate/(2*n)*hi)<(bark+vi->noisewindowhi));hi++);
  110640. p->bark[i]=((lo-1)<<16)+(hi-1);
  110641. }
  110642. for(i=0;i<n;i++)
  110643. p->octave[i]=toOC((i+.25f)*.5*rate/n)*(1<<(p->shiftoc+1))+.5f;
  110644. p->tonecurves=setup_tone_curves(vi->toneatt,rate*.5/n,n,
  110645. vi->tone_centerboost,vi->tone_decay);
  110646. /* set up rolling noise median */
  110647. p->noiseoffset=(float**)_ogg_malloc(P_NOISECURVES*sizeof(*p->noiseoffset));
  110648. for(i=0;i<P_NOISECURVES;i++)
  110649. p->noiseoffset[i]=(float*)_ogg_malloc(n*sizeof(**p->noiseoffset));
  110650. for(i=0;i<n;i++){
  110651. float halfoc=toOC((i+.5)*rate/(2.*n))*2.;
  110652. int inthalfoc;
  110653. float del;
  110654. if(halfoc<0)halfoc=0;
  110655. if(halfoc>=P_BANDS-1)halfoc=P_BANDS-1;
  110656. inthalfoc=(int)halfoc;
  110657. del=halfoc-inthalfoc;
  110658. for(j=0;j<P_NOISECURVES;j++)
  110659. p->noiseoffset[j][i]=
  110660. p->vi->noiseoff[j][inthalfoc]*(1.-del) +
  110661. p->vi->noiseoff[j][inthalfoc+1]*del;
  110662. }
  110663. #if 0
  110664. {
  110665. static int ls=0;
  110666. _analysis_output_always("noiseoff0",ls,p->noiseoffset[0],n,1,0,0);
  110667. _analysis_output_always("noiseoff1",ls,p->noiseoffset[1],n,1,0,0);
  110668. _analysis_output_always("noiseoff2",ls++,p->noiseoffset[2],n,1,0,0);
  110669. }
  110670. #endif
  110671. }
  110672. void _vp_psy_clear(vorbis_look_psy *p){
  110673. int i,j;
  110674. if(p){
  110675. if(p->ath)_ogg_free(p->ath);
  110676. if(p->octave)_ogg_free(p->octave);
  110677. if(p->bark)_ogg_free(p->bark);
  110678. if(p->tonecurves){
  110679. for(i=0;i<P_BANDS;i++){
  110680. for(j=0;j<P_LEVELS;j++){
  110681. _ogg_free(p->tonecurves[i][j]);
  110682. }
  110683. _ogg_free(p->tonecurves[i]);
  110684. }
  110685. _ogg_free(p->tonecurves);
  110686. }
  110687. if(p->noiseoffset){
  110688. for(i=0;i<P_NOISECURVES;i++){
  110689. _ogg_free(p->noiseoffset[i]);
  110690. }
  110691. _ogg_free(p->noiseoffset);
  110692. }
  110693. memset(p,0,sizeof(*p));
  110694. }
  110695. }
  110696. /* octave/(8*eighth_octave_lines) x scale and dB y scale */
  110697. static void seed_curve(float *seed,
  110698. const float **curves,
  110699. float amp,
  110700. int oc, int n,
  110701. int linesper,float dBoffset){
  110702. int i,post1;
  110703. int seedptr;
  110704. const float *posts,*curve;
  110705. int choice=(int)((amp+dBoffset-P_LEVEL_0)*.1f);
  110706. choice=max(choice,0);
  110707. choice=min(choice,P_LEVELS-1);
  110708. posts=curves[choice];
  110709. curve=posts+2;
  110710. post1=(int)posts[1];
  110711. seedptr=oc+(posts[0]-EHMER_OFFSET)*linesper-(linesper>>1);
  110712. for(i=posts[0];i<post1;i++){
  110713. if(seedptr>0){
  110714. float lin=amp+curve[i];
  110715. if(seed[seedptr]<lin)seed[seedptr]=lin;
  110716. }
  110717. seedptr+=linesper;
  110718. if(seedptr>=n)break;
  110719. }
  110720. }
  110721. static void seed_loop(vorbis_look_psy *p,
  110722. const float ***curves,
  110723. const float *f,
  110724. const float *flr,
  110725. float *seed,
  110726. float specmax){
  110727. vorbis_info_psy *vi=p->vi;
  110728. long n=p->n,i;
  110729. float dBoffset=vi->max_curve_dB-specmax;
  110730. /* prime the working vector with peak values */
  110731. for(i=0;i<n;i++){
  110732. float max=f[i];
  110733. long oc=p->octave[i];
  110734. while(i+1<n && p->octave[i+1]==oc){
  110735. i++;
  110736. if(f[i]>max)max=f[i];
  110737. }
  110738. if(max+6.f>flr[i]){
  110739. oc=oc>>p->shiftoc;
  110740. if(oc>=P_BANDS)oc=P_BANDS-1;
  110741. if(oc<0)oc=0;
  110742. seed_curve(seed,
  110743. curves[oc],
  110744. max,
  110745. p->octave[i]-p->firstoc,
  110746. p->total_octave_lines,
  110747. p->eighth_octave_lines,
  110748. dBoffset);
  110749. }
  110750. }
  110751. }
  110752. static void seed_chase(float *seeds, int linesper, long n){
  110753. long *posstack=(long*)alloca(n*sizeof(*posstack));
  110754. float *ampstack=(float*)alloca(n*sizeof(*ampstack));
  110755. long stack=0;
  110756. long pos=0;
  110757. long i;
  110758. for(i=0;i<n;i++){
  110759. if(stack<2){
  110760. posstack[stack]=i;
  110761. ampstack[stack++]=seeds[i];
  110762. }else{
  110763. while(1){
  110764. if(seeds[i]<ampstack[stack-1]){
  110765. posstack[stack]=i;
  110766. ampstack[stack++]=seeds[i];
  110767. break;
  110768. }else{
  110769. if(i<posstack[stack-1]+linesper){
  110770. if(stack>1 && ampstack[stack-1]<=ampstack[stack-2] &&
  110771. i<posstack[stack-2]+linesper){
  110772. /* we completely overlap, making stack-1 irrelevant. pop it */
  110773. stack--;
  110774. continue;
  110775. }
  110776. }
  110777. posstack[stack]=i;
  110778. ampstack[stack++]=seeds[i];
  110779. break;
  110780. }
  110781. }
  110782. }
  110783. }
  110784. /* the stack now contains only the positions that are relevant. Scan
  110785. 'em straight through */
  110786. for(i=0;i<stack;i++){
  110787. long endpos;
  110788. if(i<stack-1 && ampstack[i+1]>ampstack[i]){
  110789. endpos=posstack[i+1];
  110790. }else{
  110791. endpos=posstack[i]+linesper+1; /* +1 is important, else bin 0 is
  110792. discarded in short frames */
  110793. }
  110794. if(endpos>n)endpos=n;
  110795. for(;pos<endpos;pos++)
  110796. seeds[pos]=ampstack[i];
  110797. }
  110798. /* there. Linear time. I now remember this was on a problem set I
  110799. had in Grad Skool... I didn't solve it at the time ;-) */
  110800. }
  110801. /* bleaugh, this is more complicated than it needs to be */
  110802. #include<stdio.h>
  110803. static void max_seeds(vorbis_look_psy *p,
  110804. float *seed,
  110805. float *flr){
  110806. long n=p->total_octave_lines;
  110807. int linesper=p->eighth_octave_lines;
  110808. long linpos=0;
  110809. long pos;
  110810. seed_chase(seed,linesper,n); /* for masking */
  110811. pos=p->octave[0]-p->firstoc-(linesper>>1);
  110812. while(linpos+1<p->n){
  110813. float minV=seed[pos];
  110814. long end=((p->octave[linpos]+p->octave[linpos+1])>>1)-p->firstoc;
  110815. if(minV>p->vi->tone_abs_limit)minV=p->vi->tone_abs_limit;
  110816. while(pos+1<=end){
  110817. pos++;
  110818. if((seed[pos]>NEGINF && seed[pos]<minV) || minV==NEGINF)
  110819. minV=seed[pos];
  110820. }
  110821. end=pos+p->firstoc;
  110822. for(;linpos<p->n && p->octave[linpos]<=end;linpos++)
  110823. if(flr[linpos]<minV)flr[linpos]=minV;
  110824. }
  110825. {
  110826. float minV=seed[p->total_octave_lines-1];
  110827. for(;linpos<p->n;linpos++)
  110828. if(flr[linpos]<minV)flr[linpos]=minV;
  110829. }
  110830. }
  110831. static void bark_noise_hybridmp(int n,const long *b,
  110832. const float *f,
  110833. float *noise,
  110834. const float offset,
  110835. const int fixed){
  110836. float *N=(float*) alloca(n*sizeof(*N));
  110837. float *X=(float*) alloca(n*sizeof(*N));
  110838. float *XX=(float*) alloca(n*sizeof(*N));
  110839. float *Y=(float*) alloca(n*sizeof(*N));
  110840. float *XY=(float*) alloca(n*sizeof(*N));
  110841. float tN, tX, tXX, tY, tXY;
  110842. int i;
  110843. int lo, hi;
  110844. float R, A, B, D;
  110845. float w, x, y;
  110846. tN = tX = tXX = tY = tXY = 0.f;
  110847. y = f[0] + offset;
  110848. if (y < 1.f) y = 1.f;
  110849. w = y * y * .5;
  110850. tN += w;
  110851. tX += w;
  110852. tY += w * y;
  110853. N[0] = tN;
  110854. X[0] = tX;
  110855. XX[0] = tXX;
  110856. Y[0] = tY;
  110857. XY[0] = tXY;
  110858. for (i = 1, x = 1.f; i < n; i++, x += 1.f) {
  110859. y = f[i] + offset;
  110860. if (y < 1.f) y = 1.f;
  110861. w = y * y;
  110862. tN += w;
  110863. tX += w * x;
  110864. tXX += w * x * x;
  110865. tY += w * y;
  110866. tXY += w * x * y;
  110867. N[i] = tN;
  110868. X[i] = tX;
  110869. XX[i] = tXX;
  110870. Y[i] = tY;
  110871. XY[i] = tXY;
  110872. }
  110873. for (i = 0, x = 0.f;; i++, x += 1.f) {
  110874. lo = b[i] >> 16;
  110875. if( lo>=0 ) break;
  110876. hi = b[i] & 0xffff;
  110877. tN = N[hi] + N[-lo];
  110878. tX = X[hi] - X[-lo];
  110879. tXX = XX[hi] + XX[-lo];
  110880. tY = Y[hi] + Y[-lo];
  110881. tXY = XY[hi] - XY[-lo];
  110882. A = tY * tXX - tX * tXY;
  110883. B = tN * tXY - tX * tY;
  110884. D = tN * tXX - tX * tX;
  110885. R = (A + x * B) / D;
  110886. if (R < 0.f)
  110887. R = 0.f;
  110888. noise[i] = R - offset;
  110889. }
  110890. for ( ;; i++, x += 1.f) {
  110891. lo = b[i] >> 16;
  110892. hi = b[i] & 0xffff;
  110893. if(hi>=n)break;
  110894. tN = N[hi] - N[lo];
  110895. tX = X[hi] - X[lo];
  110896. tXX = XX[hi] - XX[lo];
  110897. tY = Y[hi] - Y[lo];
  110898. tXY = XY[hi] - XY[lo];
  110899. A = tY * tXX - tX * tXY;
  110900. B = tN * tXY - tX * tY;
  110901. D = tN * tXX - tX * tX;
  110902. R = (A + x * B) / D;
  110903. if (R < 0.f) R = 0.f;
  110904. noise[i] = R - offset;
  110905. }
  110906. for ( ; i < n; i++, x += 1.f) {
  110907. R = (A + x * B) / D;
  110908. if (R < 0.f) R = 0.f;
  110909. noise[i] = R - offset;
  110910. }
  110911. if (fixed <= 0) return;
  110912. for (i = 0, x = 0.f;; i++, x += 1.f) {
  110913. hi = i + fixed / 2;
  110914. lo = hi - fixed;
  110915. if(lo>=0)break;
  110916. tN = N[hi] + N[-lo];
  110917. tX = X[hi] - X[-lo];
  110918. tXX = XX[hi] + XX[-lo];
  110919. tY = Y[hi] + Y[-lo];
  110920. tXY = XY[hi] - XY[-lo];
  110921. A = tY * tXX - tX * tXY;
  110922. B = tN * tXY - tX * tY;
  110923. D = tN * tXX - tX * tX;
  110924. R = (A + x * B) / D;
  110925. if (R - offset < noise[i]) noise[i] = R - offset;
  110926. }
  110927. for ( ;; i++, x += 1.f) {
  110928. hi = i + fixed / 2;
  110929. lo = hi - fixed;
  110930. if(hi>=n)break;
  110931. tN = N[hi] - N[lo];
  110932. tX = X[hi] - X[lo];
  110933. tXX = XX[hi] - XX[lo];
  110934. tY = Y[hi] - Y[lo];
  110935. tXY = XY[hi] - XY[lo];
  110936. A = tY * tXX - tX * tXY;
  110937. B = tN * tXY - tX * tY;
  110938. D = tN * tXX - tX * tX;
  110939. R = (A + x * B) / D;
  110940. if (R - offset < noise[i]) noise[i] = R - offset;
  110941. }
  110942. for ( ; i < n; i++, x += 1.f) {
  110943. R = (A + x * B) / D;
  110944. if (R - offset < noise[i]) noise[i] = R - offset;
  110945. }
  110946. }
  110947. static float FLOOR1_fromdB_INV_LOOKUP[256]={
  110948. 0.F, 8.81683e+06F, 8.27882e+06F, 7.77365e+06F,
  110949. 7.29930e+06F, 6.85389e+06F, 6.43567e+06F, 6.04296e+06F,
  110950. 5.67422e+06F, 5.32798e+06F, 5.00286e+06F, 4.69759e+06F,
  110951. 4.41094e+06F, 4.14178e+06F, 3.88905e+06F, 3.65174e+06F,
  110952. 3.42891e+06F, 3.21968e+06F, 3.02321e+06F, 2.83873e+06F,
  110953. 2.66551e+06F, 2.50286e+06F, 2.35014e+06F, 2.20673e+06F,
  110954. 2.07208e+06F, 1.94564e+06F, 1.82692e+06F, 1.71544e+06F,
  110955. 1.61076e+06F, 1.51247e+06F, 1.42018e+06F, 1.33352e+06F,
  110956. 1.25215e+06F, 1.17574e+06F, 1.10400e+06F, 1.03663e+06F,
  110957. 973377.F, 913981.F, 858210.F, 805842.F,
  110958. 756669.F, 710497.F, 667142.F, 626433.F,
  110959. 588208.F, 552316.F, 518613.F, 486967.F,
  110960. 457252.F, 429351.F, 403152.F, 378551.F,
  110961. 355452.F, 333762.F, 313396.F, 294273.F,
  110962. 276316.F, 259455.F, 243623.F, 228757.F,
  110963. 214798.F, 201691.F, 189384.F, 177828.F,
  110964. 166977.F, 156788.F, 147221.F, 138237.F,
  110965. 129802.F, 121881.F, 114444.F, 107461.F,
  110966. 100903.F, 94746.3F, 88964.9F, 83536.2F,
  110967. 78438.8F, 73652.5F, 69158.2F, 64938.1F,
  110968. 60975.6F, 57254.9F, 53761.2F, 50480.6F,
  110969. 47400.3F, 44507.9F, 41792.0F, 39241.9F,
  110970. 36847.3F, 34598.9F, 32487.7F, 30505.3F,
  110971. 28643.8F, 26896.0F, 25254.8F, 23713.7F,
  110972. 22266.7F, 20908.0F, 19632.2F, 18434.2F,
  110973. 17309.4F, 16253.1F, 15261.4F, 14330.1F,
  110974. 13455.7F, 12634.6F, 11863.7F, 11139.7F,
  110975. 10460.0F, 9821.72F, 9222.39F, 8659.64F,
  110976. 8131.23F, 7635.06F, 7169.17F, 6731.70F,
  110977. 6320.93F, 5935.23F, 5573.06F, 5232.99F,
  110978. 4913.67F, 4613.84F, 4332.30F, 4067.94F,
  110979. 3819.72F, 3586.64F, 3367.78F, 3162.28F,
  110980. 2969.31F, 2788.13F, 2617.99F, 2458.24F,
  110981. 2308.24F, 2167.39F, 2035.14F, 1910.95F,
  110982. 1794.35F, 1684.85F, 1582.04F, 1485.51F,
  110983. 1394.86F, 1309.75F, 1229.83F, 1154.78F,
  110984. 1084.32F, 1018.15F, 956.024F, 897.687F,
  110985. 842.910F, 791.475F, 743.179F, 697.830F,
  110986. 655.249F, 615.265F, 577.722F, 542.469F,
  110987. 509.367F, 478.286F, 449.101F, 421.696F,
  110988. 395.964F, 371.803F, 349.115F, 327.812F,
  110989. 307.809F, 289.026F, 271.390F, 254.830F,
  110990. 239.280F, 224.679F, 210.969F, 198.096F,
  110991. 186.008F, 174.658F, 164.000F, 153.993F,
  110992. 144.596F, 135.773F, 127.488F, 119.708F,
  110993. 112.404F, 105.545F, 99.1046F, 93.0572F,
  110994. 87.3788F, 82.0469F, 77.0404F, 72.3394F,
  110995. 67.9252F, 63.7804F, 59.8885F, 56.2341F,
  110996. 52.8027F, 49.5807F, 46.5553F, 43.7144F,
  110997. 41.0470F, 38.5423F, 36.1904F, 33.9821F,
  110998. 31.9085F, 29.9614F, 28.1332F, 26.4165F,
  110999. 24.8045F, 23.2910F, 21.8697F, 20.5352F,
  111000. 19.2822F, 18.1056F, 17.0008F, 15.9634F,
  111001. 14.9893F, 14.0746F, 13.2158F, 12.4094F,
  111002. 11.6522F, 10.9411F, 10.2735F, 9.64662F,
  111003. 9.05798F, 8.50526F, 7.98626F, 7.49894F,
  111004. 7.04135F, 6.61169F, 6.20824F, 5.82941F,
  111005. 5.47370F, 5.13970F, 4.82607F, 4.53158F,
  111006. 4.25507F, 3.99542F, 3.75162F, 3.52269F,
  111007. 3.30774F, 3.10590F, 2.91638F, 2.73842F,
  111008. 2.57132F, 2.41442F, 2.26709F, 2.12875F,
  111009. 1.99885F, 1.87688F, 1.76236F, 1.65482F,
  111010. 1.55384F, 1.45902F, 1.36999F, 1.28640F,
  111011. 1.20790F, 1.13419F, 1.06499F, 1.F
  111012. };
  111013. void _vp_remove_floor(vorbis_look_psy *p,
  111014. float *mdct,
  111015. int *codedflr,
  111016. float *residue,
  111017. int sliding_lowpass){
  111018. int i,n=p->n;
  111019. if(sliding_lowpass>n)sliding_lowpass=n;
  111020. for(i=0;i<sliding_lowpass;i++){
  111021. residue[i]=
  111022. mdct[i]*FLOOR1_fromdB_INV_LOOKUP[codedflr[i]];
  111023. }
  111024. for(;i<n;i++)
  111025. residue[i]=0.;
  111026. }
  111027. void _vp_noisemask(vorbis_look_psy *p,
  111028. float *logmdct,
  111029. float *logmask){
  111030. int i,n=p->n;
  111031. float *work=(float*) alloca(n*sizeof(*work));
  111032. bark_noise_hybridmp(n,p->bark,logmdct,logmask,
  111033. 140.,-1);
  111034. for(i=0;i<n;i++)work[i]=logmdct[i]-logmask[i];
  111035. bark_noise_hybridmp(n,p->bark,work,logmask,0.,
  111036. p->vi->noisewindowfixed);
  111037. for(i=0;i<n;i++)work[i]=logmdct[i]-work[i];
  111038. #if 0
  111039. {
  111040. static int seq=0;
  111041. float work2[n];
  111042. for(i=0;i<n;i++){
  111043. work2[i]=logmask[i]+work[i];
  111044. }
  111045. if(seq&1)
  111046. _analysis_output("median2R",seq/2,work,n,1,0,0);
  111047. else
  111048. _analysis_output("median2L",seq/2,work,n,1,0,0);
  111049. if(seq&1)
  111050. _analysis_output("envelope2R",seq/2,work2,n,1,0,0);
  111051. else
  111052. _analysis_output("envelope2L",seq/2,work2,n,1,0,0);
  111053. seq++;
  111054. }
  111055. #endif
  111056. for(i=0;i<n;i++){
  111057. int dB=logmask[i]+.5;
  111058. if(dB>=NOISE_COMPAND_LEVELS)dB=NOISE_COMPAND_LEVELS-1;
  111059. if(dB<0)dB=0;
  111060. logmask[i]= work[i]+p->vi->noisecompand[dB];
  111061. }
  111062. }
  111063. void _vp_tonemask(vorbis_look_psy *p,
  111064. float *logfft,
  111065. float *logmask,
  111066. float global_specmax,
  111067. float local_specmax){
  111068. int i,n=p->n;
  111069. float *seed=(float*) alloca(sizeof(*seed)*p->total_octave_lines);
  111070. float att=local_specmax+p->vi->ath_adjatt;
  111071. for(i=0;i<p->total_octave_lines;i++)seed[i]=NEGINF;
  111072. /* set the ATH (floating below localmax, not global max by a
  111073. specified att) */
  111074. if(att<p->vi->ath_maxatt)att=p->vi->ath_maxatt;
  111075. for(i=0;i<n;i++)
  111076. logmask[i]=p->ath[i]+att;
  111077. /* tone masking */
  111078. seed_loop(p,(const float ***)p->tonecurves,logfft,logmask,seed,global_specmax);
  111079. max_seeds(p,seed,logmask);
  111080. }
  111081. void _vp_offset_and_mix(vorbis_look_psy *p,
  111082. float *noise,
  111083. float *tone,
  111084. int offset_select,
  111085. float *logmask,
  111086. float *mdct,
  111087. float *logmdct){
  111088. int i,n=p->n;
  111089. float de, coeffi, cx;/* AoTuV */
  111090. float toneatt=p->vi->tone_masteratt[offset_select];
  111091. cx = p->m_val;
  111092. for(i=0;i<n;i++){
  111093. float val= noise[i]+p->noiseoffset[offset_select][i];
  111094. if(val>p->vi->noisemaxsupp)val=p->vi->noisemaxsupp;
  111095. logmask[i]=max(val,tone[i]+toneatt);
  111096. /* AoTuV */
  111097. /** @ M1 **
  111098. The following codes improve a noise problem.
  111099. A fundamental idea uses the value of masking and carries out
  111100. the relative compensation of the MDCT.
  111101. However, this code is not perfect and all noise problems cannot be solved.
  111102. by Aoyumi @ 2004/04/18
  111103. */
  111104. if(offset_select == 1) {
  111105. coeffi = -17.2; /* coeffi is a -17.2dB threshold */
  111106. val = val - logmdct[i]; /* val == mdct line value relative to floor in dB */
  111107. if(val > coeffi){
  111108. /* mdct value is > -17.2 dB below floor */
  111109. de = 1.0-((val-coeffi)*0.005*cx);
  111110. /* pro-rated attenuation:
  111111. -0.00 dB boost if mdct value is -17.2dB (relative to floor)
  111112. -0.77 dB boost if mdct value is 0dB (relative to floor)
  111113. -1.64 dB boost if mdct value is +17.2dB (relative to floor)
  111114. etc... */
  111115. if(de < 0) de = 0.0001;
  111116. }else
  111117. /* mdct value is <= -17.2 dB below floor */
  111118. de = 1.0-((val-coeffi)*0.0003*cx);
  111119. /* pro-rated attenuation:
  111120. +0.00 dB atten if mdct value is -17.2dB (relative to floor)
  111121. +0.45 dB atten if mdct value is -34.4dB (relative to floor)
  111122. etc... */
  111123. mdct[i] *= de;
  111124. }
  111125. }
  111126. }
  111127. float _vp_ampmax_decay(float amp,vorbis_dsp_state *vd){
  111128. vorbis_info *vi=vd->vi;
  111129. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111130. vorbis_info_psy_global *gi=&ci->psy_g_param;
  111131. int n=ci->blocksizes[vd->W]/2;
  111132. float secs=(float)n/vi->rate;
  111133. amp+=secs*gi->ampmax_att_per_sec;
  111134. if(amp<-9999)amp=-9999;
  111135. return(amp);
  111136. }
  111137. static void couple_lossless(float A, float B,
  111138. float *qA, float *qB){
  111139. int test1=fabs(*qA)>fabs(*qB);
  111140. test1-= fabs(*qA)<fabs(*qB);
  111141. if(!test1)test1=((fabs(A)>fabs(B))<<1)-1;
  111142. if(test1==1){
  111143. *qB=(*qA>0.f?*qA-*qB:*qB-*qA);
  111144. }else{
  111145. float temp=*qB;
  111146. *qB=(*qB>0.f?*qA-*qB:*qB-*qA);
  111147. *qA=temp;
  111148. }
  111149. if(*qB>fabs(*qA)*1.9999f){
  111150. *qB= -fabs(*qA)*2.f;
  111151. *qA= -*qA;
  111152. }
  111153. }
  111154. static float hypot_lookup[32]={
  111155. -0.009935, -0.011245, -0.012726, -0.014397,
  111156. -0.016282, -0.018407, -0.020800, -0.023494,
  111157. -0.026522, -0.029923, -0.033737, -0.038010,
  111158. -0.042787, -0.048121, -0.054064, -0.060671,
  111159. -0.068000, -0.076109, -0.085054, -0.094892,
  111160. -0.105675, -0.117451, -0.130260, -0.144134,
  111161. -0.159093, -0.175146, -0.192286, -0.210490,
  111162. -0.229718, -0.249913, -0.271001, -0.292893};
  111163. static void precomputed_couple_point(float premag,
  111164. int floorA,int floorB,
  111165. float *mag, float *ang){
  111166. int test=(floorA>floorB)-1;
  111167. int offset=31-abs(floorA-floorB);
  111168. float floormag=hypot_lookup[((offset<0)-1)&offset]+1.f;
  111169. floormag*=FLOOR1_fromdB_INV_LOOKUP[(floorB&test)|(floorA&(~test))];
  111170. *mag=premag*floormag;
  111171. *ang=0.f;
  111172. }
  111173. /* just like below, this is currently set up to only do
  111174. single-step-depth coupling. Otherwise, we'd have to do more
  111175. copying (which will be inevitable later) */
  111176. /* doing the real circular magnitude calculation is audibly superior
  111177. to (A+B)/sqrt(2) */
  111178. static float dipole_hypot(float a, float b){
  111179. if(a>0.){
  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. if(b<0.)return -sqrt(a*a+b*b);
  111185. if(-a>b)return -sqrt(a*a-b*b);
  111186. return sqrt(b*b-a*a);
  111187. }
  111188. static float round_hypot(float a, float b){
  111189. if(a>0.){
  111190. if(b>0.)return sqrt(a*a+b*b);
  111191. if(a>-b)return sqrt(a*a+b*b);
  111192. return -sqrt(b*b+a*a);
  111193. }
  111194. if(b<0.)return -sqrt(a*a+b*b);
  111195. if(-a>b)return -sqrt(a*a+b*b);
  111196. return sqrt(b*b+a*a);
  111197. }
  111198. /* revert to round hypot for now */
  111199. float **_vp_quantize_couple_memo(vorbis_block *vb,
  111200. vorbis_info_psy_global *g,
  111201. vorbis_look_psy *p,
  111202. vorbis_info_mapping0 *vi,
  111203. float **mdct){
  111204. int i,j,n=p->n;
  111205. float **ret=(float**) _vorbis_block_alloc(vb,vi->coupling_steps*sizeof(*ret));
  111206. int limit=g->coupling_pointlimit[p->vi->blockflag][PACKETBLOBS/2];
  111207. for(i=0;i<vi->coupling_steps;i++){
  111208. float *mdctM=mdct[vi->coupling_mag[i]];
  111209. float *mdctA=mdct[vi->coupling_ang[i]];
  111210. ret[i]=(float*) _vorbis_block_alloc(vb,n*sizeof(**ret));
  111211. for(j=0;j<limit;j++)
  111212. ret[i][j]=dipole_hypot(mdctM[j],mdctA[j]);
  111213. for(;j<n;j++)
  111214. ret[i][j]=round_hypot(mdctM[j],mdctA[j]);
  111215. }
  111216. return(ret);
  111217. }
  111218. /* this is for per-channel noise normalization */
  111219. static int apsort(const void *a, const void *b){
  111220. float f1=fabs(**(float**)a);
  111221. float f2=fabs(**(float**)b);
  111222. return (f1<f2)-(f1>f2);
  111223. }
  111224. int **_vp_quantize_couple_sort(vorbis_block *vb,
  111225. vorbis_look_psy *p,
  111226. vorbis_info_mapping0 *vi,
  111227. float **mags){
  111228. if(p->vi->normal_point_p){
  111229. int i,j,k,n=p->n;
  111230. int **ret=(int**) _vorbis_block_alloc(vb,vi->coupling_steps*sizeof(*ret));
  111231. int partition=p->vi->normal_partition;
  111232. float **work=(float**) alloca(sizeof(*work)*partition);
  111233. for(i=0;i<vi->coupling_steps;i++){
  111234. ret[i]=(int*) _vorbis_block_alloc(vb,n*sizeof(**ret));
  111235. for(j=0;j<n;j+=partition){
  111236. for(k=0;k<partition;k++)work[k]=mags[i]+k+j;
  111237. qsort(work,partition,sizeof(*work),apsort);
  111238. for(k=0;k<partition;k++)ret[i][k+j]=work[k]-mags[i];
  111239. }
  111240. }
  111241. return(ret);
  111242. }
  111243. return(NULL);
  111244. }
  111245. void _vp_noise_normalize_sort(vorbis_look_psy *p,
  111246. float *magnitudes,int *sortedindex){
  111247. int i,j,n=p->n;
  111248. vorbis_info_psy *vi=p->vi;
  111249. int partition=vi->normal_partition;
  111250. float **work=(float**) alloca(sizeof(*work)*partition);
  111251. int start=vi->normal_start;
  111252. for(j=start;j<n;j+=partition){
  111253. if(j+partition>n)partition=n-j;
  111254. for(i=0;i<partition;i++)work[i]=magnitudes+i+j;
  111255. qsort(work,partition,sizeof(*work),apsort);
  111256. for(i=0;i<partition;i++){
  111257. sortedindex[i+j-start]=work[i]-magnitudes;
  111258. }
  111259. }
  111260. }
  111261. void _vp_noise_normalize(vorbis_look_psy *p,
  111262. float *in,float *out,int *sortedindex){
  111263. int flag=0,i,j=0,n=p->n;
  111264. vorbis_info_psy *vi=p->vi;
  111265. int partition=vi->normal_partition;
  111266. int start=vi->normal_start;
  111267. if(start>n)start=n;
  111268. if(vi->normal_channel_p){
  111269. for(;j<start;j++)
  111270. out[j]=rint(in[j]);
  111271. for(;j+partition<=n;j+=partition){
  111272. float acc=0.;
  111273. int k;
  111274. for(i=j;i<j+partition;i++)
  111275. acc+=in[i]*in[i];
  111276. for(i=0;i<partition;i++){
  111277. k=sortedindex[i+j-start];
  111278. if(in[k]*in[k]>=.25f){
  111279. out[k]=rint(in[k]);
  111280. acc-=in[k]*in[k];
  111281. flag=1;
  111282. }else{
  111283. if(acc<vi->normal_thresh)break;
  111284. out[k]=unitnorm(in[k]);
  111285. acc-=1.;
  111286. }
  111287. }
  111288. for(;i<partition;i++){
  111289. k=sortedindex[i+j-start];
  111290. out[k]=0.;
  111291. }
  111292. }
  111293. }
  111294. for(;j<n;j++)
  111295. out[j]=rint(in[j]);
  111296. }
  111297. void _vp_couple(int blobno,
  111298. vorbis_info_psy_global *g,
  111299. vorbis_look_psy *p,
  111300. vorbis_info_mapping0 *vi,
  111301. float **res,
  111302. float **mag_memo,
  111303. int **mag_sort,
  111304. int **ifloor,
  111305. int *nonzero,
  111306. int sliding_lowpass){
  111307. int i,j,k,n=p->n;
  111308. /* perform any requested channel coupling */
  111309. /* point stereo can only be used in a first stage (in this encoder)
  111310. because of the dependency on floor lookups */
  111311. for(i=0;i<vi->coupling_steps;i++){
  111312. /* once we're doing multistage coupling in which a channel goes
  111313. through more than one coupling step, the floor vector
  111314. magnitudes will also have to be recalculated an propogated
  111315. along with PCM. Right now, we're not (that will wait until 5.1
  111316. most likely), so the code isn't here yet. The memory management
  111317. here is all assuming single depth couplings anyway. */
  111318. /* make sure coupling a zero and a nonzero channel results in two
  111319. nonzero channels. */
  111320. if(nonzero[vi->coupling_mag[i]] ||
  111321. nonzero[vi->coupling_ang[i]]){
  111322. float *rM=res[vi->coupling_mag[i]];
  111323. float *rA=res[vi->coupling_ang[i]];
  111324. float *qM=rM+n;
  111325. float *qA=rA+n;
  111326. int *floorM=ifloor[vi->coupling_mag[i]];
  111327. int *floorA=ifloor[vi->coupling_ang[i]];
  111328. float prepoint=stereo_threshholds[g->coupling_prepointamp[blobno]];
  111329. float postpoint=stereo_threshholds[g->coupling_postpointamp[blobno]];
  111330. int partition=(p->vi->normal_point_p?p->vi->normal_partition:p->n);
  111331. int limit=g->coupling_pointlimit[p->vi->blockflag][blobno];
  111332. int pointlimit=limit;
  111333. nonzero[vi->coupling_mag[i]]=1;
  111334. nonzero[vi->coupling_ang[i]]=1;
  111335. /* The threshold of a stereo is changed with the size of n */
  111336. if(n > 1000)
  111337. postpoint=stereo_threshholds_limited[g->coupling_postpointamp[blobno]];
  111338. for(j=0;j<p->n;j+=partition){
  111339. float acc=0.f;
  111340. for(k=0;k<partition;k++){
  111341. int l=k+j;
  111342. if(l<sliding_lowpass){
  111343. if((l>=limit && fabs(rM[l])<postpoint && fabs(rA[l])<postpoint) ||
  111344. (fabs(rM[l])<prepoint && fabs(rA[l])<prepoint)){
  111345. precomputed_couple_point(mag_memo[i][l],
  111346. floorM[l],floorA[l],
  111347. qM+l,qA+l);
  111348. if(rint(qM[l])==0.f)acc+=qM[l]*qM[l];
  111349. }else{
  111350. couple_lossless(rM[l],rA[l],qM+l,qA+l);
  111351. }
  111352. }else{
  111353. qM[l]=0.;
  111354. qA[l]=0.;
  111355. }
  111356. }
  111357. if(p->vi->normal_point_p){
  111358. for(k=0;k<partition && acc>=p->vi->normal_thresh;k++){
  111359. int l=mag_sort[i][j+k];
  111360. if(l<sliding_lowpass && l>=pointlimit && rint(qM[l])==0.f){
  111361. qM[l]=unitnorm(qM[l]);
  111362. acc-=1.f;
  111363. }
  111364. }
  111365. }
  111366. }
  111367. }
  111368. }
  111369. }
  111370. /* AoTuV */
  111371. /** @ M2 **
  111372. The boost problem by the combination of noise normalization and point stereo is eased.
  111373. However, this is a temporary patch.
  111374. by Aoyumi @ 2004/04/18
  111375. */
  111376. void hf_reduction(vorbis_info_psy_global *g,
  111377. vorbis_look_psy *p,
  111378. vorbis_info_mapping0 *vi,
  111379. float **mdct){
  111380. int i,j,n=p->n, de=0.3*p->m_val;
  111381. int limit=g->coupling_pointlimit[p->vi->blockflag][PACKETBLOBS/2];
  111382. for(i=0; i<vi->coupling_steps; i++){
  111383. /* for(j=start; j<limit; j++){} // ???*/
  111384. for(j=limit; j<n; j++)
  111385. mdct[i][j] *= (1.0 - de*((float)(j-limit) / (float)(n-limit)));
  111386. }
  111387. }
  111388. #endif
  111389. /********* End of inlined file: psy.c *********/
  111390. /********* Start of inlined file: registry.c *********/
  111391. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  111392. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  111393. // tasks..
  111394. #ifdef _MSC_VER
  111395. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  111396. #endif
  111397. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  111398. #if JUCE_USE_OGGVORBIS
  111399. /* seems like major overkill now; the backend numbers will grow into
  111400. the infrastructure soon enough */
  111401. extern vorbis_func_floor floor0_exportbundle;
  111402. extern vorbis_func_floor floor1_exportbundle;
  111403. extern vorbis_func_residue residue0_exportbundle;
  111404. extern vorbis_func_residue residue1_exportbundle;
  111405. extern vorbis_func_residue residue2_exportbundle;
  111406. extern vorbis_func_mapping mapping0_exportbundle;
  111407. vorbis_func_floor *_floor_P[]={
  111408. &floor0_exportbundle,
  111409. &floor1_exportbundle,
  111410. };
  111411. vorbis_func_residue *_residue_P[]={
  111412. &residue0_exportbundle,
  111413. &residue1_exportbundle,
  111414. &residue2_exportbundle,
  111415. };
  111416. vorbis_func_mapping *_mapping_P[]={
  111417. &mapping0_exportbundle,
  111418. };
  111419. #endif
  111420. /********* End of inlined file: registry.c *********/
  111421. /********* Start of inlined file: res0.c *********/
  111422. /* Slow, slow, slow, simpleminded and did I mention it was slow? The
  111423. encode/decode loops are coded for clarity and performance is not
  111424. yet even a nagging little idea lurking in the shadows. Oh and BTW,
  111425. it's slow. */
  111426. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  111427. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  111428. // tasks..
  111429. #ifdef _MSC_VER
  111430. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  111431. #endif
  111432. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  111433. #if JUCE_USE_OGGVORBIS
  111434. #include <stdlib.h>
  111435. #include <string.h>
  111436. #include <math.h>
  111437. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  111438. #include <stdio.h>
  111439. #endif
  111440. typedef struct {
  111441. vorbis_info_residue0 *info;
  111442. int parts;
  111443. int stages;
  111444. codebook *fullbooks;
  111445. codebook *phrasebook;
  111446. codebook ***partbooks;
  111447. int partvals;
  111448. int **decodemap;
  111449. long postbits;
  111450. long phrasebits;
  111451. long frames;
  111452. #if defined(TRAIN_RES) || defined(TRAIN_RESAUX)
  111453. int train_seq;
  111454. long *training_data[8][64];
  111455. float training_max[8][64];
  111456. float training_min[8][64];
  111457. float tmin;
  111458. float tmax;
  111459. #endif
  111460. } vorbis_look_residue0;
  111461. void res0_free_info(vorbis_info_residue *i){
  111462. vorbis_info_residue0 *info=(vorbis_info_residue0 *)i;
  111463. if(info){
  111464. memset(info,0,sizeof(*info));
  111465. _ogg_free(info);
  111466. }
  111467. }
  111468. void res0_free_look(vorbis_look_residue *i){
  111469. int j;
  111470. if(i){
  111471. vorbis_look_residue0 *look=(vorbis_look_residue0 *)i;
  111472. #ifdef TRAIN_RES
  111473. {
  111474. int j,k,l;
  111475. for(j=0;j<look->parts;j++){
  111476. /*fprintf(stderr,"partition %d: ",j);*/
  111477. for(k=0;k<8;k++)
  111478. if(look->training_data[k][j]){
  111479. char buffer[80];
  111480. FILE *of;
  111481. codebook *statebook=look->partbooks[j][k];
  111482. /* long and short into the same bucket by current convention */
  111483. sprintf(buffer,"res_part%d_pass%d.vqd",j,k);
  111484. of=fopen(buffer,"a");
  111485. for(l=0;l<statebook->entries;l++)
  111486. fprintf(of,"%d:%ld\n",l,look->training_data[k][j][l]);
  111487. fclose(of);
  111488. /*fprintf(stderr,"%d(%.2f|%.2f) ",k,
  111489. look->training_min[k][j],look->training_max[k][j]);*/
  111490. _ogg_free(look->training_data[k][j]);
  111491. look->training_data[k][j]=NULL;
  111492. }
  111493. /*fprintf(stderr,"\n");*/
  111494. }
  111495. }
  111496. fprintf(stderr,"min/max residue: %g::%g\n",look->tmin,look->tmax);
  111497. /*fprintf(stderr,"residue bit usage %f:%f (%f total)\n",
  111498. (float)look->phrasebits/look->frames,
  111499. (float)look->postbits/look->frames,
  111500. (float)(look->postbits+look->phrasebits)/look->frames);*/
  111501. #endif
  111502. /*vorbis_info_residue0 *info=look->info;
  111503. fprintf(stderr,
  111504. "%ld frames encoded in %ld phrasebits and %ld residue bits "
  111505. "(%g/frame) \n",look->frames,look->phrasebits,
  111506. look->resbitsflat,
  111507. (look->phrasebits+look->resbitsflat)/(float)look->frames);
  111508. for(j=0;j<look->parts;j++){
  111509. long acc=0;
  111510. fprintf(stderr,"\t[%d] == ",j);
  111511. for(k=0;k<look->stages;k++)
  111512. if((info->secondstages[j]>>k)&1){
  111513. fprintf(stderr,"%ld,",look->resbits[j][k]);
  111514. acc+=look->resbits[j][k];
  111515. }
  111516. fprintf(stderr,":: (%ld vals) %1.2fbits/sample\n",look->resvals[j],
  111517. acc?(float)acc/(look->resvals[j]*info->grouping):0);
  111518. }
  111519. fprintf(stderr,"\n");*/
  111520. for(j=0;j<look->parts;j++)
  111521. if(look->partbooks[j])_ogg_free(look->partbooks[j]);
  111522. _ogg_free(look->partbooks);
  111523. for(j=0;j<look->partvals;j++)
  111524. _ogg_free(look->decodemap[j]);
  111525. _ogg_free(look->decodemap);
  111526. memset(look,0,sizeof(*look));
  111527. _ogg_free(look);
  111528. }
  111529. }
  111530. static int icount(unsigned int v){
  111531. int ret=0;
  111532. while(v){
  111533. ret+=v&1;
  111534. v>>=1;
  111535. }
  111536. return(ret);
  111537. }
  111538. void res0_pack(vorbis_info_residue *vr,oggpack_buffer *opb){
  111539. vorbis_info_residue0 *info=(vorbis_info_residue0 *)vr;
  111540. int j,acc=0;
  111541. oggpack_write(opb,info->begin,24);
  111542. oggpack_write(opb,info->end,24);
  111543. oggpack_write(opb,info->grouping-1,24); /* residue vectors to group and
  111544. code with a partitioned book */
  111545. oggpack_write(opb,info->partitions-1,6); /* possible partition choices */
  111546. oggpack_write(opb,info->groupbook,8); /* group huffman book */
  111547. /* secondstages is a bitmask; as encoding progresses pass by pass, a
  111548. bitmask of one indicates this partition class has bits to write
  111549. this pass */
  111550. for(j=0;j<info->partitions;j++){
  111551. if(ilog(info->secondstages[j])>3){
  111552. /* yes, this is a minor hack due to not thinking ahead */
  111553. oggpack_write(opb,info->secondstages[j],3);
  111554. oggpack_write(opb,1,1);
  111555. oggpack_write(opb,info->secondstages[j]>>3,5);
  111556. }else
  111557. oggpack_write(opb,info->secondstages[j],4); /* trailing zero */
  111558. acc+=icount(info->secondstages[j]);
  111559. }
  111560. for(j=0;j<acc;j++)
  111561. oggpack_write(opb,info->booklist[j],8);
  111562. }
  111563. /* vorbis_info is for range checking */
  111564. vorbis_info_residue *res0_unpack(vorbis_info *vi,oggpack_buffer *opb){
  111565. int j,acc=0;
  111566. vorbis_info_residue0 *info=(vorbis_info_residue0*) _ogg_calloc(1,sizeof(*info));
  111567. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  111568. info->begin=oggpack_read(opb,24);
  111569. info->end=oggpack_read(opb,24);
  111570. info->grouping=oggpack_read(opb,24)+1;
  111571. info->partitions=oggpack_read(opb,6)+1;
  111572. info->groupbook=oggpack_read(opb,8);
  111573. for(j=0;j<info->partitions;j++){
  111574. int cascade=oggpack_read(opb,3);
  111575. if(oggpack_read(opb,1))
  111576. cascade|=(oggpack_read(opb,5)<<3);
  111577. info->secondstages[j]=cascade;
  111578. acc+=icount(cascade);
  111579. }
  111580. for(j=0;j<acc;j++)
  111581. info->booklist[j]=oggpack_read(opb,8);
  111582. if(info->groupbook>=ci->books)goto errout;
  111583. for(j=0;j<acc;j++)
  111584. if(info->booklist[j]>=ci->books)goto errout;
  111585. return(info);
  111586. errout:
  111587. res0_free_info(info);
  111588. return(NULL);
  111589. }
  111590. vorbis_look_residue *res0_look(vorbis_dsp_state *vd,
  111591. vorbis_info_residue *vr){
  111592. vorbis_info_residue0 *info=(vorbis_info_residue0 *)vr;
  111593. vorbis_look_residue0 *look=(vorbis_look_residue0 *)_ogg_calloc(1,sizeof(*look));
  111594. codec_setup_info *ci=(codec_setup_info*)vd->vi->codec_setup;
  111595. int j,k,acc=0;
  111596. int dim;
  111597. int maxstage=0;
  111598. look->info=info;
  111599. look->parts=info->partitions;
  111600. look->fullbooks=ci->fullbooks;
  111601. look->phrasebook=ci->fullbooks+info->groupbook;
  111602. dim=look->phrasebook->dim;
  111603. look->partbooks=(codebook***)_ogg_calloc(look->parts,sizeof(*look->partbooks));
  111604. for(j=0;j<look->parts;j++){
  111605. int stages=ilog(info->secondstages[j]);
  111606. if(stages){
  111607. if(stages>maxstage)maxstage=stages;
  111608. look->partbooks[j]=(codebook**) _ogg_calloc(stages,sizeof(*look->partbooks[j]));
  111609. for(k=0;k<stages;k++)
  111610. if(info->secondstages[j]&(1<<k)){
  111611. look->partbooks[j][k]=ci->fullbooks+info->booklist[acc++];
  111612. #ifdef TRAIN_RES
  111613. look->training_data[k][j]=_ogg_calloc(look->partbooks[j][k]->entries,
  111614. sizeof(***look->training_data));
  111615. #endif
  111616. }
  111617. }
  111618. }
  111619. look->partvals=rint(pow((float)look->parts,(float)dim));
  111620. look->stages=maxstage;
  111621. look->decodemap=(int**)_ogg_malloc(look->partvals*sizeof(*look->decodemap));
  111622. for(j=0;j<look->partvals;j++){
  111623. long val=j;
  111624. long mult=look->partvals/look->parts;
  111625. look->decodemap[j]=(int*)_ogg_malloc(dim*sizeof(*look->decodemap[j]));
  111626. for(k=0;k<dim;k++){
  111627. long deco=val/mult;
  111628. val-=deco*mult;
  111629. mult/=look->parts;
  111630. look->decodemap[j][k]=deco;
  111631. }
  111632. }
  111633. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  111634. {
  111635. static int train_seq=0;
  111636. look->train_seq=train_seq++;
  111637. }
  111638. #endif
  111639. return(look);
  111640. }
  111641. /* break an abstraction and copy some code for performance purposes */
  111642. static int local_book_besterror(codebook *book,float *a){
  111643. int dim=book->dim,i,k,o;
  111644. int best=0;
  111645. encode_aux_threshmatch *tt=book->c->thresh_tree;
  111646. /* find the quant val of each scalar */
  111647. for(k=0,o=dim;k<dim;++k){
  111648. float val=a[--o];
  111649. i=tt->threshvals>>1;
  111650. if(val<tt->quantthresh[i]){
  111651. if(val<tt->quantthresh[i-1]){
  111652. for(--i;i>0;--i)
  111653. if(val>=tt->quantthresh[i-1])
  111654. break;
  111655. }
  111656. }else{
  111657. for(++i;i<tt->threshvals-1;++i)
  111658. if(val<tt->quantthresh[i])break;
  111659. }
  111660. best=(best*tt->quantvals)+tt->quantmap[i];
  111661. }
  111662. /* regular lattices are easy :-) */
  111663. if(book->c->lengthlist[best]<=0){
  111664. const static_codebook *c=book->c;
  111665. int i,j;
  111666. float bestf=0.f;
  111667. float *e=book->valuelist;
  111668. best=-1;
  111669. for(i=0;i<book->entries;i++){
  111670. if(c->lengthlist[i]>0){
  111671. float thisx=0.f;
  111672. for(j=0;j<dim;j++){
  111673. float val=(e[j]-a[j]);
  111674. thisx+=val*val;
  111675. }
  111676. if(best==-1 || thisx<bestf){
  111677. bestf=thisx;
  111678. best=i;
  111679. }
  111680. }
  111681. e+=dim;
  111682. }
  111683. }
  111684. {
  111685. float *ptr=book->valuelist+best*dim;
  111686. for(i=0;i<dim;i++)
  111687. *a++ -= *ptr++;
  111688. }
  111689. return(best);
  111690. }
  111691. static int _encodepart(oggpack_buffer *opb,float *vec, int n,
  111692. codebook *book,long *acc){
  111693. int i,bits=0;
  111694. int dim=book->dim;
  111695. int step=n/dim;
  111696. for(i=0;i<step;i++){
  111697. int entry=local_book_besterror(book,vec+i*dim);
  111698. #ifdef TRAIN_RES
  111699. acc[entry]++;
  111700. #endif
  111701. bits+=vorbis_book_encode(book,entry,opb);
  111702. }
  111703. return(bits);
  111704. }
  111705. static long **_01class(vorbis_block *vb,vorbis_look_residue *vl,
  111706. float **in,int ch){
  111707. long i,j,k;
  111708. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  111709. vorbis_info_residue0 *info=look->info;
  111710. /* move all this setup out later */
  111711. int samples_per_partition=info->grouping;
  111712. int possible_partitions=info->partitions;
  111713. int n=info->end-info->begin;
  111714. int partvals=n/samples_per_partition;
  111715. long **partword=(long**)_vorbis_block_alloc(vb,ch*sizeof(*partword));
  111716. float scale=100./samples_per_partition;
  111717. /* we find the partition type for each partition of each
  111718. channel. We'll go back and do the interleaved encoding in a
  111719. bit. For now, clarity */
  111720. for(i=0;i<ch;i++){
  111721. partword[i]=(long*)_vorbis_block_alloc(vb,n/samples_per_partition*sizeof(*partword[i]));
  111722. memset(partword[i],0,n/samples_per_partition*sizeof(*partword[i]));
  111723. }
  111724. for(i=0;i<partvals;i++){
  111725. int offset=i*samples_per_partition+info->begin;
  111726. for(j=0;j<ch;j++){
  111727. float max=0.;
  111728. float ent=0.;
  111729. for(k=0;k<samples_per_partition;k++){
  111730. if(fabs(in[j][offset+k])>max)max=fabs(in[j][offset+k]);
  111731. ent+=fabs(rint(in[j][offset+k]));
  111732. }
  111733. ent*=scale;
  111734. for(k=0;k<possible_partitions-1;k++)
  111735. if(max<=info->classmetric1[k] &&
  111736. (info->classmetric2[k]<0 || (int)ent<info->classmetric2[k]))
  111737. break;
  111738. partword[j][i]=k;
  111739. }
  111740. }
  111741. #ifdef TRAIN_RESAUX
  111742. {
  111743. FILE *of;
  111744. char buffer[80];
  111745. for(i=0;i<ch;i++){
  111746. sprintf(buffer,"resaux_%d.vqd",look->train_seq);
  111747. of=fopen(buffer,"a");
  111748. for(j=0;j<partvals;j++)
  111749. fprintf(of,"%ld, ",partword[i][j]);
  111750. fprintf(of,"\n");
  111751. fclose(of);
  111752. }
  111753. }
  111754. #endif
  111755. look->frames++;
  111756. return(partword);
  111757. }
  111758. /* designed for stereo or other modes where the partition size is an
  111759. integer multiple of the number of channels encoded in the current
  111760. submap */
  111761. static long **_2class(vorbis_block *vb,vorbis_look_residue *vl,float **in,
  111762. int ch){
  111763. long i,j,k,l;
  111764. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  111765. vorbis_info_residue0 *info=look->info;
  111766. /* move all this setup out later */
  111767. int samples_per_partition=info->grouping;
  111768. int possible_partitions=info->partitions;
  111769. int n=info->end-info->begin;
  111770. int partvals=n/samples_per_partition;
  111771. long **partword=(long**)_vorbis_block_alloc(vb,sizeof(*partword));
  111772. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  111773. FILE *of;
  111774. char buffer[80];
  111775. #endif
  111776. partword[0]=(long*)_vorbis_block_alloc(vb,n*ch/samples_per_partition*sizeof(*partword[0]));
  111777. memset(partword[0],0,n*ch/samples_per_partition*sizeof(*partword[0]));
  111778. for(i=0,l=info->begin/ch;i<partvals;i++){
  111779. float magmax=0.f;
  111780. float angmax=0.f;
  111781. for(j=0;j<samples_per_partition;j+=ch){
  111782. if(fabs(in[0][l])>magmax)magmax=fabs(in[0][l]);
  111783. for(k=1;k<ch;k++)
  111784. if(fabs(in[k][l])>angmax)angmax=fabs(in[k][l]);
  111785. l++;
  111786. }
  111787. for(j=0;j<possible_partitions-1;j++)
  111788. if(magmax<=info->classmetric1[j] &&
  111789. angmax<=info->classmetric2[j])
  111790. break;
  111791. partword[0][i]=j;
  111792. }
  111793. #ifdef TRAIN_RESAUX
  111794. sprintf(buffer,"resaux_%d.vqd",look->train_seq);
  111795. of=fopen(buffer,"a");
  111796. for(i=0;i<partvals;i++)
  111797. fprintf(of,"%ld, ",partword[0][i]);
  111798. fprintf(of,"\n");
  111799. fclose(of);
  111800. #endif
  111801. look->frames++;
  111802. return(partword);
  111803. }
  111804. static int _01forward(oggpack_buffer *opb,
  111805. vorbis_block *vb,vorbis_look_residue *vl,
  111806. float **in,int ch,
  111807. long **partword,
  111808. int (*encode)(oggpack_buffer *,float *,int,
  111809. codebook *,long *)){
  111810. long i,j,k,s;
  111811. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  111812. vorbis_info_residue0 *info=look->info;
  111813. /* move all this setup out later */
  111814. int samples_per_partition=info->grouping;
  111815. int possible_partitions=info->partitions;
  111816. int partitions_per_word=look->phrasebook->dim;
  111817. int n=info->end-info->begin;
  111818. int partvals=n/samples_per_partition;
  111819. long resbits[128];
  111820. long resvals[128];
  111821. #ifdef TRAIN_RES
  111822. for(i=0;i<ch;i++)
  111823. for(j=info->begin;j<info->end;j++){
  111824. if(in[i][j]>look->tmax)look->tmax=in[i][j];
  111825. if(in[i][j]<look->tmin)look->tmin=in[i][j];
  111826. }
  111827. #endif
  111828. memset(resbits,0,sizeof(resbits));
  111829. memset(resvals,0,sizeof(resvals));
  111830. /* we code the partition words for each channel, then the residual
  111831. words for a partition per channel until we've written all the
  111832. residual words for that partition word. Then write the next
  111833. partition channel words... */
  111834. for(s=0;s<look->stages;s++){
  111835. for(i=0;i<partvals;){
  111836. /* first we encode a partition codeword for each channel */
  111837. if(s==0){
  111838. for(j=0;j<ch;j++){
  111839. long val=partword[j][i];
  111840. for(k=1;k<partitions_per_word;k++){
  111841. val*=possible_partitions;
  111842. if(i+k<partvals)
  111843. val+=partword[j][i+k];
  111844. }
  111845. /* training hack */
  111846. if(val<look->phrasebook->entries)
  111847. look->phrasebits+=vorbis_book_encode(look->phrasebook,val,opb);
  111848. #if 0 /*def TRAIN_RES*/
  111849. else
  111850. fprintf(stderr,"!");
  111851. #endif
  111852. }
  111853. }
  111854. /* now we encode interleaved residual values for the partitions */
  111855. for(k=0;k<partitions_per_word && i<partvals;k++,i++){
  111856. long offset=i*samples_per_partition+info->begin;
  111857. for(j=0;j<ch;j++){
  111858. if(s==0)resvals[partword[j][i]]+=samples_per_partition;
  111859. if(info->secondstages[partword[j][i]]&(1<<s)){
  111860. codebook *statebook=look->partbooks[partword[j][i]][s];
  111861. if(statebook){
  111862. int ret;
  111863. long *accumulator=NULL;
  111864. #ifdef TRAIN_RES
  111865. accumulator=look->training_data[s][partword[j][i]];
  111866. {
  111867. int l;
  111868. float *samples=in[j]+offset;
  111869. for(l=0;l<samples_per_partition;l++){
  111870. if(samples[l]<look->training_min[s][partword[j][i]])
  111871. look->training_min[s][partword[j][i]]=samples[l];
  111872. if(samples[l]>look->training_max[s][partword[j][i]])
  111873. look->training_max[s][partword[j][i]]=samples[l];
  111874. }
  111875. }
  111876. #endif
  111877. ret=encode(opb,in[j]+offset,samples_per_partition,
  111878. statebook,accumulator);
  111879. look->postbits+=ret;
  111880. resbits[partword[j][i]]+=ret;
  111881. }
  111882. }
  111883. }
  111884. }
  111885. }
  111886. }
  111887. /*{
  111888. long total=0;
  111889. long totalbits=0;
  111890. fprintf(stderr,"%d :: ",vb->mode);
  111891. for(k=0;k<possible_partitions;k++){
  111892. fprintf(stderr,"%ld/%1.2g, ",resvals[k],(float)resbits[k]/resvals[k]);
  111893. total+=resvals[k];
  111894. totalbits+=resbits[k];
  111895. }
  111896. fprintf(stderr,":: %ld:%1.2g\n",total,(double)totalbits/total);
  111897. }*/
  111898. return(0);
  111899. }
  111900. /* a truncated packet here just means 'stop working'; it's not an error */
  111901. static int _01inverse(vorbis_block *vb,vorbis_look_residue *vl,
  111902. float **in,int ch,
  111903. long (*decodepart)(codebook *, float *,
  111904. oggpack_buffer *,int)){
  111905. long i,j,k,l,s;
  111906. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  111907. vorbis_info_residue0 *info=look->info;
  111908. /* move all this setup out later */
  111909. int samples_per_partition=info->grouping;
  111910. int partitions_per_word=look->phrasebook->dim;
  111911. int n=info->end-info->begin;
  111912. int partvals=n/samples_per_partition;
  111913. int partwords=(partvals+partitions_per_word-1)/partitions_per_word;
  111914. int ***partword=(int***)alloca(ch*sizeof(*partword));
  111915. for(j=0;j<ch;j++)
  111916. partword[j]=(int**)_vorbis_block_alloc(vb,partwords*sizeof(*partword[j]));
  111917. for(s=0;s<look->stages;s++){
  111918. /* each loop decodes on partition codeword containing
  111919. partitions_pre_word partitions */
  111920. for(i=0,l=0;i<partvals;l++){
  111921. if(s==0){
  111922. /* fetch the partition word for each channel */
  111923. for(j=0;j<ch;j++){
  111924. int temp=vorbis_book_decode(look->phrasebook,&vb->opb);
  111925. if(temp==-1)goto eopbreak;
  111926. partword[j][l]=look->decodemap[temp];
  111927. if(partword[j][l]==NULL)goto errout;
  111928. }
  111929. }
  111930. /* now we decode residual values for the partitions */
  111931. for(k=0;k<partitions_per_word && i<partvals;k++,i++)
  111932. for(j=0;j<ch;j++){
  111933. long offset=info->begin+i*samples_per_partition;
  111934. if(info->secondstages[partword[j][l][k]]&(1<<s)){
  111935. codebook *stagebook=look->partbooks[partword[j][l][k]][s];
  111936. if(stagebook){
  111937. if(decodepart(stagebook,in[j]+offset,&vb->opb,
  111938. samples_per_partition)==-1)goto eopbreak;
  111939. }
  111940. }
  111941. }
  111942. }
  111943. }
  111944. errout:
  111945. eopbreak:
  111946. return(0);
  111947. }
  111948. #if 0
  111949. /* residue 0 and 1 are just slight variants of one another. 0 is
  111950. interleaved, 1 is not */
  111951. long **res0_class(vorbis_block *vb,vorbis_look_residue *vl,
  111952. float **in,int *nonzero,int ch){
  111953. /* we encode only the nonzero parts of a bundle */
  111954. int i,used=0;
  111955. for(i=0;i<ch;i++)
  111956. if(nonzero[i])
  111957. in[used++]=in[i];
  111958. if(used)
  111959. /*return(_01class(vb,vl,in,used,_interleaved_testhack));*/
  111960. return(_01class(vb,vl,in,used));
  111961. else
  111962. return(0);
  111963. }
  111964. int res0_forward(vorbis_block *vb,vorbis_look_residue *vl,
  111965. float **in,float **out,int *nonzero,int ch,
  111966. long **partword){
  111967. /* we encode only the nonzero parts of a bundle */
  111968. int i,j,used=0,n=vb->pcmend/2;
  111969. for(i=0;i<ch;i++)
  111970. if(nonzero[i]){
  111971. if(out)
  111972. for(j=0;j<n;j++)
  111973. out[i][j]+=in[i][j];
  111974. in[used++]=in[i];
  111975. }
  111976. if(used){
  111977. int ret=_01forward(vb,vl,in,used,partword,
  111978. _interleaved_encodepart);
  111979. if(out){
  111980. used=0;
  111981. for(i=0;i<ch;i++)
  111982. if(nonzero[i]){
  111983. for(j=0;j<n;j++)
  111984. out[i][j]-=in[used][j];
  111985. used++;
  111986. }
  111987. }
  111988. return(ret);
  111989. }else{
  111990. return(0);
  111991. }
  111992. }
  111993. #endif
  111994. int res0_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  111995. float **in,int *nonzero,int ch){
  111996. int i,used=0;
  111997. for(i=0;i<ch;i++)
  111998. if(nonzero[i])
  111999. in[used++]=in[i];
  112000. if(used)
  112001. return(_01inverse(vb,vl,in,used,vorbis_book_decodevs_add));
  112002. else
  112003. return(0);
  112004. }
  112005. int res1_forward(oggpack_buffer *opb,vorbis_block *vb,vorbis_look_residue *vl,
  112006. float **in,float **out,int *nonzero,int ch,
  112007. long **partword){
  112008. int i,j,used=0,n=vb->pcmend/2;
  112009. for(i=0;i<ch;i++)
  112010. if(nonzero[i]){
  112011. if(out)
  112012. for(j=0;j<n;j++)
  112013. out[i][j]+=in[i][j];
  112014. in[used++]=in[i];
  112015. }
  112016. if(used){
  112017. int ret=_01forward(opb,vb,vl,in,used,partword,_encodepart);
  112018. if(out){
  112019. used=0;
  112020. for(i=0;i<ch;i++)
  112021. if(nonzero[i]){
  112022. for(j=0;j<n;j++)
  112023. out[i][j]-=in[used][j];
  112024. used++;
  112025. }
  112026. }
  112027. return(ret);
  112028. }else{
  112029. return(0);
  112030. }
  112031. }
  112032. long **res1_class(vorbis_block *vb,vorbis_look_residue *vl,
  112033. float **in,int *nonzero,int ch){
  112034. int i,used=0;
  112035. for(i=0;i<ch;i++)
  112036. if(nonzero[i])
  112037. in[used++]=in[i];
  112038. if(used)
  112039. return(_01class(vb,vl,in,used));
  112040. else
  112041. return(0);
  112042. }
  112043. int res1_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  112044. float **in,int *nonzero,int ch){
  112045. int i,used=0;
  112046. for(i=0;i<ch;i++)
  112047. if(nonzero[i])
  112048. in[used++]=in[i];
  112049. if(used)
  112050. return(_01inverse(vb,vl,in,used,vorbis_book_decodev_add));
  112051. else
  112052. return(0);
  112053. }
  112054. long **res2_class(vorbis_block *vb,vorbis_look_residue *vl,
  112055. float **in,int *nonzero,int ch){
  112056. int i,used=0;
  112057. for(i=0;i<ch;i++)
  112058. if(nonzero[i])used++;
  112059. if(used)
  112060. return(_2class(vb,vl,in,ch));
  112061. else
  112062. return(0);
  112063. }
  112064. /* res2 is slightly more different; all the channels are interleaved
  112065. into a single vector and encoded. */
  112066. int res2_forward(oggpack_buffer *opb,
  112067. vorbis_block *vb,vorbis_look_residue *vl,
  112068. float **in,float **out,int *nonzero,int ch,
  112069. long **partword){
  112070. long i,j,k,n=vb->pcmend/2,used=0;
  112071. /* don't duplicate the code; use a working vector hack for now and
  112072. reshape ourselves into a single channel res1 */
  112073. /* ugly; reallocs for each coupling pass :-( */
  112074. float *work=(float*)_vorbis_block_alloc(vb,ch*n*sizeof(*work));
  112075. for(i=0;i<ch;i++){
  112076. float *pcm=in[i];
  112077. if(nonzero[i])used++;
  112078. for(j=0,k=i;j<n;j++,k+=ch)
  112079. work[k]=pcm[j];
  112080. }
  112081. if(used){
  112082. int ret=_01forward(opb,vb,vl,&work,1,partword,_encodepart);
  112083. /* update the sofar vector */
  112084. if(out){
  112085. for(i=0;i<ch;i++){
  112086. float *pcm=in[i];
  112087. float *sofar=out[i];
  112088. for(j=0,k=i;j<n;j++,k+=ch)
  112089. sofar[j]+=pcm[j]-work[k];
  112090. }
  112091. }
  112092. return(ret);
  112093. }else{
  112094. return(0);
  112095. }
  112096. }
  112097. /* duplicate code here as speed is somewhat more important */
  112098. int res2_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  112099. float **in,int *nonzero,int ch){
  112100. long i,k,l,s;
  112101. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  112102. vorbis_info_residue0 *info=look->info;
  112103. /* move all this setup out later */
  112104. int samples_per_partition=info->grouping;
  112105. int partitions_per_word=look->phrasebook->dim;
  112106. int n=info->end-info->begin;
  112107. int partvals=n/samples_per_partition;
  112108. int partwords=(partvals+partitions_per_word-1)/partitions_per_word;
  112109. int **partword=(int**)_vorbis_block_alloc(vb,partwords*sizeof(*partword));
  112110. for(i=0;i<ch;i++)if(nonzero[i])break;
  112111. if(i==ch)return(0); /* no nonzero vectors */
  112112. for(s=0;s<look->stages;s++){
  112113. for(i=0,l=0;i<partvals;l++){
  112114. if(s==0){
  112115. /* fetch the partition word */
  112116. int temp=vorbis_book_decode(look->phrasebook,&vb->opb);
  112117. if(temp==-1)goto eopbreak;
  112118. partword[l]=look->decodemap[temp];
  112119. if(partword[l]==NULL)goto errout;
  112120. }
  112121. /* now we decode residual values for the partitions */
  112122. for(k=0;k<partitions_per_word && i<partvals;k++,i++)
  112123. if(info->secondstages[partword[l][k]]&(1<<s)){
  112124. codebook *stagebook=look->partbooks[partword[l][k]][s];
  112125. if(stagebook){
  112126. if(vorbis_book_decodevv_add(stagebook,in,
  112127. i*samples_per_partition+info->begin,ch,
  112128. &vb->opb,samples_per_partition)==-1)
  112129. goto eopbreak;
  112130. }
  112131. }
  112132. }
  112133. }
  112134. errout:
  112135. eopbreak:
  112136. return(0);
  112137. }
  112138. vorbis_func_residue residue0_exportbundle={
  112139. NULL,
  112140. &res0_unpack,
  112141. &res0_look,
  112142. &res0_free_info,
  112143. &res0_free_look,
  112144. NULL,
  112145. NULL,
  112146. &res0_inverse
  112147. };
  112148. vorbis_func_residue residue1_exportbundle={
  112149. &res0_pack,
  112150. &res0_unpack,
  112151. &res0_look,
  112152. &res0_free_info,
  112153. &res0_free_look,
  112154. &res1_class,
  112155. &res1_forward,
  112156. &res1_inverse
  112157. };
  112158. vorbis_func_residue residue2_exportbundle={
  112159. &res0_pack,
  112160. &res0_unpack,
  112161. &res0_look,
  112162. &res0_free_info,
  112163. &res0_free_look,
  112164. &res2_class,
  112165. &res2_forward,
  112166. &res2_inverse
  112167. };
  112168. #endif
  112169. /********* End of inlined file: res0.c *********/
  112170. /********* Start of inlined file: sharedbook.c *********/
  112171. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  112172. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  112173. // tasks..
  112174. #ifdef _MSC_VER
  112175. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  112176. #endif
  112177. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  112178. #if JUCE_USE_OGGVORBIS
  112179. #include <stdlib.h>
  112180. #include <math.h>
  112181. #include <string.h>
  112182. /**** pack/unpack helpers ******************************************/
  112183. int _ilog(unsigned int v){
  112184. int ret=0;
  112185. while(v){
  112186. ret++;
  112187. v>>=1;
  112188. }
  112189. return(ret);
  112190. }
  112191. /* 32 bit float (not IEEE; nonnormalized mantissa +
  112192. biased exponent) : neeeeeee eeemmmmm mmmmmmmm mmmmmmmm
  112193. Why not IEEE? It's just not that important here. */
  112194. #define VQ_FEXP 10
  112195. #define VQ_FMAN 21
  112196. #define VQ_FEXP_BIAS 768 /* bias toward values smaller than 1. */
  112197. /* doesn't currently guard under/overflow */
  112198. long _float32_pack(float val){
  112199. int sign=0;
  112200. long exp;
  112201. long mant;
  112202. if(val<0){
  112203. sign=0x80000000;
  112204. val= -val;
  112205. }
  112206. exp= floor(log(val)/log(2.f));
  112207. mant=rint(ldexp(val,(VQ_FMAN-1)-exp));
  112208. exp=(exp+VQ_FEXP_BIAS)<<VQ_FMAN;
  112209. return(sign|exp|mant);
  112210. }
  112211. float _float32_unpack(long val){
  112212. double mant=val&0x1fffff;
  112213. int sign=val&0x80000000;
  112214. long exp =(val&0x7fe00000L)>>VQ_FMAN;
  112215. if(sign)mant= -mant;
  112216. return(ldexp(mant,exp-(VQ_FMAN-1)-VQ_FEXP_BIAS));
  112217. }
  112218. /* given a list of word lengths, generate a list of codewords. Works
  112219. for length ordered or unordered, always assigns the lowest valued
  112220. codewords first. Extended to handle unused entries (length 0) */
  112221. ogg_uint32_t *_make_words(long *l,long n,long sparsecount){
  112222. long i,j,count=0;
  112223. ogg_uint32_t marker[33];
  112224. ogg_uint32_t *r=(ogg_uint32_t*)_ogg_malloc((sparsecount?sparsecount:n)*sizeof(*r));
  112225. memset(marker,0,sizeof(marker));
  112226. for(i=0;i<n;i++){
  112227. long length=l[i];
  112228. if(length>0){
  112229. ogg_uint32_t entry=marker[length];
  112230. /* when we claim a node for an entry, we also claim the nodes
  112231. below it (pruning off the imagined tree that may have dangled
  112232. from it) as well as blocking the use of any nodes directly
  112233. above for leaves */
  112234. /* update ourself */
  112235. if(length<32 && (entry>>length)){
  112236. /* error condition; the lengths must specify an overpopulated tree */
  112237. _ogg_free(r);
  112238. return(NULL);
  112239. }
  112240. r[count++]=entry;
  112241. /* Look to see if the next shorter marker points to the node
  112242. above. if so, update it and repeat. */
  112243. {
  112244. for(j=length;j>0;j--){
  112245. if(marker[j]&1){
  112246. /* have to jump branches */
  112247. if(j==1)
  112248. marker[1]++;
  112249. else
  112250. marker[j]=marker[j-1]<<1;
  112251. break; /* invariant says next upper marker would already
  112252. have been moved if it was on the same path */
  112253. }
  112254. marker[j]++;
  112255. }
  112256. }
  112257. /* prune the tree; the implicit invariant says all the longer
  112258. markers were dangling from our just-taken node. Dangle them
  112259. from our *new* node. */
  112260. for(j=length+1;j<33;j++)
  112261. if((marker[j]>>1) == entry){
  112262. entry=marker[j];
  112263. marker[j]=marker[j-1]<<1;
  112264. }else
  112265. break;
  112266. }else
  112267. if(sparsecount==0)count++;
  112268. }
  112269. /* bitreverse the words because our bitwise packer/unpacker is LSb
  112270. endian */
  112271. for(i=0,count=0;i<n;i++){
  112272. ogg_uint32_t temp=0;
  112273. for(j=0;j<l[i];j++){
  112274. temp<<=1;
  112275. temp|=(r[count]>>j)&1;
  112276. }
  112277. if(sparsecount){
  112278. if(l[i])
  112279. r[count++]=temp;
  112280. }else
  112281. r[count++]=temp;
  112282. }
  112283. return(r);
  112284. }
  112285. /* there might be a straightforward one-line way to do the below
  112286. that's portable and totally safe against roundoff, but I haven't
  112287. thought of it. Therefore, we opt on the side of caution */
  112288. long _book_maptype1_quantvals(const static_codebook *b){
  112289. long vals=floor(pow((float)b->entries,1.f/b->dim));
  112290. /* the above *should* be reliable, but we'll not assume that FP is
  112291. ever reliable when bitstream sync is at stake; verify via integer
  112292. means that vals really is the greatest value of dim for which
  112293. vals^b->bim <= b->entries */
  112294. /* treat the above as an initial guess */
  112295. while(1){
  112296. long acc=1;
  112297. long acc1=1;
  112298. int i;
  112299. for(i=0;i<b->dim;i++){
  112300. acc*=vals;
  112301. acc1*=vals+1;
  112302. }
  112303. if(acc<=b->entries && acc1>b->entries){
  112304. return(vals);
  112305. }else{
  112306. if(acc>b->entries){
  112307. vals--;
  112308. }else{
  112309. vals++;
  112310. }
  112311. }
  112312. }
  112313. }
  112314. /* unpack the quantized list of values for encode/decode ***********/
  112315. /* we need to deal with two map types: in map type 1, the values are
  112316. generated algorithmically (each column of the vector counts through
  112317. the values in the quant vector). in map type 2, all the values came
  112318. in in an explicit list. Both value lists must be unpacked */
  112319. float *_book_unquantize(const static_codebook *b,int n,int *sparsemap){
  112320. long j,k,count=0;
  112321. if(b->maptype==1 || b->maptype==2){
  112322. int quantvals;
  112323. float mindel=_float32_unpack(b->q_min);
  112324. float delta=_float32_unpack(b->q_delta);
  112325. float *r=(float*)_ogg_calloc(n*b->dim,sizeof(*r));
  112326. /* maptype 1 and 2 both use a quantized value vector, but
  112327. different sizes */
  112328. switch(b->maptype){
  112329. case 1:
  112330. /* most of the time, entries%dimensions == 0, but we need to be
  112331. well defined. We define that the possible vales at each
  112332. scalar is values == entries/dim. If entries%dim != 0, we'll
  112333. have 'too few' values (values*dim<entries), which means that
  112334. we'll have 'left over' entries; left over entries use zeroed
  112335. values (and are wasted). So don't generate codebooks like
  112336. that */
  112337. quantvals=_book_maptype1_quantvals(b);
  112338. for(j=0;j<b->entries;j++){
  112339. if((sparsemap && b->lengthlist[j]) || !sparsemap){
  112340. float last=0.f;
  112341. int indexdiv=1;
  112342. for(k=0;k<b->dim;k++){
  112343. int index= (j/indexdiv)%quantvals;
  112344. float val=b->quantlist[index];
  112345. val=fabs(val)*delta+mindel+last;
  112346. if(b->q_sequencep)last=val;
  112347. if(sparsemap)
  112348. r[sparsemap[count]*b->dim+k]=val;
  112349. else
  112350. r[count*b->dim+k]=val;
  112351. indexdiv*=quantvals;
  112352. }
  112353. count++;
  112354. }
  112355. }
  112356. break;
  112357. case 2:
  112358. for(j=0;j<b->entries;j++){
  112359. if((sparsemap && b->lengthlist[j]) || !sparsemap){
  112360. float last=0.f;
  112361. for(k=0;k<b->dim;k++){
  112362. float val=b->quantlist[j*b->dim+k];
  112363. val=fabs(val)*delta+mindel+last;
  112364. if(b->q_sequencep)last=val;
  112365. if(sparsemap)
  112366. r[sparsemap[count]*b->dim+k]=val;
  112367. else
  112368. r[count*b->dim+k]=val;
  112369. }
  112370. count++;
  112371. }
  112372. }
  112373. break;
  112374. }
  112375. return(r);
  112376. }
  112377. return(NULL);
  112378. }
  112379. void vorbis_staticbook_clear(static_codebook *b){
  112380. if(b->allocedp){
  112381. if(b->quantlist)_ogg_free(b->quantlist);
  112382. if(b->lengthlist)_ogg_free(b->lengthlist);
  112383. if(b->nearest_tree){
  112384. _ogg_free(b->nearest_tree->ptr0);
  112385. _ogg_free(b->nearest_tree->ptr1);
  112386. _ogg_free(b->nearest_tree->p);
  112387. _ogg_free(b->nearest_tree->q);
  112388. memset(b->nearest_tree,0,sizeof(*b->nearest_tree));
  112389. _ogg_free(b->nearest_tree);
  112390. }
  112391. if(b->thresh_tree){
  112392. _ogg_free(b->thresh_tree->quantthresh);
  112393. _ogg_free(b->thresh_tree->quantmap);
  112394. memset(b->thresh_tree,0,sizeof(*b->thresh_tree));
  112395. _ogg_free(b->thresh_tree);
  112396. }
  112397. memset(b,0,sizeof(*b));
  112398. }
  112399. }
  112400. void vorbis_staticbook_destroy(static_codebook *b){
  112401. if(b->allocedp){
  112402. vorbis_staticbook_clear(b);
  112403. _ogg_free(b);
  112404. }
  112405. }
  112406. void vorbis_book_clear(codebook *b){
  112407. /* static book is not cleared; we're likely called on the lookup and
  112408. the static codebook belongs to the info struct */
  112409. if(b->valuelist)_ogg_free(b->valuelist);
  112410. if(b->codelist)_ogg_free(b->codelist);
  112411. if(b->dec_index)_ogg_free(b->dec_index);
  112412. if(b->dec_codelengths)_ogg_free(b->dec_codelengths);
  112413. if(b->dec_firsttable)_ogg_free(b->dec_firsttable);
  112414. memset(b,0,sizeof(*b));
  112415. }
  112416. int vorbis_book_init_encode(codebook *c,const static_codebook *s){
  112417. memset(c,0,sizeof(*c));
  112418. c->c=s;
  112419. c->entries=s->entries;
  112420. c->used_entries=s->entries;
  112421. c->dim=s->dim;
  112422. c->codelist=_make_words(s->lengthlist,s->entries,0);
  112423. c->valuelist=_book_unquantize(s,s->entries,NULL);
  112424. return(0);
  112425. }
  112426. static int sort32a(const void *a,const void *b){
  112427. return ( **(ogg_uint32_t **)a>**(ogg_uint32_t **)b)-
  112428. ( **(ogg_uint32_t **)a<**(ogg_uint32_t **)b);
  112429. }
  112430. /* decode codebook arrangement is more heavily optimized than encode */
  112431. int vorbis_book_init_decode(codebook *c,const static_codebook *s){
  112432. int i,j,n=0,tabn;
  112433. int *sortindex;
  112434. memset(c,0,sizeof(*c));
  112435. /* count actually used entries */
  112436. for(i=0;i<s->entries;i++)
  112437. if(s->lengthlist[i]>0)
  112438. n++;
  112439. c->entries=s->entries;
  112440. c->used_entries=n;
  112441. c->dim=s->dim;
  112442. /* two different remappings go on here.
  112443. First, we collapse the likely sparse codebook down only to
  112444. actually represented values/words. This collapsing needs to be
  112445. indexed as map-valueless books are used to encode original entry
  112446. positions as integers.
  112447. Second, we reorder all vectors, including the entry index above,
  112448. by sorted bitreversed codeword to allow treeless decode. */
  112449. {
  112450. /* perform sort */
  112451. ogg_uint32_t *codes=_make_words(s->lengthlist,s->entries,c->used_entries);
  112452. ogg_uint32_t **codep=(ogg_uint32_t**)alloca(sizeof(*codep)*n);
  112453. if(codes==NULL)goto err_out;
  112454. for(i=0;i<n;i++){
  112455. codes[i]=bitreverse(codes[i]);
  112456. codep[i]=codes+i;
  112457. }
  112458. qsort(codep,n,sizeof(*codep),sort32a);
  112459. sortindex=(int*)alloca(n*sizeof(*sortindex));
  112460. c->codelist=(ogg_uint32_t*)_ogg_malloc(n*sizeof(*c->codelist));
  112461. /* the index is a reverse index */
  112462. for(i=0;i<n;i++){
  112463. int position=codep[i]-codes;
  112464. sortindex[position]=i;
  112465. }
  112466. for(i=0;i<n;i++)
  112467. c->codelist[sortindex[i]]=codes[i];
  112468. _ogg_free(codes);
  112469. }
  112470. c->valuelist=_book_unquantize(s,n,sortindex);
  112471. c->dec_index=(int*)_ogg_malloc(n*sizeof(*c->dec_index));
  112472. for(n=0,i=0;i<s->entries;i++)
  112473. if(s->lengthlist[i]>0)
  112474. c->dec_index[sortindex[n++]]=i;
  112475. c->dec_codelengths=(char*)_ogg_malloc(n*sizeof(*c->dec_codelengths));
  112476. for(n=0,i=0;i<s->entries;i++)
  112477. if(s->lengthlist[i]>0)
  112478. c->dec_codelengths[sortindex[n++]]=s->lengthlist[i];
  112479. c->dec_firsttablen=_ilog(c->used_entries)-4; /* this is magic */
  112480. if(c->dec_firsttablen<5)c->dec_firsttablen=5;
  112481. if(c->dec_firsttablen>8)c->dec_firsttablen=8;
  112482. tabn=1<<c->dec_firsttablen;
  112483. c->dec_firsttable=(ogg_uint32_t*)_ogg_calloc(tabn,sizeof(*c->dec_firsttable));
  112484. c->dec_maxlength=0;
  112485. for(i=0;i<n;i++){
  112486. if(c->dec_maxlength<c->dec_codelengths[i])
  112487. c->dec_maxlength=c->dec_codelengths[i];
  112488. if(c->dec_codelengths[i]<=c->dec_firsttablen){
  112489. ogg_uint32_t orig=bitreverse(c->codelist[i]);
  112490. for(j=0;j<(1<<(c->dec_firsttablen-c->dec_codelengths[i]));j++)
  112491. c->dec_firsttable[orig|(j<<c->dec_codelengths[i])]=i+1;
  112492. }
  112493. }
  112494. /* now fill in 'unused' entries in the firsttable with hi/lo search
  112495. hints for the non-direct-hits */
  112496. {
  112497. ogg_uint32_t mask=0xfffffffeUL<<(31-c->dec_firsttablen);
  112498. long lo=0,hi=0;
  112499. for(i=0;i<tabn;i++){
  112500. ogg_uint32_t word=i<<(32-c->dec_firsttablen);
  112501. if(c->dec_firsttable[bitreverse(word)]==0){
  112502. while((lo+1)<n && c->codelist[lo+1]<=word)lo++;
  112503. while( hi<n && word>=(c->codelist[hi]&mask))hi++;
  112504. /* we only actually have 15 bits per hint to play with here.
  112505. In order to overflow gracefully (nothing breaks, efficiency
  112506. just drops), encode as the difference from the extremes. */
  112507. {
  112508. unsigned long loval=lo;
  112509. unsigned long hival=n-hi;
  112510. if(loval>0x7fff)loval=0x7fff;
  112511. if(hival>0x7fff)hival=0x7fff;
  112512. c->dec_firsttable[bitreverse(word)]=
  112513. 0x80000000UL | (loval<<15) | hival;
  112514. }
  112515. }
  112516. }
  112517. }
  112518. return(0);
  112519. err_out:
  112520. vorbis_book_clear(c);
  112521. return(-1);
  112522. }
  112523. static float _dist(int el,float *ref, float *b,int step){
  112524. int i;
  112525. float acc=0.f;
  112526. for(i=0;i<el;i++){
  112527. float val=(ref[i]-b[i*step]);
  112528. acc+=val*val;
  112529. }
  112530. return(acc);
  112531. }
  112532. int _best(codebook *book, float *a, int step){
  112533. encode_aux_threshmatch *tt=book->c->thresh_tree;
  112534. #if 0
  112535. encode_aux_nearestmatch *nt=book->c->nearest_tree;
  112536. encode_aux_pigeonhole *pt=book->c->pigeon_tree;
  112537. #endif
  112538. int dim=book->dim;
  112539. int k,o;
  112540. /*int savebest=-1;
  112541. float saverr;*/
  112542. /* do we have a threshhold encode hint? */
  112543. if(tt){
  112544. int index=0,i;
  112545. /* find the quant val of each scalar */
  112546. for(k=0,o=step*(dim-1);k<dim;k++,o-=step){
  112547. i=tt->threshvals>>1;
  112548. if(a[o]<tt->quantthresh[i]){
  112549. for(;i>0;i--)
  112550. if(a[o]>=tt->quantthresh[i-1])
  112551. break;
  112552. }else{
  112553. for(i++;i<tt->threshvals-1;i++)
  112554. if(a[o]<tt->quantthresh[i])break;
  112555. }
  112556. index=(index*tt->quantvals)+tt->quantmap[i];
  112557. }
  112558. /* regular lattices are easy :-) */
  112559. if(book->c->lengthlist[index]>0) /* is this unused? If so, we'll
  112560. use a decision tree after all
  112561. and fall through*/
  112562. return(index);
  112563. }
  112564. #if 0
  112565. /* do we have a pigeonhole encode hint? */
  112566. if(pt){
  112567. const static_codebook *c=book->c;
  112568. int i,besti=-1;
  112569. float best=0.f;
  112570. int entry=0;
  112571. /* dealing with sequentialness is a pain in the ass */
  112572. if(c->q_sequencep){
  112573. int pv;
  112574. long mul=1;
  112575. float qlast=0;
  112576. for(k=0,o=0;k<dim;k++,o+=step){
  112577. pv=(int)((a[o]-qlast-pt->min)/pt->del);
  112578. if(pv<0 || pv>=pt->mapentries)break;
  112579. entry+=pt->pigeonmap[pv]*mul;
  112580. mul*=pt->quantvals;
  112581. qlast+=pv*pt->del+pt->min;
  112582. }
  112583. }else{
  112584. for(k=0,o=step*(dim-1);k<dim;k++,o-=step){
  112585. int pv=(int)((a[o]-pt->min)/pt->del);
  112586. if(pv<0 || pv>=pt->mapentries)break;
  112587. entry=entry*pt->quantvals+pt->pigeonmap[pv];
  112588. }
  112589. }
  112590. /* must be within the pigeonholable range; if we quant outside (or
  112591. in an entry that we define no list for), brute force it */
  112592. if(k==dim && pt->fitlength[entry]){
  112593. /* search the abbreviated list */
  112594. long *list=pt->fitlist+pt->fitmap[entry];
  112595. for(i=0;i<pt->fitlength[entry];i++){
  112596. float this=_dist(dim,book->valuelist+list[i]*dim,a,step);
  112597. if(besti==-1 || this<best){
  112598. best=this;
  112599. besti=list[i];
  112600. }
  112601. }
  112602. return(besti);
  112603. }
  112604. }
  112605. if(nt){
  112606. /* optimized using the decision tree */
  112607. while(1){
  112608. float c=0.f;
  112609. float *p=book->valuelist+nt->p[ptr];
  112610. float *q=book->valuelist+nt->q[ptr];
  112611. for(k=0,o=0;k<dim;k++,o+=step)
  112612. c+=(p[k]-q[k])*(a[o]-(p[k]+q[k])*.5);
  112613. if(c>0.f) /* in A */
  112614. ptr= -nt->ptr0[ptr];
  112615. else /* in B */
  112616. ptr= -nt->ptr1[ptr];
  112617. if(ptr<=0)break;
  112618. }
  112619. return(-ptr);
  112620. }
  112621. #endif
  112622. /* brute force it! */
  112623. {
  112624. const static_codebook *c=book->c;
  112625. int i,besti=-1;
  112626. float best=0.f;
  112627. float *e=book->valuelist;
  112628. for(i=0;i<book->entries;i++){
  112629. if(c->lengthlist[i]>0){
  112630. float thisx=_dist(dim,e,a,step);
  112631. if(besti==-1 || thisx<best){
  112632. best=thisx;
  112633. besti=i;
  112634. }
  112635. }
  112636. e+=dim;
  112637. }
  112638. /*if(savebest!=-1 && savebest!=besti){
  112639. fprintf(stderr,"brute force/pigeonhole disagreement:\n"
  112640. "original:");
  112641. for(i=0;i<dim*step;i+=step)fprintf(stderr,"%g,",a[i]);
  112642. fprintf(stderr,"\n"
  112643. "pigeonhole (entry %d, err %g):",savebest,saverr);
  112644. for(i=0;i<dim;i++)fprintf(stderr,"%g,",
  112645. (book->valuelist+savebest*dim)[i]);
  112646. fprintf(stderr,"\n"
  112647. "bruteforce (entry %d, err %g):",besti,best);
  112648. for(i=0;i<dim;i++)fprintf(stderr,"%g,",
  112649. (book->valuelist+besti*dim)[i]);
  112650. fprintf(stderr,"\n");
  112651. }*/
  112652. return(besti);
  112653. }
  112654. }
  112655. long vorbis_book_codeword(codebook *book,int entry){
  112656. if(book->c) /* only use with encode; decode optimizations are
  112657. allowed to break this */
  112658. return book->codelist[entry];
  112659. return -1;
  112660. }
  112661. long vorbis_book_codelen(codebook *book,int entry){
  112662. if(book->c) /* only use with encode; decode optimizations are
  112663. allowed to break this */
  112664. return book->c->lengthlist[entry];
  112665. return -1;
  112666. }
  112667. #ifdef _V_SELFTEST
  112668. /* Unit tests of the dequantizer; this stuff will be OK
  112669. cross-platform, I simply want to be sure that special mapping cases
  112670. actually work properly; a bug could go unnoticed for a while */
  112671. #include <stdio.h>
  112672. /* cases:
  112673. no mapping
  112674. full, explicit mapping
  112675. algorithmic mapping
  112676. nonsequential
  112677. sequential
  112678. */
  112679. static long full_quantlist1[]={0,1,2,3, 4,5,6,7, 8,3,6,1};
  112680. static long partial_quantlist1[]={0,7,2};
  112681. /* no mapping */
  112682. static_codebook test1={
  112683. 4,16,
  112684. NULL,
  112685. 0,
  112686. 0,0,0,0,
  112687. NULL,
  112688. NULL,NULL
  112689. };
  112690. static float *test1_result=NULL;
  112691. /* linear, full mapping, nonsequential */
  112692. static_codebook test2={
  112693. 4,3,
  112694. NULL,
  112695. 2,
  112696. -533200896,1611661312,4,0,
  112697. full_quantlist1,
  112698. NULL,NULL
  112699. };
  112700. static float test2_result[]={-3,-2,-1,0, 1,2,3,4, 5,0,3,-2};
  112701. /* linear, full mapping, sequential */
  112702. static_codebook test3={
  112703. 4,3,
  112704. NULL,
  112705. 2,
  112706. -533200896,1611661312,4,1,
  112707. full_quantlist1,
  112708. NULL,NULL
  112709. };
  112710. static float test3_result[]={-3,-5,-6,-6, 1,3,6,10, 5,5,8,6};
  112711. /* linear, algorithmic mapping, nonsequential */
  112712. static_codebook test4={
  112713. 3,27,
  112714. NULL,
  112715. 1,
  112716. -533200896,1611661312,4,0,
  112717. partial_quantlist1,
  112718. NULL,NULL
  112719. };
  112720. static float test4_result[]={-3,-3,-3, 4,-3,-3, -1,-3,-3,
  112721. -3, 4,-3, 4, 4,-3, -1, 4,-3,
  112722. -3,-1,-3, 4,-1,-3, -1,-1,-3,
  112723. -3,-3, 4, 4,-3, 4, -1,-3, 4,
  112724. -3, 4, 4, 4, 4, 4, -1, 4, 4,
  112725. -3,-1, 4, 4,-1, 4, -1,-1, 4,
  112726. -3,-3,-1, 4,-3,-1, -1,-3,-1,
  112727. -3, 4,-1, 4, 4,-1, -1, 4,-1,
  112728. -3,-1,-1, 4,-1,-1, -1,-1,-1};
  112729. /* linear, algorithmic mapping, sequential */
  112730. static_codebook test5={
  112731. 3,27,
  112732. NULL,
  112733. 1,
  112734. -533200896,1611661312,4,1,
  112735. partial_quantlist1,
  112736. NULL,NULL
  112737. };
  112738. static float test5_result[]={-3,-6,-9, 4, 1,-2, -1,-4,-7,
  112739. -3, 1,-2, 4, 8, 5, -1, 3, 0,
  112740. -3,-4,-7, 4, 3, 0, -1,-2,-5,
  112741. -3,-6,-2, 4, 1, 5, -1,-4, 0,
  112742. -3, 1, 5, 4, 8,12, -1, 3, 7,
  112743. -3,-4, 0, 4, 3, 7, -1,-2, 2,
  112744. -3,-6,-7, 4, 1, 0, -1,-4,-5,
  112745. -3, 1, 0, 4, 8, 7, -1, 3, 2,
  112746. -3,-4,-5, 4, 3, 2, -1,-2,-3};
  112747. void run_test(static_codebook *b,float *comp){
  112748. float *out=_book_unquantize(b,b->entries,NULL);
  112749. int i;
  112750. if(comp){
  112751. if(!out){
  112752. fprintf(stderr,"_book_unquantize incorrectly returned NULL\n");
  112753. exit(1);
  112754. }
  112755. for(i=0;i<b->entries*b->dim;i++)
  112756. if(fabs(out[i]-comp[i])>.0001){
  112757. fprintf(stderr,"disagreement in unquantized and reference data:\n"
  112758. "position %d, %g != %g\n",i,out[i],comp[i]);
  112759. exit(1);
  112760. }
  112761. }else{
  112762. if(out){
  112763. fprintf(stderr,"_book_unquantize returned a value array: \n"
  112764. " correct result should have been NULL\n");
  112765. exit(1);
  112766. }
  112767. }
  112768. }
  112769. int main(){
  112770. /* run the nine dequant tests, and compare to the hand-rolled results */
  112771. fprintf(stderr,"Dequant test 1... ");
  112772. run_test(&test1,test1_result);
  112773. fprintf(stderr,"OK\nDequant test 2... ");
  112774. run_test(&test2,test2_result);
  112775. fprintf(stderr,"OK\nDequant test 3... ");
  112776. run_test(&test3,test3_result);
  112777. fprintf(stderr,"OK\nDequant test 4... ");
  112778. run_test(&test4,test4_result);
  112779. fprintf(stderr,"OK\nDequant test 5... ");
  112780. run_test(&test5,test5_result);
  112781. fprintf(stderr,"OK\n\n");
  112782. return(0);
  112783. }
  112784. #endif
  112785. #endif
  112786. /********* End of inlined file: sharedbook.c *********/
  112787. /********* Start of inlined file: smallft.c *********/
  112788. /* FFT implementation from OggSquish, minus cosine transforms,
  112789. * minus all but radix 2/4 case. In Vorbis we only need this
  112790. * cut-down version.
  112791. *
  112792. * To do more than just power-of-two sized vectors, see the full
  112793. * version I wrote for NetLib.
  112794. *
  112795. * Note that the packing is a little strange; rather than the FFT r/i
  112796. * packing following R_0, I_n, R_1, I_1, R_2, I_2 ... R_n-1, I_n-1,
  112797. * it follows R_0, R_1, I_1, R_2, I_2 ... R_n-1, I_n-1, I_n like the
  112798. * FORTRAN version
  112799. */
  112800. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  112801. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  112802. // tasks..
  112803. #ifdef _MSC_VER
  112804. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  112805. #endif
  112806. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  112807. #if JUCE_USE_OGGVORBIS
  112808. #include <stdlib.h>
  112809. #include <string.h>
  112810. #include <math.h>
  112811. static void drfti1(int n, float *wa, int *ifac){
  112812. static int ntryh[4] = { 4,2,3,5 };
  112813. static float tpi = 6.28318530717958648f;
  112814. float arg,argh,argld,fi;
  112815. int ntry=0,i,j=-1;
  112816. int k1, l1, l2, ib;
  112817. int ld, ii, ip, is, nq, nr;
  112818. int ido, ipm, nfm1;
  112819. int nl=n;
  112820. int nf=0;
  112821. L101:
  112822. j++;
  112823. if (j < 4)
  112824. ntry=ntryh[j];
  112825. else
  112826. ntry+=2;
  112827. L104:
  112828. nq=nl/ntry;
  112829. nr=nl-ntry*nq;
  112830. if (nr!=0) goto L101;
  112831. nf++;
  112832. ifac[nf+1]=ntry;
  112833. nl=nq;
  112834. if(ntry!=2)goto L107;
  112835. if(nf==1)goto L107;
  112836. for (i=1;i<nf;i++){
  112837. ib=nf-i+1;
  112838. ifac[ib+1]=ifac[ib];
  112839. }
  112840. ifac[2] = 2;
  112841. L107:
  112842. if(nl!=1)goto L104;
  112843. ifac[0]=n;
  112844. ifac[1]=nf;
  112845. argh=tpi/n;
  112846. is=0;
  112847. nfm1=nf-1;
  112848. l1=1;
  112849. if(nfm1==0)return;
  112850. for (k1=0;k1<nfm1;k1++){
  112851. ip=ifac[k1+2];
  112852. ld=0;
  112853. l2=l1*ip;
  112854. ido=n/l2;
  112855. ipm=ip-1;
  112856. for (j=0;j<ipm;j++){
  112857. ld+=l1;
  112858. i=is;
  112859. argld=(float)ld*argh;
  112860. fi=0.f;
  112861. for (ii=2;ii<ido;ii+=2){
  112862. fi+=1.f;
  112863. arg=fi*argld;
  112864. wa[i++]=cos(arg);
  112865. wa[i++]=sin(arg);
  112866. }
  112867. is+=ido;
  112868. }
  112869. l1=l2;
  112870. }
  112871. }
  112872. static void fdrffti(int n, float *wsave, int *ifac){
  112873. if (n == 1) return;
  112874. drfti1(n, wsave+n, ifac);
  112875. }
  112876. static void dradf2(int ido,int l1,float *cc,float *ch,float *wa1){
  112877. int i,k;
  112878. float ti2,tr2;
  112879. int t0,t1,t2,t3,t4,t5,t6;
  112880. t1=0;
  112881. t0=(t2=l1*ido);
  112882. t3=ido<<1;
  112883. for(k=0;k<l1;k++){
  112884. ch[t1<<1]=cc[t1]+cc[t2];
  112885. ch[(t1<<1)+t3-1]=cc[t1]-cc[t2];
  112886. t1+=ido;
  112887. t2+=ido;
  112888. }
  112889. if(ido<2)return;
  112890. if(ido==2)goto L105;
  112891. t1=0;
  112892. t2=t0;
  112893. for(k=0;k<l1;k++){
  112894. t3=t2;
  112895. t4=(t1<<1)+(ido<<1);
  112896. t5=t1;
  112897. t6=t1+t1;
  112898. for(i=2;i<ido;i+=2){
  112899. t3+=2;
  112900. t4-=2;
  112901. t5+=2;
  112902. t6+=2;
  112903. tr2=wa1[i-2]*cc[t3-1]+wa1[i-1]*cc[t3];
  112904. ti2=wa1[i-2]*cc[t3]-wa1[i-1]*cc[t3-1];
  112905. ch[t6]=cc[t5]+ti2;
  112906. ch[t4]=ti2-cc[t5];
  112907. ch[t6-1]=cc[t5-1]+tr2;
  112908. ch[t4-1]=cc[t5-1]-tr2;
  112909. }
  112910. t1+=ido;
  112911. t2+=ido;
  112912. }
  112913. if(ido%2==1)return;
  112914. L105:
  112915. t3=(t2=(t1=ido)-1);
  112916. t2+=t0;
  112917. for(k=0;k<l1;k++){
  112918. ch[t1]=-cc[t2];
  112919. ch[t1-1]=cc[t3];
  112920. t1+=ido<<1;
  112921. t2+=ido;
  112922. t3+=ido;
  112923. }
  112924. }
  112925. static void dradf4(int ido,int l1,float *cc,float *ch,float *wa1,
  112926. float *wa2,float *wa3){
  112927. static float hsqt2 = .70710678118654752f;
  112928. int i,k,t0,t1,t2,t3,t4,t5,t6;
  112929. float ci2,ci3,ci4,cr2,cr3,cr4,ti1,ti2,ti3,ti4,tr1,tr2,tr3,tr4;
  112930. t0=l1*ido;
  112931. t1=t0;
  112932. t4=t1<<1;
  112933. t2=t1+(t1<<1);
  112934. t3=0;
  112935. for(k=0;k<l1;k++){
  112936. tr1=cc[t1]+cc[t2];
  112937. tr2=cc[t3]+cc[t4];
  112938. ch[t5=t3<<2]=tr1+tr2;
  112939. ch[(ido<<2)+t5-1]=tr2-tr1;
  112940. ch[(t5+=(ido<<1))-1]=cc[t3]-cc[t4];
  112941. ch[t5]=cc[t2]-cc[t1];
  112942. t1+=ido;
  112943. t2+=ido;
  112944. t3+=ido;
  112945. t4+=ido;
  112946. }
  112947. if(ido<2)return;
  112948. if(ido==2)goto L105;
  112949. t1=0;
  112950. for(k=0;k<l1;k++){
  112951. t2=t1;
  112952. t4=t1<<2;
  112953. t5=(t6=ido<<1)+t4;
  112954. for(i=2;i<ido;i+=2){
  112955. t3=(t2+=2);
  112956. t4+=2;
  112957. t5-=2;
  112958. t3+=t0;
  112959. cr2=wa1[i-2]*cc[t3-1]+wa1[i-1]*cc[t3];
  112960. ci2=wa1[i-2]*cc[t3]-wa1[i-1]*cc[t3-1];
  112961. t3+=t0;
  112962. cr3=wa2[i-2]*cc[t3-1]+wa2[i-1]*cc[t3];
  112963. ci3=wa2[i-2]*cc[t3]-wa2[i-1]*cc[t3-1];
  112964. t3+=t0;
  112965. cr4=wa3[i-2]*cc[t3-1]+wa3[i-1]*cc[t3];
  112966. ci4=wa3[i-2]*cc[t3]-wa3[i-1]*cc[t3-1];
  112967. tr1=cr2+cr4;
  112968. tr4=cr4-cr2;
  112969. ti1=ci2+ci4;
  112970. ti4=ci2-ci4;
  112971. ti2=cc[t2]+ci3;
  112972. ti3=cc[t2]-ci3;
  112973. tr2=cc[t2-1]+cr3;
  112974. tr3=cc[t2-1]-cr3;
  112975. ch[t4-1]=tr1+tr2;
  112976. ch[t4]=ti1+ti2;
  112977. ch[t5-1]=tr3-ti4;
  112978. ch[t5]=tr4-ti3;
  112979. ch[t4+t6-1]=ti4+tr3;
  112980. ch[t4+t6]=tr4+ti3;
  112981. ch[t5+t6-1]=tr2-tr1;
  112982. ch[t5+t6]=ti1-ti2;
  112983. }
  112984. t1+=ido;
  112985. }
  112986. if(ido&1)return;
  112987. L105:
  112988. t2=(t1=t0+ido-1)+(t0<<1);
  112989. t3=ido<<2;
  112990. t4=ido;
  112991. t5=ido<<1;
  112992. t6=ido;
  112993. for(k=0;k<l1;k++){
  112994. ti1=-hsqt2*(cc[t1]+cc[t2]);
  112995. tr1=hsqt2*(cc[t1]-cc[t2]);
  112996. ch[t4-1]=tr1+cc[t6-1];
  112997. ch[t4+t5-1]=cc[t6-1]-tr1;
  112998. ch[t4]=ti1-cc[t1+t0];
  112999. ch[t4+t5]=ti1+cc[t1+t0];
  113000. t1+=ido;
  113001. t2+=ido;
  113002. t4+=t3;
  113003. t6+=ido;
  113004. }
  113005. }
  113006. static void dradfg(int ido,int ip,int l1,int idl1,float *cc,float *c1,
  113007. float *c2,float *ch,float *ch2,float *wa){
  113008. static float tpi=6.283185307179586f;
  113009. int idij,ipph,i,j,k,l,ic,ik,is;
  113010. int t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10;
  113011. float dc2,ai1,ai2,ar1,ar2,ds2;
  113012. int nbd;
  113013. float dcp,arg,dsp,ar1h,ar2h;
  113014. int idp2,ipp2;
  113015. arg=tpi/(float)ip;
  113016. dcp=cos(arg);
  113017. dsp=sin(arg);
  113018. ipph=(ip+1)>>1;
  113019. ipp2=ip;
  113020. idp2=ido;
  113021. nbd=(ido-1)>>1;
  113022. t0=l1*ido;
  113023. t10=ip*ido;
  113024. if(ido==1)goto L119;
  113025. for(ik=0;ik<idl1;ik++)ch2[ik]=c2[ik];
  113026. t1=0;
  113027. for(j=1;j<ip;j++){
  113028. t1+=t0;
  113029. t2=t1;
  113030. for(k=0;k<l1;k++){
  113031. ch[t2]=c1[t2];
  113032. t2+=ido;
  113033. }
  113034. }
  113035. is=-ido;
  113036. t1=0;
  113037. if(nbd>l1){
  113038. for(j=1;j<ip;j++){
  113039. t1+=t0;
  113040. is+=ido;
  113041. t2= -ido+t1;
  113042. for(k=0;k<l1;k++){
  113043. idij=is-1;
  113044. t2+=ido;
  113045. t3=t2;
  113046. for(i=2;i<ido;i+=2){
  113047. idij+=2;
  113048. t3+=2;
  113049. ch[t3-1]=wa[idij-1]*c1[t3-1]+wa[idij]*c1[t3];
  113050. ch[t3]=wa[idij-1]*c1[t3]-wa[idij]*c1[t3-1];
  113051. }
  113052. }
  113053. }
  113054. }else{
  113055. for(j=1;j<ip;j++){
  113056. is+=ido;
  113057. idij=is-1;
  113058. t1+=t0;
  113059. t2=t1;
  113060. for(i=2;i<ido;i+=2){
  113061. idij+=2;
  113062. t2+=2;
  113063. t3=t2;
  113064. for(k=0;k<l1;k++){
  113065. ch[t3-1]=wa[idij-1]*c1[t3-1]+wa[idij]*c1[t3];
  113066. ch[t3]=wa[idij-1]*c1[t3]-wa[idij]*c1[t3-1];
  113067. t3+=ido;
  113068. }
  113069. }
  113070. }
  113071. }
  113072. t1=0;
  113073. t2=ipp2*t0;
  113074. if(nbd<l1){
  113075. for(j=1;j<ipph;j++){
  113076. t1+=t0;
  113077. t2-=t0;
  113078. t3=t1;
  113079. t4=t2;
  113080. for(i=2;i<ido;i+=2){
  113081. t3+=2;
  113082. t4+=2;
  113083. t5=t3-ido;
  113084. t6=t4-ido;
  113085. for(k=0;k<l1;k++){
  113086. t5+=ido;
  113087. t6+=ido;
  113088. c1[t5-1]=ch[t5-1]+ch[t6-1];
  113089. c1[t6-1]=ch[t5]-ch[t6];
  113090. c1[t5]=ch[t5]+ch[t6];
  113091. c1[t6]=ch[t6-1]-ch[t5-1];
  113092. }
  113093. }
  113094. }
  113095. }else{
  113096. for(j=1;j<ipph;j++){
  113097. t1+=t0;
  113098. t2-=t0;
  113099. t3=t1;
  113100. t4=t2;
  113101. for(k=0;k<l1;k++){
  113102. t5=t3;
  113103. t6=t4;
  113104. for(i=2;i<ido;i+=2){
  113105. t5+=2;
  113106. t6+=2;
  113107. c1[t5-1]=ch[t5-1]+ch[t6-1];
  113108. c1[t6-1]=ch[t5]-ch[t6];
  113109. c1[t5]=ch[t5]+ch[t6];
  113110. c1[t6]=ch[t6-1]-ch[t5-1];
  113111. }
  113112. t3+=ido;
  113113. t4+=ido;
  113114. }
  113115. }
  113116. }
  113117. L119:
  113118. for(ik=0;ik<idl1;ik++)c2[ik]=ch2[ik];
  113119. t1=0;
  113120. t2=ipp2*idl1;
  113121. for(j=1;j<ipph;j++){
  113122. t1+=t0;
  113123. t2-=t0;
  113124. t3=t1-ido;
  113125. t4=t2-ido;
  113126. for(k=0;k<l1;k++){
  113127. t3+=ido;
  113128. t4+=ido;
  113129. c1[t3]=ch[t3]+ch[t4];
  113130. c1[t4]=ch[t4]-ch[t3];
  113131. }
  113132. }
  113133. ar1=1.f;
  113134. ai1=0.f;
  113135. t1=0;
  113136. t2=ipp2*idl1;
  113137. t3=(ip-1)*idl1;
  113138. for(l=1;l<ipph;l++){
  113139. t1+=idl1;
  113140. t2-=idl1;
  113141. ar1h=dcp*ar1-dsp*ai1;
  113142. ai1=dcp*ai1+dsp*ar1;
  113143. ar1=ar1h;
  113144. t4=t1;
  113145. t5=t2;
  113146. t6=t3;
  113147. t7=idl1;
  113148. for(ik=0;ik<idl1;ik++){
  113149. ch2[t4++]=c2[ik]+ar1*c2[t7++];
  113150. ch2[t5++]=ai1*c2[t6++];
  113151. }
  113152. dc2=ar1;
  113153. ds2=ai1;
  113154. ar2=ar1;
  113155. ai2=ai1;
  113156. t4=idl1;
  113157. t5=(ipp2-1)*idl1;
  113158. for(j=2;j<ipph;j++){
  113159. t4+=idl1;
  113160. t5-=idl1;
  113161. ar2h=dc2*ar2-ds2*ai2;
  113162. ai2=dc2*ai2+ds2*ar2;
  113163. ar2=ar2h;
  113164. t6=t1;
  113165. t7=t2;
  113166. t8=t4;
  113167. t9=t5;
  113168. for(ik=0;ik<idl1;ik++){
  113169. ch2[t6++]+=ar2*c2[t8++];
  113170. ch2[t7++]+=ai2*c2[t9++];
  113171. }
  113172. }
  113173. }
  113174. t1=0;
  113175. for(j=1;j<ipph;j++){
  113176. t1+=idl1;
  113177. t2=t1;
  113178. for(ik=0;ik<idl1;ik++)ch2[ik]+=c2[t2++];
  113179. }
  113180. if(ido<l1)goto L132;
  113181. t1=0;
  113182. t2=0;
  113183. for(k=0;k<l1;k++){
  113184. t3=t1;
  113185. t4=t2;
  113186. for(i=0;i<ido;i++)cc[t4++]=ch[t3++];
  113187. t1+=ido;
  113188. t2+=t10;
  113189. }
  113190. goto L135;
  113191. L132:
  113192. for(i=0;i<ido;i++){
  113193. t1=i;
  113194. t2=i;
  113195. for(k=0;k<l1;k++){
  113196. cc[t2]=ch[t1];
  113197. t1+=ido;
  113198. t2+=t10;
  113199. }
  113200. }
  113201. L135:
  113202. t1=0;
  113203. t2=ido<<1;
  113204. t3=0;
  113205. t4=ipp2*t0;
  113206. for(j=1;j<ipph;j++){
  113207. t1+=t2;
  113208. t3+=t0;
  113209. t4-=t0;
  113210. t5=t1;
  113211. t6=t3;
  113212. t7=t4;
  113213. for(k=0;k<l1;k++){
  113214. cc[t5-1]=ch[t6];
  113215. cc[t5]=ch[t7];
  113216. t5+=t10;
  113217. t6+=ido;
  113218. t7+=ido;
  113219. }
  113220. }
  113221. if(ido==1)return;
  113222. if(nbd<l1)goto L141;
  113223. t1=-ido;
  113224. t3=0;
  113225. t4=0;
  113226. t5=ipp2*t0;
  113227. for(j=1;j<ipph;j++){
  113228. t1+=t2;
  113229. t3+=t2;
  113230. t4+=t0;
  113231. t5-=t0;
  113232. t6=t1;
  113233. t7=t3;
  113234. t8=t4;
  113235. t9=t5;
  113236. for(k=0;k<l1;k++){
  113237. for(i=2;i<ido;i+=2){
  113238. ic=idp2-i;
  113239. cc[i+t7-1]=ch[i+t8-1]+ch[i+t9-1];
  113240. cc[ic+t6-1]=ch[i+t8-1]-ch[i+t9-1];
  113241. cc[i+t7]=ch[i+t8]+ch[i+t9];
  113242. cc[ic+t6]=ch[i+t9]-ch[i+t8];
  113243. }
  113244. t6+=t10;
  113245. t7+=t10;
  113246. t8+=ido;
  113247. t9+=ido;
  113248. }
  113249. }
  113250. return;
  113251. L141:
  113252. t1=-ido;
  113253. t3=0;
  113254. t4=0;
  113255. t5=ipp2*t0;
  113256. for(j=1;j<ipph;j++){
  113257. t1+=t2;
  113258. t3+=t2;
  113259. t4+=t0;
  113260. t5-=t0;
  113261. for(i=2;i<ido;i+=2){
  113262. t6=idp2+t1-i;
  113263. t7=i+t3;
  113264. t8=i+t4;
  113265. t9=i+t5;
  113266. for(k=0;k<l1;k++){
  113267. cc[t7-1]=ch[t8-1]+ch[t9-1];
  113268. cc[t6-1]=ch[t8-1]-ch[t9-1];
  113269. cc[t7]=ch[t8]+ch[t9];
  113270. cc[t6]=ch[t9]-ch[t8];
  113271. t6+=t10;
  113272. t7+=t10;
  113273. t8+=ido;
  113274. t9+=ido;
  113275. }
  113276. }
  113277. }
  113278. }
  113279. static void drftf1(int n,float *c,float *ch,float *wa,int *ifac){
  113280. int i,k1,l1,l2;
  113281. int na,kh,nf;
  113282. int ip,iw,ido,idl1,ix2,ix3;
  113283. nf=ifac[1];
  113284. na=1;
  113285. l2=n;
  113286. iw=n;
  113287. for(k1=0;k1<nf;k1++){
  113288. kh=nf-k1;
  113289. ip=ifac[kh+1];
  113290. l1=l2/ip;
  113291. ido=n/l2;
  113292. idl1=ido*l1;
  113293. iw-=(ip-1)*ido;
  113294. na=1-na;
  113295. if(ip!=4)goto L102;
  113296. ix2=iw+ido;
  113297. ix3=ix2+ido;
  113298. if(na!=0)
  113299. dradf4(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1);
  113300. else
  113301. dradf4(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1);
  113302. goto L110;
  113303. L102:
  113304. if(ip!=2)goto L104;
  113305. if(na!=0)goto L103;
  113306. dradf2(ido,l1,c,ch,wa+iw-1);
  113307. goto L110;
  113308. L103:
  113309. dradf2(ido,l1,ch,c,wa+iw-1);
  113310. goto L110;
  113311. L104:
  113312. if(ido==1)na=1-na;
  113313. if(na!=0)goto L109;
  113314. dradfg(ido,ip,l1,idl1,c,c,c,ch,ch,wa+iw-1);
  113315. na=1;
  113316. goto L110;
  113317. L109:
  113318. dradfg(ido,ip,l1,idl1,ch,ch,ch,c,c,wa+iw-1);
  113319. na=0;
  113320. L110:
  113321. l2=l1;
  113322. }
  113323. if(na==1)return;
  113324. for(i=0;i<n;i++)c[i]=ch[i];
  113325. }
  113326. static void dradb2(int ido,int l1,float *cc,float *ch,float *wa1){
  113327. int i,k,t0,t1,t2,t3,t4,t5,t6;
  113328. float ti2,tr2;
  113329. t0=l1*ido;
  113330. t1=0;
  113331. t2=0;
  113332. t3=(ido<<1)-1;
  113333. for(k=0;k<l1;k++){
  113334. ch[t1]=cc[t2]+cc[t3+t2];
  113335. ch[t1+t0]=cc[t2]-cc[t3+t2];
  113336. t2=(t1+=ido)<<1;
  113337. }
  113338. if(ido<2)return;
  113339. if(ido==2)goto L105;
  113340. t1=0;
  113341. t2=0;
  113342. for(k=0;k<l1;k++){
  113343. t3=t1;
  113344. t5=(t4=t2)+(ido<<1);
  113345. t6=t0+t1;
  113346. for(i=2;i<ido;i+=2){
  113347. t3+=2;
  113348. t4+=2;
  113349. t5-=2;
  113350. t6+=2;
  113351. ch[t3-1]=cc[t4-1]+cc[t5-1];
  113352. tr2=cc[t4-1]-cc[t5-1];
  113353. ch[t3]=cc[t4]-cc[t5];
  113354. ti2=cc[t4]+cc[t5];
  113355. ch[t6-1]=wa1[i-2]*tr2-wa1[i-1]*ti2;
  113356. ch[t6]=wa1[i-2]*ti2+wa1[i-1]*tr2;
  113357. }
  113358. t2=(t1+=ido)<<1;
  113359. }
  113360. if(ido%2==1)return;
  113361. L105:
  113362. t1=ido-1;
  113363. t2=ido-1;
  113364. for(k=0;k<l1;k++){
  113365. ch[t1]=cc[t2]+cc[t2];
  113366. ch[t1+t0]=-(cc[t2+1]+cc[t2+1]);
  113367. t1+=ido;
  113368. t2+=ido<<1;
  113369. }
  113370. }
  113371. static void dradb3(int ido,int l1,float *cc,float *ch,float *wa1,
  113372. float *wa2){
  113373. static float taur = -.5f;
  113374. static float taui = .8660254037844386f;
  113375. int i,k,t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10;
  113376. float ci2,ci3,di2,di3,cr2,cr3,dr2,dr3,ti2,tr2;
  113377. t0=l1*ido;
  113378. t1=0;
  113379. t2=t0<<1;
  113380. t3=ido<<1;
  113381. t4=ido+(ido<<1);
  113382. t5=0;
  113383. for(k=0;k<l1;k++){
  113384. tr2=cc[t3-1]+cc[t3-1];
  113385. cr2=cc[t5]+(taur*tr2);
  113386. ch[t1]=cc[t5]+tr2;
  113387. ci3=taui*(cc[t3]+cc[t3]);
  113388. ch[t1+t0]=cr2-ci3;
  113389. ch[t1+t2]=cr2+ci3;
  113390. t1+=ido;
  113391. t3+=t4;
  113392. t5+=t4;
  113393. }
  113394. if(ido==1)return;
  113395. t1=0;
  113396. t3=ido<<1;
  113397. for(k=0;k<l1;k++){
  113398. t7=t1+(t1<<1);
  113399. t6=(t5=t7+t3);
  113400. t8=t1;
  113401. t10=(t9=t1+t0)+t0;
  113402. for(i=2;i<ido;i+=2){
  113403. t5+=2;
  113404. t6-=2;
  113405. t7+=2;
  113406. t8+=2;
  113407. t9+=2;
  113408. t10+=2;
  113409. tr2=cc[t5-1]+cc[t6-1];
  113410. cr2=cc[t7-1]+(taur*tr2);
  113411. ch[t8-1]=cc[t7-1]+tr2;
  113412. ti2=cc[t5]-cc[t6];
  113413. ci2=cc[t7]+(taur*ti2);
  113414. ch[t8]=cc[t7]+ti2;
  113415. cr3=taui*(cc[t5-1]-cc[t6-1]);
  113416. ci3=taui*(cc[t5]+cc[t6]);
  113417. dr2=cr2-ci3;
  113418. dr3=cr2+ci3;
  113419. di2=ci2+cr3;
  113420. di3=ci2-cr3;
  113421. ch[t9-1]=wa1[i-2]*dr2-wa1[i-1]*di2;
  113422. ch[t9]=wa1[i-2]*di2+wa1[i-1]*dr2;
  113423. ch[t10-1]=wa2[i-2]*dr3-wa2[i-1]*di3;
  113424. ch[t10]=wa2[i-2]*di3+wa2[i-1]*dr3;
  113425. }
  113426. t1+=ido;
  113427. }
  113428. }
  113429. static void dradb4(int ido,int l1,float *cc,float *ch,float *wa1,
  113430. float *wa2,float *wa3){
  113431. static float sqrt2=1.414213562373095f;
  113432. int i,k,t0,t1,t2,t3,t4,t5,t6,t7,t8;
  113433. float ci2,ci3,ci4,cr2,cr3,cr4,ti1,ti2,ti3,ti4,tr1,tr2,tr3,tr4;
  113434. t0=l1*ido;
  113435. t1=0;
  113436. t2=ido<<2;
  113437. t3=0;
  113438. t6=ido<<1;
  113439. for(k=0;k<l1;k++){
  113440. t4=t3+t6;
  113441. t5=t1;
  113442. tr3=cc[t4-1]+cc[t4-1];
  113443. tr4=cc[t4]+cc[t4];
  113444. tr1=cc[t3]-cc[(t4+=t6)-1];
  113445. tr2=cc[t3]+cc[t4-1];
  113446. ch[t5]=tr2+tr3;
  113447. ch[t5+=t0]=tr1-tr4;
  113448. ch[t5+=t0]=tr2-tr3;
  113449. ch[t5+=t0]=tr1+tr4;
  113450. t1+=ido;
  113451. t3+=t2;
  113452. }
  113453. if(ido<2)return;
  113454. if(ido==2)goto L105;
  113455. t1=0;
  113456. for(k=0;k<l1;k++){
  113457. t5=(t4=(t3=(t2=t1<<2)+t6))+t6;
  113458. t7=t1;
  113459. for(i=2;i<ido;i+=2){
  113460. t2+=2;
  113461. t3+=2;
  113462. t4-=2;
  113463. t5-=2;
  113464. t7+=2;
  113465. ti1=cc[t2]+cc[t5];
  113466. ti2=cc[t2]-cc[t5];
  113467. ti3=cc[t3]-cc[t4];
  113468. tr4=cc[t3]+cc[t4];
  113469. tr1=cc[t2-1]-cc[t5-1];
  113470. tr2=cc[t2-1]+cc[t5-1];
  113471. ti4=cc[t3-1]-cc[t4-1];
  113472. tr3=cc[t3-1]+cc[t4-1];
  113473. ch[t7-1]=tr2+tr3;
  113474. cr3=tr2-tr3;
  113475. ch[t7]=ti2+ti3;
  113476. ci3=ti2-ti3;
  113477. cr2=tr1-tr4;
  113478. cr4=tr1+tr4;
  113479. ci2=ti1+ti4;
  113480. ci4=ti1-ti4;
  113481. ch[(t8=t7+t0)-1]=wa1[i-2]*cr2-wa1[i-1]*ci2;
  113482. ch[t8]=wa1[i-2]*ci2+wa1[i-1]*cr2;
  113483. ch[(t8+=t0)-1]=wa2[i-2]*cr3-wa2[i-1]*ci3;
  113484. ch[t8]=wa2[i-2]*ci3+wa2[i-1]*cr3;
  113485. ch[(t8+=t0)-1]=wa3[i-2]*cr4-wa3[i-1]*ci4;
  113486. ch[t8]=wa3[i-2]*ci4+wa3[i-1]*cr4;
  113487. }
  113488. t1+=ido;
  113489. }
  113490. if(ido%2 == 1)return;
  113491. L105:
  113492. t1=ido;
  113493. t2=ido<<2;
  113494. t3=ido-1;
  113495. t4=ido+(ido<<1);
  113496. for(k=0;k<l1;k++){
  113497. t5=t3;
  113498. ti1=cc[t1]+cc[t4];
  113499. ti2=cc[t4]-cc[t1];
  113500. tr1=cc[t1-1]-cc[t4-1];
  113501. tr2=cc[t1-1]+cc[t4-1];
  113502. ch[t5]=tr2+tr2;
  113503. ch[t5+=t0]=sqrt2*(tr1-ti1);
  113504. ch[t5+=t0]=ti2+ti2;
  113505. ch[t5+=t0]=-sqrt2*(tr1+ti1);
  113506. t3+=ido;
  113507. t1+=t2;
  113508. t4+=t2;
  113509. }
  113510. }
  113511. static void dradbg(int ido,int ip,int l1,int idl1,float *cc,float *c1,
  113512. float *c2,float *ch,float *ch2,float *wa){
  113513. static float tpi=6.283185307179586f;
  113514. int idij,ipph,i,j,k,l,ik,is,t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10,
  113515. t11,t12;
  113516. float dc2,ai1,ai2,ar1,ar2,ds2;
  113517. int nbd;
  113518. float dcp,arg,dsp,ar1h,ar2h;
  113519. int ipp2;
  113520. t10=ip*ido;
  113521. t0=l1*ido;
  113522. arg=tpi/(float)ip;
  113523. dcp=cos(arg);
  113524. dsp=sin(arg);
  113525. nbd=(ido-1)>>1;
  113526. ipp2=ip;
  113527. ipph=(ip+1)>>1;
  113528. if(ido<l1)goto L103;
  113529. t1=0;
  113530. t2=0;
  113531. for(k=0;k<l1;k++){
  113532. t3=t1;
  113533. t4=t2;
  113534. for(i=0;i<ido;i++){
  113535. ch[t3]=cc[t4];
  113536. t3++;
  113537. t4++;
  113538. }
  113539. t1+=ido;
  113540. t2+=t10;
  113541. }
  113542. goto L106;
  113543. L103:
  113544. t1=0;
  113545. for(i=0;i<ido;i++){
  113546. t2=t1;
  113547. t3=t1;
  113548. for(k=0;k<l1;k++){
  113549. ch[t2]=cc[t3];
  113550. t2+=ido;
  113551. t3+=t10;
  113552. }
  113553. t1++;
  113554. }
  113555. L106:
  113556. t1=0;
  113557. t2=ipp2*t0;
  113558. t7=(t5=ido<<1);
  113559. for(j=1;j<ipph;j++){
  113560. t1+=t0;
  113561. t2-=t0;
  113562. t3=t1;
  113563. t4=t2;
  113564. t6=t5;
  113565. for(k=0;k<l1;k++){
  113566. ch[t3]=cc[t6-1]+cc[t6-1];
  113567. ch[t4]=cc[t6]+cc[t6];
  113568. t3+=ido;
  113569. t4+=ido;
  113570. t6+=t10;
  113571. }
  113572. t5+=t7;
  113573. }
  113574. if (ido == 1)goto L116;
  113575. if(nbd<l1)goto L112;
  113576. t1=0;
  113577. t2=ipp2*t0;
  113578. t7=0;
  113579. for(j=1;j<ipph;j++){
  113580. t1+=t0;
  113581. t2-=t0;
  113582. t3=t1;
  113583. t4=t2;
  113584. t7+=(ido<<1);
  113585. t8=t7;
  113586. for(k=0;k<l1;k++){
  113587. t5=t3;
  113588. t6=t4;
  113589. t9=t8;
  113590. t11=t8;
  113591. for(i=2;i<ido;i+=2){
  113592. t5+=2;
  113593. t6+=2;
  113594. t9+=2;
  113595. t11-=2;
  113596. ch[t5-1]=cc[t9-1]+cc[t11-1];
  113597. ch[t6-1]=cc[t9-1]-cc[t11-1];
  113598. ch[t5]=cc[t9]-cc[t11];
  113599. ch[t6]=cc[t9]+cc[t11];
  113600. }
  113601. t3+=ido;
  113602. t4+=ido;
  113603. t8+=t10;
  113604. }
  113605. }
  113606. goto L116;
  113607. L112:
  113608. t1=0;
  113609. t2=ipp2*t0;
  113610. t7=0;
  113611. for(j=1;j<ipph;j++){
  113612. t1+=t0;
  113613. t2-=t0;
  113614. t3=t1;
  113615. t4=t2;
  113616. t7+=(ido<<1);
  113617. t8=t7;
  113618. t9=t7;
  113619. for(i=2;i<ido;i+=2){
  113620. t3+=2;
  113621. t4+=2;
  113622. t8+=2;
  113623. t9-=2;
  113624. t5=t3;
  113625. t6=t4;
  113626. t11=t8;
  113627. t12=t9;
  113628. for(k=0;k<l1;k++){
  113629. ch[t5-1]=cc[t11-1]+cc[t12-1];
  113630. ch[t6-1]=cc[t11-1]-cc[t12-1];
  113631. ch[t5]=cc[t11]-cc[t12];
  113632. ch[t6]=cc[t11]+cc[t12];
  113633. t5+=ido;
  113634. t6+=ido;
  113635. t11+=t10;
  113636. t12+=t10;
  113637. }
  113638. }
  113639. }
  113640. L116:
  113641. ar1=1.f;
  113642. ai1=0.f;
  113643. t1=0;
  113644. t9=(t2=ipp2*idl1);
  113645. t3=(ip-1)*idl1;
  113646. for(l=1;l<ipph;l++){
  113647. t1+=idl1;
  113648. t2-=idl1;
  113649. ar1h=dcp*ar1-dsp*ai1;
  113650. ai1=dcp*ai1+dsp*ar1;
  113651. ar1=ar1h;
  113652. t4=t1;
  113653. t5=t2;
  113654. t6=0;
  113655. t7=idl1;
  113656. t8=t3;
  113657. for(ik=0;ik<idl1;ik++){
  113658. c2[t4++]=ch2[t6++]+ar1*ch2[t7++];
  113659. c2[t5++]=ai1*ch2[t8++];
  113660. }
  113661. dc2=ar1;
  113662. ds2=ai1;
  113663. ar2=ar1;
  113664. ai2=ai1;
  113665. t6=idl1;
  113666. t7=t9-idl1;
  113667. for(j=2;j<ipph;j++){
  113668. t6+=idl1;
  113669. t7-=idl1;
  113670. ar2h=dc2*ar2-ds2*ai2;
  113671. ai2=dc2*ai2+ds2*ar2;
  113672. ar2=ar2h;
  113673. t4=t1;
  113674. t5=t2;
  113675. t11=t6;
  113676. t12=t7;
  113677. for(ik=0;ik<idl1;ik++){
  113678. c2[t4++]+=ar2*ch2[t11++];
  113679. c2[t5++]+=ai2*ch2[t12++];
  113680. }
  113681. }
  113682. }
  113683. t1=0;
  113684. for(j=1;j<ipph;j++){
  113685. t1+=idl1;
  113686. t2=t1;
  113687. for(ik=0;ik<idl1;ik++)ch2[ik]+=ch2[t2++];
  113688. }
  113689. t1=0;
  113690. t2=ipp2*t0;
  113691. for(j=1;j<ipph;j++){
  113692. t1+=t0;
  113693. t2-=t0;
  113694. t3=t1;
  113695. t4=t2;
  113696. for(k=0;k<l1;k++){
  113697. ch[t3]=c1[t3]-c1[t4];
  113698. ch[t4]=c1[t3]+c1[t4];
  113699. t3+=ido;
  113700. t4+=ido;
  113701. }
  113702. }
  113703. if(ido==1)goto L132;
  113704. if(nbd<l1)goto L128;
  113705. t1=0;
  113706. t2=ipp2*t0;
  113707. for(j=1;j<ipph;j++){
  113708. t1+=t0;
  113709. t2-=t0;
  113710. t3=t1;
  113711. t4=t2;
  113712. for(k=0;k<l1;k++){
  113713. t5=t3;
  113714. t6=t4;
  113715. for(i=2;i<ido;i+=2){
  113716. t5+=2;
  113717. t6+=2;
  113718. ch[t5-1]=c1[t5-1]-c1[t6];
  113719. ch[t6-1]=c1[t5-1]+c1[t6];
  113720. ch[t5]=c1[t5]+c1[t6-1];
  113721. ch[t6]=c1[t5]-c1[t6-1];
  113722. }
  113723. t3+=ido;
  113724. t4+=ido;
  113725. }
  113726. }
  113727. goto L132;
  113728. L128:
  113729. t1=0;
  113730. t2=ipp2*t0;
  113731. for(j=1;j<ipph;j++){
  113732. t1+=t0;
  113733. t2-=t0;
  113734. t3=t1;
  113735. t4=t2;
  113736. for(i=2;i<ido;i+=2){
  113737. t3+=2;
  113738. t4+=2;
  113739. t5=t3;
  113740. t6=t4;
  113741. for(k=0;k<l1;k++){
  113742. ch[t5-1]=c1[t5-1]-c1[t6];
  113743. ch[t6-1]=c1[t5-1]+c1[t6];
  113744. ch[t5]=c1[t5]+c1[t6-1];
  113745. ch[t6]=c1[t5]-c1[t6-1];
  113746. t5+=ido;
  113747. t6+=ido;
  113748. }
  113749. }
  113750. }
  113751. L132:
  113752. if(ido==1)return;
  113753. for(ik=0;ik<idl1;ik++)c2[ik]=ch2[ik];
  113754. t1=0;
  113755. for(j=1;j<ip;j++){
  113756. t2=(t1+=t0);
  113757. for(k=0;k<l1;k++){
  113758. c1[t2]=ch[t2];
  113759. t2+=ido;
  113760. }
  113761. }
  113762. if(nbd>l1)goto L139;
  113763. is= -ido-1;
  113764. t1=0;
  113765. for(j=1;j<ip;j++){
  113766. is+=ido;
  113767. t1+=t0;
  113768. idij=is;
  113769. t2=t1;
  113770. for(i=2;i<ido;i+=2){
  113771. t2+=2;
  113772. idij+=2;
  113773. t3=t2;
  113774. for(k=0;k<l1;k++){
  113775. c1[t3-1]=wa[idij-1]*ch[t3-1]-wa[idij]*ch[t3];
  113776. c1[t3]=wa[idij-1]*ch[t3]+wa[idij]*ch[t3-1];
  113777. t3+=ido;
  113778. }
  113779. }
  113780. }
  113781. return;
  113782. L139:
  113783. is= -ido-1;
  113784. t1=0;
  113785. for(j=1;j<ip;j++){
  113786. is+=ido;
  113787. t1+=t0;
  113788. t2=t1;
  113789. for(k=0;k<l1;k++){
  113790. idij=is;
  113791. t3=t2;
  113792. for(i=2;i<ido;i+=2){
  113793. idij+=2;
  113794. t3+=2;
  113795. c1[t3-1]=wa[idij-1]*ch[t3-1]-wa[idij]*ch[t3];
  113796. c1[t3]=wa[idij-1]*ch[t3]+wa[idij]*ch[t3-1];
  113797. }
  113798. t2+=ido;
  113799. }
  113800. }
  113801. }
  113802. static void drftb1(int n, float *c, float *ch, float *wa, int *ifac){
  113803. int i,k1,l1,l2;
  113804. int na;
  113805. int nf,ip,iw,ix2,ix3,ido,idl1;
  113806. nf=ifac[1];
  113807. na=0;
  113808. l1=1;
  113809. iw=1;
  113810. for(k1=0;k1<nf;k1++){
  113811. ip=ifac[k1 + 2];
  113812. l2=ip*l1;
  113813. ido=n/l2;
  113814. idl1=ido*l1;
  113815. if(ip!=4)goto L103;
  113816. ix2=iw+ido;
  113817. ix3=ix2+ido;
  113818. if(na!=0)
  113819. dradb4(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1);
  113820. else
  113821. dradb4(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1);
  113822. na=1-na;
  113823. goto L115;
  113824. L103:
  113825. if(ip!=2)goto L106;
  113826. if(na!=0)
  113827. dradb2(ido,l1,ch,c,wa+iw-1);
  113828. else
  113829. dradb2(ido,l1,c,ch,wa+iw-1);
  113830. na=1-na;
  113831. goto L115;
  113832. L106:
  113833. if(ip!=3)goto L109;
  113834. ix2=iw+ido;
  113835. if(na!=0)
  113836. dradb3(ido,l1,ch,c,wa+iw-1,wa+ix2-1);
  113837. else
  113838. dradb3(ido,l1,c,ch,wa+iw-1,wa+ix2-1);
  113839. na=1-na;
  113840. goto L115;
  113841. L109:
  113842. /* The radix five case can be translated later..... */
  113843. /* if(ip!=5)goto L112;
  113844. ix2=iw+ido;
  113845. ix3=ix2+ido;
  113846. ix4=ix3+ido;
  113847. if(na!=0)
  113848. dradb5(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1,wa+ix4-1);
  113849. else
  113850. dradb5(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1,wa+ix4-1);
  113851. na=1-na;
  113852. goto L115;
  113853. L112:*/
  113854. if(na!=0)
  113855. dradbg(ido,ip,l1,idl1,ch,ch,ch,c,c,wa+iw-1);
  113856. else
  113857. dradbg(ido,ip,l1,idl1,c,c,c,ch,ch,wa+iw-1);
  113858. if(ido==1)na=1-na;
  113859. L115:
  113860. l1=l2;
  113861. iw+=(ip-1)*ido;
  113862. }
  113863. if(na==0)return;
  113864. for(i=0;i<n;i++)c[i]=ch[i];
  113865. }
  113866. void drft_forward(drft_lookup *l,float *data){
  113867. if(l->n==1)return;
  113868. drftf1(l->n,data,l->trigcache,l->trigcache+l->n,l->splitcache);
  113869. }
  113870. void drft_backward(drft_lookup *l,float *data){
  113871. if (l->n==1)return;
  113872. drftb1(l->n,data,l->trigcache,l->trigcache+l->n,l->splitcache);
  113873. }
  113874. void drft_init(drft_lookup *l,int n){
  113875. l->n=n;
  113876. l->trigcache=(float*)_ogg_calloc(3*n,sizeof(*l->trigcache));
  113877. l->splitcache=(int*)_ogg_calloc(32,sizeof(*l->splitcache));
  113878. fdrffti(n, l->trigcache, l->splitcache);
  113879. }
  113880. void drft_clear(drft_lookup *l){
  113881. if(l){
  113882. if(l->trigcache)_ogg_free(l->trigcache);
  113883. if(l->splitcache)_ogg_free(l->splitcache);
  113884. memset(l,0,sizeof(*l));
  113885. }
  113886. }
  113887. #endif
  113888. /********* End of inlined file: smallft.c *********/
  113889. /********* Start of inlined file: synthesis.c *********/
  113890. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  113891. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  113892. // tasks..
  113893. #ifdef _MSC_VER
  113894. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  113895. #endif
  113896. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  113897. #if JUCE_USE_OGGVORBIS
  113898. #include <stdio.h>
  113899. int vorbis_synthesis(vorbis_block *vb,ogg_packet *op){
  113900. vorbis_dsp_state *vd=vb->vd;
  113901. private_state *b=(private_state*)vd->backend_state;
  113902. vorbis_info *vi=vd->vi;
  113903. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  113904. oggpack_buffer *opb=&vb->opb;
  113905. int type,mode,i;
  113906. /* first things first. Make sure decode is ready */
  113907. _vorbis_block_ripcord(vb);
  113908. oggpack_readinit(opb,op->packet,op->bytes);
  113909. /* Check the packet type */
  113910. if(oggpack_read(opb,1)!=0){
  113911. /* Oops. This is not an audio data packet */
  113912. return(OV_ENOTAUDIO);
  113913. }
  113914. /* read our mode and pre/post windowsize */
  113915. mode=oggpack_read(opb,b->modebits);
  113916. if(mode==-1)return(OV_EBADPACKET);
  113917. vb->mode=mode;
  113918. vb->W=ci->mode_param[mode]->blockflag;
  113919. if(vb->W){
  113920. /* this doesn;t get mapped through mode selection as it's used
  113921. only for window selection */
  113922. vb->lW=oggpack_read(opb,1);
  113923. vb->nW=oggpack_read(opb,1);
  113924. if(vb->nW==-1) return(OV_EBADPACKET);
  113925. }else{
  113926. vb->lW=0;
  113927. vb->nW=0;
  113928. }
  113929. /* more setup */
  113930. vb->granulepos=op->granulepos;
  113931. vb->sequence=op->packetno;
  113932. vb->eofflag=op->e_o_s;
  113933. /* alloc pcm passback storage */
  113934. vb->pcmend=ci->blocksizes[vb->W];
  113935. vb->pcm=(float**)_vorbis_block_alloc(vb,sizeof(*vb->pcm)*vi->channels);
  113936. for(i=0;i<vi->channels;i++)
  113937. vb->pcm[i]=(float*)_vorbis_block_alloc(vb,vb->pcmend*sizeof(*vb->pcm[i]));
  113938. /* unpack_header enforces range checking */
  113939. type=ci->map_type[ci->mode_param[mode]->mapping];
  113940. return(_mapping_P[type]->inverse(vb,ci->map_param[ci->mode_param[mode]->
  113941. mapping]));
  113942. }
  113943. /* used to track pcm position without actually performing decode.
  113944. Useful for sequential 'fast forward' */
  113945. int vorbis_synthesis_trackonly(vorbis_block *vb,ogg_packet *op){
  113946. vorbis_dsp_state *vd=vb->vd;
  113947. private_state *b=(private_state*)vd->backend_state;
  113948. vorbis_info *vi=vd->vi;
  113949. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  113950. oggpack_buffer *opb=&vb->opb;
  113951. int mode;
  113952. /* first things first. Make sure decode is ready */
  113953. _vorbis_block_ripcord(vb);
  113954. oggpack_readinit(opb,op->packet,op->bytes);
  113955. /* Check the packet type */
  113956. if(oggpack_read(opb,1)!=0){
  113957. /* Oops. This is not an audio data packet */
  113958. return(OV_ENOTAUDIO);
  113959. }
  113960. /* read our mode and pre/post windowsize */
  113961. mode=oggpack_read(opb,b->modebits);
  113962. if(mode==-1)return(OV_EBADPACKET);
  113963. vb->mode=mode;
  113964. vb->W=ci->mode_param[mode]->blockflag;
  113965. if(vb->W){
  113966. vb->lW=oggpack_read(opb,1);
  113967. vb->nW=oggpack_read(opb,1);
  113968. if(vb->nW==-1) return(OV_EBADPACKET);
  113969. }else{
  113970. vb->lW=0;
  113971. vb->nW=0;
  113972. }
  113973. /* more setup */
  113974. vb->granulepos=op->granulepos;
  113975. vb->sequence=op->packetno;
  113976. vb->eofflag=op->e_o_s;
  113977. /* no pcm */
  113978. vb->pcmend=0;
  113979. vb->pcm=NULL;
  113980. return(0);
  113981. }
  113982. long vorbis_packet_blocksize(vorbis_info *vi,ogg_packet *op){
  113983. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  113984. oggpack_buffer opb;
  113985. int mode;
  113986. oggpack_readinit(&opb,op->packet,op->bytes);
  113987. /* Check the packet type */
  113988. if(oggpack_read(&opb,1)!=0){
  113989. /* Oops. This is not an audio data packet */
  113990. return(OV_ENOTAUDIO);
  113991. }
  113992. {
  113993. int modebits=0;
  113994. int v=ci->modes;
  113995. while(v>1){
  113996. modebits++;
  113997. v>>=1;
  113998. }
  113999. /* read our mode and pre/post windowsize */
  114000. mode=oggpack_read(&opb,modebits);
  114001. }
  114002. if(mode==-1)return(OV_EBADPACKET);
  114003. return(ci->blocksizes[ci->mode_param[mode]->blockflag]);
  114004. }
  114005. int vorbis_synthesis_halfrate(vorbis_info *vi,int flag){
  114006. /* set / clear half-sample-rate mode */
  114007. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  114008. /* right now, our MDCT can't handle < 64 sample windows. */
  114009. if(ci->blocksizes[0]<=64 && flag)return -1;
  114010. ci->halfrate_flag=(flag?1:0);
  114011. return 0;
  114012. }
  114013. int vorbis_synthesis_halfrate_p(vorbis_info *vi){
  114014. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  114015. return ci->halfrate_flag;
  114016. }
  114017. #endif
  114018. /********* End of inlined file: synthesis.c *********/
  114019. /********* Start of inlined file: vorbisenc.c *********/
  114020. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  114021. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  114022. // tasks..
  114023. #ifdef _MSC_VER
  114024. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  114025. #endif
  114026. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  114027. #if JUCE_USE_OGGVORBIS
  114028. #include <stdlib.h>
  114029. #include <string.h>
  114030. #include <math.h>
  114031. /* careful with this; it's using static array sizing to make managing
  114032. all the modes a little less annoying. If we use a residue backend
  114033. with > 12 partition types, or a different division of iteration,
  114034. this needs to be updated. */
  114035. typedef struct {
  114036. static_codebook *books[12][3];
  114037. } static_bookblock;
  114038. typedef struct {
  114039. int res_type;
  114040. int limit_type; /* 0 lowpass limited, 1 point stereo limited */
  114041. vorbis_info_residue0 *res;
  114042. static_codebook *book_aux;
  114043. static_codebook *book_aux_managed;
  114044. static_bookblock *books_base;
  114045. static_bookblock *books_base_managed;
  114046. } vorbis_residue_template;
  114047. typedef struct {
  114048. vorbis_info_mapping0 *map;
  114049. vorbis_residue_template *res;
  114050. } vorbis_mapping_template;
  114051. typedef struct vp_adjblock{
  114052. int block[P_BANDS];
  114053. } vp_adjblock;
  114054. typedef struct {
  114055. int data[NOISE_COMPAND_LEVELS];
  114056. } compandblock;
  114057. /* high level configuration information for setting things up
  114058. step-by-step with the detailed vorbis_encode_ctl interface.
  114059. There's a fair amount of redundancy such that interactive setup
  114060. does not directly deal with any vorbis_info or codec_setup_info
  114061. initialization; it's all stored (until full init) in this highlevel
  114062. setup, then flushed out to the real codec setup structs later. */
  114063. typedef struct {
  114064. int att[P_NOISECURVES];
  114065. float boost;
  114066. float decay;
  114067. } att3;
  114068. typedef struct { int data[P_NOISECURVES]; } adj3;
  114069. typedef struct {
  114070. int pre[PACKETBLOBS];
  114071. int post[PACKETBLOBS];
  114072. float kHz[PACKETBLOBS];
  114073. float lowpasskHz[PACKETBLOBS];
  114074. } adj_stereo;
  114075. typedef struct {
  114076. int lo;
  114077. int hi;
  114078. int fixed;
  114079. } noiseguard;
  114080. typedef struct {
  114081. int data[P_NOISECURVES][17];
  114082. } noise3;
  114083. typedef struct {
  114084. int mappings;
  114085. double *rate_mapping;
  114086. double *quality_mapping;
  114087. int coupling_restriction;
  114088. long samplerate_min_restriction;
  114089. long samplerate_max_restriction;
  114090. int *blocksize_short;
  114091. int *blocksize_long;
  114092. att3 *psy_tone_masteratt;
  114093. int *psy_tone_0dB;
  114094. int *psy_tone_dBsuppress;
  114095. vp_adjblock *psy_tone_adj_impulse;
  114096. vp_adjblock *psy_tone_adj_long;
  114097. vp_adjblock *psy_tone_adj_other;
  114098. noiseguard *psy_noiseguards;
  114099. noise3 *psy_noise_bias_impulse;
  114100. noise3 *psy_noise_bias_padding;
  114101. noise3 *psy_noise_bias_trans;
  114102. noise3 *psy_noise_bias_long;
  114103. int *psy_noise_dBsuppress;
  114104. compandblock *psy_noise_compand;
  114105. double *psy_noise_compand_short_mapping;
  114106. double *psy_noise_compand_long_mapping;
  114107. int *psy_noise_normal_start[2];
  114108. int *psy_noise_normal_partition[2];
  114109. double *psy_noise_normal_thresh;
  114110. int *psy_ath_float;
  114111. int *psy_ath_abs;
  114112. double *psy_lowpass;
  114113. vorbis_info_psy_global *global_params;
  114114. double *global_mapping;
  114115. adj_stereo *stereo_modes;
  114116. static_codebook ***floor_books;
  114117. vorbis_info_floor1 *floor_params;
  114118. int *floor_short_mapping;
  114119. int *floor_long_mapping;
  114120. vorbis_mapping_template *maps;
  114121. } ve_setup_data_template;
  114122. /* a few static coder conventions */
  114123. static vorbis_info_mode _mode_template[2]={
  114124. {0,0,0,0},
  114125. {1,0,0,1}
  114126. };
  114127. static vorbis_info_mapping0 _map_nominal[2]={
  114128. {1, {0,0}, {0}, {0}, 1,{0},{1}},
  114129. {1, {0,0}, {1}, {1}, 1,{0},{1}}
  114130. };
  114131. /********* Start of inlined file: setup_44.h *********/
  114132. /********* Start of inlined file: floor_all.h *********/
  114133. /********* Start of inlined file: floor_books.h *********/
  114134. static long _huff_lengthlist_line_256x7_0sub1[] = {
  114135. 0, 2, 3, 3, 3, 3, 4, 3, 4,
  114136. };
  114137. static static_codebook _huff_book_line_256x7_0sub1 = {
  114138. 1, 9,
  114139. _huff_lengthlist_line_256x7_0sub1,
  114140. 0, 0, 0, 0, 0,
  114141. NULL,
  114142. NULL,
  114143. NULL,
  114144. NULL,
  114145. 0
  114146. };
  114147. static long _huff_lengthlist_line_256x7_0sub2[] = {
  114148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 3, 4, 3, 5, 3,
  114149. 6, 3, 6, 4, 6, 4, 7, 5, 7,
  114150. };
  114151. static static_codebook _huff_book_line_256x7_0sub2 = {
  114152. 1, 25,
  114153. _huff_lengthlist_line_256x7_0sub2,
  114154. 0, 0, 0, 0, 0,
  114155. NULL,
  114156. NULL,
  114157. NULL,
  114158. NULL,
  114159. 0
  114160. };
  114161. static long _huff_lengthlist_line_256x7_0sub3[] = {
  114162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  114163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 5, 2, 5, 3, 5, 3,
  114164. 6, 3, 6, 4, 7, 6, 7, 8, 7, 9, 8, 9, 9, 9,10, 9,
  114165. 11,13,11,13,10,10,13,13,13,13,13,13,12,12,12,12,
  114166. };
  114167. static static_codebook _huff_book_line_256x7_0sub3 = {
  114168. 1, 64,
  114169. _huff_lengthlist_line_256x7_0sub3,
  114170. 0, 0, 0, 0, 0,
  114171. NULL,
  114172. NULL,
  114173. NULL,
  114174. NULL,
  114175. 0
  114176. };
  114177. static long _huff_lengthlist_line_256x7_1sub1[] = {
  114178. 0, 3, 3, 3, 3, 2, 4, 3, 4,
  114179. };
  114180. static static_codebook _huff_book_line_256x7_1sub1 = {
  114181. 1, 9,
  114182. _huff_lengthlist_line_256x7_1sub1,
  114183. 0, 0, 0, 0, 0,
  114184. NULL,
  114185. NULL,
  114186. NULL,
  114187. NULL,
  114188. 0
  114189. };
  114190. static long _huff_lengthlist_line_256x7_1sub2[] = {
  114191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 3, 4, 3, 4, 4,
  114192. 5, 4, 6, 5, 6, 7, 6, 8, 8,
  114193. };
  114194. static static_codebook _huff_book_line_256x7_1sub2 = {
  114195. 1, 25,
  114196. _huff_lengthlist_line_256x7_1sub2,
  114197. 0, 0, 0, 0, 0,
  114198. NULL,
  114199. NULL,
  114200. NULL,
  114201. NULL,
  114202. 0
  114203. };
  114204. static long _huff_lengthlist_line_256x7_1sub3[] = {
  114205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  114206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 2, 4, 3, 6, 3, 7,
  114207. 3, 8, 5, 8, 6, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  114208. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7,
  114209. };
  114210. static static_codebook _huff_book_line_256x7_1sub3 = {
  114211. 1, 64,
  114212. _huff_lengthlist_line_256x7_1sub3,
  114213. 0, 0, 0, 0, 0,
  114214. NULL,
  114215. NULL,
  114216. NULL,
  114217. NULL,
  114218. 0
  114219. };
  114220. static long _huff_lengthlist_line_256x7_class0[] = {
  114221. 7, 5, 5, 9, 9, 6, 6, 9,12, 8, 7, 8,11, 8, 9,15,
  114222. 6, 3, 3, 7, 7, 4, 3, 6, 9, 6, 5, 6, 8, 6, 8,15,
  114223. 8, 5, 5, 9, 8, 5, 4, 6,10, 7, 5, 5,11, 8, 7,15,
  114224. 14,15,13,13,13,13, 8,11,15,10, 7, 6,11, 9,10,15,
  114225. };
  114226. static static_codebook _huff_book_line_256x7_class0 = {
  114227. 1, 64,
  114228. _huff_lengthlist_line_256x7_class0,
  114229. 0, 0, 0, 0, 0,
  114230. NULL,
  114231. NULL,
  114232. NULL,
  114233. NULL,
  114234. 0
  114235. };
  114236. static long _huff_lengthlist_line_256x7_class1[] = {
  114237. 5, 6, 8,15, 6, 9,10,15,10,11,12,15,15,15,15,15,
  114238. 4, 6, 7,15, 6, 7, 8,15, 9, 8, 9,15,15,15,15,15,
  114239. 6, 8, 9,15, 7, 7, 8,15,10, 9,10,15,15,15,15,15,
  114240. 15,13,15,15,15,10,11,15,15,13,13,15,15,15,15,15,
  114241. 4, 6, 7,15, 6, 8, 9,15,10,10,12,15,15,15,15,15,
  114242. 2, 5, 6,15, 5, 6, 7,15, 8, 6, 7,15,15,15,15,15,
  114243. 5, 6, 8,15, 5, 6, 7,15, 9, 6, 7,15,15,15,15,15,
  114244. 14,12,13,15,12,10,11,15,15,15,15,15,15,15,15,15,
  114245. 7, 8, 9,15, 9,10,10,15,15,14,14,15,15,15,15,15,
  114246. 5, 6, 7,15, 7, 8, 9,15,12, 9,10,15,15,15,15,15,
  114247. 7, 7, 9,15, 7, 7, 8,15,12, 8, 9,15,15,15,15,15,
  114248. 13,13,14,15,12,11,12,15,15,15,15,15,15,15,15,15,
  114249. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,
  114250. 13,13,13,15,15,15,15,15,15,15,15,15,15,15,15,15,
  114251. 15,12,13,15,15,12,13,15,15,14,15,15,15,15,15,15,
  114252. 15,15,15,15,15,15,13,15,15,15,15,15,15,15,15,15,
  114253. };
  114254. static static_codebook _huff_book_line_256x7_class1 = {
  114255. 1, 256,
  114256. _huff_lengthlist_line_256x7_class1,
  114257. 0, 0, 0, 0, 0,
  114258. NULL,
  114259. NULL,
  114260. NULL,
  114261. NULL,
  114262. 0
  114263. };
  114264. static long _huff_lengthlist_line_512x17_0sub0[] = {
  114265. 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  114266. 5, 6, 5, 6, 6, 6, 6, 5, 6, 6, 7, 6, 7, 6, 7, 6,
  114267. 7, 6, 8, 7, 8, 7, 8, 7, 8, 7, 8, 7, 9, 7, 9, 7,
  114268. 9, 7, 9, 8, 9, 8,10, 8,10, 8,10, 7,10, 6,10, 8,
  114269. 10, 8,11, 7,10, 7,11, 8,11,11,12,12,11,11,12,11,
  114270. 13,11,13,11,13,12,15,12,13,13,14,14,14,14,14,15,
  114271. 15,15,16,14,17,19,19,18,18,18,18,18,18,18,18,18,
  114272. 18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,
  114273. };
  114274. static static_codebook _huff_book_line_512x17_0sub0 = {
  114275. 1, 128,
  114276. _huff_lengthlist_line_512x17_0sub0,
  114277. 0, 0, 0, 0, 0,
  114278. NULL,
  114279. NULL,
  114280. NULL,
  114281. NULL,
  114282. 0
  114283. };
  114284. static long _huff_lengthlist_line_512x17_1sub0[] = {
  114285. 2, 4, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  114286. 6, 5, 6, 6, 7, 6, 7, 6, 8, 7, 8, 7, 8, 7, 8, 7,
  114287. };
  114288. static static_codebook _huff_book_line_512x17_1sub0 = {
  114289. 1, 32,
  114290. _huff_lengthlist_line_512x17_1sub0,
  114291. 0, 0, 0, 0, 0,
  114292. NULL,
  114293. NULL,
  114294. NULL,
  114295. NULL,
  114296. 0
  114297. };
  114298. static long _huff_lengthlist_line_512x17_1sub1[] = {
  114299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  114300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  114301. 4, 3, 5, 3, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 6, 5,
  114302. 6, 5, 7, 5, 8, 6, 8, 6, 8, 6, 8, 6, 8, 7, 9, 7,
  114303. 9, 7,11, 9,11,11,12,11,14,12,14,16,14,16,13,16,
  114304. 14,16,12,15,13,16,14,16,13,14,12,15,13,15,13,13,
  114305. 13,15,12,14,14,15,13,15,12,15,15,15,15,15,15,15,
  114306. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,
  114307. };
  114308. static static_codebook _huff_book_line_512x17_1sub1 = {
  114309. 1, 128,
  114310. _huff_lengthlist_line_512x17_1sub1,
  114311. 0, 0, 0, 0, 0,
  114312. NULL,
  114313. NULL,
  114314. NULL,
  114315. NULL,
  114316. 0
  114317. };
  114318. static long _huff_lengthlist_line_512x17_2sub1[] = {
  114319. 0, 4, 5, 4, 4, 4, 5, 4, 4, 4, 5, 4, 5, 4, 5, 3,
  114320. 5, 3,
  114321. };
  114322. static static_codebook _huff_book_line_512x17_2sub1 = {
  114323. 1, 18,
  114324. _huff_lengthlist_line_512x17_2sub1,
  114325. 0, 0, 0, 0, 0,
  114326. NULL,
  114327. NULL,
  114328. NULL,
  114329. NULL,
  114330. 0
  114331. };
  114332. static long _huff_lengthlist_line_512x17_2sub2[] = {
  114333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  114334. 0, 0, 4, 3, 4, 3, 4, 4, 5, 4, 5, 4, 6, 4, 6, 5,
  114335. 6, 5, 7, 5, 7, 6, 8, 6, 8, 6, 8, 7, 8, 7, 9, 7,
  114336. 9, 8,
  114337. };
  114338. static static_codebook _huff_book_line_512x17_2sub2 = {
  114339. 1, 50,
  114340. _huff_lengthlist_line_512x17_2sub2,
  114341. 0, 0, 0, 0, 0,
  114342. NULL,
  114343. NULL,
  114344. NULL,
  114345. NULL,
  114346. 0
  114347. };
  114348. static long _huff_lengthlist_line_512x17_2sub3[] = {
  114349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  114350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  114351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  114352. 0, 0, 3, 3, 3, 3, 4, 3, 4, 4, 5, 5, 6, 6, 7, 7,
  114353. 7, 8, 8,11, 8, 9, 9, 9,10,11,11,11, 9,10,10,11,
  114354. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,
  114355. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  114356. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  114357. };
  114358. static static_codebook _huff_book_line_512x17_2sub3 = {
  114359. 1, 128,
  114360. _huff_lengthlist_line_512x17_2sub3,
  114361. 0, 0, 0, 0, 0,
  114362. NULL,
  114363. NULL,
  114364. NULL,
  114365. NULL,
  114366. 0
  114367. };
  114368. static long _huff_lengthlist_line_512x17_3sub1[] = {
  114369. 0, 4, 4, 4, 4, 4, 4, 3, 4, 4, 4, 4, 4, 5, 4, 5,
  114370. 5, 5,
  114371. };
  114372. static static_codebook _huff_book_line_512x17_3sub1 = {
  114373. 1, 18,
  114374. _huff_lengthlist_line_512x17_3sub1,
  114375. 0, 0, 0, 0, 0,
  114376. NULL,
  114377. NULL,
  114378. NULL,
  114379. NULL,
  114380. 0
  114381. };
  114382. static long _huff_lengthlist_line_512x17_3sub2[] = {
  114383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  114384. 0, 0, 2, 3, 3, 4, 3, 5, 4, 6, 4, 6, 5, 7, 6, 7,
  114385. 6, 8, 6, 8, 7, 9, 8,10, 8,12, 9,13,10,15,10,15,
  114386. 11,14,
  114387. };
  114388. static static_codebook _huff_book_line_512x17_3sub2 = {
  114389. 1, 50,
  114390. _huff_lengthlist_line_512x17_3sub2,
  114391. 0, 0, 0, 0, 0,
  114392. NULL,
  114393. NULL,
  114394. NULL,
  114395. NULL,
  114396. 0
  114397. };
  114398. static long _huff_lengthlist_line_512x17_3sub3[] = {
  114399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  114400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  114401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  114402. 0, 0, 4, 8, 4, 8, 4, 8, 4, 8, 5, 8, 5, 8, 6, 8,
  114403. 4, 8, 4, 8, 5, 8, 5, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  114404. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  114405. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  114406. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  114407. };
  114408. static static_codebook _huff_book_line_512x17_3sub3 = {
  114409. 1, 128,
  114410. _huff_lengthlist_line_512x17_3sub3,
  114411. 0, 0, 0, 0, 0,
  114412. NULL,
  114413. NULL,
  114414. NULL,
  114415. NULL,
  114416. 0
  114417. };
  114418. static long _huff_lengthlist_line_512x17_class1[] = {
  114419. 1, 2, 3, 6, 5, 4, 7, 7,
  114420. };
  114421. static static_codebook _huff_book_line_512x17_class1 = {
  114422. 1, 8,
  114423. _huff_lengthlist_line_512x17_class1,
  114424. 0, 0, 0, 0, 0,
  114425. NULL,
  114426. NULL,
  114427. NULL,
  114428. NULL,
  114429. 0
  114430. };
  114431. static long _huff_lengthlist_line_512x17_class2[] = {
  114432. 3, 3, 3,14, 5, 4, 4,11, 8, 6, 6,10,17,12,11,17,
  114433. 6, 5, 5,15, 5, 3, 4,11, 8, 5, 5, 8,16, 9,10,14,
  114434. 10, 8, 9,17, 8, 6, 6,13,10, 7, 7,10,16,11,13,14,
  114435. 17,17,17,17,17,16,16,16,16,15,16,16,16,16,16,16,
  114436. };
  114437. static static_codebook _huff_book_line_512x17_class2 = {
  114438. 1, 64,
  114439. _huff_lengthlist_line_512x17_class2,
  114440. 0, 0, 0, 0, 0,
  114441. NULL,
  114442. NULL,
  114443. NULL,
  114444. NULL,
  114445. 0
  114446. };
  114447. static long _huff_lengthlist_line_512x17_class3[] = {
  114448. 2, 4, 6,17, 4, 5, 7,17, 8, 7,10,17,17,17,17,17,
  114449. 3, 4, 6,15, 3, 3, 6,15, 7, 6, 9,17,17,17,17,17,
  114450. 6, 8,10,17, 6, 6, 8,16, 9, 8,10,17,17,15,16,17,
  114451. 17,17,17,17,12,15,15,16,12,15,15,16,16,16,16,16,
  114452. };
  114453. static static_codebook _huff_book_line_512x17_class3 = {
  114454. 1, 64,
  114455. _huff_lengthlist_line_512x17_class3,
  114456. 0, 0, 0, 0, 0,
  114457. NULL,
  114458. NULL,
  114459. NULL,
  114460. NULL,
  114461. 0
  114462. };
  114463. static long _huff_lengthlist_line_128x4_class0[] = {
  114464. 7, 7, 7,11, 6, 6, 7,11, 7, 6, 6,10,12,10,10,13,
  114465. 7, 7, 8,11, 7, 7, 7,11, 7, 6, 7,10,11,10,10,13,
  114466. 10,10, 9,12, 9, 9, 9,11, 8, 8, 8,11,13,11,10,14,
  114467. 15,15,14,15,15,14,13,14,15,12,12,17,17,17,17,17,
  114468. 7, 7, 6, 9, 6, 6, 6, 9, 7, 6, 6, 8,11,11,10,12,
  114469. 7, 7, 7, 9, 7, 6, 6, 9, 7, 6, 6, 9,13,10,10,11,
  114470. 10, 9, 8,10, 9, 8, 8,10, 8, 8, 7, 9,13,12,10,11,
  114471. 17,14,14,13,15,14,12,13,17,13,12,15,17,17,14,17,
  114472. 7, 6, 6, 7, 6, 6, 5, 7, 6, 6, 6, 6,11, 9, 9, 9,
  114473. 7, 7, 6, 7, 7, 6, 6, 7, 6, 6, 6, 6,10, 9, 8, 9,
  114474. 10, 9, 8, 8, 9, 8, 7, 8, 8, 7, 6, 8,11,10, 9,10,
  114475. 17,17,12,15,15,15,12,14,14,14,10,12,15,13,12,13,
  114476. 11,10, 8,10,11,10, 8, 8,10, 9, 7, 7,10, 9, 9,11,
  114477. 11,11, 9,10,11,10, 8, 9,10, 8, 6, 8,10, 9, 9,11,
  114478. 14,13,10,12,12,11,10,10, 8, 7, 8,10,10,11,11,12,
  114479. 17,17,15,17,17,17,17,17,17,13,12,17,17,17,14,17,
  114480. };
  114481. static static_codebook _huff_book_line_128x4_class0 = {
  114482. 1, 256,
  114483. _huff_lengthlist_line_128x4_class0,
  114484. 0, 0, 0, 0, 0,
  114485. NULL,
  114486. NULL,
  114487. NULL,
  114488. NULL,
  114489. 0
  114490. };
  114491. static long _huff_lengthlist_line_128x4_0sub0[] = {
  114492. 2, 2, 2, 2,
  114493. };
  114494. static static_codebook _huff_book_line_128x4_0sub0 = {
  114495. 1, 4,
  114496. _huff_lengthlist_line_128x4_0sub0,
  114497. 0, 0, 0, 0, 0,
  114498. NULL,
  114499. NULL,
  114500. NULL,
  114501. NULL,
  114502. 0
  114503. };
  114504. static long _huff_lengthlist_line_128x4_0sub1[] = {
  114505. 0, 0, 0, 0, 3, 2, 3, 2, 3, 3,
  114506. };
  114507. static static_codebook _huff_book_line_128x4_0sub1 = {
  114508. 1, 10,
  114509. _huff_lengthlist_line_128x4_0sub1,
  114510. 0, 0, 0, 0, 0,
  114511. NULL,
  114512. NULL,
  114513. NULL,
  114514. NULL,
  114515. 0
  114516. };
  114517. static long _huff_lengthlist_line_128x4_0sub2[] = {
  114518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 4, 3, 4, 3,
  114519. 4, 4, 5, 4, 5, 4, 6, 5, 6,
  114520. };
  114521. static static_codebook _huff_book_line_128x4_0sub2 = {
  114522. 1, 25,
  114523. _huff_lengthlist_line_128x4_0sub2,
  114524. 0, 0, 0, 0, 0,
  114525. NULL,
  114526. NULL,
  114527. NULL,
  114528. NULL,
  114529. 0
  114530. };
  114531. static long _huff_lengthlist_line_128x4_0sub3[] = {
  114532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  114533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 4, 3, 5, 3, 5, 3,
  114534. 5, 4, 6, 5, 6, 5, 7, 6, 6, 7, 7, 9, 9,11,11,16,
  114535. 11,14,10,11,11,13,16,15,15,15,15,15,15,15,15,15,
  114536. };
  114537. static static_codebook _huff_book_line_128x4_0sub3 = {
  114538. 1, 64,
  114539. _huff_lengthlist_line_128x4_0sub3,
  114540. 0, 0, 0, 0, 0,
  114541. NULL,
  114542. NULL,
  114543. NULL,
  114544. NULL,
  114545. 0
  114546. };
  114547. static long _huff_lengthlist_line_256x4_class0[] = {
  114548. 6, 7, 7,12, 6, 6, 7,12, 7, 6, 6,10,15,12,11,13,
  114549. 7, 7, 8,13, 7, 7, 8,12, 7, 7, 7,11,12,12,11,13,
  114550. 10, 9, 9,11, 9, 9, 9,10,10, 8, 8,12,14,12,12,14,
  114551. 11,11,12,14,11,12,11,15,15,12,13,15,15,15,15,15,
  114552. 6, 6, 7,10, 6, 6, 6,11, 7, 6, 6, 9,14,12,11,13,
  114553. 7, 7, 7,10, 6, 6, 7, 9, 7, 7, 6,10,13,12,10,12,
  114554. 9, 9, 9,11, 9, 9, 8, 9, 9, 8, 8,10,13,12,10,12,
  114555. 12,12,11,13,12,12,11,12,15,13,12,15,15,15,14,14,
  114556. 6, 6, 6, 8, 6, 6, 5, 6, 7, 7, 6, 5,11,10, 9, 8,
  114557. 7, 6, 6, 7, 6, 6, 5, 6, 7, 7, 6, 6,11,10, 9, 8,
  114558. 8, 8, 8, 9, 8, 8, 7, 8, 8, 8, 6, 7,11,10, 9, 9,
  114559. 14,11,10,14,14,11,10,15,13,11, 9,11,15,12,12,11,
  114560. 11, 9, 8, 8,10, 9, 8, 9,11,10, 9, 8,12,11,12,11,
  114561. 13,10, 8, 9,11,10, 8, 9,10, 9, 8, 9,10, 8,12,12,
  114562. 15,11,10,10,13,11,10,10, 8, 8, 7,12,10, 9,11,12,
  114563. 15,12,11,15,13,11,11,15,12,14,11,13,15,15,13,13,
  114564. };
  114565. static static_codebook _huff_book_line_256x4_class0 = {
  114566. 1, 256,
  114567. _huff_lengthlist_line_256x4_class0,
  114568. 0, 0, 0, 0, 0,
  114569. NULL,
  114570. NULL,
  114571. NULL,
  114572. NULL,
  114573. 0
  114574. };
  114575. static long _huff_lengthlist_line_256x4_0sub0[] = {
  114576. 2, 2, 2, 2,
  114577. };
  114578. static static_codebook _huff_book_line_256x4_0sub0 = {
  114579. 1, 4,
  114580. _huff_lengthlist_line_256x4_0sub0,
  114581. 0, 0, 0, 0, 0,
  114582. NULL,
  114583. NULL,
  114584. NULL,
  114585. NULL,
  114586. 0
  114587. };
  114588. static long _huff_lengthlist_line_256x4_0sub1[] = {
  114589. 0, 0, 0, 0, 2, 2, 3, 3, 3, 3,
  114590. };
  114591. static static_codebook _huff_book_line_256x4_0sub1 = {
  114592. 1, 10,
  114593. _huff_lengthlist_line_256x4_0sub1,
  114594. 0, 0, 0, 0, 0,
  114595. NULL,
  114596. NULL,
  114597. NULL,
  114598. NULL,
  114599. 0
  114600. };
  114601. static long _huff_lengthlist_line_256x4_0sub2[] = {
  114602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 3, 4, 3, 4, 3,
  114603. 5, 3, 5, 4, 5, 4, 6, 4, 6,
  114604. };
  114605. static static_codebook _huff_book_line_256x4_0sub2 = {
  114606. 1, 25,
  114607. _huff_lengthlist_line_256x4_0sub2,
  114608. 0, 0, 0, 0, 0,
  114609. NULL,
  114610. NULL,
  114611. NULL,
  114612. NULL,
  114613. 0
  114614. };
  114615. static long _huff_lengthlist_line_256x4_0sub3[] = {
  114616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  114617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 4, 3, 5, 3, 5, 3,
  114618. 6, 4, 7, 4, 7, 5, 7, 6, 7, 6, 7, 8,10,13,13,13,
  114619. 13,13,13,13,13,13,13,13,13,13,13,12,12,12,12,12,
  114620. };
  114621. static static_codebook _huff_book_line_256x4_0sub3 = {
  114622. 1, 64,
  114623. _huff_lengthlist_line_256x4_0sub3,
  114624. 0, 0, 0, 0, 0,
  114625. NULL,
  114626. NULL,
  114627. NULL,
  114628. NULL,
  114629. 0
  114630. };
  114631. static long _huff_lengthlist_line_128x7_class0[] = {
  114632. 10, 7, 8,13, 9, 6, 7,11,10, 8, 8,12,17,17,17,17,
  114633. 7, 5, 5, 9, 6, 4, 4, 8, 8, 5, 5, 8,16,14,13,16,
  114634. 7, 5, 5, 7, 6, 3, 3, 5, 8, 5, 4, 7,14,12,12,15,
  114635. 10, 7, 8, 9, 7, 5, 5, 6, 9, 6, 5, 5,15,12, 9,10,
  114636. };
  114637. static static_codebook _huff_book_line_128x7_class0 = {
  114638. 1, 64,
  114639. _huff_lengthlist_line_128x7_class0,
  114640. 0, 0, 0, 0, 0,
  114641. NULL,
  114642. NULL,
  114643. NULL,
  114644. NULL,
  114645. 0
  114646. };
  114647. static long _huff_lengthlist_line_128x7_class1[] = {
  114648. 8,13,17,17, 8,11,17,17,11,13,17,17,17,17,17,17,
  114649. 6,10,16,17, 6,10,15,17, 8,10,16,17,17,17,17,17,
  114650. 9,13,15,17, 8,11,17,17,10,12,17,17,17,17,17,17,
  114651. 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,
  114652. 6,11,15,17, 7,10,15,17, 8,10,17,17,17,15,17,17,
  114653. 4, 8,13,17, 4, 7,13,17, 6, 8,15,17,16,15,17,17,
  114654. 6,11,15,17, 6, 9,13,17, 8,10,17,17,15,17,17,17,
  114655. 16,17,17,17,12,14,15,17,13,14,15,17,17,17,17,17,
  114656. 5,10,14,17, 5, 9,14,17, 7, 9,15,17,15,15,17,17,
  114657. 3, 7,12,17, 3, 6,11,17, 5, 7,13,17,12,12,17,17,
  114658. 5, 9,14,17, 3, 7,11,17, 5, 8,13,17,13,11,16,17,
  114659. 12,17,17,17, 9,14,15,17,10,11,14,17,16,14,17,17,
  114660. 8,12,17,17, 8,12,17,17,10,12,17,17,17,17,17,17,
  114661. 5,10,17,17, 5, 9,15,17, 7, 9,17,17,13,13,17,17,
  114662. 7,11,17,17, 6,10,15,17, 7, 9,15,17,12,11,17,17,
  114663. 12,15,17,17,11,14,17,17,11,10,15,17,17,16,17,17,
  114664. };
  114665. static static_codebook _huff_book_line_128x7_class1 = {
  114666. 1, 256,
  114667. _huff_lengthlist_line_128x7_class1,
  114668. 0, 0, 0, 0, 0,
  114669. NULL,
  114670. NULL,
  114671. NULL,
  114672. NULL,
  114673. 0
  114674. };
  114675. static long _huff_lengthlist_line_128x7_0sub1[] = {
  114676. 0, 3, 3, 3, 3, 3, 3, 3, 3,
  114677. };
  114678. static static_codebook _huff_book_line_128x7_0sub1 = {
  114679. 1, 9,
  114680. _huff_lengthlist_line_128x7_0sub1,
  114681. 0, 0, 0, 0, 0,
  114682. NULL,
  114683. NULL,
  114684. NULL,
  114685. NULL,
  114686. 0
  114687. };
  114688. static long _huff_lengthlist_line_128x7_0sub2[] = {
  114689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 4, 4, 4, 4,
  114690. 5, 4, 5, 4, 5, 4, 6, 4, 6,
  114691. };
  114692. static static_codebook _huff_book_line_128x7_0sub2 = {
  114693. 1, 25,
  114694. _huff_lengthlist_line_128x7_0sub2,
  114695. 0, 0, 0, 0, 0,
  114696. NULL,
  114697. NULL,
  114698. NULL,
  114699. NULL,
  114700. 0
  114701. };
  114702. static long _huff_lengthlist_line_128x7_0sub3[] = {
  114703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  114704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 5, 3, 5, 3, 5, 4,
  114705. 5, 4, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  114706. 7, 8, 9,11,13,13,13,13,13,13,13,13,13,13,13,13,
  114707. };
  114708. static static_codebook _huff_book_line_128x7_0sub3 = {
  114709. 1, 64,
  114710. _huff_lengthlist_line_128x7_0sub3,
  114711. 0, 0, 0, 0, 0,
  114712. NULL,
  114713. NULL,
  114714. NULL,
  114715. NULL,
  114716. 0
  114717. };
  114718. static long _huff_lengthlist_line_128x7_1sub1[] = {
  114719. 0, 3, 3, 2, 3, 3, 4, 3, 4,
  114720. };
  114721. static static_codebook _huff_book_line_128x7_1sub1 = {
  114722. 1, 9,
  114723. _huff_lengthlist_line_128x7_1sub1,
  114724. 0, 0, 0, 0, 0,
  114725. NULL,
  114726. NULL,
  114727. NULL,
  114728. NULL,
  114729. 0
  114730. };
  114731. static long _huff_lengthlist_line_128x7_1sub2[] = {
  114732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 3, 6, 3, 6, 3,
  114733. 6, 3, 7, 3, 8, 4, 9, 4, 9,
  114734. };
  114735. static static_codebook _huff_book_line_128x7_1sub2 = {
  114736. 1, 25,
  114737. _huff_lengthlist_line_128x7_1sub2,
  114738. 0, 0, 0, 0, 0,
  114739. NULL,
  114740. NULL,
  114741. NULL,
  114742. NULL,
  114743. 0
  114744. };
  114745. static long _huff_lengthlist_line_128x7_1sub3[] = {
  114746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  114747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 7, 2, 7, 3, 8, 4,
  114748. 9, 5, 9, 8,10,11,11,12,14,14,14,14,14,14,14,14,
  114749. 14,14,14,14,14,14,14,14,14,14,14,14,13,13,13,13,
  114750. };
  114751. static static_codebook _huff_book_line_128x7_1sub3 = {
  114752. 1, 64,
  114753. _huff_lengthlist_line_128x7_1sub3,
  114754. 0, 0, 0, 0, 0,
  114755. NULL,
  114756. NULL,
  114757. NULL,
  114758. NULL,
  114759. 0
  114760. };
  114761. static long _huff_lengthlist_line_128x11_class1[] = {
  114762. 1, 6, 3, 7, 2, 4, 5, 7,
  114763. };
  114764. static static_codebook _huff_book_line_128x11_class1 = {
  114765. 1, 8,
  114766. _huff_lengthlist_line_128x11_class1,
  114767. 0, 0, 0, 0, 0,
  114768. NULL,
  114769. NULL,
  114770. NULL,
  114771. NULL,
  114772. 0
  114773. };
  114774. static long _huff_lengthlist_line_128x11_class2[] = {
  114775. 1, 6,12,16, 4,12,15,16, 9,15,16,16,16,16,16,16,
  114776. 2, 5,11,16, 5,11,13,16, 9,13,16,16,16,16,16,16,
  114777. 4, 8,12,16, 5, 9,12,16, 9,13,15,16,16,16,16,16,
  114778. 15,16,16,16,11,14,13,16,12,15,16,16,16,16,16,15,
  114779. };
  114780. static static_codebook _huff_book_line_128x11_class2 = {
  114781. 1, 64,
  114782. _huff_lengthlist_line_128x11_class2,
  114783. 0, 0, 0, 0, 0,
  114784. NULL,
  114785. NULL,
  114786. NULL,
  114787. NULL,
  114788. 0
  114789. };
  114790. static long _huff_lengthlist_line_128x11_class3[] = {
  114791. 7, 6, 9,17, 7, 6, 8,17,12, 9,11,16,16,16,16,16,
  114792. 5, 4, 7,16, 5, 3, 6,14, 9, 6, 8,15,16,16,16,16,
  114793. 5, 4, 6,13, 3, 2, 4,11, 7, 4, 6,13,16,11,10,14,
  114794. 12,12,12,16, 9, 7,10,15,12, 9,11,16,16,15,15,16,
  114795. };
  114796. static static_codebook _huff_book_line_128x11_class3 = {
  114797. 1, 64,
  114798. _huff_lengthlist_line_128x11_class3,
  114799. 0, 0, 0, 0, 0,
  114800. NULL,
  114801. NULL,
  114802. NULL,
  114803. NULL,
  114804. 0
  114805. };
  114806. static long _huff_lengthlist_line_128x11_0sub0[] = {
  114807. 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  114808. 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 6, 6, 6, 7, 6,
  114809. 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 8, 6, 8, 6, 8, 7,
  114810. 8, 7, 8, 7, 8, 7, 9, 7, 9, 8, 9, 8, 9, 8,10, 8,
  114811. 10, 9,10, 9,10, 9,11, 9,11, 9,10,10,11,10,11,10,
  114812. 11,11,11,11,11,11,12,13,14,14,14,15,15,16,16,16,
  114813. 17,15,16,15,16,16,17,17,16,17,17,17,17,17,17,17,
  114814. 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,
  114815. };
  114816. static static_codebook _huff_book_line_128x11_0sub0 = {
  114817. 1, 128,
  114818. _huff_lengthlist_line_128x11_0sub0,
  114819. 0, 0, 0, 0, 0,
  114820. NULL,
  114821. NULL,
  114822. NULL,
  114823. NULL,
  114824. 0
  114825. };
  114826. static long _huff_lengthlist_line_128x11_1sub0[] = {
  114827. 2, 5, 5, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5, 5, 5, 5,
  114828. 6, 5, 6, 5, 6, 5, 7, 6, 7, 6, 7, 6, 8, 6, 8, 6,
  114829. };
  114830. static static_codebook _huff_book_line_128x11_1sub0 = {
  114831. 1, 32,
  114832. _huff_lengthlist_line_128x11_1sub0,
  114833. 0, 0, 0, 0, 0,
  114834. NULL,
  114835. NULL,
  114836. NULL,
  114837. NULL,
  114838. 0
  114839. };
  114840. static long _huff_lengthlist_line_128x11_1sub1[] = {
  114841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  114842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  114843. 5, 3, 5, 3, 6, 4, 6, 4, 7, 4, 7, 4, 7, 4, 8, 4,
  114844. 8, 4, 9, 5, 9, 5, 9, 5, 9, 6,10, 6,10, 6,11, 7,
  114845. 10, 7,10, 8,11, 9,11, 9,11,10,11,11,12,11,11,12,
  114846. 15,15,12,14,11,14,12,14,11,14,13,14,12,14,11,14,
  114847. 11,14,12,14,11,14,11,14,13,13,14,14,14,14,14,14,
  114848. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  114849. };
  114850. static static_codebook _huff_book_line_128x11_1sub1 = {
  114851. 1, 128,
  114852. _huff_lengthlist_line_128x11_1sub1,
  114853. 0, 0, 0, 0, 0,
  114854. NULL,
  114855. NULL,
  114856. NULL,
  114857. NULL,
  114858. 0
  114859. };
  114860. static long _huff_lengthlist_line_128x11_2sub1[] = {
  114861. 0, 4, 5, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4, 4, 4,
  114862. 5, 5,
  114863. };
  114864. static static_codebook _huff_book_line_128x11_2sub1 = {
  114865. 1, 18,
  114866. _huff_lengthlist_line_128x11_2sub1,
  114867. 0, 0, 0, 0, 0,
  114868. NULL,
  114869. NULL,
  114870. NULL,
  114871. NULL,
  114872. 0
  114873. };
  114874. static long _huff_lengthlist_line_128x11_2sub2[] = {
  114875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  114876. 0, 0, 3, 3, 3, 4, 4, 4, 4, 5, 4, 5, 4, 6, 5, 7,
  114877. 5, 7, 6, 8, 6, 8, 6, 9, 7, 9, 7,10, 7, 9, 8,11,
  114878. 8,11,
  114879. };
  114880. static static_codebook _huff_book_line_128x11_2sub2 = {
  114881. 1, 50,
  114882. _huff_lengthlist_line_128x11_2sub2,
  114883. 0, 0, 0, 0, 0,
  114884. NULL,
  114885. NULL,
  114886. NULL,
  114887. NULL,
  114888. 0
  114889. };
  114890. static long _huff_lengthlist_line_128x11_2sub3[] = {
  114891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  114892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  114893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  114894. 0, 0, 4, 8, 3, 8, 4, 8, 4, 8, 6, 8, 5, 8, 4, 8,
  114895. 4, 8, 6, 8, 7, 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  114896. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  114897. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  114898. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  114899. };
  114900. static static_codebook _huff_book_line_128x11_2sub3 = {
  114901. 1, 128,
  114902. _huff_lengthlist_line_128x11_2sub3,
  114903. 0, 0, 0, 0, 0,
  114904. NULL,
  114905. NULL,
  114906. NULL,
  114907. NULL,
  114908. 0
  114909. };
  114910. static long _huff_lengthlist_line_128x11_3sub1[] = {
  114911. 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 4,
  114912. 5, 4,
  114913. };
  114914. static static_codebook _huff_book_line_128x11_3sub1 = {
  114915. 1, 18,
  114916. _huff_lengthlist_line_128x11_3sub1,
  114917. 0, 0, 0, 0, 0,
  114918. NULL,
  114919. NULL,
  114920. NULL,
  114921. NULL,
  114922. 0
  114923. };
  114924. static long _huff_lengthlist_line_128x11_3sub2[] = {
  114925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  114926. 0, 0, 5, 3, 5, 4, 6, 4, 6, 4, 7, 4, 7, 4, 8, 4,
  114927. 8, 4, 9, 4, 9, 4,10, 4,10, 5,10, 5,11, 5,12, 6,
  114928. 12, 6,
  114929. };
  114930. static static_codebook _huff_book_line_128x11_3sub2 = {
  114931. 1, 50,
  114932. _huff_lengthlist_line_128x11_3sub2,
  114933. 0, 0, 0, 0, 0,
  114934. NULL,
  114935. NULL,
  114936. NULL,
  114937. NULL,
  114938. 0
  114939. };
  114940. static long _huff_lengthlist_line_128x11_3sub3[] = {
  114941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  114942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  114943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  114944. 0, 0, 7, 1, 6, 3, 7, 3, 8, 4, 8, 5, 8, 8, 8, 9,
  114945. 7, 8, 8, 7, 7, 7, 8, 9,10, 9, 9,10,10,10,10,10,
  114946. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  114947. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  114948. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  114949. };
  114950. static static_codebook _huff_book_line_128x11_3sub3 = {
  114951. 1, 128,
  114952. _huff_lengthlist_line_128x11_3sub3,
  114953. 0, 0, 0, 0, 0,
  114954. NULL,
  114955. NULL,
  114956. NULL,
  114957. NULL,
  114958. 0
  114959. };
  114960. static long _huff_lengthlist_line_128x17_class1[] = {
  114961. 1, 3, 4, 7, 2, 5, 6, 7,
  114962. };
  114963. static static_codebook _huff_book_line_128x17_class1 = {
  114964. 1, 8,
  114965. _huff_lengthlist_line_128x17_class1,
  114966. 0, 0, 0, 0, 0,
  114967. NULL,
  114968. NULL,
  114969. NULL,
  114970. NULL,
  114971. 0
  114972. };
  114973. static long _huff_lengthlist_line_128x17_class2[] = {
  114974. 1, 4,10,19, 3, 8,13,19, 7,12,19,19,19,19,19,19,
  114975. 2, 6,11,19, 8,13,19,19, 9,11,19,19,19,19,19,19,
  114976. 6, 7,13,19, 9,13,19,19,10,13,18,18,18,18,18,18,
  114977. 18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,
  114978. };
  114979. static static_codebook _huff_book_line_128x17_class2 = {
  114980. 1, 64,
  114981. _huff_lengthlist_line_128x17_class2,
  114982. 0, 0, 0, 0, 0,
  114983. NULL,
  114984. NULL,
  114985. NULL,
  114986. NULL,
  114987. 0
  114988. };
  114989. static long _huff_lengthlist_line_128x17_class3[] = {
  114990. 3, 6,10,17, 4, 8,11,20, 8,10,11,20,20,20,20,20,
  114991. 2, 4, 8,18, 4, 6, 8,17, 7, 8,10,20,20,17,20,20,
  114992. 3, 5, 8,17, 3, 4, 6,17, 8, 8,10,17,17,12,16,20,
  114993. 13,13,15,20,10,10,12,20,15,14,15,20,20,20,19,19,
  114994. };
  114995. static static_codebook _huff_book_line_128x17_class3 = {
  114996. 1, 64,
  114997. _huff_lengthlist_line_128x17_class3,
  114998. 0, 0, 0, 0, 0,
  114999. NULL,
  115000. NULL,
  115001. NULL,
  115002. NULL,
  115003. 0
  115004. };
  115005. static long _huff_lengthlist_line_128x17_0sub0[] = {
  115006. 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  115007. 7, 5, 7, 5, 7, 5, 7, 5, 7, 5, 7, 5, 8, 5, 8, 5,
  115008. 8, 5, 8, 5, 8, 6, 8, 6, 8, 6, 9, 6, 9, 6, 9, 6,
  115009. 9, 6, 9, 7, 9, 7, 9, 7, 9, 7,10, 7,10, 8,10, 8,
  115010. 10, 8,10, 8,10, 8,11, 8,11, 8,11, 8,11, 8,11, 9,
  115011. 12, 9,12, 9,12, 9,12, 9,12,10,12,10,13,11,13,11,
  115012. 14,12,14,13,15,14,16,14,17,15,18,16,20,20,20,20,
  115013. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  115014. };
  115015. static static_codebook _huff_book_line_128x17_0sub0 = {
  115016. 1, 128,
  115017. _huff_lengthlist_line_128x17_0sub0,
  115018. 0, 0, 0, 0, 0,
  115019. NULL,
  115020. NULL,
  115021. NULL,
  115022. NULL,
  115023. 0
  115024. };
  115025. static long _huff_lengthlist_line_128x17_1sub0[] = {
  115026. 2, 5, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  115027. 6, 5, 6, 5, 7, 6, 7, 6, 7, 6, 8, 6, 9, 7, 9, 7,
  115028. };
  115029. static static_codebook _huff_book_line_128x17_1sub0 = {
  115030. 1, 32,
  115031. _huff_lengthlist_line_128x17_1sub0,
  115032. 0, 0, 0, 0, 0,
  115033. NULL,
  115034. NULL,
  115035. NULL,
  115036. NULL,
  115037. 0
  115038. };
  115039. static long _huff_lengthlist_line_128x17_1sub1[] = {
  115040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115042. 4, 3, 5, 3, 5, 3, 6, 3, 6, 4, 6, 4, 7, 4, 7, 5,
  115043. 8, 5, 8, 6, 9, 7, 9, 7, 9, 8,10, 9,10, 9,11,10,
  115044. 11,11,11,11,11,11,12,12,12,13,12,13,12,14,12,15,
  115045. 12,14,12,16,13,17,13,17,14,17,14,16,13,17,14,17,
  115046. 14,17,15,17,15,15,16,17,17,17,17,17,17,17,17,17,
  115047. 17,17,17,17,17,17,16,16,16,16,16,16,16,16,16,16,
  115048. };
  115049. static static_codebook _huff_book_line_128x17_1sub1 = {
  115050. 1, 128,
  115051. _huff_lengthlist_line_128x17_1sub1,
  115052. 0, 0, 0, 0, 0,
  115053. NULL,
  115054. NULL,
  115055. NULL,
  115056. NULL,
  115057. 0
  115058. };
  115059. static long _huff_lengthlist_line_128x17_2sub1[] = {
  115060. 0, 4, 5, 4, 6, 4, 8, 3, 9, 3, 9, 2, 9, 3, 8, 4,
  115061. 9, 4,
  115062. };
  115063. static static_codebook _huff_book_line_128x17_2sub1 = {
  115064. 1, 18,
  115065. _huff_lengthlist_line_128x17_2sub1,
  115066. 0, 0, 0, 0, 0,
  115067. NULL,
  115068. NULL,
  115069. NULL,
  115070. NULL,
  115071. 0
  115072. };
  115073. static long _huff_lengthlist_line_128x17_2sub2[] = {
  115074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115075. 0, 0, 5, 1, 5, 3, 5, 3, 5, 4, 7, 5,10, 7,10, 7,
  115076. 12,10,14,10,14, 9,14,11,14,14,14,13,13,13,13,13,
  115077. 13,13,
  115078. };
  115079. static static_codebook _huff_book_line_128x17_2sub2 = {
  115080. 1, 50,
  115081. _huff_lengthlist_line_128x17_2sub2,
  115082. 0, 0, 0, 0, 0,
  115083. NULL,
  115084. NULL,
  115085. NULL,
  115086. NULL,
  115087. 0
  115088. };
  115089. static long _huff_lengthlist_line_128x17_2sub3[] = {
  115090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115093. 0, 0, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  115094. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 6, 6,
  115095. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  115096. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  115097. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  115098. };
  115099. static static_codebook _huff_book_line_128x17_2sub3 = {
  115100. 1, 128,
  115101. _huff_lengthlist_line_128x17_2sub3,
  115102. 0, 0, 0, 0, 0,
  115103. NULL,
  115104. NULL,
  115105. NULL,
  115106. NULL,
  115107. 0
  115108. };
  115109. static long _huff_lengthlist_line_128x17_3sub1[] = {
  115110. 0, 4, 4, 4, 4, 4, 4, 4, 5, 3, 5, 3, 5, 4, 6, 4,
  115111. 6, 4,
  115112. };
  115113. static static_codebook _huff_book_line_128x17_3sub1 = {
  115114. 1, 18,
  115115. _huff_lengthlist_line_128x17_3sub1,
  115116. 0, 0, 0, 0, 0,
  115117. NULL,
  115118. NULL,
  115119. NULL,
  115120. NULL,
  115121. 0
  115122. };
  115123. static long _huff_lengthlist_line_128x17_3sub2[] = {
  115124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115125. 0, 0, 5, 3, 6, 3, 6, 4, 7, 4, 7, 4, 7, 4, 8, 4,
  115126. 8, 4, 8, 4, 8, 4, 9, 4, 9, 5,10, 5,10, 7,10, 8,
  115127. 10, 8,
  115128. };
  115129. static static_codebook _huff_book_line_128x17_3sub2 = {
  115130. 1, 50,
  115131. _huff_lengthlist_line_128x17_3sub2,
  115132. 0, 0, 0, 0, 0,
  115133. NULL,
  115134. NULL,
  115135. NULL,
  115136. NULL,
  115137. 0
  115138. };
  115139. static long _huff_lengthlist_line_128x17_3sub3[] = {
  115140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115143. 0, 0, 3, 2, 4, 3, 4, 4, 4, 5, 4, 7, 5, 8, 5,11,
  115144. 6,10, 6,12, 7,12, 7,12, 8,12, 8,12,10,12,12,12,
  115145. 12,12,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  115146. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  115147. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  115148. };
  115149. static static_codebook _huff_book_line_128x17_3sub3 = {
  115150. 1, 128,
  115151. _huff_lengthlist_line_128x17_3sub3,
  115152. 0, 0, 0, 0, 0,
  115153. NULL,
  115154. NULL,
  115155. NULL,
  115156. NULL,
  115157. 0
  115158. };
  115159. static long _huff_lengthlist_line_1024x27_class1[] = {
  115160. 2,10, 8,14, 7,12,11,14, 1, 5, 3, 7, 4, 9, 7,13,
  115161. };
  115162. static static_codebook _huff_book_line_1024x27_class1 = {
  115163. 1, 16,
  115164. _huff_lengthlist_line_1024x27_class1,
  115165. 0, 0, 0, 0, 0,
  115166. NULL,
  115167. NULL,
  115168. NULL,
  115169. NULL,
  115170. 0
  115171. };
  115172. static long _huff_lengthlist_line_1024x27_class2[] = {
  115173. 1, 4, 2, 6, 3, 7, 5, 7,
  115174. };
  115175. static static_codebook _huff_book_line_1024x27_class2 = {
  115176. 1, 8,
  115177. _huff_lengthlist_line_1024x27_class2,
  115178. 0, 0, 0, 0, 0,
  115179. NULL,
  115180. NULL,
  115181. NULL,
  115182. NULL,
  115183. 0
  115184. };
  115185. static long _huff_lengthlist_line_1024x27_class3[] = {
  115186. 1, 5, 7,21, 5, 8, 9,21,10, 9,12,20,20,16,20,20,
  115187. 4, 8, 9,20, 6, 8, 9,20,11,11,13,20,20,15,17,20,
  115188. 9,11,14,20, 8,10,15,20,11,13,15,20,20,20,20,20,
  115189. 20,20,20,20,13,20,20,20,18,18,20,20,20,20,20,20,
  115190. 3, 6, 8,20, 6, 7, 9,20,10, 9,12,20,20,20,20,20,
  115191. 5, 7, 9,20, 6, 6, 9,20,10, 9,12,20,20,20,20,20,
  115192. 8,10,13,20, 8, 9,12,20,11,10,12,20,20,20,20,20,
  115193. 18,20,20,20,15,17,18,20,18,17,18,20,20,20,20,20,
  115194. 7,10,12,20, 8, 9,11,20,14,13,14,20,20,20,20,20,
  115195. 6, 9,12,20, 7, 8,11,20,12,11,13,20,20,20,20,20,
  115196. 9,11,15,20, 8,10,14,20,12,11,14,20,20,20,20,20,
  115197. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  115198. 11,16,18,20,15,15,17,20,20,17,20,20,20,20,20,20,
  115199. 9,14,16,20,12,12,15,20,17,15,18,20,20,20,20,20,
  115200. 16,19,18,20,15,16,20,20,17,17,20,20,20,20,20,20,
  115201. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  115202. };
  115203. static static_codebook _huff_book_line_1024x27_class3 = {
  115204. 1, 256,
  115205. _huff_lengthlist_line_1024x27_class3,
  115206. 0, 0, 0, 0, 0,
  115207. NULL,
  115208. NULL,
  115209. NULL,
  115210. NULL,
  115211. 0
  115212. };
  115213. static long _huff_lengthlist_line_1024x27_class4[] = {
  115214. 2, 3, 7,13, 4, 4, 7,15, 8, 6, 9,17,21,16,15,21,
  115215. 2, 5, 7,11, 5, 5, 7,14, 9, 7,10,16,17,15,16,21,
  115216. 4, 7,10,17, 7, 7, 9,15,11, 9,11,16,21,18,15,21,
  115217. 18,21,21,21,15,17,17,19,21,19,18,20,21,21,21,20,
  115218. };
  115219. static static_codebook _huff_book_line_1024x27_class4 = {
  115220. 1, 64,
  115221. _huff_lengthlist_line_1024x27_class4,
  115222. 0, 0, 0, 0, 0,
  115223. NULL,
  115224. NULL,
  115225. NULL,
  115226. NULL,
  115227. 0
  115228. };
  115229. static long _huff_lengthlist_line_1024x27_0sub0[] = {
  115230. 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  115231. 6, 5, 6, 5, 6, 5, 6, 5, 7, 5, 7, 5, 7, 5, 7, 5,
  115232. 8, 6, 8, 6, 8, 6, 9, 6, 9, 6,10, 6,10, 6,11, 6,
  115233. 11, 7,11, 7,12, 7,12, 7,12, 7,12, 7,12, 7,12, 7,
  115234. 12, 7,12, 8,13, 8,12, 8,12, 8,13, 8,13, 9,13, 9,
  115235. 13, 9,13, 9,12,10,12,10,13,10,14,11,14,12,14,13,
  115236. 14,13,14,14,15,16,15,15,15,14,15,17,21,22,22,21,
  115237. 22,22,22,22,22,22,21,21,21,21,21,21,21,21,21,21,
  115238. };
  115239. static static_codebook _huff_book_line_1024x27_0sub0 = {
  115240. 1, 128,
  115241. _huff_lengthlist_line_1024x27_0sub0,
  115242. 0, 0, 0, 0, 0,
  115243. NULL,
  115244. NULL,
  115245. NULL,
  115246. NULL,
  115247. 0
  115248. };
  115249. static long _huff_lengthlist_line_1024x27_1sub0[] = {
  115250. 2, 5, 5, 4, 5, 4, 5, 4, 5, 4, 6, 5, 6, 5, 6, 5,
  115251. 6, 5, 7, 5, 7, 6, 8, 6, 8, 6, 8, 6, 9, 6, 9, 6,
  115252. };
  115253. static static_codebook _huff_book_line_1024x27_1sub0 = {
  115254. 1, 32,
  115255. _huff_lengthlist_line_1024x27_1sub0,
  115256. 0, 0, 0, 0, 0,
  115257. NULL,
  115258. NULL,
  115259. NULL,
  115260. NULL,
  115261. 0
  115262. };
  115263. static long _huff_lengthlist_line_1024x27_1sub1[] = {
  115264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115266. 8, 5, 8, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 4,
  115267. 9, 4, 9, 4, 9, 4, 8, 4, 8, 4, 9, 5, 9, 5, 9, 5,
  115268. 9, 5, 9, 6,10, 6,10, 7,10, 8,11, 9,11,11,12,13,
  115269. 12,14,13,15,13,15,14,16,14,17,15,17,15,15,16,16,
  115270. 15,16,16,16,15,18,16,15,17,17,19,19,19,19,19,19,
  115271. 19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,
  115272. };
  115273. static static_codebook _huff_book_line_1024x27_1sub1 = {
  115274. 1, 128,
  115275. _huff_lengthlist_line_1024x27_1sub1,
  115276. 0, 0, 0, 0, 0,
  115277. NULL,
  115278. NULL,
  115279. NULL,
  115280. NULL,
  115281. 0
  115282. };
  115283. static long _huff_lengthlist_line_1024x27_2sub0[] = {
  115284. 1, 5, 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  115285. 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 9, 8,10, 9,10, 9,
  115286. };
  115287. static static_codebook _huff_book_line_1024x27_2sub0 = {
  115288. 1, 32,
  115289. _huff_lengthlist_line_1024x27_2sub0,
  115290. 0, 0, 0, 0, 0,
  115291. NULL,
  115292. NULL,
  115293. NULL,
  115294. NULL,
  115295. 0
  115296. };
  115297. static long _huff_lengthlist_line_1024x27_2sub1[] = {
  115298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115300. 4, 3, 4, 3, 4, 4, 5, 4, 5, 4, 5, 5, 6, 5, 6, 5,
  115301. 7, 5, 7, 6, 7, 6, 8, 7, 8, 7, 8, 7, 9, 8, 9, 9,
  115302. 9, 9,10,10,10,11, 9,12, 9,12, 9,15,10,14, 9,13,
  115303. 10,13,10,12,10,12,10,13,10,12,11,13,11,14,12,13,
  115304. 13,14,14,13,14,15,14,16,13,13,14,16,16,16,16,16,
  115305. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,15,15,
  115306. };
  115307. static static_codebook _huff_book_line_1024x27_2sub1 = {
  115308. 1, 128,
  115309. _huff_lengthlist_line_1024x27_2sub1,
  115310. 0, 0, 0, 0, 0,
  115311. NULL,
  115312. NULL,
  115313. NULL,
  115314. NULL,
  115315. 0
  115316. };
  115317. static long _huff_lengthlist_line_1024x27_3sub1[] = {
  115318. 0, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4, 4, 4, 4, 5,
  115319. 5, 5,
  115320. };
  115321. static static_codebook _huff_book_line_1024x27_3sub1 = {
  115322. 1, 18,
  115323. _huff_lengthlist_line_1024x27_3sub1,
  115324. 0, 0, 0, 0, 0,
  115325. NULL,
  115326. NULL,
  115327. NULL,
  115328. NULL,
  115329. 0
  115330. };
  115331. static long _huff_lengthlist_line_1024x27_3sub2[] = {
  115332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115333. 0, 0, 3, 3, 4, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5, 6,
  115334. 5, 7, 5, 8, 6, 8, 6, 9, 7,10, 7,10, 8,10, 8,11,
  115335. 9,11,
  115336. };
  115337. static static_codebook _huff_book_line_1024x27_3sub2 = {
  115338. 1, 50,
  115339. _huff_lengthlist_line_1024x27_3sub2,
  115340. 0, 0, 0, 0, 0,
  115341. NULL,
  115342. NULL,
  115343. NULL,
  115344. NULL,
  115345. 0
  115346. };
  115347. static long _huff_lengthlist_line_1024x27_3sub3[] = {
  115348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115351. 0, 0, 3, 7, 3, 8, 3,10, 3, 8, 3, 9, 3, 8, 4, 9,
  115352. 4, 9, 5, 9, 6,10, 6, 9, 7,11, 7,12, 9,13,10,13,
  115353. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  115354. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  115355. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  115356. };
  115357. static static_codebook _huff_book_line_1024x27_3sub3 = {
  115358. 1, 128,
  115359. _huff_lengthlist_line_1024x27_3sub3,
  115360. 0, 0, 0, 0, 0,
  115361. NULL,
  115362. NULL,
  115363. NULL,
  115364. NULL,
  115365. 0
  115366. };
  115367. static long _huff_lengthlist_line_1024x27_4sub1[] = {
  115368. 0, 4, 5, 4, 5, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4,
  115369. 5, 4,
  115370. };
  115371. static static_codebook _huff_book_line_1024x27_4sub1 = {
  115372. 1, 18,
  115373. _huff_lengthlist_line_1024x27_4sub1,
  115374. 0, 0, 0, 0, 0,
  115375. NULL,
  115376. NULL,
  115377. NULL,
  115378. NULL,
  115379. 0
  115380. };
  115381. static long _huff_lengthlist_line_1024x27_4sub2[] = {
  115382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115383. 0, 0, 4, 2, 4, 2, 5, 3, 5, 4, 6, 6, 6, 7, 7, 8,
  115384. 7, 8, 7, 8, 7, 9, 8, 9, 8, 9, 8,10, 8,11, 9,12,
  115385. 9,12,
  115386. };
  115387. static static_codebook _huff_book_line_1024x27_4sub2 = {
  115388. 1, 50,
  115389. _huff_lengthlist_line_1024x27_4sub2,
  115390. 0, 0, 0, 0, 0,
  115391. NULL,
  115392. NULL,
  115393. NULL,
  115394. NULL,
  115395. 0
  115396. };
  115397. static long _huff_lengthlist_line_1024x27_4sub3[] = {
  115398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115401. 0, 0, 2, 5, 2, 6, 3, 6, 4, 7, 4, 7, 5, 9, 5,11,
  115402. 6,11, 6,11, 7,11, 6,11, 6,11, 9,11, 8,11,11,11,
  115403. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  115404. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  115405. 11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,
  115406. };
  115407. static static_codebook _huff_book_line_1024x27_4sub3 = {
  115408. 1, 128,
  115409. _huff_lengthlist_line_1024x27_4sub3,
  115410. 0, 0, 0, 0, 0,
  115411. NULL,
  115412. NULL,
  115413. NULL,
  115414. NULL,
  115415. 0
  115416. };
  115417. static long _huff_lengthlist_line_2048x27_class1[] = {
  115418. 2, 6, 8, 9, 7,11,13,13, 1, 3, 5, 5, 6, 6,12,10,
  115419. };
  115420. static static_codebook _huff_book_line_2048x27_class1 = {
  115421. 1, 16,
  115422. _huff_lengthlist_line_2048x27_class1,
  115423. 0, 0, 0, 0, 0,
  115424. NULL,
  115425. NULL,
  115426. NULL,
  115427. NULL,
  115428. 0
  115429. };
  115430. static long _huff_lengthlist_line_2048x27_class2[] = {
  115431. 1, 2, 3, 6, 4, 7, 5, 7,
  115432. };
  115433. static static_codebook _huff_book_line_2048x27_class2 = {
  115434. 1, 8,
  115435. _huff_lengthlist_line_2048x27_class2,
  115436. 0, 0, 0, 0, 0,
  115437. NULL,
  115438. NULL,
  115439. NULL,
  115440. NULL,
  115441. 0
  115442. };
  115443. static long _huff_lengthlist_line_2048x27_class3[] = {
  115444. 3, 3, 6,16, 5, 5, 7,16, 9, 8,11,16,16,16,16,16,
  115445. 5, 5, 8,16, 5, 5, 7,16, 8, 7, 9,16,16,16,16,16,
  115446. 9, 9,12,16, 6, 8,11,16, 9,10,11,16,16,16,16,16,
  115447. 16,16,16,16,13,16,16,16,15,16,16,16,16,16,16,16,
  115448. 5, 4, 7,16, 6, 5, 8,16, 9, 8,10,16,16,16,16,16,
  115449. 5, 5, 7,15, 5, 4, 6,15, 7, 6, 8,16,16,16,16,16,
  115450. 9, 9,11,15, 7, 7, 9,16, 8, 8, 9,16,16,16,16,16,
  115451. 16,16,16,16,15,15,15,16,15,15,14,16,16,16,16,16,
  115452. 8, 8,11,16, 8, 9,10,16,11,10,14,16,16,16,16,16,
  115453. 6, 8,10,16, 6, 7,10,16, 8, 8,11,16,14,16,16,16,
  115454. 10,11,14,16, 9, 9,11,16,10,10,11,16,16,16,16,16,
  115455. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  115456. 16,16,16,16,15,16,16,16,16,16,16,16,16,16,16,16,
  115457. 12,16,15,16,12,14,16,16,16,16,16,16,16,16,16,16,
  115458. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  115459. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  115460. };
  115461. static static_codebook _huff_book_line_2048x27_class3 = {
  115462. 1, 256,
  115463. _huff_lengthlist_line_2048x27_class3,
  115464. 0, 0, 0, 0, 0,
  115465. NULL,
  115466. NULL,
  115467. NULL,
  115468. NULL,
  115469. 0
  115470. };
  115471. static long _huff_lengthlist_line_2048x27_class4[] = {
  115472. 2, 4, 7,13, 4, 5, 7,15, 8, 7,10,16,16,14,16,16,
  115473. 2, 4, 7,16, 3, 4, 7,14, 8, 8,10,16,16,16,15,16,
  115474. 6, 8,11,16, 7, 7, 9,16,11, 9,13,16,16,16,15,16,
  115475. 16,16,16,16,14,16,16,16,16,16,16,16,16,16,16,16,
  115476. };
  115477. static static_codebook _huff_book_line_2048x27_class4 = {
  115478. 1, 64,
  115479. _huff_lengthlist_line_2048x27_class4,
  115480. 0, 0, 0, 0, 0,
  115481. NULL,
  115482. NULL,
  115483. NULL,
  115484. NULL,
  115485. 0
  115486. };
  115487. static long _huff_lengthlist_line_2048x27_0sub0[] = {
  115488. 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  115489. 6, 5, 7, 5, 7, 5, 7, 5, 8, 5, 8, 5, 8, 5, 9, 5,
  115490. 9, 6,10, 6,10, 6,11, 6,11, 6,11, 6,11, 6,11, 6,
  115491. 11, 6,11, 6,12, 7,11, 7,11, 7,11, 7,11, 7,10, 7,
  115492. 11, 7,11, 7,12, 7,11, 8,11, 8,11, 8,11, 8,13, 8,
  115493. 12, 9,11, 9,11, 9,11,10,12,10,12, 9,12,10,12,11,
  115494. 14,12,16,12,12,11,14,16,17,17,17,17,17,17,17,17,
  115495. 17,17,17,17,17,17,17,17,17,17,17,17,16,16,16,16,
  115496. };
  115497. static static_codebook _huff_book_line_2048x27_0sub0 = {
  115498. 1, 128,
  115499. _huff_lengthlist_line_2048x27_0sub0,
  115500. 0, 0, 0, 0, 0,
  115501. NULL,
  115502. NULL,
  115503. NULL,
  115504. NULL,
  115505. 0
  115506. };
  115507. static long _huff_lengthlist_line_2048x27_1sub0[] = {
  115508. 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5,
  115509. 5, 5, 6, 6, 6, 6, 6, 6, 7, 6, 7, 6, 7, 6, 7, 6,
  115510. };
  115511. static static_codebook _huff_book_line_2048x27_1sub0 = {
  115512. 1, 32,
  115513. _huff_lengthlist_line_2048x27_1sub0,
  115514. 0, 0, 0, 0, 0,
  115515. NULL,
  115516. NULL,
  115517. NULL,
  115518. NULL,
  115519. 0
  115520. };
  115521. static long _huff_lengthlist_line_2048x27_1sub1[] = {
  115522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115524. 6, 5, 7, 5, 7, 4, 7, 4, 8, 4, 8, 4, 8, 4, 8, 3,
  115525. 8, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 5, 9, 5, 9, 6,
  115526. 9, 7, 9, 8, 9, 9, 9,10, 9,11, 9,14, 9,15,10,15,
  115527. 10,15,10,15,10,15,11,15,10,14,12,14,11,14,13,14,
  115528. 13,15,15,15,12,15,15,15,13,15,13,15,13,15,15,15,
  115529. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,14,
  115530. };
  115531. static static_codebook _huff_book_line_2048x27_1sub1 = {
  115532. 1, 128,
  115533. _huff_lengthlist_line_2048x27_1sub1,
  115534. 0, 0, 0, 0, 0,
  115535. NULL,
  115536. NULL,
  115537. NULL,
  115538. NULL,
  115539. 0
  115540. };
  115541. static long _huff_lengthlist_line_2048x27_2sub0[] = {
  115542. 2, 4, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  115543. 6, 5, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  115544. };
  115545. static static_codebook _huff_book_line_2048x27_2sub0 = {
  115546. 1, 32,
  115547. _huff_lengthlist_line_2048x27_2sub0,
  115548. 0, 0, 0, 0, 0,
  115549. NULL,
  115550. NULL,
  115551. NULL,
  115552. NULL,
  115553. 0
  115554. };
  115555. static long _huff_lengthlist_line_2048x27_2sub1[] = {
  115556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115558. 3, 4, 3, 4, 3, 4, 4, 5, 4, 5, 5, 5, 6, 6, 6, 7,
  115559. 6, 8, 6, 8, 6, 9, 7,10, 7,10, 7,10, 7,12, 7,12,
  115560. 7,12, 9,12,11,12,10,12,10,12,11,12,12,12,10,12,
  115561. 10,12,10,12, 9,12,11,12,12,12,12,12,11,12,11,12,
  115562. 12,12,12,12,12,12,12,12,10,10,12,12,12,12,12,10,
  115563. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  115564. };
  115565. static static_codebook _huff_book_line_2048x27_2sub1 = {
  115566. 1, 128,
  115567. _huff_lengthlist_line_2048x27_2sub1,
  115568. 0, 0, 0, 0, 0,
  115569. NULL,
  115570. NULL,
  115571. NULL,
  115572. NULL,
  115573. 0
  115574. };
  115575. static long _huff_lengthlist_line_2048x27_3sub1[] = {
  115576. 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
  115577. 5, 5,
  115578. };
  115579. static static_codebook _huff_book_line_2048x27_3sub1 = {
  115580. 1, 18,
  115581. _huff_lengthlist_line_2048x27_3sub1,
  115582. 0, 0, 0, 0, 0,
  115583. NULL,
  115584. NULL,
  115585. NULL,
  115586. NULL,
  115587. 0
  115588. };
  115589. static long _huff_lengthlist_line_2048x27_3sub2[] = {
  115590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115591. 0, 0, 3, 3, 3, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 6,
  115592. 6, 7, 6, 7, 6, 8, 6, 9, 7, 9, 7, 9, 9,11, 9,12,
  115593. 10,12,
  115594. };
  115595. static static_codebook _huff_book_line_2048x27_3sub2 = {
  115596. 1, 50,
  115597. _huff_lengthlist_line_2048x27_3sub2,
  115598. 0, 0, 0, 0, 0,
  115599. NULL,
  115600. NULL,
  115601. NULL,
  115602. NULL,
  115603. 0
  115604. };
  115605. static long _huff_lengthlist_line_2048x27_3sub3[] = {
  115606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115609. 0, 0, 3, 6, 3, 7, 3, 7, 5, 7, 7, 7, 7, 7, 6, 7,
  115610. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  115611. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  115612. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  115613. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  115614. };
  115615. static static_codebook _huff_book_line_2048x27_3sub3 = {
  115616. 1, 128,
  115617. _huff_lengthlist_line_2048x27_3sub3,
  115618. 0, 0, 0, 0, 0,
  115619. NULL,
  115620. NULL,
  115621. NULL,
  115622. NULL,
  115623. 0
  115624. };
  115625. static long _huff_lengthlist_line_2048x27_4sub1[] = {
  115626. 0, 3, 4, 4, 4, 4, 4, 4, 4, 4, 5, 4, 5, 4, 5, 4,
  115627. 4, 5,
  115628. };
  115629. static static_codebook _huff_book_line_2048x27_4sub1 = {
  115630. 1, 18,
  115631. _huff_lengthlist_line_2048x27_4sub1,
  115632. 0, 0, 0, 0, 0,
  115633. NULL,
  115634. NULL,
  115635. NULL,
  115636. NULL,
  115637. 0
  115638. };
  115639. static long _huff_lengthlist_line_2048x27_4sub2[] = {
  115640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115641. 0, 0, 3, 2, 4, 3, 4, 4, 4, 5, 5, 6, 5, 6, 5, 7,
  115642. 6, 6, 6, 7, 7, 7, 8, 9, 9, 9,12,10,11,10,10,12,
  115643. 10,10,
  115644. };
  115645. static static_codebook _huff_book_line_2048x27_4sub2 = {
  115646. 1, 50,
  115647. _huff_lengthlist_line_2048x27_4sub2,
  115648. 0, 0, 0, 0, 0,
  115649. NULL,
  115650. NULL,
  115651. NULL,
  115652. NULL,
  115653. 0
  115654. };
  115655. static long _huff_lengthlist_line_2048x27_4sub3[] = {
  115656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115659. 0, 0, 3, 6, 5, 7, 5, 7, 7, 7, 7, 7, 5, 7, 5, 7,
  115660. 5, 7, 5, 7, 7, 7, 7, 7, 4, 7, 7, 7, 7, 7, 7, 7,
  115661. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  115662. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  115663. 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  115664. };
  115665. static static_codebook _huff_book_line_2048x27_4sub3 = {
  115666. 1, 128,
  115667. _huff_lengthlist_line_2048x27_4sub3,
  115668. 0, 0, 0, 0, 0,
  115669. NULL,
  115670. NULL,
  115671. NULL,
  115672. NULL,
  115673. 0
  115674. };
  115675. static long _huff_lengthlist_line_256x4low_class0[] = {
  115676. 4, 5, 6,11, 5, 5, 6,10, 7, 7, 6, 6,14,13, 9, 9,
  115677. 6, 6, 6,10, 6, 6, 6, 9, 8, 7, 7, 9,14,12, 8,11,
  115678. 8, 7, 7,11, 8, 8, 7,11, 9, 9, 7, 9,13,11, 9,13,
  115679. 19,19,18,19,15,16,16,19,11,11,10,13,10,10, 9,15,
  115680. 5, 5, 6,13, 6, 6, 6,11, 8, 7, 6, 7,14,11,10,11,
  115681. 6, 6, 6,12, 7, 6, 6,11, 8, 7, 7,11,13,11, 9,11,
  115682. 9, 7, 6,12, 8, 7, 6,12, 9, 8, 8,11,13,10, 7,13,
  115683. 19,19,17,19,17,14,14,19,12,10, 8,12,13,10, 9,16,
  115684. 7, 8, 7,12, 7, 7, 7,11, 8, 7, 7, 8,12,12,11,11,
  115685. 8, 8, 7,12, 8, 7, 6,11, 8, 7, 7,10,10,11,10,11,
  115686. 9, 8, 8,13, 9, 8, 7,12,10, 9, 7,11, 9, 8, 7,11,
  115687. 18,18,15,18,18,16,17,18,15,11,10,18,11, 9, 9,18,
  115688. 16,16,13,16,12,11,10,16,12,11, 9, 6,15,12,11,13,
  115689. 16,16,14,14,13,11,12,16,12, 9, 9,13,13,10,10,12,
  115690. 17,18,17,17,14,15,14,16,14,12,14,15,12,10,11,12,
  115691. 18,18,18,18,18,18,18,18,18,12,13,18,16,11, 9,18,
  115692. };
  115693. static static_codebook _huff_book_line_256x4low_class0 = {
  115694. 1, 256,
  115695. _huff_lengthlist_line_256x4low_class0,
  115696. 0, 0, 0, 0, 0,
  115697. NULL,
  115698. NULL,
  115699. NULL,
  115700. NULL,
  115701. 0
  115702. };
  115703. static long _huff_lengthlist_line_256x4low_0sub0[] = {
  115704. 1, 3, 2, 3,
  115705. };
  115706. static static_codebook _huff_book_line_256x4low_0sub0 = {
  115707. 1, 4,
  115708. _huff_lengthlist_line_256x4low_0sub0,
  115709. 0, 0, 0, 0, 0,
  115710. NULL,
  115711. NULL,
  115712. NULL,
  115713. NULL,
  115714. 0
  115715. };
  115716. static long _huff_lengthlist_line_256x4low_0sub1[] = {
  115717. 0, 0, 0, 0, 2, 3, 2, 3, 3, 3,
  115718. };
  115719. static static_codebook _huff_book_line_256x4low_0sub1 = {
  115720. 1, 10,
  115721. _huff_lengthlist_line_256x4low_0sub1,
  115722. 0, 0, 0, 0, 0,
  115723. NULL,
  115724. NULL,
  115725. NULL,
  115726. NULL,
  115727. 0
  115728. };
  115729. static long _huff_lengthlist_line_256x4low_0sub2[] = {
  115730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 4, 3, 4,
  115731. 4, 4, 4, 4, 5, 5, 5, 6, 6,
  115732. };
  115733. static static_codebook _huff_book_line_256x4low_0sub2 = {
  115734. 1, 25,
  115735. _huff_lengthlist_line_256x4low_0sub2,
  115736. 0, 0, 0, 0, 0,
  115737. NULL,
  115738. NULL,
  115739. NULL,
  115740. NULL,
  115741. 0
  115742. };
  115743. static long _huff_lengthlist_line_256x4low_0sub3[] = {
  115744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  115745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 2, 4, 3, 5, 4,
  115746. 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 7, 7, 8, 6, 9,
  115747. 7,12,11,16,13,16,12,15,13,15,12,14,12,15,15,15,
  115748. };
  115749. static static_codebook _huff_book_line_256x4low_0sub3 = {
  115750. 1, 64,
  115751. _huff_lengthlist_line_256x4low_0sub3,
  115752. 0, 0, 0, 0, 0,
  115753. NULL,
  115754. NULL,
  115755. NULL,
  115756. NULL,
  115757. 0
  115758. };
  115759. /********* End of inlined file: floor_books.h *********/
  115760. static static_codebook *_floor_128x4_books[]={
  115761. &_huff_book_line_128x4_class0,
  115762. &_huff_book_line_128x4_0sub0,
  115763. &_huff_book_line_128x4_0sub1,
  115764. &_huff_book_line_128x4_0sub2,
  115765. &_huff_book_line_128x4_0sub3,
  115766. };
  115767. static static_codebook *_floor_256x4_books[]={
  115768. &_huff_book_line_256x4_class0,
  115769. &_huff_book_line_256x4_0sub0,
  115770. &_huff_book_line_256x4_0sub1,
  115771. &_huff_book_line_256x4_0sub2,
  115772. &_huff_book_line_256x4_0sub3,
  115773. };
  115774. static static_codebook *_floor_128x7_books[]={
  115775. &_huff_book_line_128x7_class0,
  115776. &_huff_book_line_128x7_class1,
  115777. &_huff_book_line_128x7_0sub1,
  115778. &_huff_book_line_128x7_0sub2,
  115779. &_huff_book_line_128x7_0sub3,
  115780. &_huff_book_line_128x7_1sub1,
  115781. &_huff_book_line_128x7_1sub2,
  115782. &_huff_book_line_128x7_1sub3,
  115783. };
  115784. static static_codebook *_floor_256x7_books[]={
  115785. &_huff_book_line_256x7_class0,
  115786. &_huff_book_line_256x7_class1,
  115787. &_huff_book_line_256x7_0sub1,
  115788. &_huff_book_line_256x7_0sub2,
  115789. &_huff_book_line_256x7_0sub3,
  115790. &_huff_book_line_256x7_1sub1,
  115791. &_huff_book_line_256x7_1sub2,
  115792. &_huff_book_line_256x7_1sub3,
  115793. };
  115794. static static_codebook *_floor_128x11_books[]={
  115795. &_huff_book_line_128x11_class1,
  115796. &_huff_book_line_128x11_class2,
  115797. &_huff_book_line_128x11_class3,
  115798. &_huff_book_line_128x11_0sub0,
  115799. &_huff_book_line_128x11_1sub0,
  115800. &_huff_book_line_128x11_1sub1,
  115801. &_huff_book_line_128x11_2sub1,
  115802. &_huff_book_line_128x11_2sub2,
  115803. &_huff_book_line_128x11_2sub3,
  115804. &_huff_book_line_128x11_3sub1,
  115805. &_huff_book_line_128x11_3sub2,
  115806. &_huff_book_line_128x11_3sub3,
  115807. };
  115808. static static_codebook *_floor_128x17_books[]={
  115809. &_huff_book_line_128x17_class1,
  115810. &_huff_book_line_128x17_class2,
  115811. &_huff_book_line_128x17_class3,
  115812. &_huff_book_line_128x17_0sub0,
  115813. &_huff_book_line_128x17_1sub0,
  115814. &_huff_book_line_128x17_1sub1,
  115815. &_huff_book_line_128x17_2sub1,
  115816. &_huff_book_line_128x17_2sub2,
  115817. &_huff_book_line_128x17_2sub3,
  115818. &_huff_book_line_128x17_3sub1,
  115819. &_huff_book_line_128x17_3sub2,
  115820. &_huff_book_line_128x17_3sub3,
  115821. };
  115822. static static_codebook *_floor_256x4low_books[]={
  115823. &_huff_book_line_256x4low_class0,
  115824. &_huff_book_line_256x4low_0sub0,
  115825. &_huff_book_line_256x4low_0sub1,
  115826. &_huff_book_line_256x4low_0sub2,
  115827. &_huff_book_line_256x4low_0sub3,
  115828. };
  115829. static static_codebook *_floor_1024x27_books[]={
  115830. &_huff_book_line_1024x27_class1,
  115831. &_huff_book_line_1024x27_class2,
  115832. &_huff_book_line_1024x27_class3,
  115833. &_huff_book_line_1024x27_class4,
  115834. &_huff_book_line_1024x27_0sub0,
  115835. &_huff_book_line_1024x27_1sub0,
  115836. &_huff_book_line_1024x27_1sub1,
  115837. &_huff_book_line_1024x27_2sub0,
  115838. &_huff_book_line_1024x27_2sub1,
  115839. &_huff_book_line_1024x27_3sub1,
  115840. &_huff_book_line_1024x27_3sub2,
  115841. &_huff_book_line_1024x27_3sub3,
  115842. &_huff_book_line_1024x27_4sub1,
  115843. &_huff_book_line_1024x27_4sub2,
  115844. &_huff_book_line_1024x27_4sub3,
  115845. };
  115846. static static_codebook *_floor_2048x27_books[]={
  115847. &_huff_book_line_2048x27_class1,
  115848. &_huff_book_line_2048x27_class2,
  115849. &_huff_book_line_2048x27_class3,
  115850. &_huff_book_line_2048x27_class4,
  115851. &_huff_book_line_2048x27_0sub0,
  115852. &_huff_book_line_2048x27_1sub0,
  115853. &_huff_book_line_2048x27_1sub1,
  115854. &_huff_book_line_2048x27_2sub0,
  115855. &_huff_book_line_2048x27_2sub1,
  115856. &_huff_book_line_2048x27_3sub1,
  115857. &_huff_book_line_2048x27_3sub2,
  115858. &_huff_book_line_2048x27_3sub3,
  115859. &_huff_book_line_2048x27_4sub1,
  115860. &_huff_book_line_2048x27_4sub2,
  115861. &_huff_book_line_2048x27_4sub3,
  115862. };
  115863. static static_codebook *_floor_512x17_books[]={
  115864. &_huff_book_line_512x17_class1,
  115865. &_huff_book_line_512x17_class2,
  115866. &_huff_book_line_512x17_class3,
  115867. &_huff_book_line_512x17_0sub0,
  115868. &_huff_book_line_512x17_1sub0,
  115869. &_huff_book_line_512x17_1sub1,
  115870. &_huff_book_line_512x17_2sub1,
  115871. &_huff_book_line_512x17_2sub2,
  115872. &_huff_book_line_512x17_2sub3,
  115873. &_huff_book_line_512x17_3sub1,
  115874. &_huff_book_line_512x17_3sub2,
  115875. &_huff_book_line_512x17_3sub3,
  115876. };
  115877. static static_codebook **_floor_books[10]={
  115878. _floor_128x4_books,
  115879. _floor_256x4_books,
  115880. _floor_128x7_books,
  115881. _floor_256x7_books,
  115882. _floor_128x11_books,
  115883. _floor_128x17_books,
  115884. _floor_256x4low_books,
  115885. _floor_1024x27_books,
  115886. _floor_2048x27_books,
  115887. _floor_512x17_books,
  115888. };
  115889. static vorbis_info_floor1 _floor[10]={
  115890. /* 128 x 4 */
  115891. {
  115892. 1,{0},{4},{2},{0},
  115893. {{1,2,3,4}},
  115894. 4,{0,128, 33,8,16,70},
  115895. 60,30,500, 1.,18., -1
  115896. },
  115897. /* 256 x 4 */
  115898. {
  115899. 1,{0},{4},{2},{0},
  115900. {{1,2,3,4}},
  115901. 4,{0,256, 66,16,32,140},
  115902. 60,30,500, 1.,18., -1
  115903. },
  115904. /* 128 x 7 */
  115905. {
  115906. 2,{0,1},{3,4},{2,2},{0,1},
  115907. {{-1,2,3,4},{-1,5,6,7}},
  115908. 4,{0,128, 14,4,58, 2,8,28,90},
  115909. 60,30,500, 1.,18., -1
  115910. },
  115911. /* 256 x 7 */
  115912. {
  115913. 2,{0,1},{3,4},{2,2},{0,1},
  115914. {{-1,2,3,4},{-1,5,6,7}},
  115915. 4,{0,256, 28,8,116, 4,16,56,180},
  115916. 60,30,500, 1.,18., -1
  115917. },
  115918. /* 128 x 11 */
  115919. {
  115920. 4,{0,1,2,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  115921. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  115922. 2,{0,128, 8,33, 4,16,70, 2,6,12, 23,46,90},
  115923. 60,30,500, 1,18., -1
  115924. },
  115925. /* 128 x 17 */
  115926. {
  115927. 6,{0,1,1,2,3,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  115928. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  115929. 2,{0,128, 12,46, 4,8,16, 23,33,70, 2,6,10, 14,19,28, 39,58,90},
  115930. 60,30,500, 1,18., -1
  115931. },
  115932. /* 256 x 4 (low bitrate version) */
  115933. {
  115934. 1,{0},{4},{2},{0},
  115935. {{1,2,3,4}},
  115936. 4,{0,256, 66,16,32,140},
  115937. 60,30,500, 1.,18., -1
  115938. },
  115939. /* 1024 x 27 */
  115940. {
  115941. 8,{0,1,2,2,3,3,4,4},{3,4,3,4,3},{0,1,1,2,2},{-1,0,1,2,3},
  115942. {{4},{5,6},{7,8},{-1,9,10,11},{-1,12,13,14}},
  115943. 2,{0,1024, 93,23,372, 6,46,186,750, 14,33,65, 130,260,556,
  115944. 3,10,18,28, 39,55,79,111, 158,220,312, 464,650,850},
  115945. 60,30,500, 3,18., -1 /* lowpass */
  115946. },
  115947. /* 2048 x 27 */
  115948. {
  115949. 8,{0,1,2,2,3,3,4,4},{3,4,3,4,3},{0,1,1,2,2},{-1,0,1,2,3},
  115950. {{4},{5,6},{7,8},{-1,9,10,11},{-1,12,13,14}},
  115951. 2,{0,2048, 186,46,744, 12,92,372,1500, 28,66,130, 260,520,1112,
  115952. 6,20,36,56, 78,110,158,222, 316,440,624, 928,1300,1700},
  115953. 60,30,500, 3,18., -1 /* lowpass */
  115954. },
  115955. /* 512 x 17 */
  115956. {
  115957. 6,{0,1,1,2,3,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  115958. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  115959. 2,{0,512, 46,186, 16,33,65, 93,130,278,
  115960. 7,23,39, 55,79,110, 156,232,360},
  115961. 60,30,500, 1,18., -1 /* lowpass! */
  115962. },
  115963. };
  115964. /********* End of inlined file: floor_all.h *********/
  115965. /********* Start of inlined file: residue_44.h *********/
  115966. /********* Start of inlined file: res_books_stereo.h *********/
  115967. static long _vq_quantlist__16c0_s_p1_0[] = {
  115968. 1,
  115969. 0,
  115970. 2,
  115971. };
  115972. static long _vq_lengthlist__16c0_s_p1_0[] = {
  115973. 1, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  115974. 0, 0, 5, 7, 7, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0,
  115979. 0, 0, 0, 7, 9,10, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  115984. 0, 0, 0, 0, 7, 9, 9, 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, 0, 0, 0, 0, 0, 0, 0,
  116005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0,
  116010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0,
  116015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  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, 5, 8, 8, 0, 0, 0, 0,
  116019. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8,10,10, 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, 7,10,10, 0, 0, 0,
  116024. 0, 0, 0, 9, 9,12, 0, 0, 0, 0, 0, 0,10,12,11, 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, 7,10,10, 0, 0,
  116029. 0, 0, 0, 0, 9,12,10, 0, 0, 0, 0, 0, 0,10,11,12,
  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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116051. 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116056. 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0,
  116065. 0, 0, 0, 0, 8,10,10, 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, 7,10,10, 0, 0, 0, 0, 0, 0,10,12,11, 0,
  116070. 0, 0, 0, 0, 0, 9,10,12, 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, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,12,
  116075. 0, 0, 0, 0, 0, 0, 9,12, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116383. 0,
  116384. };
  116385. static float _vq_quantthresh__16c0_s_p1_0[] = {
  116386. -0.5, 0.5,
  116387. };
  116388. static long _vq_quantmap__16c0_s_p1_0[] = {
  116389. 1, 0, 2,
  116390. };
  116391. static encode_aux_threshmatch _vq_auxt__16c0_s_p1_0 = {
  116392. _vq_quantthresh__16c0_s_p1_0,
  116393. _vq_quantmap__16c0_s_p1_0,
  116394. 3,
  116395. 3
  116396. };
  116397. static static_codebook _16c0_s_p1_0 = {
  116398. 8, 6561,
  116399. _vq_lengthlist__16c0_s_p1_0,
  116400. 1, -535822336, 1611661312, 2, 0,
  116401. _vq_quantlist__16c0_s_p1_0,
  116402. NULL,
  116403. &_vq_auxt__16c0_s_p1_0,
  116404. NULL,
  116405. 0
  116406. };
  116407. static long _vq_quantlist__16c0_s_p2_0[] = {
  116408. 2,
  116409. 1,
  116410. 3,
  116411. 0,
  116412. 4,
  116413. };
  116414. static long _vq_lengthlist__16c0_s_p2_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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116454. 0,
  116455. };
  116456. static float _vq_quantthresh__16c0_s_p2_0[] = {
  116457. -1.5, -0.5, 0.5, 1.5,
  116458. };
  116459. static long _vq_quantmap__16c0_s_p2_0[] = {
  116460. 3, 1, 0, 2, 4,
  116461. };
  116462. static encode_aux_threshmatch _vq_auxt__16c0_s_p2_0 = {
  116463. _vq_quantthresh__16c0_s_p2_0,
  116464. _vq_quantmap__16c0_s_p2_0,
  116465. 5,
  116466. 5
  116467. };
  116468. static static_codebook _16c0_s_p2_0 = {
  116469. 4, 625,
  116470. _vq_lengthlist__16c0_s_p2_0,
  116471. 1, -533725184, 1611661312, 3, 0,
  116472. _vq_quantlist__16c0_s_p2_0,
  116473. NULL,
  116474. &_vq_auxt__16c0_s_p2_0,
  116475. NULL,
  116476. 0
  116477. };
  116478. static long _vq_quantlist__16c0_s_p3_0[] = {
  116479. 2,
  116480. 1,
  116481. 3,
  116482. 0,
  116483. 4,
  116484. };
  116485. static long _vq_lengthlist__16c0_s_p3_0[] = {
  116486. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 7, 6, 0, 0,
  116488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116489. 0, 0, 4, 6, 6, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  116491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116492. 0, 0, 0, 0, 6, 6, 6, 9, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116525. 0,
  116526. };
  116527. static float _vq_quantthresh__16c0_s_p3_0[] = {
  116528. -1.5, -0.5, 0.5, 1.5,
  116529. };
  116530. static long _vq_quantmap__16c0_s_p3_0[] = {
  116531. 3, 1, 0, 2, 4,
  116532. };
  116533. static encode_aux_threshmatch _vq_auxt__16c0_s_p3_0 = {
  116534. _vq_quantthresh__16c0_s_p3_0,
  116535. _vq_quantmap__16c0_s_p3_0,
  116536. 5,
  116537. 5
  116538. };
  116539. static static_codebook _16c0_s_p3_0 = {
  116540. 4, 625,
  116541. _vq_lengthlist__16c0_s_p3_0,
  116542. 1, -533725184, 1611661312, 3, 0,
  116543. _vq_quantlist__16c0_s_p3_0,
  116544. NULL,
  116545. &_vq_auxt__16c0_s_p3_0,
  116546. NULL,
  116547. 0
  116548. };
  116549. static long _vq_quantlist__16c0_s_p4_0[] = {
  116550. 4,
  116551. 3,
  116552. 5,
  116553. 2,
  116554. 6,
  116555. 1,
  116556. 7,
  116557. 0,
  116558. 8,
  116559. };
  116560. static long _vq_lengthlist__16c0_s_p4_0[] = {
  116561. 1, 3, 2, 7, 8, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  116562. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  116563. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  116564. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  116565. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116566. 0,
  116567. };
  116568. static float _vq_quantthresh__16c0_s_p4_0[] = {
  116569. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  116570. };
  116571. static long _vq_quantmap__16c0_s_p4_0[] = {
  116572. 7, 5, 3, 1, 0, 2, 4, 6,
  116573. 8,
  116574. };
  116575. static encode_aux_threshmatch _vq_auxt__16c0_s_p4_0 = {
  116576. _vq_quantthresh__16c0_s_p4_0,
  116577. _vq_quantmap__16c0_s_p4_0,
  116578. 9,
  116579. 9
  116580. };
  116581. static static_codebook _16c0_s_p4_0 = {
  116582. 2, 81,
  116583. _vq_lengthlist__16c0_s_p4_0,
  116584. 1, -531628032, 1611661312, 4, 0,
  116585. _vq_quantlist__16c0_s_p4_0,
  116586. NULL,
  116587. &_vq_auxt__16c0_s_p4_0,
  116588. NULL,
  116589. 0
  116590. };
  116591. static long _vq_quantlist__16c0_s_p5_0[] = {
  116592. 4,
  116593. 3,
  116594. 5,
  116595. 2,
  116596. 6,
  116597. 1,
  116598. 7,
  116599. 0,
  116600. 8,
  116601. };
  116602. static long _vq_lengthlist__16c0_s_p5_0[] = {
  116603. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  116604. 8, 8, 0, 0, 0, 7, 7, 7, 7, 8, 8, 0, 0, 0, 7, 7,
  116605. 8, 8, 9, 9, 0, 0, 0, 7, 7, 8, 8, 9, 9, 0, 0, 0,
  116606. 8, 9, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  116607. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  116608. 10,
  116609. };
  116610. static float _vq_quantthresh__16c0_s_p5_0[] = {
  116611. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  116612. };
  116613. static long _vq_quantmap__16c0_s_p5_0[] = {
  116614. 7, 5, 3, 1, 0, 2, 4, 6,
  116615. 8,
  116616. };
  116617. static encode_aux_threshmatch _vq_auxt__16c0_s_p5_0 = {
  116618. _vq_quantthresh__16c0_s_p5_0,
  116619. _vq_quantmap__16c0_s_p5_0,
  116620. 9,
  116621. 9
  116622. };
  116623. static static_codebook _16c0_s_p5_0 = {
  116624. 2, 81,
  116625. _vq_lengthlist__16c0_s_p5_0,
  116626. 1, -531628032, 1611661312, 4, 0,
  116627. _vq_quantlist__16c0_s_p5_0,
  116628. NULL,
  116629. &_vq_auxt__16c0_s_p5_0,
  116630. NULL,
  116631. 0
  116632. };
  116633. static long _vq_quantlist__16c0_s_p6_0[] = {
  116634. 8,
  116635. 7,
  116636. 9,
  116637. 6,
  116638. 10,
  116639. 5,
  116640. 11,
  116641. 4,
  116642. 12,
  116643. 3,
  116644. 13,
  116645. 2,
  116646. 14,
  116647. 1,
  116648. 15,
  116649. 0,
  116650. 16,
  116651. };
  116652. static long _vq_lengthlist__16c0_s_p6_0[] = {
  116653. 1, 3, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  116654. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,11,
  116655. 11,11, 0, 0, 0, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  116656. 11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  116657. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  116658. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  116659. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  116660. 10,11,11,12,12,12,13, 0, 0, 0, 9, 9, 9, 9,10,10,
  116661. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,10,10,10,
  116662. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  116663. 10,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0, 0, 9,
  116664. 9,10,10,11,11,12,12,13,13,13,14, 0, 0, 0, 0, 0,
  116665. 10,10,10,11,11,11,12,12,13,13,13,14, 0, 0, 0, 0,
  116666. 0, 0, 0,10,10,11,11,12,12,13,13,14,14, 0, 0, 0,
  116667. 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0, 0,
  116668. 0, 0, 0, 0, 0,11,11,12,12,12,13,13,14,15,14, 0,
  116669. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,14,14,15,
  116670. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,14,13,14,
  116671. 14,
  116672. };
  116673. static float _vq_quantthresh__16c0_s_p6_0[] = {
  116674. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  116675. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  116676. };
  116677. static long _vq_quantmap__16c0_s_p6_0[] = {
  116678. 15, 13, 11, 9, 7, 5, 3, 1,
  116679. 0, 2, 4, 6, 8, 10, 12, 14,
  116680. 16,
  116681. };
  116682. static encode_aux_threshmatch _vq_auxt__16c0_s_p6_0 = {
  116683. _vq_quantthresh__16c0_s_p6_0,
  116684. _vq_quantmap__16c0_s_p6_0,
  116685. 17,
  116686. 17
  116687. };
  116688. static static_codebook _16c0_s_p6_0 = {
  116689. 2, 289,
  116690. _vq_lengthlist__16c0_s_p6_0,
  116691. 1, -529530880, 1611661312, 5, 0,
  116692. _vq_quantlist__16c0_s_p6_0,
  116693. NULL,
  116694. &_vq_auxt__16c0_s_p6_0,
  116695. NULL,
  116696. 0
  116697. };
  116698. static long _vq_quantlist__16c0_s_p7_0[] = {
  116699. 1,
  116700. 0,
  116701. 2,
  116702. };
  116703. static long _vq_lengthlist__16c0_s_p7_0[] = {
  116704. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,11,10,10,11,
  116705. 11,10, 4, 7, 7,10,10,10,11,10,10, 6,10,10,11,11,
  116706. 11,11,11,10, 6, 9, 9,11,12,12,11, 9, 9, 6, 9,10,
  116707. 11,12,12,11, 9,10, 7,11,11,11,11,11,12,13,12, 6,
  116708. 9,10,11,10,10,12,13,13, 6,10, 9,11,10,10,11,12,
  116709. 13,
  116710. };
  116711. static float _vq_quantthresh__16c0_s_p7_0[] = {
  116712. -5.5, 5.5,
  116713. };
  116714. static long _vq_quantmap__16c0_s_p7_0[] = {
  116715. 1, 0, 2,
  116716. };
  116717. static encode_aux_threshmatch _vq_auxt__16c0_s_p7_0 = {
  116718. _vq_quantthresh__16c0_s_p7_0,
  116719. _vq_quantmap__16c0_s_p7_0,
  116720. 3,
  116721. 3
  116722. };
  116723. static static_codebook _16c0_s_p7_0 = {
  116724. 4, 81,
  116725. _vq_lengthlist__16c0_s_p7_0,
  116726. 1, -529137664, 1618345984, 2, 0,
  116727. _vq_quantlist__16c0_s_p7_0,
  116728. NULL,
  116729. &_vq_auxt__16c0_s_p7_0,
  116730. NULL,
  116731. 0
  116732. };
  116733. static long _vq_quantlist__16c0_s_p7_1[] = {
  116734. 5,
  116735. 4,
  116736. 6,
  116737. 3,
  116738. 7,
  116739. 2,
  116740. 8,
  116741. 1,
  116742. 9,
  116743. 0,
  116744. 10,
  116745. };
  116746. static long _vq_lengthlist__16c0_s_p7_1[] = {
  116747. 1, 3, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7,
  116748. 8, 8, 8, 9, 9, 9,10,10,10, 6, 7, 8, 8, 8, 8, 9,
  116749. 8,10,10,10, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10, 7,
  116750. 7, 8, 8, 9, 9, 8, 9,10,10,10, 8, 8, 9, 9, 9, 9,
  116751. 9, 9,11,11,11, 8, 8, 9, 9, 9, 9, 9,10,10,11,11,
  116752. 9, 9, 9, 9, 9, 9, 9,10,11,11,11,10,11, 9, 9, 9,
  116753. 9,10, 9,11,11,11,10,11,10,10, 9, 9,10,10,11,11,
  116754. 11,11,11, 9, 9, 9, 9,10,10,
  116755. };
  116756. static float _vq_quantthresh__16c0_s_p7_1[] = {
  116757. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  116758. 3.5, 4.5,
  116759. };
  116760. static long _vq_quantmap__16c0_s_p7_1[] = {
  116761. 9, 7, 5, 3, 1, 0, 2, 4,
  116762. 6, 8, 10,
  116763. };
  116764. static encode_aux_threshmatch _vq_auxt__16c0_s_p7_1 = {
  116765. _vq_quantthresh__16c0_s_p7_1,
  116766. _vq_quantmap__16c0_s_p7_1,
  116767. 11,
  116768. 11
  116769. };
  116770. static static_codebook _16c0_s_p7_1 = {
  116771. 2, 121,
  116772. _vq_lengthlist__16c0_s_p7_1,
  116773. 1, -531365888, 1611661312, 4, 0,
  116774. _vq_quantlist__16c0_s_p7_1,
  116775. NULL,
  116776. &_vq_auxt__16c0_s_p7_1,
  116777. NULL,
  116778. 0
  116779. };
  116780. static long _vq_quantlist__16c0_s_p8_0[] = {
  116781. 6,
  116782. 5,
  116783. 7,
  116784. 4,
  116785. 8,
  116786. 3,
  116787. 9,
  116788. 2,
  116789. 10,
  116790. 1,
  116791. 11,
  116792. 0,
  116793. 12,
  116794. };
  116795. static long _vq_lengthlist__16c0_s_p8_0[] = {
  116796. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8,10,10, 6, 5, 6,
  116797. 8, 8, 8, 8, 8, 8, 8, 9,10,10, 7, 6, 6, 8, 8, 8,
  116798. 8, 8, 8, 8, 8,10,10, 0, 8, 8, 8, 8, 9, 8, 9, 9,
  116799. 9,10,10,10, 0, 9, 8, 8, 8, 9, 9, 8, 8, 9, 9,10,
  116800. 10, 0,12,11, 8, 8, 9, 9, 9, 9,10,10,11,10, 0,12,
  116801. 13, 8, 8, 9,10, 9, 9,11,11,11,12, 0, 0, 0, 8, 8,
  116802. 8, 8,10, 9,12,13,12,14, 0, 0, 0, 8, 8, 8, 9,10,
  116803. 10,12,12,13,14, 0, 0, 0,13,13, 9, 9,11,11, 0, 0,
  116804. 14, 0, 0, 0, 0,14,14,10,10,12,11,12,14,14,14, 0,
  116805. 0, 0, 0, 0,11,11,13,13,14,13,14,14, 0, 0, 0, 0,
  116806. 0,12,13,13,12,13,14,14,14,
  116807. };
  116808. static float _vq_quantthresh__16c0_s_p8_0[] = {
  116809. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  116810. 12.5, 17.5, 22.5, 27.5,
  116811. };
  116812. static long _vq_quantmap__16c0_s_p8_0[] = {
  116813. 11, 9, 7, 5, 3, 1, 0, 2,
  116814. 4, 6, 8, 10, 12,
  116815. };
  116816. static encode_aux_threshmatch _vq_auxt__16c0_s_p8_0 = {
  116817. _vq_quantthresh__16c0_s_p8_0,
  116818. _vq_quantmap__16c0_s_p8_0,
  116819. 13,
  116820. 13
  116821. };
  116822. static static_codebook _16c0_s_p8_0 = {
  116823. 2, 169,
  116824. _vq_lengthlist__16c0_s_p8_0,
  116825. 1, -526516224, 1616117760, 4, 0,
  116826. _vq_quantlist__16c0_s_p8_0,
  116827. NULL,
  116828. &_vq_auxt__16c0_s_p8_0,
  116829. NULL,
  116830. 0
  116831. };
  116832. static long _vq_quantlist__16c0_s_p8_1[] = {
  116833. 2,
  116834. 1,
  116835. 3,
  116836. 0,
  116837. 4,
  116838. };
  116839. static long _vq_lengthlist__16c0_s_p8_1[] = {
  116840. 1, 4, 3, 5, 5, 7, 7, 7, 6, 6, 7, 7, 7, 5, 5, 7,
  116841. 7, 7, 6, 6, 7, 7, 7, 6, 6,
  116842. };
  116843. static float _vq_quantthresh__16c0_s_p8_1[] = {
  116844. -1.5, -0.5, 0.5, 1.5,
  116845. };
  116846. static long _vq_quantmap__16c0_s_p8_1[] = {
  116847. 3, 1, 0, 2, 4,
  116848. };
  116849. static encode_aux_threshmatch _vq_auxt__16c0_s_p8_1 = {
  116850. _vq_quantthresh__16c0_s_p8_1,
  116851. _vq_quantmap__16c0_s_p8_1,
  116852. 5,
  116853. 5
  116854. };
  116855. static static_codebook _16c0_s_p8_1 = {
  116856. 2, 25,
  116857. _vq_lengthlist__16c0_s_p8_1,
  116858. 1, -533725184, 1611661312, 3, 0,
  116859. _vq_quantlist__16c0_s_p8_1,
  116860. NULL,
  116861. &_vq_auxt__16c0_s_p8_1,
  116862. NULL,
  116863. 0
  116864. };
  116865. static long _vq_quantlist__16c0_s_p9_0[] = {
  116866. 1,
  116867. 0,
  116868. 2,
  116869. };
  116870. static long _vq_lengthlist__16c0_s_p9_0[] = {
  116871. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  116872. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  116873. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  116874. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  116875. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  116876. 7,
  116877. };
  116878. static float _vq_quantthresh__16c0_s_p9_0[] = {
  116879. -157.5, 157.5,
  116880. };
  116881. static long _vq_quantmap__16c0_s_p9_0[] = {
  116882. 1, 0, 2,
  116883. };
  116884. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_0 = {
  116885. _vq_quantthresh__16c0_s_p9_0,
  116886. _vq_quantmap__16c0_s_p9_0,
  116887. 3,
  116888. 3
  116889. };
  116890. static static_codebook _16c0_s_p9_0 = {
  116891. 4, 81,
  116892. _vq_lengthlist__16c0_s_p9_0,
  116893. 1, -518803456, 1628680192, 2, 0,
  116894. _vq_quantlist__16c0_s_p9_0,
  116895. NULL,
  116896. &_vq_auxt__16c0_s_p9_0,
  116897. NULL,
  116898. 0
  116899. };
  116900. static long _vq_quantlist__16c0_s_p9_1[] = {
  116901. 7,
  116902. 6,
  116903. 8,
  116904. 5,
  116905. 9,
  116906. 4,
  116907. 10,
  116908. 3,
  116909. 11,
  116910. 2,
  116911. 12,
  116912. 1,
  116913. 13,
  116914. 0,
  116915. 14,
  116916. };
  116917. static long _vq_lengthlist__16c0_s_p9_1[] = {
  116918. 1, 5, 5, 5, 5, 9,11,11,10,10,10,10,10,10,10, 7,
  116919. 6, 6, 6, 6,10,10,10,10,10,10,10,10,10,10, 7, 6,
  116920. 6, 6, 6,10, 9,10,10,10,10,10,10,10,10,10, 7, 7,
  116921. 8, 9,10,10,10,10,10,10,10,10,10,10,10, 8, 7,10,
  116922. 10,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,
  116923. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  116924. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  116925. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  116926. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  116927. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  116928. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  116929. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  116930. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  116931. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  116932. 10,
  116933. };
  116934. static float _vq_quantthresh__16c0_s_p9_1[] = {
  116935. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  116936. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  116937. };
  116938. static long _vq_quantmap__16c0_s_p9_1[] = {
  116939. 13, 11, 9, 7, 5, 3, 1, 0,
  116940. 2, 4, 6, 8, 10, 12, 14,
  116941. };
  116942. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_1 = {
  116943. _vq_quantthresh__16c0_s_p9_1,
  116944. _vq_quantmap__16c0_s_p9_1,
  116945. 15,
  116946. 15
  116947. };
  116948. static static_codebook _16c0_s_p9_1 = {
  116949. 2, 225,
  116950. _vq_lengthlist__16c0_s_p9_1,
  116951. 1, -520986624, 1620377600, 4, 0,
  116952. _vq_quantlist__16c0_s_p9_1,
  116953. NULL,
  116954. &_vq_auxt__16c0_s_p9_1,
  116955. NULL,
  116956. 0
  116957. };
  116958. static long _vq_quantlist__16c0_s_p9_2[] = {
  116959. 10,
  116960. 9,
  116961. 11,
  116962. 8,
  116963. 12,
  116964. 7,
  116965. 13,
  116966. 6,
  116967. 14,
  116968. 5,
  116969. 15,
  116970. 4,
  116971. 16,
  116972. 3,
  116973. 17,
  116974. 2,
  116975. 18,
  116976. 1,
  116977. 19,
  116978. 0,
  116979. 20,
  116980. };
  116981. static long _vq_lengthlist__16c0_s_p9_2[] = {
  116982. 1, 5, 5, 7, 8, 8, 7, 9, 9, 9,12,12,11,12,12,10,
  116983. 10,11,12,12,12,11,12,12, 8, 9, 8, 7, 9,10,10,11,
  116984. 11,10,11,12,10,12,10,12,12,12,11,12,11, 9, 8, 8,
  116985. 9,10, 9, 8, 9,10,12,12,11,11,12,11,10,11,12,11,
  116986. 12,12, 8, 9, 9, 9,10,11,12,11,12,11,11,11,11,12,
  116987. 12,11,11,12,12,11,11, 9, 9, 8, 9, 9,11, 9, 9,10,
  116988. 9,11,11,11,11,12,11,11,10,12,12,12, 9,12,11,10,
  116989. 11,11,11,11,12,12,12,11,11,11,12,10,12,12,12,10,
  116990. 10, 9,10, 9,10,10, 9, 9, 9,10,10,12,10,11,11, 9,
  116991. 11,11,10,11,11,11,10,10,10, 9, 9,10,10, 9, 9,10,
  116992. 11,11,10,11,10,11,10,11,11,10,11,11,11,10, 9,10,
  116993. 10, 9,10, 9, 9,11, 9, 9,11,10,10,11,11,10,10,11,
  116994. 10,11, 8, 9,11,11,10, 9,10,11,11,10,11,11,10,10,
  116995. 10,11,10, 9,10,10,11, 9,10,10, 9,11,10,10,10,10,
  116996. 11,10,11,11, 9,11,10,11,10,10,11,11,10,10,10, 9,
  116997. 10,10,11,11,11, 9,10,10,10,10,10,11,10,10,10, 9,
  116998. 10,10,11,10,10,10,10,10, 9,10,11,10,10,10,10,11,
  116999. 11,11,10,10,10,10,10,11,10,11,10,11,10,10,10, 9,
  117000. 11,11,10,10,10,11,11,10,10,10,10,10,10,10,10,11,
  117001. 11, 9,10,10,10,11,10,11,10,10,10,11, 9,10,11,10,
  117002. 11,10,10, 9,10,10,10,11,10,11,10,10,10,10,10,11,
  117003. 11,10,11,11,10,10,11,11,10, 9, 9,10,10,10,10,10,
  117004. 9,11, 9,10,10,10,11,11,10,10,10,10,11,11,11,10,
  117005. 9, 9,10,10,11,10,10,10,10,10,11,11,11,10,10,10,
  117006. 11,11,11, 9,10,10,10,10, 9,10, 9,10,11,10,11,10,
  117007. 10,11,11,10,11,11,11,11,11,10,11,10,10,10, 9,11,
  117008. 11,10,11,11,11,11,11,11,11,11,11,10,11,10,10,10,
  117009. 10,11,10,10,11, 9,10,10,10,
  117010. };
  117011. static float _vq_quantthresh__16c0_s_p9_2[] = {
  117012. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  117013. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  117014. 6.5, 7.5, 8.5, 9.5,
  117015. };
  117016. static long _vq_quantmap__16c0_s_p9_2[] = {
  117017. 19, 17, 15, 13, 11, 9, 7, 5,
  117018. 3, 1, 0, 2, 4, 6, 8, 10,
  117019. 12, 14, 16, 18, 20,
  117020. };
  117021. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_2 = {
  117022. _vq_quantthresh__16c0_s_p9_2,
  117023. _vq_quantmap__16c0_s_p9_2,
  117024. 21,
  117025. 21
  117026. };
  117027. static static_codebook _16c0_s_p9_2 = {
  117028. 2, 441,
  117029. _vq_lengthlist__16c0_s_p9_2,
  117030. 1, -529268736, 1611661312, 5, 0,
  117031. _vq_quantlist__16c0_s_p9_2,
  117032. NULL,
  117033. &_vq_auxt__16c0_s_p9_2,
  117034. NULL,
  117035. 0
  117036. };
  117037. static long _huff_lengthlist__16c0_s_single[] = {
  117038. 3, 4,19, 7, 9, 7, 8,11, 9,12, 4, 1,19, 6, 7, 7,
  117039. 8,10,11,13,18,18,18,18,18,18,18,18,18,18, 8, 6,
  117040. 18, 8, 9, 9,11,12,14,18, 9, 6,18, 9, 7, 8, 9,11,
  117041. 12,18, 7, 6,18, 8, 7, 7, 7, 9,11,17, 8, 8,18, 9,
  117042. 7, 6, 6, 8,11,17,10,10,18,12, 9, 8, 7, 9,12,18,
  117043. 13,15,18,15,13,11,10,11,15,18,14,18,18,18,18,18,
  117044. 16,16,18,18,
  117045. };
  117046. static static_codebook _huff_book__16c0_s_single = {
  117047. 2, 100,
  117048. _huff_lengthlist__16c0_s_single,
  117049. 0, 0, 0, 0, 0,
  117050. NULL,
  117051. NULL,
  117052. NULL,
  117053. NULL,
  117054. 0
  117055. };
  117056. static long _huff_lengthlist__16c1_s_long[] = {
  117057. 2, 5,20, 7,10, 7, 8,10,11,11, 4, 2,20, 5, 8, 6,
  117058. 7, 9,10,10,20,20,20,20,19,19,19,19,19,19, 7, 5,
  117059. 19, 6,10, 7, 9,11,13,17,11, 8,19,10, 7, 7, 8,10,
  117060. 11,15, 7, 5,19, 7, 7, 5, 6, 9,11,16, 7, 6,19, 8,
  117061. 7, 6, 6, 7, 9,13, 9, 9,19,11, 9, 8, 6, 7, 8,13,
  117062. 12,14,19,16,13,10, 9, 8, 9,13,14,17,19,18,18,17,
  117063. 12,11,11,13,
  117064. };
  117065. static static_codebook _huff_book__16c1_s_long = {
  117066. 2, 100,
  117067. _huff_lengthlist__16c1_s_long,
  117068. 0, 0, 0, 0, 0,
  117069. NULL,
  117070. NULL,
  117071. NULL,
  117072. NULL,
  117073. 0
  117074. };
  117075. static long _vq_quantlist__16c1_s_p1_0[] = {
  117076. 1,
  117077. 0,
  117078. 2,
  117079. };
  117080. static long _vq_lengthlist__16c1_s_p1_0[] = {
  117081. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  117082. 0, 0, 5, 7, 7, 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, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  117087. 0, 0, 0, 7, 8, 9, 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, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  117092. 0, 0, 0, 0, 7, 9, 9, 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, 0, 0, 0, 0, 0, 0, 0,
  117113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0,
  117118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0,
  117123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  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, 5, 8, 7, 0, 0, 0, 0,
  117127. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 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, 7, 9, 9, 0, 0, 0,
  117132. 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0, 9,11,10, 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, 7, 9, 9, 0, 0,
  117137. 0, 0, 0, 0, 8,11, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117159. 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117164. 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  117173. 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  117178. 0, 0, 0, 0, 0, 8, 9,11, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  117183. 0, 0, 0, 0, 0, 0, 9,11, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117491. 0,
  117492. };
  117493. static float _vq_quantthresh__16c1_s_p1_0[] = {
  117494. -0.5, 0.5,
  117495. };
  117496. static long _vq_quantmap__16c1_s_p1_0[] = {
  117497. 1, 0, 2,
  117498. };
  117499. static encode_aux_threshmatch _vq_auxt__16c1_s_p1_0 = {
  117500. _vq_quantthresh__16c1_s_p1_0,
  117501. _vq_quantmap__16c1_s_p1_0,
  117502. 3,
  117503. 3
  117504. };
  117505. static static_codebook _16c1_s_p1_0 = {
  117506. 8, 6561,
  117507. _vq_lengthlist__16c1_s_p1_0,
  117508. 1, -535822336, 1611661312, 2, 0,
  117509. _vq_quantlist__16c1_s_p1_0,
  117510. NULL,
  117511. &_vq_auxt__16c1_s_p1_0,
  117512. NULL,
  117513. 0
  117514. };
  117515. static long _vq_quantlist__16c1_s_p2_0[] = {
  117516. 2,
  117517. 1,
  117518. 3,
  117519. 0,
  117520. 4,
  117521. };
  117522. static long _vq_lengthlist__16c1_s_p2_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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117562. 0,
  117563. };
  117564. static float _vq_quantthresh__16c1_s_p2_0[] = {
  117565. -1.5, -0.5, 0.5, 1.5,
  117566. };
  117567. static long _vq_quantmap__16c1_s_p2_0[] = {
  117568. 3, 1, 0, 2, 4,
  117569. };
  117570. static encode_aux_threshmatch _vq_auxt__16c1_s_p2_0 = {
  117571. _vq_quantthresh__16c1_s_p2_0,
  117572. _vq_quantmap__16c1_s_p2_0,
  117573. 5,
  117574. 5
  117575. };
  117576. static static_codebook _16c1_s_p2_0 = {
  117577. 4, 625,
  117578. _vq_lengthlist__16c1_s_p2_0,
  117579. 1, -533725184, 1611661312, 3, 0,
  117580. _vq_quantlist__16c1_s_p2_0,
  117581. NULL,
  117582. &_vq_auxt__16c1_s_p2_0,
  117583. NULL,
  117584. 0
  117585. };
  117586. static long _vq_quantlist__16c1_s_p3_0[] = {
  117587. 2,
  117588. 1,
  117589. 3,
  117590. 0,
  117591. 4,
  117592. };
  117593. static long _vq_lengthlist__16c1_s_p3_0[] = {
  117594. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  117596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117597. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 7, 7, 9, 9,
  117599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117600. 0, 0, 0, 0, 6, 7, 7, 9, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117633. 0,
  117634. };
  117635. static float _vq_quantthresh__16c1_s_p3_0[] = {
  117636. -1.5, -0.5, 0.5, 1.5,
  117637. };
  117638. static long _vq_quantmap__16c1_s_p3_0[] = {
  117639. 3, 1, 0, 2, 4,
  117640. };
  117641. static encode_aux_threshmatch _vq_auxt__16c1_s_p3_0 = {
  117642. _vq_quantthresh__16c1_s_p3_0,
  117643. _vq_quantmap__16c1_s_p3_0,
  117644. 5,
  117645. 5
  117646. };
  117647. static static_codebook _16c1_s_p3_0 = {
  117648. 4, 625,
  117649. _vq_lengthlist__16c1_s_p3_0,
  117650. 1, -533725184, 1611661312, 3, 0,
  117651. _vq_quantlist__16c1_s_p3_0,
  117652. NULL,
  117653. &_vq_auxt__16c1_s_p3_0,
  117654. NULL,
  117655. 0
  117656. };
  117657. static long _vq_quantlist__16c1_s_p4_0[] = {
  117658. 4,
  117659. 3,
  117660. 5,
  117661. 2,
  117662. 6,
  117663. 1,
  117664. 7,
  117665. 0,
  117666. 8,
  117667. };
  117668. static long _vq_lengthlist__16c1_s_p4_0[] = {
  117669. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  117670. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  117671. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  117672. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 9, 0, 0, 0, 0, 0,
  117673. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  117674. 0,
  117675. };
  117676. static float _vq_quantthresh__16c1_s_p4_0[] = {
  117677. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  117678. };
  117679. static long _vq_quantmap__16c1_s_p4_0[] = {
  117680. 7, 5, 3, 1, 0, 2, 4, 6,
  117681. 8,
  117682. };
  117683. static encode_aux_threshmatch _vq_auxt__16c1_s_p4_0 = {
  117684. _vq_quantthresh__16c1_s_p4_0,
  117685. _vq_quantmap__16c1_s_p4_0,
  117686. 9,
  117687. 9
  117688. };
  117689. static static_codebook _16c1_s_p4_0 = {
  117690. 2, 81,
  117691. _vq_lengthlist__16c1_s_p4_0,
  117692. 1, -531628032, 1611661312, 4, 0,
  117693. _vq_quantlist__16c1_s_p4_0,
  117694. NULL,
  117695. &_vq_auxt__16c1_s_p4_0,
  117696. NULL,
  117697. 0
  117698. };
  117699. static long _vq_quantlist__16c1_s_p5_0[] = {
  117700. 4,
  117701. 3,
  117702. 5,
  117703. 2,
  117704. 6,
  117705. 1,
  117706. 7,
  117707. 0,
  117708. 8,
  117709. };
  117710. static long _vq_lengthlist__16c1_s_p5_0[] = {
  117711. 1, 3, 3, 5, 5, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  117712. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 8, 8,
  117713. 8, 8, 9, 9, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  117714. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  117715. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  117716. 10,
  117717. };
  117718. static float _vq_quantthresh__16c1_s_p5_0[] = {
  117719. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  117720. };
  117721. static long _vq_quantmap__16c1_s_p5_0[] = {
  117722. 7, 5, 3, 1, 0, 2, 4, 6,
  117723. 8,
  117724. };
  117725. static encode_aux_threshmatch _vq_auxt__16c1_s_p5_0 = {
  117726. _vq_quantthresh__16c1_s_p5_0,
  117727. _vq_quantmap__16c1_s_p5_0,
  117728. 9,
  117729. 9
  117730. };
  117731. static static_codebook _16c1_s_p5_0 = {
  117732. 2, 81,
  117733. _vq_lengthlist__16c1_s_p5_0,
  117734. 1, -531628032, 1611661312, 4, 0,
  117735. _vq_quantlist__16c1_s_p5_0,
  117736. NULL,
  117737. &_vq_auxt__16c1_s_p5_0,
  117738. NULL,
  117739. 0
  117740. };
  117741. static long _vq_quantlist__16c1_s_p6_0[] = {
  117742. 8,
  117743. 7,
  117744. 9,
  117745. 6,
  117746. 10,
  117747. 5,
  117748. 11,
  117749. 4,
  117750. 12,
  117751. 3,
  117752. 13,
  117753. 2,
  117754. 14,
  117755. 1,
  117756. 15,
  117757. 0,
  117758. 16,
  117759. };
  117760. static long _vq_lengthlist__16c1_s_p6_0[] = {
  117761. 1, 3, 3, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,12,
  117762. 12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  117763. 12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  117764. 11,12,12, 0, 0, 0, 8, 8, 8, 9,10, 9,10,10,10,10,
  117765. 11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,11,
  117766. 11,11,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  117767. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  117768. 10,11,11,12,12,13,13, 0, 0, 0, 9, 9, 9, 9,10,10,
  117769. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  117770. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  117771. 10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0, 9,
  117772. 9,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0,
  117773. 10,10,11,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0,
  117774. 0, 0, 0,10,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  117775. 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0, 0,
  117776. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0,
  117777. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  117778. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  117779. 14,
  117780. };
  117781. static float _vq_quantthresh__16c1_s_p6_0[] = {
  117782. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  117783. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  117784. };
  117785. static long _vq_quantmap__16c1_s_p6_0[] = {
  117786. 15, 13, 11, 9, 7, 5, 3, 1,
  117787. 0, 2, 4, 6, 8, 10, 12, 14,
  117788. 16,
  117789. };
  117790. static encode_aux_threshmatch _vq_auxt__16c1_s_p6_0 = {
  117791. _vq_quantthresh__16c1_s_p6_0,
  117792. _vq_quantmap__16c1_s_p6_0,
  117793. 17,
  117794. 17
  117795. };
  117796. static static_codebook _16c1_s_p6_0 = {
  117797. 2, 289,
  117798. _vq_lengthlist__16c1_s_p6_0,
  117799. 1, -529530880, 1611661312, 5, 0,
  117800. _vq_quantlist__16c1_s_p6_0,
  117801. NULL,
  117802. &_vq_auxt__16c1_s_p6_0,
  117803. NULL,
  117804. 0
  117805. };
  117806. static long _vq_quantlist__16c1_s_p7_0[] = {
  117807. 1,
  117808. 0,
  117809. 2,
  117810. };
  117811. static long _vq_lengthlist__16c1_s_p7_0[] = {
  117812. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,10, 9,10,10,
  117813. 10, 9, 4, 7, 7,10,10,10,11,10,10, 6,10,10,11,11,
  117814. 11,11,10,10, 6,10, 9,11,11,11,11,10,10, 6,10,10,
  117815. 11,11,11,11,10,10, 7,11,11,11,11,11,12,12,11, 6,
  117816. 10,10,11,10,10,11,11,11, 6,10,10,10,11,10,11,11,
  117817. 11,
  117818. };
  117819. static float _vq_quantthresh__16c1_s_p7_0[] = {
  117820. -5.5, 5.5,
  117821. };
  117822. static long _vq_quantmap__16c1_s_p7_0[] = {
  117823. 1, 0, 2,
  117824. };
  117825. static encode_aux_threshmatch _vq_auxt__16c1_s_p7_0 = {
  117826. _vq_quantthresh__16c1_s_p7_0,
  117827. _vq_quantmap__16c1_s_p7_0,
  117828. 3,
  117829. 3
  117830. };
  117831. static static_codebook _16c1_s_p7_0 = {
  117832. 4, 81,
  117833. _vq_lengthlist__16c1_s_p7_0,
  117834. 1, -529137664, 1618345984, 2, 0,
  117835. _vq_quantlist__16c1_s_p7_0,
  117836. NULL,
  117837. &_vq_auxt__16c1_s_p7_0,
  117838. NULL,
  117839. 0
  117840. };
  117841. static long _vq_quantlist__16c1_s_p7_1[] = {
  117842. 5,
  117843. 4,
  117844. 6,
  117845. 3,
  117846. 7,
  117847. 2,
  117848. 8,
  117849. 1,
  117850. 9,
  117851. 0,
  117852. 10,
  117853. };
  117854. static long _vq_lengthlist__16c1_s_p7_1[] = {
  117855. 2, 3, 3, 5, 6, 7, 7, 7, 7, 8, 8,10,10,10, 6, 6,
  117856. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  117857. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  117858. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  117859. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  117860. 8, 8, 8, 8, 8, 8, 9, 9,10,10,10,10,10, 8, 8, 8,
  117861. 8, 9, 9,10,10,10,10,10, 9, 9, 8, 8, 9, 9,10,10,
  117862. 10,10,10, 8, 8, 8, 8, 9, 9,
  117863. };
  117864. static float _vq_quantthresh__16c1_s_p7_1[] = {
  117865. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  117866. 3.5, 4.5,
  117867. };
  117868. static long _vq_quantmap__16c1_s_p7_1[] = {
  117869. 9, 7, 5, 3, 1, 0, 2, 4,
  117870. 6, 8, 10,
  117871. };
  117872. static encode_aux_threshmatch _vq_auxt__16c1_s_p7_1 = {
  117873. _vq_quantthresh__16c1_s_p7_1,
  117874. _vq_quantmap__16c1_s_p7_1,
  117875. 11,
  117876. 11
  117877. };
  117878. static static_codebook _16c1_s_p7_1 = {
  117879. 2, 121,
  117880. _vq_lengthlist__16c1_s_p7_1,
  117881. 1, -531365888, 1611661312, 4, 0,
  117882. _vq_quantlist__16c1_s_p7_1,
  117883. NULL,
  117884. &_vq_auxt__16c1_s_p7_1,
  117885. NULL,
  117886. 0
  117887. };
  117888. static long _vq_quantlist__16c1_s_p8_0[] = {
  117889. 6,
  117890. 5,
  117891. 7,
  117892. 4,
  117893. 8,
  117894. 3,
  117895. 9,
  117896. 2,
  117897. 10,
  117898. 1,
  117899. 11,
  117900. 0,
  117901. 12,
  117902. };
  117903. static long _vq_lengthlist__16c1_s_p8_0[] = {
  117904. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 6, 5, 5,
  117905. 7, 8, 8, 9, 8, 8, 9, 9,10,11, 6, 5, 5, 8, 8, 9,
  117906. 9, 8, 8, 9,10,10,11, 0, 8, 8, 8, 9, 9, 9, 9, 9,
  117907. 10,10,11,11, 0, 9, 9, 9, 8, 9, 9, 9, 9,10,10,11,
  117908. 11, 0,13,13, 9, 9,10,10,10,10,11,11,12,12, 0,14,
  117909. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  117910. 9, 9,11,11,12,12,13,12, 0, 0, 0,10,10, 9, 9,10,
  117911. 10,12,12,13,13, 0, 0, 0,13,14,11,10,11,11,12,12,
  117912. 13,14, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  117913. 0, 0, 0, 0,12,12,12,12,13,13,14,15, 0, 0, 0, 0,
  117914. 0,12,12,12,12,13,13,14,15,
  117915. };
  117916. static float _vq_quantthresh__16c1_s_p8_0[] = {
  117917. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  117918. 12.5, 17.5, 22.5, 27.5,
  117919. };
  117920. static long _vq_quantmap__16c1_s_p8_0[] = {
  117921. 11, 9, 7, 5, 3, 1, 0, 2,
  117922. 4, 6, 8, 10, 12,
  117923. };
  117924. static encode_aux_threshmatch _vq_auxt__16c1_s_p8_0 = {
  117925. _vq_quantthresh__16c1_s_p8_0,
  117926. _vq_quantmap__16c1_s_p8_0,
  117927. 13,
  117928. 13
  117929. };
  117930. static static_codebook _16c1_s_p8_0 = {
  117931. 2, 169,
  117932. _vq_lengthlist__16c1_s_p8_0,
  117933. 1, -526516224, 1616117760, 4, 0,
  117934. _vq_quantlist__16c1_s_p8_0,
  117935. NULL,
  117936. &_vq_auxt__16c1_s_p8_0,
  117937. NULL,
  117938. 0
  117939. };
  117940. static long _vq_quantlist__16c1_s_p8_1[] = {
  117941. 2,
  117942. 1,
  117943. 3,
  117944. 0,
  117945. 4,
  117946. };
  117947. static long _vq_lengthlist__16c1_s_p8_1[] = {
  117948. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  117949. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  117950. };
  117951. static float _vq_quantthresh__16c1_s_p8_1[] = {
  117952. -1.5, -0.5, 0.5, 1.5,
  117953. };
  117954. static long _vq_quantmap__16c1_s_p8_1[] = {
  117955. 3, 1, 0, 2, 4,
  117956. };
  117957. static encode_aux_threshmatch _vq_auxt__16c1_s_p8_1 = {
  117958. _vq_quantthresh__16c1_s_p8_1,
  117959. _vq_quantmap__16c1_s_p8_1,
  117960. 5,
  117961. 5
  117962. };
  117963. static static_codebook _16c1_s_p8_1 = {
  117964. 2, 25,
  117965. _vq_lengthlist__16c1_s_p8_1,
  117966. 1, -533725184, 1611661312, 3, 0,
  117967. _vq_quantlist__16c1_s_p8_1,
  117968. NULL,
  117969. &_vq_auxt__16c1_s_p8_1,
  117970. NULL,
  117971. 0
  117972. };
  117973. static long _vq_quantlist__16c1_s_p9_0[] = {
  117974. 6,
  117975. 5,
  117976. 7,
  117977. 4,
  117978. 8,
  117979. 3,
  117980. 9,
  117981. 2,
  117982. 10,
  117983. 1,
  117984. 11,
  117985. 0,
  117986. 12,
  117987. };
  117988. static long _vq_lengthlist__16c1_s_p9_0[] = {
  117989. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  117990. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  117991. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  117992. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  117993. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  117994. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  117995. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  117996. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  117997. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  117998. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  117999. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  118000. };
  118001. static float _vq_quantthresh__16c1_s_p9_0[] = {
  118002. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  118003. 787.5, 1102.5, 1417.5, 1732.5,
  118004. };
  118005. static long _vq_quantmap__16c1_s_p9_0[] = {
  118006. 11, 9, 7, 5, 3, 1, 0, 2,
  118007. 4, 6, 8, 10, 12,
  118008. };
  118009. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_0 = {
  118010. _vq_quantthresh__16c1_s_p9_0,
  118011. _vq_quantmap__16c1_s_p9_0,
  118012. 13,
  118013. 13
  118014. };
  118015. static static_codebook _16c1_s_p9_0 = {
  118016. 2, 169,
  118017. _vq_lengthlist__16c1_s_p9_0,
  118018. 1, -513964032, 1628680192, 4, 0,
  118019. _vq_quantlist__16c1_s_p9_0,
  118020. NULL,
  118021. &_vq_auxt__16c1_s_p9_0,
  118022. NULL,
  118023. 0
  118024. };
  118025. static long _vq_quantlist__16c1_s_p9_1[] = {
  118026. 7,
  118027. 6,
  118028. 8,
  118029. 5,
  118030. 9,
  118031. 4,
  118032. 10,
  118033. 3,
  118034. 11,
  118035. 2,
  118036. 12,
  118037. 1,
  118038. 13,
  118039. 0,
  118040. 14,
  118041. };
  118042. static long _vq_lengthlist__16c1_s_p9_1[] = {
  118043. 1, 4, 4, 4, 4, 8, 8,12,13,14,14,14,14,14,14, 6,
  118044. 6, 6, 6, 6,10, 9,14,14,14,14,14,14,14,14, 7, 6,
  118045. 5, 6, 6,10, 9,12,13,13,13,13,13,13,13,13, 7, 7,
  118046. 9, 9,11,11,12,13,13,13,13,13,13,13,13, 7, 7, 8,
  118047. 8,11,12,13,13,13,13,13,13,13,13,13,12,12,10,10,
  118048. 13,12,13,13,13,13,13,13,13,13,13,12,12,10,10,13,
  118049. 13,13,13,13,13,13,13,13,13,13,13,13,13,12,13,12,
  118050. 13,13,13,13,13,13,13,13,13,13,13,13,12,13,13,13,
  118051. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  118052. 13,13,13,13,13,13,13,13,13,13,13,13,12,13,13,13,
  118053. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  118054. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  118055. 13,13,13,13,13,13,13,13,13,12,13,13,13,13,13,13,
  118056. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  118057. 13,
  118058. };
  118059. static float _vq_quantthresh__16c1_s_p9_1[] = {
  118060. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  118061. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  118062. };
  118063. static long _vq_quantmap__16c1_s_p9_1[] = {
  118064. 13, 11, 9, 7, 5, 3, 1, 0,
  118065. 2, 4, 6, 8, 10, 12, 14,
  118066. };
  118067. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_1 = {
  118068. _vq_quantthresh__16c1_s_p9_1,
  118069. _vq_quantmap__16c1_s_p9_1,
  118070. 15,
  118071. 15
  118072. };
  118073. static static_codebook _16c1_s_p9_1 = {
  118074. 2, 225,
  118075. _vq_lengthlist__16c1_s_p9_1,
  118076. 1, -520986624, 1620377600, 4, 0,
  118077. _vq_quantlist__16c1_s_p9_1,
  118078. NULL,
  118079. &_vq_auxt__16c1_s_p9_1,
  118080. NULL,
  118081. 0
  118082. };
  118083. static long _vq_quantlist__16c1_s_p9_2[] = {
  118084. 10,
  118085. 9,
  118086. 11,
  118087. 8,
  118088. 12,
  118089. 7,
  118090. 13,
  118091. 6,
  118092. 14,
  118093. 5,
  118094. 15,
  118095. 4,
  118096. 16,
  118097. 3,
  118098. 17,
  118099. 2,
  118100. 18,
  118101. 1,
  118102. 19,
  118103. 0,
  118104. 20,
  118105. };
  118106. static long _vq_lengthlist__16c1_s_p9_2[] = {
  118107. 1, 4, 4, 6, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9,10,
  118108. 10,10, 9,10,10,11,12,12, 8, 8, 8, 8, 9, 9, 9, 9,
  118109. 10,10,10,10,10,11,11,10,12,11,11,13,11, 7, 7, 8,
  118110. 8, 8, 8, 9, 9, 9,10,10,10,10, 9,10,10,11,11,12,
  118111. 11,11, 8, 8, 8, 8, 9, 9,10,10,10,10,11,11,11,11,
  118112. 11,11,11,12,11,12,12, 8, 8, 9, 9, 9, 9, 9,10,10,
  118113. 10,10,10,10,11,11,11,11,11,11,12,11, 9, 9, 9, 9,
  118114. 10,10,10,10,11,10,11,11,11,11,11,11,12,12,12,12,
  118115. 11, 9, 9, 9, 9,10,10,10,10,11,11,11,11,11,11,11,
  118116. 11,11,12,12,12,13, 9,10,10, 9,11,10,10,10,10,11,
  118117. 11,11,11,11,10,11,12,11,12,12,11,12,11,10, 9,10,
  118118. 10,11,10,11,11,11,11,11,11,11,11,11,12,12,11,12,
  118119. 12,12,10,10,10,11,10,11,11,11,11,11,11,11,11,11,
  118120. 11,11,12,13,12,12,11, 9,10,10,11,11,10,11,11,11,
  118121. 12,11,11,11,11,11,12,12,13,13,12,13,10,10,12,10,
  118122. 11,11,11,11,11,11,11,11,11,12,12,11,13,12,12,12,
  118123. 12,13,12,11,11,11,11,11,11,12,11,12,11,11,11,11,
  118124. 12,12,13,12,11,12,12,11,11,11,11,11,12,11,11,11,
  118125. 11,12,11,11,12,11,12,13,13,12,12,12,12,11,11,11,
  118126. 11,11,12,11,11,12,11,12,11,11,11,11,13,12,12,12,
  118127. 12,13,11,11,11,12,12,11,11,11,12,11,12,12,12,11,
  118128. 12,13,12,11,11,12,12,11,12,11,11,11,12,12,11,12,
  118129. 11,11,11,12,12,12,12,13,12,13,12,12,12,12,11,11,
  118130. 12,11,11,11,11,11,11,12,12,12,13,12,11,13,13,12,
  118131. 12,11,12,10,11,11,11,11,12,11,12,12,11,12,12,13,
  118132. 12,12,13,12,12,12,12,12,11,12,12,12,11,12,11,11,
  118133. 11,12,13,12,13,13,13,13,13,12,13,13,12,12,13,11,
  118134. 11,11,11,11,12,11,11,12,11,
  118135. };
  118136. static float _vq_quantthresh__16c1_s_p9_2[] = {
  118137. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  118138. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  118139. 6.5, 7.5, 8.5, 9.5,
  118140. };
  118141. static long _vq_quantmap__16c1_s_p9_2[] = {
  118142. 19, 17, 15, 13, 11, 9, 7, 5,
  118143. 3, 1, 0, 2, 4, 6, 8, 10,
  118144. 12, 14, 16, 18, 20,
  118145. };
  118146. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_2 = {
  118147. _vq_quantthresh__16c1_s_p9_2,
  118148. _vq_quantmap__16c1_s_p9_2,
  118149. 21,
  118150. 21
  118151. };
  118152. static static_codebook _16c1_s_p9_2 = {
  118153. 2, 441,
  118154. _vq_lengthlist__16c1_s_p9_2,
  118155. 1, -529268736, 1611661312, 5, 0,
  118156. _vq_quantlist__16c1_s_p9_2,
  118157. NULL,
  118158. &_vq_auxt__16c1_s_p9_2,
  118159. NULL,
  118160. 0
  118161. };
  118162. static long _huff_lengthlist__16c1_s_short[] = {
  118163. 5, 6,17, 8,12, 9,10,10,12,13, 5, 2,17, 4, 9, 5,
  118164. 7, 8,11,13,16,16,16,16,16,16,16,16,16,16, 6, 4,
  118165. 16, 5,10, 5, 7,10,14,16,13, 9,16,11, 8, 7, 8, 9,
  118166. 13,16, 7, 4,16, 5, 7, 4, 6, 8,11,13, 8, 6,16, 7,
  118167. 8, 5, 5, 7, 9,13, 9, 8,16, 9, 8, 6, 6, 7, 9,13,
  118168. 11,11,16,10,10, 7, 7, 7, 9,13,13,13,16,13,13, 9,
  118169. 9, 9,10,13,
  118170. };
  118171. static static_codebook _huff_book__16c1_s_short = {
  118172. 2, 100,
  118173. _huff_lengthlist__16c1_s_short,
  118174. 0, 0, 0, 0, 0,
  118175. NULL,
  118176. NULL,
  118177. NULL,
  118178. NULL,
  118179. 0
  118180. };
  118181. static long _huff_lengthlist__16c2_s_long[] = {
  118182. 4, 7, 9, 9, 9, 8, 9,10,15,19, 5, 4, 5, 6, 7, 7,
  118183. 8, 9,14,16, 6, 5, 4, 5, 6, 7, 8,10,12,19, 7, 6,
  118184. 5, 4, 5, 6, 7, 9,11,18, 8, 7, 6, 5, 5, 5, 7, 9,
  118185. 10,17, 8, 7, 7, 5, 5, 5, 6, 7,12,18, 8, 8, 8, 7,
  118186. 7, 5, 5, 7,12,18, 8, 9,10, 9, 9, 7, 6, 7,12,17,
  118187. 14,18,16,16,15,12,11,10,12,18,15,17,18,18,18,15,
  118188. 14,14,16,18,
  118189. };
  118190. static static_codebook _huff_book__16c2_s_long = {
  118191. 2, 100,
  118192. _huff_lengthlist__16c2_s_long,
  118193. 0, 0, 0, 0, 0,
  118194. NULL,
  118195. NULL,
  118196. NULL,
  118197. NULL,
  118198. 0
  118199. };
  118200. static long _vq_quantlist__16c2_s_p1_0[] = {
  118201. 1,
  118202. 0,
  118203. 2,
  118204. };
  118205. static long _vq_lengthlist__16c2_s_p1_0[] = {
  118206. 1, 3, 3, 0, 0, 0, 0, 0, 0, 4, 5, 5, 0, 0, 0, 0,
  118207. 0, 0, 4, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118211. 0,
  118212. };
  118213. static float _vq_quantthresh__16c2_s_p1_0[] = {
  118214. -0.5, 0.5,
  118215. };
  118216. static long _vq_quantmap__16c2_s_p1_0[] = {
  118217. 1, 0, 2,
  118218. };
  118219. static encode_aux_threshmatch _vq_auxt__16c2_s_p1_0 = {
  118220. _vq_quantthresh__16c2_s_p1_0,
  118221. _vq_quantmap__16c2_s_p1_0,
  118222. 3,
  118223. 3
  118224. };
  118225. static static_codebook _16c2_s_p1_0 = {
  118226. 4, 81,
  118227. _vq_lengthlist__16c2_s_p1_0,
  118228. 1, -535822336, 1611661312, 2, 0,
  118229. _vq_quantlist__16c2_s_p1_0,
  118230. NULL,
  118231. &_vq_auxt__16c2_s_p1_0,
  118232. NULL,
  118233. 0
  118234. };
  118235. static long _vq_quantlist__16c2_s_p2_0[] = {
  118236. 2,
  118237. 1,
  118238. 3,
  118239. 0,
  118240. 4,
  118241. };
  118242. static long _vq_lengthlist__16c2_s_p2_0[] = {
  118243. 2, 4, 3, 7, 7, 0, 0, 0, 7, 8, 0, 0, 0, 8, 8, 0,
  118244. 0, 0, 8, 8, 0, 0, 0, 8, 8, 4, 5, 4, 8, 8, 0, 0,
  118245. 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 9, 9, 0, 0, 0,
  118246. 9, 9, 4, 4, 5, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8,
  118247. 8, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 7, 8, 8,10,10,
  118248. 0, 0, 0,12,11, 0, 0, 0,11,11, 0, 0, 0,14,13, 0,
  118249. 0, 0,14,13, 7, 8, 8, 9,10, 0, 0, 0,11,12, 0, 0,
  118250. 0,11,11, 0, 0, 0,14,14, 0, 0, 0,13,14, 0, 0, 0,
  118251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118252. 0, 0, 0, 0, 0, 0, 0, 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, 8, 8, 8,11,11, 0, 0, 0,
  118256. 11,11, 0, 0, 0,12,11, 0, 0, 0,12,12, 0, 0, 0,13,
  118257. 13, 8, 8, 8,11,11, 0, 0, 0,11,11, 0, 0, 0,11,12,
  118258. 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0,
  118259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118260. 0, 0, 0, 0, 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, 8, 8, 8,12,11, 0, 0, 0,12,11, 0,
  118264. 0, 0,11,11, 0, 0, 0,13,13, 0, 0, 0,13,12, 8, 8,
  118265. 8,11,12, 0, 0, 0,11,12, 0, 0, 0,11,11, 0, 0, 0,
  118266. 13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118271. 0, 0, 8, 9, 9,14,13, 0, 0, 0,13,12, 0, 0, 0,13,
  118272. 13, 0, 0, 0,13,12, 0, 0, 0,13,13, 8, 9, 9,13,14,
  118273. 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0,12,13, 0,
  118274. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8,
  118279. 9, 9,14,13, 0, 0, 0,13,13, 0, 0, 0,13,12, 0, 0,
  118280. 0,13,13, 0, 0, 0,13,12, 8, 9, 9,14,14, 0, 0, 0,
  118281. 13,13, 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0,12,
  118282. 13,
  118283. };
  118284. static float _vq_quantthresh__16c2_s_p2_0[] = {
  118285. -1.5, -0.5, 0.5, 1.5,
  118286. };
  118287. static long _vq_quantmap__16c2_s_p2_0[] = {
  118288. 3, 1, 0, 2, 4,
  118289. };
  118290. static encode_aux_threshmatch _vq_auxt__16c2_s_p2_0 = {
  118291. _vq_quantthresh__16c2_s_p2_0,
  118292. _vq_quantmap__16c2_s_p2_0,
  118293. 5,
  118294. 5
  118295. };
  118296. static static_codebook _16c2_s_p2_0 = {
  118297. 4, 625,
  118298. _vq_lengthlist__16c2_s_p2_0,
  118299. 1, -533725184, 1611661312, 3, 0,
  118300. _vq_quantlist__16c2_s_p2_0,
  118301. NULL,
  118302. &_vq_auxt__16c2_s_p2_0,
  118303. NULL,
  118304. 0
  118305. };
  118306. static long _vq_quantlist__16c2_s_p3_0[] = {
  118307. 4,
  118308. 3,
  118309. 5,
  118310. 2,
  118311. 6,
  118312. 1,
  118313. 7,
  118314. 0,
  118315. 8,
  118316. };
  118317. static long _vq_lengthlist__16c2_s_p3_0[] = {
  118318. 1, 3, 3, 6, 6, 7, 7, 8, 8, 0, 0, 0, 6, 6, 7, 7,
  118319. 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  118320. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  118321. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 9, 9,10,10, 0,
  118322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118323. 0,
  118324. };
  118325. static float _vq_quantthresh__16c2_s_p3_0[] = {
  118326. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  118327. };
  118328. static long _vq_quantmap__16c2_s_p3_0[] = {
  118329. 7, 5, 3, 1, 0, 2, 4, 6,
  118330. 8,
  118331. };
  118332. static encode_aux_threshmatch _vq_auxt__16c2_s_p3_0 = {
  118333. _vq_quantthresh__16c2_s_p3_0,
  118334. _vq_quantmap__16c2_s_p3_0,
  118335. 9,
  118336. 9
  118337. };
  118338. static static_codebook _16c2_s_p3_0 = {
  118339. 2, 81,
  118340. _vq_lengthlist__16c2_s_p3_0,
  118341. 1, -531628032, 1611661312, 4, 0,
  118342. _vq_quantlist__16c2_s_p3_0,
  118343. NULL,
  118344. &_vq_auxt__16c2_s_p3_0,
  118345. NULL,
  118346. 0
  118347. };
  118348. static long _vq_quantlist__16c2_s_p4_0[] = {
  118349. 8,
  118350. 7,
  118351. 9,
  118352. 6,
  118353. 10,
  118354. 5,
  118355. 11,
  118356. 4,
  118357. 12,
  118358. 3,
  118359. 13,
  118360. 2,
  118361. 14,
  118362. 1,
  118363. 15,
  118364. 0,
  118365. 16,
  118366. };
  118367. static long _vq_lengthlist__16c2_s_p4_0[] = {
  118368. 2, 3, 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9,10,
  118369. 10, 0, 0, 0, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  118370. 11,11, 0, 0, 0, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  118371. 10,10,11, 0, 0, 0, 6, 6, 8, 8, 8, 8, 9, 9,10,10,
  118372. 10,11,11,11, 0, 0, 0, 6, 6, 8, 8, 9, 9, 9, 9,10,
  118373. 10,11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,
  118374. 10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9,
  118375. 9,10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  118376. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8, 8, 9,
  118377. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  118378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118386. 0,
  118387. };
  118388. static float _vq_quantthresh__16c2_s_p4_0[] = {
  118389. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  118390. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  118391. };
  118392. static long _vq_quantmap__16c2_s_p4_0[] = {
  118393. 15, 13, 11, 9, 7, 5, 3, 1,
  118394. 0, 2, 4, 6, 8, 10, 12, 14,
  118395. 16,
  118396. };
  118397. static encode_aux_threshmatch _vq_auxt__16c2_s_p4_0 = {
  118398. _vq_quantthresh__16c2_s_p4_0,
  118399. _vq_quantmap__16c2_s_p4_0,
  118400. 17,
  118401. 17
  118402. };
  118403. static static_codebook _16c2_s_p4_0 = {
  118404. 2, 289,
  118405. _vq_lengthlist__16c2_s_p4_0,
  118406. 1, -529530880, 1611661312, 5, 0,
  118407. _vq_quantlist__16c2_s_p4_0,
  118408. NULL,
  118409. &_vq_auxt__16c2_s_p4_0,
  118410. NULL,
  118411. 0
  118412. };
  118413. static long _vq_quantlist__16c2_s_p5_0[] = {
  118414. 1,
  118415. 0,
  118416. 2,
  118417. };
  118418. static long _vq_lengthlist__16c2_s_p5_0[] = {
  118419. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 6,10,10,10,10,
  118420. 10,10, 4, 7, 6,10,10,10,10,10,10, 5, 9, 9, 9,12,
  118421. 11,10,11,12, 7,10,10,12,12,12,12,12,12, 7,10,10,
  118422. 11,12,12,12,12,13, 6,10,10,10,12,12,10,12,12, 7,
  118423. 10,10,11,13,12,12,12,12, 7,10,10,11,12,12,12,12,
  118424. 12,
  118425. };
  118426. static float _vq_quantthresh__16c2_s_p5_0[] = {
  118427. -5.5, 5.5,
  118428. };
  118429. static long _vq_quantmap__16c2_s_p5_0[] = {
  118430. 1, 0, 2,
  118431. };
  118432. static encode_aux_threshmatch _vq_auxt__16c2_s_p5_0 = {
  118433. _vq_quantthresh__16c2_s_p5_0,
  118434. _vq_quantmap__16c2_s_p5_0,
  118435. 3,
  118436. 3
  118437. };
  118438. static static_codebook _16c2_s_p5_0 = {
  118439. 4, 81,
  118440. _vq_lengthlist__16c2_s_p5_0,
  118441. 1, -529137664, 1618345984, 2, 0,
  118442. _vq_quantlist__16c2_s_p5_0,
  118443. NULL,
  118444. &_vq_auxt__16c2_s_p5_0,
  118445. NULL,
  118446. 0
  118447. };
  118448. static long _vq_quantlist__16c2_s_p5_1[] = {
  118449. 5,
  118450. 4,
  118451. 6,
  118452. 3,
  118453. 7,
  118454. 2,
  118455. 8,
  118456. 1,
  118457. 9,
  118458. 0,
  118459. 10,
  118460. };
  118461. static long _vq_lengthlist__16c2_s_p5_1[] = {
  118462. 2, 3, 3, 6, 6, 7, 7, 7, 7, 8, 8,11,11,11, 6, 6,
  118463. 7, 7, 8, 8, 8, 8,11,11,11, 6, 6, 7, 7, 8, 8, 8,
  118464. 8,11,11,11, 6, 6, 8, 8, 8, 8, 9, 9,11,11,11, 6,
  118465. 6, 8, 8, 8, 8, 9, 9,11,11,11, 7, 7, 8, 8, 8, 8,
  118466. 8, 8,11,11,11, 7, 7, 8, 8, 8, 8, 8, 9,11,11,11,
  118467. 8, 8, 8, 8, 8, 8, 8, 8,11,11,11,11,11, 8, 8, 8,
  118468. 8, 8, 8,11,11,11,11,11, 8, 8, 8, 8, 8, 8,11,11,
  118469. 11,11,11, 7, 7, 8, 8, 8, 8,
  118470. };
  118471. static float _vq_quantthresh__16c2_s_p5_1[] = {
  118472. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  118473. 3.5, 4.5,
  118474. };
  118475. static long _vq_quantmap__16c2_s_p5_1[] = {
  118476. 9, 7, 5, 3, 1, 0, 2, 4,
  118477. 6, 8, 10,
  118478. };
  118479. static encode_aux_threshmatch _vq_auxt__16c2_s_p5_1 = {
  118480. _vq_quantthresh__16c2_s_p5_1,
  118481. _vq_quantmap__16c2_s_p5_1,
  118482. 11,
  118483. 11
  118484. };
  118485. static static_codebook _16c2_s_p5_1 = {
  118486. 2, 121,
  118487. _vq_lengthlist__16c2_s_p5_1,
  118488. 1, -531365888, 1611661312, 4, 0,
  118489. _vq_quantlist__16c2_s_p5_1,
  118490. NULL,
  118491. &_vq_auxt__16c2_s_p5_1,
  118492. NULL,
  118493. 0
  118494. };
  118495. static long _vq_quantlist__16c2_s_p6_0[] = {
  118496. 6,
  118497. 5,
  118498. 7,
  118499. 4,
  118500. 8,
  118501. 3,
  118502. 9,
  118503. 2,
  118504. 10,
  118505. 1,
  118506. 11,
  118507. 0,
  118508. 12,
  118509. };
  118510. static long _vq_lengthlist__16c2_s_p6_0[] = {
  118511. 1, 4, 4, 7, 6, 8, 8, 9, 9,10,10,11,11, 5, 5, 5,
  118512. 7, 7, 9, 9, 9, 9,11,11,12,12, 6, 5, 5, 7, 7, 9,
  118513. 9,10,10,11,11,12,12, 0, 6, 6, 7, 7, 9, 9,10,10,
  118514. 11,11,12,12, 0, 7, 7, 7, 7, 9, 9,10,10,11,12,12,
  118515. 12, 0,11,11, 8, 8,10,10,11,11,12,12,13,13, 0,11,
  118516. 12, 8, 8,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  118517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118521. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  118522. };
  118523. static float _vq_quantthresh__16c2_s_p6_0[] = {
  118524. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  118525. 12.5, 17.5, 22.5, 27.5,
  118526. };
  118527. static long _vq_quantmap__16c2_s_p6_0[] = {
  118528. 11, 9, 7, 5, 3, 1, 0, 2,
  118529. 4, 6, 8, 10, 12,
  118530. };
  118531. static encode_aux_threshmatch _vq_auxt__16c2_s_p6_0 = {
  118532. _vq_quantthresh__16c2_s_p6_0,
  118533. _vq_quantmap__16c2_s_p6_0,
  118534. 13,
  118535. 13
  118536. };
  118537. static static_codebook _16c2_s_p6_0 = {
  118538. 2, 169,
  118539. _vq_lengthlist__16c2_s_p6_0,
  118540. 1, -526516224, 1616117760, 4, 0,
  118541. _vq_quantlist__16c2_s_p6_0,
  118542. NULL,
  118543. &_vq_auxt__16c2_s_p6_0,
  118544. NULL,
  118545. 0
  118546. };
  118547. static long _vq_quantlist__16c2_s_p6_1[] = {
  118548. 2,
  118549. 1,
  118550. 3,
  118551. 0,
  118552. 4,
  118553. };
  118554. static long _vq_lengthlist__16c2_s_p6_1[] = {
  118555. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  118556. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  118557. };
  118558. static float _vq_quantthresh__16c2_s_p6_1[] = {
  118559. -1.5, -0.5, 0.5, 1.5,
  118560. };
  118561. static long _vq_quantmap__16c2_s_p6_1[] = {
  118562. 3, 1, 0, 2, 4,
  118563. };
  118564. static encode_aux_threshmatch _vq_auxt__16c2_s_p6_1 = {
  118565. _vq_quantthresh__16c2_s_p6_1,
  118566. _vq_quantmap__16c2_s_p6_1,
  118567. 5,
  118568. 5
  118569. };
  118570. static static_codebook _16c2_s_p6_1 = {
  118571. 2, 25,
  118572. _vq_lengthlist__16c2_s_p6_1,
  118573. 1, -533725184, 1611661312, 3, 0,
  118574. _vq_quantlist__16c2_s_p6_1,
  118575. NULL,
  118576. &_vq_auxt__16c2_s_p6_1,
  118577. NULL,
  118578. 0
  118579. };
  118580. static long _vq_quantlist__16c2_s_p7_0[] = {
  118581. 6,
  118582. 5,
  118583. 7,
  118584. 4,
  118585. 8,
  118586. 3,
  118587. 9,
  118588. 2,
  118589. 10,
  118590. 1,
  118591. 11,
  118592. 0,
  118593. 12,
  118594. };
  118595. static long _vq_lengthlist__16c2_s_p7_0[] = {
  118596. 1, 4, 4, 7, 7, 8, 8, 9, 9,10,10,11,11, 5, 5, 5,
  118597. 8, 8, 9, 9,10,10,11,11,12,12, 6, 5, 5, 8, 8, 9,
  118598. 9,10,10,11,11,12,13,18, 6, 6, 7, 7, 9, 9,10,10,
  118599. 12,12,13,13,18, 6, 6, 7, 7, 9, 9,10,10,12,12,13,
  118600. 13,18,11,10, 8, 8,10,10,11,11,12,12,13,13,18,11,
  118601. 11, 8, 8,10,10,11,11,12,13,13,13,18,18,18,10,11,
  118602. 11,11,12,12,13,13,14,14,18,18,18,11,11,11,11,12,
  118603. 12,13,13,14,14,18,18,18,14,14,12,12,12,12,14,14,
  118604. 15,14,18,18,18,15,15,11,12,12,12,13,13,15,15,18,
  118605. 18,18,18,18,13,13,13,13,13,14,17,16,18,18,18,18,
  118606. 18,13,14,13,13,14,13,15,14,
  118607. };
  118608. static float _vq_quantthresh__16c2_s_p7_0[] = {
  118609. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  118610. 27.5, 38.5, 49.5, 60.5,
  118611. };
  118612. static long _vq_quantmap__16c2_s_p7_0[] = {
  118613. 11, 9, 7, 5, 3, 1, 0, 2,
  118614. 4, 6, 8, 10, 12,
  118615. };
  118616. static encode_aux_threshmatch _vq_auxt__16c2_s_p7_0 = {
  118617. _vq_quantthresh__16c2_s_p7_0,
  118618. _vq_quantmap__16c2_s_p7_0,
  118619. 13,
  118620. 13
  118621. };
  118622. static static_codebook _16c2_s_p7_0 = {
  118623. 2, 169,
  118624. _vq_lengthlist__16c2_s_p7_0,
  118625. 1, -523206656, 1618345984, 4, 0,
  118626. _vq_quantlist__16c2_s_p7_0,
  118627. NULL,
  118628. &_vq_auxt__16c2_s_p7_0,
  118629. NULL,
  118630. 0
  118631. };
  118632. static long _vq_quantlist__16c2_s_p7_1[] = {
  118633. 5,
  118634. 4,
  118635. 6,
  118636. 3,
  118637. 7,
  118638. 2,
  118639. 8,
  118640. 1,
  118641. 9,
  118642. 0,
  118643. 10,
  118644. };
  118645. static long _vq_lengthlist__16c2_s_p7_1[] = {
  118646. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 7, 9, 9, 9, 6, 6,
  118647. 7, 7, 8, 8, 8, 8, 9, 9, 9, 6, 6, 7, 7, 8, 8, 8,
  118648. 8, 9, 9, 9, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 7,
  118649. 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8,
  118650. 8, 8, 9, 9, 9, 7, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  118651. 7, 7, 8, 8, 7, 7, 8, 8, 9, 9, 9, 9, 9, 7, 7, 7,
  118652. 7, 8, 8, 9, 9, 9, 9, 9, 8, 8, 7, 7, 8, 8, 9, 9,
  118653. 9, 9, 9, 7, 7, 7, 7, 8, 8,
  118654. };
  118655. static float _vq_quantthresh__16c2_s_p7_1[] = {
  118656. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  118657. 3.5, 4.5,
  118658. };
  118659. static long _vq_quantmap__16c2_s_p7_1[] = {
  118660. 9, 7, 5, 3, 1, 0, 2, 4,
  118661. 6, 8, 10,
  118662. };
  118663. static encode_aux_threshmatch _vq_auxt__16c2_s_p7_1 = {
  118664. _vq_quantthresh__16c2_s_p7_1,
  118665. _vq_quantmap__16c2_s_p7_1,
  118666. 11,
  118667. 11
  118668. };
  118669. static static_codebook _16c2_s_p7_1 = {
  118670. 2, 121,
  118671. _vq_lengthlist__16c2_s_p7_1,
  118672. 1, -531365888, 1611661312, 4, 0,
  118673. _vq_quantlist__16c2_s_p7_1,
  118674. NULL,
  118675. &_vq_auxt__16c2_s_p7_1,
  118676. NULL,
  118677. 0
  118678. };
  118679. static long _vq_quantlist__16c2_s_p8_0[] = {
  118680. 7,
  118681. 6,
  118682. 8,
  118683. 5,
  118684. 9,
  118685. 4,
  118686. 10,
  118687. 3,
  118688. 11,
  118689. 2,
  118690. 12,
  118691. 1,
  118692. 13,
  118693. 0,
  118694. 14,
  118695. };
  118696. static long _vq_lengthlist__16c2_s_p8_0[] = {
  118697. 1, 4, 4, 7, 6, 7, 7, 6, 6, 8, 8, 9, 9,10,10, 6,
  118698. 6, 6, 8, 8, 9, 8, 8, 8, 9, 9,11,10,11,11, 7, 6,
  118699. 6, 8, 8, 9, 8, 7, 7, 9, 9,10,10,12,11,14, 8, 8,
  118700. 8, 9, 9, 9, 9, 9,10, 9,10,10,11,13,14, 8, 8, 8,
  118701. 8, 9, 9, 8, 8, 9, 9,10,10,11,12,14,13,11, 9, 9,
  118702. 9, 9, 9, 9, 9,10,11,10,13,12,14,11,13, 8, 9, 9,
  118703. 9, 9, 9,10,10,11,10,13,12,14,14,14, 8, 9, 9, 9,
  118704. 11,11,11,11,11,12,13,13,14,14,14, 9, 8, 9, 9,10,
  118705. 10,12,10,11,12,12,14,14,14,14,11,12,10,10,12,12,
  118706. 12,12,13,14,12,12,14,14,14,12,12, 9,10,11,11,12,
  118707. 14,12,14,14,14,14,14,14,14,14,11,11,12,11,12,14,
  118708. 14,14,14,14,14,14,14,14,14,12,11,11,11,11,14,14,
  118709. 14,14,14,14,14,14,14,14,14,14,13,12,14,14,14,14,
  118710. 14,14,14,14,14,14,14,14,14,12,12,12,13,14,14,13,
  118711. 13,
  118712. };
  118713. static float _vq_quantthresh__16c2_s_p8_0[] = {
  118714. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  118715. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  118716. };
  118717. static long _vq_quantmap__16c2_s_p8_0[] = {
  118718. 13, 11, 9, 7, 5, 3, 1, 0,
  118719. 2, 4, 6, 8, 10, 12, 14,
  118720. };
  118721. static encode_aux_threshmatch _vq_auxt__16c2_s_p8_0 = {
  118722. _vq_quantthresh__16c2_s_p8_0,
  118723. _vq_quantmap__16c2_s_p8_0,
  118724. 15,
  118725. 15
  118726. };
  118727. static static_codebook _16c2_s_p8_0 = {
  118728. 2, 225,
  118729. _vq_lengthlist__16c2_s_p8_0,
  118730. 1, -520986624, 1620377600, 4, 0,
  118731. _vq_quantlist__16c2_s_p8_0,
  118732. NULL,
  118733. &_vq_auxt__16c2_s_p8_0,
  118734. NULL,
  118735. 0
  118736. };
  118737. static long _vq_quantlist__16c2_s_p8_1[] = {
  118738. 10,
  118739. 9,
  118740. 11,
  118741. 8,
  118742. 12,
  118743. 7,
  118744. 13,
  118745. 6,
  118746. 14,
  118747. 5,
  118748. 15,
  118749. 4,
  118750. 16,
  118751. 3,
  118752. 17,
  118753. 2,
  118754. 18,
  118755. 1,
  118756. 19,
  118757. 0,
  118758. 20,
  118759. };
  118760. static long _vq_lengthlist__16c2_s_p8_1[] = {
  118761. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 8,
  118762. 8, 8, 8, 8, 8,11,12,11, 7, 7, 8, 8, 8, 8, 9, 9,
  118763. 9, 9, 9, 9, 9, 9, 9,10, 9, 9,11,11,10, 7, 7, 8,
  118764. 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  118765. 11,11, 8, 7, 8, 8, 9, 9, 9, 9, 9, 9,10,10, 9,10,
  118766. 10, 9,10,10,11,11,12, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  118767. 9, 9, 9,10, 9,10,10,10,10,11,11,11, 8, 8, 9, 9,
  118768. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,11,
  118769. 11, 8, 8, 9, 8, 9, 9, 9, 9,10, 9, 9, 9,10,10,10,
  118770. 10, 9,10,11,11,11, 9, 9, 9, 9,10, 9, 9, 9,10,10,
  118771. 9,10, 9,10,10,10,10,10,11,12,11,11,11, 9, 9, 9,
  118772. 9, 9,10,10, 9,10,10,10,10,10,10,10,10,12,11,13,
  118773. 13,11, 9, 9, 9, 9,10,10, 9,10,10,10,10,11,10,10,
  118774. 10,10,11,12,11,12,11, 9, 9, 9,10,10, 9,10,10,10,
  118775. 10,10,10,10,10,10,10,11,11,11,12,11, 9,10,10,10,
  118776. 10,10,10,10,10,10,10,10,10,10,10,10,11,12,12,12,
  118777. 11,11,11,10, 9,10,10,10,10,10,10,10,10,11,10,10,
  118778. 10,11,11,11,11,11,11,11,10,10,10,11,10,10,10,10,
  118779. 10,10,10,10,10,10,11,11,11,11,12,12,11,10,10,10,
  118780. 10,10,10,10,10,11,10,10,10,11,10,12,11,11,12,11,
  118781. 11,11,10,10,10,10,10,11,10,10,10,10,10,11,10,10,
  118782. 11,11,11,12,11,12,11,11,12,10,10,10,10,10,10,10,
  118783. 11,10,10,11,10,12,11,11,11,12,11,11,11,11,10,10,
  118784. 10,10,10,10,10,11,11,11,10,11,12,11,11,11,12,11,
  118785. 12,11,12,10,11,10,10,10,10,11,10,10,10,10,10,10,
  118786. 12,11,11,11,11,11,12,12,10,10,10,10,10,11,10,10,
  118787. 11,10,11,11,11,11,11,11,11,11,11,11,11,11,12,11,
  118788. 10,11,10,10,10,10,10,10,10,
  118789. };
  118790. static float _vq_quantthresh__16c2_s_p8_1[] = {
  118791. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  118792. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  118793. 6.5, 7.5, 8.5, 9.5,
  118794. };
  118795. static long _vq_quantmap__16c2_s_p8_1[] = {
  118796. 19, 17, 15, 13, 11, 9, 7, 5,
  118797. 3, 1, 0, 2, 4, 6, 8, 10,
  118798. 12, 14, 16, 18, 20,
  118799. };
  118800. static encode_aux_threshmatch _vq_auxt__16c2_s_p8_1 = {
  118801. _vq_quantthresh__16c2_s_p8_1,
  118802. _vq_quantmap__16c2_s_p8_1,
  118803. 21,
  118804. 21
  118805. };
  118806. static static_codebook _16c2_s_p8_1 = {
  118807. 2, 441,
  118808. _vq_lengthlist__16c2_s_p8_1,
  118809. 1, -529268736, 1611661312, 5, 0,
  118810. _vq_quantlist__16c2_s_p8_1,
  118811. NULL,
  118812. &_vq_auxt__16c2_s_p8_1,
  118813. NULL,
  118814. 0
  118815. };
  118816. static long _vq_quantlist__16c2_s_p9_0[] = {
  118817. 6,
  118818. 5,
  118819. 7,
  118820. 4,
  118821. 8,
  118822. 3,
  118823. 9,
  118824. 2,
  118825. 10,
  118826. 1,
  118827. 11,
  118828. 0,
  118829. 12,
  118830. };
  118831. static long _vq_lengthlist__16c2_s_p9_0[] = {
  118832. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  118833. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  118834. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  118835. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  118836. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  118837. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  118838. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  118839. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  118840. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  118841. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  118842. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  118843. };
  118844. static float _vq_quantthresh__16c2_s_p9_0[] = {
  118845. -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5, 465.5, 1396.5,
  118846. 2327.5, 3258.5, 4189.5, 5120.5,
  118847. };
  118848. static long _vq_quantmap__16c2_s_p9_0[] = {
  118849. 11, 9, 7, 5, 3, 1, 0, 2,
  118850. 4, 6, 8, 10, 12,
  118851. };
  118852. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_0 = {
  118853. _vq_quantthresh__16c2_s_p9_0,
  118854. _vq_quantmap__16c2_s_p9_0,
  118855. 13,
  118856. 13
  118857. };
  118858. static static_codebook _16c2_s_p9_0 = {
  118859. 2, 169,
  118860. _vq_lengthlist__16c2_s_p9_0,
  118861. 1, -510275072, 1631393792, 4, 0,
  118862. _vq_quantlist__16c2_s_p9_0,
  118863. NULL,
  118864. &_vq_auxt__16c2_s_p9_0,
  118865. NULL,
  118866. 0
  118867. };
  118868. static long _vq_quantlist__16c2_s_p9_1[] = {
  118869. 8,
  118870. 7,
  118871. 9,
  118872. 6,
  118873. 10,
  118874. 5,
  118875. 11,
  118876. 4,
  118877. 12,
  118878. 3,
  118879. 13,
  118880. 2,
  118881. 14,
  118882. 1,
  118883. 15,
  118884. 0,
  118885. 16,
  118886. };
  118887. static long _vq_lengthlist__16c2_s_p9_1[] = {
  118888. 1, 5, 5, 9, 8, 7, 7, 7, 6,10,11,11,11,11,11,11,
  118889. 11, 8, 7, 6, 8, 8,10, 9,10,10,10, 9,11,10,10,10,
  118890. 10,10, 8, 6, 6, 8, 8, 9, 8, 9, 8, 9,10,10,10,10,
  118891. 10,10,10,10, 8,10, 9, 9, 9, 9,10,10,10,10,10,10,
  118892. 10,10,10,10,10, 8, 9, 9, 9,10,10, 9,10,10,10,10,
  118893. 10,10,10,10,10,10,10,10, 9, 8, 9, 9,10,10,10,10,
  118894. 10,10,10,10,10,10,10,10, 9, 8, 8, 9, 9,10,10,10,
  118895. 10,10,10,10,10,10,10,10,10,10, 9,10, 9, 9,10,10,
  118896. 10,10,10,10,10,10,10,10,10,10,10, 9, 8, 9, 9,10,
  118897. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  118898. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  118899. 8,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  118900. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  118901. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  118902. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  118903. 10,10,10,10, 9,10, 9,10,10,10,10,10,10,10,10,10,
  118904. 10,10,10,10,10,10,10,10,10, 9,10,10,10,10,10,10,
  118905. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  118906. 10,
  118907. };
  118908. static float _vq_quantthresh__16c2_s_p9_1[] = {
  118909. -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5, -24.5,
  118910. 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5, 367.5,
  118911. };
  118912. static long _vq_quantmap__16c2_s_p9_1[] = {
  118913. 15, 13, 11, 9, 7, 5, 3, 1,
  118914. 0, 2, 4, 6, 8, 10, 12, 14,
  118915. 16,
  118916. };
  118917. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_1 = {
  118918. _vq_quantthresh__16c2_s_p9_1,
  118919. _vq_quantmap__16c2_s_p9_1,
  118920. 17,
  118921. 17
  118922. };
  118923. static static_codebook _16c2_s_p9_1 = {
  118924. 2, 289,
  118925. _vq_lengthlist__16c2_s_p9_1,
  118926. 1, -518488064, 1622704128, 5, 0,
  118927. _vq_quantlist__16c2_s_p9_1,
  118928. NULL,
  118929. &_vq_auxt__16c2_s_p9_1,
  118930. NULL,
  118931. 0
  118932. };
  118933. static long _vq_quantlist__16c2_s_p9_2[] = {
  118934. 13,
  118935. 12,
  118936. 14,
  118937. 11,
  118938. 15,
  118939. 10,
  118940. 16,
  118941. 9,
  118942. 17,
  118943. 8,
  118944. 18,
  118945. 7,
  118946. 19,
  118947. 6,
  118948. 20,
  118949. 5,
  118950. 21,
  118951. 4,
  118952. 22,
  118953. 3,
  118954. 23,
  118955. 2,
  118956. 24,
  118957. 1,
  118958. 25,
  118959. 0,
  118960. 26,
  118961. };
  118962. static long _vq_lengthlist__16c2_s_p9_2[] = {
  118963. 1, 4, 4, 5, 5, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  118964. 7, 7, 7, 7, 8, 7, 8, 7, 7, 4, 4,
  118965. };
  118966. static float _vq_quantthresh__16c2_s_p9_2[] = {
  118967. -12.5, -11.5, -10.5, -9.5, -8.5, -7.5, -6.5, -5.5,
  118968. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  118969. 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 9.5, 10.5,
  118970. 11.5, 12.5,
  118971. };
  118972. static long _vq_quantmap__16c2_s_p9_2[] = {
  118973. 25, 23, 21, 19, 17, 15, 13, 11,
  118974. 9, 7, 5, 3, 1, 0, 2, 4,
  118975. 6, 8, 10, 12, 14, 16, 18, 20,
  118976. 22, 24, 26,
  118977. };
  118978. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_2 = {
  118979. _vq_quantthresh__16c2_s_p9_2,
  118980. _vq_quantmap__16c2_s_p9_2,
  118981. 27,
  118982. 27
  118983. };
  118984. static static_codebook _16c2_s_p9_2 = {
  118985. 1, 27,
  118986. _vq_lengthlist__16c2_s_p9_2,
  118987. 1, -528875520, 1611661312, 5, 0,
  118988. _vq_quantlist__16c2_s_p9_2,
  118989. NULL,
  118990. &_vq_auxt__16c2_s_p9_2,
  118991. NULL,
  118992. 0
  118993. };
  118994. static long _huff_lengthlist__16c2_s_short[] = {
  118995. 7,10,11,11,11,14,15,15,17,14, 8, 6, 7, 7, 8, 9,
  118996. 11,11,14,17, 9, 6, 6, 6, 7, 7,10,11,15,16, 9, 6,
  118997. 6, 4, 4, 5, 8, 9,12,16,10, 6, 6, 4, 4, 4, 6, 9,
  118998. 13,16,10, 7, 6, 5, 4, 3, 5, 7,13,16,11, 9, 8, 7,
  118999. 6, 5, 5, 6,12,15,10,10,10, 9, 7, 6, 6, 7,11,15,
  119000. 13,13,13,13,11,10,10, 9,12,16,16,16,16,14,16,15,
  119001. 15,12,14,14,
  119002. };
  119003. static static_codebook _huff_book__16c2_s_short = {
  119004. 2, 100,
  119005. _huff_lengthlist__16c2_s_short,
  119006. 0, 0, 0, 0, 0,
  119007. NULL,
  119008. NULL,
  119009. NULL,
  119010. NULL,
  119011. 0
  119012. };
  119013. static long _vq_quantlist__8c0_s_p1_0[] = {
  119014. 1,
  119015. 0,
  119016. 2,
  119017. };
  119018. static long _vq_lengthlist__8c0_s_p1_0[] = {
  119019. 1, 5, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  119020. 0, 0, 5, 7, 7, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 9, 0, 0, 0,
  119025. 0, 0, 0, 7, 8, 9, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  119030. 0, 0, 0, 0, 7, 9, 8, 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, 0, 0, 0, 0, 0, 0, 0,
  119051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0,
  119056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0,
  119061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  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, 5, 8, 8, 0, 0, 0, 0,
  119065. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 7,10, 9, 0, 0, 0,
  119070. 0, 0, 0, 8, 9,11, 0, 0, 0, 0, 0, 0, 9,11,11, 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, 7, 9,10, 0, 0,
  119075. 0, 0, 0, 0, 9,11,10, 0, 0, 0, 0, 0, 0, 9,11,11,
  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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119097. 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119102. 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  119111. 0, 0, 0, 0, 8, 9,10, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,11, 0,
  119116. 0, 0, 0, 0, 0, 9,10,11, 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, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,11,11,
  119121. 0, 0, 0, 0, 0, 0, 8,11, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119429. 0,
  119430. };
  119431. static float _vq_quantthresh__8c0_s_p1_0[] = {
  119432. -0.5, 0.5,
  119433. };
  119434. static long _vq_quantmap__8c0_s_p1_0[] = {
  119435. 1, 0, 2,
  119436. };
  119437. static encode_aux_threshmatch _vq_auxt__8c0_s_p1_0 = {
  119438. _vq_quantthresh__8c0_s_p1_0,
  119439. _vq_quantmap__8c0_s_p1_0,
  119440. 3,
  119441. 3
  119442. };
  119443. static static_codebook _8c0_s_p1_0 = {
  119444. 8, 6561,
  119445. _vq_lengthlist__8c0_s_p1_0,
  119446. 1, -535822336, 1611661312, 2, 0,
  119447. _vq_quantlist__8c0_s_p1_0,
  119448. NULL,
  119449. &_vq_auxt__8c0_s_p1_0,
  119450. NULL,
  119451. 0
  119452. };
  119453. static long _vq_quantlist__8c0_s_p2_0[] = {
  119454. 2,
  119455. 1,
  119456. 3,
  119457. 0,
  119458. 4,
  119459. };
  119460. static long _vq_lengthlist__8c0_s_p2_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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119500. 0,
  119501. };
  119502. static float _vq_quantthresh__8c0_s_p2_0[] = {
  119503. -1.5, -0.5, 0.5, 1.5,
  119504. };
  119505. static long _vq_quantmap__8c0_s_p2_0[] = {
  119506. 3, 1, 0, 2, 4,
  119507. };
  119508. static encode_aux_threshmatch _vq_auxt__8c0_s_p2_0 = {
  119509. _vq_quantthresh__8c0_s_p2_0,
  119510. _vq_quantmap__8c0_s_p2_0,
  119511. 5,
  119512. 5
  119513. };
  119514. static static_codebook _8c0_s_p2_0 = {
  119515. 4, 625,
  119516. _vq_lengthlist__8c0_s_p2_0,
  119517. 1, -533725184, 1611661312, 3, 0,
  119518. _vq_quantlist__8c0_s_p2_0,
  119519. NULL,
  119520. &_vq_auxt__8c0_s_p2_0,
  119521. NULL,
  119522. 0
  119523. };
  119524. static long _vq_quantlist__8c0_s_p3_0[] = {
  119525. 2,
  119526. 1,
  119527. 3,
  119528. 0,
  119529. 4,
  119530. };
  119531. static long _vq_lengthlist__8c0_s_p3_0[] = {
  119532. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 6, 7, 7, 0, 0,
  119534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119535. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 8, 8,
  119537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119538. 0, 0, 0, 0, 6, 7, 7, 8, 8, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119571. 0,
  119572. };
  119573. static float _vq_quantthresh__8c0_s_p3_0[] = {
  119574. -1.5, -0.5, 0.5, 1.5,
  119575. };
  119576. static long _vq_quantmap__8c0_s_p3_0[] = {
  119577. 3, 1, 0, 2, 4,
  119578. };
  119579. static encode_aux_threshmatch _vq_auxt__8c0_s_p3_0 = {
  119580. _vq_quantthresh__8c0_s_p3_0,
  119581. _vq_quantmap__8c0_s_p3_0,
  119582. 5,
  119583. 5
  119584. };
  119585. static static_codebook _8c0_s_p3_0 = {
  119586. 4, 625,
  119587. _vq_lengthlist__8c0_s_p3_0,
  119588. 1, -533725184, 1611661312, 3, 0,
  119589. _vq_quantlist__8c0_s_p3_0,
  119590. NULL,
  119591. &_vq_auxt__8c0_s_p3_0,
  119592. NULL,
  119593. 0
  119594. };
  119595. static long _vq_quantlist__8c0_s_p4_0[] = {
  119596. 4,
  119597. 3,
  119598. 5,
  119599. 2,
  119600. 6,
  119601. 1,
  119602. 7,
  119603. 0,
  119604. 8,
  119605. };
  119606. static long _vq_lengthlist__8c0_s_p4_0[] = {
  119607. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  119608. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  119609. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  119610. 8, 8, 0, 0, 0, 0, 0, 0, 0, 9, 8, 0, 0, 0, 0, 0,
  119611. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  119612. 0,
  119613. };
  119614. static float _vq_quantthresh__8c0_s_p4_0[] = {
  119615. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  119616. };
  119617. static long _vq_quantmap__8c0_s_p4_0[] = {
  119618. 7, 5, 3, 1, 0, 2, 4, 6,
  119619. 8,
  119620. };
  119621. static encode_aux_threshmatch _vq_auxt__8c0_s_p4_0 = {
  119622. _vq_quantthresh__8c0_s_p4_0,
  119623. _vq_quantmap__8c0_s_p4_0,
  119624. 9,
  119625. 9
  119626. };
  119627. static static_codebook _8c0_s_p4_0 = {
  119628. 2, 81,
  119629. _vq_lengthlist__8c0_s_p4_0,
  119630. 1, -531628032, 1611661312, 4, 0,
  119631. _vq_quantlist__8c0_s_p4_0,
  119632. NULL,
  119633. &_vq_auxt__8c0_s_p4_0,
  119634. NULL,
  119635. 0
  119636. };
  119637. static long _vq_quantlist__8c0_s_p5_0[] = {
  119638. 4,
  119639. 3,
  119640. 5,
  119641. 2,
  119642. 6,
  119643. 1,
  119644. 7,
  119645. 0,
  119646. 8,
  119647. };
  119648. static long _vq_lengthlist__8c0_s_p5_0[] = {
  119649. 1, 3, 3, 5, 5, 7, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  119650. 8, 8, 0, 0, 0, 7, 7, 7, 7, 8, 9, 0, 0, 0, 8, 8,
  119651. 8, 8, 9, 9, 0, 0, 0, 8, 8, 8, 8, 9, 9, 0, 0, 0,
  119652. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  119653. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  119654. 10,
  119655. };
  119656. static float _vq_quantthresh__8c0_s_p5_0[] = {
  119657. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  119658. };
  119659. static long _vq_quantmap__8c0_s_p5_0[] = {
  119660. 7, 5, 3, 1, 0, 2, 4, 6,
  119661. 8,
  119662. };
  119663. static encode_aux_threshmatch _vq_auxt__8c0_s_p5_0 = {
  119664. _vq_quantthresh__8c0_s_p5_0,
  119665. _vq_quantmap__8c0_s_p5_0,
  119666. 9,
  119667. 9
  119668. };
  119669. static static_codebook _8c0_s_p5_0 = {
  119670. 2, 81,
  119671. _vq_lengthlist__8c0_s_p5_0,
  119672. 1, -531628032, 1611661312, 4, 0,
  119673. _vq_quantlist__8c0_s_p5_0,
  119674. NULL,
  119675. &_vq_auxt__8c0_s_p5_0,
  119676. NULL,
  119677. 0
  119678. };
  119679. static long _vq_quantlist__8c0_s_p6_0[] = {
  119680. 8,
  119681. 7,
  119682. 9,
  119683. 6,
  119684. 10,
  119685. 5,
  119686. 11,
  119687. 4,
  119688. 12,
  119689. 3,
  119690. 13,
  119691. 2,
  119692. 14,
  119693. 1,
  119694. 15,
  119695. 0,
  119696. 16,
  119697. };
  119698. static long _vq_lengthlist__8c0_s_p6_0[] = {
  119699. 1, 3, 3, 6, 6, 8, 8, 9, 9, 8, 8,10, 9,10,10,11,
  119700. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  119701. 11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  119702. 11,12,11, 0, 0, 0, 8, 8, 9, 9,10,10, 9, 9,10,10,
  119703. 11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10, 9, 9,11,
  119704. 10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,10,10,
  119705. 11,11,11,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,10,
  119706. 10,11,11,12,12,13,13, 0, 0, 0,10,10,10,10,11,11,
  119707. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,10, 9,10,
  119708. 11,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  119709. 10, 9,10,11,12,12,13,13,14,13, 0, 0, 0, 0, 0, 9,
  119710. 9, 9,10,10,10,11,11,13,12,13,13, 0, 0, 0, 0, 0,
  119711. 10,10,10,10,11,11,12,12,13,13,14,14, 0, 0, 0, 0,
  119712. 0, 0, 0,10,10,11,11,12,12,13,13,13,14, 0, 0, 0,
  119713. 0, 0, 0, 0,11,11,11,11,12,12,13,14,14,14, 0, 0,
  119714. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,14,13, 0,
  119715. 0, 0, 0, 0, 0, 0,11,11,12,12,13,13,14,14,14,14,
  119716. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  119717. 14,
  119718. };
  119719. static float _vq_quantthresh__8c0_s_p6_0[] = {
  119720. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  119721. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  119722. };
  119723. static long _vq_quantmap__8c0_s_p6_0[] = {
  119724. 15, 13, 11, 9, 7, 5, 3, 1,
  119725. 0, 2, 4, 6, 8, 10, 12, 14,
  119726. 16,
  119727. };
  119728. static encode_aux_threshmatch _vq_auxt__8c0_s_p6_0 = {
  119729. _vq_quantthresh__8c0_s_p6_0,
  119730. _vq_quantmap__8c0_s_p6_0,
  119731. 17,
  119732. 17
  119733. };
  119734. static static_codebook _8c0_s_p6_0 = {
  119735. 2, 289,
  119736. _vq_lengthlist__8c0_s_p6_0,
  119737. 1, -529530880, 1611661312, 5, 0,
  119738. _vq_quantlist__8c0_s_p6_0,
  119739. NULL,
  119740. &_vq_auxt__8c0_s_p6_0,
  119741. NULL,
  119742. 0
  119743. };
  119744. static long _vq_quantlist__8c0_s_p7_0[] = {
  119745. 1,
  119746. 0,
  119747. 2,
  119748. };
  119749. static long _vq_lengthlist__8c0_s_p7_0[] = {
  119750. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,11, 9,10,12,
  119751. 9,10, 4, 7, 7,10,10,10,11, 9, 9, 6,11,10,11,11,
  119752. 12,11,11,11, 6,10,10,11,11,12,11,10,10, 6, 9,10,
  119753. 11,11,11,11,10,10, 7,10,11,12,11,11,12,11,12, 6,
  119754. 9, 9,10, 9, 9,11,10,10, 6, 9, 9,10,10,10,11,10,
  119755. 10,
  119756. };
  119757. static float _vq_quantthresh__8c0_s_p7_0[] = {
  119758. -5.5, 5.5,
  119759. };
  119760. static long _vq_quantmap__8c0_s_p7_0[] = {
  119761. 1, 0, 2,
  119762. };
  119763. static encode_aux_threshmatch _vq_auxt__8c0_s_p7_0 = {
  119764. _vq_quantthresh__8c0_s_p7_0,
  119765. _vq_quantmap__8c0_s_p7_0,
  119766. 3,
  119767. 3
  119768. };
  119769. static static_codebook _8c0_s_p7_0 = {
  119770. 4, 81,
  119771. _vq_lengthlist__8c0_s_p7_0,
  119772. 1, -529137664, 1618345984, 2, 0,
  119773. _vq_quantlist__8c0_s_p7_0,
  119774. NULL,
  119775. &_vq_auxt__8c0_s_p7_0,
  119776. NULL,
  119777. 0
  119778. };
  119779. static long _vq_quantlist__8c0_s_p7_1[] = {
  119780. 5,
  119781. 4,
  119782. 6,
  119783. 3,
  119784. 7,
  119785. 2,
  119786. 8,
  119787. 1,
  119788. 9,
  119789. 0,
  119790. 10,
  119791. };
  119792. static long _vq_lengthlist__8c0_s_p7_1[] = {
  119793. 1, 3, 3, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10, 7, 7,
  119794. 8, 8, 9, 9, 9, 9,10,10, 9, 7, 7, 8, 8, 9, 9, 9,
  119795. 9,10,10,10, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10, 8,
  119796. 8, 9, 9, 9, 9, 8, 9,10,10,10, 8, 8, 9, 9, 9,10,
  119797. 10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,10,11,10,11,
  119798. 9, 9, 9, 9,10,10,10,10,11,11,11,10,10, 9, 9,10,
  119799. 10,10, 9,11,10,10,10,10,10,10, 9, 9,10,10,11,11,
  119800. 10,10,10, 9, 9, 9,10,10,10,
  119801. };
  119802. static float _vq_quantthresh__8c0_s_p7_1[] = {
  119803. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  119804. 3.5, 4.5,
  119805. };
  119806. static long _vq_quantmap__8c0_s_p7_1[] = {
  119807. 9, 7, 5, 3, 1, 0, 2, 4,
  119808. 6, 8, 10,
  119809. };
  119810. static encode_aux_threshmatch _vq_auxt__8c0_s_p7_1 = {
  119811. _vq_quantthresh__8c0_s_p7_1,
  119812. _vq_quantmap__8c0_s_p7_1,
  119813. 11,
  119814. 11
  119815. };
  119816. static static_codebook _8c0_s_p7_1 = {
  119817. 2, 121,
  119818. _vq_lengthlist__8c0_s_p7_1,
  119819. 1, -531365888, 1611661312, 4, 0,
  119820. _vq_quantlist__8c0_s_p7_1,
  119821. NULL,
  119822. &_vq_auxt__8c0_s_p7_1,
  119823. NULL,
  119824. 0
  119825. };
  119826. static long _vq_quantlist__8c0_s_p8_0[] = {
  119827. 6,
  119828. 5,
  119829. 7,
  119830. 4,
  119831. 8,
  119832. 3,
  119833. 9,
  119834. 2,
  119835. 10,
  119836. 1,
  119837. 11,
  119838. 0,
  119839. 12,
  119840. };
  119841. static long _vq_lengthlist__8c0_s_p8_0[] = {
  119842. 1, 4, 4, 7, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 6, 6,
  119843. 7, 7, 8, 8, 7, 7, 8, 9,10,10, 7, 6, 6, 7, 7, 8,
  119844. 7, 7, 7, 9, 9,10,12, 0, 8, 8, 8, 8, 8, 9, 8, 8,
  119845. 9, 9,10,10, 0, 8, 8, 8, 8, 8, 9, 8, 9, 9, 9,11,
  119846. 10, 0, 0,13, 9, 8, 9, 9, 9, 9,10,10,11,11, 0,13,
  119847. 0, 9, 9, 9, 9, 9, 9,11,10,11,11, 0, 0, 0, 8, 9,
  119848. 10, 9,10,10,13,11,12,12, 0, 0, 0, 8, 9, 9, 9,10,
  119849. 10,13,12,12,13, 0, 0, 0,12, 0,10,10,12,11,10,11,
  119850. 12,12, 0, 0, 0,13,13,10,10,10,11,12, 0,13, 0, 0,
  119851. 0, 0, 0, 0,13,11, 0,12,12,12,13,12, 0, 0, 0, 0,
  119852. 0, 0,13,13,11,13,13,11,12,
  119853. };
  119854. static float _vq_quantthresh__8c0_s_p8_0[] = {
  119855. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  119856. 12.5, 17.5, 22.5, 27.5,
  119857. };
  119858. static long _vq_quantmap__8c0_s_p8_0[] = {
  119859. 11, 9, 7, 5, 3, 1, 0, 2,
  119860. 4, 6, 8, 10, 12,
  119861. };
  119862. static encode_aux_threshmatch _vq_auxt__8c0_s_p8_0 = {
  119863. _vq_quantthresh__8c0_s_p8_0,
  119864. _vq_quantmap__8c0_s_p8_0,
  119865. 13,
  119866. 13
  119867. };
  119868. static static_codebook _8c0_s_p8_0 = {
  119869. 2, 169,
  119870. _vq_lengthlist__8c0_s_p8_0,
  119871. 1, -526516224, 1616117760, 4, 0,
  119872. _vq_quantlist__8c0_s_p8_0,
  119873. NULL,
  119874. &_vq_auxt__8c0_s_p8_0,
  119875. NULL,
  119876. 0
  119877. };
  119878. static long _vq_quantlist__8c0_s_p8_1[] = {
  119879. 2,
  119880. 1,
  119881. 3,
  119882. 0,
  119883. 4,
  119884. };
  119885. static long _vq_lengthlist__8c0_s_p8_1[] = {
  119886. 1, 3, 4, 5, 5, 7, 6, 6, 6, 5, 7, 7, 7, 6, 6, 7,
  119887. 7, 7, 6, 6, 7, 7, 7, 6, 6,
  119888. };
  119889. static float _vq_quantthresh__8c0_s_p8_1[] = {
  119890. -1.5, -0.5, 0.5, 1.5,
  119891. };
  119892. static long _vq_quantmap__8c0_s_p8_1[] = {
  119893. 3, 1, 0, 2, 4,
  119894. };
  119895. static encode_aux_threshmatch _vq_auxt__8c0_s_p8_1 = {
  119896. _vq_quantthresh__8c0_s_p8_1,
  119897. _vq_quantmap__8c0_s_p8_1,
  119898. 5,
  119899. 5
  119900. };
  119901. static static_codebook _8c0_s_p8_1 = {
  119902. 2, 25,
  119903. _vq_lengthlist__8c0_s_p8_1,
  119904. 1, -533725184, 1611661312, 3, 0,
  119905. _vq_quantlist__8c0_s_p8_1,
  119906. NULL,
  119907. &_vq_auxt__8c0_s_p8_1,
  119908. NULL,
  119909. 0
  119910. };
  119911. static long _vq_quantlist__8c0_s_p9_0[] = {
  119912. 1,
  119913. 0,
  119914. 2,
  119915. };
  119916. static long _vq_lengthlist__8c0_s_p9_0[] = {
  119917. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  119918. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  119919. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  119920. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  119921. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  119922. 7,
  119923. };
  119924. static float _vq_quantthresh__8c0_s_p9_0[] = {
  119925. -157.5, 157.5,
  119926. };
  119927. static long _vq_quantmap__8c0_s_p9_0[] = {
  119928. 1, 0, 2,
  119929. };
  119930. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_0 = {
  119931. _vq_quantthresh__8c0_s_p9_0,
  119932. _vq_quantmap__8c0_s_p9_0,
  119933. 3,
  119934. 3
  119935. };
  119936. static static_codebook _8c0_s_p9_0 = {
  119937. 4, 81,
  119938. _vq_lengthlist__8c0_s_p9_0,
  119939. 1, -518803456, 1628680192, 2, 0,
  119940. _vq_quantlist__8c0_s_p9_0,
  119941. NULL,
  119942. &_vq_auxt__8c0_s_p9_0,
  119943. NULL,
  119944. 0
  119945. };
  119946. static long _vq_quantlist__8c0_s_p9_1[] = {
  119947. 7,
  119948. 6,
  119949. 8,
  119950. 5,
  119951. 9,
  119952. 4,
  119953. 10,
  119954. 3,
  119955. 11,
  119956. 2,
  119957. 12,
  119958. 1,
  119959. 13,
  119960. 0,
  119961. 14,
  119962. };
  119963. static long _vq_lengthlist__8c0_s_p9_1[] = {
  119964. 1, 4, 4, 5, 5,10, 8,11,11,11,11,11,11,11,11, 6,
  119965. 6, 6, 7, 6,11,10,11,11,11,11,11,11,11,11, 7, 5,
  119966. 6, 6, 6, 8, 7,11,11,11,11,11,11,11,11,11, 7, 8,
  119967. 8, 8, 9, 9,11,11,11,11,11,11,11,11,11, 9, 8, 7,
  119968. 8, 9,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  119969. 11,11,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  119970. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  119971. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  119972. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  119973. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  119974. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  119975. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  119976. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  119977. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  119978. 11,
  119979. };
  119980. static float _vq_quantthresh__8c0_s_p9_1[] = {
  119981. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  119982. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  119983. };
  119984. static long _vq_quantmap__8c0_s_p9_1[] = {
  119985. 13, 11, 9, 7, 5, 3, 1, 0,
  119986. 2, 4, 6, 8, 10, 12, 14,
  119987. };
  119988. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_1 = {
  119989. _vq_quantthresh__8c0_s_p9_1,
  119990. _vq_quantmap__8c0_s_p9_1,
  119991. 15,
  119992. 15
  119993. };
  119994. static static_codebook _8c0_s_p9_1 = {
  119995. 2, 225,
  119996. _vq_lengthlist__8c0_s_p9_1,
  119997. 1, -520986624, 1620377600, 4, 0,
  119998. _vq_quantlist__8c0_s_p9_1,
  119999. NULL,
  120000. &_vq_auxt__8c0_s_p9_1,
  120001. NULL,
  120002. 0
  120003. };
  120004. static long _vq_quantlist__8c0_s_p9_2[] = {
  120005. 10,
  120006. 9,
  120007. 11,
  120008. 8,
  120009. 12,
  120010. 7,
  120011. 13,
  120012. 6,
  120013. 14,
  120014. 5,
  120015. 15,
  120016. 4,
  120017. 16,
  120018. 3,
  120019. 17,
  120020. 2,
  120021. 18,
  120022. 1,
  120023. 19,
  120024. 0,
  120025. 20,
  120026. };
  120027. static long _vq_lengthlist__8c0_s_p9_2[] = {
  120028. 1, 5, 5, 7, 7, 8, 7, 8, 8,10,10, 9, 9,10,10,10,
  120029. 11,11,10,12,11,12,12,12, 9, 8, 8, 8, 8, 8, 9,10,
  120030. 10,10,10,11,11,11,10,11,11,12,12,11,12, 8, 8, 7,
  120031. 7, 8, 9,10,10,10, 9,10,10, 9,10,10,11,11,11,11,
  120032. 11,11, 9, 9, 9, 9, 8, 9,10,10,11,10,10,11,11,12,
  120033. 10,10,12,12,11,11,10, 9, 9,10, 8, 9,10,10,10, 9,
  120034. 10,10,11,11,10,11,10,10,10,12,12,12, 9,10, 9,10,
  120035. 9, 9,10,10,11,11,11,11,10,10,10,11,12,11,12,11,
  120036. 12,10,11,10,11, 9,10, 9,10, 9,10,10, 9,10,10,11,
  120037. 10,11,11,11,11,12,11, 9,10,10,10,10,11,11,11,11,
  120038. 11,10,11,11,11,11,10,12,10,12,12,11,12,10,10,11,
  120039. 10, 9,11,10,11, 9,10,11,10,10,10,11,11,11,11,12,
  120040. 12,10, 9, 9,11,10, 9,12,11,10,12,12,11,11,11,11,
  120041. 10,11,11,12,11,10,12, 9,11,10,11,10,10,11,10,11,
  120042. 9,10,10,10,11,12,11,11,12,11,10,10,11,11, 9,10,
  120043. 10,12,10,11,10,10,10, 9,10,10,10,10, 9,10,10,11,
  120044. 11,11,11,12,11,10,10,10,10,11,11,10,11,11, 9,11,
  120045. 10,12,10,12,11,10,11,10,10,10,11,10,10,11,11,10,
  120046. 11,10,10,10,10,11,11,12,10,10,10,11,10,11,12,11,
  120047. 10,11,10,10,11,11,10,12,10, 9,10,10,11,11,11,10,
  120048. 12,10,10,11,11,11,10,10,11,10,10,10,11,10,11,10,
  120049. 12,11,11,10,10,10,12,10,10,11, 9,10,11,11,11,10,
  120050. 10,11,10,10, 9,11,11,12,12,11,12,11,11,11,11,11,
  120051. 11, 9,10,11,10,12,10,10,10,10,11,10,10,11,10,10,
  120052. 12,10,10,10,10,10, 9,12,10,10,10,10,12, 9,11,10,
  120053. 10,11,10,12,12,10,12,12,12,10,10,10,10, 9,10,11,
  120054. 10,10,12,10,10,12,11,10,11,10,10,12,11,10,12,10,
  120055. 10,11, 9,11,10, 9,10, 9,10,
  120056. };
  120057. static float _vq_quantthresh__8c0_s_p9_2[] = {
  120058. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  120059. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  120060. 6.5, 7.5, 8.5, 9.5,
  120061. };
  120062. static long _vq_quantmap__8c0_s_p9_2[] = {
  120063. 19, 17, 15, 13, 11, 9, 7, 5,
  120064. 3, 1, 0, 2, 4, 6, 8, 10,
  120065. 12, 14, 16, 18, 20,
  120066. };
  120067. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_2 = {
  120068. _vq_quantthresh__8c0_s_p9_2,
  120069. _vq_quantmap__8c0_s_p9_2,
  120070. 21,
  120071. 21
  120072. };
  120073. static static_codebook _8c0_s_p9_2 = {
  120074. 2, 441,
  120075. _vq_lengthlist__8c0_s_p9_2,
  120076. 1, -529268736, 1611661312, 5, 0,
  120077. _vq_quantlist__8c0_s_p9_2,
  120078. NULL,
  120079. &_vq_auxt__8c0_s_p9_2,
  120080. NULL,
  120081. 0
  120082. };
  120083. static long _huff_lengthlist__8c0_s_single[] = {
  120084. 4, 5,18, 7,10, 6, 7, 8, 9,10, 5, 2,18, 5, 7, 5,
  120085. 6, 7, 8,11,17,17,17,17,17,17,17,17,17,17, 7, 4,
  120086. 17, 6, 9, 6, 8,10,12,15,11, 7,17, 9, 6, 6, 7, 9,
  120087. 11,15, 6, 4,17, 6, 6, 4, 5, 8,11,16, 6, 6,17, 8,
  120088. 6, 5, 6, 9,13,16, 8, 9,17,11, 9, 8, 8,11,13,17,
  120089. 9,12,17,15,14,13,12,13,14,17,12,15,17,17,17,17,
  120090. 17,16,17,17,
  120091. };
  120092. static static_codebook _huff_book__8c0_s_single = {
  120093. 2, 100,
  120094. _huff_lengthlist__8c0_s_single,
  120095. 0, 0, 0, 0, 0,
  120096. NULL,
  120097. NULL,
  120098. NULL,
  120099. NULL,
  120100. 0
  120101. };
  120102. static long _vq_quantlist__8c1_s_p1_0[] = {
  120103. 1,
  120104. 0,
  120105. 2,
  120106. };
  120107. static long _vq_lengthlist__8c1_s_p1_0[] = {
  120108. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  120109. 0, 0, 5, 7, 7, 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, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 8, 9, 0, 0, 0,
  120114. 0, 0, 0, 7, 8, 9, 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, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  120119. 0, 0, 0, 0, 7, 9, 8, 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, 0, 0, 0, 0, 0, 0, 0,
  120140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0,
  120145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0,
  120150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  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, 5, 8, 8, 0, 0, 0, 0,
  120154. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0,
  120159. 0, 0, 0, 8, 8,10, 0, 0, 0, 0, 0, 0, 9,10,10, 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, 7, 9, 9, 0, 0,
  120164. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120186. 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120191. 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  120200. 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  120205. 0, 0, 0, 0, 0, 8, 9,10, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  120210. 0, 0, 0, 0, 0, 0, 8,10, 8, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120518. 0,
  120519. };
  120520. static float _vq_quantthresh__8c1_s_p1_0[] = {
  120521. -0.5, 0.5,
  120522. };
  120523. static long _vq_quantmap__8c1_s_p1_0[] = {
  120524. 1, 0, 2,
  120525. };
  120526. static encode_aux_threshmatch _vq_auxt__8c1_s_p1_0 = {
  120527. _vq_quantthresh__8c1_s_p1_0,
  120528. _vq_quantmap__8c1_s_p1_0,
  120529. 3,
  120530. 3
  120531. };
  120532. static static_codebook _8c1_s_p1_0 = {
  120533. 8, 6561,
  120534. _vq_lengthlist__8c1_s_p1_0,
  120535. 1, -535822336, 1611661312, 2, 0,
  120536. _vq_quantlist__8c1_s_p1_0,
  120537. NULL,
  120538. &_vq_auxt__8c1_s_p1_0,
  120539. NULL,
  120540. 0
  120541. };
  120542. static long _vq_quantlist__8c1_s_p2_0[] = {
  120543. 2,
  120544. 1,
  120545. 3,
  120546. 0,
  120547. 4,
  120548. };
  120549. static long _vq_lengthlist__8c1_s_p2_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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120589. 0,
  120590. };
  120591. static float _vq_quantthresh__8c1_s_p2_0[] = {
  120592. -1.5, -0.5, 0.5, 1.5,
  120593. };
  120594. static long _vq_quantmap__8c1_s_p2_0[] = {
  120595. 3, 1, 0, 2, 4,
  120596. };
  120597. static encode_aux_threshmatch _vq_auxt__8c1_s_p2_0 = {
  120598. _vq_quantthresh__8c1_s_p2_0,
  120599. _vq_quantmap__8c1_s_p2_0,
  120600. 5,
  120601. 5
  120602. };
  120603. static static_codebook _8c1_s_p2_0 = {
  120604. 4, 625,
  120605. _vq_lengthlist__8c1_s_p2_0,
  120606. 1, -533725184, 1611661312, 3, 0,
  120607. _vq_quantlist__8c1_s_p2_0,
  120608. NULL,
  120609. &_vq_auxt__8c1_s_p2_0,
  120610. NULL,
  120611. 0
  120612. };
  120613. static long _vq_quantlist__8c1_s_p3_0[] = {
  120614. 2,
  120615. 1,
  120616. 3,
  120617. 0,
  120618. 4,
  120619. };
  120620. static long _vq_lengthlist__8c1_s_p3_0[] = {
  120621. 2, 4, 4, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  120623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120624. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 7, 7,
  120626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120627. 0, 0, 0, 0, 6, 6, 6, 7, 7, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120660. 0,
  120661. };
  120662. static float _vq_quantthresh__8c1_s_p3_0[] = {
  120663. -1.5, -0.5, 0.5, 1.5,
  120664. };
  120665. static long _vq_quantmap__8c1_s_p3_0[] = {
  120666. 3, 1, 0, 2, 4,
  120667. };
  120668. static encode_aux_threshmatch _vq_auxt__8c1_s_p3_0 = {
  120669. _vq_quantthresh__8c1_s_p3_0,
  120670. _vq_quantmap__8c1_s_p3_0,
  120671. 5,
  120672. 5
  120673. };
  120674. static static_codebook _8c1_s_p3_0 = {
  120675. 4, 625,
  120676. _vq_lengthlist__8c1_s_p3_0,
  120677. 1, -533725184, 1611661312, 3, 0,
  120678. _vq_quantlist__8c1_s_p3_0,
  120679. NULL,
  120680. &_vq_auxt__8c1_s_p3_0,
  120681. NULL,
  120682. 0
  120683. };
  120684. static long _vq_quantlist__8c1_s_p4_0[] = {
  120685. 4,
  120686. 3,
  120687. 5,
  120688. 2,
  120689. 6,
  120690. 1,
  120691. 7,
  120692. 0,
  120693. 8,
  120694. };
  120695. static long _vq_lengthlist__8c1_s_p4_0[] = {
  120696. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  120697. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  120698. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  120699. 8, 8, 0, 0, 0, 0, 0, 0, 0, 9, 8, 0, 0, 0, 0, 0,
  120700. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120701. 0,
  120702. };
  120703. static float _vq_quantthresh__8c1_s_p4_0[] = {
  120704. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  120705. };
  120706. static long _vq_quantmap__8c1_s_p4_0[] = {
  120707. 7, 5, 3, 1, 0, 2, 4, 6,
  120708. 8,
  120709. };
  120710. static encode_aux_threshmatch _vq_auxt__8c1_s_p4_0 = {
  120711. _vq_quantthresh__8c1_s_p4_0,
  120712. _vq_quantmap__8c1_s_p4_0,
  120713. 9,
  120714. 9
  120715. };
  120716. static static_codebook _8c1_s_p4_0 = {
  120717. 2, 81,
  120718. _vq_lengthlist__8c1_s_p4_0,
  120719. 1, -531628032, 1611661312, 4, 0,
  120720. _vq_quantlist__8c1_s_p4_0,
  120721. NULL,
  120722. &_vq_auxt__8c1_s_p4_0,
  120723. NULL,
  120724. 0
  120725. };
  120726. static long _vq_quantlist__8c1_s_p5_0[] = {
  120727. 4,
  120728. 3,
  120729. 5,
  120730. 2,
  120731. 6,
  120732. 1,
  120733. 7,
  120734. 0,
  120735. 8,
  120736. };
  120737. static long _vq_lengthlist__8c1_s_p5_0[] = {
  120738. 1, 3, 3, 4, 5, 6, 6, 8, 8, 0, 0, 0, 8, 8, 7, 7,
  120739. 9, 9, 0, 0, 0, 8, 8, 7, 7, 9, 9, 0, 0, 0, 9,10,
  120740. 8, 8, 9, 9, 0, 0, 0,10,10, 8, 8, 9, 9, 0, 0, 0,
  120741. 11,10, 8, 8,10,10, 0, 0, 0,11,11, 8, 8,10,10, 0,
  120742. 0, 0,12,12, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  120743. 10,
  120744. };
  120745. static float _vq_quantthresh__8c1_s_p5_0[] = {
  120746. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  120747. };
  120748. static long _vq_quantmap__8c1_s_p5_0[] = {
  120749. 7, 5, 3, 1, 0, 2, 4, 6,
  120750. 8,
  120751. };
  120752. static encode_aux_threshmatch _vq_auxt__8c1_s_p5_0 = {
  120753. _vq_quantthresh__8c1_s_p5_0,
  120754. _vq_quantmap__8c1_s_p5_0,
  120755. 9,
  120756. 9
  120757. };
  120758. static static_codebook _8c1_s_p5_0 = {
  120759. 2, 81,
  120760. _vq_lengthlist__8c1_s_p5_0,
  120761. 1, -531628032, 1611661312, 4, 0,
  120762. _vq_quantlist__8c1_s_p5_0,
  120763. NULL,
  120764. &_vq_auxt__8c1_s_p5_0,
  120765. NULL,
  120766. 0
  120767. };
  120768. static long _vq_quantlist__8c1_s_p6_0[] = {
  120769. 8,
  120770. 7,
  120771. 9,
  120772. 6,
  120773. 10,
  120774. 5,
  120775. 11,
  120776. 4,
  120777. 12,
  120778. 3,
  120779. 13,
  120780. 2,
  120781. 14,
  120782. 1,
  120783. 15,
  120784. 0,
  120785. 16,
  120786. };
  120787. static long _vq_lengthlist__8c1_s_p6_0[] = {
  120788. 1, 3, 3, 5, 5, 8, 8, 8, 8, 9, 9,10,10,11,11,11,
  120789. 11, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,11,
  120790. 12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  120791. 11,12,12, 0, 0, 0, 9, 9, 8, 8,10,10,10,10,11,11,
  120792. 12,12,12,12, 0, 0, 0, 9, 9, 8, 8,10,10,10,10,11,
  120793. 11,12,12,12,12, 0, 0, 0,10,10, 9, 9,10,10,10,10,
  120794. 11,11,12,12,13,13, 0, 0, 0,10,10, 9, 9,10,10,10,
  120795. 10,11,11,12,12,13,13, 0, 0, 0,11,11, 9, 9,10,10,
  120796. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  120797. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  120798. 10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0, 9,
  120799. 9,10,10,11,11,12,11,12,12,13,13, 0, 0, 0, 0, 0,
  120800. 10,10,11,11,11,11,12,12,13,12,13,13, 0, 0, 0, 0,
  120801. 0, 0, 0,11,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  120802. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  120803. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,13, 0,
  120804. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  120805. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  120806. 14,
  120807. };
  120808. static float _vq_quantthresh__8c1_s_p6_0[] = {
  120809. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  120810. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  120811. };
  120812. static long _vq_quantmap__8c1_s_p6_0[] = {
  120813. 15, 13, 11, 9, 7, 5, 3, 1,
  120814. 0, 2, 4, 6, 8, 10, 12, 14,
  120815. 16,
  120816. };
  120817. static encode_aux_threshmatch _vq_auxt__8c1_s_p6_0 = {
  120818. _vq_quantthresh__8c1_s_p6_0,
  120819. _vq_quantmap__8c1_s_p6_0,
  120820. 17,
  120821. 17
  120822. };
  120823. static static_codebook _8c1_s_p6_0 = {
  120824. 2, 289,
  120825. _vq_lengthlist__8c1_s_p6_0,
  120826. 1, -529530880, 1611661312, 5, 0,
  120827. _vq_quantlist__8c1_s_p6_0,
  120828. NULL,
  120829. &_vq_auxt__8c1_s_p6_0,
  120830. NULL,
  120831. 0
  120832. };
  120833. static long _vq_quantlist__8c1_s_p7_0[] = {
  120834. 1,
  120835. 0,
  120836. 2,
  120837. };
  120838. static long _vq_lengthlist__8c1_s_p7_0[] = {
  120839. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,10,
  120840. 9, 9, 5, 7, 7,10, 9, 9,10, 9, 9, 6,10,10,10,10,
  120841. 10,11,10,10, 6, 9, 9,10, 9,10,11,10,10, 6, 9, 9,
  120842. 10, 9, 9,11, 9,10, 7,10,10,11,11,11,11,10,10, 6,
  120843. 9, 9,10,10,10,11, 9, 9, 6, 9, 9,10,10,10,10, 9,
  120844. 9,
  120845. };
  120846. static float _vq_quantthresh__8c1_s_p7_0[] = {
  120847. -5.5, 5.5,
  120848. };
  120849. static long _vq_quantmap__8c1_s_p7_0[] = {
  120850. 1, 0, 2,
  120851. };
  120852. static encode_aux_threshmatch _vq_auxt__8c1_s_p7_0 = {
  120853. _vq_quantthresh__8c1_s_p7_0,
  120854. _vq_quantmap__8c1_s_p7_0,
  120855. 3,
  120856. 3
  120857. };
  120858. static static_codebook _8c1_s_p7_0 = {
  120859. 4, 81,
  120860. _vq_lengthlist__8c1_s_p7_0,
  120861. 1, -529137664, 1618345984, 2, 0,
  120862. _vq_quantlist__8c1_s_p7_0,
  120863. NULL,
  120864. &_vq_auxt__8c1_s_p7_0,
  120865. NULL,
  120866. 0
  120867. };
  120868. static long _vq_quantlist__8c1_s_p7_1[] = {
  120869. 5,
  120870. 4,
  120871. 6,
  120872. 3,
  120873. 7,
  120874. 2,
  120875. 8,
  120876. 1,
  120877. 9,
  120878. 0,
  120879. 10,
  120880. };
  120881. static long _vq_lengthlist__8c1_s_p7_1[] = {
  120882. 2, 3, 3, 5, 5, 7, 7, 7, 7, 7, 7,10,10, 9, 7, 7,
  120883. 7, 7, 8, 8, 8, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8, 8,
  120884. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  120885. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  120886. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  120887. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  120888. 8, 8, 8,10,10,10,10,10, 8, 8, 8, 8, 8, 8,10,10,
  120889. 10,10,10, 8, 8, 8, 8, 8, 8,
  120890. };
  120891. static float _vq_quantthresh__8c1_s_p7_1[] = {
  120892. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  120893. 3.5, 4.5,
  120894. };
  120895. static long _vq_quantmap__8c1_s_p7_1[] = {
  120896. 9, 7, 5, 3, 1, 0, 2, 4,
  120897. 6, 8, 10,
  120898. };
  120899. static encode_aux_threshmatch _vq_auxt__8c1_s_p7_1 = {
  120900. _vq_quantthresh__8c1_s_p7_1,
  120901. _vq_quantmap__8c1_s_p7_1,
  120902. 11,
  120903. 11
  120904. };
  120905. static static_codebook _8c1_s_p7_1 = {
  120906. 2, 121,
  120907. _vq_lengthlist__8c1_s_p7_1,
  120908. 1, -531365888, 1611661312, 4, 0,
  120909. _vq_quantlist__8c1_s_p7_1,
  120910. NULL,
  120911. &_vq_auxt__8c1_s_p7_1,
  120912. NULL,
  120913. 0
  120914. };
  120915. static long _vq_quantlist__8c1_s_p8_0[] = {
  120916. 6,
  120917. 5,
  120918. 7,
  120919. 4,
  120920. 8,
  120921. 3,
  120922. 9,
  120923. 2,
  120924. 10,
  120925. 1,
  120926. 11,
  120927. 0,
  120928. 12,
  120929. };
  120930. static long _vq_lengthlist__8c1_s_p8_0[] = {
  120931. 1, 4, 4, 6, 6, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5,
  120932. 7, 7, 8, 8, 8, 8, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  120933. 8, 9, 9,10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  120934. 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  120935. 11, 0,12,12, 9, 9, 9, 9,10, 9,10,11,11,11, 0,13,
  120936. 12, 9, 8, 9, 9,10,10,11,11,12,11, 0, 0, 0, 9, 9,
  120937. 9, 9,10,10,11,11,12,12, 0, 0, 0,10,10, 9, 9,10,
  120938. 10,11,11,12,12, 0, 0, 0,13,13,10,10,11,11,12,11,
  120939. 13,12, 0, 0, 0,14,14,10,10,11,10,11,11,12,12, 0,
  120940. 0, 0, 0, 0,12,12,11,11,12,12,13,13, 0, 0, 0, 0,
  120941. 0,12,12,11,10,12,11,13,12,
  120942. };
  120943. static float _vq_quantthresh__8c1_s_p8_0[] = {
  120944. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  120945. 12.5, 17.5, 22.5, 27.5,
  120946. };
  120947. static long _vq_quantmap__8c1_s_p8_0[] = {
  120948. 11, 9, 7, 5, 3, 1, 0, 2,
  120949. 4, 6, 8, 10, 12,
  120950. };
  120951. static encode_aux_threshmatch _vq_auxt__8c1_s_p8_0 = {
  120952. _vq_quantthresh__8c1_s_p8_0,
  120953. _vq_quantmap__8c1_s_p8_0,
  120954. 13,
  120955. 13
  120956. };
  120957. static static_codebook _8c1_s_p8_0 = {
  120958. 2, 169,
  120959. _vq_lengthlist__8c1_s_p8_0,
  120960. 1, -526516224, 1616117760, 4, 0,
  120961. _vq_quantlist__8c1_s_p8_0,
  120962. NULL,
  120963. &_vq_auxt__8c1_s_p8_0,
  120964. NULL,
  120965. 0
  120966. };
  120967. static long _vq_quantlist__8c1_s_p8_1[] = {
  120968. 2,
  120969. 1,
  120970. 3,
  120971. 0,
  120972. 4,
  120973. };
  120974. static long _vq_lengthlist__8c1_s_p8_1[] = {
  120975. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  120976. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  120977. };
  120978. static float _vq_quantthresh__8c1_s_p8_1[] = {
  120979. -1.5, -0.5, 0.5, 1.5,
  120980. };
  120981. static long _vq_quantmap__8c1_s_p8_1[] = {
  120982. 3, 1, 0, 2, 4,
  120983. };
  120984. static encode_aux_threshmatch _vq_auxt__8c1_s_p8_1 = {
  120985. _vq_quantthresh__8c1_s_p8_1,
  120986. _vq_quantmap__8c1_s_p8_1,
  120987. 5,
  120988. 5
  120989. };
  120990. static static_codebook _8c1_s_p8_1 = {
  120991. 2, 25,
  120992. _vq_lengthlist__8c1_s_p8_1,
  120993. 1, -533725184, 1611661312, 3, 0,
  120994. _vq_quantlist__8c1_s_p8_1,
  120995. NULL,
  120996. &_vq_auxt__8c1_s_p8_1,
  120997. NULL,
  120998. 0
  120999. };
  121000. static long _vq_quantlist__8c1_s_p9_0[] = {
  121001. 6,
  121002. 5,
  121003. 7,
  121004. 4,
  121005. 8,
  121006. 3,
  121007. 9,
  121008. 2,
  121009. 10,
  121010. 1,
  121011. 11,
  121012. 0,
  121013. 12,
  121014. };
  121015. static long _vq_lengthlist__8c1_s_p9_0[] = {
  121016. 1, 3, 3,10,10,10,10,10,10,10,10,10,10, 5, 6, 6,
  121017. 10,10,10,10,10,10,10,10,10,10, 6, 7, 8,10,10,10,
  121018. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121019. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121020. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121021. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121022. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121023. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121024. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121025. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121026. 10,10,10,10,10, 9, 9, 9, 9,
  121027. };
  121028. static float _vq_quantthresh__8c1_s_p9_0[] = {
  121029. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  121030. 787.5, 1102.5, 1417.5, 1732.5,
  121031. };
  121032. static long _vq_quantmap__8c1_s_p9_0[] = {
  121033. 11, 9, 7, 5, 3, 1, 0, 2,
  121034. 4, 6, 8, 10, 12,
  121035. };
  121036. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_0 = {
  121037. _vq_quantthresh__8c1_s_p9_0,
  121038. _vq_quantmap__8c1_s_p9_0,
  121039. 13,
  121040. 13
  121041. };
  121042. static static_codebook _8c1_s_p9_0 = {
  121043. 2, 169,
  121044. _vq_lengthlist__8c1_s_p9_0,
  121045. 1, -513964032, 1628680192, 4, 0,
  121046. _vq_quantlist__8c1_s_p9_0,
  121047. NULL,
  121048. &_vq_auxt__8c1_s_p9_0,
  121049. NULL,
  121050. 0
  121051. };
  121052. static long _vq_quantlist__8c1_s_p9_1[] = {
  121053. 7,
  121054. 6,
  121055. 8,
  121056. 5,
  121057. 9,
  121058. 4,
  121059. 10,
  121060. 3,
  121061. 11,
  121062. 2,
  121063. 12,
  121064. 1,
  121065. 13,
  121066. 0,
  121067. 14,
  121068. };
  121069. static long _vq_lengthlist__8c1_s_p9_1[] = {
  121070. 1, 4, 4, 5, 5, 7, 7, 9, 9,11,11,12,12,13,13, 6,
  121071. 5, 5, 6, 6, 9, 9,10,10,12,12,12,13,15,14, 6, 5,
  121072. 5, 7, 7, 9, 9,10,10,12,12,12,13,14,13,17, 7, 7,
  121073. 8, 8,10,10,11,11,12,13,13,13,13,13,17, 7, 7, 8,
  121074. 8,10,10,11,11,13,13,13,13,14,14,17,11,11, 9, 9,
  121075. 11,11,12,12,12,13,13,14,15,13,17,12,12, 9, 9,11,
  121076. 11,12,12,13,13,13,13,14,16,17,17,17,11,12,12,12,
  121077. 13,13,13,14,15,14,15,15,17,17,17,12,12,11,11,13,
  121078. 13,14,14,15,14,15,15,17,17,17,15,15,13,13,14,14,
  121079. 15,14,15,15,16,15,17,17,17,15,15,13,13,13,14,14,
  121080. 15,15,15,15,16,17,17,17,17,16,14,15,14,14,15,14,
  121081. 14,15,15,15,17,17,17,17,17,14,14,16,14,15,15,15,
  121082. 15,15,15,17,17,17,17,17,17,16,16,15,17,15,15,14,
  121083. 17,15,17,16,17,17,17,17,16,15,14,15,15,15,15,15,
  121084. 15,
  121085. };
  121086. static float _vq_quantthresh__8c1_s_p9_1[] = {
  121087. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  121088. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  121089. };
  121090. static long _vq_quantmap__8c1_s_p9_1[] = {
  121091. 13, 11, 9, 7, 5, 3, 1, 0,
  121092. 2, 4, 6, 8, 10, 12, 14,
  121093. };
  121094. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_1 = {
  121095. _vq_quantthresh__8c1_s_p9_1,
  121096. _vq_quantmap__8c1_s_p9_1,
  121097. 15,
  121098. 15
  121099. };
  121100. static static_codebook _8c1_s_p9_1 = {
  121101. 2, 225,
  121102. _vq_lengthlist__8c1_s_p9_1,
  121103. 1, -520986624, 1620377600, 4, 0,
  121104. _vq_quantlist__8c1_s_p9_1,
  121105. NULL,
  121106. &_vq_auxt__8c1_s_p9_1,
  121107. NULL,
  121108. 0
  121109. };
  121110. static long _vq_quantlist__8c1_s_p9_2[] = {
  121111. 10,
  121112. 9,
  121113. 11,
  121114. 8,
  121115. 12,
  121116. 7,
  121117. 13,
  121118. 6,
  121119. 14,
  121120. 5,
  121121. 15,
  121122. 4,
  121123. 16,
  121124. 3,
  121125. 17,
  121126. 2,
  121127. 18,
  121128. 1,
  121129. 19,
  121130. 0,
  121131. 20,
  121132. };
  121133. static long _vq_lengthlist__8c1_s_p9_2[] = {
  121134. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9,
  121135. 9, 9, 9, 9, 9,11,11,12, 7, 7, 7, 7, 8, 8, 9, 9,
  121136. 9, 9,10,10,10,10,10,10,10,10,11,11,11, 7, 7, 7,
  121137. 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,11,
  121138. 11,12, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,10,
  121139. 10,10,10,10,11,11,11, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  121140. 9,10,10,10,10,10,10,10,10,11,11,11, 8, 8, 8, 8,
  121141. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,11,11,
  121142. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,
  121143. 10,10,10,11,12,11, 9, 9, 8, 9, 9, 9, 9, 9,10,10,
  121144. 10,10,10,10,10,10,10,10,11,11,11,11,11, 8, 8, 9,
  121145. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,11,12,11,
  121146. 12,11, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  121147. 10,10,11,11,11,11,11, 9, 9, 9, 9,10,10,10,10,10,
  121148. 10,10,10,10,10,10,10,12,11,12,11,11, 9, 9, 9,10,
  121149. 10,10,10,10,10,10,10,10,10,10,10,10,12,11,11,11,
  121150. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121151. 11,11,11,12,11,11,12,11,10,10,10,10,10,10,10,10,
  121152. 10,10,10,10,11,10,11,11,11,11,11,11,11,10,10,10,
  121153. 10,10,10,10,10,10,10,10,10,10,10,11,11,12,11,12,
  121154. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121155. 11,11,12,11,12,11,11,11,11,10,10,10,10,10,10,10,
  121156. 10,10,10,10,10,11,11,12,11,11,12,11,11,12,10,10,
  121157. 11,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  121158. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,12,
  121159. 12,11,12,11,11,12,12,12,11,11,10,10,10,10,10,10,
  121160. 10,10,10,11,12,12,11,12,12,11,12,11,11,11,11,10,
  121161. 10,10,10,10,10,10,10,10,10,
  121162. };
  121163. static float _vq_quantthresh__8c1_s_p9_2[] = {
  121164. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  121165. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  121166. 6.5, 7.5, 8.5, 9.5,
  121167. };
  121168. static long _vq_quantmap__8c1_s_p9_2[] = {
  121169. 19, 17, 15, 13, 11, 9, 7, 5,
  121170. 3, 1, 0, 2, 4, 6, 8, 10,
  121171. 12, 14, 16, 18, 20,
  121172. };
  121173. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_2 = {
  121174. _vq_quantthresh__8c1_s_p9_2,
  121175. _vq_quantmap__8c1_s_p9_2,
  121176. 21,
  121177. 21
  121178. };
  121179. static static_codebook _8c1_s_p9_2 = {
  121180. 2, 441,
  121181. _vq_lengthlist__8c1_s_p9_2,
  121182. 1, -529268736, 1611661312, 5, 0,
  121183. _vq_quantlist__8c1_s_p9_2,
  121184. NULL,
  121185. &_vq_auxt__8c1_s_p9_2,
  121186. NULL,
  121187. 0
  121188. };
  121189. static long _huff_lengthlist__8c1_s_single[] = {
  121190. 4, 6,18, 8,11, 8, 8, 9, 9,10, 4, 4,18, 5, 9, 5,
  121191. 6, 7, 8,10,18,18,18,18,17,17,17,17,17,17, 7, 5,
  121192. 17, 6,11, 6, 7, 8, 9,12,12, 9,17,12, 8, 8, 9,10,
  121193. 10,13, 7, 5,17, 6, 8, 4, 5, 6, 8,10, 6, 5,17, 6,
  121194. 8, 5, 4, 5, 7, 9, 7, 7,17, 8, 9, 6, 5, 5, 6, 8,
  121195. 8, 8,17, 9,11, 8, 6, 6, 6, 7, 9,10,17,12,12,10,
  121196. 9, 7, 7, 8,
  121197. };
  121198. static static_codebook _huff_book__8c1_s_single = {
  121199. 2, 100,
  121200. _huff_lengthlist__8c1_s_single,
  121201. 0, 0, 0, 0, 0,
  121202. NULL,
  121203. NULL,
  121204. NULL,
  121205. NULL,
  121206. 0
  121207. };
  121208. static long _huff_lengthlist__44c2_s_long[] = {
  121209. 6, 6,12,10,10,10, 9,10,12,12, 6, 1,10, 5, 6, 6,
  121210. 7, 9,11,14,12, 9, 8,11, 7, 8, 9,11,13,15,10, 5,
  121211. 12, 7, 8, 7, 9,12,14,15,10, 6, 7, 8, 5, 6, 7, 9,
  121212. 12,14, 9, 6, 8, 7, 6, 6, 7, 9,12,12, 9, 7, 9, 9,
  121213. 7, 6, 6, 7,10,10,10, 9,10,11, 8, 7, 6, 6, 8,10,
  121214. 12,11,13,13,11,10, 8, 8, 8,10,11,13,15,15,14,13,
  121215. 10, 8, 8, 9,
  121216. };
  121217. static static_codebook _huff_book__44c2_s_long = {
  121218. 2, 100,
  121219. _huff_lengthlist__44c2_s_long,
  121220. 0, 0, 0, 0, 0,
  121221. NULL,
  121222. NULL,
  121223. NULL,
  121224. NULL,
  121225. 0
  121226. };
  121227. static long _vq_quantlist__44c2_s_p1_0[] = {
  121228. 1,
  121229. 0,
  121230. 2,
  121231. };
  121232. static long _vq_lengthlist__44c2_s_p1_0[] = {
  121233. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  121234. 0, 0, 5, 6, 7, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  121239. 0, 0, 0, 6, 8, 8, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  121244. 0, 0, 0, 0, 7, 8, 8, 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, 0, 0, 0, 0, 0, 0, 0,
  121265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0,
  121270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0,
  121275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  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, 5, 7, 7, 0, 0, 0, 0,
  121279. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 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, 7, 8, 8, 0, 0, 0,
  121284. 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 6, 8, 8, 0, 0,
  121289. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121311. 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121316. 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  121325. 0, 0, 0, 0, 7, 8, 8, 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, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  121330. 0, 0, 0, 0, 0, 8, 8, 9, 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, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  121335. 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121643. 0,
  121644. };
  121645. static float _vq_quantthresh__44c2_s_p1_0[] = {
  121646. -0.5, 0.5,
  121647. };
  121648. static long _vq_quantmap__44c2_s_p1_0[] = {
  121649. 1, 0, 2,
  121650. };
  121651. static encode_aux_threshmatch _vq_auxt__44c2_s_p1_0 = {
  121652. _vq_quantthresh__44c2_s_p1_0,
  121653. _vq_quantmap__44c2_s_p1_0,
  121654. 3,
  121655. 3
  121656. };
  121657. static static_codebook _44c2_s_p1_0 = {
  121658. 8, 6561,
  121659. _vq_lengthlist__44c2_s_p1_0,
  121660. 1, -535822336, 1611661312, 2, 0,
  121661. _vq_quantlist__44c2_s_p1_0,
  121662. NULL,
  121663. &_vq_auxt__44c2_s_p1_0,
  121664. NULL,
  121665. 0
  121666. };
  121667. static long _vq_quantlist__44c2_s_p2_0[] = {
  121668. 2,
  121669. 1,
  121670. 3,
  121671. 0,
  121672. 4,
  121673. };
  121674. static long _vq_lengthlist__44c2_s_p2_0[] = {
  121675. 1, 4, 4, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0,
  121676. 8, 8, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 0, 0, 0, 8,
  121677. 8, 0, 0, 0, 8, 8, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0,
  121678. 0, 0, 4, 6, 6, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8, 0,
  121679. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 7, 8, 8, 0, 0, 0,11,11, 0, 0,
  121685. 0,11,11, 0, 0, 0,12,11, 0, 0, 0, 0, 0, 0, 0, 7,
  121686. 8, 8, 0, 0, 0,10,11, 0, 0, 0,11,11, 0, 0, 0,11,
  121687. 12, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 6, 8, 8, 0, 0, 0,11,11, 0, 0, 0,11,11,
  121693. 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0,
  121694. 0, 0,10,11, 0, 0, 0,10,11, 0, 0, 0,11,11, 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. 8, 9, 9, 0, 0, 0,11,12, 0, 0, 0,11,12, 0, 0, 0,
  121701. 12,11, 0, 0, 0, 0, 0, 0, 0, 8,10, 9, 0, 0, 0,12,
  121702. 11, 0, 0, 0,12,11, 0, 0, 0,11,12, 0, 0, 0, 0, 0,
  121703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121714. 0,
  121715. };
  121716. static float _vq_quantthresh__44c2_s_p2_0[] = {
  121717. -1.5, -0.5, 0.5, 1.5,
  121718. };
  121719. static long _vq_quantmap__44c2_s_p2_0[] = {
  121720. 3, 1, 0, 2, 4,
  121721. };
  121722. static encode_aux_threshmatch _vq_auxt__44c2_s_p2_0 = {
  121723. _vq_quantthresh__44c2_s_p2_0,
  121724. _vq_quantmap__44c2_s_p2_0,
  121725. 5,
  121726. 5
  121727. };
  121728. static static_codebook _44c2_s_p2_0 = {
  121729. 4, 625,
  121730. _vq_lengthlist__44c2_s_p2_0,
  121731. 1, -533725184, 1611661312, 3, 0,
  121732. _vq_quantlist__44c2_s_p2_0,
  121733. NULL,
  121734. &_vq_auxt__44c2_s_p2_0,
  121735. NULL,
  121736. 0
  121737. };
  121738. static long _vq_quantlist__44c2_s_p3_0[] = {
  121739. 2,
  121740. 1,
  121741. 3,
  121742. 0,
  121743. 4,
  121744. };
  121745. static long _vq_lengthlist__44c2_s_p3_0[] = {
  121746. 2, 4, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  121748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121749. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  121751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121752. 0, 0, 0, 0, 6, 6, 7, 9, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121785. 0,
  121786. };
  121787. static float _vq_quantthresh__44c2_s_p3_0[] = {
  121788. -1.5, -0.5, 0.5, 1.5,
  121789. };
  121790. static long _vq_quantmap__44c2_s_p3_0[] = {
  121791. 3, 1, 0, 2, 4,
  121792. };
  121793. static encode_aux_threshmatch _vq_auxt__44c2_s_p3_0 = {
  121794. _vq_quantthresh__44c2_s_p3_0,
  121795. _vq_quantmap__44c2_s_p3_0,
  121796. 5,
  121797. 5
  121798. };
  121799. static static_codebook _44c2_s_p3_0 = {
  121800. 4, 625,
  121801. _vq_lengthlist__44c2_s_p3_0,
  121802. 1, -533725184, 1611661312, 3, 0,
  121803. _vq_quantlist__44c2_s_p3_0,
  121804. NULL,
  121805. &_vq_auxt__44c2_s_p3_0,
  121806. NULL,
  121807. 0
  121808. };
  121809. static long _vq_quantlist__44c2_s_p4_0[] = {
  121810. 4,
  121811. 3,
  121812. 5,
  121813. 2,
  121814. 6,
  121815. 1,
  121816. 7,
  121817. 0,
  121818. 8,
  121819. };
  121820. static long _vq_lengthlist__44c2_s_p4_0[] = {
  121821. 1, 3, 3, 6, 6, 0, 0, 0, 0, 0, 6, 6, 6, 6, 0, 0,
  121822. 0, 0, 0, 6, 6, 6, 6, 0, 0, 0, 0, 0, 7, 7, 6, 6,
  121823. 0, 0, 0, 0, 0, 0, 0, 6, 7, 0, 0, 0, 0, 0, 0, 0,
  121824. 7, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  121825. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121826. 0,
  121827. };
  121828. static float _vq_quantthresh__44c2_s_p4_0[] = {
  121829. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  121830. };
  121831. static long _vq_quantmap__44c2_s_p4_0[] = {
  121832. 7, 5, 3, 1, 0, 2, 4, 6,
  121833. 8,
  121834. };
  121835. static encode_aux_threshmatch _vq_auxt__44c2_s_p4_0 = {
  121836. _vq_quantthresh__44c2_s_p4_0,
  121837. _vq_quantmap__44c2_s_p4_0,
  121838. 9,
  121839. 9
  121840. };
  121841. static static_codebook _44c2_s_p4_0 = {
  121842. 2, 81,
  121843. _vq_lengthlist__44c2_s_p4_0,
  121844. 1, -531628032, 1611661312, 4, 0,
  121845. _vq_quantlist__44c2_s_p4_0,
  121846. NULL,
  121847. &_vq_auxt__44c2_s_p4_0,
  121848. NULL,
  121849. 0
  121850. };
  121851. static long _vq_quantlist__44c2_s_p5_0[] = {
  121852. 4,
  121853. 3,
  121854. 5,
  121855. 2,
  121856. 6,
  121857. 1,
  121858. 7,
  121859. 0,
  121860. 8,
  121861. };
  121862. static long _vq_lengthlist__44c2_s_p5_0[] = {
  121863. 1, 3, 3, 6, 6, 7, 7, 9, 9, 0, 7, 7, 7, 7, 7, 7,
  121864. 9, 9, 0, 7, 7, 7, 7, 7, 7, 9, 9, 0, 8, 8, 7, 7,
  121865. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  121866. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  121867. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  121868. 11,
  121869. };
  121870. static float _vq_quantthresh__44c2_s_p5_0[] = {
  121871. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  121872. };
  121873. static long _vq_quantmap__44c2_s_p5_0[] = {
  121874. 7, 5, 3, 1, 0, 2, 4, 6,
  121875. 8,
  121876. };
  121877. static encode_aux_threshmatch _vq_auxt__44c2_s_p5_0 = {
  121878. _vq_quantthresh__44c2_s_p5_0,
  121879. _vq_quantmap__44c2_s_p5_0,
  121880. 9,
  121881. 9
  121882. };
  121883. static static_codebook _44c2_s_p5_0 = {
  121884. 2, 81,
  121885. _vq_lengthlist__44c2_s_p5_0,
  121886. 1, -531628032, 1611661312, 4, 0,
  121887. _vq_quantlist__44c2_s_p5_0,
  121888. NULL,
  121889. &_vq_auxt__44c2_s_p5_0,
  121890. NULL,
  121891. 0
  121892. };
  121893. static long _vq_quantlist__44c2_s_p6_0[] = {
  121894. 8,
  121895. 7,
  121896. 9,
  121897. 6,
  121898. 10,
  121899. 5,
  121900. 11,
  121901. 4,
  121902. 12,
  121903. 3,
  121904. 13,
  121905. 2,
  121906. 14,
  121907. 1,
  121908. 15,
  121909. 0,
  121910. 16,
  121911. };
  121912. static long _vq_lengthlist__44c2_s_p6_0[] = {
  121913. 1, 4, 3, 6, 6, 8, 8, 9, 9, 9, 9, 9, 9,10,10,11,
  121914. 11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  121915. 12,11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  121916. 11,11,12, 0, 8, 8, 7, 7, 9, 9,10,10, 9, 9,10,10,
  121917. 11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10, 9,10,
  121918. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  121919. 11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  121920. 10,11,11,12,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  121921. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  121922. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  121923. 10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  121924. 9,10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  121925. 10,10,10,10,11,11,12,12,13,12,13,13, 0, 0, 0, 0,
  121926. 0, 0, 0,10,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  121927. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  121928. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0,
  121929. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  121930. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  121931. 14,
  121932. };
  121933. static float _vq_quantthresh__44c2_s_p6_0[] = {
  121934. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  121935. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  121936. };
  121937. static long _vq_quantmap__44c2_s_p6_0[] = {
  121938. 15, 13, 11, 9, 7, 5, 3, 1,
  121939. 0, 2, 4, 6, 8, 10, 12, 14,
  121940. 16,
  121941. };
  121942. static encode_aux_threshmatch _vq_auxt__44c2_s_p6_0 = {
  121943. _vq_quantthresh__44c2_s_p6_0,
  121944. _vq_quantmap__44c2_s_p6_0,
  121945. 17,
  121946. 17
  121947. };
  121948. static static_codebook _44c2_s_p6_0 = {
  121949. 2, 289,
  121950. _vq_lengthlist__44c2_s_p6_0,
  121951. 1, -529530880, 1611661312, 5, 0,
  121952. _vq_quantlist__44c2_s_p6_0,
  121953. NULL,
  121954. &_vq_auxt__44c2_s_p6_0,
  121955. NULL,
  121956. 0
  121957. };
  121958. static long _vq_quantlist__44c2_s_p7_0[] = {
  121959. 1,
  121960. 0,
  121961. 2,
  121962. };
  121963. static long _vq_lengthlist__44c2_s_p7_0[] = {
  121964. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  121965. 9, 9, 4, 7, 7,10, 9, 9,10, 9, 9, 7,10,10,11,10,
  121966. 11,11,10,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  121967. 11,10,11,11,10,10, 7,11,10,11,11,11,12,11,11, 6,
  121968. 9, 9,11,10,10,11,11,10, 6, 9, 9,11,10,10,12,10,
  121969. 11,
  121970. };
  121971. static float _vq_quantthresh__44c2_s_p7_0[] = {
  121972. -5.5, 5.5,
  121973. };
  121974. static long _vq_quantmap__44c2_s_p7_0[] = {
  121975. 1, 0, 2,
  121976. };
  121977. static encode_aux_threshmatch _vq_auxt__44c2_s_p7_0 = {
  121978. _vq_quantthresh__44c2_s_p7_0,
  121979. _vq_quantmap__44c2_s_p7_0,
  121980. 3,
  121981. 3
  121982. };
  121983. static static_codebook _44c2_s_p7_0 = {
  121984. 4, 81,
  121985. _vq_lengthlist__44c2_s_p7_0,
  121986. 1, -529137664, 1618345984, 2, 0,
  121987. _vq_quantlist__44c2_s_p7_0,
  121988. NULL,
  121989. &_vq_auxt__44c2_s_p7_0,
  121990. NULL,
  121991. 0
  121992. };
  121993. static long _vq_quantlist__44c2_s_p7_1[] = {
  121994. 5,
  121995. 4,
  121996. 6,
  121997. 3,
  121998. 7,
  121999. 2,
  122000. 8,
  122001. 1,
  122002. 9,
  122003. 0,
  122004. 10,
  122005. };
  122006. static long _vq_lengthlist__44c2_s_p7_1[] = {
  122007. 2, 3, 4, 6, 6, 7, 7, 7, 7, 7, 7, 9, 7, 7, 6, 6,
  122008. 7, 7, 8, 8, 8, 8, 9, 6, 6, 6, 6, 7, 7, 8, 8, 8,
  122009. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  122010. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  122011. 8, 8,10,10,10, 7, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  122012. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  122013. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  122014. 10,10,10, 8, 8, 8, 8, 8, 8,
  122015. };
  122016. static float _vq_quantthresh__44c2_s_p7_1[] = {
  122017. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  122018. 3.5, 4.5,
  122019. };
  122020. static long _vq_quantmap__44c2_s_p7_1[] = {
  122021. 9, 7, 5, 3, 1, 0, 2, 4,
  122022. 6, 8, 10,
  122023. };
  122024. static encode_aux_threshmatch _vq_auxt__44c2_s_p7_1 = {
  122025. _vq_quantthresh__44c2_s_p7_1,
  122026. _vq_quantmap__44c2_s_p7_1,
  122027. 11,
  122028. 11
  122029. };
  122030. static static_codebook _44c2_s_p7_1 = {
  122031. 2, 121,
  122032. _vq_lengthlist__44c2_s_p7_1,
  122033. 1, -531365888, 1611661312, 4, 0,
  122034. _vq_quantlist__44c2_s_p7_1,
  122035. NULL,
  122036. &_vq_auxt__44c2_s_p7_1,
  122037. NULL,
  122038. 0
  122039. };
  122040. static long _vq_quantlist__44c2_s_p8_0[] = {
  122041. 6,
  122042. 5,
  122043. 7,
  122044. 4,
  122045. 8,
  122046. 3,
  122047. 9,
  122048. 2,
  122049. 10,
  122050. 1,
  122051. 11,
  122052. 0,
  122053. 12,
  122054. };
  122055. static long _vq_lengthlist__44c2_s_p8_0[] = {
  122056. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 6, 5, 5,
  122057. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 6, 5, 7, 7, 8,
  122058. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  122059. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  122060. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  122061. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  122062. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  122063. 11,12,12,12,12, 0, 0, 0,14,14,10,11,11,11,12,12,
  122064. 13,13, 0, 0, 0,14,14,11,10,11,11,13,12,13,13, 0,
  122065. 0, 0, 0, 0,12,12,11,12,13,12,14,14, 0, 0, 0, 0,
  122066. 0,12,12,12,12,13,12,14,14,
  122067. };
  122068. static float _vq_quantthresh__44c2_s_p8_0[] = {
  122069. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  122070. 12.5, 17.5, 22.5, 27.5,
  122071. };
  122072. static long _vq_quantmap__44c2_s_p8_0[] = {
  122073. 11, 9, 7, 5, 3, 1, 0, 2,
  122074. 4, 6, 8, 10, 12,
  122075. };
  122076. static encode_aux_threshmatch _vq_auxt__44c2_s_p8_0 = {
  122077. _vq_quantthresh__44c2_s_p8_0,
  122078. _vq_quantmap__44c2_s_p8_0,
  122079. 13,
  122080. 13
  122081. };
  122082. static static_codebook _44c2_s_p8_0 = {
  122083. 2, 169,
  122084. _vq_lengthlist__44c2_s_p8_0,
  122085. 1, -526516224, 1616117760, 4, 0,
  122086. _vq_quantlist__44c2_s_p8_0,
  122087. NULL,
  122088. &_vq_auxt__44c2_s_p8_0,
  122089. NULL,
  122090. 0
  122091. };
  122092. static long _vq_quantlist__44c2_s_p8_1[] = {
  122093. 2,
  122094. 1,
  122095. 3,
  122096. 0,
  122097. 4,
  122098. };
  122099. static long _vq_lengthlist__44c2_s_p8_1[] = {
  122100. 2, 4, 4, 5, 4, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  122101. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  122102. };
  122103. static float _vq_quantthresh__44c2_s_p8_1[] = {
  122104. -1.5, -0.5, 0.5, 1.5,
  122105. };
  122106. static long _vq_quantmap__44c2_s_p8_1[] = {
  122107. 3, 1, 0, 2, 4,
  122108. };
  122109. static encode_aux_threshmatch _vq_auxt__44c2_s_p8_1 = {
  122110. _vq_quantthresh__44c2_s_p8_1,
  122111. _vq_quantmap__44c2_s_p8_1,
  122112. 5,
  122113. 5
  122114. };
  122115. static static_codebook _44c2_s_p8_1 = {
  122116. 2, 25,
  122117. _vq_lengthlist__44c2_s_p8_1,
  122118. 1, -533725184, 1611661312, 3, 0,
  122119. _vq_quantlist__44c2_s_p8_1,
  122120. NULL,
  122121. &_vq_auxt__44c2_s_p8_1,
  122122. NULL,
  122123. 0
  122124. };
  122125. static long _vq_quantlist__44c2_s_p9_0[] = {
  122126. 6,
  122127. 5,
  122128. 7,
  122129. 4,
  122130. 8,
  122131. 3,
  122132. 9,
  122133. 2,
  122134. 10,
  122135. 1,
  122136. 11,
  122137. 0,
  122138. 12,
  122139. };
  122140. static long _vq_lengthlist__44c2_s_p9_0[] = {
  122141. 1, 5, 4,12,12,12,12,12,12,12,12,12,12, 4, 9, 8,
  122142. 11,11,11,11,11,11,11,11,11,11, 2, 8, 7,11,11,11,
  122143. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  122144. 11,11,11,11,11,11,10,11,11,11,11,11,11,11,11,11,
  122145. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  122146. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  122147. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  122148. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  122149. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  122150. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  122151. 11,11,11,11,11,11,11,11,11,
  122152. };
  122153. static float _vq_quantthresh__44c2_s_p9_0[] = {
  122154. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  122155. 552.5, 773.5, 994.5, 1215.5,
  122156. };
  122157. static long _vq_quantmap__44c2_s_p9_0[] = {
  122158. 11, 9, 7, 5, 3, 1, 0, 2,
  122159. 4, 6, 8, 10, 12,
  122160. };
  122161. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_0 = {
  122162. _vq_quantthresh__44c2_s_p9_0,
  122163. _vq_quantmap__44c2_s_p9_0,
  122164. 13,
  122165. 13
  122166. };
  122167. static static_codebook _44c2_s_p9_0 = {
  122168. 2, 169,
  122169. _vq_lengthlist__44c2_s_p9_0,
  122170. 1, -514541568, 1627103232, 4, 0,
  122171. _vq_quantlist__44c2_s_p9_0,
  122172. NULL,
  122173. &_vq_auxt__44c2_s_p9_0,
  122174. NULL,
  122175. 0
  122176. };
  122177. static long _vq_quantlist__44c2_s_p9_1[] = {
  122178. 6,
  122179. 5,
  122180. 7,
  122181. 4,
  122182. 8,
  122183. 3,
  122184. 9,
  122185. 2,
  122186. 10,
  122187. 1,
  122188. 11,
  122189. 0,
  122190. 12,
  122191. };
  122192. static long _vq_lengthlist__44c2_s_p9_1[] = {
  122193. 1, 4, 4, 6, 6, 7, 6, 8, 8,10, 9,10,10, 6, 5, 5,
  122194. 7, 7, 8, 7,10, 9,11,11,12,13, 6, 5, 5, 7, 7, 8,
  122195. 8,10,10,11,11,13,13,18, 8, 8, 8, 8, 9, 9,10,10,
  122196. 12,12,12,13,18, 8, 8, 8, 8, 9, 9,10,10,12,12,13,
  122197. 13,18,11,11, 8, 8,10,10,11,11,12,11,13,12,18,11,
  122198. 11, 9, 7,10,10,11,11,11,12,12,13,17,17,17,10,10,
  122199. 11,11,12,12,12,10,12,12,17,17,17,11,10,11,10,13,
  122200. 12,11,12,12,12,17,17,17,15,14,11,11,12,11,13,10,
  122201. 13,12,17,17,17,14,14,12,10,11,11,13,13,13,13,17,
  122202. 17,16,17,16,13,13,12,10,13,10,14,13,17,16,17,16,
  122203. 17,13,12,12,10,13,11,14,14,
  122204. };
  122205. static float _vq_quantthresh__44c2_s_p9_1[] = {
  122206. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  122207. 42.5, 59.5, 76.5, 93.5,
  122208. };
  122209. static long _vq_quantmap__44c2_s_p9_1[] = {
  122210. 11, 9, 7, 5, 3, 1, 0, 2,
  122211. 4, 6, 8, 10, 12,
  122212. };
  122213. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_1 = {
  122214. _vq_quantthresh__44c2_s_p9_1,
  122215. _vq_quantmap__44c2_s_p9_1,
  122216. 13,
  122217. 13
  122218. };
  122219. static static_codebook _44c2_s_p9_1 = {
  122220. 2, 169,
  122221. _vq_lengthlist__44c2_s_p9_1,
  122222. 1, -522616832, 1620115456, 4, 0,
  122223. _vq_quantlist__44c2_s_p9_1,
  122224. NULL,
  122225. &_vq_auxt__44c2_s_p9_1,
  122226. NULL,
  122227. 0
  122228. };
  122229. static long _vq_quantlist__44c2_s_p9_2[] = {
  122230. 8,
  122231. 7,
  122232. 9,
  122233. 6,
  122234. 10,
  122235. 5,
  122236. 11,
  122237. 4,
  122238. 12,
  122239. 3,
  122240. 13,
  122241. 2,
  122242. 14,
  122243. 1,
  122244. 15,
  122245. 0,
  122246. 16,
  122247. };
  122248. static long _vq_lengthlist__44c2_s_p9_2[] = {
  122249. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8,
  122250. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  122251. 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9,
  122252. 9, 9, 9,10, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  122253. 9, 9, 9, 9,10,10,10, 8, 7, 8, 8, 8, 8, 9, 9, 9,
  122254. 9, 9, 9, 9, 9,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  122255. 9, 9,10, 9, 9, 9,10,11,10, 8, 8, 8, 8, 9, 9, 9,
  122256. 9, 9, 9, 9,10,10,10,10,11,10, 8, 8, 9, 9, 9, 9,
  122257. 9, 9,10, 9, 9,10, 9,10,11,10,11,11,11, 8, 8, 9,
  122258. 9, 9, 9, 9, 9, 9, 9,10,10,11,11,11,11,11, 9, 9,
  122259. 9, 9, 9, 9,10, 9, 9, 9,10,10,11,11,11,11,11, 9,
  122260. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,11,11,11,11,11,
  122261. 9, 9, 9, 9,10,10, 9, 9, 9,10,10,10,11,11,11,11,
  122262. 11,11,11, 9, 9, 9,10, 9, 9,10,10,10,10,11,11,10,
  122263. 11,11,11,11,10, 9,10,10, 9, 9, 9, 9,10,10,11,10,
  122264. 11,11,11,11,11, 9, 9, 9, 9,10, 9,10,10,10,10,11,
  122265. 10,11,11,11,11,11,10,10, 9, 9,10, 9,10,10,10,10,
  122266. 10,10,10,11,11,11,11,11,11, 9, 9,10, 9,10, 9,10,
  122267. 10,
  122268. };
  122269. static float _vq_quantthresh__44c2_s_p9_2[] = {
  122270. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  122271. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  122272. };
  122273. static long _vq_quantmap__44c2_s_p9_2[] = {
  122274. 15, 13, 11, 9, 7, 5, 3, 1,
  122275. 0, 2, 4, 6, 8, 10, 12, 14,
  122276. 16,
  122277. };
  122278. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_2 = {
  122279. _vq_quantthresh__44c2_s_p9_2,
  122280. _vq_quantmap__44c2_s_p9_2,
  122281. 17,
  122282. 17
  122283. };
  122284. static static_codebook _44c2_s_p9_2 = {
  122285. 2, 289,
  122286. _vq_lengthlist__44c2_s_p9_2,
  122287. 1, -529530880, 1611661312, 5, 0,
  122288. _vq_quantlist__44c2_s_p9_2,
  122289. NULL,
  122290. &_vq_auxt__44c2_s_p9_2,
  122291. NULL,
  122292. 0
  122293. };
  122294. static long _huff_lengthlist__44c2_s_short[] = {
  122295. 11, 9,13,12,12,11,12,12,13,15, 8, 2,11, 4, 8, 5,
  122296. 7,10,12,15,13, 7,10, 9, 8, 8,10,13,17,17,11, 4,
  122297. 12, 5, 9, 5, 8,11,14,16,12, 6, 8, 7, 6, 6, 8,11,
  122298. 13,16,11, 4, 9, 5, 6, 4, 6,10,13,16,11, 6,11, 7,
  122299. 7, 6, 7,10,13,15,13, 9,12, 9, 8, 6, 8,10,12,14,
  122300. 14,10,10, 8, 6, 5, 6, 9,11,13,15,11,11, 9, 6, 5,
  122301. 6, 8, 9,12,
  122302. };
  122303. static static_codebook _huff_book__44c2_s_short = {
  122304. 2, 100,
  122305. _huff_lengthlist__44c2_s_short,
  122306. 0, 0, 0, 0, 0,
  122307. NULL,
  122308. NULL,
  122309. NULL,
  122310. NULL,
  122311. 0
  122312. };
  122313. static long _huff_lengthlist__44c3_s_long[] = {
  122314. 5, 6,11,11,11,11,10,10,12,11, 5, 2,11, 5, 6, 6,
  122315. 7, 9,11,13,13,10, 7,11, 6, 7, 8, 9,10,12,11, 5,
  122316. 11, 6, 8, 7, 9,11,14,15,11, 6, 6, 8, 4, 5, 7, 8,
  122317. 10,13,10, 5, 7, 7, 5, 5, 6, 8,10,11,10, 7, 7, 8,
  122318. 6, 5, 5, 7, 9, 9,11, 8, 8,11, 8, 7, 6, 6, 7, 9,
  122319. 12,11,10,13, 9, 9, 7, 7, 7, 9,11,13,12,15,12,11,
  122320. 9, 8, 8, 8,
  122321. };
  122322. static static_codebook _huff_book__44c3_s_long = {
  122323. 2, 100,
  122324. _huff_lengthlist__44c3_s_long,
  122325. 0, 0, 0, 0, 0,
  122326. NULL,
  122327. NULL,
  122328. NULL,
  122329. NULL,
  122330. 0
  122331. };
  122332. static long _vq_quantlist__44c3_s_p1_0[] = {
  122333. 1,
  122334. 0,
  122335. 2,
  122336. };
  122337. static long _vq_lengthlist__44c3_s_p1_0[] = {
  122338. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  122339. 0, 0, 5, 6, 6, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  122344. 0, 0, 0, 6, 7, 8, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  122349. 0, 0, 0, 0, 7, 8, 8, 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, 0, 0, 0, 0, 0, 0, 0,
  122370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0,
  122375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0,
  122380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  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, 5, 7, 7, 0, 0, 0, 0,
  122384. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 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, 7, 8, 8, 0, 0, 0,
  122389. 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 6, 8, 8, 0, 0,
  122394. 0, 0, 0, 0, 7, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122416. 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122421. 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  122430. 0, 0, 0, 0, 7, 8, 8, 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, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  122435. 0, 0, 0, 0, 0, 7, 8, 9, 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, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  122440. 0, 0, 0, 0, 0, 0, 8, 9, 8, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122748. 0,
  122749. };
  122750. static float _vq_quantthresh__44c3_s_p1_0[] = {
  122751. -0.5, 0.5,
  122752. };
  122753. static long _vq_quantmap__44c3_s_p1_0[] = {
  122754. 1, 0, 2,
  122755. };
  122756. static encode_aux_threshmatch _vq_auxt__44c3_s_p1_0 = {
  122757. _vq_quantthresh__44c3_s_p1_0,
  122758. _vq_quantmap__44c3_s_p1_0,
  122759. 3,
  122760. 3
  122761. };
  122762. static static_codebook _44c3_s_p1_0 = {
  122763. 8, 6561,
  122764. _vq_lengthlist__44c3_s_p1_0,
  122765. 1, -535822336, 1611661312, 2, 0,
  122766. _vq_quantlist__44c3_s_p1_0,
  122767. NULL,
  122768. &_vq_auxt__44c3_s_p1_0,
  122769. NULL,
  122770. 0
  122771. };
  122772. static long _vq_quantlist__44c3_s_p2_0[] = {
  122773. 2,
  122774. 1,
  122775. 3,
  122776. 0,
  122777. 4,
  122778. };
  122779. static long _vq_lengthlist__44c3_s_p2_0[] = {
  122780. 2, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  122781. 7, 8, 0, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 7,
  122782. 7, 0, 0, 0, 7, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  122783. 0, 0, 5, 6, 6, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0,
  122784. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0,
  122790. 0, 7, 7, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5,
  122791. 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9,
  122792. 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7,
  122798. 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0,
  122799. 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9, 9, 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. 8,10,10, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 0, 0, 0,
  122806. 10,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0, 9,
  122807. 9, 0, 0, 0, 9, 9, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  122808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122819. 0,
  122820. };
  122821. static float _vq_quantthresh__44c3_s_p2_0[] = {
  122822. -1.5, -0.5, 0.5, 1.5,
  122823. };
  122824. static long _vq_quantmap__44c3_s_p2_0[] = {
  122825. 3, 1, 0, 2, 4,
  122826. };
  122827. static encode_aux_threshmatch _vq_auxt__44c3_s_p2_0 = {
  122828. _vq_quantthresh__44c3_s_p2_0,
  122829. _vq_quantmap__44c3_s_p2_0,
  122830. 5,
  122831. 5
  122832. };
  122833. static static_codebook _44c3_s_p2_0 = {
  122834. 4, 625,
  122835. _vq_lengthlist__44c3_s_p2_0,
  122836. 1, -533725184, 1611661312, 3, 0,
  122837. _vq_quantlist__44c3_s_p2_0,
  122838. NULL,
  122839. &_vq_auxt__44c3_s_p2_0,
  122840. NULL,
  122841. 0
  122842. };
  122843. static long _vq_quantlist__44c3_s_p3_0[] = {
  122844. 2,
  122845. 1,
  122846. 3,
  122847. 0,
  122848. 4,
  122849. };
  122850. static long _vq_lengthlist__44c3_s_p3_0[] = {
  122851. 2, 4, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  122853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122854. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  122856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122857. 0, 0, 0, 0, 6, 6, 7, 9, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122890. 0,
  122891. };
  122892. static float _vq_quantthresh__44c3_s_p3_0[] = {
  122893. -1.5, -0.5, 0.5, 1.5,
  122894. };
  122895. static long _vq_quantmap__44c3_s_p3_0[] = {
  122896. 3, 1, 0, 2, 4,
  122897. };
  122898. static encode_aux_threshmatch _vq_auxt__44c3_s_p3_0 = {
  122899. _vq_quantthresh__44c3_s_p3_0,
  122900. _vq_quantmap__44c3_s_p3_0,
  122901. 5,
  122902. 5
  122903. };
  122904. static static_codebook _44c3_s_p3_0 = {
  122905. 4, 625,
  122906. _vq_lengthlist__44c3_s_p3_0,
  122907. 1, -533725184, 1611661312, 3, 0,
  122908. _vq_quantlist__44c3_s_p3_0,
  122909. NULL,
  122910. &_vq_auxt__44c3_s_p3_0,
  122911. NULL,
  122912. 0
  122913. };
  122914. static long _vq_quantlist__44c3_s_p4_0[] = {
  122915. 4,
  122916. 3,
  122917. 5,
  122918. 2,
  122919. 6,
  122920. 1,
  122921. 7,
  122922. 0,
  122923. 8,
  122924. };
  122925. static long _vq_lengthlist__44c3_s_p4_0[] = {
  122926. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  122927. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  122928. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  122929. 7, 8, 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0,
  122930. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122931. 0,
  122932. };
  122933. static float _vq_quantthresh__44c3_s_p4_0[] = {
  122934. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  122935. };
  122936. static long _vq_quantmap__44c3_s_p4_0[] = {
  122937. 7, 5, 3, 1, 0, 2, 4, 6,
  122938. 8,
  122939. };
  122940. static encode_aux_threshmatch _vq_auxt__44c3_s_p4_0 = {
  122941. _vq_quantthresh__44c3_s_p4_0,
  122942. _vq_quantmap__44c3_s_p4_0,
  122943. 9,
  122944. 9
  122945. };
  122946. static static_codebook _44c3_s_p4_0 = {
  122947. 2, 81,
  122948. _vq_lengthlist__44c3_s_p4_0,
  122949. 1, -531628032, 1611661312, 4, 0,
  122950. _vq_quantlist__44c3_s_p4_0,
  122951. NULL,
  122952. &_vq_auxt__44c3_s_p4_0,
  122953. NULL,
  122954. 0
  122955. };
  122956. static long _vq_quantlist__44c3_s_p5_0[] = {
  122957. 4,
  122958. 3,
  122959. 5,
  122960. 2,
  122961. 6,
  122962. 1,
  122963. 7,
  122964. 0,
  122965. 8,
  122966. };
  122967. static long _vq_lengthlist__44c3_s_p5_0[] = {
  122968. 1, 3, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 7, 8,
  122969. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  122970. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  122971. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  122972. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  122973. 11,
  122974. };
  122975. static float _vq_quantthresh__44c3_s_p5_0[] = {
  122976. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  122977. };
  122978. static long _vq_quantmap__44c3_s_p5_0[] = {
  122979. 7, 5, 3, 1, 0, 2, 4, 6,
  122980. 8,
  122981. };
  122982. static encode_aux_threshmatch _vq_auxt__44c3_s_p5_0 = {
  122983. _vq_quantthresh__44c3_s_p5_0,
  122984. _vq_quantmap__44c3_s_p5_0,
  122985. 9,
  122986. 9
  122987. };
  122988. static static_codebook _44c3_s_p5_0 = {
  122989. 2, 81,
  122990. _vq_lengthlist__44c3_s_p5_0,
  122991. 1, -531628032, 1611661312, 4, 0,
  122992. _vq_quantlist__44c3_s_p5_0,
  122993. NULL,
  122994. &_vq_auxt__44c3_s_p5_0,
  122995. NULL,
  122996. 0
  122997. };
  122998. static long _vq_quantlist__44c3_s_p6_0[] = {
  122999. 8,
  123000. 7,
  123001. 9,
  123002. 6,
  123003. 10,
  123004. 5,
  123005. 11,
  123006. 4,
  123007. 12,
  123008. 3,
  123009. 13,
  123010. 2,
  123011. 14,
  123012. 1,
  123013. 15,
  123014. 0,
  123015. 16,
  123016. };
  123017. static long _vq_lengthlist__44c3_s_p6_0[] = {
  123018. 2, 3, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  123019. 10, 0, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  123020. 11,11, 0, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  123021. 10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  123022. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  123023. 10,11,11,11,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  123024. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9,
  123025. 9,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  123026. 10,10,11,10,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  123027. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 8,
  123028. 9, 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8,
  123029. 8, 9, 9,10,10,11,11,12,11,12,12, 0, 0, 0, 0, 0,
  123030. 9,10,10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0,
  123031. 0, 0, 0,10,10,10,10,11,11,12,12,13,13, 0, 0, 0,
  123032. 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0, 0,
  123033. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  123034. 0, 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,13,
  123035. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,
  123036. 13,
  123037. };
  123038. static float _vq_quantthresh__44c3_s_p6_0[] = {
  123039. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  123040. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  123041. };
  123042. static long _vq_quantmap__44c3_s_p6_0[] = {
  123043. 15, 13, 11, 9, 7, 5, 3, 1,
  123044. 0, 2, 4, 6, 8, 10, 12, 14,
  123045. 16,
  123046. };
  123047. static encode_aux_threshmatch _vq_auxt__44c3_s_p6_0 = {
  123048. _vq_quantthresh__44c3_s_p6_0,
  123049. _vq_quantmap__44c3_s_p6_0,
  123050. 17,
  123051. 17
  123052. };
  123053. static static_codebook _44c3_s_p6_0 = {
  123054. 2, 289,
  123055. _vq_lengthlist__44c3_s_p6_0,
  123056. 1, -529530880, 1611661312, 5, 0,
  123057. _vq_quantlist__44c3_s_p6_0,
  123058. NULL,
  123059. &_vq_auxt__44c3_s_p6_0,
  123060. NULL,
  123061. 0
  123062. };
  123063. static long _vq_quantlist__44c3_s_p7_0[] = {
  123064. 1,
  123065. 0,
  123066. 2,
  123067. };
  123068. static long _vq_lengthlist__44c3_s_p7_0[] = {
  123069. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  123070. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  123071. 10,12,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  123072. 11,10,10,11,10,10, 7,11,11,11,11,11,12,11,11, 6,
  123073. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  123074. 10,
  123075. };
  123076. static float _vq_quantthresh__44c3_s_p7_0[] = {
  123077. -5.5, 5.5,
  123078. };
  123079. static long _vq_quantmap__44c3_s_p7_0[] = {
  123080. 1, 0, 2,
  123081. };
  123082. static encode_aux_threshmatch _vq_auxt__44c3_s_p7_0 = {
  123083. _vq_quantthresh__44c3_s_p7_0,
  123084. _vq_quantmap__44c3_s_p7_0,
  123085. 3,
  123086. 3
  123087. };
  123088. static static_codebook _44c3_s_p7_0 = {
  123089. 4, 81,
  123090. _vq_lengthlist__44c3_s_p7_0,
  123091. 1, -529137664, 1618345984, 2, 0,
  123092. _vq_quantlist__44c3_s_p7_0,
  123093. NULL,
  123094. &_vq_auxt__44c3_s_p7_0,
  123095. NULL,
  123096. 0
  123097. };
  123098. static long _vq_quantlist__44c3_s_p7_1[] = {
  123099. 5,
  123100. 4,
  123101. 6,
  123102. 3,
  123103. 7,
  123104. 2,
  123105. 8,
  123106. 1,
  123107. 9,
  123108. 0,
  123109. 10,
  123110. };
  123111. static long _vq_lengthlist__44c3_s_p7_1[] = {
  123112. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  123113. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  123114. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  123115. 7, 8, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  123116. 8, 8,10,10,10, 7, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  123117. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  123118. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 9, 8,10,10,
  123119. 10,10,10, 8, 8, 8, 8, 8, 8,
  123120. };
  123121. static float _vq_quantthresh__44c3_s_p7_1[] = {
  123122. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  123123. 3.5, 4.5,
  123124. };
  123125. static long _vq_quantmap__44c3_s_p7_1[] = {
  123126. 9, 7, 5, 3, 1, 0, 2, 4,
  123127. 6, 8, 10,
  123128. };
  123129. static encode_aux_threshmatch _vq_auxt__44c3_s_p7_1 = {
  123130. _vq_quantthresh__44c3_s_p7_1,
  123131. _vq_quantmap__44c3_s_p7_1,
  123132. 11,
  123133. 11
  123134. };
  123135. static static_codebook _44c3_s_p7_1 = {
  123136. 2, 121,
  123137. _vq_lengthlist__44c3_s_p7_1,
  123138. 1, -531365888, 1611661312, 4, 0,
  123139. _vq_quantlist__44c3_s_p7_1,
  123140. NULL,
  123141. &_vq_auxt__44c3_s_p7_1,
  123142. NULL,
  123143. 0
  123144. };
  123145. static long _vq_quantlist__44c3_s_p8_0[] = {
  123146. 6,
  123147. 5,
  123148. 7,
  123149. 4,
  123150. 8,
  123151. 3,
  123152. 9,
  123153. 2,
  123154. 10,
  123155. 1,
  123156. 11,
  123157. 0,
  123158. 12,
  123159. };
  123160. static long _vq_lengthlist__44c3_s_p8_0[] = {
  123161. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  123162. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5, 7, 7, 8,
  123163. 8, 8, 8, 9, 9,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  123164. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  123165. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,12, 0,13,
  123166. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  123167. 10,10,11,11,12,12,12,12, 0, 0, 0,10,10,10,10,11,
  123168. 11,12,12,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  123169. 13,13, 0, 0, 0,14,14,11,11,11,11,12,12,13,13, 0,
  123170. 0, 0, 0, 0,12,12,12,12,13,13,14,13, 0, 0, 0, 0,
  123171. 0,13,13,12,12,13,12,14,13,
  123172. };
  123173. static float _vq_quantthresh__44c3_s_p8_0[] = {
  123174. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  123175. 12.5, 17.5, 22.5, 27.5,
  123176. };
  123177. static long _vq_quantmap__44c3_s_p8_0[] = {
  123178. 11, 9, 7, 5, 3, 1, 0, 2,
  123179. 4, 6, 8, 10, 12,
  123180. };
  123181. static encode_aux_threshmatch _vq_auxt__44c3_s_p8_0 = {
  123182. _vq_quantthresh__44c3_s_p8_0,
  123183. _vq_quantmap__44c3_s_p8_0,
  123184. 13,
  123185. 13
  123186. };
  123187. static static_codebook _44c3_s_p8_0 = {
  123188. 2, 169,
  123189. _vq_lengthlist__44c3_s_p8_0,
  123190. 1, -526516224, 1616117760, 4, 0,
  123191. _vq_quantlist__44c3_s_p8_0,
  123192. NULL,
  123193. &_vq_auxt__44c3_s_p8_0,
  123194. NULL,
  123195. 0
  123196. };
  123197. static long _vq_quantlist__44c3_s_p8_1[] = {
  123198. 2,
  123199. 1,
  123200. 3,
  123201. 0,
  123202. 4,
  123203. };
  123204. static long _vq_lengthlist__44c3_s_p8_1[] = {
  123205. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 4, 5, 5, 5, 6,
  123206. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  123207. };
  123208. static float _vq_quantthresh__44c3_s_p8_1[] = {
  123209. -1.5, -0.5, 0.5, 1.5,
  123210. };
  123211. static long _vq_quantmap__44c3_s_p8_1[] = {
  123212. 3, 1, 0, 2, 4,
  123213. };
  123214. static encode_aux_threshmatch _vq_auxt__44c3_s_p8_1 = {
  123215. _vq_quantthresh__44c3_s_p8_1,
  123216. _vq_quantmap__44c3_s_p8_1,
  123217. 5,
  123218. 5
  123219. };
  123220. static static_codebook _44c3_s_p8_1 = {
  123221. 2, 25,
  123222. _vq_lengthlist__44c3_s_p8_1,
  123223. 1, -533725184, 1611661312, 3, 0,
  123224. _vq_quantlist__44c3_s_p8_1,
  123225. NULL,
  123226. &_vq_auxt__44c3_s_p8_1,
  123227. NULL,
  123228. 0
  123229. };
  123230. static long _vq_quantlist__44c3_s_p9_0[] = {
  123231. 6,
  123232. 5,
  123233. 7,
  123234. 4,
  123235. 8,
  123236. 3,
  123237. 9,
  123238. 2,
  123239. 10,
  123240. 1,
  123241. 11,
  123242. 0,
  123243. 12,
  123244. };
  123245. static long _vq_lengthlist__44c3_s_p9_0[] = {
  123246. 1, 4, 4,12,12,12,12,12,12,12,12,12,12, 4, 9, 8,
  123247. 12,12,12,12,12,12,12,12,12,12, 2, 9, 7,12,12,12,
  123248. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  123249. 12,12,12,12,12,12,11,12,12,12,12,12,12,12,12,12,
  123250. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  123251. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  123252. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  123253. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  123254. 12,12,12,12,12,12,12,12,12,12,11,11,11,11,11,11,
  123255. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  123256. 11,11,11,11,11,11,11,11,11,
  123257. };
  123258. static float _vq_quantthresh__44c3_s_p9_0[] = {
  123259. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  123260. 637.5, 892.5, 1147.5, 1402.5,
  123261. };
  123262. static long _vq_quantmap__44c3_s_p9_0[] = {
  123263. 11, 9, 7, 5, 3, 1, 0, 2,
  123264. 4, 6, 8, 10, 12,
  123265. };
  123266. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_0 = {
  123267. _vq_quantthresh__44c3_s_p9_0,
  123268. _vq_quantmap__44c3_s_p9_0,
  123269. 13,
  123270. 13
  123271. };
  123272. static static_codebook _44c3_s_p9_0 = {
  123273. 2, 169,
  123274. _vq_lengthlist__44c3_s_p9_0,
  123275. 1, -514332672, 1627381760, 4, 0,
  123276. _vq_quantlist__44c3_s_p9_0,
  123277. NULL,
  123278. &_vq_auxt__44c3_s_p9_0,
  123279. NULL,
  123280. 0
  123281. };
  123282. static long _vq_quantlist__44c3_s_p9_1[] = {
  123283. 7,
  123284. 6,
  123285. 8,
  123286. 5,
  123287. 9,
  123288. 4,
  123289. 10,
  123290. 3,
  123291. 11,
  123292. 2,
  123293. 12,
  123294. 1,
  123295. 13,
  123296. 0,
  123297. 14,
  123298. };
  123299. static long _vq_lengthlist__44c3_s_p9_1[] = {
  123300. 1, 4, 4, 6, 6, 7, 7, 8, 7, 9, 9,10,10,10,10, 6,
  123301. 5, 5, 7, 7, 8, 8,10, 8,11,10,12,12,13,13, 6, 5,
  123302. 5, 7, 7, 8, 8,10, 9,11,11,12,12,13,12,18, 8, 8,
  123303. 8, 8, 9, 9,10, 9,11,10,12,12,13,13,18, 8, 8, 8,
  123304. 8, 9, 9,10,10,11,11,13,12,14,13,18,11,11, 9, 9,
  123305. 10,10,11,11,11,12,13,12,13,14,18,11,11, 9, 8,11,
  123306. 10,11,11,11,11,12,12,14,13,18,18,18,10,11,10,11,
  123307. 12,12,12,12,13,12,14,13,18,18,18,10,11,11, 9,12,
  123308. 11,12,12,12,13,13,13,18,18,17,14,14,11,11,12,12,
  123309. 13,12,14,12,14,13,18,18,18,14,14,11,10,12, 9,12,
  123310. 13,13,13,13,13,18,18,17,16,18,13,13,12,12,13,11,
  123311. 14,12,14,14,17,18,18,17,18,13,12,13,10,12,11,14,
  123312. 14,14,14,17,18,18,18,18,15,16,12,12,13,10,14,12,
  123313. 14,15,18,18,18,16,17,16,14,12,11,13,10,13,13,14,
  123314. 15,
  123315. };
  123316. static float _vq_quantthresh__44c3_s_p9_1[] = {
  123317. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  123318. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  123319. };
  123320. static long _vq_quantmap__44c3_s_p9_1[] = {
  123321. 13, 11, 9, 7, 5, 3, 1, 0,
  123322. 2, 4, 6, 8, 10, 12, 14,
  123323. };
  123324. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_1 = {
  123325. _vq_quantthresh__44c3_s_p9_1,
  123326. _vq_quantmap__44c3_s_p9_1,
  123327. 15,
  123328. 15
  123329. };
  123330. static static_codebook _44c3_s_p9_1 = {
  123331. 2, 225,
  123332. _vq_lengthlist__44c3_s_p9_1,
  123333. 1, -522338304, 1620115456, 4, 0,
  123334. _vq_quantlist__44c3_s_p9_1,
  123335. NULL,
  123336. &_vq_auxt__44c3_s_p9_1,
  123337. NULL,
  123338. 0
  123339. };
  123340. static long _vq_quantlist__44c3_s_p9_2[] = {
  123341. 8,
  123342. 7,
  123343. 9,
  123344. 6,
  123345. 10,
  123346. 5,
  123347. 11,
  123348. 4,
  123349. 12,
  123350. 3,
  123351. 13,
  123352. 2,
  123353. 14,
  123354. 1,
  123355. 15,
  123356. 0,
  123357. 16,
  123358. };
  123359. static long _vq_lengthlist__44c3_s_p9_2[] = {
  123360. 2, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8,
  123361. 8,10, 6, 6, 7, 7, 8, 7, 8, 8, 8, 8, 8, 9, 9, 9,
  123362. 9, 9,10, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  123363. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  123364. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 9, 9, 9, 9,
  123365. 9, 9, 9, 9, 9,11,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  123366. 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  123367. 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 9, 9, 9, 9, 9,
  123368. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,11,11, 9, 9, 9,
  123369. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,11, 9, 9,
  123370. 9, 9, 9, 9,10,10, 9, 9,10, 9,11,10,11,11,11, 9,
  123371. 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,11,11,11,11,11,
  123372. 9, 9, 9, 9,10,10, 9, 9, 9, 9,10, 9,11,11,11,11,
  123373. 11,11,11, 9, 9, 9, 9, 9, 9,10,10,10,10,11,11,11,
  123374. 11,11,11,11,10, 9,10,10, 9,10, 9, 9,10, 9,11,10,
  123375. 10,11,11,11,11, 9,10, 9, 9, 9, 9,10,10,10,10,11,
  123376. 11,11,11,11,11,10,10,10, 9, 9,10, 9,10, 9,10,10,
  123377. 10,10,11,11,11,11,11,11,11, 9, 9, 9, 9, 9,10,10,
  123378. 10,
  123379. };
  123380. static float _vq_quantthresh__44c3_s_p9_2[] = {
  123381. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  123382. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  123383. };
  123384. static long _vq_quantmap__44c3_s_p9_2[] = {
  123385. 15, 13, 11, 9, 7, 5, 3, 1,
  123386. 0, 2, 4, 6, 8, 10, 12, 14,
  123387. 16,
  123388. };
  123389. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_2 = {
  123390. _vq_quantthresh__44c3_s_p9_2,
  123391. _vq_quantmap__44c3_s_p9_2,
  123392. 17,
  123393. 17
  123394. };
  123395. static static_codebook _44c3_s_p9_2 = {
  123396. 2, 289,
  123397. _vq_lengthlist__44c3_s_p9_2,
  123398. 1, -529530880, 1611661312, 5, 0,
  123399. _vq_quantlist__44c3_s_p9_2,
  123400. NULL,
  123401. &_vq_auxt__44c3_s_p9_2,
  123402. NULL,
  123403. 0
  123404. };
  123405. static long _huff_lengthlist__44c3_s_short[] = {
  123406. 10, 9,13,11,14,10,12,13,13,14, 7, 2,12, 5,10, 5,
  123407. 7,10,12,14,12, 6, 9, 8, 7, 7, 9,11,13,16,10, 4,
  123408. 12, 5,10, 6, 8,12,14,16,12, 6, 8, 7, 6, 5, 7,11,
  123409. 12,16,10, 4, 8, 5, 6, 4, 6, 9,13,16,10, 6,10, 7,
  123410. 7, 6, 7, 9,13,15,12, 9,11, 9, 8, 6, 7,10,12,14,
  123411. 14,11,10, 9, 6, 5, 6, 9,11,13,15,13,11,10, 6, 5,
  123412. 6, 8, 9,11,
  123413. };
  123414. static static_codebook _huff_book__44c3_s_short = {
  123415. 2, 100,
  123416. _huff_lengthlist__44c3_s_short,
  123417. 0, 0, 0, 0, 0,
  123418. NULL,
  123419. NULL,
  123420. NULL,
  123421. NULL,
  123422. 0
  123423. };
  123424. static long _huff_lengthlist__44c4_s_long[] = {
  123425. 4, 7,11,11,11,11,10,11,12,11, 5, 2,11, 5, 6, 6,
  123426. 7, 9,11,12,11, 9, 6,10, 6, 7, 8, 9,10,11,11, 5,
  123427. 11, 7, 8, 8, 9,11,13,14,11, 6, 5, 8, 4, 5, 7, 8,
  123428. 10,11,10, 6, 7, 7, 5, 5, 6, 8, 9,11,10, 7, 8, 9,
  123429. 6, 6, 6, 7, 8, 9,11, 9, 9,11, 7, 7, 6, 6, 7, 9,
  123430. 12,12,10,13, 9, 8, 7, 7, 7, 8,11,13,11,14,11,10,
  123431. 9, 8, 7, 7,
  123432. };
  123433. static static_codebook _huff_book__44c4_s_long = {
  123434. 2, 100,
  123435. _huff_lengthlist__44c4_s_long,
  123436. 0, 0, 0, 0, 0,
  123437. NULL,
  123438. NULL,
  123439. NULL,
  123440. NULL,
  123441. 0
  123442. };
  123443. static long _vq_quantlist__44c4_s_p1_0[] = {
  123444. 1,
  123445. 0,
  123446. 2,
  123447. };
  123448. static long _vq_lengthlist__44c4_s_p1_0[] = {
  123449. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  123450. 0, 0, 5, 6, 7, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  123455. 0, 0, 0, 6, 8, 8, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  123460. 0, 0, 0, 0, 7, 8, 8, 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, 0, 0, 0, 0, 0, 0, 0,
  123481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0,
  123486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0,
  123491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  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, 5, 7, 7, 0, 0, 0, 0,
  123495. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 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, 7, 8, 8, 0, 0, 0,
  123500. 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 6, 8, 8, 0, 0,
  123505. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123527. 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123532. 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  123541. 0, 0, 0, 0, 7, 8, 8, 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, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  123546. 0, 0, 0, 0, 0, 8, 8, 9, 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, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  123551. 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123859. 0,
  123860. };
  123861. static float _vq_quantthresh__44c4_s_p1_0[] = {
  123862. -0.5, 0.5,
  123863. };
  123864. static long _vq_quantmap__44c4_s_p1_0[] = {
  123865. 1, 0, 2,
  123866. };
  123867. static encode_aux_threshmatch _vq_auxt__44c4_s_p1_0 = {
  123868. _vq_quantthresh__44c4_s_p1_0,
  123869. _vq_quantmap__44c4_s_p1_0,
  123870. 3,
  123871. 3
  123872. };
  123873. static static_codebook _44c4_s_p1_0 = {
  123874. 8, 6561,
  123875. _vq_lengthlist__44c4_s_p1_0,
  123876. 1, -535822336, 1611661312, 2, 0,
  123877. _vq_quantlist__44c4_s_p1_0,
  123878. NULL,
  123879. &_vq_auxt__44c4_s_p1_0,
  123880. NULL,
  123881. 0
  123882. };
  123883. static long _vq_quantlist__44c4_s_p2_0[] = {
  123884. 2,
  123885. 1,
  123886. 3,
  123887. 0,
  123888. 4,
  123889. };
  123890. static long _vq_lengthlist__44c4_s_p2_0[] = {
  123891. 2, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  123892. 7, 7, 0, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 7,
  123893. 7, 0, 0, 0, 7, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  123894. 0, 0, 5, 6, 6, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0,
  123895. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5, 8, 7, 0, 0, 0, 7, 7, 0, 0,
  123901. 0, 7, 7, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5,
  123902. 7, 8, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9,
  123903. 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7,
  123909. 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0,
  123910. 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9, 9, 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. 7,10,10, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 0, 0, 0,
  123917. 10,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0, 9,
  123918. 9, 0, 0, 0, 9, 9, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  123919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123930. 0,
  123931. };
  123932. static float _vq_quantthresh__44c4_s_p2_0[] = {
  123933. -1.5, -0.5, 0.5, 1.5,
  123934. };
  123935. static long _vq_quantmap__44c4_s_p2_0[] = {
  123936. 3, 1, 0, 2, 4,
  123937. };
  123938. static encode_aux_threshmatch _vq_auxt__44c4_s_p2_0 = {
  123939. _vq_quantthresh__44c4_s_p2_0,
  123940. _vq_quantmap__44c4_s_p2_0,
  123941. 5,
  123942. 5
  123943. };
  123944. static static_codebook _44c4_s_p2_0 = {
  123945. 4, 625,
  123946. _vq_lengthlist__44c4_s_p2_0,
  123947. 1, -533725184, 1611661312, 3, 0,
  123948. _vq_quantlist__44c4_s_p2_0,
  123949. NULL,
  123950. &_vq_auxt__44c4_s_p2_0,
  123951. NULL,
  123952. 0
  123953. };
  123954. static long _vq_quantlist__44c4_s_p3_0[] = {
  123955. 2,
  123956. 1,
  123957. 3,
  123958. 0,
  123959. 4,
  123960. };
  123961. static long _vq_lengthlist__44c4_s_p3_0[] = {
  123962. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 4, 6, 6, 0, 0,
  123964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123965. 0, 0, 4, 4, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  123967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123968. 0, 0, 0, 0, 6, 6, 7, 9, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124001. 0,
  124002. };
  124003. static float _vq_quantthresh__44c4_s_p3_0[] = {
  124004. -1.5, -0.5, 0.5, 1.5,
  124005. };
  124006. static long _vq_quantmap__44c4_s_p3_0[] = {
  124007. 3, 1, 0, 2, 4,
  124008. };
  124009. static encode_aux_threshmatch _vq_auxt__44c4_s_p3_0 = {
  124010. _vq_quantthresh__44c4_s_p3_0,
  124011. _vq_quantmap__44c4_s_p3_0,
  124012. 5,
  124013. 5
  124014. };
  124015. static static_codebook _44c4_s_p3_0 = {
  124016. 4, 625,
  124017. _vq_lengthlist__44c4_s_p3_0,
  124018. 1, -533725184, 1611661312, 3, 0,
  124019. _vq_quantlist__44c4_s_p3_0,
  124020. NULL,
  124021. &_vq_auxt__44c4_s_p3_0,
  124022. NULL,
  124023. 0
  124024. };
  124025. static long _vq_quantlist__44c4_s_p4_0[] = {
  124026. 4,
  124027. 3,
  124028. 5,
  124029. 2,
  124030. 6,
  124031. 1,
  124032. 7,
  124033. 0,
  124034. 8,
  124035. };
  124036. static long _vq_lengthlist__44c4_s_p4_0[] = {
  124037. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  124038. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  124039. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  124040. 7, 8, 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0,
  124041. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124042. 0,
  124043. };
  124044. static float _vq_quantthresh__44c4_s_p4_0[] = {
  124045. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  124046. };
  124047. static long _vq_quantmap__44c4_s_p4_0[] = {
  124048. 7, 5, 3, 1, 0, 2, 4, 6,
  124049. 8,
  124050. };
  124051. static encode_aux_threshmatch _vq_auxt__44c4_s_p4_0 = {
  124052. _vq_quantthresh__44c4_s_p4_0,
  124053. _vq_quantmap__44c4_s_p4_0,
  124054. 9,
  124055. 9
  124056. };
  124057. static static_codebook _44c4_s_p4_0 = {
  124058. 2, 81,
  124059. _vq_lengthlist__44c4_s_p4_0,
  124060. 1, -531628032, 1611661312, 4, 0,
  124061. _vq_quantlist__44c4_s_p4_0,
  124062. NULL,
  124063. &_vq_auxt__44c4_s_p4_0,
  124064. NULL,
  124065. 0
  124066. };
  124067. static long _vq_quantlist__44c4_s_p5_0[] = {
  124068. 4,
  124069. 3,
  124070. 5,
  124071. 2,
  124072. 6,
  124073. 1,
  124074. 7,
  124075. 0,
  124076. 8,
  124077. };
  124078. static long _vq_lengthlist__44c4_s_p5_0[] = {
  124079. 2, 3, 3, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  124080. 9, 9, 0, 4, 5, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7,
  124081. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10, 9, 0, 0, 0,
  124082. 9, 8, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  124083. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,10,
  124084. 10,
  124085. };
  124086. static float _vq_quantthresh__44c4_s_p5_0[] = {
  124087. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  124088. };
  124089. static long _vq_quantmap__44c4_s_p5_0[] = {
  124090. 7, 5, 3, 1, 0, 2, 4, 6,
  124091. 8,
  124092. };
  124093. static encode_aux_threshmatch _vq_auxt__44c4_s_p5_0 = {
  124094. _vq_quantthresh__44c4_s_p5_0,
  124095. _vq_quantmap__44c4_s_p5_0,
  124096. 9,
  124097. 9
  124098. };
  124099. static static_codebook _44c4_s_p5_0 = {
  124100. 2, 81,
  124101. _vq_lengthlist__44c4_s_p5_0,
  124102. 1, -531628032, 1611661312, 4, 0,
  124103. _vq_quantlist__44c4_s_p5_0,
  124104. NULL,
  124105. &_vq_auxt__44c4_s_p5_0,
  124106. NULL,
  124107. 0
  124108. };
  124109. static long _vq_quantlist__44c4_s_p6_0[] = {
  124110. 8,
  124111. 7,
  124112. 9,
  124113. 6,
  124114. 10,
  124115. 5,
  124116. 11,
  124117. 4,
  124118. 12,
  124119. 3,
  124120. 13,
  124121. 2,
  124122. 14,
  124123. 1,
  124124. 15,
  124125. 0,
  124126. 16,
  124127. };
  124128. static long _vq_lengthlist__44c4_s_p6_0[] = {
  124129. 2, 4, 4, 6, 6, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,
  124130. 11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,
  124131. 11,11, 0, 4, 4, 7, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  124132. 11,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  124133. 11,11,11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  124134. 10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  124135. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9,
  124136. 9,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  124137. 10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  124138. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,
  124139. 9,10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9,
  124140. 9, 9, 9,10,10,11,11,11,12,12,12, 0, 0, 0, 0, 0,
  124141. 10,10,10,10,11,11,11,11,12,12,13,12, 0, 0, 0, 0,
  124142. 0, 0, 0,10,10,11,11,11,11,12,12,12,12, 0, 0, 0,
  124143. 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0, 0,
  124144. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  124145. 0, 0, 0, 0, 0, 0,12,12,12,12,12,12,13,13,13,13,
  124146. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,12,13,13,
  124147. 13,
  124148. };
  124149. static float _vq_quantthresh__44c4_s_p6_0[] = {
  124150. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  124151. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  124152. };
  124153. static long _vq_quantmap__44c4_s_p6_0[] = {
  124154. 15, 13, 11, 9, 7, 5, 3, 1,
  124155. 0, 2, 4, 6, 8, 10, 12, 14,
  124156. 16,
  124157. };
  124158. static encode_aux_threshmatch _vq_auxt__44c4_s_p6_0 = {
  124159. _vq_quantthresh__44c4_s_p6_0,
  124160. _vq_quantmap__44c4_s_p6_0,
  124161. 17,
  124162. 17
  124163. };
  124164. static static_codebook _44c4_s_p6_0 = {
  124165. 2, 289,
  124166. _vq_lengthlist__44c4_s_p6_0,
  124167. 1, -529530880, 1611661312, 5, 0,
  124168. _vq_quantlist__44c4_s_p6_0,
  124169. NULL,
  124170. &_vq_auxt__44c4_s_p6_0,
  124171. NULL,
  124172. 0
  124173. };
  124174. static long _vq_quantlist__44c4_s_p7_0[] = {
  124175. 1,
  124176. 0,
  124177. 2,
  124178. };
  124179. static long _vq_lengthlist__44c4_s_p7_0[] = {
  124180. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  124181. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  124182. 10,11,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  124183. 11,10,10,11,10,10, 7,11,11,12,11,11,12,11,11, 6,
  124184. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  124185. 10,
  124186. };
  124187. static float _vq_quantthresh__44c4_s_p7_0[] = {
  124188. -5.5, 5.5,
  124189. };
  124190. static long _vq_quantmap__44c4_s_p7_0[] = {
  124191. 1, 0, 2,
  124192. };
  124193. static encode_aux_threshmatch _vq_auxt__44c4_s_p7_0 = {
  124194. _vq_quantthresh__44c4_s_p7_0,
  124195. _vq_quantmap__44c4_s_p7_0,
  124196. 3,
  124197. 3
  124198. };
  124199. static static_codebook _44c4_s_p7_0 = {
  124200. 4, 81,
  124201. _vq_lengthlist__44c4_s_p7_0,
  124202. 1, -529137664, 1618345984, 2, 0,
  124203. _vq_quantlist__44c4_s_p7_0,
  124204. NULL,
  124205. &_vq_auxt__44c4_s_p7_0,
  124206. NULL,
  124207. 0
  124208. };
  124209. static long _vq_quantlist__44c4_s_p7_1[] = {
  124210. 5,
  124211. 4,
  124212. 6,
  124213. 3,
  124214. 7,
  124215. 2,
  124216. 8,
  124217. 1,
  124218. 9,
  124219. 0,
  124220. 10,
  124221. };
  124222. static long _vq_lengthlist__44c4_s_p7_1[] = {
  124223. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  124224. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  124225. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  124226. 7, 8, 8, 8, 8, 8, 8,10,10,10, 8, 7, 8, 8, 8, 8,
  124227. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  124228. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  124229. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 9, 8,10,10,
  124230. 10,10,10, 8, 8, 8, 8, 9, 9,
  124231. };
  124232. static float _vq_quantthresh__44c4_s_p7_1[] = {
  124233. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  124234. 3.5, 4.5,
  124235. };
  124236. static long _vq_quantmap__44c4_s_p7_1[] = {
  124237. 9, 7, 5, 3, 1, 0, 2, 4,
  124238. 6, 8, 10,
  124239. };
  124240. static encode_aux_threshmatch _vq_auxt__44c4_s_p7_1 = {
  124241. _vq_quantthresh__44c4_s_p7_1,
  124242. _vq_quantmap__44c4_s_p7_1,
  124243. 11,
  124244. 11
  124245. };
  124246. static static_codebook _44c4_s_p7_1 = {
  124247. 2, 121,
  124248. _vq_lengthlist__44c4_s_p7_1,
  124249. 1, -531365888, 1611661312, 4, 0,
  124250. _vq_quantlist__44c4_s_p7_1,
  124251. NULL,
  124252. &_vq_auxt__44c4_s_p7_1,
  124253. NULL,
  124254. 0
  124255. };
  124256. static long _vq_quantlist__44c4_s_p8_0[] = {
  124257. 6,
  124258. 5,
  124259. 7,
  124260. 4,
  124261. 8,
  124262. 3,
  124263. 9,
  124264. 2,
  124265. 10,
  124266. 1,
  124267. 11,
  124268. 0,
  124269. 12,
  124270. };
  124271. static long _vq_lengthlist__44c4_s_p8_0[] = {
  124272. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  124273. 7, 7, 8, 8, 8, 8, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  124274. 8, 9, 9,10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  124275. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  124276. 11, 0,12,12, 9, 9, 9, 9,10,10,10,10,11,11, 0,13,
  124277. 13, 9, 9,10, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  124278. 10,10,10,10,11,11,12,12, 0, 0, 0,10,10,10,10,10,
  124279. 10,11,11,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  124280. 12,12, 0, 0, 0,14,14,11,11,11,11,12,12,12,13, 0,
  124281. 0, 0, 0, 0,12,12,12,12,12,12,13,13, 0, 0, 0, 0,
  124282. 0,13,12,12,12,12,12,13,13,
  124283. };
  124284. static float _vq_quantthresh__44c4_s_p8_0[] = {
  124285. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  124286. 12.5, 17.5, 22.5, 27.5,
  124287. };
  124288. static long _vq_quantmap__44c4_s_p8_0[] = {
  124289. 11, 9, 7, 5, 3, 1, 0, 2,
  124290. 4, 6, 8, 10, 12,
  124291. };
  124292. static encode_aux_threshmatch _vq_auxt__44c4_s_p8_0 = {
  124293. _vq_quantthresh__44c4_s_p8_0,
  124294. _vq_quantmap__44c4_s_p8_0,
  124295. 13,
  124296. 13
  124297. };
  124298. static static_codebook _44c4_s_p8_0 = {
  124299. 2, 169,
  124300. _vq_lengthlist__44c4_s_p8_0,
  124301. 1, -526516224, 1616117760, 4, 0,
  124302. _vq_quantlist__44c4_s_p8_0,
  124303. NULL,
  124304. &_vq_auxt__44c4_s_p8_0,
  124305. NULL,
  124306. 0
  124307. };
  124308. static long _vq_quantlist__44c4_s_p8_1[] = {
  124309. 2,
  124310. 1,
  124311. 3,
  124312. 0,
  124313. 4,
  124314. };
  124315. static long _vq_lengthlist__44c4_s_p8_1[] = {
  124316. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 5, 4, 5, 5, 6,
  124317. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  124318. };
  124319. static float _vq_quantthresh__44c4_s_p8_1[] = {
  124320. -1.5, -0.5, 0.5, 1.5,
  124321. };
  124322. static long _vq_quantmap__44c4_s_p8_1[] = {
  124323. 3, 1, 0, 2, 4,
  124324. };
  124325. static encode_aux_threshmatch _vq_auxt__44c4_s_p8_1 = {
  124326. _vq_quantthresh__44c4_s_p8_1,
  124327. _vq_quantmap__44c4_s_p8_1,
  124328. 5,
  124329. 5
  124330. };
  124331. static static_codebook _44c4_s_p8_1 = {
  124332. 2, 25,
  124333. _vq_lengthlist__44c4_s_p8_1,
  124334. 1, -533725184, 1611661312, 3, 0,
  124335. _vq_quantlist__44c4_s_p8_1,
  124336. NULL,
  124337. &_vq_auxt__44c4_s_p8_1,
  124338. NULL,
  124339. 0
  124340. };
  124341. static long _vq_quantlist__44c4_s_p9_0[] = {
  124342. 6,
  124343. 5,
  124344. 7,
  124345. 4,
  124346. 8,
  124347. 3,
  124348. 9,
  124349. 2,
  124350. 10,
  124351. 1,
  124352. 11,
  124353. 0,
  124354. 12,
  124355. };
  124356. static long _vq_lengthlist__44c4_s_p9_0[] = {
  124357. 1, 3, 3,12,12,12,12,12,12,12,12,12,12, 4, 7, 7,
  124358. 12,12,12,12,12,12,12,12,12,12, 3, 8, 8,12,12,12,
  124359. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  124360. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  124361. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  124362. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  124363. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  124364. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  124365. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  124366. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  124367. 12,12,12,12,12,12,12,12,12,
  124368. };
  124369. static float _vq_quantthresh__44c4_s_p9_0[] = {
  124370. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  124371. 787.5, 1102.5, 1417.5, 1732.5,
  124372. };
  124373. static long _vq_quantmap__44c4_s_p9_0[] = {
  124374. 11, 9, 7, 5, 3, 1, 0, 2,
  124375. 4, 6, 8, 10, 12,
  124376. };
  124377. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_0 = {
  124378. _vq_quantthresh__44c4_s_p9_0,
  124379. _vq_quantmap__44c4_s_p9_0,
  124380. 13,
  124381. 13
  124382. };
  124383. static static_codebook _44c4_s_p9_0 = {
  124384. 2, 169,
  124385. _vq_lengthlist__44c4_s_p9_0,
  124386. 1, -513964032, 1628680192, 4, 0,
  124387. _vq_quantlist__44c4_s_p9_0,
  124388. NULL,
  124389. &_vq_auxt__44c4_s_p9_0,
  124390. NULL,
  124391. 0
  124392. };
  124393. static long _vq_quantlist__44c4_s_p9_1[] = {
  124394. 7,
  124395. 6,
  124396. 8,
  124397. 5,
  124398. 9,
  124399. 4,
  124400. 10,
  124401. 3,
  124402. 11,
  124403. 2,
  124404. 12,
  124405. 1,
  124406. 13,
  124407. 0,
  124408. 14,
  124409. };
  124410. static long _vq_lengthlist__44c4_s_p9_1[] = {
  124411. 1, 4, 4, 5, 5, 7, 7, 9, 8,10, 9,10,10,10,10, 6,
  124412. 5, 5, 7, 7, 9, 8,10, 9,11,10,12,12,13,13, 6, 5,
  124413. 5, 7, 7, 9, 9,10,10,11,11,12,12,12,13,19, 8, 8,
  124414. 8, 8, 9, 9,10,10,12,11,12,12,13,13,19, 8, 8, 8,
  124415. 8, 9, 9,11,11,12,12,13,13,13,13,19,12,12, 9, 9,
  124416. 11,11,11,11,12,11,13,12,13,13,18,12,12, 9, 9,11,
  124417. 10,11,11,12,12,12,13,13,14,19,18,18,11,11,11,11,
  124418. 12,12,13,12,13,13,14,14,16,18,18,11,11,11,10,12,
  124419. 11,13,13,13,13,13,14,17,18,18,14,15,11,12,12,13,
  124420. 13,13,13,14,14,14,18,18,18,15,15,12,10,13,10,13,
  124421. 13,13,13,13,14,18,17,18,17,18,12,13,12,13,13,13,
  124422. 14,14,16,14,18,17,18,18,17,13,12,13,10,12,12,14,
  124423. 14,14,14,17,18,18,18,18,14,15,12,12,13,12,14,14,
  124424. 15,15,18,18,18,17,18,15,14,12,11,12,12,14,14,14,
  124425. 15,
  124426. };
  124427. static float _vq_quantthresh__44c4_s_p9_1[] = {
  124428. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  124429. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  124430. };
  124431. static long _vq_quantmap__44c4_s_p9_1[] = {
  124432. 13, 11, 9, 7, 5, 3, 1, 0,
  124433. 2, 4, 6, 8, 10, 12, 14,
  124434. };
  124435. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_1 = {
  124436. _vq_quantthresh__44c4_s_p9_1,
  124437. _vq_quantmap__44c4_s_p9_1,
  124438. 15,
  124439. 15
  124440. };
  124441. static static_codebook _44c4_s_p9_1 = {
  124442. 2, 225,
  124443. _vq_lengthlist__44c4_s_p9_1,
  124444. 1, -520986624, 1620377600, 4, 0,
  124445. _vq_quantlist__44c4_s_p9_1,
  124446. NULL,
  124447. &_vq_auxt__44c4_s_p9_1,
  124448. NULL,
  124449. 0
  124450. };
  124451. static long _vq_quantlist__44c4_s_p9_2[] = {
  124452. 10,
  124453. 9,
  124454. 11,
  124455. 8,
  124456. 12,
  124457. 7,
  124458. 13,
  124459. 6,
  124460. 14,
  124461. 5,
  124462. 15,
  124463. 4,
  124464. 16,
  124465. 3,
  124466. 17,
  124467. 2,
  124468. 18,
  124469. 1,
  124470. 19,
  124471. 0,
  124472. 20,
  124473. };
  124474. static long _vq_lengthlist__44c4_s_p9_2[] = {
  124475. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  124476. 8, 9, 9, 9, 9,11, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  124477. 9, 9, 9, 9, 9, 9,10,10,10,10,11, 6, 6, 7, 7, 8,
  124478. 8, 8, 8, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,11,
  124479. 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  124480. 10,10,10,10,12,11,11, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  124481. 9,10,10,10,10,10,10,10,10,12,11,12, 8, 8, 8, 8,
  124482. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,11,
  124483. 11, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,10,10,10,10,
  124484. 10,10,10,11,11,12, 9, 9, 9, 9, 9, 9,10, 9,10,10,
  124485. 10,10,10,10,10,10,10,10,11,11,11,11,11, 9, 9, 9,
  124486. 9,10,10,10,10,10,10,10,10,10,10,10,10,11,12,11,
  124487. 11,11, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  124488. 10,10,11,11,11,11,11, 9, 9, 9, 9,10,10,10,10,10,
  124489. 10,10,10,10,10,10,10,11,11,11,12,12,10,10,10,10,
  124490. 10,10,10,10,10,10,10,10,10,10,10,10,11,12,11,12,
  124491. 11,11,11, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  124492. 10,11,12,11,11,11,11,11,10,10,10,10,10,10,10,10,
  124493. 10,10,10,10,10,10,11,11,11,12,11,11,11,10,10,10,
  124494. 10,10,10,10,10,10,10,10,10,10,10,12,11,11,12,11,
  124495. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  124496. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  124497. 10,10,10,10,10,11,11,11,11,12,12,11,11,11,11,11,
  124498. 11,11,10,10,10,10,10,10,10,10,12,12,12,11,11,11,
  124499. 12,11,11,11,10,10,10,10,10,10,10,10,10,10,10,12,
  124500. 11,12,12,12,12,12,11,12,11,11,10,10,10,10,10,10,
  124501. 10,10,10,10,12,12,12,12,11,11,11,11,11,11,11,10,
  124502. 10,10,10,10,10,10,10,10,10,
  124503. };
  124504. static float _vq_quantthresh__44c4_s_p9_2[] = {
  124505. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  124506. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  124507. 6.5, 7.5, 8.5, 9.5,
  124508. };
  124509. static long _vq_quantmap__44c4_s_p9_2[] = {
  124510. 19, 17, 15, 13, 11, 9, 7, 5,
  124511. 3, 1, 0, 2, 4, 6, 8, 10,
  124512. 12, 14, 16, 18, 20,
  124513. };
  124514. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_2 = {
  124515. _vq_quantthresh__44c4_s_p9_2,
  124516. _vq_quantmap__44c4_s_p9_2,
  124517. 21,
  124518. 21
  124519. };
  124520. static static_codebook _44c4_s_p9_2 = {
  124521. 2, 441,
  124522. _vq_lengthlist__44c4_s_p9_2,
  124523. 1, -529268736, 1611661312, 5, 0,
  124524. _vq_quantlist__44c4_s_p9_2,
  124525. NULL,
  124526. &_vq_auxt__44c4_s_p9_2,
  124527. NULL,
  124528. 0
  124529. };
  124530. static long _huff_lengthlist__44c4_s_short[] = {
  124531. 4, 7,14,10,15,10,12,15,16,15, 4, 2,11, 5,10, 6,
  124532. 8,11,14,14,14,10, 7,11, 6, 8,10,11,13,15, 9, 4,
  124533. 11, 5, 9, 6, 9,12,14,15,14, 9, 6, 9, 4, 5, 7,10,
  124534. 12,13, 9, 5, 7, 6, 5, 5, 7,10,13,13,10, 8, 9, 8,
  124535. 7, 6, 8,10,14,14,13,11,10,10, 7, 7, 8,11,14,15,
  124536. 13,12, 9, 9, 6, 5, 7,10,14,17,15,13,11,10, 6, 6,
  124537. 7, 9,12,17,
  124538. };
  124539. static static_codebook _huff_book__44c4_s_short = {
  124540. 2, 100,
  124541. _huff_lengthlist__44c4_s_short,
  124542. 0, 0, 0, 0, 0,
  124543. NULL,
  124544. NULL,
  124545. NULL,
  124546. NULL,
  124547. 0
  124548. };
  124549. static long _huff_lengthlist__44c5_s_long[] = {
  124550. 3, 8, 9,13,10,12,12,12,12,12, 6, 4, 6, 8, 6, 8,
  124551. 10,10,11,12, 8, 5, 4,10, 4, 7, 8, 9,10,11,13, 8,
  124552. 10, 8, 9, 9,11,12,13,14,10, 6, 4, 9, 3, 5, 6, 8,
  124553. 10,11,11, 8, 6, 9, 5, 5, 6, 7, 9,11,12, 9, 7,11,
  124554. 6, 6, 6, 7, 8,10,12,11, 9,12, 7, 7, 6, 6, 7, 9,
  124555. 13,12,10,13, 9, 8, 7, 7, 7, 8,11,15,11,15,11,10,
  124556. 9, 8, 7, 7,
  124557. };
  124558. static static_codebook _huff_book__44c5_s_long = {
  124559. 2, 100,
  124560. _huff_lengthlist__44c5_s_long,
  124561. 0, 0, 0, 0, 0,
  124562. NULL,
  124563. NULL,
  124564. NULL,
  124565. NULL,
  124566. 0
  124567. };
  124568. static long _vq_quantlist__44c5_s_p1_0[] = {
  124569. 1,
  124570. 0,
  124571. 2,
  124572. };
  124573. static long _vq_lengthlist__44c5_s_p1_0[] = {
  124574. 2, 4, 4, 0, 0, 0, 0, 0, 0, 4, 7, 7, 0, 0, 0, 0,
  124575. 0, 0, 4, 6, 7, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  124580. 0, 0, 0, 7, 8, 9, 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, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  124585. 0, 0, 0, 0, 7, 9, 9, 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, 0, 0, 0, 0, 0, 0, 0,
  124606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0,
  124611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0,
  124616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  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, 4, 7, 7, 0, 0, 0, 0,
  124620. 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 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, 7, 9, 9, 0, 0, 0,
  124625. 0, 0, 0, 9,10,11, 0, 0, 0, 0, 0, 0, 9,10,10, 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, 7, 9, 9, 0, 0,
  124630. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124652. 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124657. 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  124666. 0, 0, 0, 0, 7, 9, 9, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  124671. 0, 0, 0, 0, 0, 8, 9,10, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  124676. 0, 0, 0, 0, 0, 0, 9,11,10, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124984. 0,
  124985. };
  124986. static float _vq_quantthresh__44c5_s_p1_0[] = {
  124987. -0.5, 0.5,
  124988. };
  124989. static long _vq_quantmap__44c5_s_p1_0[] = {
  124990. 1, 0, 2,
  124991. };
  124992. static encode_aux_threshmatch _vq_auxt__44c5_s_p1_0 = {
  124993. _vq_quantthresh__44c5_s_p1_0,
  124994. _vq_quantmap__44c5_s_p1_0,
  124995. 3,
  124996. 3
  124997. };
  124998. static static_codebook _44c5_s_p1_0 = {
  124999. 8, 6561,
  125000. _vq_lengthlist__44c5_s_p1_0,
  125001. 1, -535822336, 1611661312, 2, 0,
  125002. _vq_quantlist__44c5_s_p1_0,
  125003. NULL,
  125004. &_vq_auxt__44c5_s_p1_0,
  125005. NULL,
  125006. 0
  125007. };
  125008. static long _vq_quantlist__44c5_s_p2_0[] = {
  125009. 2,
  125010. 1,
  125011. 3,
  125012. 0,
  125013. 4,
  125014. };
  125015. static long _vq_lengthlist__44c5_s_p2_0[] = {
  125016. 2, 4, 4, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  125017. 8, 7, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 0, 0, 0, 8,
  125018. 8, 0, 0, 0, 8, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  125019. 0, 0, 4, 6, 6, 0, 0, 0, 8, 8, 0, 0, 0, 7, 8, 0,
  125020. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5, 8, 7, 0, 0, 0, 8, 8, 0, 0,
  125026. 0, 8, 8, 0, 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 5,
  125027. 7, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0,10,
  125028. 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8,
  125034. 0, 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0,
  125035. 0, 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0,10,10, 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. 8,10,10, 0, 0, 0,10,10, 0, 0, 0, 9,10, 0, 0, 0,
  125042. 11,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0,10,
  125043. 10, 0, 0, 0,10,10, 0, 0, 0,10,11, 0, 0, 0, 0, 0,
  125044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125055. 0,
  125056. };
  125057. static float _vq_quantthresh__44c5_s_p2_0[] = {
  125058. -1.5, -0.5, 0.5, 1.5,
  125059. };
  125060. static long _vq_quantmap__44c5_s_p2_0[] = {
  125061. 3, 1, 0, 2, 4,
  125062. };
  125063. static encode_aux_threshmatch _vq_auxt__44c5_s_p2_0 = {
  125064. _vq_quantthresh__44c5_s_p2_0,
  125065. _vq_quantmap__44c5_s_p2_0,
  125066. 5,
  125067. 5
  125068. };
  125069. static static_codebook _44c5_s_p2_0 = {
  125070. 4, 625,
  125071. _vq_lengthlist__44c5_s_p2_0,
  125072. 1, -533725184, 1611661312, 3, 0,
  125073. _vq_quantlist__44c5_s_p2_0,
  125074. NULL,
  125075. &_vq_auxt__44c5_s_p2_0,
  125076. NULL,
  125077. 0
  125078. };
  125079. static long _vq_quantlist__44c5_s_p3_0[] = {
  125080. 2,
  125081. 1,
  125082. 3,
  125083. 0,
  125084. 4,
  125085. };
  125086. static long _vq_lengthlist__44c5_s_p3_0[] = {
  125087. 2, 4, 3, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 6, 6, 0, 0,
  125089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125090. 0, 0, 3, 5, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 8, 8,
  125092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125093. 0, 0, 0, 0, 5, 6, 6, 8, 8, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125126. 0,
  125127. };
  125128. static float _vq_quantthresh__44c5_s_p3_0[] = {
  125129. -1.5, -0.5, 0.5, 1.5,
  125130. };
  125131. static long _vq_quantmap__44c5_s_p3_0[] = {
  125132. 3, 1, 0, 2, 4,
  125133. };
  125134. static encode_aux_threshmatch _vq_auxt__44c5_s_p3_0 = {
  125135. _vq_quantthresh__44c5_s_p3_0,
  125136. _vq_quantmap__44c5_s_p3_0,
  125137. 5,
  125138. 5
  125139. };
  125140. static static_codebook _44c5_s_p3_0 = {
  125141. 4, 625,
  125142. _vq_lengthlist__44c5_s_p3_0,
  125143. 1, -533725184, 1611661312, 3, 0,
  125144. _vq_quantlist__44c5_s_p3_0,
  125145. NULL,
  125146. &_vq_auxt__44c5_s_p3_0,
  125147. NULL,
  125148. 0
  125149. };
  125150. static long _vq_quantlist__44c5_s_p4_0[] = {
  125151. 4,
  125152. 3,
  125153. 5,
  125154. 2,
  125155. 6,
  125156. 1,
  125157. 7,
  125158. 0,
  125159. 8,
  125160. };
  125161. static long _vq_lengthlist__44c5_s_p4_0[] = {
  125162. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  125163. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  125164. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  125165. 7, 7, 0, 0, 0, 0, 0, 0, 0, 8, 7, 0, 0, 0, 0, 0,
  125166. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125167. 0,
  125168. };
  125169. static float _vq_quantthresh__44c5_s_p4_0[] = {
  125170. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  125171. };
  125172. static long _vq_quantmap__44c5_s_p4_0[] = {
  125173. 7, 5, 3, 1, 0, 2, 4, 6,
  125174. 8,
  125175. };
  125176. static encode_aux_threshmatch _vq_auxt__44c5_s_p4_0 = {
  125177. _vq_quantthresh__44c5_s_p4_0,
  125178. _vq_quantmap__44c5_s_p4_0,
  125179. 9,
  125180. 9
  125181. };
  125182. static static_codebook _44c5_s_p4_0 = {
  125183. 2, 81,
  125184. _vq_lengthlist__44c5_s_p4_0,
  125185. 1, -531628032, 1611661312, 4, 0,
  125186. _vq_quantlist__44c5_s_p4_0,
  125187. NULL,
  125188. &_vq_auxt__44c5_s_p4_0,
  125189. NULL,
  125190. 0
  125191. };
  125192. static long _vq_quantlist__44c5_s_p5_0[] = {
  125193. 4,
  125194. 3,
  125195. 5,
  125196. 2,
  125197. 6,
  125198. 1,
  125199. 7,
  125200. 0,
  125201. 8,
  125202. };
  125203. static long _vq_lengthlist__44c5_s_p5_0[] = {
  125204. 2, 4, 3, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  125205. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7,
  125206. 7, 7, 9, 9, 0, 0, 0, 7, 6, 7, 7, 9, 9, 0, 0, 0,
  125207. 8, 8, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  125208. 0, 0, 9, 9, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  125209. 10,
  125210. };
  125211. static float _vq_quantthresh__44c5_s_p5_0[] = {
  125212. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  125213. };
  125214. static long _vq_quantmap__44c5_s_p5_0[] = {
  125215. 7, 5, 3, 1, 0, 2, 4, 6,
  125216. 8,
  125217. };
  125218. static encode_aux_threshmatch _vq_auxt__44c5_s_p5_0 = {
  125219. _vq_quantthresh__44c5_s_p5_0,
  125220. _vq_quantmap__44c5_s_p5_0,
  125221. 9,
  125222. 9
  125223. };
  125224. static static_codebook _44c5_s_p5_0 = {
  125225. 2, 81,
  125226. _vq_lengthlist__44c5_s_p5_0,
  125227. 1, -531628032, 1611661312, 4, 0,
  125228. _vq_quantlist__44c5_s_p5_0,
  125229. NULL,
  125230. &_vq_auxt__44c5_s_p5_0,
  125231. NULL,
  125232. 0
  125233. };
  125234. static long _vq_quantlist__44c5_s_p6_0[] = {
  125235. 8,
  125236. 7,
  125237. 9,
  125238. 6,
  125239. 10,
  125240. 5,
  125241. 11,
  125242. 4,
  125243. 12,
  125244. 3,
  125245. 13,
  125246. 2,
  125247. 14,
  125248. 1,
  125249. 15,
  125250. 0,
  125251. 16,
  125252. };
  125253. static long _vq_lengthlist__44c5_s_p6_0[] = {
  125254. 2, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,11,
  125255. 11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,
  125256. 12,12, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  125257. 11,12,12, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  125258. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  125259. 10,11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10,10,
  125260. 11,11,11,11,12,12, 0, 0, 0, 7, 7, 8, 9,10,10,10,
  125261. 10,11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,
  125262. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  125263. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  125264. 10,10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9,
  125265. 9, 9,10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0,
  125266. 10,10,10,10,11,11,11,12,12,12,13,13, 0, 0, 0, 0,
  125267. 0, 0, 0,10,10,11,11,11,11,12,12,13,13, 0, 0, 0,
  125268. 0, 0, 0, 0,11,11,11,11,12,12,12,13,13,13, 0, 0,
  125269. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  125270. 0, 0, 0, 0, 0, 0,12,12,12,12,13,12,13,13,13,13,
  125271. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,
  125272. 13,
  125273. };
  125274. static float _vq_quantthresh__44c5_s_p6_0[] = {
  125275. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  125276. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  125277. };
  125278. static long _vq_quantmap__44c5_s_p6_0[] = {
  125279. 15, 13, 11, 9, 7, 5, 3, 1,
  125280. 0, 2, 4, 6, 8, 10, 12, 14,
  125281. 16,
  125282. };
  125283. static encode_aux_threshmatch _vq_auxt__44c5_s_p6_0 = {
  125284. _vq_quantthresh__44c5_s_p6_0,
  125285. _vq_quantmap__44c5_s_p6_0,
  125286. 17,
  125287. 17
  125288. };
  125289. static static_codebook _44c5_s_p6_0 = {
  125290. 2, 289,
  125291. _vq_lengthlist__44c5_s_p6_0,
  125292. 1, -529530880, 1611661312, 5, 0,
  125293. _vq_quantlist__44c5_s_p6_0,
  125294. NULL,
  125295. &_vq_auxt__44c5_s_p6_0,
  125296. NULL,
  125297. 0
  125298. };
  125299. static long _vq_quantlist__44c5_s_p7_0[] = {
  125300. 1,
  125301. 0,
  125302. 2,
  125303. };
  125304. static long _vq_lengthlist__44c5_s_p7_0[] = {
  125305. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  125306. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  125307. 10,11,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  125308. 11,10,10,11,10,10, 7,11,11,12,11,11,12,11,11, 6,
  125309. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  125310. 10,
  125311. };
  125312. static float _vq_quantthresh__44c5_s_p7_0[] = {
  125313. -5.5, 5.5,
  125314. };
  125315. static long _vq_quantmap__44c5_s_p7_0[] = {
  125316. 1, 0, 2,
  125317. };
  125318. static encode_aux_threshmatch _vq_auxt__44c5_s_p7_0 = {
  125319. _vq_quantthresh__44c5_s_p7_0,
  125320. _vq_quantmap__44c5_s_p7_0,
  125321. 3,
  125322. 3
  125323. };
  125324. static static_codebook _44c5_s_p7_0 = {
  125325. 4, 81,
  125326. _vq_lengthlist__44c5_s_p7_0,
  125327. 1, -529137664, 1618345984, 2, 0,
  125328. _vq_quantlist__44c5_s_p7_0,
  125329. NULL,
  125330. &_vq_auxt__44c5_s_p7_0,
  125331. NULL,
  125332. 0
  125333. };
  125334. static long _vq_quantlist__44c5_s_p7_1[] = {
  125335. 5,
  125336. 4,
  125337. 6,
  125338. 3,
  125339. 7,
  125340. 2,
  125341. 8,
  125342. 1,
  125343. 9,
  125344. 0,
  125345. 10,
  125346. };
  125347. static long _vq_lengthlist__44c5_s_p7_1[] = {
  125348. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6,
  125349. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  125350. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  125351. 7, 8, 8, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  125352. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  125353. 8, 8, 8, 8, 8, 8, 8, 9,10,10,10,10,10, 8, 8, 8,
  125354. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  125355. 10,10,10, 8, 8, 8, 8, 8, 8,
  125356. };
  125357. static float _vq_quantthresh__44c5_s_p7_1[] = {
  125358. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  125359. 3.5, 4.5,
  125360. };
  125361. static long _vq_quantmap__44c5_s_p7_1[] = {
  125362. 9, 7, 5, 3, 1, 0, 2, 4,
  125363. 6, 8, 10,
  125364. };
  125365. static encode_aux_threshmatch _vq_auxt__44c5_s_p7_1 = {
  125366. _vq_quantthresh__44c5_s_p7_1,
  125367. _vq_quantmap__44c5_s_p7_1,
  125368. 11,
  125369. 11
  125370. };
  125371. static static_codebook _44c5_s_p7_1 = {
  125372. 2, 121,
  125373. _vq_lengthlist__44c5_s_p7_1,
  125374. 1, -531365888, 1611661312, 4, 0,
  125375. _vq_quantlist__44c5_s_p7_1,
  125376. NULL,
  125377. &_vq_auxt__44c5_s_p7_1,
  125378. NULL,
  125379. 0
  125380. };
  125381. static long _vq_quantlist__44c5_s_p8_0[] = {
  125382. 6,
  125383. 5,
  125384. 7,
  125385. 4,
  125386. 8,
  125387. 3,
  125388. 9,
  125389. 2,
  125390. 10,
  125391. 1,
  125392. 11,
  125393. 0,
  125394. 12,
  125395. };
  125396. static long _vq_lengthlist__44c5_s_p8_0[] = {
  125397. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  125398. 7, 7, 8, 8, 8, 9,10,10,10,10, 7, 5, 5, 7, 7, 8,
  125399. 8, 9, 9,10,10,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  125400. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  125401. 11, 0,12,12, 9, 9, 9,10,10,10,10,10,11,11, 0,13,
  125402. 13, 9, 9, 9, 9,10,10,11,11,11,11, 0, 0, 0,10,10,
  125403. 10,10,10,10,11,11,11,11, 0, 0, 0,10,10,10,10,10,
  125404. 10,11,11,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  125405. 12,12, 0, 0, 0,14,14,11,11,11,11,12,12,12,12, 0,
  125406. 0, 0, 0, 0,12,12,12,12,12,12,13,13, 0, 0, 0, 0,
  125407. 0,12,12,12,12,12,12,13,13,
  125408. };
  125409. static float _vq_quantthresh__44c5_s_p8_0[] = {
  125410. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  125411. 12.5, 17.5, 22.5, 27.5,
  125412. };
  125413. static long _vq_quantmap__44c5_s_p8_0[] = {
  125414. 11, 9, 7, 5, 3, 1, 0, 2,
  125415. 4, 6, 8, 10, 12,
  125416. };
  125417. static encode_aux_threshmatch _vq_auxt__44c5_s_p8_0 = {
  125418. _vq_quantthresh__44c5_s_p8_0,
  125419. _vq_quantmap__44c5_s_p8_0,
  125420. 13,
  125421. 13
  125422. };
  125423. static static_codebook _44c5_s_p8_0 = {
  125424. 2, 169,
  125425. _vq_lengthlist__44c5_s_p8_0,
  125426. 1, -526516224, 1616117760, 4, 0,
  125427. _vq_quantlist__44c5_s_p8_0,
  125428. NULL,
  125429. &_vq_auxt__44c5_s_p8_0,
  125430. NULL,
  125431. 0
  125432. };
  125433. static long _vq_quantlist__44c5_s_p8_1[] = {
  125434. 2,
  125435. 1,
  125436. 3,
  125437. 0,
  125438. 4,
  125439. };
  125440. static long _vq_lengthlist__44c5_s_p8_1[] = {
  125441. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 4, 5, 5, 5, 6,
  125442. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  125443. };
  125444. static float _vq_quantthresh__44c5_s_p8_1[] = {
  125445. -1.5, -0.5, 0.5, 1.5,
  125446. };
  125447. static long _vq_quantmap__44c5_s_p8_1[] = {
  125448. 3, 1, 0, 2, 4,
  125449. };
  125450. static encode_aux_threshmatch _vq_auxt__44c5_s_p8_1 = {
  125451. _vq_quantthresh__44c5_s_p8_1,
  125452. _vq_quantmap__44c5_s_p8_1,
  125453. 5,
  125454. 5
  125455. };
  125456. static static_codebook _44c5_s_p8_1 = {
  125457. 2, 25,
  125458. _vq_lengthlist__44c5_s_p8_1,
  125459. 1, -533725184, 1611661312, 3, 0,
  125460. _vq_quantlist__44c5_s_p8_1,
  125461. NULL,
  125462. &_vq_auxt__44c5_s_p8_1,
  125463. NULL,
  125464. 0
  125465. };
  125466. static long _vq_quantlist__44c5_s_p9_0[] = {
  125467. 7,
  125468. 6,
  125469. 8,
  125470. 5,
  125471. 9,
  125472. 4,
  125473. 10,
  125474. 3,
  125475. 11,
  125476. 2,
  125477. 12,
  125478. 1,
  125479. 13,
  125480. 0,
  125481. 14,
  125482. };
  125483. static long _vq_lengthlist__44c5_s_p9_0[] = {
  125484. 1, 3, 3,13,13,13,13,13,13,13,13,13,13,13,13, 4,
  125485. 7, 7,13,13,13,13,13,13,13,13,13,13,13,13, 3, 8,
  125486. 6,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  125487. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  125488. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  125489. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  125490. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  125491. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  125492. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  125493. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  125494. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  125495. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  125496. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  125497. 13,13,13,13,13,13,13,13,13,12,12,12,12,12,12,12,
  125498. 12,
  125499. };
  125500. static float _vq_quantthresh__44c5_s_p9_0[] = {
  125501. -2320.5, -1963.5, -1606.5, -1249.5, -892.5, -535.5, -178.5, 178.5,
  125502. 535.5, 892.5, 1249.5, 1606.5, 1963.5, 2320.5,
  125503. };
  125504. static long _vq_quantmap__44c5_s_p9_0[] = {
  125505. 13, 11, 9, 7, 5, 3, 1, 0,
  125506. 2, 4, 6, 8, 10, 12, 14,
  125507. };
  125508. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_0 = {
  125509. _vq_quantthresh__44c5_s_p9_0,
  125510. _vq_quantmap__44c5_s_p9_0,
  125511. 15,
  125512. 15
  125513. };
  125514. static static_codebook _44c5_s_p9_0 = {
  125515. 2, 225,
  125516. _vq_lengthlist__44c5_s_p9_0,
  125517. 1, -512522752, 1628852224, 4, 0,
  125518. _vq_quantlist__44c5_s_p9_0,
  125519. NULL,
  125520. &_vq_auxt__44c5_s_p9_0,
  125521. NULL,
  125522. 0
  125523. };
  125524. static long _vq_quantlist__44c5_s_p9_1[] = {
  125525. 8,
  125526. 7,
  125527. 9,
  125528. 6,
  125529. 10,
  125530. 5,
  125531. 11,
  125532. 4,
  125533. 12,
  125534. 3,
  125535. 13,
  125536. 2,
  125537. 14,
  125538. 1,
  125539. 15,
  125540. 0,
  125541. 16,
  125542. };
  125543. static long _vq_lengthlist__44c5_s_p9_1[] = {
  125544. 1, 4, 4, 5, 5, 7, 7, 9, 8,10, 9,10,10,11,10,11,
  125545. 11, 6, 5, 5, 7, 7, 8, 9,10,10,11,10,12,11,12,11,
  125546. 13,12, 6, 5, 5, 7, 7, 9, 9,10,10,11,11,12,12,13,
  125547. 12,13,13,18, 8, 8, 8, 8, 9, 9,10,11,11,11,12,11,
  125548. 13,11,13,12,18, 8, 8, 8, 8,10,10,11,11,12,12,13,
  125549. 13,13,13,13,14,18,12,12, 9, 9,11,11,11,11,12,12,
  125550. 13,12,13,12,13,13,20,13,12, 9, 9,11,11,11,11,12,
  125551. 12,13,13,13,14,14,13,20,18,19,11,12,11,11,12,12,
  125552. 13,13,13,13,13,13,14,13,18,19,19,12,11,11,11,12,
  125553. 12,13,12,13,13,13,14,14,13,18,17,19,14,15,12,12,
  125554. 12,13,13,13,14,14,14,14,14,14,19,19,19,16,15,12,
  125555. 11,13,12,14,14,14,13,13,14,14,14,19,18,19,18,19,
  125556. 13,13,13,13,14,14,14,13,14,14,14,14,18,17,19,19,
  125557. 19,13,13,13,11,13,11,13,14,14,14,14,14,19,17,17,
  125558. 18,18,16,16,13,13,13,13,14,13,15,15,14,14,19,19,
  125559. 17,17,18,16,16,13,11,14,10,13,12,14,14,14,14,19,
  125560. 19,19,19,19,18,17,13,14,13,11,14,13,14,14,15,15,
  125561. 19,19,19,17,19,18,18,14,13,12,11,14,11,15,15,15,
  125562. 15,
  125563. };
  125564. static float _vq_quantthresh__44c5_s_p9_1[] = {
  125565. -157.5, -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5,
  125566. 10.5, 31.5, 52.5, 73.5, 94.5, 115.5, 136.5, 157.5,
  125567. };
  125568. static long _vq_quantmap__44c5_s_p9_1[] = {
  125569. 15, 13, 11, 9, 7, 5, 3, 1,
  125570. 0, 2, 4, 6, 8, 10, 12, 14,
  125571. 16,
  125572. };
  125573. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_1 = {
  125574. _vq_quantthresh__44c5_s_p9_1,
  125575. _vq_quantmap__44c5_s_p9_1,
  125576. 17,
  125577. 17
  125578. };
  125579. static static_codebook _44c5_s_p9_1 = {
  125580. 2, 289,
  125581. _vq_lengthlist__44c5_s_p9_1,
  125582. 1, -520814592, 1620377600, 5, 0,
  125583. _vq_quantlist__44c5_s_p9_1,
  125584. NULL,
  125585. &_vq_auxt__44c5_s_p9_1,
  125586. NULL,
  125587. 0
  125588. };
  125589. static long _vq_quantlist__44c5_s_p9_2[] = {
  125590. 10,
  125591. 9,
  125592. 11,
  125593. 8,
  125594. 12,
  125595. 7,
  125596. 13,
  125597. 6,
  125598. 14,
  125599. 5,
  125600. 15,
  125601. 4,
  125602. 16,
  125603. 3,
  125604. 17,
  125605. 2,
  125606. 18,
  125607. 1,
  125608. 19,
  125609. 0,
  125610. 20,
  125611. };
  125612. static long _vq_lengthlist__44c5_s_p9_2[] = {
  125613. 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  125614. 8, 8, 8, 8, 9,11, 5, 6, 7, 7, 8, 7, 8, 8, 8, 8,
  125615. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11, 5, 5, 7, 7, 7,
  125616. 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  125617. 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  125618. 9,10, 9,10,11,11,11, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  125619. 9, 9, 9,10,10,10,10,10,10,11,11,11, 8, 8, 8, 8,
  125620. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,11,11,
  125621. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,
  125622. 10,10,10,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  125623. 10,10,10,10,10,10,10,10,11,11,11,11,11, 9, 9, 9,
  125624. 9, 9, 9,10, 9,10,10,10,10,10,10,10,10,11,11,11,
  125625. 11,11, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,
  125626. 10,10,11,11,11,11,11, 9, 9, 9, 9, 9, 9,10,10,10,
  125627. 10,10,10,10,10,10,10,11,11,11,11,11, 9, 9,10, 9,
  125628. 10,10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,
  125629. 11,11,11, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  125630. 10,11,11,11,11,11,11,11,10,10,10,10,10,10,10,10,
  125631. 10,10,10,10,10,10,11,11,11,11,11,11,11,10,10,10,
  125632. 10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,
  125633. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125634. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  125635. 10,10,10,10,10,11,11,11,11,11,11,11,11,11,10,10,
  125636. 10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  125637. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,11,
  125638. 11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,10,
  125639. 10,10,10,10,11,11,11,11,11,11,11,11,11,11,11,10,
  125640. 10,10,10,10,10,10,10,10,10,
  125641. };
  125642. static float _vq_quantthresh__44c5_s_p9_2[] = {
  125643. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  125644. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  125645. 6.5, 7.5, 8.5, 9.5,
  125646. };
  125647. static long _vq_quantmap__44c5_s_p9_2[] = {
  125648. 19, 17, 15, 13, 11, 9, 7, 5,
  125649. 3, 1, 0, 2, 4, 6, 8, 10,
  125650. 12, 14, 16, 18, 20,
  125651. };
  125652. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_2 = {
  125653. _vq_quantthresh__44c5_s_p9_2,
  125654. _vq_quantmap__44c5_s_p9_2,
  125655. 21,
  125656. 21
  125657. };
  125658. static static_codebook _44c5_s_p9_2 = {
  125659. 2, 441,
  125660. _vq_lengthlist__44c5_s_p9_2,
  125661. 1, -529268736, 1611661312, 5, 0,
  125662. _vq_quantlist__44c5_s_p9_2,
  125663. NULL,
  125664. &_vq_auxt__44c5_s_p9_2,
  125665. NULL,
  125666. 0
  125667. };
  125668. static long _huff_lengthlist__44c5_s_short[] = {
  125669. 5, 8,10,14,11,11,12,16,15,17, 5, 5, 7, 9, 7, 8,
  125670. 10,13,17,17, 7, 5, 5,10, 5, 7, 8,11,13,15,10, 8,
  125671. 10, 8, 8, 8,11,15,18,18, 8, 5, 5, 8, 3, 4, 6,10,
  125672. 14,16, 9, 7, 6, 7, 4, 3, 5, 9,14,18,10, 9, 8,10,
  125673. 6, 5, 6, 9,14,18,12,12,11,12, 8, 7, 8,11,14,18,
  125674. 14,13,12,10, 7, 5, 6, 9,14,18,14,14,13,10, 6, 5,
  125675. 6, 8,11,16,
  125676. };
  125677. static static_codebook _huff_book__44c5_s_short = {
  125678. 2, 100,
  125679. _huff_lengthlist__44c5_s_short,
  125680. 0, 0, 0, 0, 0,
  125681. NULL,
  125682. NULL,
  125683. NULL,
  125684. NULL,
  125685. 0
  125686. };
  125687. static long _huff_lengthlist__44c6_s_long[] = {
  125688. 3, 8,11,13,14,14,13,13,16,14, 6, 3, 4, 7, 9, 9,
  125689. 10,11,14,13,10, 4, 3, 5, 7, 7, 9,10,13,15,12, 7,
  125690. 4, 4, 6, 6, 8,10,13,15,12, 8, 6, 6, 6, 6, 8,10,
  125691. 13,14,11, 9, 7, 6, 6, 6, 7, 8,12,11,13,10, 9, 8,
  125692. 7, 6, 6, 7,11,11,13,11,10, 9, 9, 7, 7, 6,10,11,
  125693. 13,13,13,13,13,11, 9, 8,10,12,12,15,15,16,15,12,
  125694. 11,10,10,12,
  125695. };
  125696. static static_codebook _huff_book__44c6_s_long = {
  125697. 2, 100,
  125698. _huff_lengthlist__44c6_s_long,
  125699. 0, 0, 0, 0, 0,
  125700. NULL,
  125701. NULL,
  125702. NULL,
  125703. NULL,
  125704. 0
  125705. };
  125706. static long _vq_quantlist__44c6_s_p1_0[] = {
  125707. 1,
  125708. 0,
  125709. 2,
  125710. };
  125711. static long _vq_lengthlist__44c6_s_p1_0[] = {
  125712. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 8, 7, 0, 9, 9, 0,
  125713. 9, 8, 5, 7, 8, 0, 9, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  125714. 0, 0, 0, 0, 5, 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  125715. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  125716. 9, 9, 0, 8, 8, 0, 8, 8, 5, 9, 9, 0, 8, 8, 0, 8,
  125717. 8,
  125718. };
  125719. static float _vq_quantthresh__44c6_s_p1_0[] = {
  125720. -0.5, 0.5,
  125721. };
  125722. static long _vq_quantmap__44c6_s_p1_0[] = {
  125723. 1, 0, 2,
  125724. };
  125725. static encode_aux_threshmatch _vq_auxt__44c6_s_p1_0 = {
  125726. _vq_quantthresh__44c6_s_p1_0,
  125727. _vq_quantmap__44c6_s_p1_0,
  125728. 3,
  125729. 3
  125730. };
  125731. static static_codebook _44c6_s_p1_0 = {
  125732. 4, 81,
  125733. _vq_lengthlist__44c6_s_p1_0,
  125734. 1, -535822336, 1611661312, 2, 0,
  125735. _vq_quantlist__44c6_s_p1_0,
  125736. NULL,
  125737. &_vq_auxt__44c6_s_p1_0,
  125738. NULL,
  125739. 0
  125740. };
  125741. static long _vq_quantlist__44c6_s_p2_0[] = {
  125742. 2,
  125743. 1,
  125744. 3,
  125745. 0,
  125746. 4,
  125747. };
  125748. static long _vq_lengthlist__44c6_s_p2_0[] = {
  125749. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  125750. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  125751. 8,10,10, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  125752. 11,11, 5, 7, 7, 9, 9, 0, 8, 8,10,10, 0, 7, 8, 9,
  125753. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,11,
  125754. 0,11,11,12,12, 0,11,10,12,12, 0,13,14,14,14, 0,
  125755. 0, 0,14,13, 8, 9, 9,11,11, 0,11,11,12,12, 0,10,
  125756. 11,12,12, 0,14,13,14,14, 0, 0, 0,13,14, 0, 0, 0,
  125757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125758. 0, 0, 0, 0, 0, 0, 5, 8, 7,11,10, 0, 7, 7,10,10,
  125759. 0, 7, 7,10,10, 0, 9, 9,11,10, 0, 0, 0,11,11, 5,
  125760. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  125761. 9,10,11, 0, 0, 0,11,11, 8,10, 9,12,12, 0,10,10,
  125762. 12,12, 0,10,10,12,12, 0,12,12,13,13, 0, 0, 0,13,
  125763. 13, 8, 9,10,12,12, 0,10,10,11,12, 0,10,10,12,12,
  125764. 0,12,12,13,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0,
  125765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125766. 0, 0, 0, 5, 8, 8,11,11, 0, 7, 7,10,10, 0, 7, 7,
  125767. 10,10, 0, 9, 9,10,11, 0, 0, 0,11,10, 5, 8, 8,11,
  125768. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,11,11,
  125769. 0, 0, 0,10,11, 8,10,10,12,12, 0,10,10,12,12, 0,
  125770. 10,10,12,12, 0,12,13,13,13, 0, 0, 0,14,13, 8,10,
  125771. 10,12,12, 0,10,10,12,12, 0,10,10,12,12, 0,13,12,
  125772. 13,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125774. 7,10,10,14,13, 0, 9, 9,13,12, 0, 9, 9,12,12, 0,
  125775. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,14, 0, 9,
  125776. 9,12,13, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  125777. 12,12, 9,11,11,14,13, 0,11,10,14,13, 0,11,11,13,
  125778. 13, 0,12,12,13,13, 0, 0, 0,13,13, 9,11,11,13,14,
  125779. 0,10,11,13,14, 0,11,11,13,13, 0,12,12,13,13, 0,
  125780. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  125785. 11,11,14,14, 0,11,11,13,13, 0,11,10,13,13, 0,12,
  125786. 12,13,13, 0, 0, 0,13,13, 9,11,11,14,14, 0,11,11,
  125787. 13,13, 0,10,11,13,13, 0,12,12,14,13, 0, 0, 0,13,
  125788. 13,
  125789. };
  125790. static float _vq_quantthresh__44c6_s_p2_0[] = {
  125791. -1.5, -0.5, 0.5, 1.5,
  125792. };
  125793. static long _vq_quantmap__44c6_s_p2_0[] = {
  125794. 3, 1, 0, 2, 4,
  125795. };
  125796. static encode_aux_threshmatch _vq_auxt__44c6_s_p2_0 = {
  125797. _vq_quantthresh__44c6_s_p2_0,
  125798. _vq_quantmap__44c6_s_p2_0,
  125799. 5,
  125800. 5
  125801. };
  125802. static static_codebook _44c6_s_p2_0 = {
  125803. 4, 625,
  125804. _vq_lengthlist__44c6_s_p2_0,
  125805. 1, -533725184, 1611661312, 3, 0,
  125806. _vq_quantlist__44c6_s_p2_0,
  125807. NULL,
  125808. &_vq_auxt__44c6_s_p2_0,
  125809. NULL,
  125810. 0
  125811. };
  125812. static long _vq_quantlist__44c6_s_p3_0[] = {
  125813. 4,
  125814. 3,
  125815. 5,
  125816. 2,
  125817. 6,
  125818. 1,
  125819. 7,
  125820. 0,
  125821. 8,
  125822. };
  125823. static long _vq_lengthlist__44c6_s_p3_0[] = {
  125824. 2, 3, 4, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  125825. 9,10, 0, 4, 4, 6, 6, 7, 7,10, 9, 0, 5, 5, 7, 7,
  125826. 8, 8,10,10, 0, 0, 0, 7, 6, 8, 8,10,10, 0, 0, 0,
  125827. 7, 7, 9, 9,11,11, 0, 0, 0, 7, 7, 9, 9,11,11, 0,
  125828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125829. 0,
  125830. };
  125831. static float _vq_quantthresh__44c6_s_p3_0[] = {
  125832. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  125833. };
  125834. static long _vq_quantmap__44c6_s_p3_0[] = {
  125835. 7, 5, 3, 1, 0, 2, 4, 6,
  125836. 8,
  125837. };
  125838. static encode_aux_threshmatch _vq_auxt__44c6_s_p3_0 = {
  125839. _vq_quantthresh__44c6_s_p3_0,
  125840. _vq_quantmap__44c6_s_p3_0,
  125841. 9,
  125842. 9
  125843. };
  125844. static static_codebook _44c6_s_p3_0 = {
  125845. 2, 81,
  125846. _vq_lengthlist__44c6_s_p3_0,
  125847. 1, -531628032, 1611661312, 4, 0,
  125848. _vq_quantlist__44c6_s_p3_0,
  125849. NULL,
  125850. &_vq_auxt__44c6_s_p3_0,
  125851. NULL,
  125852. 0
  125853. };
  125854. static long _vq_quantlist__44c6_s_p4_0[] = {
  125855. 8,
  125856. 7,
  125857. 9,
  125858. 6,
  125859. 10,
  125860. 5,
  125861. 11,
  125862. 4,
  125863. 12,
  125864. 3,
  125865. 13,
  125866. 2,
  125867. 14,
  125868. 1,
  125869. 15,
  125870. 0,
  125871. 16,
  125872. };
  125873. static long _vq_lengthlist__44c6_s_p4_0[] = {
  125874. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9,10,10,
  125875. 10, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,
  125876. 11,11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,
  125877. 10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  125878. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  125879. 10,11,11,11,11, 0, 0, 0, 7, 7, 9, 9,10,10,10,10,
  125880. 11,11,11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10,
  125881. 10,11,11,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  125882. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8, 8, 9,
  125883. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  125884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125892. 0,
  125893. };
  125894. static float _vq_quantthresh__44c6_s_p4_0[] = {
  125895. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  125896. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  125897. };
  125898. static long _vq_quantmap__44c6_s_p4_0[] = {
  125899. 15, 13, 11, 9, 7, 5, 3, 1,
  125900. 0, 2, 4, 6, 8, 10, 12, 14,
  125901. 16,
  125902. };
  125903. static encode_aux_threshmatch _vq_auxt__44c6_s_p4_0 = {
  125904. _vq_quantthresh__44c6_s_p4_0,
  125905. _vq_quantmap__44c6_s_p4_0,
  125906. 17,
  125907. 17
  125908. };
  125909. static static_codebook _44c6_s_p4_0 = {
  125910. 2, 289,
  125911. _vq_lengthlist__44c6_s_p4_0,
  125912. 1, -529530880, 1611661312, 5, 0,
  125913. _vq_quantlist__44c6_s_p4_0,
  125914. NULL,
  125915. &_vq_auxt__44c6_s_p4_0,
  125916. NULL,
  125917. 0
  125918. };
  125919. static long _vq_quantlist__44c6_s_p5_0[] = {
  125920. 1,
  125921. 0,
  125922. 2,
  125923. };
  125924. static long _vq_lengthlist__44c6_s_p5_0[] = {
  125925. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 6, 9, 9,10,10,
  125926. 10, 9, 4, 6, 6, 9,10, 9,10, 9,10, 6, 9, 9,10,12,
  125927. 11,10,11,11, 7,10, 9,11,12,12,12,12,12, 7,10,10,
  125928. 11,12,12,12,12,12, 6,10,10,10,12,12,11,12,12, 7,
  125929. 9,10,11,12,12,12,12,12, 7,10, 9,12,12,12,12,12,
  125930. 12,
  125931. };
  125932. static float _vq_quantthresh__44c6_s_p5_0[] = {
  125933. -5.5, 5.5,
  125934. };
  125935. static long _vq_quantmap__44c6_s_p5_0[] = {
  125936. 1, 0, 2,
  125937. };
  125938. static encode_aux_threshmatch _vq_auxt__44c6_s_p5_0 = {
  125939. _vq_quantthresh__44c6_s_p5_0,
  125940. _vq_quantmap__44c6_s_p5_0,
  125941. 3,
  125942. 3
  125943. };
  125944. static static_codebook _44c6_s_p5_0 = {
  125945. 4, 81,
  125946. _vq_lengthlist__44c6_s_p5_0,
  125947. 1, -529137664, 1618345984, 2, 0,
  125948. _vq_quantlist__44c6_s_p5_0,
  125949. NULL,
  125950. &_vq_auxt__44c6_s_p5_0,
  125951. NULL,
  125952. 0
  125953. };
  125954. static long _vq_quantlist__44c6_s_p5_1[] = {
  125955. 5,
  125956. 4,
  125957. 6,
  125958. 3,
  125959. 7,
  125960. 2,
  125961. 8,
  125962. 1,
  125963. 9,
  125964. 0,
  125965. 10,
  125966. };
  125967. static long _vq_lengthlist__44c6_s_p5_1[] = {
  125968. 3, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6,
  125969. 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6, 7, 7, 8, 8, 8,
  125970. 8,11, 6, 6, 6, 6, 8, 8, 8, 8, 9, 9,11,11,11, 6,
  125971. 6, 7, 8, 8, 8, 8, 9,11,11,11, 7, 7, 8, 8, 8, 8,
  125972. 8, 8,11,11,11, 7, 7, 8, 8, 8, 8, 8, 8,11,11,11,
  125973. 8, 8, 8, 8, 8, 8, 8, 8,11,11,11,10,10, 8, 8, 8,
  125974. 8, 8, 8,11,11,11,10,10, 8, 8, 8, 8, 8, 8,11,11,
  125975. 11,10,10, 7, 7, 8, 8, 8, 8,
  125976. };
  125977. static float _vq_quantthresh__44c6_s_p5_1[] = {
  125978. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  125979. 3.5, 4.5,
  125980. };
  125981. static long _vq_quantmap__44c6_s_p5_1[] = {
  125982. 9, 7, 5, 3, 1, 0, 2, 4,
  125983. 6, 8, 10,
  125984. };
  125985. static encode_aux_threshmatch _vq_auxt__44c6_s_p5_1 = {
  125986. _vq_quantthresh__44c6_s_p5_1,
  125987. _vq_quantmap__44c6_s_p5_1,
  125988. 11,
  125989. 11
  125990. };
  125991. static static_codebook _44c6_s_p5_1 = {
  125992. 2, 121,
  125993. _vq_lengthlist__44c6_s_p5_1,
  125994. 1, -531365888, 1611661312, 4, 0,
  125995. _vq_quantlist__44c6_s_p5_1,
  125996. NULL,
  125997. &_vq_auxt__44c6_s_p5_1,
  125998. NULL,
  125999. 0
  126000. };
  126001. static long _vq_quantlist__44c6_s_p6_0[] = {
  126002. 6,
  126003. 5,
  126004. 7,
  126005. 4,
  126006. 8,
  126007. 3,
  126008. 9,
  126009. 2,
  126010. 10,
  126011. 1,
  126012. 11,
  126013. 0,
  126014. 12,
  126015. };
  126016. static long _vq_lengthlist__44c6_s_p6_0[] = {
  126017. 1, 4, 4, 6, 6, 8, 8, 8, 8,10, 9,10,10, 6, 5, 5,
  126018. 7, 7, 9, 9, 9, 9,10,10,11,11, 6, 5, 5, 7, 7, 9,
  126019. 9,10, 9,11,10,11,11, 0, 6, 6, 7, 7, 9, 9,10,10,
  126020. 11,11,12,12, 0, 7, 7, 7, 7, 9, 9,10,10,11,11,12,
  126021. 12, 0,11,11, 8, 8,10,10,11,11,12,12,12,12, 0,11,
  126022. 12, 9, 8,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  126023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126027. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126028. };
  126029. static float _vq_quantthresh__44c6_s_p6_0[] = {
  126030. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  126031. 12.5, 17.5, 22.5, 27.5,
  126032. };
  126033. static long _vq_quantmap__44c6_s_p6_0[] = {
  126034. 11, 9, 7, 5, 3, 1, 0, 2,
  126035. 4, 6, 8, 10, 12,
  126036. };
  126037. static encode_aux_threshmatch _vq_auxt__44c6_s_p6_0 = {
  126038. _vq_quantthresh__44c6_s_p6_0,
  126039. _vq_quantmap__44c6_s_p6_0,
  126040. 13,
  126041. 13
  126042. };
  126043. static static_codebook _44c6_s_p6_0 = {
  126044. 2, 169,
  126045. _vq_lengthlist__44c6_s_p6_0,
  126046. 1, -526516224, 1616117760, 4, 0,
  126047. _vq_quantlist__44c6_s_p6_0,
  126048. NULL,
  126049. &_vq_auxt__44c6_s_p6_0,
  126050. NULL,
  126051. 0
  126052. };
  126053. static long _vq_quantlist__44c6_s_p6_1[] = {
  126054. 2,
  126055. 1,
  126056. 3,
  126057. 0,
  126058. 4,
  126059. };
  126060. static long _vq_lengthlist__44c6_s_p6_1[] = {
  126061. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  126062. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  126063. };
  126064. static float _vq_quantthresh__44c6_s_p6_1[] = {
  126065. -1.5, -0.5, 0.5, 1.5,
  126066. };
  126067. static long _vq_quantmap__44c6_s_p6_1[] = {
  126068. 3, 1, 0, 2, 4,
  126069. };
  126070. static encode_aux_threshmatch _vq_auxt__44c6_s_p6_1 = {
  126071. _vq_quantthresh__44c6_s_p6_1,
  126072. _vq_quantmap__44c6_s_p6_1,
  126073. 5,
  126074. 5
  126075. };
  126076. static static_codebook _44c6_s_p6_1 = {
  126077. 2, 25,
  126078. _vq_lengthlist__44c6_s_p6_1,
  126079. 1, -533725184, 1611661312, 3, 0,
  126080. _vq_quantlist__44c6_s_p6_1,
  126081. NULL,
  126082. &_vq_auxt__44c6_s_p6_1,
  126083. NULL,
  126084. 0
  126085. };
  126086. static long _vq_quantlist__44c6_s_p7_0[] = {
  126087. 6,
  126088. 5,
  126089. 7,
  126090. 4,
  126091. 8,
  126092. 3,
  126093. 9,
  126094. 2,
  126095. 10,
  126096. 1,
  126097. 11,
  126098. 0,
  126099. 12,
  126100. };
  126101. static long _vq_lengthlist__44c6_s_p7_0[] = {
  126102. 1, 4, 4, 6, 6, 8, 8, 8, 8,10,10,11,10, 6, 5, 5,
  126103. 7, 7, 8, 8, 9, 9,10,10,12,11, 6, 5, 5, 7, 7, 8,
  126104. 8, 9, 9,10,10,12,11,21, 7, 7, 7, 7, 9, 9,10,10,
  126105. 11,11,12,12,21, 7, 7, 7, 7, 9, 9,10,10,11,11,12,
  126106. 12,21,12,12, 9, 9,10,10,11,11,11,11,12,12,21,12,
  126107. 12, 9, 9,10,10,11,11,12,12,12,12,21,21,21,11,11,
  126108. 10,10,11,12,12,12,13,13,21,21,21,11,11,10,10,12,
  126109. 12,12,12,13,13,21,21,21,15,15,11,11,12,12,13,13,
  126110. 13,13,21,21,21,15,16,11,11,12,12,13,13,14,14,21,
  126111. 21,21,21,20,13,13,13,13,13,13,14,14,20,20,20,20,
  126112. 20,13,13,13,13,13,13,14,14,
  126113. };
  126114. static float _vq_quantthresh__44c6_s_p7_0[] = {
  126115. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  126116. 27.5, 38.5, 49.5, 60.5,
  126117. };
  126118. static long _vq_quantmap__44c6_s_p7_0[] = {
  126119. 11, 9, 7, 5, 3, 1, 0, 2,
  126120. 4, 6, 8, 10, 12,
  126121. };
  126122. static encode_aux_threshmatch _vq_auxt__44c6_s_p7_0 = {
  126123. _vq_quantthresh__44c6_s_p7_0,
  126124. _vq_quantmap__44c6_s_p7_0,
  126125. 13,
  126126. 13
  126127. };
  126128. static static_codebook _44c6_s_p7_0 = {
  126129. 2, 169,
  126130. _vq_lengthlist__44c6_s_p7_0,
  126131. 1, -523206656, 1618345984, 4, 0,
  126132. _vq_quantlist__44c6_s_p7_0,
  126133. NULL,
  126134. &_vq_auxt__44c6_s_p7_0,
  126135. NULL,
  126136. 0
  126137. };
  126138. static long _vq_quantlist__44c6_s_p7_1[] = {
  126139. 5,
  126140. 4,
  126141. 6,
  126142. 3,
  126143. 7,
  126144. 2,
  126145. 8,
  126146. 1,
  126147. 9,
  126148. 0,
  126149. 10,
  126150. };
  126151. static long _vq_lengthlist__44c6_s_p7_1[] = {
  126152. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 9, 5, 5, 6, 6,
  126153. 7, 7, 7, 7, 8, 7, 8, 5, 5, 6, 6, 7, 7, 7, 7, 7,
  126154. 7, 9, 6, 6, 7, 7, 7, 7, 8, 7, 7, 8, 9, 9, 9, 7,
  126155. 7, 7, 7, 7, 7, 7, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8,
  126156. 8, 8, 9, 9, 9, 7, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  126157. 8, 8, 8, 8, 7, 7, 8, 8, 9, 9, 9, 9, 8, 8, 8, 7,
  126158. 7, 8, 8, 9, 9, 9, 8, 8, 8, 8, 7, 7, 8, 8, 9, 9,
  126159. 9, 8, 8, 7, 7, 7, 7, 8, 8,
  126160. };
  126161. static float _vq_quantthresh__44c6_s_p7_1[] = {
  126162. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  126163. 3.5, 4.5,
  126164. };
  126165. static long _vq_quantmap__44c6_s_p7_1[] = {
  126166. 9, 7, 5, 3, 1, 0, 2, 4,
  126167. 6, 8, 10,
  126168. };
  126169. static encode_aux_threshmatch _vq_auxt__44c6_s_p7_1 = {
  126170. _vq_quantthresh__44c6_s_p7_1,
  126171. _vq_quantmap__44c6_s_p7_1,
  126172. 11,
  126173. 11
  126174. };
  126175. static static_codebook _44c6_s_p7_1 = {
  126176. 2, 121,
  126177. _vq_lengthlist__44c6_s_p7_1,
  126178. 1, -531365888, 1611661312, 4, 0,
  126179. _vq_quantlist__44c6_s_p7_1,
  126180. NULL,
  126181. &_vq_auxt__44c6_s_p7_1,
  126182. NULL,
  126183. 0
  126184. };
  126185. static long _vq_quantlist__44c6_s_p8_0[] = {
  126186. 7,
  126187. 6,
  126188. 8,
  126189. 5,
  126190. 9,
  126191. 4,
  126192. 10,
  126193. 3,
  126194. 11,
  126195. 2,
  126196. 12,
  126197. 1,
  126198. 13,
  126199. 0,
  126200. 14,
  126201. };
  126202. static long _vq_lengthlist__44c6_s_p8_0[] = {
  126203. 1, 4, 4, 7, 7, 8, 8, 7, 7, 8, 7, 9, 8,10, 9, 6,
  126204. 5, 5, 8, 8, 9, 9, 8, 8, 9, 9,11,10,11,10, 6, 5,
  126205. 5, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,11,18, 8, 8,
  126206. 9, 8,10,10, 9, 9,10,10,10,10,11,10,18, 8, 8, 9,
  126207. 9,10,10, 9, 9,10,10,11,11,12,12,18,12,13, 9,10,
  126208. 10,10, 9,10,10,10,11,11,12,11,18,13,13, 9, 9,10,
  126209. 10,10,10,10,10,11,11,12,12,18,18,18,10,10, 9, 9,
  126210. 11,11,11,11,11,12,12,12,18,18,18,10, 9,10, 9,11,
  126211. 10,11,11,11,11,13,12,18,18,18,14,13,10,10,11,11,
  126212. 12,12,12,12,12,12,18,18,18,14,13,10,10,11,10,12,
  126213. 12,12,12,12,12,18,18,18,18,18,12,12,11,11,12,12,
  126214. 13,13,13,14,18,18,18,18,18,12,12,11,11,12,11,13,
  126215. 13,14,13,18,18,18,18,18,16,16,11,12,12,13,13,13,
  126216. 14,13,18,18,18,18,18,16,15,12,11,12,11,13,11,15,
  126217. 14,
  126218. };
  126219. static float _vq_quantthresh__44c6_s_p8_0[] = {
  126220. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  126221. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  126222. };
  126223. static long _vq_quantmap__44c6_s_p8_0[] = {
  126224. 13, 11, 9, 7, 5, 3, 1, 0,
  126225. 2, 4, 6, 8, 10, 12, 14,
  126226. };
  126227. static encode_aux_threshmatch _vq_auxt__44c6_s_p8_0 = {
  126228. _vq_quantthresh__44c6_s_p8_0,
  126229. _vq_quantmap__44c6_s_p8_0,
  126230. 15,
  126231. 15
  126232. };
  126233. static static_codebook _44c6_s_p8_0 = {
  126234. 2, 225,
  126235. _vq_lengthlist__44c6_s_p8_0,
  126236. 1, -520986624, 1620377600, 4, 0,
  126237. _vq_quantlist__44c6_s_p8_0,
  126238. NULL,
  126239. &_vq_auxt__44c6_s_p8_0,
  126240. NULL,
  126241. 0
  126242. };
  126243. static long _vq_quantlist__44c6_s_p8_1[] = {
  126244. 10,
  126245. 9,
  126246. 11,
  126247. 8,
  126248. 12,
  126249. 7,
  126250. 13,
  126251. 6,
  126252. 14,
  126253. 5,
  126254. 15,
  126255. 4,
  126256. 16,
  126257. 3,
  126258. 17,
  126259. 2,
  126260. 18,
  126261. 1,
  126262. 19,
  126263. 0,
  126264. 20,
  126265. };
  126266. static long _vq_lengthlist__44c6_s_p8_1[] = {
  126267. 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 8,
  126268. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,
  126269. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  126270. 8, 8, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,10,
  126271. 7, 7, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  126272. 9, 9, 9, 9,10,11,11, 8, 7, 8, 8, 8, 9, 9, 9, 9,
  126273. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,11, 8, 8, 8, 8,
  126274. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,
  126275. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  126276. 9, 9, 9,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  126277. 9, 9, 9, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9, 9,
  126278. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,11,
  126279. 11,11, 9, 9, 9, 9, 9, 9,10, 9, 9,10, 9,10, 9, 9,
  126280. 10, 9,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,10,10,
  126281. 10,10, 9,10,10, 9,10,11,11,11,11,11, 9, 9, 9, 9,
  126282. 10,10,10, 9,10,10,10,10, 9,10,10, 9,11,11,11,11,
  126283. 11,11,11, 9, 9, 9, 9,10,10,10,10, 9,10,10,10,10,
  126284. 10,11,11,11,11,11,11,11,10, 9,10,10,10,10,10,10,
  126285. 10, 9,10, 9,10,10,11,11,11,11,11,11,11,10, 9,10,
  126286. 9,10,10, 9,10,10,10,10,10,10,10,11,11,11,11,11,
  126287. 11,11,10,10,10,10,10,10,10, 9,10,10,10,10,10, 9,
  126288. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  126289. 10,10,10,10,10,11,11,11,11,11,11,11,11,11,10,10,
  126290. 10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  126291. 11,11,11,10,10,10,10,10,10,10,10,10, 9,10,10,11,
  126292. 11,11,11,11,11,11,11,11,10,10,10, 9,10,10,10,10,
  126293. 10,10,10,10,10,11,11,11,11,11,11,11,11,10,11, 9,
  126294. 10,10,10,10,10,10,10,10,10,
  126295. };
  126296. static float _vq_quantthresh__44c6_s_p8_1[] = {
  126297. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  126298. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  126299. 6.5, 7.5, 8.5, 9.5,
  126300. };
  126301. static long _vq_quantmap__44c6_s_p8_1[] = {
  126302. 19, 17, 15, 13, 11, 9, 7, 5,
  126303. 3, 1, 0, 2, 4, 6, 8, 10,
  126304. 12, 14, 16, 18, 20,
  126305. };
  126306. static encode_aux_threshmatch _vq_auxt__44c6_s_p8_1 = {
  126307. _vq_quantthresh__44c6_s_p8_1,
  126308. _vq_quantmap__44c6_s_p8_1,
  126309. 21,
  126310. 21
  126311. };
  126312. static static_codebook _44c6_s_p8_1 = {
  126313. 2, 441,
  126314. _vq_lengthlist__44c6_s_p8_1,
  126315. 1, -529268736, 1611661312, 5, 0,
  126316. _vq_quantlist__44c6_s_p8_1,
  126317. NULL,
  126318. &_vq_auxt__44c6_s_p8_1,
  126319. NULL,
  126320. 0
  126321. };
  126322. static long _vq_quantlist__44c6_s_p9_0[] = {
  126323. 6,
  126324. 5,
  126325. 7,
  126326. 4,
  126327. 8,
  126328. 3,
  126329. 9,
  126330. 2,
  126331. 10,
  126332. 1,
  126333. 11,
  126334. 0,
  126335. 12,
  126336. };
  126337. static long _vq_lengthlist__44c6_s_p9_0[] = {
  126338. 1, 3, 3,11,11,11,11,11,11,11,11,11,11, 4, 7, 7,
  126339. 11,11,11,11,11,11,11,11,11,11, 5, 8, 9,11,11,11,
  126340. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126341. 11,11,11,11,11,10,10,10,10,10,10,10,10,10,10,10,
  126342. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  126343. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  126344. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  126345. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  126346. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  126347. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  126348. 10,10,10,10,10,10,10,10,10,
  126349. };
  126350. static float _vq_quantthresh__44c6_s_p9_0[] = {
  126351. -3503.5, -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5,
  126352. 1592.5, 2229.5, 2866.5, 3503.5,
  126353. };
  126354. static long _vq_quantmap__44c6_s_p9_0[] = {
  126355. 11, 9, 7, 5, 3, 1, 0, 2,
  126356. 4, 6, 8, 10, 12,
  126357. };
  126358. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_0 = {
  126359. _vq_quantthresh__44c6_s_p9_0,
  126360. _vq_quantmap__44c6_s_p9_0,
  126361. 13,
  126362. 13
  126363. };
  126364. static static_codebook _44c6_s_p9_0 = {
  126365. 2, 169,
  126366. _vq_lengthlist__44c6_s_p9_0,
  126367. 1, -511845376, 1630791680, 4, 0,
  126368. _vq_quantlist__44c6_s_p9_0,
  126369. NULL,
  126370. &_vq_auxt__44c6_s_p9_0,
  126371. NULL,
  126372. 0
  126373. };
  126374. static long _vq_quantlist__44c6_s_p9_1[] = {
  126375. 6,
  126376. 5,
  126377. 7,
  126378. 4,
  126379. 8,
  126380. 3,
  126381. 9,
  126382. 2,
  126383. 10,
  126384. 1,
  126385. 11,
  126386. 0,
  126387. 12,
  126388. };
  126389. static long _vq_lengthlist__44c6_s_p9_1[] = {
  126390. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8, 8, 8, 6, 6, 6,
  126391. 8, 8, 8, 8, 8, 7, 9, 8,10,10, 5, 6, 6, 8, 8, 9,
  126392. 9, 8, 8,10,10,10,10,16, 9, 9, 9, 9, 9, 9, 9, 8,
  126393. 10, 9,11,11,16, 8, 9, 9, 9, 9, 9, 9, 9,10,10,11,
  126394. 11,16,13,13, 9, 9,10, 9, 9,10,11,11,11,12,16,13,
  126395. 14, 9, 8,10, 8, 9, 9,10,10,12,11,16,14,16, 9, 9,
  126396. 9, 9,11,11,12,11,12,11,16,16,16, 9, 7, 9, 6,11,
  126397. 11,11,10,11,11,16,16,16,11,12, 9,10,11,11,12,11,
  126398. 13,13,16,16,16,12,11,10, 7,12,10,12,12,12,12,16,
  126399. 16,15,16,16,10,11,10,11,13,13,14,12,16,16,16,15,
  126400. 15,12,10,11,11,13,11,12,13,
  126401. };
  126402. static float _vq_quantthresh__44c6_s_p9_1[] = {
  126403. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  126404. 122.5, 171.5, 220.5, 269.5,
  126405. };
  126406. static long _vq_quantmap__44c6_s_p9_1[] = {
  126407. 11, 9, 7, 5, 3, 1, 0, 2,
  126408. 4, 6, 8, 10, 12,
  126409. };
  126410. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_1 = {
  126411. _vq_quantthresh__44c6_s_p9_1,
  126412. _vq_quantmap__44c6_s_p9_1,
  126413. 13,
  126414. 13
  126415. };
  126416. static static_codebook _44c6_s_p9_1 = {
  126417. 2, 169,
  126418. _vq_lengthlist__44c6_s_p9_1,
  126419. 1, -518889472, 1622704128, 4, 0,
  126420. _vq_quantlist__44c6_s_p9_1,
  126421. NULL,
  126422. &_vq_auxt__44c6_s_p9_1,
  126423. NULL,
  126424. 0
  126425. };
  126426. static long _vq_quantlist__44c6_s_p9_2[] = {
  126427. 24,
  126428. 23,
  126429. 25,
  126430. 22,
  126431. 26,
  126432. 21,
  126433. 27,
  126434. 20,
  126435. 28,
  126436. 19,
  126437. 29,
  126438. 18,
  126439. 30,
  126440. 17,
  126441. 31,
  126442. 16,
  126443. 32,
  126444. 15,
  126445. 33,
  126446. 14,
  126447. 34,
  126448. 13,
  126449. 35,
  126450. 12,
  126451. 36,
  126452. 11,
  126453. 37,
  126454. 10,
  126455. 38,
  126456. 9,
  126457. 39,
  126458. 8,
  126459. 40,
  126460. 7,
  126461. 41,
  126462. 6,
  126463. 42,
  126464. 5,
  126465. 43,
  126466. 4,
  126467. 44,
  126468. 3,
  126469. 45,
  126470. 2,
  126471. 46,
  126472. 1,
  126473. 47,
  126474. 0,
  126475. 48,
  126476. };
  126477. static long _vq_lengthlist__44c6_s_p9_2[] = {
  126478. 2, 4, 3, 4, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  126479. 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  126480. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  126481. 7,
  126482. };
  126483. static float _vq_quantthresh__44c6_s_p9_2[] = {
  126484. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  126485. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  126486. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  126487. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  126488. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  126489. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  126490. };
  126491. static long _vq_quantmap__44c6_s_p9_2[] = {
  126492. 47, 45, 43, 41, 39, 37, 35, 33,
  126493. 31, 29, 27, 25, 23, 21, 19, 17,
  126494. 15, 13, 11, 9, 7, 5, 3, 1,
  126495. 0, 2, 4, 6, 8, 10, 12, 14,
  126496. 16, 18, 20, 22, 24, 26, 28, 30,
  126497. 32, 34, 36, 38, 40, 42, 44, 46,
  126498. 48,
  126499. };
  126500. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_2 = {
  126501. _vq_quantthresh__44c6_s_p9_2,
  126502. _vq_quantmap__44c6_s_p9_2,
  126503. 49,
  126504. 49
  126505. };
  126506. static static_codebook _44c6_s_p9_2 = {
  126507. 1, 49,
  126508. _vq_lengthlist__44c6_s_p9_2,
  126509. 1, -526909440, 1611661312, 6, 0,
  126510. _vq_quantlist__44c6_s_p9_2,
  126511. NULL,
  126512. &_vq_auxt__44c6_s_p9_2,
  126513. NULL,
  126514. 0
  126515. };
  126516. static long _huff_lengthlist__44c6_s_short[] = {
  126517. 3, 9,11,11,13,14,19,17,17,19, 5, 4, 5, 8,10,10,
  126518. 13,16,18,19, 7, 4, 4, 5, 8, 9,12,14,17,19, 8, 6,
  126519. 5, 5, 7, 7,10,13,16,18,10, 8, 7, 6, 5, 5, 8,11,
  126520. 17,19,11, 9, 7, 7, 5, 4, 5, 8,17,19,13,11, 8, 7,
  126521. 7, 5, 5, 7,16,18,14,13, 8, 6, 6, 5, 5, 7,16,18,
  126522. 18,16,10, 8, 8, 7, 7, 9,16,18,18,18,12,10,10, 9,
  126523. 9,10,17,18,
  126524. };
  126525. static static_codebook _huff_book__44c6_s_short = {
  126526. 2, 100,
  126527. _huff_lengthlist__44c6_s_short,
  126528. 0, 0, 0, 0, 0,
  126529. NULL,
  126530. NULL,
  126531. NULL,
  126532. NULL,
  126533. 0
  126534. };
  126535. static long _huff_lengthlist__44c7_s_long[] = {
  126536. 3, 8,11,13,15,14,14,13,15,14, 6, 4, 5, 7, 9,10,
  126537. 11,11,14,13,10, 4, 3, 5, 7, 8, 9,10,13,13,12, 7,
  126538. 4, 4, 5, 6, 8, 9,12,14,13, 9, 6, 5, 5, 6, 8, 9,
  126539. 12,14,12, 9, 7, 6, 5, 5, 6, 8,11,11,12,11, 9, 8,
  126540. 7, 6, 6, 7,10,11,13,11,10, 9, 8, 7, 6, 6, 9,11,
  126541. 13,13,12,12,12,10, 9, 8, 9,11,12,14,15,15,14,12,
  126542. 11,10,10,12,
  126543. };
  126544. static static_codebook _huff_book__44c7_s_long = {
  126545. 2, 100,
  126546. _huff_lengthlist__44c7_s_long,
  126547. 0, 0, 0, 0, 0,
  126548. NULL,
  126549. NULL,
  126550. NULL,
  126551. NULL,
  126552. 0
  126553. };
  126554. static long _vq_quantlist__44c7_s_p1_0[] = {
  126555. 1,
  126556. 0,
  126557. 2,
  126558. };
  126559. static long _vq_lengthlist__44c7_s_p1_0[] = {
  126560. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 8, 7, 0, 9, 9, 0,
  126561. 9, 8, 5, 7, 8, 0, 9, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  126562. 0, 0, 0, 0, 5, 9, 9, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  126563. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  126564. 9, 9, 0, 8, 8, 0, 8, 8, 5, 8, 9, 0, 8, 8, 0, 8,
  126565. 8,
  126566. };
  126567. static float _vq_quantthresh__44c7_s_p1_0[] = {
  126568. -0.5, 0.5,
  126569. };
  126570. static long _vq_quantmap__44c7_s_p1_0[] = {
  126571. 1, 0, 2,
  126572. };
  126573. static encode_aux_threshmatch _vq_auxt__44c7_s_p1_0 = {
  126574. _vq_quantthresh__44c7_s_p1_0,
  126575. _vq_quantmap__44c7_s_p1_0,
  126576. 3,
  126577. 3
  126578. };
  126579. static static_codebook _44c7_s_p1_0 = {
  126580. 4, 81,
  126581. _vq_lengthlist__44c7_s_p1_0,
  126582. 1, -535822336, 1611661312, 2, 0,
  126583. _vq_quantlist__44c7_s_p1_0,
  126584. NULL,
  126585. &_vq_auxt__44c7_s_p1_0,
  126586. NULL,
  126587. 0
  126588. };
  126589. static long _vq_quantlist__44c7_s_p2_0[] = {
  126590. 2,
  126591. 1,
  126592. 3,
  126593. 0,
  126594. 4,
  126595. };
  126596. static long _vq_lengthlist__44c7_s_p2_0[] = {
  126597. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  126598. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  126599. 8,10,10, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  126600. 11,11, 5, 7, 7, 9, 9, 0, 8, 8,10,10, 0, 7, 8, 9,
  126601. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,10,
  126602. 0,11,11,12,12, 0,11,10,12,12, 0,13,14,14,14, 0,
  126603. 0, 0,14,13, 8, 9, 9,10,11, 0,11,11,12,12, 0,10,
  126604. 11,12,12, 0,13,13,14,14, 0, 0, 0,13,14, 0, 0, 0,
  126605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126606. 0, 0, 0, 0, 0, 0, 5, 8, 7,11,10, 0, 7, 7,10,10,
  126607. 0, 7, 7,10,10, 0, 9, 9,11,10, 0, 0, 0,11,11, 5,
  126608. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  126609. 9,10,11, 0, 0, 0,11,11, 8,10, 9,12,12, 0,10,10,
  126610. 12,12, 0,10,10,12,12, 0,12,12,13,13, 0, 0, 0,13,
  126611. 13, 8, 9,10,12,12, 0,10,10,12,12, 0,10,10,11,12,
  126612. 0,12,12,13,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0,
  126613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126614. 0, 0, 0, 5, 8, 8,11,11, 0, 7, 7,10,10, 0, 7, 7,
  126615. 10,10, 0, 9, 9,10,11, 0, 0, 0,11,10, 5, 8, 8,10,
  126616. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,11,10,
  126617. 0, 0, 0,10,11, 9,10,10,12,12, 0,10,10,12,12, 0,
  126618. 10,10,12,12, 0,12,13,13,13, 0, 0, 0,13,12, 9,10,
  126619. 10,12,12, 0,10,10,12,12, 0,10,10,12,12, 0,13,12,
  126620. 13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126622. 7,10,10,14,13, 0, 9, 9,12,12, 0, 9, 9,12,12, 0,
  126623. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,14, 0, 9,
  126624. 9,12,13, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  126625. 12,12, 9,11,11,14,13, 0,11,10,13,12, 0,11,11,13,
  126626. 13, 0,12,12,13,13, 0, 0, 0,13,13, 9,11,11,13,14,
  126627. 0,10,11,12,13, 0,11,11,13,13, 0,12,12,13,13, 0,
  126628. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  126633. 11,11,14,14, 0,10,11,13,13, 0,11,10,13,13, 0,12,
  126634. 12,13,13, 0, 0, 0,13,12, 9,11,11,14,14, 0,11,10,
  126635. 13,13, 0,10,11,13,13, 0,12,12,14,13, 0, 0, 0,13,
  126636. 13,
  126637. };
  126638. static float _vq_quantthresh__44c7_s_p2_0[] = {
  126639. -1.5, -0.5, 0.5, 1.5,
  126640. };
  126641. static long _vq_quantmap__44c7_s_p2_0[] = {
  126642. 3, 1, 0, 2, 4,
  126643. };
  126644. static encode_aux_threshmatch _vq_auxt__44c7_s_p2_0 = {
  126645. _vq_quantthresh__44c7_s_p2_0,
  126646. _vq_quantmap__44c7_s_p2_0,
  126647. 5,
  126648. 5
  126649. };
  126650. static static_codebook _44c7_s_p2_0 = {
  126651. 4, 625,
  126652. _vq_lengthlist__44c7_s_p2_0,
  126653. 1, -533725184, 1611661312, 3, 0,
  126654. _vq_quantlist__44c7_s_p2_0,
  126655. NULL,
  126656. &_vq_auxt__44c7_s_p2_0,
  126657. NULL,
  126658. 0
  126659. };
  126660. static long _vq_quantlist__44c7_s_p3_0[] = {
  126661. 4,
  126662. 3,
  126663. 5,
  126664. 2,
  126665. 6,
  126666. 1,
  126667. 7,
  126668. 0,
  126669. 8,
  126670. };
  126671. static long _vq_lengthlist__44c7_s_p3_0[] = {
  126672. 2, 4, 4, 5, 5, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  126673. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 6, 6,
  126674. 8, 8,10,10, 0, 0, 0, 6, 6, 8, 8,10,10, 0, 0, 0,
  126675. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0,
  126676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126677. 0,
  126678. };
  126679. static float _vq_quantthresh__44c7_s_p3_0[] = {
  126680. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  126681. };
  126682. static long _vq_quantmap__44c7_s_p3_0[] = {
  126683. 7, 5, 3, 1, 0, 2, 4, 6,
  126684. 8,
  126685. };
  126686. static encode_aux_threshmatch _vq_auxt__44c7_s_p3_0 = {
  126687. _vq_quantthresh__44c7_s_p3_0,
  126688. _vq_quantmap__44c7_s_p3_0,
  126689. 9,
  126690. 9
  126691. };
  126692. static static_codebook _44c7_s_p3_0 = {
  126693. 2, 81,
  126694. _vq_lengthlist__44c7_s_p3_0,
  126695. 1, -531628032, 1611661312, 4, 0,
  126696. _vq_quantlist__44c7_s_p3_0,
  126697. NULL,
  126698. &_vq_auxt__44c7_s_p3_0,
  126699. NULL,
  126700. 0
  126701. };
  126702. static long _vq_quantlist__44c7_s_p4_0[] = {
  126703. 8,
  126704. 7,
  126705. 9,
  126706. 6,
  126707. 10,
  126708. 5,
  126709. 11,
  126710. 4,
  126711. 12,
  126712. 3,
  126713. 13,
  126714. 2,
  126715. 14,
  126716. 1,
  126717. 15,
  126718. 0,
  126719. 16,
  126720. };
  126721. static long _vq_lengthlist__44c7_s_p4_0[] = {
  126722. 3, 4, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  126723. 11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,
  126724. 12,12, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  126725. 11,12,12, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,
  126726. 11,12,12,12, 0, 0, 0, 6, 6, 8, 7, 9, 9, 9, 9,10,
  126727. 10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,
  126728. 11,11,12,12,13,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,
  126729. 10,11,11,12,12,12,13, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  126730. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  126731. 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 0, 0,
  126732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126740. 0,
  126741. };
  126742. static float _vq_quantthresh__44c7_s_p4_0[] = {
  126743. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  126744. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  126745. };
  126746. static long _vq_quantmap__44c7_s_p4_0[] = {
  126747. 15, 13, 11, 9, 7, 5, 3, 1,
  126748. 0, 2, 4, 6, 8, 10, 12, 14,
  126749. 16,
  126750. };
  126751. static encode_aux_threshmatch _vq_auxt__44c7_s_p4_0 = {
  126752. _vq_quantthresh__44c7_s_p4_0,
  126753. _vq_quantmap__44c7_s_p4_0,
  126754. 17,
  126755. 17
  126756. };
  126757. static static_codebook _44c7_s_p4_0 = {
  126758. 2, 289,
  126759. _vq_lengthlist__44c7_s_p4_0,
  126760. 1, -529530880, 1611661312, 5, 0,
  126761. _vq_quantlist__44c7_s_p4_0,
  126762. NULL,
  126763. &_vq_auxt__44c7_s_p4_0,
  126764. NULL,
  126765. 0
  126766. };
  126767. static long _vq_quantlist__44c7_s_p5_0[] = {
  126768. 1,
  126769. 0,
  126770. 2,
  126771. };
  126772. static long _vq_lengthlist__44c7_s_p5_0[] = {
  126773. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 7,10,10,10,10,
  126774. 10, 9, 4, 6, 6,10,10,10,10, 9,10, 5,10,10, 9,11,
  126775. 12,10,11,12, 7,10,10,11,12,12,12,12,12, 7,10,10,
  126776. 11,12,12,12,12,12, 6,10,10,10,12,12,11,12,12, 7,
  126777. 10,10,12,12,12,12,11,12, 7,10,10,11,12,12,12,12,
  126778. 12,
  126779. };
  126780. static float _vq_quantthresh__44c7_s_p5_0[] = {
  126781. -5.5, 5.5,
  126782. };
  126783. static long _vq_quantmap__44c7_s_p5_0[] = {
  126784. 1, 0, 2,
  126785. };
  126786. static encode_aux_threshmatch _vq_auxt__44c7_s_p5_0 = {
  126787. _vq_quantthresh__44c7_s_p5_0,
  126788. _vq_quantmap__44c7_s_p5_0,
  126789. 3,
  126790. 3
  126791. };
  126792. static static_codebook _44c7_s_p5_0 = {
  126793. 4, 81,
  126794. _vq_lengthlist__44c7_s_p5_0,
  126795. 1, -529137664, 1618345984, 2, 0,
  126796. _vq_quantlist__44c7_s_p5_0,
  126797. NULL,
  126798. &_vq_auxt__44c7_s_p5_0,
  126799. NULL,
  126800. 0
  126801. };
  126802. static long _vq_quantlist__44c7_s_p5_1[] = {
  126803. 5,
  126804. 4,
  126805. 6,
  126806. 3,
  126807. 7,
  126808. 2,
  126809. 8,
  126810. 1,
  126811. 9,
  126812. 0,
  126813. 10,
  126814. };
  126815. static long _vq_lengthlist__44c7_s_p5_1[] = {
  126816. 3, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6,
  126817. 7, 7, 8, 8, 9, 9,11, 4, 4, 6, 6, 7, 7, 8, 8, 9,
  126818. 9,12, 5, 5, 6, 6, 7, 7, 9, 9, 9, 9,12,12,12, 6,
  126819. 6, 7, 7, 9, 9, 9, 9,11,11,11, 7, 7, 7, 7, 8, 8,
  126820. 9, 9,11,11,11, 7, 7, 7, 7, 8, 8, 9, 9,11,11,11,
  126821. 7, 7, 8, 8, 8, 8, 9, 9,11,11,11,11,11, 8, 8, 8,
  126822. 8, 8, 9,11,11,11,11,11, 8, 8, 8, 8, 8, 8,11,11,
  126823. 11,11,11, 7, 7, 8, 8, 8, 8,
  126824. };
  126825. static float _vq_quantthresh__44c7_s_p5_1[] = {
  126826. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  126827. 3.5, 4.5,
  126828. };
  126829. static long _vq_quantmap__44c7_s_p5_1[] = {
  126830. 9, 7, 5, 3, 1, 0, 2, 4,
  126831. 6, 8, 10,
  126832. };
  126833. static encode_aux_threshmatch _vq_auxt__44c7_s_p5_1 = {
  126834. _vq_quantthresh__44c7_s_p5_1,
  126835. _vq_quantmap__44c7_s_p5_1,
  126836. 11,
  126837. 11
  126838. };
  126839. static static_codebook _44c7_s_p5_1 = {
  126840. 2, 121,
  126841. _vq_lengthlist__44c7_s_p5_1,
  126842. 1, -531365888, 1611661312, 4, 0,
  126843. _vq_quantlist__44c7_s_p5_1,
  126844. NULL,
  126845. &_vq_auxt__44c7_s_p5_1,
  126846. NULL,
  126847. 0
  126848. };
  126849. static long _vq_quantlist__44c7_s_p6_0[] = {
  126850. 6,
  126851. 5,
  126852. 7,
  126853. 4,
  126854. 8,
  126855. 3,
  126856. 9,
  126857. 2,
  126858. 10,
  126859. 1,
  126860. 11,
  126861. 0,
  126862. 12,
  126863. };
  126864. static long _vq_lengthlist__44c7_s_p6_0[] = {
  126865. 1, 4, 4, 6, 6, 7, 7, 8, 7, 9, 8,10,10, 6, 5, 5,
  126866. 7, 7, 8, 8, 9, 9, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  126867. 8, 9, 9,10,10,11,11, 0, 7, 7, 7, 7, 9, 8, 9, 9,
  126868. 10,10,11,11, 0, 8, 8, 7, 7, 8, 9, 9, 9,10,10,11,
  126869. 11, 0,11,11, 9, 9,10,10,11,10,11,11,12,12, 0,12,
  126870. 12, 9, 9,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0,
  126871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126875. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126876. };
  126877. static float _vq_quantthresh__44c7_s_p6_0[] = {
  126878. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  126879. 12.5, 17.5, 22.5, 27.5,
  126880. };
  126881. static long _vq_quantmap__44c7_s_p6_0[] = {
  126882. 11, 9, 7, 5, 3, 1, 0, 2,
  126883. 4, 6, 8, 10, 12,
  126884. };
  126885. static encode_aux_threshmatch _vq_auxt__44c7_s_p6_0 = {
  126886. _vq_quantthresh__44c7_s_p6_0,
  126887. _vq_quantmap__44c7_s_p6_0,
  126888. 13,
  126889. 13
  126890. };
  126891. static static_codebook _44c7_s_p6_0 = {
  126892. 2, 169,
  126893. _vq_lengthlist__44c7_s_p6_0,
  126894. 1, -526516224, 1616117760, 4, 0,
  126895. _vq_quantlist__44c7_s_p6_0,
  126896. NULL,
  126897. &_vq_auxt__44c7_s_p6_0,
  126898. NULL,
  126899. 0
  126900. };
  126901. static long _vq_quantlist__44c7_s_p6_1[] = {
  126902. 2,
  126903. 1,
  126904. 3,
  126905. 0,
  126906. 4,
  126907. };
  126908. static long _vq_lengthlist__44c7_s_p6_1[] = {
  126909. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  126910. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  126911. };
  126912. static float _vq_quantthresh__44c7_s_p6_1[] = {
  126913. -1.5, -0.5, 0.5, 1.5,
  126914. };
  126915. static long _vq_quantmap__44c7_s_p6_1[] = {
  126916. 3, 1, 0, 2, 4,
  126917. };
  126918. static encode_aux_threshmatch _vq_auxt__44c7_s_p6_1 = {
  126919. _vq_quantthresh__44c7_s_p6_1,
  126920. _vq_quantmap__44c7_s_p6_1,
  126921. 5,
  126922. 5
  126923. };
  126924. static static_codebook _44c7_s_p6_1 = {
  126925. 2, 25,
  126926. _vq_lengthlist__44c7_s_p6_1,
  126927. 1, -533725184, 1611661312, 3, 0,
  126928. _vq_quantlist__44c7_s_p6_1,
  126929. NULL,
  126930. &_vq_auxt__44c7_s_p6_1,
  126931. NULL,
  126932. 0
  126933. };
  126934. static long _vq_quantlist__44c7_s_p7_0[] = {
  126935. 6,
  126936. 5,
  126937. 7,
  126938. 4,
  126939. 8,
  126940. 3,
  126941. 9,
  126942. 2,
  126943. 10,
  126944. 1,
  126945. 11,
  126946. 0,
  126947. 12,
  126948. };
  126949. static long _vq_lengthlist__44c7_s_p7_0[] = {
  126950. 1, 4, 4, 6, 6, 7, 8, 9, 9,10,10,12,11, 6, 5, 5,
  126951. 7, 7, 8, 8, 9,10,11,11,12,12, 7, 5, 5, 7, 7, 8,
  126952. 8,10,10,11,11,12,12,20, 7, 7, 7, 7, 8, 9,10,10,
  126953. 11,11,12,13,20, 7, 7, 7, 7, 9, 9,10,10,11,12,13,
  126954. 13,20,11,11, 8, 8, 9, 9,11,11,12,12,13,13,20,11,
  126955. 11, 8, 8, 9, 9,11,11,12,12,13,13,20,20,20,10,10,
  126956. 10,10,12,12,13,13,13,13,20,20,20,10,10,10,10,12,
  126957. 12,13,13,13,14,20,20,20,14,14,11,11,12,12,13,13,
  126958. 14,14,20,20,20,14,14,11,11,12,12,13,13,14,14,20,
  126959. 20,20,20,19,13,13,13,13,14,14,15,14,19,19,19,19,
  126960. 19,13,13,13,13,14,14,15,15,
  126961. };
  126962. static float _vq_quantthresh__44c7_s_p7_0[] = {
  126963. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  126964. 27.5, 38.5, 49.5, 60.5,
  126965. };
  126966. static long _vq_quantmap__44c7_s_p7_0[] = {
  126967. 11, 9, 7, 5, 3, 1, 0, 2,
  126968. 4, 6, 8, 10, 12,
  126969. };
  126970. static encode_aux_threshmatch _vq_auxt__44c7_s_p7_0 = {
  126971. _vq_quantthresh__44c7_s_p7_0,
  126972. _vq_quantmap__44c7_s_p7_0,
  126973. 13,
  126974. 13
  126975. };
  126976. static static_codebook _44c7_s_p7_0 = {
  126977. 2, 169,
  126978. _vq_lengthlist__44c7_s_p7_0,
  126979. 1, -523206656, 1618345984, 4, 0,
  126980. _vq_quantlist__44c7_s_p7_0,
  126981. NULL,
  126982. &_vq_auxt__44c7_s_p7_0,
  126983. NULL,
  126984. 0
  126985. };
  126986. static long _vq_quantlist__44c7_s_p7_1[] = {
  126987. 5,
  126988. 4,
  126989. 6,
  126990. 3,
  126991. 7,
  126992. 2,
  126993. 8,
  126994. 1,
  126995. 9,
  126996. 0,
  126997. 10,
  126998. };
  126999. static long _vq_lengthlist__44c7_s_p7_1[] = {
  127000. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 8, 6, 6, 7, 7,
  127001. 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  127002. 7, 8, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7,
  127003. 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  127004. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  127005. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  127006. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  127007. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  127008. };
  127009. static float _vq_quantthresh__44c7_s_p7_1[] = {
  127010. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  127011. 3.5, 4.5,
  127012. };
  127013. static long _vq_quantmap__44c7_s_p7_1[] = {
  127014. 9, 7, 5, 3, 1, 0, 2, 4,
  127015. 6, 8, 10,
  127016. };
  127017. static encode_aux_threshmatch _vq_auxt__44c7_s_p7_1 = {
  127018. _vq_quantthresh__44c7_s_p7_1,
  127019. _vq_quantmap__44c7_s_p7_1,
  127020. 11,
  127021. 11
  127022. };
  127023. static static_codebook _44c7_s_p7_1 = {
  127024. 2, 121,
  127025. _vq_lengthlist__44c7_s_p7_1,
  127026. 1, -531365888, 1611661312, 4, 0,
  127027. _vq_quantlist__44c7_s_p7_1,
  127028. NULL,
  127029. &_vq_auxt__44c7_s_p7_1,
  127030. NULL,
  127031. 0
  127032. };
  127033. static long _vq_quantlist__44c7_s_p8_0[] = {
  127034. 7,
  127035. 6,
  127036. 8,
  127037. 5,
  127038. 9,
  127039. 4,
  127040. 10,
  127041. 3,
  127042. 11,
  127043. 2,
  127044. 12,
  127045. 1,
  127046. 13,
  127047. 0,
  127048. 14,
  127049. };
  127050. static long _vq_lengthlist__44c7_s_p8_0[] = {
  127051. 1, 4, 4, 7, 7, 8, 8, 8, 7, 9, 8, 9, 9,10,10, 6,
  127052. 5, 5, 7, 7, 9, 9, 8, 8,10, 9,11,10,12,11, 6, 5,
  127053. 5, 8, 7, 9, 9, 8, 8,10,10,11,11,12,11,19, 8, 8,
  127054. 8, 8,10,10, 9, 9,10,10,11,11,12,11,19, 8, 8, 8,
  127055. 8,10,10, 9, 9,10,10,11,11,12,12,19,12,12, 9, 9,
  127056. 10,10, 9,10,10,10,11,11,12,12,19,12,12, 9, 9,10,
  127057. 10,10,10,10,10,12,12,12,12,19,19,19, 9, 9, 9, 9,
  127058. 11,10,11,11,12,11,13,13,19,19,19, 9, 9, 9, 9,11,
  127059. 10,11,11,11,12,13,13,19,19,19,13,13,10,10,11,11,
  127060. 12,12,12,12,13,12,19,19,19,14,13,10,10,11,11,12,
  127061. 12,12,13,13,13,19,19,19,19,19,12,12,12,11,12,13,
  127062. 14,13,13,13,19,19,19,19,19,12,12,12,11,12,12,13,
  127063. 14,13,14,19,19,19,19,19,16,16,12,13,12,13,13,14,
  127064. 15,14,19,18,18,18,18,16,15,12,11,12,11,14,12,14,
  127065. 14,
  127066. };
  127067. static float _vq_quantthresh__44c7_s_p8_0[] = {
  127068. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  127069. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  127070. };
  127071. static long _vq_quantmap__44c7_s_p8_0[] = {
  127072. 13, 11, 9, 7, 5, 3, 1, 0,
  127073. 2, 4, 6, 8, 10, 12, 14,
  127074. };
  127075. static encode_aux_threshmatch _vq_auxt__44c7_s_p8_0 = {
  127076. _vq_quantthresh__44c7_s_p8_0,
  127077. _vq_quantmap__44c7_s_p8_0,
  127078. 15,
  127079. 15
  127080. };
  127081. static static_codebook _44c7_s_p8_0 = {
  127082. 2, 225,
  127083. _vq_lengthlist__44c7_s_p8_0,
  127084. 1, -520986624, 1620377600, 4, 0,
  127085. _vq_quantlist__44c7_s_p8_0,
  127086. NULL,
  127087. &_vq_auxt__44c7_s_p8_0,
  127088. NULL,
  127089. 0
  127090. };
  127091. static long _vq_quantlist__44c7_s_p8_1[] = {
  127092. 10,
  127093. 9,
  127094. 11,
  127095. 8,
  127096. 12,
  127097. 7,
  127098. 13,
  127099. 6,
  127100. 14,
  127101. 5,
  127102. 15,
  127103. 4,
  127104. 16,
  127105. 3,
  127106. 17,
  127107. 2,
  127108. 18,
  127109. 1,
  127110. 19,
  127111. 0,
  127112. 20,
  127113. };
  127114. static long _vq_lengthlist__44c7_s_p8_1[] = {
  127115. 3, 5, 5, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  127116. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  127117. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  127118. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  127119. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  127120. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  127121. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 9,
  127122. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  127123. 10, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  127124. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  127125. 9, 9, 9, 9, 9, 9, 9, 9,10,11,10,10,10, 9, 9, 9,
  127126. 9, 9, 9, 9, 9, 9, 9,10, 9, 9,10, 9, 9,10,11,10,
  127127. 11,10, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,10, 9, 9,
  127128. 9, 9,11,10,11,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9,
  127129. 10, 9, 9,10, 9, 9,10,11,10,10,11,10, 9, 9, 9, 9,
  127130. 9,10,10, 9,10,10,10,10, 9,10,10,10,10,10,10,11,
  127131. 11,11,10, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,
  127132. 10,10,10,11,11,10,10,10,10,10,10,10,10,10,10,10,
  127133. 10, 9,10,10, 9,10,11,11,10,11,10,11,10, 9,10,10,
  127134. 9,10,10,10,10,10,10,10,10,10,10,11,11,11,11,10,
  127135. 11,11,10,10,10,10,10,10, 9,10, 9,10,10, 9,10, 9,
  127136. 10,10,10,11,10,11,10,11,11,10,10,10,10,10,10, 9,
  127137. 10,10,10,10,10,10,10,11,10,10,10,10,10,10,10,10,
  127138. 10,10,10,10,10,10,10,10,10,10,10,10,10,11,10,11,
  127139. 11,10,10,10,10, 9, 9,10,10, 9, 9,10, 9,10,10,10,
  127140. 10,11,11,10,10,10,10,10,10,10, 9, 9,10,10,10, 9,
  127141. 9,10,10,10,10,10,11,10,11,10,10,10,10,10,10, 9,
  127142. 10,10,10,10,10,10,10,10,10,
  127143. };
  127144. static float _vq_quantthresh__44c7_s_p8_1[] = {
  127145. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  127146. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  127147. 6.5, 7.5, 8.5, 9.5,
  127148. };
  127149. static long _vq_quantmap__44c7_s_p8_1[] = {
  127150. 19, 17, 15, 13, 11, 9, 7, 5,
  127151. 3, 1, 0, 2, 4, 6, 8, 10,
  127152. 12, 14, 16, 18, 20,
  127153. };
  127154. static encode_aux_threshmatch _vq_auxt__44c7_s_p8_1 = {
  127155. _vq_quantthresh__44c7_s_p8_1,
  127156. _vq_quantmap__44c7_s_p8_1,
  127157. 21,
  127158. 21
  127159. };
  127160. static static_codebook _44c7_s_p8_1 = {
  127161. 2, 441,
  127162. _vq_lengthlist__44c7_s_p8_1,
  127163. 1, -529268736, 1611661312, 5, 0,
  127164. _vq_quantlist__44c7_s_p8_1,
  127165. NULL,
  127166. &_vq_auxt__44c7_s_p8_1,
  127167. NULL,
  127168. 0
  127169. };
  127170. static long _vq_quantlist__44c7_s_p9_0[] = {
  127171. 6,
  127172. 5,
  127173. 7,
  127174. 4,
  127175. 8,
  127176. 3,
  127177. 9,
  127178. 2,
  127179. 10,
  127180. 1,
  127181. 11,
  127182. 0,
  127183. 12,
  127184. };
  127185. static long _vq_lengthlist__44c7_s_p9_0[] = {
  127186. 1, 3, 3,11,11,11,11,11,11,11,11,11,11, 4, 6, 6,
  127187. 11,11,11,11,11,11,11,11,11,11, 4, 7, 7,11,11,11,
  127188. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  127189. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  127190. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  127191. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  127192. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  127193. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  127194. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  127195. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  127196. 11,11,11,11,11,11,11,11,11,
  127197. };
  127198. static float _vq_quantthresh__44c7_s_p9_0[] = {
  127199. -3503.5, -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5,
  127200. 1592.5, 2229.5, 2866.5, 3503.5,
  127201. };
  127202. static long _vq_quantmap__44c7_s_p9_0[] = {
  127203. 11, 9, 7, 5, 3, 1, 0, 2,
  127204. 4, 6, 8, 10, 12,
  127205. };
  127206. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_0 = {
  127207. _vq_quantthresh__44c7_s_p9_0,
  127208. _vq_quantmap__44c7_s_p9_0,
  127209. 13,
  127210. 13
  127211. };
  127212. static static_codebook _44c7_s_p9_0 = {
  127213. 2, 169,
  127214. _vq_lengthlist__44c7_s_p9_0,
  127215. 1, -511845376, 1630791680, 4, 0,
  127216. _vq_quantlist__44c7_s_p9_0,
  127217. NULL,
  127218. &_vq_auxt__44c7_s_p9_0,
  127219. NULL,
  127220. 0
  127221. };
  127222. static long _vq_quantlist__44c7_s_p9_1[] = {
  127223. 6,
  127224. 5,
  127225. 7,
  127226. 4,
  127227. 8,
  127228. 3,
  127229. 9,
  127230. 2,
  127231. 10,
  127232. 1,
  127233. 11,
  127234. 0,
  127235. 12,
  127236. };
  127237. static long _vq_lengthlist__44c7_s_p9_1[] = {
  127238. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8, 8, 8, 6, 6, 6,
  127239. 8, 8, 9, 8, 8, 7, 9, 8,11,10, 5, 6, 6, 8, 8, 9,
  127240. 8, 8, 8,10, 9,11,11,16, 8, 8, 9, 8, 9, 9, 9, 8,
  127241. 10, 9,11,10,16, 8, 8, 9, 9,10,10, 9, 9,10,10,11,
  127242. 11,16,13,13, 9, 9,10,10, 9,10,11,11,12,11,16,13,
  127243. 13, 9, 8,10, 9,10,10,10,10,11,11,16,14,16, 8, 9,
  127244. 9, 9,11,10,11,11,12,11,16,16,16, 9, 7,10, 7,11,
  127245. 10,11,11,12,11,16,16,16,12,12, 9,10,11,11,12,11,
  127246. 12,12,16,16,16,12,10,10, 7,11, 8,12,11,12,12,16,
  127247. 16,15,16,16,11,12,10,10,12,11,12,12,16,16,16,15,
  127248. 15,11,11,10,10,12,12,12,12,
  127249. };
  127250. static float _vq_quantthresh__44c7_s_p9_1[] = {
  127251. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  127252. 122.5, 171.5, 220.5, 269.5,
  127253. };
  127254. static long _vq_quantmap__44c7_s_p9_1[] = {
  127255. 11, 9, 7, 5, 3, 1, 0, 2,
  127256. 4, 6, 8, 10, 12,
  127257. };
  127258. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_1 = {
  127259. _vq_quantthresh__44c7_s_p9_1,
  127260. _vq_quantmap__44c7_s_p9_1,
  127261. 13,
  127262. 13
  127263. };
  127264. static static_codebook _44c7_s_p9_1 = {
  127265. 2, 169,
  127266. _vq_lengthlist__44c7_s_p9_1,
  127267. 1, -518889472, 1622704128, 4, 0,
  127268. _vq_quantlist__44c7_s_p9_1,
  127269. NULL,
  127270. &_vq_auxt__44c7_s_p9_1,
  127271. NULL,
  127272. 0
  127273. };
  127274. static long _vq_quantlist__44c7_s_p9_2[] = {
  127275. 24,
  127276. 23,
  127277. 25,
  127278. 22,
  127279. 26,
  127280. 21,
  127281. 27,
  127282. 20,
  127283. 28,
  127284. 19,
  127285. 29,
  127286. 18,
  127287. 30,
  127288. 17,
  127289. 31,
  127290. 16,
  127291. 32,
  127292. 15,
  127293. 33,
  127294. 14,
  127295. 34,
  127296. 13,
  127297. 35,
  127298. 12,
  127299. 36,
  127300. 11,
  127301. 37,
  127302. 10,
  127303. 38,
  127304. 9,
  127305. 39,
  127306. 8,
  127307. 40,
  127308. 7,
  127309. 41,
  127310. 6,
  127311. 42,
  127312. 5,
  127313. 43,
  127314. 4,
  127315. 44,
  127316. 3,
  127317. 45,
  127318. 2,
  127319. 46,
  127320. 1,
  127321. 47,
  127322. 0,
  127323. 48,
  127324. };
  127325. static long _vq_lengthlist__44c7_s_p9_2[] = {
  127326. 2, 4, 3, 4, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  127327. 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  127328. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  127329. 7,
  127330. };
  127331. static float _vq_quantthresh__44c7_s_p9_2[] = {
  127332. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  127333. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  127334. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  127335. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  127336. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  127337. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  127338. };
  127339. static long _vq_quantmap__44c7_s_p9_2[] = {
  127340. 47, 45, 43, 41, 39, 37, 35, 33,
  127341. 31, 29, 27, 25, 23, 21, 19, 17,
  127342. 15, 13, 11, 9, 7, 5, 3, 1,
  127343. 0, 2, 4, 6, 8, 10, 12, 14,
  127344. 16, 18, 20, 22, 24, 26, 28, 30,
  127345. 32, 34, 36, 38, 40, 42, 44, 46,
  127346. 48,
  127347. };
  127348. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_2 = {
  127349. _vq_quantthresh__44c7_s_p9_2,
  127350. _vq_quantmap__44c7_s_p9_2,
  127351. 49,
  127352. 49
  127353. };
  127354. static static_codebook _44c7_s_p9_2 = {
  127355. 1, 49,
  127356. _vq_lengthlist__44c7_s_p9_2,
  127357. 1, -526909440, 1611661312, 6, 0,
  127358. _vq_quantlist__44c7_s_p9_2,
  127359. NULL,
  127360. &_vq_auxt__44c7_s_p9_2,
  127361. NULL,
  127362. 0
  127363. };
  127364. static long _huff_lengthlist__44c7_s_short[] = {
  127365. 4,11,12,14,15,15,17,17,18,18, 5, 6, 6, 8, 9,10,
  127366. 13,17,18,19, 7, 5, 4, 6, 8, 9,11,15,19,19, 8, 6,
  127367. 5, 5, 6, 7,11,14,16,17, 9, 7, 7, 6, 7, 7,10,13,
  127368. 15,19,10, 8, 7, 6, 7, 6, 7, 9,14,16,12,10, 9, 7,
  127369. 7, 6, 4, 5,10,15,14,13,11, 7, 6, 6, 4, 2, 7,13,
  127370. 16,16,15, 9, 8, 8, 8, 6, 9,13,19,19,17,12,11,10,
  127371. 10, 9,11,14,
  127372. };
  127373. static static_codebook _huff_book__44c7_s_short = {
  127374. 2, 100,
  127375. _huff_lengthlist__44c7_s_short,
  127376. 0, 0, 0, 0, 0,
  127377. NULL,
  127378. NULL,
  127379. NULL,
  127380. NULL,
  127381. 0
  127382. };
  127383. static long _huff_lengthlist__44c8_s_long[] = {
  127384. 3, 8,12,13,14,14,14,13,14,14, 6, 4, 5, 8,10,10,
  127385. 11,11,14,13, 9, 5, 4, 5, 7, 8, 9,10,13,13,12, 7,
  127386. 5, 4, 5, 6, 8, 9,12,13,13, 9, 6, 5, 5, 5, 7, 9,
  127387. 11,14,12,10, 7, 6, 5, 4, 6, 7,10,11,12,11, 9, 8,
  127388. 7, 5, 5, 6,10,10,13,12,10, 9, 8, 6, 6, 5, 8,10,
  127389. 14,13,12,12,11,10, 9, 7, 8,10,12,13,14,14,13,12,
  127390. 11, 9, 9,10,
  127391. };
  127392. static static_codebook _huff_book__44c8_s_long = {
  127393. 2, 100,
  127394. _huff_lengthlist__44c8_s_long,
  127395. 0, 0, 0, 0, 0,
  127396. NULL,
  127397. NULL,
  127398. NULL,
  127399. NULL,
  127400. 0
  127401. };
  127402. static long _vq_quantlist__44c8_s_p1_0[] = {
  127403. 1,
  127404. 0,
  127405. 2,
  127406. };
  127407. static long _vq_lengthlist__44c8_s_p1_0[] = {
  127408. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 7, 7, 0, 9, 8, 0,
  127409. 9, 8, 6, 7, 7, 0, 8, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  127410. 0, 0, 0, 0, 5, 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  127411. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  127412. 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9, 0, 8, 8, 0, 8,
  127413. 8,
  127414. };
  127415. static float _vq_quantthresh__44c8_s_p1_0[] = {
  127416. -0.5, 0.5,
  127417. };
  127418. static long _vq_quantmap__44c8_s_p1_0[] = {
  127419. 1, 0, 2,
  127420. };
  127421. static encode_aux_threshmatch _vq_auxt__44c8_s_p1_0 = {
  127422. _vq_quantthresh__44c8_s_p1_0,
  127423. _vq_quantmap__44c8_s_p1_0,
  127424. 3,
  127425. 3
  127426. };
  127427. static static_codebook _44c8_s_p1_0 = {
  127428. 4, 81,
  127429. _vq_lengthlist__44c8_s_p1_0,
  127430. 1, -535822336, 1611661312, 2, 0,
  127431. _vq_quantlist__44c8_s_p1_0,
  127432. NULL,
  127433. &_vq_auxt__44c8_s_p1_0,
  127434. NULL,
  127435. 0
  127436. };
  127437. static long _vq_quantlist__44c8_s_p2_0[] = {
  127438. 2,
  127439. 1,
  127440. 3,
  127441. 0,
  127442. 4,
  127443. };
  127444. static long _vq_lengthlist__44c8_s_p2_0[] = {
  127445. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  127446. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  127447. 7,10, 9, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  127448. 11,11, 5, 7, 7, 9, 9, 0, 7, 8, 9,10, 0, 7, 8, 9,
  127449. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,10,
  127450. 0,11,10,12,11, 0,11,10,12,12, 0,13,13,14,14, 0,
  127451. 0, 0,14,13, 8, 9, 9,10,11, 0,10,11,12,12, 0,10,
  127452. 11,12,12, 0,13,13,14,14, 0, 0, 0,13,14, 0, 0, 0,
  127453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127454. 0, 0, 0, 0, 0, 0, 5, 8, 7,11,10, 0, 7, 7,10,10,
  127455. 0, 7, 7,10,10, 0, 9, 9,10,10, 0, 0, 0,11,10, 5,
  127456. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  127457. 9,10,10, 0, 0, 0,10,10, 8,10, 9,12,12, 0,10,10,
  127458. 12,11, 0,10,10,12,12, 0,12,12,13,12, 0, 0, 0,13,
  127459. 12, 8, 9,10,12,12, 0,10,10,11,12, 0,10,10,11,12,
  127460. 0,12,12,13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0,
  127461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127462. 0, 0, 0, 6, 8, 7,11,10, 0, 7, 7,10,10, 0, 7, 7,
  127463. 10,10, 0, 9, 9,10,11, 0, 0, 0,10,10, 6, 7, 8,10,
  127464. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,10,10,
  127465. 0, 0, 0,10,10, 9,10, 9,12,12, 0,10,10,12,12, 0,
  127466. 10,10,12,11, 0,12,12,13,13, 0, 0, 0,13,12, 8, 9,
  127467. 10,12,12, 0,10,10,12,12, 0,10,10,11,12, 0,12,12,
  127468. 13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127470. 7,10,10,13,13, 0, 9, 9,12,12, 0, 9, 9,12,12, 0,
  127471. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,13, 0, 9,
  127472. 9,12,12, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  127473. 12,12, 9,11,11,14,13, 0,10,10,13,12, 0,11,10,13,
  127474. 12, 0,12,12,13,12, 0, 0, 0,13,13, 9,11,11,13,14,
  127475. 0,10,11,12,13, 0,10,11,13,13, 0,12,12,12,13, 0,
  127476. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  127481. 11,11,14,14, 0,10,11,13,13, 0,11,10,13,13, 0,11,
  127482. 12,13,13, 0, 0, 0,13,12, 9,11,11,14,14, 0,11,10,
  127483. 13,13, 0,10,11,13,13, 0,12,12,13,13, 0, 0, 0,12,
  127484. 13,
  127485. };
  127486. static float _vq_quantthresh__44c8_s_p2_0[] = {
  127487. -1.5, -0.5, 0.5, 1.5,
  127488. };
  127489. static long _vq_quantmap__44c8_s_p2_0[] = {
  127490. 3, 1, 0, 2, 4,
  127491. };
  127492. static encode_aux_threshmatch _vq_auxt__44c8_s_p2_0 = {
  127493. _vq_quantthresh__44c8_s_p2_0,
  127494. _vq_quantmap__44c8_s_p2_0,
  127495. 5,
  127496. 5
  127497. };
  127498. static static_codebook _44c8_s_p2_0 = {
  127499. 4, 625,
  127500. _vq_lengthlist__44c8_s_p2_0,
  127501. 1, -533725184, 1611661312, 3, 0,
  127502. _vq_quantlist__44c8_s_p2_0,
  127503. NULL,
  127504. &_vq_auxt__44c8_s_p2_0,
  127505. NULL,
  127506. 0
  127507. };
  127508. static long _vq_quantlist__44c8_s_p3_0[] = {
  127509. 4,
  127510. 3,
  127511. 5,
  127512. 2,
  127513. 6,
  127514. 1,
  127515. 7,
  127516. 0,
  127517. 8,
  127518. };
  127519. static long _vq_lengthlist__44c8_s_p3_0[] = {
  127520. 2, 4, 4, 5, 5, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  127521. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 6, 6,
  127522. 8, 8,10,10, 0, 0, 0, 6, 6, 8, 8,10,10, 0, 0, 0,
  127523. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0,
  127524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127525. 0,
  127526. };
  127527. static float _vq_quantthresh__44c8_s_p3_0[] = {
  127528. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  127529. };
  127530. static long _vq_quantmap__44c8_s_p3_0[] = {
  127531. 7, 5, 3, 1, 0, 2, 4, 6,
  127532. 8,
  127533. };
  127534. static encode_aux_threshmatch _vq_auxt__44c8_s_p3_0 = {
  127535. _vq_quantthresh__44c8_s_p3_0,
  127536. _vq_quantmap__44c8_s_p3_0,
  127537. 9,
  127538. 9
  127539. };
  127540. static static_codebook _44c8_s_p3_0 = {
  127541. 2, 81,
  127542. _vq_lengthlist__44c8_s_p3_0,
  127543. 1, -531628032, 1611661312, 4, 0,
  127544. _vq_quantlist__44c8_s_p3_0,
  127545. NULL,
  127546. &_vq_auxt__44c8_s_p3_0,
  127547. NULL,
  127548. 0
  127549. };
  127550. static long _vq_quantlist__44c8_s_p4_0[] = {
  127551. 8,
  127552. 7,
  127553. 9,
  127554. 6,
  127555. 10,
  127556. 5,
  127557. 11,
  127558. 4,
  127559. 12,
  127560. 3,
  127561. 13,
  127562. 2,
  127563. 14,
  127564. 1,
  127565. 15,
  127566. 0,
  127567. 16,
  127568. };
  127569. static long _vq_lengthlist__44c8_s_p4_0[] = {
  127570. 3, 4, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  127571. 11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 8,10,10,11,11,
  127572. 11,11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  127573. 11,11,11, 0, 6, 5, 6, 6, 7, 7, 9, 9, 9, 9,10,10,
  127574. 11,11,12,12, 0, 0, 0, 6, 6, 7, 7, 9, 9, 9, 9,10,
  127575. 10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,
  127576. 11,11,11,12,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,
  127577. 10,11,11,11,12,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  127578. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  127579. 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 0, 0,
  127580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127588. 0,
  127589. };
  127590. static float _vq_quantthresh__44c8_s_p4_0[] = {
  127591. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  127592. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  127593. };
  127594. static long _vq_quantmap__44c8_s_p4_0[] = {
  127595. 15, 13, 11, 9, 7, 5, 3, 1,
  127596. 0, 2, 4, 6, 8, 10, 12, 14,
  127597. 16,
  127598. };
  127599. static encode_aux_threshmatch _vq_auxt__44c8_s_p4_0 = {
  127600. _vq_quantthresh__44c8_s_p4_0,
  127601. _vq_quantmap__44c8_s_p4_0,
  127602. 17,
  127603. 17
  127604. };
  127605. static static_codebook _44c8_s_p4_0 = {
  127606. 2, 289,
  127607. _vq_lengthlist__44c8_s_p4_0,
  127608. 1, -529530880, 1611661312, 5, 0,
  127609. _vq_quantlist__44c8_s_p4_0,
  127610. NULL,
  127611. &_vq_auxt__44c8_s_p4_0,
  127612. NULL,
  127613. 0
  127614. };
  127615. static long _vq_quantlist__44c8_s_p5_0[] = {
  127616. 1,
  127617. 0,
  127618. 2,
  127619. };
  127620. static long _vq_lengthlist__44c8_s_p5_0[] = {
  127621. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 7, 6,10,10,10,10,
  127622. 10,10, 4, 6, 6,10,10,10,10, 9,10, 5,10,10, 9,11,
  127623. 11,10,11,11, 7,10,10,11,12,12,12,12,12, 7,10,10,
  127624. 11,12,12,12,12,12, 6,10,10,10,12,12,10,12,12, 7,
  127625. 10,10,11,12,12,12,12,12, 7,10,10,11,12,12,12,12,
  127626. 12,
  127627. };
  127628. static float _vq_quantthresh__44c8_s_p5_0[] = {
  127629. -5.5, 5.5,
  127630. };
  127631. static long _vq_quantmap__44c8_s_p5_0[] = {
  127632. 1, 0, 2,
  127633. };
  127634. static encode_aux_threshmatch _vq_auxt__44c8_s_p5_0 = {
  127635. _vq_quantthresh__44c8_s_p5_0,
  127636. _vq_quantmap__44c8_s_p5_0,
  127637. 3,
  127638. 3
  127639. };
  127640. static static_codebook _44c8_s_p5_0 = {
  127641. 4, 81,
  127642. _vq_lengthlist__44c8_s_p5_0,
  127643. 1, -529137664, 1618345984, 2, 0,
  127644. _vq_quantlist__44c8_s_p5_0,
  127645. NULL,
  127646. &_vq_auxt__44c8_s_p5_0,
  127647. NULL,
  127648. 0
  127649. };
  127650. static long _vq_quantlist__44c8_s_p5_1[] = {
  127651. 5,
  127652. 4,
  127653. 6,
  127654. 3,
  127655. 7,
  127656. 2,
  127657. 8,
  127658. 1,
  127659. 9,
  127660. 0,
  127661. 10,
  127662. };
  127663. static long _vq_lengthlist__44c8_s_p5_1[] = {
  127664. 3, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 5, 6, 6,
  127665. 7, 7, 8, 8, 8, 8,11, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  127666. 9,12, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,12,12,12, 6,
  127667. 6, 7, 7, 8, 8, 9, 9,11,11,11, 6, 6, 7, 7, 8, 8,
  127668. 8, 8,11,11,11, 6, 6, 7, 7, 8, 8, 8, 8,11,11,11,
  127669. 7, 7, 7, 8, 8, 8, 8, 8,11,11,11,11,11, 7, 7, 8,
  127670. 8, 8, 8,11,11,11,11,11, 7, 7, 7, 7, 8, 8,11,11,
  127671. 11,11,11, 7, 7, 7, 7, 8, 8,
  127672. };
  127673. static float _vq_quantthresh__44c8_s_p5_1[] = {
  127674. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  127675. 3.5, 4.5,
  127676. };
  127677. static long _vq_quantmap__44c8_s_p5_1[] = {
  127678. 9, 7, 5, 3, 1, 0, 2, 4,
  127679. 6, 8, 10,
  127680. };
  127681. static encode_aux_threshmatch _vq_auxt__44c8_s_p5_1 = {
  127682. _vq_quantthresh__44c8_s_p5_1,
  127683. _vq_quantmap__44c8_s_p5_1,
  127684. 11,
  127685. 11
  127686. };
  127687. static static_codebook _44c8_s_p5_1 = {
  127688. 2, 121,
  127689. _vq_lengthlist__44c8_s_p5_1,
  127690. 1, -531365888, 1611661312, 4, 0,
  127691. _vq_quantlist__44c8_s_p5_1,
  127692. NULL,
  127693. &_vq_auxt__44c8_s_p5_1,
  127694. NULL,
  127695. 0
  127696. };
  127697. static long _vq_quantlist__44c8_s_p6_0[] = {
  127698. 6,
  127699. 5,
  127700. 7,
  127701. 4,
  127702. 8,
  127703. 3,
  127704. 9,
  127705. 2,
  127706. 10,
  127707. 1,
  127708. 11,
  127709. 0,
  127710. 12,
  127711. };
  127712. static long _vq_lengthlist__44c8_s_p6_0[] = {
  127713. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  127714. 7, 7, 8, 8, 9, 9,10,10,11,11, 6, 5, 5, 7, 7, 8,
  127715. 8, 9, 9,10,10,11,11, 0, 7, 7, 7, 7, 9, 9,10,10,
  127716. 10,10,11,11, 0, 7, 7, 7, 7, 9, 9,10,10,10,10,11,
  127717. 11, 0,11,11, 9, 9,10,10,11,11,11,11,12,12, 0,12,
  127718. 12, 9, 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0,
  127719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127723. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127724. };
  127725. static float _vq_quantthresh__44c8_s_p6_0[] = {
  127726. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  127727. 12.5, 17.5, 22.5, 27.5,
  127728. };
  127729. static long _vq_quantmap__44c8_s_p6_0[] = {
  127730. 11, 9, 7, 5, 3, 1, 0, 2,
  127731. 4, 6, 8, 10, 12,
  127732. };
  127733. static encode_aux_threshmatch _vq_auxt__44c8_s_p6_0 = {
  127734. _vq_quantthresh__44c8_s_p6_0,
  127735. _vq_quantmap__44c8_s_p6_0,
  127736. 13,
  127737. 13
  127738. };
  127739. static static_codebook _44c8_s_p6_0 = {
  127740. 2, 169,
  127741. _vq_lengthlist__44c8_s_p6_0,
  127742. 1, -526516224, 1616117760, 4, 0,
  127743. _vq_quantlist__44c8_s_p6_0,
  127744. NULL,
  127745. &_vq_auxt__44c8_s_p6_0,
  127746. NULL,
  127747. 0
  127748. };
  127749. static long _vq_quantlist__44c8_s_p6_1[] = {
  127750. 2,
  127751. 1,
  127752. 3,
  127753. 0,
  127754. 4,
  127755. };
  127756. static long _vq_lengthlist__44c8_s_p6_1[] = {
  127757. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  127758. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  127759. };
  127760. static float _vq_quantthresh__44c8_s_p6_1[] = {
  127761. -1.5, -0.5, 0.5, 1.5,
  127762. };
  127763. static long _vq_quantmap__44c8_s_p6_1[] = {
  127764. 3, 1, 0, 2, 4,
  127765. };
  127766. static encode_aux_threshmatch _vq_auxt__44c8_s_p6_1 = {
  127767. _vq_quantthresh__44c8_s_p6_1,
  127768. _vq_quantmap__44c8_s_p6_1,
  127769. 5,
  127770. 5
  127771. };
  127772. static static_codebook _44c8_s_p6_1 = {
  127773. 2, 25,
  127774. _vq_lengthlist__44c8_s_p6_1,
  127775. 1, -533725184, 1611661312, 3, 0,
  127776. _vq_quantlist__44c8_s_p6_1,
  127777. NULL,
  127778. &_vq_auxt__44c8_s_p6_1,
  127779. NULL,
  127780. 0
  127781. };
  127782. static long _vq_quantlist__44c8_s_p7_0[] = {
  127783. 6,
  127784. 5,
  127785. 7,
  127786. 4,
  127787. 8,
  127788. 3,
  127789. 9,
  127790. 2,
  127791. 10,
  127792. 1,
  127793. 11,
  127794. 0,
  127795. 12,
  127796. };
  127797. static long _vq_lengthlist__44c8_s_p7_0[] = {
  127798. 1, 4, 4, 6, 6, 8, 7, 9, 9,10,10,12,12, 6, 5, 5,
  127799. 7, 7, 8, 8,10,10,11,11,12,12, 7, 5, 5, 7, 7, 8,
  127800. 8,10,10,11,11,12,12,21, 7, 7, 7, 7, 8, 9,10,10,
  127801. 11,11,12,12,21, 7, 7, 7, 7, 9, 9,10,10,12,12,13,
  127802. 13,21,11,11, 8, 8, 9, 9,11,11,12,12,13,13,21,11,
  127803. 11, 8, 8, 9, 9,11,11,12,12,13,13,21,21,21,10,10,
  127804. 10,10,11,11,12,13,13,13,21,21,21,10,10,10,10,11,
  127805. 11,13,13,14,13,21,21,21,13,13,11,11,12,12,13,13,
  127806. 14,14,21,21,21,14,14,11,11,12,12,13,13,14,14,21,
  127807. 21,21,21,20,13,13,13,12,14,14,16,15,20,20,20,20,
  127808. 20,13,13,13,13,14,13,15,15,
  127809. };
  127810. static float _vq_quantthresh__44c8_s_p7_0[] = {
  127811. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  127812. 27.5, 38.5, 49.5, 60.5,
  127813. };
  127814. static long _vq_quantmap__44c8_s_p7_0[] = {
  127815. 11, 9, 7, 5, 3, 1, 0, 2,
  127816. 4, 6, 8, 10, 12,
  127817. };
  127818. static encode_aux_threshmatch _vq_auxt__44c8_s_p7_0 = {
  127819. _vq_quantthresh__44c8_s_p7_0,
  127820. _vq_quantmap__44c8_s_p7_0,
  127821. 13,
  127822. 13
  127823. };
  127824. static static_codebook _44c8_s_p7_0 = {
  127825. 2, 169,
  127826. _vq_lengthlist__44c8_s_p7_0,
  127827. 1, -523206656, 1618345984, 4, 0,
  127828. _vq_quantlist__44c8_s_p7_0,
  127829. NULL,
  127830. &_vq_auxt__44c8_s_p7_0,
  127831. NULL,
  127832. 0
  127833. };
  127834. static long _vq_quantlist__44c8_s_p7_1[] = {
  127835. 5,
  127836. 4,
  127837. 6,
  127838. 3,
  127839. 7,
  127840. 2,
  127841. 8,
  127842. 1,
  127843. 9,
  127844. 0,
  127845. 10,
  127846. };
  127847. static long _vq_lengthlist__44c8_s_p7_1[] = {
  127848. 4, 5, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 7,
  127849. 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  127850. 7, 8, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7,
  127851. 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  127852. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  127853. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  127854. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  127855. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  127856. };
  127857. static float _vq_quantthresh__44c8_s_p7_1[] = {
  127858. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  127859. 3.5, 4.5,
  127860. };
  127861. static long _vq_quantmap__44c8_s_p7_1[] = {
  127862. 9, 7, 5, 3, 1, 0, 2, 4,
  127863. 6, 8, 10,
  127864. };
  127865. static encode_aux_threshmatch _vq_auxt__44c8_s_p7_1 = {
  127866. _vq_quantthresh__44c8_s_p7_1,
  127867. _vq_quantmap__44c8_s_p7_1,
  127868. 11,
  127869. 11
  127870. };
  127871. static static_codebook _44c8_s_p7_1 = {
  127872. 2, 121,
  127873. _vq_lengthlist__44c8_s_p7_1,
  127874. 1, -531365888, 1611661312, 4, 0,
  127875. _vq_quantlist__44c8_s_p7_1,
  127876. NULL,
  127877. &_vq_auxt__44c8_s_p7_1,
  127878. NULL,
  127879. 0
  127880. };
  127881. static long _vq_quantlist__44c8_s_p8_0[] = {
  127882. 7,
  127883. 6,
  127884. 8,
  127885. 5,
  127886. 9,
  127887. 4,
  127888. 10,
  127889. 3,
  127890. 11,
  127891. 2,
  127892. 12,
  127893. 1,
  127894. 13,
  127895. 0,
  127896. 14,
  127897. };
  127898. static long _vq_lengthlist__44c8_s_p8_0[] = {
  127899. 1, 4, 4, 7, 6, 8, 8, 8, 7, 9, 8,10,10,11,10, 6,
  127900. 5, 5, 7, 7, 9, 9, 8, 8,10,10,11,11,12,11, 6, 5,
  127901. 5, 7, 7, 9, 9, 9, 9,10,10,11,11,12,12,20, 8, 8,
  127902. 8, 8, 9, 9, 9, 9,10,10,11,11,12,12,20, 8, 8, 8,
  127903. 8,10, 9, 9, 9,10,10,11,11,12,12,20,12,12, 9, 9,
  127904. 10,10,10,10,10,11,12,12,12,12,20,12,12, 9, 9,10,
  127905. 10,10,10,11,11,12,12,13,13,20,20,20, 9, 9, 9, 9,
  127906. 11,10,11,11,12,12,12,13,20,19,19, 9, 9, 9, 9,11,
  127907. 11,11,12,12,12,13,13,19,19,19,13,13,10,10,11,11,
  127908. 12,12,13,13,13,13,19,19,19,14,13,11,10,11,11,12,
  127909. 12,12,13,13,13,19,19,19,19,19,12,12,12,12,13,13,
  127910. 13,13,14,13,19,19,19,19,19,12,12,12,11,12,12,13,
  127911. 14,14,14,19,19,19,19,19,16,15,13,12,13,13,13,14,
  127912. 14,14,19,19,19,19,19,17,17,13,12,13,11,14,13,15,
  127913. 15,
  127914. };
  127915. static float _vq_quantthresh__44c8_s_p8_0[] = {
  127916. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  127917. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  127918. };
  127919. static long _vq_quantmap__44c8_s_p8_0[] = {
  127920. 13, 11, 9, 7, 5, 3, 1, 0,
  127921. 2, 4, 6, 8, 10, 12, 14,
  127922. };
  127923. static encode_aux_threshmatch _vq_auxt__44c8_s_p8_0 = {
  127924. _vq_quantthresh__44c8_s_p8_0,
  127925. _vq_quantmap__44c8_s_p8_0,
  127926. 15,
  127927. 15
  127928. };
  127929. static static_codebook _44c8_s_p8_0 = {
  127930. 2, 225,
  127931. _vq_lengthlist__44c8_s_p8_0,
  127932. 1, -520986624, 1620377600, 4, 0,
  127933. _vq_quantlist__44c8_s_p8_0,
  127934. NULL,
  127935. &_vq_auxt__44c8_s_p8_0,
  127936. NULL,
  127937. 0
  127938. };
  127939. static long _vq_quantlist__44c8_s_p8_1[] = {
  127940. 10,
  127941. 9,
  127942. 11,
  127943. 8,
  127944. 12,
  127945. 7,
  127946. 13,
  127947. 6,
  127948. 14,
  127949. 5,
  127950. 15,
  127951. 4,
  127952. 16,
  127953. 3,
  127954. 17,
  127955. 2,
  127956. 18,
  127957. 1,
  127958. 19,
  127959. 0,
  127960. 20,
  127961. };
  127962. static long _vq_lengthlist__44c8_s_p8_1[] = {
  127963. 4, 5, 5, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  127964. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  127965. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  127966. 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  127967. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  127968. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  127969. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 9,
  127970. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  127971. 10, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  127972. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  127973. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  127974. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  127975. 10,10, 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9, 9, 9,
  127976. 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  127977. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9,
  127978. 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,10,10,10,10,
  127979. 10,10,10, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  127980. 9,10,10,10,10,10,10,10, 9,10,10, 9,10,10,10,10,
  127981. 9,10, 9,10,10, 9,10,10,10,10,10,10,10, 9,10,10,
  127982. 10,10,10,10, 9, 9,10,10, 9,10,10,10,10,10,10,10,
  127983. 10,10,10,10,10,10,10,10, 9, 9, 9,10, 9, 9, 9, 9,
  127984. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  127985. 10, 9,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  127986. 10,10,10,10, 9, 9,10, 9, 9, 9,10,10,10,10,10,10,
  127987. 10,10,10,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9,10,10,
  127988. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9,10, 9,
  127989. 9,10, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  127990. 10, 9, 9,10,10, 9,10, 9, 9,
  127991. };
  127992. static float _vq_quantthresh__44c8_s_p8_1[] = {
  127993. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  127994. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  127995. 6.5, 7.5, 8.5, 9.5,
  127996. };
  127997. static long _vq_quantmap__44c8_s_p8_1[] = {
  127998. 19, 17, 15, 13, 11, 9, 7, 5,
  127999. 3, 1, 0, 2, 4, 6, 8, 10,
  128000. 12, 14, 16, 18, 20,
  128001. };
  128002. static encode_aux_threshmatch _vq_auxt__44c8_s_p8_1 = {
  128003. _vq_quantthresh__44c8_s_p8_1,
  128004. _vq_quantmap__44c8_s_p8_1,
  128005. 21,
  128006. 21
  128007. };
  128008. static static_codebook _44c8_s_p8_1 = {
  128009. 2, 441,
  128010. _vq_lengthlist__44c8_s_p8_1,
  128011. 1, -529268736, 1611661312, 5, 0,
  128012. _vq_quantlist__44c8_s_p8_1,
  128013. NULL,
  128014. &_vq_auxt__44c8_s_p8_1,
  128015. NULL,
  128016. 0
  128017. };
  128018. static long _vq_quantlist__44c8_s_p9_0[] = {
  128019. 8,
  128020. 7,
  128021. 9,
  128022. 6,
  128023. 10,
  128024. 5,
  128025. 11,
  128026. 4,
  128027. 12,
  128028. 3,
  128029. 13,
  128030. 2,
  128031. 14,
  128032. 1,
  128033. 15,
  128034. 0,
  128035. 16,
  128036. };
  128037. static long _vq_lengthlist__44c8_s_p9_0[] = {
  128038. 1, 4, 3,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128039. 11, 4, 7, 7,11,11,11,11,11,11,11,11,11,11,11,11,
  128040. 11,11, 4, 8,11,11,11,11,11,11,11,11,11,11,11,11,
  128041. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128042. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128043. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128044. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128045. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128046. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128047. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128048. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128049. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128050. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128051. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128052. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  128053. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  128054. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  128055. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  128056. 10,
  128057. };
  128058. static float _vq_quantthresh__44c8_s_p9_0[] = {
  128059. -6982.5, -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5,
  128060. 465.5, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5, 6982.5,
  128061. };
  128062. static long _vq_quantmap__44c8_s_p9_0[] = {
  128063. 15, 13, 11, 9, 7, 5, 3, 1,
  128064. 0, 2, 4, 6, 8, 10, 12, 14,
  128065. 16,
  128066. };
  128067. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_0 = {
  128068. _vq_quantthresh__44c8_s_p9_0,
  128069. _vq_quantmap__44c8_s_p9_0,
  128070. 17,
  128071. 17
  128072. };
  128073. static static_codebook _44c8_s_p9_0 = {
  128074. 2, 289,
  128075. _vq_lengthlist__44c8_s_p9_0,
  128076. 1, -509798400, 1631393792, 5, 0,
  128077. _vq_quantlist__44c8_s_p9_0,
  128078. NULL,
  128079. &_vq_auxt__44c8_s_p9_0,
  128080. NULL,
  128081. 0
  128082. };
  128083. static long _vq_quantlist__44c8_s_p9_1[] = {
  128084. 9,
  128085. 8,
  128086. 10,
  128087. 7,
  128088. 11,
  128089. 6,
  128090. 12,
  128091. 5,
  128092. 13,
  128093. 4,
  128094. 14,
  128095. 3,
  128096. 15,
  128097. 2,
  128098. 16,
  128099. 1,
  128100. 17,
  128101. 0,
  128102. 18,
  128103. };
  128104. static long _vq_lengthlist__44c8_s_p9_1[] = {
  128105. 1, 4, 4, 7, 6, 7, 7, 7, 7, 8, 8, 9, 9,10,10,10,
  128106. 10,11,11, 6, 6, 6, 8, 8, 9, 8, 8, 7,10, 8,11,10,
  128107. 12,11,12,12,13,13, 5, 5, 6, 8, 8, 9, 9, 8, 8,10,
  128108. 9,11,11,12,12,13,13,13,13,17, 8, 8, 9, 9, 9, 9,
  128109. 9, 9,10, 9,12,10,12,12,13,12,13,13,17, 9, 8, 9,
  128110. 9, 9, 9, 9, 9,10,10,12,12,12,12,13,13,13,13,17,
  128111. 13,13, 9, 9,10,10,10,10,11,11,12,11,13,12,13,13,
  128112. 14,15,17,13,13, 9, 8,10, 9,10,10,11,11,12,12,14,
  128113. 13,15,13,14,15,17,17,17, 9,10, 9,10,11,11,12,12,
  128114. 12,12,13,13,14,14,15,15,17,17,17, 9, 8, 9, 8,11,
  128115. 11,12,12,12,12,14,13,14,14,14,15,17,17,17,12,14,
  128116. 9,10,11,11,12,12,14,13,13,14,15,13,15,15,17,17,
  128117. 17,13,11,10, 8,11, 9,13,12,13,13,13,13,13,14,14,
  128118. 14,17,17,17,17,17,11,12,11,11,13,13,14,13,15,14,
  128119. 13,15,16,15,17,17,17,17,17,11,11,12, 8,13,12,14,
  128120. 13,17,14,15,14,15,14,17,17,17,17,17,15,15,12,12,
  128121. 12,12,13,14,14,14,15,14,17,14,17,17,17,17,17,16,
  128122. 17,12,12,13,12,13,13,14,14,14,14,14,14,17,17,17,
  128123. 17,17,17,17,14,14,13,12,13,13,15,15,14,13,15,17,
  128124. 17,17,17,17,17,17,17,13,14,13,13,13,13,14,15,15,
  128125. 15,14,15,17,17,17,17,17,17,17,16,15,13,14,13,13,
  128126. 14,14,15,14,14,16,17,17,17,17,17,17,17,16,16,13,
  128127. 14,13,13,14,14,15,14,15,14,
  128128. };
  128129. static float _vq_quantthresh__44c8_s_p9_1[] = {
  128130. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  128131. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  128132. 367.5, 416.5,
  128133. };
  128134. static long _vq_quantmap__44c8_s_p9_1[] = {
  128135. 17, 15, 13, 11, 9, 7, 5, 3,
  128136. 1, 0, 2, 4, 6, 8, 10, 12,
  128137. 14, 16, 18,
  128138. };
  128139. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_1 = {
  128140. _vq_quantthresh__44c8_s_p9_1,
  128141. _vq_quantmap__44c8_s_p9_1,
  128142. 19,
  128143. 19
  128144. };
  128145. static static_codebook _44c8_s_p9_1 = {
  128146. 2, 361,
  128147. _vq_lengthlist__44c8_s_p9_1,
  128148. 1, -518287360, 1622704128, 5, 0,
  128149. _vq_quantlist__44c8_s_p9_1,
  128150. NULL,
  128151. &_vq_auxt__44c8_s_p9_1,
  128152. NULL,
  128153. 0
  128154. };
  128155. static long _vq_quantlist__44c8_s_p9_2[] = {
  128156. 24,
  128157. 23,
  128158. 25,
  128159. 22,
  128160. 26,
  128161. 21,
  128162. 27,
  128163. 20,
  128164. 28,
  128165. 19,
  128166. 29,
  128167. 18,
  128168. 30,
  128169. 17,
  128170. 31,
  128171. 16,
  128172. 32,
  128173. 15,
  128174. 33,
  128175. 14,
  128176. 34,
  128177. 13,
  128178. 35,
  128179. 12,
  128180. 36,
  128181. 11,
  128182. 37,
  128183. 10,
  128184. 38,
  128185. 9,
  128186. 39,
  128187. 8,
  128188. 40,
  128189. 7,
  128190. 41,
  128191. 6,
  128192. 42,
  128193. 5,
  128194. 43,
  128195. 4,
  128196. 44,
  128197. 3,
  128198. 45,
  128199. 2,
  128200. 46,
  128201. 1,
  128202. 47,
  128203. 0,
  128204. 48,
  128205. };
  128206. static long _vq_lengthlist__44c8_s_p9_2[] = {
  128207. 2, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  128208. 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  128209. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  128210. 7,
  128211. };
  128212. static float _vq_quantthresh__44c8_s_p9_2[] = {
  128213. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  128214. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  128215. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  128216. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  128217. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  128218. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  128219. };
  128220. static long _vq_quantmap__44c8_s_p9_2[] = {
  128221. 47, 45, 43, 41, 39, 37, 35, 33,
  128222. 31, 29, 27, 25, 23, 21, 19, 17,
  128223. 15, 13, 11, 9, 7, 5, 3, 1,
  128224. 0, 2, 4, 6, 8, 10, 12, 14,
  128225. 16, 18, 20, 22, 24, 26, 28, 30,
  128226. 32, 34, 36, 38, 40, 42, 44, 46,
  128227. 48,
  128228. };
  128229. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_2 = {
  128230. _vq_quantthresh__44c8_s_p9_2,
  128231. _vq_quantmap__44c8_s_p9_2,
  128232. 49,
  128233. 49
  128234. };
  128235. static static_codebook _44c8_s_p9_2 = {
  128236. 1, 49,
  128237. _vq_lengthlist__44c8_s_p9_2,
  128238. 1, -526909440, 1611661312, 6, 0,
  128239. _vq_quantlist__44c8_s_p9_2,
  128240. NULL,
  128241. &_vq_auxt__44c8_s_p9_2,
  128242. NULL,
  128243. 0
  128244. };
  128245. static long _huff_lengthlist__44c8_s_short[] = {
  128246. 4,11,13,14,15,15,18,17,19,17, 5, 6, 8, 9,10,10,
  128247. 12,15,19,19, 6, 6, 6, 6, 8, 8,11,14,18,19, 8, 6,
  128248. 5, 4, 6, 7,10,13,16,17, 9, 7, 6, 5, 6, 7, 9,12,
  128249. 15,19,10, 8, 7, 6, 6, 6, 7, 9,13,15,12,10, 9, 8,
  128250. 7, 6, 4, 5,10,15,13,13,11, 8, 6, 6, 4, 2, 7,12,
  128251. 17,15,16,10, 8, 8, 7, 6, 9,12,19,18,17,13,11,10,
  128252. 10, 9,11,14,
  128253. };
  128254. static static_codebook _huff_book__44c8_s_short = {
  128255. 2, 100,
  128256. _huff_lengthlist__44c8_s_short,
  128257. 0, 0, 0, 0, 0,
  128258. NULL,
  128259. NULL,
  128260. NULL,
  128261. NULL,
  128262. 0
  128263. };
  128264. static long _huff_lengthlist__44c9_s_long[] = {
  128265. 3, 8,12,14,15,15,15,13,15,15, 6, 5, 8,10,12,12,
  128266. 13,12,14,13,10, 6, 5, 6, 8, 9,11,11,13,13,13, 8,
  128267. 5, 4, 5, 6, 8,10,11,13,14,10, 7, 5, 4, 5, 7, 9,
  128268. 11,12,13,11, 8, 6, 5, 4, 5, 7, 9,11,12,11,10, 8,
  128269. 7, 5, 4, 5, 9,10,13,13,11,10, 8, 6, 5, 4, 7, 9,
  128270. 15,14,13,12,10, 9, 8, 7, 8, 9,12,12,14,13,12,11,
  128271. 10, 9, 8, 9,
  128272. };
  128273. static static_codebook _huff_book__44c9_s_long = {
  128274. 2, 100,
  128275. _huff_lengthlist__44c9_s_long,
  128276. 0, 0, 0, 0, 0,
  128277. NULL,
  128278. NULL,
  128279. NULL,
  128280. NULL,
  128281. 0
  128282. };
  128283. static long _vq_quantlist__44c9_s_p1_0[] = {
  128284. 1,
  128285. 0,
  128286. 2,
  128287. };
  128288. static long _vq_lengthlist__44c9_s_p1_0[] = {
  128289. 1, 5, 5, 0, 5, 5, 0, 5, 5, 6, 8, 8, 0, 9, 8, 0,
  128290. 9, 8, 6, 8, 8, 0, 8, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  128291. 0, 0, 0, 0, 5, 8, 8, 0, 7, 7, 0, 8, 8, 5, 8, 8,
  128292. 0, 7, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  128293. 9, 8, 0, 8, 8, 0, 7, 7, 5, 8, 9, 0, 8, 8, 0, 7,
  128294. 7,
  128295. };
  128296. static float _vq_quantthresh__44c9_s_p1_0[] = {
  128297. -0.5, 0.5,
  128298. };
  128299. static long _vq_quantmap__44c9_s_p1_0[] = {
  128300. 1, 0, 2,
  128301. };
  128302. static encode_aux_threshmatch _vq_auxt__44c9_s_p1_0 = {
  128303. _vq_quantthresh__44c9_s_p1_0,
  128304. _vq_quantmap__44c9_s_p1_0,
  128305. 3,
  128306. 3
  128307. };
  128308. static static_codebook _44c9_s_p1_0 = {
  128309. 4, 81,
  128310. _vq_lengthlist__44c9_s_p1_0,
  128311. 1, -535822336, 1611661312, 2, 0,
  128312. _vq_quantlist__44c9_s_p1_0,
  128313. NULL,
  128314. &_vq_auxt__44c9_s_p1_0,
  128315. NULL,
  128316. 0
  128317. };
  128318. static long _vq_quantlist__44c9_s_p2_0[] = {
  128319. 2,
  128320. 1,
  128321. 3,
  128322. 0,
  128323. 4,
  128324. };
  128325. static long _vq_lengthlist__44c9_s_p2_0[] = {
  128326. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  128327. 7, 7, 9, 9, 0, 0, 0, 9, 9, 6, 7, 7, 9, 8, 0, 8,
  128328. 8, 9, 9, 0, 8, 7, 9, 9, 0, 9,10,10,10, 0, 0, 0,
  128329. 11,10, 6, 7, 7, 8, 9, 0, 8, 8, 9, 9, 0, 7, 8, 9,
  128330. 9, 0,10, 9,11,10, 0, 0, 0,10,10, 8, 9, 8,10,10,
  128331. 0,10,10,12,11, 0,10,10,11,11, 0,12,13,13,13, 0,
  128332. 0, 0,13,12, 8, 8, 9,10,10, 0,10,10,11,12, 0,10,
  128333. 10,11,11, 0,13,12,13,13, 0, 0, 0,13,13, 0, 0, 0,
  128334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128335. 0, 0, 0, 0, 0, 0, 6, 8, 7,10,10, 0, 7, 7,10, 9,
  128336. 0, 7, 7,10,10, 0, 9, 9,10,10, 0, 0, 0,10,10, 6,
  128337. 7, 8,10,10, 0, 7, 7, 9,10, 0, 7, 7,10,10, 0, 9,
  128338. 9,10,10, 0, 0, 0,10,10, 8, 9, 9,11,11, 0,10,10,
  128339. 11,11, 0,10,10,11,11, 0,12,12,12,12, 0, 0, 0,12,
  128340. 12, 8, 9,10,11,11, 0, 9,10,11,11, 0,10,10,11,11,
  128341. 0,12,12,12,12, 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0,
  128342. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128343. 0, 0, 0, 5, 8, 7,10,10, 0, 7, 7,10,10, 0, 7, 7,
  128344. 10, 9, 0, 9, 9,10,10, 0, 0, 0,10,10, 6, 7, 8,10,
  128345. 10, 0, 7, 7,10,10, 0, 7, 7, 9,10, 0, 9, 9,10,10,
  128346. 0, 0, 0,10,10, 8,10, 9,12,11, 0,10,10,12,11, 0,
  128347. 10, 9,11,11, 0,11,12,12,12, 0, 0, 0,12,12, 8, 9,
  128348. 10,11,12, 0,10,10,11,11, 0, 9,10,11,11, 0,12,11,
  128349. 12,12, 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128351. 7,10, 9,12,12, 0, 9, 9,12,11, 0, 9, 9,11,11, 0,
  128352. 10,10,12,11, 0, 0, 0,11,12, 7, 9,10,12,12, 0, 9,
  128353. 9,11,12, 0, 9, 9,11,11, 0,10,10,11,12, 0, 0, 0,
  128354. 11,11, 9,11,10,13,12, 0,10,10,12,12, 0,10,10,12,
  128355. 12, 0,11,11,12,12, 0, 0, 0,13,12, 9,10,11,12,13,
  128356. 0,10,10,12,12, 0,10,10,12,12, 0,11,12,12,12, 0,
  128357. 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  128362. 11,10,13,13, 0,10,10,12,12, 0,10,10,12,12, 0,11,
  128363. 12,12,12, 0, 0, 0,12,12, 9,10,11,13,13, 0,10,10,
  128364. 12,12, 0,10,10,12,12, 0,12,11,13,12, 0, 0, 0,12,
  128365. 12,
  128366. };
  128367. static float _vq_quantthresh__44c9_s_p2_0[] = {
  128368. -1.5, -0.5, 0.5, 1.5,
  128369. };
  128370. static long _vq_quantmap__44c9_s_p2_0[] = {
  128371. 3, 1, 0, 2, 4,
  128372. };
  128373. static encode_aux_threshmatch _vq_auxt__44c9_s_p2_0 = {
  128374. _vq_quantthresh__44c9_s_p2_0,
  128375. _vq_quantmap__44c9_s_p2_0,
  128376. 5,
  128377. 5
  128378. };
  128379. static static_codebook _44c9_s_p2_0 = {
  128380. 4, 625,
  128381. _vq_lengthlist__44c9_s_p2_0,
  128382. 1, -533725184, 1611661312, 3, 0,
  128383. _vq_quantlist__44c9_s_p2_0,
  128384. NULL,
  128385. &_vq_auxt__44c9_s_p2_0,
  128386. NULL,
  128387. 0
  128388. };
  128389. static long _vq_quantlist__44c9_s_p3_0[] = {
  128390. 4,
  128391. 3,
  128392. 5,
  128393. 2,
  128394. 6,
  128395. 1,
  128396. 7,
  128397. 0,
  128398. 8,
  128399. };
  128400. static long _vq_lengthlist__44c9_s_p3_0[] = {
  128401. 3, 4, 4, 5, 5, 6, 6, 8, 8, 0, 4, 4, 5, 5, 6, 7,
  128402. 8, 8, 0, 4, 4, 5, 5, 7, 7, 8, 8, 0, 5, 5, 6, 6,
  128403. 7, 7, 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0,
  128404. 7, 7, 8, 8, 9, 9, 0, 0, 0, 7, 7, 8, 8, 9, 9, 0,
  128405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128406. 0,
  128407. };
  128408. static float _vq_quantthresh__44c9_s_p3_0[] = {
  128409. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  128410. };
  128411. static long _vq_quantmap__44c9_s_p3_0[] = {
  128412. 7, 5, 3, 1, 0, 2, 4, 6,
  128413. 8,
  128414. };
  128415. static encode_aux_threshmatch _vq_auxt__44c9_s_p3_0 = {
  128416. _vq_quantthresh__44c9_s_p3_0,
  128417. _vq_quantmap__44c9_s_p3_0,
  128418. 9,
  128419. 9
  128420. };
  128421. static static_codebook _44c9_s_p3_0 = {
  128422. 2, 81,
  128423. _vq_lengthlist__44c9_s_p3_0,
  128424. 1, -531628032, 1611661312, 4, 0,
  128425. _vq_quantlist__44c9_s_p3_0,
  128426. NULL,
  128427. &_vq_auxt__44c9_s_p3_0,
  128428. NULL,
  128429. 0
  128430. };
  128431. static long _vq_quantlist__44c9_s_p4_0[] = {
  128432. 8,
  128433. 7,
  128434. 9,
  128435. 6,
  128436. 10,
  128437. 5,
  128438. 11,
  128439. 4,
  128440. 12,
  128441. 3,
  128442. 13,
  128443. 2,
  128444. 14,
  128445. 1,
  128446. 15,
  128447. 0,
  128448. 16,
  128449. };
  128450. static long _vq_lengthlist__44c9_s_p4_0[] = {
  128451. 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,10,
  128452. 10, 0, 5, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  128453. 11,11, 0, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  128454. 10,11,11, 0, 6, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,
  128455. 11,11,11,12, 0, 0, 0, 6, 6, 7, 7, 8, 8, 9, 9,10,
  128456. 10,11,11,12,12, 0, 0, 0, 7, 7, 7, 7, 9, 9, 9, 9,
  128457. 10,10,11,11,12,12, 0, 0, 0, 7, 7, 7, 8, 9, 9, 9,
  128458. 9,10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  128459. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  128460. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  128461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128469. 0,
  128470. };
  128471. static float _vq_quantthresh__44c9_s_p4_0[] = {
  128472. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  128473. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  128474. };
  128475. static long _vq_quantmap__44c9_s_p4_0[] = {
  128476. 15, 13, 11, 9, 7, 5, 3, 1,
  128477. 0, 2, 4, 6, 8, 10, 12, 14,
  128478. 16,
  128479. };
  128480. static encode_aux_threshmatch _vq_auxt__44c9_s_p4_0 = {
  128481. _vq_quantthresh__44c9_s_p4_0,
  128482. _vq_quantmap__44c9_s_p4_0,
  128483. 17,
  128484. 17
  128485. };
  128486. static static_codebook _44c9_s_p4_0 = {
  128487. 2, 289,
  128488. _vq_lengthlist__44c9_s_p4_0,
  128489. 1, -529530880, 1611661312, 5, 0,
  128490. _vq_quantlist__44c9_s_p4_0,
  128491. NULL,
  128492. &_vq_auxt__44c9_s_p4_0,
  128493. NULL,
  128494. 0
  128495. };
  128496. static long _vq_quantlist__44c9_s_p5_0[] = {
  128497. 1,
  128498. 0,
  128499. 2,
  128500. };
  128501. static long _vq_lengthlist__44c9_s_p5_0[] = {
  128502. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 7, 6, 9,10,10,10,
  128503. 10, 9, 4, 6, 7, 9,10,10,10, 9,10, 5, 9, 9, 9,11,
  128504. 11,10,11,11, 7,10, 9,11,12,11,12,12,12, 7, 9,10,
  128505. 11,11,12,12,12,12, 6,10,10,10,12,12,10,12,11, 7,
  128506. 10,10,11,12,12,11,12,12, 7,10,10,11,12,12,12,12,
  128507. 12,
  128508. };
  128509. static float _vq_quantthresh__44c9_s_p5_0[] = {
  128510. -5.5, 5.5,
  128511. };
  128512. static long _vq_quantmap__44c9_s_p5_0[] = {
  128513. 1, 0, 2,
  128514. };
  128515. static encode_aux_threshmatch _vq_auxt__44c9_s_p5_0 = {
  128516. _vq_quantthresh__44c9_s_p5_0,
  128517. _vq_quantmap__44c9_s_p5_0,
  128518. 3,
  128519. 3
  128520. };
  128521. static static_codebook _44c9_s_p5_0 = {
  128522. 4, 81,
  128523. _vq_lengthlist__44c9_s_p5_0,
  128524. 1, -529137664, 1618345984, 2, 0,
  128525. _vq_quantlist__44c9_s_p5_0,
  128526. NULL,
  128527. &_vq_auxt__44c9_s_p5_0,
  128528. NULL,
  128529. 0
  128530. };
  128531. static long _vq_quantlist__44c9_s_p5_1[] = {
  128532. 5,
  128533. 4,
  128534. 6,
  128535. 3,
  128536. 7,
  128537. 2,
  128538. 8,
  128539. 1,
  128540. 9,
  128541. 0,
  128542. 10,
  128543. };
  128544. static long _vq_lengthlist__44c9_s_p5_1[] = {
  128545. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7,11, 5, 5, 6, 6,
  128546. 7, 7, 7, 7, 8, 8,11, 5, 5, 6, 6, 7, 7, 7, 7, 8,
  128547. 8,11, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11,11,11, 6,
  128548. 6, 7, 7, 7, 8, 8, 8,11,11,11, 6, 6, 7, 7, 7, 8,
  128549. 8, 8,11,11,11, 6, 6, 7, 7, 7, 7, 8, 8,11,11,11,
  128550. 7, 7, 7, 7, 7, 7, 8, 8,11,11,11,10,10, 7, 7, 7,
  128551. 7, 8, 8,11,11,11,11,11, 7, 7, 7, 7, 7, 7,11,11,
  128552. 11,11,11, 7, 7, 7, 7, 7, 7,
  128553. };
  128554. static float _vq_quantthresh__44c9_s_p5_1[] = {
  128555. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  128556. 3.5, 4.5,
  128557. };
  128558. static long _vq_quantmap__44c9_s_p5_1[] = {
  128559. 9, 7, 5, 3, 1, 0, 2, 4,
  128560. 6, 8, 10,
  128561. };
  128562. static encode_aux_threshmatch _vq_auxt__44c9_s_p5_1 = {
  128563. _vq_quantthresh__44c9_s_p5_1,
  128564. _vq_quantmap__44c9_s_p5_1,
  128565. 11,
  128566. 11
  128567. };
  128568. static static_codebook _44c9_s_p5_1 = {
  128569. 2, 121,
  128570. _vq_lengthlist__44c9_s_p5_1,
  128571. 1, -531365888, 1611661312, 4, 0,
  128572. _vq_quantlist__44c9_s_p5_1,
  128573. NULL,
  128574. &_vq_auxt__44c9_s_p5_1,
  128575. NULL,
  128576. 0
  128577. };
  128578. static long _vq_quantlist__44c9_s_p6_0[] = {
  128579. 6,
  128580. 5,
  128581. 7,
  128582. 4,
  128583. 8,
  128584. 3,
  128585. 9,
  128586. 2,
  128587. 10,
  128588. 1,
  128589. 11,
  128590. 0,
  128591. 12,
  128592. };
  128593. static long _vq_lengthlist__44c9_s_p6_0[] = {
  128594. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 5, 4, 4,
  128595. 6, 6, 8, 8, 9, 9, 9, 9,10,10, 6, 4, 4, 6, 6, 8,
  128596. 8, 9, 9, 9, 9,10,10, 0, 6, 6, 7, 7, 8, 8, 9, 9,
  128597. 10,10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  128598. 11, 0,10,10, 8, 8, 9, 9,10,10,11,11,12,12, 0,11,
  128599. 11, 8, 8, 9, 9,10,10,11,11,12,12, 0, 0, 0, 0, 0,
  128600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128604. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128605. };
  128606. static float _vq_quantthresh__44c9_s_p6_0[] = {
  128607. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  128608. 12.5, 17.5, 22.5, 27.5,
  128609. };
  128610. static long _vq_quantmap__44c9_s_p6_0[] = {
  128611. 11, 9, 7, 5, 3, 1, 0, 2,
  128612. 4, 6, 8, 10, 12,
  128613. };
  128614. static encode_aux_threshmatch _vq_auxt__44c9_s_p6_0 = {
  128615. _vq_quantthresh__44c9_s_p6_0,
  128616. _vq_quantmap__44c9_s_p6_0,
  128617. 13,
  128618. 13
  128619. };
  128620. static static_codebook _44c9_s_p6_0 = {
  128621. 2, 169,
  128622. _vq_lengthlist__44c9_s_p6_0,
  128623. 1, -526516224, 1616117760, 4, 0,
  128624. _vq_quantlist__44c9_s_p6_0,
  128625. NULL,
  128626. &_vq_auxt__44c9_s_p6_0,
  128627. NULL,
  128628. 0
  128629. };
  128630. static long _vq_quantlist__44c9_s_p6_1[] = {
  128631. 2,
  128632. 1,
  128633. 3,
  128634. 0,
  128635. 4,
  128636. };
  128637. static long _vq_lengthlist__44c9_s_p6_1[] = {
  128638. 4, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5,
  128639. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  128640. };
  128641. static float _vq_quantthresh__44c9_s_p6_1[] = {
  128642. -1.5, -0.5, 0.5, 1.5,
  128643. };
  128644. static long _vq_quantmap__44c9_s_p6_1[] = {
  128645. 3, 1, 0, 2, 4,
  128646. };
  128647. static encode_aux_threshmatch _vq_auxt__44c9_s_p6_1 = {
  128648. _vq_quantthresh__44c9_s_p6_1,
  128649. _vq_quantmap__44c9_s_p6_1,
  128650. 5,
  128651. 5
  128652. };
  128653. static static_codebook _44c9_s_p6_1 = {
  128654. 2, 25,
  128655. _vq_lengthlist__44c9_s_p6_1,
  128656. 1, -533725184, 1611661312, 3, 0,
  128657. _vq_quantlist__44c9_s_p6_1,
  128658. NULL,
  128659. &_vq_auxt__44c9_s_p6_1,
  128660. NULL,
  128661. 0
  128662. };
  128663. static long _vq_quantlist__44c9_s_p7_0[] = {
  128664. 6,
  128665. 5,
  128666. 7,
  128667. 4,
  128668. 8,
  128669. 3,
  128670. 9,
  128671. 2,
  128672. 10,
  128673. 1,
  128674. 11,
  128675. 0,
  128676. 12,
  128677. };
  128678. static long _vq_lengthlist__44c9_s_p7_0[] = {
  128679. 2, 4, 4, 6, 6, 7, 7, 8, 8,10,10,11,11, 6, 4, 4,
  128680. 6, 6, 8, 8, 9, 9,10,10,12,12, 6, 4, 5, 6, 6, 8,
  128681. 8, 9, 9,10,10,12,12,20, 6, 6, 6, 6, 8, 8, 9,10,
  128682. 11,11,12,12,20, 6, 6, 6, 6, 8, 8,10,10,11,11,12,
  128683. 12,20,10,10, 7, 7, 9, 9,10,10,11,11,12,12,20,11,
  128684. 11, 7, 7, 9, 9,10,10,11,11,12,12,20,20,20, 9, 9,
  128685. 9, 9,11,11,12,12,13,13,20,20,20, 9, 9, 9, 9,11,
  128686. 11,12,12,13,13,20,20,20,13,13,10,10,11,11,12,13,
  128687. 13,13,20,20,20,13,13,10,10,11,11,12,13,13,13,20,
  128688. 20,20,20,19,12,12,12,12,13,13,14,15,19,19,19,19,
  128689. 19,12,12,12,12,13,13,14,14,
  128690. };
  128691. static float _vq_quantthresh__44c9_s_p7_0[] = {
  128692. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  128693. 27.5, 38.5, 49.5, 60.5,
  128694. };
  128695. static long _vq_quantmap__44c9_s_p7_0[] = {
  128696. 11, 9, 7, 5, 3, 1, 0, 2,
  128697. 4, 6, 8, 10, 12,
  128698. };
  128699. static encode_aux_threshmatch _vq_auxt__44c9_s_p7_0 = {
  128700. _vq_quantthresh__44c9_s_p7_0,
  128701. _vq_quantmap__44c9_s_p7_0,
  128702. 13,
  128703. 13
  128704. };
  128705. static static_codebook _44c9_s_p7_0 = {
  128706. 2, 169,
  128707. _vq_lengthlist__44c9_s_p7_0,
  128708. 1, -523206656, 1618345984, 4, 0,
  128709. _vq_quantlist__44c9_s_p7_0,
  128710. NULL,
  128711. &_vq_auxt__44c9_s_p7_0,
  128712. NULL,
  128713. 0
  128714. };
  128715. static long _vq_quantlist__44c9_s_p7_1[] = {
  128716. 5,
  128717. 4,
  128718. 6,
  128719. 3,
  128720. 7,
  128721. 2,
  128722. 8,
  128723. 1,
  128724. 9,
  128725. 0,
  128726. 10,
  128727. };
  128728. static long _vq_lengthlist__44c9_s_p7_1[] = {
  128729. 5, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6,
  128730. 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  128731. 7, 8, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 6,
  128732. 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  128733. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  128734. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  128735. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  128736. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  128737. };
  128738. static float _vq_quantthresh__44c9_s_p7_1[] = {
  128739. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  128740. 3.5, 4.5,
  128741. };
  128742. static long _vq_quantmap__44c9_s_p7_1[] = {
  128743. 9, 7, 5, 3, 1, 0, 2, 4,
  128744. 6, 8, 10,
  128745. };
  128746. static encode_aux_threshmatch _vq_auxt__44c9_s_p7_1 = {
  128747. _vq_quantthresh__44c9_s_p7_1,
  128748. _vq_quantmap__44c9_s_p7_1,
  128749. 11,
  128750. 11
  128751. };
  128752. static static_codebook _44c9_s_p7_1 = {
  128753. 2, 121,
  128754. _vq_lengthlist__44c9_s_p7_1,
  128755. 1, -531365888, 1611661312, 4, 0,
  128756. _vq_quantlist__44c9_s_p7_1,
  128757. NULL,
  128758. &_vq_auxt__44c9_s_p7_1,
  128759. NULL,
  128760. 0
  128761. };
  128762. static long _vq_quantlist__44c9_s_p8_0[] = {
  128763. 7,
  128764. 6,
  128765. 8,
  128766. 5,
  128767. 9,
  128768. 4,
  128769. 10,
  128770. 3,
  128771. 11,
  128772. 2,
  128773. 12,
  128774. 1,
  128775. 13,
  128776. 0,
  128777. 14,
  128778. };
  128779. static long _vq_lengthlist__44c9_s_p8_0[] = {
  128780. 1, 4, 4, 7, 6, 8, 8, 8, 8, 9, 9,10,10,11,10, 6,
  128781. 5, 5, 7, 7, 9, 9, 8, 9,10,10,11,11,12,12, 6, 5,
  128782. 5, 7, 7, 9, 9, 9, 9,10,10,11,11,12,12,21, 7, 8,
  128783. 8, 8, 9, 9, 9, 9,10,10,11,11,12,12,21, 8, 8, 8,
  128784. 8, 9, 9, 9, 9,10,10,11,11,12,12,21,11,12, 9, 9,
  128785. 10,10,10,10,10,11,11,12,12,12,21,12,12, 9, 8,10,
  128786. 10,10,10,11,11,12,12,13,13,21,21,21, 9, 9, 9, 9,
  128787. 11,11,11,11,12,12,12,13,21,20,20, 9, 9, 9, 9,10,
  128788. 11,11,11,12,12,13,13,20,20,20,13,13,10,10,11,11,
  128789. 12,12,13,13,13,13,20,20,20,13,13,10,10,11,11,12,
  128790. 12,13,13,13,13,20,20,20,20,20,12,12,12,12,12,12,
  128791. 13,13,14,14,20,20,20,20,20,12,12,12,11,13,12,13,
  128792. 13,14,14,20,20,20,20,20,15,16,13,12,13,13,14,13,
  128793. 14,14,20,20,20,20,20,16,15,12,12,13,12,14,13,14,
  128794. 14,
  128795. };
  128796. static float _vq_quantthresh__44c9_s_p8_0[] = {
  128797. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  128798. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  128799. };
  128800. static long _vq_quantmap__44c9_s_p8_0[] = {
  128801. 13, 11, 9, 7, 5, 3, 1, 0,
  128802. 2, 4, 6, 8, 10, 12, 14,
  128803. };
  128804. static encode_aux_threshmatch _vq_auxt__44c9_s_p8_0 = {
  128805. _vq_quantthresh__44c9_s_p8_0,
  128806. _vq_quantmap__44c9_s_p8_0,
  128807. 15,
  128808. 15
  128809. };
  128810. static static_codebook _44c9_s_p8_0 = {
  128811. 2, 225,
  128812. _vq_lengthlist__44c9_s_p8_0,
  128813. 1, -520986624, 1620377600, 4, 0,
  128814. _vq_quantlist__44c9_s_p8_0,
  128815. NULL,
  128816. &_vq_auxt__44c9_s_p8_0,
  128817. NULL,
  128818. 0
  128819. };
  128820. static long _vq_quantlist__44c9_s_p8_1[] = {
  128821. 10,
  128822. 9,
  128823. 11,
  128824. 8,
  128825. 12,
  128826. 7,
  128827. 13,
  128828. 6,
  128829. 14,
  128830. 5,
  128831. 15,
  128832. 4,
  128833. 16,
  128834. 3,
  128835. 17,
  128836. 2,
  128837. 18,
  128838. 1,
  128839. 19,
  128840. 0,
  128841. 20,
  128842. };
  128843. static long _vq_lengthlist__44c9_s_p8_1[] = {
  128844. 4, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  128845. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  128846. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  128847. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  128848. 7, 7, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  128849. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  128850. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8,
  128851. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  128852. 10, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  128853. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  128854. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  128855. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  128856. 10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  128857. 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  128858. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9,
  128859. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10,10,10,10,
  128860. 10,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9, 9, 9, 9, 9,
  128861. 9,10,10,10,10,10,10,10, 9, 9, 9,10,10,10,10,10,
  128862. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10, 9, 9,10,
  128863. 9,10, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  128864. 10,10,10,10, 9, 9,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  128865. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  128866. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  128867. 10,10, 9, 9,10, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  128868. 10,10,10,10,10, 9, 9,10,10, 9, 9,10, 9, 9, 9,10,
  128869. 10,10,10,10,10,10,10,10,10,10, 9, 9,10, 9, 9, 9,
  128870. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10, 9,
  128871. 9, 9, 9,10, 9, 9, 9, 9, 9,
  128872. };
  128873. static float _vq_quantthresh__44c9_s_p8_1[] = {
  128874. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  128875. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  128876. 6.5, 7.5, 8.5, 9.5,
  128877. };
  128878. static long _vq_quantmap__44c9_s_p8_1[] = {
  128879. 19, 17, 15, 13, 11, 9, 7, 5,
  128880. 3, 1, 0, 2, 4, 6, 8, 10,
  128881. 12, 14, 16, 18, 20,
  128882. };
  128883. static encode_aux_threshmatch _vq_auxt__44c9_s_p8_1 = {
  128884. _vq_quantthresh__44c9_s_p8_1,
  128885. _vq_quantmap__44c9_s_p8_1,
  128886. 21,
  128887. 21
  128888. };
  128889. static static_codebook _44c9_s_p8_1 = {
  128890. 2, 441,
  128891. _vq_lengthlist__44c9_s_p8_1,
  128892. 1, -529268736, 1611661312, 5, 0,
  128893. _vq_quantlist__44c9_s_p8_1,
  128894. NULL,
  128895. &_vq_auxt__44c9_s_p8_1,
  128896. NULL,
  128897. 0
  128898. };
  128899. static long _vq_quantlist__44c9_s_p9_0[] = {
  128900. 9,
  128901. 8,
  128902. 10,
  128903. 7,
  128904. 11,
  128905. 6,
  128906. 12,
  128907. 5,
  128908. 13,
  128909. 4,
  128910. 14,
  128911. 3,
  128912. 15,
  128913. 2,
  128914. 16,
  128915. 1,
  128916. 17,
  128917. 0,
  128918. 18,
  128919. };
  128920. static long _vq_lengthlist__44c9_s_p9_0[] = {
  128921. 1, 4, 3,12,12,12,12,12,12,12,12,12,12,12,12,12,
  128922. 12,12,12, 4, 5, 6,12,12,12,12,12,12,12,12,12,12,
  128923. 12,12,12,12,12,12, 4, 6, 6,12,12,12,12,12,12,12,
  128924. 12,12,12,12,12,12,12,12,12,12,12,11,12,12,12,12,
  128925. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  128926. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  128927. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  128928. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  128929. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  128930. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  128931. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  128932. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  128933. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  128934. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  128935. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  128936. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  128937. 12,12,12,12,12,12,12,12,12,12,11,11,11,11,11,11,
  128938. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128939. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128940. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128941. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128942. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  128943. 11,11,11,11,11,11,11,11,11,
  128944. };
  128945. static float _vq_quantthresh__44c9_s_p9_0[] = {
  128946. -7913.5, -6982.5, -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5,
  128947. -465.5, 465.5, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5,
  128948. 6982.5, 7913.5,
  128949. };
  128950. static long _vq_quantmap__44c9_s_p9_0[] = {
  128951. 17, 15, 13, 11, 9, 7, 5, 3,
  128952. 1, 0, 2, 4, 6, 8, 10, 12,
  128953. 14, 16, 18,
  128954. };
  128955. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_0 = {
  128956. _vq_quantthresh__44c9_s_p9_0,
  128957. _vq_quantmap__44c9_s_p9_0,
  128958. 19,
  128959. 19
  128960. };
  128961. static static_codebook _44c9_s_p9_0 = {
  128962. 2, 361,
  128963. _vq_lengthlist__44c9_s_p9_0,
  128964. 1, -508535424, 1631393792, 5, 0,
  128965. _vq_quantlist__44c9_s_p9_0,
  128966. NULL,
  128967. &_vq_auxt__44c9_s_p9_0,
  128968. NULL,
  128969. 0
  128970. };
  128971. static long _vq_quantlist__44c9_s_p9_1[] = {
  128972. 9,
  128973. 8,
  128974. 10,
  128975. 7,
  128976. 11,
  128977. 6,
  128978. 12,
  128979. 5,
  128980. 13,
  128981. 4,
  128982. 14,
  128983. 3,
  128984. 15,
  128985. 2,
  128986. 16,
  128987. 1,
  128988. 17,
  128989. 0,
  128990. 18,
  128991. };
  128992. static long _vq_lengthlist__44c9_s_p9_1[] = {
  128993. 1, 4, 4, 7, 7, 7, 7, 8, 7, 9, 8, 9, 9,10,10,11,
  128994. 11,11,11, 6, 5, 5, 8, 8, 9, 9, 9, 8,10, 9,11,10,
  128995. 12,12,13,12,13,13, 5, 5, 5, 8, 8, 9, 9, 9, 9,10,
  128996. 10,11,11,12,12,13,12,13,13,17, 8, 8, 9, 9, 9, 9,
  128997. 9, 9,10,10,12,11,13,12,13,13,13,13,18, 8, 8, 9,
  128998. 9, 9, 9, 9, 9,11,11,12,12,13,13,13,13,13,13,17,
  128999. 13,12, 9, 9,10,10,10,10,11,11,12,12,12,13,13,13,
  129000. 14,14,18,13,12, 9, 9,10,10,10,10,11,11,12,12,13,
  129001. 13,13,14,14,14,17,18,18,10,10,10,10,11,11,11,12,
  129002. 12,12,14,13,14,13,13,14,18,18,18,10, 9,10, 9,11,
  129003. 11,12,12,12,12,13,13,15,14,14,14,18,18,16,13,14,
  129004. 10,11,11,11,12,13,13,13,13,14,13,13,14,14,18,18,
  129005. 18,14,12,11, 9,11,10,13,12,13,13,13,14,14,14,13,
  129006. 14,18,18,17,18,18,11,12,12,12,13,13,14,13,14,14,
  129007. 13,14,14,14,18,18,18,18,17,12,10,12, 9,13,11,13,
  129008. 14,14,14,14,14,15,14,18,18,17,17,18,14,15,12,13,
  129009. 13,13,14,13,14,14,15,14,15,14,18,17,18,18,18,15,
  129010. 15,12,10,14,10,14,14,13,13,14,14,14,14,18,16,18,
  129011. 18,18,18,17,14,14,13,14,14,13,13,14,14,14,15,15,
  129012. 18,18,18,18,17,17,17,14,14,14,12,14,13,14,14,15,
  129013. 14,15,14,18,18,18,18,18,18,18,17,16,13,13,13,14,
  129014. 14,14,14,15,16,15,18,18,18,18,18,18,18,17,17,13,
  129015. 13,13,13,14,13,14,15,15,15,
  129016. };
  129017. static float _vq_quantthresh__44c9_s_p9_1[] = {
  129018. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  129019. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  129020. 367.5, 416.5,
  129021. };
  129022. static long _vq_quantmap__44c9_s_p9_1[] = {
  129023. 17, 15, 13, 11, 9, 7, 5, 3,
  129024. 1, 0, 2, 4, 6, 8, 10, 12,
  129025. 14, 16, 18,
  129026. };
  129027. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_1 = {
  129028. _vq_quantthresh__44c9_s_p9_1,
  129029. _vq_quantmap__44c9_s_p9_1,
  129030. 19,
  129031. 19
  129032. };
  129033. static static_codebook _44c9_s_p9_1 = {
  129034. 2, 361,
  129035. _vq_lengthlist__44c9_s_p9_1,
  129036. 1, -518287360, 1622704128, 5, 0,
  129037. _vq_quantlist__44c9_s_p9_1,
  129038. NULL,
  129039. &_vq_auxt__44c9_s_p9_1,
  129040. NULL,
  129041. 0
  129042. };
  129043. static long _vq_quantlist__44c9_s_p9_2[] = {
  129044. 24,
  129045. 23,
  129046. 25,
  129047. 22,
  129048. 26,
  129049. 21,
  129050. 27,
  129051. 20,
  129052. 28,
  129053. 19,
  129054. 29,
  129055. 18,
  129056. 30,
  129057. 17,
  129058. 31,
  129059. 16,
  129060. 32,
  129061. 15,
  129062. 33,
  129063. 14,
  129064. 34,
  129065. 13,
  129066. 35,
  129067. 12,
  129068. 36,
  129069. 11,
  129070. 37,
  129071. 10,
  129072. 38,
  129073. 9,
  129074. 39,
  129075. 8,
  129076. 40,
  129077. 7,
  129078. 41,
  129079. 6,
  129080. 42,
  129081. 5,
  129082. 43,
  129083. 4,
  129084. 44,
  129085. 3,
  129086. 45,
  129087. 2,
  129088. 46,
  129089. 1,
  129090. 47,
  129091. 0,
  129092. 48,
  129093. };
  129094. static long _vq_lengthlist__44c9_s_p9_2[] = {
  129095. 2, 4, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  129096. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  129097. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  129098. 7,
  129099. };
  129100. static float _vq_quantthresh__44c9_s_p9_2[] = {
  129101. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  129102. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  129103. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  129104. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  129105. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  129106. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  129107. };
  129108. static long _vq_quantmap__44c9_s_p9_2[] = {
  129109. 47, 45, 43, 41, 39, 37, 35, 33,
  129110. 31, 29, 27, 25, 23, 21, 19, 17,
  129111. 15, 13, 11, 9, 7, 5, 3, 1,
  129112. 0, 2, 4, 6, 8, 10, 12, 14,
  129113. 16, 18, 20, 22, 24, 26, 28, 30,
  129114. 32, 34, 36, 38, 40, 42, 44, 46,
  129115. 48,
  129116. };
  129117. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_2 = {
  129118. _vq_quantthresh__44c9_s_p9_2,
  129119. _vq_quantmap__44c9_s_p9_2,
  129120. 49,
  129121. 49
  129122. };
  129123. static static_codebook _44c9_s_p9_2 = {
  129124. 1, 49,
  129125. _vq_lengthlist__44c9_s_p9_2,
  129126. 1, -526909440, 1611661312, 6, 0,
  129127. _vq_quantlist__44c9_s_p9_2,
  129128. NULL,
  129129. &_vq_auxt__44c9_s_p9_2,
  129130. NULL,
  129131. 0
  129132. };
  129133. static long _huff_lengthlist__44c9_s_short[] = {
  129134. 5,13,18,16,17,17,19,18,19,19, 5, 7,10,11,12,12,
  129135. 13,16,17,18, 6, 6, 7, 7, 9, 9,10,14,17,19, 8, 7,
  129136. 6, 5, 6, 7, 9,12,19,17, 8, 7, 7, 6, 5, 6, 8,11,
  129137. 15,19, 9, 8, 7, 6, 5, 5, 6, 8,13,15,11,10, 8, 8,
  129138. 7, 5, 4, 4,10,14,12,13,11, 9, 7, 6, 4, 2, 6,12,
  129139. 18,16,16,13, 8, 7, 7, 5, 8,13,16,17,18,15,11, 9,
  129140. 9, 8,10,13,
  129141. };
  129142. static static_codebook _huff_book__44c9_s_short = {
  129143. 2, 100,
  129144. _huff_lengthlist__44c9_s_short,
  129145. 0, 0, 0, 0, 0,
  129146. NULL,
  129147. NULL,
  129148. NULL,
  129149. NULL,
  129150. 0
  129151. };
  129152. static long _huff_lengthlist__44c0_s_long[] = {
  129153. 5, 4, 8, 9, 8, 9,10,12,15, 4, 1, 5, 5, 6, 8,11,
  129154. 12,12, 8, 5, 8, 9, 9,11,13,12,12, 9, 5, 8, 5, 7,
  129155. 9,12,13,13, 8, 6, 8, 7, 7, 9,11,11,11, 9, 7, 9,
  129156. 7, 7, 7, 7,10,12,10,10,11, 9, 8, 7, 7, 9,11,11,
  129157. 12,13,12,11, 9, 8, 9,11,13,16,16,15,15,12,10,11,
  129158. 12,
  129159. };
  129160. static static_codebook _huff_book__44c0_s_long = {
  129161. 2, 81,
  129162. _huff_lengthlist__44c0_s_long,
  129163. 0, 0, 0, 0, 0,
  129164. NULL,
  129165. NULL,
  129166. NULL,
  129167. NULL,
  129168. 0
  129169. };
  129170. static long _vq_quantlist__44c0_s_p1_0[] = {
  129171. 1,
  129172. 0,
  129173. 2,
  129174. };
  129175. static long _vq_lengthlist__44c0_s_p1_0[] = {
  129176. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  129177. 0, 0, 5, 7, 7, 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, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  129182. 0, 0, 0, 7, 9, 9, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  129187. 0, 0, 0, 0, 7, 9, 9, 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, 0, 0, 0, 0, 0, 0, 0,
  129208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0,
  129213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0,
  129218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  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, 5, 7, 7, 0, 0, 0, 0,
  129222. 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 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, 7, 9, 9, 0, 0, 0,
  129227. 0, 0, 0, 9,10,11, 0, 0, 0, 0, 0, 0, 9,11,10, 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, 7, 9, 9, 0, 0,
  129232. 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129254. 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129259. 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  129268. 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  129273. 0, 0, 0, 0, 0, 9, 9,11, 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, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,10,11,
  129278. 0, 0, 0, 0, 0, 0, 9,11,10, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129586. 0,
  129587. };
  129588. static float _vq_quantthresh__44c0_s_p1_0[] = {
  129589. -0.5, 0.5,
  129590. };
  129591. static long _vq_quantmap__44c0_s_p1_0[] = {
  129592. 1, 0, 2,
  129593. };
  129594. static encode_aux_threshmatch _vq_auxt__44c0_s_p1_0 = {
  129595. _vq_quantthresh__44c0_s_p1_0,
  129596. _vq_quantmap__44c0_s_p1_0,
  129597. 3,
  129598. 3
  129599. };
  129600. static static_codebook _44c0_s_p1_0 = {
  129601. 8, 6561,
  129602. _vq_lengthlist__44c0_s_p1_0,
  129603. 1, -535822336, 1611661312, 2, 0,
  129604. _vq_quantlist__44c0_s_p1_0,
  129605. NULL,
  129606. &_vq_auxt__44c0_s_p1_0,
  129607. NULL,
  129608. 0
  129609. };
  129610. static long _vq_quantlist__44c0_s_p2_0[] = {
  129611. 2,
  129612. 1,
  129613. 3,
  129614. 0,
  129615. 4,
  129616. };
  129617. static long _vq_lengthlist__44c0_s_p2_0[] = {
  129618. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 6, 0, 0,
  129620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129621. 0, 0, 4, 5, 6, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  129623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129624. 0, 0, 0, 0, 6, 7, 7, 9, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129657. 0,
  129658. };
  129659. static float _vq_quantthresh__44c0_s_p2_0[] = {
  129660. -1.5, -0.5, 0.5, 1.5,
  129661. };
  129662. static long _vq_quantmap__44c0_s_p2_0[] = {
  129663. 3, 1, 0, 2, 4,
  129664. };
  129665. static encode_aux_threshmatch _vq_auxt__44c0_s_p2_0 = {
  129666. _vq_quantthresh__44c0_s_p2_0,
  129667. _vq_quantmap__44c0_s_p2_0,
  129668. 5,
  129669. 5
  129670. };
  129671. static static_codebook _44c0_s_p2_0 = {
  129672. 4, 625,
  129673. _vq_lengthlist__44c0_s_p2_0,
  129674. 1, -533725184, 1611661312, 3, 0,
  129675. _vq_quantlist__44c0_s_p2_0,
  129676. NULL,
  129677. &_vq_auxt__44c0_s_p2_0,
  129678. NULL,
  129679. 0
  129680. };
  129681. static long _vq_quantlist__44c0_s_p3_0[] = {
  129682. 4,
  129683. 3,
  129684. 5,
  129685. 2,
  129686. 6,
  129687. 1,
  129688. 7,
  129689. 0,
  129690. 8,
  129691. };
  129692. static long _vq_lengthlist__44c0_s_p3_0[] = {
  129693. 1, 3, 2, 8, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  129694. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  129695. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  129696. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  129697. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129698. 0,
  129699. };
  129700. static float _vq_quantthresh__44c0_s_p3_0[] = {
  129701. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  129702. };
  129703. static long _vq_quantmap__44c0_s_p3_0[] = {
  129704. 7, 5, 3, 1, 0, 2, 4, 6,
  129705. 8,
  129706. };
  129707. static encode_aux_threshmatch _vq_auxt__44c0_s_p3_0 = {
  129708. _vq_quantthresh__44c0_s_p3_0,
  129709. _vq_quantmap__44c0_s_p3_0,
  129710. 9,
  129711. 9
  129712. };
  129713. static static_codebook _44c0_s_p3_0 = {
  129714. 2, 81,
  129715. _vq_lengthlist__44c0_s_p3_0,
  129716. 1, -531628032, 1611661312, 4, 0,
  129717. _vq_quantlist__44c0_s_p3_0,
  129718. NULL,
  129719. &_vq_auxt__44c0_s_p3_0,
  129720. NULL,
  129721. 0
  129722. };
  129723. static long _vq_quantlist__44c0_s_p4_0[] = {
  129724. 4,
  129725. 3,
  129726. 5,
  129727. 2,
  129728. 6,
  129729. 1,
  129730. 7,
  129731. 0,
  129732. 8,
  129733. };
  129734. static long _vq_lengthlist__44c0_s_p4_0[] = {
  129735. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  129736. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  129737. 7, 8, 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0,
  129738. 9, 9, 8, 8,10,10, 0, 0, 0, 8, 9, 8, 8,10,10, 0,
  129739. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  129740. 10,
  129741. };
  129742. static float _vq_quantthresh__44c0_s_p4_0[] = {
  129743. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  129744. };
  129745. static long _vq_quantmap__44c0_s_p4_0[] = {
  129746. 7, 5, 3, 1, 0, 2, 4, 6,
  129747. 8,
  129748. };
  129749. static encode_aux_threshmatch _vq_auxt__44c0_s_p4_0 = {
  129750. _vq_quantthresh__44c0_s_p4_0,
  129751. _vq_quantmap__44c0_s_p4_0,
  129752. 9,
  129753. 9
  129754. };
  129755. static static_codebook _44c0_s_p4_0 = {
  129756. 2, 81,
  129757. _vq_lengthlist__44c0_s_p4_0,
  129758. 1, -531628032, 1611661312, 4, 0,
  129759. _vq_quantlist__44c0_s_p4_0,
  129760. NULL,
  129761. &_vq_auxt__44c0_s_p4_0,
  129762. NULL,
  129763. 0
  129764. };
  129765. static long _vq_quantlist__44c0_s_p5_0[] = {
  129766. 8,
  129767. 7,
  129768. 9,
  129769. 6,
  129770. 10,
  129771. 5,
  129772. 11,
  129773. 4,
  129774. 12,
  129775. 3,
  129776. 13,
  129777. 2,
  129778. 14,
  129779. 1,
  129780. 15,
  129781. 0,
  129782. 16,
  129783. };
  129784. static long _vq_lengthlist__44c0_s_p5_0[] = {
  129785. 1, 4, 3, 6, 6, 8, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  129786. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9, 9,10,10,10,
  129787. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  129788. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  129789. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  129790. 10,11,11,11,11, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,10,
  129791. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,
  129792. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  129793. 10,10,11,11,11,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  129794. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,
  129795. 10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  129796. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  129797. 10,10,11,11,11,11,11,12,12,12,13,13, 0, 0, 0, 0,
  129798. 0, 0, 0,11,10,11,11,11,11,12,12,13,13, 0, 0, 0,
  129799. 0, 0, 0, 0,11,11,12,11,12,12,12,12,13,13, 0, 0,
  129800. 0, 0, 0, 0, 0,11,11,11,12,12,12,12,13,13,13, 0,
  129801. 0, 0, 0, 0, 0, 0,12,12,12,12,12,13,13,13,14,14,
  129802. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  129803. 14,
  129804. };
  129805. static float _vq_quantthresh__44c0_s_p5_0[] = {
  129806. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  129807. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  129808. };
  129809. static long _vq_quantmap__44c0_s_p5_0[] = {
  129810. 15, 13, 11, 9, 7, 5, 3, 1,
  129811. 0, 2, 4, 6, 8, 10, 12, 14,
  129812. 16,
  129813. };
  129814. static encode_aux_threshmatch _vq_auxt__44c0_s_p5_0 = {
  129815. _vq_quantthresh__44c0_s_p5_0,
  129816. _vq_quantmap__44c0_s_p5_0,
  129817. 17,
  129818. 17
  129819. };
  129820. static static_codebook _44c0_s_p5_0 = {
  129821. 2, 289,
  129822. _vq_lengthlist__44c0_s_p5_0,
  129823. 1, -529530880, 1611661312, 5, 0,
  129824. _vq_quantlist__44c0_s_p5_0,
  129825. NULL,
  129826. &_vq_auxt__44c0_s_p5_0,
  129827. NULL,
  129828. 0
  129829. };
  129830. static long _vq_quantlist__44c0_s_p6_0[] = {
  129831. 1,
  129832. 0,
  129833. 2,
  129834. };
  129835. static long _vq_lengthlist__44c0_s_p6_0[] = {
  129836. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,10,
  129837. 9, 9, 4, 6, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  129838. 11,12,10,11, 6, 9, 9,11,10,11,11,10,10, 6, 9, 9,
  129839. 11,10,11,11,10,10, 7,11,10,12,11,11,11,11,11, 7,
  129840. 9, 9,10,10,10,11,11,10, 6, 9, 9,11,10,10,11,10,
  129841. 10,
  129842. };
  129843. static float _vq_quantthresh__44c0_s_p6_0[] = {
  129844. -5.5, 5.5,
  129845. };
  129846. static long _vq_quantmap__44c0_s_p6_0[] = {
  129847. 1, 0, 2,
  129848. };
  129849. static encode_aux_threshmatch _vq_auxt__44c0_s_p6_0 = {
  129850. _vq_quantthresh__44c0_s_p6_0,
  129851. _vq_quantmap__44c0_s_p6_0,
  129852. 3,
  129853. 3
  129854. };
  129855. static static_codebook _44c0_s_p6_0 = {
  129856. 4, 81,
  129857. _vq_lengthlist__44c0_s_p6_0,
  129858. 1, -529137664, 1618345984, 2, 0,
  129859. _vq_quantlist__44c0_s_p6_0,
  129860. NULL,
  129861. &_vq_auxt__44c0_s_p6_0,
  129862. NULL,
  129863. 0
  129864. };
  129865. static long _vq_quantlist__44c0_s_p6_1[] = {
  129866. 5,
  129867. 4,
  129868. 6,
  129869. 3,
  129870. 7,
  129871. 2,
  129872. 8,
  129873. 1,
  129874. 9,
  129875. 0,
  129876. 10,
  129877. };
  129878. static long _vq_lengthlist__44c0_s_p6_1[] = {
  129879. 2, 3, 3, 6, 6, 7, 7, 7, 7, 7, 8,10,10,10, 6, 6,
  129880. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  129881. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  129882. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 7, 8, 8, 8, 8,
  129883. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  129884. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  129885. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  129886. 10,10,10, 8, 8, 8, 8, 8, 8,
  129887. };
  129888. static float _vq_quantthresh__44c0_s_p6_1[] = {
  129889. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  129890. 3.5, 4.5,
  129891. };
  129892. static long _vq_quantmap__44c0_s_p6_1[] = {
  129893. 9, 7, 5, 3, 1, 0, 2, 4,
  129894. 6, 8, 10,
  129895. };
  129896. static encode_aux_threshmatch _vq_auxt__44c0_s_p6_1 = {
  129897. _vq_quantthresh__44c0_s_p6_1,
  129898. _vq_quantmap__44c0_s_p6_1,
  129899. 11,
  129900. 11
  129901. };
  129902. static static_codebook _44c0_s_p6_1 = {
  129903. 2, 121,
  129904. _vq_lengthlist__44c0_s_p6_1,
  129905. 1, -531365888, 1611661312, 4, 0,
  129906. _vq_quantlist__44c0_s_p6_1,
  129907. NULL,
  129908. &_vq_auxt__44c0_s_p6_1,
  129909. NULL,
  129910. 0
  129911. };
  129912. static long _vq_quantlist__44c0_s_p7_0[] = {
  129913. 6,
  129914. 5,
  129915. 7,
  129916. 4,
  129917. 8,
  129918. 3,
  129919. 9,
  129920. 2,
  129921. 10,
  129922. 1,
  129923. 11,
  129924. 0,
  129925. 12,
  129926. };
  129927. static long _vq_lengthlist__44c0_s_p7_0[] = {
  129928. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  129929. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 6, 7, 7, 8,
  129930. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  129931. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  129932. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  129933. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  129934. 10,10,11,11,11,11,12,12, 0, 0, 0,10,10, 9, 9,11,
  129935. 11,11,12,12,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  129936. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  129937. 0, 0, 0, 0,11,11,11,11,13,12,13,13, 0, 0, 0, 0,
  129938. 0,12,12,11,11,12,12,13,13,
  129939. };
  129940. static float _vq_quantthresh__44c0_s_p7_0[] = {
  129941. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  129942. 12.5, 17.5, 22.5, 27.5,
  129943. };
  129944. static long _vq_quantmap__44c0_s_p7_0[] = {
  129945. 11, 9, 7, 5, 3, 1, 0, 2,
  129946. 4, 6, 8, 10, 12,
  129947. };
  129948. static encode_aux_threshmatch _vq_auxt__44c0_s_p7_0 = {
  129949. _vq_quantthresh__44c0_s_p7_0,
  129950. _vq_quantmap__44c0_s_p7_0,
  129951. 13,
  129952. 13
  129953. };
  129954. static static_codebook _44c0_s_p7_0 = {
  129955. 2, 169,
  129956. _vq_lengthlist__44c0_s_p7_0,
  129957. 1, -526516224, 1616117760, 4, 0,
  129958. _vq_quantlist__44c0_s_p7_0,
  129959. NULL,
  129960. &_vq_auxt__44c0_s_p7_0,
  129961. NULL,
  129962. 0
  129963. };
  129964. static long _vq_quantlist__44c0_s_p7_1[] = {
  129965. 2,
  129966. 1,
  129967. 3,
  129968. 0,
  129969. 4,
  129970. };
  129971. static long _vq_lengthlist__44c0_s_p7_1[] = {
  129972. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  129973. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  129974. };
  129975. static float _vq_quantthresh__44c0_s_p7_1[] = {
  129976. -1.5, -0.5, 0.5, 1.5,
  129977. };
  129978. static long _vq_quantmap__44c0_s_p7_1[] = {
  129979. 3, 1, 0, 2, 4,
  129980. };
  129981. static encode_aux_threshmatch _vq_auxt__44c0_s_p7_1 = {
  129982. _vq_quantthresh__44c0_s_p7_1,
  129983. _vq_quantmap__44c0_s_p7_1,
  129984. 5,
  129985. 5
  129986. };
  129987. static static_codebook _44c0_s_p7_1 = {
  129988. 2, 25,
  129989. _vq_lengthlist__44c0_s_p7_1,
  129990. 1, -533725184, 1611661312, 3, 0,
  129991. _vq_quantlist__44c0_s_p7_1,
  129992. NULL,
  129993. &_vq_auxt__44c0_s_p7_1,
  129994. NULL,
  129995. 0
  129996. };
  129997. static long _vq_quantlist__44c0_s_p8_0[] = {
  129998. 2,
  129999. 1,
  130000. 3,
  130001. 0,
  130002. 4,
  130003. };
  130004. static long _vq_lengthlist__44c0_s_p8_0[] = {
  130005. 1, 5, 5,10,10, 6, 9, 8,10,10, 6,10, 9,10,10,10,
  130006. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  130007. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  130008. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  130009. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  130010. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  130011. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  130012. 10,10,10,10,10,10,10,10,10,10,10,10,10, 8,10,10,
  130013. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  130014. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  130015. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  130016. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  130017. 10,10,10,10,10,10,10,10,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,10,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,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130031. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130032. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130033. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130034. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130035. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130036. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130037. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130038. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130039. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130040. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130041. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130042. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130043. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130044. 11,
  130045. };
  130046. static float _vq_quantthresh__44c0_s_p8_0[] = {
  130047. -331.5, -110.5, 110.5, 331.5,
  130048. };
  130049. static long _vq_quantmap__44c0_s_p8_0[] = {
  130050. 3, 1, 0, 2, 4,
  130051. };
  130052. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_0 = {
  130053. _vq_quantthresh__44c0_s_p8_0,
  130054. _vq_quantmap__44c0_s_p8_0,
  130055. 5,
  130056. 5
  130057. };
  130058. static static_codebook _44c0_s_p8_0 = {
  130059. 4, 625,
  130060. _vq_lengthlist__44c0_s_p8_0,
  130061. 1, -518283264, 1627103232, 3, 0,
  130062. _vq_quantlist__44c0_s_p8_0,
  130063. NULL,
  130064. &_vq_auxt__44c0_s_p8_0,
  130065. NULL,
  130066. 0
  130067. };
  130068. static long _vq_quantlist__44c0_s_p8_1[] = {
  130069. 6,
  130070. 5,
  130071. 7,
  130072. 4,
  130073. 8,
  130074. 3,
  130075. 9,
  130076. 2,
  130077. 10,
  130078. 1,
  130079. 11,
  130080. 0,
  130081. 12,
  130082. };
  130083. static long _vq_lengthlist__44c0_s_p8_1[] = {
  130084. 1, 4, 4, 6, 6, 7, 7, 9, 9,11,12,13,12, 6, 5, 5,
  130085. 7, 7, 8, 8,10, 9,12,12,12,12, 6, 5, 5, 7, 7, 8,
  130086. 8,10, 9,12,11,11,13,16, 7, 7, 8, 8, 9, 9,10,10,
  130087. 12,12,13,12,16, 7, 7, 8, 7, 9, 9,10,10,11,12,12,
  130088. 13,16,10,10, 8, 8,10,10,11,12,12,12,13,13,16,11,
  130089. 10, 8, 7,11,10,11,11,12,11,13,13,16,16,16,10,10,
  130090. 10,10,11,11,13,12,13,13,16,16,16,11, 9,11, 9,15,
  130091. 13,12,13,13,13,16,16,16,15,13,11,11,12,13,12,12,
  130092. 14,13,16,16,16,14,13,11,11,13,12,14,13,13,13,16,
  130093. 16,16,16,16,13,13,13,12,14,13,14,14,16,16,16,16,
  130094. 16,13,13,12,12,14,14,15,13,
  130095. };
  130096. static float _vq_quantthresh__44c0_s_p8_1[] = {
  130097. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  130098. 42.5, 59.5, 76.5, 93.5,
  130099. };
  130100. static long _vq_quantmap__44c0_s_p8_1[] = {
  130101. 11, 9, 7, 5, 3, 1, 0, 2,
  130102. 4, 6, 8, 10, 12,
  130103. };
  130104. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_1 = {
  130105. _vq_quantthresh__44c0_s_p8_1,
  130106. _vq_quantmap__44c0_s_p8_1,
  130107. 13,
  130108. 13
  130109. };
  130110. static static_codebook _44c0_s_p8_1 = {
  130111. 2, 169,
  130112. _vq_lengthlist__44c0_s_p8_1,
  130113. 1, -522616832, 1620115456, 4, 0,
  130114. _vq_quantlist__44c0_s_p8_1,
  130115. NULL,
  130116. &_vq_auxt__44c0_s_p8_1,
  130117. NULL,
  130118. 0
  130119. };
  130120. static long _vq_quantlist__44c0_s_p8_2[] = {
  130121. 8,
  130122. 7,
  130123. 9,
  130124. 6,
  130125. 10,
  130126. 5,
  130127. 11,
  130128. 4,
  130129. 12,
  130130. 3,
  130131. 13,
  130132. 2,
  130133. 14,
  130134. 1,
  130135. 15,
  130136. 0,
  130137. 16,
  130138. };
  130139. static long _vq_lengthlist__44c0_s_p8_2[] = {
  130140. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  130141. 8,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  130142. 9, 9,10,10,10, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  130143. 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  130144. 9,10, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  130145. 9,10, 9, 9,10,10,10,10, 8, 8, 8, 8, 9, 8, 9, 9,
  130146. 9, 9, 9,10, 9,10,10,10,10, 7, 7, 8, 8, 9, 9, 9,
  130147. 9, 9, 9,10, 9,10,10,10,10,10, 8, 8, 8, 9, 9, 9,
  130148. 9, 9, 9, 9,10,10,10, 9,11,10,10,10,10, 8, 8, 9,
  130149. 9, 9, 9, 9,10, 9, 9, 9,10,10,10,10,11,11, 9, 9,
  130150. 9, 9, 9, 9, 9, 9,10, 9, 9,10,11,10,10,11,11, 9,
  130151. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,11,10,11,11,
  130152. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,10,10,11,
  130153. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  130154. 11,11,11,11, 9,10, 9,10, 9, 9, 9, 9,10, 9,10,11,
  130155. 10,11,10,10,10,10,10, 9, 9, 9,10, 9, 9, 9,10,11,
  130156. 11,10,11,11,10,11,10,10,10, 9, 9, 9, 9,10, 9, 9,
  130157. 10,11,10,11,11,11,11,10,11,10,10, 9,10, 9, 9, 9,
  130158. 10,
  130159. };
  130160. static float _vq_quantthresh__44c0_s_p8_2[] = {
  130161. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  130162. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  130163. };
  130164. static long _vq_quantmap__44c0_s_p8_2[] = {
  130165. 15, 13, 11, 9, 7, 5, 3, 1,
  130166. 0, 2, 4, 6, 8, 10, 12, 14,
  130167. 16,
  130168. };
  130169. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_2 = {
  130170. _vq_quantthresh__44c0_s_p8_2,
  130171. _vq_quantmap__44c0_s_p8_2,
  130172. 17,
  130173. 17
  130174. };
  130175. static static_codebook _44c0_s_p8_2 = {
  130176. 2, 289,
  130177. _vq_lengthlist__44c0_s_p8_2,
  130178. 1, -529530880, 1611661312, 5, 0,
  130179. _vq_quantlist__44c0_s_p8_2,
  130180. NULL,
  130181. &_vq_auxt__44c0_s_p8_2,
  130182. NULL,
  130183. 0
  130184. };
  130185. static long _huff_lengthlist__44c0_s_short[] = {
  130186. 9, 8,12,11,12,13,14,14,16, 6, 1, 5, 6, 6, 9,12,
  130187. 14,17, 9, 4, 5, 9, 7, 9,13,15,16, 8, 5, 8, 6, 8,
  130188. 10,13,17,17, 9, 6, 7, 7, 8, 9,13,15,17,11, 8, 9,
  130189. 9, 9,10,12,16,16,13, 7, 8, 7, 7, 9,12,14,15,13,
  130190. 6, 7, 5, 5, 7,10,13,13,14, 7, 8, 5, 6, 7, 9,10,
  130191. 12,
  130192. };
  130193. static static_codebook _huff_book__44c0_s_short = {
  130194. 2, 81,
  130195. _huff_lengthlist__44c0_s_short,
  130196. 0, 0, 0, 0, 0,
  130197. NULL,
  130198. NULL,
  130199. NULL,
  130200. NULL,
  130201. 0
  130202. };
  130203. static long _huff_lengthlist__44c0_sm_long[] = {
  130204. 5, 4, 9,10, 9,10,11,12,13, 4, 1, 5, 7, 7, 9,11,
  130205. 12,14, 8, 5, 7, 9, 8,10,13,13,13,10, 7, 9, 4, 6,
  130206. 7,10,12,14, 9, 6, 7, 6, 6, 7,10,12,12, 9, 8, 9,
  130207. 7, 6, 7, 8,11,12,11,11,11, 9, 8, 7, 8,10,12,12,
  130208. 13,14,12,11, 9, 9, 9,12,12,17,17,15,16,12,10,11,
  130209. 13,
  130210. };
  130211. static static_codebook _huff_book__44c0_sm_long = {
  130212. 2, 81,
  130213. _huff_lengthlist__44c0_sm_long,
  130214. 0, 0, 0, 0, 0,
  130215. NULL,
  130216. NULL,
  130217. NULL,
  130218. NULL,
  130219. 0
  130220. };
  130221. static long _vq_quantlist__44c0_sm_p1_0[] = {
  130222. 1,
  130223. 0,
  130224. 2,
  130225. };
  130226. static long _vq_lengthlist__44c0_sm_p1_0[] = {
  130227. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  130228. 0, 0, 5, 7, 7, 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, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  130233. 0, 0, 0, 7, 8, 9, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  130238. 0, 0, 0, 0, 7, 9, 9, 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, 0, 0, 0, 0, 0, 0, 0,
  130259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0,
  130264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0,
  130269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  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, 5, 8, 7, 0, 0, 0, 0,
  130273. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0,
  130278. 0, 0, 0, 9,10,10, 0, 0, 0, 0, 0, 0, 9,10,10, 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, 7, 9, 9, 0, 0,
  130283. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130305. 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130310. 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  130319. 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  130324. 0, 0, 0, 0, 0, 9, 9,10, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  130329. 0, 0, 0, 0, 0, 0, 9,10,10, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130637. 0,
  130638. };
  130639. static float _vq_quantthresh__44c0_sm_p1_0[] = {
  130640. -0.5, 0.5,
  130641. };
  130642. static long _vq_quantmap__44c0_sm_p1_0[] = {
  130643. 1, 0, 2,
  130644. };
  130645. static encode_aux_threshmatch _vq_auxt__44c0_sm_p1_0 = {
  130646. _vq_quantthresh__44c0_sm_p1_0,
  130647. _vq_quantmap__44c0_sm_p1_0,
  130648. 3,
  130649. 3
  130650. };
  130651. static static_codebook _44c0_sm_p1_0 = {
  130652. 8, 6561,
  130653. _vq_lengthlist__44c0_sm_p1_0,
  130654. 1, -535822336, 1611661312, 2, 0,
  130655. _vq_quantlist__44c0_sm_p1_0,
  130656. NULL,
  130657. &_vq_auxt__44c0_sm_p1_0,
  130658. NULL,
  130659. 0
  130660. };
  130661. static long _vq_quantlist__44c0_sm_p2_0[] = {
  130662. 2,
  130663. 1,
  130664. 3,
  130665. 0,
  130666. 4,
  130667. };
  130668. static long _vq_lengthlist__44c0_sm_p2_0[] = {
  130669. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  130671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130672. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  130674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130675. 0, 0, 0, 0, 7, 7, 7, 9, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130708. 0,
  130709. };
  130710. static float _vq_quantthresh__44c0_sm_p2_0[] = {
  130711. -1.5, -0.5, 0.5, 1.5,
  130712. };
  130713. static long _vq_quantmap__44c0_sm_p2_0[] = {
  130714. 3, 1, 0, 2, 4,
  130715. };
  130716. static encode_aux_threshmatch _vq_auxt__44c0_sm_p2_0 = {
  130717. _vq_quantthresh__44c0_sm_p2_0,
  130718. _vq_quantmap__44c0_sm_p2_0,
  130719. 5,
  130720. 5
  130721. };
  130722. static static_codebook _44c0_sm_p2_0 = {
  130723. 4, 625,
  130724. _vq_lengthlist__44c0_sm_p2_0,
  130725. 1, -533725184, 1611661312, 3, 0,
  130726. _vq_quantlist__44c0_sm_p2_0,
  130727. NULL,
  130728. &_vq_auxt__44c0_sm_p2_0,
  130729. NULL,
  130730. 0
  130731. };
  130732. static long _vq_quantlist__44c0_sm_p3_0[] = {
  130733. 4,
  130734. 3,
  130735. 5,
  130736. 2,
  130737. 6,
  130738. 1,
  130739. 7,
  130740. 0,
  130741. 8,
  130742. };
  130743. static long _vq_lengthlist__44c0_sm_p3_0[] = {
  130744. 1, 3, 3, 7, 7, 0, 0, 0, 0, 0, 5, 4, 7, 7, 0, 0,
  130745. 0, 0, 0, 5, 5, 7, 7, 0, 0, 0, 0, 0, 6, 7, 8, 8,
  130746. 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  130747. 9,10, 0, 0, 0, 0, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0,
  130748. 0, 0,11,11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130749. 0,
  130750. };
  130751. static float _vq_quantthresh__44c0_sm_p3_0[] = {
  130752. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  130753. };
  130754. static long _vq_quantmap__44c0_sm_p3_0[] = {
  130755. 7, 5, 3, 1, 0, 2, 4, 6,
  130756. 8,
  130757. };
  130758. static encode_aux_threshmatch _vq_auxt__44c0_sm_p3_0 = {
  130759. _vq_quantthresh__44c0_sm_p3_0,
  130760. _vq_quantmap__44c0_sm_p3_0,
  130761. 9,
  130762. 9
  130763. };
  130764. static static_codebook _44c0_sm_p3_0 = {
  130765. 2, 81,
  130766. _vq_lengthlist__44c0_sm_p3_0,
  130767. 1, -531628032, 1611661312, 4, 0,
  130768. _vq_quantlist__44c0_sm_p3_0,
  130769. NULL,
  130770. &_vq_auxt__44c0_sm_p3_0,
  130771. NULL,
  130772. 0
  130773. };
  130774. static long _vq_quantlist__44c0_sm_p4_0[] = {
  130775. 4,
  130776. 3,
  130777. 5,
  130778. 2,
  130779. 6,
  130780. 1,
  130781. 7,
  130782. 0,
  130783. 8,
  130784. };
  130785. static long _vq_lengthlist__44c0_sm_p4_0[] = {
  130786. 1, 4, 3, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 8, 7,
  130787. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  130788. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  130789. 9, 9, 9, 9,11,11, 0, 0, 0, 9, 9, 9, 9,11,11, 0,
  130790. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  130791. 11,
  130792. };
  130793. static float _vq_quantthresh__44c0_sm_p4_0[] = {
  130794. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  130795. };
  130796. static long _vq_quantmap__44c0_sm_p4_0[] = {
  130797. 7, 5, 3, 1, 0, 2, 4, 6,
  130798. 8,
  130799. };
  130800. static encode_aux_threshmatch _vq_auxt__44c0_sm_p4_0 = {
  130801. _vq_quantthresh__44c0_sm_p4_0,
  130802. _vq_quantmap__44c0_sm_p4_0,
  130803. 9,
  130804. 9
  130805. };
  130806. static static_codebook _44c0_sm_p4_0 = {
  130807. 2, 81,
  130808. _vq_lengthlist__44c0_sm_p4_0,
  130809. 1, -531628032, 1611661312, 4, 0,
  130810. _vq_quantlist__44c0_sm_p4_0,
  130811. NULL,
  130812. &_vq_auxt__44c0_sm_p4_0,
  130813. NULL,
  130814. 0
  130815. };
  130816. static long _vq_quantlist__44c0_sm_p5_0[] = {
  130817. 8,
  130818. 7,
  130819. 9,
  130820. 6,
  130821. 10,
  130822. 5,
  130823. 11,
  130824. 4,
  130825. 12,
  130826. 3,
  130827. 13,
  130828. 2,
  130829. 14,
  130830. 1,
  130831. 15,
  130832. 0,
  130833. 16,
  130834. };
  130835. static long _vq_lengthlist__44c0_sm_p5_0[] = {
  130836. 1, 4, 4, 6, 6, 8, 8, 8, 8, 8, 8, 9, 9,10,10,11,
  130837. 11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,11,
  130838. 11,11, 0, 5, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  130839. 11,11,11, 0, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,
  130840. 11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,
  130841. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  130842. 11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  130843. 10,11,11,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  130844. 10,10,11,11,12,12,12,13, 0, 0, 0, 0, 0, 9, 9,10,
  130845. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  130846. 10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  130847. 9,10,10,11,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  130848. 10,10,10,10,11,11,12,12,12,13,13,13, 0, 0, 0, 0,
  130849. 0, 0, 0,10,10,11,11,12,12,12,13,13,13, 0, 0, 0,
  130850. 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0, 0,
  130851. 0, 0, 0, 0, 0,11,11,12,11,12,12,13,13,13,13, 0,
  130852. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  130853. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  130854. 14,
  130855. };
  130856. static float _vq_quantthresh__44c0_sm_p5_0[] = {
  130857. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  130858. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  130859. };
  130860. static long _vq_quantmap__44c0_sm_p5_0[] = {
  130861. 15, 13, 11, 9, 7, 5, 3, 1,
  130862. 0, 2, 4, 6, 8, 10, 12, 14,
  130863. 16,
  130864. };
  130865. static encode_aux_threshmatch _vq_auxt__44c0_sm_p5_0 = {
  130866. _vq_quantthresh__44c0_sm_p5_0,
  130867. _vq_quantmap__44c0_sm_p5_0,
  130868. 17,
  130869. 17
  130870. };
  130871. static static_codebook _44c0_sm_p5_0 = {
  130872. 2, 289,
  130873. _vq_lengthlist__44c0_sm_p5_0,
  130874. 1, -529530880, 1611661312, 5, 0,
  130875. _vq_quantlist__44c0_sm_p5_0,
  130876. NULL,
  130877. &_vq_auxt__44c0_sm_p5_0,
  130878. NULL,
  130879. 0
  130880. };
  130881. static long _vq_quantlist__44c0_sm_p6_0[] = {
  130882. 1,
  130883. 0,
  130884. 2,
  130885. };
  130886. static long _vq_lengthlist__44c0_sm_p6_0[] = {
  130887. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  130888. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  130889. 11,11,10,10, 6, 9, 9,11,11,10,11,10,10, 6, 9, 9,
  130890. 11,10,11,11,10,10, 7,11,10,11,11,11,11,11,11, 6,
  130891. 9, 9,11,10,10,11,11,10, 6, 9, 9,11,10,10,11,10,
  130892. 11,
  130893. };
  130894. static float _vq_quantthresh__44c0_sm_p6_0[] = {
  130895. -5.5, 5.5,
  130896. };
  130897. static long _vq_quantmap__44c0_sm_p6_0[] = {
  130898. 1, 0, 2,
  130899. };
  130900. static encode_aux_threshmatch _vq_auxt__44c0_sm_p6_0 = {
  130901. _vq_quantthresh__44c0_sm_p6_0,
  130902. _vq_quantmap__44c0_sm_p6_0,
  130903. 3,
  130904. 3
  130905. };
  130906. static static_codebook _44c0_sm_p6_0 = {
  130907. 4, 81,
  130908. _vq_lengthlist__44c0_sm_p6_0,
  130909. 1, -529137664, 1618345984, 2, 0,
  130910. _vq_quantlist__44c0_sm_p6_0,
  130911. NULL,
  130912. &_vq_auxt__44c0_sm_p6_0,
  130913. NULL,
  130914. 0
  130915. };
  130916. static long _vq_quantlist__44c0_sm_p6_1[] = {
  130917. 5,
  130918. 4,
  130919. 6,
  130920. 3,
  130921. 7,
  130922. 2,
  130923. 8,
  130924. 1,
  130925. 9,
  130926. 0,
  130927. 10,
  130928. };
  130929. static long _vq_lengthlist__44c0_sm_p6_1[] = {
  130930. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 8, 9, 5, 5, 6, 6,
  130931. 7, 7, 8, 8, 8, 8, 9, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  130932. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  130933. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  130934. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  130935. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  130936. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  130937. 10,10,10, 8, 8, 8, 8, 8, 8,
  130938. };
  130939. static float _vq_quantthresh__44c0_sm_p6_1[] = {
  130940. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  130941. 3.5, 4.5,
  130942. };
  130943. static long _vq_quantmap__44c0_sm_p6_1[] = {
  130944. 9, 7, 5, 3, 1, 0, 2, 4,
  130945. 6, 8, 10,
  130946. };
  130947. static encode_aux_threshmatch _vq_auxt__44c0_sm_p6_1 = {
  130948. _vq_quantthresh__44c0_sm_p6_1,
  130949. _vq_quantmap__44c0_sm_p6_1,
  130950. 11,
  130951. 11
  130952. };
  130953. static static_codebook _44c0_sm_p6_1 = {
  130954. 2, 121,
  130955. _vq_lengthlist__44c0_sm_p6_1,
  130956. 1, -531365888, 1611661312, 4, 0,
  130957. _vq_quantlist__44c0_sm_p6_1,
  130958. NULL,
  130959. &_vq_auxt__44c0_sm_p6_1,
  130960. NULL,
  130961. 0
  130962. };
  130963. static long _vq_quantlist__44c0_sm_p7_0[] = {
  130964. 6,
  130965. 5,
  130966. 7,
  130967. 4,
  130968. 8,
  130969. 3,
  130970. 9,
  130971. 2,
  130972. 10,
  130973. 1,
  130974. 11,
  130975. 0,
  130976. 12,
  130977. };
  130978. static long _vq_lengthlist__44c0_sm_p7_0[] = {
  130979. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  130980. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 6, 5, 7, 7, 8,
  130981. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  130982. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  130983. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  130984. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0, 9,10,
  130985. 10,10,11,11,12,11,12,12, 0, 0, 0,10,10, 9, 9,11,
  130986. 11,12,12,12,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  130987. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  130988. 0, 0, 0, 0,11,12,11,11,13,12,13,13, 0, 0, 0, 0,
  130989. 0,12,12,11,11,13,12,14,14,
  130990. };
  130991. static float _vq_quantthresh__44c0_sm_p7_0[] = {
  130992. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  130993. 12.5, 17.5, 22.5, 27.5,
  130994. };
  130995. static long _vq_quantmap__44c0_sm_p7_0[] = {
  130996. 11, 9, 7, 5, 3, 1, 0, 2,
  130997. 4, 6, 8, 10, 12,
  130998. };
  130999. static encode_aux_threshmatch _vq_auxt__44c0_sm_p7_0 = {
  131000. _vq_quantthresh__44c0_sm_p7_0,
  131001. _vq_quantmap__44c0_sm_p7_0,
  131002. 13,
  131003. 13
  131004. };
  131005. static static_codebook _44c0_sm_p7_0 = {
  131006. 2, 169,
  131007. _vq_lengthlist__44c0_sm_p7_0,
  131008. 1, -526516224, 1616117760, 4, 0,
  131009. _vq_quantlist__44c0_sm_p7_0,
  131010. NULL,
  131011. &_vq_auxt__44c0_sm_p7_0,
  131012. NULL,
  131013. 0
  131014. };
  131015. static long _vq_quantlist__44c0_sm_p7_1[] = {
  131016. 2,
  131017. 1,
  131018. 3,
  131019. 0,
  131020. 4,
  131021. };
  131022. static long _vq_lengthlist__44c0_sm_p7_1[] = {
  131023. 2, 4, 4, 4, 4, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  131024. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  131025. };
  131026. static float _vq_quantthresh__44c0_sm_p7_1[] = {
  131027. -1.5, -0.5, 0.5, 1.5,
  131028. };
  131029. static long _vq_quantmap__44c0_sm_p7_1[] = {
  131030. 3, 1, 0, 2, 4,
  131031. };
  131032. static encode_aux_threshmatch _vq_auxt__44c0_sm_p7_1 = {
  131033. _vq_quantthresh__44c0_sm_p7_1,
  131034. _vq_quantmap__44c0_sm_p7_1,
  131035. 5,
  131036. 5
  131037. };
  131038. static static_codebook _44c0_sm_p7_1 = {
  131039. 2, 25,
  131040. _vq_lengthlist__44c0_sm_p7_1,
  131041. 1, -533725184, 1611661312, 3, 0,
  131042. _vq_quantlist__44c0_sm_p7_1,
  131043. NULL,
  131044. &_vq_auxt__44c0_sm_p7_1,
  131045. NULL,
  131046. 0
  131047. };
  131048. static long _vq_quantlist__44c0_sm_p8_0[] = {
  131049. 4,
  131050. 3,
  131051. 5,
  131052. 2,
  131053. 6,
  131054. 1,
  131055. 7,
  131056. 0,
  131057. 8,
  131058. };
  131059. static long _vq_lengthlist__44c0_sm_p8_0[] = {
  131060. 1, 3, 3,11,11,11,11,11,11, 3, 7, 6,11,11,11,11,
  131061. 11,11, 4, 8, 7,11,11,11,11,11,11,11,11,11,11,11,
  131062. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  131063. 11,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131064. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131065. 12,
  131066. };
  131067. static float _vq_quantthresh__44c0_sm_p8_0[] = {
  131068. -773.5, -552.5, -331.5, -110.5, 110.5, 331.5, 552.5, 773.5,
  131069. };
  131070. static long _vq_quantmap__44c0_sm_p8_0[] = {
  131071. 7, 5, 3, 1, 0, 2, 4, 6,
  131072. 8,
  131073. };
  131074. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_0 = {
  131075. _vq_quantthresh__44c0_sm_p8_0,
  131076. _vq_quantmap__44c0_sm_p8_0,
  131077. 9,
  131078. 9
  131079. };
  131080. static static_codebook _44c0_sm_p8_0 = {
  131081. 2, 81,
  131082. _vq_lengthlist__44c0_sm_p8_0,
  131083. 1, -516186112, 1627103232, 4, 0,
  131084. _vq_quantlist__44c0_sm_p8_0,
  131085. NULL,
  131086. &_vq_auxt__44c0_sm_p8_0,
  131087. NULL,
  131088. 0
  131089. };
  131090. static long _vq_quantlist__44c0_sm_p8_1[] = {
  131091. 6,
  131092. 5,
  131093. 7,
  131094. 4,
  131095. 8,
  131096. 3,
  131097. 9,
  131098. 2,
  131099. 10,
  131100. 1,
  131101. 11,
  131102. 0,
  131103. 12,
  131104. };
  131105. static long _vq_lengthlist__44c0_sm_p8_1[] = {
  131106. 1, 4, 4, 6, 6, 7, 7, 9, 9,10,11,12,12, 6, 5, 5,
  131107. 7, 7, 8, 8,10,10,12,11,12,12, 6, 5, 5, 7, 7, 8,
  131108. 8,10,10,12,11,12,12,17, 7, 7, 8, 8, 9, 9,10,10,
  131109. 12,12,13,13,18, 7, 7, 8, 7, 9, 9,10,10,12,12,12,
  131110. 13,19,10,10, 8, 8,10,10,11,11,12,12,13,14,19,11,
  131111. 10, 8, 7,10,10,11,11,12,12,13,12,19,19,19,10,10,
  131112. 10,10,11,11,12,12,13,13,19,19,19,11, 9,11, 9,14,
  131113. 12,13,12,13,13,19,20,18,13,14,11,11,12,12,13,13,
  131114. 14,13,20,20,20,15,13,11,10,13,11,13,13,14,13,20,
  131115. 20,20,20,20,13,14,12,12,13,13,13,13,20,20,20,20,
  131116. 20,13,13,12,12,16,13,15,13,
  131117. };
  131118. static float _vq_quantthresh__44c0_sm_p8_1[] = {
  131119. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  131120. 42.5, 59.5, 76.5, 93.5,
  131121. };
  131122. static long _vq_quantmap__44c0_sm_p8_1[] = {
  131123. 11, 9, 7, 5, 3, 1, 0, 2,
  131124. 4, 6, 8, 10, 12,
  131125. };
  131126. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_1 = {
  131127. _vq_quantthresh__44c0_sm_p8_1,
  131128. _vq_quantmap__44c0_sm_p8_1,
  131129. 13,
  131130. 13
  131131. };
  131132. static static_codebook _44c0_sm_p8_1 = {
  131133. 2, 169,
  131134. _vq_lengthlist__44c0_sm_p8_1,
  131135. 1, -522616832, 1620115456, 4, 0,
  131136. _vq_quantlist__44c0_sm_p8_1,
  131137. NULL,
  131138. &_vq_auxt__44c0_sm_p8_1,
  131139. NULL,
  131140. 0
  131141. };
  131142. static long _vq_quantlist__44c0_sm_p8_2[] = {
  131143. 8,
  131144. 7,
  131145. 9,
  131146. 6,
  131147. 10,
  131148. 5,
  131149. 11,
  131150. 4,
  131151. 12,
  131152. 3,
  131153. 13,
  131154. 2,
  131155. 14,
  131156. 1,
  131157. 15,
  131158. 0,
  131159. 16,
  131160. };
  131161. static long _vq_lengthlist__44c0_sm_p8_2[] = {
  131162. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  131163. 8,10, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  131164. 9, 9,10, 6, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  131165. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  131166. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  131167. 9,10, 9, 9,10,10,10,11, 8, 8, 8, 8, 9, 9, 9, 9,
  131168. 9, 9, 9,10, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  131169. 9, 9, 9, 9, 9,10,10,11,10,10, 8, 8, 9, 9, 9, 9,
  131170. 9, 9, 9, 9, 9, 9,10,10,10,10,10,11,11, 8, 8, 9,
  131171. 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,11,11,11, 9, 9,
  131172. 9, 9, 9, 9, 9, 9,10, 9,10, 9,11,11,10,11,11, 9,
  131173. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,11,10,11,11,
  131174. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,10,11,11,
  131175. 11,11,11, 9, 9,10, 9, 9, 9, 9, 9, 9, 9,10,11,10,
  131176. 11,11,11,11,10,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  131177. 11,11,11,11,11, 9,10, 9, 9, 9, 9, 9, 9, 9, 9,11,
  131178. 11,10,11,11,11,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  131179. 10,11,10,11,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,
  131180. 9,
  131181. };
  131182. static float _vq_quantthresh__44c0_sm_p8_2[] = {
  131183. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  131184. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  131185. };
  131186. static long _vq_quantmap__44c0_sm_p8_2[] = {
  131187. 15, 13, 11, 9, 7, 5, 3, 1,
  131188. 0, 2, 4, 6, 8, 10, 12, 14,
  131189. 16,
  131190. };
  131191. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_2 = {
  131192. _vq_quantthresh__44c0_sm_p8_2,
  131193. _vq_quantmap__44c0_sm_p8_2,
  131194. 17,
  131195. 17
  131196. };
  131197. static static_codebook _44c0_sm_p8_2 = {
  131198. 2, 289,
  131199. _vq_lengthlist__44c0_sm_p8_2,
  131200. 1, -529530880, 1611661312, 5, 0,
  131201. _vq_quantlist__44c0_sm_p8_2,
  131202. NULL,
  131203. &_vq_auxt__44c0_sm_p8_2,
  131204. NULL,
  131205. 0
  131206. };
  131207. static long _huff_lengthlist__44c0_sm_short[] = {
  131208. 6, 6,12,13,13,14,16,17,17, 4, 2, 5, 8, 7, 9,12,
  131209. 15,15, 9, 4, 5, 9, 7, 9,12,16,18,11, 6, 7, 4, 6,
  131210. 8,11,14,18,10, 5, 6, 5, 5, 7,10,14,17,10, 5, 7,
  131211. 7, 6, 7,10,13,16,11, 5, 7, 7, 7, 8,10,12,15,13,
  131212. 6, 7, 5, 5, 7, 9,12,13,16, 8, 9, 6, 6, 7, 9,10,
  131213. 12,
  131214. };
  131215. static static_codebook _huff_book__44c0_sm_short = {
  131216. 2, 81,
  131217. _huff_lengthlist__44c0_sm_short,
  131218. 0, 0, 0, 0, 0,
  131219. NULL,
  131220. NULL,
  131221. NULL,
  131222. NULL,
  131223. 0
  131224. };
  131225. static long _huff_lengthlist__44c1_s_long[] = {
  131226. 5, 5, 9,10, 9, 9,10,11,12, 5, 1, 5, 6, 6, 7,10,
  131227. 12,14, 9, 5, 6, 8, 8,10,12,14,14,10, 5, 8, 5, 6,
  131228. 8,11,13,14, 9, 5, 7, 6, 6, 8,10,12,11, 9, 7, 9,
  131229. 7, 6, 6, 7,10,10,10, 9,12, 9, 8, 7, 7,10,12,11,
  131230. 11,13,12,10, 9, 8, 9,11,11,14,15,15,13,11, 9, 9,
  131231. 11,
  131232. };
  131233. static static_codebook _huff_book__44c1_s_long = {
  131234. 2, 81,
  131235. _huff_lengthlist__44c1_s_long,
  131236. 0, 0, 0, 0, 0,
  131237. NULL,
  131238. NULL,
  131239. NULL,
  131240. NULL,
  131241. 0
  131242. };
  131243. static long _vq_quantlist__44c1_s_p1_0[] = {
  131244. 1,
  131245. 0,
  131246. 2,
  131247. };
  131248. static long _vq_lengthlist__44c1_s_p1_0[] = {
  131249. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 6, 0, 0, 0, 0,
  131250. 0, 0, 5, 6, 7, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  131255. 0, 0, 0, 7, 8, 8, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  131260. 0, 0, 0, 0, 7, 8, 8, 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, 0, 0, 0, 0, 0, 0, 0,
  131281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0,
  131286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0,
  131291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  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, 4, 7, 7, 0, 0, 0, 0,
  131295. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 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, 7, 8, 8, 0, 0, 0,
  131300. 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 6, 8, 8, 0, 0,
  131305. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131327. 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131332. 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  131341. 0, 0, 0, 0, 7, 8, 9, 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, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8,10, 9, 0,
  131346. 0, 0, 0, 0, 0, 8, 8, 9, 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, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  131351. 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131659. 0,
  131660. };
  131661. static float _vq_quantthresh__44c1_s_p1_0[] = {
  131662. -0.5, 0.5,
  131663. };
  131664. static long _vq_quantmap__44c1_s_p1_0[] = {
  131665. 1, 0, 2,
  131666. };
  131667. static encode_aux_threshmatch _vq_auxt__44c1_s_p1_0 = {
  131668. _vq_quantthresh__44c1_s_p1_0,
  131669. _vq_quantmap__44c1_s_p1_0,
  131670. 3,
  131671. 3
  131672. };
  131673. static static_codebook _44c1_s_p1_0 = {
  131674. 8, 6561,
  131675. _vq_lengthlist__44c1_s_p1_0,
  131676. 1, -535822336, 1611661312, 2, 0,
  131677. _vq_quantlist__44c1_s_p1_0,
  131678. NULL,
  131679. &_vq_auxt__44c1_s_p1_0,
  131680. NULL,
  131681. 0
  131682. };
  131683. static long _vq_quantlist__44c1_s_p2_0[] = {
  131684. 2,
  131685. 1,
  131686. 3,
  131687. 0,
  131688. 4,
  131689. };
  131690. static long _vq_lengthlist__44c1_s_p2_0[] = {
  131691. 2, 3, 4, 6, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  131693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131694. 0, 0, 4, 4, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 8, 8,
  131696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131697. 0, 0, 0, 0, 6, 6, 6, 8, 8, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131730. 0,
  131731. };
  131732. static float _vq_quantthresh__44c1_s_p2_0[] = {
  131733. -1.5, -0.5, 0.5, 1.5,
  131734. };
  131735. static long _vq_quantmap__44c1_s_p2_0[] = {
  131736. 3, 1, 0, 2, 4,
  131737. };
  131738. static encode_aux_threshmatch _vq_auxt__44c1_s_p2_0 = {
  131739. _vq_quantthresh__44c1_s_p2_0,
  131740. _vq_quantmap__44c1_s_p2_0,
  131741. 5,
  131742. 5
  131743. };
  131744. static static_codebook _44c1_s_p2_0 = {
  131745. 4, 625,
  131746. _vq_lengthlist__44c1_s_p2_0,
  131747. 1, -533725184, 1611661312, 3, 0,
  131748. _vq_quantlist__44c1_s_p2_0,
  131749. NULL,
  131750. &_vq_auxt__44c1_s_p2_0,
  131751. NULL,
  131752. 0
  131753. };
  131754. static long _vq_quantlist__44c1_s_p3_0[] = {
  131755. 4,
  131756. 3,
  131757. 5,
  131758. 2,
  131759. 6,
  131760. 1,
  131761. 7,
  131762. 0,
  131763. 8,
  131764. };
  131765. static long _vq_lengthlist__44c1_s_p3_0[] = {
  131766. 1, 3, 2, 7, 7, 0, 0, 0, 0, 0,13,13, 6, 6, 0, 0,
  131767. 0, 0, 0,12, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  131768. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  131769. 8, 9, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  131770. 0, 0,11,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131771. 0,
  131772. };
  131773. static float _vq_quantthresh__44c1_s_p3_0[] = {
  131774. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  131775. };
  131776. static long _vq_quantmap__44c1_s_p3_0[] = {
  131777. 7, 5, 3, 1, 0, 2, 4, 6,
  131778. 8,
  131779. };
  131780. static encode_aux_threshmatch _vq_auxt__44c1_s_p3_0 = {
  131781. _vq_quantthresh__44c1_s_p3_0,
  131782. _vq_quantmap__44c1_s_p3_0,
  131783. 9,
  131784. 9
  131785. };
  131786. static static_codebook _44c1_s_p3_0 = {
  131787. 2, 81,
  131788. _vq_lengthlist__44c1_s_p3_0,
  131789. 1, -531628032, 1611661312, 4, 0,
  131790. _vq_quantlist__44c1_s_p3_0,
  131791. NULL,
  131792. &_vq_auxt__44c1_s_p3_0,
  131793. NULL,
  131794. 0
  131795. };
  131796. static long _vq_quantlist__44c1_s_p4_0[] = {
  131797. 4,
  131798. 3,
  131799. 5,
  131800. 2,
  131801. 6,
  131802. 1,
  131803. 7,
  131804. 0,
  131805. 8,
  131806. };
  131807. static long _vq_lengthlist__44c1_s_p4_0[] = {
  131808. 1, 3, 3, 6, 5, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  131809. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  131810. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  131811. 9, 9, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  131812. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  131813. 11,
  131814. };
  131815. static float _vq_quantthresh__44c1_s_p4_0[] = {
  131816. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  131817. };
  131818. static long _vq_quantmap__44c1_s_p4_0[] = {
  131819. 7, 5, 3, 1, 0, 2, 4, 6,
  131820. 8,
  131821. };
  131822. static encode_aux_threshmatch _vq_auxt__44c1_s_p4_0 = {
  131823. _vq_quantthresh__44c1_s_p4_0,
  131824. _vq_quantmap__44c1_s_p4_0,
  131825. 9,
  131826. 9
  131827. };
  131828. static static_codebook _44c1_s_p4_0 = {
  131829. 2, 81,
  131830. _vq_lengthlist__44c1_s_p4_0,
  131831. 1, -531628032, 1611661312, 4, 0,
  131832. _vq_quantlist__44c1_s_p4_0,
  131833. NULL,
  131834. &_vq_auxt__44c1_s_p4_0,
  131835. NULL,
  131836. 0
  131837. };
  131838. static long _vq_quantlist__44c1_s_p5_0[] = {
  131839. 8,
  131840. 7,
  131841. 9,
  131842. 6,
  131843. 10,
  131844. 5,
  131845. 11,
  131846. 4,
  131847. 12,
  131848. 3,
  131849. 13,
  131850. 2,
  131851. 14,
  131852. 1,
  131853. 15,
  131854. 0,
  131855. 16,
  131856. };
  131857. static long _vq_lengthlist__44c1_s_p5_0[] = {
  131858. 1, 4, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  131859. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  131860. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  131861. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  131862. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  131863. 10,11,11,12,11, 0, 0, 0, 8, 8, 9, 9, 9,10,10,10,
  131864. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10, 9,10,
  131865. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  131866. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  131867. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  131868. 10,10,10,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  131869. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  131870. 10,10,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0,
  131871. 0, 0, 0,10,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  131872. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,13, 0, 0,
  131873. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0,
  131874. 0, 0, 0, 0, 0, 0,12,12,12,12,12,12,13,13,14,14,
  131875. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  131876. 14,
  131877. };
  131878. static float _vq_quantthresh__44c1_s_p5_0[] = {
  131879. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  131880. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  131881. };
  131882. static long _vq_quantmap__44c1_s_p5_0[] = {
  131883. 15, 13, 11, 9, 7, 5, 3, 1,
  131884. 0, 2, 4, 6, 8, 10, 12, 14,
  131885. 16,
  131886. };
  131887. static encode_aux_threshmatch _vq_auxt__44c1_s_p5_0 = {
  131888. _vq_quantthresh__44c1_s_p5_0,
  131889. _vq_quantmap__44c1_s_p5_0,
  131890. 17,
  131891. 17
  131892. };
  131893. static static_codebook _44c1_s_p5_0 = {
  131894. 2, 289,
  131895. _vq_lengthlist__44c1_s_p5_0,
  131896. 1, -529530880, 1611661312, 5, 0,
  131897. _vq_quantlist__44c1_s_p5_0,
  131898. NULL,
  131899. &_vq_auxt__44c1_s_p5_0,
  131900. NULL,
  131901. 0
  131902. };
  131903. static long _vq_quantlist__44c1_s_p6_0[] = {
  131904. 1,
  131905. 0,
  131906. 2,
  131907. };
  131908. static long _vq_lengthlist__44c1_s_p6_0[] = {
  131909. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  131910. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 6,10,10,11,11,
  131911. 11,11,10,10, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  131912. 11,10,11,11,10,10, 7,11,10,11,11,11,12,11,11, 7,
  131913. 9, 9,11,10,10,11,11,10, 6, 9, 9,10,10,10,12,10,
  131914. 11,
  131915. };
  131916. static float _vq_quantthresh__44c1_s_p6_0[] = {
  131917. -5.5, 5.5,
  131918. };
  131919. static long _vq_quantmap__44c1_s_p6_0[] = {
  131920. 1, 0, 2,
  131921. };
  131922. static encode_aux_threshmatch _vq_auxt__44c1_s_p6_0 = {
  131923. _vq_quantthresh__44c1_s_p6_0,
  131924. _vq_quantmap__44c1_s_p6_0,
  131925. 3,
  131926. 3
  131927. };
  131928. static static_codebook _44c1_s_p6_0 = {
  131929. 4, 81,
  131930. _vq_lengthlist__44c1_s_p6_0,
  131931. 1, -529137664, 1618345984, 2, 0,
  131932. _vq_quantlist__44c1_s_p6_0,
  131933. NULL,
  131934. &_vq_auxt__44c1_s_p6_0,
  131935. NULL,
  131936. 0
  131937. };
  131938. static long _vq_quantlist__44c1_s_p6_1[] = {
  131939. 5,
  131940. 4,
  131941. 6,
  131942. 3,
  131943. 7,
  131944. 2,
  131945. 8,
  131946. 1,
  131947. 9,
  131948. 0,
  131949. 10,
  131950. };
  131951. static long _vq_lengthlist__44c1_s_p6_1[] = {
  131952. 2, 3, 3, 6, 6, 7, 7, 7, 7, 8, 8,10,10,10, 6, 6,
  131953. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  131954. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  131955. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  131956. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  131957. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  131958. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  131959. 10,10,10, 8, 8, 8, 8, 8, 8,
  131960. };
  131961. static float _vq_quantthresh__44c1_s_p6_1[] = {
  131962. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  131963. 3.5, 4.5,
  131964. };
  131965. static long _vq_quantmap__44c1_s_p6_1[] = {
  131966. 9, 7, 5, 3, 1, 0, 2, 4,
  131967. 6, 8, 10,
  131968. };
  131969. static encode_aux_threshmatch _vq_auxt__44c1_s_p6_1 = {
  131970. _vq_quantthresh__44c1_s_p6_1,
  131971. _vq_quantmap__44c1_s_p6_1,
  131972. 11,
  131973. 11
  131974. };
  131975. static static_codebook _44c1_s_p6_1 = {
  131976. 2, 121,
  131977. _vq_lengthlist__44c1_s_p6_1,
  131978. 1, -531365888, 1611661312, 4, 0,
  131979. _vq_quantlist__44c1_s_p6_1,
  131980. NULL,
  131981. &_vq_auxt__44c1_s_p6_1,
  131982. NULL,
  131983. 0
  131984. };
  131985. static long _vq_quantlist__44c1_s_p7_0[] = {
  131986. 6,
  131987. 5,
  131988. 7,
  131989. 4,
  131990. 8,
  131991. 3,
  131992. 9,
  131993. 2,
  131994. 10,
  131995. 1,
  131996. 11,
  131997. 0,
  131998. 12,
  131999. };
  132000. static long _vq_lengthlist__44c1_s_p7_0[] = {
  132001. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 9, 7, 5, 6,
  132002. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5, 7, 7, 8,
  132003. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  132004. 10,10,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  132005. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,11,11, 0,13,
  132006. 13, 9, 9, 9, 9,10,10,11,11,11,11, 0, 0, 0,10,10,
  132007. 10,10,11,11,12,11,12,12, 0, 0, 0,10,10,10, 9,11,
  132008. 11,12,11,13,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  132009. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  132010. 0, 0, 0, 0,11,12,11,11,12,12,14,13, 0, 0, 0, 0,
  132011. 0,12,11,11,11,13,10,14,13,
  132012. };
  132013. static float _vq_quantthresh__44c1_s_p7_0[] = {
  132014. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  132015. 12.5, 17.5, 22.5, 27.5,
  132016. };
  132017. static long _vq_quantmap__44c1_s_p7_0[] = {
  132018. 11, 9, 7, 5, 3, 1, 0, 2,
  132019. 4, 6, 8, 10, 12,
  132020. };
  132021. static encode_aux_threshmatch _vq_auxt__44c1_s_p7_0 = {
  132022. _vq_quantthresh__44c1_s_p7_0,
  132023. _vq_quantmap__44c1_s_p7_0,
  132024. 13,
  132025. 13
  132026. };
  132027. static static_codebook _44c1_s_p7_0 = {
  132028. 2, 169,
  132029. _vq_lengthlist__44c1_s_p7_0,
  132030. 1, -526516224, 1616117760, 4, 0,
  132031. _vq_quantlist__44c1_s_p7_0,
  132032. NULL,
  132033. &_vq_auxt__44c1_s_p7_0,
  132034. NULL,
  132035. 0
  132036. };
  132037. static long _vq_quantlist__44c1_s_p7_1[] = {
  132038. 2,
  132039. 1,
  132040. 3,
  132041. 0,
  132042. 4,
  132043. };
  132044. static long _vq_lengthlist__44c1_s_p7_1[] = {
  132045. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  132046. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  132047. };
  132048. static float _vq_quantthresh__44c1_s_p7_1[] = {
  132049. -1.5, -0.5, 0.5, 1.5,
  132050. };
  132051. static long _vq_quantmap__44c1_s_p7_1[] = {
  132052. 3, 1, 0, 2, 4,
  132053. };
  132054. static encode_aux_threshmatch _vq_auxt__44c1_s_p7_1 = {
  132055. _vq_quantthresh__44c1_s_p7_1,
  132056. _vq_quantmap__44c1_s_p7_1,
  132057. 5,
  132058. 5
  132059. };
  132060. static static_codebook _44c1_s_p7_1 = {
  132061. 2, 25,
  132062. _vq_lengthlist__44c1_s_p7_1,
  132063. 1, -533725184, 1611661312, 3, 0,
  132064. _vq_quantlist__44c1_s_p7_1,
  132065. NULL,
  132066. &_vq_auxt__44c1_s_p7_1,
  132067. NULL,
  132068. 0
  132069. };
  132070. static long _vq_quantlist__44c1_s_p8_0[] = {
  132071. 6,
  132072. 5,
  132073. 7,
  132074. 4,
  132075. 8,
  132076. 3,
  132077. 9,
  132078. 2,
  132079. 10,
  132080. 1,
  132081. 11,
  132082. 0,
  132083. 12,
  132084. };
  132085. static long _vq_lengthlist__44c1_s_p8_0[] = {
  132086. 1, 4, 3,10,10,10,10,10,10,10,10,10,10, 4, 8, 6,
  132087. 10,10,10,10,10,10,10,10,10,10, 4, 8, 7,10,10,10,
  132088. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132089. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132090. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132091. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132092. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132093. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132094. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132095. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132096. 10,10,10,10,10,10,10,10,10,
  132097. };
  132098. static float _vq_quantthresh__44c1_s_p8_0[] = {
  132099. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  132100. 552.5, 773.5, 994.5, 1215.5,
  132101. };
  132102. static long _vq_quantmap__44c1_s_p8_0[] = {
  132103. 11, 9, 7, 5, 3, 1, 0, 2,
  132104. 4, 6, 8, 10, 12,
  132105. };
  132106. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_0 = {
  132107. _vq_quantthresh__44c1_s_p8_0,
  132108. _vq_quantmap__44c1_s_p8_0,
  132109. 13,
  132110. 13
  132111. };
  132112. static static_codebook _44c1_s_p8_0 = {
  132113. 2, 169,
  132114. _vq_lengthlist__44c1_s_p8_0,
  132115. 1, -514541568, 1627103232, 4, 0,
  132116. _vq_quantlist__44c1_s_p8_0,
  132117. NULL,
  132118. &_vq_auxt__44c1_s_p8_0,
  132119. NULL,
  132120. 0
  132121. };
  132122. static long _vq_quantlist__44c1_s_p8_1[] = {
  132123. 6,
  132124. 5,
  132125. 7,
  132126. 4,
  132127. 8,
  132128. 3,
  132129. 9,
  132130. 2,
  132131. 10,
  132132. 1,
  132133. 11,
  132134. 0,
  132135. 12,
  132136. };
  132137. static long _vq_lengthlist__44c1_s_p8_1[] = {
  132138. 1, 4, 4, 6, 5, 7, 7, 9, 9,10,10,12,12, 6, 5, 5,
  132139. 7, 7, 8, 8,10,10,12,11,12,12, 6, 5, 5, 7, 7, 8,
  132140. 8,10,10,11,11,12,12,15, 7, 7, 8, 8, 9, 9,11,11,
  132141. 12,12,13,12,15, 8, 8, 8, 7, 9, 9,10,10,12,12,13,
  132142. 13,16,11,10, 8, 8,10,10,11,11,12,12,13,13,16,11,
  132143. 11, 9, 8,11,10,11,11,12,12,13,12,16,16,16,10,11,
  132144. 10,11,12,12,12,12,13,13,16,16,16,11, 9,11, 9,14,
  132145. 12,12,12,13,13,16,16,16,12,14,11,12,12,12,13,13,
  132146. 14,13,16,16,16,15,13,12,10,13,10,13,14,13,13,16,
  132147. 16,16,16,16,13,14,12,13,13,12,13,13,16,16,16,16,
  132148. 16,13,12,12,11,14,12,15,13,
  132149. };
  132150. static float _vq_quantthresh__44c1_s_p8_1[] = {
  132151. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  132152. 42.5, 59.5, 76.5, 93.5,
  132153. };
  132154. static long _vq_quantmap__44c1_s_p8_1[] = {
  132155. 11, 9, 7, 5, 3, 1, 0, 2,
  132156. 4, 6, 8, 10, 12,
  132157. };
  132158. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_1 = {
  132159. _vq_quantthresh__44c1_s_p8_1,
  132160. _vq_quantmap__44c1_s_p8_1,
  132161. 13,
  132162. 13
  132163. };
  132164. static static_codebook _44c1_s_p8_1 = {
  132165. 2, 169,
  132166. _vq_lengthlist__44c1_s_p8_1,
  132167. 1, -522616832, 1620115456, 4, 0,
  132168. _vq_quantlist__44c1_s_p8_1,
  132169. NULL,
  132170. &_vq_auxt__44c1_s_p8_1,
  132171. NULL,
  132172. 0
  132173. };
  132174. static long _vq_quantlist__44c1_s_p8_2[] = {
  132175. 8,
  132176. 7,
  132177. 9,
  132178. 6,
  132179. 10,
  132180. 5,
  132181. 11,
  132182. 4,
  132183. 12,
  132184. 3,
  132185. 13,
  132186. 2,
  132187. 14,
  132188. 1,
  132189. 15,
  132190. 0,
  132191. 16,
  132192. };
  132193. static long _vq_lengthlist__44c1_s_p8_2[] = {
  132194. 2, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  132195. 8,10,10,10, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  132196. 9, 9,10,10,10, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  132197. 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  132198. 9,10, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  132199. 9,10, 9, 9,10,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  132200. 9, 9,10, 9, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  132201. 9, 9, 9, 9, 9,10,10,11,11,11, 8, 8, 9, 9, 9, 9,
  132202. 9, 9, 9, 9, 9, 9,10,10,10,10,11,11,11, 8, 8, 9,
  132203. 9, 9, 9,10, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9,
  132204. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,11, 9,
  132205. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,11,10,11,11,
  132206. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10,10,11,11,
  132207. 11,11,11, 9, 9, 9,10, 9, 9, 9, 9, 9, 9,10,11,11,
  132208. 11,11,11,11,10,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  132209. 11,11,11,11,11, 9,10, 9, 9, 9, 9,10, 9, 9, 9,11,
  132210. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9,10, 9,
  132211. 11,11,10,11,11,11,11,10,11, 9, 9, 9, 9, 9, 9, 9,
  132212. 9,
  132213. };
  132214. static float _vq_quantthresh__44c1_s_p8_2[] = {
  132215. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  132216. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  132217. };
  132218. static long _vq_quantmap__44c1_s_p8_2[] = {
  132219. 15, 13, 11, 9, 7, 5, 3, 1,
  132220. 0, 2, 4, 6, 8, 10, 12, 14,
  132221. 16,
  132222. };
  132223. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_2 = {
  132224. _vq_quantthresh__44c1_s_p8_2,
  132225. _vq_quantmap__44c1_s_p8_2,
  132226. 17,
  132227. 17
  132228. };
  132229. static static_codebook _44c1_s_p8_2 = {
  132230. 2, 289,
  132231. _vq_lengthlist__44c1_s_p8_2,
  132232. 1, -529530880, 1611661312, 5, 0,
  132233. _vq_quantlist__44c1_s_p8_2,
  132234. NULL,
  132235. &_vq_auxt__44c1_s_p8_2,
  132236. NULL,
  132237. 0
  132238. };
  132239. static long _huff_lengthlist__44c1_s_short[] = {
  132240. 6, 8,13,12,13,14,15,16,16, 4, 2, 4, 7, 6, 8,11,
  132241. 13,15,10, 4, 4, 8, 6, 8,11,14,17,11, 5, 6, 5, 6,
  132242. 8,12,14,17,11, 5, 5, 6, 5, 7,10,13,16,12, 6, 7,
  132243. 8, 7, 8,10,13,15,13, 8, 8, 7, 7, 8,10,12,15,15,
  132244. 7, 7, 5, 5, 7, 9,12,14,15, 8, 8, 6, 6, 7, 8,10,
  132245. 11,
  132246. };
  132247. static static_codebook _huff_book__44c1_s_short = {
  132248. 2, 81,
  132249. _huff_lengthlist__44c1_s_short,
  132250. 0, 0, 0, 0, 0,
  132251. NULL,
  132252. NULL,
  132253. NULL,
  132254. NULL,
  132255. 0
  132256. };
  132257. static long _huff_lengthlist__44c1_sm_long[] = {
  132258. 5, 4, 8,10, 9, 9,10,11,12, 4, 2, 5, 6, 6, 8,10,
  132259. 11,13, 8, 4, 6, 8, 7, 9,12,12,14,10, 6, 8, 4, 5,
  132260. 6, 9,11,12, 9, 5, 6, 5, 5, 6, 9,11,11, 9, 7, 9,
  132261. 6, 5, 5, 7,10,10,10, 9,11, 8, 7, 6, 7, 9,11,11,
  132262. 12,13,10,10, 9, 8, 9,11,11,15,15,12,13,11, 9,10,
  132263. 11,
  132264. };
  132265. static static_codebook _huff_book__44c1_sm_long = {
  132266. 2, 81,
  132267. _huff_lengthlist__44c1_sm_long,
  132268. 0, 0, 0, 0, 0,
  132269. NULL,
  132270. NULL,
  132271. NULL,
  132272. NULL,
  132273. 0
  132274. };
  132275. static long _vq_quantlist__44c1_sm_p1_0[] = {
  132276. 1,
  132277. 0,
  132278. 2,
  132279. };
  132280. static long _vq_lengthlist__44c1_sm_p1_0[] = {
  132281. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  132282. 0, 0, 5, 7, 7, 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, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  132287. 0, 0, 0, 7, 8, 9, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  132292. 0, 0, 0, 0, 7, 9, 9, 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, 0, 0, 0, 0, 0, 0, 0,
  132313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0,
  132318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0,
  132323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  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, 5, 8, 7, 0, 0, 0, 0,
  132327. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0,
  132332. 0, 0, 0, 9, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10, 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, 7, 9, 9, 0, 0,
  132337. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132359. 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132364. 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5, 7, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  132373. 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  132378. 0, 0, 0, 0, 0, 8, 9,10, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  132383. 0, 0, 0, 0, 0, 0, 9,10, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132691. 0,
  132692. };
  132693. static float _vq_quantthresh__44c1_sm_p1_0[] = {
  132694. -0.5, 0.5,
  132695. };
  132696. static long _vq_quantmap__44c1_sm_p1_0[] = {
  132697. 1, 0, 2,
  132698. };
  132699. static encode_aux_threshmatch _vq_auxt__44c1_sm_p1_0 = {
  132700. _vq_quantthresh__44c1_sm_p1_0,
  132701. _vq_quantmap__44c1_sm_p1_0,
  132702. 3,
  132703. 3
  132704. };
  132705. static static_codebook _44c1_sm_p1_0 = {
  132706. 8, 6561,
  132707. _vq_lengthlist__44c1_sm_p1_0,
  132708. 1, -535822336, 1611661312, 2, 0,
  132709. _vq_quantlist__44c1_sm_p1_0,
  132710. NULL,
  132711. &_vq_auxt__44c1_sm_p1_0,
  132712. NULL,
  132713. 0
  132714. };
  132715. static long _vq_quantlist__44c1_sm_p2_0[] = {
  132716. 2,
  132717. 1,
  132718. 3,
  132719. 0,
  132720. 4,
  132721. };
  132722. static long _vq_lengthlist__44c1_sm_p2_0[] = {
  132723. 2, 3, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  132725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132726. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  132728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132729. 0, 0, 0, 0, 6, 6, 7, 9, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132762. 0,
  132763. };
  132764. static float _vq_quantthresh__44c1_sm_p2_0[] = {
  132765. -1.5, -0.5, 0.5, 1.5,
  132766. };
  132767. static long _vq_quantmap__44c1_sm_p2_0[] = {
  132768. 3, 1, 0, 2, 4,
  132769. };
  132770. static encode_aux_threshmatch _vq_auxt__44c1_sm_p2_0 = {
  132771. _vq_quantthresh__44c1_sm_p2_0,
  132772. _vq_quantmap__44c1_sm_p2_0,
  132773. 5,
  132774. 5
  132775. };
  132776. static static_codebook _44c1_sm_p2_0 = {
  132777. 4, 625,
  132778. _vq_lengthlist__44c1_sm_p2_0,
  132779. 1, -533725184, 1611661312, 3, 0,
  132780. _vq_quantlist__44c1_sm_p2_0,
  132781. NULL,
  132782. &_vq_auxt__44c1_sm_p2_0,
  132783. NULL,
  132784. 0
  132785. };
  132786. static long _vq_quantlist__44c1_sm_p3_0[] = {
  132787. 4,
  132788. 3,
  132789. 5,
  132790. 2,
  132791. 6,
  132792. 1,
  132793. 7,
  132794. 0,
  132795. 8,
  132796. };
  132797. static long _vq_lengthlist__44c1_sm_p3_0[] = {
  132798. 1, 3, 3, 7, 7, 0, 0, 0, 0, 0, 5, 5, 6, 6, 0, 0,
  132799. 0, 0, 0, 5, 5, 7, 7, 0, 0, 0, 0, 0, 7, 7, 7, 7,
  132800. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  132801. 8, 9, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  132802. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132803. 0,
  132804. };
  132805. static float _vq_quantthresh__44c1_sm_p3_0[] = {
  132806. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  132807. };
  132808. static long _vq_quantmap__44c1_sm_p3_0[] = {
  132809. 7, 5, 3, 1, 0, 2, 4, 6,
  132810. 8,
  132811. };
  132812. static encode_aux_threshmatch _vq_auxt__44c1_sm_p3_0 = {
  132813. _vq_quantthresh__44c1_sm_p3_0,
  132814. _vq_quantmap__44c1_sm_p3_0,
  132815. 9,
  132816. 9
  132817. };
  132818. static static_codebook _44c1_sm_p3_0 = {
  132819. 2, 81,
  132820. _vq_lengthlist__44c1_sm_p3_0,
  132821. 1, -531628032, 1611661312, 4, 0,
  132822. _vq_quantlist__44c1_sm_p3_0,
  132823. NULL,
  132824. &_vq_auxt__44c1_sm_p3_0,
  132825. NULL,
  132826. 0
  132827. };
  132828. static long _vq_quantlist__44c1_sm_p4_0[] = {
  132829. 4,
  132830. 3,
  132831. 5,
  132832. 2,
  132833. 6,
  132834. 1,
  132835. 7,
  132836. 0,
  132837. 8,
  132838. };
  132839. static long _vq_lengthlist__44c1_sm_p4_0[] = {
  132840. 1, 3, 3, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7, 8, 8,
  132841. 9, 9, 0, 6, 6, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  132842. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  132843. 8, 8, 9, 9,11,11, 0, 0, 0, 9, 9, 9, 9,11,11, 0,
  132844. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  132845. 11,
  132846. };
  132847. static float _vq_quantthresh__44c1_sm_p4_0[] = {
  132848. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  132849. };
  132850. static long _vq_quantmap__44c1_sm_p4_0[] = {
  132851. 7, 5, 3, 1, 0, 2, 4, 6,
  132852. 8,
  132853. };
  132854. static encode_aux_threshmatch _vq_auxt__44c1_sm_p4_0 = {
  132855. _vq_quantthresh__44c1_sm_p4_0,
  132856. _vq_quantmap__44c1_sm_p4_0,
  132857. 9,
  132858. 9
  132859. };
  132860. static static_codebook _44c1_sm_p4_0 = {
  132861. 2, 81,
  132862. _vq_lengthlist__44c1_sm_p4_0,
  132863. 1, -531628032, 1611661312, 4, 0,
  132864. _vq_quantlist__44c1_sm_p4_0,
  132865. NULL,
  132866. &_vq_auxt__44c1_sm_p4_0,
  132867. NULL,
  132868. 0
  132869. };
  132870. static long _vq_quantlist__44c1_sm_p5_0[] = {
  132871. 8,
  132872. 7,
  132873. 9,
  132874. 6,
  132875. 10,
  132876. 5,
  132877. 11,
  132878. 4,
  132879. 12,
  132880. 3,
  132881. 13,
  132882. 2,
  132883. 14,
  132884. 1,
  132885. 15,
  132886. 0,
  132887. 16,
  132888. };
  132889. static long _vq_lengthlist__44c1_sm_p5_0[] = {
  132890. 2, 3, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  132891. 11, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,
  132892. 11,11, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,
  132893. 10,11,11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  132894. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  132895. 10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9,10,10,
  132896. 10,11,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9,10,
  132897. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  132898. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  132899. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  132900. 9, 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  132901. 9, 9, 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  132902. 9, 9,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0,
  132903. 0, 0, 0,10,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  132904. 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0, 0,
  132905. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0,
  132906. 0, 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14,
  132907. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  132908. 14,
  132909. };
  132910. static float _vq_quantthresh__44c1_sm_p5_0[] = {
  132911. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  132912. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  132913. };
  132914. static long _vq_quantmap__44c1_sm_p5_0[] = {
  132915. 15, 13, 11, 9, 7, 5, 3, 1,
  132916. 0, 2, 4, 6, 8, 10, 12, 14,
  132917. 16,
  132918. };
  132919. static encode_aux_threshmatch _vq_auxt__44c1_sm_p5_0 = {
  132920. _vq_quantthresh__44c1_sm_p5_0,
  132921. _vq_quantmap__44c1_sm_p5_0,
  132922. 17,
  132923. 17
  132924. };
  132925. static static_codebook _44c1_sm_p5_0 = {
  132926. 2, 289,
  132927. _vq_lengthlist__44c1_sm_p5_0,
  132928. 1, -529530880, 1611661312, 5, 0,
  132929. _vq_quantlist__44c1_sm_p5_0,
  132930. NULL,
  132931. &_vq_auxt__44c1_sm_p5_0,
  132932. NULL,
  132933. 0
  132934. };
  132935. static long _vq_quantlist__44c1_sm_p6_0[] = {
  132936. 1,
  132937. 0,
  132938. 2,
  132939. };
  132940. static long _vq_lengthlist__44c1_sm_p6_0[] = {
  132941. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  132942. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  132943. 11,11,10,10, 6, 9, 9,11,11,10,11,10,10, 6, 9, 9,
  132944. 11,10,11,11,10,10, 7,11,11,11,11,11,11,11,11, 6,
  132945. 9, 9,11,10,10,11,11,10, 6, 9, 9,10,10,10,11,10,
  132946. 11,
  132947. };
  132948. static float _vq_quantthresh__44c1_sm_p6_0[] = {
  132949. -5.5, 5.5,
  132950. };
  132951. static long _vq_quantmap__44c1_sm_p6_0[] = {
  132952. 1, 0, 2,
  132953. };
  132954. static encode_aux_threshmatch _vq_auxt__44c1_sm_p6_0 = {
  132955. _vq_quantthresh__44c1_sm_p6_0,
  132956. _vq_quantmap__44c1_sm_p6_0,
  132957. 3,
  132958. 3
  132959. };
  132960. static static_codebook _44c1_sm_p6_0 = {
  132961. 4, 81,
  132962. _vq_lengthlist__44c1_sm_p6_0,
  132963. 1, -529137664, 1618345984, 2, 0,
  132964. _vq_quantlist__44c1_sm_p6_0,
  132965. NULL,
  132966. &_vq_auxt__44c1_sm_p6_0,
  132967. NULL,
  132968. 0
  132969. };
  132970. static long _vq_quantlist__44c1_sm_p6_1[] = {
  132971. 5,
  132972. 4,
  132973. 6,
  132974. 3,
  132975. 7,
  132976. 2,
  132977. 8,
  132978. 1,
  132979. 9,
  132980. 0,
  132981. 10,
  132982. };
  132983. static long _vq_lengthlist__44c1_sm_p6_1[] = {
  132984. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  132985. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  132986. 8,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  132987. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  132988. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  132989. 8, 8, 8, 8, 8, 8, 9, 8,10,10,10,10,10, 8, 8, 8,
  132990. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  132991. 10,10,10, 8, 8, 8, 8, 8, 8,
  132992. };
  132993. static float _vq_quantthresh__44c1_sm_p6_1[] = {
  132994. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  132995. 3.5, 4.5,
  132996. };
  132997. static long _vq_quantmap__44c1_sm_p6_1[] = {
  132998. 9, 7, 5, 3, 1, 0, 2, 4,
  132999. 6, 8, 10,
  133000. };
  133001. static encode_aux_threshmatch _vq_auxt__44c1_sm_p6_1 = {
  133002. _vq_quantthresh__44c1_sm_p6_1,
  133003. _vq_quantmap__44c1_sm_p6_1,
  133004. 11,
  133005. 11
  133006. };
  133007. static static_codebook _44c1_sm_p6_1 = {
  133008. 2, 121,
  133009. _vq_lengthlist__44c1_sm_p6_1,
  133010. 1, -531365888, 1611661312, 4, 0,
  133011. _vq_quantlist__44c1_sm_p6_1,
  133012. NULL,
  133013. &_vq_auxt__44c1_sm_p6_1,
  133014. NULL,
  133015. 0
  133016. };
  133017. static long _vq_quantlist__44c1_sm_p7_0[] = {
  133018. 6,
  133019. 5,
  133020. 7,
  133021. 4,
  133022. 8,
  133023. 3,
  133024. 9,
  133025. 2,
  133026. 10,
  133027. 1,
  133028. 11,
  133029. 0,
  133030. 12,
  133031. };
  133032. static long _vq_lengthlist__44c1_sm_p7_0[] = {
  133033. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  133034. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 6, 7, 7, 8,
  133035. 8, 8, 8, 9, 9,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  133036. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  133037. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  133038. 13, 9, 9, 9, 9,10,10,11,11,12,12, 0, 0, 0, 9,10,
  133039. 9,10,11,11,12,11,13,12, 0, 0, 0,10,10, 9, 9,11,
  133040. 11,12,12,13,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  133041. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  133042. 0, 0, 0, 0,11,12,11,11,12,13,14,13, 0, 0, 0, 0,
  133043. 0,12,12,11,11,13,12,14,13,
  133044. };
  133045. static float _vq_quantthresh__44c1_sm_p7_0[] = {
  133046. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  133047. 12.5, 17.5, 22.5, 27.5,
  133048. };
  133049. static long _vq_quantmap__44c1_sm_p7_0[] = {
  133050. 11, 9, 7, 5, 3, 1, 0, 2,
  133051. 4, 6, 8, 10, 12,
  133052. };
  133053. static encode_aux_threshmatch _vq_auxt__44c1_sm_p7_0 = {
  133054. _vq_quantthresh__44c1_sm_p7_0,
  133055. _vq_quantmap__44c1_sm_p7_0,
  133056. 13,
  133057. 13
  133058. };
  133059. static static_codebook _44c1_sm_p7_0 = {
  133060. 2, 169,
  133061. _vq_lengthlist__44c1_sm_p7_0,
  133062. 1, -526516224, 1616117760, 4, 0,
  133063. _vq_quantlist__44c1_sm_p7_0,
  133064. NULL,
  133065. &_vq_auxt__44c1_sm_p7_0,
  133066. NULL,
  133067. 0
  133068. };
  133069. static long _vq_quantlist__44c1_sm_p7_1[] = {
  133070. 2,
  133071. 1,
  133072. 3,
  133073. 0,
  133074. 4,
  133075. };
  133076. static long _vq_lengthlist__44c1_sm_p7_1[] = {
  133077. 2, 4, 4, 4, 5, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  133078. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  133079. };
  133080. static float _vq_quantthresh__44c1_sm_p7_1[] = {
  133081. -1.5, -0.5, 0.5, 1.5,
  133082. };
  133083. static long _vq_quantmap__44c1_sm_p7_1[] = {
  133084. 3, 1, 0, 2, 4,
  133085. };
  133086. static encode_aux_threshmatch _vq_auxt__44c1_sm_p7_1 = {
  133087. _vq_quantthresh__44c1_sm_p7_1,
  133088. _vq_quantmap__44c1_sm_p7_1,
  133089. 5,
  133090. 5
  133091. };
  133092. static static_codebook _44c1_sm_p7_1 = {
  133093. 2, 25,
  133094. _vq_lengthlist__44c1_sm_p7_1,
  133095. 1, -533725184, 1611661312, 3, 0,
  133096. _vq_quantlist__44c1_sm_p7_1,
  133097. NULL,
  133098. &_vq_auxt__44c1_sm_p7_1,
  133099. NULL,
  133100. 0
  133101. };
  133102. static long _vq_quantlist__44c1_sm_p8_0[] = {
  133103. 6,
  133104. 5,
  133105. 7,
  133106. 4,
  133107. 8,
  133108. 3,
  133109. 9,
  133110. 2,
  133111. 10,
  133112. 1,
  133113. 11,
  133114. 0,
  133115. 12,
  133116. };
  133117. static long _vq_lengthlist__44c1_sm_p8_0[] = {
  133118. 1, 3, 3,13,13,13,13,13,13,13,13,13,13, 3, 6, 6,
  133119. 13,13,13,13,13,13,13,13,13,13, 4, 8, 7,13,13,13,
  133120. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  133121. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  133122. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  133123. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  133124. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  133125. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  133126. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  133127. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  133128. 13,13,13,13,13,13,13,13,13,
  133129. };
  133130. static float _vq_quantthresh__44c1_sm_p8_0[] = {
  133131. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  133132. 552.5, 773.5, 994.5, 1215.5,
  133133. };
  133134. static long _vq_quantmap__44c1_sm_p8_0[] = {
  133135. 11, 9, 7, 5, 3, 1, 0, 2,
  133136. 4, 6, 8, 10, 12,
  133137. };
  133138. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_0 = {
  133139. _vq_quantthresh__44c1_sm_p8_0,
  133140. _vq_quantmap__44c1_sm_p8_0,
  133141. 13,
  133142. 13
  133143. };
  133144. static static_codebook _44c1_sm_p8_0 = {
  133145. 2, 169,
  133146. _vq_lengthlist__44c1_sm_p8_0,
  133147. 1, -514541568, 1627103232, 4, 0,
  133148. _vq_quantlist__44c1_sm_p8_0,
  133149. NULL,
  133150. &_vq_auxt__44c1_sm_p8_0,
  133151. NULL,
  133152. 0
  133153. };
  133154. static long _vq_quantlist__44c1_sm_p8_1[] = {
  133155. 6,
  133156. 5,
  133157. 7,
  133158. 4,
  133159. 8,
  133160. 3,
  133161. 9,
  133162. 2,
  133163. 10,
  133164. 1,
  133165. 11,
  133166. 0,
  133167. 12,
  133168. };
  133169. static long _vq_lengthlist__44c1_sm_p8_1[] = {
  133170. 1, 4, 4, 6, 6, 7, 7, 9, 9,10,11,12,12, 6, 5, 5,
  133171. 7, 7, 8, 7,10,10,11,11,12,12, 6, 5, 5, 7, 7, 8,
  133172. 8,10,10,11,11,12,12,16, 7, 7, 8, 8, 9, 9,11,11,
  133173. 12,12,13,13,17, 7, 7, 8, 7, 9, 9,11,10,12,12,13,
  133174. 13,19,11,10, 8, 8,10,10,11,11,12,12,13,13,19,11,
  133175. 11, 9, 7,11,10,11,11,12,12,13,12,19,19,19,10,10,
  133176. 10,10,11,12,12,12,13,14,18,19,19,11, 9,11, 9,13,
  133177. 12,12,12,13,13,19,20,19,13,15,11,11,12,12,13,13,
  133178. 14,13,18,19,20,15,13,12,10,13,10,13,13,13,14,20,
  133179. 20,20,20,20,13,14,12,12,13,12,13,13,20,20,20,20,
  133180. 20,13,12,12,12,14,12,14,13,
  133181. };
  133182. static float _vq_quantthresh__44c1_sm_p8_1[] = {
  133183. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  133184. 42.5, 59.5, 76.5, 93.5,
  133185. };
  133186. static long _vq_quantmap__44c1_sm_p8_1[] = {
  133187. 11, 9, 7, 5, 3, 1, 0, 2,
  133188. 4, 6, 8, 10, 12,
  133189. };
  133190. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_1 = {
  133191. _vq_quantthresh__44c1_sm_p8_1,
  133192. _vq_quantmap__44c1_sm_p8_1,
  133193. 13,
  133194. 13
  133195. };
  133196. static static_codebook _44c1_sm_p8_1 = {
  133197. 2, 169,
  133198. _vq_lengthlist__44c1_sm_p8_1,
  133199. 1, -522616832, 1620115456, 4, 0,
  133200. _vq_quantlist__44c1_sm_p8_1,
  133201. NULL,
  133202. &_vq_auxt__44c1_sm_p8_1,
  133203. NULL,
  133204. 0
  133205. };
  133206. static long _vq_quantlist__44c1_sm_p8_2[] = {
  133207. 8,
  133208. 7,
  133209. 9,
  133210. 6,
  133211. 10,
  133212. 5,
  133213. 11,
  133214. 4,
  133215. 12,
  133216. 3,
  133217. 13,
  133218. 2,
  133219. 14,
  133220. 1,
  133221. 15,
  133222. 0,
  133223. 16,
  133224. };
  133225. static long _vq_lengthlist__44c1_sm_p8_2[] = {
  133226. 2, 5, 5, 6, 6, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  133227. 8,10, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  133228. 9, 9,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  133229. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  133230. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  133231. 9, 9, 9, 9, 9,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  133232. 9, 9,10,10, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  133233. 9, 9, 9, 9, 9,10,10,11,10,10, 8, 8, 9, 9, 9, 9,
  133234. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,11,11, 8, 8, 9,
  133235. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9,
  133236. 9, 9, 9, 9, 9, 9,10, 9,10, 9,11,11,11,11,11, 9,
  133237. 8, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,10,11,11,
  133238. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,11,11,
  133239. 11,11,11, 9, 9,10, 9, 9, 9, 9,10, 9,10,10,11,10,
  133240. 11,11,11,11, 9,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  133241. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,
  133242. 11,10,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9,10, 9,
  133243. 10,11,10,11,11,11,11,11,11, 9, 9,10, 9, 9, 9, 9,
  133244. 9,
  133245. };
  133246. static float _vq_quantthresh__44c1_sm_p8_2[] = {
  133247. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  133248. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  133249. };
  133250. static long _vq_quantmap__44c1_sm_p8_2[] = {
  133251. 15, 13, 11, 9, 7, 5, 3, 1,
  133252. 0, 2, 4, 6, 8, 10, 12, 14,
  133253. 16,
  133254. };
  133255. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_2 = {
  133256. _vq_quantthresh__44c1_sm_p8_2,
  133257. _vq_quantmap__44c1_sm_p8_2,
  133258. 17,
  133259. 17
  133260. };
  133261. static static_codebook _44c1_sm_p8_2 = {
  133262. 2, 289,
  133263. _vq_lengthlist__44c1_sm_p8_2,
  133264. 1, -529530880, 1611661312, 5, 0,
  133265. _vq_quantlist__44c1_sm_p8_2,
  133266. NULL,
  133267. &_vq_auxt__44c1_sm_p8_2,
  133268. NULL,
  133269. 0
  133270. };
  133271. static long _huff_lengthlist__44c1_sm_short[] = {
  133272. 4, 7,13,14,14,15,16,18,18, 4, 2, 5, 8, 7, 9,12,
  133273. 15,15,10, 4, 5,10, 6, 8,11,15,17,12, 5, 7, 5, 6,
  133274. 8,11,14,17,11, 5, 6, 6, 5, 6, 9,13,17,12, 6, 7,
  133275. 6, 5, 6, 8,12,14,14, 7, 8, 6, 6, 7, 9,11,14,14,
  133276. 8, 9, 6, 5, 6, 9,11,13,16,10,10, 7, 6, 7, 8,10,
  133277. 11,
  133278. };
  133279. static static_codebook _huff_book__44c1_sm_short = {
  133280. 2, 81,
  133281. _huff_lengthlist__44c1_sm_short,
  133282. 0, 0, 0, 0, 0,
  133283. NULL,
  133284. NULL,
  133285. NULL,
  133286. NULL,
  133287. 0
  133288. };
  133289. static long _huff_lengthlist__44cn1_s_long[] = {
  133290. 4, 4, 7, 8, 7, 8,10,12,17, 3, 1, 6, 6, 7, 8,10,
  133291. 12,15, 7, 6, 9, 9, 9,11,12,14,17, 8, 6, 9, 6, 7,
  133292. 9,11,13,17, 7, 6, 9, 7, 7, 8, 9,12,15, 8, 8,10,
  133293. 8, 7, 7, 7,10,14, 9,10,12,10, 8, 8, 8,10,14,11,
  133294. 13,15,13,12,11,11,12,16,17,18,18,19,20,18,16,16,
  133295. 20,
  133296. };
  133297. static static_codebook _huff_book__44cn1_s_long = {
  133298. 2, 81,
  133299. _huff_lengthlist__44cn1_s_long,
  133300. 0, 0, 0, 0, 0,
  133301. NULL,
  133302. NULL,
  133303. NULL,
  133304. NULL,
  133305. 0
  133306. };
  133307. static long _vq_quantlist__44cn1_s_p1_0[] = {
  133308. 1,
  133309. 0,
  133310. 2,
  133311. };
  133312. static long _vq_lengthlist__44cn1_s_p1_0[] = {
  133313. 1, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  133314. 0, 0, 5, 7, 7, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0,
  133319. 0, 0, 0, 7, 9,10, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7,10, 9, 0, 0,
  133324. 0, 0, 0, 0, 8,10, 9, 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, 0, 0, 0, 0, 0, 0, 0,
  133345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0,
  133350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0,
  133355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  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, 5, 8, 8, 0, 0, 0, 0,
  133359. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8, 9,10, 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, 7,10,10, 0, 0, 0,
  133364. 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0,10,11,11, 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, 7,10,10, 0, 0,
  133369. 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0,10,11,11,
  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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133391. 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133396. 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0,
  133405. 0, 0, 0, 0, 8,10,10, 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, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,11, 0,
  133410. 0, 0, 0, 0, 0, 9, 9,11, 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, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,11,
  133415. 0, 0, 0, 0, 0, 0, 9,11, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133723. 0,
  133724. };
  133725. static float _vq_quantthresh__44cn1_s_p1_0[] = {
  133726. -0.5, 0.5,
  133727. };
  133728. static long _vq_quantmap__44cn1_s_p1_0[] = {
  133729. 1, 0, 2,
  133730. };
  133731. static encode_aux_threshmatch _vq_auxt__44cn1_s_p1_0 = {
  133732. _vq_quantthresh__44cn1_s_p1_0,
  133733. _vq_quantmap__44cn1_s_p1_0,
  133734. 3,
  133735. 3
  133736. };
  133737. static static_codebook _44cn1_s_p1_0 = {
  133738. 8, 6561,
  133739. _vq_lengthlist__44cn1_s_p1_0,
  133740. 1, -535822336, 1611661312, 2, 0,
  133741. _vq_quantlist__44cn1_s_p1_0,
  133742. NULL,
  133743. &_vq_auxt__44cn1_s_p1_0,
  133744. NULL,
  133745. 0
  133746. };
  133747. static long _vq_quantlist__44cn1_s_p2_0[] = {
  133748. 2,
  133749. 1,
  133750. 3,
  133751. 0,
  133752. 4,
  133753. };
  133754. static long _vq_lengthlist__44cn1_s_p2_0[] = {
  133755. 1, 4, 4, 7, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  133757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133758. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  133760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133761. 0, 0, 0, 0, 6, 7, 7, 9, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133794. 0,
  133795. };
  133796. static float _vq_quantthresh__44cn1_s_p2_0[] = {
  133797. -1.5, -0.5, 0.5, 1.5,
  133798. };
  133799. static long _vq_quantmap__44cn1_s_p2_0[] = {
  133800. 3, 1, 0, 2, 4,
  133801. };
  133802. static encode_aux_threshmatch _vq_auxt__44cn1_s_p2_0 = {
  133803. _vq_quantthresh__44cn1_s_p2_0,
  133804. _vq_quantmap__44cn1_s_p2_0,
  133805. 5,
  133806. 5
  133807. };
  133808. static static_codebook _44cn1_s_p2_0 = {
  133809. 4, 625,
  133810. _vq_lengthlist__44cn1_s_p2_0,
  133811. 1, -533725184, 1611661312, 3, 0,
  133812. _vq_quantlist__44cn1_s_p2_0,
  133813. NULL,
  133814. &_vq_auxt__44cn1_s_p2_0,
  133815. NULL,
  133816. 0
  133817. };
  133818. static long _vq_quantlist__44cn1_s_p3_0[] = {
  133819. 4,
  133820. 3,
  133821. 5,
  133822. 2,
  133823. 6,
  133824. 1,
  133825. 7,
  133826. 0,
  133827. 8,
  133828. };
  133829. static long _vq_lengthlist__44cn1_s_p3_0[] = {
  133830. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  133831. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  133832. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  133833. 9, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  133834. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133835. 0,
  133836. };
  133837. static float _vq_quantthresh__44cn1_s_p3_0[] = {
  133838. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  133839. };
  133840. static long _vq_quantmap__44cn1_s_p3_0[] = {
  133841. 7, 5, 3, 1, 0, 2, 4, 6,
  133842. 8,
  133843. };
  133844. static encode_aux_threshmatch _vq_auxt__44cn1_s_p3_0 = {
  133845. _vq_quantthresh__44cn1_s_p3_0,
  133846. _vq_quantmap__44cn1_s_p3_0,
  133847. 9,
  133848. 9
  133849. };
  133850. static static_codebook _44cn1_s_p3_0 = {
  133851. 2, 81,
  133852. _vq_lengthlist__44cn1_s_p3_0,
  133853. 1, -531628032, 1611661312, 4, 0,
  133854. _vq_quantlist__44cn1_s_p3_0,
  133855. NULL,
  133856. &_vq_auxt__44cn1_s_p3_0,
  133857. NULL,
  133858. 0
  133859. };
  133860. static long _vq_quantlist__44cn1_s_p4_0[] = {
  133861. 4,
  133862. 3,
  133863. 5,
  133864. 2,
  133865. 6,
  133866. 1,
  133867. 7,
  133868. 0,
  133869. 8,
  133870. };
  133871. static long _vq_lengthlist__44cn1_s_p4_0[] = {
  133872. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 6, 6, 7, 7,
  133873. 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  133874. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  133875. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  133876. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  133877. 11,
  133878. };
  133879. static float _vq_quantthresh__44cn1_s_p4_0[] = {
  133880. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  133881. };
  133882. static long _vq_quantmap__44cn1_s_p4_0[] = {
  133883. 7, 5, 3, 1, 0, 2, 4, 6,
  133884. 8,
  133885. };
  133886. static encode_aux_threshmatch _vq_auxt__44cn1_s_p4_0 = {
  133887. _vq_quantthresh__44cn1_s_p4_0,
  133888. _vq_quantmap__44cn1_s_p4_0,
  133889. 9,
  133890. 9
  133891. };
  133892. static static_codebook _44cn1_s_p4_0 = {
  133893. 2, 81,
  133894. _vq_lengthlist__44cn1_s_p4_0,
  133895. 1, -531628032, 1611661312, 4, 0,
  133896. _vq_quantlist__44cn1_s_p4_0,
  133897. NULL,
  133898. &_vq_auxt__44cn1_s_p4_0,
  133899. NULL,
  133900. 0
  133901. };
  133902. static long _vq_quantlist__44cn1_s_p5_0[] = {
  133903. 8,
  133904. 7,
  133905. 9,
  133906. 6,
  133907. 10,
  133908. 5,
  133909. 11,
  133910. 4,
  133911. 12,
  133912. 3,
  133913. 13,
  133914. 2,
  133915. 14,
  133916. 1,
  133917. 15,
  133918. 0,
  133919. 16,
  133920. };
  133921. static long _vq_lengthlist__44cn1_s_p5_0[] = {
  133922. 1, 4, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,10,
  133923. 10, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  133924. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  133925. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  133926. 11,11,11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  133927. 10,11,11,11,11, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,10,
  133928. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,
  133929. 10,10,11,11,11,12,12, 0, 0, 0, 9, 9,10, 9,10,10,
  133930. 10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  133931. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  133932. 10,10,10,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  133933. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  133934. 10,10,11,10,11,11,11,12,13,12,13,13, 0, 0, 0, 0,
  133935. 0, 0, 0,11,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  133936. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  133937. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0,
  133938. 0, 0, 0, 0, 0, 0,12,12,12,13,13,13,13,13,14,14,
  133939. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,12,13,13,14,
  133940. 14,
  133941. };
  133942. static float _vq_quantthresh__44cn1_s_p5_0[] = {
  133943. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  133944. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  133945. };
  133946. static long _vq_quantmap__44cn1_s_p5_0[] = {
  133947. 15, 13, 11, 9, 7, 5, 3, 1,
  133948. 0, 2, 4, 6, 8, 10, 12, 14,
  133949. 16,
  133950. };
  133951. static encode_aux_threshmatch _vq_auxt__44cn1_s_p5_0 = {
  133952. _vq_quantthresh__44cn1_s_p5_0,
  133953. _vq_quantmap__44cn1_s_p5_0,
  133954. 17,
  133955. 17
  133956. };
  133957. static static_codebook _44cn1_s_p5_0 = {
  133958. 2, 289,
  133959. _vq_lengthlist__44cn1_s_p5_0,
  133960. 1, -529530880, 1611661312, 5, 0,
  133961. _vq_quantlist__44cn1_s_p5_0,
  133962. NULL,
  133963. &_vq_auxt__44cn1_s_p5_0,
  133964. NULL,
  133965. 0
  133966. };
  133967. static long _vq_quantlist__44cn1_s_p6_0[] = {
  133968. 1,
  133969. 0,
  133970. 2,
  133971. };
  133972. static long _vq_lengthlist__44cn1_s_p6_0[] = {
  133973. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 6, 6,10, 9, 9,11,
  133974. 9, 9, 4, 6, 6,10, 9, 9,10, 9, 9, 7,10,10,11,11,
  133975. 11,12,11,11, 7, 9, 9,11,11,10,11,10,10, 7, 9, 9,
  133976. 11,10,11,11,10,10, 7,10,10,11,11,11,12,11,11, 7,
  133977. 9, 9,11,10,10,11,10,10, 7, 9, 9,11,10,10,11,10,
  133978. 10,
  133979. };
  133980. static float _vq_quantthresh__44cn1_s_p6_0[] = {
  133981. -5.5, 5.5,
  133982. };
  133983. static long _vq_quantmap__44cn1_s_p6_0[] = {
  133984. 1, 0, 2,
  133985. };
  133986. static encode_aux_threshmatch _vq_auxt__44cn1_s_p6_0 = {
  133987. _vq_quantthresh__44cn1_s_p6_0,
  133988. _vq_quantmap__44cn1_s_p6_0,
  133989. 3,
  133990. 3
  133991. };
  133992. static static_codebook _44cn1_s_p6_0 = {
  133993. 4, 81,
  133994. _vq_lengthlist__44cn1_s_p6_0,
  133995. 1, -529137664, 1618345984, 2, 0,
  133996. _vq_quantlist__44cn1_s_p6_0,
  133997. NULL,
  133998. &_vq_auxt__44cn1_s_p6_0,
  133999. NULL,
  134000. 0
  134001. };
  134002. static long _vq_quantlist__44cn1_s_p6_1[] = {
  134003. 5,
  134004. 4,
  134005. 6,
  134006. 3,
  134007. 7,
  134008. 2,
  134009. 8,
  134010. 1,
  134011. 9,
  134012. 0,
  134013. 10,
  134014. };
  134015. static long _vq_lengthlist__44cn1_s_p6_1[] = {
  134016. 1, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,10, 7, 6,
  134017. 8, 8, 8, 8, 8, 8,10,10,10, 7, 6, 7, 7, 8, 8, 8,
  134018. 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  134019. 7, 8, 8, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 9, 9,
  134020. 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,
  134021. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  134022. 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,10,
  134023. 10,10,10, 9, 9, 9, 9, 9, 9,
  134024. };
  134025. static float _vq_quantthresh__44cn1_s_p6_1[] = {
  134026. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  134027. 3.5, 4.5,
  134028. };
  134029. static long _vq_quantmap__44cn1_s_p6_1[] = {
  134030. 9, 7, 5, 3, 1, 0, 2, 4,
  134031. 6, 8, 10,
  134032. };
  134033. static encode_aux_threshmatch _vq_auxt__44cn1_s_p6_1 = {
  134034. _vq_quantthresh__44cn1_s_p6_1,
  134035. _vq_quantmap__44cn1_s_p6_1,
  134036. 11,
  134037. 11
  134038. };
  134039. static static_codebook _44cn1_s_p6_1 = {
  134040. 2, 121,
  134041. _vq_lengthlist__44cn1_s_p6_1,
  134042. 1, -531365888, 1611661312, 4, 0,
  134043. _vq_quantlist__44cn1_s_p6_1,
  134044. NULL,
  134045. &_vq_auxt__44cn1_s_p6_1,
  134046. NULL,
  134047. 0
  134048. };
  134049. static long _vq_quantlist__44cn1_s_p7_0[] = {
  134050. 6,
  134051. 5,
  134052. 7,
  134053. 4,
  134054. 8,
  134055. 3,
  134056. 9,
  134057. 2,
  134058. 10,
  134059. 1,
  134060. 11,
  134061. 0,
  134062. 12,
  134063. };
  134064. static long _vq_lengthlist__44cn1_s_p7_0[] = {
  134065. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  134066. 7, 7, 8, 8, 8, 8, 9, 9,11,11, 7, 5, 5, 7, 7, 8,
  134067. 8, 8, 8, 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  134068. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  134069. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,11,12, 0,13,
  134070. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  134071. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  134072. 11,12,12,13,12, 0, 0, 0,14,14,11,10,11,12,12,13,
  134073. 13,14, 0, 0, 0,15,15,11,11,12,11,12,12,14,13, 0,
  134074. 0, 0, 0, 0,12,12,12,12,13,13,14,14, 0, 0, 0, 0,
  134075. 0,13,13,12,12,13,13,13,14,
  134076. };
  134077. static float _vq_quantthresh__44cn1_s_p7_0[] = {
  134078. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  134079. 12.5, 17.5, 22.5, 27.5,
  134080. };
  134081. static long _vq_quantmap__44cn1_s_p7_0[] = {
  134082. 11, 9, 7, 5, 3, 1, 0, 2,
  134083. 4, 6, 8, 10, 12,
  134084. };
  134085. static encode_aux_threshmatch _vq_auxt__44cn1_s_p7_0 = {
  134086. _vq_quantthresh__44cn1_s_p7_0,
  134087. _vq_quantmap__44cn1_s_p7_0,
  134088. 13,
  134089. 13
  134090. };
  134091. static static_codebook _44cn1_s_p7_0 = {
  134092. 2, 169,
  134093. _vq_lengthlist__44cn1_s_p7_0,
  134094. 1, -526516224, 1616117760, 4, 0,
  134095. _vq_quantlist__44cn1_s_p7_0,
  134096. NULL,
  134097. &_vq_auxt__44cn1_s_p7_0,
  134098. NULL,
  134099. 0
  134100. };
  134101. static long _vq_quantlist__44cn1_s_p7_1[] = {
  134102. 2,
  134103. 1,
  134104. 3,
  134105. 0,
  134106. 4,
  134107. };
  134108. static long _vq_lengthlist__44cn1_s_p7_1[] = {
  134109. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  134110. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  134111. };
  134112. static float _vq_quantthresh__44cn1_s_p7_1[] = {
  134113. -1.5, -0.5, 0.5, 1.5,
  134114. };
  134115. static long _vq_quantmap__44cn1_s_p7_1[] = {
  134116. 3, 1, 0, 2, 4,
  134117. };
  134118. static encode_aux_threshmatch _vq_auxt__44cn1_s_p7_1 = {
  134119. _vq_quantthresh__44cn1_s_p7_1,
  134120. _vq_quantmap__44cn1_s_p7_1,
  134121. 5,
  134122. 5
  134123. };
  134124. static static_codebook _44cn1_s_p7_1 = {
  134125. 2, 25,
  134126. _vq_lengthlist__44cn1_s_p7_1,
  134127. 1, -533725184, 1611661312, 3, 0,
  134128. _vq_quantlist__44cn1_s_p7_1,
  134129. NULL,
  134130. &_vq_auxt__44cn1_s_p7_1,
  134131. NULL,
  134132. 0
  134133. };
  134134. static long _vq_quantlist__44cn1_s_p8_0[] = {
  134135. 2,
  134136. 1,
  134137. 3,
  134138. 0,
  134139. 4,
  134140. };
  134141. static long _vq_lengthlist__44cn1_s_p8_0[] = {
  134142. 1, 7, 7,11,11, 8,11,11,11,11, 4,11, 3,11,11,11,
  134143. 11,11,11,11,11,11,11,11,11,11,11,10,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,10,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, 7,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,10,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,10,
  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, 8,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,11,11,11,11,11,11,11,11,11,
  134162. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134163. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134164. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134165. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134166. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134167. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134168. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134169. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134170. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134171. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134172. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134173. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134174. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134175. 11,11,11,11,11,11,11,12,12,12,12,12,12,12,12,12,
  134176. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  134177. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  134178. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  134179. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  134180. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  134181. 12,
  134182. };
  134183. static float _vq_quantthresh__44cn1_s_p8_0[] = {
  134184. -331.5, -110.5, 110.5, 331.5,
  134185. };
  134186. static long _vq_quantmap__44cn1_s_p8_0[] = {
  134187. 3, 1, 0, 2, 4,
  134188. };
  134189. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_0 = {
  134190. _vq_quantthresh__44cn1_s_p8_0,
  134191. _vq_quantmap__44cn1_s_p8_0,
  134192. 5,
  134193. 5
  134194. };
  134195. static static_codebook _44cn1_s_p8_0 = {
  134196. 4, 625,
  134197. _vq_lengthlist__44cn1_s_p8_0,
  134198. 1, -518283264, 1627103232, 3, 0,
  134199. _vq_quantlist__44cn1_s_p8_0,
  134200. NULL,
  134201. &_vq_auxt__44cn1_s_p8_0,
  134202. NULL,
  134203. 0
  134204. };
  134205. static long _vq_quantlist__44cn1_s_p8_1[] = {
  134206. 6,
  134207. 5,
  134208. 7,
  134209. 4,
  134210. 8,
  134211. 3,
  134212. 9,
  134213. 2,
  134214. 10,
  134215. 1,
  134216. 11,
  134217. 0,
  134218. 12,
  134219. };
  134220. static long _vq_lengthlist__44cn1_s_p8_1[] = {
  134221. 1, 4, 4, 6, 6, 8, 8, 9,10,10,11,11,11, 6, 5, 5,
  134222. 7, 7, 8, 8, 9,10, 9,11,11,12, 5, 5, 5, 7, 7, 8,
  134223. 9,10,10,12,12,14,13,15, 7, 7, 8, 8, 9,10,11,11,
  134224. 10,12,10,11,15, 7, 8, 8, 8, 9, 9,11,11,13,12,12,
  134225. 13,15,10,10, 8, 8,10,10,12,12,11,14,10,10,15,11,
  134226. 11, 8, 8,10,10,12,13,13,14,15,13,15,15,15,10,10,
  134227. 10,10,12,12,13,12,13,10,15,15,15,10,10,11,10,13,
  134228. 11,13,13,15,13,15,15,15,13,13,10,11,11,11,12,10,
  134229. 14,11,15,15,14,14,13,10,10,12,11,13,13,14,14,15,
  134230. 15,15,15,15,11,11,11,11,12,11,15,12,15,15,15,15,
  134231. 15,12,12,11,11,14,12,13,14,
  134232. };
  134233. static float _vq_quantthresh__44cn1_s_p8_1[] = {
  134234. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  134235. 42.5, 59.5, 76.5, 93.5,
  134236. };
  134237. static long _vq_quantmap__44cn1_s_p8_1[] = {
  134238. 11, 9, 7, 5, 3, 1, 0, 2,
  134239. 4, 6, 8, 10, 12,
  134240. };
  134241. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_1 = {
  134242. _vq_quantthresh__44cn1_s_p8_1,
  134243. _vq_quantmap__44cn1_s_p8_1,
  134244. 13,
  134245. 13
  134246. };
  134247. static static_codebook _44cn1_s_p8_1 = {
  134248. 2, 169,
  134249. _vq_lengthlist__44cn1_s_p8_1,
  134250. 1, -522616832, 1620115456, 4, 0,
  134251. _vq_quantlist__44cn1_s_p8_1,
  134252. NULL,
  134253. &_vq_auxt__44cn1_s_p8_1,
  134254. NULL,
  134255. 0
  134256. };
  134257. static long _vq_quantlist__44cn1_s_p8_2[] = {
  134258. 8,
  134259. 7,
  134260. 9,
  134261. 6,
  134262. 10,
  134263. 5,
  134264. 11,
  134265. 4,
  134266. 12,
  134267. 3,
  134268. 13,
  134269. 2,
  134270. 14,
  134271. 1,
  134272. 15,
  134273. 0,
  134274. 16,
  134275. };
  134276. static long _vq_lengthlist__44cn1_s_p8_2[] = {
  134277. 3, 4, 3, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  134278. 9,10,11,11, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  134279. 9, 9,10,10,10, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  134280. 9, 9, 9,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9,
  134281. 9, 9,10, 9,10,11,10, 7, 6, 7, 7, 8, 8, 9, 9, 9,
  134282. 9, 9, 9, 9,10,10,10,11, 7, 7, 8, 8, 8, 8, 9, 9,
  134283. 9, 9, 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 8, 9,
  134284. 9, 9, 9, 9, 9, 9,10,11,11,11, 8, 8, 8, 8, 8, 8,
  134285. 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,11, 8, 8, 8,
  134286. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,11,11, 9, 9,
  134287. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,10,11,11, 9,
  134288. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,11,10,11,11,
  134289. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,
  134290. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,11,11,
  134291. 10,11,11,11, 9,10,10, 9, 9, 9, 9, 9, 9, 9,10,11,
  134292. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  134293. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  134294. 11,11,11,10,11,11,11,11,11, 9, 9, 9,10, 9, 9, 9,
  134295. 9,
  134296. };
  134297. static float _vq_quantthresh__44cn1_s_p8_2[] = {
  134298. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  134299. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  134300. };
  134301. static long _vq_quantmap__44cn1_s_p8_2[] = {
  134302. 15, 13, 11, 9, 7, 5, 3, 1,
  134303. 0, 2, 4, 6, 8, 10, 12, 14,
  134304. 16,
  134305. };
  134306. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_2 = {
  134307. _vq_quantthresh__44cn1_s_p8_2,
  134308. _vq_quantmap__44cn1_s_p8_2,
  134309. 17,
  134310. 17
  134311. };
  134312. static static_codebook _44cn1_s_p8_2 = {
  134313. 2, 289,
  134314. _vq_lengthlist__44cn1_s_p8_2,
  134315. 1, -529530880, 1611661312, 5, 0,
  134316. _vq_quantlist__44cn1_s_p8_2,
  134317. NULL,
  134318. &_vq_auxt__44cn1_s_p8_2,
  134319. NULL,
  134320. 0
  134321. };
  134322. static long _huff_lengthlist__44cn1_s_short[] = {
  134323. 10, 9,12,15,12,13,16,14,16, 7, 1, 5,14, 7,10,13,
  134324. 16,16, 9, 4, 6,16, 8,11,16,16,16,14, 4, 7,16, 9,
  134325. 12,14,16,16,10, 5, 7,14, 9,12,14,15,15,13, 8, 9,
  134326. 14,10,12,13,14,15,13, 9, 9, 7, 6, 8,11,12,12,14,
  134327. 8, 8, 5, 4, 5, 8,11,12,16,10,10, 6, 5, 6, 8, 9,
  134328. 10,
  134329. };
  134330. static static_codebook _huff_book__44cn1_s_short = {
  134331. 2, 81,
  134332. _huff_lengthlist__44cn1_s_short,
  134333. 0, 0, 0, 0, 0,
  134334. NULL,
  134335. NULL,
  134336. NULL,
  134337. NULL,
  134338. 0
  134339. };
  134340. static long _huff_lengthlist__44cn1_sm_long[] = {
  134341. 3, 3, 8, 8, 8, 8,10,12,14, 3, 2, 6, 7, 7, 8,10,
  134342. 12,16, 7, 6, 7, 9, 8,10,12,14,16, 8, 6, 8, 4, 5,
  134343. 7, 9,11,13, 7, 6, 8, 5, 6, 7, 9,11,14, 8, 8,10,
  134344. 7, 7, 6, 8,10,13, 9,11,12, 9, 9, 7, 8,10,12,10,
  134345. 13,15,11,11,10, 9,10,13,13,16,17,14,15,14,13,14,
  134346. 17,
  134347. };
  134348. static static_codebook _huff_book__44cn1_sm_long = {
  134349. 2, 81,
  134350. _huff_lengthlist__44cn1_sm_long,
  134351. 0, 0, 0, 0, 0,
  134352. NULL,
  134353. NULL,
  134354. NULL,
  134355. NULL,
  134356. 0
  134357. };
  134358. static long _vq_quantlist__44cn1_sm_p1_0[] = {
  134359. 1,
  134360. 0,
  134361. 2,
  134362. };
  134363. static long _vq_lengthlist__44cn1_sm_p1_0[] = {
  134364. 1, 4, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  134365. 0, 0, 5, 7, 7, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0,
  134370. 0, 0, 0, 7, 8, 9, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  134375. 0, 0, 0, 0, 8, 9, 9, 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, 0, 0, 0, 0, 0, 0, 0,
  134396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0,
  134401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0,
  134406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  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, 5, 8, 8, 0, 0, 0, 0,
  134410. 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 7,10, 9, 0, 0, 0,
  134415. 0, 0, 0, 9, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10, 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, 7, 9, 9, 0, 0,
  134420. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134442. 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134447. 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  134456. 0, 0, 0, 0, 8, 9,10, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  134461. 0, 0, 0, 0, 0, 8, 9,10, 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, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10,
  134466. 0, 0, 0, 0, 0, 0, 9,10, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134774. 0,
  134775. };
  134776. static float _vq_quantthresh__44cn1_sm_p1_0[] = {
  134777. -0.5, 0.5,
  134778. };
  134779. static long _vq_quantmap__44cn1_sm_p1_0[] = {
  134780. 1, 0, 2,
  134781. };
  134782. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p1_0 = {
  134783. _vq_quantthresh__44cn1_sm_p1_0,
  134784. _vq_quantmap__44cn1_sm_p1_0,
  134785. 3,
  134786. 3
  134787. };
  134788. static static_codebook _44cn1_sm_p1_0 = {
  134789. 8, 6561,
  134790. _vq_lengthlist__44cn1_sm_p1_0,
  134791. 1, -535822336, 1611661312, 2, 0,
  134792. _vq_quantlist__44cn1_sm_p1_0,
  134793. NULL,
  134794. &_vq_auxt__44cn1_sm_p1_0,
  134795. NULL,
  134796. 0
  134797. };
  134798. static long _vq_quantlist__44cn1_sm_p2_0[] = {
  134799. 2,
  134800. 1,
  134801. 3,
  134802. 0,
  134803. 4,
  134804. };
  134805. static long _vq_lengthlist__44cn1_sm_p2_0[] = {
  134806. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  134808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134809. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  134811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134812. 0, 0, 0, 0, 7, 7, 7, 9, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134845. 0,
  134846. };
  134847. static float _vq_quantthresh__44cn1_sm_p2_0[] = {
  134848. -1.5, -0.5, 0.5, 1.5,
  134849. };
  134850. static long _vq_quantmap__44cn1_sm_p2_0[] = {
  134851. 3, 1, 0, 2, 4,
  134852. };
  134853. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p2_0 = {
  134854. _vq_quantthresh__44cn1_sm_p2_0,
  134855. _vq_quantmap__44cn1_sm_p2_0,
  134856. 5,
  134857. 5
  134858. };
  134859. static static_codebook _44cn1_sm_p2_0 = {
  134860. 4, 625,
  134861. _vq_lengthlist__44cn1_sm_p2_0,
  134862. 1, -533725184, 1611661312, 3, 0,
  134863. _vq_quantlist__44cn1_sm_p2_0,
  134864. NULL,
  134865. &_vq_auxt__44cn1_sm_p2_0,
  134866. NULL,
  134867. 0
  134868. };
  134869. static long _vq_quantlist__44cn1_sm_p3_0[] = {
  134870. 4,
  134871. 3,
  134872. 5,
  134873. 2,
  134874. 6,
  134875. 1,
  134876. 7,
  134877. 0,
  134878. 8,
  134879. };
  134880. static long _vq_lengthlist__44cn1_sm_p3_0[] = {
  134881. 1, 3, 4, 7, 7, 0, 0, 0, 0, 0, 4, 4, 7, 7, 0, 0,
  134882. 0, 0, 0, 4, 5, 7, 7, 0, 0, 0, 0, 0, 6, 7, 8, 8,
  134883. 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  134884. 9, 9, 0, 0, 0, 0, 0, 0, 0,10, 9, 0, 0, 0, 0, 0,
  134885. 0, 0,11,11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134886. 0,
  134887. };
  134888. static float _vq_quantthresh__44cn1_sm_p3_0[] = {
  134889. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  134890. };
  134891. static long _vq_quantmap__44cn1_sm_p3_0[] = {
  134892. 7, 5, 3, 1, 0, 2, 4, 6,
  134893. 8,
  134894. };
  134895. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p3_0 = {
  134896. _vq_quantthresh__44cn1_sm_p3_0,
  134897. _vq_quantmap__44cn1_sm_p3_0,
  134898. 9,
  134899. 9
  134900. };
  134901. static static_codebook _44cn1_sm_p3_0 = {
  134902. 2, 81,
  134903. _vq_lengthlist__44cn1_sm_p3_0,
  134904. 1, -531628032, 1611661312, 4, 0,
  134905. _vq_quantlist__44cn1_sm_p3_0,
  134906. NULL,
  134907. &_vq_auxt__44cn1_sm_p3_0,
  134908. NULL,
  134909. 0
  134910. };
  134911. static long _vq_quantlist__44cn1_sm_p4_0[] = {
  134912. 4,
  134913. 3,
  134914. 5,
  134915. 2,
  134916. 6,
  134917. 1,
  134918. 7,
  134919. 0,
  134920. 8,
  134921. };
  134922. static long _vq_lengthlist__44cn1_sm_p4_0[] = {
  134923. 1, 4, 3, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 8, 7,
  134924. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  134925. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  134926. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  134927. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  134928. 11,
  134929. };
  134930. static float _vq_quantthresh__44cn1_sm_p4_0[] = {
  134931. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  134932. };
  134933. static long _vq_quantmap__44cn1_sm_p4_0[] = {
  134934. 7, 5, 3, 1, 0, 2, 4, 6,
  134935. 8,
  134936. };
  134937. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p4_0 = {
  134938. _vq_quantthresh__44cn1_sm_p4_0,
  134939. _vq_quantmap__44cn1_sm_p4_0,
  134940. 9,
  134941. 9
  134942. };
  134943. static static_codebook _44cn1_sm_p4_0 = {
  134944. 2, 81,
  134945. _vq_lengthlist__44cn1_sm_p4_0,
  134946. 1, -531628032, 1611661312, 4, 0,
  134947. _vq_quantlist__44cn1_sm_p4_0,
  134948. NULL,
  134949. &_vq_auxt__44cn1_sm_p4_0,
  134950. NULL,
  134951. 0
  134952. };
  134953. static long _vq_quantlist__44cn1_sm_p5_0[] = {
  134954. 8,
  134955. 7,
  134956. 9,
  134957. 6,
  134958. 10,
  134959. 5,
  134960. 11,
  134961. 4,
  134962. 12,
  134963. 3,
  134964. 13,
  134965. 2,
  134966. 14,
  134967. 1,
  134968. 15,
  134969. 0,
  134970. 16,
  134971. };
  134972. static long _vq_lengthlist__44cn1_sm_p5_0[] = {
  134973. 1, 4, 4, 6, 6, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,
  134974. 11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  134975. 12,12, 0, 6, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  134976. 11,12,12, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  134977. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,11,
  134978. 11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  134979. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  134980. 10,11,11,12,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  134981. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  134982. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  134983. 10,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0, 0, 9,
  134984. 9,10,10,11,11,12,12,12,13,13,13, 0, 0, 0, 0, 0,
  134985. 10,10,11,11,11,11,12,12,13,13,14,14, 0, 0, 0, 0,
  134986. 0, 0, 0,11,11,11,11,12,12,13,13,14,14, 0, 0, 0,
  134987. 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0, 0,
  134988. 0, 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0,
  134989. 0, 0, 0, 0, 0, 0,12,12,12,13,13,13,14,14,14,14,
  134990. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,14,14,14,
  134991. 14,
  134992. };
  134993. static float _vq_quantthresh__44cn1_sm_p5_0[] = {
  134994. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  134995. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  134996. };
  134997. static long _vq_quantmap__44cn1_sm_p5_0[] = {
  134998. 15, 13, 11, 9, 7, 5, 3, 1,
  134999. 0, 2, 4, 6, 8, 10, 12, 14,
  135000. 16,
  135001. };
  135002. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p5_0 = {
  135003. _vq_quantthresh__44cn1_sm_p5_0,
  135004. _vq_quantmap__44cn1_sm_p5_0,
  135005. 17,
  135006. 17
  135007. };
  135008. static static_codebook _44cn1_sm_p5_0 = {
  135009. 2, 289,
  135010. _vq_lengthlist__44cn1_sm_p5_0,
  135011. 1, -529530880, 1611661312, 5, 0,
  135012. _vq_quantlist__44cn1_sm_p5_0,
  135013. NULL,
  135014. &_vq_auxt__44cn1_sm_p5_0,
  135015. NULL,
  135016. 0
  135017. };
  135018. static long _vq_quantlist__44cn1_sm_p6_0[] = {
  135019. 1,
  135020. 0,
  135021. 2,
  135022. };
  135023. static long _vq_lengthlist__44cn1_sm_p6_0[] = {
  135024. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 6,10, 9, 9,11,
  135025. 9, 9, 4, 6, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  135026. 11,11,11,10, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  135027. 11,10,11,11,10,10, 7,11,11,11,11,11,12,11,11, 7,
  135028. 9, 9,11,10,10,12,10,10, 7, 9, 9,11,10,10,11,10,
  135029. 10,
  135030. };
  135031. static float _vq_quantthresh__44cn1_sm_p6_0[] = {
  135032. -5.5, 5.5,
  135033. };
  135034. static long _vq_quantmap__44cn1_sm_p6_0[] = {
  135035. 1, 0, 2,
  135036. };
  135037. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p6_0 = {
  135038. _vq_quantthresh__44cn1_sm_p6_0,
  135039. _vq_quantmap__44cn1_sm_p6_0,
  135040. 3,
  135041. 3
  135042. };
  135043. static static_codebook _44cn1_sm_p6_0 = {
  135044. 4, 81,
  135045. _vq_lengthlist__44cn1_sm_p6_0,
  135046. 1, -529137664, 1618345984, 2, 0,
  135047. _vq_quantlist__44cn1_sm_p6_0,
  135048. NULL,
  135049. &_vq_auxt__44cn1_sm_p6_0,
  135050. NULL,
  135051. 0
  135052. };
  135053. static long _vq_quantlist__44cn1_sm_p6_1[] = {
  135054. 5,
  135055. 4,
  135056. 6,
  135057. 3,
  135058. 7,
  135059. 2,
  135060. 8,
  135061. 1,
  135062. 9,
  135063. 0,
  135064. 10,
  135065. };
  135066. static long _vq_lengthlist__44cn1_sm_p6_1[] = {
  135067. 2, 4, 4, 5, 5, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  135068. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  135069. 8,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  135070. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  135071. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  135072. 8, 8, 8, 8, 8, 8, 9, 9,10,10,10,10,10, 8, 8, 8,
  135073. 8, 9, 9,10,10,10,10,10, 9, 9, 9, 9, 8, 9,10,10,
  135074. 10,10,10, 8, 9, 8, 8, 9, 8,
  135075. };
  135076. static float _vq_quantthresh__44cn1_sm_p6_1[] = {
  135077. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  135078. 3.5, 4.5,
  135079. };
  135080. static long _vq_quantmap__44cn1_sm_p6_1[] = {
  135081. 9, 7, 5, 3, 1, 0, 2, 4,
  135082. 6, 8, 10,
  135083. };
  135084. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p6_1 = {
  135085. _vq_quantthresh__44cn1_sm_p6_1,
  135086. _vq_quantmap__44cn1_sm_p6_1,
  135087. 11,
  135088. 11
  135089. };
  135090. static static_codebook _44cn1_sm_p6_1 = {
  135091. 2, 121,
  135092. _vq_lengthlist__44cn1_sm_p6_1,
  135093. 1, -531365888, 1611661312, 4, 0,
  135094. _vq_quantlist__44cn1_sm_p6_1,
  135095. NULL,
  135096. &_vq_auxt__44cn1_sm_p6_1,
  135097. NULL,
  135098. 0
  135099. };
  135100. static long _vq_quantlist__44cn1_sm_p7_0[] = {
  135101. 6,
  135102. 5,
  135103. 7,
  135104. 4,
  135105. 8,
  135106. 3,
  135107. 9,
  135108. 2,
  135109. 10,
  135110. 1,
  135111. 11,
  135112. 0,
  135113. 12,
  135114. };
  135115. static long _vq_lengthlist__44cn1_sm_p7_0[] = {
  135116. 1, 4, 4, 6, 6, 7, 7, 7, 7, 9, 9,10,10, 7, 5, 5,
  135117. 7, 7, 8, 8, 8, 8,10, 9,11,10, 7, 5, 5, 7, 7, 8,
  135118. 8, 8, 8, 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  135119. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  135120. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,12,12, 0,13,
  135121. 13, 9, 9, 9, 9,10,10,11,11,12,12, 0, 0, 0,10,10,
  135122. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  135123. 11,12,12,12,12, 0, 0, 0,14,14,11,11,11,11,12,13,
  135124. 13,13, 0, 0, 0,14,14,11,10,11,11,12,12,13,13, 0,
  135125. 0, 0, 0, 0,12,12,12,12,13,13,13,14, 0, 0, 0, 0,
  135126. 0,13,12,12,12,13,13,13,14,
  135127. };
  135128. static float _vq_quantthresh__44cn1_sm_p7_0[] = {
  135129. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  135130. 12.5, 17.5, 22.5, 27.5,
  135131. };
  135132. static long _vq_quantmap__44cn1_sm_p7_0[] = {
  135133. 11, 9, 7, 5, 3, 1, 0, 2,
  135134. 4, 6, 8, 10, 12,
  135135. };
  135136. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p7_0 = {
  135137. _vq_quantthresh__44cn1_sm_p7_0,
  135138. _vq_quantmap__44cn1_sm_p7_0,
  135139. 13,
  135140. 13
  135141. };
  135142. static static_codebook _44cn1_sm_p7_0 = {
  135143. 2, 169,
  135144. _vq_lengthlist__44cn1_sm_p7_0,
  135145. 1, -526516224, 1616117760, 4, 0,
  135146. _vq_quantlist__44cn1_sm_p7_0,
  135147. NULL,
  135148. &_vq_auxt__44cn1_sm_p7_0,
  135149. NULL,
  135150. 0
  135151. };
  135152. static long _vq_quantlist__44cn1_sm_p7_1[] = {
  135153. 2,
  135154. 1,
  135155. 3,
  135156. 0,
  135157. 4,
  135158. };
  135159. static long _vq_lengthlist__44cn1_sm_p7_1[] = {
  135160. 2, 4, 4, 4, 5, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  135161. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  135162. };
  135163. static float _vq_quantthresh__44cn1_sm_p7_1[] = {
  135164. -1.5, -0.5, 0.5, 1.5,
  135165. };
  135166. static long _vq_quantmap__44cn1_sm_p7_1[] = {
  135167. 3, 1, 0, 2, 4,
  135168. };
  135169. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p7_1 = {
  135170. _vq_quantthresh__44cn1_sm_p7_1,
  135171. _vq_quantmap__44cn1_sm_p7_1,
  135172. 5,
  135173. 5
  135174. };
  135175. static static_codebook _44cn1_sm_p7_1 = {
  135176. 2, 25,
  135177. _vq_lengthlist__44cn1_sm_p7_1,
  135178. 1, -533725184, 1611661312, 3, 0,
  135179. _vq_quantlist__44cn1_sm_p7_1,
  135180. NULL,
  135181. &_vq_auxt__44cn1_sm_p7_1,
  135182. NULL,
  135183. 0
  135184. };
  135185. static long _vq_quantlist__44cn1_sm_p8_0[] = {
  135186. 4,
  135187. 3,
  135188. 5,
  135189. 2,
  135190. 6,
  135191. 1,
  135192. 7,
  135193. 0,
  135194. 8,
  135195. };
  135196. static long _vq_lengthlist__44cn1_sm_p8_0[] = {
  135197. 1, 4, 4,12,11,13,13,14,14, 4, 7, 7,11,13,14,14,
  135198. 14,14, 3, 8, 3,14,14,14,14,14,14,14,10,12,14,14,
  135199. 14,14,14,14,14,14, 5,14, 8,14,14,14,14,14,12,14,
  135200. 13,14,14,14,14,14,14,14,13,14,10,14,14,14,14,14,
  135201. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  135202. 14,
  135203. };
  135204. static float _vq_quantthresh__44cn1_sm_p8_0[] = {
  135205. -773.5, -552.5, -331.5, -110.5, 110.5, 331.5, 552.5, 773.5,
  135206. };
  135207. static long _vq_quantmap__44cn1_sm_p8_0[] = {
  135208. 7, 5, 3, 1, 0, 2, 4, 6,
  135209. 8,
  135210. };
  135211. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_0 = {
  135212. _vq_quantthresh__44cn1_sm_p8_0,
  135213. _vq_quantmap__44cn1_sm_p8_0,
  135214. 9,
  135215. 9
  135216. };
  135217. static static_codebook _44cn1_sm_p8_0 = {
  135218. 2, 81,
  135219. _vq_lengthlist__44cn1_sm_p8_0,
  135220. 1, -516186112, 1627103232, 4, 0,
  135221. _vq_quantlist__44cn1_sm_p8_0,
  135222. NULL,
  135223. &_vq_auxt__44cn1_sm_p8_0,
  135224. NULL,
  135225. 0
  135226. };
  135227. static long _vq_quantlist__44cn1_sm_p8_1[] = {
  135228. 6,
  135229. 5,
  135230. 7,
  135231. 4,
  135232. 8,
  135233. 3,
  135234. 9,
  135235. 2,
  135236. 10,
  135237. 1,
  135238. 11,
  135239. 0,
  135240. 12,
  135241. };
  135242. static long _vq_lengthlist__44cn1_sm_p8_1[] = {
  135243. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,11,11,11, 6, 5, 5,
  135244. 7, 7, 8, 8,10,10,10,11,11,11, 6, 5, 5, 7, 7, 8,
  135245. 8,10,10,11,12,12,12,14, 7, 7, 7, 8, 9, 9,11,11,
  135246. 11,12,11,12,17, 7, 7, 8, 7, 9, 9,11,11,12,12,12,
  135247. 12,14,11,11, 8, 8,10,10,11,12,12,13,11,12,14,11,
  135248. 11, 8, 8,10,10,11,12,12,13,13,12,14,15,14,10,10,
  135249. 10,10,11,12,12,12,12,11,14,13,16,10,10,10, 9,12,
  135250. 11,12,12,13,14,14,15,14,14,13,10,10,11,11,12,11,
  135251. 13,11,14,12,15,13,14,11,10,12,10,12,12,13,13,13,
  135252. 13,14,15,15,12,12,11,11,12,11,13,12,14,14,14,14,
  135253. 17,12,12,11,10,13,11,13,13,
  135254. };
  135255. static float _vq_quantthresh__44cn1_sm_p8_1[] = {
  135256. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  135257. 42.5, 59.5, 76.5, 93.5,
  135258. };
  135259. static long _vq_quantmap__44cn1_sm_p8_1[] = {
  135260. 11, 9, 7, 5, 3, 1, 0, 2,
  135261. 4, 6, 8, 10, 12,
  135262. };
  135263. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_1 = {
  135264. _vq_quantthresh__44cn1_sm_p8_1,
  135265. _vq_quantmap__44cn1_sm_p8_1,
  135266. 13,
  135267. 13
  135268. };
  135269. static static_codebook _44cn1_sm_p8_1 = {
  135270. 2, 169,
  135271. _vq_lengthlist__44cn1_sm_p8_1,
  135272. 1, -522616832, 1620115456, 4, 0,
  135273. _vq_quantlist__44cn1_sm_p8_1,
  135274. NULL,
  135275. &_vq_auxt__44cn1_sm_p8_1,
  135276. NULL,
  135277. 0
  135278. };
  135279. static long _vq_quantlist__44cn1_sm_p8_2[] = {
  135280. 8,
  135281. 7,
  135282. 9,
  135283. 6,
  135284. 10,
  135285. 5,
  135286. 11,
  135287. 4,
  135288. 12,
  135289. 3,
  135290. 13,
  135291. 2,
  135292. 14,
  135293. 1,
  135294. 15,
  135295. 0,
  135296. 16,
  135297. };
  135298. static long _vq_lengthlist__44cn1_sm_p8_2[] = {
  135299. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  135300. 9,10, 6, 6, 6, 6, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  135301. 9, 9,10, 6, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  135302. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  135303. 9, 9, 9, 9,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9,
  135304. 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 8, 8, 9, 9,
  135305. 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 8, 8, 9,
  135306. 9, 9, 9, 9, 9, 9, 9,11,10,11, 8, 8, 8, 8, 8, 8,
  135307. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,11,11, 8, 8, 8,
  135308. 8, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,11, 9, 9,
  135309. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,10,11,11, 9,
  135310. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,10,11,11,
  135311. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,
  135312. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,
  135313. 11,11,11,11, 9,10,10,10, 9, 9, 9, 9, 9, 9,11,10,
  135314. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  135315. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  135316. 10,11,11,11,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,
  135317. 9,
  135318. };
  135319. static float _vq_quantthresh__44cn1_sm_p8_2[] = {
  135320. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  135321. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  135322. };
  135323. static long _vq_quantmap__44cn1_sm_p8_2[] = {
  135324. 15, 13, 11, 9, 7, 5, 3, 1,
  135325. 0, 2, 4, 6, 8, 10, 12, 14,
  135326. 16,
  135327. };
  135328. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_2 = {
  135329. _vq_quantthresh__44cn1_sm_p8_2,
  135330. _vq_quantmap__44cn1_sm_p8_2,
  135331. 17,
  135332. 17
  135333. };
  135334. static static_codebook _44cn1_sm_p8_2 = {
  135335. 2, 289,
  135336. _vq_lengthlist__44cn1_sm_p8_2,
  135337. 1, -529530880, 1611661312, 5, 0,
  135338. _vq_quantlist__44cn1_sm_p8_2,
  135339. NULL,
  135340. &_vq_auxt__44cn1_sm_p8_2,
  135341. NULL,
  135342. 0
  135343. };
  135344. static long _huff_lengthlist__44cn1_sm_short[] = {
  135345. 5, 6,12,14,12,14,16,17,18, 4, 2, 5,11, 7,10,12,
  135346. 14,15, 9, 4, 5,11, 7,10,13,15,18,15, 6, 7, 5, 6,
  135347. 8,11,13,16,11, 5, 6, 5, 5, 6, 9,13,15,12, 5, 7,
  135348. 6, 5, 6, 9,12,14,12, 6, 7, 8, 6, 7, 9,12,13,14,
  135349. 8, 8, 7, 5, 5, 8,10,12,16, 9, 9, 8, 6, 6, 7, 9,
  135350. 9,
  135351. };
  135352. static static_codebook _huff_book__44cn1_sm_short = {
  135353. 2, 81,
  135354. _huff_lengthlist__44cn1_sm_short,
  135355. 0, 0, 0, 0, 0,
  135356. NULL,
  135357. NULL,
  135358. NULL,
  135359. NULL,
  135360. 0
  135361. };
  135362. /********* End of inlined file: res_books_stereo.h *********/
  135363. /***** residue backends *********************************************/
  135364. static vorbis_info_residue0 _residue_44_low={
  135365. 0,-1, -1, 9,-1,
  135366. /* 0 1 2 3 4 5 6 7 */
  135367. {0},
  135368. {-1},
  135369. { .5, 1.5, 2.5, 2.5, 4.5, 8.5, 16.5, 32.5},
  135370. { .5, .5, .5, 999., 4.5, 8.5, 16.5, 32.5},
  135371. };
  135372. static vorbis_info_residue0 _residue_44_mid={
  135373. 0,-1, -1, 10,-1,
  135374. /* 0 1 2 3 4 5 6 7 8 */
  135375. {0},
  135376. {-1},
  135377. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 8.5, 16.5, 32.5},
  135378. { .5, .5, 999., .5, 999., 4.5, 8.5, 16.5, 32.5},
  135379. };
  135380. static vorbis_info_residue0 _residue_44_high={
  135381. 0,-1, -1, 10,-1,
  135382. /* 0 1 2 3 4 5 6 7 8 */
  135383. {0},
  135384. {-1},
  135385. { .5, 1.5, 2.5, 4.5, 8.5, 16.5, 32.5, 71.5,157.5},
  135386. { .5, 1.5, 2.5, 3.5, 4.5, 8.5, 16.5, 71.5,157.5},
  135387. };
  135388. static static_bookblock _resbook_44s_n1={
  135389. {
  135390. {0},{0,0,&_44cn1_s_p1_0},{0,0,&_44cn1_s_p2_0},
  135391. {0,0,&_44cn1_s_p3_0},{0,0,&_44cn1_s_p4_0},{0,0,&_44cn1_s_p5_0},
  135392. {&_44cn1_s_p6_0,&_44cn1_s_p6_1},{&_44cn1_s_p7_0,&_44cn1_s_p7_1},
  135393. {&_44cn1_s_p8_0,&_44cn1_s_p8_1,&_44cn1_s_p8_2}
  135394. }
  135395. };
  135396. static static_bookblock _resbook_44sm_n1={
  135397. {
  135398. {0},{0,0,&_44cn1_sm_p1_0},{0,0,&_44cn1_sm_p2_0},
  135399. {0,0,&_44cn1_sm_p3_0},{0,0,&_44cn1_sm_p4_0},{0,0,&_44cn1_sm_p5_0},
  135400. {&_44cn1_sm_p6_0,&_44cn1_sm_p6_1},{&_44cn1_sm_p7_0,&_44cn1_sm_p7_1},
  135401. {&_44cn1_sm_p8_0,&_44cn1_sm_p8_1,&_44cn1_sm_p8_2}
  135402. }
  135403. };
  135404. static static_bookblock _resbook_44s_0={
  135405. {
  135406. {0},{0,0,&_44c0_s_p1_0},{0,0,&_44c0_s_p2_0},
  135407. {0,0,&_44c0_s_p3_0},{0,0,&_44c0_s_p4_0},{0,0,&_44c0_s_p5_0},
  135408. {&_44c0_s_p6_0,&_44c0_s_p6_1},{&_44c0_s_p7_0,&_44c0_s_p7_1},
  135409. {&_44c0_s_p8_0,&_44c0_s_p8_1,&_44c0_s_p8_2}
  135410. }
  135411. };
  135412. static static_bookblock _resbook_44sm_0={
  135413. {
  135414. {0},{0,0,&_44c0_sm_p1_0},{0,0,&_44c0_sm_p2_0},
  135415. {0,0,&_44c0_sm_p3_0},{0,0,&_44c0_sm_p4_0},{0,0,&_44c0_sm_p5_0},
  135416. {&_44c0_sm_p6_0,&_44c0_sm_p6_1},{&_44c0_sm_p7_0,&_44c0_sm_p7_1},
  135417. {&_44c0_sm_p8_0,&_44c0_sm_p8_1,&_44c0_sm_p8_2}
  135418. }
  135419. };
  135420. static static_bookblock _resbook_44s_1={
  135421. {
  135422. {0},{0,0,&_44c1_s_p1_0},{0,0,&_44c1_s_p2_0},
  135423. {0,0,&_44c1_s_p3_0},{0,0,&_44c1_s_p4_0},{0,0,&_44c1_s_p5_0},
  135424. {&_44c1_s_p6_0,&_44c1_s_p6_1},{&_44c1_s_p7_0,&_44c1_s_p7_1},
  135425. {&_44c1_s_p8_0,&_44c1_s_p8_1,&_44c1_s_p8_2}
  135426. }
  135427. };
  135428. static static_bookblock _resbook_44sm_1={
  135429. {
  135430. {0},{0,0,&_44c1_sm_p1_0},{0,0,&_44c1_sm_p2_0},
  135431. {0,0,&_44c1_sm_p3_0},{0,0,&_44c1_sm_p4_0},{0,0,&_44c1_sm_p5_0},
  135432. {&_44c1_sm_p6_0,&_44c1_sm_p6_1},{&_44c1_sm_p7_0,&_44c1_sm_p7_1},
  135433. {&_44c1_sm_p8_0,&_44c1_sm_p8_1,&_44c1_sm_p8_2}
  135434. }
  135435. };
  135436. static static_bookblock _resbook_44s_2={
  135437. {
  135438. {0},{0,0,&_44c2_s_p1_0},{0,0,&_44c2_s_p2_0},{0,0,&_44c2_s_p3_0},
  135439. {0,0,&_44c2_s_p4_0},{0,0,&_44c2_s_p5_0},{0,0,&_44c2_s_p6_0},
  135440. {&_44c2_s_p7_0,&_44c2_s_p7_1},{&_44c2_s_p8_0,&_44c2_s_p8_1},
  135441. {&_44c2_s_p9_0,&_44c2_s_p9_1,&_44c2_s_p9_2}
  135442. }
  135443. };
  135444. static static_bookblock _resbook_44s_3={
  135445. {
  135446. {0},{0,0,&_44c3_s_p1_0},{0,0,&_44c3_s_p2_0},{0,0,&_44c3_s_p3_0},
  135447. {0,0,&_44c3_s_p4_0},{0,0,&_44c3_s_p5_0},{0,0,&_44c3_s_p6_0},
  135448. {&_44c3_s_p7_0,&_44c3_s_p7_1},{&_44c3_s_p8_0,&_44c3_s_p8_1},
  135449. {&_44c3_s_p9_0,&_44c3_s_p9_1,&_44c3_s_p9_2}
  135450. }
  135451. };
  135452. static static_bookblock _resbook_44s_4={
  135453. {
  135454. {0},{0,0,&_44c4_s_p1_0},{0,0,&_44c4_s_p2_0},{0,0,&_44c4_s_p3_0},
  135455. {0,0,&_44c4_s_p4_0},{0,0,&_44c4_s_p5_0},{0,0,&_44c4_s_p6_0},
  135456. {&_44c4_s_p7_0,&_44c4_s_p7_1},{&_44c4_s_p8_0,&_44c4_s_p8_1},
  135457. {&_44c4_s_p9_0,&_44c4_s_p9_1,&_44c4_s_p9_2}
  135458. }
  135459. };
  135460. static static_bookblock _resbook_44s_5={
  135461. {
  135462. {0},{0,0,&_44c5_s_p1_0},{0,0,&_44c5_s_p2_0},{0,0,&_44c5_s_p3_0},
  135463. {0,0,&_44c5_s_p4_0},{0,0,&_44c5_s_p5_0},{0,0,&_44c5_s_p6_0},
  135464. {&_44c5_s_p7_0,&_44c5_s_p7_1},{&_44c5_s_p8_0,&_44c5_s_p8_1},
  135465. {&_44c5_s_p9_0,&_44c5_s_p9_1,&_44c5_s_p9_2}
  135466. }
  135467. };
  135468. static static_bookblock _resbook_44s_6={
  135469. {
  135470. {0},{0,0,&_44c6_s_p1_0},{0,0,&_44c6_s_p2_0},{0,0,&_44c6_s_p3_0},
  135471. {0,0,&_44c6_s_p4_0},
  135472. {&_44c6_s_p5_0,&_44c6_s_p5_1},
  135473. {&_44c6_s_p6_0,&_44c6_s_p6_1},
  135474. {&_44c6_s_p7_0,&_44c6_s_p7_1},
  135475. {&_44c6_s_p8_0,&_44c6_s_p8_1},
  135476. {&_44c6_s_p9_0,&_44c6_s_p9_1,&_44c6_s_p9_2}
  135477. }
  135478. };
  135479. static static_bookblock _resbook_44s_7={
  135480. {
  135481. {0},{0,0,&_44c7_s_p1_0},{0,0,&_44c7_s_p2_0},{0,0,&_44c7_s_p3_0},
  135482. {0,0,&_44c7_s_p4_0},
  135483. {&_44c7_s_p5_0,&_44c7_s_p5_1},
  135484. {&_44c7_s_p6_0,&_44c7_s_p6_1},
  135485. {&_44c7_s_p7_0,&_44c7_s_p7_1},
  135486. {&_44c7_s_p8_0,&_44c7_s_p8_1},
  135487. {&_44c7_s_p9_0,&_44c7_s_p9_1,&_44c7_s_p9_2}
  135488. }
  135489. };
  135490. static static_bookblock _resbook_44s_8={
  135491. {
  135492. {0},{0,0,&_44c8_s_p1_0},{0,0,&_44c8_s_p2_0},{0,0,&_44c8_s_p3_0},
  135493. {0,0,&_44c8_s_p4_0},
  135494. {&_44c8_s_p5_0,&_44c8_s_p5_1},
  135495. {&_44c8_s_p6_0,&_44c8_s_p6_1},
  135496. {&_44c8_s_p7_0,&_44c8_s_p7_1},
  135497. {&_44c8_s_p8_0,&_44c8_s_p8_1},
  135498. {&_44c8_s_p9_0,&_44c8_s_p9_1,&_44c8_s_p9_2}
  135499. }
  135500. };
  135501. static static_bookblock _resbook_44s_9={
  135502. {
  135503. {0},{0,0,&_44c9_s_p1_0},{0,0,&_44c9_s_p2_0},{0,0,&_44c9_s_p3_0},
  135504. {0,0,&_44c9_s_p4_0},
  135505. {&_44c9_s_p5_0,&_44c9_s_p5_1},
  135506. {&_44c9_s_p6_0,&_44c9_s_p6_1},
  135507. {&_44c9_s_p7_0,&_44c9_s_p7_1},
  135508. {&_44c9_s_p8_0,&_44c9_s_p8_1},
  135509. {&_44c9_s_p9_0,&_44c9_s_p9_1,&_44c9_s_p9_2}
  135510. }
  135511. };
  135512. static vorbis_residue_template _res_44s_n1[]={
  135513. {2,0, &_residue_44_low,
  135514. &_huff_book__44cn1_s_short,&_huff_book__44cn1_sm_short,
  135515. &_resbook_44s_n1,&_resbook_44sm_n1},
  135516. {2,0, &_residue_44_low,
  135517. &_huff_book__44cn1_s_long,&_huff_book__44cn1_sm_long,
  135518. &_resbook_44s_n1,&_resbook_44sm_n1}
  135519. };
  135520. static vorbis_residue_template _res_44s_0[]={
  135521. {2,0, &_residue_44_low,
  135522. &_huff_book__44c0_s_short,&_huff_book__44c0_sm_short,
  135523. &_resbook_44s_0,&_resbook_44sm_0},
  135524. {2,0, &_residue_44_low,
  135525. &_huff_book__44c0_s_long,&_huff_book__44c0_sm_long,
  135526. &_resbook_44s_0,&_resbook_44sm_0}
  135527. };
  135528. static vorbis_residue_template _res_44s_1[]={
  135529. {2,0, &_residue_44_low,
  135530. &_huff_book__44c1_s_short,&_huff_book__44c1_sm_short,
  135531. &_resbook_44s_1,&_resbook_44sm_1},
  135532. {2,0, &_residue_44_low,
  135533. &_huff_book__44c1_s_long,&_huff_book__44c1_sm_long,
  135534. &_resbook_44s_1,&_resbook_44sm_1}
  135535. };
  135536. static vorbis_residue_template _res_44s_2[]={
  135537. {2,0, &_residue_44_mid,
  135538. &_huff_book__44c2_s_short,&_huff_book__44c2_s_short,
  135539. &_resbook_44s_2,&_resbook_44s_2},
  135540. {2,0, &_residue_44_mid,
  135541. &_huff_book__44c2_s_long,&_huff_book__44c2_s_long,
  135542. &_resbook_44s_2,&_resbook_44s_2}
  135543. };
  135544. static vorbis_residue_template _res_44s_3[]={
  135545. {2,0, &_residue_44_mid,
  135546. &_huff_book__44c3_s_short,&_huff_book__44c3_s_short,
  135547. &_resbook_44s_3,&_resbook_44s_3},
  135548. {2,0, &_residue_44_mid,
  135549. &_huff_book__44c3_s_long,&_huff_book__44c3_s_long,
  135550. &_resbook_44s_3,&_resbook_44s_3}
  135551. };
  135552. static vorbis_residue_template _res_44s_4[]={
  135553. {2,0, &_residue_44_mid,
  135554. &_huff_book__44c4_s_short,&_huff_book__44c4_s_short,
  135555. &_resbook_44s_4,&_resbook_44s_4},
  135556. {2,0, &_residue_44_mid,
  135557. &_huff_book__44c4_s_long,&_huff_book__44c4_s_long,
  135558. &_resbook_44s_4,&_resbook_44s_4}
  135559. };
  135560. static vorbis_residue_template _res_44s_5[]={
  135561. {2,0, &_residue_44_mid,
  135562. &_huff_book__44c5_s_short,&_huff_book__44c5_s_short,
  135563. &_resbook_44s_5,&_resbook_44s_5},
  135564. {2,0, &_residue_44_mid,
  135565. &_huff_book__44c5_s_long,&_huff_book__44c5_s_long,
  135566. &_resbook_44s_5,&_resbook_44s_5}
  135567. };
  135568. static vorbis_residue_template _res_44s_6[]={
  135569. {2,0, &_residue_44_high,
  135570. &_huff_book__44c6_s_short,&_huff_book__44c6_s_short,
  135571. &_resbook_44s_6,&_resbook_44s_6},
  135572. {2,0, &_residue_44_high,
  135573. &_huff_book__44c6_s_long,&_huff_book__44c6_s_long,
  135574. &_resbook_44s_6,&_resbook_44s_6}
  135575. };
  135576. static vorbis_residue_template _res_44s_7[]={
  135577. {2,0, &_residue_44_high,
  135578. &_huff_book__44c7_s_short,&_huff_book__44c7_s_short,
  135579. &_resbook_44s_7,&_resbook_44s_7},
  135580. {2,0, &_residue_44_high,
  135581. &_huff_book__44c7_s_long,&_huff_book__44c7_s_long,
  135582. &_resbook_44s_7,&_resbook_44s_7}
  135583. };
  135584. static vorbis_residue_template _res_44s_8[]={
  135585. {2,0, &_residue_44_high,
  135586. &_huff_book__44c8_s_short,&_huff_book__44c8_s_short,
  135587. &_resbook_44s_8,&_resbook_44s_8},
  135588. {2,0, &_residue_44_high,
  135589. &_huff_book__44c8_s_long,&_huff_book__44c8_s_long,
  135590. &_resbook_44s_8,&_resbook_44s_8}
  135591. };
  135592. static vorbis_residue_template _res_44s_9[]={
  135593. {2,0, &_residue_44_high,
  135594. &_huff_book__44c9_s_short,&_huff_book__44c9_s_short,
  135595. &_resbook_44s_9,&_resbook_44s_9},
  135596. {2,0, &_residue_44_high,
  135597. &_huff_book__44c9_s_long,&_huff_book__44c9_s_long,
  135598. &_resbook_44s_9,&_resbook_44s_9}
  135599. };
  135600. static vorbis_mapping_template _mapres_template_44_stereo[]={
  135601. { _map_nominal, _res_44s_n1 }, /* -1 */
  135602. { _map_nominal, _res_44s_0 }, /* 0 */
  135603. { _map_nominal, _res_44s_1 }, /* 1 */
  135604. { _map_nominal, _res_44s_2 }, /* 2 */
  135605. { _map_nominal, _res_44s_3 }, /* 3 */
  135606. { _map_nominal, _res_44s_4 }, /* 4 */
  135607. { _map_nominal, _res_44s_5 }, /* 5 */
  135608. { _map_nominal, _res_44s_6 }, /* 6 */
  135609. { _map_nominal, _res_44s_7 }, /* 7 */
  135610. { _map_nominal, _res_44s_8 }, /* 8 */
  135611. { _map_nominal, _res_44s_9 }, /* 9 */
  135612. };
  135613. /********* End of inlined file: residue_44.h *********/
  135614. /********* Start of inlined file: psych_44.h *********/
  135615. /* preecho trigger settings *****************************************/
  135616. static vorbis_info_psy_global _psy_global_44[5]={
  135617. {8, /* lines per eighth octave */
  135618. {20.f,14.f,12.f,12.f,12.f,12.f,12.f},
  135619. {-60.f,-30.f,-40.f,-40.f,-40.f,-40.f,-40.f}, 2,-75.f,
  135620. -6.f,
  135621. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  135622. },
  135623. {8, /* lines per eighth octave */
  135624. {14.f,10.f,10.f,10.f,10.f,10.f,10.f},
  135625. {-40.f,-30.f,-25.f,-25.f,-25.f,-25.f,-25.f}, 2,-80.f,
  135626. -6.f,
  135627. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  135628. },
  135629. {8, /* lines per eighth octave */
  135630. {12.f,10.f,10.f,10.f,10.f,10.f,10.f},
  135631. {-20.f,-20.f,-15.f,-15.f,-15.f,-15.f,-15.f}, 0,-80.f,
  135632. -6.f,
  135633. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  135634. },
  135635. {8, /* lines per eighth octave */
  135636. {10.f,8.f,8.f,8.f,8.f,8.f,8.f},
  135637. {-20.f,-15.f,-12.f,-12.f,-12.f,-12.f,-12.f}, 0,-80.f,
  135638. -6.f,
  135639. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  135640. },
  135641. {8, /* lines per eighth octave */
  135642. {10.f,6.f,6.f,6.f,6.f,6.f,6.f},
  135643. {-15.f,-15.f,-12.f,-12.f,-12.f,-12.f,-12.f}, 0,-85.f,
  135644. -6.f,
  135645. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  135646. },
  135647. };
  135648. /* noise compander lookups * low, mid, high quality ****************/
  135649. static compandblock _psy_compand_44[6]={
  135650. /* sub-mode Z short */
  135651. {{
  135652. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  135653. 8, 9,10,11,12,13,14, 15, /* 15dB */
  135654. 16,17,18,19,20,21,22, 23, /* 23dB */
  135655. 24,25,26,27,28,29,30, 31, /* 31dB */
  135656. 32,33,34,35,36,37,38, 39, /* 39dB */
  135657. }},
  135658. /* mode_Z nominal short */
  135659. {{
  135660. 0, 1, 2, 3, 4, 5, 6, 6, /* 7dB */
  135661. 7, 7, 7, 7, 6, 6, 6, 7, /* 15dB */
  135662. 7, 8, 9,10,11,12,13, 14, /* 23dB */
  135663. 15,16,17,17,17,18,18, 19, /* 31dB */
  135664. 19,19,20,21,22,23,24, 25, /* 39dB */
  135665. }},
  135666. /* mode A short */
  135667. {{
  135668. 0, 1, 2, 3, 4, 5, 5, 5, /* 7dB */
  135669. 6, 6, 6, 5, 4, 4, 4, 4, /* 15dB */
  135670. 4, 4, 5, 5, 5, 6, 6, 6, /* 23dB */
  135671. 7, 7, 7, 8, 8, 8, 9, 10, /* 31dB */
  135672. 11,12,13,14,15,16,17, 18, /* 39dB */
  135673. }},
  135674. /* sub-mode Z long */
  135675. {{
  135676. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  135677. 8, 9,10,11,12,13,14, 15, /* 15dB */
  135678. 16,17,18,19,20,21,22, 23, /* 23dB */
  135679. 24,25,26,27,28,29,30, 31, /* 31dB */
  135680. 32,33,34,35,36,37,38, 39, /* 39dB */
  135681. }},
  135682. /* mode_Z nominal long */
  135683. {{
  135684. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  135685. 8, 9,10,11,12,12,13, 13, /* 15dB */
  135686. 13,14,14,14,15,15,15, 15, /* 23dB */
  135687. 16,16,17,17,17,18,18, 19, /* 31dB */
  135688. 19,19,20,21,22,23,24, 25, /* 39dB */
  135689. }},
  135690. /* mode A long */
  135691. {{
  135692. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  135693. 8, 8, 7, 6, 5, 4, 4, 4, /* 15dB */
  135694. 4, 4, 5, 5, 5, 6, 6, 6, /* 23dB */
  135695. 7, 7, 7, 8, 8, 8, 9, 10, /* 31dB */
  135696. 11,12,13,14,15,16,17, 18, /* 39dB */
  135697. }}
  135698. };
  135699. /* tonal masking curve level adjustments *************************/
  135700. static vp_adjblock _vp_tonemask_adj_longblock[12]={
  135701. /* 63 125 250 500 1 2 4 8 16 */
  135702. {{ -3, -8,-13,-15,-10,-10,-10,-10,-10,-10,-10, 0, 0, 0, 0, 0, 0}}, /* -1 */
  135703. /* {{-15,-15,-15,-15,-10, -8, -4, -2, 0, 0, 0, 10, 0, 0, 0, 0, 0}}, 0 */
  135704. {{ -4,-10,-14,-16,-15,-14,-13,-12,-12,-12,-11, -1, -1, -1, -1, -1, 0}}, /* 0 */
  135705. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 5, 0, 0, 0, 0, 0}}, 1 */
  135706. {{ -6,-12,-14,-16,-15,-15,-14,-13,-13,-12,-12, -2, -2, -1, -1, -1, 0}}, /* 1 */
  135707. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 2 */
  135708. {{-12,-13,-14,-16,-16,-16,-15,-14,-13,-12,-12, -6, -3, -1, -1, -1, 0}}, /* 2 */
  135709. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 3 */
  135710. {{-15,-15,-15,-16,-16,-16,-16,-14,-13,-13,-13,-10, -4, -2, -1, -1, 0}}, /* 3 */
  135711. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, *//* 4 */
  135712. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 4 */
  135713. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 5 */
  135714. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 5 */
  135715. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 6 */
  135716. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -8, -4, -2, -2, 0}}, /* 6 */
  135717. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 7 */
  135718. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 7 */
  135719. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 8 */
  135720. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 8 */
  135721. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 9 */
  135722. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 9 */
  135723. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 10 */
  135724. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 10 */
  135725. };
  135726. static vp_adjblock _vp_tonemask_adj_otherblock[12]={
  135727. /* 63 125 250 500 1 2 4 8 16 */
  135728. {{ -3, -8,-13,-15,-10,-10, -9, -9, -9, -9, -9, 1, 1, 1, 1, 1, 1}}, /* -1 */
  135729. /* {{-20,-20,-20,-20,-14,-12,-10, -8, -4, 0, 0, 10, 0, 0, 0, 0, 0}}, 0 */
  135730. {{ -4,-10,-14,-16,-14,-13,-12,-12,-11,-11,-10, 0, 0, 0, 0, 0, 0}}, /* 0 */
  135731. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 5, 0, 0, 0, 0, 0}}, 1 */
  135732. {{ -6,-12,-14,-16,-15,-15,-14,-13,-13,-12,-12, -2, -2, -1, 0, 0, 0}}, /* 1 */
  135733. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 2 */
  135734. {{-12,-13,-14,-16,-16,-16,-15,-14,-13,-12,-12, -5, -2, -1, 0, 0, 0}}, /* 2 */
  135735. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 3 */
  135736. {{-15,-15,-15,-16,-16,-16,-16,-14,-13,-13,-13,-10, -4, -2, 0, 0, 0}}, /* 3 */
  135737. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 4 */
  135738. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 4 */
  135739. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 5 */
  135740. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 5 */
  135741. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 6 */
  135742. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -8, -4, -2, -2, 0}}, /* 6 */
  135743. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 7 */
  135744. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 7 */
  135745. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 8 */
  135746. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 8 */
  135747. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 9 */
  135748. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 9 */
  135749. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 10 */
  135750. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 10 */
  135751. };
  135752. /* noise bias (transition block) */
  135753. static noise3 _psy_noisebias_trans[12]={
  135754. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  135755. /* -1 */
  135756. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  135757. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  135758. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  135759. /* 0
  135760. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  135761. {-30,-30,-30,-30,-26,-22,-20,-14, -8, -4, 0, 0, 0, 0, 2, 4, 10},
  135762. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -4, -4, -4, -2}}},*/
  135763. {{{-15,-15,-15,-15,-15,-12, -6, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  135764. {-30,-30,-30,-30,-26,-22,-20,-14, -8, -4, 0, 0, 0, 0, 2, 3, 6},
  135765. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -4, -4, -4, -2}}},
  135766. /* 1
  135767. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  135768. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 8},
  135769. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},*/
  135770. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  135771. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 1, 4},
  135772. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},
  135773. /* 2
  135774. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  135775. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 6},
  135776. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}}, */
  135777. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  135778. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -2, -1, 0, 3},
  135779. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -7, -4}}},
  135780. /* 3
  135781. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  135782. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 6},
  135783. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  135784. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  135785. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -2, 0, 2},
  135786. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  135787. /* 4
  135788. {{{-20,-20,-20,-20,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  135789. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 5},
  135790. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  135791. {{{-20,-20,-20,-20,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  135792. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -2, -1, 1},
  135793. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  135794. /* 5
  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,-22,-16,-12, -6, -4, -4, -4, -4, -2, -1, 2},
  135797. {-34,-34,-34,-34,-30,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}}, */
  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,-22,-16,-12, -6, -4, -4, -4, -4, -3, -1, 0},
  135800. {-34,-34,-34,-34,-30,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}},
  135801. /* 6
  135802. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  135803. {-32,-32,-32,-32,-28,-24,-24,-18,-14, -8, -6, -6, -6, -6, -4, -2, 1},
  135804. {-34,-34,-34,-34,-30,-26,-24,-18,-17,-15,-15,-15,-15,-13,-13,-12, -8}}},*/
  135805. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  135806. {-32,-32,-32,-32,-28,-24,-24,-18,-14, -8, -6, -6, -6, -6, -5, -2, 0},
  135807. {-34,-34,-34,-34,-30,-26,-26,-24,-22,-19,-19,-19,-19,-18,-17,-16,-12}}},
  135808. /* 7
  135809. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  135810. {-32,-32,-32,-32,-28,-24,-24,-18,-14,-12,-10, -8, -8, -8, -6, -4, 0},
  135811. {-34,-34,-34,-34,-30,-26,-26,-24,-22,-19,-19,-19,-19,-18,-17,-16,-12}}},*/
  135812. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  135813. {-32,-32,-32,-32,-28,-24,-24,-24,-18,-14,-12,-10,-10,-10, -8, -6, -2},
  135814. {-34,-34,-34,-34,-30,-26,-26,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},
  135815. /* 8
  135816. {{{-24,-24,-24,-24,-22,-20,-15,-10, -8, -2, 0, 0, 0, 1, 2, 3, 7},
  135817. {-36,-36,-36,-36,-30,-30,-30,-24,-18,-14,-12,-10,-10,-10, -8, -6, -2},
  135818. {-36,-36,-36,-36,-34,-30,-28,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},*/
  135819. {{{-24,-24,-24,-24,-22,-20,-15,-10, -8, -2, 0, 0, 0, 1, 2, 3, 7},
  135820. {-36,-36,-36,-36,-30,-30,-30,-24,-20,-16,-16,-16,-16,-14,-12,-10, -7},
  135821. {-36,-36,-36,-36,-34,-30,-28,-26,-24,-30,-30,-30,-30,-30,-30,-24,-20}}},
  135822. /* 9
  135823. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  135824. {-36,-36,-36,-36,-34,-32,-32,-28,-20,-16,-16,-16,-16,-14,-12,-10, -7},
  135825. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},*/
  135826. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  135827. {-38,-38,-38,-38,-36,-34,-34,-30,-24,-20,-20,-20,-20,-18,-16,-12,-10},
  135828. {-40,-40,-40,-40,-40,-40,-40,-38,-35,-35,-35,-35,-35,-35,-35,-35,-30}}},
  135829. /* 10 */
  135830. {{{-30,-30,-30,-30,-30,-30,-30,-28,-20,-14,-14,-14,-14,-14,-14,-12,-10},
  135831. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-30,-30,-30,-30,-30,-30,-20},
  135832. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  135833. };
  135834. /* noise bias (long block) */
  135835. static noise3 _psy_noisebias_long[12]={
  135836. /*63 125 250 500 1k 2k 4k 8k 16k*/
  135837. /* -1 */
  135838. {{{-10,-10,-10,-10,-10, -4, 0, 0, 0, 6, 6, 6, 6, 10, 10, 12, 20},
  135839. {-20,-20,-20,-20,-20,-20,-10, -2, 0, 0, 0, 0, 0, 2, 4, 6, 15},
  135840. {-20,-20,-20,-20,-20,-20,-20,-10, -6, -6, -6, -6, -6, -4, -4, -4, -2}}},
  135841. /* 0 */
  135842. /* {{{-10,-10,-10,-10,-10,-10, -8, 2, 2, 2, 4, 4, 5, 5, 5, 8, 10},
  135843. {-20,-20,-20,-20,-20,-20,-20,-14, -6, 0, 0, 0, 0, 0, 2, 4, 10},
  135844. {-20,-20,-20,-20,-20,-20,-20,-14, -8, -6, -6, -6, -6, -4, -4, -4, -2}}},*/
  135845. {{{-10,-10,-10,-10,-10,-10, -8, 2, 2, 2, 4, 4, 5, 5, 5, 8, 10},
  135846. {-20,-20,-20,-20,-20,-20,-20,-14, -6, 0, 0, 0, 0, 0, 2, 3, 6},
  135847. {-20,-20,-20,-20,-20,-20,-20,-14, -8, -6, -6, -6, -6, -4, -4, -4, -2}}},
  135848. /* 1 */
  135849. /* {{{-10,-10,-10,-10,-10,-10, -8, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  135850. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 8},
  135851. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},*/
  135852. {{{-10,-10,-10,-10,-10,-10, -8, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  135853. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 1, 4},
  135854. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},
  135855. /* 2 */
  135856. /* {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  135857. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 6},
  135858. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  135859. {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  135860. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -2, -1, 0, 3},
  135861. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  135862. /* 3 */
  135863. /* {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  135864. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 6},
  135865. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  135866. {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  135867. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -2, 0, 2},
  135868. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -5}}},
  135869. /* 4 */
  135870. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  135871. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 5},
  135872. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  135873. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  135874. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -2, -1, 1},
  135875. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -7}}},
  135876. /* 5 */
  135877. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  135878. {-22,-22,-22,-22,-22,-22,-22,-16,-12, -6, -4, -4, -4, -4, -2, -1, 2},
  135879. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}},*/
  135880. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  135881. {-22,-22,-22,-22,-22,-22,-22,-16,-12, -6, -4, -4, -4, -4, -3, -1, 0},
  135882. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -8}}},
  135883. /* 6 */
  135884. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  135885. {-24,-24,-24,-24,-24,-24,-24,-18,-14, -8, -6, -6, -6, -6, -4, -2, 1},
  135886. {-26,-26,-26,-26,-26,-26,-26,-18,-16,-15,-15,-15,-15,-13,-13,-12, -8}}},*/
  135887. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  135888. {-24,-24,-24,-24,-24,-24,-24,-18,-14, -8, -6, -6, -6, -6, -5, -2, 0},
  135889. {-26,-26,-26,-26,-26,-26,-26,-18,-16,-15,-15,-15,-15,-13,-13,-12,-10}}},
  135890. /* 7 */
  135891. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  135892. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-10, -8, -8, -8, -8, -6, -4, 0},
  135893. {-26,-26,-26,-26,-26,-26,-26,-22,-20,-19,-19,-19,-19,-18,-17,-16,-12}}},
  135894. /* 8 */
  135895. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 0, 0, 0, 0, 1, 2, 3, 7},
  135896. {-26,-26,-26,-26,-26,-26,-26,-20,-16,-12,-10,-10,-10,-10, -8, -6, -2},
  135897. {-28,-28,-28,-28,-28,-28,-28,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},
  135898. /* 9 */
  135899. {{{-22,-22,-22,-22,-22,-22,-22,-18,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  135900. {-26,-26,-26,-26,-26,-26,-26,-22,-18,-16,-16,-16,-16,-14,-12,-10, -7},
  135901. {-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},
  135902. /* 10 */
  135903. {{{-24,-24,-24,-24,-24,-24,-24,-24,-24,-18,-14,-14,-14,-14,-14,-12,-10},
  135904. {-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-20},
  135905. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  135906. };
  135907. /* noise bias (impulse block) */
  135908. static noise3 _psy_noisebias_impulse[12]={
  135909. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  135910. /* -1 */
  135911. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  135912. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  135913. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  135914. /* 0 */
  135915. /* {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 4, 8, 8, 8, 10, 12, 14, 20},
  135916. {-30,-30,-30,-30,-26,-22,-20,-14, -6, -2, 0, 0, 0, 0, 2, 4, 10},
  135917. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},*/
  135918. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 4, 8, 8, 8, 10, 12, 14, 20},
  135919. {-30,-30,-30,-30,-26,-22,-20,-14, -6, -2, 0, 0, 0, 0, 2, 3, 6},
  135920. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  135921. /* 1 */
  135922. {{{-12,-12,-12,-12,-12, -8, -6, -4, 0, 4, 4, 4, 4, 10, 12, 14, 20},
  135923. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -4, -4, -2, -2, -2, -2, 2},
  135924. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8,-10,-10, -8, -8, -8, -6, -4}}},
  135925. /* 2 */
  135926. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  135927. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  135928. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  135929. /* 3 */
  135930. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 6, 8, 8, 14},
  135931. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  135932. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  135933. /* 4 */
  135934. {{{-16,-16,-16,-16,-16,-12,-10, -6, -2, 0, 0, 0, 0, 4, 6, 6, 12},
  135935. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  135936. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  135937. /* 5 */
  135938. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  135939. {-32,-32,-32,-32,-28,-24,-22,-16,-10, -6, -8, -8, -6, -6, -6, -4, -2},
  135940. {-34,-34,-34,-34,-30,-26,-24,-18,-14,-12,-12,-12,-12,-12,-10, -9, -5}}},
  135941. /* 6
  135942. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  135943. {-34,-34,-34,-34,-30,-30,-24,-20,-12,-12,-14,-14,-10, -9, -8, -6, -4},
  135944. {-34,-34,-34,-34,-34,-30,-26,-20,-16,-15,-15,-15,-15,-15,-13,-12, -8}}},*/
  135945. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  135946. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-16,-16,-16,-16,-16,-14,-14,-12},
  135947. {-36,-36,-36,-36,-36,-34,-28,-24,-20,-20,-20,-20,-20,-20,-20,-18,-16}}},
  135948. /* 7 */
  135949. /* {{{-22,-22,-22,-22,-22,-20,-14,-10, -6, 0, 0, 0, 0, 4, 4, 6, 11},
  135950. {-34,-34,-34,-34,-30,-30,-24,-20,-14,-14,-16,-16,-14,-12,-10,-10,-10},
  135951. {-34,-34,-34,-34,-32,-32,-30,-24,-20,-19,-19,-19,-19,-19,-17,-16,-12}}},*/
  135952. {{{-22,-22,-22,-22,-22,-20,-14,-10, -6, 0, 0, 0, 0, 4, 4, 6, 11},
  135953. {-34,-34,-34,-34,-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-24,-22},
  135954. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-30,-24}}},
  135955. /* 8 */
  135956. /* {{{-24,-24,-24,-24,-24,-22,-14,-10, -6, -1, -1, -1, -1, 3, 3, 5, 10},
  135957. {-34,-34,-34,-34,-30,-30,-30,-24,-20,-20,-20,-20,-20,-18,-16,-16,-14},
  135958. {-36,-36,-36,-36,-36,-34,-28,-24,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},*/
  135959. {{{-24,-24,-24,-24,-24,-22,-14,-10, -6, -1, -1, -1, -1, 3, 3, 5, 10},
  135960. {-34,-34,-34,-34,-34,-32,-32,-30,-26,-26,-26,-26,-26,-26,-26,-26,-24},
  135961. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-30,-24}}},
  135962. /* 9 */
  135963. /* {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  135964. {-36,-36,-36,-36,-34,-32,-32,-30,-26,-26,-26,-26,-26,-22,-20,-20,-18},
  135965. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},*/
  135966. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  135967. {-36,-36,-36,-36,-34,-32,-32,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26},
  135968. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},
  135969. /* 10 */
  135970. {{{-30,-30,-30,-30,-30,-26,-24,-24,-24,-20,-16,-16,-16,-16,-16,-14,-12},
  135971. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-30,-30,-30,-30,-30,-30,-26},
  135972. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  135973. };
  135974. /* noise bias (padding block) */
  135975. static noise3 _psy_noisebias_padding[12]={
  135976. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  135977. /* -1 */
  135978. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  135979. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  135980. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  135981. /* 0 */
  135982. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  135983. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, 2, 3, 6, 6, 8, 10},
  135984. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -4, -4, -4, -4, -2, 0, 2}}},
  135985. /* 1 */
  135986. {{{-12,-12,-12,-12,-12, -8, -6, -4, 0, 4, 4, 4, 4, 10, 12, 14, 20},
  135987. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, 0, 0, 0, 2, 2, 4, 8},
  135988. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -6, -4, -2, 0}}},
  135989. /* 2 */
  135990. /* {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  135991. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, 0, 0, 0, 2, 2, 4, 8},
  135992. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},*/
  135993. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  135994. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, 0, 0, 2, 6},
  135995. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  135996. /* 3 */
  135997. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 6, 8, 8, 14},
  135998. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, 0, 0, 2, 6},
  135999. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  136000. /* 4 */
  136001. {{{-16,-16,-16,-16,-16,-12,-10, -6, -2, 0, 0, 0, 0, 4, 6, 6, 12},
  136002. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, -1, 0, 2, 6},
  136003. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  136004. /* 5 */
  136005. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  136006. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -3, -3, -3, -3, -2, 0, 4},
  136007. {-34,-34,-34,-34,-30,-26,-24,-18,-14,-10,-10,-10,-10,-10, -8, -5, -3}}},
  136008. /* 6 */
  136009. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  136010. {-34,-34,-34,-34,-30,-30,-24,-20,-14, -8, -4, -4, -4, -4, -3, -1, 4},
  136011. {-34,-34,-34,-34,-34,-30,-26,-20,-16,-13,-13,-13,-13,-13,-11, -8, -6}}},
  136012. /* 7 */
  136013. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  136014. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-10, -8, -6, -6, -6, -5, -3, 1},
  136015. {-34,-34,-34,-34,-32,-32,-28,-22,-18,-16,-16,-16,-16,-16,-14,-12,-10}}},
  136016. /* 8 */
  136017. {{{-22,-22,-22,-22,-22,-20,-14,-10, -4, 0, 0, 0, 0, 3, 5, 5, 11},
  136018. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-12,-10, -8, -8, -8, -7, -5, -2},
  136019. {-36,-36,-36,-36,-36,-34,-28,-22,-20,-20,-20,-20,-20,-20,-20,-16,-14}}},
  136020. /* 9 */
  136021. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -2, -2, -2, -2, 0, 2, 6},
  136022. {-36,-36,-36,-36,-34,-32,-32,-24,-16,-12,-12,-12,-12,-12,-10, -8, -5},
  136023. {-40,-40,-40,-40,-40,-40,-40,-32,-26,-24,-24,-24,-24,-24,-24,-20,-18}}},
  136024. /* 10 */
  136025. {{{-30,-30,-30,-30,-30,-26,-24,-24,-24,-20,-12,-12,-12,-12,-12,-10, -8},
  136026. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-25,-25,-25,-25,-25,-25,-15},
  136027. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  136028. };
  136029. static noiseguard _psy_noiseguards_44[4]={
  136030. {3,3,15},
  136031. {3,3,15},
  136032. {10,10,100},
  136033. {10,10,100},
  136034. };
  136035. static int _psy_tone_suppress[12]={
  136036. -20,-20,-20,-20,-20,-24,-30,-40,-40,-45,-45,-45,
  136037. };
  136038. static int _psy_tone_0dB[12]={
  136039. 90,90,95,95,95,95,105,105,105,105,105,105,
  136040. };
  136041. static int _psy_noise_suppress[12]={
  136042. -20,-20,-24,-24,-24,-24,-30,-40,-40,-45,-45,-45,
  136043. };
  136044. static vorbis_info_psy _psy_info_template={
  136045. /* blockflag */
  136046. -1,
  136047. /* ath_adjatt, ath_maxatt */
  136048. -140.,-140.,
  136049. /* tonemask att boost/decay,suppr,curves */
  136050. {0.f,0.f,0.f}, 0.,0., -40.f, {0.},
  136051. /*noisemaskp,supp, low/high window, low/hi guard, minimum */
  136052. 1, -0.f, .5f, .5f, 0,0,0,
  136053. /* noiseoffset*3, noisecompand, max_curve_dB */
  136054. {{-1},{-1},{-1}},{-1},105.f,
  136055. /* noise normalization - channel_p, point_p, start, partition, thresh. */
  136056. 0,0,-1,-1,0.,
  136057. };
  136058. /* ath ****************/
  136059. static int _psy_ath_floater[12]={
  136060. -100,-100,-100,-100,-100,-100,-105,-105,-105,-105,-110,-120,
  136061. };
  136062. static int _psy_ath_abs[12]={
  136063. -130,-130,-130,-130,-140,-140,-140,-140,-140,-140,-140,-150,
  136064. };
  136065. /* stereo setup. These don't map directly to quality level, there's
  136066. an additional indirection as several of the below may be used in a
  136067. single bitmanaged stream
  136068. ****************/
  136069. /* various stereo possibilities */
  136070. /* stereo mode by base quality level */
  136071. static adj_stereo _psy_stereo_modes_44[12]={
  136072. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 -1 */
  136073. {{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 2, 1, 0, 0, 0, 0},
  136074. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 5, 4, 3},
  136075. { 1, 2, 3, 4, 4, 4, 4, 4, 4, 5, 6, 7, 8, 8, 8},
  136076. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},
  136077. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 0 */
  136078. /*{{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 2, 1, 0, 0, 0, 0},
  136079. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 5, 4, 3},
  136080. { 1, 2, 3, 4, 5, 5, 6, 6, 6, 6, 6, 7, 8, 8, 8},
  136081. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  136082. {{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 1, 0, 0, 0, 0, 0},
  136083. { 8, 8, 8, 8, 6, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3},
  136084. { 1, 2, 3, 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  136085. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},
  136086. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 1 */
  136087. {{ 3, 3, 3, 3, 3, 3, 3, 3, 2, 1, 0, 0, 0, 0, 0},
  136088. { 8, 8, 8, 8, 6, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3},
  136089. { 1, 2, 3, 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  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 2 */
  136092. /* {{ 3, 3, 3, 3, 3, 3, 2, 2, 2, 1, 0, 0, 0, 0, 0},
  136093. { 8, 8, 8, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3, 2, 1},
  136094. { 3, 4, 4, 4, 5, 6, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  136095. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}}, */
  136096. {{ 3, 3, 3, 3, 3, 3, 3, 2, 1, 1, 0, 0, 0, 0, 0},
  136097. { 8, 8, 6, 6, 5, 5, 4, 4, 4, 4, 4, 4, 3, 2, 1},
  136098. { 3, 4, 4, 5, 5, 6, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  136099. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  136100. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 3 */
  136101. {{ 2, 2, 2, 2, 2, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0},
  136102. { 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 2, 1},
  136103. { 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 10, 10, 10, 10, 10},
  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 4 */
  136106. {{ 2, 2, 2, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  136107. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 3, 2, 1, 0},
  136108. { 6, 6, 6, 8, 8, 8, 8, 8, 8, 8, 10, 10, 10, 10, 10},
  136109. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  136110. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 5 */
  136111. /* {{ 2, 2, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  136112. { 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0},
  136113. { 6, 6, 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  136114. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  136115. {{ 2, 2, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  136116. { 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0},
  136117. { 6, 7, 8, 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12},
  136118. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  136119. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 6 */
  136120. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  136121. { 3, 3, 3, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  136122. { 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  136123. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}}, */
  136124. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  136125. { 3, 3, 3, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  136126. { 8, 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  136127. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  136128. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 7 */
  136129. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  136130. { 3, 3, 3, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  136131. { 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  136132. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  136133. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  136134. { 3, 3, 3, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  136135. { 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  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 8 */
  136138. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  136139. { 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  136140. { 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  136141. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  136142. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  136143. { 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  136144. { 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  136145. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  136146. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 9 */
  136147. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  136148. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  136149. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  136150. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  136151. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 10 */
  136152. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  136153. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  136154. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  136155. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  136156. };
  136157. /* tone master attenuation by base quality mode and bitrate tweak */
  136158. static att3 _psy_tone_masteratt_44[12]={
  136159. {{ 35, 21, 9}, 0, 0}, /* -1 */
  136160. {{ 30, 20, 8}, -2, 1.25}, /* 0 */
  136161. /* {{ 25, 14, 4}, 0, 0}, *//* 1 */
  136162. {{ 25, 12, 2}, 0, 0}, /* 1 */
  136163. /* {{ 20, 10, -2}, 0, 0}, *//* 2 */
  136164. {{ 20, 9, -3}, 0, 0}, /* 2 */
  136165. {{ 20, 9, -4}, 0, 0}, /* 3 */
  136166. {{ 20, 9, -4}, 0, 0}, /* 4 */
  136167. {{ 20, 6, -6}, 0, 0}, /* 5 */
  136168. {{ 20, 3, -10}, 0, 0}, /* 6 */
  136169. {{ 18, 1, -14}, 0, 0}, /* 7 */
  136170. {{ 18, 0, -16}, 0, 0}, /* 8 */
  136171. {{ 18, -2, -16}, 0, 0}, /* 9 */
  136172. {{ 12, -2, -20}, 0, 0}, /* 10 */
  136173. };
  136174. /* lowpass by mode **************/
  136175. static double _psy_lowpass_44[12]={
  136176. /* 15.1,15.8,16.5,17.9,20.5,48.,999.,999.,999.,999.,999. */
  136177. 13.9,15.1,15.8,16.5,17.2,18.9,20.1,48.,999.,999.,999.,999.
  136178. };
  136179. /* noise normalization **********/
  136180. static int _noise_start_short_44[11]={
  136181. /* 16,16,16,16,32,32,9999,9999,9999,9999 */
  136182. 32,16,16,16,32,9999,9999,9999,9999,9999,9999
  136183. };
  136184. static int _noise_start_long_44[11]={
  136185. /* 128,128,128,256,512,512,9999,9999,9999,9999 */
  136186. 256,128,128,256,512,9999,9999,9999,9999,9999,9999
  136187. };
  136188. static int _noise_part_short_44[11]={
  136189. 8,8,8,8,8,8,8,8,8,8,8
  136190. };
  136191. static int _noise_part_long_44[11]={
  136192. 32,32,32,32,32,32,32,32,32,32,32
  136193. };
  136194. static double _noise_thresh_44[11]={
  136195. /* .2,.2,.3,.4,.5,.5,9999.,9999.,9999.,9999., */
  136196. .2,.2,.2,.4,.6,9999.,9999.,9999.,9999.,9999.,9999.,
  136197. };
  136198. static double _noise_thresh_5only[2]={
  136199. .5,.5,
  136200. };
  136201. /********* End of inlined file: psych_44.h *********/
  136202. static double rate_mapping_44_stereo[12]={
  136203. 22500.,32000.,40000.,48000.,56000.,64000.,
  136204. 80000.,96000.,112000.,128000.,160000.,250001.
  136205. };
  136206. static double quality_mapping_44[12]={
  136207. -.1,.0,.1,.2,.3,.4,.5,.6,.7,.8,.9,1.0
  136208. };
  136209. static int blocksize_short_44[11]={
  136210. 512,256,256,256,256,256,256,256,256,256,256
  136211. };
  136212. static int blocksize_long_44[11]={
  136213. 4096,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048
  136214. };
  136215. static double _psy_compand_short_mapping[12]={
  136216. 0.5, 1., 1., 1.3, 1.6, 2., 2., 2., 2., 2., 2., 2.
  136217. };
  136218. static double _psy_compand_long_mapping[12]={
  136219. 3.5, 4., 4., 4.3, 4.6, 5., 5., 5., 5., 5., 5., 5.
  136220. };
  136221. static double _global_mapping_44[12]={
  136222. /* 1., 1., 1.5, 2., 2., 2.5, 2.7, 3.0, 3.5, 4., 4. */
  136223. 0., 1., 1., 1.5, 2., 2., 2.5, 2.7, 3.0, 3.7, 4., 4.
  136224. };
  136225. static int _floor_short_mapping_44[11]={
  136226. 1,0,0,2,2,4,5,5,5,5,5
  136227. };
  136228. static int _floor_long_mapping_44[11]={
  136229. 8,7,7,7,7,7,7,7,7,7,7
  136230. };
  136231. ve_setup_data_template ve_setup_44_stereo={
  136232. 11,
  136233. rate_mapping_44_stereo,
  136234. quality_mapping_44,
  136235. 2,
  136236. 40000,
  136237. 50000,
  136238. blocksize_short_44,
  136239. blocksize_long_44,
  136240. _psy_tone_masteratt_44,
  136241. _psy_tone_0dB,
  136242. _psy_tone_suppress,
  136243. _vp_tonemask_adj_otherblock,
  136244. _vp_tonemask_adj_longblock,
  136245. _vp_tonemask_adj_otherblock,
  136246. _psy_noiseguards_44,
  136247. _psy_noisebias_impulse,
  136248. _psy_noisebias_padding,
  136249. _psy_noisebias_trans,
  136250. _psy_noisebias_long,
  136251. _psy_noise_suppress,
  136252. _psy_compand_44,
  136253. _psy_compand_short_mapping,
  136254. _psy_compand_long_mapping,
  136255. {_noise_start_short_44,_noise_start_long_44},
  136256. {_noise_part_short_44,_noise_part_long_44},
  136257. _noise_thresh_44,
  136258. _psy_ath_floater,
  136259. _psy_ath_abs,
  136260. _psy_lowpass_44,
  136261. _psy_global_44,
  136262. _global_mapping_44,
  136263. _psy_stereo_modes_44,
  136264. _floor_books,
  136265. _floor,
  136266. _floor_short_mapping_44,
  136267. _floor_long_mapping_44,
  136268. _mapres_template_44_stereo
  136269. };
  136270. /********* End of inlined file: setup_44.h *********/
  136271. /********* Start of inlined file: setup_44u.h *********/
  136272. /********* Start of inlined file: residue_44u.h *********/
  136273. /********* Start of inlined file: res_books_uncoupled.h *********/
  136274. static long _vq_quantlist__16u0__p1_0[] = {
  136275. 1,
  136276. 0,
  136277. 2,
  136278. };
  136279. static long _vq_lengthlist__16u0__p1_0[] = {
  136280. 1, 4, 4, 5, 7, 7, 5, 7, 8, 5, 8, 8, 8,10,10, 8,
  136281. 10,11, 5, 8, 8, 8,10,10, 8,10,10, 4, 9, 9, 9,12,
  136282. 11, 8,11,11, 8,12,11,10,12,14,10,13,13, 7,11,11,
  136283. 10,14,12,11,14,14, 4, 9, 9, 8,11,11, 9,11,12, 7,
  136284. 11,11,10,13,14,10,12,14, 8,11,12,10,14,14,10,13,
  136285. 12,
  136286. };
  136287. static float _vq_quantthresh__16u0__p1_0[] = {
  136288. -0.5, 0.5,
  136289. };
  136290. static long _vq_quantmap__16u0__p1_0[] = {
  136291. 1, 0, 2,
  136292. };
  136293. static encode_aux_threshmatch _vq_auxt__16u0__p1_0 = {
  136294. _vq_quantthresh__16u0__p1_0,
  136295. _vq_quantmap__16u0__p1_0,
  136296. 3,
  136297. 3
  136298. };
  136299. static static_codebook _16u0__p1_0 = {
  136300. 4, 81,
  136301. _vq_lengthlist__16u0__p1_0,
  136302. 1, -535822336, 1611661312, 2, 0,
  136303. _vq_quantlist__16u0__p1_0,
  136304. NULL,
  136305. &_vq_auxt__16u0__p1_0,
  136306. NULL,
  136307. 0
  136308. };
  136309. static long _vq_quantlist__16u0__p2_0[] = {
  136310. 1,
  136311. 0,
  136312. 2,
  136313. };
  136314. static long _vq_lengthlist__16u0__p2_0[] = {
  136315. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 9, 7,
  136316. 8, 9, 5, 7, 7, 7, 9, 8, 7, 9, 7, 4, 7, 7, 7, 9,
  136317. 9, 7, 8, 8, 6, 9, 8, 7, 8,11, 9,11,10, 6, 8, 9,
  136318. 8,11, 8, 9,10,11, 4, 7, 7, 7, 8, 8, 7, 9, 9, 6,
  136319. 9, 8, 9,11,10, 8, 8,11, 6, 8, 9, 9,10,11, 8,11,
  136320. 8,
  136321. };
  136322. static float _vq_quantthresh__16u0__p2_0[] = {
  136323. -0.5, 0.5,
  136324. };
  136325. static long _vq_quantmap__16u0__p2_0[] = {
  136326. 1, 0, 2,
  136327. };
  136328. static encode_aux_threshmatch _vq_auxt__16u0__p2_0 = {
  136329. _vq_quantthresh__16u0__p2_0,
  136330. _vq_quantmap__16u0__p2_0,
  136331. 3,
  136332. 3
  136333. };
  136334. static static_codebook _16u0__p2_0 = {
  136335. 4, 81,
  136336. _vq_lengthlist__16u0__p2_0,
  136337. 1, -535822336, 1611661312, 2, 0,
  136338. _vq_quantlist__16u0__p2_0,
  136339. NULL,
  136340. &_vq_auxt__16u0__p2_0,
  136341. NULL,
  136342. 0
  136343. };
  136344. static long _vq_quantlist__16u0__p3_0[] = {
  136345. 2,
  136346. 1,
  136347. 3,
  136348. 0,
  136349. 4,
  136350. };
  136351. static long _vq_lengthlist__16u0__p3_0[] = {
  136352. 1, 5, 5, 7, 7, 6, 7, 7, 8, 8, 6, 7, 8, 8, 8, 8,
  136353. 9, 9,11,11, 8, 9, 9,11,11, 6, 9, 8,10,10, 8,10,
  136354. 10,11,11, 8,10,10,11,11,10,11,10,13,12, 9,11,10,
  136355. 13,13, 6, 8, 9,10,10, 8,10,10,11,11, 8,10,10,11,
  136356. 11, 9,10,11,13,12,10,10,11,12,12, 8,11,11,14,13,
  136357. 10,12,11,15,13, 9,12,11,15,14,12,14,13,16,14,12,
  136358. 13,13,17,14, 8,11,11,13,14, 9,11,12,14,15,10,11,
  136359. 12,13,15,11,13,13,14,16,12,13,14,14,16, 5, 9, 9,
  136360. 11,11, 9,11,11,12,12, 8,11,11,12,12,11,12,12,15,
  136361. 14,10,12,12,15,15, 8,11,11,13,12,10,12,12,13,13,
  136362. 10,12,12,14,13,12,12,13,14,15,11,13,13,17,16, 7,
  136363. 11,11,13,13,10,12,12,14,13,10,12,12,13,14,12,13,
  136364. 12,15,14,11,13,13,15,14, 9,12,12,16,15,11,13,13,
  136365. 17,16,10,13,13,16,16,13,14,15,15,16,13,15,14,19,
  136366. 17, 9,12,12,14,16,11,13,13,15,16,10,13,13,17,16,
  136367. 13,14,13,17,15,12,15,15,16,17, 5, 9, 9,11,11, 8,
  136368. 11,11,13,12, 9,11,11,12,12,10,12,12,14,15,11,12,
  136369. 12,14,14, 7,11,10,13,12,10,12,12,14,13,10,11,12,
  136370. 13,13,11,13,13,15,16,12,12,13,15,15, 7,11,11,13,
  136371. 13,10,13,13,14,14,10,12,12,13,13,11,13,13,16,15,
  136372. 12,13,13,15,14, 9,12,12,15,15,10,13,13,17,16,11,
  136373. 12,13,15,15,12,15,14,18,18,13,14,14,16,17, 9,12,
  136374. 12,15,16,10,13,13,15,16,11,13,13,15,16,13,15,15,
  136375. 17,17,13,15,14,16,15, 7,11,11,15,16,10,13,12,16,
  136376. 17,10,12,13,15,17,15,16,16,18,17,13,15,15,17,18,
  136377. 8,12,12,16,16,11,13,14,17,18,11,13,13,18,16,15,
  136378. 17,16,17,19,14,15,15,17,16, 8,12,12,16,15,11,14,
  136379. 13,18,17,11,13,14,18,17,15,16,16,18,17,13,16,16,
  136380. 18,18,11,15,14,18,17,13,14,15,18, 0,12,15,15, 0,
  136381. 17,17,16,17,17,18,14,16,18,18, 0,11,14,14,17, 0,
  136382. 12,15,14,17,19,12,15,14,18, 0,15,18,16, 0,17,14,
  136383. 18,16,18, 0, 7,11,11,16,15,10,12,12,18,16,10,13,
  136384. 13,16,15,13,15,14,17,17,14,16,16,19,18, 8,12,12,
  136385. 16,16,11,13,13,18,16,11,13,14,17,16,14,15,15,19,
  136386. 18,15,16,16, 0,19, 8,12,12,16,17,11,13,13,17,17,
  136387. 11,14,13,17,17,13,15,15,17,19,15,17,17,19, 0,11,
  136388. 14,15,19,17,12,15,16,18,18,12,14,15,19,17,14,16,
  136389. 17, 0,18,16,16,19,17, 0,11,14,14,18,19,12,15,14,
  136390. 17,17,13,16,14,17,16,14,17,16,18,18,15,18,15, 0,
  136391. 18,
  136392. };
  136393. static float _vq_quantthresh__16u0__p3_0[] = {
  136394. -1.5, -0.5, 0.5, 1.5,
  136395. };
  136396. static long _vq_quantmap__16u0__p3_0[] = {
  136397. 3, 1, 0, 2, 4,
  136398. };
  136399. static encode_aux_threshmatch _vq_auxt__16u0__p3_0 = {
  136400. _vq_quantthresh__16u0__p3_0,
  136401. _vq_quantmap__16u0__p3_0,
  136402. 5,
  136403. 5
  136404. };
  136405. static static_codebook _16u0__p3_0 = {
  136406. 4, 625,
  136407. _vq_lengthlist__16u0__p3_0,
  136408. 1, -533725184, 1611661312, 3, 0,
  136409. _vq_quantlist__16u0__p3_0,
  136410. NULL,
  136411. &_vq_auxt__16u0__p3_0,
  136412. NULL,
  136413. 0
  136414. };
  136415. static long _vq_quantlist__16u0__p4_0[] = {
  136416. 2,
  136417. 1,
  136418. 3,
  136419. 0,
  136420. 4,
  136421. };
  136422. static long _vq_lengthlist__16u0__p4_0[] = {
  136423. 3, 5, 5, 8, 8, 6, 6, 6, 9, 9, 6, 6, 6, 9, 9, 9,
  136424. 10, 9,11,11, 9, 9, 9,11,11, 6, 7, 7,10,10, 7, 7,
  136425. 8,10,10, 7, 7, 8,10,10,10,10,10,11,12, 9,10,10,
  136426. 11,12, 6, 7, 7,10,10, 7, 8, 7,10,10, 7, 8, 7,10,
  136427. 10,10,11,10,12,11,10,10,10,13,10, 9,10,10,12,12,
  136428. 10,11,10,14,12, 9,11,11,13,13,11,12,13,13,13,11,
  136429. 12,12,15,13, 9,10,10,12,13, 9,11,10,12,13,10,10,
  136430. 11,12,13,11,12,12,12,13,11,12,12,13,13, 5, 7, 7,
  136431. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,12,
  136432. 13,10,10,11,12,12, 6, 8, 8,11,10, 7, 8, 9,10,12,
  136433. 8, 9, 9,11,11,11,10,11,11,12,10,11,11,13,12, 7,
  136434. 8, 8,10,11, 8, 9, 8,11,10, 8, 9, 9,11,11,10,12,
  136435. 10,13,11,10,11,11,13,13,10,11,10,14,13,10,10,11,
  136436. 13,13,10,12,11,14,13,12,11,13,12,13,13,12,13,14,
  136437. 14,10,11,11,13,13,10,11,10,12,13,10,12,12,12,14,
  136438. 12,12,12,14,12,12,13,12,17,15, 5, 7, 7,10,10, 7,
  136439. 8, 8,10,10, 7, 8, 8,11,10,10,10,11,12,12,10,11,
  136440. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  136441. 10,11,11,11,11,12,12,10,10,11,12,13, 6, 8, 8,10,
  136442. 11, 8, 9, 9,11,11, 7, 9, 7,11,10,10,12,12,13,13,
  136443. 11,11,10,13,11, 9,11,10,14,13,11,11,11,15,13,10,
  136444. 10,11,13,13,12,13,13,14,14,12,11,12,12,13,10,11,
  136445. 11,12,13,10,11,12,13,13,10,11,10,13,12,12,12,13,
  136446. 14, 0,12,13,11,13,11, 8,10,10,13,13,10,11,11,14,
  136447. 13,10,11,11,13,12,13,14,14,14,15,12,12,12,15,14,
  136448. 9,11,10,13,12,10,10,11,13,14,11,11,11,15,12,13,
  136449. 12,14,15,16,13,13,13,14,13, 9,11,11,12,12,10,12,
  136450. 11,13,13,10,11,11,13,14,13,13,13,15,15,13,13,14,
  136451. 17,15,11,12,12,14,14,10,11,12,13,15,12,13,13, 0,
  136452. 15,13,11,14,12,16,14,16,14, 0,15,11,12,12,14,16,
  136453. 11,13,12,16,15,12,13,13,14,15,12,14,12,15,13,15,
  136454. 14,14,16,16, 8,10,10,13,13,10,11,10,13,14,10,11,
  136455. 11,13,13,13,13,12,14,14,14,13,13,16,17, 9,10,10,
  136456. 12,14,10,12,11,14,13,10,11,12,13,14,12,12,12,15,
  136457. 15,13,13,13,14,14, 9,10,10,13,13,10,11,12,12,14,
  136458. 10,11,10,13,13,13,13,13,14,16,13,13,13,14,14,11,
  136459. 12,13,15,13,12,14,13,14,16,12,12,13,13,14,13,14,
  136460. 14,17,15,13,12,17,13,16,11,12,13,14,15,12,13,14,
  136461. 14,17,11,12,11,14,14,13,16,14,16, 0,14,15,11,15,
  136462. 11,
  136463. };
  136464. static float _vq_quantthresh__16u0__p4_0[] = {
  136465. -1.5, -0.5, 0.5, 1.5,
  136466. };
  136467. static long _vq_quantmap__16u0__p4_0[] = {
  136468. 3, 1, 0, 2, 4,
  136469. };
  136470. static encode_aux_threshmatch _vq_auxt__16u0__p4_0 = {
  136471. _vq_quantthresh__16u0__p4_0,
  136472. _vq_quantmap__16u0__p4_0,
  136473. 5,
  136474. 5
  136475. };
  136476. static static_codebook _16u0__p4_0 = {
  136477. 4, 625,
  136478. _vq_lengthlist__16u0__p4_0,
  136479. 1, -533725184, 1611661312, 3, 0,
  136480. _vq_quantlist__16u0__p4_0,
  136481. NULL,
  136482. &_vq_auxt__16u0__p4_0,
  136483. NULL,
  136484. 0
  136485. };
  136486. static long _vq_quantlist__16u0__p5_0[] = {
  136487. 4,
  136488. 3,
  136489. 5,
  136490. 2,
  136491. 6,
  136492. 1,
  136493. 7,
  136494. 0,
  136495. 8,
  136496. };
  136497. static long _vq_lengthlist__16u0__p5_0[] = {
  136498. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  136499. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  136500. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,11, 7, 8, 8,
  136501. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  136502. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,10,11,11,12,
  136503. 12,
  136504. };
  136505. static float _vq_quantthresh__16u0__p5_0[] = {
  136506. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  136507. };
  136508. static long _vq_quantmap__16u0__p5_0[] = {
  136509. 7, 5, 3, 1, 0, 2, 4, 6,
  136510. 8,
  136511. };
  136512. static encode_aux_threshmatch _vq_auxt__16u0__p5_0 = {
  136513. _vq_quantthresh__16u0__p5_0,
  136514. _vq_quantmap__16u0__p5_0,
  136515. 9,
  136516. 9
  136517. };
  136518. static static_codebook _16u0__p5_0 = {
  136519. 2, 81,
  136520. _vq_lengthlist__16u0__p5_0,
  136521. 1, -531628032, 1611661312, 4, 0,
  136522. _vq_quantlist__16u0__p5_0,
  136523. NULL,
  136524. &_vq_auxt__16u0__p5_0,
  136525. NULL,
  136526. 0
  136527. };
  136528. static long _vq_quantlist__16u0__p6_0[] = {
  136529. 6,
  136530. 5,
  136531. 7,
  136532. 4,
  136533. 8,
  136534. 3,
  136535. 9,
  136536. 2,
  136537. 10,
  136538. 1,
  136539. 11,
  136540. 0,
  136541. 12,
  136542. };
  136543. static long _vq_lengthlist__16u0__p6_0[] = {
  136544. 1, 4, 4, 7, 7,10,10,12,12,13,13,18,17, 3, 6, 6,
  136545. 9, 9,11,11,13,13,14,14,18,17, 3, 6, 6, 9, 9,11,
  136546. 11,13,13,14,14,17,18, 7, 9, 9,11,11,13,13,14,14,
  136547. 15,15, 0, 0, 7, 9, 9,11,11,13,13,14,14,15,16,19,
  136548. 18,10,11,11,13,13,14,14,16,15,17,18, 0, 0,10,11,
  136549. 11,13,13,14,14,15,15,16,18, 0, 0,11,13,13,14,14,
  136550. 15,15,17,17, 0,19, 0, 0,11,13,13,14,14,14,15,16,
  136551. 18, 0,19, 0, 0,13,14,14,15,15,18,17,18,18, 0,19,
  136552. 0, 0,13,14,14,15,16,16,16,18,18,19, 0, 0, 0,16,
  136553. 17,17, 0,17,19,19, 0,19, 0, 0, 0, 0,16,19,16,17,
  136554. 18, 0,19, 0, 0, 0, 0, 0, 0,
  136555. };
  136556. static float _vq_quantthresh__16u0__p6_0[] = {
  136557. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  136558. 12.5, 17.5, 22.5, 27.5,
  136559. };
  136560. static long _vq_quantmap__16u0__p6_0[] = {
  136561. 11, 9, 7, 5, 3, 1, 0, 2,
  136562. 4, 6, 8, 10, 12,
  136563. };
  136564. static encode_aux_threshmatch _vq_auxt__16u0__p6_0 = {
  136565. _vq_quantthresh__16u0__p6_0,
  136566. _vq_quantmap__16u0__p6_0,
  136567. 13,
  136568. 13
  136569. };
  136570. static static_codebook _16u0__p6_0 = {
  136571. 2, 169,
  136572. _vq_lengthlist__16u0__p6_0,
  136573. 1, -526516224, 1616117760, 4, 0,
  136574. _vq_quantlist__16u0__p6_0,
  136575. NULL,
  136576. &_vq_auxt__16u0__p6_0,
  136577. NULL,
  136578. 0
  136579. };
  136580. static long _vq_quantlist__16u0__p6_1[] = {
  136581. 2,
  136582. 1,
  136583. 3,
  136584. 0,
  136585. 4,
  136586. };
  136587. static long _vq_lengthlist__16u0__p6_1[] = {
  136588. 1, 4, 5, 6, 6, 4, 6, 6, 6, 6, 4, 6, 6, 6, 6, 6,
  136589. 6, 6, 7, 7, 6, 6, 6, 7, 7,
  136590. };
  136591. static float _vq_quantthresh__16u0__p6_1[] = {
  136592. -1.5, -0.5, 0.5, 1.5,
  136593. };
  136594. static long _vq_quantmap__16u0__p6_1[] = {
  136595. 3, 1, 0, 2, 4,
  136596. };
  136597. static encode_aux_threshmatch _vq_auxt__16u0__p6_1 = {
  136598. _vq_quantthresh__16u0__p6_1,
  136599. _vq_quantmap__16u0__p6_1,
  136600. 5,
  136601. 5
  136602. };
  136603. static static_codebook _16u0__p6_1 = {
  136604. 2, 25,
  136605. _vq_lengthlist__16u0__p6_1,
  136606. 1, -533725184, 1611661312, 3, 0,
  136607. _vq_quantlist__16u0__p6_1,
  136608. NULL,
  136609. &_vq_auxt__16u0__p6_1,
  136610. NULL,
  136611. 0
  136612. };
  136613. static long _vq_quantlist__16u0__p7_0[] = {
  136614. 1,
  136615. 0,
  136616. 2,
  136617. };
  136618. static long _vq_lengthlist__16u0__p7_0[] = {
  136619. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  136620. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  136621. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  136622. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  136623. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  136624. 7,
  136625. };
  136626. static float _vq_quantthresh__16u0__p7_0[] = {
  136627. -157.5, 157.5,
  136628. };
  136629. static long _vq_quantmap__16u0__p7_0[] = {
  136630. 1, 0, 2,
  136631. };
  136632. static encode_aux_threshmatch _vq_auxt__16u0__p7_0 = {
  136633. _vq_quantthresh__16u0__p7_0,
  136634. _vq_quantmap__16u0__p7_0,
  136635. 3,
  136636. 3
  136637. };
  136638. static static_codebook _16u0__p7_0 = {
  136639. 4, 81,
  136640. _vq_lengthlist__16u0__p7_0,
  136641. 1, -518803456, 1628680192, 2, 0,
  136642. _vq_quantlist__16u0__p7_0,
  136643. NULL,
  136644. &_vq_auxt__16u0__p7_0,
  136645. NULL,
  136646. 0
  136647. };
  136648. static long _vq_quantlist__16u0__p7_1[] = {
  136649. 7,
  136650. 6,
  136651. 8,
  136652. 5,
  136653. 9,
  136654. 4,
  136655. 10,
  136656. 3,
  136657. 11,
  136658. 2,
  136659. 12,
  136660. 1,
  136661. 13,
  136662. 0,
  136663. 14,
  136664. };
  136665. static long _vq_lengthlist__16u0__p7_1[] = {
  136666. 1, 5, 5, 6, 5, 9,10,11,11,10,10,10,10,10,10, 5,
  136667. 8, 8, 8,10,10,10,10,10,10,10,10,10,10,10, 5, 8,
  136668. 9, 9, 9,10,10,10,10,10,10,10,10,10,10, 5,10, 8,
  136669. 10,10,10,10,10,10,10,10,10,10,10,10, 4, 8, 9,10,
  136670. 10,10,10,10,10,10,10,10,10,10,10, 9,10,10,10,10,
  136671. 10,10,10,10,10,10,10,10,10,10, 9,10,10,10,10,10,
  136672. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136673. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136674. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136675. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136676. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136677. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136678. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136679. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136680. 10,
  136681. };
  136682. static float _vq_quantthresh__16u0__p7_1[] = {
  136683. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  136684. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  136685. };
  136686. static long _vq_quantmap__16u0__p7_1[] = {
  136687. 13, 11, 9, 7, 5, 3, 1, 0,
  136688. 2, 4, 6, 8, 10, 12, 14,
  136689. };
  136690. static encode_aux_threshmatch _vq_auxt__16u0__p7_1 = {
  136691. _vq_quantthresh__16u0__p7_1,
  136692. _vq_quantmap__16u0__p7_1,
  136693. 15,
  136694. 15
  136695. };
  136696. static static_codebook _16u0__p7_1 = {
  136697. 2, 225,
  136698. _vq_lengthlist__16u0__p7_1,
  136699. 1, -520986624, 1620377600, 4, 0,
  136700. _vq_quantlist__16u0__p7_1,
  136701. NULL,
  136702. &_vq_auxt__16u0__p7_1,
  136703. NULL,
  136704. 0
  136705. };
  136706. static long _vq_quantlist__16u0__p7_2[] = {
  136707. 10,
  136708. 9,
  136709. 11,
  136710. 8,
  136711. 12,
  136712. 7,
  136713. 13,
  136714. 6,
  136715. 14,
  136716. 5,
  136717. 15,
  136718. 4,
  136719. 16,
  136720. 3,
  136721. 17,
  136722. 2,
  136723. 18,
  136724. 1,
  136725. 19,
  136726. 0,
  136727. 20,
  136728. };
  136729. static long _vq_lengthlist__16u0__p7_2[] = {
  136730. 1, 6, 6, 7, 8, 7, 7,10, 9,10, 9,11,10, 9,11,10,
  136731. 9, 9, 9, 9,10, 6, 8, 7, 9, 9, 8, 8,10,10, 9,11,
  136732. 11,12,12,10, 9,11, 9,12,10, 9, 6, 9, 8, 9,12, 8,
  136733. 8,11, 9,11,11,12,11,12,12,10,11,11,10,10,11, 7,
  136734. 10, 9, 9, 9, 9, 9,10, 9,10, 9,10,10,12,10,10,10,
  136735. 11,12,10,10, 7, 9, 9, 9,10, 9, 9,10,10, 9, 9, 9,
  136736. 11,11,10,10,10,10, 9, 9,12, 7, 9,10, 9,11, 9,10,
  136737. 9,10,11,11,11,10,11,12, 9,12,11,10,10,10, 7, 9,
  136738. 9, 9, 9,10,12,10, 9,11,12,10,11,12,12,11, 9,10,
  136739. 11,10,11, 7, 9,10,10,11,10, 9,10,11,11,11,10,12,
  136740. 12,12,11,11,10,11,11,12, 8, 9,10,12,11,10,10,12,
  136741. 12,12,12,12,10,11,11, 9,11,10,12,11,11, 8, 9,10,
  136742. 10,11,12,11,11,10,10,10,12,12,12, 9,10,12,12,12,
  136743. 12,12, 8,10,11,10,10,12, 9,11,12,12,11,12,12,12,
  136744. 12,10,12,10,10,10,10, 8,12,11,11,11,10,10,11,12,
  136745. 12,12,12,11,12,12,12,11,11,11,12,10, 9,10,10,12,
  136746. 10,12,10,12,12,10,10,10,11,12,12,12,11,12,12,12,
  136747. 11,10,11,12,12,12,11,12,12,11,12,12,11,12,12,12,
  136748. 12,11,12,12,10,10,10,10,11,11,12,11,12,12,12,12,
  136749. 12,12,12,11,12,11,10,11,11,12,11,11, 9,10,10,10,
  136750. 12,10,10,11, 9,11,12,11,12,11,12,12,10,11,10,12,
  136751. 9, 9, 9,12,11,10,11,10,12,10,12,10,12,12,12,11,
  136752. 11,11,11,11,10, 9,10,10,11,10,11,11,12,11,10,11,
  136753. 12,12,12,11,11, 9,12,10,12, 9,10,12,10,10,11,10,
  136754. 11,11,12,11,10,11,10,11,11,11,11,12,11,11,10, 9,
  136755. 10,10,10, 9,11,11,10, 9,12,10,11,12,11,12,12,11,
  136756. 12,11,12,11,10,11,10,12,11,12,11,12,11,12,10,11,
  136757. 10,10,12,11,10,11,11,11,10,
  136758. };
  136759. static float _vq_quantthresh__16u0__p7_2[] = {
  136760. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  136761. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  136762. 6.5, 7.5, 8.5, 9.5,
  136763. };
  136764. static long _vq_quantmap__16u0__p7_2[] = {
  136765. 19, 17, 15, 13, 11, 9, 7, 5,
  136766. 3, 1, 0, 2, 4, 6, 8, 10,
  136767. 12, 14, 16, 18, 20,
  136768. };
  136769. static encode_aux_threshmatch _vq_auxt__16u0__p7_2 = {
  136770. _vq_quantthresh__16u0__p7_2,
  136771. _vq_quantmap__16u0__p7_2,
  136772. 21,
  136773. 21
  136774. };
  136775. static static_codebook _16u0__p7_2 = {
  136776. 2, 441,
  136777. _vq_lengthlist__16u0__p7_2,
  136778. 1, -529268736, 1611661312, 5, 0,
  136779. _vq_quantlist__16u0__p7_2,
  136780. NULL,
  136781. &_vq_auxt__16u0__p7_2,
  136782. NULL,
  136783. 0
  136784. };
  136785. static long _huff_lengthlist__16u0__single[] = {
  136786. 3, 5, 8, 7,14, 8, 9,19, 5, 2, 5, 5, 9, 6, 9,19,
  136787. 8, 4, 5, 7, 8, 9,13,19, 7, 4, 6, 5, 9, 6, 9,19,
  136788. 12, 8, 7, 9,10,11,13,19, 8, 5, 8, 6, 9, 6, 7,19,
  136789. 8, 8,10, 7, 7, 4, 5,19,12,17,19,15,18,13,11,18,
  136790. };
  136791. static static_codebook _huff_book__16u0__single = {
  136792. 2, 64,
  136793. _huff_lengthlist__16u0__single,
  136794. 0, 0, 0, 0, 0,
  136795. NULL,
  136796. NULL,
  136797. NULL,
  136798. NULL,
  136799. 0
  136800. };
  136801. static long _huff_lengthlist__16u1__long[] = {
  136802. 3, 6,10, 8,12, 8,14, 8,14,19, 5, 3, 5, 5, 7, 6,
  136803. 11, 7,16,19, 7, 5, 6, 7, 7, 9,11,12,19,19, 6, 4,
  136804. 7, 5, 7, 6,10, 7,18,18, 8, 6, 7, 7, 7, 7, 8, 9,
  136805. 18,18, 7, 5, 8, 5, 7, 5, 8, 6,18,18,12, 9,10, 9,
  136806. 9, 9, 8, 9,18,18, 8, 7,10, 6, 8, 5, 6, 4,11,18,
  136807. 11,15,16,12,11, 8, 8, 6, 9,18,14,18,18,18,16,16,
  136808. 16,13,16,18,
  136809. };
  136810. static static_codebook _huff_book__16u1__long = {
  136811. 2, 100,
  136812. _huff_lengthlist__16u1__long,
  136813. 0, 0, 0, 0, 0,
  136814. NULL,
  136815. NULL,
  136816. NULL,
  136817. NULL,
  136818. 0
  136819. };
  136820. static long _vq_quantlist__16u1__p1_0[] = {
  136821. 1,
  136822. 0,
  136823. 2,
  136824. };
  136825. static long _vq_lengthlist__16u1__p1_0[] = {
  136826. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 7, 7,10,10, 7,
  136827. 9,10, 5, 7, 8, 7,10, 9, 7,10,10, 5, 8, 8, 8,10,
  136828. 10, 8,10,10, 7,10,10,10,11,12,10,12,13, 7,10,10,
  136829. 9,13,11,10,12,13, 5, 8, 8, 8,10,10, 8,10,10, 7,
  136830. 10,10,10,12,12, 9,11,12, 7,10,11,10,12,12,10,13,
  136831. 11,
  136832. };
  136833. static float _vq_quantthresh__16u1__p1_0[] = {
  136834. -0.5, 0.5,
  136835. };
  136836. static long _vq_quantmap__16u1__p1_0[] = {
  136837. 1, 0, 2,
  136838. };
  136839. static encode_aux_threshmatch _vq_auxt__16u1__p1_0 = {
  136840. _vq_quantthresh__16u1__p1_0,
  136841. _vq_quantmap__16u1__p1_0,
  136842. 3,
  136843. 3
  136844. };
  136845. static static_codebook _16u1__p1_0 = {
  136846. 4, 81,
  136847. _vq_lengthlist__16u1__p1_0,
  136848. 1, -535822336, 1611661312, 2, 0,
  136849. _vq_quantlist__16u1__p1_0,
  136850. NULL,
  136851. &_vq_auxt__16u1__p1_0,
  136852. NULL,
  136853. 0
  136854. };
  136855. static long _vq_quantlist__16u1__p2_0[] = {
  136856. 1,
  136857. 0,
  136858. 2,
  136859. };
  136860. static long _vq_lengthlist__16u1__p2_0[] = {
  136861. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 7, 8, 6,
  136862. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 7, 5, 6, 6, 6, 8,
  136863. 8, 6, 8, 8, 6, 8, 8, 7, 7,10, 8, 9, 9, 6, 8, 8,
  136864. 7, 9, 8, 8, 9,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  136865. 8, 8, 8,10, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 7,10,
  136866. 8,
  136867. };
  136868. static float _vq_quantthresh__16u1__p2_0[] = {
  136869. -0.5, 0.5,
  136870. };
  136871. static long _vq_quantmap__16u1__p2_0[] = {
  136872. 1, 0, 2,
  136873. };
  136874. static encode_aux_threshmatch _vq_auxt__16u1__p2_0 = {
  136875. _vq_quantthresh__16u1__p2_0,
  136876. _vq_quantmap__16u1__p2_0,
  136877. 3,
  136878. 3
  136879. };
  136880. static static_codebook _16u1__p2_0 = {
  136881. 4, 81,
  136882. _vq_lengthlist__16u1__p2_0,
  136883. 1, -535822336, 1611661312, 2, 0,
  136884. _vq_quantlist__16u1__p2_0,
  136885. NULL,
  136886. &_vq_auxt__16u1__p2_0,
  136887. NULL,
  136888. 0
  136889. };
  136890. static long _vq_quantlist__16u1__p3_0[] = {
  136891. 2,
  136892. 1,
  136893. 3,
  136894. 0,
  136895. 4,
  136896. };
  136897. static long _vq_lengthlist__16u1__p3_0[] = {
  136898. 1, 5, 5, 8, 8, 6, 7, 7, 9, 9, 5, 7, 7, 9, 9, 9,
  136899. 10, 9,11,11, 9, 9,10,11,11, 6, 8, 8,10,10, 8, 9,
  136900. 10,11,11, 8, 9,10,11,11,10,11,11,12,13,10,11,11,
  136901. 13,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10, 9,11,
  136902. 11,10,11,11,13,13,10,11,11,13,12, 9,11,11,14,13,
  136903. 10,12,12,15,14,10,12,11,14,13,12,13,13,15,15,12,
  136904. 13,13,16,14, 9,11,11,13,14,10,11,12,14,14,10,12,
  136905. 12,14,15,12,13,13,14,15,12,13,14,15,16, 5, 8, 8,
  136906. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  136907. 14,11,12,12,14,14, 8,10,10,12,12, 9,11,12,12,13,
  136908. 10,12,12,13,13,12,12,13,14,15,11,13,13,15,15, 7,
  136909. 10,10,12,12, 9,12,11,13,12,10,11,12,13,13,12,13,
  136910. 12,15,14,11,12,13,15,15,10,12,12,15,14,11,13,13,
  136911. 16,15,11,13,13,16,15,14,13,14,15,16,13,15,15,17,
  136912. 17,10,12,12,14,15,11,12,12,15,15,11,13,13,15,16,
  136913. 13,15,13,16,15,13,15,15,16,17, 5, 8, 8,11,11, 8,
  136914. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  136915. 12,14,14, 7,10,10,12,12,10,12,12,14,13, 9,11,12,
  136916. 12,13,12,13,13,15,15,12,12,13,13,15, 7,10,10,12,
  136917. 13,10,11,12,13,13,10,12,11,13,13,11,13,13,15,15,
  136918. 12,13,12,15,14, 9,12,12,15,14,11,13,13,15,15,11,
  136919. 12,13,15,15,13,14,14,17,19,13,13,14,16,16,10,12,
  136920. 12,14,15,11,13,13,15,16,11,13,12,16,15,13,15,15,
  136921. 17,18,14,15,13,16,15, 8,11,11,15,14,10,12,12,16,
  136922. 15,10,12,12,16,16,14,15,15,18,17,13,14,15,16,18,
  136923. 9,12,12,15,15,11,12,14,16,17,11,13,13,16,15,15,
  136924. 15,15,17,18,14,15,16,17,17, 9,12,12,15,15,11,14,
  136925. 13,16,16,11,13,13,16,16,15,16,15,17,18,14,16,15,
  136926. 17,16,12,14,14,17,16,12,14,15,18,17,13,15,15,17,
  136927. 17,15,15,18,16,20,15,16,17,18,18,11,14,14,16,17,
  136928. 13,15,14,18,17,13,15,15,17,17,15,17,15,18,17,15,
  136929. 17,16,19,18, 8,11,11,14,15,10,12,12,15,15,10,12,
  136930. 12,16,16,13,14,14,17,16,14,15,15,17,17, 9,12,12,
  136931. 15,16,11,13,13,16,16,11,12,13,16,16,14,16,15,20,
  136932. 17,14,16,16,17,17, 9,12,12,15,16,11,13,13,16,17,
  136933. 11,13,13,17,16,14,15,15,17,18,15,15,15,18,18,11,
  136934. 14,14,17,16,13,15,15,17,17,13,14,14,18,17,15,16,
  136935. 16,18,19,15,15,17,17,19,11,14,14,16,17,13,15,14,
  136936. 17,19,13,15,14,18,17,15,17,16,18,18,15,17,15,18,
  136937. 16,
  136938. };
  136939. static float _vq_quantthresh__16u1__p3_0[] = {
  136940. -1.5, -0.5, 0.5, 1.5,
  136941. };
  136942. static long _vq_quantmap__16u1__p3_0[] = {
  136943. 3, 1, 0, 2, 4,
  136944. };
  136945. static encode_aux_threshmatch _vq_auxt__16u1__p3_0 = {
  136946. _vq_quantthresh__16u1__p3_0,
  136947. _vq_quantmap__16u1__p3_0,
  136948. 5,
  136949. 5
  136950. };
  136951. static static_codebook _16u1__p3_0 = {
  136952. 4, 625,
  136953. _vq_lengthlist__16u1__p3_0,
  136954. 1, -533725184, 1611661312, 3, 0,
  136955. _vq_quantlist__16u1__p3_0,
  136956. NULL,
  136957. &_vq_auxt__16u1__p3_0,
  136958. NULL,
  136959. 0
  136960. };
  136961. static long _vq_quantlist__16u1__p4_0[] = {
  136962. 2,
  136963. 1,
  136964. 3,
  136965. 0,
  136966. 4,
  136967. };
  136968. static long _vq_lengthlist__16u1__p4_0[] = {
  136969. 4, 5, 5, 8, 8, 6, 6, 7, 9, 9, 6, 6, 6, 9, 9, 9,
  136970. 10, 9,11,11, 9, 9,10,11,11, 6, 7, 7,10, 9, 7, 7,
  136971. 8, 9,10, 7, 7, 8,10,10,10,10,10,10,12, 9, 9,10,
  136972. 11,12, 6, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 7,10,
  136973. 10, 9,10, 9,12,11,10,10, 9,12,10, 9,10,10,12,11,
  136974. 10,10,10,12,12, 9,10,10,12,12,12,11,12,13,13,11,
  136975. 11,12,12,13, 9,10,10,11,12, 9,10,10,12,12,10,10,
  136976. 10,12,12,11,12,11,14,13,11,12,12,14,13, 5, 7, 7,
  136977. 10,10, 7, 8, 8,10,10, 7, 8, 7,10,10,10,10,10,12,
  136978. 12,10,10,10,12,12, 6, 8, 7,10,10, 7, 7, 9,10,11,
  136979. 8, 9, 9,11,10,10,10,11,11,13,10,10,11,12,13, 6,
  136980. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,10,11,10,11,
  136981. 10,13,11,10,11,10,12,12,10,11,10,12,11,10,10,10,
  136982. 12,13,10,11,11,13,12,11,11,13,11,14,12,12,13,14,
  136983. 14, 9,10,10,12,13,10,11,10,13,12,10,11,11,12,13,
  136984. 11,12,11,14,12,12,13,13,15,14, 5, 7, 7,10,10, 7,
  136985. 7, 8,10,10, 7, 8, 8,10,10,10,10,10,11,12,10,10,
  136986. 10,12,12, 7, 8, 8,10,10, 8, 9, 8,11,10, 7, 8, 9,
  136987. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 7, 8,10,
  136988. 10, 8, 8, 9,10,11, 7, 9, 7,11,10,10,11,11,13,12,
  136989. 11,11,10,13,11, 9,10,10,12,12,10,11,11,13,12,10,
  136990. 10,11,12,12,12,13,13,14,14,11,11,12,12,14,10,10,
  136991. 11,12,12,10,11,11,12,13,10,10,10,13,12,12,13,13,
  136992. 15,14,12,13,10,14,11, 8,10,10,12,12,10,11,10,13,
  136993. 13, 9,10,10,12,12,12,13,13,15,14,11,12,12,13,13,
  136994. 9,10,10,13,12,10,10,11,13,13,10,11,10,13,12,12,
  136995. 12,13,14,15,12,13,12,15,13, 9,10,10,12,13,10,11,
  136996. 10,13,12,10,10,11,12,13,12,14,12,15,13,12,12,13,
  136997. 14,15,11,12,11,14,13,11,11,12,14,15,12,13,12,15,
  136998. 14,13,11,15,11,16,13,14,14,16,15,11,12,12,14,14,
  136999. 11,12,11,14,13,12,12,13,14,15,13,14,12,16,12,14,
  137000. 14,14,15,15, 8,10,10,12,12, 9,10,10,12,12,10,10,
  137001. 11,13,13,11,12,12,13,13,12,13,13,14,15, 9,10,10,
  137002. 13,12,10,11,11,13,12,10,10,11,13,13,12,13,12,15,
  137003. 14,12,12,13,13,16, 9, 9,10,12,13,10,10,11,12,13,
  137004. 10,11,10,13,13,12,12,13,13,15,13,13,12,15,13,11,
  137005. 12,12,14,14,12,13,12,15,14,11,11,12,13,14,14,14,
  137006. 14,16,15,13,12,15,12,16,11,11,12,13,14,12,13,13,
  137007. 14,15,10,12,11,14,13,14,15,14,16,16,13,14,11,15,
  137008. 11,
  137009. };
  137010. static float _vq_quantthresh__16u1__p4_0[] = {
  137011. -1.5, -0.5, 0.5, 1.5,
  137012. };
  137013. static long _vq_quantmap__16u1__p4_0[] = {
  137014. 3, 1, 0, 2, 4,
  137015. };
  137016. static encode_aux_threshmatch _vq_auxt__16u1__p4_0 = {
  137017. _vq_quantthresh__16u1__p4_0,
  137018. _vq_quantmap__16u1__p4_0,
  137019. 5,
  137020. 5
  137021. };
  137022. static static_codebook _16u1__p4_0 = {
  137023. 4, 625,
  137024. _vq_lengthlist__16u1__p4_0,
  137025. 1, -533725184, 1611661312, 3, 0,
  137026. _vq_quantlist__16u1__p4_0,
  137027. NULL,
  137028. &_vq_auxt__16u1__p4_0,
  137029. NULL,
  137030. 0
  137031. };
  137032. static long _vq_quantlist__16u1__p5_0[] = {
  137033. 4,
  137034. 3,
  137035. 5,
  137036. 2,
  137037. 6,
  137038. 1,
  137039. 7,
  137040. 0,
  137041. 8,
  137042. };
  137043. static long _vq_lengthlist__16u1__p5_0[] = {
  137044. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  137045. 10,10, 4, 5, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  137046. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 7, 8, 8,
  137047. 10, 9,11,11,12,11, 7, 8, 8, 9, 9,11,11,12,12, 9,
  137048. 10,10,11,11,12,12,13,12, 9,10,10,11,11,12,12,12,
  137049. 13,
  137050. };
  137051. static float _vq_quantthresh__16u1__p5_0[] = {
  137052. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  137053. };
  137054. static long _vq_quantmap__16u1__p5_0[] = {
  137055. 7, 5, 3, 1, 0, 2, 4, 6,
  137056. 8,
  137057. };
  137058. static encode_aux_threshmatch _vq_auxt__16u1__p5_0 = {
  137059. _vq_quantthresh__16u1__p5_0,
  137060. _vq_quantmap__16u1__p5_0,
  137061. 9,
  137062. 9
  137063. };
  137064. static static_codebook _16u1__p5_0 = {
  137065. 2, 81,
  137066. _vq_lengthlist__16u1__p5_0,
  137067. 1, -531628032, 1611661312, 4, 0,
  137068. _vq_quantlist__16u1__p5_0,
  137069. NULL,
  137070. &_vq_auxt__16u1__p5_0,
  137071. NULL,
  137072. 0
  137073. };
  137074. static long _vq_quantlist__16u1__p6_0[] = {
  137075. 4,
  137076. 3,
  137077. 5,
  137078. 2,
  137079. 6,
  137080. 1,
  137081. 7,
  137082. 0,
  137083. 8,
  137084. };
  137085. static long _vq_lengthlist__16u1__p6_0[] = {
  137086. 3, 4, 4, 6, 6, 7, 7, 9, 9, 4, 4, 4, 6, 6, 8, 8,
  137087. 9, 9, 4, 4, 4, 6, 6, 7, 7, 9, 9, 6, 6, 6, 7, 7,
  137088. 8, 8,10, 9, 6, 6, 6, 7, 7, 8, 8, 9,10, 7, 8, 7,
  137089. 8, 8, 9, 9,10,10, 7, 8, 8, 8, 8, 9, 9,10,10, 9,
  137090. 9, 9,10,10,10,10,11,11, 9, 9, 9,10,10,10,10,11,
  137091. 11,
  137092. };
  137093. static float _vq_quantthresh__16u1__p6_0[] = {
  137094. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  137095. };
  137096. static long _vq_quantmap__16u1__p6_0[] = {
  137097. 7, 5, 3, 1, 0, 2, 4, 6,
  137098. 8,
  137099. };
  137100. static encode_aux_threshmatch _vq_auxt__16u1__p6_0 = {
  137101. _vq_quantthresh__16u1__p6_0,
  137102. _vq_quantmap__16u1__p6_0,
  137103. 9,
  137104. 9
  137105. };
  137106. static static_codebook _16u1__p6_0 = {
  137107. 2, 81,
  137108. _vq_lengthlist__16u1__p6_0,
  137109. 1, -531628032, 1611661312, 4, 0,
  137110. _vq_quantlist__16u1__p6_0,
  137111. NULL,
  137112. &_vq_auxt__16u1__p6_0,
  137113. NULL,
  137114. 0
  137115. };
  137116. static long _vq_quantlist__16u1__p7_0[] = {
  137117. 1,
  137118. 0,
  137119. 2,
  137120. };
  137121. static long _vq_lengthlist__16u1__p7_0[] = {
  137122. 1, 4, 4, 4, 8, 8, 4, 8, 8, 5,11, 9, 8,12,11, 8,
  137123. 12,11, 5,10,11, 8,11,12, 8,11,12, 4,11,11,11,14,
  137124. 13,10,13,13, 8,14,13,12,14,16,12,16,15, 8,14,14,
  137125. 13,16,14,12,15,16, 4,11,11,10,14,13,11,14,14, 8,
  137126. 15,14,12,15,15,12,14,16, 8,14,14,11,16,15,12,15,
  137127. 13,
  137128. };
  137129. static float _vq_quantthresh__16u1__p7_0[] = {
  137130. -5.5, 5.5,
  137131. };
  137132. static long _vq_quantmap__16u1__p7_0[] = {
  137133. 1, 0, 2,
  137134. };
  137135. static encode_aux_threshmatch _vq_auxt__16u1__p7_0 = {
  137136. _vq_quantthresh__16u1__p7_0,
  137137. _vq_quantmap__16u1__p7_0,
  137138. 3,
  137139. 3
  137140. };
  137141. static static_codebook _16u1__p7_0 = {
  137142. 4, 81,
  137143. _vq_lengthlist__16u1__p7_0,
  137144. 1, -529137664, 1618345984, 2, 0,
  137145. _vq_quantlist__16u1__p7_0,
  137146. NULL,
  137147. &_vq_auxt__16u1__p7_0,
  137148. NULL,
  137149. 0
  137150. };
  137151. static long _vq_quantlist__16u1__p7_1[] = {
  137152. 5,
  137153. 4,
  137154. 6,
  137155. 3,
  137156. 7,
  137157. 2,
  137158. 8,
  137159. 1,
  137160. 9,
  137161. 0,
  137162. 10,
  137163. };
  137164. static long _vq_lengthlist__16u1__p7_1[] = {
  137165. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 6, 5, 7, 7,
  137166. 8, 8, 8, 8, 8, 8, 4, 5, 6, 7, 7, 8, 8, 8, 8, 8,
  137167. 8, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  137168. 8, 8, 8, 9, 9, 9, 9, 7, 8, 8, 8, 8, 9, 9, 9,10,
  137169. 9,10, 7, 8, 8, 8, 8, 9, 9, 9, 9,10, 9, 8, 8, 8,
  137170. 9, 9,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9,10,
  137171. 10,10,10, 8, 8, 8, 9, 9, 9,10,10,10,10,10, 8, 8,
  137172. 8, 9, 9,10,10,10,10,10,10,
  137173. };
  137174. static float _vq_quantthresh__16u1__p7_1[] = {
  137175. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  137176. 3.5, 4.5,
  137177. };
  137178. static long _vq_quantmap__16u1__p7_1[] = {
  137179. 9, 7, 5, 3, 1, 0, 2, 4,
  137180. 6, 8, 10,
  137181. };
  137182. static encode_aux_threshmatch _vq_auxt__16u1__p7_1 = {
  137183. _vq_quantthresh__16u1__p7_1,
  137184. _vq_quantmap__16u1__p7_1,
  137185. 11,
  137186. 11
  137187. };
  137188. static static_codebook _16u1__p7_1 = {
  137189. 2, 121,
  137190. _vq_lengthlist__16u1__p7_1,
  137191. 1, -531365888, 1611661312, 4, 0,
  137192. _vq_quantlist__16u1__p7_1,
  137193. NULL,
  137194. &_vq_auxt__16u1__p7_1,
  137195. NULL,
  137196. 0
  137197. };
  137198. static long _vq_quantlist__16u1__p8_0[] = {
  137199. 5,
  137200. 4,
  137201. 6,
  137202. 3,
  137203. 7,
  137204. 2,
  137205. 8,
  137206. 1,
  137207. 9,
  137208. 0,
  137209. 10,
  137210. };
  137211. static long _vq_lengthlist__16u1__p8_0[] = {
  137212. 1, 4, 4, 5, 5, 8, 8,10,10,12,12, 4, 7, 7, 8, 8,
  137213. 9, 9,12,11,14,13, 4, 7, 7, 7, 8, 9,10,11,11,13,
  137214. 12, 5, 8, 8, 9, 9,11,11,12,13,15,14, 5, 7, 8, 9,
  137215. 9,11,11,13,13,17,15, 8, 9,10,11,11,12,13,17,14,
  137216. 17,16, 8,10, 9,11,11,12,12,13,15,15,17,10,11,11,
  137217. 12,13,14,15,15,16,16,17, 9,11,11,12,12,14,15,17,
  137218. 15,15,16,11,14,12,14,15,16,15,16,16,16,15,11,13,
  137219. 13,14,14,15,15,16,16,15,16,
  137220. };
  137221. static float _vq_quantthresh__16u1__p8_0[] = {
  137222. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  137223. 38.5, 49.5,
  137224. };
  137225. static long _vq_quantmap__16u1__p8_0[] = {
  137226. 9, 7, 5, 3, 1, 0, 2, 4,
  137227. 6, 8, 10,
  137228. };
  137229. static encode_aux_threshmatch _vq_auxt__16u1__p8_0 = {
  137230. _vq_quantthresh__16u1__p8_0,
  137231. _vq_quantmap__16u1__p8_0,
  137232. 11,
  137233. 11
  137234. };
  137235. static static_codebook _16u1__p8_0 = {
  137236. 2, 121,
  137237. _vq_lengthlist__16u1__p8_0,
  137238. 1, -524582912, 1618345984, 4, 0,
  137239. _vq_quantlist__16u1__p8_0,
  137240. NULL,
  137241. &_vq_auxt__16u1__p8_0,
  137242. NULL,
  137243. 0
  137244. };
  137245. static long _vq_quantlist__16u1__p8_1[] = {
  137246. 5,
  137247. 4,
  137248. 6,
  137249. 3,
  137250. 7,
  137251. 2,
  137252. 8,
  137253. 1,
  137254. 9,
  137255. 0,
  137256. 10,
  137257. };
  137258. static long _vq_lengthlist__16u1__p8_1[] = {
  137259. 2, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 4, 6, 6, 7, 7,
  137260. 8, 7, 8, 8, 8, 8, 4, 6, 6, 7, 7, 7, 7, 8, 8, 8,
  137261. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 9, 6, 7, 7, 7,
  137262. 7, 8, 8, 8, 8, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9,
  137263. 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  137264. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  137265. 9, 9, 9, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  137266. 8, 9, 9, 9, 9, 9, 9, 9, 9,
  137267. };
  137268. static float _vq_quantthresh__16u1__p8_1[] = {
  137269. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  137270. 3.5, 4.5,
  137271. };
  137272. static long _vq_quantmap__16u1__p8_1[] = {
  137273. 9, 7, 5, 3, 1, 0, 2, 4,
  137274. 6, 8, 10,
  137275. };
  137276. static encode_aux_threshmatch _vq_auxt__16u1__p8_1 = {
  137277. _vq_quantthresh__16u1__p8_1,
  137278. _vq_quantmap__16u1__p8_1,
  137279. 11,
  137280. 11
  137281. };
  137282. static static_codebook _16u1__p8_1 = {
  137283. 2, 121,
  137284. _vq_lengthlist__16u1__p8_1,
  137285. 1, -531365888, 1611661312, 4, 0,
  137286. _vq_quantlist__16u1__p8_1,
  137287. NULL,
  137288. &_vq_auxt__16u1__p8_1,
  137289. NULL,
  137290. 0
  137291. };
  137292. static long _vq_quantlist__16u1__p9_0[] = {
  137293. 7,
  137294. 6,
  137295. 8,
  137296. 5,
  137297. 9,
  137298. 4,
  137299. 10,
  137300. 3,
  137301. 11,
  137302. 2,
  137303. 12,
  137304. 1,
  137305. 13,
  137306. 0,
  137307. 14,
  137308. };
  137309. static long _vq_lengthlist__16u1__p9_0[] = {
  137310. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  137311. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  137312. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  137313. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  137314. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  137315. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  137316. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  137317. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  137318. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  137319. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  137320. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  137321. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  137322. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  137323. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  137324. 8,
  137325. };
  137326. static float _vq_quantthresh__16u1__p9_0[] = {
  137327. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  137328. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  137329. };
  137330. static long _vq_quantmap__16u1__p9_0[] = {
  137331. 13, 11, 9, 7, 5, 3, 1, 0,
  137332. 2, 4, 6, 8, 10, 12, 14,
  137333. };
  137334. static encode_aux_threshmatch _vq_auxt__16u1__p9_0 = {
  137335. _vq_quantthresh__16u1__p9_0,
  137336. _vq_quantmap__16u1__p9_0,
  137337. 15,
  137338. 15
  137339. };
  137340. static static_codebook _16u1__p9_0 = {
  137341. 2, 225,
  137342. _vq_lengthlist__16u1__p9_0,
  137343. 1, -514071552, 1627381760, 4, 0,
  137344. _vq_quantlist__16u1__p9_0,
  137345. NULL,
  137346. &_vq_auxt__16u1__p9_0,
  137347. NULL,
  137348. 0
  137349. };
  137350. static long _vq_quantlist__16u1__p9_1[] = {
  137351. 7,
  137352. 6,
  137353. 8,
  137354. 5,
  137355. 9,
  137356. 4,
  137357. 10,
  137358. 3,
  137359. 11,
  137360. 2,
  137361. 12,
  137362. 1,
  137363. 13,
  137364. 0,
  137365. 14,
  137366. };
  137367. static long _vq_lengthlist__16u1__p9_1[] = {
  137368. 1, 6, 5, 9, 9,10,10, 6, 7, 9, 9,10,10,10,10, 5,
  137369. 10, 8,10, 8,10,10, 8, 8,10, 9,10,10,10,10, 5, 8,
  137370. 9,10,10,10,10, 8,10,10,10,10,10,10,10, 9,10,10,
  137371. 10,10,10,10, 9, 9,10,10,10,10,10,10, 9, 9, 8, 9,
  137372. 10,10,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  137373. 10,10,10,10,10,10,10,10,10,10,10, 8,10,10,10,10,
  137374. 10,10,10,10,10,10,10,10,10, 6, 8, 8,10,10,10, 8,
  137375. 10,10,10,10,10,10,10,10, 5, 8, 8,10,10,10, 9, 9,
  137376. 10,10,10,10,10,10,10,10, 9,10,10,10,10,10,10,10,
  137377. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  137378. 10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  137379. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  137380. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  137381. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  137382. 9,
  137383. };
  137384. static float _vq_quantthresh__16u1__p9_1[] = {
  137385. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  137386. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  137387. };
  137388. static long _vq_quantmap__16u1__p9_1[] = {
  137389. 13, 11, 9, 7, 5, 3, 1, 0,
  137390. 2, 4, 6, 8, 10, 12, 14,
  137391. };
  137392. static encode_aux_threshmatch _vq_auxt__16u1__p9_1 = {
  137393. _vq_quantthresh__16u1__p9_1,
  137394. _vq_quantmap__16u1__p9_1,
  137395. 15,
  137396. 15
  137397. };
  137398. static static_codebook _16u1__p9_1 = {
  137399. 2, 225,
  137400. _vq_lengthlist__16u1__p9_1,
  137401. 1, -522338304, 1620115456, 4, 0,
  137402. _vq_quantlist__16u1__p9_1,
  137403. NULL,
  137404. &_vq_auxt__16u1__p9_1,
  137405. NULL,
  137406. 0
  137407. };
  137408. static long _vq_quantlist__16u1__p9_2[] = {
  137409. 8,
  137410. 7,
  137411. 9,
  137412. 6,
  137413. 10,
  137414. 5,
  137415. 11,
  137416. 4,
  137417. 12,
  137418. 3,
  137419. 13,
  137420. 2,
  137421. 14,
  137422. 1,
  137423. 15,
  137424. 0,
  137425. 16,
  137426. };
  137427. static long _vq_lengthlist__16u1__p9_2[] = {
  137428. 1, 6, 6, 7, 8, 8,11,10, 9, 9,11, 9,10, 9,11,11,
  137429. 9, 6, 7, 6,11, 8,11, 9,10,10,11, 9,11,10,10,10,
  137430. 11, 9, 5, 7, 7, 8, 8,10,11, 8, 8,11, 9, 9,10,11,
  137431. 9,10,11, 8, 9, 6, 8, 8, 9, 9,10,10,11,11,11, 9,
  137432. 11,10, 9,11, 8, 8, 8, 9, 8, 9,10,11, 9, 9,11,11,
  137433. 10, 9, 9,11,10, 8,11, 8, 9, 8,11, 9,10, 9,10,11,
  137434. 11,10,10, 9,10,10, 8, 8, 9,10,10,10, 9,11, 9,10,
  137435. 11,11,11,11,10, 9,11, 9, 9,11,11,10, 8,11,11,11,
  137436. 9,10,10,11,10,11,11, 9,11,10, 9,11,10,10,10,10,
  137437. 9,11,10,11,10, 9, 9,10,11, 9, 8,10,11,11,10,10,
  137438. 11, 9,11,10,11,11,10,11, 9, 9, 8,10, 8, 9,11, 9,
  137439. 8,10,10, 9,11,10,11,10,11, 9,11, 8,10,11,11,11,
  137440. 11,10,10,11,11,11,11,10,11,11,10, 9, 8,10,10, 9,
  137441. 11,10,11,11,11, 9, 9, 9,11,11,11,10,10, 9, 9,10,
  137442. 9,11,11,11,11, 8,10,11,10,11,11,10,11,11, 9, 9,
  137443. 9,10, 9,11, 9,11,11,11,11,11,10,11,11,10,11,10,
  137444. 11,11, 9,11,10,11,10, 9,10, 9,10,10,11,11,11,11,
  137445. 9,10, 9,10,11,11,10,11,11,11,11,11,11,10,11,11,
  137446. 10,
  137447. };
  137448. static float _vq_quantthresh__16u1__p9_2[] = {
  137449. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  137450. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  137451. };
  137452. static long _vq_quantmap__16u1__p9_2[] = {
  137453. 15, 13, 11, 9, 7, 5, 3, 1,
  137454. 0, 2, 4, 6, 8, 10, 12, 14,
  137455. 16,
  137456. };
  137457. static encode_aux_threshmatch _vq_auxt__16u1__p9_2 = {
  137458. _vq_quantthresh__16u1__p9_2,
  137459. _vq_quantmap__16u1__p9_2,
  137460. 17,
  137461. 17
  137462. };
  137463. static static_codebook _16u1__p9_2 = {
  137464. 2, 289,
  137465. _vq_lengthlist__16u1__p9_2,
  137466. 1, -529530880, 1611661312, 5, 0,
  137467. _vq_quantlist__16u1__p9_2,
  137468. NULL,
  137469. &_vq_auxt__16u1__p9_2,
  137470. NULL,
  137471. 0
  137472. };
  137473. static long _huff_lengthlist__16u1__short[] = {
  137474. 5, 7,10, 9,11,10,15,11,13,16, 6, 4, 6, 6, 7, 7,
  137475. 10, 9,12,16,10, 6, 5, 6, 6, 7,10,11,16,16, 9, 6,
  137476. 7, 6, 7, 7,10, 8,14,16,11, 6, 5, 4, 5, 6, 8, 9,
  137477. 15,16, 9, 6, 6, 5, 6, 6, 9, 8,14,16,12, 7, 6, 6,
  137478. 5, 6, 6, 7,13,16, 8, 6, 7, 6, 5, 5, 4, 4,11,16,
  137479. 9, 8, 9, 9, 7, 7, 6, 5,13,16,14,14,16,15,16,15,
  137480. 16,16,16,16,
  137481. };
  137482. static static_codebook _huff_book__16u1__short = {
  137483. 2, 100,
  137484. _huff_lengthlist__16u1__short,
  137485. 0, 0, 0, 0, 0,
  137486. NULL,
  137487. NULL,
  137488. NULL,
  137489. NULL,
  137490. 0
  137491. };
  137492. static long _huff_lengthlist__16u2__long[] = {
  137493. 5, 7,10,10,10,11,11,13,18,19, 6, 5, 5, 6, 7, 8,
  137494. 9,12,19,19, 8, 5, 4, 4, 6, 7, 9,13,19,19, 8, 5,
  137495. 4, 4, 5, 6, 8,12,17,19, 7, 5, 5, 4, 4, 5, 7,12,
  137496. 18,18, 8, 7, 7, 6, 5, 5, 6,10,18,18, 9, 9, 9, 8,
  137497. 6, 5, 6, 9,18,18,11,13,13,13, 8, 7, 7, 9,16,18,
  137498. 13,17,18,16,11, 9, 9, 9,17,18,15,18,18,18,15,13,
  137499. 13,14,18,18,
  137500. };
  137501. static static_codebook _huff_book__16u2__long = {
  137502. 2, 100,
  137503. _huff_lengthlist__16u2__long,
  137504. 0, 0, 0, 0, 0,
  137505. NULL,
  137506. NULL,
  137507. NULL,
  137508. NULL,
  137509. 0
  137510. };
  137511. static long _huff_lengthlist__16u2__short[] = {
  137512. 8,11,12,12,14,15,16,16,16,16, 9, 7, 7, 8, 9,11,
  137513. 13,14,16,16,13, 7, 6, 6, 7, 9,12,13,15,16,15, 7,
  137514. 6, 5, 4, 6,10,11,14,16,12, 8, 7, 4, 2, 4, 7,10,
  137515. 14,16,11, 9, 7, 5, 3, 4, 6, 9,14,16,11,10, 9, 7,
  137516. 5, 5, 6, 9,16,16,10,10, 9, 8, 6, 6, 7,10,16,16,
  137517. 11,11,11,10,10,10,11,14,16,16,16,14,14,13,14,16,
  137518. 16,16,16,16,
  137519. };
  137520. static static_codebook _huff_book__16u2__short = {
  137521. 2, 100,
  137522. _huff_lengthlist__16u2__short,
  137523. 0, 0, 0, 0, 0,
  137524. NULL,
  137525. NULL,
  137526. NULL,
  137527. NULL,
  137528. 0
  137529. };
  137530. static long _vq_quantlist__16u2_p1_0[] = {
  137531. 1,
  137532. 0,
  137533. 2,
  137534. };
  137535. static long _vq_lengthlist__16u2_p1_0[] = {
  137536. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 7, 9, 9, 7,
  137537. 9, 9, 5, 7, 7, 7, 9, 9, 7, 9, 9, 5, 7, 7, 8, 9,
  137538. 9, 7, 9, 9, 7, 9, 9, 9,10,10, 9,10,10, 7, 9, 9,
  137539. 9,10,10, 9,10,11, 5, 7, 8, 8, 9, 9, 8, 9, 9, 7,
  137540. 9, 9, 9,10,10, 9, 9,10, 7, 9, 9, 9,10,10, 9,11,
  137541. 10,
  137542. };
  137543. static float _vq_quantthresh__16u2_p1_0[] = {
  137544. -0.5, 0.5,
  137545. };
  137546. static long _vq_quantmap__16u2_p1_0[] = {
  137547. 1, 0, 2,
  137548. };
  137549. static encode_aux_threshmatch _vq_auxt__16u2_p1_0 = {
  137550. _vq_quantthresh__16u2_p1_0,
  137551. _vq_quantmap__16u2_p1_0,
  137552. 3,
  137553. 3
  137554. };
  137555. static static_codebook _16u2_p1_0 = {
  137556. 4, 81,
  137557. _vq_lengthlist__16u2_p1_0,
  137558. 1, -535822336, 1611661312, 2, 0,
  137559. _vq_quantlist__16u2_p1_0,
  137560. NULL,
  137561. &_vq_auxt__16u2_p1_0,
  137562. NULL,
  137563. 0
  137564. };
  137565. static long _vq_quantlist__16u2_p2_0[] = {
  137566. 2,
  137567. 1,
  137568. 3,
  137569. 0,
  137570. 4,
  137571. };
  137572. static long _vq_lengthlist__16u2_p2_0[] = {
  137573. 3, 5, 5, 8, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 9,
  137574. 10, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  137575. 8,10,10, 7, 8, 8,10,10,10,10,10,12,12, 9,10,10,
  137576. 11,12, 5, 7, 7, 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,
  137577. 10, 9,10,10,12,11,10,10,10,12,12, 9,10,10,12,12,
  137578. 10,11,10,13,12, 9,10,10,12,12,12,12,12,14,14,11,
  137579. 12,12,13,14, 9,10,10,12,12, 9,10,10,12,12,10,10,
  137580. 10,12,12,11,12,12,14,13,12,13,12,14,14, 5, 7, 7,
  137581. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,12,
  137582. 12,10,10,11,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  137583. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,12,13, 7,
  137584. 8, 8,10,10, 8, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  137585. 10,13,12,10,11,11,13,13, 9,11,10,13,13,10,11,11,
  137586. 13,13,10,11,11,13,13,12,12,13,13,15,12,12,13,14,
  137587. 15, 9,10,10,12,12,10,11,10,13,12,10,11,11,13,13,
  137588. 11,13,11,14,13,12,13,13,15,15, 5, 7, 7, 9, 9, 7,
  137589. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,12,10,10,
  137590. 11,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11, 8, 8, 9,
  137591. 10,11,10,11,11,13,13,10,10,11,12,13, 7, 8, 8,10,
  137592. 11, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,12,
  137593. 11,11,11,13,12, 9,10,10,12,12,10,11,11,13,13,10,
  137594. 10,11,12,13,12,13,13,15,14,11,11,13,12,14,10,10,
  137595. 11,13,13,10,11,11,13,13,10,11,11,13,13,12,13,13,
  137596. 14,14,12,13,12,14,13, 8,10, 9,12,12, 9,11,10,13,
  137597. 13, 9,10,10,12,13,12,13,13,14,14,12,12,13,14,14,
  137598. 9,11,10,13,13,10,11,11,13,13,10,11,11,13,13,12,
  137599. 13,13,15,15,13,13,13,14,15, 9,10,10,12,13,10,11,
  137600. 10,13,12,10,11,11,13,13,12,13,12,15,14,13,13,13,
  137601. 14,15,11,12,12,15,14,12,12,13,15,15,12,13,13,15,
  137602. 14,14,13,15,14,16,13,14,15,16,16,11,12,12,14,14,
  137603. 11,12,12,15,14,12,13,13,15,15,13,14,13,16,14,14,
  137604. 14,14,16,16, 8, 9, 9,12,12, 9,10,10,13,12, 9,10,
  137605. 10,13,13,12,12,12,14,14,12,12,13,15,15, 9,10,10,
  137606. 13,12,10,11,11,13,13,10,10,11,13,14,12,13,13,15,
  137607. 15,12,12,13,14,15, 9,10,10,13,13,10,11,11,13,13,
  137608. 10,11,11,13,13,12,13,13,14,14,13,14,13,15,14,11,
  137609. 12,12,14,14,12,13,13,15,14,11,12,12,14,15,14,14,
  137610. 14,16,15,13,12,14,14,16,11,12,13,14,15,12,13,13,
  137611. 14,16,12,13,12,15,14,13,15,14,16,16,14,15,13,16,
  137612. 13,
  137613. };
  137614. static float _vq_quantthresh__16u2_p2_0[] = {
  137615. -1.5, -0.5, 0.5, 1.5,
  137616. };
  137617. static long _vq_quantmap__16u2_p2_0[] = {
  137618. 3, 1, 0, 2, 4,
  137619. };
  137620. static encode_aux_threshmatch _vq_auxt__16u2_p2_0 = {
  137621. _vq_quantthresh__16u2_p2_0,
  137622. _vq_quantmap__16u2_p2_0,
  137623. 5,
  137624. 5
  137625. };
  137626. static static_codebook _16u2_p2_0 = {
  137627. 4, 625,
  137628. _vq_lengthlist__16u2_p2_0,
  137629. 1, -533725184, 1611661312, 3, 0,
  137630. _vq_quantlist__16u2_p2_0,
  137631. NULL,
  137632. &_vq_auxt__16u2_p2_0,
  137633. NULL,
  137634. 0
  137635. };
  137636. static long _vq_quantlist__16u2_p3_0[] = {
  137637. 4,
  137638. 3,
  137639. 5,
  137640. 2,
  137641. 6,
  137642. 1,
  137643. 7,
  137644. 0,
  137645. 8,
  137646. };
  137647. static long _vq_lengthlist__16u2_p3_0[] = {
  137648. 2, 4, 4, 6, 6, 7, 7, 9, 9, 4, 5, 5, 6, 6, 8, 7,
  137649. 9, 9, 4, 5, 5, 6, 6, 7, 8, 9, 9, 6, 6, 6, 7, 7,
  137650. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8, 9,10, 7, 8, 7,
  137651. 8, 8, 9, 9,10,10, 7, 8, 8, 8, 8, 9, 9,10,10, 9,
  137652. 9, 9,10, 9,10,10,11,11, 9, 9, 9,10,10,10,10,11,
  137653. 11,
  137654. };
  137655. static float _vq_quantthresh__16u2_p3_0[] = {
  137656. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  137657. };
  137658. static long _vq_quantmap__16u2_p3_0[] = {
  137659. 7, 5, 3, 1, 0, 2, 4, 6,
  137660. 8,
  137661. };
  137662. static encode_aux_threshmatch _vq_auxt__16u2_p3_0 = {
  137663. _vq_quantthresh__16u2_p3_0,
  137664. _vq_quantmap__16u2_p3_0,
  137665. 9,
  137666. 9
  137667. };
  137668. static static_codebook _16u2_p3_0 = {
  137669. 2, 81,
  137670. _vq_lengthlist__16u2_p3_0,
  137671. 1, -531628032, 1611661312, 4, 0,
  137672. _vq_quantlist__16u2_p3_0,
  137673. NULL,
  137674. &_vq_auxt__16u2_p3_0,
  137675. NULL,
  137676. 0
  137677. };
  137678. static long _vq_quantlist__16u2_p4_0[] = {
  137679. 8,
  137680. 7,
  137681. 9,
  137682. 6,
  137683. 10,
  137684. 5,
  137685. 11,
  137686. 4,
  137687. 12,
  137688. 3,
  137689. 13,
  137690. 2,
  137691. 14,
  137692. 1,
  137693. 15,
  137694. 0,
  137695. 16,
  137696. };
  137697. static long _vq_lengthlist__16u2_p4_0[] = {
  137698. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,11,
  137699. 11, 5, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  137700. 12,11, 5, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  137701. 11,12,12, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  137702. 11,11,12,12, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,
  137703. 10,11,11,12,12, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,
  137704. 11,11,12,12,12,12, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  137705. 10,11,11,11,12,12,12, 9, 9, 9, 9, 9, 9,10,10,10,
  137706. 10,10,11,11,12,12,13,13, 8, 9, 9, 9, 9,10, 9,10,
  137707. 10,10,10,11,11,12,12,13,13, 9, 9, 9, 9, 9,10,10,
  137708. 10,10,11,11,11,12,12,12,13,13, 9, 9, 9, 9, 9,10,
  137709. 10,10,10,11,11,12,11,12,12,13,13,10,10,10,10,10,
  137710. 11,11,11,11,11,12,12,12,12,13,13,14,10,10,10,10,
  137711. 10,11,11,11,11,12,11,12,12,13,12,13,13,11,11,11,
  137712. 11,11,12,12,12,12,12,12,13,13,13,13,14,14,11,11,
  137713. 11,11,11,12,12,12,12,12,12,13,12,13,13,14,14,11,
  137714. 12,12,12,12,12,12,13,13,13,13,13,13,14,14,14,14,
  137715. 11,12,12,12,12,12,12,13,13,13,13,14,13,14,14,14,
  137716. 14,
  137717. };
  137718. static float _vq_quantthresh__16u2_p4_0[] = {
  137719. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  137720. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  137721. };
  137722. static long _vq_quantmap__16u2_p4_0[] = {
  137723. 15, 13, 11, 9, 7, 5, 3, 1,
  137724. 0, 2, 4, 6, 8, 10, 12, 14,
  137725. 16,
  137726. };
  137727. static encode_aux_threshmatch _vq_auxt__16u2_p4_0 = {
  137728. _vq_quantthresh__16u2_p4_0,
  137729. _vq_quantmap__16u2_p4_0,
  137730. 17,
  137731. 17
  137732. };
  137733. static static_codebook _16u2_p4_0 = {
  137734. 2, 289,
  137735. _vq_lengthlist__16u2_p4_0,
  137736. 1, -529530880, 1611661312, 5, 0,
  137737. _vq_quantlist__16u2_p4_0,
  137738. NULL,
  137739. &_vq_auxt__16u2_p4_0,
  137740. NULL,
  137741. 0
  137742. };
  137743. static long _vq_quantlist__16u2_p5_0[] = {
  137744. 1,
  137745. 0,
  137746. 2,
  137747. };
  137748. static long _vq_lengthlist__16u2_p5_0[] = {
  137749. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 7,10, 9, 7,
  137750. 10, 9, 5, 8, 9, 7, 9,10, 7, 9,10, 4, 9, 9, 9,11,
  137751. 11, 8,11,11, 7,11,11,10,10,13,10,14,13, 7,11,11,
  137752. 10,13,11,10,13,14, 5, 9, 9, 8,11,11, 9,11,11, 7,
  137753. 11,11,10,14,13,10,12,14, 7,11,11,10,13,13,10,13,
  137754. 10,
  137755. };
  137756. static float _vq_quantthresh__16u2_p5_0[] = {
  137757. -5.5, 5.5,
  137758. };
  137759. static long _vq_quantmap__16u2_p5_0[] = {
  137760. 1, 0, 2,
  137761. };
  137762. static encode_aux_threshmatch _vq_auxt__16u2_p5_0 = {
  137763. _vq_quantthresh__16u2_p5_0,
  137764. _vq_quantmap__16u2_p5_0,
  137765. 3,
  137766. 3
  137767. };
  137768. static static_codebook _16u2_p5_0 = {
  137769. 4, 81,
  137770. _vq_lengthlist__16u2_p5_0,
  137771. 1, -529137664, 1618345984, 2, 0,
  137772. _vq_quantlist__16u2_p5_0,
  137773. NULL,
  137774. &_vq_auxt__16u2_p5_0,
  137775. NULL,
  137776. 0
  137777. };
  137778. static long _vq_quantlist__16u2_p5_1[] = {
  137779. 5,
  137780. 4,
  137781. 6,
  137782. 3,
  137783. 7,
  137784. 2,
  137785. 8,
  137786. 1,
  137787. 9,
  137788. 0,
  137789. 10,
  137790. };
  137791. static long _vq_lengthlist__16u2_p5_1[] = {
  137792. 2, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 5, 5, 5, 7, 7,
  137793. 7, 7, 8, 8, 8, 8, 5, 5, 6, 7, 7, 7, 7, 8, 8, 8,
  137794. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  137795. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 9, 9,
  137796. 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  137797. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  137798. 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  137799. 8, 8, 8, 9, 9, 9, 9, 9, 9,
  137800. };
  137801. static float _vq_quantthresh__16u2_p5_1[] = {
  137802. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  137803. 3.5, 4.5,
  137804. };
  137805. static long _vq_quantmap__16u2_p5_1[] = {
  137806. 9, 7, 5, 3, 1, 0, 2, 4,
  137807. 6, 8, 10,
  137808. };
  137809. static encode_aux_threshmatch _vq_auxt__16u2_p5_1 = {
  137810. _vq_quantthresh__16u2_p5_1,
  137811. _vq_quantmap__16u2_p5_1,
  137812. 11,
  137813. 11
  137814. };
  137815. static static_codebook _16u2_p5_1 = {
  137816. 2, 121,
  137817. _vq_lengthlist__16u2_p5_1,
  137818. 1, -531365888, 1611661312, 4, 0,
  137819. _vq_quantlist__16u2_p5_1,
  137820. NULL,
  137821. &_vq_auxt__16u2_p5_1,
  137822. NULL,
  137823. 0
  137824. };
  137825. static long _vq_quantlist__16u2_p6_0[] = {
  137826. 6,
  137827. 5,
  137828. 7,
  137829. 4,
  137830. 8,
  137831. 3,
  137832. 9,
  137833. 2,
  137834. 10,
  137835. 1,
  137836. 11,
  137837. 0,
  137838. 12,
  137839. };
  137840. static long _vq_lengthlist__16u2_p6_0[] = {
  137841. 1, 4, 4, 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 6, 6,
  137842. 8, 8, 9, 9, 9, 9,10,10,12,11, 4, 6, 6, 8, 8, 9,
  137843. 9, 9, 9,10,10,11,12, 7, 8, 8, 9, 9,10,10,10,10,
  137844. 12,12,13,12, 7, 8, 8, 9, 9,10,10,10,10,11,12,12,
  137845. 12, 8, 9, 9,10,10,11,11,11,11,12,12,13,13, 8, 9,
  137846. 9,10,10,11,11,11,11,12,13,13,13, 8, 9, 9,10,10,
  137847. 11,11,12,12,13,13,14,14, 8, 9, 9,10,10,11,11,12,
  137848. 12,13,13,14,14, 9,10,10,11,12,13,12,13,14,14,14,
  137849. 14,14, 9,10,10,11,12,12,13,13,13,14,14,14,14,10,
  137850. 11,11,12,12,13,13,14,14,15,15,15,15,10,11,11,12,
  137851. 12,13,13,14,14,14,14,15,15,
  137852. };
  137853. static float _vq_quantthresh__16u2_p6_0[] = {
  137854. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  137855. 12.5, 17.5, 22.5, 27.5,
  137856. };
  137857. static long _vq_quantmap__16u2_p6_0[] = {
  137858. 11, 9, 7, 5, 3, 1, 0, 2,
  137859. 4, 6, 8, 10, 12,
  137860. };
  137861. static encode_aux_threshmatch _vq_auxt__16u2_p6_0 = {
  137862. _vq_quantthresh__16u2_p6_0,
  137863. _vq_quantmap__16u2_p6_0,
  137864. 13,
  137865. 13
  137866. };
  137867. static static_codebook _16u2_p6_0 = {
  137868. 2, 169,
  137869. _vq_lengthlist__16u2_p6_0,
  137870. 1, -526516224, 1616117760, 4, 0,
  137871. _vq_quantlist__16u2_p6_0,
  137872. NULL,
  137873. &_vq_auxt__16u2_p6_0,
  137874. NULL,
  137875. 0
  137876. };
  137877. static long _vq_quantlist__16u2_p6_1[] = {
  137878. 2,
  137879. 1,
  137880. 3,
  137881. 0,
  137882. 4,
  137883. };
  137884. static long _vq_lengthlist__16u2_p6_1[] = {
  137885. 2, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  137886. 5, 5, 6, 6, 5, 5, 5, 6, 6,
  137887. };
  137888. static float _vq_quantthresh__16u2_p6_1[] = {
  137889. -1.5, -0.5, 0.5, 1.5,
  137890. };
  137891. static long _vq_quantmap__16u2_p6_1[] = {
  137892. 3, 1, 0, 2, 4,
  137893. };
  137894. static encode_aux_threshmatch _vq_auxt__16u2_p6_1 = {
  137895. _vq_quantthresh__16u2_p6_1,
  137896. _vq_quantmap__16u2_p6_1,
  137897. 5,
  137898. 5
  137899. };
  137900. static static_codebook _16u2_p6_1 = {
  137901. 2, 25,
  137902. _vq_lengthlist__16u2_p6_1,
  137903. 1, -533725184, 1611661312, 3, 0,
  137904. _vq_quantlist__16u2_p6_1,
  137905. NULL,
  137906. &_vq_auxt__16u2_p6_1,
  137907. NULL,
  137908. 0
  137909. };
  137910. static long _vq_quantlist__16u2_p7_0[] = {
  137911. 6,
  137912. 5,
  137913. 7,
  137914. 4,
  137915. 8,
  137916. 3,
  137917. 9,
  137918. 2,
  137919. 10,
  137920. 1,
  137921. 11,
  137922. 0,
  137923. 12,
  137924. };
  137925. static long _vq_lengthlist__16u2_p7_0[] = {
  137926. 1, 4, 4, 7, 7, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 6,
  137927. 9, 9, 9, 9, 9, 9,10,10,11,11, 4, 6, 6, 8, 9, 9,
  137928. 9, 9, 9,10,11,12,11, 7, 8, 9,10,10,10,10,11,10,
  137929. 11,12,12,13, 7, 9, 9,10,10,10,10,10,10,11,12,13,
  137930. 13, 7, 9, 8,10,10,11,11,11,12,12,13,13,14, 7, 9,
  137931. 9,10,10,11,11,11,12,13,13,13,13, 8, 9, 9,10,11,
  137932. 11,12,12,12,13,13,13,13, 8, 9, 9,10,11,11,11,12,
  137933. 12,13,13,14,14, 9,10,10,12,11,12,13,13,13,14,13,
  137934. 13,13, 9,10,10,11,11,12,12,13,14,13,13,14,13,10,
  137935. 11,11,12,13,14,14,14,15,14,14,14,14,10,11,11,12,
  137936. 12,13,13,13,14,14,14,15,14,
  137937. };
  137938. static float _vq_quantthresh__16u2_p7_0[] = {
  137939. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  137940. 27.5, 38.5, 49.5, 60.5,
  137941. };
  137942. static long _vq_quantmap__16u2_p7_0[] = {
  137943. 11, 9, 7, 5, 3, 1, 0, 2,
  137944. 4, 6, 8, 10, 12,
  137945. };
  137946. static encode_aux_threshmatch _vq_auxt__16u2_p7_0 = {
  137947. _vq_quantthresh__16u2_p7_0,
  137948. _vq_quantmap__16u2_p7_0,
  137949. 13,
  137950. 13
  137951. };
  137952. static static_codebook _16u2_p7_0 = {
  137953. 2, 169,
  137954. _vq_lengthlist__16u2_p7_0,
  137955. 1, -523206656, 1618345984, 4, 0,
  137956. _vq_quantlist__16u2_p7_0,
  137957. NULL,
  137958. &_vq_auxt__16u2_p7_0,
  137959. NULL,
  137960. 0
  137961. };
  137962. static long _vq_quantlist__16u2_p7_1[] = {
  137963. 5,
  137964. 4,
  137965. 6,
  137966. 3,
  137967. 7,
  137968. 2,
  137969. 8,
  137970. 1,
  137971. 9,
  137972. 0,
  137973. 10,
  137974. };
  137975. static long _vq_lengthlist__16u2_p7_1[] = {
  137976. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  137977. 7, 7, 7, 7, 8, 8, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8,
  137978. 8, 6, 6, 7, 7, 7, 8, 7, 8, 8, 8, 8, 6, 7, 7, 7,
  137979. 7, 7, 7, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  137980. 8, 8, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7,
  137981. 8, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8,
  137982. 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  137983. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  137984. };
  137985. static float _vq_quantthresh__16u2_p7_1[] = {
  137986. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  137987. 3.5, 4.5,
  137988. };
  137989. static long _vq_quantmap__16u2_p7_1[] = {
  137990. 9, 7, 5, 3, 1, 0, 2, 4,
  137991. 6, 8, 10,
  137992. };
  137993. static encode_aux_threshmatch _vq_auxt__16u2_p7_1 = {
  137994. _vq_quantthresh__16u2_p7_1,
  137995. _vq_quantmap__16u2_p7_1,
  137996. 11,
  137997. 11
  137998. };
  137999. static static_codebook _16u2_p7_1 = {
  138000. 2, 121,
  138001. _vq_lengthlist__16u2_p7_1,
  138002. 1, -531365888, 1611661312, 4, 0,
  138003. _vq_quantlist__16u2_p7_1,
  138004. NULL,
  138005. &_vq_auxt__16u2_p7_1,
  138006. NULL,
  138007. 0
  138008. };
  138009. static long _vq_quantlist__16u2_p8_0[] = {
  138010. 7,
  138011. 6,
  138012. 8,
  138013. 5,
  138014. 9,
  138015. 4,
  138016. 10,
  138017. 3,
  138018. 11,
  138019. 2,
  138020. 12,
  138021. 1,
  138022. 13,
  138023. 0,
  138024. 14,
  138025. };
  138026. static long _vq_lengthlist__16u2_p8_0[] = {
  138027. 1, 5, 5, 7, 7, 8, 8, 7, 7, 8, 8,10, 9,11,11, 4,
  138028. 6, 6, 8, 8,10, 9, 9, 8, 9, 9,10,10,12,14, 4, 6,
  138029. 7, 8, 9, 9,10, 9, 8, 9, 9,10,12,12,11, 7, 8, 8,
  138030. 10,10,10,10, 9, 9,10,10,11,13,13,12, 7, 8, 8, 9,
  138031. 11,11,10, 9, 9,11,10,12,11,11,14, 8, 9, 9,11,10,
  138032. 11,11,10,10,11,11,13,12,14,12, 8, 9, 9,11,12,11,
  138033. 11,10,10,12,11,12,12,12,14, 7, 8, 8, 9, 9,10,10,
  138034. 10,11,12,11,13,13,14,12, 7, 8, 9, 9, 9,10,10,11,
  138035. 11,11,12,12,14,14,14, 8,10, 9,10,11,11,11,11,14,
  138036. 12,12,13,14,14,13, 9, 9, 9,10,11,11,11,12,12,12,
  138037. 14,12,14,13,14,10,10,10,12,11,12,11,14,13,14,13,
  138038. 14,14,13,14, 9,10,10,11,12,11,13,12,13,13,14,14,
  138039. 14,13,14,10,13,13,12,12,11,12,14,13,14,13,14,12,
  138040. 14,13,10,11,11,12,11,12,12,14,14,14,13,14,14,14,
  138041. 14,
  138042. };
  138043. static float _vq_quantthresh__16u2_p8_0[] = {
  138044. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  138045. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  138046. };
  138047. static long _vq_quantmap__16u2_p8_0[] = {
  138048. 13, 11, 9, 7, 5, 3, 1, 0,
  138049. 2, 4, 6, 8, 10, 12, 14,
  138050. };
  138051. static encode_aux_threshmatch _vq_auxt__16u2_p8_0 = {
  138052. _vq_quantthresh__16u2_p8_0,
  138053. _vq_quantmap__16u2_p8_0,
  138054. 15,
  138055. 15
  138056. };
  138057. static static_codebook _16u2_p8_0 = {
  138058. 2, 225,
  138059. _vq_lengthlist__16u2_p8_0,
  138060. 1, -520986624, 1620377600, 4, 0,
  138061. _vq_quantlist__16u2_p8_0,
  138062. NULL,
  138063. &_vq_auxt__16u2_p8_0,
  138064. NULL,
  138065. 0
  138066. };
  138067. static long _vq_quantlist__16u2_p8_1[] = {
  138068. 10,
  138069. 9,
  138070. 11,
  138071. 8,
  138072. 12,
  138073. 7,
  138074. 13,
  138075. 6,
  138076. 14,
  138077. 5,
  138078. 15,
  138079. 4,
  138080. 16,
  138081. 3,
  138082. 17,
  138083. 2,
  138084. 18,
  138085. 1,
  138086. 19,
  138087. 0,
  138088. 20,
  138089. };
  138090. static long _vq_lengthlist__16u2_p8_1[] = {
  138091. 2, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10, 9,10, 9, 9,
  138092. 9,10,10,10,10, 5, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,
  138093. 10, 9,10,10,10,10,10,10,11,10, 5, 6, 6, 7, 7, 8,
  138094. 8, 8, 9, 9,10,10,10,10,10,10,10,10,10,10,10, 7,
  138095. 7, 7, 8, 8, 9, 8, 9, 9,10, 9,10,10,10,10,10,10,
  138096. 11,10,11,10, 7, 7, 7, 8, 8, 8, 9, 9, 9,10, 9,10,
  138097. 10,10,10,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9,
  138098. 10, 9,10,10,10,10,10,10,10,11,10,10,11,10, 8, 8,
  138099. 8, 8, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,
  138100. 11,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  138101. 11,10,11,10,11,10,11,10, 8, 9, 9, 9, 9, 9,10,10,
  138102. 10,10,10,10,10,10,10,10,11,11,10,10,10, 9,10, 9,
  138103. 9,10,10,10,11,10,10,10,10,10,10,10,10,11,11,11,
  138104. 11,11, 9, 9, 9,10, 9,10,10,10,10,10,10,11,10,11,
  138105. 10,11,11,11,11,10,10, 9,10, 9,10,10,10,10,11,10,
  138106. 10,10,10,10,11,10,11,10,11,10,10,11, 9,10,10,10,
  138107. 10,10,10,10,10,10,11,10,10,11,11,10,11,11,11,11,
  138108. 11, 9, 9,10,10,10,10,10,11,10,10,11,10,10,11,10,
  138109. 10,11,11,11,11,11, 9,10,10,10,10,10,10,10,11,10,
  138110. 11,10,11,10,11,11,11,11,11,10,11,10,10,10,10,10,
  138111. 10,10,10,10,11,11,11,11,11,11,11,11,11,10,11,11,
  138112. 10,10,10,10,10,11,10,10,10,11,10,11,11,11,11,10,
  138113. 12,11,11,11,10,10,10,10,10,10,11,10,10,10,11,11,
  138114. 12,11,11,11,11,11,11,11,11,11,10,10,10,11,10,11,
  138115. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  138116. 10,10,11,10,11,10,10,11,11,11,11,11,11,11,11,11,
  138117. 11,11,11,10,10,10,10,10,10,10,11,11,10,11,11,10,
  138118. 11,11,10,11,11,11,10,11,11,
  138119. };
  138120. static float _vq_quantthresh__16u2_p8_1[] = {
  138121. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  138122. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  138123. 6.5, 7.5, 8.5, 9.5,
  138124. };
  138125. static long _vq_quantmap__16u2_p8_1[] = {
  138126. 19, 17, 15, 13, 11, 9, 7, 5,
  138127. 3, 1, 0, 2, 4, 6, 8, 10,
  138128. 12, 14, 16, 18, 20,
  138129. };
  138130. static encode_aux_threshmatch _vq_auxt__16u2_p8_1 = {
  138131. _vq_quantthresh__16u2_p8_1,
  138132. _vq_quantmap__16u2_p8_1,
  138133. 21,
  138134. 21
  138135. };
  138136. static static_codebook _16u2_p8_1 = {
  138137. 2, 441,
  138138. _vq_lengthlist__16u2_p8_1,
  138139. 1, -529268736, 1611661312, 5, 0,
  138140. _vq_quantlist__16u2_p8_1,
  138141. NULL,
  138142. &_vq_auxt__16u2_p8_1,
  138143. NULL,
  138144. 0
  138145. };
  138146. static long _vq_quantlist__16u2_p9_0[] = {
  138147. 5586,
  138148. 4655,
  138149. 6517,
  138150. 3724,
  138151. 7448,
  138152. 2793,
  138153. 8379,
  138154. 1862,
  138155. 9310,
  138156. 931,
  138157. 10241,
  138158. 0,
  138159. 11172,
  138160. 5521,
  138161. 5651,
  138162. };
  138163. static long _vq_lengthlist__16u2_p9_0[] = {
  138164. 1,10,10,10,10,10,10,10,10,10,10,10,10, 5, 4,10,
  138165. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138166. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138167. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138168. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138169. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138170. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138171. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138172. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138173. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138174. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138175. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138176. 10,10,10, 4,10,10,10,10,10,10,10,10,10,10,10,10,
  138177. 6, 6, 5,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 5,
  138178. 5,
  138179. };
  138180. static float _vq_quantthresh__16u2_p9_0[] = {
  138181. -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -498, -32.5, 32.5,
  138182. 498, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5,
  138183. };
  138184. static long _vq_quantmap__16u2_p9_0[] = {
  138185. 11, 9, 7, 5, 3, 1, 13, 0,
  138186. 14, 2, 4, 6, 8, 10, 12,
  138187. };
  138188. static encode_aux_threshmatch _vq_auxt__16u2_p9_0 = {
  138189. _vq_quantthresh__16u2_p9_0,
  138190. _vq_quantmap__16u2_p9_0,
  138191. 15,
  138192. 15
  138193. };
  138194. static static_codebook _16u2_p9_0 = {
  138195. 2, 225,
  138196. _vq_lengthlist__16u2_p9_0,
  138197. 1, -510275072, 1611661312, 14, 0,
  138198. _vq_quantlist__16u2_p9_0,
  138199. NULL,
  138200. &_vq_auxt__16u2_p9_0,
  138201. NULL,
  138202. 0
  138203. };
  138204. static long _vq_quantlist__16u2_p9_1[] = {
  138205. 392,
  138206. 343,
  138207. 441,
  138208. 294,
  138209. 490,
  138210. 245,
  138211. 539,
  138212. 196,
  138213. 588,
  138214. 147,
  138215. 637,
  138216. 98,
  138217. 686,
  138218. 49,
  138219. 735,
  138220. 0,
  138221. 784,
  138222. 388,
  138223. 396,
  138224. };
  138225. static long _vq_lengthlist__16u2_p9_1[] = {
  138226. 1,12,10,12,10,12,10,12,11,12,12,12,12,12,12,12,
  138227. 12, 5, 5, 9,10,12,11,11,12,12,12,12,12,12,12,12,
  138228. 12,12,12,12,10, 9, 9,11, 9,11,11,12,11,12,12,12,
  138229. 12,12,12,12,12,12,12, 8, 8,10,11, 9,12,11,12,12,
  138230. 12,12,12,12,12,12,12,12,12,12, 9, 8,10,11,12,11,
  138231. 12,11,12,12,12,12,12,12,12,12,12,12,12, 8, 9,11,
  138232. 11,10,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  138233. 9,10,11,12,11,12,11,12,12,12,12,12,12,12,12,12,
  138234. 12,12,12, 9, 9,11,12,12,12,12,12,12,12,12,12,12,
  138235. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  138236. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  138237. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  138238. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  138239. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  138240. 12,12,12,12,11,11,11,11,11,11,11,11,11,11,11,11,
  138241. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  138242. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  138243. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  138244. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  138245. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  138246. 11,11,11, 5, 8, 9, 9, 8,11, 9,11,11,11,11,11,11,
  138247. 11,11,11,11, 5, 5, 4, 8, 8, 8, 8,10, 9,10,10,11,
  138248. 11,11,11,11,11,11,11, 5, 4,
  138249. };
  138250. static float _vq_quantthresh__16u2_p9_1[] = {
  138251. -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5, -26.5,
  138252. -2, 2, 26.5, 73.5, 122.5, 171.5, 220.5, 269.5,
  138253. 318.5, 367.5,
  138254. };
  138255. static long _vq_quantmap__16u2_p9_1[] = {
  138256. 15, 13, 11, 9, 7, 5, 3, 1,
  138257. 17, 0, 18, 2, 4, 6, 8, 10,
  138258. 12, 14, 16,
  138259. };
  138260. static encode_aux_threshmatch _vq_auxt__16u2_p9_1 = {
  138261. _vq_quantthresh__16u2_p9_1,
  138262. _vq_quantmap__16u2_p9_1,
  138263. 19,
  138264. 19
  138265. };
  138266. static static_codebook _16u2_p9_1 = {
  138267. 2, 361,
  138268. _vq_lengthlist__16u2_p9_1,
  138269. 1, -518488064, 1611661312, 10, 0,
  138270. _vq_quantlist__16u2_p9_1,
  138271. NULL,
  138272. &_vq_auxt__16u2_p9_1,
  138273. NULL,
  138274. 0
  138275. };
  138276. static long _vq_quantlist__16u2_p9_2[] = {
  138277. 24,
  138278. 23,
  138279. 25,
  138280. 22,
  138281. 26,
  138282. 21,
  138283. 27,
  138284. 20,
  138285. 28,
  138286. 19,
  138287. 29,
  138288. 18,
  138289. 30,
  138290. 17,
  138291. 31,
  138292. 16,
  138293. 32,
  138294. 15,
  138295. 33,
  138296. 14,
  138297. 34,
  138298. 13,
  138299. 35,
  138300. 12,
  138301. 36,
  138302. 11,
  138303. 37,
  138304. 10,
  138305. 38,
  138306. 9,
  138307. 39,
  138308. 8,
  138309. 40,
  138310. 7,
  138311. 41,
  138312. 6,
  138313. 42,
  138314. 5,
  138315. 43,
  138316. 4,
  138317. 44,
  138318. 3,
  138319. 45,
  138320. 2,
  138321. 46,
  138322. 1,
  138323. 47,
  138324. 0,
  138325. 48,
  138326. };
  138327. static long _vq_lengthlist__16u2_p9_2[] = {
  138328. 1, 3, 3, 4, 7, 7, 7, 8, 7, 7, 7, 7, 8, 8, 8, 8,
  138329. 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 9, 9, 8, 9, 9,
  138330. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,12,12,10,
  138331. 11,
  138332. };
  138333. static float _vq_quantthresh__16u2_p9_2[] = {
  138334. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  138335. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  138336. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  138337. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  138338. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  138339. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  138340. };
  138341. static long _vq_quantmap__16u2_p9_2[] = {
  138342. 47, 45, 43, 41, 39, 37, 35, 33,
  138343. 31, 29, 27, 25, 23, 21, 19, 17,
  138344. 15, 13, 11, 9, 7, 5, 3, 1,
  138345. 0, 2, 4, 6, 8, 10, 12, 14,
  138346. 16, 18, 20, 22, 24, 26, 28, 30,
  138347. 32, 34, 36, 38, 40, 42, 44, 46,
  138348. 48,
  138349. };
  138350. static encode_aux_threshmatch _vq_auxt__16u2_p9_2 = {
  138351. _vq_quantthresh__16u2_p9_2,
  138352. _vq_quantmap__16u2_p9_2,
  138353. 49,
  138354. 49
  138355. };
  138356. static static_codebook _16u2_p9_2 = {
  138357. 1, 49,
  138358. _vq_lengthlist__16u2_p9_2,
  138359. 1, -526909440, 1611661312, 6, 0,
  138360. _vq_quantlist__16u2_p9_2,
  138361. NULL,
  138362. &_vq_auxt__16u2_p9_2,
  138363. NULL,
  138364. 0
  138365. };
  138366. static long _vq_quantlist__8u0__p1_0[] = {
  138367. 1,
  138368. 0,
  138369. 2,
  138370. };
  138371. static long _vq_lengthlist__8u0__p1_0[] = {
  138372. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  138373. 10,10, 5, 8, 8, 7,10,10, 8,10,10, 4, 9, 8, 8,11,
  138374. 11, 8,11,11, 7,11,11,10,11,13,10,13,13, 7,11,11,
  138375. 10,13,12,10,13,13, 5, 9, 8, 8,11,11, 8,11,11, 7,
  138376. 11,11, 9,13,13,10,12,13, 7,11,11,10,13,13,10,13,
  138377. 11,
  138378. };
  138379. static float _vq_quantthresh__8u0__p1_0[] = {
  138380. -0.5, 0.5,
  138381. };
  138382. static long _vq_quantmap__8u0__p1_0[] = {
  138383. 1, 0, 2,
  138384. };
  138385. static encode_aux_threshmatch _vq_auxt__8u0__p1_0 = {
  138386. _vq_quantthresh__8u0__p1_0,
  138387. _vq_quantmap__8u0__p1_0,
  138388. 3,
  138389. 3
  138390. };
  138391. static static_codebook _8u0__p1_0 = {
  138392. 4, 81,
  138393. _vq_lengthlist__8u0__p1_0,
  138394. 1, -535822336, 1611661312, 2, 0,
  138395. _vq_quantlist__8u0__p1_0,
  138396. NULL,
  138397. &_vq_auxt__8u0__p1_0,
  138398. NULL,
  138399. 0
  138400. };
  138401. static long _vq_quantlist__8u0__p2_0[] = {
  138402. 1,
  138403. 0,
  138404. 2,
  138405. };
  138406. static long _vq_lengthlist__8u0__p2_0[] = {
  138407. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 6, 7, 8, 6,
  138408. 7, 8, 5, 7, 7, 6, 8, 8, 7, 9, 7, 5, 7, 7, 7, 9,
  138409. 9, 7, 8, 8, 6, 9, 8, 7, 7,10, 8,10,10, 6, 8, 8,
  138410. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 9, 6,
  138411. 8, 8, 8,10,10, 8, 8,10, 6, 8, 9, 8,10,10, 7,10,
  138412. 8,
  138413. };
  138414. static float _vq_quantthresh__8u0__p2_0[] = {
  138415. -0.5, 0.5,
  138416. };
  138417. static long _vq_quantmap__8u0__p2_0[] = {
  138418. 1, 0, 2,
  138419. };
  138420. static encode_aux_threshmatch _vq_auxt__8u0__p2_0 = {
  138421. _vq_quantthresh__8u0__p2_0,
  138422. _vq_quantmap__8u0__p2_0,
  138423. 3,
  138424. 3
  138425. };
  138426. static static_codebook _8u0__p2_0 = {
  138427. 4, 81,
  138428. _vq_lengthlist__8u0__p2_0,
  138429. 1, -535822336, 1611661312, 2, 0,
  138430. _vq_quantlist__8u0__p2_0,
  138431. NULL,
  138432. &_vq_auxt__8u0__p2_0,
  138433. NULL,
  138434. 0
  138435. };
  138436. static long _vq_quantlist__8u0__p3_0[] = {
  138437. 2,
  138438. 1,
  138439. 3,
  138440. 0,
  138441. 4,
  138442. };
  138443. static long _vq_lengthlist__8u0__p3_0[] = {
  138444. 1, 5, 5, 7, 7, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  138445. 10, 9,11,11, 8, 9, 9,11,11, 6, 8, 8,10,10, 8,10,
  138446. 10,11,11, 8,10,10,11,11,10,11,11,12,12,10,11,11,
  138447. 12,13, 6, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  138448. 11, 9,10,11,12,12,10,11,11,12,12, 8,11,11,14,13,
  138449. 10,12,11,15,13,10,12,11,14,14,12,13,12,16,14,12,
  138450. 14,12,16,15, 8,11,11,13,14,10,11,12,13,15,10,11,
  138451. 12,13,15,11,12,13,14,15,12,12,14,14,16, 5, 8, 8,
  138452. 11,11, 9,11,11,12,12, 8,10,11,12,12,11,12,12,15,
  138453. 14,11,12,12,14,14, 7,11,10,13,12,10,11,12,13,14,
  138454. 10,12,12,14,13,12,13,13,14,15,12,13,13,15,15, 7,
  138455. 10,11,12,13,10,12,11,14,13,10,12,13,13,15,12,13,
  138456. 12,14,14,11,13,13,15,16, 9,12,12,15,14,11,13,13,
  138457. 15,16,11,13,13,16,16,13,14,15,15,15,12,14,15,17,
  138458. 16, 9,12,12,14,15,11,13,13,15,16,11,13,13,16,18,
  138459. 13,14,14,17,16,13,15,15,17,18, 5, 8, 9,11,11, 8,
  138460. 11,11,12,12, 8,10,11,12,12,11,12,12,14,14,11,12,
  138461. 12,14,15, 7,11,10,12,13,10,12,12,14,13,10,11,12,
  138462. 13,14,11,13,13,15,14,12,13,13,14,15, 7,10,11,13,
  138463. 13,10,12,12,13,14,10,12,12,13,13,11,13,13,16,16,
  138464. 12,13,13,15,14, 9,12,12,16,15,10,13,13,15,15,11,
  138465. 13,13,17,15,12,15,15,18,17,13,14,14,15,16, 9,12,
  138466. 12,15,15,11,13,13,15,16,11,13,13,15,15,12,15,15,
  138467. 16,16,13,15,14,17,15, 7,11,11,15,15,10,13,13,16,
  138468. 15,10,13,13,15,16,14,15,15,17,19,13,15,14,15,18,
  138469. 9,12,12,16,16,11,13,14,17,16,11,13,13,17,16,15,
  138470. 15,16,17,19,13,15,16, 0,18, 9,12,12,16,15,11,14,
  138471. 13,17,17,11,13,14,16,16,15,16,16,19,18,13,15,15,
  138472. 17,19,11,14,14,19,16,12,14,15, 0,18,12,16,15,18,
  138473. 17,15,15,18,16,19,14,15,17,19,19,11,14,14,18,19,
  138474. 13,15,14,19,19,12,16,15,18,17,15,17,15, 0,16,14,
  138475. 17,16,19, 0, 7,11,11,14,14,10,12,12,15,15,10,13,
  138476. 13,16,15,13,15,15,17, 0,14,15,15,16,19, 9,12,12,
  138477. 16,16,11,14,14,16,16,11,13,13,16,16,14,17,16,19,
  138478. 0,14,18,17,17,19, 9,12,12,15,16,11,13,13,15,17,
  138479. 12,14,13,19,16,13,15,15,17,19,15,17,16,17,19,11,
  138480. 14,14,19,16,12,15,15,19,17,13,14,15,17,19,14,16,
  138481. 17,19,19,16,15,16,17,19,11,15,14,16,16,12,15,15,
  138482. 19, 0,12,14,15,19,19,14,16,16, 0,18,15,19,14,18,
  138483. 16,
  138484. };
  138485. static float _vq_quantthresh__8u0__p3_0[] = {
  138486. -1.5, -0.5, 0.5, 1.5,
  138487. };
  138488. static long _vq_quantmap__8u0__p3_0[] = {
  138489. 3, 1, 0, 2, 4,
  138490. };
  138491. static encode_aux_threshmatch _vq_auxt__8u0__p3_0 = {
  138492. _vq_quantthresh__8u0__p3_0,
  138493. _vq_quantmap__8u0__p3_0,
  138494. 5,
  138495. 5
  138496. };
  138497. static static_codebook _8u0__p3_0 = {
  138498. 4, 625,
  138499. _vq_lengthlist__8u0__p3_0,
  138500. 1, -533725184, 1611661312, 3, 0,
  138501. _vq_quantlist__8u0__p3_0,
  138502. NULL,
  138503. &_vq_auxt__8u0__p3_0,
  138504. NULL,
  138505. 0
  138506. };
  138507. static long _vq_quantlist__8u0__p4_0[] = {
  138508. 2,
  138509. 1,
  138510. 3,
  138511. 0,
  138512. 4,
  138513. };
  138514. static long _vq_lengthlist__8u0__p4_0[] = {
  138515. 3, 5, 5, 8, 8, 5, 6, 7, 9, 9, 6, 7, 6, 9, 9, 9,
  138516. 9, 9,10,11, 9, 9, 9,11,10, 6, 7, 7,10,10, 7, 7,
  138517. 8,10,10, 7, 8, 8,10,10,10,10,10,10,11, 9,10,10,
  138518. 11,12, 6, 7, 7,10,10, 7, 8, 8,10,10, 7, 8, 7,10,
  138519. 10, 9,10,10,12,11,10,10,10,11,10, 9,10,10,12,11,
  138520. 10,10,10,13,11, 9,10,10,12,12,11,11,12,12,13,11,
  138521. 11,11,12,13, 9,10,10,12,12,10,10,11,12,12,10,10,
  138522. 11,12,12,11,11,11,13,13,11,12,12,13,13, 5, 7, 7,
  138523. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,11,12,
  138524. 12,10,11,10,12,12, 7, 8, 8,11,11, 7, 8, 9,10,11,
  138525. 8, 9, 9,11,11,11,10,11,10,12,10,11,11,12,13, 7,
  138526. 8, 8,10,11, 8, 9, 8,12,10, 8, 9, 9,11,12,10,11,
  138527. 10,13,11,10,11,11,13,12, 9,11,10,13,12,10,10,11,
  138528. 12,12,10,11,11,13,13,12,10,13,11,14,11,12,12,15,
  138529. 13, 9,11,11,13,13,10,11,11,13,12,10,11,11,12,14,
  138530. 12,13,11,14,12,12,12,12,14,14, 5, 7, 7,10,10, 7,
  138531. 8, 8,10,10, 7, 8, 8,11,10,10,11,11,12,12,10,11,
  138532. 10,12,12, 7, 8, 8,10,11, 8, 9, 9,12,11, 8, 8, 9,
  138533. 10,11,10,11,11,12,13,11,10,11,11,13, 6, 8, 8,10,
  138534. 11, 8, 9, 9,11,11, 7, 9, 7,11,10,10,11,11,12,12,
  138535. 10,11,10,13,10, 9,11,10,13,12,10,12,11,13,13,10,
  138536. 10,11,12,13,11,12,13,15,14,11,11,13,12,13, 9,10,
  138537. 11,12,13,10,11,11,12,13,10,11,10,13,12,12,13,13,
  138538. 13,14,12,12,11,14,11, 8,10,10,12,13,10,11,11,13,
  138539. 13,10,11,10,13,13,12,13,14,15,14,12,12,12,14,13,
  138540. 9,10,10,13,12,10,10,12,13,13,10,11,11,15,12,12,
  138541. 12,13,15,14,12,13,13,15,13, 9,10,11,12,13,10,12,
  138542. 10,13,12,10,11,11,12,13,12,14,12,15,13,12,12,12,
  138543. 15,14,11,12,11,14,13,11,11,12,14,14,12,13,13,14,
  138544. 13,13,11,15,11,15,14,14,14,16,15,11,12,12,13,14,
  138545. 11,13,11,14,14,12,12,13,14,15,12,14,12,15,12,13,
  138546. 15,14,16,15, 8,10,10,12,12,10,10,10,12,13,10,11,
  138547. 11,13,13,12,12,12,13,14,13,13,13,15,15, 9,10,10,
  138548. 12,12,10,11,11,13,12,10,10,11,13,13,12,12,12,14,
  138549. 14,12,12,13,15,14, 9,10,10,13,12,10,10,12,12,13,
  138550. 10,11,10,13,13,12,13,13,14,14,12,13,12,14,13,11,
  138551. 12,12,14,13,12,13,12,14,14,10,12,12,14,14,14,14,
  138552. 14,16,14,13,12,14,12,15,10,12,12,14,15,12,13,13,
  138553. 14,16,11,12,11,15,14,13,14,14,14,15,13,14,11,14,
  138554. 12,
  138555. };
  138556. static float _vq_quantthresh__8u0__p4_0[] = {
  138557. -1.5, -0.5, 0.5, 1.5,
  138558. };
  138559. static long _vq_quantmap__8u0__p4_0[] = {
  138560. 3, 1, 0, 2, 4,
  138561. };
  138562. static encode_aux_threshmatch _vq_auxt__8u0__p4_0 = {
  138563. _vq_quantthresh__8u0__p4_0,
  138564. _vq_quantmap__8u0__p4_0,
  138565. 5,
  138566. 5
  138567. };
  138568. static static_codebook _8u0__p4_0 = {
  138569. 4, 625,
  138570. _vq_lengthlist__8u0__p4_0,
  138571. 1, -533725184, 1611661312, 3, 0,
  138572. _vq_quantlist__8u0__p4_0,
  138573. NULL,
  138574. &_vq_auxt__8u0__p4_0,
  138575. NULL,
  138576. 0
  138577. };
  138578. static long _vq_quantlist__8u0__p5_0[] = {
  138579. 4,
  138580. 3,
  138581. 5,
  138582. 2,
  138583. 6,
  138584. 1,
  138585. 7,
  138586. 0,
  138587. 8,
  138588. };
  138589. static long _vq_lengthlist__8u0__p5_0[] = {
  138590. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 7, 8, 8,
  138591. 10,10, 4, 6, 6, 8, 8, 8, 8,10,10, 6, 8, 8, 9, 9,
  138592. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 7, 8, 8,
  138593. 9, 9,10,10,12,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  138594. 10,10,11,11,11,12,12,12, 9,10,10,11,11,12,12,12,
  138595. 12,
  138596. };
  138597. static float _vq_quantthresh__8u0__p5_0[] = {
  138598. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  138599. };
  138600. static long _vq_quantmap__8u0__p5_0[] = {
  138601. 7, 5, 3, 1, 0, 2, 4, 6,
  138602. 8,
  138603. };
  138604. static encode_aux_threshmatch _vq_auxt__8u0__p5_0 = {
  138605. _vq_quantthresh__8u0__p5_0,
  138606. _vq_quantmap__8u0__p5_0,
  138607. 9,
  138608. 9
  138609. };
  138610. static static_codebook _8u0__p5_0 = {
  138611. 2, 81,
  138612. _vq_lengthlist__8u0__p5_0,
  138613. 1, -531628032, 1611661312, 4, 0,
  138614. _vq_quantlist__8u0__p5_0,
  138615. NULL,
  138616. &_vq_auxt__8u0__p5_0,
  138617. NULL,
  138618. 0
  138619. };
  138620. static long _vq_quantlist__8u0__p6_0[] = {
  138621. 6,
  138622. 5,
  138623. 7,
  138624. 4,
  138625. 8,
  138626. 3,
  138627. 9,
  138628. 2,
  138629. 10,
  138630. 1,
  138631. 11,
  138632. 0,
  138633. 12,
  138634. };
  138635. static long _vq_lengthlist__8u0__p6_0[] = {
  138636. 1, 4, 4, 7, 7, 9, 9,11,11,12,12,16,16, 3, 6, 6,
  138637. 9, 9,11,11,12,12,13,14,18,16, 3, 6, 7, 9, 9,11,
  138638. 11,13,12,14,14,17,16, 7, 9, 9,11,11,12,12,14,14,
  138639. 14,14,17,16, 7, 9, 9,11,11,13,12,13,13,14,14,17,
  138640. 0, 9,11,11,12,13,14,14,14,13,15,14,17,17, 9,11,
  138641. 11,12,12,14,14,13,14,14,15, 0, 0,11,12,12,15,14,
  138642. 15,14,15,14,15,16,17, 0,11,12,13,13,13,14,14,15,
  138643. 14,15,15, 0, 0,12,14,14,15,15,14,16,15,15,17,16,
  138644. 0,18,13,14,14,15,14,15,14,15,16,17,16, 0, 0,17,
  138645. 17,18, 0,16,18,16, 0, 0, 0,17, 0, 0,16, 0, 0,16,
  138646. 16, 0,15, 0,17, 0, 0, 0, 0,
  138647. };
  138648. static float _vq_quantthresh__8u0__p6_0[] = {
  138649. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  138650. 12.5, 17.5, 22.5, 27.5,
  138651. };
  138652. static long _vq_quantmap__8u0__p6_0[] = {
  138653. 11, 9, 7, 5, 3, 1, 0, 2,
  138654. 4, 6, 8, 10, 12,
  138655. };
  138656. static encode_aux_threshmatch _vq_auxt__8u0__p6_0 = {
  138657. _vq_quantthresh__8u0__p6_0,
  138658. _vq_quantmap__8u0__p6_0,
  138659. 13,
  138660. 13
  138661. };
  138662. static static_codebook _8u0__p6_0 = {
  138663. 2, 169,
  138664. _vq_lengthlist__8u0__p6_0,
  138665. 1, -526516224, 1616117760, 4, 0,
  138666. _vq_quantlist__8u0__p6_0,
  138667. NULL,
  138668. &_vq_auxt__8u0__p6_0,
  138669. NULL,
  138670. 0
  138671. };
  138672. static long _vq_quantlist__8u0__p6_1[] = {
  138673. 2,
  138674. 1,
  138675. 3,
  138676. 0,
  138677. 4,
  138678. };
  138679. static long _vq_lengthlist__8u0__p6_1[] = {
  138680. 1, 4, 4, 6, 6, 4, 6, 5, 7, 7, 4, 5, 6, 7, 7, 6,
  138681. 7, 7, 7, 7, 6, 7, 7, 7, 7,
  138682. };
  138683. static float _vq_quantthresh__8u0__p6_1[] = {
  138684. -1.5, -0.5, 0.5, 1.5,
  138685. };
  138686. static long _vq_quantmap__8u0__p6_1[] = {
  138687. 3, 1, 0, 2, 4,
  138688. };
  138689. static encode_aux_threshmatch _vq_auxt__8u0__p6_1 = {
  138690. _vq_quantthresh__8u0__p6_1,
  138691. _vq_quantmap__8u0__p6_1,
  138692. 5,
  138693. 5
  138694. };
  138695. static static_codebook _8u0__p6_1 = {
  138696. 2, 25,
  138697. _vq_lengthlist__8u0__p6_1,
  138698. 1, -533725184, 1611661312, 3, 0,
  138699. _vq_quantlist__8u0__p6_1,
  138700. NULL,
  138701. &_vq_auxt__8u0__p6_1,
  138702. NULL,
  138703. 0
  138704. };
  138705. static long _vq_quantlist__8u0__p7_0[] = {
  138706. 1,
  138707. 0,
  138708. 2,
  138709. };
  138710. static long _vq_lengthlist__8u0__p7_0[] = {
  138711. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  138712. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  138713. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  138714. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  138715. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  138716. 7,
  138717. };
  138718. static float _vq_quantthresh__8u0__p7_0[] = {
  138719. -157.5, 157.5,
  138720. };
  138721. static long _vq_quantmap__8u0__p7_0[] = {
  138722. 1, 0, 2,
  138723. };
  138724. static encode_aux_threshmatch _vq_auxt__8u0__p7_0 = {
  138725. _vq_quantthresh__8u0__p7_0,
  138726. _vq_quantmap__8u0__p7_0,
  138727. 3,
  138728. 3
  138729. };
  138730. static static_codebook _8u0__p7_0 = {
  138731. 4, 81,
  138732. _vq_lengthlist__8u0__p7_0,
  138733. 1, -518803456, 1628680192, 2, 0,
  138734. _vq_quantlist__8u0__p7_0,
  138735. NULL,
  138736. &_vq_auxt__8u0__p7_0,
  138737. NULL,
  138738. 0
  138739. };
  138740. static long _vq_quantlist__8u0__p7_1[] = {
  138741. 7,
  138742. 6,
  138743. 8,
  138744. 5,
  138745. 9,
  138746. 4,
  138747. 10,
  138748. 3,
  138749. 11,
  138750. 2,
  138751. 12,
  138752. 1,
  138753. 13,
  138754. 0,
  138755. 14,
  138756. };
  138757. static long _vq_lengthlist__8u0__p7_1[] = {
  138758. 1, 5, 5, 5, 5,10,10,11,11,11,11,11,11,11,11, 5,
  138759. 7, 6, 8, 8, 9,10,11,11,11,11,11,11,11,11, 6, 6,
  138760. 7, 9, 7,11,10,11,11,11,11,11,11,11,11, 5, 6, 6,
  138761. 11, 8,11,11,11,11,11,11,11,11,11,11, 5, 6, 6, 9,
  138762. 10,11,10,11,11,11,11,11,11,11,11, 7,10,10,11,11,
  138763. 11,11,11,11,11,11,11,11,11,11, 7,11, 8,11,11,11,
  138764. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  138765. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  138766. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  138767. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  138768. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  138769. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  138770. 11,11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,
  138771. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138772. 10,
  138773. };
  138774. static float _vq_quantthresh__8u0__p7_1[] = {
  138775. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  138776. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  138777. };
  138778. static long _vq_quantmap__8u0__p7_1[] = {
  138779. 13, 11, 9, 7, 5, 3, 1, 0,
  138780. 2, 4, 6, 8, 10, 12, 14,
  138781. };
  138782. static encode_aux_threshmatch _vq_auxt__8u0__p7_1 = {
  138783. _vq_quantthresh__8u0__p7_1,
  138784. _vq_quantmap__8u0__p7_1,
  138785. 15,
  138786. 15
  138787. };
  138788. static static_codebook _8u0__p7_1 = {
  138789. 2, 225,
  138790. _vq_lengthlist__8u0__p7_1,
  138791. 1, -520986624, 1620377600, 4, 0,
  138792. _vq_quantlist__8u0__p7_1,
  138793. NULL,
  138794. &_vq_auxt__8u0__p7_1,
  138795. NULL,
  138796. 0
  138797. };
  138798. static long _vq_quantlist__8u0__p7_2[] = {
  138799. 10,
  138800. 9,
  138801. 11,
  138802. 8,
  138803. 12,
  138804. 7,
  138805. 13,
  138806. 6,
  138807. 14,
  138808. 5,
  138809. 15,
  138810. 4,
  138811. 16,
  138812. 3,
  138813. 17,
  138814. 2,
  138815. 18,
  138816. 1,
  138817. 19,
  138818. 0,
  138819. 20,
  138820. };
  138821. static long _vq_lengthlist__8u0__p7_2[] = {
  138822. 1, 6, 5, 7, 7, 9, 9, 9, 9,10,12,12,10,11,11,10,
  138823. 11,11,11,10,11, 6, 8, 8, 9, 9,10,10, 9,10,11,11,
  138824. 10,11,11,11,11,10,11,11,11,11, 6, 7, 8, 9, 9, 9,
  138825. 10,11,10,11,12,11,10,11,11,11,11,11,11,12,10, 8,
  138826. 9, 9,10, 9,10,10, 9,10,10,10,10,10, 9,10,10,10,
  138827. 10, 9,10,10, 9, 9, 9, 9,10,10, 9, 9,10,10,11,10,
  138828. 9,12,10,11,10, 9,10,10,10, 8, 9, 9,10, 9,10, 9,
  138829. 9,10,10, 9,10, 9,11,10,10,10,10,10, 9,10, 8, 8,
  138830. 9, 9,10, 9,11, 9, 8, 9, 9,10,11,10,10,10,11,12,
  138831. 9, 9,11, 8, 9, 8,11,10,11,10,10, 9,11,10,10,10,
  138832. 10,10,10,10,11,11,11,11, 8, 9, 9, 9,10,10,10,11,
  138833. 11,12,11,12,11,10,10,10,12,11,11,11,10, 8,10, 9,
  138834. 11,10,10,11,12,10,11,12,11,11,12,11,12,12,10,11,
  138835. 11,10, 9, 9,10,11,12,10,10,10,11,10,11,11,10,12,
  138836. 12,10,11,10,11,12,10, 9,10,10,11,10,11,11,11,11,
  138837. 11,12,11,11,11, 9,11,10,11,10,11,10, 9, 9,10,11,
  138838. 11,11,10,10,11,12,12,11,12,11,11,11,12,12,12,12,
  138839. 11, 9,11,11,12,10,11,11,11,11,11,11,12,11,11,12,
  138840. 11,11,11,10,11,11, 9,11,10,11,11,11,10,10,10,11,
  138841. 11,11,12,10,11,10,11,11,11,11,12, 9,11,10,11,11,
  138842. 10,10,11,11, 9,11,11,12,10,10,10,10,10,11,11,10,
  138843. 9,10,11,11,12,11,10,10,12,11,11,12,11,12,11,11,
  138844. 10,10,11,11,10,12,11,10,11,10,11,10,10,10,11,11,
  138845. 10,10,11,11,11,11,10,10,10,12,11,11,11,11,10, 9,
  138846. 10,11,11,11,12,11,11,11,12,10,11,11,11, 9,10,11,
  138847. 11,11,11,11,11,10,10,11,11,12,11,10,11,12,11,10,
  138848. 10,11, 9,10,11,11,11,11,11,10,11,11,10,12,11,11,
  138849. 11,12,11,11,11,10,10,11,11,
  138850. };
  138851. static float _vq_quantthresh__8u0__p7_2[] = {
  138852. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  138853. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  138854. 6.5, 7.5, 8.5, 9.5,
  138855. };
  138856. static long _vq_quantmap__8u0__p7_2[] = {
  138857. 19, 17, 15, 13, 11, 9, 7, 5,
  138858. 3, 1, 0, 2, 4, 6, 8, 10,
  138859. 12, 14, 16, 18, 20,
  138860. };
  138861. static encode_aux_threshmatch _vq_auxt__8u0__p7_2 = {
  138862. _vq_quantthresh__8u0__p7_2,
  138863. _vq_quantmap__8u0__p7_2,
  138864. 21,
  138865. 21
  138866. };
  138867. static static_codebook _8u0__p7_2 = {
  138868. 2, 441,
  138869. _vq_lengthlist__8u0__p7_2,
  138870. 1, -529268736, 1611661312, 5, 0,
  138871. _vq_quantlist__8u0__p7_2,
  138872. NULL,
  138873. &_vq_auxt__8u0__p7_2,
  138874. NULL,
  138875. 0
  138876. };
  138877. static long _huff_lengthlist__8u0__single[] = {
  138878. 4, 7,11, 9,12, 8, 7,10, 6, 4, 5, 5, 7, 5, 6,16,
  138879. 9, 5, 5, 6, 7, 7, 9,16, 7, 4, 6, 5, 7, 5, 7,17,
  138880. 10, 7, 7, 8, 7, 7, 8,18, 7, 5, 6, 4, 5, 4, 5,15,
  138881. 7, 6, 7, 5, 6, 4, 5,15,12,13,18,12,17,11, 9,17,
  138882. };
  138883. static static_codebook _huff_book__8u0__single = {
  138884. 2, 64,
  138885. _huff_lengthlist__8u0__single,
  138886. 0, 0, 0, 0, 0,
  138887. NULL,
  138888. NULL,
  138889. NULL,
  138890. NULL,
  138891. 0
  138892. };
  138893. static long _vq_quantlist__8u1__p1_0[] = {
  138894. 1,
  138895. 0,
  138896. 2,
  138897. };
  138898. static long _vq_lengthlist__8u1__p1_0[] = {
  138899. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 7, 9,10, 7,
  138900. 9, 9, 5, 8, 8, 7,10, 9, 7, 9, 9, 5, 8, 8, 8,10,
  138901. 10, 8,10,10, 7,10,10, 9,10,12,10,12,12, 7,10,10,
  138902. 9,12,11,10,12,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  138903. 10,10,10,12,12, 9,11,12, 7,10,10,10,12,12, 9,12,
  138904. 10,
  138905. };
  138906. static float _vq_quantthresh__8u1__p1_0[] = {
  138907. -0.5, 0.5,
  138908. };
  138909. static long _vq_quantmap__8u1__p1_0[] = {
  138910. 1, 0, 2,
  138911. };
  138912. static encode_aux_threshmatch _vq_auxt__8u1__p1_0 = {
  138913. _vq_quantthresh__8u1__p1_0,
  138914. _vq_quantmap__8u1__p1_0,
  138915. 3,
  138916. 3
  138917. };
  138918. static static_codebook _8u1__p1_0 = {
  138919. 4, 81,
  138920. _vq_lengthlist__8u1__p1_0,
  138921. 1, -535822336, 1611661312, 2, 0,
  138922. _vq_quantlist__8u1__p1_0,
  138923. NULL,
  138924. &_vq_auxt__8u1__p1_0,
  138925. NULL,
  138926. 0
  138927. };
  138928. static long _vq_quantlist__8u1__p2_0[] = {
  138929. 1,
  138930. 0,
  138931. 2,
  138932. };
  138933. static long _vq_lengthlist__8u1__p2_0[] = {
  138934. 3, 4, 5, 5, 6, 6, 5, 6, 6, 5, 7, 6, 6, 7, 8, 6,
  138935. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 7, 5, 6, 6, 7, 8,
  138936. 8, 6, 7, 7, 6, 8, 7, 7, 7, 9, 8, 9, 9, 6, 7, 8,
  138937. 7, 9, 7, 8, 9, 9, 5, 6, 6, 6, 7, 7, 7, 8, 8, 6,
  138938. 8, 7, 8, 9, 9, 7, 7, 9, 6, 7, 8, 8, 9, 9, 7, 9,
  138939. 7,
  138940. };
  138941. static float _vq_quantthresh__8u1__p2_0[] = {
  138942. -0.5, 0.5,
  138943. };
  138944. static long _vq_quantmap__8u1__p2_0[] = {
  138945. 1, 0, 2,
  138946. };
  138947. static encode_aux_threshmatch _vq_auxt__8u1__p2_0 = {
  138948. _vq_quantthresh__8u1__p2_0,
  138949. _vq_quantmap__8u1__p2_0,
  138950. 3,
  138951. 3
  138952. };
  138953. static static_codebook _8u1__p2_0 = {
  138954. 4, 81,
  138955. _vq_lengthlist__8u1__p2_0,
  138956. 1, -535822336, 1611661312, 2, 0,
  138957. _vq_quantlist__8u1__p2_0,
  138958. NULL,
  138959. &_vq_auxt__8u1__p2_0,
  138960. NULL,
  138961. 0
  138962. };
  138963. static long _vq_quantlist__8u1__p3_0[] = {
  138964. 2,
  138965. 1,
  138966. 3,
  138967. 0,
  138968. 4,
  138969. };
  138970. static long _vq_lengthlist__8u1__p3_0[] = {
  138971. 1, 5, 5, 7, 7, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  138972. 10, 9,11,11, 9, 9, 9,11,11, 6, 8, 8,10,10, 8,10,
  138973. 10,11,11, 8, 9,10,11,11,10,11,11,12,12,10,11,11,
  138974. 12,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10, 9,11,
  138975. 11,10,11,11,12,12,10,11,11,12,12, 9,11,11,14,13,
  138976. 10,12,11,14,14,10,12,11,14,13,12,13,13,15,14,12,
  138977. 13,13,15,14, 8,11,11,13,14,10,11,12,13,15,10,11,
  138978. 12,14,14,12,13,13,14,15,12,13,13,14,15, 5, 8, 8,
  138979. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  138980. 13,11,12,12,13,14, 8,10,10,12,12, 9,11,12,13,14,
  138981. 10,12,12,13,13,12,12,13,14,14,11,13,13,15,15, 7,
  138982. 10,10,12,12, 9,12,11,14,12,10,11,12,13,14,12,13,
  138983. 12,14,14,12,13,13,15,16,10,12,12,15,14,11,12,13,
  138984. 15,15,11,13,13,15,16,14,14,15,15,16,13,14,15,17,
  138985. 15, 9,12,12,14,15,11,13,12,15,15,11,13,13,15,15,
  138986. 13,14,13,15,14,13,14,14,17, 0, 5, 8, 8,11,11, 8,
  138987. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  138988. 12,14,14, 7,10,10,12,12,10,12,12,13,13, 9,11,12,
  138989. 12,13,11,12,13,15,15,11,12,13,14,15, 8,10,10,12,
  138990. 12,10,12,11,13,13,10,12,11,13,13,11,13,13,15,14,
  138991. 12,13,12,15,13, 9,12,12,14,14,11,13,13,16,15,11,
  138992. 12,13,16,15,13,14,15,16,16,13,13,15,15,16,10,12,
  138993. 12,15,14,11,13,13,14,16,11,13,13,15,16,13,15,15,
  138994. 16,17,13,15,14,16,15, 8,11,11,14,15,10,12,12,15,
  138995. 15,10,12,12,15,16,14,15,15,16,17,13,14,14,16,16,
  138996. 9,12,12,15,15,11,13,14,15,17,11,13,13,15,16,14,
  138997. 15,16,19,17,13,15,15, 0,17, 9,12,12,15,15,11,14,
  138998. 13,16,15,11,13,13,15,16,15,15,15,18,17,13,15,15,
  138999. 17,17,11,15,14,18,16,12,14,15,17,17,12,15,15,18,
  139000. 18,15,15,16,15,19,14,16,16, 0, 0,11,14,14,16,17,
  139001. 12,15,14,18,17,12,15,15,18,18,15,17,15,18,16,14,
  139002. 16,16,18,18, 7,11,11,14,14,10,12,12,15,15,10,12,
  139003. 13,15,15,13,14,15,16,16,14,15,15,18,18, 9,12,12,
  139004. 15,15,11,13,13,16,15,11,12,13,16,16,14,15,15,17,
  139005. 16,15,16,16,17,17, 9,12,12,15,15,11,13,13,15,17,
  139006. 11,14,13,16,15,13,15,15,17,17,15,15,15,18,17,11,
  139007. 14,14,17,15,12,14,15,17,18,13,13,15,17,17,14,16,
  139008. 16,19,18,16,15,17,17, 0,11,14,14,17,17,12,15,15,
  139009. 18, 0,12,15,14,18,16,14,17,17,19, 0,16,18,15, 0,
  139010. 16,
  139011. };
  139012. static float _vq_quantthresh__8u1__p3_0[] = {
  139013. -1.5, -0.5, 0.5, 1.5,
  139014. };
  139015. static long _vq_quantmap__8u1__p3_0[] = {
  139016. 3, 1, 0, 2, 4,
  139017. };
  139018. static encode_aux_threshmatch _vq_auxt__8u1__p3_0 = {
  139019. _vq_quantthresh__8u1__p3_0,
  139020. _vq_quantmap__8u1__p3_0,
  139021. 5,
  139022. 5
  139023. };
  139024. static static_codebook _8u1__p3_0 = {
  139025. 4, 625,
  139026. _vq_lengthlist__8u1__p3_0,
  139027. 1, -533725184, 1611661312, 3, 0,
  139028. _vq_quantlist__8u1__p3_0,
  139029. NULL,
  139030. &_vq_auxt__8u1__p3_0,
  139031. NULL,
  139032. 0
  139033. };
  139034. static long _vq_quantlist__8u1__p4_0[] = {
  139035. 2,
  139036. 1,
  139037. 3,
  139038. 0,
  139039. 4,
  139040. };
  139041. static long _vq_lengthlist__8u1__p4_0[] = {
  139042. 4, 5, 5, 9, 9, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 9,
  139043. 9, 9,11,11, 9, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 7,
  139044. 8, 9,10, 7, 7, 8, 9,10, 9, 9,10,10,11, 9, 9,10,
  139045. 10,12, 6, 7, 7, 9, 9, 7, 8, 7,10, 9, 7, 8, 7,10,
  139046. 9, 9,10, 9,12,11,10,10, 9,12,10, 9,10,10,12,11,
  139047. 9,10,10,12,11, 9,10,10,12,12,11,11,12,12,13,11,
  139048. 11,12,12,13, 9, 9,10,12,11, 9,10,10,12,12,10,10,
  139049. 10,12,12,11,12,11,13,12,11,12,11,13,12, 6, 7, 7,
  139050. 9, 9, 7, 8, 8,10,10, 7, 8, 7,10, 9,10,10,10,12,
  139051. 12,10,10,10,12,11, 7, 8, 7,10,10, 7, 7, 9,10,11,
  139052. 8, 9, 9,11,10,10,10,11,10,12,10,10,11,12,12, 7,
  139053. 8, 8,10,10, 7, 9, 8,11,10, 8, 8, 9,11,11,10,11,
  139054. 10,12,11,10,11,11,12,12, 9,10,10,12,12, 9,10,10,
  139055. 12,12,10,11,11,13,12,11,10,12,10,14,12,12,12,13,
  139056. 14, 9,10,10,12,12, 9,11,10,12,12,10,11,11,12,12,
  139057. 11,12,11,14,12,12,12,12,14,14, 5, 7, 7, 9, 9, 7,
  139058. 7, 7, 9,10, 7, 8, 8,10,10,10,10,10,11,11,10,10,
  139059. 10,12,12, 7, 8, 8,10,10, 8, 9, 8,11,10, 7, 8, 9,
  139060. 10,11,10,10,10,11,12,10,10,11,11,13, 6, 7, 8,10,
  139061. 10, 8, 9, 9,10,10, 7, 9, 7,11,10,10,11,10,12,12,
  139062. 10,11,10,12,10, 9,10,10,12,12,10,11,11,13,12, 9,
  139063. 10,10,12,12,12,12,12,14,13,11,11,12,11,14, 9,10,
  139064. 10,11,12,10,11,11,12,13, 9,10,10,12,12,12,12,12,
  139065. 14,13,11,12,10,14,11, 9, 9,10,11,12, 9,10,10,12,
  139066. 12, 9,10,10,12,12,12,12,12,14,14,11,12,12,13,12,
  139067. 9,10, 9,12,12, 9,10,11,12,13,10,11,10,13,11,12,
  139068. 12,13,13,14,12,12,12,13,13, 9,10,10,12,12,10,11,
  139069. 10,13,12,10,10,11,12,13,12,13,12,14,13,12,12,12,
  139070. 13,14,11,12,11,14,13,10,10,11,13,13,12,12,12,14,
  139071. 13,12,10,14,10,15,13,14,14,14,14,11,11,12,13,14,
  139072. 10,12,11,13,13,12,12,12,13,15,12,13,11,15,12,13,
  139073. 13,14,14,14, 9,10, 9,12,12, 9,10,10,12,12,10,10,
  139074. 10,12,12,11,11,12,12,13,12,12,12,14,14, 9,10,10,
  139075. 12,12,10,11,10,13,12,10,10,11,12,13,12,12,12,14,
  139076. 13,12,12,13,13,14, 9,10,10,12,13,10,10,11,11,12,
  139077. 9,11,10,13,12,12,12,12,13,14,12,13,12,14,13,11,
  139078. 12,11,13,13,12,13,12,14,13,10,11,12,13,13,13,13,
  139079. 13,14,15,12,11,14,12,14,11,11,12,12,13,12,12,12,
  139080. 13,14,10,12,10,14,13,13,13,13,14,15,12,14,11,15,
  139081. 10,
  139082. };
  139083. static float _vq_quantthresh__8u1__p4_0[] = {
  139084. -1.5, -0.5, 0.5, 1.5,
  139085. };
  139086. static long _vq_quantmap__8u1__p4_0[] = {
  139087. 3, 1, 0, 2, 4,
  139088. };
  139089. static encode_aux_threshmatch _vq_auxt__8u1__p4_0 = {
  139090. _vq_quantthresh__8u1__p4_0,
  139091. _vq_quantmap__8u1__p4_0,
  139092. 5,
  139093. 5
  139094. };
  139095. static static_codebook _8u1__p4_0 = {
  139096. 4, 625,
  139097. _vq_lengthlist__8u1__p4_0,
  139098. 1, -533725184, 1611661312, 3, 0,
  139099. _vq_quantlist__8u1__p4_0,
  139100. NULL,
  139101. &_vq_auxt__8u1__p4_0,
  139102. NULL,
  139103. 0
  139104. };
  139105. static long _vq_quantlist__8u1__p5_0[] = {
  139106. 4,
  139107. 3,
  139108. 5,
  139109. 2,
  139110. 6,
  139111. 1,
  139112. 7,
  139113. 0,
  139114. 8,
  139115. };
  139116. static long _vq_lengthlist__8u1__p5_0[] = {
  139117. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 5, 8, 7, 8, 8,
  139118. 10,10, 4, 6, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  139119. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 8, 8, 8,
  139120. 9, 9,10,10,12,11, 8, 8, 8, 9, 9,10,10,11,11, 9,
  139121. 10,10,11,11,11,11,13,12, 9,10,10,11,11,12,12,12,
  139122. 13,
  139123. };
  139124. static float _vq_quantthresh__8u1__p5_0[] = {
  139125. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  139126. };
  139127. static long _vq_quantmap__8u1__p5_0[] = {
  139128. 7, 5, 3, 1, 0, 2, 4, 6,
  139129. 8,
  139130. };
  139131. static encode_aux_threshmatch _vq_auxt__8u1__p5_0 = {
  139132. _vq_quantthresh__8u1__p5_0,
  139133. _vq_quantmap__8u1__p5_0,
  139134. 9,
  139135. 9
  139136. };
  139137. static static_codebook _8u1__p5_0 = {
  139138. 2, 81,
  139139. _vq_lengthlist__8u1__p5_0,
  139140. 1, -531628032, 1611661312, 4, 0,
  139141. _vq_quantlist__8u1__p5_0,
  139142. NULL,
  139143. &_vq_auxt__8u1__p5_0,
  139144. NULL,
  139145. 0
  139146. };
  139147. static long _vq_quantlist__8u1__p6_0[] = {
  139148. 4,
  139149. 3,
  139150. 5,
  139151. 2,
  139152. 6,
  139153. 1,
  139154. 7,
  139155. 0,
  139156. 8,
  139157. };
  139158. static long _vq_lengthlist__8u1__p6_0[] = {
  139159. 3, 4, 4, 6, 6, 7, 7, 9, 9, 4, 4, 5, 6, 6, 7, 7,
  139160. 9, 9, 4, 4, 4, 6, 6, 7, 7, 9, 9, 6, 6, 6, 7, 7,
  139161. 8, 8, 9, 9, 6, 6, 6, 7, 7, 8, 8, 9, 9, 7, 7, 7,
  139162. 8, 8, 8, 9,10,10, 7, 7, 7, 8, 8, 9, 8,10,10, 9,
  139163. 9, 9, 9, 9,10,10,10,10, 9, 9, 9, 9, 9,10,10,10,
  139164. 10,
  139165. };
  139166. static float _vq_quantthresh__8u1__p6_0[] = {
  139167. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  139168. };
  139169. static long _vq_quantmap__8u1__p6_0[] = {
  139170. 7, 5, 3, 1, 0, 2, 4, 6,
  139171. 8,
  139172. };
  139173. static encode_aux_threshmatch _vq_auxt__8u1__p6_0 = {
  139174. _vq_quantthresh__8u1__p6_0,
  139175. _vq_quantmap__8u1__p6_0,
  139176. 9,
  139177. 9
  139178. };
  139179. static static_codebook _8u1__p6_0 = {
  139180. 2, 81,
  139181. _vq_lengthlist__8u1__p6_0,
  139182. 1, -531628032, 1611661312, 4, 0,
  139183. _vq_quantlist__8u1__p6_0,
  139184. NULL,
  139185. &_vq_auxt__8u1__p6_0,
  139186. NULL,
  139187. 0
  139188. };
  139189. static long _vq_quantlist__8u1__p7_0[] = {
  139190. 1,
  139191. 0,
  139192. 2,
  139193. };
  139194. static long _vq_lengthlist__8u1__p7_0[] = {
  139195. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 9, 8,10,10, 8,
  139196. 10,10, 5, 9, 9, 7,10,10, 8,10,10, 4,10,10, 9,12,
  139197. 12, 9,11,11, 7,12,11,10,11,13,10,13,13, 7,12,12,
  139198. 10,13,12,10,13,13, 4,10,10, 9,12,12, 9,12,12, 7,
  139199. 12,12,10,13,13,10,12,13, 7,11,12,10,13,13,10,13,
  139200. 11,
  139201. };
  139202. static float _vq_quantthresh__8u1__p7_0[] = {
  139203. -5.5, 5.5,
  139204. };
  139205. static long _vq_quantmap__8u1__p7_0[] = {
  139206. 1, 0, 2,
  139207. };
  139208. static encode_aux_threshmatch _vq_auxt__8u1__p7_0 = {
  139209. _vq_quantthresh__8u1__p7_0,
  139210. _vq_quantmap__8u1__p7_0,
  139211. 3,
  139212. 3
  139213. };
  139214. static static_codebook _8u1__p7_0 = {
  139215. 4, 81,
  139216. _vq_lengthlist__8u1__p7_0,
  139217. 1, -529137664, 1618345984, 2, 0,
  139218. _vq_quantlist__8u1__p7_0,
  139219. NULL,
  139220. &_vq_auxt__8u1__p7_0,
  139221. NULL,
  139222. 0
  139223. };
  139224. static long _vq_quantlist__8u1__p7_1[] = {
  139225. 5,
  139226. 4,
  139227. 6,
  139228. 3,
  139229. 7,
  139230. 2,
  139231. 8,
  139232. 1,
  139233. 9,
  139234. 0,
  139235. 10,
  139236. };
  139237. static long _vq_lengthlist__8u1__p7_1[] = {
  139238. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 7,
  139239. 8, 8, 9, 9, 9, 9, 4, 5, 5, 7, 7, 8, 8, 9, 9, 9,
  139240. 9, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  139241. 8, 8, 8, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  139242. 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 9, 9,
  139243. 9, 9, 9, 9,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  139244. 10,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10, 8, 9,
  139245. 9, 9, 9, 9, 9,10,10,10,10,
  139246. };
  139247. static float _vq_quantthresh__8u1__p7_1[] = {
  139248. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  139249. 3.5, 4.5,
  139250. };
  139251. static long _vq_quantmap__8u1__p7_1[] = {
  139252. 9, 7, 5, 3, 1, 0, 2, 4,
  139253. 6, 8, 10,
  139254. };
  139255. static encode_aux_threshmatch _vq_auxt__8u1__p7_1 = {
  139256. _vq_quantthresh__8u1__p7_1,
  139257. _vq_quantmap__8u1__p7_1,
  139258. 11,
  139259. 11
  139260. };
  139261. static static_codebook _8u1__p7_1 = {
  139262. 2, 121,
  139263. _vq_lengthlist__8u1__p7_1,
  139264. 1, -531365888, 1611661312, 4, 0,
  139265. _vq_quantlist__8u1__p7_1,
  139266. NULL,
  139267. &_vq_auxt__8u1__p7_1,
  139268. NULL,
  139269. 0
  139270. };
  139271. static long _vq_quantlist__8u1__p8_0[] = {
  139272. 5,
  139273. 4,
  139274. 6,
  139275. 3,
  139276. 7,
  139277. 2,
  139278. 8,
  139279. 1,
  139280. 9,
  139281. 0,
  139282. 10,
  139283. };
  139284. static long _vq_lengthlist__8u1__p8_0[] = {
  139285. 1, 4, 4, 6, 6, 8, 8,10,10,11,11, 4, 6, 6, 7, 7,
  139286. 9, 9,11,11,13,12, 4, 6, 6, 7, 7, 9, 9,11,11,12,
  139287. 12, 6, 7, 7, 9, 9,11,11,12,12,13,13, 6, 7, 7, 9,
  139288. 9,11,11,12,12,13,13, 8, 9, 9,11,11,12,12,13,13,
  139289. 14,14, 8, 9, 9,11,11,12,12,13,13,14,14, 9,11,11,
  139290. 12,12,13,13,14,14,15,15, 9,11,11,12,12,13,13,14,
  139291. 14,15,14,11,12,12,13,13,14,14,15,15,16,16,11,12,
  139292. 12,13,13,14,14,15,15,15,15,
  139293. };
  139294. static float _vq_quantthresh__8u1__p8_0[] = {
  139295. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  139296. 38.5, 49.5,
  139297. };
  139298. static long _vq_quantmap__8u1__p8_0[] = {
  139299. 9, 7, 5, 3, 1, 0, 2, 4,
  139300. 6, 8, 10,
  139301. };
  139302. static encode_aux_threshmatch _vq_auxt__8u1__p8_0 = {
  139303. _vq_quantthresh__8u1__p8_0,
  139304. _vq_quantmap__8u1__p8_0,
  139305. 11,
  139306. 11
  139307. };
  139308. static static_codebook _8u1__p8_0 = {
  139309. 2, 121,
  139310. _vq_lengthlist__8u1__p8_0,
  139311. 1, -524582912, 1618345984, 4, 0,
  139312. _vq_quantlist__8u1__p8_0,
  139313. NULL,
  139314. &_vq_auxt__8u1__p8_0,
  139315. NULL,
  139316. 0
  139317. };
  139318. static long _vq_quantlist__8u1__p8_1[] = {
  139319. 5,
  139320. 4,
  139321. 6,
  139322. 3,
  139323. 7,
  139324. 2,
  139325. 8,
  139326. 1,
  139327. 9,
  139328. 0,
  139329. 10,
  139330. };
  139331. static long _vq_lengthlist__8u1__p8_1[] = {
  139332. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 5, 6, 6, 7, 7,
  139333. 7, 7, 8, 8, 8, 8, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8,
  139334. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  139335. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  139336. 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  139337. 8, 8, 8, 8, 9, 8, 9, 9, 7, 8, 8, 8, 8, 8, 8, 9,
  139338. 8, 9, 9, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8,
  139339. 8, 8, 8, 8, 8, 9, 9, 9, 9,
  139340. };
  139341. static float _vq_quantthresh__8u1__p8_1[] = {
  139342. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  139343. 3.5, 4.5,
  139344. };
  139345. static long _vq_quantmap__8u1__p8_1[] = {
  139346. 9, 7, 5, 3, 1, 0, 2, 4,
  139347. 6, 8, 10,
  139348. };
  139349. static encode_aux_threshmatch _vq_auxt__8u1__p8_1 = {
  139350. _vq_quantthresh__8u1__p8_1,
  139351. _vq_quantmap__8u1__p8_1,
  139352. 11,
  139353. 11
  139354. };
  139355. static static_codebook _8u1__p8_1 = {
  139356. 2, 121,
  139357. _vq_lengthlist__8u1__p8_1,
  139358. 1, -531365888, 1611661312, 4, 0,
  139359. _vq_quantlist__8u1__p8_1,
  139360. NULL,
  139361. &_vq_auxt__8u1__p8_1,
  139362. NULL,
  139363. 0
  139364. };
  139365. static long _vq_quantlist__8u1__p9_0[] = {
  139366. 7,
  139367. 6,
  139368. 8,
  139369. 5,
  139370. 9,
  139371. 4,
  139372. 10,
  139373. 3,
  139374. 11,
  139375. 2,
  139376. 12,
  139377. 1,
  139378. 13,
  139379. 0,
  139380. 14,
  139381. };
  139382. static long _vq_lengthlist__8u1__p9_0[] = {
  139383. 1, 4, 4,11,11,11,11,11,11,11,11,11,11,11,11, 3,
  139384. 11, 8,11,11,11,11,11,11,11,11,11,11,11,11, 3, 9,
  139385. 9,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139386. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139387. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139388. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139389. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139390. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139391. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139392. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139393. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139394. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139395. 11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,
  139396. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  139397. 10,
  139398. };
  139399. static float _vq_quantthresh__8u1__p9_0[] = {
  139400. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  139401. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  139402. };
  139403. static long _vq_quantmap__8u1__p9_0[] = {
  139404. 13, 11, 9, 7, 5, 3, 1, 0,
  139405. 2, 4, 6, 8, 10, 12, 14,
  139406. };
  139407. static encode_aux_threshmatch _vq_auxt__8u1__p9_0 = {
  139408. _vq_quantthresh__8u1__p9_0,
  139409. _vq_quantmap__8u1__p9_0,
  139410. 15,
  139411. 15
  139412. };
  139413. static static_codebook _8u1__p9_0 = {
  139414. 2, 225,
  139415. _vq_lengthlist__8u1__p9_0,
  139416. 1, -514071552, 1627381760, 4, 0,
  139417. _vq_quantlist__8u1__p9_0,
  139418. NULL,
  139419. &_vq_auxt__8u1__p9_0,
  139420. NULL,
  139421. 0
  139422. };
  139423. static long _vq_quantlist__8u1__p9_1[] = {
  139424. 7,
  139425. 6,
  139426. 8,
  139427. 5,
  139428. 9,
  139429. 4,
  139430. 10,
  139431. 3,
  139432. 11,
  139433. 2,
  139434. 12,
  139435. 1,
  139436. 13,
  139437. 0,
  139438. 14,
  139439. };
  139440. static long _vq_lengthlist__8u1__p9_1[] = {
  139441. 1, 4, 4, 7, 7, 9, 9, 7, 7, 8, 8,10,10,11,11, 4,
  139442. 7, 7, 9, 9,10,10, 8, 8,10,10,10,11,10,11, 4, 7,
  139443. 7, 9, 9,10,10, 8, 8,10, 9,11,11,11,11, 7, 9, 9,
  139444. 12,12,11,12,10,10,11,10,12,11,11,11, 7, 9, 9,11,
  139445. 11,13,12, 9, 9,11,10,11,11,12,11, 9,10,10,12,12,
  139446. 14,14,10,10,11,12,12,11,11,11, 9,10,11,11,13,14,
  139447. 13,10,11,11,11,12,11,12,12, 7, 8, 8,10, 9,11,10,
  139448. 11,12,12,11,12,14,12,13, 7, 8, 8, 9,10,10,11,12,
  139449. 12,12,11,12,12,12,13, 9, 9, 9,11,11,13,12,12,12,
  139450. 12,11,12,12,13,12, 8,10,10,11,10,11,12,12,12,12,
  139451. 12,12,14,12,12, 9,11,11,11,12,12,12,12,13,13,12,
  139452. 12,13,13,12,10,11,11,12,11,12,12,12,11,12,13,12,
  139453. 12,12,13,11,11,12,12,12,13,12,12,11,12,13,13,12,
  139454. 12,13,12,11,12,12,13,13,12,13,12,13,13,13,13,14,
  139455. 13,
  139456. };
  139457. static float _vq_quantthresh__8u1__p9_1[] = {
  139458. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  139459. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  139460. };
  139461. static long _vq_quantmap__8u1__p9_1[] = {
  139462. 13, 11, 9, 7, 5, 3, 1, 0,
  139463. 2, 4, 6, 8, 10, 12, 14,
  139464. };
  139465. static encode_aux_threshmatch _vq_auxt__8u1__p9_1 = {
  139466. _vq_quantthresh__8u1__p9_1,
  139467. _vq_quantmap__8u1__p9_1,
  139468. 15,
  139469. 15
  139470. };
  139471. static static_codebook _8u1__p9_1 = {
  139472. 2, 225,
  139473. _vq_lengthlist__8u1__p9_1,
  139474. 1, -522338304, 1620115456, 4, 0,
  139475. _vq_quantlist__8u1__p9_1,
  139476. NULL,
  139477. &_vq_auxt__8u1__p9_1,
  139478. NULL,
  139479. 0
  139480. };
  139481. static long _vq_quantlist__8u1__p9_2[] = {
  139482. 8,
  139483. 7,
  139484. 9,
  139485. 6,
  139486. 10,
  139487. 5,
  139488. 11,
  139489. 4,
  139490. 12,
  139491. 3,
  139492. 13,
  139493. 2,
  139494. 14,
  139495. 1,
  139496. 15,
  139497. 0,
  139498. 16,
  139499. };
  139500. static long _vq_lengthlist__8u1__p9_2[] = {
  139501. 2, 5, 4, 6, 6, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  139502. 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  139503. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  139504. 9, 9, 9, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  139505. 9,10,10, 9, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  139506. 9, 9, 9,10,10, 8, 8, 8, 9, 9, 9, 9,10,10,10, 9,
  139507. 10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  139508. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,10,
  139509. 10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,10,10,
  139510. 10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,
  139511. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  139512. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,10,
  139513. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  139514. 9,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  139515. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,10,
  139516. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  139517. 10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  139518. 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  139519. 10,
  139520. };
  139521. static float _vq_quantthresh__8u1__p9_2[] = {
  139522. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  139523. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  139524. };
  139525. static long _vq_quantmap__8u1__p9_2[] = {
  139526. 15, 13, 11, 9, 7, 5, 3, 1,
  139527. 0, 2, 4, 6, 8, 10, 12, 14,
  139528. 16,
  139529. };
  139530. static encode_aux_threshmatch _vq_auxt__8u1__p9_2 = {
  139531. _vq_quantthresh__8u1__p9_2,
  139532. _vq_quantmap__8u1__p9_2,
  139533. 17,
  139534. 17
  139535. };
  139536. static static_codebook _8u1__p9_2 = {
  139537. 2, 289,
  139538. _vq_lengthlist__8u1__p9_2,
  139539. 1, -529530880, 1611661312, 5, 0,
  139540. _vq_quantlist__8u1__p9_2,
  139541. NULL,
  139542. &_vq_auxt__8u1__p9_2,
  139543. NULL,
  139544. 0
  139545. };
  139546. static long _huff_lengthlist__8u1__single[] = {
  139547. 4, 7,13, 9,15, 9,16, 8,10,13, 7, 5, 8, 6, 9, 7,
  139548. 10, 7,10,11,11, 6, 7, 8, 8, 9, 9, 9,12,16, 8, 5,
  139549. 8, 6, 8, 6, 9, 7,10,12,11, 7, 7, 7, 6, 7, 7, 7,
  139550. 11,15, 7, 5, 8, 6, 7, 5, 7, 6, 9,13,13, 9, 9, 8,
  139551. 6, 6, 5, 5, 9,14, 8, 6, 8, 6, 6, 4, 5, 3, 5,13,
  139552. 9, 9,11, 8,10, 7, 8, 4, 5,12,11,16,17,15,17,12,
  139553. 13, 8, 8,15,
  139554. };
  139555. static static_codebook _huff_book__8u1__single = {
  139556. 2, 100,
  139557. _huff_lengthlist__8u1__single,
  139558. 0, 0, 0, 0, 0,
  139559. NULL,
  139560. NULL,
  139561. NULL,
  139562. NULL,
  139563. 0
  139564. };
  139565. static long _huff_lengthlist__44u0__long[] = {
  139566. 5, 8,13,10,17,11,11,15, 7, 2, 4, 5, 8, 7, 9,16,
  139567. 13, 4, 3, 5, 6, 8,11,20,10, 4, 5, 5, 7, 6, 8,18,
  139568. 15, 7, 6, 7, 8,10,14,20,10, 6, 7, 6, 9, 7, 8,17,
  139569. 9, 8,10, 8,10, 5, 4,11,12,17,19,14,16,10, 7,12,
  139570. };
  139571. static static_codebook _huff_book__44u0__long = {
  139572. 2, 64,
  139573. _huff_lengthlist__44u0__long,
  139574. 0, 0, 0, 0, 0,
  139575. NULL,
  139576. NULL,
  139577. NULL,
  139578. NULL,
  139579. 0
  139580. };
  139581. static long _vq_quantlist__44u0__p1_0[] = {
  139582. 1,
  139583. 0,
  139584. 2,
  139585. };
  139586. static long _vq_lengthlist__44u0__p1_0[] = {
  139587. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  139588. 10,10, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  139589. 11, 8,11,11, 8,12,11,11,13,13,11,13,14, 7,11,11,
  139590. 10,13,12,11,13,14, 4, 8, 8, 8,11,11, 8,11,12, 8,
  139591. 11,11,11,13,13,10,12,13, 8,11,11,11,14,13,11,14,
  139592. 13,
  139593. };
  139594. static float _vq_quantthresh__44u0__p1_0[] = {
  139595. -0.5, 0.5,
  139596. };
  139597. static long _vq_quantmap__44u0__p1_0[] = {
  139598. 1, 0, 2,
  139599. };
  139600. static encode_aux_threshmatch _vq_auxt__44u0__p1_0 = {
  139601. _vq_quantthresh__44u0__p1_0,
  139602. _vq_quantmap__44u0__p1_0,
  139603. 3,
  139604. 3
  139605. };
  139606. static static_codebook _44u0__p1_0 = {
  139607. 4, 81,
  139608. _vq_lengthlist__44u0__p1_0,
  139609. 1, -535822336, 1611661312, 2, 0,
  139610. _vq_quantlist__44u0__p1_0,
  139611. NULL,
  139612. &_vq_auxt__44u0__p1_0,
  139613. NULL,
  139614. 0
  139615. };
  139616. static long _vq_quantlist__44u0__p2_0[] = {
  139617. 1,
  139618. 0,
  139619. 2,
  139620. };
  139621. static long _vq_lengthlist__44u0__p2_0[] = {
  139622. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  139623. 8, 8, 5, 7, 7, 6, 8, 8, 7, 8, 8, 4, 7, 7, 7, 8,
  139624. 8, 7, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  139625. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 8, 6,
  139626. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  139627. 9,
  139628. };
  139629. static float _vq_quantthresh__44u0__p2_0[] = {
  139630. -0.5, 0.5,
  139631. };
  139632. static long _vq_quantmap__44u0__p2_0[] = {
  139633. 1, 0, 2,
  139634. };
  139635. static encode_aux_threshmatch _vq_auxt__44u0__p2_0 = {
  139636. _vq_quantthresh__44u0__p2_0,
  139637. _vq_quantmap__44u0__p2_0,
  139638. 3,
  139639. 3
  139640. };
  139641. static static_codebook _44u0__p2_0 = {
  139642. 4, 81,
  139643. _vq_lengthlist__44u0__p2_0,
  139644. 1, -535822336, 1611661312, 2, 0,
  139645. _vq_quantlist__44u0__p2_0,
  139646. NULL,
  139647. &_vq_auxt__44u0__p2_0,
  139648. NULL,
  139649. 0
  139650. };
  139651. static long _vq_quantlist__44u0__p3_0[] = {
  139652. 2,
  139653. 1,
  139654. 3,
  139655. 0,
  139656. 4,
  139657. };
  139658. static long _vq_lengthlist__44u0__p3_0[] = {
  139659. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  139660. 10, 9,12,12, 9, 9,10,12,12, 6, 8, 8,11,10, 8,10,
  139661. 10,11,11, 8, 9,10,11,11,10,11,11,14,13,10,11,11,
  139662. 13,13, 5, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  139663. 11,10,11,11,13,13,10,11,11,13,13, 9,11,11,15,14,
  139664. 10,12,12,15,14,10,12,11,15,14,13,14,14,16,16,12,
  139665. 14,13,17,15, 9,11,11,14,15,10,11,12,14,16,10,11,
  139666. 12,14,16,12,13,14,16,16,13,13,15,15,18, 5, 8, 8,
  139667. 11,11, 8,10,10,12,12, 8,10,10,12,13,11,12,12,14,
  139668. 14,11,12,12,15,15, 8,10,10,13,13,10,12,12,13,13,
  139669. 10,12,12,14,14,12,13,13,15,15,12,13,13,16,16, 7,
  139670. 10,10,12,12,10,12,11,13,13,10,12,12,13,14,12,13,
  139671. 12,15,14,12,13,13,16,16,10,12,12,17,16,12,13,13,
  139672. 16,15,11,13,13,17,17,15,15,15,16,17,14,15,15,19,
  139673. 19,10,12,12,15,16,11,13,12,15,18,11,13,13,16,16,
  139674. 14,15,15,17,17,14,15,15,17,19, 5, 8, 8,11,11, 8,
  139675. 10,10,12,12, 8,10,10,12,12,11,12,12,16,15,11,12,
  139676. 12,14,15, 7,10,10,13,13,10,12,12,14,13,10,11,12,
  139677. 13,13,12,13,13,16,16,12,12,13,15,15, 8,10,10,13,
  139678. 13,10,12,12,14,14,10,12,12,13,13,12,13,13,16,16,
  139679. 12,13,13,15,15,10,12,12,16,15,11,13,13,17,16,11,
  139680. 12,13,16,15,13,15,15,19,17,14,15,14,17,16,10,12,
  139681. 12,16,16,11,13,13,16,17,12,13,13,15,17,14,15,15,
  139682. 17,19,14,15,15,17,17, 8,11,11,16,16,10,13,12,17,
  139683. 17,10,12,13,16,16,15,17,16,20,19,14,15,17,18,19,
  139684. 9,12,12,16,17,11,13,14,17,18,11,13,13,19,18,16,
  139685. 17,18,19,19,15,16,16,19,19, 9,12,12,16,17,11,14,
  139686. 13,18,17,11,13,13,17,17,16,17,16,20,19,14,16,16,
  139687. 18,18,12,15,15,19,17,14,15,16, 0,20,13,15,16,20,
  139688. 17,18,16,20, 0, 0,15,16,19,20, 0,12,15,14,18,19,
  139689. 13,16,15,20,19,13,16,15,20,18,17,18,17, 0,20,16,
  139690. 17,16, 0, 0, 8,11,11,16,15,10,12,12,17,17,10,13,
  139691. 13,17,16,14,16,15,18,20,15,16,16,19,19, 9,12,12,
  139692. 16,16,11,13,13,17,16,11,13,14,17,18,15,15,16,20,
  139693. 20,16,16,17,19,19, 9,13,12,16,17,11,14,13,17,17,
  139694. 11,14,14,18,17,14,16,15,18,19,16,17,18,18,19,12,
  139695. 14,15,19,18,13,15,16,18, 0,13,14,15, 0, 0,16,16,
  139696. 17,20, 0,17,17,20,20, 0,12,15,15,19,20,13,15,15,
  139697. 0, 0,14,16,15, 0, 0,15,18,16, 0, 0,17,18,16, 0,
  139698. 19,
  139699. };
  139700. static float _vq_quantthresh__44u0__p3_0[] = {
  139701. -1.5, -0.5, 0.5, 1.5,
  139702. };
  139703. static long _vq_quantmap__44u0__p3_0[] = {
  139704. 3, 1, 0, 2, 4,
  139705. };
  139706. static encode_aux_threshmatch _vq_auxt__44u0__p3_0 = {
  139707. _vq_quantthresh__44u0__p3_0,
  139708. _vq_quantmap__44u0__p3_0,
  139709. 5,
  139710. 5
  139711. };
  139712. static static_codebook _44u0__p3_0 = {
  139713. 4, 625,
  139714. _vq_lengthlist__44u0__p3_0,
  139715. 1, -533725184, 1611661312, 3, 0,
  139716. _vq_quantlist__44u0__p3_0,
  139717. NULL,
  139718. &_vq_auxt__44u0__p3_0,
  139719. NULL,
  139720. 0
  139721. };
  139722. static long _vq_quantlist__44u0__p4_0[] = {
  139723. 2,
  139724. 1,
  139725. 3,
  139726. 0,
  139727. 4,
  139728. };
  139729. static long _vq_lengthlist__44u0__p4_0[] = {
  139730. 4, 5, 5, 9, 9, 5, 6, 6, 9, 9, 5, 6, 6, 9, 9, 9,
  139731. 10, 9,12,12, 9, 9,10,12,12, 5, 7, 7,10,10, 7, 7,
  139732. 8,10,10, 6, 7, 8,10,10,10,10,10,11,13,10, 9,10,
  139733. 12,13, 5, 7, 7,10,10, 6, 8, 7,10,10, 7, 8, 7,10,
  139734. 10, 9,10,10,12,12,10,10,10,13,11, 9,10,10,13,13,
  139735. 10,11,10,13,13,10,10,10,13,13,12,12,13,14,14,12,
  139736. 12,13,14,14, 9,10,10,13,13,10,10,10,13,13,10,10,
  139737. 10,13,13,12,13,12,15,14,12,13,12,15,15, 5, 7, 6,
  139738. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,13,
  139739. 13,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,10,11,
  139740. 8, 9, 9,11,11,11,10,11,11,14,11,11,11,13,13, 6,
  139741. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  139742. 10,14,11,10,11,11,13,13,10,11,11,14,13,10,10,11,
  139743. 14,13,10,11,11,14,14,12,11,13,12,16,13,14,14,15,
  139744. 15,10,10,11,13,14,10,11,10,14,13,10,11,11,14,14,
  139745. 12,13,12,15,13,13,13,14,15,16, 5, 7, 7,10,10, 7,
  139746. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,13,13,10,10,
  139747. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  139748. 10,11,10,11,11,13,13,10,10,11,11,13, 6, 8, 8,10,
  139749. 11, 8, 9, 9,11,11, 8, 9, 8,12,10,10,11,11,13,13,
  139750. 10,11,10,14,11,10,10,10,14,13,10,11,11,14,13,10,
  139751. 10,11,13,13,12,14,14,16,16,12,12,13,13,15,10,11,
  139752. 11,13,14,10,11,11,14,15,10,11,10,13,13,13,14,13,
  139753. 16,16,12,13,11,15,12, 9,10,10,13,13,10,11,11,14,
  139754. 13,10,10,11,13,14,13,14,13,16,16,13,13,13,15,16,
  139755. 9,10,10,13,13,10,10,11,13,14,10,11,11,15,13,13,
  139756. 13,14,14,18,13,13,14,16,15, 9,10,10,13,14,10,11,
  139757. 10,14,13,10,11,11,13,14,13,14,13,16,15,13,13,14,
  139758. 15,16,12,13,12,16,14,11,11,13,15,15,13,14,13,16,
  139759. 15,15,12,16,12,17,14,15,15,17,17,12,13,13,14,16,
  139760. 11,13,11,16,15,12,13,14,15,16,14,15,13, 0,14,14,
  139761. 16,16, 0, 0, 9,10,10,13,13,10,11,10,14,14,10,11,
  139762. 11,13,13,12,13,13,14,16,13,14,14,16,16, 9,10,10,
  139763. 14,14,11,11,11,14,13,10,10,11,14,14,13,13,13,16,
  139764. 16,13,13,14,14,17, 9,10,10,13,14,10,11,11,13,15,
  139765. 10,11,10,14,14,13,13,13,14,17,13,14,13,17,14,12,
  139766. 13,13,16,14,13,14,13,16,15,12,12,13,15,16,15,15,
  139767. 16,18,16,15,13,15,14, 0,12,12,13,14,16,13,13,14,
  139768. 15,16,11,12,11,16,14,15,16,16,17,17,14,15,12,17,
  139769. 12,
  139770. };
  139771. static float _vq_quantthresh__44u0__p4_0[] = {
  139772. -1.5, -0.5, 0.5, 1.5,
  139773. };
  139774. static long _vq_quantmap__44u0__p4_0[] = {
  139775. 3, 1, 0, 2, 4,
  139776. };
  139777. static encode_aux_threshmatch _vq_auxt__44u0__p4_0 = {
  139778. _vq_quantthresh__44u0__p4_0,
  139779. _vq_quantmap__44u0__p4_0,
  139780. 5,
  139781. 5
  139782. };
  139783. static static_codebook _44u0__p4_0 = {
  139784. 4, 625,
  139785. _vq_lengthlist__44u0__p4_0,
  139786. 1, -533725184, 1611661312, 3, 0,
  139787. _vq_quantlist__44u0__p4_0,
  139788. NULL,
  139789. &_vq_auxt__44u0__p4_0,
  139790. NULL,
  139791. 0
  139792. };
  139793. static long _vq_quantlist__44u0__p5_0[] = {
  139794. 4,
  139795. 3,
  139796. 5,
  139797. 2,
  139798. 6,
  139799. 1,
  139800. 7,
  139801. 0,
  139802. 8,
  139803. };
  139804. static long _vq_lengthlist__44u0__p5_0[] = {
  139805. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  139806. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  139807. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,10, 7, 8, 8,
  139808. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  139809. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,11,11,11,12,
  139810. 12,
  139811. };
  139812. static float _vq_quantthresh__44u0__p5_0[] = {
  139813. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  139814. };
  139815. static long _vq_quantmap__44u0__p5_0[] = {
  139816. 7, 5, 3, 1, 0, 2, 4, 6,
  139817. 8,
  139818. };
  139819. static encode_aux_threshmatch _vq_auxt__44u0__p5_0 = {
  139820. _vq_quantthresh__44u0__p5_0,
  139821. _vq_quantmap__44u0__p5_0,
  139822. 9,
  139823. 9
  139824. };
  139825. static static_codebook _44u0__p5_0 = {
  139826. 2, 81,
  139827. _vq_lengthlist__44u0__p5_0,
  139828. 1, -531628032, 1611661312, 4, 0,
  139829. _vq_quantlist__44u0__p5_0,
  139830. NULL,
  139831. &_vq_auxt__44u0__p5_0,
  139832. NULL,
  139833. 0
  139834. };
  139835. static long _vq_quantlist__44u0__p6_0[] = {
  139836. 6,
  139837. 5,
  139838. 7,
  139839. 4,
  139840. 8,
  139841. 3,
  139842. 9,
  139843. 2,
  139844. 10,
  139845. 1,
  139846. 11,
  139847. 0,
  139848. 12,
  139849. };
  139850. static long _vq_lengthlist__44u0__p6_0[] = {
  139851. 1, 4, 4, 6, 6, 8, 8,10, 9,11,10,14,13, 4, 6, 5,
  139852. 8, 8, 9, 9,11,10,11,11,14,14, 4, 5, 6, 8, 8, 9,
  139853. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  139854. 12,12,16,15, 7, 8, 8, 9, 9,10,10,11,11,12,12,15,
  139855. 15, 9,10,10,10,10,11,11,12,12,12,12,15,15, 9,10,
  139856. 9,10,11,11,11,12,12,12,13,15,15,10,10,11,11,11,
  139857. 12,12,13,12,13,13,16,15,10,11,11,11,11,12,12,13,
  139858. 12,13,13,16,17,11,11,12,12,12,13,13,13,14,14,15,
  139859. 17,17,11,11,12,12,12,13,13,13,14,14,14,16,18,14,
  139860. 15,15,15,15,16,16,16,16,17,18, 0, 0,14,15,15,15,
  139861. 15,17,16,17,18,17,17,18, 0,
  139862. };
  139863. static float _vq_quantthresh__44u0__p6_0[] = {
  139864. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  139865. 12.5, 17.5, 22.5, 27.5,
  139866. };
  139867. static long _vq_quantmap__44u0__p6_0[] = {
  139868. 11, 9, 7, 5, 3, 1, 0, 2,
  139869. 4, 6, 8, 10, 12,
  139870. };
  139871. static encode_aux_threshmatch _vq_auxt__44u0__p6_0 = {
  139872. _vq_quantthresh__44u0__p6_0,
  139873. _vq_quantmap__44u0__p6_0,
  139874. 13,
  139875. 13
  139876. };
  139877. static static_codebook _44u0__p6_0 = {
  139878. 2, 169,
  139879. _vq_lengthlist__44u0__p6_0,
  139880. 1, -526516224, 1616117760, 4, 0,
  139881. _vq_quantlist__44u0__p6_0,
  139882. NULL,
  139883. &_vq_auxt__44u0__p6_0,
  139884. NULL,
  139885. 0
  139886. };
  139887. static long _vq_quantlist__44u0__p6_1[] = {
  139888. 2,
  139889. 1,
  139890. 3,
  139891. 0,
  139892. 4,
  139893. };
  139894. static long _vq_lengthlist__44u0__p6_1[] = {
  139895. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  139896. 6, 6, 6, 6, 5, 6, 6, 6, 6,
  139897. };
  139898. static float _vq_quantthresh__44u0__p6_1[] = {
  139899. -1.5, -0.5, 0.5, 1.5,
  139900. };
  139901. static long _vq_quantmap__44u0__p6_1[] = {
  139902. 3, 1, 0, 2, 4,
  139903. };
  139904. static encode_aux_threshmatch _vq_auxt__44u0__p6_1 = {
  139905. _vq_quantthresh__44u0__p6_1,
  139906. _vq_quantmap__44u0__p6_1,
  139907. 5,
  139908. 5
  139909. };
  139910. static static_codebook _44u0__p6_1 = {
  139911. 2, 25,
  139912. _vq_lengthlist__44u0__p6_1,
  139913. 1, -533725184, 1611661312, 3, 0,
  139914. _vq_quantlist__44u0__p6_1,
  139915. NULL,
  139916. &_vq_auxt__44u0__p6_1,
  139917. NULL,
  139918. 0
  139919. };
  139920. static long _vq_quantlist__44u0__p7_0[] = {
  139921. 2,
  139922. 1,
  139923. 3,
  139924. 0,
  139925. 4,
  139926. };
  139927. static long _vq_lengthlist__44u0__p7_0[] = {
  139928. 1, 4, 4,11,11, 9,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, 9,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,10,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,11,11,11,11,11,11,11,11,11,11,
  139945. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139946. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139947. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139948. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139949. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139950. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139951. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139952. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139953. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139954. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139955. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139956. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139957. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  139958. 11,11,11,11,11,11,10,10,10,10,10,10,10,10,10,10,
  139959. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  139960. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  139961. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  139962. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  139963. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  139964. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  139965. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  139966. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  139967. 10,
  139968. };
  139969. static float _vq_quantthresh__44u0__p7_0[] = {
  139970. -253.5, -84.5, 84.5, 253.5,
  139971. };
  139972. static long _vq_quantmap__44u0__p7_0[] = {
  139973. 3, 1, 0, 2, 4,
  139974. };
  139975. static encode_aux_threshmatch _vq_auxt__44u0__p7_0 = {
  139976. _vq_quantthresh__44u0__p7_0,
  139977. _vq_quantmap__44u0__p7_0,
  139978. 5,
  139979. 5
  139980. };
  139981. static static_codebook _44u0__p7_0 = {
  139982. 4, 625,
  139983. _vq_lengthlist__44u0__p7_0,
  139984. 1, -518709248, 1626677248, 3, 0,
  139985. _vq_quantlist__44u0__p7_0,
  139986. NULL,
  139987. &_vq_auxt__44u0__p7_0,
  139988. NULL,
  139989. 0
  139990. };
  139991. static long _vq_quantlist__44u0__p7_1[] = {
  139992. 6,
  139993. 5,
  139994. 7,
  139995. 4,
  139996. 8,
  139997. 3,
  139998. 9,
  139999. 2,
  140000. 10,
  140001. 1,
  140002. 11,
  140003. 0,
  140004. 12,
  140005. };
  140006. static long _vq_lengthlist__44u0__p7_1[] = {
  140007. 1, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 9, 9, 5, 7, 7,
  140008. 8, 7, 7, 7, 9, 8,10, 9,10,11, 5, 7, 7, 8, 8, 7,
  140009. 7, 8, 9,10,10,11,11, 6, 8, 8, 9, 9, 9, 9,11,10,
  140010. 12,12,15,12, 6, 8, 8, 9, 9, 9, 9,11,11,12,11,14,
  140011. 12, 7, 8, 8,10,10,12,12,13,13,13,15,13,13, 7, 8,
  140012. 8,10,10,11,11,13,12,14,15,15,15, 9,10,10,11,12,
  140013. 13,13,14,15,14,15,14,15, 8,10,10,12,12,14,14,15,
  140014. 14,14,15,15,14,10,12,12,14,14,15,14,15,15,15,14,
  140015. 15,15,10,12,12,13,14,15,14,15,15,14,15,15,15,12,
  140016. 15,13,15,14,15,15,15,15,15,15,15,15,13,13,15,15,
  140017. 15,15,15,15,15,15,15,15,15,
  140018. };
  140019. static float _vq_quantthresh__44u0__p7_1[] = {
  140020. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  140021. 32.5, 45.5, 58.5, 71.5,
  140022. };
  140023. static long _vq_quantmap__44u0__p7_1[] = {
  140024. 11, 9, 7, 5, 3, 1, 0, 2,
  140025. 4, 6, 8, 10, 12,
  140026. };
  140027. static encode_aux_threshmatch _vq_auxt__44u0__p7_1 = {
  140028. _vq_quantthresh__44u0__p7_1,
  140029. _vq_quantmap__44u0__p7_1,
  140030. 13,
  140031. 13
  140032. };
  140033. static static_codebook _44u0__p7_1 = {
  140034. 2, 169,
  140035. _vq_lengthlist__44u0__p7_1,
  140036. 1, -523010048, 1618608128, 4, 0,
  140037. _vq_quantlist__44u0__p7_1,
  140038. NULL,
  140039. &_vq_auxt__44u0__p7_1,
  140040. NULL,
  140041. 0
  140042. };
  140043. static long _vq_quantlist__44u0__p7_2[] = {
  140044. 6,
  140045. 5,
  140046. 7,
  140047. 4,
  140048. 8,
  140049. 3,
  140050. 9,
  140051. 2,
  140052. 10,
  140053. 1,
  140054. 11,
  140055. 0,
  140056. 12,
  140057. };
  140058. static long _vq_lengthlist__44u0__p7_2[] = {
  140059. 2, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 5, 5, 6,
  140060. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 5, 6, 5, 7, 7, 8,
  140061. 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8, 8, 8, 8, 9, 8,
  140062. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  140063. 9, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 7, 8,
  140064. 8, 9, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 9, 8, 9, 9,
  140065. 9, 9, 9, 9, 9, 9,10,10, 8, 8, 9, 9, 9, 9, 9, 9,
  140066. 9, 9,10, 9,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  140067. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  140068. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  140069. 9, 9, 9,10, 9, 9,10,10, 9,
  140070. };
  140071. static float _vq_quantthresh__44u0__p7_2[] = {
  140072. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  140073. 2.5, 3.5, 4.5, 5.5,
  140074. };
  140075. static long _vq_quantmap__44u0__p7_2[] = {
  140076. 11, 9, 7, 5, 3, 1, 0, 2,
  140077. 4, 6, 8, 10, 12,
  140078. };
  140079. static encode_aux_threshmatch _vq_auxt__44u0__p7_2 = {
  140080. _vq_quantthresh__44u0__p7_2,
  140081. _vq_quantmap__44u0__p7_2,
  140082. 13,
  140083. 13
  140084. };
  140085. static static_codebook _44u0__p7_2 = {
  140086. 2, 169,
  140087. _vq_lengthlist__44u0__p7_2,
  140088. 1, -531103744, 1611661312, 4, 0,
  140089. _vq_quantlist__44u0__p7_2,
  140090. NULL,
  140091. &_vq_auxt__44u0__p7_2,
  140092. NULL,
  140093. 0
  140094. };
  140095. static long _huff_lengthlist__44u0__short[] = {
  140096. 12,13,14,13,17,12,15,17, 5, 5, 6,10,10,11,15,16,
  140097. 4, 3, 3, 7, 5, 7,10,16, 7, 7, 7,10, 9,11,12,16,
  140098. 6, 5, 5, 9, 5, 6,10,16, 8, 7, 7, 9, 6, 7, 9,16,
  140099. 11, 7, 3, 6, 4, 5, 8,16,12, 9, 4, 8, 5, 7, 9,16,
  140100. };
  140101. static static_codebook _huff_book__44u0__short = {
  140102. 2, 64,
  140103. _huff_lengthlist__44u0__short,
  140104. 0, 0, 0, 0, 0,
  140105. NULL,
  140106. NULL,
  140107. NULL,
  140108. NULL,
  140109. 0
  140110. };
  140111. static long _huff_lengthlist__44u1__long[] = {
  140112. 5, 8,13,10,17,11,11,15, 7, 2, 4, 5, 8, 7, 9,16,
  140113. 13, 4, 3, 5, 6, 8,11,20,10, 4, 5, 5, 7, 6, 8,18,
  140114. 15, 7, 6, 7, 8,10,14,20,10, 6, 7, 6, 9, 7, 8,17,
  140115. 9, 8,10, 8,10, 5, 4,11,12,17,19,14,16,10, 7,12,
  140116. };
  140117. static static_codebook _huff_book__44u1__long = {
  140118. 2, 64,
  140119. _huff_lengthlist__44u1__long,
  140120. 0, 0, 0, 0, 0,
  140121. NULL,
  140122. NULL,
  140123. NULL,
  140124. NULL,
  140125. 0
  140126. };
  140127. static long _vq_quantlist__44u1__p1_0[] = {
  140128. 1,
  140129. 0,
  140130. 2,
  140131. };
  140132. static long _vq_lengthlist__44u1__p1_0[] = {
  140133. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  140134. 10,10, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  140135. 11, 8,11,11, 8,12,11,11,13,13,11,13,14, 7,11,11,
  140136. 10,13,12,11,13,14, 4, 8, 8, 8,11,11, 8,11,12, 8,
  140137. 11,11,11,13,13,10,12,13, 8,11,11,11,14,13,11,14,
  140138. 13,
  140139. };
  140140. static float _vq_quantthresh__44u1__p1_0[] = {
  140141. -0.5, 0.5,
  140142. };
  140143. static long _vq_quantmap__44u1__p1_0[] = {
  140144. 1, 0, 2,
  140145. };
  140146. static encode_aux_threshmatch _vq_auxt__44u1__p1_0 = {
  140147. _vq_quantthresh__44u1__p1_0,
  140148. _vq_quantmap__44u1__p1_0,
  140149. 3,
  140150. 3
  140151. };
  140152. static static_codebook _44u1__p1_0 = {
  140153. 4, 81,
  140154. _vq_lengthlist__44u1__p1_0,
  140155. 1, -535822336, 1611661312, 2, 0,
  140156. _vq_quantlist__44u1__p1_0,
  140157. NULL,
  140158. &_vq_auxt__44u1__p1_0,
  140159. NULL,
  140160. 0
  140161. };
  140162. static long _vq_quantlist__44u1__p2_0[] = {
  140163. 1,
  140164. 0,
  140165. 2,
  140166. };
  140167. static long _vq_lengthlist__44u1__p2_0[] = {
  140168. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  140169. 8, 8, 5, 7, 7, 6, 8, 8, 7, 8, 8, 4, 7, 7, 7, 8,
  140170. 8, 7, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  140171. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 8, 6,
  140172. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  140173. 9,
  140174. };
  140175. static float _vq_quantthresh__44u1__p2_0[] = {
  140176. -0.5, 0.5,
  140177. };
  140178. static long _vq_quantmap__44u1__p2_0[] = {
  140179. 1, 0, 2,
  140180. };
  140181. static encode_aux_threshmatch _vq_auxt__44u1__p2_0 = {
  140182. _vq_quantthresh__44u1__p2_0,
  140183. _vq_quantmap__44u1__p2_0,
  140184. 3,
  140185. 3
  140186. };
  140187. static static_codebook _44u1__p2_0 = {
  140188. 4, 81,
  140189. _vq_lengthlist__44u1__p2_0,
  140190. 1, -535822336, 1611661312, 2, 0,
  140191. _vq_quantlist__44u1__p2_0,
  140192. NULL,
  140193. &_vq_auxt__44u1__p2_0,
  140194. NULL,
  140195. 0
  140196. };
  140197. static long _vq_quantlist__44u1__p3_0[] = {
  140198. 2,
  140199. 1,
  140200. 3,
  140201. 0,
  140202. 4,
  140203. };
  140204. static long _vq_lengthlist__44u1__p3_0[] = {
  140205. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  140206. 10, 9,12,12, 9, 9,10,12,12, 6, 8, 8,11,10, 8,10,
  140207. 10,11,11, 8, 9,10,11,11,10,11,11,14,13,10,11,11,
  140208. 13,13, 5, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  140209. 11,10,11,11,13,13,10,11,11,13,13, 9,11,11,15,14,
  140210. 10,12,12,15,14,10,12,11,15,14,13,14,14,16,16,12,
  140211. 14,13,17,15, 9,11,11,14,15,10,11,12,14,16,10,11,
  140212. 12,14,16,12,13,14,16,16,13,13,15,15,18, 5, 8, 8,
  140213. 11,11, 8,10,10,12,12, 8,10,10,12,13,11,12,12,14,
  140214. 14,11,12,12,15,15, 8,10,10,13,13,10,12,12,13,13,
  140215. 10,12,12,14,14,12,13,13,15,15,12,13,13,16,16, 7,
  140216. 10,10,12,12,10,12,11,13,13,10,12,12,13,14,12,13,
  140217. 12,15,14,12,13,13,16,16,10,12,12,17,16,12,13,13,
  140218. 16,15,11,13,13,17,17,15,15,15,16,17,14,15,15,19,
  140219. 19,10,12,12,15,16,11,13,12,15,18,11,13,13,16,16,
  140220. 14,15,15,17,17,14,15,15,17,19, 5, 8, 8,11,11, 8,
  140221. 10,10,12,12, 8,10,10,12,12,11,12,12,16,15,11,12,
  140222. 12,14,15, 7,10,10,13,13,10,12,12,14,13,10,11,12,
  140223. 13,13,12,13,13,16,16,12,12,13,15,15, 8,10,10,13,
  140224. 13,10,12,12,14,14,10,12,12,13,13,12,13,13,16,16,
  140225. 12,13,13,15,15,10,12,12,16,15,11,13,13,17,16,11,
  140226. 12,13,16,15,13,15,15,19,17,14,15,14,17,16,10,12,
  140227. 12,16,16,11,13,13,16,17,12,13,13,15,17,14,15,15,
  140228. 17,19,14,15,15,17,17, 8,11,11,16,16,10,13,12,17,
  140229. 17,10,12,13,16,16,15,17,16,20,19,14,15,17,18,19,
  140230. 9,12,12,16,17,11,13,14,17,18,11,13,13,19,18,16,
  140231. 17,18,19,19,15,16,16,19,19, 9,12,12,16,17,11,14,
  140232. 13,18,17,11,13,13,17,17,16,17,16,20,19,14,16,16,
  140233. 18,18,12,15,15,19,17,14,15,16, 0,20,13,15,16,20,
  140234. 17,18,16,20, 0, 0,15,16,19,20, 0,12,15,14,18,19,
  140235. 13,16,15,20,19,13,16,15,20,18,17,18,17, 0,20,16,
  140236. 17,16, 0, 0, 8,11,11,16,15,10,12,12,17,17,10,13,
  140237. 13,17,16,14,16,15,18,20,15,16,16,19,19, 9,12,12,
  140238. 16,16,11,13,13,17,16,11,13,14,17,18,15,15,16,20,
  140239. 20,16,16,17,19,19, 9,13,12,16,17,11,14,13,17,17,
  140240. 11,14,14,18,17,14,16,15,18,19,16,17,18,18,19,12,
  140241. 14,15,19,18,13,15,16,18, 0,13,14,15, 0, 0,16,16,
  140242. 17,20, 0,17,17,20,20, 0,12,15,15,19,20,13,15,15,
  140243. 0, 0,14,16,15, 0, 0,15,18,16, 0, 0,17,18,16, 0,
  140244. 19,
  140245. };
  140246. static float _vq_quantthresh__44u1__p3_0[] = {
  140247. -1.5, -0.5, 0.5, 1.5,
  140248. };
  140249. static long _vq_quantmap__44u1__p3_0[] = {
  140250. 3, 1, 0, 2, 4,
  140251. };
  140252. static encode_aux_threshmatch _vq_auxt__44u1__p3_0 = {
  140253. _vq_quantthresh__44u1__p3_0,
  140254. _vq_quantmap__44u1__p3_0,
  140255. 5,
  140256. 5
  140257. };
  140258. static static_codebook _44u1__p3_0 = {
  140259. 4, 625,
  140260. _vq_lengthlist__44u1__p3_0,
  140261. 1, -533725184, 1611661312, 3, 0,
  140262. _vq_quantlist__44u1__p3_0,
  140263. NULL,
  140264. &_vq_auxt__44u1__p3_0,
  140265. NULL,
  140266. 0
  140267. };
  140268. static long _vq_quantlist__44u1__p4_0[] = {
  140269. 2,
  140270. 1,
  140271. 3,
  140272. 0,
  140273. 4,
  140274. };
  140275. static long _vq_lengthlist__44u1__p4_0[] = {
  140276. 4, 5, 5, 9, 9, 5, 6, 6, 9, 9, 5, 6, 6, 9, 9, 9,
  140277. 10, 9,12,12, 9, 9,10,12,12, 5, 7, 7,10,10, 7, 7,
  140278. 8,10,10, 6, 7, 8,10,10,10,10,10,11,13,10, 9,10,
  140279. 12,13, 5, 7, 7,10,10, 6, 8, 7,10,10, 7, 8, 7,10,
  140280. 10, 9,10,10,12,12,10,10,10,13,11, 9,10,10,13,13,
  140281. 10,11,10,13,13,10,10,10,13,13,12,12,13,14,14,12,
  140282. 12,13,14,14, 9,10,10,13,13,10,10,10,13,13,10,10,
  140283. 10,13,13,12,13,12,15,14,12,13,12,15,15, 5, 7, 6,
  140284. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,13,
  140285. 13,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,10,11,
  140286. 8, 9, 9,11,11,11,10,11,11,14,11,11,11,13,13, 6,
  140287. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  140288. 10,14,11,10,11,11,13,13,10,11,11,14,13,10,10,11,
  140289. 14,13,10,11,11,14,14,12,11,13,12,16,13,14,14,15,
  140290. 15,10,10,11,13,14,10,11,10,14,13,10,11,11,14,14,
  140291. 12,13,12,15,13,13,13,14,15,16, 5, 7, 7,10,10, 7,
  140292. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,13,13,10,10,
  140293. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  140294. 10,11,10,11,11,13,13,10,10,11,11,13, 6, 8, 8,10,
  140295. 11, 8, 9, 9,11,11, 8, 9, 8,12,10,10,11,11,13,13,
  140296. 10,11,10,14,11,10,10,10,14,13,10,11,11,14,13,10,
  140297. 10,11,13,13,12,14,14,16,16,12,12,13,13,15,10,11,
  140298. 11,13,14,10,11,11,14,15,10,11,10,13,13,13,14,13,
  140299. 16,16,12,13,11,15,12, 9,10,10,13,13,10,11,11,14,
  140300. 13,10,10,11,13,14,13,14,13,16,16,13,13,13,15,16,
  140301. 9,10,10,13,13,10,10,11,13,14,10,11,11,15,13,13,
  140302. 13,14,14,18,13,13,14,16,15, 9,10,10,13,14,10,11,
  140303. 10,14,13,10,11,11,13,14,13,14,13,16,15,13,13,14,
  140304. 15,16,12,13,12,16,14,11,11,13,15,15,13,14,13,16,
  140305. 15,15,12,16,12,17,14,15,15,17,17,12,13,13,14,16,
  140306. 11,13,11,16,15,12,13,14,15,16,14,15,13, 0,14,14,
  140307. 16,16, 0, 0, 9,10,10,13,13,10,11,10,14,14,10,11,
  140308. 11,13,13,12,13,13,14,16,13,14,14,16,16, 9,10,10,
  140309. 14,14,11,11,11,14,13,10,10,11,14,14,13,13,13,16,
  140310. 16,13,13,14,14,17, 9,10,10,13,14,10,11,11,13,15,
  140311. 10,11,10,14,14,13,13,13,14,17,13,14,13,17,14,12,
  140312. 13,13,16,14,13,14,13,16,15,12,12,13,15,16,15,15,
  140313. 16,18,16,15,13,15,14, 0,12,12,13,14,16,13,13,14,
  140314. 15,16,11,12,11,16,14,15,16,16,17,17,14,15,12,17,
  140315. 12,
  140316. };
  140317. static float _vq_quantthresh__44u1__p4_0[] = {
  140318. -1.5, -0.5, 0.5, 1.5,
  140319. };
  140320. static long _vq_quantmap__44u1__p4_0[] = {
  140321. 3, 1, 0, 2, 4,
  140322. };
  140323. static encode_aux_threshmatch _vq_auxt__44u1__p4_0 = {
  140324. _vq_quantthresh__44u1__p4_0,
  140325. _vq_quantmap__44u1__p4_0,
  140326. 5,
  140327. 5
  140328. };
  140329. static static_codebook _44u1__p4_0 = {
  140330. 4, 625,
  140331. _vq_lengthlist__44u1__p4_0,
  140332. 1, -533725184, 1611661312, 3, 0,
  140333. _vq_quantlist__44u1__p4_0,
  140334. NULL,
  140335. &_vq_auxt__44u1__p4_0,
  140336. NULL,
  140337. 0
  140338. };
  140339. static long _vq_quantlist__44u1__p5_0[] = {
  140340. 4,
  140341. 3,
  140342. 5,
  140343. 2,
  140344. 6,
  140345. 1,
  140346. 7,
  140347. 0,
  140348. 8,
  140349. };
  140350. static long _vq_lengthlist__44u1__p5_0[] = {
  140351. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  140352. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  140353. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,10, 7, 8, 8,
  140354. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  140355. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,11,11,11,12,
  140356. 12,
  140357. };
  140358. static float _vq_quantthresh__44u1__p5_0[] = {
  140359. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  140360. };
  140361. static long _vq_quantmap__44u1__p5_0[] = {
  140362. 7, 5, 3, 1, 0, 2, 4, 6,
  140363. 8,
  140364. };
  140365. static encode_aux_threshmatch _vq_auxt__44u1__p5_0 = {
  140366. _vq_quantthresh__44u1__p5_0,
  140367. _vq_quantmap__44u1__p5_0,
  140368. 9,
  140369. 9
  140370. };
  140371. static static_codebook _44u1__p5_0 = {
  140372. 2, 81,
  140373. _vq_lengthlist__44u1__p5_0,
  140374. 1, -531628032, 1611661312, 4, 0,
  140375. _vq_quantlist__44u1__p5_0,
  140376. NULL,
  140377. &_vq_auxt__44u1__p5_0,
  140378. NULL,
  140379. 0
  140380. };
  140381. static long _vq_quantlist__44u1__p6_0[] = {
  140382. 6,
  140383. 5,
  140384. 7,
  140385. 4,
  140386. 8,
  140387. 3,
  140388. 9,
  140389. 2,
  140390. 10,
  140391. 1,
  140392. 11,
  140393. 0,
  140394. 12,
  140395. };
  140396. static long _vq_lengthlist__44u1__p6_0[] = {
  140397. 1, 4, 4, 6, 6, 8, 8,10, 9,11,10,14,13, 4, 6, 5,
  140398. 8, 8, 9, 9,11,10,11,11,14,14, 4, 5, 6, 8, 8, 9,
  140399. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  140400. 12,12,16,15, 7, 8, 8, 9, 9,10,10,11,11,12,12,15,
  140401. 15, 9,10,10,10,10,11,11,12,12,12,12,15,15, 9,10,
  140402. 9,10,11,11,11,12,12,12,13,15,15,10,10,11,11,11,
  140403. 12,12,13,12,13,13,16,15,10,11,11,11,11,12,12,13,
  140404. 12,13,13,16,17,11,11,12,12,12,13,13,13,14,14,15,
  140405. 17,17,11,11,12,12,12,13,13,13,14,14,14,16,18,14,
  140406. 15,15,15,15,16,16,16,16,17,18, 0, 0,14,15,15,15,
  140407. 15,17,16,17,18,17,17,18, 0,
  140408. };
  140409. static float _vq_quantthresh__44u1__p6_0[] = {
  140410. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  140411. 12.5, 17.5, 22.5, 27.5,
  140412. };
  140413. static long _vq_quantmap__44u1__p6_0[] = {
  140414. 11, 9, 7, 5, 3, 1, 0, 2,
  140415. 4, 6, 8, 10, 12,
  140416. };
  140417. static encode_aux_threshmatch _vq_auxt__44u1__p6_0 = {
  140418. _vq_quantthresh__44u1__p6_0,
  140419. _vq_quantmap__44u1__p6_0,
  140420. 13,
  140421. 13
  140422. };
  140423. static static_codebook _44u1__p6_0 = {
  140424. 2, 169,
  140425. _vq_lengthlist__44u1__p6_0,
  140426. 1, -526516224, 1616117760, 4, 0,
  140427. _vq_quantlist__44u1__p6_0,
  140428. NULL,
  140429. &_vq_auxt__44u1__p6_0,
  140430. NULL,
  140431. 0
  140432. };
  140433. static long _vq_quantlist__44u1__p6_1[] = {
  140434. 2,
  140435. 1,
  140436. 3,
  140437. 0,
  140438. 4,
  140439. };
  140440. static long _vq_lengthlist__44u1__p6_1[] = {
  140441. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  140442. 6, 6, 6, 6, 5, 6, 6, 6, 6,
  140443. };
  140444. static float _vq_quantthresh__44u1__p6_1[] = {
  140445. -1.5, -0.5, 0.5, 1.5,
  140446. };
  140447. static long _vq_quantmap__44u1__p6_1[] = {
  140448. 3, 1, 0, 2, 4,
  140449. };
  140450. static encode_aux_threshmatch _vq_auxt__44u1__p6_1 = {
  140451. _vq_quantthresh__44u1__p6_1,
  140452. _vq_quantmap__44u1__p6_1,
  140453. 5,
  140454. 5
  140455. };
  140456. static static_codebook _44u1__p6_1 = {
  140457. 2, 25,
  140458. _vq_lengthlist__44u1__p6_1,
  140459. 1, -533725184, 1611661312, 3, 0,
  140460. _vq_quantlist__44u1__p6_1,
  140461. NULL,
  140462. &_vq_auxt__44u1__p6_1,
  140463. NULL,
  140464. 0
  140465. };
  140466. static long _vq_quantlist__44u1__p7_0[] = {
  140467. 3,
  140468. 2,
  140469. 4,
  140470. 1,
  140471. 5,
  140472. 0,
  140473. 6,
  140474. };
  140475. static long _vq_lengthlist__44u1__p7_0[] = {
  140476. 1, 3, 2, 9, 9, 7, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  140477. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  140478. 9, 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  140479. 8,
  140480. };
  140481. static float _vq_quantthresh__44u1__p7_0[] = {
  140482. -422.5, -253.5, -84.5, 84.5, 253.5, 422.5,
  140483. };
  140484. static long _vq_quantmap__44u1__p7_0[] = {
  140485. 5, 3, 1, 0, 2, 4, 6,
  140486. };
  140487. static encode_aux_threshmatch _vq_auxt__44u1__p7_0 = {
  140488. _vq_quantthresh__44u1__p7_0,
  140489. _vq_quantmap__44u1__p7_0,
  140490. 7,
  140491. 7
  140492. };
  140493. static static_codebook _44u1__p7_0 = {
  140494. 2, 49,
  140495. _vq_lengthlist__44u1__p7_0,
  140496. 1, -518017024, 1626677248, 3, 0,
  140497. _vq_quantlist__44u1__p7_0,
  140498. NULL,
  140499. &_vq_auxt__44u1__p7_0,
  140500. NULL,
  140501. 0
  140502. };
  140503. static long _vq_quantlist__44u1__p7_1[] = {
  140504. 6,
  140505. 5,
  140506. 7,
  140507. 4,
  140508. 8,
  140509. 3,
  140510. 9,
  140511. 2,
  140512. 10,
  140513. 1,
  140514. 11,
  140515. 0,
  140516. 12,
  140517. };
  140518. static long _vq_lengthlist__44u1__p7_1[] = {
  140519. 1, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 9, 9, 5, 7, 7,
  140520. 8, 7, 7, 7, 9, 8,10, 9,10,11, 5, 7, 7, 8, 8, 7,
  140521. 7, 8, 9,10,10,11,11, 6, 8, 8, 9, 9, 9, 9,11,10,
  140522. 12,12,15,12, 6, 8, 8, 9, 9, 9, 9,11,11,12,11,14,
  140523. 12, 7, 8, 8,10,10,12,12,13,13,13,15,13,13, 7, 8,
  140524. 8,10,10,11,11,13,12,14,15,15,15, 9,10,10,11,12,
  140525. 13,13,14,15,14,15,14,15, 8,10,10,12,12,14,14,15,
  140526. 14,14,15,15,14,10,12,12,14,14,15,14,15,15,15,14,
  140527. 15,15,10,12,12,13,14,15,14,15,15,14,15,15,15,12,
  140528. 15,13,15,14,15,15,15,15,15,15,15,15,13,13,15,15,
  140529. 15,15,15,15,15,15,15,15,15,
  140530. };
  140531. static float _vq_quantthresh__44u1__p7_1[] = {
  140532. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  140533. 32.5, 45.5, 58.5, 71.5,
  140534. };
  140535. static long _vq_quantmap__44u1__p7_1[] = {
  140536. 11, 9, 7, 5, 3, 1, 0, 2,
  140537. 4, 6, 8, 10, 12,
  140538. };
  140539. static encode_aux_threshmatch _vq_auxt__44u1__p7_1 = {
  140540. _vq_quantthresh__44u1__p7_1,
  140541. _vq_quantmap__44u1__p7_1,
  140542. 13,
  140543. 13
  140544. };
  140545. static static_codebook _44u1__p7_1 = {
  140546. 2, 169,
  140547. _vq_lengthlist__44u1__p7_1,
  140548. 1, -523010048, 1618608128, 4, 0,
  140549. _vq_quantlist__44u1__p7_1,
  140550. NULL,
  140551. &_vq_auxt__44u1__p7_1,
  140552. NULL,
  140553. 0
  140554. };
  140555. static long _vq_quantlist__44u1__p7_2[] = {
  140556. 6,
  140557. 5,
  140558. 7,
  140559. 4,
  140560. 8,
  140561. 3,
  140562. 9,
  140563. 2,
  140564. 10,
  140565. 1,
  140566. 11,
  140567. 0,
  140568. 12,
  140569. };
  140570. static long _vq_lengthlist__44u1__p7_2[] = {
  140571. 2, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 5, 5, 6,
  140572. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 5, 6, 5, 7, 7, 8,
  140573. 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8, 8, 8, 8, 9, 8,
  140574. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  140575. 9, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 7, 8,
  140576. 8, 9, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 9, 8, 9, 9,
  140577. 9, 9, 9, 9, 9, 9,10,10, 8, 8, 9, 9, 9, 9, 9, 9,
  140578. 9, 9,10, 9,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  140579. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  140580. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  140581. 9, 9, 9,10, 9, 9,10,10, 9,
  140582. };
  140583. static float _vq_quantthresh__44u1__p7_2[] = {
  140584. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  140585. 2.5, 3.5, 4.5, 5.5,
  140586. };
  140587. static long _vq_quantmap__44u1__p7_2[] = {
  140588. 11, 9, 7, 5, 3, 1, 0, 2,
  140589. 4, 6, 8, 10, 12,
  140590. };
  140591. static encode_aux_threshmatch _vq_auxt__44u1__p7_2 = {
  140592. _vq_quantthresh__44u1__p7_2,
  140593. _vq_quantmap__44u1__p7_2,
  140594. 13,
  140595. 13
  140596. };
  140597. static static_codebook _44u1__p7_2 = {
  140598. 2, 169,
  140599. _vq_lengthlist__44u1__p7_2,
  140600. 1, -531103744, 1611661312, 4, 0,
  140601. _vq_quantlist__44u1__p7_2,
  140602. NULL,
  140603. &_vq_auxt__44u1__p7_2,
  140604. NULL,
  140605. 0
  140606. };
  140607. static long _huff_lengthlist__44u1__short[] = {
  140608. 12,13,14,13,17,12,15,17, 5, 5, 6,10,10,11,15,16,
  140609. 4, 3, 3, 7, 5, 7,10,16, 7, 7, 7,10, 9,11,12,16,
  140610. 6, 5, 5, 9, 5, 6,10,16, 8, 7, 7, 9, 6, 7, 9,16,
  140611. 11, 7, 3, 6, 4, 5, 8,16,12, 9, 4, 8, 5, 7, 9,16,
  140612. };
  140613. static static_codebook _huff_book__44u1__short = {
  140614. 2, 64,
  140615. _huff_lengthlist__44u1__short,
  140616. 0, 0, 0, 0, 0,
  140617. NULL,
  140618. NULL,
  140619. NULL,
  140620. NULL,
  140621. 0
  140622. };
  140623. static long _huff_lengthlist__44u2__long[] = {
  140624. 5, 9,14,12,15,13,10,13, 7, 4, 5, 6, 8, 7, 8,12,
  140625. 13, 4, 3, 5, 5, 6, 9,15,12, 6, 5, 6, 6, 6, 7,14,
  140626. 14, 7, 4, 6, 4, 6, 8,15,12, 6, 6, 5, 5, 5, 6,14,
  140627. 9, 7, 8, 6, 7, 5, 4,10,10,13,14,14,15,10, 6, 8,
  140628. };
  140629. static static_codebook _huff_book__44u2__long = {
  140630. 2, 64,
  140631. _huff_lengthlist__44u2__long,
  140632. 0, 0, 0, 0, 0,
  140633. NULL,
  140634. NULL,
  140635. NULL,
  140636. NULL,
  140637. 0
  140638. };
  140639. static long _vq_quantlist__44u2__p1_0[] = {
  140640. 1,
  140641. 0,
  140642. 2,
  140643. };
  140644. static long _vq_lengthlist__44u2__p1_0[] = {
  140645. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  140646. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  140647. 11, 8,11,11, 8,11,11,11,13,14,11,13,13, 7,11,11,
  140648. 10,13,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 8,
  140649. 11,11,11,14,13,10,12,13, 8,11,11,11,13,13,11,13,
  140650. 13,
  140651. };
  140652. static float _vq_quantthresh__44u2__p1_0[] = {
  140653. -0.5, 0.5,
  140654. };
  140655. static long _vq_quantmap__44u2__p1_0[] = {
  140656. 1, 0, 2,
  140657. };
  140658. static encode_aux_threshmatch _vq_auxt__44u2__p1_0 = {
  140659. _vq_quantthresh__44u2__p1_0,
  140660. _vq_quantmap__44u2__p1_0,
  140661. 3,
  140662. 3
  140663. };
  140664. static static_codebook _44u2__p1_0 = {
  140665. 4, 81,
  140666. _vq_lengthlist__44u2__p1_0,
  140667. 1, -535822336, 1611661312, 2, 0,
  140668. _vq_quantlist__44u2__p1_0,
  140669. NULL,
  140670. &_vq_auxt__44u2__p1_0,
  140671. NULL,
  140672. 0
  140673. };
  140674. static long _vq_quantlist__44u2__p2_0[] = {
  140675. 1,
  140676. 0,
  140677. 2,
  140678. };
  140679. static long _vq_lengthlist__44u2__p2_0[] = {
  140680. 2, 5, 5, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  140681. 8, 8, 5, 6, 6, 6, 8, 7, 7, 8, 8, 5, 6, 6, 7, 8,
  140682. 8, 6, 8, 8, 6, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  140683. 7,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  140684. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  140685. 9,
  140686. };
  140687. static float _vq_quantthresh__44u2__p2_0[] = {
  140688. -0.5, 0.5,
  140689. };
  140690. static long _vq_quantmap__44u2__p2_0[] = {
  140691. 1, 0, 2,
  140692. };
  140693. static encode_aux_threshmatch _vq_auxt__44u2__p2_0 = {
  140694. _vq_quantthresh__44u2__p2_0,
  140695. _vq_quantmap__44u2__p2_0,
  140696. 3,
  140697. 3
  140698. };
  140699. static static_codebook _44u2__p2_0 = {
  140700. 4, 81,
  140701. _vq_lengthlist__44u2__p2_0,
  140702. 1, -535822336, 1611661312, 2, 0,
  140703. _vq_quantlist__44u2__p2_0,
  140704. NULL,
  140705. &_vq_auxt__44u2__p2_0,
  140706. NULL,
  140707. 0
  140708. };
  140709. static long _vq_quantlist__44u2__p3_0[] = {
  140710. 2,
  140711. 1,
  140712. 3,
  140713. 0,
  140714. 4,
  140715. };
  140716. static long _vq_lengthlist__44u2__p3_0[] = {
  140717. 2, 4, 4, 7, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  140718. 9, 9,12,11, 8, 9, 9,11,12, 5, 7, 7,10,10, 7, 9,
  140719. 9,11,11, 7, 9, 9,10,11,10,11,11,13,13, 9,10,11,
  140720. 12,13, 5, 7, 7,10,10, 7, 9, 9,11,10, 7, 9, 9,11,
  140721. 11, 9,11,10,13,13,10,11,11,13,13, 8,10,10,14,13,
  140722. 10,11,11,15,14, 9,11,11,15,14,13,14,13,16,14,12,
  140723. 13,13,15,16, 8,10,10,13,14, 9,11,11,14,15,10,11,
  140724. 11,14,15,12,13,13,15,15,12,13,14,15,16, 5, 7, 7,
  140725. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,12,10,11,11,14,
  140726. 13,10,11,11,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  140727. 9,11,11,13,13,12,13,12,14,14,11,12,13,15,15, 7,
  140728. 9, 9,12,12, 8,11,10,13,12, 9,11,11,13,13,11,13,
  140729. 12,15,13,11,13,13,15,16, 9,12,11,15,15,11,12,12,
  140730. 16,15,11,12,13,16,16,13,14,15,16,15,13,15,15,17,
  140731. 17, 9,11,11,14,15,10,12,12,15,15,11,13,12,15,16,
  140732. 13,15,14,16,16,13,15,15,17,19, 5, 7, 7,10,10, 7,
  140733. 9, 9,12,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  140734. 11,13,14, 7, 9, 9,12,12, 9,11,11,13,13, 9,10,11,
  140735. 12,13,11,13,12,16,15,11,12,12,14,15, 7, 9, 9,12,
  140736. 12, 9,11,11,13,13, 9,11,11,13,12,11,13,12,15,16,
  140737. 12,13,13,15,14, 9,11,11,15,14,11,13,12,16,15,10,
  140738. 11,12,15,15,13,14,14,18,17,13,14,14,15,17,10,11,
  140739. 11,14,15,11,13,12,15,17,11,13,12,15,16,13,15,14,
  140740. 18,17,14,15,15,16,18, 7,10,10,14,14,10,12,12,15,
  140741. 15,10,12,12,15,15,14,15,15,18,17,13,15,15,16,16,
  140742. 9,11,11,16,15,11,13,13,16,18,11,13,13,16,16,15,
  140743. 16,16, 0, 0,14,15,16,18,17, 9,11,11,15,15,10,13,
  140744. 12,17,16,11,12,13,16,17,14,15,16,19,19,14,15,15,
  140745. 0,20,12,14,14, 0, 0,13,14,16,19,18,13,15,16,20,
  140746. 17,16,18, 0, 0, 0,15,16,17,18,19,11,14,14, 0,19,
  140747. 12,15,14,17,17,13,15,15, 0, 0,16,17,15,20,19,15,
  140748. 17,16,19, 0, 8,10,10,14,15,10,12,11,15,15,10,11,
  140749. 12,16,15,13,14,14,19,17,14,15,15, 0, 0, 9,11,11,
  140750. 16,15,11,13,13,17,16,10,12,13,16,17,14,15,15,18,
  140751. 18,14,15,16,20,19, 9,12,12, 0,15,11,13,13,16,17,
  140752. 11,13,13,19,17,14,16,16,18,17,15,16,16,17,19,11,
  140753. 14,14,18,18,13,14,15, 0, 0,12,14,15,19,18,15,16,
  140754. 19, 0,19,15,16,19,19,17,12,14,14,16,19,13,15,15,
  140755. 0,17,13,15,14,18,18,15,16,15, 0,18,16,17,17, 0,
  140756. 0,
  140757. };
  140758. static float _vq_quantthresh__44u2__p3_0[] = {
  140759. -1.5, -0.5, 0.5, 1.5,
  140760. };
  140761. static long _vq_quantmap__44u2__p3_0[] = {
  140762. 3, 1, 0, 2, 4,
  140763. };
  140764. static encode_aux_threshmatch _vq_auxt__44u2__p3_0 = {
  140765. _vq_quantthresh__44u2__p3_0,
  140766. _vq_quantmap__44u2__p3_0,
  140767. 5,
  140768. 5
  140769. };
  140770. static static_codebook _44u2__p3_0 = {
  140771. 4, 625,
  140772. _vq_lengthlist__44u2__p3_0,
  140773. 1, -533725184, 1611661312, 3, 0,
  140774. _vq_quantlist__44u2__p3_0,
  140775. NULL,
  140776. &_vq_auxt__44u2__p3_0,
  140777. NULL,
  140778. 0
  140779. };
  140780. static long _vq_quantlist__44u2__p4_0[] = {
  140781. 2,
  140782. 1,
  140783. 3,
  140784. 0,
  140785. 4,
  140786. };
  140787. static long _vq_lengthlist__44u2__p4_0[] = {
  140788. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  140789. 9, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  140790. 8,10,10, 7, 7, 8,10,10,10,10,10,11,12, 9,10,10,
  140791. 11,12, 5, 7, 7, 9, 9, 6, 8, 7,10,10, 7, 8, 8,10,
  140792. 10, 9,10,10,12,11, 9,10,10,12,11, 9,10,10,12,12,
  140793. 10,10,10,13,12, 9,10,10,12,13,12,12,12,14,14,11,
  140794. 12,12,13,14, 9,10,10,12,12, 9,10,10,12,13,10,10,
  140795. 10,12,13,11,12,12,14,13,12,12,12,14,13, 5, 7, 7,
  140796. 10, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  140797. 12,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  140798. 8, 9, 9,11,11,10,11,11,12,13,10,11,11,13,13, 6,
  140799. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  140800. 10,13,11,10,11,11,13,13, 9,10,10,13,13,10,11,11,
  140801. 13,13,10,11,11,14,13,12,11,13,12,15,12,13,13,15,
  140802. 15, 9,10,10,12,13,10,11,10,13,13,10,11,11,13,13,
  140803. 12,13,11,15,13,12,13,13,15,15, 5, 7, 7, 9,10, 7,
  140804. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,12,10,10,
  140805. 11,12,12, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  140806. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  140807. 11, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,11,13,13,
  140808. 10,11,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  140809. 10,11,13,13,12,13,13,15,15,12,11,13,12,14, 9,10,
  140810. 10,12,13,10,11,11,13,14,10,11,11,13,13,12,13,13,
  140811. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  140812. 13, 9,10,10,13,13,12,13,13,15,15,12,12,12,14,14,
  140813. 9,10,10,13,13,10,11,11,13,14,10,11,11,14,12,13,
  140814. 13,14,14,16,12,13,13,15,14, 9,10,10,13,13,10,11,
  140815. 10,14,13,10,11,11,13,14,12,14,13,16,14,13,13,13,
  140816. 14,15,11,13,12,15,14,11,12,13,14,15,12,13,13,16,
  140817. 15,14,12,15,12,16,14,15,15,17,16,11,12,12,14,15,
  140818. 11,13,11,15,14,12,13,13,15,16,13,15,12,17,13,14,
  140819. 15,15,16,16, 8, 9, 9,12,12, 9,10,10,13,13, 9,10,
  140820. 10,13,13,12,13,12,14,14,12,13,13,15,15, 9,10,10,
  140821. 13,13,10,11,11,14,13,10,10,11,13,14,12,13,13,15,
  140822. 14,12,12,14,14,16, 9,10,10,13,13,10,11,11,13,14,
  140823. 10,11,11,14,13,13,13,13,15,15,13,14,13,16,14,11,
  140824. 12,12,14,14,12,13,13,16,15,11,12,13,14,15,14,15,
  140825. 15,16,16,14,13,15,13,17,11,12,12,14,15,12,13,13,
  140826. 15,16,11,13,12,15,15,14,15,14,16,16,14,15,12,17,
  140827. 13,
  140828. };
  140829. static float _vq_quantthresh__44u2__p4_0[] = {
  140830. -1.5, -0.5, 0.5, 1.5,
  140831. };
  140832. static long _vq_quantmap__44u2__p4_0[] = {
  140833. 3, 1, 0, 2, 4,
  140834. };
  140835. static encode_aux_threshmatch _vq_auxt__44u2__p4_0 = {
  140836. _vq_quantthresh__44u2__p4_0,
  140837. _vq_quantmap__44u2__p4_0,
  140838. 5,
  140839. 5
  140840. };
  140841. static static_codebook _44u2__p4_0 = {
  140842. 4, 625,
  140843. _vq_lengthlist__44u2__p4_0,
  140844. 1, -533725184, 1611661312, 3, 0,
  140845. _vq_quantlist__44u2__p4_0,
  140846. NULL,
  140847. &_vq_auxt__44u2__p4_0,
  140848. NULL,
  140849. 0
  140850. };
  140851. static long _vq_quantlist__44u2__p5_0[] = {
  140852. 4,
  140853. 3,
  140854. 5,
  140855. 2,
  140856. 6,
  140857. 1,
  140858. 7,
  140859. 0,
  140860. 8,
  140861. };
  140862. static long _vq_lengthlist__44u2__p5_0[] = {
  140863. 1, 4, 4, 7, 7, 8, 8, 9, 9, 4, 6, 5, 8, 8, 8, 8,
  140864. 10,10, 4, 5, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  140865. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 8, 8, 8,
  140866. 9, 9,10,11,12,12, 8, 8, 8, 9, 9,10,10,12,12,10,
  140867. 10,10,11,11,12,12,13,13,10,10,10,11,11,12,12,13,
  140868. 13,
  140869. };
  140870. static float _vq_quantthresh__44u2__p5_0[] = {
  140871. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  140872. };
  140873. static long _vq_quantmap__44u2__p5_0[] = {
  140874. 7, 5, 3, 1, 0, 2, 4, 6,
  140875. 8,
  140876. };
  140877. static encode_aux_threshmatch _vq_auxt__44u2__p5_0 = {
  140878. _vq_quantthresh__44u2__p5_0,
  140879. _vq_quantmap__44u2__p5_0,
  140880. 9,
  140881. 9
  140882. };
  140883. static static_codebook _44u2__p5_0 = {
  140884. 2, 81,
  140885. _vq_lengthlist__44u2__p5_0,
  140886. 1, -531628032, 1611661312, 4, 0,
  140887. _vq_quantlist__44u2__p5_0,
  140888. NULL,
  140889. &_vq_auxt__44u2__p5_0,
  140890. NULL,
  140891. 0
  140892. };
  140893. static long _vq_quantlist__44u2__p6_0[] = {
  140894. 6,
  140895. 5,
  140896. 7,
  140897. 4,
  140898. 8,
  140899. 3,
  140900. 9,
  140901. 2,
  140902. 10,
  140903. 1,
  140904. 11,
  140905. 0,
  140906. 12,
  140907. };
  140908. static long _vq_lengthlist__44u2__p6_0[] = {
  140909. 1, 4, 4, 6, 6, 8, 8,10,10,11,11,14,13, 4, 6, 5,
  140910. 8, 8, 9, 9,11,10,12,11,15,14, 4, 5, 6, 8, 8, 9,
  140911. 9,11,11,11,11,14,14, 6, 8, 8,10, 9,11,11,11,11,
  140912. 12,12,15,15, 6, 8, 8, 9, 9,11,11,11,12,12,12,15,
  140913. 15, 8,10,10,11,11,11,11,12,12,13,13,15,16, 8,10,
  140914. 10,11,11,11,11,12,12,13,13,16,16,10,11,11,12,12,
  140915. 12,12,13,13,13,13,17,16,10,11,11,12,12,12,12,13,
  140916. 13,13,14,16,17,11,12,12,13,13,13,13,14,14,15,14,
  140917. 18,17,11,12,12,13,13,13,13,14,14,14,15,19,18,14,
  140918. 15,15,15,15,16,16,18,19,18,18, 0, 0,14,15,15,16,
  140919. 15,17,17,16,18,17,18, 0, 0,
  140920. };
  140921. static float _vq_quantthresh__44u2__p6_0[] = {
  140922. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  140923. 12.5, 17.5, 22.5, 27.5,
  140924. };
  140925. static long _vq_quantmap__44u2__p6_0[] = {
  140926. 11, 9, 7, 5, 3, 1, 0, 2,
  140927. 4, 6, 8, 10, 12,
  140928. };
  140929. static encode_aux_threshmatch _vq_auxt__44u2__p6_0 = {
  140930. _vq_quantthresh__44u2__p6_0,
  140931. _vq_quantmap__44u2__p6_0,
  140932. 13,
  140933. 13
  140934. };
  140935. static static_codebook _44u2__p6_0 = {
  140936. 2, 169,
  140937. _vq_lengthlist__44u2__p6_0,
  140938. 1, -526516224, 1616117760, 4, 0,
  140939. _vq_quantlist__44u2__p6_0,
  140940. NULL,
  140941. &_vq_auxt__44u2__p6_0,
  140942. NULL,
  140943. 0
  140944. };
  140945. static long _vq_quantlist__44u2__p6_1[] = {
  140946. 2,
  140947. 1,
  140948. 3,
  140949. 0,
  140950. 4,
  140951. };
  140952. static long _vq_lengthlist__44u2__p6_1[] = {
  140953. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  140954. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  140955. };
  140956. static float _vq_quantthresh__44u2__p6_1[] = {
  140957. -1.5, -0.5, 0.5, 1.5,
  140958. };
  140959. static long _vq_quantmap__44u2__p6_1[] = {
  140960. 3, 1, 0, 2, 4,
  140961. };
  140962. static encode_aux_threshmatch _vq_auxt__44u2__p6_1 = {
  140963. _vq_quantthresh__44u2__p6_1,
  140964. _vq_quantmap__44u2__p6_1,
  140965. 5,
  140966. 5
  140967. };
  140968. static static_codebook _44u2__p6_1 = {
  140969. 2, 25,
  140970. _vq_lengthlist__44u2__p6_1,
  140971. 1, -533725184, 1611661312, 3, 0,
  140972. _vq_quantlist__44u2__p6_1,
  140973. NULL,
  140974. &_vq_auxt__44u2__p6_1,
  140975. NULL,
  140976. 0
  140977. };
  140978. static long _vq_quantlist__44u2__p7_0[] = {
  140979. 4,
  140980. 3,
  140981. 5,
  140982. 2,
  140983. 6,
  140984. 1,
  140985. 7,
  140986. 0,
  140987. 8,
  140988. };
  140989. static long _vq_lengthlist__44u2__p7_0[] = {
  140990. 1, 3, 2,12,12,12,12,12,12, 4,12,12,12,12,12,12,
  140991. 12,12, 5,12,12,12,12,12,12,12,12,12,12,11,11,11,
  140992. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140993. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140994. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  140995. 11,
  140996. };
  140997. static float _vq_quantthresh__44u2__p7_0[] = {
  140998. -591.5, -422.5, -253.5, -84.5, 84.5, 253.5, 422.5, 591.5,
  140999. };
  141000. static long _vq_quantmap__44u2__p7_0[] = {
  141001. 7, 5, 3, 1, 0, 2, 4, 6,
  141002. 8,
  141003. };
  141004. static encode_aux_threshmatch _vq_auxt__44u2__p7_0 = {
  141005. _vq_quantthresh__44u2__p7_0,
  141006. _vq_quantmap__44u2__p7_0,
  141007. 9,
  141008. 9
  141009. };
  141010. static static_codebook _44u2__p7_0 = {
  141011. 2, 81,
  141012. _vq_lengthlist__44u2__p7_0,
  141013. 1, -516612096, 1626677248, 4, 0,
  141014. _vq_quantlist__44u2__p7_0,
  141015. NULL,
  141016. &_vq_auxt__44u2__p7_0,
  141017. NULL,
  141018. 0
  141019. };
  141020. static long _vq_quantlist__44u2__p7_1[] = {
  141021. 6,
  141022. 5,
  141023. 7,
  141024. 4,
  141025. 8,
  141026. 3,
  141027. 9,
  141028. 2,
  141029. 10,
  141030. 1,
  141031. 11,
  141032. 0,
  141033. 12,
  141034. };
  141035. static long _vq_lengthlist__44u2__p7_1[] = {
  141036. 1, 4, 4, 7, 6, 7, 6, 8, 7, 9, 7, 9, 8, 4, 7, 6,
  141037. 8, 8, 9, 8,10, 9,10,10,11,11, 4, 7, 7, 8, 8, 8,
  141038. 8, 9,10,11,11,11,11, 6, 8, 8,10,10,10,10,11,11,
  141039. 12,12,12,12, 7, 8, 8,10,10,10,10,11,11,12,12,13,
  141040. 13, 7, 9, 9,11,10,12,12,13,13,14,13,14,14, 7, 9,
  141041. 9,10,11,11,12,13,13,13,13,16,14, 9,10,10,12,12,
  141042. 13,13,14,14,15,16,15,16, 9,10,10,12,12,12,13,14,
  141043. 14,14,15,16,15,10,12,12,13,13,15,13,16,16,15,17,
  141044. 17,17,10,11,11,12,14,14,14,15,15,17,17,15,17,11,
  141045. 12,12,14,14,14,15,15,15,17,16,17,17,10,12,12,13,
  141046. 14,14,14,17,15,17,17,17,17,
  141047. };
  141048. static float _vq_quantthresh__44u2__p7_1[] = {
  141049. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  141050. 32.5, 45.5, 58.5, 71.5,
  141051. };
  141052. static long _vq_quantmap__44u2__p7_1[] = {
  141053. 11, 9, 7, 5, 3, 1, 0, 2,
  141054. 4, 6, 8, 10, 12,
  141055. };
  141056. static encode_aux_threshmatch _vq_auxt__44u2__p7_1 = {
  141057. _vq_quantthresh__44u2__p7_1,
  141058. _vq_quantmap__44u2__p7_1,
  141059. 13,
  141060. 13
  141061. };
  141062. static static_codebook _44u2__p7_1 = {
  141063. 2, 169,
  141064. _vq_lengthlist__44u2__p7_1,
  141065. 1, -523010048, 1618608128, 4, 0,
  141066. _vq_quantlist__44u2__p7_1,
  141067. NULL,
  141068. &_vq_auxt__44u2__p7_1,
  141069. NULL,
  141070. 0
  141071. };
  141072. static long _vq_quantlist__44u2__p7_2[] = {
  141073. 6,
  141074. 5,
  141075. 7,
  141076. 4,
  141077. 8,
  141078. 3,
  141079. 9,
  141080. 2,
  141081. 10,
  141082. 1,
  141083. 11,
  141084. 0,
  141085. 12,
  141086. };
  141087. static long _vq_lengthlist__44u2__p7_2[] = {
  141088. 2, 5, 5, 6, 6, 7, 7, 8, 7, 8, 8, 8, 8, 5, 6, 6,
  141089. 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 5, 6, 6, 7, 7, 8,
  141090. 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7, 8, 8, 8, 8, 8,
  141091. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  141092. 9, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 7, 8,
  141093. 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 9,
  141094. 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  141095. 9, 9, 9, 9, 9, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  141096. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8,
  141097. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9, 9,
  141098. 9, 9, 9, 9, 9, 9, 9, 9, 9,
  141099. };
  141100. static float _vq_quantthresh__44u2__p7_2[] = {
  141101. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  141102. 2.5, 3.5, 4.5, 5.5,
  141103. };
  141104. static long _vq_quantmap__44u2__p7_2[] = {
  141105. 11, 9, 7, 5, 3, 1, 0, 2,
  141106. 4, 6, 8, 10, 12,
  141107. };
  141108. static encode_aux_threshmatch _vq_auxt__44u2__p7_2 = {
  141109. _vq_quantthresh__44u2__p7_2,
  141110. _vq_quantmap__44u2__p7_2,
  141111. 13,
  141112. 13
  141113. };
  141114. static static_codebook _44u2__p7_2 = {
  141115. 2, 169,
  141116. _vq_lengthlist__44u2__p7_2,
  141117. 1, -531103744, 1611661312, 4, 0,
  141118. _vq_quantlist__44u2__p7_2,
  141119. NULL,
  141120. &_vq_auxt__44u2__p7_2,
  141121. NULL,
  141122. 0
  141123. };
  141124. static long _huff_lengthlist__44u2__short[] = {
  141125. 13,15,17,17,15,15,12,17,11, 9, 7,10,10, 9,12,17,
  141126. 10, 6, 3, 6, 5, 7,10,17,15,10, 6, 9, 8, 9,11,17,
  141127. 15, 8, 4, 7, 3, 5, 9,16,16,10, 5, 8, 4, 5, 8,16,
  141128. 13,11, 5, 8, 3, 3, 5,14,13,12, 7,10, 5, 5, 7,14,
  141129. };
  141130. static static_codebook _huff_book__44u2__short = {
  141131. 2, 64,
  141132. _huff_lengthlist__44u2__short,
  141133. 0, 0, 0, 0, 0,
  141134. NULL,
  141135. NULL,
  141136. NULL,
  141137. NULL,
  141138. 0
  141139. };
  141140. static long _huff_lengthlist__44u3__long[] = {
  141141. 6, 9,13,12,14,11,10,13, 8, 4, 5, 7, 8, 7, 8,12,
  141142. 11, 4, 3, 5, 5, 7, 9,14,11, 6, 5, 6, 6, 6, 7,13,
  141143. 13, 7, 5, 6, 4, 5, 7,14,11, 7, 6, 6, 5, 5, 6,13,
  141144. 9, 7, 8, 6, 7, 5, 3, 9, 9,12,13,12,14,10, 6, 7,
  141145. };
  141146. static static_codebook _huff_book__44u3__long = {
  141147. 2, 64,
  141148. _huff_lengthlist__44u3__long,
  141149. 0, 0, 0, 0, 0,
  141150. NULL,
  141151. NULL,
  141152. NULL,
  141153. NULL,
  141154. 0
  141155. };
  141156. static long _vq_quantlist__44u3__p1_0[] = {
  141157. 1,
  141158. 0,
  141159. 2,
  141160. };
  141161. static long _vq_lengthlist__44u3__p1_0[] = {
  141162. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  141163. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  141164. 11, 8,11,11, 8,11,11,11,13,14,11,14,14, 8,11,11,
  141165. 10,14,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 7,
  141166. 11,11,11,14,14,10,12,14, 8,11,11,11,14,14,11,14,
  141167. 13,
  141168. };
  141169. static float _vq_quantthresh__44u3__p1_0[] = {
  141170. -0.5, 0.5,
  141171. };
  141172. static long _vq_quantmap__44u3__p1_0[] = {
  141173. 1, 0, 2,
  141174. };
  141175. static encode_aux_threshmatch _vq_auxt__44u3__p1_0 = {
  141176. _vq_quantthresh__44u3__p1_0,
  141177. _vq_quantmap__44u3__p1_0,
  141178. 3,
  141179. 3
  141180. };
  141181. static static_codebook _44u3__p1_0 = {
  141182. 4, 81,
  141183. _vq_lengthlist__44u3__p1_0,
  141184. 1, -535822336, 1611661312, 2, 0,
  141185. _vq_quantlist__44u3__p1_0,
  141186. NULL,
  141187. &_vq_auxt__44u3__p1_0,
  141188. NULL,
  141189. 0
  141190. };
  141191. static long _vq_quantlist__44u3__p2_0[] = {
  141192. 1,
  141193. 0,
  141194. 2,
  141195. };
  141196. static long _vq_lengthlist__44u3__p2_0[] = {
  141197. 2, 5, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  141198. 8, 8, 5, 6, 6, 6, 8, 8, 7, 8, 8, 5, 7, 6, 7, 8,
  141199. 8, 6, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  141200. 8,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  141201. 8, 8, 8,10,10, 8, 8,10, 7, 8, 8, 8,10,10, 8,10,
  141202. 9,
  141203. };
  141204. static float _vq_quantthresh__44u3__p2_0[] = {
  141205. -0.5, 0.5,
  141206. };
  141207. static long _vq_quantmap__44u3__p2_0[] = {
  141208. 1, 0, 2,
  141209. };
  141210. static encode_aux_threshmatch _vq_auxt__44u3__p2_0 = {
  141211. _vq_quantthresh__44u3__p2_0,
  141212. _vq_quantmap__44u3__p2_0,
  141213. 3,
  141214. 3
  141215. };
  141216. static static_codebook _44u3__p2_0 = {
  141217. 4, 81,
  141218. _vq_lengthlist__44u3__p2_0,
  141219. 1, -535822336, 1611661312, 2, 0,
  141220. _vq_quantlist__44u3__p2_0,
  141221. NULL,
  141222. &_vq_auxt__44u3__p2_0,
  141223. NULL,
  141224. 0
  141225. };
  141226. static long _vq_quantlist__44u3__p3_0[] = {
  141227. 2,
  141228. 1,
  141229. 3,
  141230. 0,
  141231. 4,
  141232. };
  141233. static long _vq_lengthlist__44u3__p3_0[] = {
  141234. 2, 4, 4, 7, 7, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  141235. 9, 9,12,12, 8, 9, 9,11,12, 5, 7, 7,10,10, 7, 9,
  141236. 9,11,11, 7, 9, 9,10,11,10,11,11,13,13, 9,10,11,
  141237. 13,13, 5, 7, 7,10,10, 7, 9, 9,11,10, 7, 9, 9,11,
  141238. 11, 9,11,10,13,13,10,11,11,14,13, 8,10,10,14,13,
  141239. 10,11,11,15,14, 9,11,11,14,14,13,14,13,16,16,12,
  141240. 13,13,15,15, 8,10,10,13,14, 9,11,11,14,14,10,11,
  141241. 11,14,15,12,13,13,15,15,13,14,14,15,16, 5, 7, 7,
  141242. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,12,10,11,11,14,
  141243. 14,10,11,11,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  141244. 9,11,11,13,13,12,12,13,15,15,11,12,13,15,16, 7,
  141245. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,13,11,13,
  141246. 12,15,13,11,13,13,15,16, 9,12,11,15,14,11,12,13,
  141247. 16,15,11,13,13,15,16,14,14,15,17,16,13,15,16, 0,
  141248. 17, 9,11,11,15,15,10,13,12,15,15,11,13,13,15,16,
  141249. 13,15,13,16,15,14,16,15, 0,19, 5, 7, 7,10,10, 7,
  141250. 9, 9,11,11, 7, 9, 9,11,11,10,12,11,14,14,10,11,
  141251. 12,14,14, 7, 9, 9,12,12, 9,11,11,14,13, 9,10,11,
  141252. 12,13,11,13,13,16,16,11,12,13,13,16, 7, 9, 9,12,
  141253. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,15,15,
  141254. 12,13,12,15,14, 9,11,11,15,14,11,13,12,16,16,10,
  141255. 12,12,15,15,13,15,15,17,19,13,14,15,16,17,10,12,
  141256. 12,15,15,11,13,13,16,16,11,13,13,15,16,13,15,15,
  141257. 0, 0,14,15,15,16,16, 8,10,10,14,14,10,12,12,15,
  141258. 15,10,12,11,15,16,14,15,15,19,20,13,14,14,18,16,
  141259. 9,11,11,15,15,11,13,13,17,16,11,13,13,16,16,15,
  141260. 17,17,20,20,14,15,16,17,20, 9,11,11,15,15,10,13,
  141261. 12,16,15,11,13,13,15,17,14,16,15,18, 0,14,16,15,
  141262. 18,20,12,14,14, 0, 0,14,14,16, 0, 0,13,16,15, 0,
  141263. 0,17,17,18, 0, 0,16,17,19,19, 0,12,14,14,18, 0,
  141264. 12,16,14, 0,17,13,15,15,18, 0,16,18,17, 0,17,16,
  141265. 18,17, 0, 0, 7,10,10,14,14,10,12,11,15,15,10,12,
  141266. 12,16,15,13,15,15,18, 0,14,15,15,17, 0, 9,11,11,
  141267. 15,15,11,13,13,16,16,11,12,13,16,16,14,15,16,17,
  141268. 17,14,16,16,16,18, 9,11,12,16,16,11,13,13,17,17,
  141269. 11,14,13,20,17,15,16,16,19, 0,15,16,17, 0,19,11,
  141270. 13,14,17,16,14,15,15,20,18,13,14,15,17,19,16,18,
  141271. 18, 0,20,16,16,19,17, 0,12,15,14,17, 0,14,15,15,
  141272. 18,19,13,16,15,19,20,15,18,18, 0,20,17, 0,16, 0,
  141273. 0,
  141274. };
  141275. static float _vq_quantthresh__44u3__p3_0[] = {
  141276. -1.5, -0.5, 0.5, 1.5,
  141277. };
  141278. static long _vq_quantmap__44u3__p3_0[] = {
  141279. 3, 1, 0, 2, 4,
  141280. };
  141281. static encode_aux_threshmatch _vq_auxt__44u3__p3_0 = {
  141282. _vq_quantthresh__44u3__p3_0,
  141283. _vq_quantmap__44u3__p3_0,
  141284. 5,
  141285. 5
  141286. };
  141287. static static_codebook _44u3__p3_0 = {
  141288. 4, 625,
  141289. _vq_lengthlist__44u3__p3_0,
  141290. 1, -533725184, 1611661312, 3, 0,
  141291. _vq_quantlist__44u3__p3_0,
  141292. NULL,
  141293. &_vq_auxt__44u3__p3_0,
  141294. NULL,
  141295. 0
  141296. };
  141297. static long _vq_quantlist__44u3__p4_0[] = {
  141298. 2,
  141299. 1,
  141300. 3,
  141301. 0,
  141302. 4,
  141303. };
  141304. static long _vq_lengthlist__44u3__p4_0[] = {
  141305. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  141306. 9, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  141307. 8,10,10, 7, 7, 8,10,10, 9,10,10,11,12, 9,10,10,
  141308. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  141309. 10, 9,10, 9,12,11, 9,10,10,12,11, 9,10, 9,12,12,
  141310. 9,10,10,13,12, 9,10,10,12,13,12,12,12,14,14,11,
  141311. 12,12,13,14, 9, 9,10,12,12, 9,10,10,12,12, 9,10,
  141312. 10,12,13,11,12,11,14,13,12,12,12,14,13, 5, 7, 7,
  141313. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  141314. 12, 9,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  141315. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,13,13, 6,
  141316. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  141317. 10,13,11,10,11,11,13,13, 9,11,10,13,12,10,11,11,
  141318. 13,13,10,11,11,13,13,12,12,13,12,15,12,13,13,15,
  141319. 15, 9,10,10,12,13,10,11,10,13,12,10,11,11,13,14,
  141320. 12,13,11,15,13,12,13,13,15,15, 5, 7, 7, 9, 9, 7,
  141321. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12,10,10,
  141322. 11,12,12, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  141323. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  141324. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,13,
  141325. 11,11,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  141326. 10,11,12,13,12,13,13,15,15,12,11,13,13,14, 9,10,
  141327. 11,12,13,10,11,11,13,13,10,11,11,13,13,12,13,13,
  141328. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  141329. 13, 9,10,10,13,13,12,13,13,15,14,12,12,12,14,13,
  141330. 9,10,10,13,12,10,11,11,13,13,10,11,11,14,12,13,
  141331. 13,14,14,16,12,13,13,15,15, 9,10,10,13,13,10,11,
  141332. 10,14,13,10,11,11,13,14,12,14,13,15,14,13,13,13,
  141333. 15,15,11,13,12,15,14,11,12,13,14,15,12,13,13,16,
  141334. 14,14,12,15,12,16,14,15,15,17,15,11,12,12,14,14,
  141335. 11,13,11,15,14,12,13,13,15,15,13,15,12,17,13,14,
  141336. 15,15,16,16, 8, 9, 9,12,12, 9,10,10,12,13, 9,10,
  141337. 10,13,13,12,12,12,14,14,12,13,13,15,15, 9,10,10,
  141338. 13,12,10,11,11,14,13,10,10,11,13,14,12,13,13,15,
  141339. 15,12,12,13,14,16, 9,10,10,13,13,10,11,11,13,14,
  141340. 10,11,11,14,13,12,13,13,14,15,13,14,13,16,14,11,
  141341. 12,12,14,14,12,13,13,15,14,11,12,13,14,15,14,15,
  141342. 15,16,16,13,13,15,13,16,11,12,12,14,15,12,13,13,
  141343. 14,15,11,13,12,15,14,14,15,15,16,16,14,15,12,16,
  141344. 13,
  141345. };
  141346. static float _vq_quantthresh__44u3__p4_0[] = {
  141347. -1.5, -0.5, 0.5, 1.5,
  141348. };
  141349. static long _vq_quantmap__44u3__p4_0[] = {
  141350. 3, 1, 0, 2, 4,
  141351. };
  141352. static encode_aux_threshmatch _vq_auxt__44u3__p4_0 = {
  141353. _vq_quantthresh__44u3__p4_0,
  141354. _vq_quantmap__44u3__p4_0,
  141355. 5,
  141356. 5
  141357. };
  141358. static static_codebook _44u3__p4_0 = {
  141359. 4, 625,
  141360. _vq_lengthlist__44u3__p4_0,
  141361. 1, -533725184, 1611661312, 3, 0,
  141362. _vq_quantlist__44u3__p4_0,
  141363. NULL,
  141364. &_vq_auxt__44u3__p4_0,
  141365. NULL,
  141366. 0
  141367. };
  141368. static long _vq_quantlist__44u3__p5_0[] = {
  141369. 4,
  141370. 3,
  141371. 5,
  141372. 2,
  141373. 6,
  141374. 1,
  141375. 7,
  141376. 0,
  141377. 8,
  141378. };
  141379. static long _vq_lengthlist__44u3__p5_0[] = {
  141380. 2, 3, 3, 6, 6, 7, 7, 9, 9, 4, 5, 5, 7, 7, 8, 8,
  141381. 10,10, 4, 5, 5, 7, 7, 8, 8,10,10, 6, 7, 7, 8, 8,
  141382. 9, 9,11,10, 6, 7, 7, 8, 8, 9, 9,10,10, 7, 8, 8,
  141383. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  141384. 10,10,11,10,11,11,12,12, 9,10,10,10,10,11,11,12,
  141385. 12,
  141386. };
  141387. static float _vq_quantthresh__44u3__p5_0[] = {
  141388. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  141389. };
  141390. static long _vq_quantmap__44u3__p5_0[] = {
  141391. 7, 5, 3, 1, 0, 2, 4, 6,
  141392. 8,
  141393. };
  141394. static encode_aux_threshmatch _vq_auxt__44u3__p5_0 = {
  141395. _vq_quantthresh__44u3__p5_0,
  141396. _vq_quantmap__44u3__p5_0,
  141397. 9,
  141398. 9
  141399. };
  141400. static static_codebook _44u3__p5_0 = {
  141401. 2, 81,
  141402. _vq_lengthlist__44u3__p5_0,
  141403. 1, -531628032, 1611661312, 4, 0,
  141404. _vq_quantlist__44u3__p5_0,
  141405. NULL,
  141406. &_vq_auxt__44u3__p5_0,
  141407. NULL,
  141408. 0
  141409. };
  141410. static long _vq_quantlist__44u3__p6_0[] = {
  141411. 6,
  141412. 5,
  141413. 7,
  141414. 4,
  141415. 8,
  141416. 3,
  141417. 9,
  141418. 2,
  141419. 10,
  141420. 1,
  141421. 11,
  141422. 0,
  141423. 12,
  141424. };
  141425. static long _vq_lengthlist__44u3__p6_0[] = {
  141426. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,11,13,14, 4, 6, 5,
  141427. 8, 8, 9, 9,10,10,11,11,14,14, 4, 6, 6, 8, 8, 9,
  141428. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  141429. 12,12,15,15, 6, 8, 8, 9, 9,10,11,11,11,12,12,15,
  141430. 15, 8, 9, 9,11,10,11,11,12,12,13,13,15,16, 8, 9,
  141431. 9,10,11,11,11,12,12,13,13,16,16,10,10,11,11,11,
  141432. 12,12,13,13,13,14,17,16, 9,10,11,12,11,12,12,13,
  141433. 13,13,13,16,18,11,12,11,12,12,13,13,13,14,15,14,
  141434. 17,17,11,11,12,12,12,13,13,13,14,14,15,18,17,14,
  141435. 15,15,15,15,16,16,17,17,19,18, 0,20,14,15,14,15,
  141436. 15,16,16,16,17,18,16,20,18,
  141437. };
  141438. static float _vq_quantthresh__44u3__p6_0[] = {
  141439. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  141440. 12.5, 17.5, 22.5, 27.5,
  141441. };
  141442. static long _vq_quantmap__44u3__p6_0[] = {
  141443. 11, 9, 7, 5, 3, 1, 0, 2,
  141444. 4, 6, 8, 10, 12,
  141445. };
  141446. static encode_aux_threshmatch _vq_auxt__44u3__p6_0 = {
  141447. _vq_quantthresh__44u3__p6_0,
  141448. _vq_quantmap__44u3__p6_0,
  141449. 13,
  141450. 13
  141451. };
  141452. static static_codebook _44u3__p6_0 = {
  141453. 2, 169,
  141454. _vq_lengthlist__44u3__p6_0,
  141455. 1, -526516224, 1616117760, 4, 0,
  141456. _vq_quantlist__44u3__p6_0,
  141457. NULL,
  141458. &_vq_auxt__44u3__p6_0,
  141459. NULL,
  141460. 0
  141461. };
  141462. static long _vq_quantlist__44u3__p6_1[] = {
  141463. 2,
  141464. 1,
  141465. 3,
  141466. 0,
  141467. 4,
  141468. };
  141469. static long _vq_lengthlist__44u3__p6_1[] = {
  141470. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  141471. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  141472. };
  141473. static float _vq_quantthresh__44u3__p6_1[] = {
  141474. -1.5, -0.5, 0.5, 1.5,
  141475. };
  141476. static long _vq_quantmap__44u3__p6_1[] = {
  141477. 3, 1, 0, 2, 4,
  141478. };
  141479. static encode_aux_threshmatch _vq_auxt__44u3__p6_1 = {
  141480. _vq_quantthresh__44u3__p6_1,
  141481. _vq_quantmap__44u3__p6_1,
  141482. 5,
  141483. 5
  141484. };
  141485. static static_codebook _44u3__p6_1 = {
  141486. 2, 25,
  141487. _vq_lengthlist__44u3__p6_1,
  141488. 1, -533725184, 1611661312, 3, 0,
  141489. _vq_quantlist__44u3__p6_1,
  141490. NULL,
  141491. &_vq_auxt__44u3__p6_1,
  141492. NULL,
  141493. 0
  141494. };
  141495. static long _vq_quantlist__44u3__p7_0[] = {
  141496. 4,
  141497. 3,
  141498. 5,
  141499. 2,
  141500. 6,
  141501. 1,
  141502. 7,
  141503. 0,
  141504. 8,
  141505. };
  141506. static long _vq_lengthlist__44u3__p7_0[] = {
  141507. 1, 3, 3,10,10,10,10,10,10, 4,10,10,10,10,10,10,
  141508. 10,10, 4,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  141509. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  141510. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  141511. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  141512. 9,
  141513. };
  141514. static float _vq_quantthresh__44u3__p7_0[] = {
  141515. -892.5, -637.5, -382.5, -127.5, 127.5, 382.5, 637.5, 892.5,
  141516. };
  141517. static long _vq_quantmap__44u3__p7_0[] = {
  141518. 7, 5, 3, 1, 0, 2, 4, 6,
  141519. 8,
  141520. };
  141521. static encode_aux_threshmatch _vq_auxt__44u3__p7_0 = {
  141522. _vq_quantthresh__44u3__p7_0,
  141523. _vq_quantmap__44u3__p7_0,
  141524. 9,
  141525. 9
  141526. };
  141527. static static_codebook _44u3__p7_0 = {
  141528. 2, 81,
  141529. _vq_lengthlist__44u3__p7_0,
  141530. 1, -515907584, 1627381760, 4, 0,
  141531. _vq_quantlist__44u3__p7_0,
  141532. NULL,
  141533. &_vq_auxt__44u3__p7_0,
  141534. NULL,
  141535. 0
  141536. };
  141537. static long _vq_quantlist__44u3__p7_1[] = {
  141538. 7,
  141539. 6,
  141540. 8,
  141541. 5,
  141542. 9,
  141543. 4,
  141544. 10,
  141545. 3,
  141546. 11,
  141547. 2,
  141548. 12,
  141549. 1,
  141550. 13,
  141551. 0,
  141552. 14,
  141553. };
  141554. static long _vq_lengthlist__44u3__p7_1[] = {
  141555. 1, 4, 4, 6, 6, 7, 6, 8, 7, 9, 8,10, 9,11,11, 4,
  141556. 7, 7, 8, 7, 9, 9,10,10,11,11,11,11,12,12, 4, 7,
  141557. 7, 7, 7, 9, 9,10,10,11,11,12,12,12,11, 6, 8, 8,
  141558. 9, 9,10,10,11,11,12,12,13,12,13,13, 6, 8, 8, 9,
  141559. 9,10,11,11,11,12,12,13,14,13,13, 8, 9, 9,11,11,
  141560. 12,12,12,13,14,13,14,14,14,15, 8, 9, 9,11,11,11,
  141561. 12,13,14,13,14,15,17,14,15, 9,10,10,12,12,13,13,
  141562. 13,14,15,15,15,16,16,16, 9,11,11,12,12,13,13,14,
  141563. 14,14,15,16,16,16,16,10,12,12,13,13,14,14,15,15,
  141564. 15,16,17,17,17,17,10,12,11,13,13,15,14,15,14,16,
  141565. 17,16,16,16,16,11,13,12,14,14,14,14,15,16,17,16,
  141566. 17,17,17,17,11,13,12,14,14,14,15,17,16,17,17,17,
  141567. 17,17,17,12,13,13,15,16,15,16,17,17,16,16,17,17,
  141568. 17,17,12,13,13,15,15,15,16,17,17,17,16,17,16,17,
  141569. 17,
  141570. };
  141571. static float _vq_quantthresh__44u3__p7_1[] = {
  141572. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  141573. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  141574. };
  141575. static long _vq_quantmap__44u3__p7_1[] = {
  141576. 13, 11, 9, 7, 5, 3, 1, 0,
  141577. 2, 4, 6, 8, 10, 12, 14,
  141578. };
  141579. static encode_aux_threshmatch _vq_auxt__44u3__p7_1 = {
  141580. _vq_quantthresh__44u3__p7_1,
  141581. _vq_quantmap__44u3__p7_1,
  141582. 15,
  141583. 15
  141584. };
  141585. static static_codebook _44u3__p7_1 = {
  141586. 2, 225,
  141587. _vq_lengthlist__44u3__p7_1,
  141588. 1, -522338304, 1620115456, 4, 0,
  141589. _vq_quantlist__44u3__p7_1,
  141590. NULL,
  141591. &_vq_auxt__44u3__p7_1,
  141592. NULL,
  141593. 0
  141594. };
  141595. static long _vq_quantlist__44u3__p7_2[] = {
  141596. 8,
  141597. 7,
  141598. 9,
  141599. 6,
  141600. 10,
  141601. 5,
  141602. 11,
  141603. 4,
  141604. 12,
  141605. 3,
  141606. 13,
  141607. 2,
  141608. 14,
  141609. 1,
  141610. 15,
  141611. 0,
  141612. 16,
  141613. };
  141614. static long _vq_lengthlist__44u3__p7_2[] = {
  141615. 2, 5, 5, 7, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  141616. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  141617. 10,10, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9,
  141618. 9,10, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  141619. 10,10,10,10, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  141620. 9,10,10,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  141621. 10,10,10,10,10,10, 7, 8, 8, 9, 8, 9, 9, 9, 9,10,
  141622. 9,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  141623. 9,10,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9,10,
  141624. 9,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,
  141625. 9,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  141626. 9,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10, 9,
  141627. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10,
  141628. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  141629. 10,10,10,10,10,10,10,10,10,10,10,10,10,11, 9,10,
  141630. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,11, 9,
  141631. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  141632. 9,10,10,10,10,10,10,10,10,10,10,10,11,11,11,10,
  141633. 11,
  141634. };
  141635. static float _vq_quantthresh__44u3__p7_2[] = {
  141636. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  141637. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  141638. };
  141639. static long _vq_quantmap__44u3__p7_2[] = {
  141640. 15, 13, 11, 9, 7, 5, 3, 1,
  141641. 0, 2, 4, 6, 8, 10, 12, 14,
  141642. 16,
  141643. };
  141644. static encode_aux_threshmatch _vq_auxt__44u3__p7_2 = {
  141645. _vq_quantthresh__44u3__p7_2,
  141646. _vq_quantmap__44u3__p7_2,
  141647. 17,
  141648. 17
  141649. };
  141650. static static_codebook _44u3__p7_2 = {
  141651. 2, 289,
  141652. _vq_lengthlist__44u3__p7_2,
  141653. 1, -529530880, 1611661312, 5, 0,
  141654. _vq_quantlist__44u3__p7_2,
  141655. NULL,
  141656. &_vq_auxt__44u3__p7_2,
  141657. NULL,
  141658. 0
  141659. };
  141660. static long _huff_lengthlist__44u3__short[] = {
  141661. 14,14,14,15,13,15,12,16,10, 8, 7, 9, 9, 8,12,16,
  141662. 10, 5, 4, 6, 5, 6, 9,16,14, 8, 6, 8, 7, 8,10,16,
  141663. 14, 7, 4, 6, 3, 5, 8,16,15, 9, 5, 7, 4, 4, 7,16,
  141664. 13,10, 6, 7, 4, 3, 4,13,13,12, 7, 9, 5, 5, 6,12,
  141665. };
  141666. static static_codebook _huff_book__44u3__short = {
  141667. 2, 64,
  141668. _huff_lengthlist__44u3__short,
  141669. 0, 0, 0, 0, 0,
  141670. NULL,
  141671. NULL,
  141672. NULL,
  141673. NULL,
  141674. 0
  141675. };
  141676. static long _huff_lengthlist__44u4__long[] = {
  141677. 3, 8,12,12,13,12,11,13, 5, 4, 6, 7, 8, 8, 9,13,
  141678. 9, 5, 4, 5, 5, 7, 9,13, 9, 6, 5, 6, 6, 7, 8,12,
  141679. 12, 7, 5, 6, 4, 5, 8,13,11, 7, 6, 6, 5, 5, 6,12,
  141680. 10, 8, 8, 7, 7, 5, 3, 8,10,12,13,12,12, 9, 6, 7,
  141681. };
  141682. static static_codebook _huff_book__44u4__long = {
  141683. 2, 64,
  141684. _huff_lengthlist__44u4__long,
  141685. 0, 0, 0, 0, 0,
  141686. NULL,
  141687. NULL,
  141688. NULL,
  141689. NULL,
  141690. 0
  141691. };
  141692. static long _vq_quantlist__44u4__p1_0[] = {
  141693. 1,
  141694. 0,
  141695. 2,
  141696. };
  141697. static long _vq_lengthlist__44u4__p1_0[] = {
  141698. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  141699. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  141700. 11, 8,11,11, 8,11,11,11,13,14,11,15,14, 8,11,11,
  141701. 10,13,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 7,
  141702. 11,11,11,15,14,10,12,14, 8,11,11,11,14,14,11,14,
  141703. 13,
  141704. };
  141705. static float _vq_quantthresh__44u4__p1_0[] = {
  141706. -0.5, 0.5,
  141707. };
  141708. static long _vq_quantmap__44u4__p1_0[] = {
  141709. 1, 0, 2,
  141710. };
  141711. static encode_aux_threshmatch _vq_auxt__44u4__p1_0 = {
  141712. _vq_quantthresh__44u4__p1_0,
  141713. _vq_quantmap__44u4__p1_0,
  141714. 3,
  141715. 3
  141716. };
  141717. static static_codebook _44u4__p1_0 = {
  141718. 4, 81,
  141719. _vq_lengthlist__44u4__p1_0,
  141720. 1, -535822336, 1611661312, 2, 0,
  141721. _vq_quantlist__44u4__p1_0,
  141722. NULL,
  141723. &_vq_auxt__44u4__p1_0,
  141724. NULL,
  141725. 0
  141726. };
  141727. static long _vq_quantlist__44u4__p2_0[] = {
  141728. 1,
  141729. 0,
  141730. 2,
  141731. };
  141732. static long _vq_lengthlist__44u4__p2_0[] = {
  141733. 2, 5, 5, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  141734. 8, 8, 5, 6, 6, 6, 8, 8, 7, 8, 8, 5, 7, 6, 6, 8,
  141735. 8, 6, 8, 8, 6, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  141736. 8,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 6, 8, 8, 6,
  141737. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  141738. 9,
  141739. };
  141740. static float _vq_quantthresh__44u4__p2_0[] = {
  141741. -0.5, 0.5,
  141742. };
  141743. static long _vq_quantmap__44u4__p2_0[] = {
  141744. 1, 0, 2,
  141745. };
  141746. static encode_aux_threshmatch _vq_auxt__44u4__p2_0 = {
  141747. _vq_quantthresh__44u4__p2_0,
  141748. _vq_quantmap__44u4__p2_0,
  141749. 3,
  141750. 3
  141751. };
  141752. static static_codebook _44u4__p2_0 = {
  141753. 4, 81,
  141754. _vq_lengthlist__44u4__p2_0,
  141755. 1, -535822336, 1611661312, 2, 0,
  141756. _vq_quantlist__44u4__p2_0,
  141757. NULL,
  141758. &_vq_auxt__44u4__p2_0,
  141759. NULL,
  141760. 0
  141761. };
  141762. static long _vq_quantlist__44u4__p3_0[] = {
  141763. 2,
  141764. 1,
  141765. 3,
  141766. 0,
  141767. 4,
  141768. };
  141769. static long _vq_lengthlist__44u4__p3_0[] = {
  141770. 2, 4, 4, 8, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  141771. 10, 9,12,12, 8, 9,10,12,12, 5, 7, 7,10,10, 7, 9,
  141772. 9,11,11, 7, 9, 9,11,11,10,12,11,14,14, 9,10,11,
  141773. 13,14, 5, 7, 7,10,10, 7, 9, 9,11,11, 7, 9, 9,11,
  141774. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,14,13,
  141775. 10,12,12,15,14, 9,11,11,15,14,13,14,14,17,17,12,
  141776. 14,14,16,16, 8,10,10,14,14, 9,11,11,14,15,10,12,
  141777. 12,14,15,12,14,13,16,16,13,14,15,15,18, 4, 7, 7,
  141778. 10,10, 7, 9, 9,12,11, 7, 9, 9,11,12,10,12,11,15,
  141779. 14,10,11,12,14,15, 7, 9, 9,12,12, 9,11,12,13,13,
  141780. 9,11,12,13,13,12,13,13,15,16,11,13,13,15,16, 7,
  141781. 9, 9,12,12, 9,11,10,13,12, 9,11,12,13,14,11,13,
  141782. 12,16,14,12,13,13,15,16,10,12,12,16,15,11,13,13,
  141783. 17,16,11,13,13,17,16,14,15,15,17,17,14,16,16,18,
  141784. 20, 9,11,11,15,16,11,13,12,16,16,11,13,13,16,17,
  141785. 14,15,14,18,16,14,16,16,17,20, 5, 7, 7,10,10, 7,
  141786. 9, 9,12,11, 7, 9,10,11,12,10,12,11,15,15,10,12,
  141787. 12,14,14, 7, 9, 9,12,12, 9,12,11,14,13, 9,10,11,
  141788. 12,13,12,13,14,16,16,11,12,13,14,16, 7, 9, 9,12,
  141789. 12, 9,12,11,13,13, 9,12,11,13,13,11,13,13,16,16,
  141790. 12,13,13,16,15, 9,11,11,16,14,11,13,13,16,16,11,
  141791. 12,13,16,16,14,16,16,17,17,13,14,15,16,17,10,12,
  141792. 12,15,15,11,13,13,16,17,11,13,13,16,16,14,16,15,
  141793. 19,19,14,15,15,17,18, 8,10,10,14,14,10,12,12,15,
  141794. 15,10,12,12,16,16,14,16,15,20,19,13,15,15,17,16,
  141795. 9,12,12,16,16,11,13,13,16,18,11,14,13,16,17,16,
  141796. 17,16,20, 0,15,16,18,18,20, 9,11,11,15,15,11,14,
  141797. 12,17,16,11,13,13,17,17,15,17,15,20,20,14,16,16,
  141798. 17, 0,13,15,14,18,16,14,15,16, 0,18,14,16,16, 0,
  141799. 0,18,16, 0, 0,20,16,18,18, 0, 0,12,14,14,17,18,
  141800. 13,15,14,20,18,14,16,15,19,19,16,20,16, 0,18,16,
  141801. 19,17,19, 0, 8,10,10,14,14,10,12,12,16,15,10,12,
  141802. 12,16,16,13,15,15,18,17,14,16,16,19, 0, 9,11,11,
  141803. 16,15,11,14,13,18,17,11,12,13,17,18,14,17,16,18,
  141804. 18,15,16,17,18,18, 9,12,12,16,16,11,13,13,16,18,
  141805. 11,14,13,17,17,15,16,16,18,20,16,17,17,20,20,12,
  141806. 14,14,18,17,14,16,16, 0,19,13,14,15,18, 0,16, 0,
  141807. 0, 0, 0,16,16, 0,19,20,13,15,14, 0, 0,14,16,16,
  141808. 18,19,14,16,15, 0,20,16,20,18, 0,20,17,20,17, 0,
  141809. 0,
  141810. };
  141811. static float _vq_quantthresh__44u4__p3_0[] = {
  141812. -1.5, -0.5, 0.5, 1.5,
  141813. };
  141814. static long _vq_quantmap__44u4__p3_0[] = {
  141815. 3, 1, 0, 2, 4,
  141816. };
  141817. static encode_aux_threshmatch _vq_auxt__44u4__p3_0 = {
  141818. _vq_quantthresh__44u4__p3_0,
  141819. _vq_quantmap__44u4__p3_0,
  141820. 5,
  141821. 5
  141822. };
  141823. static static_codebook _44u4__p3_0 = {
  141824. 4, 625,
  141825. _vq_lengthlist__44u4__p3_0,
  141826. 1, -533725184, 1611661312, 3, 0,
  141827. _vq_quantlist__44u4__p3_0,
  141828. NULL,
  141829. &_vq_auxt__44u4__p3_0,
  141830. NULL,
  141831. 0
  141832. };
  141833. static long _vq_quantlist__44u4__p4_0[] = {
  141834. 2,
  141835. 1,
  141836. 3,
  141837. 0,
  141838. 4,
  141839. };
  141840. static long _vq_lengthlist__44u4__p4_0[] = {
  141841. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  141842. 9, 9,11,11, 8, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  141843. 8,10,10, 7, 7, 8,10,10, 9,10,10,11,12, 9,10,10,
  141844. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  141845. 10, 9,10,10,12,11, 9,10,10,12,11, 9,10, 9,12,12,
  141846. 9,10,10,13,12, 9,10,10,12,12,12,12,12,14,14,11,
  141847. 12,12,13,14, 9, 9,10,12,12, 9,10,10,13,13, 9,10,
  141848. 10,12,13,11,12,12,14,13,11,12,12,14,14, 5, 7, 7,
  141849. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  141850. 12, 9,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  141851. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,13,13, 6,
  141852. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  141853. 10,13,11,10,11,11,13,13, 9,11,10,13,12,10,11,11,
  141854. 13,14,10,11,11,14,13,12,12,13,12,15,12,13,13,15,
  141855. 15, 9,10,10,12,13,10,11,10,13,12,10,11,11,13,14,
  141856. 12,13,11,15,13,13,13,13,15,15, 5, 7, 7, 9, 9, 7,
  141857. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12,10,10,
  141858. 11,12,13, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  141859. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  141860. 11, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,11,13,13,
  141861. 11,12,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  141862. 10,11,12,13,12,13,13,15,15,12,11,13,13,14, 9,10,
  141863. 11,12,13,10,11,11,13,14,10,11,11,13,13,12,13,13,
  141864. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  141865. 13, 9,10,10,13,13,12,13,13,15,15,12,12,12,14,14,
  141866. 9,10,10,13,13,10,11,11,13,14,10,11,11,14,13,13,
  141867. 13,14,14,16,13,13,13,15,15, 9,10,10,13,13,10,11,
  141868. 10,14,13,10,11,11,13,14,12,14,13,16,14,12,13,13,
  141869. 14,15,11,12,12,15,14,11,12,13,14,15,12,13,13,16,
  141870. 15,14,12,15,12,16,14,15,15,16,16,11,12,12,14,14,
  141871. 11,13,12,15,14,12,13,13,15,16,13,15,13,17,13,14,
  141872. 15,15,16,17, 8, 9, 9,12,12, 9,10,10,12,13, 9,10,
  141873. 10,13,13,12,12,12,14,14,12,13,13,15,15, 9,10,10,
  141874. 13,12,10,11,11,14,13,10,10,11,13,14,13,13,13,15,
  141875. 15,12,13,14,14,16, 9,10,10,13,13,10,11,11,13,14,
  141876. 10,11,11,14,14,13,13,13,15,15,13,14,13,16,14,11,
  141877. 12,12,15,14,12,13,13,16,15,11,12,13,14,15,14,15,
  141878. 15,17,16,13,13,15,13,16,11,12,13,14,15,13,13,13,
  141879. 15,16,11,13,12,15,14,14,15,15,16,16,14,15,12,17,
  141880. 13,
  141881. };
  141882. static float _vq_quantthresh__44u4__p4_0[] = {
  141883. -1.5, -0.5, 0.5, 1.5,
  141884. };
  141885. static long _vq_quantmap__44u4__p4_0[] = {
  141886. 3, 1, 0, 2, 4,
  141887. };
  141888. static encode_aux_threshmatch _vq_auxt__44u4__p4_0 = {
  141889. _vq_quantthresh__44u4__p4_0,
  141890. _vq_quantmap__44u4__p4_0,
  141891. 5,
  141892. 5
  141893. };
  141894. static static_codebook _44u4__p4_0 = {
  141895. 4, 625,
  141896. _vq_lengthlist__44u4__p4_0,
  141897. 1, -533725184, 1611661312, 3, 0,
  141898. _vq_quantlist__44u4__p4_0,
  141899. NULL,
  141900. &_vq_auxt__44u4__p4_0,
  141901. NULL,
  141902. 0
  141903. };
  141904. static long _vq_quantlist__44u4__p5_0[] = {
  141905. 4,
  141906. 3,
  141907. 5,
  141908. 2,
  141909. 6,
  141910. 1,
  141911. 7,
  141912. 0,
  141913. 8,
  141914. };
  141915. static long _vq_lengthlist__44u4__p5_0[] = {
  141916. 2, 3, 3, 6, 6, 7, 7, 9, 9, 4, 5, 5, 7, 7, 8, 8,
  141917. 10, 9, 4, 5, 5, 7, 7, 8, 8,10,10, 6, 7, 7, 8, 8,
  141918. 9, 9,11,10, 6, 7, 7, 8, 8, 9, 9,10,11, 7, 8, 8,
  141919. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  141920. 10,10,11,10,11,11,12,12, 9,10,10,10,11,11,11,12,
  141921. 12,
  141922. };
  141923. static float _vq_quantthresh__44u4__p5_0[] = {
  141924. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  141925. };
  141926. static long _vq_quantmap__44u4__p5_0[] = {
  141927. 7, 5, 3, 1, 0, 2, 4, 6,
  141928. 8,
  141929. };
  141930. static encode_aux_threshmatch _vq_auxt__44u4__p5_0 = {
  141931. _vq_quantthresh__44u4__p5_0,
  141932. _vq_quantmap__44u4__p5_0,
  141933. 9,
  141934. 9
  141935. };
  141936. static static_codebook _44u4__p5_0 = {
  141937. 2, 81,
  141938. _vq_lengthlist__44u4__p5_0,
  141939. 1, -531628032, 1611661312, 4, 0,
  141940. _vq_quantlist__44u4__p5_0,
  141941. NULL,
  141942. &_vq_auxt__44u4__p5_0,
  141943. NULL,
  141944. 0
  141945. };
  141946. static long _vq_quantlist__44u4__p6_0[] = {
  141947. 6,
  141948. 5,
  141949. 7,
  141950. 4,
  141951. 8,
  141952. 3,
  141953. 9,
  141954. 2,
  141955. 10,
  141956. 1,
  141957. 11,
  141958. 0,
  141959. 12,
  141960. };
  141961. static long _vq_lengthlist__44u4__p6_0[] = {
  141962. 1, 4, 4, 6, 6, 8, 8, 9, 9,11,10,13,13, 4, 6, 5,
  141963. 8, 8, 9, 9,10,10,11,11,14,14, 4, 6, 6, 8, 8, 9,
  141964. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  141965. 12,12,15,15, 6, 8, 8, 9, 9,10,11,11,11,12,12,15,
  141966. 15, 8, 9, 9,11,10,11,11,12,12,13,13,16,16, 8, 9,
  141967. 9,10,10,11,11,12,12,13,13,16,16,10,10,10,12,11,
  141968. 12,12,13,13,14,14,16,16,10,10,10,11,12,12,12,13,
  141969. 13,13,14,16,17,11,12,11,12,12,13,13,14,14,15,14,
  141970. 18,17,11,11,12,12,12,13,13,14,14,14,15,19,18,14,
  141971. 15,14,15,15,17,16,17,17,17,17,21, 0,14,15,15,16,
  141972. 16,16,16,17,17,18,17,20,21,
  141973. };
  141974. static float _vq_quantthresh__44u4__p6_0[] = {
  141975. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  141976. 12.5, 17.5, 22.5, 27.5,
  141977. };
  141978. static long _vq_quantmap__44u4__p6_0[] = {
  141979. 11, 9, 7, 5, 3, 1, 0, 2,
  141980. 4, 6, 8, 10, 12,
  141981. };
  141982. static encode_aux_threshmatch _vq_auxt__44u4__p6_0 = {
  141983. _vq_quantthresh__44u4__p6_0,
  141984. _vq_quantmap__44u4__p6_0,
  141985. 13,
  141986. 13
  141987. };
  141988. static static_codebook _44u4__p6_0 = {
  141989. 2, 169,
  141990. _vq_lengthlist__44u4__p6_0,
  141991. 1, -526516224, 1616117760, 4, 0,
  141992. _vq_quantlist__44u4__p6_0,
  141993. NULL,
  141994. &_vq_auxt__44u4__p6_0,
  141995. NULL,
  141996. 0
  141997. };
  141998. static long _vq_quantlist__44u4__p6_1[] = {
  141999. 2,
  142000. 1,
  142001. 3,
  142002. 0,
  142003. 4,
  142004. };
  142005. static long _vq_lengthlist__44u4__p6_1[] = {
  142006. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  142007. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  142008. };
  142009. static float _vq_quantthresh__44u4__p6_1[] = {
  142010. -1.5, -0.5, 0.5, 1.5,
  142011. };
  142012. static long _vq_quantmap__44u4__p6_1[] = {
  142013. 3, 1, 0, 2, 4,
  142014. };
  142015. static encode_aux_threshmatch _vq_auxt__44u4__p6_1 = {
  142016. _vq_quantthresh__44u4__p6_1,
  142017. _vq_quantmap__44u4__p6_1,
  142018. 5,
  142019. 5
  142020. };
  142021. static static_codebook _44u4__p6_1 = {
  142022. 2, 25,
  142023. _vq_lengthlist__44u4__p6_1,
  142024. 1, -533725184, 1611661312, 3, 0,
  142025. _vq_quantlist__44u4__p6_1,
  142026. NULL,
  142027. &_vq_auxt__44u4__p6_1,
  142028. NULL,
  142029. 0
  142030. };
  142031. static long _vq_quantlist__44u4__p7_0[] = {
  142032. 6,
  142033. 5,
  142034. 7,
  142035. 4,
  142036. 8,
  142037. 3,
  142038. 9,
  142039. 2,
  142040. 10,
  142041. 1,
  142042. 11,
  142043. 0,
  142044. 12,
  142045. };
  142046. static long _vq_lengthlist__44u4__p7_0[] = {
  142047. 1, 3, 3,12,12,12,12,12,12,12,12,12,12, 3,12,11,
  142048. 12,12,12,12,12,12,12,12,12,12, 4,11,10,12,12,12,
  142049. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  142050. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  142051. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  142052. 12,12,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142053. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142054. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142055. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142056. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  142057. 11,11,11,11,11,11,11,11,11,
  142058. };
  142059. static float _vq_quantthresh__44u4__p7_0[] = {
  142060. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  142061. 637.5, 892.5, 1147.5, 1402.5,
  142062. };
  142063. static long _vq_quantmap__44u4__p7_0[] = {
  142064. 11, 9, 7, 5, 3, 1, 0, 2,
  142065. 4, 6, 8, 10, 12,
  142066. };
  142067. static encode_aux_threshmatch _vq_auxt__44u4__p7_0 = {
  142068. _vq_quantthresh__44u4__p7_0,
  142069. _vq_quantmap__44u4__p7_0,
  142070. 13,
  142071. 13
  142072. };
  142073. static static_codebook _44u4__p7_0 = {
  142074. 2, 169,
  142075. _vq_lengthlist__44u4__p7_0,
  142076. 1, -514332672, 1627381760, 4, 0,
  142077. _vq_quantlist__44u4__p7_0,
  142078. NULL,
  142079. &_vq_auxt__44u4__p7_0,
  142080. NULL,
  142081. 0
  142082. };
  142083. static long _vq_quantlist__44u4__p7_1[] = {
  142084. 7,
  142085. 6,
  142086. 8,
  142087. 5,
  142088. 9,
  142089. 4,
  142090. 10,
  142091. 3,
  142092. 11,
  142093. 2,
  142094. 12,
  142095. 1,
  142096. 13,
  142097. 0,
  142098. 14,
  142099. };
  142100. static long _vq_lengthlist__44u4__p7_1[] = {
  142101. 1, 4, 4, 6, 6, 7, 7, 9, 8,10, 8,10, 9,11,11, 4,
  142102. 7, 6, 8, 7, 9, 9,10,10,11,10,11,10,12,10, 4, 6,
  142103. 7, 8, 8, 9, 9,10,10,11,11,11,11,12,12, 6, 8, 8,
  142104. 10, 9,11,10,12,11,12,12,12,12,13,13, 6, 8, 8,10,
  142105. 10,10,11,11,11,12,12,13,12,13,13, 8, 9, 9,11,11,
  142106. 12,11,12,12,13,13,13,13,13,13, 8, 9, 9,11,11,11,
  142107. 12,12,12,13,13,13,13,13,13, 9,10,10,12,11,13,13,
  142108. 13,13,14,13,13,14,14,14, 9,10,11,11,12,12,13,13,
  142109. 13,13,13,14,15,14,14,10,11,11,12,12,13,13,14,14,
  142110. 14,14,14,15,16,16,10,11,11,12,13,13,13,13,15,14,
  142111. 14,15,16,15,16,10,12,12,13,13,14,14,14,15,15,15,
  142112. 15,15,15,16,11,12,12,13,13,14,14,14,15,15,15,16,
  142113. 15,17,16,11,12,12,13,13,13,15,15,14,16,16,16,16,
  142114. 16,17,11,12,12,13,13,14,14,15,14,15,15,17,17,16,
  142115. 16,
  142116. };
  142117. static float _vq_quantthresh__44u4__p7_1[] = {
  142118. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  142119. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  142120. };
  142121. static long _vq_quantmap__44u4__p7_1[] = {
  142122. 13, 11, 9, 7, 5, 3, 1, 0,
  142123. 2, 4, 6, 8, 10, 12, 14,
  142124. };
  142125. static encode_aux_threshmatch _vq_auxt__44u4__p7_1 = {
  142126. _vq_quantthresh__44u4__p7_1,
  142127. _vq_quantmap__44u4__p7_1,
  142128. 15,
  142129. 15
  142130. };
  142131. static static_codebook _44u4__p7_1 = {
  142132. 2, 225,
  142133. _vq_lengthlist__44u4__p7_1,
  142134. 1, -522338304, 1620115456, 4, 0,
  142135. _vq_quantlist__44u4__p7_1,
  142136. NULL,
  142137. &_vq_auxt__44u4__p7_1,
  142138. NULL,
  142139. 0
  142140. };
  142141. static long _vq_quantlist__44u4__p7_2[] = {
  142142. 8,
  142143. 7,
  142144. 9,
  142145. 6,
  142146. 10,
  142147. 5,
  142148. 11,
  142149. 4,
  142150. 12,
  142151. 3,
  142152. 13,
  142153. 2,
  142154. 14,
  142155. 1,
  142156. 15,
  142157. 0,
  142158. 16,
  142159. };
  142160. static long _vq_lengthlist__44u4__p7_2[] = {
  142161. 2, 5, 5, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  142162. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  142163. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  142164. 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  142165. 10,10,10,10, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  142166. 9,10, 9,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  142167. 10,10,10,10,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  142168. 9,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  142169. 10,10,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9,
  142170. 10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,10,
  142171. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  142172. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,10,
  142173. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  142174. 10,10,10,10,10,10,10,10,10,11,10,10,10, 9, 9, 9,
  142175. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  142176. 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  142177. 10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  142178. 9,10, 9,10,10,10,10,10,10,10,10,10,10,11,10,10,
  142179. 10,
  142180. };
  142181. static float _vq_quantthresh__44u4__p7_2[] = {
  142182. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  142183. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  142184. };
  142185. static long _vq_quantmap__44u4__p7_2[] = {
  142186. 15, 13, 11, 9, 7, 5, 3, 1,
  142187. 0, 2, 4, 6, 8, 10, 12, 14,
  142188. 16,
  142189. };
  142190. static encode_aux_threshmatch _vq_auxt__44u4__p7_2 = {
  142191. _vq_quantthresh__44u4__p7_2,
  142192. _vq_quantmap__44u4__p7_2,
  142193. 17,
  142194. 17
  142195. };
  142196. static static_codebook _44u4__p7_2 = {
  142197. 2, 289,
  142198. _vq_lengthlist__44u4__p7_2,
  142199. 1, -529530880, 1611661312, 5, 0,
  142200. _vq_quantlist__44u4__p7_2,
  142201. NULL,
  142202. &_vq_auxt__44u4__p7_2,
  142203. NULL,
  142204. 0
  142205. };
  142206. static long _huff_lengthlist__44u4__short[] = {
  142207. 14,17,15,17,16,14,13,16,10, 7, 7,10,13,10,15,16,
  142208. 9, 4, 4, 6, 5, 7, 9,16,12, 8, 7, 8, 8, 8,11,16,
  142209. 14, 7, 4, 6, 3, 5, 8,15,13, 8, 5, 7, 4, 5, 7,16,
  142210. 12, 9, 6, 8, 3, 3, 5,16,14,13, 7,10, 5, 5, 7,15,
  142211. };
  142212. static static_codebook _huff_book__44u4__short = {
  142213. 2, 64,
  142214. _huff_lengthlist__44u4__short,
  142215. 0, 0, 0, 0, 0,
  142216. NULL,
  142217. NULL,
  142218. NULL,
  142219. NULL,
  142220. 0
  142221. };
  142222. static long _huff_lengthlist__44u5__long[] = {
  142223. 3, 8,13,12,14,12,16,11,13,14, 5, 4, 5, 6, 7, 8,
  142224. 10, 9,12,15,10, 5, 5, 5, 6, 8, 9, 9,13,15,10, 5,
  142225. 5, 6, 6, 7, 8, 8,11,13,12, 7, 5, 6, 4, 6, 7, 7,
  142226. 11,14,11, 7, 7, 6, 6, 6, 7, 6,10,14,14, 9, 8, 8,
  142227. 6, 7, 7, 7,11,16,11, 8, 8, 7, 6, 6, 7, 4, 7,12,
  142228. 10,10,12,10,10, 9,10, 5, 6, 9,10,12,15,13,14,14,
  142229. 14, 8, 7, 8,
  142230. };
  142231. static static_codebook _huff_book__44u5__long = {
  142232. 2, 100,
  142233. _huff_lengthlist__44u5__long,
  142234. 0, 0, 0, 0, 0,
  142235. NULL,
  142236. NULL,
  142237. NULL,
  142238. NULL,
  142239. 0
  142240. };
  142241. static long _vq_quantlist__44u5__p1_0[] = {
  142242. 1,
  142243. 0,
  142244. 2,
  142245. };
  142246. static long _vq_lengthlist__44u5__p1_0[] = {
  142247. 1, 4, 4, 5, 8, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  142248. 9,10, 5, 8, 8, 7,10, 9, 8,10,10, 5, 8, 8, 8,10,
  142249. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  142250. 10,13,11,10,13,13, 4, 8, 8, 8,11,10, 8,10,10, 7,
  142251. 10,10,10,13,13,10,11,13, 8,10,11,10,13,13,10,13,
  142252. 12,
  142253. };
  142254. static float _vq_quantthresh__44u5__p1_0[] = {
  142255. -0.5, 0.5,
  142256. };
  142257. static long _vq_quantmap__44u5__p1_0[] = {
  142258. 1, 0, 2,
  142259. };
  142260. static encode_aux_threshmatch _vq_auxt__44u5__p1_0 = {
  142261. _vq_quantthresh__44u5__p1_0,
  142262. _vq_quantmap__44u5__p1_0,
  142263. 3,
  142264. 3
  142265. };
  142266. static static_codebook _44u5__p1_0 = {
  142267. 4, 81,
  142268. _vq_lengthlist__44u5__p1_0,
  142269. 1, -535822336, 1611661312, 2, 0,
  142270. _vq_quantlist__44u5__p1_0,
  142271. NULL,
  142272. &_vq_auxt__44u5__p1_0,
  142273. NULL,
  142274. 0
  142275. };
  142276. static long _vq_quantlist__44u5__p2_0[] = {
  142277. 1,
  142278. 0,
  142279. 2,
  142280. };
  142281. static long _vq_lengthlist__44u5__p2_0[] = {
  142282. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  142283. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  142284. 8, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 8, 7,
  142285. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  142286. 8, 7, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  142287. 9,
  142288. };
  142289. static float _vq_quantthresh__44u5__p2_0[] = {
  142290. -0.5, 0.5,
  142291. };
  142292. static long _vq_quantmap__44u5__p2_0[] = {
  142293. 1, 0, 2,
  142294. };
  142295. static encode_aux_threshmatch _vq_auxt__44u5__p2_0 = {
  142296. _vq_quantthresh__44u5__p2_0,
  142297. _vq_quantmap__44u5__p2_0,
  142298. 3,
  142299. 3
  142300. };
  142301. static static_codebook _44u5__p2_0 = {
  142302. 4, 81,
  142303. _vq_lengthlist__44u5__p2_0,
  142304. 1, -535822336, 1611661312, 2, 0,
  142305. _vq_quantlist__44u5__p2_0,
  142306. NULL,
  142307. &_vq_auxt__44u5__p2_0,
  142308. NULL,
  142309. 0
  142310. };
  142311. static long _vq_quantlist__44u5__p3_0[] = {
  142312. 2,
  142313. 1,
  142314. 3,
  142315. 0,
  142316. 4,
  142317. };
  142318. static long _vq_lengthlist__44u5__p3_0[] = {
  142319. 2, 4, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  142320. 10, 9,13,12, 8, 9,10,12,12, 5, 7, 7,10,10, 7, 9,
  142321. 9,11,11, 6, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  142322. 13,14, 5, 7, 7, 9,10, 7, 9, 8,11,11, 7, 9, 9,11,
  142323. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,13,13,
  142324. 10,11,11,15,14, 9,11,11,14,14,13,14,14,17,16,12,
  142325. 13,13,15,16, 8,10,10,13,13, 9,11,11,14,15,10,11,
  142326. 11,14,15,12,14,13,16,16,13,15,14,15,17, 5, 7, 7,
  142327. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,
  142328. 14,10,11,12,14,14, 7, 9, 9,12,11, 9,11,11,13,13,
  142329. 9,11,11,13,13,12,13,13,15,16,11,12,13,15,16, 6,
  142330. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,14,11,13,
  142331. 12,16,14,11,13,13,16,17,10,12,11,15,15,11,13,13,
  142332. 16,16,11,13,13,17,16,14,15,15,17,17,14,16,16,17,
  142333. 18, 9,11,11,14,15,10,12,12,15,15,11,13,13,16,17,
  142334. 13,15,13,17,15,14,15,16,18, 0, 5, 7, 7,10,10, 7,
  142335. 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  142336. 12,14,15, 6, 9, 9,12,11, 9,11,11,13,13, 8,10,11,
  142337. 12,13,11,13,13,16,15,11,12,13,14,15, 7, 9, 9,11,
  142338. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,15,16,
  142339. 11,13,13,15,14, 9,11,11,15,14,11,13,13,17,15,10,
  142340. 12,12,15,15,14,16,16,17,17,13,13,15,15,17,10,11,
  142341. 12,15,15,11,13,13,16,16,11,13,13,15,15,14,15,15,
  142342. 18,18,14,15,15,17,17, 8,10,10,13,13,10,12,11,15,
  142343. 15,10,11,12,15,15,14,15,15,18,18,13,14,14,18,18,
  142344. 9,11,11,15,16,11,13,13,17,17,11,13,13,16,16,15,
  142345. 15,16,17, 0,14,15,17, 0, 0, 9,11,11,15,15,10,13,
  142346. 12,18,16,11,13,13,15,16,14,16,15,20,20,14,15,16,
  142347. 17, 0,13,14,14,20,16,14,15,16,19,18,14,15,15,19,
  142348. 0,18,16, 0,20,20,16,18,18, 0, 0,12,14,14,18,18,
  142349. 13,15,14,18,16,14,15,16,18,20,16,19,16, 0,17,17,
  142350. 18,18,19, 0, 8,10,10,14,14,10,11,11,14,15,10,11,
  142351. 12,15,15,13,15,14,19,17,13,15,15,17, 0, 9,11,11,
  142352. 16,15,11,13,13,16,16,10,12,13,15,17,14,16,16,18,
  142353. 18,14,15,15,18, 0, 9,11,11,15,15,11,13,13,16,17,
  142354. 11,13,13,18,17,14,18,16,18,18,15,17,17,18, 0,12,
  142355. 14,14,18,18,14,15,15,20, 0,13,14,15,17, 0,16,18,
  142356. 17, 0, 0,16,16, 0,17,20,12,14,14,18,18,14,16,15,
  142357. 0,18,14,16,15,18, 0,16,19,17, 0, 0,17,18,16, 0,
  142358. 0,
  142359. };
  142360. static float _vq_quantthresh__44u5__p3_0[] = {
  142361. -1.5, -0.5, 0.5, 1.5,
  142362. };
  142363. static long _vq_quantmap__44u5__p3_0[] = {
  142364. 3, 1, 0, 2, 4,
  142365. };
  142366. static encode_aux_threshmatch _vq_auxt__44u5__p3_0 = {
  142367. _vq_quantthresh__44u5__p3_0,
  142368. _vq_quantmap__44u5__p3_0,
  142369. 5,
  142370. 5
  142371. };
  142372. static static_codebook _44u5__p3_0 = {
  142373. 4, 625,
  142374. _vq_lengthlist__44u5__p3_0,
  142375. 1, -533725184, 1611661312, 3, 0,
  142376. _vq_quantlist__44u5__p3_0,
  142377. NULL,
  142378. &_vq_auxt__44u5__p3_0,
  142379. NULL,
  142380. 0
  142381. };
  142382. static long _vq_quantlist__44u5__p4_0[] = {
  142383. 2,
  142384. 1,
  142385. 3,
  142386. 0,
  142387. 4,
  142388. };
  142389. static long _vq_lengthlist__44u5__p4_0[] = {
  142390. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  142391. 9, 9,11,11, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  142392. 8,10,10, 6, 7, 8, 9,10, 9,10,10,11,12, 9, 9,10,
  142393. 11,12, 6, 7, 7, 9, 9, 6, 8, 7,10, 9, 7, 8, 8,10,
  142394. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,12,11,
  142395. 9,10,10,12,12, 9,10,10,12,12,11,12,12,13,14,11,
  142396. 11,12,13,14, 8, 9, 9,11,12, 9,10,10,12,12, 9,10,
  142397. 10,12,12,11,12,11,14,13,11,12,12,13,13, 5, 7, 7,
  142398. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  142399. 12, 9,10,10,12,12, 7, 8, 8,10,10, 8, 8, 9,10,11,
  142400. 8, 9, 9,11,11,10,10,11,11,13,10,11,11,12,13, 6,
  142401. 7, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  142402. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  142403. 12,13,10,11,11,13,13,12,11,13,12,15,12,13,13,14,
  142404. 15, 9,10,10,12,12, 9,11,10,13,12,10,11,11,13,13,
  142405. 11,13,11,14,12,12,13,13,14,15, 5, 7, 7, 9, 9, 7,
  142406. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,
  142407. 10,12,12, 6, 8, 7,10,10, 8, 9, 9,11,11, 7, 8, 9,
  142408. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 8, 8,10,
  142409. 10, 8, 9, 9,11,11, 8, 9, 8,11,10,10,11,11,13,12,
  142410. 10,11,10,13,11, 9,10,10,12,12,10,11,11,13,12, 9,
  142411. 10,10,12,13,12,13,13,14,15,11,11,13,12,14, 9,10,
  142412. 10,12,12,10,11,11,13,13,10,11,10,13,12,12,13,13,
  142413. 14,14,12,13,11,14,12, 8, 9, 9,12,12, 9,10,10,12,
  142414. 12, 9,10,10,12,12,12,12,12,14,14,11,12,12,14,13,
  142415. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,12,12,
  142416. 12,13,14,15,12,13,13,15,14, 9,10,10,12,12,10,11,
  142417. 10,13,12,10,11,11,12,13,12,13,12,15,13,12,13,13,
  142418. 14,15,11,12,12,14,13,11,12,12,14,15,12,13,13,15,
  142419. 14,13,12,14,12,16,13,14,14,15,15,11,11,12,14,14,
  142420. 11,12,11,14,13,12,13,13,14,15,13,14,12,16,12,14,
  142421. 14,15,16,16, 8, 9, 9,11,12, 9,10,10,12,12, 9,10,
  142422. 10,12,13,11,12,12,13,13,12,12,13,14,14, 9,10,10,
  142423. 12,12,10,11,10,13,12,10,10,11,12,13,12,13,13,15,
  142424. 14,12,12,13,13,15, 9,10,10,12,13,10,11,11,12,13,
  142425. 10,11,11,13,13,12,13,13,14,15,12,13,12,15,14,11,
  142426. 12,11,14,13,12,13,13,15,14,11,11,12,13,14,14,15,
  142427. 14,16,15,13,12,14,13,16,11,12,12,13,14,12,13,13,
  142428. 14,15,11,12,11,14,14,14,14,14,15,16,13,15,12,16,
  142429. 12,
  142430. };
  142431. static float _vq_quantthresh__44u5__p4_0[] = {
  142432. -1.5, -0.5, 0.5, 1.5,
  142433. };
  142434. static long _vq_quantmap__44u5__p4_0[] = {
  142435. 3, 1, 0, 2, 4,
  142436. };
  142437. static encode_aux_threshmatch _vq_auxt__44u5__p4_0 = {
  142438. _vq_quantthresh__44u5__p4_0,
  142439. _vq_quantmap__44u5__p4_0,
  142440. 5,
  142441. 5
  142442. };
  142443. static static_codebook _44u5__p4_0 = {
  142444. 4, 625,
  142445. _vq_lengthlist__44u5__p4_0,
  142446. 1, -533725184, 1611661312, 3, 0,
  142447. _vq_quantlist__44u5__p4_0,
  142448. NULL,
  142449. &_vq_auxt__44u5__p4_0,
  142450. NULL,
  142451. 0
  142452. };
  142453. static long _vq_quantlist__44u5__p5_0[] = {
  142454. 4,
  142455. 3,
  142456. 5,
  142457. 2,
  142458. 6,
  142459. 1,
  142460. 7,
  142461. 0,
  142462. 8,
  142463. };
  142464. static long _vq_lengthlist__44u5__p5_0[] = {
  142465. 2, 3, 3, 6, 6, 8, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  142466. 11,10, 3, 5, 5, 7, 8, 8, 8,10,11, 6, 8, 7,10, 9,
  142467. 10,10,11,11, 6, 7, 8, 9, 9, 9,10,11,12, 8, 8, 8,
  142468. 10,10,11,11,13,12, 8, 8, 9, 9,10,11,11,12,13,10,
  142469. 11,10,12,11,13,12,14,14,10,10,11,11,12,12,13,14,
  142470. 14,
  142471. };
  142472. static float _vq_quantthresh__44u5__p5_0[] = {
  142473. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  142474. };
  142475. static long _vq_quantmap__44u5__p5_0[] = {
  142476. 7, 5, 3, 1, 0, 2, 4, 6,
  142477. 8,
  142478. };
  142479. static encode_aux_threshmatch _vq_auxt__44u5__p5_0 = {
  142480. _vq_quantthresh__44u5__p5_0,
  142481. _vq_quantmap__44u5__p5_0,
  142482. 9,
  142483. 9
  142484. };
  142485. static static_codebook _44u5__p5_0 = {
  142486. 2, 81,
  142487. _vq_lengthlist__44u5__p5_0,
  142488. 1, -531628032, 1611661312, 4, 0,
  142489. _vq_quantlist__44u5__p5_0,
  142490. NULL,
  142491. &_vq_auxt__44u5__p5_0,
  142492. NULL,
  142493. 0
  142494. };
  142495. static long _vq_quantlist__44u5__p6_0[] = {
  142496. 4,
  142497. 3,
  142498. 5,
  142499. 2,
  142500. 6,
  142501. 1,
  142502. 7,
  142503. 0,
  142504. 8,
  142505. };
  142506. static long _vq_lengthlist__44u5__p6_0[] = {
  142507. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  142508. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  142509. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8,10,10, 7, 7, 7,
  142510. 8, 8, 9, 9,11,10, 7, 7, 7, 8, 8, 9, 9,10,11, 9,
  142511. 9, 9,10,10,11,10,11,11, 9, 9, 9,10,10,11,10,11,
  142512. 11,
  142513. };
  142514. static float _vq_quantthresh__44u5__p6_0[] = {
  142515. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  142516. };
  142517. static long _vq_quantmap__44u5__p6_0[] = {
  142518. 7, 5, 3, 1, 0, 2, 4, 6,
  142519. 8,
  142520. };
  142521. static encode_aux_threshmatch _vq_auxt__44u5__p6_0 = {
  142522. _vq_quantthresh__44u5__p6_0,
  142523. _vq_quantmap__44u5__p6_0,
  142524. 9,
  142525. 9
  142526. };
  142527. static static_codebook _44u5__p6_0 = {
  142528. 2, 81,
  142529. _vq_lengthlist__44u5__p6_0,
  142530. 1, -531628032, 1611661312, 4, 0,
  142531. _vq_quantlist__44u5__p6_0,
  142532. NULL,
  142533. &_vq_auxt__44u5__p6_0,
  142534. NULL,
  142535. 0
  142536. };
  142537. static long _vq_quantlist__44u5__p7_0[] = {
  142538. 1,
  142539. 0,
  142540. 2,
  142541. };
  142542. static long _vq_lengthlist__44u5__p7_0[] = {
  142543. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 9, 8,11,10, 7,
  142544. 11,10, 5, 9, 9, 7,10,10, 8,10,11, 4, 9, 9, 9,12,
  142545. 12, 9,12,12, 8,12,12,11,12,12,10,12,13, 7,12,12,
  142546. 11,12,12,10,12,13, 4, 9, 9, 9,12,12, 9,12,12, 7,
  142547. 12,11,10,13,13,11,12,12, 7,12,12,10,13,13,11,12,
  142548. 12,
  142549. };
  142550. static float _vq_quantthresh__44u5__p7_0[] = {
  142551. -5.5, 5.5,
  142552. };
  142553. static long _vq_quantmap__44u5__p7_0[] = {
  142554. 1, 0, 2,
  142555. };
  142556. static encode_aux_threshmatch _vq_auxt__44u5__p7_0 = {
  142557. _vq_quantthresh__44u5__p7_0,
  142558. _vq_quantmap__44u5__p7_0,
  142559. 3,
  142560. 3
  142561. };
  142562. static static_codebook _44u5__p7_0 = {
  142563. 4, 81,
  142564. _vq_lengthlist__44u5__p7_0,
  142565. 1, -529137664, 1618345984, 2, 0,
  142566. _vq_quantlist__44u5__p7_0,
  142567. NULL,
  142568. &_vq_auxt__44u5__p7_0,
  142569. NULL,
  142570. 0
  142571. };
  142572. static long _vq_quantlist__44u5__p7_1[] = {
  142573. 5,
  142574. 4,
  142575. 6,
  142576. 3,
  142577. 7,
  142578. 2,
  142579. 8,
  142580. 1,
  142581. 9,
  142582. 0,
  142583. 10,
  142584. };
  142585. static long _vq_lengthlist__44u5__p7_1[] = {
  142586. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 7,
  142587. 8, 8, 9, 8, 8, 9, 4, 5, 5, 7, 7, 8, 8, 9, 9, 8,
  142588. 9, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  142589. 8, 9, 9, 9, 9, 9, 9, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  142590. 9, 9, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9,
  142591. 9, 9, 9, 9,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  142592. 10,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10, 8, 9,
  142593. 9, 9, 9, 9, 9,10,10,10,10,
  142594. };
  142595. static float _vq_quantthresh__44u5__p7_1[] = {
  142596. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  142597. 3.5, 4.5,
  142598. };
  142599. static long _vq_quantmap__44u5__p7_1[] = {
  142600. 9, 7, 5, 3, 1, 0, 2, 4,
  142601. 6, 8, 10,
  142602. };
  142603. static encode_aux_threshmatch _vq_auxt__44u5__p7_1 = {
  142604. _vq_quantthresh__44u5__p7_1,
  142605. _vq_quantmap__44u5__p7_1,
  142606. 11,
  142607. 11
  142608. };
  142609. static static_codebook _44u5__p7_1 = {
  142610. 2, 121,
  142611. _vq_lengthlist__44u5__p7_1,
  142612. 1, -531365888, 1611661312, 4, 0,
  142613. _vq_quantlist__44u5__p7_1,
  142614. NULL,
  142615. &_vq_auxt__44u5__p7_1,
  142616. NULL,
  142617. 0
  142618. };
  142619. static long _vq_quantlist__44u5__p8_0[] = {
  142620. 5,
  142621. 4,
  142622. 6,
  142623. 3,
  142624. 7,
  142625. 2,
  142626. 8,
  142627. 1,
  142628. 9,
  142629. 0,
  142630. 10,
  142631. };
  142632. static long _vq_lengthlist__44u5__p8_0[] = {
  142633. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7,
  142634. 9, 9,10,10,11,11, 4, 6, 6, 7, 7, 9, 9,10,10,11,
  142635. 11, 6, 8, 7, 9, 9,10,10,11,11,13,12, 6, 8, 8, 9,
  142636. 9,10,10,11,11,12,13, 8, 9, 9,10,10,12,12,13,12,
  142637. 14,13, 8, 9, 9,10,10,12,12,13,13,14,14, 9,11,11,
  142638. 12,12,13,13,14,14,15,14, 9,11,11,12,12,13,13,14,
  142639. 14,15,14,11,12,12,13,13,14,14,15,14,15,14,11,11,
  142640. 12,13,13,14,14,14,14,15,15,
  142641. };
  142642. static float _vq_quantthresh__44u5__p8_0[] = {
  142643. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  142644. 38.5, 49.5,
  142645. };
  142646. static long _vq_quantmap__44u5__p8_0[] = {
  142647. 9, 7, 5, 3, 1, 0, 2, 4,
  142648. 6, 8, 10,
  142649. };
  142650. static encode_aux_threshmatch _vq_auxt__44u5__p8_0 = {
  142651. _vq_quantthresh__44u5__p8_0,
  142652. _vq_quantmap__44u5__p8_0,
  142653. 11,
  142654. 11
  142655. };
  142656. static static_codebook _44u5__p8_0 = {
  142657. 2, 121,
  142658. _vq_lengthlist__44u5__p8_0,
  142659. 1, -524582912, 1618345984, 4, 0,
  142660. _vq_quantlist__44u5__p8_0,
  142661. NULL,
  142662. &_vq_auxt__44u5__p8_0,
  142663. NULL,
  142664. 0
  142665. };
  142666. static long _vq_quantlist__44u5__p8_1[] = {
  142667. 5,
  142668. 4,
  142669. 6,
  142670. 3,
  142671. 7,
  142672. 2,
  142673. 8,
  142674. 1,
  142675. 9,
  142676. 0,
  142677. 10,
  142678. };
  142679. static long _vq_lengthlist__44u5__p8_1[] = {
  142680. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 5, 7, 6,
  142681. 7, 7, 8, 8, 8, 8, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  142682. 8, 6, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 6, 6, 7, 7,
  142683. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  142684. 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8,
  142685. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  142686. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  142687. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  142688. };
  142689. static float _vq_quantthresh__44u5__p8_1[] = {
  142690. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  142691. 3.5, 4.5,
  142692. };
  142693. static long _vq_quantmap__44u5__p8_1[] = {
  142694. 9, 7, 5, 3, 1, 0, 2, 4,
  142695. 6, 8, 10,
  142696. };
  142697. static encode_aux_threshmatch _vq_auxt__44u5__p8_1 = {
  142698. _vq_quantthresh__44u5__p8_1,
  142699. _vq_quantmap__44u5__p8_1,
  142700. 11,
  142701. 11
  142702. };
  142703. static static_codebook _44u5__p8_1 = {
  142704. 2, 121,
  142705. _vq_lengthlist__44u5__p8_1,
  142706. 1, -531365888, 1611661312, 4, 0,
  142707. _vq_quantlist__44u5__p8_1,
  142708. NULL,
  142709. &_vq_auxt__44u5__p8_1,
  142710. NULL,
  142711. 0
  142712. };
  142713. static long _vq_quantlist__44u5__p9_0[] = {
  142714. 6,
  142715. 5,
  142716. 7,
  142717. 4,
  142718. 8,
  142719. 3,
  142720. 9,
  142721. 2,
  142722. 10,
  142723. 1,
  142724. 11,
  142725. 0,
  142726. 12,
  142727. };
  142728. static long _vq_lengthlist__44u5__p9_0[] = {
  142729. 1, 3, 2,12,10,13,13,13,13,13,13,13,13, 4, 9, 9,
  142730. 13,13,13,13,13,13,13,13,13,13, 5,10, 9,13,13,13,
  142731. 13,13,13,13,13,13,13,12,13,13,13,13,13,13,13,13,
  142732. 13,13,13,13,11,13,13,13,13,13,13,13,13,13,13,13,
  142733. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  142734. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  142735. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  142736. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  142737. 13,13,13,13,13,13,13,13,13,13,13,13,13,12,12,12,
  142738. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  142739. 12,12,12,12,12,12,12,12,12,
  142740. };
  142741. static float _vq_quantthresh__44u5__p9_0[] = {
  142742. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  142743. 637.5, 892.5, 1147.5, 1402.5,
  142744. };
  142745. static long _vq_quantmap__44u5__p9_0[] = {
  142746. 11, 9, 7, 5, 3, 1, 0, 2,
  142747. 4, 6, 8, 10, 12,
  142748. };
  142749. static encode_aux_threshmatch _vq_auxt__44u5__p9_0 = {
  142750. _vq_quantthresh__44u5__p9_0,
  142751. _vq_quantmap__44u5__p9_0,
  142752. 13,
  142753. 13
  142754. };
  142755. static static_codebook _44u5__p9_0 = {
  142756. 2, 169,
  142757. _vq_lengthlist__44u5__p9_0,
  142758. 1, -514332672, 1627381760, 4, 0,
  142759. _vq_quantlist__44u5__p9_0,
  142760. NULL,
  142761. &_vq_auxt__44u5__p9_0,
  142762. NULL,
  142763. 0
  142764. };
  142765. static long _vq_quantlist__44u5__p9_1[] = {
  142766. 7,
  142767. 6,
  142768. 8,
  142769. 5,
  142770. 9,
  142771. 4,
  142772. 10,
  142773. 3,
  142774. 11,
  142775. 2,
  142776. 12,
  142777. 1,
  142778. 13,
  142779. 0,
  142780. 14,
  142781. };
  142782. static long _vq_lengthlist__44u5__p9_1[] = {
  142783. 1, 4, 4, 7, 7, 8, 8, 8, 7, 8, 7, 9, 8, 9, 9, 4,
  142784. 7, 6, 9, 8,10,10, 9, 8, 9, 9, 9, 9, 9, 8, 5, 6,
  142785. 6, 8, 9,10,10, 9, 9, 9,10,10,10,10,11, 7, 8, 8,
  142786. 10,10,11,11,10,10,11,11,11,12,11,11, 7, 8, 8,10,
  142787. 10,11,11,10,10,11,11,12,11,11,11, 8, 9, 9,11,11,
  142788. 12,12,11,11,12,11,12,12,12,12, 8, 9,10,11,11,12,
  142789. 12,11,11,12,12,12,12,12,12, 8, 9, 9,10,10,12,11,
  142790. 12,12,12,12,12,12,12,13, 8, 9, 9,11,11,11,11,12,
  142791. 12,12,12,13,12,13,13, 9,10,10,11,11,12,12,12,13,
  142792. 12,13,13,13,14,13, 9,10,10,11,11,12,12,12,13,13,
  142793. 12,13,13,14,13, 9,11,10,12,11,13,12,12,13,13,13,
  142794. 13,13,13,14, 9,10,10,12,12,12,12,12,13,13,13,13,
  142795. 13,14,14,10,11,11,12,12,12,13,13,13,14,14,13,14,
  142796. 14,14,10,11,11,12,12,12,12,13,12,13,14,13,14,14,
  142797. 14,
  142798. };
  142799. static float _vq_quantthresh__44u5__p9_1[] = {
  142800. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  142801. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  142802. };
  142803. static long _vq_quantmap__44u5__p9_1[] = {
  142804. 13, 11, 9, 7, 5, 3, 1, 0,
  142805. 2, 4, 6, 8, 10, 12, 14,
  142806. };
  142807. static encode_aux_threshmatch _vq_auxt__44u5__p9_1 = {
  142808. _vq_quantthresh__44u5__p9_1,
  142809. _vq_quantmap__44u5__p9_1,
  142810. 15,
  142811. 15
  142812. };
  142813. static static_codebook _44u5__p9_1 = {
  142814. 2, 225,
  142815. _vq_lengthlist__44u5__p9_1,
  142816. 1, -522338304, 1620115456, 4, 0,
  142817. _vq_quantlist__44u5__p9_1,
  142818. NULL,
  142819. &_vq_auxt__44u5__p9_1,
  142820. NULL,
  142821. 0
  142822. };
  142823. static long _vq_quantlist__44u5__p9_2[] = {
  142824. 8,
  142825. 7,
  142826. 9,
  142827. 6,
  142828. 10,
  142829. 5,
  142830. 11,
  142831. 4,
  142832. 12,
  142833. 3,
  142834. 13,
  142835. 2,
  142836. 14,
  142837. 1,
  142838. 15,
  142839. 0,
  142840. 16,
  142841. };
  142842. static long _vq_lengthlist__44u5__p9_2[] = {
  142843. 2, 5, 5, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  142844. 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  142845. 9, 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  142846. 9, 9, 9, 7, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  142847. 9, 9, 9, 9, 7, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  142848. 9, 9, 9, 9, 9, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  142849. 9,10, 9,10,10,10, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  142850. 9, 9,10, 9,10, 9,10, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  142851. 9,10, 9,10,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  142852. 9,10, 9,10,10,10,10,10,10, 9, 9, 9, 9, 9,10, 9,
  142853. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,
  142854. 9,10, 9,10, 9,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  142855. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  142856. 9, 9,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  142857. 9,10,10, 9,10,10,10,10,10,10,10,10,10,10, 9, 9,
  142858. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  142859. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  142860. 9, 9, 9,10, 9,10,10,10,10,10,10,10,10,10,10,10,
  142861. 10,
  142862. };
  142863. static float _vq_quantthresh__44u5__p9_2[] = {
  142864. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  142865. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  142866. };
  142867. static long _vq_quantmap__44u5__p9_2[] = {
  142868. 15, 13, 11, 9, 7, 5, 3, 1,
  142869. 0, 2, 4, 6, 8, 10, 12, 14,
  142870. 16,
  142871. };
  142872. static encode_aux_threshmatch _vq_auxt__44u5__p9_2 = {
  142873. _vq_quantthresh__44u5__p9_2,
  142874. _vq_quantmap__44u5__p9_2,
  142875. 17,
  142876. 17
  142877. };
  142878. static static_codebook _44u5__p9_2 = {
  142879. 2, 289,
  142880. _vq_lengthlist__44u5__p9_2,
  142881. 1, -529530880, 1611661312, 5, 0,
  142882. _vq_quantlist__44u5__p9_2,
  142883. NULL,
  142884. &_vq_auxt__44u5__p9_2,
  142885. NULL,
  142886. 0
  142887. };
  142888. static long _huff_lengthlist__44u5__short[] = {
  142889. 4,10,17,13,17,13,17,17,17,17, 3, 6, 8, 9,11, 9,
  142890. 15,12,16,17, 6, 5, 5, 7, 7, 8,10,11,17,17, 7, 8,
  142891. 7, 9, 9,10,13,13,17,17, 8, 6, 5, 7, 4, 7, 5, 8,
  142892. 14,17, 9, 9, 8, 9, 7, 9, 8,10,16,17,12,10, 7, 8,
  142893. 4, 7, 4, 7,16,17,12,11, 9,10, 6, 9, 5, 7,14,17,
  142894. 14,13,10,15, 4, 8, 3, 5,14,17,17,14,11,15, 6,10,
  142895. 6, 8,15,17,
  142896. };
  142897. static static_codebook _huff_book__44u5__short = {
  142898. 2, 100,
  142899. _huff_lengthlist__44u5__short,
  142900. 0, 0, 0, 0, 0,
  142901. NULL,
  142902. NULL,
  142903. NULL,
  142904. NULL,
  142905. 0
  142906. };
  142907. static long _huff_lengthlist__44u6__long[] = {
  142908. 3, 9,14,13,14,13,16,12,13,14, 5, 4, 6, 6, 8, 9,
  142909. 11,10,12,15,10, 5, 5, 6, 6, 8,10,10,13,16,10, 6,
  142910. 6, 6, 6, 8, 9, 9,12,14,13, 7, 6, 6, 4, 6, 6, 7,
  142911. 11,14,10, 7, 7, 7, 6, 6, 6, 7,10,13,15,10, 9, 8,
  142912. 5, 6, 5, 6,10,14,10, 9, 8, 8, 6, 6, 5, 4, 6,11,
  142913. 11,11,12,11,10, 9, 9, 5, 5, 9,10,12,15,13,13,13,
  142914. 13, 8, 7, 7,
  142915. };
  142916. static static_codebook _huff_book__44u6__long = {
  142917. 2, 100,
  142918. _huff_lengthlist__44u6__long,
  142919. 0, 0, 0, 0, 0,
  142920. NULL,
  142921. NULL,
  142922. NULL,
  142923. NULL,
  142924. 0
  142925. };
  142926. static long _vq_quantlist__44u6__p1_0[] = {
  142927. 1,
  142928. 0,
  142929. 2,
  142930. };
  142931. static long _vq_lengthlist__44u6__p1_0[] = {
  142932. 1, 4, 4, 4, 8, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  142933. 9,10, 5, 8, 8, 7,10, 9, 8,10,10, 5, 8, 8, 8,10,
  142934. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  142935. 10,13,11,10,13,13, 5, 8, 8, 8,11,10, 8,10,10, 7,
  142936. 10,10,10,13,13,10,11,13, 8,10,11,10,13,13,10,13,
  142937. 12,
  142938. };
  142939. static float _vq_quantthresh__44u6__p1_0[] = {
  142940. -0.5, 0.5,
  142941. };
  142942. static long _vq_quantmap__44u6__p1_0[] = {
  142943. 1, 0, 2,
  142944. };
  142945. static encode_aux_threshmatch _vq_auxt__44u6__p1_0 = {
  142946. _vq_quantthresh__44u6__p1_0,
  142947. _vq_quantmap__44u6__p1_0,
  142948. 3,
  142949. 3
  142950. };
  142951. static static_codebook _44u6__p1_0 = {
  142952. 4, 81,
  142953. _vq_lengthlist__44u6__p1_0,
  142954. 1, -535822336, 1611661312, 2, 0,
  142955. _vq_quantlist__44u6__p1_0,
  142956. NULL,
  142957. &_vq_auxt__44u6__p1_0,
  142958. NULL,
  142959. 0
  142960. };
  142961. static long _vq_quantlist__44u6__p2_0[] = {
  142962. 1,
  142963. 0,
  142964. 2,
  142965. };
  142966. static long _vq_lengthlist__44u6__p2_0[] = {
  142967. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  142968. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  142969. 8, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 7, 7,
  142970. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  142971. 8, 8, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  142972. 9,
  142973. };
  142974. static float _vq_quantthresh__44u6__p2_0[] = {
  142975. -0.5, 0.5,
  142976. };
  142977. static long _vq_quantmap__44u6__p2_0[] = {
  142978. 1, 0, 2,
  142979. };
  142980. static encode_aux_threshmatch _vq_auxt__44u6__p2_0 = {
  142981. _vq_quantthresh__44u6__p2_0,
  142982. _vq_quantmap__44u6__p2_0,
  142983. 3,
  142984. 3
  142985. };
  142986. static static_codebook _44u6__p2_0 = {
  142987. 4, 81,
  142988. _vq_lengthlist__44u6__p2_0,
  142989. 1, -535822336, 1611661312, 2, 0,
  142990. _vq_quantlist__44u6__p2_0,
  142991. NULL,
  142992. &_vq_auxt__44u6__p2_0,
  142993. NULL,
  142994. 0
  142995. };
  142996. static long _vq_quantlist__44u6__p3_0[] = {
  142997. 2,
  142998. 1,
  142999. 3,
  143000. 0,
  143001. 4,
  143002. };
  143003. static long _vq_lengthlist__44u6__p3_0[] = {
  143004. 2, 5, 4, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  143005. 9, 9,13,12, 8, 9,10,12,13, 5, 7, 7,10, 9, 7, 9,
  143006. 9,11,11, 7, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  143007. 13,14, 5, 7, 7, 9,10, 6, 9, 8,11,11, 7, 9, 9,11,
  143008. 11, 9,11,10,14,13,10,11,11,14,13, 8,10,10,13,13,
  143009. 10,11,11,15,15, 9,11,11,14,14,13,14,14,17,16,12,
  143010. 13,14,16,16, 8,10,10,13,14, 9,11,11,14,15,10,11,
  143011. 12,14,15,12,14,13,16,15,13,14,14,15,17, 5, 7, 7,
  143012. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,12,11,14,
  143013. 14,10,11,11,14,14, 7, 9, 9,12,11, 9,11,11,13,13,
  143014. 9,11,11,13,13,11,13,13,14,15,11,12,13,15,16, 6,
  143015. 9, 9,11,12, 8,11,10,13,12, 9,11,11,13,14,11,13,
  143016. 12,16,14,11,13,13,15,16,10,12,11,14,15,11,13,13,
  143017. 15,17,11,13,13,17,16,15,15,16,17,16,14,15,16,18,
  143018. 0, 9,11,11,14,15,10,12,12,16,15,11,13,13,16,16,
  143019. 13,15,14,18,15,14,16,16, 0, 0, 5, 7, 7,10,10, 7,
  143020. 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  143021. 12,14,14, 6, 9, 9,11,11, 9,11,11,13,13, 8,10,11,
  143022. 12,13,11,13,13,16,15,11,12,13,14,16, 7, 9, 9,11,
  143023. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,16,15,
  143024. 11,13,12,15,15, 9,11,11,15,14,11,13,13,17,16,10,
  143025. 12,13,15,16,14,16,16, 0,18,14,14,15,15,17,10,11,
  143026. 12,15,15,11,13,13,16,16,11,13,13,16,16,14,16,16,
  143027. 19,17,14,15,15,17,17, 8,10,10,14,14,10,12,11,15,
  143028. 15,10,11,12,16,15,14,15,15,18,20,13,14,16,17,18,
  143029. 9,11,11,15,16,11,13,13,17,17,11,13,13,17,16,15,
  143030. 16,16, 0, 0,15,16,16, 0, 0, 9,11,11,15,15,10,13,
  143031. 12,17,15,11,13,13,17,16,15,17,15,20,19,15,16,16,
  143032. 19, 0,13,15,14, 0,17,14,15,16, 0,20,15,16,16, 0,
  143033. 19,17,18, 0, 0, 0,16,17,18, 0, 0,12,14,14,19,18,
  143034. 13,15,14, 0,17,14,15,16,19,19,16,18,16, 0,19,19,
  143035. 20,17,20, 0, 8,10,10,13,14,10,11,11,15,15,10,12,
  143036. 12,15,16,14,15,14,19,16,14,15,15, 0,18, 9,11,11,
  143037. 16,15,11,13,13, 0,16,11,12,13,16,17,14,16,17, 0,
  143038. 19,15,16,16,18, 0, 9,11,11,15,16,11,13,13,16,16,
  143039. 11,14,13,18,17,15,16,16,18,20,15,17,19, 0, 0,12,
  143040. 14,14,17,17,14,16,15, 0, 0,13,14,15,19, 0,16,18,
  143041. 20, 0, 0,16,16,18,18, 0,12,14,14,17,20,14,16,16,
  143042. 19, 0,14,16,14, 0,20,16,20,17, 0, 0,17, 0,15, 0,
  143043. 19,
  143044. };
  143045. static float _vq_quantthresh__44u6__p3_0[] = {
  143046. -1.5, -0.5, 0.5, 1.5,
  143047. };
  143048. static long _vq_quantmap__44u6__p3_0[] = {
  143049. 3, 1, 0, 2, 4,
  143050. };
  143051. static encode_aux_threshmatch _vq_auxt__44u6__p3_0 = {
  143052. _vq_quantthresh__44u6__p3_0,
  143053. _vq_quantmap__44u6__p3_0,
  143054. 5,
  143055. 5
  143056. };
  143057. static static_codebook _44u6__p3_0 = {
  143058. 4, 625,
  143059. _vq_lengthlist__44u6__p3_0,
  143060. 1, -533725184, 1611661312, 3, 0,
  143061. _vq_quantlist__44u6__p3_0,
  143062. NULL,
  143063. &_vq_auxt__44u6__p3_0,
  143064. NULL,
  143065. 0
  143066. };
  143067. static long _vq_quantlist__44u6__p4_0[] = {
  143068. 2,
  143069. 1,
  143070. 3,
  143071. 0,
  143072. 4,
  143073. };
  143074. static long _vq_lengthlist__44u6__p4_0[] = {
  143075. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  143076. 9, 9,11,11, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  143077. 8,10,10, 7, 7, 8, 9,10, 9,10,10,11,11, 9, 9,10,
  143078. 11,12, 6, 7, 7, 9, 9, 7, 8, 7,10, 9, 7, 8, 8,10,
  143079. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,11,11,
  143080. 9,10,10,12,12, 9,10,10,12,12,11,12,12,14,13,11,
  143081. 11,12,13,13, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  143082. 10,12,12,11,12,11,13,12,11,12,12,13,13, 5, 7, 7,
  143083. 9, 9, 7, 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,
  143084. 11, 9,10,10,11,12, 7, 8, 8,10,10, 8, 8, 9,11,11,
  143085. 8, 9, 9,11,11,10,10,11,12,13,10,10,11,12,12, 6,
  143086. 7, 7,10,10, 7, 9, 8,11,10, 8, 8, 9,10,11,10,11,
  143087. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  143088. 13,13,10,11,11,12,13,12,12,12,13,14,12,12,13,14,
  143089. 14, 9,10,10,12,12, 9,10,10,13,12,10,11,11,13,13,
  143090. 11,12,11,14,12,12,13,13,14,14, 6, 7, 7, 9, 9, 7,
  143091. 8, 7,10,10, 7, 8, 8,10,10, 9,10,10,12,11, 9,10,
  143092. 10,11,12, 6, 7, 7,10,10, 8, 9, 8,11,10, 7, 8, 9,
  143093. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 8, 8,10,
  143094. 10, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,10,13,12,
  143095. 10,11,11,13,12, 9,10,10,12,12,10,11,11,13,12, 9,
  143096. 10,10,12,13,12,13,12,14,14,11,11,12,12,14, 9,10,
  143097. 10,12,12,10,11,11,13,13,10,11,10,13,12,12,12,12,
  143098. 14,14,12,13,12,14,13, 8, 9, 9,11,11, 9,10,10,12,
  143099. 12, 9,10,10,12,12,11,12,12,14,13,11,12,12,13,14,
  143100. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,13,12,
  143101. 12,13,14,15,12,12,13,14,14, 9,10,10,12,12, 9,11,
  143102. 10,13,12,10,10,11,12,13,12,13,12,14,13,12,12,13,
  143103. 14,15,11,12,12,14,13,11,12,12,14,14,12,13,13,14,
  143104. 14,13,13,14,14,16,13,14,14,15,15,11,12,11,13,13,
  143105. 11,12,11,14,13,12,12,13,14,15,12,14,12,15,12,13,
  143106. 14,15,15,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  143107. 10,12,12,11,12,12,14,13,11,12,12,13,13, 9,10,10,
  143108. 12,12,10,11,10,13,12, 9,10,11,12,13,12,13,12,14,
  143109. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,13,13,
  143110. 10,11,11,13,13,12,13,12,14,14,12,13,13,14,14,11,
  143111. 11,11,13,13,12,13,12,14,14,11,11,12,13,14,14,14,
  143112. 14,16,15,12,12,14,12,15,11,12,12,13,14,12,13,13,
  143113. 14,15,11,12,12,14,14,13,14,14,16,16,13,14,13,16,
  143114. 13,
  143115. };
  143116. static float _vq_quantthresh__44u6__p4_0[] = {
  143117. -1.5, -0.5, 0.5, 1.5,
  143118. };
  143119. static long _vq_quantmap__44u6__p4_0[] = {
  143120. 3, 1, 0, 2, 4,
  143121. };
  143122. static encode_aux_threshmatch _vq_auxt__44u6__p4_0 = {
  143123. _vq_quantthresh__44u6__p4_0,
  143124. _vq_quantmap__44u6__p4_0,
  143125. 5,
  143126. 5
  143127. };
  143128. static static_codebook _44u6__p4_0 = {
  143129. 4, 625,
  143130. _vq_lengthlist__44u6__p4_0,
  143131. 1, -533725184, 1611661312, 3, 0,
  143132. _vq_quantlist__44u6__p4_0,
  143133. NULL,
  143134. &_vq_auxt__44u6__p4_0,
  143135. NULL,
  143136. 0
  143137. };
  143138. static long _vq_quantlist__44u6__p5_0[] = {
  143139. 4,
  143140. 3,
  143141. 5,
  143142. 2,
  143143. 6,
  143144. 1,
  143145. 7,
  143146. 0,
  143147. 8,
  143148. };
  143149. static long _vq_lengthlist__44u6__p5_0[] = {
  143150. 2, 3, 3, 6, 6, 8, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  143151. 11,11, 3, 5, 5, 7, 8, 8, 8,11,11, 6, 8, 7, 9, 9,
  143152. 10, 9,12,11, 6, 7, 8, 9, 9, 9,10,11,12, 8, 8, 8,
  143153. 10, 9,12,11,13,13, 8, 8, 9, 9,10,11,12,13,13,10,
  143154. 11,11,12,12,13,13,14,14,10,10,11,11,12,13,13,14,
  143155. 14,
  143156. };
  143157. static float _vq_quantthresh__44u6__p5_0[] = {
  143158. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  143159. };
  143160. static long _vq_quantmap__44u6__p5_0[] = {
  143161. 7, 5, 3, 1, 0, 2, 4, 6,
  143162. 8,
  143163. };
  143164. static encode_aux_threshmatch _vq_auxt__44u6__p5_0 = {
  143165. _vq_quantthresh__44u6__p5_0,
  143166. _vq_quantmap__44u6__p5_0,
  143167. 9,
  143168. 9
  143169. };
  143170. static static_codebook _44u6__p5_0 = {
  143171. 2, 81,
  143172. _vq_lengthlist__44u6__p5_0,
  143173. 1, -531628032, 1611661312, 4, 0,
  143174. _vq_quantlist__44u6__p5_0,
  143175. NULL,
  143176. &_vq_auxt__44u6__p5_0,
  143177. NULL,
  143178. 0
  143179. };
  143180. static long _vq_quantlist__44u6__p6_0[] = {
  143181. 4,
  143182. 3,
  143183. 5,
  143184. 2,
  143185. 6,
  143186. 1,
  143187. 7,
  143188. 0,
  143189. 8,
  143190. };
  143191. static long _vq_lengthlist__44u6__p6_0[] = {
  143192. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  143193. 9, 9, 4, 4, 5, 6, 6, 7, 8, 9, 9, 5, 6, 6, 7, 7,
  143194. 8, 8,10,10, 5, 6, 6, 7, 7, 8, 8,10,10, 7, 8, 7,
  143195. 8, 8,10, 9,11,11, 7, 7, 8, 8, 8, 9,10,10,11, 9,
  143196. 9, 9,10,10,11,11,12,11, 9, 9, 9,10,10,11,11,11,
  143197. 12,
  143198. };
  143199. static float _vq_quantthresh__44u6__p6_0[] = {
  143200. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  143201. };
  143202. static long _vq_quantmap__44u6__p6_0[] = {
  143203. 7, 5, 3, 1, 0, 2, 4, 6,
  143204. 8,
  143205. };
  143206. static encode_aux_threshmatch _vq_auxt__44u6__p6_0 = {
  143207. _vq_quantthresh__44u6__p6_0,
  143208. _vq_quantmap__44u6__p6_0,
  143209. 9,
  143210. 9
  143211. };
  143212. static static_codebook _44u6__p6_0 = {
  143213. 2, 81,
  143214. _vq_lengthlist__44u6__p6_0,
  143215. 1, -531628032, 1611661312, 4, 0,
  143216. _vq_quantlist__44u6__p6_0,
  143217. NULL,
  143218. &_vq_auxt__44u6__p6_0,
  143219. NULL,
  143220. 0
  143221. };
  143222. static long _vq_quantlist__44u6__p7_0[] = {
  143223. 1,
  143224. 0,
  143225. 2,
  143226. };
  143227. static long _vq_lengthlist__44u6__p7_0[] = {
  143228. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 7,10,10, 8,
  143229. 10,10, 5, 8, 9, 7,10,10, 7,10, 9, 4, 8, 8, 9,11,
  143230. 11, 8,11,11, 7,11,11,10,10,13,10,13,13, 7,11,11,
  143231. 10,13,12,10,13,13, 5, 9, 8, 8,11,11, 9,11,11, 7,
  143232. 11,11,10,13,13,10,12,13, 7,11,11,10,13,13, 9,13,
  143233. 10,
  143234. };
  143235. static float _vq_quantthresh__44u6__p7_0[] = {
  143236. -5.5, 5.5,
  143237. };
  143238. static long _vq_quantmap__44u6__p7_0[] = {
  143239. 1, 0, 2,
  143240. };
  143241. static encode_aux_threshmatch _vq_auxt__44u6__p7_0 = {
  143242. _vq_quantthresh__44u6__p7_0,
  143243. _vq_quantmap__44u6__p7_0,
  143244. 3,
  143245. 3
  143246. };
  143247. static static_codebook _44u6__p7_0 = {
  143248. 4, 81,
  143249. _vq_lengthlist__44u6__p7_0,
  143250. 1, -529137664, 1618345984, 2, 0,
  143251. _vq_quantlist__44u6__p7_0,
  143252. NULL,
  143253. &_vq_auxt__44u6__p7_0,
  143254. NULL,
  143255. 0
  143256. };
  143257. static long _vq_quantlist__44u6__p7_1[] = {
  143258. 5,
  143259. 4,
  143260. 6,
  143261. 3,
  143262. 7,
  143263. 2,
  143264. 8,
  143265. 1,
  143266. 9,
  143267. 0,
  143268. 10,
  143269. };
  143270. static long _vq_lengthlist__44u6__p7_1[] = {
  143271. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 6,
  143272. 8, 8, 8, 8, 8, 8, 4, 5, 5, 6, 7, 8, 8, 8, 8, 8,
  143273. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  143274. 7, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 9, 9,
  143275. 9, 9, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  143276. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  143277. 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  143278. 8, 8, 8, 9, 9, 9, 9, 9, 9,
  143279. };
  143280. static float _vq_quantthresh__44u6__p7_1[] = {
  143281. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  143282. 3.5, 4.5,
  143283. };
  143284. static long _vq_quantmap__44u6__p7_1[] = {
  143285. 9, 7, 5, 3, 1, 0, 2, 4,
  143286. 6, 8, 10,
  143287. };
  143288. static encode_aux_threshmatch _vq_auxt__44u6__p7_1 = {
  143289. _vq_quantthresh__44u6__p7_1,
  143290. _vq_quantmap__44u6__p7_1,
  143291. 11,
  143292. 11
  143293. };
  143294. static static_codebook _44u6__p7_1 = {
  143295. 2, 121,
  143296. _vq_lengthlist__44u6__p7_1,
  143297. 1, -531365888, 1611661312, 4, 0,
  143298. _vq_quantlist__44u6__p7_1,
  143299. NULL,
  143300. &_vq_auxt__44u6__p7_1,
  143301. NULL,
  143302. 0
  143303. };
  143304. static long _vq_quantlist__44u6__p8_0[] = {
  143305. 5,
  143306. 4,
  143307. 6,
  143308. 3,
  143309. 7,
  143310. 2,
  143311. 8,
  143312. 1,
  143313. 9,
  143314. 0,
  143315. 10,
  143316. };
  143317. static long _vq_lengthlist__44u6__p8_0[] = {
  143318. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7,
  143319. 9, 9,10,10,11,11, 4, 6, 6, 7, 7, 9, 9,10,10,11,
  143320. 11, 6, 8, 8, 9, 9,10,10,11,11,12,12, 6, 8, 8, 9,
  143321. 9,10,10,11,11,12,12, 8, 9, 9,10,10,11,11,12,12,
  143322. 13,13, 8, 9, 9,10,10,11,11,12,12,13,13,10,10,10,
  143323. 11,11,13,13,13,13,15,14, 9,10,10,12,11,12,13,13,
  143324. 13,14,15,11,12,12,13,13,13,13,15,14,15,15,11,11,
  143325. 12,13,13,14,14,14,15,15,15,
  143326. };
  143327. static float _vq_quantthresh__44u6__p8_0[] = {
  143328. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  143329. 38.5, 49.5,
  143330. };
  143331. static long _vq_quantmap__44u6__p8_0[] = {
  143332. 9, 7, 5, 3, 1, 0, 2, 4,
  143333. 6, 8, 10,
  143334. };
  143335. static encode_aux_threshmatch _vq_auxt__44u6__p8_0 = {
  143336. _vq_quantthresh__44u6__p8_0,
  143337. _vq_quantmap__44u6__p8_0,
  143338. 11,
  143339. 11
  143340. };
  143341. static static_codebook _44u6__p8_0 = {
  143342. 2, 121,
  143343. _vq_lengthlist__44u6__p8_0,
  143344. 1, -524582912, 1618345984, 4, 0,
  143345. _vq_quantlist__44u6__p8_0,
  143346. NULL,
  143347. &_vq_auxt__44u6__p8_0,
  143348. NULL,
  143349. 0
  143350. };
  143351. static long _vq_quantlist__44u6__p8_1[] = {
  143352. 5,
  143353. 4,
  143354. 6,
  143355. 3,
  143356. 7,
  143357. 2,
  143358. 8,
  143359. 1,
  143360. 9,
  143361. 0,
  143362. 10,
  143363. };
  143364. static long _vq_lengthlist__44u6__p8_1[] = {
  143365. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 5, 7, 7,
  143366. 7, 7, 8, 7, 8, 8, 5, 5, 6, 6, 7, 7, 7, 7, 7, 8,
  143367. 8, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 6, 6, 7, 7,
  143368. 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  143369. 8, 8, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7,
  143370. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  143371. 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  143372. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  143373. };
  143374. static float _vq_quantthresh__44u6__p8_1[] = {
  143375. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  143376. 3.5, 4.5,
  143377. };
  143378. static long _vq_quantmap__44u6__p8_1[] = {
  143379. 9, 7, 5, 3, 1, 0, 2, 4,
  143380. 6, 8, 10,
  143381. };
  143382. static encode_aux_threshmatch _vq_auxt__44u6__p8_1 = {
  143383. _vq_quantthresh__44u6__p8_1,
  143384. _vq_quantmap__44u6__p8_1,
  143385. 11,
  143386. 11
  143387. };
  143388. static static_codebook _44u6__p8_1 = {
  143389. 2, 121,
  143390. _vq_lengthlist__44u6__p8_1,
  143391. 1, -531365888, 1611661312, 4, 0,
  143392. _vq_quantlist__44u6__p8_1,
  143393. NULL,
  143394. &_vq_auxt__44u6__p8_1,
  143395. NULL,
  143396. 0
  143397. };
  143398. static long _vq_quantlist__44u6__p9_0[] = {
  143399. 7,
  143400. 6,
  143401. 8,
  143402. 5,
  143403. 9,
  143404. 4,
  143405. 10,
  143406. 3,
  143407. 11,
  143408. 2,
  143409. 12,
  143410. 1,
  143411. 13,
  143412. 0,
  143413. 14,
  143414. };
  143415. static long _vq_lengthlist__44u6__p9_0[] = {
  143416. 1, 3, 2, 9, 8,15,15,15,15,15,15,15,15,15,15, 4,
  143417. 8, 9,13,14,14,14,14,14,14,14,14,14,14,14, 5, 8,
  143418. 9,14,14,14,14,14,14,14,14,14,14,14,14,11,14,14,
  143419. 14,14,14,14,14,14,14,14,14,14,14,14,11,14,14,14,
  143420. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  143421. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  143422. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  143423. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  143424. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  143425. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  143426. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  143427. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  143428. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  143429. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  143430. 14,
  143431. };
  143432. static float _vq_quantthresh__44u6__p9_0[] = {
  143433. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  143434. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  143435. };
  143436. static long _vq_quantmap__44u6__p9_0[] = {
  143437. 13, 11, 9, 7, 5, 3, 1, 0,
  143438. 2, 4, 6, 8, 10, 12, 14,
  143439. };
  143440. static encode_aux_threshmatch _vq_auxt__44u6__p9_0 = {
  143441. _vq_quantthresh__44u6__p9_0,
  143442. _vq_quantmap__44u6__p9_0,
  143443. 15,
  143444. 15
  143445. };
  143446. static static_codebook _44u6__p9_0 = {
  143447. 2, 225,
  143448. _vq_lengthlist__44u6__p9_0,
  143449. 1, -514071552, 1627381760, 4, 0,
  143450. _vq_quantlist__44u6__p9_0,
  143451. NULL,
  143452. &_vq_auxt__44u6__p9_0,
  143453. NULL,
  143454. 0
  143455. };
  143456. static long _vq_quantlist__44u6__p9_1[] = {
  143457. 7,
  143458. 6,
  143459. 8,
  143460. 5,
  143461. 9,
  143462. 4,
  143463. 10,
  143464. 3,
  143465. 11,
  143466. 2,
  143467. 12,
  143468. 1,
  143469. 13,
  143470. 0,
  143471. 14,
  143472. };
  143473. static long _vq_lengthlist__44u6__p9_1[] = {
  143474. 1, 4, 4, 7, 7, 8, 9, 8, 8, 9, 8, 9, 8, 9, 9, 4,
  143475. 7, 6, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 4, 7,
  143476. 6, 9, 9,10,10, 9, 9,10,10,10,10,11,11, 7, 9, 8,
  143477. 10,10,11,11,10,10,11,11,11,11,11,11, 7, 8, 9,10,
  143478. 10,11,11,10,10,11,11,11,11,11,12, 8,10,10,11,11,
  143479. 12,12,11,11,12,12,12,12,13,12, 8,10,10,11,11,12,
  143480. 11,11,11,11,12,12,12,12,13, 8, 9, 9,11,10,11,11,
  143481. 12,12,12,12,13,12,13,12, 8, 9, 9,11,11,11,11,12,
  143482. 12,12,12,12,13,13,13, 9,10,10,11,12,12,12,12,12,
  143483. 13,13,13,13,13,13, 9,10,10,11,11,12,12,12,12,13,
  143484. 13,13,13,14,13,10,10,10,12,11,12,12,13,13,13,13,
  143485. 13,13,13,13,10,10,11,11,11,12,12,13,13,13,13,13,
  143486. 13,13,13,10,11,11,12,12,13,12,12,13,13,13,13,13,
  143487. 13,14,10,11,11,12,12,13,12,13,13,13,14,13,13,14,
  143488. 13,
  143489. };
  143490. static float _vq_quantthresh__44u6__p9_1[] = {
  143491. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  143492. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  143493. };
  143494. static long _vq_quantmap__44u6__p9_1[] = {
  143495. 13, 11, 9, 7, 5, 3, 1, 0,
  143496. 2, 4, 6, 8, 10, 12, 14,
  143497. };
  143498. static encode_aux_threshmatch _vq_auxt__44u6__p9_1 = {
  143499. _vq_quantthresh__44u6__p9_1,
  143500. _vq_quantmap__44u6__p9_1,
  143501. 15,
  143502. 15
  143503. };
  143504. static static_codebook _44u6__p9_1 = {
  143505. 2, 225,
  143506. _vq_lengthlist__44u6__p9_1,
  143507. 1, -522338304, 1620115456, 4, 0,
  143508. _vq_quantlist__44u6__p9_1,
  143509. NULL,
  143510. &_vq_auxt__44u6__p9_1,
  143511. NULL,
  143512. 0
  143513. };
  143514. static long _vq_quantlist__44u6__p9_2[] = {
  143515. 8,
  143516. 7,
  143517. 9,
  143518. 6,
  143519. 10,
  143520. 5,
  143521. 11,
  143522. 4,
  143523. 12,
  143524. 3,
  143525. 13,
  143526. 2,
  143527. 14,
  143528. 1,
  143529. 15,
  143530. 0,
  143531. 16,
  143532. };
  143533. static long _vq_lengthlist__44u6__p9_2[] = {
  143534. 3, 5, 5, 7, 7, 8, 8, 8, 8, 8, 8, 9, 8, 8, 9, 9,
  143535. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  143536. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9,
  143537. 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  143538. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  143539. 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  143540. 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  143541. 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  143542. 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  143543. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9, 9, 9, 9, 9,
  143544. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 8, 9, 9, 9, 9, 9,
  143545. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  143546. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9, 9, 9, 9, 9,
  143547. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,
  143548. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10, 9, 9, 9,
  143549. 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10, 9, 9,10, 9,
  143550. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,10, 9,10,10,
  143551. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10,10, 9, 9,
  143552. 10,
  143553. };
  143554. static float _vq_quantthresh__44u6__p9_2[] = {
  143555. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  143556. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  143557. };
  143558. static long _vq_quantmap__44u6__p9_2[] = {
  143559. 15, 13, 11, 9, 7, 5, 3, 1,
  143560. 0, 2, 4, 6, 8, 10, 12, 14,
  143561. 16,
  143562. };
  143563. static encode_aux_threshmatch _vq_auxt__44u6__p9_2 = {
  143564. _vq_quantthresh__44u6__p9_2,
  143565. _vq_quantmap__44u6__p9_2,
  143566. 17,
  143567. 17
  143568. };
  143569. static static_codebook _44u6__p9_2 = {
  143570. 2, 289,
  143571. _vq_lengthlist__44u6__p9_2,
  143572. 1, -529530880, 1611661312, 5, 0,
  143573. _vq_quantlist__44u6__p9_2,
  143574. NULL,
  143575. &_vq_auxt__44u6__p9_2,
  143576. NULL,
  143577. 0
  143578. };
  143579. static long _huff_lengthlist__44u6__short[] = {
  143580. 4,11,16,13,17,13,17,16,17,17, 4, 7, 9, 9,13,10,
  143581. 16,12,16,17, 7, 6, 5, 7, 8, 9,12,12,16,17, 6, 9,
  143582. 7, 9,10,10,15,15,17,17, 6, 7, 5, 7, 5, 7, 7,10,
  143583. 16,17, 7, 9, 8, 9, 8,10,11,11,15,17, 7, 7, 7, 8,
  143584. 5, 8, 8, 9,15,17, 8, 7, 9, 9, 7, 8, 7, 2, 7,15,
  143585. 14,13,13,15, 5,10, 4, 3, 6,17,17,15,13,17, 7,11,
  143586. 7, 6, 9,16,
  143587. };
  143588. static static_codebook _huff_book__44u6__short = {
  143589. 2, 100,
  143590. _huff_lengthlist__44u6__short,
  143591. 0, 0, 0, 0, 0,
  143592. NULL,
  143593. NULL,
  143594. NULL,
  143595. NULL,
  143596. 0
  143597. };
  143598. static long _huff_lengthlist__44u7__long[] = {
  143599. 3, 9,14,13,15,14,16,13,13,14, 5, 5, 7, 7, 8, 9,
  143600. 11,10,12,15,10, 6, 5, 6, 6, 9,10,10,13,16,10, 6,
  143601. 6, 6, 6, 8, 9, 9,12,15,14, 7, 6, 6, 5, 6, 6, 8,
  143602. 12,15,10, 8, 7, 7, 6, 7, 7, 7,11,13,14,10, 9, 8,
  143603. 5, 6, 4, 5, 9,12,10, 9, 9, 8, 6, 6, 5, 3, 6,11,
  143604. 12,11,12,12,10, 9, 8, 5, 5, 8,10,11,15,13,13,13,
  143605. 12, 8, 6, 7,
  143606. };
  143607. static static_codebook _huff_book__44u7__long = {
  143608. 2, 100,
  143609. _huff_lengthlist__44u7__long,
  143610. 0, 0, 0, 0, 0,
  143611. NULL,
  143612. NULL,
  143613. NULL,
  143614. NULL,
  143615. 0
  143616. };
  143617. static long _vq_quantlist__44u7__p1_0[] = {
  143618. 1,
  143619. 0,
  143620. 2,
  143621. };
  143622. static long _vq_lengthlist__44u7__p1_0[] = {
  143623. 1, 4, 4, 4, 7, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  143624. 10,10, 5, 8, 8, 7,10,10, 8,10,10, 5, 8, 8, 8,11,
  143625. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  143626. 10,13,12,10,13,13, 5, 8, 8, 8,11,10, 8,10,11, 7,
  143627. 10,10,10,13,13,10,12,13, 8,11,11,10,13,13,10,13,
  143628. 12,
  143629. };
  143630. static float _vq_quantthresh__44u7__p1_0[] = {
  143631. -0.5, 0.5,
  143632. };
  143633. static long _vq_quantmap__44u7__p1_0[] = {
  143634. 1, 0, 2,
  143635. };
  143636. static encode_aux_threshmatch _vq_auxt__44u7__p1_0 = {
  143637. _vq_quantthresh__44u7__p1_0,
  143638. _vq_quantmap__44u7__p1_0,
  143639. 3,
  143640. 3
  143641. };
  143642. static static_codebook _44u7__p1_0 = {
  143643. 4, 81,
  143644. _vq_lengthlist__44u7__p1_0,
  143645. 1, -535822336, 1611661312, 2, 0,
  143646. _vq_quantlist__44u7__p1_0,
  143647. NULL,
  143648. &_vq_auxt__44u7__p1_0,
  143649. NULL,
  143650. 0
  143651. };
  143652. static long _vq_quantlist__44u7__p2_0[] = {
  143653. 1,
  143654. 0,
  143655. 2,
  143656. };
  143657. static long _vq_lengthlist__44u7__p2_0[] = {
  143658. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  143659. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  143660. 7, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 8, 7,
  143661. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  143662. 8, 8, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  143663. 9,
  143664. };
  143665. static float _vq_quantthresh__44u7__p2_0[] = {
  143666. -0.5, 0.5,
  143667. };
  143668. static long _vq_quantmap__44u7__p2_0[] = {
  143669. 1, 0, 2,
  143670. };
  143671. static encode_aux_threshmatch _vq_auxt__44u7__p2_0 = {
  143672. _vq_quantthresh__44u7__p2_0,
  143673. _vq_quantmap__44u7__p2_0,
  143674. 3,
  143675. 3
  143676. };
  143677. static static_codebook _44u7__p2_0 = {
  143678. 4, 81,
  143679. _vq_lengthlist__44u7__p2_0,
  143680. 1, -535822336, 1611661312, 2, 0,
  143681. _vq_quantlist__44u7__p2_0,
  143682. NULL,
  143683. &_vq_auxt__44u7__p2_0,
  143684. NULL,
  143685. 0
  143686. };
  143687. static long _vq_quantlist__44u7__p3_0[] = {
  143688. 2,
  143689. 1,
  143690. 3,
  143691. 0,
  143692. 4,
  143693. };
  143694. static long _vq_lengthlist__44u7__p3_0[] = {
  143695. 2, 5, 4, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  143696. 9, 9,13,12, 8, 9,10,12,13, 5, 7, 7,10, 9, 7, 9,
  143697. 9,11,11, 6, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  143698. 13,14, 5, 7, 7, 9, 9, 7, 9, 8,11,11, 7, 9, 9,11,
  143699. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,14,13,
  143700. 10,11,12,15,14, 9,11,11,15,14,13,14,14,16,16,12,
  143701. 13,14,17,16, 8,10,10,13,13, 9,11,11,14,15,10,11,
  143702. 12,14,15,12,14,13,16,16,13,14,15,15,17, 5, 7, 7,
  143703. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,12,11,15,
  143704. 14,10,11,12,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  143705. 9,11,11,13,13,11,13,13,14,17,11,13,13,15,16, 6,
  143706. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,13,11,13,
  143707. 12,16,14,11,13,13,16,16,10,12,12,15,15,11,13,13,
  143708. 16,16,11,13,13,16,15,14,16,17,17,19,14,16,16,18,
  143709. 0, 9,11,11,14,15,10,13,12,16,15,11,13,13,16,16,
  143710. 14,15,14, 0,16,14,16,16,18, 0, 5, 7, 7,10,10, 7,
  143711. 9, 9,12,11, 7, 9, 9,11,12,10,11,11,15,14,10,11,
  143712. 12,14,14, 6, 9, 9,11,11, 9,11,11,13,13, 8,10,11,
  143713. 12,13,11,13,13,17,15,11,12,13,14,15, 7, 9, 9,11,
  143714. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,12,16,16,
  143715. 11,13,13,15,14, 9,11,11,14,15,11,13,13,16,15,10,
  143716. 12,13,16,16,15,16,16, 0, 0,14,13,15,16,18,10,11,
  143717. 11,15,15,11,13,14,16,18,11,13,13,16,15,15,16,16,
  143718. 19, 0,14,15,15,16,16, 8,10,10,13,13,10,12,11,16,
  143719. 15,10,11,11,16,15,13,15,16,18, 0,13,14,15,17,17,
  143720. 9,11,11,15,15,11,13,13,16,18,11,13,13,16,17,15,
  143721. 16,16, 0, 0,15,18,16, 0,17, 9,11,11,15,15,11,13,
  143722. 12,17,15,11,13,14,16,17,15,18,15, 0,17,15,16,16,
  143723. 18,19,13,15,14, 0,18,14,16,16,19,18,14,16,15,19,
  143724. 19,16,18,19, 0, 0,16,17, 0, 0, 0,12,14,14,17,17,
  143725. 13,16,14, 0,18,14,16,15,18, 0,16,18,16,19,17,18,
  143726. 19,17, 0, 0, 8,10,10,14,14, 9,12,11,15,15,10,11,
  143727. 12,15,17,13,15,15,18,16,14,16,15,18,17, 9,11,11,
  143728. 16,15,11,13,13, 0,16,11,12,13,16,15,15,16,16, 0,
  143729. 17,15,15,16,18,17, 9,12,11,15,17,11,13,13,16,16,
  143730. 11,14,13,16,16,15,15,16,18,19,16,18,16, 0, 0,12,
  143731. 14,14, 0,16,14,16,16, 0,18,13,14,15,16, 0,17,16,
  143732. 18, 0, 0,16,16,17,19, 0,13,14,14,17, 0,14,17,16,
  143733. 0,19,14,15,15,18,19,17,16,18, 0, 0,15,19,16, 0,
  143734. 0,
  143735. };
  143736. static float _vq_quantthresh__44u7__p3_0[] = {
  143737. -1.5, -0.5, 0.5, 1.5,
  143738. };
  143739. static long _vq_quantmap__44u7__p3_0[] = {
  143740. 3, 1, 0, 2, 4,
  143741. };
  143742. static encode_aux_threshmatch _vq_auxt__44u7__p3_0 = {
  143743. _vq_quantthresh__44u7__p3_0,
  143744. _vq_quantmap__44u7__p3_0,
  143745. 5,
  143746. 5
  143747. };
  143748. static static_codebook _44u7__p3_0 = {
  143749. 4, 625,
  143750. _vq_lengthlist__44u7__p3_0,
  143751. 1, -533725184, 1611661312, 3, 0,
  143752. _vq_quantlist__44u7__p3_0,
  143753. NULL,
  143754. &_vq_auxt__44u7__p3_0,
  143755. NULL,
  143756. 0
  143757. };
  143758. static long _vq_quantlist__44u7__p4_0[] = {
  143759. 2,
  143760. 1,
  143761. 3,
  143762. 0,
  143763. 4,
  143764. };
  143765. static long _vq_lengthlist__44u7__p4_0[] = {
  143766. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  143767. 9, 9,11,11, 8, 9, 9,10,11, 6, 7, 7, 9, 9, 7, 8,
  143768. 8,10,10, 6, 7, 8, 9,10, 9,10,10,12,12, 9, 9,10,
  143769. 11,12, 6, 7, 7, 9, 9, 6, 8, 7,10, 9, 7, 8, 8,10,
  143770. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,11,11,
  143771. 9,10,10,12,12, 9,10,10,12,12,11,12,12,13,14,11,
  143772. 11,12,13,13, 8, 9, 9,11,11, 9,10,10,12,11, 9,10,
  143773. 10,12,12,11,12,11,13,13,11,12,12,13,13, 6, 7, 7,
  143774. 9, 9, 7, 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,
  143775. 11, 9,10,10,12,12, 7, 8, 8,10,10, 8, 8, 9,11,11,
  143776. 8, 9, 9,11,11,10,11,11,12,12,10,10,11,12,13, 6,
  143777. 7, 7,10,10, 7, 9, 8,11,10, 8, 8, 9,10,11,10,11,
  143778. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  143779. 13,13,10,11,11,13,12,12,12,13,13,14,12,12,13,14,
  143780. 14, 9,10,10,12,12, 9,10,10,12,12,10,11,11,13,13,
  143781. 11,12,11,14,12,12,13,13,14,14, 6, 7, 7, 9, 9, 7,
  143782. 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,11, 9,10,
  143783. 10,11,12, 6, 7, 7,10,10, 8, 9, 8,11,10, 7, 8, 9,
  143784. 10,11,10,11,11,13,12,10,10,11,11,13, 7, 8, 8,10,
  143785. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,10,13,12,
  143786. 10,11,11,12,12, 9,10,10,12,12,10,11,11,13,12, 9,
  143787. 10,10,12,13,12,13,12,14,14,11,11,12,12,14, 9,10,
  143788. 10,12,12,10,11,11,13,13,10,11,11,13,13,12,13,12,
  143789. 14,14,12,13,12,14,13, 8, 9, 9,11,11, 9,10,10,12,
  143790. 12, 9,10,10,12,12,11,12,12,14,13,11,12,12,13,13,
  143791. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,12,12,
  143792. 13,13,14,14,12,12,13,14,14, 9,10,10,12,12, 9,11,
  143793. 10,13,12,10,10,11,12,13,11,13,12,14,13,12,12,13,
  143794. 14,14,11,12,12,13,13,11,12,13,14,14,12,13,13,14,
  143795. 14,13,13,14,14,16,13,14,14,16,16,11,11,11,13,13,
  143796. 11,12,11,14,13,12,12,13,14,15,13,14,12,16,13,14,
  143797. 14,14,15,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  143798. 10,12,12,11,12,12,14,13,11,12,12,13,14, 9,10,10,
  143799. 12,12,10,11,10,13,12, 9,10,11,12,13,12,13,12,14,
  143800. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,12,13,
  143801. 10,11,11,13,13,12,13,12,14,14,12,13,13,14,14,11,
  143802. 12,12,13,13,12,13,12,14,14,11,11,12,13,14,13,15,
  143803. 14,16,15,13,12,14,13,16,11,12,12,13,13,12,13,13,
  143804. 14,14,12,12,12,14,14,13,14,14,15,15,13,14,13,16,
  143805. 14,
  143806. };
  143807. static float _vq_quantthresh__44u7__p4_0[] = {
  143808. -1.5, -0.5, 0.5, 1.5,
  143809. };
  143810. static long _vq_quantmap__44u7__p4_0[] = {
  143811. 3, 1, 0, 2, 4,
  143812. };
  143813. static encode_aux_threshmatch _vq_auxt__44u7__p4_0 = {
  143814. _vq_quantthresh__44u7__p4_0,
  143815. _vq_quantmap__44u7__p4_0,
  143816. 5,
  143817. 5
  143818. };
  143819. static static_codebook _44u7__p4_0 = {
  143820. 4, 625,
  143821. _vq_lengthlist__44u7__p4_0,
  143822. 1, -533725184, 1611661312, 3, 0,
  143823. _vq_quantlist__44u7__p4_0,
  143824. NULL,
  143825. &_vq_auxt__44u7__p4_0,
  143826. NULL,
  143827. 0
  143828. };
  143829. static long _vq_quantlist__44u7__p5_0[] = {
  143830. 4,
  143831. 3,
  143832. 5,
  143833. 2,
  143834. 6,
  143835. 1,
  143836. 7,
  143837. 0,
  143838. 8,
  143839. };
  143840. static long _vq_lengthlist__44u7__p5_0[] = {
  143841. 2, 3, 3, 6, 6, 7, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  143842. 11,11, 3, 5, 5, 7, 7, 8, 9,11,11, 6, 8, 7, 9, 9,
  143843. 10,10,12,12, 6, 7, 8, 9,10,10,10,12,12, 8, 8, 8,
  143844. 10,10,12,11,13,13, 8, 8, 9,10,10,11,11,13,13,10,
  143845. 11,11,12,12,13,13,14,14,10,11,11,12,12,13,13,14,
  143846. 14,
  143847. };
  143848. static float _vq_quantthresh__44u7__p5_0[] = {
  143849. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  143850. };
  143851. static long _vq_quantmap__44u7__p5_0[] = {
  143852. 7, 5, 3, 1, 0, 2, 4, 6,
  143853. 8,
  143854. };
  143855. static encode_aux_threshmatch _vq_auxt__44u7__p5_0 = {
  143856. _vq_quantthresh__44u7__p5_0,
  143857. _vq_quantmap__44u7__p5_0,
  143858. 9,
  143859. 9
  143860. };
  143861. static static_codebook _44u7__p5_0 = {
  143862. 2, 81,
  143863. _vq_lengthlist__44u7__p5_0,
  143864. 1, -531628032, 1611661312, 4, 0,
  143865. _vq_quantlist__44u7__p5_0,
  143866. NULL,
  143867. &_vq_auxt__44u7__p5_0,
  143868. NULL,
  143869. 0
  143870. };
  143871. static long _vq_quantlist__44u7__p6_0[] = {
  143872. 4,
  143873. 3,
  143874. 5,
  143875. 2,
  143876. 6,
  143877. 1,
  143878. 7,
  143879. 0,
  143880. 8,
  143881. };
  143882. static long _vq_lengthlist__44u7__p6_0[] = {
  143883. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 8, 7,
  143884. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  143885. 8, 8,10,10, 5, 6, 6, 7, 7, 8, 8,10,10, 7, 8, 7,
  143886. 8, 8,10, 9,11,11, 7, 7, 8, 8, 8, 9,10,11,11, 9,
  143887. 9, 9,10,10,11,10,12,11, 9, 9, 9,10,10,11,11,11,
  143888. 12,
  143889. };
  143890. static float _vq_quantthresh__44u7__p6_0[] = {
  143891. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  143892. };
  143893. static long _vq_quantmap__44u7__p6_0[] = {
  143894. 7, 5, 3, 1, 0, 2, 4, 6,
  143895. 8,
  143896. };
  143897. static encode_aux_threshmatch _vq_auxt__44u7__p6_0 = {
  143898. _vq_quantthresh__44u7__p6_0,
  143899. _vq_quantmap__44u7__p6_0,
  143900. 9,
  143901. 9
  143902. };
  143903. static static_codebook _44u7__p6_0 = {
  143904. 2, 81,
  143905. _vq_lengthlist__44u7__p6_0,
  143906. 1, -531628032, 1611661312, 4, 0,
  143907. _vq_quantlist__44u7__p6_0,
  143908. NULL,
  143909. &_vq_auxt__44u7__p6_0,
  143910. NULL,
  143911. 0
  143912. };
  143913. static long _vq_quantlist__44u7__p7_0[] = {
  143914. 1,
  143915. 0,
  143916. 2,
  143917. };
  143918. static long _vq_lengthlist__44u7__p7_0[] = {
  143919. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 8, 9, 9, 7,
  143920. 10,10, 5, 8, 9, 7, 9,10, 8, 9, 9, 4, 9, 9, 9,11,
  143921. 10, 8,10,10, 7,11,10,10,10,12,10,12,12, 7,10,10,
  143922. 10,12,11,10,12,12, 5, 9, 9, 8,10,10, 9,11,11, 7,
  143923. 11,10,10,12,12,10,11,12, 7,10,11,10,12,12,10,12,
  143924. 10,
  143925. };
  143926. static float _vq_quantthresh__44u7__p7_0[] = {
  143927. -5.5, 5.5,
  143928. };
  143929. static long _vq_quantmap__44u7__p7_0[] = {
  143930. 1, 0, 2,
  143931. };
  143932. static encode_aux_threshmatch _vq_auxt__44u7__p7_0 = {
  143933. _vq_quantthresh__44u7__p7_0,
  143934. _vq_quantmap__44u7__p7_0,
  143935. 3,
  143936. 3
  143937. };
  143938. static static_codebook _44u7__p7_0 = {
  143939. 4, 81,
  143940. _vq_lengthlist__44u7__p7_0,
  143941. 1, -529137664, 1618345984, 2, 0,
  143942. _vq_quantlist__44u7__p7_0,
  143943. NULL,
  143944. &_vq_auxt__44u7__p7_0,
  143945. NULL,
  143946. 0
  143947. };
  143948. static long _vq_quantlist__44u7__p7_1[] = {
  143949. 5,
  143950. 4,
  143951. 6,
  143952. 3,
  143953. 7,
  143954. 2,
  143955. 8,
  143956. 1,
  143957. 9,
  143958. 0,
  143959. 10,
  143960. };
  143961. static long _vq_lengthlist__44u7__p7_1[] = {
  143962. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 6, 6,
  143963. 8, 7, 8, 8, 8, 8, 4, 5, 5, 6, 6, 7, 8, 8, 8, 8,
  143964. 8, 6, 7, 6, 7, 7, 8, 8, 9, 9, 9, 9, 6, 6, 7, 7,
  143965. 7, 8, 8, 9, 9, 9, 9, 7, 8, 7, 8, 8, 9, 9, 9, 9,
  143966. 9, 9, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8,
  143967. 9, 9, 9, 9,10, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  143968. 9, 9,10, 8, 8, 8, 9, 9, 9, 9,10, 9,10,10, 8, 8,
  143969. 8, 9, 9, 9, 9, 9,10,10,10,
  143970. };
  143971. static float _vq_quantthresh__44u7__p7_1[] = {
  143972. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  143973. 3.5, 4.5,
  143974. };
  143975. static long _vq_quantmap__44u7__p7_1[] = {
  143976. 9, 7, 5, 3, 1, 0, 2, 4,
  143977. 6, 8, 10,
  143978. };
  143979. static encode_aux_threshmatch _vq_auxt__44u7__p7_1 = {
  143980. _vq_quantthresh__44u7__p7_1,
  143981. _vq_quantmap__44u7__p7_1,
  143982. 11,
  143983. 11
  143984. };
  143985. static static_codebook _44u7__p7_1 = {
  143986. 2, 121,
  143987. _vq_lengthlist__44u7__p7_1,
  143988. 1, -531365888, 1611661312, 4, 0,
  143989. _vq_quantlist__44u7__p7_1,
  143990. NULL,
  143991. &_vq_auxt__44u7__p7_1,
  143992. NULL,
  143993. 0
  143994. };
  143995. static long _vq_quantlist__44u7__p8_0[] = {
  143996. 5,
  143997. 4,
  143998. 6,
  143999. 3,
  144000. 7,
  144001. 2,
  144002. 8,
  144003. 1,
  144004. 9,
  144005. 0,
  144006. 10,
  144007. };
  144008. static long _vq_lengthlist__44u7__p8_0[] = {
  144009. 1, 4, 4, 6, 6, 8, 8,10,10,11,11, 4, 6, 6, 7, 7,
  144010. 9, 9,11,10,12,12, 5, 6, 5, 7, 7, 9, 9,10,11,12,
  144011. 12, 6, 7, 7, 8, 8,10,10,11,11,13,13, 6, 7, 7, 8,
  144012. 8,10,10,11,12,13,13, 8, 9, 9,10,10,11,11,12,12,
  144013. 14,14, 8, 9, 9,10,10,11,11,12,12,14,14,10,10,10,
  144014. 11,11,13,12,14,14,15,15,10,10,10,12,12,13,13,14,
  144015. 14,15,15,11,12,12,13,13,14,14,15,14,16,15,11,12,
  144016. 12,13,13,14,14,15,15,15,16,
  144017. };
  144018. static float _vq_quantthresh__44u7__p8_0[] = {
  144019. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  144020. 38.5, 49.5,
  144021. };
  144022. static long _vq_quantmap__44u7__p8_0[] = {
  144023. 9, 7, 5, 3, 1, 0, 2, 4,
  144024. 6, 8, 10,
  144025. };
  144026. static encode_aux_threshmatch _vq_auxt__44u7__p8_0 = {
  144027. _vq_quantthresh__44u7__p8_0,
  144028. _vq_quantmap__44u7__p8_0,
  144029. 11,
  144030. 11
  144031. };
  144032. static static_codebook _44u7__p8_0 = {
  144033. 2, 121,
  144034. _vq_lengthlist__44u7__p8_0,
  144035. 1, -524582912, 1618345984, 4, 0,
  144036. _vq_quantlist__44u7__p8_0,
  144037. NULL,
  144038. &_vq_auxt__44u7__p8_0,
  144039. NULL,
  144040. 0
  144041. };
  144042. static long _vq_quantlist__44u7__p8_1[] = {
  144043. 5,
  144044. 4,
  144045. 6,
  144046. 3,
  144047. 7,
  144048. 2,
  144049. 8,
  144050. 1,
  144051. 9,
  144052. 0,
  144053. 10,
  144054. };
  144055. static long _vq_lengthlist__44u7__p8_1[] = {
  144056. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  144057. 7, 7, 7, 7, 7, 7, 5, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  144058. 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 6, 7, 7, 7,
  144059. 7, 7, 7, 7, 7, 8, 8, 7, 7, 7, 7, 7, 8, 7, 8, 8,
  144060. 8, 8, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  144061. 7, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8,
  144062. 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 7,
  144063. 7, 8, 8, 8, 8, 8, 8, 8, 8,
  144064. };
  144065. static float _vq_quantthresh__44u7__p8_1[] = {
  144066. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  144067. 3.5, 4.5,
  144068. };
  144069. static long _vq_quantmap__44u7__p8_1[] = {
  144070. 9, 7, 5, 3, 1, 0, 2, 4,
  144071. 6, 8, 10,
  144072. };
  144073. static encode_aux_threshmatch _vq_auxt__44u7__p8_1 = {
  144074. _vq_quantthresh__44u7__p8_1,
  144075. _vq_quantmap__44u7__p8_1,
  144076. 11,
  144077. 11
  144078. };
  144079. static static_codebook _44u7__p8_1 = {
  144080. 2, 121,
  144081. _vq_lengthlist__44u7__p8_1,
  144082. 1, -531365888, 1611661312, 4, 0,
  144083. _vq_quantlist__44u7__p8_1,
  144084. NULL,
  144085. &_vq_auxt__44u7__p8_1,
  144086. NULL,
  144087. 0
  144088. };
  144089. static long _vq_quantlist__44u7__p9_0[] = {
  144090. 5,
  144091. 4,
  144092. 6,
  144093. 3,
  144094. 7,
  144095. 2,
  144096. 8,
  144097. 1,
  144098. 9,
  144099. 0,
  144100. 10,
  144101. };
  144102. static long _vq_lengthlist__44u7__p9_0[] = {
  144103. 1, 3, 3,10,10,10,10,10,10,10,10, 4,10,10,10,10,
  144104. 10,10,10,10,10,10, 4,10,10,10,10,10,10,10,10,10,
  144105. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144106. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144107. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144108. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144109. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  144110. 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144111. };
  144112. static float _vq_quantthresh__44u7__p9_0[] = {
  144113. -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5, 1592.5,
  144114. 2229.5, 2866.5,
  144115. };
  144116. static long _vq_quantmap__44u7__p9_0[] = {
  144117. 9, 7, 5, 3, 1, 0, 2, 4,
  144118. 6, 8, 10,
  144119. };
  144120. static encode_aux_threshmatch _vq_auxt__44u7__p9_0 = {
  144121. _vq_quantthresh__44u7__p9_0,
  144122. _vq_quantmap__44u7__p9_0,
  144123. 11,
  144124. 11
  144125. };
  144126. static static_codebook _44u7__p9_0 = {
  144127. 2, 121,
  144128. _vq_lengthlist__44u7__p9_0,
  144129. 1, -512171520, 1630791680, 4, 0,
  144130. _vq_quantlist__44u7__p9_0,
  144131. NULL,
  144132. &_vq_auxt__44u7__p9_0,
  144133. NULL,
  144134. 0
  144135. };
  144136. static long _vq_quantlist__44u7__p9_1[] = {
  144137. 6,
  144138. 5,
  144139. 7,
  144140. 4,
  144141. 8,
  144142. 3,
  144143. 9,
  144144. 2,
  144145. 10,
  144146. 1,
  144147. 11,
  144148. 0,
  144149. 12,
  144150. };
  144151. static long _vq_lengthlist__44u7__p9_1[] = {
  144152. 1, 4, 4, 6, 5, 8, 6, 9, 8,10, 9,11,10, 4, 6, 6,
  144153. 8, 8, 9, 9,11,10,11,11,11,11, 4, 6, 6, 8, 8,10,
  144154. 9,11,11,11,11,11,12, 6, 8, 8,10,10,11,11,12,12,
  144155. 13,12,13,13, 6, 8, 8,10,10,11,11,12,12,12,13,14,
  144156. 13, 8,10,10,11,11,12,13,14,14,14,14,15,15, 8,10,
  144157. 10,11,12,12,13,13,14,14,14,14,15, 9,11,11,13,13,
  144158. 14,14,15,14,16,15,17,15, 9,11,11,12,13,14,14,15,
  144159. 14,15,15,15,16,10,12,12,13,14,15,15,15,15,16,17,
  144160. 16,17,10,13,12,13,14,14,16,16,16,16,15,16,17,11,
  144161. 13,13,14,15,14,17,15,16,17,17,17,17,11,13,13,14,
  144162. 15,15,15,15,17,17,16,17,16,
  144163. };
  144164. static float _vq_quantthresh__44u7__p9_1[] = {
  144165. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  144166. 122.5, 171.5, 220.5, 269.5,
  144167. };
  144168. static long _vq_quantmap__44u7__p9_1[] = {
  144169. 11, 9, 7, 5, 3, 1, 0, 2,
  144170. 4, 6, 8, 10, 12,
  144171. };
  144172. static encode_aux_threshmatch _vq_auxt__44u7__p9_1 = {
  144173. _vq_quantthresh__44u7__p9_1,
  144174. _vq_quantmap__44u7__p9_1,
  144175. 13,
  144176. 13
  144177. };
  144178. static static_codebook _44u7__p9_1 = {
  144179. 2, 169,
  144180. _vq_lengthlist__44u7__p9_1,
  144181. 1, -518889472, 1622704128, 4, 0,
  144182. _vq_quantlist__44u7__p9_1,
  144183. NULL,
  144184. &_vq_auxt__44u7__p9_1,
  144185. NULL,
  144186. 0
  144187. };
  144188. static long _vq_quantlist__44u7__p9_2[] = {
  144189. 24,
  144190. 23,
  144191. 25,
  144192. 22,
  144193. 26,
  144194. 21,
  144195. 27,
  144196. 20,
  144197. 28,
  144198. 19,
  144199. 29,
  144200. 18,
  144201. 30,
  144202. 17,
  144203. 31,
  144204. 16,
  144205. 32,
  144206. 15,
  144207. 33,
  144208. 14,
  144209. 34,
  144210. 13,
  144211. 35,
  144212. 12,
  144213. 36,
  144214. 11,
  144215. 37,
  144216. 10,
  144217. 38,
  144218. 9,
  144219. 39,
  144220. 8,
  144221. 40,
  144222. 7,
  144223. 41,
  144224. 6,
  144225. 42,
  144226. 5,
  144227. 43,
  144228. 4,
  144229. 44,
  144230. 3,
  144231. 45,
  144232. 2,
  144233. 46,
  144234. 1,
  144235. 47,
  144236. 0,
  144237. 48,
  144238. };
  144239. static long _vq_lengthlist__44u7__p9_2[] = {
  144240. 2, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6,
  144241. 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  144242. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  144243. 8,
  144244. };
  144245. static float _vq_quantthresh__44u7__p9_2[] = {
  144246. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  144247. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  144248. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  144249. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  144250. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  144251. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  144252. };
  144253. static long _vq_quantmap__44u7__p9_2[] = {
  144254. 47, 45, 43, 41, 39, 37, 35, 33,
  144255. 31, 29, 27, 25, 23, 21, 19, 17,
  144256. 15, 13, 11, 9, 7, 5, 3, 1,
  144257. 0, 2, 4, 6, 8, 10, 12, 14,
  144258. 16, 18, 20, 22, 24, 26, 28, 30,
  144259. 32, 34, 36, 38, 40, 42, 44, 46,
  144260. 48,
  144261. };
  144262. static encode_aux_threshmatch _vq_auxt__44u7__p9_2 = {
  144263. _vq_quantthresh__44u7__p9_2,
  144264. _vq_quantmap__44u7__p9_2,
  144265. 49,
  144266. 49
  144267. };
  144268. static static_codebook _44u7__p9_2 = {
  144269. 1, 49,
  144270. _vq_lengthlist__44u7__p9_2,
  144271. 1, -526909440, 1611661312, 6, 0,
  144272. _vq_quantlist__44u7__p9_2,
  144273. NULL,
  144274. &_vq_auxt__44u7__p9_2,
  144275. NULL,
  144276. 0
  144277. };
  144278. static long _huff_lengthlist__44u7__short[] = {
  144279. 5,12,17,16,16,17,17,17,17,17, 4, 7,11,11,12, 9,
  144280. 17,10,17,17, 7, 7, 8, 9, 7, 9,11,10,15,17, 7, 9,
  144281. 10,11,10,12,14,12,16,17, 7, 8, 5, 7, 4, 7, 7, 8,
  144282. 16,16, 6,10, 9,10, 7,10,11,11,16,17, 6, 8, 8, 9,
  144283. 5, 7, 5, 8,16,17, 5, 5, 8, 7, 6, 7, 7, 6, 6,14,
  144284. 12,10,12,11, 7,11, 4, 4, 2, 7,17,15,15,15, 8,15,
  144285. 6, 8, 5, 9,
  144286. };
  144287. static static_codebook _huff_book__44u7__short = {
  144288. 2, 100,
  144289. _huff_lengthlist__44u7__short,
  144290. 0, 0, 0, 0, 0,
  144291. NULL,
  144292. NULL,
  144293. NULL,
  144294. NULL,
  144295. 0
  144296. };
  144297. static long _huff_lengthlist__44u8__long[] = {
  144298. 3, 9,13,14,14,15,14,14,15,15, 5, 4, 6, 8,10,12,
  144299. 12,14,15,15, 9, 5, 4, 5, 8,10,11,13,16,16,10, 7,
  144300. 4, 3, 5, 7, 9,11,13,13,10, 9, 7, 4, 4, 6, 8,10,
  144301. 12,14,13,11, 9, 6, 5, 5, 6, 8,12,14,13,11,10, 8,
  144302. 7, 6, 6, 7,10,14,13,11,12,10, 8, 7, 6, 6, 9,13,
  144303. 12,11,14,12,11, 9, 8, 7, 9,11,11,12,14,13,14,11,
  144304. 10, 8, 8, 9,
  144305. };
  144306. static static_codebook _huff_book__44u8__long = {
  144307. 2, 100,
  144308. _huff_lengthlist__44u8__long,
  144309. 0, 0, 0, 0, 0,
  144310. NULL,
  144311. NULL,
  144312. NULL,
  144313. NULL,
  144314. 0
  144315. };
  144316. static long _huff_lengthlist__44u8__short[] = {
  144317. 6,14,18,18,17,17,17,17,17,17, 4, 7, 9, 9,10,13,
  144318. 15,17,17,17, 6, 7, 5, 6, 8,11,16,17,16,17, 5, 7,
  144319. 5, 4, 6,10,14,17,17,17, 6, 6, 6, 5, 7,10,13,16,
  144320. 17,17, 7, 6, 7, 7, 7, 8, 7,10,15,16,12, 9, 9, 6,
  144321. 6, 5, 3, 5,11,15,14,14,13, 5, 5, 7, 3, 4, 8,15,
  144322. 17,17,13, 7, 7,10, 6, 6,10,15,17,17,16,10,11,14,
  144323. 10,10,15,17,
  144324. };
  144325. static static_codebook _huff_book__44u8__short = {
  144326. 2, 100,
  144327. _huff_lengthlist__44u8__short,
  144328. 0, 0, 0, 0, 0,
  144329. NULL,
  144330. NULL,
  144331. NULL,
  144332. NULL,
  144333. 0
  144334. };
  144335. static long _vq_quantlist__44u8_p1_0[] = {
  144336. 1,
  144337. 0,
  144338. 2,
  144339. };
  144340. static long _vq_lengthlist__44u8_p1_0[] = {
  144341. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 8, 9, 9, 7,
  144342. 9, 9, 5, 7, 7, 7, 9, 9, 8, 9, 9, 5, 7, 7, 7, 9,
  144343. 9, 7, 9, 9, 7, 9, 9, 9,10,11, 9,11,10, 7, 9, 9,
  144344. 9,11,10, 9,10,11, 5, 7, 7, 7, 9, 9, 7, 9, 9, 7,
  144345. 9, 9, 9,11,10, 9,10,10, 8, 9, 9, 9,11,11, 9,11,
  144346. 10,
  144347. };
  144348. static float _vq_quantthresh__44u8_p1_0[] = {
  144349. -0.5, 0.5,
  144350. };
  144351. static long _vq_quantmap__44u8_p1_0[] = {
  144352. 1, 0, 2,
  144353. };
  144354. static encode_aux_threshmatch _vq_auxt__44u8_p1_0 = {
  144355. _vq_quantthresh__44u8_p1_0,
  144356. _vq_quantmap__44u8_p1_0,
  144357. 3,
  144358. 3
  144359. };
  144360. static static_codebook _44u8_p1_0 = {
  144361. 4, 81,
  144362. _vq_lengthlist__44u8_p1_0,
  144363. 1, -535822336, 1611661312, 2, 0,
  144364. _vq_quantlist__44u8_p1_0,
  144365. NULL,
  144366. &_vq_auxt__44u8_p1_0,
  144367. NULL,
  144368. 0
  144369. };
  144370. static long _vq_quantlist__44u8_p2_0[] = {
  144371. 2,
  144372. 1,
  144373. 3,
  144374. 0,
  144375. 4,
  144376. };
  144377. static long _vq_lengthlist__44u8_p2_0[] = {
  144378. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  144379. 9, 9,11,11, 8, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  144380. 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,10,
  144381. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  144382. 10, 9,10, 9,12,11, 9,10,10,12,12, 8, 9, 9,12,11,
  144383. 9,10,10,12,12, 9,10,10,12,12,11,12,12,14,14,11,
  144384. 11,12,13,14, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  144385. 10,12,12,11,12,11,13,13,11,12,12,14,14, 5, 7, 7,
  144386. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  144387. 12, 9,10,10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  144388. 8, 9, 9,11,11,10,11,11,12,13,10,11,11,12,13, 6,
  144389. 8, 8,10,10, 8, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  144390. 10,13,12,10,11,11,13,13, 9,10,10,12,12,10,11,11,
  144391. 13,13,10,11,11,13,13,12,12,13,13,14,12,13,13,14,
  144392. 14, 9,10,10,12,12,10,11,10,13,12,10,11,11,13,13,
  144393. 11,13,12,14,13,12,13,13,14,14, 5, 7, 7, 9, 9, 7,
  144394. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,
  144395. 10,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11, 8, 8, 9,
  144396. 10,11,10,11,11,13,13,10,10,11,12,13, 7, 8, 8,10,
  144397. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,13,
  144398. 10,11,11,13,12, 9,10,10,12,12,10,11,11,13,13,10,
  144399. 10,11,12,13,12,13,13,14,14,12,12,13,13,14, 9,10,
  144400. 10,12,12,10,11,11,13,13,10,11,11,13,13,12,13,13,
  144401. 15,14,12,13,13,14,13, 8, 9, 9,11,11, 9,10,10,12,
  144402. 12, 9,10,10,12,12,12,12,12,14,13,11,12,12,14,14,
  144403. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,13,12,
  144404. 13,13,14,15,12,13,13,14,15, 9,10,10,12,12,10,11,
  144405. 10,13,12,10,11,11,13,13,12,13,12,15,14,12,13,13,
  144406. 14,15,11,12,12,14,14,12,13,13,14,14,12,13,13,15,
  144407. 14,14,14,14,14,16,14,14,15,16,16,11,12,12,14,14,
  144408. 11,12,12,14,14,12,13,13,14,15,13,14,13,16,14,14,
  144409. 14,14,16,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  144410. 10,12,12,11,12,12,14,13,11,12,12,14,14, 9,10,10,
  144411. 12,12,10,11,11,13,13,10,10,11,12,13,12,13,13,15,
  144412. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,13,13,
  144413. 10,11,11,13,13,12,13,13,14,14,12,13,13,15,14,11,
  144414. 12,12,14,13,12,13,13,15,14,11,12,12,13,14,14,15,
  144415. 14,16,15,13,13,14,13,16,11,12,12,14,14,12,13,13,
  144416. 14,15,12,13,12,15,14,14,14,14,16,15,14,15,13,16,
  144417. 14,
  144418. };
  144419. static float _vq_quantthresh__44u8_p2_0[] = {
  144420. -1.5, -0.5, 0.5, 1.5,
  144421. };
  144422. static long _vq_quantmap__44u8_p2_0[] = {
  144423. 3, 1, 0, 2, 4,
  144424. };
  144425. static encode_aux_threshmatch _vq_auxt__44u8_p2_0 = {
  144426. _vq_quantthresh__44u8_p2_0,
  144427. _vq_quantmap__44u8_p2_0,
  144428. 5,
  144429. 5
  144430. };
  144431. static static_codebook _44u8_p2_0 = {
  144432. 4, 625,
  144433. _vq_lengthlist__44u8_p2_0,
  144434. 1, -533725184, 1611661312, 3, 0,
  144435. _vq_quantlist__44u8_p2_0,
  144436. NULL,
  144437. &_vq_auxt__44u8_p2_0,
  144438. NULL,
  144439. 0
  144440. };
  144441. static long _vq_quantlist__44u8_p3_0[] = {
  144442. 4,
  144443. 3,
  144444. 5,
  144445. 2,
  144446. 6,
  144447. 1,
  144448. 7,
  144449. 0,
  144450. 8,
  144451. };
  144452. static long _vq_lengthlist__44u8_p3_0[] = {
  144453. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  144454. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  144455. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8,10,10, 7, 7, 7,
  144456. 8, 8, 9, 9,11,10, 7, 7, 7, 8, 8, 9, 9,10,11, 9,
  144457. 9, 9,10,10,11,10,12,11, 9, 9, 9, 9,10,11,11,11,
  144458. 12,
  144459. };
  144460. static float _vq_quantthresh__44u8_p3_0[] = {
  144461. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  144462. };
  144463. static long _vq_quantmap__44u8_p3_0[] = {
  144464. 7, 5, 3, 1, 0, 2, 4, 6,
  144465. 8,
  144466. };
  144467. static encode_aux_threshmatch _vq_auxt__44u8_p3_0 = {
  144468. _vq_quantthresh__44u8_p3_0,
  144469. _vq_quantmap__44u8_p3_0,
  144470. 9,
  144471. 9
  144472. };
  144473. static static_codebook _44u8_p3_0 = {
  144474. 2, 81,
  144475. _vq_lengthlist__44u8_p3_0,
  144476. 1, -531628032, 1611661312, 4, 0,
  144477. _vq_quantlist__44u8_p3_0,
  144478. NULL,
  144479. &_vq_auxt__44u8_p3_0,
  144480. NULL,
  144481. 0
  144482. };
  144483. static long _vq_quantlist__44u8_p4_0[] = {
  144484. 8,
  144485. 7,
  144486. 9,
  144487. 6,
  144488. 10,
  144489. 5,
  144490. 11,
  144491. 4,
  144492. 12,
  144493. 3,
  144494. 13,
  144495. 2,
  144496. 14,
  144497. 1,
  144498. 15,
  144499. 0,
  144500. 16,
  144501. };
  144502. static long _vq_lengthlist__44u8_p4_0[] = {
  144503. 4, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,11,11,11,
  144504. 11, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,
  144505. 12,12, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  144506. 11,12,12, 6, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  144507. 11,11,12,12, 6, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,
  144508. 10,11,11,12,12, 7, 7, 7, 8, 8, 9, 8,10, 9,10, 9,
  144509. 11,10,12,11,13,12, 7, 7, 7, 8, 8, 8, 9, 9,10, 9,
  144510. 10,10,11,11,12,12,13, 8, 8, 8, 9, 9, 9, 9,10,10,
  144511. 11,10,11,11,12,12,13,13, 8, 8, 8, 9, 9, 9,10,10,
  144512. 10,10,11,11,11,12,12,12,13, 8, 9, 9, 9, 9,10, 9,
  144513. 11,10,11,11,12,11,13,12,13,13, 8, 9, 9, 9, 9, 9,
  144514. 10,10,11,11,11,11,12,12,13,13,13,10,10,10,10,10,
  144515. 11,10,11,11,12,11,13,12,13,13,14,13,10,10,10,10,
  144516. 10,10,11,11,11,11,12,12,13,13,13,13,14,11,11,11,
  144517. 11,11,12,11,12,12,13,12,13,13,14,13,14,14,11,11,
  144518. 11,11,11,11,12,12,12,12,13,13,13,13,14,14,14,11,
  144519. 12,12,12,12,13,12,13,12,13,13,14,13,14,14,14,14,
  144520. 11,12,12,12,12,12,12,13,13,13,13,13,14,14,14,14,
  144521. 14,
  144522. };
  144523. static float _vq_quantthresh__44u8_p4_0[] = {
  144524. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  144525. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  144526. };
  144527. static long _vq_quantmap__44u8_p4_0[] = {
  144528. 15, 13, 11, 9, 7, 5, 3, 1,
  144529. 0, 2, 4, 6, 8, 10, 12, 14,
  144530. 16,
  144531. };
  144532. static encode_aux_threshmatch _vq_auxt__44u8_p4_0 = {
  144533. _vq_quantthresh__44u8_p4_0,
  144534. _vq_quantmap__44u8_p4_0,
  144535. 17,
  144536. 17
  144537. };
  144538. static static_codebook _44u8_p4_0 = {
  144539. 2, 289,
  144540. _vq_lengthlist__44u8_p4_0,
  144541. 1, -529530880, 1611661312, 5, 0,
  144542. _vq_quantlist__44u8_p4_0,
  144543. NULL,
  144544. &_vq_auxt__44u8_p4_0,
  144545. NULL,
  144546. 0
  144547. };
  144548. static long _vq_quantlist__44u8_p5_0[] = {
  144549. 1,
  144550. 0,
  144551. 2,
  144552. };
  144553. static long _vq_lengthlist__44u8_p5_0[] = {
  144554. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8, 9, 9, 7,
  144555. 9, 9, 5, 8, 8, 7, 9, 9, 8, 9, 9, 5, 8, 8, 8,10,
  144556. 10, 8,10,10, 7,10,10, 9,10,12, 9,12,11, 7,10,10,
  144557. 9,11,10, 9,11,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  144558. 10,10, 9,11,11, 9,10,11, 7,10,10, 9,11,11,10,12,
  144559. 10,
  144560. };
  144561. static float _vq_quantthresh__44u8_p5_0[] = {
  144562. -5.5, 5.5,
  144563. };
  144564. static long _vq_quantmap__44u8_p5_0[] = {
  144565. 1, 0, 2,
  144566. };
  144567. static encode_aux_threshmatch _vq_auxt__44u8_p5_0 = {
  144568. _vq_quantthresh__44u8_p5_0,
  144569. _vq_quantmap__44u8_p5_0,
  144570. 3,
  144571. 3
  144572. };
  144573. static static_codebook _44u8_p5_0 = {
  144574. 4, 81,
  144575. _vq_lengthlist__44u8_p5_0,
  144576. 1, -529137664, 1618345984, 2, 0,
  144577. _vq_quantlist__44u8_p5_0,
  144578. NULL,
  144579. &_vq_auxt__44u8_p5_0,
  144580. NULL,
  144581. 0
  144582. };
  144583. static long _vq_quantlist__44u8_p5_1[] = {
  144584. 5,
  144585. 4,
  144586. 6,
  144587. 3,
  144588. 7,
  144589. 2,
  144590. 8,
  144591. 1,
  144592. 9,
  144593. 0,
  144594. 10,
  144595. };
  144596. static long _vq_lengthlist__44u8_p5_1[] = {
  144597. 4, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 5, 5, 5, 6, 6,
  144598. 7, 7, 8, 8, 8, 8, 5, 5, 5, 6, 6, 7, 7, 7, 8, 8,
  144599. 8, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 6, 6, 6, 7,
  144600. 7, 7, 7, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  144601. 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 7, 8, 7,
  144602. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  144603. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 8, 8,
  144604. 8, 8, 8, 8, 8, 8, 8, 9, 9,
  144605. };
  144606. static float _vq_quantthresh__44u8_p5_1[] = {
  144607. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  144608. 3.5, 4.5,
  144609. };
  144610. static long _vq_quantmap__44u8_p5_1[] = {
  144611. 9, 7, 5, 3, 1, 0, 2, 4,
  144612. 6, 8, 10,
  144613. };
  144614. static encode_aux_threshmatch _vq_auxt__44u8_p5_1 = {
  144615. _vq_quantthresh__44u8_p5_1,
  144616. _vq_quantmap__44u8_p5_1,
  144617. 11,
  144618. 11
  144619. };
  144620. static static_codebook _44u8_p5_1 = {
  144621. 2, 121,
  144622. _vq_lengthlist__44u8_p5_1,
  144623. 1, -531365888, 1611661312, 4, 0,
  144624. _vq_quantlist__44u8_p5_1,
  144625. NULL,
  144626. &_vq_auxt__44u8_p5_1,
  144627. NULL,
  144628. 0
  144629. };
  144630. static long _vq_quantlist__44u8_p6_0[] = {
  144631. 6,
  144632. 5,
  144633. 7,
  144634. 4,
  144635. 8,
  144636. 3,
  144637. 9,
  144638. 2,
  144639. 10,
  144640. 1,
  144641. 11,
  144642. 0,
  144643. 12,
  144644. };
  144645. static long _vq_lengthlist__44u8_p6_0[] = {
  144646. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 5,
  144647. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7, 8,
  144648. 8, 8, 8, 9, 9,10,10, 6, 7, 7, 7, 8, 8, 8, 8, 9,
  144649. 9,10,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 8,10, 9,11,
  144650. 10, 7, 8, 8, 8, 8, 8, 9, 9, 9,10,10,11,11, 7, 8,
  144651. 8, 8, 8, 9, 8, 9, 9,10,10,11,11, 8, 8, 8, 9, 9,
  144652. 9, 9, 9,10,10,10,11,11, 8, 8, 8, 9, 9, 9, 9,10,
  144653. 9,10,10,11,11, 9, 9, 9, 9,10,10,10,10,10,10,11,
  144654. 11,12, 9, 9, 9,10, 9,10,10,10,10,11,10,12,11,10,
  144655. 10,10,10,10,11,11,11,11,11,12,12,12,10,10,10,10,
  144656. 11,11,11,11,11,12,11,12,12,
  144657. };
  144658. static float _vq_quantthresh__44u8_p6_0[] = {
  144659. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  144660. 12.5, 17.5, 22.5, 27.5,
  144661. };
  144662. static long _vq_quantmap__44u8_p6_0[] = {
  144663. 11, 9, 7, 5, 3, 1, 0, 2,
  144664. 4, 6, 8, 10, 12,
  144665. };
  144666. static encode_aux_threshmatch _vq_auxt__44u8_p6_0 = {
  144667. _vq_quantthresh__44u8_p6_0,
  144668. _vq_quantmap__44u8_p6_0,
  144669. 13,
  144670. 13
  144671. };
  144672. static static_codebook _44u8_p6_0 = {
  144673. 2, 169,
  144674. _vq_lengthlist__44u8_p6_0,
  144675. 1, -526516224, 1616117760, 4, 0,
  144676. _vq_quantlist__44u8_p6_0,
  144677. NULL,
  144678. &_vq_auxt__44u8_p6_0,
  144679. NULL,
  144680. 0
  144681. };
  144682. static long _vq_quantlist__44u8_p6_1[] = {
  144683. 2,
  144684. 1,
  144685. 3,
  144686. 0,
  144687. 4,
  144688. };
  144689. static long _vq_lengthlist__44u8_p6_1[] = {
  144690. 3, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  144691. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  144692. };
  144693. static float _vq_quantthresh__44u8_p6_1[] = {
  144694. -1.5, -0.5, 0.5, 1.5,
  144695. };
  144696. static long _vq_quantmap__44u8_p6_1[] = {
  144697. 3, 1, 0, 2, 4,
  144698. };
  144699. static encode_aux_threshmatch _vq_auxt__44u8_p6_1 = {
  144700. _vq_quantthresh__44u8_p6_1,
  144701. _vq_quantmap__44u8_p6_1,
  144702. 5,
  144703. 5
  144704. };
  144705. static static_codebook _44u8_p6_1 = {
  144706. 2, 25,
  144707. _vq_lengthlist__44u8_p6_1,
  144708. 1, -533725184, 1611661312, 3, 0,
  144709. _vq_quantlist__44u8_p6_1,
  144710. NULL,
  144711. &_vq_auxt__44u8_p6_1,
  144712. NULL,
  144713. 0
  144714. };
  144715. static long _vq_quantlist__44u8_p7_0[] = {
  144716. 6,
  144717. 5,
  144718. 7,
  144719. 4,
  144720. 8,
  144721. 3,
  144722. 9,
  144723. 2,
  144724. 10,
  144725. 1,
  144726. 11,
  144727. 0,
  144728. 12,
  144729. };
  144730. static long _vq_lengthlist__44u8_p7_0[] = {
  144731. 1, 4, 5, 6, 6, 7, 7, 8, 8,10,10,11,11, 5, 6, 6,
  144732. 7, 7, 8, 8, 9, 9,11,10,12,11, 5, 6, 6, 7, 7, 8,
  144733. 8, 9, 9,10,11,11,12, 6, 7, 7, 8, 8, 9, 9,10,10,
  144734. 11,11,12,12, 6, 7, 7, 8, 8, 9, 9,10,10,11,12,13,
  144735. 12, 7, 8, 8, 9, 9,10,10,11,11,12,12,13,13, 8, 8,
  144736. 8, 9, 9,10,10,11,11,12,12,13,13, 9, 9, 9,10,10,
  144737. 11,11,12,12,13,13,14,14, 9, 9, 9,10,10,11,11,12,
  144738. 12,13,13,14,14,10,11,11,12,11,13,12,13,13,14,14,
  144739. 15,15,10,11,11,11,12,12,13,13,14,14,14,15,15,11,
  144740. 12,12,13,13,14,13,15,14,15,15,16,15,11,11,12,13,
  144741. 13,13,14,14,14,15,15,15,16,
  144742. };
  144743. static float _vq_quantthresh__44u8_p7_0[] = {
  144744. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  144745. 27.5, 38.5, 49.5, 60.5,
  144746. };
  144747. static long _vq_quantmap__44u8_p7_0[] = {
  144748. 11, 9, 7, 5, 3, 1, 0, 2,
  144749. 4, 6, 8, 10, 12,
  144750. };
  144751. static encode_aux_threshmatch _vq_auxt__44u8_p7_0 = {
  144752. _vq_quantthresh__44u8_p7_0,
  144753. _vq_quantmap__44u8_p7_0,
  144754. 13,
  144755. 13
  144756. };
  144757. static static_codebook _44u8_p7_0 = {
  144758. 2, 169,
  144759. _vq_lengthlist__44u8_p7_0,
  144760. 1, -523206656, 1618345984, 4, 0,
  144761. _vq_quantlist__44u8_p7_0,
  144762. NULL,
  144763. &_vq_auxt__44u8_p7_0,
  144764. NULL,
  144765. 0
  144766. };
  144767. static long _vq_quantlist__44u8_p7_1[] = {
  144768. 5,
  144769. 4,
  144770. 6,
  144771. 3,
  144772. 7,
  144773. 2,
  144774. 8,
  144775. 1,
  144776. 9,
  144777. 0,
  144778. 10,
  144779. };
  144780. static long _vq_lengthlist__44u8_p7_1[] = {
  144781. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  144782. 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7, 7, 7, 7, 7, 7,
  144783. 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 6, 7, 7, 7,
  144784. 7, 7, 7, 7, 7, 7, 8, 7, 7, 7, 7, 7, 7, 7, 8, 8,
  144785. 8, 8, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 7, 7, 7,
  144786. 8, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8,
  144787. 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 7,
  144788. 7, 8, 8, 8, 8, 8, 8, 8, 8,
  144789. };
  144790. static float _vq_quantthresh__44u8_p7_1[] = {
  144791. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  144792. 3.5, 4.5,
  144793. };
  144794. static long _vq_quantmap__44u8_p7_1[] = {
  144795. 9, 7, 5, 3, 1, 0, 2, 4,
  144796. 6, 8, 10,
  144797. };
  144798. static encode_aux_threshmatch _vq_auxt__44u8_p7_1 = {
  144799. _vq_quantthresh__44u8_p7_1,
  144800. _vq_quantmap__44u8_p7_1,
  144801. 11,
  144802. 11
  144803. };
  144804. static static_codebook _44u8_p7_1 = {
  144805. 2, 121,
  144806. _vq_lengthlist__44u8_p7_1,
  144807. 1, -531365888, 1611661312, 4, 0,
  144808. _vq_quantlist__44u8_p7_1,
  144809. NULL,
  144810. &_vq_auxt__44u8_p7_1,
  144811. NULL,
  144812. 0
  144813. };
  144814. static long _vq_quantlist__44u8_p8_0[] = {
  144815. 7,
  144816. 6,
  144817. 8,
  144818. 5,
  144819. 9,
  144820. 4,
  144821. 10,
  144822. 3,
  144823. 11,
  144824. 2,
  144825. 12,
  144826. 1,
  144827. 13,
  144828. 0,
  144829. 14,
  144830. };
  144831. static long _vq_lengthlist__44u8_p8_0[] = {
  144832. 1, 4, 4, 7, 7, 8, 8, 8, 7, 9, 8,10, 9,11,10, 4,
  144833. 6, 6, 8, 8,10, 9, 9, 9,10,10,11,10,12,10, 4, 6,
  144834. 6, 8, 8,10,10, 9, 9,10,10,11,11,11,12, 7, 8, 8,
  144835. 10,10,11,11,11,10,12,11,12,12,13,11, 7, 8, 8,10,
  144836. 10,11,11,10,10,11,11,12,12,13,13, 8,10,10,11,11,
  144837. 12,11,12,11,13,12,13,12,14,13, 8,10, 9,11,11,12,
  144838. 12,12,12,12,12,13,13,14,13, 8, 9, 9,11,10,12,11,
  144839. 13,12,13,13,14,13,14,13, 8, 9, 9,10,11,12,12,12,
  144840. 12,13,13,14,15,14,14, 9,10,10,12,11,13,12,13,13,
  144841. 14,13,14,14,14,14, 9,10,10,12,12,12,12,13,13,14,
  144842. 14,14,15,14,14,10,11,11,13,12,13,12,14,14,14,14,
  144843. 14,14,15,15,10,11,11,12,12,13,13,14,14,14,15,15,
  144844. 14,16,15,11,12,12,13,12,14,14,14,13,15,14,15,15,
  144845. 15,17,11,12,12,13,13,14,14,14,15,15,14,15,15,14,
  144846. 17,
  144847. };
  144848. static float _vq_quantthresh__44u8_p8_0[] = {
  144849. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  144850. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  144851. };
  144852. static long _vq_quantmap__44u8_p8_0[] = {
  144853. 13, 11, 9, 7, 5, 3, 1, 0,
  144854. 2, 4, 6, 8, 10, 12, 14,
  144855. };
  144856. static encode_aux_threshmatch _vq_auxt__44u8_p8_0 = {
  144857. _vq_quantthresh__44u8_p8_0,
  144858. _vq_quantmap__44u8_p8_0,
  144859. 15,
  144860. 15
  144861. };
  144862. static static_codebook _44u8_p8_0 = {
  144863. 2, 225,
  144864. _vq_lengthlist__44u8_p8_0,
  144865. 1, -520986624, 1620377600, 4, 0,
  144866. _vq_quantlist__44u8_p8_0,
  144867. NULL,
  144868. &_vq_auxt__44u8_p8_0,
  144869. NULL,
  144870. 0
  144871. };
  144872. static long _vq_quantlist__44u8_p8_1[] = {
  144873. 10,
  144874. 9,
  144875. 11,
  144876. 8,
  144877. 12,
  144878. 7,
  144879. 13,
  144880. 6,
  144881. 14,
  144882. 5,
  144883. 15,
  144884. 4,
  144885. 16,
  144886. 3,
  144887. 17,
  144888. 2,
  144889. 18,
  144890. 1,
  144891. 19,
  144892. 0,
  144893. 20,
  144894. };
  144895. static long _vq_lengthlist__44u8_p8_1[] = {
  144896. 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  144897. 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  144898. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 5, 6, 6, 7, 7, 8,
  144899. 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 7,
  144900. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144901. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  144902. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9,
  144903. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10, 8, 8,
  144904. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,
  144905. 10, 9,10, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,
  144906. 10,10,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9, 9,
  144907. 9, 9, 9, 9, 9, 9,10,10,10,10, 9,10,10, 9, 9, 9,
  144908. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  144909. 10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,
  144910. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9,10, 9,
  144911. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  144912. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,
  144913. 10, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  144914. 10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  144915. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  144916. 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144917. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  144918. 10,10,10,10,10, 9, 9, 9,10, 9,10,10,10,10,10,10,
  144919. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  144920. 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  144921. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  144922. 10,10,10,10, 9, 9, 9,10, 9,10, 9,10,10,10,10,10,
  144923. 10,10,10,10,10,10,10,10,10,
  144924. };
  144925. static float _vq_quantthresh__44u8_p8_1[] = {
  144926. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  144927. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  144928. 6.5, 7.5, 8.5, 9.5,
  144929. };
  144930. static long _vq_quantmap__44u8_p8_1[] = {
  144931. 19, 17, 15, 13, 11, 9, 7, 5,
  144932. 3, 1, 0, 2, 4, 6, 8, 10,
  144933. 12, 14, 16, 18, 20,
  144934. };
  144935. static encode_aux_threshmatch _vq_auxt__44u8_p8_1 = {
  144936. _vq_quantthresh__44u8_p8_1,
  144937. _vq_quantmap__44u8_p8_1,
  144938. 21,
  144939. 21
  144940. };
  144941. static static_codebook _44u8_p8_1 = {
  144942. 2, 441,
  144943. _vq_lengthlist__44u8_p8_1,
  144944. 1, -529268736, 1611661312, 5, 0,
  144945. _vq_quantlist__44u8_p8_1,
  144946. NULL,
  144947. &_vq_auxt__44u8_p8_1,
  144948. NULL,
  144949. 0
  144950. };
  144951. static long _vq_quantlist__44u8_p9_0[] = {
  144952. 4,
  144953. 3,
  144954. 5,
  144955. 2,
  144956. 6,
  144957. 1,
  144958. 7,
  144959. 0,
  144960. 8,
  144961. };
  144962. static long _vq_lengthlist__44u8_p9_0[] = {
  144963. 1, 3, 3, 9, 9, 9, 9, 9, 9, 4, 9, 9, 9, 9, 9, 9,
  144964. 9, 9, 5, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144965. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144966. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144967. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8,
  144968. 8,
  144969. };
  144970. static float _vq_quantthresh__44u8_p9_0[] = {
  144971. -3258.5, -2327.5, -1396.5, -465.5, 465.5, 1396.5, 2327.5, 3258.5,
  144972. };
  144973. static long _vq_quantmap__44u8_p9_0[] = {
  144974. 7, 5, 3, 1, 0, 2, 4, 6,
  144975. 8,
  144976. };
  144977. static encode_aux_threshmatch _vq_auxt__44u8_p9_0 = {
  144978. _vq_quantthresh__44u8_p9_0,
  144979. _vq_quantmap__44u8_p9_0,
  144980. 9,
  144981. 9
  144982. };
  144983. static static_codebook _44u8_p9_0 = {
  144984. 2, 81,
  144985. _vq_lengthlist__44u8_p9_0,
  144986. 1, -511895552, 1631393792, 4, 0,
  144987. _vq_quantlist__44u8_p9_0,
  144988. NULL,
  144989. &_vq_auxt__44u8_p9_0,
  144990. NULL,
  144991. 0
  144992. };
  144993. static long _vq_quantlist__44u8_p9_1[] = {
  144994. 9,
  144995. 8,
  144996. 10,
  144997. 7,
  144998. 11,
  144999. 6,
  145000. 12,
  145001. 5,
  145002. 13,
  145003. 4,
  145004. 14,
  145005. 3,
  145006. 15,
  145007. 2,
  145008. 16,
  145009. 1,
  145010. 17,
  145011. 0,
  145012. 18,
  145013. };
  145014. static long _vq_lengthlist__44u8_p9_1[] = {
  145015. 1, 4, 4, 7, 7, 8, 7, 8, 6, 9, 7,10, 8,11,10,11,
  145016. 11,11,11, 4, 7, 6, 9, 9,10, 9, 9, 9,10,10,11,10,
  145017. 11,10,11,11,13,11, 4, 7, 7, 9, 9, 9, 9, 9, 9,10,
  145018. 10,11,10,11,11,11,12,11,12, 7, 9, 8,11,11,11,11,
  145019. 10,10,11,11,12,12,12,12,12,12,14,13, 7, 8, 9,10,
  145020. 11,11,11,10,10,11,11,11,11,12,12,14,12,13,14, 8,
  145021. 9, 9,11,11,11,11,11,11,12,12,14,12,15,14,14,14,
  145022. 15,14, 8, 9, 9,11,11,11,11,12,11,12,12,13,13,13,
  145023. 13,13,13,14,14, 8, 9, 9,11,10,12,11,12,12,13,13,
  145024. 13,13,15,14,14,14,16,16, 8, 9, 9,10,11,11,12,12,
  145025. 12,13,13,13,14,14,14,15,16,15,15, 9,10,10,11,12,
  145026. 12,13,13,13,14,14,16,14,14,16,16,16,16,15, 9,10,
  145027. 10,11,11,12,13,13,14,15,14,16,14,15,16,16,16,16,
  145028. 15,10,11,11,12,13,13,14,15,15,15,15,15,16,15,16,
  145029. 15,16,15,15,10,11,11,13,13,14,13,13,15,14,15,15,
  145030. 16,15,15,15,16,15,16,10,12,12,14,14,14,14,14,16,
  145031. 16,15,15,15,16,16,16,16,16,16,11,12,12,14,14,14,
  145032. 14,15,15,16,15,16,15,16,15,16,16,16,16,12,12,13,
  145033. 14,14,15,16,16,16,16,16,16,15,16,16,16,16,16,16,
  145034. 12,13,13,14,14,14,14,15,16,15,16,16,16,16,16,16,
  145035. 16,16,16,12,13,14,14,14,16,15,16,15,16,16,16,16,
  145036. 16,16,16,16,16,16,12,14,13,14,15,15,15,16,15,16,
  145037. 16,15,16,16,16,16,16,16,16,
  145038. };
  145039. static float _vq_quantthresh__44u8_p9_1[] = {
  145040. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  145041. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  145042. 367.5, 416.5,
  145043. };
  145044. static long _vq_quantmap__44u8_p9_1[] = {
  145045. 17, 15, 13, 11, 9, 7, 5, 3,
  145046. 1, 0, 2, 4, 6, 8, 10, 12,
  145047. 14, 16, 18,
  145048. };
  145049. static encode_aux_threshmatch _vq_auxt__44u8_p9_1 = {
  145050. _vq_quantthresh__44u8_p9_1,
  145051. _vq_quantmap__44u8_p9_1,
  145052. 19,
  145053. 19
  145054. };
  145055. static static_codebook _44u8_p9_1 = {
  145056. 2, 361,
  145057. _vq_lengthlist__44u8_p9_1,
  145058. 1, -518287360, 1622704128, 5, 0,
  145059. _vq_quantlist__44u8_p9_1,
  145060. NULL,
  145061. &_vq_auxt__44u8_p9_1,
  145062. NULL,
  145063. 0
  145064. };
  145065. static long _vq_quantlist__44u8_p9_2[] = {
  145066. 24,
  145067. 23,
  145068. 25,
  145069. 22,
  145070. 26,
  145071. 21,
  145072. 27,
  145073. 20,
  145074. 28,
  145075. 19,
  145076. 29,
  145077. 18,
  145078. 30,
  145079. 17,
  145080. 31,
  145081. 16,
  145082. 32,
  145083. 15,
  145084. 33,
  145085. 14,
  145086. 34,
  145087. 13,
  145088. 35,
  145089. 12,
  145090. 36,
  145091. 11,
  145092. 37,
  145093. 10,
  145094. 38,
  145095. 9,
  145096. 39,
  145097. 8,
  145098. 40,
  145099. 7,
  145100. 41,
  145101. 6,
  145102. 42,
  145103. 5,
  145104. 43,
  145105. 4,
  145106. 44,
  145107. 3,
  145108. 45,
  145109. 2,
  145110. 46,
  145111. 1,
  145112. 47,
  145113. 0,
  145114. 48,
  145115. };
  145116. static long _vq_lengthlist__44u8_p9_2[] = {
  145117. 2, 3, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  145118. 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  145119. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  145120. 7,
  145121. };
  145122. static float _vq_quantthresh__44u8_p9_2[] = {
  145123. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  145124. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  145125. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  145126. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  145127. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  145128. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  145129. };
  145130. static long _vq_quantmap__44u8_p9_2[] = {
  145131. 47, 45, 43, 41, 39, 37, 35, 33,
  145132. 31, 29, 27, 25, 23, 21, 19, 17,
  145133. 15, 13, 11, 9, 7, 5, 3, 1,
  145134. 0, 2, 4, 6, 8, 10, 12, 14,
  145135. 16, 18, 20, 22, 24, 26, 28, 30,
  145136. 32, 34, 36, 38, 40, 42, 44, 46,
  145137. 48,
  145138. };
  145139. static encode_aux_threshmatch _vq_auxt__44u8_p9_2 = {
  145140. _vq_quantthresh__44u8_p9_2,
  145141. _vq_quantmap__44u8_p9_2,
  145142. 49,
  145143. 49
  145144. };
  145145. static static_codebook _44u8_p9_2 = {
  145146. 1, 49,
  145147. _vq_lengthlist__44u8_p9_2,
  145148. 1, -526909440, 1611661312, 6, 0,
  145149. _vq_quantlist__44u8_p9_2,
  145150. NULL,
  145151. &_vq_auxt__44u8_p9_2,
  145152. NULL,
  145153. 0
  145154. };
  145155. static long _huff_lengthlist__44u9__long[] = {
  145156. 3, 9,13,13,14,15,14,14,15,15, 5, 5, 9,10,12,12,
  145157. 13,14,16,15,10, 6, 6, 6, 8,11,12,13,16,15,11, 7,
  145158. 5, 3, 5, 8,10,12,15,15,10,10, 7, 4, 3, 5, 8,10,
  145159. 12,12,12,12, 9, 7, 5, 4, 6, 8,10,13,13,12,11, 9,
  145160. 7, 5, 5, 6, 9,12,14,12,12,10, 8, 6, 6, 6, 7,11,
  145161. 13,12,14,13,10, 8, 7, 7, 7,10,11,11,12,13,12,11,
  145162. 10, 8, 8, 9,
  145163. };
  145164. static static_codebook _huff_book__44u9__long = {
  145165. 2, 100,
  145166. _huff_lengthlist__44u9__long,
  145167. 0, 0, 0, 0, 0,
  145168. NULL,
  145169. NULL,
  145170. NULL,
  145171. NULL,
  145172. 0
  145173. };
  145174. static long _huff_lengthlist__44u9__short[] = {
  145175. 9,16,18,18,17,17,17,17,17,17, 5, 8,11,12,11,12,
  145176. 17,17,16,16, 6, 6, 8, 8, 9,10,14,15,16,16, 6, 7,
  145177. 7, 4, 6, 9,13,16,16,16, 6, 6, 7, 4, 5, 8,11,15,
  145178. 17,16, 7, 6, 7, 6, 6, 8, 9,10,14,16,11, 8, 8, 7,
  145179. 6, 6, 3, 4,10,15,14,12,12,10, 5, 6, 3, 3, 8,13,
  145180. 15,17,15,11, 6, 8, 6, 6, 9,14,17,15,15,12, 8,10,
  145181. 9, 9,12,15,
  145182. };
  145183. static static_codebook _huff_book__44u9__short = {
  145184. 2, 100,
  145185. _huff_lengthlist__44u9__short,
  145186. 0, 0, 0, 0, 0,
  145187. NULL,
  145188. NULL,
  145189. NULL,
  145190. NULL,
  145191. 0
  145192. };
  145193. static long _vq_quantlist__44u9_p1_0[] = {
  145194. 1,
  145195. 0,
  145196. 2,
  145197. };
  145198. static long _vq_lengthlist__44u9_p1_0[] = {
  145199. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 7, 9, 9, 7,
  145200. 9, 9, 5, 7, 7, 7, 9, 9, 7, 9, 9, 5, 7, 7, 7, 9,
  145201. 9, 7, 9, 9, 8, 9, 9, 9,10,11, 9,11,11, 7, 9, 9,
  145202. 9,11,10, 9,11,11, 5, 7, 7, 7, 9, 9, 8, 9,10, 7,
  145203. 9, 9, 9,11,11, 9,10,11, 7, 9,10, 9,11,11, 9,11,
  145204. 10,
  145205. };
  145206. static float _vq_quantthresh__44u9_p1_0[] = {
  145207. -0.5, 0.5,
  145208. };
  145209. static long _vq_quantmap__44u9_p1_0[] = {
  145210. 1, 0, 2,
  145211. };
  145212. static encode_aux_threshmatch _vq_auxt__44u9_p1_0 = {
  145213. _vq_quantthresh__44u9_p1_0,
  145214. _vq_quantmap__44u9_p1_0,
  145215. 3,
  145216. 3
  145217. };
  145218. static static_codebook _44u9_p1_0 = {
  145219. 4, 81,
  145220. _vq_lengthlist__44u9_p1_0,
  145221. 1, -535822336, 1611661312, 2, 0,
  145222. _vq_quantlist__44u9_p1_0,
  145223. NULL,
  145224. &_vq_auxt__44u9_p1_0,
  145225. NULL,
  145226. 0
  145227. };
  145228. static long _vq_quantlist__44u9_p2_0[] = {
  145229. 2,
  145230. 1,
  145231. 3,
  145232. 0,
  145233. 4,
  145234. };
  145235. static long _vq_lengthlist__44u9_p2_0[] = {
  145236. 3, 5, 5, 8, 8, 5, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  145237. 9, 9,11,10, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  145238. 8,10,10, 7, 8, 8, 9,10, 9,10,10,11,11, 9, 9,10,
  145239. 11,11, 6, 7, 7, 9, 9, 7, 8, 8,10, 9, 7, 8, 8,10,
  145240. 10, 9,10, 9,11,11, 9,10,10,11,11, 8, 9, 9,11,11,
  145241. 9,10,10,12,11, 9,10,10,11,12,11,11,11,13,13,11,
  145242. 11,11,12,13, 8, 9, 9,11,11, 9,10,10,11,11, 9,10,
  145243. 10,12,11,11,12,11,13,12,11,11,12,13,13, 6, 7, 7,
  145244. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  145245. 11, 9,10,10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  145246. 8, 9, 9,10,10,10,11,11,12,12,10,10,11,12,12, 7,
  145247. 8, 8,10,10, 8, 9, 8,10,10, 8, 9, 9,10,10,10,11,
  145248. 10,12,11,10,10,11,12,12, 9,10,10,11,12,10,11,11,
  145249. 12,12,10,11,10,12,12,12,12,12,13,13,11,12,12,13,
  145250. 13, 9,10,10,11,11, 9,10,10,12,12,10,11,11,12,13,
  145251. 11,12,11,13,12,12,12,12,13,14, 6, 7, 7, 9, 9, 7,
  145252. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,11,11, 9,10,
  145253. 10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,10, 8, 8, 9,
  145254. 10,10,10,11,10,12,12,10,10,11,11,12, 7, 8, 8,10,
  145255. 10, 8, 9, 9,10,10, 8, 9, 9,10,10,10,11,10,12,12,
  145256. 10,11,10,12,12, 9,10,10,12,11,10,11,11,12,12, 9,
  145257. 10,10,12,12,12,12,12,13,13,11,11,12,12,14, 9,10,
  145258. 10,11,12,10,11,11,12,12,10,11,11,12,12,11,12,12,
  145259. 14,14,12,12,12,13,13, 8, 9, 9,11,11, 9,10,10,12,
  145260. 11, 9,10,10,12,12,11,12,11,13,13,11,11,12,13,13,
  145261. 9,10,10,12,12,10,11,11,12,12,10,11,11,12,12,12,
  145262. 12,12,14,14,12,12,12,13,13, 9,10,10,12,11,10,11,
  145263. 10,12,12,10,11,11,12,12,11,12,12,14,13,12,12,12,
  145264. 13,14,11,12,11,13,13,11,12,12,13,13,12,12,12,14,
  145265. 14,13,13,13,13,15,13,13,14,15,15,11,11,11,13,13,
  145266. 11,12,11,13,13,11,12,12,13,13,12,13,12,15,13,13,
  145267. 13,14,14,15, 8, 9, 9,11,11, 9,10,10,11,12, 9,10,
  145268. 10,11,12,11,12,11,13,13,11,12,12,13,13, 9,10,10,
  145269. 11,12,10,11,10,12,12,10,10,11,12,13,12,12,12,14,
  145270. 13,11,12,12,13,14, 9,10,10,12,12,10,11,11,12,12,
  145271. 10,11,11,12,12,12,12,12,14,13,12,12,12,14,13,11,
  145272. 11,11,13,13,11,12,12,14,13,11,11,12,13,13,13,13,
  145273. 13,15,14,12,12,13,13,15,11,12,12,13,13,12,12,12,
  145274. 13,14,11,12,12,13,13,13,13,14,14,15,13,13,13,14,
  145275. 14,
  145276. };
  145277. static float _vq_quantthresh__44u9_p2_0[] = {
  145278. -1.5, -0.5, 0.5, 1.5,
  145279. };
  145280. static long _vq_quantmap__44u9_p2_0[] = {
  145281. 3, 1, 0, 2, 4,
  145282. };
  145283. static encode_aux_threshmatch _vq_auxt__44u9_p2_0 = {
  145284. _vq_quantthresh__44u9_p2_0,
  145285. _vq_quantmap__44u9_p2_0,
  145286. 5,
  145287. 5
  145288. };
  145289. static static_codebook _44u9_p2_0 = {
  145290. 4, 625,
  145291. _vq_lengthlist__44u9_p2_0,
  145292. 1, -533725184, 1611661312, 3, 0,
  145293. _vq_quantlist__44u9_p2_0,
  145294. NULL,
  145295. &_vq_auxt__44u9_p2_0,
  145296. NULL,
  145297. 0
  145298. };
  145299. static long _vq_quantlist__44u9_p3_0[] = {
  145300. 4,
  145301. 3,
  145302. 5,
  145303. 2,
  145304. 6,
  145305. 1,
  145306. 7,
  145307. 0,
  145308. 8,
  145309. };
  145310. static long _vq_lengthlist__44u9_p3_0[] = {
  145311. 3, 4, 4, 5, 5, 7, 7, 8, 8, 4, 5, 5, 6, 6, 7, 7,
  145312. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  145313. 8, 8, 9, 9, 5, 6, 6, 7, 7, 8, 8, 9, 9, 7, 7, 7,
  145314. 8, 8, 9, 9,10,10, 7, 7, 7, 8, 8, 9, 9,10,10, 8,
  145315. 9, 9,10, 9,10,10,11,11, 8, 9, 9, 9,10,10,10,11,
  145316. 11,
  145317. };
  145318. static float _vq_quantthresh__44u9_p3_0[] = {
  145319. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  145320. };
  145321. static long _vq_quantmap__44u9_p3_0[] = {
  145322. 7, 5, 3, 1, 0, 2, 4, 6,
  145323. 8,
  145324. };
  145325. static encode_aux_threshmatch _vq_auxt__44u9_p3_0 = {
  145326. _vq_quantthresh__44u9_p3_0,
  145327. _vq_quantmap__44u9_p3_0,
  145328. 9,
  145329. 9
  145330. };
  145331. static static_codebook _44u9_p3_0 = {
  145332. 2, 81,
  145333. _vq_lengthlist__44u9_p3_0,
  145334. 1, -531628032, 1611661312, 4, 0,
  145335. _vq_quantlist__44u9_p3_0,
  145336. NULL,
  145337. &_vq_auxt__44u9_p3_0,
  145338. NULL,
  145339. 0
  145340. };
  145341. static long _vq_quantlist__44u9_p4_0[] = {
  145342. 8,
  145343. 7,
  145344. 9,
  145345. 6,
  145346. 10,
  145347. 5,
  145348. 11,
  145349. 4,
  145350. 12,
  145351. 3,
  145352. 13,
  145353. 2,
  145354. 14,
  145355. 1,
  145356. 15,
  145357. 0,
  145358. 16,
  145359. };
  145360. static long _vq_lengthlist__44u9_p4_0[] = {
  145361. 4, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  145362. 11, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  145363. 11,11, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  145364. 10,11,11, 6, 6, 6, 7, 6, 7, 7, 8, 8, 9, 9,10,10,
  145365. 11,11,12,11, 6, 6, 6, 6, 7, 7, 7, 8, 8, 9, 9,10,
  145366. 10,11,11,11,12, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,
  145367. 10,10,11,11,12,12, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  145368. 9,10,10,11,11,12,12, 8, 8, 8, 8, 8, 9, 8,10, 9,
  145369. 10,10,11,10,12,11,13,12, 8, 8, 8, 8, 8, 9, 9, 9,
  145370. 10,10,10,10,11,11,12,12,12, 8, 8, 8, 9, 9, 9, 9,
  145371. 10,10,11,10,12,11,12,12,13,12, 8, 8, 8, 9, 9, 9,
  145372. 9,10,10,10,11,11,11,12,12,12,13, 9, 9, 9,10,10,
  145373. 10,10,11,10,11,11,12,11,13,12,13,13, 9, 9,10,10,
  145374. 10,10,10,10,11,11,11,11,12,12,13,13,13,10,11,10,
  145375. 11,11,11,11,12,11,12,12,13,12,13,13,14,13,10,10,
  145376. 10,11,11,11,11,11,12,12,12,12,13,13,13,13,14,11,
  145377. 11,11,12,11,12,12,12,12,13,13,13,13,14,13,14,14,
  145378. 11,11,11,11,12,12,12,12,12,12,13,13,13,13,14,14,
  145379. 14,
  145380. };
  145381. static float _vq_quantthresh__44u9_p4_0[] = {
  145382. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  145383. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  145384. };
  145385. static long _vq_quantmap__44u9_p4_0[] = {
  145386. 15, 13, 11, 9, 7, 5, 3, 1,
  145387. 0, 2, 4, 6, 8, 10, 12, 14,
  145388. 16,
  145389. };
  145390. static encode_aux_threshmatch _vq_auxt__44u9_p4_0 = {
  145391. _vq_quantthresh__44u9_p4_0,
  145392. _vq_quantmap__44u9_p4_0,
  145393. 17,
  145394. 17
  145395. };
  145396. static static_codebook _44u9_p4_0 = {
  145397. 2, 289,
  145398. _vq_lengthlist__44u9_p4_0,
  145399. 1, -529530880, 1611661312, 5, 0,
  145400. _vq_quantlist__44u9_p4_0,
  145401. NULL,
  145402. &_vq_auxt__44u9_p4_0,
  145403. NULL,
  145404. 0
  145405. };
  145406. static long _vq_quantlist__44u9_p5_0[] = {
  145407. 1,
  145408. 0,
  145409. 2,
  145410. };
  145411. static long _vq_lengthlist__44u9_p5_0[] = {
  145412. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8, 9, 9, 7,
  145413. 9, 9, 5, 8, 8, 7, 9, 9, 8, 9, 9, 5, 8, 8, 8,10,
  145414. 10, 8,10,10, 7,10,10, 9,10,12, 9,11,11, 7,10,10,
  145415. 9,11,10, 9,11,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  145416. 10,10, 9,12,11, 9,10,11, 7,10,10, 9,11,11,10,12,
  145417. 10,
  145418. };
  145419. static float _vq_quantthresh__44u9_p5_0[] = {
  145420. -5.5, 5.5,
  145421. };
  145422. static long _vq_quantmap__44u9_p5_0[] = {
  145423. 1, 0, 2,
  145424. };
  145425. static encode_aux_threshmatch _vq_auxt__44u9_p5_0 = {
  145426. _vq_quantthresh__44u9_p5_0,
  145427. _vq_quantmap__44u9_p5_0,
  145428. 3,
  145429. 3
  145430. };
  145431. static static_codebook _44u9_p5_0 = {
  145432. 4, 81,
  145433. _vq_lengthlist__44u9_p5_0,
  145434. 1, -529137664, 1618345984, 2, 0,
  145435. _vq_quantlist__44u9_p5_0,
  145436. NULL,
  145437. &_vq_auxt__44u9_p5_0,
  145438. NULL,
  145439. 0
  145440. };
  145441. static long _vq_quantlist__44u9_p5_1[] = {
  145442. 5,
  145443. 4,
  145444. 6,
  145445. 3,
  145446. 7,
  145447. 2,
  145448. 8,
  145449. 1,
  145450. 9,
  145451. 0,
  145452. 10,
  145453. };
  145454. static long _vq_lengthlist__44u9_p5_1[] = {
  145455. 5, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 6, 6,
  145456. 7, 7, 7, 7, 8, 7, 5, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  145457. 7, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 6, 6, 6, 7,
  145458. 7, 7, 7, 7, 7, 8, 8, 7, 7, 7, 7, 7, 8, 7, 8, 8,
  145459. 8, 8, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  145460. 8, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 8, 8, 8, 8,
  145461. 8, 8, 8, 7, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  145462. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  145463. };
  145464. static float _vq_quantthresh__44u9_p5_1[] = {
  145465. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  145466. 3.5, 4.5,
  145467. };
  145468. static long _vq_quantmap__44u9_p5_1[] = {
  145469. 9, 7, 5, 3, 1, 0, 2, 4,
  145470. 6, 8, 10,
  145471. };
  145472. static encode_aux_threshmatch _vq_auxt__44u9_p5_1 = {
  145473. _vq_quantthresh__44u9_p5_1,
  145474. _vq_quantmap__44u9_p5_1,
  145475. 11,
  145476. 11
  145477. };
  145478. static static_codebook _44u9_p5_1 = {
  145479. 2, 121,
  145480. _vq_lengthlist__44u9_p5_1,
  145481. 1, -531365888, 1611661312, 4, 0,
  145482. _vq_quantlist__44u9_p5_1,
  145483. NULL,
  145484. &_vq_auxt__44u9_p5_1,
  145485. NULL,
  145486. 0
  145487. };
  145488. static long _vq_quantlist__44u9_p6_0[] = {
  145489. 6,
  145490. 5,
  145491. 7,
  145492. 4,
  145493. 8,
  145494. 3,
  145495. 9,
  145496. 2,
  145497. 10,
  145498. 1,
  145499. 11,
  145500. 0,
  145501. 12,
  145502. };
  145503. static long _vq_lengthlist__44u9_p6_0[] = {
  145504. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 5,
  145505. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 5, 6, 7, 7, 8,
  145506. 8, 8, 8, 9, 9,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  145507. 10,10,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,10,
  145508. 10, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,11, 7, 8,
  145509. 8, 8, 8, 9, 9, 9, 9,10,10,11,11, 8, 8, 8, 9, 9,
  145510. 9, 9, 9,10,10,10,11,11, 8, 8, 8, 9, 9, 9, 9,10,
  145511. 9,10,10,11,11, 9, 9, 9,10,10,10,10,10,11,11,11,
  145512. 11,12, 9, 9, 9,10,10,10,10,10,10,11,10,12,11,10,
  145513. 10,10,10,10,11,11,11,11,11,12,12,12,10,10,10,10,
  145514. 10,11,11,11,11,12,11,12,12,
  145515. };
  145516. static float _vq_quantthresh__44u9_p6_0[] = {
  145517. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  145518. 12.5, 17.5, 22.5, 27.5,
  145519. };
  145520. static long _vq_quantmap__44u9_p6_0[] = {
  145521. 11, 9, 7, 5, 3, 1, 0, 2,
  145522. 4, 6, 8, 10, 12,
  145523. };
  145524. static encode_aux_threshmatch _vq_auxt__44u9_p6_0 = {
  145525. _vq_quantthresh__44u9_p6_0,
  145526. _vq_quantmap__44u9_p6_0,
  145527. 13,
  145528. 13
  145529. };
  145530. static static_codebook _44u9_p6_0 = {
  145531. 2, 169,
  145532. _vq_lengthlist__44u9_p6_0,
  145533. 1, -526516224, 1616117760, 4, 0,
  145534. _vq_quantlist__44u9_p6_0,
  145535. NULL,
  145536. &_vq_auxt__44u9_p6_0,
  145537. NULL,
  145538. 0
  145539. };
  145540. static long _vq_quantlist__44u9_p6_1[] = {
  145541. 2,
  145542. 1,
  145543. 3,
  145544. 0,
  145545. 4,
  145546. };
  145547. static long _vq_lengthlist__44u9_p6_1[] = {
  145548. 4, 4, 4, 5, 5, 4, 5, 4, 5, 5, 4, 4, 5, 5, 5, 5,
  145549. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  145550. };
  145551. static float _vq_quantthresh__44u9_p6_1[] = {
  145552. -1.5, -0.5, 0.5, 1.5,
  145553. };
  145554. static long _vq_quantmap__44u9_p6_1[] = {
  145555. 3, 1, 0, 2, 4,
  145556. };
  145557. static encode_aux_threshmatch _vq_auxt__44u9_p6_1 = {
  145558. _vq_quantthresh__44u9_p6_1,
  145559. _vq_quantmap__44u9_p6_1,
  145560. 5,
  145561. 5
  145562. };
  145563. static static_codebook _44u9_p6_1 = {
  145564. 2, 25,
  145565. _vq_lengthlist__44u9_p6_1,
  145566. 1, -533725184, 1611661312, 3, 0,
  145567. _vq_quantlist__44u9_p6_1,
  145568. NULL,
  145569. &_vq_auxt__44u9_p6_1,
  145570. NULL,
  145571. 0
  145572. };
  145573. static long _vq_quantlist__44u9_p7_0[] = {
  145574. 6,
  145575. 5,
  145576. 7,
  145577. 4,
  145578. 8,
  145579. 3,
  145580. 9,
  145581. 2,
  145582. 10,
  145583. 1,
  145584. 11,
  145585. 0,
  145586. 12,
  145587. };
  145588. static long _vq_lengthlist__44u9_p7_0[] = {
  145589. 1, 4, 5, 6, 6, 7, 7, 8, 9,10,10,11,11, 5, 6, 6,
  145590. 7, 7, 8, 8, 9, 9,10,10,11,11, 5, 6, 6, 7, 7, 8,
  145591. 8, 9, 9,10,10,11,11, 6, 7, 7, 8, 8, 9, 9,10,10,
  145592. 11,11,12,12, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,12,
  145593. 12, 8, 8, 8, 9, 9,10,10,11,11,12,12,13,13, 8, 8,
  145594. 8, 9, 9,10,10,11,11,12,12,13,13, 9, 9, 9,10,10,
  145595. 11,11,12,12,13,13,13,13, 9, 9, 9,10,10,11,11,12,
  145596. 12,13,13,14,14,10,10,10,11,11,12,12,13,13,14,13,
  145597. 15,14,10,10,10,11,11,12,12,13,13,14,14,14,14,11,
  145598. 11,12,12,12,13,13,14,14,14,14,15,15,11,11,12,12,
  145599. 12,13,13,14,14,14,15,15,15,
  145600. };
  145601. static float _vq_quantthresh__44u9_p7_0[] = {
  145602. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  145603. 27.5, 38.5, 49.5, 60.5,
  145604. };
  145605. static long _vq_quantmap__44u9_p7_0[] = {
  145606. 11, 9, 7, 5, 3, 1, 0, 2,
  145607. 4, 6, 8, 10, 12,
  145608. };
  145609. static encode_aux_threshmatch _vq_auxt__44u9_p7_0 = {
  145610. _vq_quantthresh__44u9_p7_0,
  145611. _vq_quantmap__44u9_p7_0,
  145612. 13,
  145613. 13
  145614. };
  145615. static static_codebook _44u9_p7_0 = {
  145616. 2, 169,
  145617. _vq_lengthlist__44u9_p7_0,
  145618. 1, -523206656, 1618345984, 4, 0,
  145619. _vq_quantlist__44u9_p7_0,
  145620. NULL,
  145621. &_vq_auxt__44u9_p7_0,
  145622. NULL,
  145623. 0
  145624. };
  145625. static long _vq_quantlist__44u9_p7_1[] = {
  145626. 5,
  145627. 4,
  145628. 6,
  145629. 3,
  145630. 7,
  145631. 2,
  145632. 8,
  145633. 1,
  145634. 9,
  145635. 0,
  145636. 10,
  145637. };
  145638. static long _vq_lengthlist__44u9_p7_1[] = {
  145639. 5, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 7, 7,
  145640. 7, 7, 7, 7, 7, 7, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7,
  145641. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 6, 7, 7, 7,
  145642. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  145643. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  145644. 7, 7, 7, 7, 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  145645. 7, 8, 8, 7, 7, 7, 7, 7, 7, 7, 8, 7, 8, 8, 7, 7,
  145646. 7, 7, 7, 7, 7, 8, 8, 8, 8,
  145647. };
  145648. static float _vq_quantthresh__44u9_p7_1[] = {
  145649. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  145650. 3.5, 4.5,
  145651. };
  145652. static long _vq_quantmap__44u9_p7_1[] = {
  145653. 9, 7, 5, 3, 1, 0, 2, 4,
  145654. 6, 8, 10,
  145655. };
  145656. static encode_aux_threshmatch _vq_auxt__44u9_p7_1 = {
  145657. _vq_quantthresh__44u9_p7_1,
  145658. _vq_quantmap__44u9_p7_1,
  145659. 11,
  145660. 11
  145661. };
  145662. static static_codebook _44u9_p7_1 = {
  145663. 2, 121,
  145664. _vq_lengthlist__44u9_p7_1,
  145665. 1, -531365888, 1611661312, 4, 0,
  145666. _vq_quantlist__44u9_p7_1,
  145667. NULL,
  145668. &_vq_auxt__44u9_p7_1,
  145669. NULL,
  145670. 0
  145671. };
  145672. static long _vq_quantlist__44u9_p8_0[] = {
  145673. 7,
  145674. 6,
  145675. 8,
  145676. 5,
  145677. 9,
  145678. 4,
  145679. 10,
  145680. 3,
  145681. 11,
  145682. 2,
  145683. 12,
  145684. 1,
  145685. 13,
  145686. 0,
  145687. 14,
  145688. };
  145689. static long _vq_lengthlist__44u9_p8_0[] = {
  145690. 1, 4, 4, 7, 7, 8, 8, 8, 8, 9, 9,10, 9,11,10, 4,
  145691. 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,10,12,10, 4, 6,
  145692. 6, 8, 8, 9,10, 9, 9,10,10,11,11,12,12, 7, 8, 8,
  145693. 10,10,11,11,10,10,11,11,12,12,13,12, 7, 8, 8,10,
  145694. 10,11,11,10,10,11,11,12,12,12,13, 8,10, 9,11,11,
  145695. 12,12,11,11,12,12,13,13,14,13, 8, 9, 9,11,11,12,
  145696. 12,11,12,12,12,13,13,14,13, 8, 9, 9,10,10,12,11,
  145697. 13,12,13,13,14,13,15,14, 8, 9, 9,10,10,11,12,12,
  145698. 12,13,13,13,14,14,14, 9,10,10,12,11,13,12,13,13,
  145699. 14,13,14,14,14,15, 9,10,10,11,12,12,12,13,13,14,
  145700. 14,14,15,15,15,10,11,11,12,12,13,13,14,14,14,14,
  145701. 15,14,16,15,10,11,11,12,12,13,13,13,14,14,14,14,
  145702. 14,15,16,11,12,12,13,13,14,13,14,14,15,14,15,16,
  145703. 16,16,11,12,12,13,13,14,13,14,14,15,15,15,16,15,
  145704. 15,
  145705. };
  145706. static float _vq_quantthresh__44u9_p8_0[] = {
  145707. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  145708. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  145709. };
  145710. static long _vq_quantmap__44u9_p8_0[] = {
  145711. 13, 11, 9, 7, 5, 3, 1, 0,
  145712. 2, 4, 6, 8, 10, 12, 14,
  145713. };
  145714. static encode_aux_threshmatch _vq_auxt__44u9_p8_0 = {
  145715. _vq_quantthresh__44u9_p8_0,
  145716. _vq_quantmap__44u9_p8_0,
  145717. 15,
  145718. 15
  145719. };
  145720. static static_codebook _44u9_p8_0 = {
  145721. 2, 225,
  145722. _vq_lengthlist__44u9_p8_0,
  145723. 1, -520986624, 1620377600, 4, 0,
  145724. _vq_quantlist__44u9_p8_0,
  145725. NULL,
  145726. &_vq_auxt__44u9_p8_0,
  145727. NULL,
  145728. 0
  145729. };
  145730. static long _vq_quantlist__44u9_p8_1[] = {
  145731. 10,
  145732. 9,
  145733. 11,
  145734. 8,
  145735. 12,
  145736. 7,
  145737. 13,
  145738. 6,
  145739. 14,
  145740. 5,
  145741. 15,
  145742. 4,
  145743. 16,
  145744. 3,
  145745. 17,
  145746. 2,
  145747. 18,
  145748. 1,
  145749. 19,
  145750. 0,
  145751. 20,
  145752. };
  145753. static long _vq_lengthlist__44u9_p8_1[] = {
  145754. 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  145755. 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  145756. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8,
  145757. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 7,
  145758. 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  145759. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  145760. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9,
  145761. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10, 8, 8,
  145762. 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  145763. 9,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  145764. 10, 9,10, 9,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9,
  145765. 9, 9, 9, 9, 9,10,10, 9,10,10,10,10,10, 9, 9, 9,
  145766. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  145767. 10,10, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  145768. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  145769. 9, 9,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  145770. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  145771. 10, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  145772. 10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  145773. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  145774. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145775. 9, 9, 9, 9,10, 9, 9,10,10,10,10,10,10,10,10,10,
  145776. 10,10,10,10,10, 9, 9, 9,10, 9,10, 9,10,10,10,10,
  145777. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10, 9,10,
  145778. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  145779. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  145780. 10,10,10,10, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  145781. 10,10,10,10,10,10,10,10,10,
  145782. };
  145783. static float _vq_quantthresh__44u9_p8_1[] = {
  145784. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  145785. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  145786. 6.5, 7.5, 8.5, 9.5,
  145787. };
  145788. static long _vq_quantmap__44u9_p8_1[] = {
  145789. 19, 17, 15, 13, 11, 9, 7, 5,
  145790. 3, 1, 0, 2, 4, 6, 8, 10,
  145791. 12, 14, 16, 18, 20,
  145792. };
  145793. static encode_aux_threshmatch _vq_auxt__44u9_p8_1 = {
  145794. _vq_quantthresh__44u9_p8_1,
  145795. _vq_quantmap__44u9_p8_1,
  145796. 21,
  145797. 21
  145798. };
  145799. static static_codebook _44u9_p8_1 = {
  145800. 2, 441,
  145801. _vq_lengthlist__44u9_p8_1,
  145802. 1, -529268736, 1611661312, 5, 0,
  145803. _vq_quantlist__44u9_p8_1,
  145804. NULL,
  145805. &_vq_auxt__44u9_p8_1,
  145806. NULL,
  145807. 0
  145808. };
  145809. static long _vq_quantlist__44u9_p9_0[] = {
  145810. 7,
  145811. 6,
  145812. 8,
  145813. 5,
  145814. 9,
  145815. 4,
  145816. 10,
  145817. 3,
  145818. 11,
  145819. 2,
  145820. 12,
  145821. 1,
  145822. 13,
  145823. 0,
  145824. 14,
  145825. };
  145826. static long _vq_lengthlist__44u9_p9_0[] = {
  145827. 1, 3, 3,11,11,11,11,11,11,11,11,11,11,11,11, 4,
  145828. 10,11,11,11,11,11,11,11,11,11,11,11,11,11, 4,10,
  145829. 10,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145830. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145831. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145832. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145833. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145834. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145835. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145836. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145837. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145838. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145839. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145840. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145841. 10,
  145842. };
  145843. static float _vq_quantthresh__44u9_p9_0[] = {
  145844. -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5, 465.5,
  145845. 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5,
  145846. };
  145847. static long _vq_quantmap__44u9_p9_0[] = {
  145848. 13, 11, 9, 7, 5, 3, 1, 0,
  145849. 2, 4, 6, 8, 10, 12, 14,
  145850. };
  145851. static encode_aux_threshmatch _vq_auxt__44u9_p9_0 = {
  145852. _vq_quantthresh__44u9_p9_0,
  145853. _vq_quantmap__44u9_p9_0,
  145854. 15,
  145855. 15
  145856. };
  145857. static static_codebook _44u9_p9_0 = {
  145858. 2, 225,
  145859. _vq_lengthlist__44u9_p9_0,
  145860. 1, -510036736, 1631393792, 4, 0,
  145861. _vq_quantlist__44u9_p9_0,
  145862. NULL,
  145863. &_vq_auxt__44u9_p9_0,
  145864. NULL,
  145865. 0
  145866. };
  145867. static long _vq_quantlist__44u9_p9_1[] = {
  145868. 9,
  145869. 8,
  145870. 10,
  145871. 7,
  145872. 11,
  145873. 6,
  145874. 12,
  145875. 5,
  145876. 13,
  145877. 4,
  145878. 14,
  145879. 3,
  145880. 15,
  145881. 2,
  145882. 16,
  145883. 1,
  145884. 17,
  145885. 0,
  145886. 18,
  145887. };
  145888. static long _vq_lengthlist__44u9_p9_1[] = {
  145889. 1, 4, 4, 7, 7, 8, 7, 8, 7, 9, 8,10, 9,10,10,11,
  145890. 11,12,12, 4, 7, 6, 9, 9,10, 9, 9, 8,10,10,11,10,
  145891. 12,10,13,12,13,12, 4, 6, 6, 9, 9, 9, 9, 9, 9,10,
  145892. 10,11,11,11,12,12,12,12,12, 7, 9, 8,11,10,10,10,
  145893. 11,10,11,11,12,12,13,12,13,13,13,13, 7, 8, 9,10,
  145894. 10,11,11,10,10,11,11,11,12,13,13,13,13,14,14, 8,
  145895. 9, 9,11,11,12,11,12,12,13,12,12,13,13,14,15,14,
  145896. 14,14, 8, 9, 9,10,11,11,11,12,12,13,12,13,13,14,
  145897. 14,14,15,14,16, 8, 9, 9,11,10,12,12,12,12,15,13,
  145898. 13,13,17,14,15,15,15,14, 8, 9, 9,10,11,11,12,13,
  145899. 12,13,13,13,14,15,14,14,14,16,15, 9,11,10,12,12,
  145900. 13,13,13,13,14,14,16,15,14,14,14,15,15,17, 9,10,
  145901. 10,11,11,13,13,13,14,14,13,15,14,15,14,15,16,15,
  145902. 16,10,11,11,12,12,13,14,15,14,15,14,14,15,17,16,
  145903. 15,15,17,17,10,12,11,13,12,14,14,13,14,15,15,15,
  145904. 15,16,17,17,15,17,16,11,12,12,14,13,15,14,15,16,
  145905. 17,15,17,15,17,15,15,16,17,15,11,11,12,14,14,14,
  145906. 14,14,15,15,16,15,17,17,17,16,17,16,15,12,12,13,
  145907. 14,14,14,15,14,15,15,16,16,17,16,17,15,17,17,16,
  145908. 12,14,12,14,14,15,15,15,14,14,16,16,16,15,16,16,
  145909. 15,17,15,12,13,13,14,15,14,15,17,15,17,16,17,17,
  145910. 17,16,17,16,17,17,12,13,13,14,16,15,15,15,16,15,
  145911. 17,17,15,17,15,17,16,16,17,
  145912. };
  145913. static float _vq_quantthresh__44u9_p9_1[] = {
  145914. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  145915. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  145916. 367.5, 416.5,
  145917. };
  145918. static long _vq_quantmap__44u9_p9_1[] = {
  145919. 17, 15, 13, 11, 9, 7, 5, 3,
  145920. 1, 0, 2, 4, 6, 8, 10, 12,
  145921. 14, 16, 18,
  145922. };
  145923. static encode_aux_threshmatch _vq_auxt__44u9_p9_1 = {
  145924. _vq_quantthresh__44u9_p9_1,
  145925. _vq_quantmap__44u9_p9_1,
  145926. 19,
  145927. 19
  145928. };
  145929. static static_codebook _44u9_p9_1 = {
  145930. 2, 361,
  145931. _vq_lengthlist__44u9_p9_1,
  145932. 1, -518287360, 1622704128, 5, 0,
  145933. _vq_quantlist__44u9_p9_1,
  145934. NULL,
  145935. &_vq_auxt__44u9_p9_1,
  145936. NULL,
  145937. 0
  145938. };
  145939. static long _vq_quantlist__44u9_p9_2[] = {
  145940. 24,
  145941. 23,
  145942. 25,
  145943. 22,
  145944. 26,
  145945. 21,
  145946. 27,
  145947. 20,
  145948. 28,
  145949. 19,
  145950. 29,
  145951. 18,
  145952. 30,
  145953. 17,
  145954. 31,
  145955. 16,
  145956. 32,
  145957. 15,
  145958. 33,
  145959. 14,
  145960. 34,
  145961. 13,
  145962. 35,
  145963. 12,
  145964. 36,
  145965. 11,
  145966. 37,
  145967. 10,
  145968. 38,
  145969. 9,
  145970. 39,
  145971. 8,
  145972. 40,
  145973. 7,
  145974. 41,
  145975. 6,
  145976. 42,
  145977. 5,
  145978. 43,
  145979. 4,
  145980. 44,
  145981. 3,
  145982. 45,
  145983. 2,
  145984. 46,
  145985. 1,
  145986. 47,
  145987. 0,
  145988. 48,
  145989. };
  145990. static long _vq_lengthlist__44u9_p9_2[] = {
  145991. 2, 4, 4, 5, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6,
  145992. 6, 6, 6, 7, 6, 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  145993. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  145994. 7,
  145995. };
  145996. static float _vq_quantthresh__44u9_p9_2[] = {
  145997. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  145998. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  145999. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  146000. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  146001. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  146002. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  146003. };
  146004. static long _vq_quantmap__44u9_p9_2[] = {
  146005. 47, 45, 43, 41, 39, 37, 35, 33,
  146006. 31, 29, 27, 25, 23, 21, 19, 17,
  146007. 15, 13, 11, 9, 7, 5, 3, 1,
  146008. 0, 2, 4, 6, 8, 10, 12, 14,
  146009. 16, 18, 20, 22, 24, 26, 28, 30,
  146010. 32, 34, 36, 38, 40, 42, 44, 46,
  146011. 48,
  146012. };
  146013. static encode_aux_threshmatch _vq_auxt__44u9_p9_2 = {
  146014. _vq_quantthresh__44u9_p9_2,
  146015. _vq_quantmap__44u9_p9_2,
  146016. 49,
  146017. 49
  146018. };
  146019. static static_codebook _44u9_p9_2 = {
  146020. 1, 49,
  146021. _vq_lengthlist__44u9_p9_2,
  146022. 1, -526909440, 1611661312, 6, 0,
  146023. _vq_quantlist__44u9_p9_2,
  146024. NULL,
  146025. &_vq_auxt__44u9_p9_2,
  146026. NULL,
  146027. 0
  146028. };
  146029. static long _huff_lengthlist__44un1__long[] = {
  146030. 5, 6,12, 9,14, 9, 9,19, 6, 1, 5, 5, 8, 7, 9,19,
  146031. 12, 4, 4, 7, 7, 9,11,18, 9, 5, 6, 6, 8, 7, 8,17,
  146032. 14, 8, 7, 8, 8,10,12,18, 9, 6, 8, 6, 8, 6, 8,18,
  146033. 9, 8,11, 8,11, 7, 5,15,16,18,18,18,17,15,11,18,
  146034. };
  146035. static static_codebook _huff_book__44un1__long = {
  146036. 2, 64,
  146037. _huff_lengthlist__44un1__long,
  146038. 0, 0, 0, 0, 0,
  146039. NULL,
  146040. NULL,
  146041. NULL,
  146042. NULL,
  146043. 0
  146044. };
  146045. static long _vq_quantlist__44un1__p1_0[] = {
  146046. 1,
  146047. 0,
  146048. 2,
  146049. };
  146050. static long _vq_lengthlist__44un1__p1_0[] = {
  146051. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  146052. 10,11, 5, 8, 8, 8,11,10, 8,11,10, 4, 9, 9, 8,11,
  146053. 11, 8,11,11, 8,12,11,10,12,14,11,13,13, 7,11,11,
  146054. 10,13,11,11,13,14, 4, 8, 9, 8,11,11, 8,11,12, 7,
  146055. 11,11,11,14,13,10,11,13, 8,11,12,11,13,13,10,14,
  146056. 12,
  146057. };
  146058. static float _vq_quantthresh__44un1__p1_0[] = {
  146059. -0.5, 0.5,
  146060. };
  146061. static long _vq_quantmap__44un1__p1_0[] = {
  146062. 1, 0, 2,
  146063. };
  146064. static encode_aux_threshmatch _vq_auxt__44un1__p1_0 = {
  146065. _vq_quantthresh__44un1__p1_0,
  146066. _vq_quantmap__44un1__p1_0,
  146067. 3,
  146068. 3
  146069. };
  146070. static static_codebook _44un1__p1_0 = {
  146071. 4, 81,
  146072. _vq_lengthlist__44un1__p1_0,
  146073. 1, -535822336, 1611661312, 2, 0,
  146074. _vq_quantlist__44un1__p1_0,
  146075. NULL,
  146076. &_vq_auxt__44un1__p1_0,
  146077. NULL,
  146078. 0
  146079. };
  146080. static long _vq_quantlist__44un1__p2_0[] = {
  146081. 1,
  146082. 0,
  146083. 2,
  146084. };
  146085. static long _vq_lengthlist__44un1__p2_0[] = {
  146086. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  146087. 7, 9, 5, 7, 7, 6, 8, 7, 7, 9, 8, 4, 7, 7, 7, 9,
  146088. 8, 7, 8, 8, 7, 9, 8, 8, 8,10, 9,10,10, 6, 8, 8,
  146089. 7,10, 8, 9,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 9, 6,
  146090. 8, 8, 9,10,10, 7, 8,10, 6, 8, 9, 9,10,10, 8,10,
  146091. 8,
  146092. };
  146093. static float _vq_quantthresh__44un1__p2_0[] = {
  146094. -0.5, 0.5,
  146095. };
  146096. static long _vq_quantmap__44un1__p2_0[] = {
  146097. 1, 0, 2,
  146098. };
  146099. static encode_aux_threshmatch _vq_auxt__44un1__p2_0 = {
  146100. _vq_quantthresh__44un1__p2_0,
  146101. _vq_quantmap__44un1__p2_0,
  146102. 3,
  146103. 3
  146104. };
  146105. static static_codebook _44un1__p2_0 = {
  146106. 4, 81,
  146107. _vq_lengthlist__44un1__p2_0,
  146108. 1, -535822336, 1611661312, 2, 0,
  146109. _vq_quantlist__44un1__p2_0,
  146110. NULL,
  146111. &_vq_auxt__44un1__p2_0,
  146112. NULL,
  146113. 0
  146114. };
  146115. static long _vq_quantlist__44un1__p3_0[] = {
  146116. 2,
  146117. 1,
  146118. 3,
  146119. 0,
  146120. 4,
  146121. };
  146122. static long _vq_lengthlist__44un1__p3_0[] = {
  146123. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  146124. 10, 9,12,12, 9, 9,10,11,12, 6, 8, 8,10,10, 8,10,
  146125. 10,11,11, 8, 9,10,11,11,10,11,11,13,13,10,11,11,
  146126. 12,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10,10,11,
  146127. 11,10,11,11,13,12,10,11,11,13,12, 9,11,11,15,13,
  146128. 10,12,11,15,13,10,11,11,15,14,12,14,13,16,15,12,
  146129. 13,13,17,16, 9,11,11,13,15,10,11,12,14,15,10,11,
  146130. 12,14,15,12,13,13,15,16,12,13,13,16,16, 5, 8, 8,
  146131. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  146132. 14,11,12,12,14,14, 8,11,10,13,12,10,11,12,12,13,
  146133. 10,12,12,13,13,12,12,13,13,15,11,12,13,15,14, 7,
  146134. 10,10,12,12, 9,12,11,13,12,10,12,12,13,14,12,13,
  146135. 12,15,13,11,13,12,14,15,10,12,12,16,14,11,12,12,
  146136. 16,15,11,13,12,17,16,13,13,15,15,17,13,15,15,20,
  146137. 17,10,12,12,14,16,11,12,12,15,15,11,13,13,15,18,
  146138. 13,14,13,15,15,13,15,14,16,16, 5, 8, 8,11,11, 8,
  146139. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  146140. 12,14,15, 7,10,10,13,12,10,12,12,14,13, 9,10,12,
  146141. 12,13,11,13,13,15,15,11,12,13,13,15, 8,10,10,12,
  146142. 13,10,12,12,13,13,10,12,11,13,13,11,13,12,15,15,
  146143. 12,13,12,15,13,10,12,12,16,14,11,12,12,16,15,10,
  146144. 12,12,16,14,14,15,14,18,16,13,13,14,15,16,10,12,
  146145. 12,14,16,11,13,13,16,16,11,13,12,14,16,13,15,15,
  146146. 18,18,13,15,13,16,14, 8,11,11,16,16,10,13,13,17,
  146147. 16,10,12,12,16,15,14,16,15,20,17,13,14,14,17,17,
  146148. 9,12,12,16,16,11,13,14,16,17,11,13,13,16,16,15,
  146149. 15,19,18, 0,14,15,15,18,18, 9,12,12,17,16,11,13,
  146150. 12,17,16,11,12,13,15,17,15,16,15, 0,19,14,15,14,
  146151. 19,18,12,14,14, 0,16,13,14,14,19,18,13,15,16,17,
  146152. 16,15,15,17,18, 0,14,16,16,19, 0,12,14,14,16,18,
  146153. 13,15,13,17,18,13,15,14,17,18,15,18,14,18,18,16,
  146154. 17,16, 0,17, 8,11,11,15,15,10,12,12,16,16,10,13,
  146155. 13,16,16,13,15,14,17,17,14,15,17,17,18, 9,12,12,
  146156. 16,15,11,13,13,16,16,11,12,13,17,17,14,14,15,17,
  146157. 17,14,15,16, 0,18, 9,12,12,16,17,11,13,13,16,17,
  146158. 11,14,13,18,17,14,16,14,17,17,15,17,17,18,18,12,
  146159. 14,14, 0,16,13,15,15,19, 0,12,13,15, 0, 0,14,17,
  146160. 16,19, 0,16,15,18,18, 0,12,14,14,17, 0,13,14,14,
  146161. 17, 0,13,15,14, 0,18,15,16,16, 0,18,15,18,15, 0,
  146162. 17,
  146163. };
  146164. static float _vq_quantthresh__44un1__p3_0[] = {
  146165. -1.5, -0.5, 0.5, 1.5,
  146166. };
  146167. static long _vq_quantmap__44un1__p3_0[] = {
  146168. 3, 1, 0, 2, 4,
  146169. };
  146170. static encode_aux_threshmatch _vq_auxt__44un1__p3_0 = {
  146171. _vq_quantthresh__44un1__p3_0,
  146172. _vq_quantmap__44un1__p3_0,
  146173. 5,
  146174. 5
  146175. };
  146176. static static_codebook _44un1__p3_0 = {
  146177. 4, 625,
  146178. _vq_lengthlist__44un1__p3_0,
  146179. 1, -533725184, 1611661312, 3, 0,
  146180. _vq_quantlist__44un1__p3_0,
  146181. NULL,
  146182. &_vq_auxt__44un1__p3_0,
  146183. NULL,
  146184. 0
  146185. };
  146186. static long _vq_quantlist__44un1__p4_0[] = {
  146187. 2,
  146188. 1,
  146189. 3,
  146190. 0,
  146191. 4,
  146192. };
  146193. static long _vq_lengthlist__44un1__p4_0[] = {
  146194. 3, 5, 5, 9, 9, 5, 6, 6,10, 9, 5, 6, 6, 9,10,10,
  146195. 10,10,12,11, 9,10,10,12,12, 5, 7, 7,10,10, 7, 7,
  146196. 8,10,11, 7, 7, 8,10,11,10,10,11,11,13,10,10,11,
  146197. 11,13, 6, 7, 7,10,10, 7, 8, 7,11,10, 7, 8, 7,10,
  146198. 10,10,11, 9,13,11,10,11,10,13,11,10,10,10,14,13,
  146199. 10,11,11,14,13,10,10,11,13,14,12,12,13,15,15,12,
  146200. 12,13,13,14,10,10,10,12,13,10,11,10,13,13,10,11,
  146201. 11,13,13,12,13,12,14,13,12,13,13,14,13, 5, 7, 7,
  146202. 10,10, 7, 8, 8,11,10, 7, 8, 8,10,10,11,11,11,13,
  146203. 13,10,11,11,12,12, 7, 8, 8,11,11, 7, 8, 9,10,12,
  146204. 8, 9, 9,11,11,11,10,12,11,14,11,11,12,13,13, 6,
  146205. 8, 8,10,11, 7, 9, 7,12,10, 8, 9,10,11,12,10,12,
  146206. 10,14,11,11,12,11,13,13,10,11,11,14,14,10,10,11,
  146207. 13,14,11,12,12,15,13,12,11,14,12,16,12,13,14,15,
  146208. 16,10,10,11,13,14,10,11,10,14,12,11,12,12,13,14,
  146209. 12,13,11,15,12,14,14,14,15,15, 5, 7, 7,10,10, 7,
  146210. 8, 8,10,10, 7, 8, 8,10,11,10,11,10,12,12,10,11,
  146211. 11,12,13, 6, 8, 8,11,11, 8, 9, 9,12,11, 7, 7, 9,
  146212. 10,12,11,11,11,12,13,11,10,12,11,15, 7, 8, 8,11,
  146213. 11, 8, 9, 9,11,11, 7, 9, 8,12,10,11,12,11,13,12,
  146214. 11,12,10,15,11,10,11,10,14,12,11,12,11,14,13,10,
  146215. 10,11,13,14,13,13,13,17,15,12,11,14,12,15,10,10,
  146216. 11,13,14,11,12,12,14,14,10,11,10,14,13,13,14,13,
  146217. 16,17,12,14,11,16,12, 9,10,10,14,13,10,11,10,14,
  146218. 14,10,11,11,13,13,13,14,14,16,15,12,13,13,14,14,
  146219. 9,11,10,14,13,10,10,12,13,14,11,12,11,14,13,13,
  146220. 14,14,14,15,13,14,14,15,15, 9,10,11,13,14,10,11,
  146221. 10,15,13,11,11,12,12,15,13,14,12,15,14,13,13,14,
  146222. 14,15,12,13,12,16,14,11,11,12,15,14,13,15,13,16,
  146223. 14,13,12,15,12,17,15,16,15,16,16,12,12,13,13,15,
  146224. 11,13,11,15,14,13,13,14,15,17,13,14,12, 0,13,14,
  146225. 15,14,15, 0, 9,10,10,13,13,10,11,11,13,13,10,11,
  146226. 11,13,13,12,13,12,14,14,13,14,14,15,17, 9,10,10,
  146227. 13,13,11,12,11,15,12,10,10,11,13,16,13,14,13,15,
  146228. 14,13,13,14,15,16,10,10,11,13,14,11,11,12,13,14,
  146229. 10,12,11,14,14,13,13,13,14,15,13,15,13,16,15,12,
  146230. 13,12,15,13,12,15,13,15,15,11,11,13,14,15,15,15,
  146231. 15,15,17,13,12,14,13,17,12,12,14,14,15,13,13,14,
  146232. 14,16,11,13,11,16,15,14,16,16,17, 0,14,13,11,16,
  146233. 12,
  146234. };
  146235. static float _vq_quantthresh__44un1__p4_0[] = {
  146236. -1.5, -0.5, 0.5, 1.5,
  146237. };
  146238. static long _vq_quantmap__44un1__p4_0[] = {
  146239. 3, 1, 0, 2, 4,
  146240. };
  146241. static encode_aux_threshmatch _vq_auxt__44un1__p4_0 = {
  146242. _vq_quantthresh__44un1__p4_0,
  146243. _vq_quantmap__44un1__p4_0,
  146244. 5,
  146245. 5
  146246. };
  146247. static static_codebook _44un1__p4_0 = {
  146248. 4, 625,
  146249. _vq_lengthlist__44un1__p4_0,
  146250. 1, -533725184, 1611661312, 3, 0,
  146251. _vq_quantlist__44un1__p4_0,
  146252. NULL,
  146253. &_vq_auxt__44un1__p4_0,
  146254. NULL,
  146255. 0
  146256. };
  146257. static long _vq_quantlist__44un1__p5_0[] = {
  146258. 4,
  146259. 3,
  146260. 5,
  146261. 2,
  146262. 6,
  146263. 1,
  146264. 7,
  146265. 0,
  146266. 8,
  146267. };
  146268. static long _vq_lengthlist__44un1__p5_0[] = {
  146269. 1, 4, 4, 7, 7, 8, 8, 9, 9, 4, 6, 5, 8, 7, 8, 8,
  146270. 10, 9, 4, 6, 6, 8, 8, 8, 8,10,10, 7, 8, 7, 9, 9,
  146271. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,11, 8, 8, 8,
  146272. 9, 9,10,10,11,11, 8, 8, 8, 9, 9,10,10,11,11, 9,
  146273. 10,10,11,10,11,11,12,12, 9,10,10,10,11,11,11,12,
  146274. 12,
  146275. };
  146276. static float _vq_quantthresh__44un1__p5_0[] = {
  146277. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  146278. };
  146279. static long _vq_quantmap__44un1__p5_0[] = {
  146280. 7, 5, 3, 1, 0, 2, 4, 6,
  146281. 8,
  146282. };
  146283. static encode_aux_threshmatch _vq_auxt__44un1__p5_0 = {
  146284. _vq_quantthresh__44un1__p5_0,
  146285. _vq_quantmap__44un1__p5_0,
  146286. 9,
  146287. 9
  146288. };
  146289. static static_codebook _44un1__p5_0 = {
  146290. 2, 81,
  146291. _vq_lengthlist__44un1__p5_0,
  146292. 1, -531628032, 1611661312, 4, 0,
  146293. _vq_quantlist__44un1__p5_0,
  146294. NULL,
  146295. &_vq_auxt__44un1__p5_0,
  146296. NULL,
  146297. 0
  146298. };
  146299. static long _vq_quantlist__44un1__p6_0[] = {
  146300. 6,
  146301. 5,
  146302. 7,
  146303. 4,
  146304. 8,
  146305. 3,
  146306. 9,
  146307. 2,
  146308. 10,
  146309. 1,
  146310. 11,
  146311. 0,
  146312. 12,
  146313. };
  146314. static long _vq_lengthlist__44un1__p6_0[] = {
  146315. 1, 4, 4, 6, 6, 8, 8,10,10,11,11,15,15, 4, 5, 5,
  146316. 8, 8, 9, 9,11,11,12,12,16,16, 4, 5, 6, 8, 8, 9,
  146317. 9,11,11,12,12,14,14, 7, 8, 8, 9, 9,10,10,11,12,
  146318. 13,13,16,17, 7, 8, 8, 9, 9,10,10,12,12,12,13,15,
  146319. 15, 9,10,10,10,10,11,11,12,12,13,13,15,16, 9, 9,
  146320. 9,10,10,11,11,13,12,13,13,17,17,10,11,11,11,12,
  146321. 12,12,13,13,14,15, 0,18,10,11,11,12,12,12,13,14,
  146322. 13,14,14,17,16,11,12,12,13,13,14,14,14,14,15,16,
  146323. 17,16,11,12,12,13,13,14,14,14,14,15,15,17,17,14,
  146324. 15,15,16,16,16,17,17,16, 0,17, 0,18,14,15,15,16,
  146325. 16, 0,15,18,18, 0,16, 0, 0,
  146326. };
  146327. static float _vq_quantthresh__44un1__p6_0[] = {
  146328. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  146329. 12.5, 17.5, 22.5, 27.5,
  146330. };
  146331. static long _vq_quantmap__44un1__p6_0[] = {
  146332. 11, 9, 7, 5, 3, 1, 0, 2,
  146333. 4, 6, 8, 10, 12,
  146334. };
  146335. static encode_aux_threshmatch _vq_auxt__44un1__p6_0 = {
  146336. _vq_quantthresh__44un1__p6_0,
  146337. _vq_quantmap__44un1__p6_0,
  146338. 13,
  146339. 13
  146340. };
  146341. static static_codebook _44un1__p6_0 = {
  146342. 2, 169,
  146343. _vq_lengthlist__44un1__p6_0,
  146344. 1, -526516224, 1616117760, 4, 0,
  146345. _vq_quantlist__44un1__p6_0,
  146346. NULL,
  146347. &_vq_auxt__44un1__p6_0,
  146348. NULL,
  146349. 0
  146350. };
  146351. static long _vq_quantlist__44un1__p6_1[] = {
  146352. 2,
  146353. 1,
  146354. 3,
  146355. 0,
  146356. 4,
  146357. };
  146358. static long _vq_lengthlist__44un1__p6_1[] = {
  146359. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 6, 5, 5,
  146360. 6, 5, 6, 6, 5, 6, 6, 6, 6,
  146361. };
  146362. static float _vq_quantthresh__44un1__p6_1[] = {
  146363. -1.5, -0.5, 0.5, 1.5,
  146364. };
  146365. static long _vq_quantmap__44un1__p6_1[] = {
  146366. 3, 1, 0, 2, 4,
  146367. };
  146368. static encode_aux_threshmatch _vq_auxt__44un1__p6_1 = {
  146369. _vq_quantthresh__44un1__p6_1,
  146370. _vq_quantmap__44un1__p6_1,
  146371. 5,
  146372. 5
  146373. };
  146374. static static_codebook _44un1__p6_1 = {
  146375. 2, 25,
  146376. _vq_lengthlist__44un1__p6_1,
  146377. 1, -533725184, 1611661312, 3, 0,
  146378. _vq_quantlist__44un1__p6_1,
  146379. NULL,
  146380. &_vq_auxt__44un1__p6_1,
  146381. NULL,
  146382. 0
  146383. };
  146384. static long _vq_quantlist__44un1__p7_0[] = {
  146385. 2,
  146386. 1,
  146387. 3,
  146388. 0,
  146389. 4,
  146390. };
  146391. static long _vq_lengthlist__44un1__p7_0[] = {
  146392. 1, 5, 3,11,11,11,11,11,11,11, 8,11,11,11,11,11,
  146393. 11,11,11,11,11,11,11,11,11,10,11,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,10,11,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, 8,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,10,
  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, 7,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,10,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. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146415. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146416. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146417. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146418. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146419. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146420. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146421. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146422. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146423. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146424. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146425. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146426. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146427. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146428. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146429. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146430. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146431. 10,
  146432. };
  146433. static float _vq_quantthresh__44un1__p7_0[] = {
  146434. -253.5, -84.5, 84.5, 253.5,
  146435. };
  146436. static long _vq_quantmap__44un1__p7_0[] = {
  146437. 3, 1, 0, 2, 4,
  146438. };
  146439. static encode_aux_threshmatch _vq_auxt__44un1__p7_0 = {
  146440. _vq_quantthresh__44un1__p7_0,
  146441. _vq_quantmap__44un1__p7_0,
  146442. 5,
  146443. 5
  146444. };
  146445. static static_codebook _44un1__p7_0 = {
  146446. 4, 625,
  146447. _vq_lengthlist__44un1__p7_0,
  146448. 1, -518709248, 1626677248, 3, 0,
  146449. _vq_quantlist__44un1__p7_0,
  146450. NULL,
  146451. &_vq_auxt__44un1__p7_0,
  146452. NULL,
  146453. 0
  146454. };
  146455. static long _vq_quantlist__44un1__p7_1[] = {
  146456. 6,
  146457. 5,
  146458. 7,
  146459. 4,
  146460. 8,
  146461. 3,
  146462. 9,
  146463. 2,
  146464. 10,
  146465. 1,
  146466. 11,
  146467. 0,
  146468. 12,
  146469. };
  146470. static long _vq_lengthlist__44un1__p7_1[] = {
  146471. 1, 4, 4, 6, 6, 6, 6, 9, 8, 9, 8, 8, 8, 5, 7, 7,
  146472. 7, 7, 8, 8, 8,10, 8,10, 8, 9, 5, 7, 7, 8, 7, 7,
  146473. 8,10,10,11,10,12,11, 7, 8, 8, 9, 9, 9,10,11,11,
  146474. 11,11,11,11, 7, 8, 8, 8, 9, 9, 9,10,10,10,11,11,
  146475. 12, 7, 8, 8, 9, 9,10,11,11,12,11,12,11,11, 7, 8,
  146476. 8, 9, 9,10,10,11,11,11,12,12,11, 8,10,10,10,10,
  146477. 11,11,14,11,12,12,12,13, 9,10,10,10,10,12,11,14,
  146478. 11,14,11,12,13,10,11,11,11,11,13,11,14,14,13,13,
  146479. 13,14,11,11,11,12,11,12,12,12,13,14,14,13,14,12,
  146480. 11,12,12,12,12,13,13,13,14,13,14,14,11,12,12,14,
  146481. 12,13,13,12,13,13,14,14,14,
  146482. };
  146483. static float _vq_quantthresh__44un1__p7_1[] = {
  146484. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  146485. 32.5, 45.5, 58.5, 71.5,
  146486. };
  146487. static long _vq_quantmap__44un1__p7_1[] = {
  146488. 11, 9, 7, 5, 3, 1, 0, 2,
  146489. 4, 6, 8, 10, 12,
  146490. };
  146491. static encode_aux_threshmatch _vq_auxt__44un1__p7_1 = {
  146492. _vq_quantthresh__44un1__p7_1,
  146493. _vq_quantmap__44un1__p7_1,
  146494. 13,
  146495. 13
  146496. };
  146497. static static_codebook _44un1__p7_1 = {
  146498. 2, 169,
  146499. _vq_lengthlist__44un1__p7_1,
  146500. 1, -523010048, 1618608128, 4, 0,
  146501. _vq_quantlist__44un1__p7_1,
  146502. NULL,
  146503. &_vq_auxt__44un1__p7_1,
  146504. NULL,
  146505. 0
  146506. };
  146507. static long _vq_quantlist__44un1__p7_2[] = {
  146508. 6,
  146509. 5,
  146510. 7,
  146511. 4,
  146512. 8,
  146513. 3,
  146514. 9,
  146515. 2,
  146516. 10,
  146517. 1,
  146518. 11,
  146519. 0,
  146520. 12,
  146521. };
  146522. static long _vq_lengthlist__44un1__p7_2[] = {
  146523. 3, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9, 9, 8, 4, 5, 5,
  146524. 6, 6, 8, 8, 9, 8, 9, 9, 9, 9, 4, 5, 5, 7, 6, 8,
  146525. 8, 8, 8, 9, 8, 9, 8, 6, 7, 7, 7, 8, 8, 8, 9, 9,
  146526. 9, 9, 9, 9, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  146527. 9, 7, 8, 8, 8, 8, 9, 8, 9, 9,10, 9, 9,10, 7, 8,
  146528. 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10, 8, 9, 9, 9, 9,
  146529. 9, 9, 9, 9,10,10, 9,10, 8, 9, 9, 9, 9, 9, 9, 9,
  146530. 9, 9, 9,10,10, 9, 9, 9,10, 9, 9,10, 9, 9,10,10,
  146531. 10,10, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10, 9,
  146532. 9, 9,10, 9, 9,10,10, 9,10,10,10,10, 9, 9, 9,10,
  146533. 9, 9, 9,10,10,10,10,10,10,
  146534. };
  146535. static float _vq_quantthresh__44un1__p7_2[] = {
  146536. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  146537. 2.5, 3.5, 4.5, 5.5,
  146538. };
  146539. static long _vq_quantmap__44un1__p7_2[] = {
  146540. 11, 9, 7, 5, 3, 1, 0, 2,
  146541. 4, 6, 8, 10, 12,
  146542. };
  146543. static encode_aux_threshmatch _vq_auxt__44un1__p7_2 = {
  146544. _vq_quantthresh__44un1__p7_2,
  146545. _vq_quantmap__44un1__p7_2,
  146546. 13,
  146547. 13
  146548. };
  146549. static static_codebook _44un1__p7_2 = {
  146550. 2, 169,
  146551. _vq_lengthlist__44un1__p7_2,
  146552. 1, -531103744, 1611661312, 4, 0,
  146553. _vq_quantlist__44un1__p7_2,
  146554. NULL,
  146555. &_vq_auxt__44un1__p7_2,
  146556. NULL,
  146557. 0
  146558. };
  146559. static long _huff_lengthlist__44un1__short[] = {
  146560. 12,12,14,12,14,14,14,14,12, 6, 6, 8, 9, 9,11,14,
  146561. 12, 4, 2, 6, 6, 7,11,14,13, 6, 5, 7, 8, 9,11,14,
  146562. 13, 8, 5, 8, 6, 8,12,14,12, 7, 7, 8, 8, 8,10,14,
  146563. 12, 6, 3, 4, 4, 4, 7,14,11, 7, 4, 6, 6, 6, 8,14,
  146564. };
  146565. static static_codebook _huff_book__44un1__short = {
  146566. 2, 64,
  146567. _huff_lengthlist__44un1__short,
  146568. 0, 0, 0, 0, 0,
  146569. NULL,
  146570. NULL,
  146571. NULL,
  146572. NULL,
  146573. 0
  146574. };
  146575. /********* End of inlined file: res_books_uncoupled.h *********/
  146576. /***** residue backends *********************************************/
  146577. static vorbis_info_residue0 _residue_44_low_un={
  146578. 0,-1, -1, 8,-1,
  146579. {0},
  146580. {-1},
  146581. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 28.5},
  146582. { -1, 25, -1, 45, -1, -1, -1}
  146583. };
  146584. static vorbis_info_residue0 _residue_44_mid_un={
  146585. 0,-1, -1, 10,-1,
  146586. /* 0 1 2 3 4 5 6 7 8 9 */
  146587. {0},
  146588. {-1},
  146589. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 4.5, 16.5, 60.5},
  146590. { -1, 30, -1, 50, -1, 80, -1, -1, -1}
  146591. };
  146592. static vorbis_info_residue0 _residue_44_hi_un={
  146593. 0,-1, -1, 10,-1,
  146594. /* 0 1 2 3 4 5 6 7 8 9 */
  146595. {0},
  146596. {-1},
  146597. { .5, 1.5, 2.5, 4.5, 8.5, 16.5, 32.5, 71.5,157.5},
  146598. { -1, -1, -1, -1, -1, -1, -1, -1, -1}
  146599. };
  146600. /* mapping conventions:
  146601. only one submap (this would change for efficient 5.1 support for example)*/
  146602. /* Four psychoacoustic profiles are used, one for each blocktype */
  146603. static vorbis_info_mapping0 _map_nominal_u[2]={
  146604. {1, {0,0}, {0}, {0}, 0,{0},{0}},
  146605. {1, {0,0}, {1}, {1}, 0,{0},{0}}
  146606. };
  146607. static static_bookblock _resbook_44u_n1={
  146608. {
  146609. {0},
  146610. {0,0,&_44un1__p1_0},
  146611. {0,0,&_44un1__p2_0},
  146612. {0,0,&_44un1__p3_0},
  146613. {0,0,&_44un1__p4_0},
  146614. {0,0,&_44un1__p5_0},
  146615. {&_44un1__p6_0,&_44un1__p6_1},
  146616. {&_44un1__p7_0,&_44un1__p7_1,&_44un1__p7_2}
  146617. }
  146618. };
  146619. static static_bookblock _resbook_44u_0={
  146620. {
  146621. {0},
  146622. {0,0,&_44u0__p1_0},
  146623. {0,0,&_44u0__p2_0},
  146624. {0,0,&_44u0__p3_0},
  146625. {0,0,&_44u0__p4_0},
  146626. {0,0,&_44u0__p5_0},
  146627. {&_44u0__p6_0,&_44u0__p6_1},
  146628. {&_44u0__p7_0,&_44u0__p7_1,&_44u0__p7_2}
  146629. }
  146630. };
  146631. static static_bookblock _resbook_44u_1={
  146632. {
  146633. {0},
  146634. {0,0,&_44u1__p1_0},
  146635. {0,0,&_44u1__p2_0},
  146636. {0,0,&_44u1__p3_0},
  146637. {0,0,&_44u1__p4_0},
  146638. {0,0,&_44u1__p5_0},
  146639. {&_44u1__p6_0,&_44u1__p6_1},
  146640. {&_44u1__p7_0,&_44u1__p7_1,&_44u1__p7_2}
  146641. }
  146642. };
  146643. static static_bookblock _resbook_44u_2={
  146644. {
  146645. {0},
  146646. {0,0,&_44u2__p1_0},
  146647. {0,0,&_44u2__p2_0},
  146648. {0,0,&_44u2__p3_0},
  146649. {0,0,&_44u2__p4_0},
  146650. {0,0,&_44u2__p5_0},
  146651. {&_44u2__p6_0,&_44u2__p6_1},
  146652. {&_44u2__p7_0,&_44u2__p7_1,&_44u2__p7_2}
  146653. }
  146654. };
  146655. static static_bookblock _resbook_44u_3={
  146656. {
  146657. {0},
  146658. {0,0,&_44u3__p1_0},
  146659. {0,0,&_44u3__p2_0},
  146660. {0,0,&_44u3__p3_0},
  146661. {0,0,&_44u3__p4_0},
  146662. {0,0,&_44u3__p5_0},
  146663. {&_44u3__p6_0,&_44u3__p6_1},
  146664. {&_44u3__p7_0,&_44u3__p7_1,&_44u3__p7_2}
  146665. }
  146666. };
  146667. static static_bookblock _resbook_44u_4={
  146668. {
  146669. {0},
  146670. {0,0,&_44u4__p1_0},
  146671. {0,0,&_44u4__p2_0},
  146672. {0,0,&_44u4__p3_0},
  146673. {0,0,&_44u4__p4_0},
  146674. {0,0,&_44u4__p5_0},
  146675. {&_44u4__p6_0,&_44u4__p6_1},
  146676. {&_44u4__p7_0,&_44u4__p7_1,&_44u4__p7_2}
  146677. }
  146678. };
  146679. static static_bookblock _resbook_44u_5={
  146680. {
  146681. {0},
  146682. {0,0,&_44u5__p1_0},
  146683. {0,0,&_44u5__p2_0},
  146684. {0,0,&_44u5__p3_0},
  146685. {0,0,&_44u5__p4_0},
  146686. {0,0,&_44u5__p5_0},
  146687. {0,0,&_44u5__p6_0},
  146688. {&_44u5__p7_0,&_44u5__p7_1},
  146689. {&_44u5__p8_0,&_44u5__p8_1},
  146690. {&_44u5__p9_0,&_44u5__p9_1,&_44u5__p9_2}
  146691. }
  146692. };
  146693. static static_bookblock _resbook_44u_6={
  146694. {
  146695. {0},
  146696. {0,0,&_44u6__p1_0},
  146697. {0,0,&_44u6__p2_0},
  146698. {0,0,&_44u6__p3_0},
  146699. {0,0,&_44u6__p4_0},
  146700. {0,0,&_44u6__p5_0},
  146701. {0,0,&_44u6__p6_0},
  146702. {&_44u6__p7_0,&_44u6__p7_1},
  146703. {&_44u6__p8_0,&_44u6__p8_1},
  146704. {&_44u6__p9_0,&_44u6__p9_1,&_44u6__p9_2}
  146705. }
  146706. };
  146707. static static_bookblock _resbook_44u_7={
  146708. {
  146709. {0},
  146710. {0,0,&_44u7__p1_0},
  146711. {0,0,&_44u7__p2_0},
  146712. {0,0,&_44u7__p3_0},
  146713. {0,0,&_44u7__p4_0},
  146714. {0,0,&_44u7__p5_0},
  146715. {0,0,&_44u7__p6_0},
  146716. {&_44u7__p7_0,&_44u7__p7_1},
  146717. {&_44u7__p8_0,&_44u7__p8_1},
  146718. {&_44u7__p9_0,&_44u7__p9_1,&_44u7__p9_2}
  146719. }
  146720. };
  146721. static static_bookblock _resbook_44u_8={
  146722. {
  146723. {0},
  146724. {0,0,&_44u8_p1_0},
  146725. {0,0,&_44u8_p2_0},
  146726. {0,0,&_44u8_p3_0},
  146727. {0,0,&_44u8_p4_0},
  146728. {&_44u8_p5_0,&_44u8_p5_1},
  146729. {&_44u8_p6_0,&_44u8_p6_1},
  146730. {&_44u8_p7_0,&_44u8_p7_1},
  146731. {&_44u8_p8_0,&_44u8_p8_1},
  146732. {&_44u8_p9_0,&_44u8_p9_1,&_44u8_p9_2}
  146733. }
  146734. };
  146735. static static_bookblock _resbook_44u_9={
  146736. {
  146737. {0},
  146738. {0,0,&_44u9_p1_0},
  146739. {0,0,&_44u9_p2_0},
  146740. {0,0,&_44u9_p3_0},
  146741. {0,0,&_44u9_p4_0},
  146742. {&_44u9_p5_0,&_44u9_p5_1},
  146743. {&_44u9_p6_0,&_44u9_p6_1},
  146744. {&_44u9_p7_0,&_44u9_p7_1},
  146745. {&_44u9_p8_0,&_44u9_p8_1},
  146746. {&_44u9_p9_0,&_44u9_p9_1,&_44u9_p9_2}
  146747. }
  146748. };
  146749. static vorbis_residue_template _res_44u_n1[]={
  146750. {1,0, &_residue_44_low_un,
  146751. &_huff_book__44un1__short,&_huff_book__44un1__short,
  146752. &_resbook_44u_n1,&_resbook_44u_n1},
  146753. {1,0, &_residue_44_low_un,
  146754. &_huff_book__44un1__long,&_huff_book__44un1__long,
  146755. &_resbook_44u_n1,&_resbook_44u_n1}
  146756. };
  146757. static vorbis_residue_template _res_44u_0[]={
  146758. {1,0, &_residue_44_low_un,
  146759. &_huff_book__44u0__short,&_huff_book__44u0__short,
  146760. &_resbook_44u_0,&_resbook_44u_0},
  146761. {1,0, &_residue_44_low_un,
  146762. &_huff_book__44u0__long,&_huff_book__44u0__long,
  146763. &_resbook_44u_0,&_resbook_44u_0}
  146764. };
  146765. static vorbis_residue_template _res_44u_1[]={
  146766. {1,0, &_residue_44_low_un,
  146767. &_huff_book__44u1__short,&_huff_book__44u1__short,
  146768. &_resbook_44u_1,&_resbook_44u_1},
  146769. {1,0, &_residue_44_low_un,
  146770. &_huff_book__44u1__long,&_huff_book__44u1__long,
  146771. &_resbook_44u_1,&_resbook_44u_1}
  146772. };
  146773. static vorbis_residue_template _res_44u_2[]={
  146774. {1,0, &_residue_44_low_un,
  146775. &_huff_book__44u2__short,&_huff_book__44u2__short,
  146776. &_resbook_44u_2,&_resbook_44u_2},
  146777. {1,0, &_residue_44_low_un,
  146778. &_huff_book__44u2__long,&_huff_book__44u2__long,
  146779. &_resbook_44u_2,&_resbook_44u_2}
  146780. };
  146781. static vorbis_residue_template _res_44u_3[]={
  146782. {1,0, &_residue_44_low_un,
  146783. &_huff_book__44u3__short,&_huff_book__44u3__short,
  146784. &_resbook_44u_3,&_resbook_44u_3},
  146785. {1,0, &_residue_44_low_un,
  146786. &_huff_book__44u3__long,&_huff_book__44u3__long,
  146787. &_resbook_44u_3,&_resbook_44u_3}
  146788. };
  146789. static vorbis_residue_template _res_44u_4[]={
  146790. {1,0, &_residue_44_low_un,
  146791. &_huff_book__44u4__short,&_huff_book__44u4__short,
  146792. &_resbook_44u_4,&_resbook_44u_4},
  146793. {1,0, &_residue_44_low_un,
  146794. &_huff_book__44u4__long,&_huff_book__44u4__long,
  146795. &_resbook_44u_4,&_resbook_44u_4}
  146796. };
  146797. static vorbis_residue_template _res_44u_5[]={
  146798. {1,0, &_residue_44_mid_un,
  146799. &_huff_book__44u5__short,&_huff_book__44u5__short,
  146800. &_resbook_44u_5,&_resbook_44u_5},
  146801. {1,0, &_residue_44_mid_un,
  146802. &_huff_book__44u5__long,&_huff_book__44u5__long,
  146803. &_resbook_44u_5,&_resbook_44u_5}
  146804. };
  146805. static vorbis_residue_template _res_44u_6[]={
  146806. {1,0, &_residue_44_mid_un,
  146807. &_huff_book__44u6__short,&_huff_book__44u6__short,
  146808. &_resbook_44u_6,&_resbook_44u_6},
  146809. {1,0, &_residue_44_mid_un,
  146810. &_huff_book__44u6__long,&_huff_book__44u6__long,
  146811. &_resbook_44u_6,&_resbook_44u_6}
  146812. };
  146813. static vorbis_residue_template _res_44u_7[]={
  146814. {1,0, &_residue_44_mid_un,
  146815. &_huff_book__44u7__short,&_huff_book__44u7__short,
  146816. &_resbook_44u_7,&_resbook_44u_7},
  146817. {1,0, &_residue_44_mid_un,
  146818. &_huff_book__44u7__long,&_huff_book__44u7__long,
  146819. &_resbook_44u_7,&_resbook_44u_7}
  146820. };
  146821. static vorbis_residue_template _res_44u_8[]={
  146822. {1,0, &_residue_44_hi_un,
  146823. &_huff_book__44u8__short,&_huff_book__44u8__short,
  146824. &_resbook_44u_8,&_resbook_44u_8},
  146825. {1,0, &_residue_44_hi_un,
  146826. &_huff_book__44u8__long,&_huff_book__44u8__long,
  146827. &_resbook_44u_8,&_resbook_44u_8}
  146828. };
  146829. static vorbis_residue_template _res_44u_9[]={
  146830. {1,0, &_residue_44_hi_un,
  146831. &_huff_book__44u9__short,&_huff_book__44u9__short,
  146832. &_resbook_44u_9,&_resbook_44u_9},
  146833. {1,0, &_residue_44_hi_un,
  146834. &_huff_book__44u9__long,&_huff_book__44u9__long,
  146835. &_resbook_44u_9,&_resbook_44u_9}
  146836. };
  146837. static vorbis_mapping_template _mapres_template_44_uncoupled[]={
  146838. { _map_nominal_u, _res_44u_n1 }, /* -1 */
  146839. { _map_nominal_u, _res_44u_0 }, /* 0 */
  146840. { _map_nominal_u, _res_44u_1 }, /* 1 */
  146841. { _map_nominal_u, _res_44u_2 }, /* 2 */
  146842. { _map_nominal_u, _res_44u_3 }, /* 3 */
  146843. { _map_nominal_u, _res_44u_4 }, /* 4 */
  146844. { _map_nominal_u, _res_44u_5 }, /* 5 */
  146845. { _map_nominal_u, _res_44u_6 }, /* 6 */
  146846. { _map_nominal_u, _res_44u_7 }, /* 7 */
  146847. { _map_nominal_u, _res_44u_8 }, /* 8 */
  146848. { _map_nominal_u, _res_44u_9 }, /* 9 */
  146849. };
  146850. /********* End of inlined file: residue_44u.h *********/
  146851. static double rate_mapping_44_un[12]={
  146852. 32000.,48000.,60000.,70000.,80000.,86000.,
  146853. 96000.,110000.,120000.,140000.,160000.,240001.
  146854. };
  146855. ve_setup_data_template ve_setup_44_uncoupled={
  146856. 11,
  146857. rate_mapping_44_un,
  146858. quality_mapping_44,
  146859. -1,
  146860. 40000,
  146861. 50000,
  146862. blocksize_short_44,
  146863. blocksize_long_44,
  146864. _psy_tone_masteratt_44,
  146865. _psy_tone_0dB,
  146866. _psy_tone_suppress,
  146867. _vp_tonemask_adj_otherblock,
  146868. _vp_tonemask_adj_longblock,
  146869. _vp_tonemask_adj_otherblock,
  146870. _psy_noiseguards_44,
  146871. _psy_noisebias_impulse,
  146872. _psy_noisebias_padding,
  146873. _psy_noisebias_trans,
  146874. _psy_noisebias_long,
  146875. _psy_noise_suppress,
  146876. _psy_compand_44,
  146877. _psy_compand_short_mapping,
  146878. _psy_compand_long_mapping,
  146879. {_noise_start_short_44,_noise_start_long_44},
  146880. {_noise_part_short_44,_noise_part_long_44},
  146881. _noise_thresh_44,
  146882. _psy_ath_floater,
  146883. _psy_ath_abs,
  146884. _psy_lowpass_44,
  146885. _psy_global_44,
  146886. _global_mapping_44,
  146887. NULL,
  146888. _floor_books,
  146889. _floor,
  146890. _floor_short_mapping_44,
  146891. _floor_long_mapping_44,
  146892. _mapres_template_44_uncoupled
  146893. };
  146894. /********* End of inlined file: setup_44u.h *********/
  146895. /********* Start of inlined file: setup_32.h *********/
  146896. static double rate_mapping_32[12]={
  146897. 18000.,28000.,35000.,45000.,56000.,60000.,
  146898. 75000.,90000.,100000.,115000.,150000.,190000.,
  146899. };
  146900. static double rate_mapping_32_un[12]={
  146901. 30000.,42000.,52000.,64000.,72000.,78000.,
  146902. 86000.,92000.,110000.,120000.,140000.,190000.,
  146903. };
  146904. static double _psy_lowpass_32[12]={
  146905. 12.3,13.,13.,14.,15.,99.,99.,99.,99.,99.,99.,99.
  146906. };
  146907. ve_setup_data_template ve_setup_32_stereo={
  146908. 11,
  146909. rate_mapping_32,
  146910. quality_mapping_44,
  146911. 2,
  146912. 26000,
  146913. 40000,
  146914. blocksize_short_44,
  146915. blocksize_long_44,
  146916. _psy_tone_masteratt_44,
  146917. _psy_tone_0dB,
  146918. _psy_tone_suppress,
  146919. _vp_tonemask_adj_otherblock,
  146920. _vp_tonemask_adj_longblock,
  146921. _vp_tonemask_adj_otherblock,
  146922. _psy_noiseguards_44,
  146923. _psy_noisebias_impulse,
  146924. _psy_noisebias_padding,
  146925. _psy_noisebias_trans,
  146926. _psy_noisebias_long,
  146927. _psy_noise_suppress,
  146928. _psy_compand_44,
  146929. _psy_compand_short_mapping,
  146930. _psy_compand_long_mapping,
  146931. {_noise_start_short_44,_noise_start_long_44},
  146932. {_noise_part_short_44,_noise_part_long_44},
  146933. _noise_thresh_44,
  146934. _psy_ath_floater,
  146935. _psy_ath_abs,
  146936. _psy_lowpass_32,
  146937. _psy_global_44,
  146938. _global_mapping_44,
  146939. _psy_stereo_modes_44,
  146940. _floor_books,
  146941. _floor,
  146942. _floor_short_mapping_44,
  146943. _floor_long_mapping_44,
  146944. _mapres_template_44_stereo
  146945. };
  146946. ve_setup_data_template ve_setup_32_uncoupled={
  146947. 11,
  146948. rate_mapping_32_un,
  146949. quality_mapping_44,
  146950. -1,
  146951. 26000,
  146952. 40000,
  146953. blocksize_short_44,
  146954. blocksize_long_44,
  146955. _psy_tone_masteratt_44,
  146956. _psy_tone_0dB,
  146957. _psy_tone_suppress,
  146958. _vp_tonemask_adj_otherblock,
  146959. _vp_tonemask_adj_longblock,
  146960. _vp_tonemask_adj_otherblock,
  146961. _psy_noiseguards_44,
  146962. _psy_noisebias_impulse,
  146963. _psy_noisebias_padding,
  146964. _psy_noisebias_trans,
  146965. _psy_noisebias_long,
  146966. _psy_noise_suppress,
  146967. _psy_compand_44,
  146968. _psy_compand_short_mapping,
  146969. _psy_compand_long_mapping,
  146970. {_noise_start_short_44,_noise_start_long_44},
  146971. {_noise_part_short_44,_noise_part_long_44},
  146972. _noise_thresh_44,
  146973. _psy_ath_floater,
  146974. _psy_ath_abs,
  146975. _psy_lowpass_32,
  146976. _psy_global_44,
  146977. _global_mapping_44,
  146978. NULL,
  146979. _floor_books,
  146980. _floor,
  146981. _floor_short_mapping_44,
  146982. _floor_long_mapping_44,
  146983. _mapres_template_44_uncoupled
  146984. };
  146985. /********* End of inlined file: setup_32.h *********/
  146986. /********* Start of inlined file: setup_8.h *********/
  146987. /********* Start of inlined file: psych_8.h *********/
  146988. static att3 _psy_tone_masteratt_8[3]={
  146989. {{ 32, 25, 12}, 0, 0}, /* 0 */
  146990. {{ 30, 25, 12}, 0, 0}, /* 0 */
  146991. {{ 20, 0, -14}, 0, 0}, /* 0 */
  146992. };
  146993. static vp_adjblock _vp_tonemask_adj_8[3]={
  146994. /* adjust for mode zero */
  146995. /* 63 125 250 500 1 2 4 8 16 */
  146996. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0,10, 0, 0,99,99,99}}, /* 1 */
  146997. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0,10, 0, 0,99,99,99}}, /* 1 */
  146998. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0, 0, 0, 0,99,99,99}}, /* 1 */
  146999. };
  147000. static noise3 _psy_noisebias_8[3]={
  147001. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  147002. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 8, 8, 8, 10, 10, 99, 99, 99},
  147003. {-10,-10,-10,-10, -5, -5, -5, 0, 0, 4, 4, 4, 4, 4, 99, 99, 99},
  147004. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  147005. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 8, 8, 8, 10, 10, 99, 99, 99},
  147006. {-10,-10,-10,-10,-10,-10, -5, -5, -5, 0, 0, 0, 0, 0, 99, 99, 99},
  147007. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  147008. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 99, 99, 99},
  147009. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10, 99, 99, 99},
  147010. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24, 99, 99, 99}}},
  147011. };
  147012. /* stereo mode by base quality level */
  147013. static adj_stereo _psy_stereo_modes_8[3]={
  147014. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 */
  147015. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  147016. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  147017. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  147018. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  147019. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  147020. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  147021. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  147022. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  147023. {{ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  147024. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  147025. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  147026. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  147027. };
  147028. static noiseguard _psy_noiseguards_8[2]={
  147029. {10,10,-1},
  147030. {10,10,-1},
  147031. };
  147032. static compandblock _psy_compand_8[2]={
  147033. {{
  147034. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  147035. 8, 8, 9, 9,10,10,11, 11, /* 15dB */
  147036. 12,12,13,13,14,14,15, 15, /* 23dB */
  147037. 16,16,17,17,17,18,18, 19, /* 31dB */
  147038. 19,19,20,21,22,23,24, 25, /* 39dB */
  147039. }},
  147040. {{
  147041. 0, 1, 2, 3, 4, 5, 6, 6, /* 7dB */
  147042. 7, 7, 6, 6, 5, 5, 4, 4, /* 15dB */
  147043. 3, 3, 3, 4, 5, 6, 7, 8, /* 23dB */
  147044. 9,10,11,12,13,14,15, 16, /* 31dB */
  147045. 17,18,19,20,21,22,23, 24, /* 39dB */
  147046. }},
  147047. };
  147048. static double _psy_lowpass_8[3]={3.,4.,4.};
  147049. static int _noise_start_8[2]={
  147050. 64,64,
  147051. };
  147052. static int _noise_part_8[2]={
  147053. 8,8,
  147054. };
  147055. static int _psy_ath_floater_8[3]={
  147056. -100,-100,-105,
  147057. };
  147058. static int _psy_ath_abs_8[3]={
  147059. -130,-130,-140,
  147060. };
  147061. /********* End of inlined file: psych_8.h *********/
  147062. /********* Start of inlined file: residue_8.h *********/
  147063. /***** residue backends *********************************************/
  147064. static static_bookblock _resbook_8s_0={
  147065. {
  147066. {0},{0,0,&_8c0_s_p1_0},{0,0,&_8c0_s_p2_0},{0,0,&_8c0_s_p3_0},
  147067. {0,0,&_8c0_s_p4_0},{0,0,&_8c0_s_p5_0},{0,0,&_8c0_s_p6_0},
  147068. {&_8c0_s_p7_0,&_8c0_s_p7_1},{&_8c0_s_p8_0,&_8c0_s_p8_1},
  147069. {&_8c0_s_p9_0,&_8c0_s_p9_1,&_8c0_s_p9_2}
  147070. }
  147071. };
  147072. static static_bookblock _resbook_8s_1={
  147073. {
  147074. {0},{0,0,&_8c1_s_p1_0},{0,0,&_8c1_s_p2_0},{0,0,&_8c1_s_p3_0},
  147075. {0,0,&_8c1_s_p4_0},{0,0,&_8c1_s_p5_0},{0,0,&_8c1_s_p6_0},
  147076. {&_8c1_s_p7_0,&_8c1_s_p7_1},{&_8c1_s_p8_0,&_8c1_s_p8_1},
  147077. {&_8c1_s_p9_0,&_8c1_s_p9_1,&_8c1_s_p9_2}
  147078. }
  147079. };
  147080. static vorbis_residue_template _res_8s_0[]={
  147081. {2,0, &_residue_44_mid,
  147082. &_huff_book__8c0_s_single,&_huff_book__8c0_s_single,
  147083. &_resbook_8s_0,&_resbook_8s_0},
  147084. };
  147085. static vorbis_residue_template _res_8s_1[]={
  147086. {2,0, &_residue_44_mid,
  147087. &_huff_book__8c1_s_single,&_huff_book__8c1_s_single,
  147088. &_resbook_8s_1,&_resbook_8s_1},
  147089. };
  147090. static vorbis_mapping_template _mapres_template_8_stereo[2]={
  147091. { _map_nominal, _res_8s_0 }, /* 0 */
  147092. { _map_nominal, _res_8s_1 }, /* 1 */
  147093. };
  147094. static static_bookblock _resbook_8u_0={
  147095. {
  147096. {0},
  147097. {0,0,&_8u0__p1_0},
  147098. {0,0,&_8u0__p2_0},
  147099. {0,0,&_8u0__p3_0},
  147100. {0,0,&_8u0__p4_0},
  147101. {0,0,&_8u0__p5_0},
  147102. {&_8u0__p6_0,&_8u0__p6_1},
  147103. {&_8u0__p7_0,&_8u0__p7_1,&_8u0__p7_2}
  147104. }
  147105. };
  147106. static static_bookblock _resbook_8u_1={
  147107. {
  147108. {0},
  147109. {0,0,&_8u1__p1_0},
  147110. {0,0,&_8u1__p2_0},
  147111. {0,0,&_8u1__p3_0},
  147112. {0,0,&_8u1__p4_0},
  147113. {0,0,&_8u1__p5_0},
  147114. {0,0,&_8u1__p6_0},
  147115. {&_8u1__p7_0,&_8u1__p7_1},
  147116. {&_8u1__p8_0,&_8u1__p8_1},
  147117. {&_8u1__p9_0,&_8u1__p9_1,&_8u1__p9_2}
  147118. }
  147119. };
  147120. static vorbis_residue_template _res_8u_0[]={
  147121. {1,0, &_residue_44_low_un,
  147122. &_huff_book__8u0__single,&_huff_book__8u0__single,
  147123. &_resbook_8u_0,&_resbook_8u_0},
  147124. };
  147125. static vorbis_residue_template _res_8u_1[]={
  147126. {1,0, &_residue_44_mid_un,
  147127. &_huff_book__8u1__single,&_huff_book__8u1__single,
  147128. &_resbook_8u_1,&_resbook_8u_1},
  147129. };
  147130. static vorbis_mapping_template _mapres_template_8_uncoupled[2]={
  147131. { _map_nominal_u, _res_8u_0 }, /* 0 */
  147132. { _map_nominal_u, _res_8u_1 }, /* 1 */
  147133. };
  147134. /********* End of inlined file: residue_8.h *********/
  147135. static int blocksize_8[2]={
  147136. 512,512
  147137. };
  147138. static int _floor_mapping_8[2]={
  147139. 6,6,
  147140. };
  147141. static double rate_mapping_8[3]={
  147142. 6000.,9000.,32000.,
  147143. };
  147144. static double rate_mapping_8_uncoupled[3]={
  147145. 8000.,14000.,42000.,
  147146. };
  147147. static double quality_mapping_8[3]={
  147148. -.1,.0,1.
  147149. };
  147150. static double _psy_compand_8_mapping[3]={ 0., 1., 1.};
  147151. static double _global_mapping_8[3]={ 1., 2., 3. };
  147152. ve_setup_data_template ve_setup_8_stereo={
  147153. 2,
  147154. rate_mapping_8,
  147155. quality_mapping_8,
  147156. 2,
  147157. 8000,
  147158. 9000,
  147159. blocksize_8,
  147160. blocksize_8,
  147161. _psy_tone_masteratt_8,
  147162. _psy_tone_0dB,
  147163. _psy_tone_suppress,
  147164. _vp_tonemask_adj_8,
  147165. NULL,
  147166. _vp_tonemask_adj_8,
  147167. _psy_noiseguards_8,
  147168. _psy_noisebias_8,
  147169. _psy_noisebias_8,
  147170. NULL,
  147171. NULL,
  147172. _psy_noise_suppress,
  147173. _psy_compand_8,
  147174. _psy_compand_8_mapping,
  147175. NULL,
  147176. {_noise_start_8,_noise_start_8},
  147177. {_noise_part_8,_noise_part_8},
  147178. _noise_thresh_5only,
  147179. _psy_ath_floater_8,
  147180. _psy_ath_abs_8,
  147181. _psy_lowpass_8,
  147182. _psy_global_44,
  147183. _global_mapping_8,
  147184. _psy_stereo_modes_8,
  147185. _floor_books,
  147186. _floor,
  147187. _floor_mapping_8,
  147188. NULL,
  147189. _mapres_template_8_stereo
  147190. };
  147191. ve_setup_data_template ve_setup_8_uncoupled={
  147192. 2,
  147193. rate_mapping_8_uncoupled,
  147194. quality_mapping_8,
  147195. -1,
  147196. 8000,
  147197. 9000,
  147198. blocksize_8,
  147199. blocksize_8,
  147200. _psy_tone_masteratt_8,
  147201. _psy_tone_0dB,
  147202. _psy_tone_suppress,
  147203. _vp_tonemask_adj_8,
  147204. NULL,
  147205. _vp_tonemask_adj_8,
  147206. _psy_noiseguards_8,
  147207. _psy_noisebias_8,
  147208. _psy_noisebias_8,
  147209. NULL,
  147210. NULL,
  147211. _psy_noise_suppress,
  147212. _psy_compand_8,
  147213. _psy_compand_8_mapping,
  147214. NULL,
  147215. {_noise_start_8,_noise_start_8},
  147216. {_noise_part_8,_noise_part_8},
  147217. _noise_thresh_5only,
  147218. _psy_ath_floater_8,
  147219. _psy_ath_abs_8,
  147220. _psy_lowpass_8,
  147221. _psy_global_44,
  147222. _global_mapping_8,
  147223. _psy_stereo_modes_8,
  147224. _floor_books,
  147225. _floor,
  147226. _floor_mapping_8,
  147227. NULL,
  147228. _mapres_template_8_uncoupled
  147229. };
  147230. /********* End of inlined file: setup_8.h *********/
  147231. /********* Start of inlined file: setup_11.h *********/
  147232. /********* Start of inlined file: psych_11.h *********/
  147233. static double _psy_lowpass_11[3]={4.5,5.5,30.,};
  147234. static att3 _psy_tone_masteratt_11[3]={
  147235. {{ 30, 25, 12}, 0, 0}, /* 0 */
  147236. {{ 30, 25, 12}, 0, 0}, /* 0 */
  147237. {{ 20, 0, -14}, 0, 0}, /* 0 */
  147238. };
  147239. static vp_adjblock _vp_tonemask_adj_11[3]={
  147240. /* adjust for mode zero */
  147241. /* 63 125 250 500 1 2 4 8 16 */
  147242. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 2, 0,99,99,99}}, /* 0 */
  147243. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 5, 0, 0,99,99,99}}, /* 1 */
  147244. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 0, 0, 0,99,99,99}}, /* 2 */
  147245. };
  147246. static noise3 _psy_noisebias_11[3]={
  147247. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  147248. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 10, 10, 12, 12, 12, 99, 99, 99},
  147249. {-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 4, 5, 5, 10, 99, 99, 99},
  147250. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  147251. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 10, 10, 12, 12, 12, 99, 99, 99},
  147252. {-15,-15,-15,-15,-10,-10, -5, -5, -5, 0, 0, 0, 0, 0, 99, 99, 99},
  147253. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  147254. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 99, 99, 99},
  147255. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10, 99, 99, 99},
  147256. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24, 99, 99, 99}}},
  147257. };
  147258. static double _noise_thresh_11[3]={ .3,.5,.5 };
  147259. /********* End of inlined file: psych_11.h *********/
  147260. static int blocksize_11[2]={
  147261. 512,512
  147262. };
  147263. static int _floor_mapping_11[2]={
  147264. 6,6,
  147265. };
  147266. static double rate_mapping_11[3]={
  147267. 8000.,13000.,44000.,
  147268. };
  147269. static double rate_mapping_11_uncoupled[3]={
  147270. 12000.,20000.,50000.,
  147271. };
  147272. static double quality_mapping_11[3]={
  147273. -.1,.0,1.
  147274. };
  147275. ve_setup_data_template ve_setup_11_stereo={
  147276. 2,
  147277. rate_mapping_11,
  147278. quality_mapping_11,
  147279. 2,
  147280. 9000,
  147281. 15000,
  147282. blocksize_11,
  147283. blocksize_11,
  147284. _psy_tone_masteratt_11,
  147285. _psy_tone_0dB,
  147286. _psy_tone_suppress,
  147287. _vp_tonemask_adj_11,
  147288. NULL,
  147289. _vp_tonemask_adj_11,
  147290. _psy_noiseguards_8,
  147291. _psy_noisebias_11,
  147292. _psy_noisebias_11,
  147293. NULL,
  147294. NULL,
  147295. _psy_noise_suppress,
  147296. _psy_compand_8,
  147297. _psy_compand_8_mapping,
  147298. NULL,
  147299. {_noise_start_8,_noise_start_8},
  147300. {_noise_part_8,_noise_part_8},
  147301. _noise_thresh_11,
  147302. _psy_ath_floater_8,
  147303. _psy_ath_abs_8,
  147304. _psy_lowpass_11,
  147305. _psy_global_44,
  147306. _global_mapping_8,
  147307. _psy_stereo_modes_8,
  147308. _floor_books,
  147309. _floor,
  147310. _floor_mapping_11,
  147311. NULL,
  147312. _mapres_template_8_stereo
  147313. };
  147314. ve_setup_data_template ve_setup_11_uncoupled={
  147315. 2,
  147316. rate_mapping_11_uncoupled,
  147317. quality_mapping_11,
  147318. -1,
  147319. 9000,
  147320. 15000,
  147321. blocksize_11,
  147322. blocksize_11,
  147323. _psy_tone_masteratt_11,
  147324. _psy_tone_0dB,
  147325. _psy_tone_suppress,
  147326. _vp_tonemask_adj_11,
  147327. NULL,
  147328. _vp_tonemask_adj_11,
  147329. _psy_noiseguards_8,
  147330. _psy_noisebias_11,
  147331. _psy_noisebias_11,
  147332. NULL,
  147333. NULL,
  147334. _psy_noise_suppress,
  147335. _psy_compand_8,
  147336. _psy_compand_8_mapping,
  147337. NULL,
  147338. {_noise_start_8,_noise_start_8},
  147339. {_noise_part_8,_noise_part_8},
  147340. _noise_thresh_11,
  147341. _psy_ath_floater_8,
  147342. _psy_ath_abs_8,
  147343. _psy_lowpass_11,
  147344. _psy_global_44,
  147345. _global_mapping_8,
  147346. _psy_stereo_modes_8,
  147347. _floor_books,
  147348. _floor,
  147349. _floor_mapping_11,
  147350. NULL,
  147351. _mapres_template_8_uncoupled
  147352. };
  147353. /********* End of inlined file: setup_11.h *********/
  147354. /********* Start of inlined file: setup_16.h *********/
  147355. /********* Start of inlined file: psych_16.h *********/
  147356. /* stereo mode by base quality level */
  147357. static adj_stereo _psy_stereo_modes_16[4]={
  147358. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 */
  147359. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  147360. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  147361. { 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 4, 4},
  147362. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  147363. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  147364. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  147365. { 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 4, 4, 4, 4, 4},
  147366. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  147367. {{ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  147368. { 5, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  147369. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  147370. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  147371. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  147372. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  147373. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8},
  147374. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  147375. };
  147376. static double _psy_lowpass_16[4]={6.5,8,30.,99.};
  147377. static att3 _psy_tone_masteratt_16[4]={
  147378. {{ 30, 25, 12}, 0, 0}, /* 0 */
  147379. {{ 25, 22, 12}, 0, 0}, /* 0 */
  147380. {{ 20, 12, 0}, 0, 0}, /* 0 */
  147381. {{ 15, 0, -14}, 0, 0}, /* 0 */
  147382. };
  147383. static vp_adjblock _vp_tonemask_adj_16[4]={
  147384. /* adjust for mode zero */
  147385. /* 63 125 250 500 1 2 4 8 16 */
  147386. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 0, 0, 0, 0, 0}}, /* 0 */
  147387. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 0, 0, 0, 0, 0}}, /* 1 */
  147388. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, /* 2 */
  147389. {{-30,-30,-30,-30,-30,-26,-20,-10, -5, 0, 0, 0, 0, 0, 0, 0, 0}}, /* 2 */
  147390. };
  147391. static noise3 _psy_noisebias_16_short[4]={
  147392. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  147393. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 10, 10, 10, 10, 12, 12, 14, 20},
  147394. {-15,-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 5, 5, 6, 8, 8, 15},
  147395. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  147396. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 6, 6, 6, 6, 8, 10, 12, 20},
  147397. {-15,-15,-15,-15,-15,-15,-15,-10, -5, -5, -5, 4, 5, 6, 8, 8, 15},
  147398. {-30,-30,-30,-30,-30,-24,-20,-14,-10,-10,-10,-10,-10,-10,-10,-10,-10}}},
  147399. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 12},
  147400. {-20,-20,-20,-20,-16,-12,-20,-14,-10,-10, -8, 0, 0, 0, 0, 2, 5},
  147401. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  147402. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  147403. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10,-10,-10, -6},
  147404. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  147405. };
  147406. static noise3 _psy_noisebias_16_impulse[4]={
  147407. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  147408. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 10, 10, 10, 10, 12, 12, 14, 20},
  147409. {-15,-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 5, 5, 6, 8, 8, 15},
  147410. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  147411. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 4, 4, 4, 5, 5, 6, 8, 15},
  147412. {-15,-15,-15,-15,-15,-15,-15,-10, -5, -5, -5, 0, 0, 0, 0, 4, 10},
  147413. {-30,-30,-30,-30,-30,-24,-20,-14,-10,-10,-10,-10,-10,-10,-10,-10,-10}}},
  147414. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 4, 10},
  147415. {-20,-20,-20,-20,-16,-12,-20,-14,-10,-10,-10,-10,-10,-10,-10, -7, -5},
  147416. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  147417. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  147418. {-30,-30,-30,-30,-26,-22,-20,-18,-18,-18,-20,-20,-20,-20,-20,-20,-16},
  147419. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  147420. };
  147421. static noise3 _psy_noisebias_16[4]={
  147422. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  147423. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 6, 8, 8, 10, 10, 10, 14, 20},
  147424. {-10,-10,-10,-10,-10, -5, -2, -2, 0, 0, 0, 4, 5, 6, 8, 8, 15},
  147425. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  147426. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 6, 6, 6, 6, 8, 10, 12, 20},
  147427. {-15,-15,-15,-15,-15,-10, -5, -5, 0, 0, 0, 4, 5, 6, 8, 8, 15},
  147428. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  147429. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 12},
  147430. {-20,-20,-20,-20,-16,-12,-20,-10, -5, -5, 0, 0, 0, 0, 0, 2, 5},
  147431. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  147432. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  147433. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10,-10,-10, -6},
  147434. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  147435. };
  147436. static double _noise_thresh_16[4]={ .3,.5,.5,.5 };
  147437. static int _noise_start_16[3]={ 256,256,9999 };
  147438. static int _noise_part_16[4]={ 8,8,8,8 };
  147439. static int _psy_ath_floater_16[4]={
  147440. -100,-100,-100,-105,
  147441. };
  147442. static int _psy_ath_abs_16[4]={
  147443. -130,-130,-130,-140,
  147444. };
  147445. /********* End of inlined file: psych_16.h *********/
  147446. /********* Start of inlined file: residue_16.h *********/
  147447. /***** residue backends *********************************************/
  147448. static static_bookblock _resbook_16s_0={
  147449. {
  147450. {0},
  147451. {0,0,&_16c0_s_p1_0},
  147452. {0,0,&_16c0_s_p2_0},
  147453. {0,0,&_16c0_s_p3_0},
  147454. {0,0,&_16c0_s_p4_0},
  147455. {0,0,&_16c0_s_p5_0},
  147456. {0,0,&_16c0_s_p6_0},
  147457. {&_16c0_s_p7_0,&_16c0_s_p7_1},
  147458. {&_16c0_s_p8_0,&_16c0_s_p8_1},
  147459. {&_16c0_s_p9_0,&_16c0_s_p9_1,&_16c0_s_p9_2}
  147460. }
  147461. };
  147462. static static_bookblock _resbook_16s_1={
  147463. {
  147464. {0},
  147465. {0,0,&_16c1_s_p1_0},
  147466. {0,0,&_16c1_s_p2_0},
  147467. {0,0,&_16c1_s_p3_0},
  147468. {0,0,&_16c1_s_p4_0},
  147469. {0,0,&_16c1_s_p5_0},
  147470. {0,0,&_16c1_s_p6_0},
  147471. {&_16c1_s_p7_0,&_16c1_s_p7_1},
  147472. {&_16c1_s_p8_0,&_16c1_s_p8_1},
  147473. {&_16c1_s_p9_0,&_16c1_s_p9_1,&_16c1_s_p9_2}
  147474. }
  147475. };
  147476. static static_bookblock _resbook_16s_2={
  147477. {
  147478. {0},
  147479. {0,0,&_16c2_s_p1_0},
  147480. {0,0,&_16c2_s_p2_0},
  147481. {0,0,&_16c2_s_p3_0},
  147482. {0,0,&_16c2_s_p4_0},
  147483. {&_16c2_s_p5_0,&_16c2_s_p5_1},
  147484. {&_16c2_s_p6_0,&_16c2_s_p6_1},
  147485. {&_16c2_s_p7_0,&_16c2_s_p7_1},
  147486. {&_16c2_s_p8_0,&_16c2_s_p8_1},
  147487. {&_16c2_s_p9_0,&_16c2_s_p9_1,&_16c2_s_p9_2}
  147488. }
  147489. };
  147490. static vorbis_residue_template _res_16s_0[]={
  147491. {2,0, &_residue_44_mid,
  147492. &_huff_book__16c0_s_single,&_huff_book__16c0_s_single,
  147493. &_resbook_16s_0,&_resbook_16s_0},
  147494. };
  147495. static vorbis_residue_template _res_16s_1[]={
  147496. {2,0, &_residue_44_mid,
  147497. &_huff_book__16c1_s_short,&_huff_book__16c1_s_short,
  147498. &_resbook_16s_1,&_resbook_16s_1},
  147499. {2,0, &_residue_44_mid,
  147500. &_huff_book__16c1_s_long,&_huff_book__16c1_s_long,
  147501. &_resbook_16s_1,&_resbook_16s_1}
  147502. };
  147503. static vorbis_residue_template _res_16s_2[]={
  147504. {2,0, &_residue_44_high,
  147505. &_huff_book__16c2_s_short,&_huff_book__16c2_s_short,
  147506. &_resbook_16s_2,&_resbook_16s_2},
  147507. {2,0, &_residue_44_high,
  147508. &_huff_book__16c2_s_long,&_huff_book__16c2_s_long,
  147509. &_resbook_16s_2,&_resbook_16s_2}
  147510. };
  147511. static vorbis_mapping_template _mapres_template_16_stereo[3]={
  147512. { _map_nominal, _res_16s_0 }, /* 0 */
  147513. { _map_nominal, _res_16s_1 }, /* 1 */
  147514. { _map_nominal, _res_16s_2 }, /* 2 */
  147515. };
  147516. static static_bookblock _resbook_16u_0={
  147517. {
  147518. {0},
  147519. {0,0,&_16u0__p1_0},
  147520. {0,0,&_16u0__p2_0},
  147521. {0,0,&_16u0__p3_0},
  147522. {0,0,&_16u0__p4_0},
  147523. {0,0,&_16u0__p5_0},
  147524. {&_16u0__p6_0,&_16u0__p6_1},
  147525. {&_16u0__p7_0,&_16u0__p7_1,&_16u0__p7_2}
  147526. }
  147527. };
  147528. static static_bookblock _resbook_16u_1={
  147529. {
  147530. {0},
  147531. {0,0,&_16u1__p1_0},
  147532. {0,0,&_16u1__p2_0},
  147533. {0,0,&_16u1__p3_0},
  147534. {0,0,&_16u1__p4_0},
  147535. {0,0,&_16u1__p5_0},
  147536. {0,0,&_16u1__p6_0},
  147537. {&_16u1__p7_0,&_16u1__p7_1},
  147538. {&_16u1__p8_0,&_16u1__p8_1},
  147539. {&_16u1__p9_0,&_16u1__p9_1,&_16u1__p9_2}
  147540. }
  147541. };
  147542. static static_bookblock _resbook_16u_2={
  147543. {
  147544. {0},
  147545. {0,0,&_16u2_p1_0},
  147546. {0,0,&_16u2_p2_0},
  147547. {0,0,&_16u2_p3_0},
  147548. {0,0,&_16u2_p4_0},
  147549. {&_16u2_p5_0,&_16u2_p5_1},
  147550. {&_16u2_p6_0,&_16u2_p6_1},
  147551. {&_16u2_p7_0,&_16u2_p7_1},
  147552. {&_16u2_p8_0,&_16u2_p8_1},
  147553. {&_16u2_p9_0,&_16u2_p9_1,&_16u2_p9_2}
  147554. }
  147555. };
  147556. static vorbis_residue_template _res_16u_0[]={
  147557. {1,0, &_residue_44_low_un,
  147558. &_huff_book__16u0__single,&_huff_book__16u0__single,
  147559. &_resbook_16u_0,&_resbook_16u_0},
  147560. };
  147561. static vorbis_residue_template _res_16u_1[]={
  147562. {1,0, &_residue_44_mid_un,
  147563. &_huff_book__16u1__short,&_huff_book__16u1__short,
  147564. &_resbook_16u_1,&_resbook_16u_1},
  147565. {1,0, &_residue_44_mid_un,
  147566. &_huff_book__16u1__long,&_huff_book__16u1__long,
  147567. &_resbook_16u_1,&_resbook_16u_1}
  147568. };
  147569. static vorbis_residue_template _res_16u_2[]={
  147570. {1,0, &_residue_44_hi_un,
  147571. &_huff_book__16u2__short,&_huff_book__16u2__short,
  147572. &_resbook_16u_2,&_resbook_16u_2},
  147573. {1,0, &_residue_44_hi_un,
  147574. &_huff_book__16u2__long,&_huff_book__16u2__long,
  147575. &_resbook_16u_2,&_resbook_16u_2}
  147576. };
  147577. static vorbis_mapping_template _mapres_template_16_uncoupled[3]={
  147578. { _map_nominal_u, _res_16u_0 }, /* 0 */
  147579. { _map_nominal_u, _res_16u_1 }, /* 1 */
  147580. { _map_nominal_u, _res_16u_2 }, /* 2 */
  147581. };
  147582. /********* End of inlined file: residue_16.h *********/
  147583. static int blocksize_16_short[3]={
  147584. 1024,512,512
  147585. };
  147586. static int blocksize_16_long[3]={
  147587. 1024,1024,1024
  147588. };
  147589. static int _floor_mapping_16_short[3]={
  147590. 9,3,3
  147591. };
  147592. static int _floor_mapping_16[3]={
  147593. 9,9,9
  147594. };
  147595. static double rate_mapping_16[4]={
  147596. 12000.,20000.,44000.,86000.
  147597. };
  147598. static double rate_mapping_16_uncoupled[4]={
  147599. 16000.,28000.,64000.,100000.
  147600. };
  147601. static double _global_mapping_16[4]={ 1., 2., 3., 4. };
  147602. static double quality_mapping_16[4]={ -.1,.05,.5,1. };
  147603. static double _psy_compand_16_mapping[4]={ 0., .8, 1., 1.};
  147604. ve_setup_data_template ve_setup_16_stereo={
  147605. 3,
  147606. rate_mapping_16,
  147607. quality_mapping_16,
  147608. 2,
  147609. 15000,
  147610. 19000,
  147611. blocksize_16_short,
  147612. blocksize_16_long,
  147613. _psy_tone_masteratt_16,
  147614. _psy_tone_0dB,
  147615. _psy_tone_suppress,
  147616. _vp_tonemask_adj_16,
  147617. _vp_tonemask_adj_16,
  147618. _vp_tonemask_adj_16,
  147619. _psy_noiseguards_8,
  147620. _psy_noisebias_16_impulse,
  147621. _psy_noisebias_16_short,
  147622. _psy_noisebias_16_short,
  147623. _psy_noisebias_16,
  147624. _psy_noise_suppress,
  147625. _psy_compand_8,
  147626. _psy_compand_16_mapping,
  147627. _psy_compand_16_mapping,
  147628. {_noise_start_16,_noise_start_16},
  147629. { _noise_part_16, _noise_part_16},
  147630. _noise_thresh_16,
  147631. _psy_ath_floater_16,
  147632. _psy_ath_abs_16,
  147633. _psy_lowpass_16,
  147634. _psy_global_44,
  147635. _global_mapping_16,
  147636. _psy_stereo_modes_16,
  147637. _floor_books,
  147638. _floor,
  147639. _floor_mapping_16_short,
  147640. _floor_mapping_16,
  147641. _mapres_template_16_stereo
  147642. };
  147643. ve_setup_data_template ve_setup_16_uncoupled={
  147644. 3,
  147645. rate_mapping_16_uncoupled,
  147646. quality_mapping_16,
  147647. -1,
  147648. 15000,
  147649. 19000,
  147650. blocksize_16_short,
  147651. blocksize_16_long,
  147652. _psy_tone_masteratt_16,
  147653. _psy_tone_0dB,
  147654. _psy_tone_suppress,
  147655. _vp_tonemask_adj_16,
  147656. _vp_tonemask_adj_16,
  147657. _vp_tonemask_adj_16,
  147658. _psy_noiseguards_8,
  147659. _psy_noisebias_16_impulse,
  147660. _psy_noisebias_16_short,
  147661. _psy_noisebias_16_short,
  147662. _psy_noisebias_16,
  147663. _psy_noise_suppress,
  147664. _psy_compand_8,
  147665. _psy_compand_16_mapping,
  147666. _psy_compand_16_mapping,
  147667. {_noise_start_16,_noise_start_16},
  147668. { _noise_part_16, _noise_part_16},
  147669. _noise_thresh_16,
  147670. _psy_ath_floater_16,
  147671. _psy_ath_abs_16,
  147672. _psy_lowpass_16,
  147673. _psy_global_44,
  147674. _global_mapping_16,
  147675. _psy_stereo_modes_16,
  147676. _floor_books,
  147677. _floor,
  147678. _floor_mapping_16_short,
  147679. _floor_mapping_16,
  147680. _mapres_template_16_uncoupled
  147681. };
  147682. /********* End of inlined file: setup_16.h *********/
  147683. /********* Start of inlined file: setup_22.h *********/
  147684. static double rate_mapping_22[4]={
  147685. 15000.,20000.,44000.,86000.
  147686. };
  147687. static double rate_mapping_22_uncoupled[4]={
  147688. 16000.,28000.,50000.,90000.
  147689. };
  147690. static double _psy_lowpass_22[4]={9.5,11.,30.,99.};
  147691. ve_setup_data_template ve_setup_22_stereo={
  147692. 3,
  147693. rate_mapping_22,
  147694. quality_mapping_16,
  147695. 2,
  147696. 19000,
  147697. 26000,
  147698. blocksize_16_short,
  147699. blocksize_16_long,
  147700. _psy_tone_masteratt_16,
  147701. _psy_tone_0dB,
  147702. _psy_tone_suppress,
  147703. _vp_tonemask_adj_16,
  147704. _vp_tonemask_adj_16,
  147705. _vp_tonemask_adj_16,
  147706. _psy_noiseguards_8,
  147707. _psy_noisebias_16_impulse,
  147708. _psy_noisebias_16_short,
  147709. _psy_noisebias_16_short,
  147710. _psy_noisebias_16,
  147711. _psy_noise_suppress,
  147712. _psy_compand_8,
  147713. _psy_compand_8_mapping,
  147714. _psy_compand_8_mapping,
  147715. {_noise_start_16,_noise_start_16},
  147716. { _noise_part_16, _noise_part_16},
  147717. _noise_thresh_16,
  147718. _psy_ath_floater_16,
  147719. _psy_ath_abs_16,
  147720. _psy_lowpass_22,
  147721. _psy_global_44,
  147722. _global_mapping_16,
  147723. _psy_stereo_modes_16,
  147724. _floor_books,
  147725. _floor,
  147726. _floor_mapping_16_short,
  147727. _floor_mapping_16,
  147728. _mapres_template_16_stereo
  147729. };
  147730. ve_setup_data_template ve_setup_22_uncoupled={
  147731. 3,
  147732. rate_mapping_22_uncoupled,
  147733. quality_mapping_16,
  147734. -1,
  147735. 19000,
  147736. 26000,
  147737. blocksize_16_short,
  147738. blocksize_16_long,
  147739. _psy_tone_masteratt_16,
  147740. _psy_tone_0dB,
  147741. _psy_tone_suppress,
  147742. _vp_tonemask_adj_16,
  147743. _vp_tonemask_adj_16,
  147744. _vp_tonemask_adj_16,
  147745. _psy_noiseguards_8,
  147746. _psy_noisebias_16_impulse,
  147747. _psy_noisebias_16_short,
  147748. _psy_noisebias_16_short,
  147749. _psy_noisebias_16,
  147750. _psy_noise_suppress,
  147751. _psy_compand_8,
  147752. _psy_compand_8_mapping,
  147753. _psy_compand_8_mapping,
  147754. {_noise_start_16,_noise_start_16},
  147755. { _noise_part_16, _noise_part_16},
  147756. _noise_thresh_16,
  147757. _psy_ath_floater_16,
  147758. _psy_ath_abs_16,
  147759. _psy_lowpass_22,
  147760. _psy_global_44,
  147761. _global_mapping_16,
  147762. _psy_stereo_modes_16,
  147763. _floor_books,
  147764. _floor,
  147765. _floor_mapping_16_short,
  147766. _floor_mapping_16,
  147767. _mapres_template_16_uncoupled
  147768. };
  147769. /********* End of inlined file: setup_22.h *********/
  147770. /********* Start of inlined file: setup_X.h *********/
  147771. static double rate_mapping_X[12]={
  147772. -1.,-1.,-1.,-1.,-1.,-1.,
  147773. -1.,-1.,-1.,-1.,-1.,-1.
  147774. };
  147775. ve_setup_data_template ve_setup_X_stereo={
  147776. 11,
  147777. rate_mapping_X,
  147778. quality_mapping_44,
  147779. 2,
  147780. 50000,
  147781. 200000,
  147782. blocksize_short_44,
  147783. blocksize_long_44,
  147784. _psy_tone_masteratt_44,
  147785. _psy_tone_0dB,
  147786. _psy_tone_suppress,
  147787. _vp_tonemask_adj_otherblock,
  147788. _vp_tonemask_adj_longblock,
  147789. _vp_tonemask_adj_otherblock,
  147790. _psy_noiseguards_44,
  147791. _psy_noisebias_impulse,
  147792. _psy_noisebias_padding,
  147793. _psy_noisebias_trans,
  147794. _psy_noisebias_long,
  147795. _psy_noise_suppress,
  147796. _psy_compand_44,
  147797. _psy_compand_short_mapping,
  147798. _psy_compand_long_mapping,
  147799. {_noise_start_short_44,_noise_start_long_44},
  147800. {_noise_part_short_44,_noise_part_long_44},
  147801. _noise_thresh_44,
  147802. _psy_ath_floater,
  147803. _psy_ath_abs,
  147804. _psy_lowpass_44,
  147805. _psy_global_44,
  147806. _global_mapping_44,
  147807. _psy_stereo_modes_44,
  147808. _floor_books,
  147809. _floor,
  147810. _floor_short_mapping_44,
  147811. _floor_long_mapping_44,
  147812. _mapres_template_44_stereo
  147813. };
  147814. ve_setup_data_template ve_setup_X_uncoupled={
  147815. 11,
  147816. rate_mapping_X,
  147817. quality_mapping_44,
  147818. -1,
  147819. 50000,
  147820. 200000,
  147821. blocksize_short_44,
  147822. blocksize_long_44,
  147823. _psy_tone_masteratt_44,
  147824. _psy_tone_0dB,
  147825. _psy_tone_suppress,
  147826. _vp_tonemask_adj_otherblock,
  147827. _vp_tonemask_adj_longblock,
  147828. _vp_tonemask_adj_otherblock,
  147829. _psy_noiseguards_44,
  147830. _psy_noisebias_impulse,
  147831. _psy_noisebias_padding,
  147832. _psy_noisebias_trans,
  147833. _psy_noisebias_long,
  147834. _psy_noise_suppress,
  147835. _psy_compand_44,
  147836. _psy_compand_short_mapping,
  147837. _psy_compand_long_mapping,
  147838. {_noise_start_short_44,_noise_start_long_44},
  147839. {_noise_part_short_44,_noise_part_long_44},
  147840. _noise_thresh_44,
  147841. _psy_ath_floater,
  147842. _psy_ath_abs,
  147843. _psy_lowpass_44,
  147844. _psy_global_44,
  147845. _global_mapping_44,
  147846. NULL,
  147847. _floor_books,
  147848. _floor,
  147849. _floor_short_mapping_44,
  147850. _floor_long_mapping_44,
  147851. _mapres_template_44_uncoupled
  147852. };
  147853. ve_setup_data_template ve_setup_XX_stereo={
  147854. 2,
  147855. rate_mapping_X,
  147856. quality_mapping_8,
  147857. 2,
  147858. 0,
  147859. 8000,
  147860. blocksize_8,
  147861. blocksize_8,
  147862. _psy_tone_masteratt_8,
  147863. _psy_tone_0dB,
  147864. _psy_tone_suppress,
  147865. _vp_tonemask_adj_8,
  147866. NULL,
  147867. _vp_tonemask_adj_8,
  147868. _psy_noiseguards_8,
  147869. _psy_noisebias_8,
  147870. _psy_noisebias_8,
  147871. NULL,
  147872. NULL,
  147873. _psy_noise_suppress,
  147874. _psy_compand_8,
  147875. _psy_compand_8_mapping,
  147876. NULL,
  147877. {_noise_start_8,_noise_start_8},
  147878. {_noise_part_8,_noise_part_8},
  147879. _noise_thresh_5only,
  147880. _psy_ath_floater_8,
  147881. _psy_ath_abs_8,
  147882. _psy_lowpass_8,
  147883. _psy_global_44,
  147884. _global_mapping_8,
  147885. _psy_stereo_modes_8,
  147886. _floor_books,
  147887. _floor,
  147888. _floor_mapping_8,
  147889. NULL,
  147890. _mapres_template_8_stereo
  147891. };
  147892. ve_setup_data_template ve_setup_XX_uncoupled={
  147893. 2,
  147894. rate_mapping_X,
  147895. quality_mapping_8,
  147896. -1,
  147897. 0,
  147898. 8000,
  147899. blocksize_8,
  147900. blocksize_8,
  147901. _psy_tone_masteratt_8,
  147902. _psy_tone_0dB,
  147903. _psy_tone_suppress,
  147904. _vp_tonemask_adj_8,
  147905. NULL,
  147906. _vp_tonemask_adj_8,
  147907. _psy_noiseguards_8,
  147908. _psy_noisebias_8,
  147909. _psy_noisebias_8,
  147910. NULL,
  147911. NULL,
  147912. _psy_noise_suppress,
  147913. _psy_compand_8,
  147914. _psy_compand_8_mapping,
  147915. NULL,
  147916. {_noise_start_8,_noise_start_8},
  147917. {_noise_part_8,_noise_part_8},
  147918. _noise_thresh_5only,
  147919. _psy_ath_floater_8,
  147920. _psy_ath_abs_8,
  147921. _psy_lowpass_8,
  147922. _psy_global_44,
  147923. _global_mapping_8,
  147924. _psy_stereo_modes_8,
  147925. _floor_books,
  147926. _floor,
  147927. _floor_mapping_8,
  147928. NULL,
  147929. _mapres_template_8_uncoupled
  147930. };
  147931. /********* End of inlined file: setup_X.h *********/
  147932. static ve_setup_data_template *setup_list[]={
  147933. &ve_setup_44_stereo,
  147934. &ve_setup_44_uncoupled,
  147935. &ve_setup_32_stereo,
  147936. &ve_setup_32_uncoupled,
  147937. &ve_setup_22_stereo,
  147938. &ve_setup_22_uncoupled,
  147939. &ve_setup_16_stereo,
  147940. &ve_setup_16_uncoupled,
  147941. &ve_setup_11_stereo,
  147942. &ve_setup_11_uncoupled,
  147943. &ve_setup_8_stereo,
  147944. &ve_setup_8_uncoupled,
  147945. &ve_setup_X_stereo,
  147946. &ve_setup_X_uncoupled,
  147947. &ve_setup_XX_stereo,
  147948. &ve_setup_XX_uncoupled,
  147949. 0
  147950. };
  147951. static int vorbis_encode_toplevel_setup(vorbis_info *vi,int ch,long rate){
  147952. if(vi && vi->codec_setup){
  147953. vi->version=0;
  147954. vi->channels=ch;
  147955. vi->rate=rate;
  147956. return(0);
  147957. }
  147958. return(OV_EINVAL);
  147959. }
  147960. static void vorbis_encode_floor_setup(vorbis_info *vi,double s,int block,
  147961. static_codebook ***books,
  147962. vorbis_info_floor1 *in,
  147963. int *x){
  147964. int i,k,is=s;
  147965. vorbis_info_floor1 *f=(vorbis_info_floor1*) _ogg_calloc(1,sizeof(*f));
  147966. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  147967. memcpy(f,in+x[is],sizeof(*f));
  147968. /* fill in the lowpass field, even if it's temporary */
  147969. f->n=ci->blocksizes[block]>>1;
  147970. /* books */
  147971. {
  147972. int partitions=f->partitions;
  147973. int maxclass=-1;
  147974. int maxbook=-1;
  147975. for(i=0;i<partitions;i++)
  147976. if(f->partitionclass[i]>maxclass)maxclass=f->partitionclass[i];
  147977. for(i=0;i<=maxclass;i++){
  147978. if(f->class_book[i]>maxbook)maxbook=f->class_book[i];
  147979. f->class_book[i]+=ci->books;
  147980. for(k=0;k<(1<<f->class_subs[i]);k++){
  147981. if(f->class_subbook[i][k]>maxbook)maxbook=f->class_subbook[i][k];
  147982. if(f->class_subbook[i][k]>=0)f->class_subbook[i][k]+=ci->books;
  147983. }
  147984. }
  147985. for(i=0;i<=maxbook;i++)
  147986. ci->book_param[ci->books++]=books[x[is]][i];
  147987. }
  147988. /* for now, we're only using floor 1 */
  147989. ci->floor_type[ci->floors]=1;
  147990. ci->floor_param[ci->floors]=f;
  147991. ci->floors++;
  147992. return;
  147993. }
  147994. static void vorbis_encode_global_psych_setup(vorbis_info *vi,double s,
  147995. vorbis_info_psy_global *in,
  147996. double *x){
  147997. int i,is=s;
  147998. double ds=s-is;
  147999. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  148000. vorbis_info_psy_global *g=&ci->psy_g_param;
  148001. memcpy(g,in+(int)x[is],sizeof(*g));
  148002. ds=x[is]*(1.-ds)+x[is+1]*ds;
  148003. is=(int)ds;
  148004. ds-=is;
  148005. if(ds==0 && is>0){
  148006. is--;
  148007. ds=1.;
  148008. }
  148009. /* interpolate the trigger threshholds */
  148010. for(i=0;i<4;i++){
  148011. g->preecho_thresh[i]=in[is].preecho_thresh[i]*(1.-ds)+in[is+1].preecho_thresh[i]*ds;
  148012. g->postecho_thresh[i]=in[is].postecho_thresh[i]*(1.-ds)+in[is+1].postecho_thresh[i]*ds;
  148013. }
  148014. g->ampmax_att_per_sec=ci->hi.amplitude_track_dBpersec;
  148015. return;
  148016. }
  148017. static void vorbis_encode_global_stereo(vorbis_info *vi,
  148018. highlevel_encode_setup *hi,
  148019. adj_stereo *p){
  148020. float s=hi->stereo_point_setting;
  148021. int i,is=s;
  148022. double ds=s-is;
  148023. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  148024. vorbis_info_psy_global *g=&ci->psy_g_param;
  148025. if(p){
  148026. memcpy(g->coupling_prepointamp,p[is].pre,sizeof(*p[is].pre)*PACKETBLOBS);
  148027. memcpy(g->coupling_postpointamp,p[is].post,sizeof(*p[is].post)*PACKETBLOBS);
  148028. if(hi->managed){
  148029. /* interpolate the kHz threshholds */
  148030. for(i=0;i<PACKETBLOBS;i++){
  148031. float kHz=p[is].kHz[i]*(1.-ds)+p[is+1].kHz[i]*ds;
  148032. g->coupling_pointlimit[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  148033. g->coupling_pointlimit[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  148034. g->coupling_pkHz[i]=kHz;
  148035. kHz=p[is].lowpasskHz[i]*(1.-ds)+p[is+1].lowpasskHz[i]*ds;
  148036. g->sliding_lowpass[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  148037. g->sliding_lowpass[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  148038. }
  148039. }else{
  148040. float kHz=p[is].kHz[PACKETBLOBS/2]*(1.-ds)+p[is+1].kHz[PACKETBLOBS/2]*ds;
  148041. for(i=0;i<PACKETBLOBS;i++){
  148042. g->coupling_pointlimit[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  148043. g->coupling_pointlimit[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  148044. g->coupling_pkHz[i]=kHz;
  148045. }
  148046. kHz=p[is].lowpasskHz[PACKETBLOBS/2]*(1.-ds)+p[is+1].lowpasskHz[PACKETBLOBS/2]*ds;
  148047. for(i=0;i<PACKETBLOBS;i++){
  148048. g->sliding_lowpass[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  148049. g->sliding_lowpass[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  148050. }
  148051. }
  148052. }else{
  148053. for(i=0;i<PACKETBLOBS;i++){
  148054. g->sliding_lowpass[0][i]=ci->blocksizes[0];
  148055. g->sliding_lowpass[1][i]=ci->blocksizes[1];
  148056. }
  148057. }
  148058. return;
  148059. }
  148060. static void vorbis_encode_psyset_setup(vorbis_info *vi,double s,
  148061. int *nn_start,
  148062. int *nn_partition,
  148063. double *nn_thresh,
  148064. int block){
  148065. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  148066. vorbis_info_psy *p=ci->psy_param[block];
  148067. highlevel_encode_setup *hi=&ci->hi;
  148068. int is=s;
  148069. if(block>=ci->psys)
  148070. ci->psys=block+1;
  148071. if(!p){
  148072. p=(vorbis_info_psy*)_ogg_calloc(1,sizeof(*p));
  148073. ci->psy_param[block]=p;
  148074. }
  148075. memcpy(p,&_psy_info_template,sizeof(*p));
  148076. p->blockflag=block>>1;
  148077. if(hi->noise_normalize_p){
  148078. p->normal_channel_p=1;
  148079. p->normal_point_p=1;
  148080. p->normal_start=nn_start[is];
  148081. p->normal_partition=nn_partition[is];
  148082. p->normal_thresh=nn_thresh[is];
  148083. }
  148084. return;
  148085. }
  148086. static void vorbis_encode_tonemask_setup(vorbis_info *vi,double s,int block,
  148087. att3 *att,
  148088. int *max,
  148089. vp_adjblock *in){
  148090. int i,is=s;
  148091. double ds=s-is;
  148092. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  148093. vorbis_info_psy *p=ci->psy_param[block];
  148094. /* 0 and 2 are only used by bitmanagement, but there's no harm to always
  148095. filling the values in here */
  148096. p->tone_masteratt[0]=att[is].att[0]*(1.-ds)+att[is+1].att[0]*ds;
  148097. p->tone_masteratt[1]=att[is].att[1]*(1.-ds)+att[is+1].att[1]*ds;
  148098. p->tone_masteratt[2]=att[is].att[2]*(1.-ds)+att[is+1].att[2]*ds;
  148099. p->tone_centerboost=att[is].boost*(1.-ds)+att[is+1].boost*ds;
  148100. p->tone_decay=att[is].decay*(1.-ds)+att[is+1].decay*ds;
  148101. p->max_curve_dB=max[is]*(1.-ds)+max[is+1]*ds;
  148102. for(i=0;i<P_BANDS;i++)
  148103. p->toneatt[i]=in[is].block[i]*(1.-ds)+in[is+1].block[i]*ds;
  148104. return;
  148105. }
  148106. static void vorbis_encode_compand_setup(vorbis_info *vi,double s,int block,
  148107. compandblock *in, double *x){
  148108. int i,is=s;
  148109. double ds=s-is;
  148110. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  148111. vorbis_info_psy *p=ci->psy_param[block];
  148112. ds=x[is]*(1.-ds)+x[is+1]*ds;
  148113. is=(int)ds;
  148114. ds-=is;
  148115. if(ds==0 && is>0){
  148116. is--;
  148117. ds=1.;
  148118. }
  148119. /* interpolate the compander settings */
  148120. for(i=0;i<NOISE_COMPAND_LEVELS;i++)
  148121. p->noisecompand[i]=in[is].data[i]*(1.-ds)+in[is+1].data[i]*ds;
  148122. return;
  148123. }
  148124. static void vorbis_encode_peak_setup(vorbis_info *vi,double s,int block,
  148125. int *suppress){
  148126. int is=s;
  148127. double ds=s-is;
  148128. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  148129. vorbis_info_psy *p=ci->psy_param[block];
  148130. p->tone_abs_limit=suppress[is]*(1.-ds)+suppress[is+1]*ds;
  148131. return;
  148132. }
  148133. static void vorbis_encode_noisebias_setup(vorbis_info *vi,double s,int block,
  148134. int *suppress,
  148135. noise3 *in,
  148136. noiseguard *guard,
  148137. double userbias){
  148138. int i,is=s,j;
  148139. double ds=s-is;
  148140. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  148141. vorbis_info_psy *p=ci->psy_param[block];
  148142. p->noisemaxsupp=suppress[is]*(1.-ds)+suppress[is+1]*ds;
  148143. p->noisewindowlomin=guard[block].lo;
  148144. p->noisewindowhimin=guard[block].hi;
  148145. p->noisewindowfixed=guard[block].fixed;
  148146. for(j=0;j<P_NOISECURVES;j++)
  148147. for(i=0;i<P_BANDS;i++)
  148148. p->noiseoff[j][i]=in[is].data[j][i]*(1.-ds)+in[is+1].data[j][i]*ds;
  148149. /* impulse blocks may take a user specified bias to boost the
  148150. nominal/high noise encoding depth */
  148151. for(j=0;j<P_NOISECURVES;j++){
  148152. float min=p->noiseoff[j][0]+6; /* the lowest it can go */
  148153. for(i=0;i<P_BANDS;i++){
  148154. p->noiseoff[j][i]+=userbias;
  148155. if(p->noiseoff[j][i]<min)p->noiseoff[j][i]=min;
  148156. }
  148157. }
  148158. return;
  148159. }
  148160. static void vorbis_encode_ath_setup(vorbis_info *vi,int block){
  148161. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  148162. vorbis_info_psy *p=ci->psy_param[block];
  148163. p->ath_adjatt=ci->hi.ath_floating_dB;
  148164. p->ath_maxatt=ci->hi.ath_absolute_dB;
  148165. return;
  148166. }
  148167. static int book_dup_or_new(codec_setup_info *ci,static_codebook *book){
  148168. int i;
  148169. for(i=0;i<ci->books;i++)
  148170. if(ci->book_param[i]==book)return(i);
  148171. return(ci->books++);
  148172. }
  148173. static void vorbis_encode_blocksize_setup(vorbis_info *vi,double s,
  148174. int *shortb,int *longb){
  148175. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  148176. int is=s;
  148177. int blockshort=shortb[is];
  148178. int blocklong=longb[is];
  148179. ci->blocksizes[0]=blockshort;
  148180. ci->blocksizes[1]=blocklong;
  148181. }
  148182. static void vorbis_encode_residue_setup(vorbis_info *vi,
  148183. int number, int block,
  148184. vorbis_residue_template *res){
  148185. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  148186. int i,n;
  148187. vorbis_info_residue0 *r=(vorbis_info_residue0*)(ci->residue_param[number]=
  148188. (vorbis_info_residue0*)_ogg_malloc(sizeof(*r)));
  148189. memcpy(r,res->res,sizeof(*r));
  148190. if(ci->residues<=number)ci->residues=number+1;
  148191. switch(ci->blocksizes[block]){
  148192. case 64:case 128:case 256:
  148193. r->grouping=16;
  148194. break;
  148195. default:
  148196. r->grouping=32;
  148197. break;
  148198. }
  148199. ci->residue_type[number]=res->res_type;
  148200. /* to be adjusted by lowpass/pointlimit later */
  148201. n=r->end=ci->blocksizes[block]>>1;
  148202. if(res->res_type==2)
  148203. n=r->end*=vi->channels;
  148204. /* fill in all the books */
  148205. {
  148206. int booklist=0,k;
  148207. if(ci->hi.managed){
  148208. for(i=0;i<r->partitions;i++)
  148209. for(k=0;k<3;k++)
  148210. if(res->books_base_managed->books[i][k])
  148211. r->secondstages[i]|=(1<<k);
  148212. r->groupbook=book_dup_or_new(ci,res->book_aux_managed);
  148213. ci->book_param[r->groupbook]=res->book_aux_managed;
  148214. for(i=0;i<r->partitions;i++){
  148215. for(k=0;k<3;k++){
  148216. if(res->books_base_managed->books[i][k]){
  148217. int bookid=book_dup_or_new(ci,res->books_base_managed->books[i][k]);
  148218. r->booklist[booklist++]=bookid;
  148219. ci->book_param[bookid]=res->books_base_managed->books[i][k];
  148220. }
  148221. }
  148222. }
  148223. }else{
  148224. for(i=0;i<r->partitions;i++)
  148225. for(k=0;k<3;k++)
  148226. if(res->books_base->books[i][k])
  148227. r->secondstages[i]|=(1<<k);
  148228. r->groupbook=book_dup_or_new(ci,res->book_aux);
  148229. ci->book_param[r->groupbook]=res->book_aux;
  148230. for(i=0;i<r->partitions;i++){
  148231. for(k=0;k<3;k++){
  148232. if(res->books_base->books[i][k]){
  148233. int bookid=book_dup_or_new(ci,res->books_base->books[i][k]);
  148234. r->booklist[booklist++]=bookid;
  148235. ci->book_param[bookid]=res->books_base->books[i][k];
  148236. }
  148237. }
  148238. }
  148239. }
  148240. }
  148241. /* lowpass setup/pointlimit */
  148242. {
  148243. double freq=ci->hi.lowpass_kHz*1000.;
  148244. vorbis_info_floor1 *f=(vorbis_info_floor1*)ci->floor_param[block]; /* by convention */
  148245. double nyq=vi->rate/2.;
  148246. long blocksize=ci->blocksizes[block]>>1;
  148247. /* lowpass needs to be set in the floor and the residue. */
  148248. if(freq>nyq)freq=nyq;
  148249. /* in the floor, the granularity can be very fine; it doesn't alter
  148250. the encoding structure, only the samples used to fit the floor
  148251. approximation */
  148252. f->n=freq/nyq*blocksize;
  148253. /* this res may by limited by the maximum pointlimit of the mode,
  148254. not the lowpass. the floor is always lowpass limited. */
  148255. if(res->limit_type){
  148256. if(ci->hi.managed)
  148257. freq=ci->psy_g_param.coupling_pkHz[PACKETBLOBS-1]*1000.;
  148258. else
  148259. freq=ci->psy_g_param.coupling_pkHz[PACKETBLOBS/2]*1000.;
  148260. if(freq>nyq)freq=nyq;
  148261. }
  148262. /* in the residue, we're constrained, physically, by partition
  148263. boundaries. We still lowpass 'wherever', but we have to round up
  148264. here to next boundary, or the vorbis spec will round it *down* to
  148265. previous boundary in encode/decode */
  148266. if(ci->residue_type[block]==2)
  148267. r->end=(int)((freq/nyq*blocksize*2)/r->grouping+.9)* /* round up only if we're well past */
  148268. r->grouping;
  148269. else
  148270. r->end=(int)((freq/nyq*blocksize)/r->grouping+.9)* /* round up only if we're well past */
  148271. r->grouping;
  148272. }
  148273. }
  148274. /* we assume two maps in this encoder */
  148275. static void vorbis_encode_map_n_res_setup(vorbis_info *vi,double s,
  148276. vorbis_mapping_template *maps){
  148277. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  148278. int i,j,is=s,modes=2;
  148279. vorbis_info_mapping0 *map=maps[is].map;
  148280. vorbis_info_mode *mode=_mode_template;
  148281. vorbis_residue_template *res=maps[is].res;
  148282. if(ci->blocksizes[0]==ci->blocksizes[1])modes=1;
  148283. for(i=0;i<modes;i++){
  148284. ci->map_param[i]=_ogg_calloc(1,sizeof(*map));
  148285. ci->mode_param[i]=(vorbis_info_mode*)_ogg_calloc(1,sizeof(*mode));
  148286. memcpy(ci->mode_param[i],mode+i,sizeof(*_mode_template));
  148287. if(i>=ci->modes)ci->modes=i+1;
  148288. ci->map_type[i]=0;
  148289. memcpy(ci->map_param[i],map+i,sizeof(*map));
  148290. if(i>=ci->maps)ci->maps=i+1;
  148291. for(j=0;j<map[i].submaps;j++)
  148292. vorbis_encode_residue_setup(vi,map[i].residuesubmap[j],i
  148293. ,res+map[i].residuesubmap[j]);
  148294. }
  148295. }
  148296. static double setting_to_approx_bitrate(vorbis_info *vi){
  148297. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  148298. highlevel_encode_setup *hi=&ci->hi;
  148299. ve_setup_data_template *setup=(ve_setup_data_template *)hi->setup;
  148300. int is=hi->base_setting;
  148301. double ds=hi->base_setting-is;
  148302. int ch=vi->channels;
  148303. double *r=setup->rate_mapping;
  148304. if(r==NULL)
  148305. return(-1);
  148306. return((r[is]*(1.-ds)+r[is+1]*ds)*ch);
  148307. }
  148308. static void get_setup_template(vorbis_info *vi,
  148309. long ch,long srate,
  148310. double req,int q_or_bitrate){
  148311. int i=0,j;
  148312. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  148313. highlevel_encode_setup *hi=&ci->hi;
  148314. if(q_or_bitrate)req/=ch;
  148315. while(setup_list[i]){
  148316. if(setup_list[i]->coupling_restriction==-1 ||
  148317. setup_list[i]->coupling_restriction==ch){
  148318. if(srate>=setup_list[i]->samplerate_min_restriction &&
  148319. srate<=setup_list[i]->samplerate_max_restriction){
  148320. int mappings=setup_list[i]->mappings;
  148321. double *map=(q_or_bitrate?
  148322. setup_list[i]->rate_mapping:
  148323. setup_list[i]->quality_mapping);
  148324. /* the template matches. Does the requested quality mode
  148325. fall within this template's modes? */
  148326. if(req<map[0]){++i;continue;}
  148327. if(req>map[setup_list[i]->mappings]){++i;continue;}
  148328. for(j=0;j<mappings;j++)
  148329. if(req>=map[j] && req<map[j+1])break;
  148330. /* an all-points match */
  148331. hi->setup=setup_list[i];
  148332. if(j==mappings)
  148333. hi->base_setting=j-.001;
  148334. else{
  148335. float low=map[j];
  148336. float high=map[j+1];
  148337. float del=(req-low)/(high-low);
  148338. hi->base_setting=j+del;
  148339. }
  148340. return;
  148341. }
  148342. }
  148343. i++;
  148344. }
  148345. hi->setup=NULL;
  148346. }
  148347. /* encoders will need to use vorbis_info_init beforehand and call
  148348. vorbis_info clear when all done */
  148349. /* two interfaces; this, more detailed one, and later a convenience
  148350. layer on top */
  148351. /* the final setup call */
  148352. int vorbis_encode_setup_init(vorbis_info *vi){
  148353. int i0=0,singleblock=0;
  148354. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  148355. ve_setup_data_template *setup=NULL;
  148356. highlevel_encode_setup *hi=&ci->hi;
  148357. if(ci==NULL)return(OV_EINVAL);
  148358. if(!hi->impulse_block_p)i0=1;
  148359. /* too low/high an ATH floater is nonsensical, but doesn't break anything */
  148360. if(hi->ath_floating_dB>-80)hi->ath_floating_dB=-80;
  148361. if(hi->ath_floating_dB<-200)hi->ath_floating_dB=-200;
  148362. /* again, bound this to avoid the app shooting itself int he foot
  148363. too badly */
  148364. if(hi->amplitude_track_dBpersec>0.)hi->amplitude_track_dBpersec=0.;
  148365. if(hi->amplitude_track_dBpersec<-99999.)hi->amplitude_track_dBpersec=-99999.;
  148366. /* get the appropriate setup template; matches the fetch in previous
  148367. stages */
  148368. setup=(ve_setup_data_template *)hi->setup;
  148369. if(setup==NULL)return(OV_EINVAL);
  148370. hi->set_in_stone=1;
  148371. /* choose block sizes from configured sizes as well as paying
  148372. attention to long_block_p and short_block_p. If the configured
  148373. short and long blocks are the same length, we set long_block_p
  148374. and unset short_block_p */
  148375. vorbis_encode_blocksize_setup(vi,hi->base_setting,
  148376. setup->blocksize_short,
  148377. setup->blocksize_long);
  148378. if(ci->blocksizes[0]==ci->blocksizes[1])singleblock=1;
  148379. /* floor setup; choose proper floor params. Allocated on the floor
  148380. stack in order; if we alloc only long floor, it's 0 */
  148381. vorbis_encode_floor_setup(vi,hi->short_setting,0,
  148382. setup->floor_books,
  148383. setup->floor_params,
  148384. setup->floor_short_mapping);
  148385. if(!singleblock)
  148386. vorbis_encode_floor_setup(vi,hi->long_setting,1,
  148387. setup->floor_books,
  148388. setup->floor_params,
  148389. setup->floor_long_mapping);
  148390. /* setup of [mostly] short block detection and stereo*/
  148391. vorbis_encode_global_psych_setup(vi,hi->trigger_setting,
  148392. setup->global_params,
  148393. setup->global_mapping);
  148394. vorbis_encode_global_stereo(vi,hi,setup->stereo_modes);
  148395. /* basic psych setup and noise normalization */
  148396. vorbis_encode_psyset_setup(vi,hi->short_setting,
  148397. setup->psy_noise_normal_start[0],
  148398. setup->psy_noise_normal_partition[0],
  148399. setup->psy_noise_normal_thresh,
  148400. 0);
  148401. vorbis_encode_psyset_setup(vi,hi->short_setting,
  148402. setup->psy_noise_normal_start[0],
  148403. setup->psy_noise_normal_partition[0],
  148404. setup->psy_noise_normal_thresh,
  148405. 1);
  148406. if(!singleblock){
  148407. vorbis_encode_psyset_setup(vi,hi->long_setting,
  148408. setup->psy_noise_normal_start[1],
  148409. setup->psy_noise_normal_partition[1],
  148410. setup->psy_noise_normal_thresh,
  148411. 2);
  148412. vorbis_encode_psyset_setup(vi,hi->long_setting,
  148413. setup->psy_noise_normal_start[1],
  148414. setup->psy_noise_normal_partition[1],
  148415. setup->psy_noise_normal_thresh,
  148416. 3);
  148417. }
  148418. /* tone masking setup */
  148419. vorbis_encode_tonemask_setup(vi,hi->block[i0].tone_mask_setting,0,
  148420. setup->psy_tone_masteratt,
  148421. setup->psy_tone_0dB,
  148422. setup->psy_tone_adj_impulse);
  148423. vorbis_encode_tonemask_setup(vi,hi->block[1].tone_mask_setting,1,
  148424. setup->psy_tone_masteratt,
  148425. setup->psy_tone_0dB,
  148426. setup->psy_tone_adj_other);
  148427. if(!singleblock){
  148428. vorbis_encode_tonemask_setup(vi,hi->block[2].tone_mask_setting,2,
  148429. setup->psy_tone_masteratt,
  148430. setup->psy_tone_0dB,
  148431. setup->psy_tone_adj_other);
  148432. vorbis_encode_tonemask_setup(vi,hi->block[3].tone_mask_setting,3,
  148433. setup->psy_tone_masteratt,
  148434. setup->psy_tone_0dB,
  148435. setup->psy_tone_adj_long);
  148436. }
  148437. /* noise companding setup */
  148438. vorbis_encode_compand_setup(vi,hi->block[i0].noise_compand_setting,0,
  148439. setup->psy_noise_compand,
  148440. setup->psy_noise_compand_short_mapping);
  148441. vorbis_encode_compand_setup(vi,hi->block[1].noise_compand_setting,1,
  148442. setup->psy_noise_compand,
  148443. setup->psy_noise_compand_short_mapping);
  148444. if(!singleblock){
  148445. vorbis_encode_compand_setup(vi,hi->block[2].noise_compand_setting,2,
  148446. setup->psy_noise_compand,
  148447. setup->psy_noise_compand_long_mapping);
  148448. vorbis_encode_compand_setup(vi,hi->block[3].noise_compand_setting,3,
  148449. setup->psy_noise_compand,
  148450. setup->psy_noise_compand_long_mapping);
  148451. }
  148452. /* peak guarding setup */
  148453. vorbis_encode_peak_setup(vi,hi->block[i0].tone_peaklimit_setting,0,
  148454. setup->psy_tone_dBsuppress);
  148455. vorbis_encode_peak_setup(vi,hi->block[1].tone_peaklimit_setting,1,
  148456. setup->psy_tone_dBsuppress);
  148457. if(!singleblock){
  148458. vorbis_encode_peak_setup(vi,hi->block[2].tone_peaklimit_setting,2,
  148459. setup->psy_tone_dBsuppress);
  148460. vorbis_encode_peak_setup(vi,hi->block[3].tone_peaklimit_setting,3,
  148461. setup->psy_tone_dBsuppress);
  148462. }
  148463. /* noise bias setup */
  148464. vorbis_encode_noisebias_setup(vi,hi->block[i0].noise_bias_setting,0,
  148465. setup->psy_noise_dBsuppress,
  148466. setup->psy_noise_bias_impulse,
  148467. setup->psy_noiseguards,
  148468. (i0==0?hi->impulse_noisetune:0.));
  148469. vorbis_encode_noisebias_setup(vi,hi->block[1].noise_bias_setting,1,
  148470. setup->psy_noise_dBsuppress,
  148471. setup->psy_noise_bias_padding,
  148472. setup->psy_noiseguards,0.);
  148473. if(!singleblock){
  148474. vorbis_encode_noisebias_setup(vi,hi->block[2].noise_bias_setting,2,
  148475. setup->psy_noise_dBsuppress,
  148476. setup->psy_noise_bias_trans,
  148477. setup->psy_noiseguards,0.);
  148478. vorbis_encode_noisebias_setup(vi,hi->block[3].noise_bias_setting,3,
  148479. setup->psy_noise_dBsuppress,
  148480. setup->psy_noise_bias_long,
  148481. setup->psy_noiseguards,0.);
  148482. }
  148483. vorbis_encode_ath_setup(vi,0);
  148484. vorbis_encode_ath_setup(vi,1);
  148485. if(!singleblock){
  148486. vorbis_encode_ath_setup(vi,2);
  148487. vorbis_encode_ath_setup(vi,3);
  148488. }
  148489. vorbis_encode_map_n_res_setup(vi,hi->base_setting,setup->maps);
  148490. /* set bitrate readonlies and management */
  148491. if(hi->bitrate_av>0)
  148492. vi->bitrate_nominal=hi->bitrate_av;
  148493. else{
  148494. vi->bitrate_nominal=setting_to_approx_bitrate(vi);
  148495. }
  148496. vi->bitrate_lower=hi->bitrate_min;
  148497. vi->bitrate_upper=hi->bitrate_max;
  148498. if(hi->bitrate_av)
  148499. vi->bitrate_window=(double)hi->bitrate_reservoir/hi->bitrate_av;
  148500. else
  148501. vi->bitrate_window=0.;
  148502. if(hi->managed){
  148503. ci->bi.avg_rate=hi->bitrate_av;
  148504. ci->bi.min_rate=hi->bitrate_min;
  148505. ci->bi.max_rate=hi->bitrate_max;
  148506. ci->bi.reservoir_bits=hi->bitrate_reservoir;
  148507. ci->bi.reservoir_bias=
  148508. hi->bitrate_reservoir_bias;
  148509. ci->bi.slew_damp=hi->bitrate_av_damp;
  148510. }
  148511. return(0);
  148512. }
  148513. static int vorbis_encode_setup_setting(vorbis_info *vi,
  148514. long channels,
  148515. long rate){
  148516. int ret=0,i,is;
  148517. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  148518. highlevel_encode_setup *hi=&ci->hi;
  148519. ve_setup_data_template *setup=(ve_setup_data_template*) hi->setup;
  148520. double ds;
  148521. ret=vorbis_encode_toplevel_setup(vi,channels,rate);
  148522. if(ret)return(ret);
  148523. is=hi->base_setting;
  148524. ds=hi->base_setting-is;
  148525. hi->short_setting=hi->base_setting;
  148526. hi->long_setting=hi->base_setting;
  148527. hi->managed=0;
  148528. hi->impulse_block_p=1;
  148529. hi->noise_normalize_p=1;
  148530. hi->stereo_point_setting=hi->base_setting;
  148531. hi->lowpass_kHz=
  148532. setup->psy_lowpass[is]*(1.-ds)+setup->psy_lowpass[is+1]*ds;
  148533. hi->ath_floating_dB=setup->psy_ath_float[is]*(1.-ds)+
  148534. setup->psy_ath_float[is+1]*ds;
  148535. hi->ath_absolute_dB=setup->psy_ath_abs[is]*(1.-ds)+
  148536. setup->psy_ath_abs[is+1]*ds;
  148537. hi->amplitude_track_dBpersec=-6.;
  148538. hi->trigger_setting=hi->base_setting;
  148539. for(i=0;i<4;i++){
  148540. hi->block[i].tone_mask_setting=hi->base_setting;
  148541. hi->block[i].tone_peaklimit_setting=hi->base_setting;
  148542. hi->block[i].noise_bias_setting=hi->base_setting;
  148543. hi->block[i].noise_compand_setting=hi->base_setting;
  148544. }
  148545. return(ret);
  148546. }
  148547. int vorbis_encode_setup_vbr(vorbis_info *vi,
  148548. long channels,
  148549. long rate,
  148550. float quality){
  148551. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  148552. highlevel_encode_setup *hi=&ci->hi;
  148553. quality+=.0000001;
  148554. if(quality>=1.)quality=.9999;
  148555. get_setup_template(vi,channels,rate,quality,0);
  148556. if(!hi->setup)return OV_EIMPL;
  148557. return vorbis_encode_setup_setting(vi,channels,rate);
  148558. }
  148559. int vorbis_encode_init_vbr(vorbis_info *vi,
  148560. long channels,
  148561. long rate,
  148562. float base_quality /* 0. to 1. */
  148563. ){
  148564. int ret=0;
  148565. ret=vorbis_encode_setup_vbr(vi,channels,rate,base_quality);
  148566. if(ret){
  148567. vorbis_info_clear(vi);
  148568. return ret;
  148569. }
  148570. ret=vorbis_encode_setup_init(vi);
  148571. if(ret)
  148572. vorbis_info_clear(vi);
  148573. return(ret);
  148574. }
  148575. int vorbis_encode_setup_managed(vorbis_info *vi,
  148576. long channels,
  148577. long rate,
  148578. long max_bitrate,
  148579. long nominal_bitrate,
  148580. long min_bitrate){
  148581. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  148582. highlevel_encode_setup *hi=&ci->hi;
  148583. double tnominal=nominal_bitrate;
  148584. int ret=0;
  148585. if(nominal_bitrate<=0.){
  148586. if(max_bitrate>0.){
  148587. if(min_bitrate>0.)
  148588. nominal_bitrate=(max_bitrate+min_bitrate)*.5;
  148589. else
  148590. nominal_bitrate=max_bitrate*.875;
  148591. }else{
  148592. if(min_bitrate>0.){
  148593. nominal_bitrate=min_bitrate;
  148594. }else{
  148595. return(OV_EINVAL);
  148596. }
  148597. }
  148598. }
  148599. get_setup_template(vi,channels,rate,nominal_bitrate,1);
  148600. if(!hi->setup)return OV_EIMPL;
  148601. ret=vorbis_encode_setup_setting(vi,channels,rate);
  148602. if(ret){
  148603. vorbis_info_clear(vi);
  148604. return ret;
  148605. }
  148606. /* initialize management with sane defaults */
  148607. hi->managed=1;
  148608. hi->bitrate_min=min_bitrate;
  148609. hi->bitrate_max=max_bitrate;
  148610. hi->bitrate_av=tnominal;
  148611. hi->bitrate_av_damp=1.5f; /* full range in no less than 1.5 second */
  148612. hi->bitrate_reservoir=nominal_bitrate*2;
  148613. hi->bitrate_reservoir_bias=.1; /* bias toward hoarding bits */
  148614. return(ret);
  148615. }
  148616. int vorbis_encode_init(vorbis_info *vi,
  148617. long channels,
  148618. long rate,
  148619. long max_bitrate,
  148620. long nominal_bitrate,
  148621. long min_bitrate){
  148622. int ret=vorbis_encode_setup_managed(vi,channels,rate,
  148623. max_bitrate,
  148624. nominal_bitrate,
  148625. min_bitrate);
  148626. if(ret){
  148627. vorbis_info_clear(vi);
  148628. return(ret);
  148629. }
  148630. ret=vorbis_encode_setup_init(vi);
  148631. if(ret)
  148632. vorbis_info_clear(vi);
  148633. return(ret);
  148634. }
  148635. int vorbis_encode_ctl(vorbis_info *vi,int number,void *arg){
  148636. if(vi){
  148637. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  148638. highlevel_encode_setup *hi=&ci->hi;
  148639. int setp=(number&0xf); /* a read request has a low nibble of 0 */
  148640. if(setp && hi->set_in_stone)return(OV_EINVAL);
  148641. switch(number){
  148642. /* now deprecated *****************/
  148643. case OV_ECTL_RATEMANAGE_GET:
  148644. {
  148645. struct ovectl_ratemanage_arg *ai=
  148646. (struct ovectl_ratemanage_arg *)arg;
  148647. ai->management_active=hi->managed;
  148648. ai->bitrate_hard_window=ai->bitrate_av_window=
  148649. (double)hi->bitrate_reservoir/vi->rate;
  148650. ai->bitrate_av_window_center=1.;
  148651. ai->bitrate_hard_min=hi->bitrate_min;
  148652. ai->bitrate_hard_max=hi->bitrate_max;
  148653. ai->bitrate_av_lo=hi->bitrate_av;
  148654. ai->bitrate_av_hi=hi->bitrate_av;
  148655. }
  148656. return(0);
  148657. /* now deprecated *****************/
  148658. case OV_ECTL_RATEMANAGE_SET:
  148659. {
  148660. struct ovectl_ratemanage_arg *ai=
  148661. (struct ovectl_ratemanage_arg *)arg;
  148662. if(ai==NULL){
  148663. hi->managed=0;
  148664. }else{
  148665. hi->managed=ai->management_active;
  148666. vorbis_encode_ctl(vi,OV_ECTL_RATEMANAGE_AVG,arg);
  148667. vorbis_encode_ctl(vi,OV_ECTL_RATEMANAGE_HARD,arg);
  148668. }
  148669. }
  148670. return 0;
  148671. /* now deprecated *****************/
  148672. case OV_ECTL_RATEMANAGE_AVG:
  148673. {
  148674. struct ovectl_ratemanage_arg *ai=
  148675. (struct ovectl_ratemanage_arg *)arg;
  148676. if(ai==NULL){
  148677. hi->bitrate_av=0;
  148678. }else{
  148679. hi->bitrate_av=(ai->bitrate_av_lo+ai->bitrate_av_hi)*.5;
  148680. }
  148681. }
  148682. return(0);
  148683. /* now deprecated *****************/
  148684. case OV_ECTL_RATEMANAGE_HARD:
  148685. {
  148686. struct ovectl_ratemanage_arg *ai=
  148687. (struct ovectl_ratemanage_arg *)arg;
  148688. if(ai==NULL){
  148689. hi->bitrate_min=0;
  148690. hi->bitrate_max=0;
  148691. }else{
  148692. hi->bitrate_min=ai->bitrate_hard_min;
  148693. hi->bitrate_max=ai->bitrate_hard_max;
  148694. hi->bitrate_reservoir=ai->bitrate_hard_window*
  148695. (hi->bitrate_max+hi->bitrate_min)*.5;
  148696. }
  148697. if(hi->bitrate_reservoir<128.)
  148698. hi->bitrate_reservoir=128.;
  148699. }
  148700. return(0);
  148701. /* replacement ratemanage interface */
  148702. case OV_ECTL_RATEMANAGE2_GET:
  148703. {
  148704. struct ovectl_ratemanage2_arg *ai=
  148705. (struct ovectl_ratemanage2_arg *)arg;
  148706. if(ai==NULL)return OV_EINVAL;
  148707. ai->management_active=hi->managed;
  148708. ai->bitrate_limit_min_kbps=hi->bitrate_min/1000;
  148709. ai->bitrate_limit_max_kbps=hi->bitrate_max/1000;
  148710. ai->bitrate_average_kbps=hi->bitrate_av/1000;
  148711. ai->bitrate_average_damping=hi->bitrate_av_damp;
  148712. ai->bitrate_limit_reservoir_bits=hi->bitrate_reservoir;
  148713. ai->bitrate_limit_reservoir_bias=hi->bitrate_reservoir_bias;
  148714. }
  148715. return (0);
  148716. case OV_ECTL_RATEMANAGE2_SET:
  148717. {
  148718. struct ovectl_ratemanage2_arg *ai=
  148719. (struct ovectl_ratemanage2_arg *)arg;
  148720. if(ai==NULL){
  148721. hi->managed=0;
  148722. }else{
  148723. /* sanity check; only catch invariant violations */
  148724. if(ai->bitrate_limit_min_kbps>0 &&
  148725. ai->bitrate_average_kbps>0 &&
  148726. ai->bitrate_limit_min_kbps>ai->bitrate_average_kbps)
  148727. return OV_EINVAL;
  148728. if(ai->bitrate_limit_max_kbps>0 &&
  148729. ai->bitrate_average_kbps>0 &&
  148730. ai->bitrate_limit_max_kbps<ai->bitrate_average_kbps)
  148731. return OV_EINVAL;
  148732. if(ai->bitrate_limit_min_kbps>0 &&
  148733. ai->bitrate_limit_max_kbps>0 &&
  148734. ai->bitrate_limit_min_kbps>ai->bitrate_limit_max_kbps)
  148735. return OV_EINVAL;
  148736. if(ai->bitrate_average_damping <= 0.)
  148737. return OV_EINVAL;
  148738. if(ai->bitrate_limit_reservoir_bits < 0)
  148739. return OV_EINVAL;
  148740. if(ai->bitrate_limit_reservoir_bias < 0.)
  148741. return OV_EINVAL;
  148742. if(ai->bitrate_limit_reservoir_bias > 1.)
  148743. return OV_EINVAL;
  148744. hi->managed=ai->management_active;
  148745. hi->bitrate_min=ai->bitrate_limit_min_kbps * 1000;
  148746. hi->bitrate_max=ai->bitrate_limit_max_kbps * 1000;
  148747. hi->bitrate_av=ai->bitrate_average_kbps * 1000;
  148748. hi->bitrate_av_damp=ai->bitrate_average_damping;
  148749. hi->bitrate_reservoir=ai->bitrate_limit_reservoir_bits;
  148750. hi->bitrate_reservoir_bias=ai->bitrate_limit_reservoir_bias;
  148751. }
  148752. }
  148753. return 0;
  148754. case OV_ECTL_LOWPASS_GET:
  148755. {
  148756. double *farg=(double *)arg;
  148757. *farg=hi->lowpass_kHz;
  148758. }
  148759. return(0);
  148760. case OV_ECTL_LOWPASS_SET:
  148761. {
  148762. double *farg=(double *)arg;
  148763. hi->lowpass_kHz=*farg;
  148764. if(hi->lowpass_kHz<2.)hi->lowpass_kHz=2.;
  148765. if(hi->lowpass_kHz>99.)hi->lowpass_kHz=99.;
  148766. }
  148767. return(0);
  148768. case OV_ECTL_IBLOCK_GET:
  148769. {
  148770. double *farg=(double *)arg;
  148771. *farg=hi->impulse_noisetune;
  148772. }
  148773. return(0);
  148774. case OV_ECTL_IBLOCK_SET:
  148775. {
  148776. double *farg=(double *)arg;
  148777. hi->impulse_noisetune=*farg;
  148778. if(hi->impulse_noisetune>0.)hi->impulse_noisetune=0.;
  148779. if(hi->impulse_noisetune<-15.)hi->impulse_noisetune=-15.;
  148780. }
  148781. return(0);
  148782. }
  148783. return(OV_EIMPL);
  148784. }
  148785. return(OV_EINVAL);
  148786. }
  148787. #endif
  148788. /********* End of inlined file: vorbisenc.c *********/
  148789. /********* Start of inlined file: vorbisfile.c *********/
  148790. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  148791. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  148792. // tasks..
  148793. #ifdef _MSC_VER
  148794. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  148795. #endif
  148796. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  148797. #if JUCE_USE_OGGVORBIS
  148798. #include <stdlib.h>
  148799. #include <stdio.h>
  148800. #include <errno.h>
  148801. #include <string.h>
  148802. #include <math.h>
  148803. /* A 'chained bitstream' is a Vorbis bitstream that contains more than
  148804. one logical bitstream arranged end to end (the only form of Ogg
  148805. multiplexing allowed in a Vorbis bitstream; grouping [parallel
  148806. multiplexing] is not allowed in Vorbis) */
  148807. /* A Vorbis file can be played beginning to end (streamed) without
  148808. worrying ahead of time about chaining (see decoder_example.c). If
  148809. we have the whole file, however, and want random access
  148810. (seeking/scrubbing) or desire to know the total length/time of a
  148811. file, we need to account for the possibility of chaining. */
  148812. /* We can handle things a number of ways; we can determine the entire
  148813. bitstream structure right off the bat, or find pieces on demand.
  148814. This example determines and caches structure for the entire
  148815. bitstream, but builds a virtual decoder on the fly when moving
  148816. between links in the chain. */
  148817. /* There are also different ways to implement seeking. Enough
  148818. information exists in an Ogg bitstream to seek to
  148819. sample-granularity positions in the output. Or, one can seek by
  148820. picking some portion of the stream roughly in the desired area if
  148821. we only want coarse navigation through the stream. */
  148822. /*************************************************************************
  148823. * Many, many internal helpers. The intention is not to be confusing;
  148824. * rampant duplication and monolithic function implementation would be
  148825. * harder to understand anyway. The high level functions are last. Begin
  148826. * grokking near the end of the file */
  148827. /* read a little more data from the file/pipe into the ogg_sync framer
  148828. */
  148829. #define CHUNKSIZE 8500 /* a shade over 8k; anyone using pages well
  148830. over 8k gets what they deserve */
  148831. static long _get_data(OggVorbis_File *vf){
  148832. errno=0;
  148833. if(vf->datasource){
  148834. char *buffer=ogg_sync_buffer(&vf->oy,CHUNKSIZE);
  148835. long bytes=(vf->callbacks.read_func)(buffer,1,CHUNKSIZE,vf->datasource);
  148836. if(bytes>0)ogg_sync_wrote(&vf->oy,bytes);
  148837. if(bytes==0 && errno)return(-1);
  148838. return(bytes);
  148839. }else
  148840. return(0);
  148841. }
  148842. /* save a tiny smidge of verbosity to make the code more readable */
  148843. static void _seek_helper(OggVorbis_File *vf,ogg_int64_t offset){
  148844. if(vf->datasource){
  148845. (vf->callbacks.seek_func)(vf->datasource, offset, SEEK_SET);
  148846. vf->offset=offset;
  148847. ogg_sync_reset(&vf->oy);
  148848. }else{
  148849. /* shouldn't happen unless someone writes a broken callback */
  148850. return;
  148851. }
  148852. }
  148853. /* The read/seek functions track absolute position within the stream */
  148854. /* from the head of the stream, get the next page. boundary specifies
  148855. if the function is allowed to fetch more data from the stream (and
  148856. how much) or only use internally buffered data.
  148857. boundary: -1) unbounded search
  148858. 0) read no additional data; use cached only
  148859. n) search for a new page beginning for n bytes
  148860. return: <0) did not find a page (OV_FALSE, OV_EOF, OV_EREAD)
  148861. n) found a page at absolute offset n */
  148862. static ogg_int64_t _get_next_page(OggVorbis_File *vf,ogg_page *og,
  148863. ogg_int64_t boundary){
  148864. if(boundary>0)boundary+=vf->offset;
  148865. while(1){
  148866. long more;
  148867. if(boundary>0 && vf->offset>=boundary)return(OV_FALSE);
  148868. more=ogg_sync_pageseek(&vf->oy,og);
  148869. if(more<0){
  148870. /* skipped n bytes */
  148871. vf->offset-=more;
  148872. }else{
  148873. if(more==0){
  148874. /* send more paramedics */
  148875. if(!boundary)return(OV_FALSE);
  148876. {
  148877. long ret=_get_data(vf);
  148878. if(ret==0)return(OV_EOF);
  148879. if(ret<0)return(OV_EREAD);
  148880. }
  148881. }else{
  148882. /* got a page. Return the offset at the page beginning,
  148883. advance the internal offset past the page end */
  148884. ogg_int64_t ret=vf->offset;
  148885. vf->offset+=more;
  148886. return(ret);
  148887. }
  148888. }
  148889. }
  148890. }
  148891. /* find the latest page beginning before the current stream cursor
  148892. position. Much dirtier than the above as Ogg doesn't have any
  148893. backward search linkage. no 'readp' as it will certainly have to
  148894. read. */
  148895. /* returns offset or OV_EREAD, OV_FAULT */
  148896. static ogg_int64_t _get_prev_page(OggVorbis_File *vf,ogg_page *og){
  148897. ogg_int64_t begin=vf->offset;
  148898. ogg_int64_t end=begin;
  148899. ogg_int64_t ret;
  148900. ogg_int64_t offset=-1;
  148901. while(offset==-1){
  148902. begin-=CHUNKSIZE;
  148903. if(begin<0)
  148904. begin=0;
  148905. _seek_helper(vf,begin);
  148906. while(vf->offset<end){
  148907. ret=_get_next_page(vf,og,end-vf->offset);
  148908. if(ret==OV_EREAD)return(OV_EREAD);
  148909. if(ret<0){
  148910. break;
  148911. }else{
  148912. offset=ret;
  148913. }
  148914. }
  148915. }
  148916. /* we have the offset. Actually snork and hold the page now */
  148917. _seek_helper(vf,offset);
  148918. ret=_get_next_page(vf,og,CHUNKSIZE);
  148919. if(ret<0)
  148920. /* this shouldn't be possible */
  148921. return(OV_EFAULT);
  148922. return(offset);
  148923. }
  148924. /* finds each bitstream link one at a time using a bisection search
  148925. (has to begin by knowing the offset of the lb's initial page).
  148926. Recurses for each link so it can alloc the link storage after
  148927. finding them all, then unroll and fill the cache at the same time */
  148928. static int _bisect_forward_serialno(OggVorbis_File *vf,
  148929. ogg_int64_t begin,
  148930. ogg_int64_t searched,
  148931. ogg_int64_t end,
  148932. long currentno,
  148933. long m){
  148934. ogg_int64_t endsearched=end;
  148935. ogg_int64_t next=end;
  148936. ogg_page og;
  148937. ogg_int64_t ret;
  148938. /* the below guards against garbage seperating the last and
  148939. first pages of two links. */
  148940. while(searched<endsearched){
  148941. ogg_int64_t bisect;
  148942. if(endsearched-searched<CHUNKSIZE){
  148943. bisect=searched;
  148944. }else{
  148945. bisect=(searched+endsearched)/2;
  148946. }
  148947. _seek_helper(vf,bisect);
  148948. ret=_get_next_page(vf,&og,-1);
  148949. if(ret==OV_EREAD)return(OV_EREAD);
  148950. if(ret<0 || ogg_page_serialno(&og)!=currentno){
  148951. endsearched=bisect;
  148952. if(ret>=0)next=ret;
  148953. }else{
  148954. searched=ret+og.header_len+og.body_len;
  148955. }
  148956. }
  148957. _seek_helper(vf,next);
  148958. ret=_get_next_page(vf,&og,-1);
  148959. if(ret==OV_EREAD)return(OV_EREAD);
  148960. if(searched>=end || ret<0){
  148961. vf->links=m+1;
  148962. vf->offsets=(ogg_int64_t*)_ogg_malloc((vf->links+1)*sizeof(*vf->offsets));
  148963. vf->serialnos=(long*)_ogg_malloc(vf->links*sizeof(*vf->serialnos));
  148964. vf->offsets[m+1]=searched;
  148965. }else{
  148966. ret=_bisect_forward_serialno(vf,next,vf->offset,
  148967. end,ogg_page_serialno(&og),m+1);
  148968. if(ret==OV_EREAD)return(OV_EREAD);
  148969. }
  148970. vf->offsets[m]=begin;
  148971. vf->serialnos[m]=currentno;
  148972. return(0);
  148973. }
  148974. /* uses the local ogg_stream storage in vf; this is important for
  148975. non-streaming input sources */
  148976. static int _fetch_headers(OggVorbis_File *vf,vorbis_info *vi,vorbis_comment *vc,
  148977. long *serialno,ogg_page *og_ptr){
  148978. ogg_page og;
  148979. ogg_packet op;
  148980. int i,ret;
  148981. if(!og_ptr){
  148982. ogg_int64_t llret=_get_next_page(vf,&og,CHUNKSIZE);
  148983. if(llret==OV_EREAD)return(OV_EREAD);
  148984. if(llret<0)return OV_ENOTVORBIS;
  148985. og_ptr=&og;
  148986. }
  148987. ogg_stream_reset_serialno(&vf->os,ogg_page_serialno(og_ptr));
  148988. if(serialno)*serialno=vf->os.serialno;
  148989. vf->ready_state=STREAMSET;
  148990. /* extract the initial header from the first page and verify that the
  148991. Ogg bitstream is in fact Vorbis data */
  148992. vorbis_info_init(vi);
  148993. vorbis_comment_init(vc);
  148994. i=0;
  148995. while(i<3){
  148996. ogg_stream_pagein(&vf->os,og_ptr);
  148997. while(i<3){
  148998. int result=ogg_stream_packetout(&vf->os,&op);
  148999. if(result==0)break;
  149000. if(result==-1){
  149001. ret=OV_EBADHEADER;
  149002. goto bail_header;
  149003. }
  149004. if((ret=vorbis_synthesis_headerin(vi,vc,&op))){
  149005. goto bail_header;
  149006. }
  149007. i++;
  149008. }
  149009. if(i<3)
  149010. if(_get_next_page(vf,og_ptr,CHUNKSIZE)<0){
  149011. ret=OV_EBADHEADER;
  149012. goto bail_header;
  149013. }
  149014. }
  149015. return 0;
  149016. bail_header:
  149017. vorbis_info_clear(vi);
  149018. vorbis_comment_clear(vc);
  149019. vf->ready_state=OPENED;
  149020. return ret;
  149021. }
  149022. /* last step of the OggVorbis_File initialization; get all the
  149023. vorbis_info structs and PCM positions. Only called by the seekable
  149024. initialization (local stream storage is hacked slightly; pay
  149025. attention to how that's done) */
  149026. /* this is void and does not propogate errors up because we want to be
  149027. able to open and use damaged bitstreams as well as we can. Just
  149028. watch out for missing information for links in the OggVorbis_File
  149029. struct */
  149030. static void _prefetch_all_headers(OggVorbis_File *vf, ogg_int64_t dataoffset){
  149031. ogg_page og;
  149032. int i;
  149033. ogg_int64_t ret;
  149034. vf->vi=(vorbis_info*) _ogg_realloc(vf->vi,vf->links*sizeof(*vf->vi));
  149035. vf->vc=(vorbis_comment*) _ogg_realloc(vf->vc,vf->links*sizeof(*vf->vc));
  149036. vf->dataoffsets=(ogg_int64_t*) _ogg_malloc(vf->links*sizeof(*vf->dataoffsets));
  149037. vf->pcmlengths=(ogg_int64_t*) _ogg_malloc(vf->links*2*sizeof(*vf->pcmlengths));
  149038. for(i=0;i<vf->links;i++){
  149039. if(i==0){
  149040. /* we already grabbed the initial header earlier. Just set the offset */
  149041. vf->dataoffsets[i]=dataoffset;
  149042. _seek_helper(vf,dataoffset);
  149043. }else{
  149044. /* seek to the location of the initial header */
  149045. _seek_helper(vf,vf->offsets[i]);
  149046. if(_fetch_headers(vf,vf->vi+i,vf->vc+i,NULL,NULL)<0){
  149047. vf->dataoffsets[i]=-1;
  149048. }else{
  149049. vf->dataoffsets[i]=vf->offset;
  149050. }
  149051. }
  149052. /* fetch beginning PCM offset */
  149053. if(vf->dataoffsets[i]!=-1){
  149054. ogg_int64_t accumulated=0;
  149055. long lastblock=-1;
  149056. int result;
  149057. ogg_stream_reset_serialno(&vf->os,vf->serialnos[i]);
  149058. while(1){
  149059. ogg_packet op;
  149060. ret=_get_next_page(vf,&og,-1);
  149061. if(ret<0)
  149062. /* this should not be possible unless the file is
  149063. truncated/mangled */
  149064. break;
  149065. if(ogg_page_serialno(&og)!=vf->serialnos[i])
  149066. break;
  149067. /* count blocksizes of all frames in the page */
  149068. ogg_stream_pagein(&vf->os,&og);
  149069. while((result=ogg_stream_packetout(&vf->os,&op))){
  149070. if(result>0){ /* ignore holes */
  149071. long thisblock=vorbis_packet_blocksize(vf->vi+i,&op);
  149072. if(lastblock!=-1)
  149073. accumulated+=(lastblock+thisblock)>>2;
  149074. lastblock=thisblock;
  149075. }
  149076. }
  149077. if(ogg_page_granulepos(&og)!=-1){
  149078. /* pcm offset of last packet on the first audio page */
  149079. accumulated= ogg_page_granulepos(&og)-accumulated;
  149080. break;
  149081. }
  149082. }
  149083. /* less than zero? This is a stream with samples trimmed off
  149084. the beginning, a normal occurrence; set the offset to zero */
  149085. if(accumulated<0)accumulated=0;
  149086. vf->pcmlengths[i*2]=accumulated;
  149087. }
  149088. /* get the PCM length of this link. To do this,
  149089. get the last page of the stream */
  149090. {
  149091. ogg_int64_t end=vf->offsets[i+1];
  149092. _seek_helper(vf,end);
  149093. while(1){
  149094. ret=_get_prev_page(vf,&og);
  149095. if(ret<0){
  149096. /* this should not be possible */
  149097. vorbis_info_clear(vf->vi+i);
  149098. vorbis_comment_clear(vf->vc+i);
  149099. break;
  149100. }
  149101. if(ogg_page_granulepos(&og)!=-1){
  149102. vf->pcmlengths[i*2+1]=ogg_page_granulepos(&og)-vf->pcmlengths[i*2];
  149103. break;
  149104. }
  149105. vf->offset=ret;
  149106. }
  149107. }
  149108. }
  149109. }
  149110. static int _make_decode_ready(OggVorbis_File *vf){
  149111. if(vf->ready_state>STREAMSET)return 0;
  149112. if(vf->ready_state<STREAMSET)return OV_EFAULT;
  149113. if(vf->seekable){
  149114. if(vorbis_synthesis_init(&vf->vd,vf->vi+vf->current_link))
  149115. return OV_EBADLINK;
  149116. }else{
  149117. if(vorbis_synthesis_init(&vf->vd,vf->vi))
  149118. return OV_EBADLINK;
  149119. }
  149120. vorbis_block_init(&vf->vd,&vf->vb);
  149121. vf->ready_state=INITSET;
  149122. vf->bittrack=0.f;
  149123. vf->samptrack=0.f;
  149124. return 0;
  149125. }
  149126. static int _open_seekable2(OggVorbis_File *vf){
  149127. long serialno=vf->current_serialno;
  149128. ogg_int64_t dataoffset=vf->offset, end;
  149129. ogg_page og;
  149130. /* we're partially open and have a first link header state in
  149131. storage in vf */
  149132. /* we can seek, so set out learning all about this file */
  149133. (vf->callbacks.seek_func)(vf->datasource,0,SEEK_END);
  149134. vf->offset=vf->end=(vf->callbacks.tell_func)(vf->datasource);
  149135. /* We get the offset for the last page of the physical bitstream.
  149136. Most OggVorbis files will contain a single logical bitstream */
  149137. end=_get_prev_page(vf,&og);
  149138. if(end<0)return(end);
  149139. /* more than one logical bitstream? */
  149140. if(ogg_page_serialno(&og)!=serialno){
  149141. /* Chained bitstream. Bisect-search each logical bitstream
  149142. section. Do so based on serial number only */
  149143. if(_bisect_forward_serialno(vf,0,0,end+1,serialno,0)<0)return(OV_EREAD);
  149144. }else{
  149145. /* Only one logical bitstream */
  149146. if(_bisect_forward_serialno(vf,0,end,end+1,serialno,0))return(OV_EREAD);
  149147. }
  149148. /* the initial header memory is referenced by vf after; don't free it */
  149149. _prefetch_all_headers(vf,dataoffset);
  149150. return(ov_raw_seek(vf,0));
  149151. }
  149152. /* clear out the current logical bitstream decoder */
  149153. static void _decode_clear(OggVorbis_File *vf){
  149154. vorbis_dsp_clear(&vf->vd);
  149155. vorbis_block_clear(&vf->vb);
  149156. vf->ready_state=OPENED;
  149157. }
  149158. /* fetch and process a packet. Handles the case where we're at a
  149159. bitstream boundary and dumps the decoding machine. If the decoding
  149160. machine is unloaded, it loads it. It also keeps pcm_offset up to
  149161. date (seek and read both use this. seek uses a special hack with
  149162. readp).
  149163. return: <0) error, OV_HOLE (lost packet) or OV_EOF
  149164. 0) need more data (only if readp==0)
  149165. 1) got a packet
  149166. */
  149167. static int _fetch_and_process_packet(OggVorbis_File *vf,
  149168. ogg_packet *op_in,
  149169. int readp,
  149170. int spanp){
  149171. ogg_page og;
  149172. /* handle one packet. Try to fetch it from current stream state */
  149173. /* extract packets from page */
  149174. while(1){
  149175. /* process a packet if we can. If the machine isn't loaded,
  149176. neither is a page */
  149177. if(vf->ready_state==INITSET){
  149178. while(1) {
  149179. ogg_packet op;
  149180. ogg_packet *op_ptr=(op_in?op_in:&op);
  149181. int result=ogg_stream_packetout(&vf->os,op_ptr);
  149182. ogg_int64_t granulepos;
  149183. op_in=NULL;
  149184. if(result==-1)return(OV_HOLE); /* hole in the data. */
  149185. if(result>0){
  149186. /* got a packet. process it */
  149187. granulepos=op_ptr->granulepos;
  149188. if(!vorbis_synthesis(&vf->vb,op_ptr)){ /* lazy check for lazy
  149189. header handling. The
  149190. header packets aren't
  149191. audio, so if/when we
  149192. submit them,
  149193. vorbis_synthesis will
  149194. reject them */
  149195. /* suck in the synthesis data and track bitrate */
  149196. {
  149197. int oldsamples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  149198. /* for proper use of libvorbis within libvorbisfile,
  149199. oldsamples will always be zero. */
  149200. if(oldsamples)return(OV_EFAULT);
  149201. vorbis_synthesis_blockin(&vf->vd,&vf->vb);
  149202. vf->samptrack+=vorbis_synthesis_pcmout(&vf->vd,NULL)-oldsamples;
  149203. vf->bittrack+=op_ptr->bytes*8;
  149204. }
  149205. /* update the pcm offset. */
  149206. if(granulepos!=-1 && !op_ptr->e_o_s){
  149207. int link=(vf->seekable?vf->current_link:0);
  149208. int i,samples;
  149209. /* this packet has a pcm_offset on it (the last packet
  149210. completed on a page carries the offset) After processing
  149211. (above), we know the pcm position of the *last* sample
  149212. ready to be returned. Find the offset of the *first*
  149213. As an aside, this trick is inaccurate if we begin
  149214. reading anew right at the last page; the end-of-stream
  149215. granulepos declares the last frame in the stream, and the
  149216. last packet of the last page may be a partial frame.
  149217. So, we need a previous granulepos from an in-sequence page
  149218. to have a reference point. Thus the !op_ptr->e_o_s clause
  149219. above */
  149220. if(vf->seekable && link>0)
  149221. granulepos-=vf->pcmlengths[link*2];
  149222. if(granulepos<0)granulepos=0; /* actually, this
  149223. shouldn't be possible
  149224. here unless the stream
  149225. is very broken */
  149226. samples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  149227. granulepos-=samples;
  149228. for(i=0;i<link;i++)
  149229. granulepos+=vf->pcmlengths[i*2+1];
  149230. vf->pcm_offset=granulepos;
  149231. }
  149232. return(1);
  149233. }
  149234. }
  149235. else
  149236. break;
  149237. }
  149238. }
  149239. if(vf->ready_state>=OPENED){
  149240. ogg_int64_t ret;
  149241. if(!readp)return(0);
  149242. if((ret=_get_next_page(vf,&og,-1))<0){
  149243. return(OV_EOF); /* eof.
  149244. leave unitialized */
  149245. }
  149246. /* bitrate tracking; add the header's bytes here, the body bytes
  149247. are done by packet above */
  149248. vf->bittrack+=og.header_len*8;
  149249. /* has our decoding just traversed a bitstream boundary? */
  149250. if(vf->ready_state==INITSET){
  149251. if(vf->current_serialno!=ogg_page_serialno(&og)){
  149252. if(!spanp)
  149253. return(OV_EOF);
  149254. _decode_clear(vf);
  149255. if(!vf->seekable){
  149256. vorbis_info_clear(vf->vi);
  149257. vorbis_comment_clear(vf->vc);
  149258. }
  149259. }
  149260. }
  149261. }
  149262. /* Do we need to load a new machine before submitting the page? */
  149263. /* This is different in the seekable and non-seekable cases.
  149264. In the seekable case, we already have all the header
  149265. information loaded and cached; we just initialize the machine
  149266. with it and continue on our merry way.
  149267. In the non-seekable (streaming) case, we'll only be at a
  149268. boundary if we just left the previous logical bitstream and
  149269. we're now nominally at the header of the next bitstream
  149270. */
  149271. if(vf->ready_state!=INITSET){
  149272. int link;
  149273. if(vf->ready_state<STREAMSET){
  149274. if(vf->seekable){
  149275. vf->current_serialno=ogg_page_serialno(&og);
  149276. /* match the serialno to bitstream section. We use this rather than
  149277. offset positions to avoid problems near logical bitstream
  149278. boundaries */
  149279. for(link=0;link<vf->links;link++)
  149280. if(vf->serialnos[link]==vf->current_serialno)break;
  149281. if(link==vf->links)return(OV_EBADLINK); /* sign of a bogus
  149282. stream. error out,
  149283. leave machine
  149284. uninitialized */
  149285. vf->current_link=link;
  149286. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  149287. vf->ready_state=STREAMSET;
  149288. }else{
  149289. /* we're streaming */
  149290. /* fetch the three header packets, build the info struct */
  149291. int ret=_fetch_headers(vf,vf->vi,vf->vc,&vf->current_serialno,&og);
  149292. if(ret)return(ret);
  149293. vf->current_link++;
  149294. link=0;
  149295. }
  149296. }
  149297. {
  149298. int ret=_make_decode_ready(vf);
  149299. if(ret<0)return ret;
  149300. }
  149301. }
  149302. ogg_stream_pagein(&vf->os,&og);
  149303. }
  149304. }
  149305. /* if, eg, 64 bit stdio is configured by default, this will build with
  149306. fseek64 */
  149307. static int _fseek64_wrap(FILE *f,ogg_int64_t off,int whence){
  149308. if(f==NULL)return(-1);
  149309. return fseek(f,off,whence);
  149310. }
  149311. static int _ov_open1(void *f,OggVorbis_File *vf,char *initial,
  149312. long ibytes, ov_callbacks callbacks){
  149313. int offsettest=(f?callbacks.seek_func(f,0,SEEK_CUR):-1);
  149314. int ret;
  149315. memset(vf,0,sizeof(*vf));
  149316. vf->datasource=f;
  149317. vf->callbacks = callbacks;
  149318. /* init the framing state */
  149319. ogg_sync_init(&vf->oy);
  149320. /* perhaps some data was previously read into a buffer for testing
  149321. against other stream types. Allow initialization from this
  149322. previously read data (as we may be reading from a non-seekable
  149323. stream) */
  149324. if(initial){
  149325. char *buffer=ogg_sync_buffer(&vf->oy,ibytes);
  149326. memcpy(buffer,initial,ibytes);
  149327. ogg_sync_wrote(&vf->oy,ibytes);
  149328. }
  149329. /* can we seek? Stevens suggests the seek test was portable */
  149330. if(offsettest!=-1)vf->seekable=1;
  149331. /* No seeking yet; Set up a 'single' (current) logical bitstream
  149332. entry for partial open */
  149333. vf->links=1;
  149334. vf->vi=(vorbis_info*) _ogg_calloc(vf->links,sizeof(*vf->vi));
  149335. vf->vc=(vorbis_comment*) _ogg_calloc(vf->links,sizeof(*vf->vc));
  149336. ogg_stream_init(&vf->os,-1); /* fill in the serialno later */
  149337. /* Try to fetch the headers, maintaining all the storage */
  149338. if((ret=_fetch_headers(vf,vf->vi,vf->vc,&vf->current_serialno,NULL))<0){
  149339. vf->datasource=NULL;
  149340. ov_clear(vf);
  149341. }else
  149342. vf->ready_state=PARTOPEN;
  149343. return(ret);
  149344. }
  149345. static int _ov_open2(OggVorbis_File *vf){
  149346. if(vf->ready_state != PARTOPEN) return OV_EINVAL;
  149347. vf->ready_state=OPENED;
  149348. if(vf->seekable){
  149349. int ret=_open_seekable2(vf);
  149350. if(ret){
  149351. vf->datasource=NULL;
  149352. ov_clear(vf);
  149353. }
  149354. return(ret);
  149355. }else
  149356. vf->ready_state=STREAMSET;
  149357. return 0;
  149358. }
  149359. /* clear out the OggVorbis_File struct */
  149360. int ov_clear(OggVorbis_File *vf){
  149361. if(vf){
  149362. vorbis_block_clear(&vf->vb);
  149363. vorbis_dsp_clear(&vf->vd);
  149364. ogg_stream_clear(&vf->os);
  149365. if(vf->vi && vf->links){
  149366. int i;
  149367. for(i=0;i<vf->links;i++){
  149368. vorbis_info_clear(vf->vi+i);
  149369. vorbis_comment_clear(vf->vc+i);
  149370. }
  149371. _ogg_free(vf->vi);
  149372. _ogg_free(vf->vc);
  149373. }
  149374. if(vf->dataoffsets)_ogg_free(vf->dataoffsets);
  149375. if(vf->pcmlengths)_ogg_free(vf->pcmlengths);
  149376. if(vf->serialnos)_ogg_free(vf->serialnos);
  149377. if(vf->offsets)_ogg_free(vf->offsets);
  149378. ogg_sync_clear(&vf->oy);
  149379. if(vf->datasource)(vf->callbacks.close_func)(vf->datasource);
  149380. memset(vf,0,sizeof(*vf));
  149381. }
  149382. #ifdef DEBUG_LEAKS
  149383. _VDBG_dump();
  149384. #endif
  149385. return(0);
  149386. }
  149387. /* inspects the OggVorbis file and finds/documents all the logical
  149388. bitstreams contained in it. Tries to be tolerant of logical
  149389. bitstream sections that are truncated/woogie.
  149390. return: -1) error
  149391. 0) OK
  149392. */
  149393. int ov_open_callbacks(void *f,OggVorbis_File *vf,char *initial,long ibytes,
  149394. ov_callbacks callbacks){
  149395. int ret=_ov_open1(f,vf,initial,ibytes,callbacks);
  149396. if(ret)return ret;
  149397. return _ov_open2(vf);
  149398. }
  149399. int ov_open(FILE *f,OggVorbis_File *vf,char *initial,long ibytes){
  149400. ov_callbacks callbacks = {
  149401. (size_t (*)(void *, size_t, size_t, void *)) fread,
  149402. (int (*)(void *, ogg_int64_t, int)) _fseek64_wrap,
  149403. (int (*)(void *)) fclose,
  149404. (long (*)(void *)) ftell
  149405. };
  149406. return ov_open_callbacks((void *)f, vf, initial, ibytes, callbacks);
  149407. }
  149408. /* cheap hack for game usage where downsampling is desirable; there's
  149409. no need for SRC as we can just do it cheaply in libvorbis. */
  149410. int ov_halfrate(OggVorbis_File *vf,int flag){
  149411. int i;
  149412. if(vf->vi==NULL)return OV_EINVAL;
  149413. if(!vf->seekable)return OV_EINVAL;
  149414. if(vf->ready_state>=STREAMSET)
  149415. _decode_clear(vf); /* clear out stream state; later on libvorbis
  149416. will be able to swap this on the fly, but
  149417. for now dumping the decode machine is needed
  149418. to reinit the MDCT lookups. 1.1 libvorbis
  149419. is planned to be able to switch on the fly */
  149420. for(i=0;i<vf->links;i++){
  149421. if(vorbis_synthesis_halfrate(vf->vi+i,flag)){
  149422. ov_halfrate(vf,0);
  149423. return OV_EINVAL;
  149424. }
  149425. }
  149426. return 0;
  149427. }
  149428. int ov_halfrate_p(OggVorbis_File *vf){
  149429. if(vf->vi==NULL)return OV_EINVAL;
  149430. return vorbis_synthesis_halfrate_p(vf->vi);
  149431. }
  149432. /* Only partially open the vorbis file; test for Vorbisness, and load
  149433. the headers for the first chain. Do not seek (although test for
  149434. seekability). Use ov_test_open to finish opening the file, else
  149435. ov_clear to close/free it. Same return codes as open. */
  149436. int ov_test_callbacks(void *f,OggVorbis_File *vf,char *initial,long ibytes,
  149437. ov_callbacks callbacks)
  149438. {
  149439. return _ov_open1(f,vf,initial,ibytes,callbacks);
  149440. }
  149441. int ov_test(FILE *f,OggVorbis_File *vf,char *initial,long ibytes){
  149442. ov_callbacks callbacks = {
  149443. (size_t (*)(void *, size_t, size_t, void *)) fread,
  149444. (int (*)(void *, ogg_int64_t, int)) _fseek64_wrap,
  149445. (int (*)(void *)) fclose,
  149446. (long (*)(void *)) ftell
  149447. };
  149448. return ov_test_callbacks((void *)f, vf, initial, ibytes, callbacks);
  149449. }
  149450. int ov_test_open(OggVorbis_File *vf){
  149451. if(vf->ready_state!=PARTOPEN)return(OV_EINVAL);
  149452. return _ov_open2(vf);
  149453. }
  149454. /* How many logical bitstreams in this physical bitstream? */
  149455. long ov_streams(OggVorbis_File *vf){
  149456. return vf->links;
  149457. }
  149458. /* Is the FILE * associated with vf seekable? */
  149459. long ov_seekable(OggVorbis_File *vf){
  149460. return vf->seekable;
  149461. }
  149462. /* returns the bitrate for a given logical bitstream or the entire
  149463. physical bitstream. If the file is open for random access, it will
  149464. find the *actual* average bitrate. If the file is streaming, it
  149465. returns the nominal bitrate (if set) else the average of the
  149466. upper/lower bounds (if set) else -1 (unset).
  149467. If you want the actual bitrate field settings, get them from the
  149468. vorbis_info structs */
  149469. long ov_bitrate(OggVorbis_File *vf,int i){
  149470. if(vf->ready_state<OPENED)return(OV_EINVAL);
  149471. if(i>=vf->links)return(OV_EINVAL);
  149472. if(!vf->seekable && i!=0)return(ov_bitrate(vf,0));
  149473. if(i<0){
  149474. ogg_int64_t bits=0;
  149475. int i;
  149476. float br;
  149477. for(i=0;i<vf->links;i++)
  149478. bits+=(vf->offsets[i+1]-vf->dataoffsets[i])*8;
  149479. /* This once read: return(rint(bits/ov_time_total(vf,-1)));
  149480. * gcc 3.x on x86 miscompiled this at optimisation level 2 and above,
  149481. * so this is slightly transformed to make it work.
  149482. */
  149483. br = bits/ov_time_total(vf,-1);
  149484. return(rint(br));
  149485. }else{
  149486. if(vf->seekable){
  149487. /* return the actual bitrate */
  149488. return(rint((vf->offsets[i+1]-vf->dataoffsets[i])*8/ov_time_total(vf,i)));
  149489. }else{
  149490. /* return nominal if set */
  149491. if(vf->vi[i].bitrate_nominal>0){
  149492. return vf->vi[i].bitrate_nominal;
  149493. }else{
  149494. if(vf->vi[i].bitrate_upper>0){
  149495. if(vf->vi[i].bitrate_lower>0){
  149496. return (vf->vi[i].bitrate_upper+vf->vi[i].bitrate_lower)/2;
  149497. }else{
  149498. return vf->vi[i].bitrate_upper;
  149499. }
  149500. }
  149501. return(OV_FALSE);
  149502. }
  149503. }
  149504. }
  149505. }
  149506. /* returns the actual bitrate since last call. returns -1 if no
  149507. additional data to offer since last call (or at beginning of stream),
  149508. EINVAL if stream is only partially open
  149509. */
  149510. long ov_bitrate_instant(OggVorbis_File *vf){
  149511. int link=(vf->seekable?vf->current_link:0);
  149512. long ret;
  149513. if(vf->ready_state<OPENED)return(OV_EINVAL);
  149514. if(vf->samptrack==0)return(OV_FALSE);
  149515. ret=vf->bittrack/vf->samptrack*vf->vi[link].rate+.5;
  149516. vf->bittrack=0.f;
  149517. vf->samptrack=0.f;
  149518. return(ret);
  149519. }
  149520. /* Guess */
  149521. long ov_serialnumber(OggVorbis_File *vf,int i){
  149522. if(i>=vf->links)return(ov_serialnumber(vf,vf->links-1));
  149523. if(!vf->seekable && i>=0)return(ov_serialnumber(vf,-1));
  149524. if(i<0){
  149525. return(vf->current_serialno);
  149526. }else{
  149527. return(vf->serialnos[i]);
  149528. }
  149529. }
  149530. /* returns: total raw (compressed) length of content if i==-1
  149531. raw (compressed) length of that logical bitstream for i==0 to n
  149532. OV_EINVAL if the stream is not seekable (we can't know the length)
  149533. or if stream is only partially open
  149534. */
  149535. ogg_int64_t ov_raw_total(OggVorbis_File *vf,int i){
  149536. if(vf->ready_state<OPENED)return(OV_EINVAL);
  149537. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  149538. if(i<0){
  149539. ogg_int64_t acc=0;
  149540. int i;
  149541. for(i=0;i<vf->links;i++)
  149542. acc+=ov_raw_total(vf,i);
  149543. return(acc);
  149544. }else{
  149545. return(vf->offsets[i+1]-vf->offsets[i]);
  149546. }
  149547. }
  149548. /* returns: total PCM length (samples) of content if i==-1 PCM length
  149549. (samples) of that logical bitstream for i==0 to n
  149550. OV_EINVAL if the stream is not seekable (we can't know the
  149551. length) or only partially open
  149552. */
  149553. ogg_int64_t ov_pcm_total(OggVorbis_File *vf,int i){
  149554. if(vf->ready_state<OPENED)return(OV_EINVAL);
  149555. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  149556. if(i<0){
  149557. ogg_int64_t acc=0;
  149558. int i;
  149559. for(i=0;i<vf->links;i++)
  149560. acc+=ov_pcm_total(vf,i);
  149561. return(acc);
  149562. }else{
  149563. return(vf->pcmlengths[i*2+1]);
  149564. }
  149565. }
  149566. /* returns: total seconds of content if i==-1
  149567. seconds in that logical bitstream for i==0 to n
  149568. OV_EINVAL if the stream is not seekable (we can't know the
  149569. length) or only partially open
  149570. */
  149571. double ov_time_total(OggVorbis_File *vf,int i){
  149572. if(vf->ready_state<OPENED)return(OV_EINVAL);
  149573. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  149574. if(i<0){
  149575. double acc=0;
  149576. int i;
  149577. for(i=0;i<vf->links;i++)
  149578. acc+=ov_time_total(vf,i);
  149579. return(acc);
  149580. }else{
  149581. return((double)(vf->pcmlengths[i*2+1])/vf->vi[i].rate);
  149582. }
  149583. }
  149584. /* seek to an offset relative to the *compressed* data. This also
  149585. scans packets to update the PCM cursor. It will cross a logical
  149586. bitstream boundary, but only if it can't get any packets out of the
  149587. tail of the bitstream we seek to (so no surprises).
  149588. returns zero on success, nonzero on failure */
  149589. int ov_raw_seek(OggVorbis_File *vf,ogg_int64_t pos){
  149590. ogg_stream_state work_os;
  149591. if(vf->ready_state<OPENED)return(OV_EINVAL);
  149592. if(!vf->seekable)
  149593. return(OV_ENOSEEK); /* don't dump machine if we can't seek */
  149594. if(pos<0 || pos>vf->end)return(OV_EINVAL);
  149595. /* don't yet clear out decoding machine (if it's initialized), in
  149596. the case we're in the same link. Restart the decode lapping, and
  149597. let _fetch_and_process_packet deal with a potential bitstream
  149598. boundary */
  149599. vf->pcm_offset=-1;
  149600. ogg_stream_reset_serialno(&vf->os,
  149601. vf->current_serialno); /* must set serialno */
  149602. vorbis_synthesis_restart(&vf->vd);
  149603. _seek_helper(vf,pos);
  149604. /* we need to make sure the pcm_offset is set, but we don't want to
  149605. advance the raw cursor past good packets just to get to the first
  149606. with a granulepos. That's not equivalent behavior to beginning
  149607. decoding as immediately after the seek position as possible.
  149608. So, a hack. We use two stream states; a local scratch state and
  149609. the shared vf->os stream state. We use the local state to
  149610. scan, and the shared state as a buffer for later decode.
  149611. Unfortuantely, on the last page we still advance to last packet
  149612. because the granulepos on the last page is not necessarily on a
  149613. packet boundary, and we need to make sure the granpos is
  149614. correct.
  149615. */
  149616. {
  149617. ogg_page og;
  149618. ogg_packet op;
  149619. int lastblock=0;
  149620. int accblock=0;
  149621. int thisblock;
  149622. int eosflag;
  149623. ogg_stream_init(&work_os,vf->current_serialno); /* get the memory ready */
  149624. ogg_stream_reset(&work_os); /* eliminate the spurious OV_HOLE
  149625. return from not necessarily
  149626. starting from the beginning */
  149627. while(1){
  149628. if(vf->ready_state>=STREAMSET){
  149629. /* snarf/scan a packet if we can */
  149630. int result=ogg_stream_packetout(&work_os,&op);
  149631. if(result>0){
  149632. if(vf->vi[vf->current_link].codec_setup){
  149633. thisblock=vorbis_packet_blocksize(vf->vi+vf->current_link,&op);
  149634. if(thisblock<0){
  149635. ogg_stream_packetout(&vf->os,NULL);
  149636. thisblock=0;
  149637. }else{
  149638. if(eosflag)
  149639. ogg_stream_packetout(&vf->os,NULL);
  149640. else
  149641. if(lastblock)accblock+=(lastblock+thisblock)>>2;
  149642. }
  149643. if(op.granulepos!=-1){
  149644. int i,link=vf->current_link;
  149645. ogg_int64_t granulepos=op.granulepos-vf->pcmlengths[link*2];
  149646. if(granulepos<0)granulepos=0;
  149647. for(i=0;i<link;i++)
  149648. granulepos+=vf->pcmlengths[i*2+1];
  149649. vf->pcm_offset=granulepos-accblock;
  149650. break;
  149651. }
  149652. lastblock=thisblock;
  149653. continue;
  149654. }else
  149655. ogg_stream_packetout(&vf->os,NULL);
  149656. }
  149657. }
  149658. if(!lastblock){
  149659. if(_get_next_page(vf,&og,-1)<0){
  149660. vf->pcm_offset=ov_pcm_total(vf,-1);
  149661. break;
  149662. }
  149663. }else{
  149664. /* huh? Bogus stream with packets but no granulepos */
  149665. vf->pcm_offset=-1;
  149666. break;
  149667. }
  149668. /* has our decoding just traversed a bitstream boundary? */
  149669. if(vf->ready_state>=STREAMSET)
  149670. if(vf->current_serialno!=ogg_page_serialno(&og)){
  149671. _decode_clear(vf); /* clear out stream state */
  149672. ogg_stream_clear(&work_os);
  149673. }
  149674. if(vf->ready_state<STREAMSET){
  149675. int link;
  149676. vf->current_serialno=ogg_page_serialno(&og);
  149677. for(link=0;link<vf->links;link++)
  149678. if(vf->serialnos[link]==vf->current_serialno)break;
  149679. if(link==vf->links)goto seek_error; /* sign of a bogus stream.
  149680. error out, leave
  149681. machine uninitialized */
  149682. vf->current_link=link;
  149683. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  149684. ogg_stream_reset_serialno(&work_os,vf->current_serialno);
  149685. vf->ready_state=STREAMSET;
  149686. }
  149687. ogg_stream_pagein(&vf->os,&og);
  149688. ogg_stream_pagein(&work_os,&og);
  149689. eosflag=ogg_page_eos(&og);
  149690. }
  149691. }
  149692. ogg_stream_clear(&work_os);
  149693. vf->bittrack=0.f;
  149694. vf->samptrack=0.f;
  149695. return(0);
  149696. seek_error:
  149697. /* dump the machine so we're in a known state */
  149698. vf->pcm_offset=-1;
  149699. ogg_stream_clear(&work_os);
  149700. _decode_clear(vf);
  149701. return OV_EBADLINK;
  149702. }
  149703. /* Page granularity seek (faster than sample granularity because we
  149704. don't do the last bit of decode to find a specific sample).
  149705. Seek to the last [granule marked] page preceeding the specified pos
  149706. location, such that decoding past the returned point will quickly
  149707. arrive at the requested position. */
  149708. int ov_pcm_seek_page(OggVorbis_File *vf,ogg_int64_t pos){
  149709. int link=-1;
  149710. ogg_int64_t result=0;
  149711. ogg_int64_t total=ov_pcm_total(vf,-1);
  149712. if(vf->ready_state<OPENED)return(OV_EINVAL);
  149713. if(!vf->seekable)return(OV_ENOSEEK);
  149714. if(pos<0 || pos>total)return(OV_EINVAL);
  149715. /* which bitstream section does this pcm offset occur in? */
  149716. for(link=vf->links-1;link>=0;link--){
  149717. total-=vf->pcmlengths[link*2+1];
  149718. if(pos>=total)break;
  149719. }
  149720. /* search within the logical bitstream for the page with the highest
  149721. pcm_pos preceeding (or equal to) pos. There is a danger here;
  149722. missing pages or incorrect frame number information in the
  149723. bitstream could make our task impossible. Account for that (it
  149724. would be an error condition) */
  149725. /* new search algorithm by HB (Nicholas Vinen) */
  149726. {
  149727. ogg_int64_t end=vf->offsets[link+1];
  149728. ogg_int64_t begin=vf->offsets[link];
  149729. ogg_int64_t begintime = vf->pcmlengths[link*2];
  149730. ogg_int64_t endtime = vf->pcmlengths[link*2+1]+begintime;
  149731. ogg_int64_t target=pos-total+begintime;
  149732. ogg_int64_t best=begin;
  149733. ogg_page og;
  149734. while(begin<end){
  149735. ogg_int64_t bisect;
  149736. if(end-begin<CHUNKSIZE){
  149737. bisect=begin;
  149738. }else{
  149739. /* take a (pretty decent) guess. */
  149740. bisect=begin +
  149741. (target-begintime)*(end-begin)/(endtime-begintime) - CHUNKSIZE;
  149742. if(bisect<=begin)
  149743. bisect=begin+1;
  149744. }
  149745. _seek_helper(vf,bisect);
  149746. while(begin<end){
  149747. result=_get_next_page(vf,&og,end-vf->offset);
  149748. if(result==OV_EREAD) goto seek_error;
  149749. if(result<0){
  149750. if(bisect<=begin+1)
  149751. end=begin; /* found it */
  149752. else{
  149753. if(bisect==0) goto seek_error;
  149754. bisect-=CHUNKSIZE;
  149755. if(bisect<=begin)bisect=begin+1;
  149756. _seek_helper(vf,bisect);
  149757. }
  149758. }else{
  149759. ogg_int64_t granulepos=ogg_page_granulepos(&og);
  149760. if(granulepos==-1)continue;
  149761. if(granulepos<target){
  149762. best=result; /* raw offset of packet with granulepos */
  149763. begin=vf->offset; /* raw offset of next page */
  149764. begintime=granulepos;
  149765. if(target-begintime>44100)break;
  149766. bisect=begin; /* *not* begin + 1 */
  149767. }else{
  149768. if(bisect<=begin+1)
  149769. end=begin; /* found it */
  149770. else{
  149771. if(end==vf->offset){ /* we're pretty close - we'd be stuck in */
  149772. end=result;
  149773. bisect-=CHUNKSIZE; /* an endless loop otherwise. */
  149774. if(bisect<=begin)bisect=begin+1;
  149775. _seek_helper(vf,bisect);
  149776. }else{
  149777. end=result;
  149778. endtime=granulepos;
  149779. break;
  149780. }
  149781. }
  149782. }
  149783. }
  149784. }
  149785. }
  149786. /* found our page. seek to it, update pcm offset. Easier case than
  149787. raw_seek, don't keep packets preceeding granulepos. */
  149788. {
  149789. ogg_page og;
  149790. ogg_packet op;
  149791. /* seek */
  149792. _seek_helper(vf,best);
  149793. vf->pcm_offset=-1;
  149794. if(_get_next_page(vf,&og,-1)<0)return(OV_EOF); /* shouldn't happen */
  149795. if(link!=vf->current_link){
  149796. /* Different link; dump entire decode machine */
  149797. _decode_clear(vf);
  149798. vf->current_link=link;
  149799. vf->current_serialno=ogg_page_serialno(&og);
  149800. vf->ready_state=STREAMSET;
  149801. }else{
  149802. vorbis_synthesis_restart(&vf->vd);
  149803. }
  149804. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  149805. ogg_stream_pagein(&vf->os,&og);
  149806. /* pull out all but last packet; the one with granulepos */
  149807. while(1){
  149808. result=ogg_stream_packetpeek(&vf->os,&op);
  149809. if(result==0){
  149810. /* !!! the packet finishing this page originated on a
  149811. preceeding page. Keep fetching previous pages until we
  149812. get one with a granulepos or without the 'continued' flag
  149813. set. Then just use raw_seek for simplicity. */
  149814. _seek_helper(vf,best);
  149815. while(1){
  149816. result=_get_prev_page(vf,&og);
  149817. if(result<0) goto seek_error;
  149818. if(ogg_page_granulepos(&og)>-1 ||
  149819. !ogg_page_continued(&og)){
  149820. return ov_raw_seek(vf,result);
  149821. }
  149822. vf->offset=result;
  149823. }
  149824. }
  149825. if(result<0){
  149826. result = OV_EBADPACKET;
  149827. goto seek_error;
  149828. }
  149829. if(op.granulepos!=-1){
  149830. vf->pcm_offset=op.granulepos-vf->pcmlengths[vf->current_link*2];
  149831. if(vf->pcm_offset<0)vf->pcm_offset=0;
  149832. vf->pcm_offset+=total;
  149833. break;
  149834. }else
  149835. result=ogg_stream_packetout(&vf->os,NULL);
  149836. }
  149837. }
  149838. }
  149839. /* verify result */
  149840. if(vf->pcm_offset>pos || pos>ov_pcm_total(vf,-1)){
  149841. result=OV_EFAULT;
  149842. goto seek_error;
  149843. }
  149844. vf->bittrack=0.f;
  149845. vf->samptrack=0.f;
  149846. return(0);
  149847. seek_error:
  149848. /* dump machine so we're in a known state */
  149849. vf->pcm_offset=-1;
  149850. _decode_clear(vf);
  149851. return (int)result;
  149852. }
  149853. /* seek to a sample offset relative to the decompressed pcm stream
  149854. returns zero on success, nonzero on failure */
  149855. int ov_pcm_seek(OggVorbis_File *vf,ogg_int64_t pos){
  149856. int thisblock,lastblock=0;
  149857. int ret=ov_pcm_seek_page(vf,pos);
  149858. if(ret<0)return(ret);
  149859. if((ret=_make_decode_ready(vf)))return ret;
  149860. /* discard leading packets we don't need for the lapping of the
  149861. position we want; don't decode them */
  149862. while(1){
  149863. ogg_packet op;
  149864. ogg_page og;
  149865. int ret=ogg_stream_packetpeek(&vf->os,&op);
  149866. if(ret>0){
  149867. thisblock=vorbis_packet_blocksize(vf->vi+vf->current_link,&op);
  149868. if(thisblock<0){
  149869. ogg_stream_packetout(&vf->os,NULL);
  149870. continue; /* non audio packet */
  149871. }
  149872. if(lastblock)vf->pcm_offset+=(lastblock+thisblock)>>2;
  149873. if(vf->pcm_offset+((thisblock+
  149874. vorbis_info_blocksize(vf->vi,1))>>2)>=pos)break;
  149875. /* remove the packet from packet queue and track its granulepos */
  149876. ogg_stream_packetout(&vf->os,NULL);
  149877. vorbis_synthesis_trackonly(&vf->vb,&op); /* set up a vb with
  149878. only tracking, no
  149879. pcm_decode */
  149880. vorbis_synthesis_blockin(&vf->vd,&vf->vb);
  149881. /* end of logical stream case is hard, especially with exact
  149882. length positioning. */
  149883. if(op.granulepos>-1){
  149884. int i;
  149885. /* always believe the stream markers */
  149886. vf->pcm_offset=op.granulepos-vf->pcmlengths[vf->current_link*2];
  149887. if(vf->pcm_offset<0)vf->pcm_offset=0;
  149888. for(i=0;i<vf->current_link;i++)
  149889. vf->pcm_offset+=vf->pcmlengths[i*2+1];
  149890. }
  149891. lastblock=thisblock;
  149892. }else{
  149893. if(ret<0 && ret!=OV_HOLE)break;
  149894. /* suck in a new page */
  149895. if(_get_next_page(vf,&og,-1)<0)break;
  149896. if(vf->current_serialno!=ogg_page_serialno(&og))_decode_clear(vf);
  149897. if(vf->ready_state<STREAMSET){
  149898. int link;
  149899. vf->current_serialno=ogg_page_serialno(&og);
  149900. for(link=0;link<vf->links;link++)
  149901. if(vf->serialnos[link]==vf->current_serialno)break;
  149902. if(link==vf->links)return(OV_EBADLINK);
  149903. vf->current_link=link;
  149904. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  149905. vf->ready_state=STREAMSET;
  149906. ret=_make_decode_ready(vf);
  149907. if(ret)return ret;
  149908. lastblock=0;
  149909. }
  149910. ogg_stream_pagein(&vf->os,&og);
  149911. }
  149912. }
  149913. vf->bittrack=0.f;
  149914. vf->samptrack=0.f;
  149915. /* discard samples until we reach the desired position. Crossing a
  149916. logical bitstream boundary with abandon is OK. */
  149917. while(vf->pcm_offset<pos){
  149918. ogg_int64_t target=pos-vf->pcm_offset;
  149919. long samples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  149920. if(samples>target)samples=target;
  149921. vorbis_synthesis_read(&vf->vd,samples);
  149922. vf->pcm_offset+=samples;
  149923. if(samples<target)
  149924. if(_fetch_and_process_packet(vf,NULL,1,1)<=0)
  149925. vf->pcm_offset=ov_pcm_total(vf,-1); /* eof */
  149926. }
  149927. return 0;
  149928. }
  149929. /* seek to a playback time relative to the decompressed pcm stream
  149930. returns zero on success, nonzero on failure */
  149931. int ov_time_seek(OggVorbis_File *vf,double seconds){
  149932. /* translate time to PCM position and call ov_pcm_seek */
  149933. int link=-1;
  149934. ogg_int64_t pcm_total=ov_pcm_total(vf,-1);
  149935. double time_total=ov_time_total(vf,-1);
  149936. if(vf->ready_state<OPENED)return(OV_EINVAL);
  149937. if(!vf->seekable)return(OV_ENOSEEK);
  149938. if(seconds<0 || seconds>time_total)return(OV_EINVAL);
  149939. /* which bitstream section does this time offset occur in? */
  149940. for(link=vf->links-1;link>=0;link--){
  149941. pcm_total-=vf->pcmlengths[link*2+1];
  149942. time_total-=ov_time_total(vf,link);
  149943. if(seconds>=time_total)break;
  149944. }
  149945. /* enough information to convert time offset to pcm offset */
  149946. {
  149947. ogg_int64_t target=pcm_total+(seconds-time_total)*vf->vi[link].rate;
  149948. return(ov_pcm_seek(vf,target));
  149949. }
  149950. }
  149951. /* page-granularity version of ov_time_seek
  149952. returns zero on success, nonzero on failure */
  149953. int ov_time_seek_page(OggVorbis_File *vf,double seconds){
  149954. /* translate time to PCM position and call ov_pcm_seek */
  149955. int link=-1;
  149956. ogg_int64_t pcm_total=ov_pcm_total(vf,-1);
  149957. double time_total=ov_time_total(vf,-1);
  149958. if(vf->ready_state<OPENED)return(OV_EINVAL);
  149959. if(!vf->seekable)return(OV_ENOSEEK);
  149960. if(seconds<0 || seconds>time_total)return(OV_EINVAL);
  149961. /* which bitstream section does this time offset occur in? */
  149962. for(link=vf->links-1;link>=0;link--){
  149963. pcm_total-=vf->pcmlengths[link*2+1];
  149964. time_total-=ov_time_total(vf,link);
  149965. if(seconds>=time_total)break;
  149966. }
  149967. /* enough information to convert time offset to pcm offset */
  149968. {
  149969. ogg_int64_t target=pcm_total+(seconds-time_total)*vf->vi[link].rate;
  149970. return(ov_pcm_seek_page(vf,target));
  149971. }
  149972. }
  149973. /* tell the current stream offset cursor. Note that seek followed by
  149974. tell will likely not give the set offset due to caching */
  149975. ogg_int64_t ov_raw_tell(OggVorbis_File *vf){
  149976. if(vf->ready_state<OPENED)return(OV_EINVAL);
  149977. return(vf->offset);
  149978. }
  149979. /* return PCM offset (sample) of next PCM sample to be read */
  149980. ogg_int64_t ov_pcm_tell(OggVorbis_File *vf){
  149981. if(vf->ready_state<OPENED)return(OV_EINVAL);
  149982. return(vf->pcm_offset);
  149983. }
  149984. /* return time offset (seconds) of next PCM sample to be read */
  149985. double ov_time_tell(OggVorbis_File *vf){
  149986. int link=0;
  149987. ogg_int64_t pcm_total=0;
  149988. double time_total=0.f;
  149989. if(vf->ready_state<OPENED)return(OV_EINVAL);
  149990. if(vf->seekable){
  149991. pcm_total=ov_pcm_total(vf,-1);
  149992. time_total=ov_time_total(vf,-1);
  149993. /* which bitstream section does this time offset occur in? */
  149994. for(link=vf->links-1;link>=0;link--){
  149995. pcm_total-=vf->pcmlengths[link*2+1];
  149996. time_total-=ov_time_total(vf,link);
  149997. if(vf->pcm_offset>=pcm_total)break;
  149998. }
  149999. }
  150000. return((double)time_total+(double)(vf->pcm_offset-pcm_total)/vf->vi[link].rate);
  150001. }
  150002. /* link: -1) return the vorbis_info struct for the bitstream section
  150003. currently being decoded
  150004. 0-n) to request information for a specific bitstream section
  150005. In the case of a non-seekable bitstream, any call returns the
  150006. current bitstream. NULL in the case that the machine is not
  150007. initialized */
  150008. vorbis_info *ov_info(OggVorbis_File *vf,int link){
  150009. if(vf->seekable){
  150010. if(link<0)
  150011. if(vf->ready_state>=STREAMSET)
  150012. return vf->vi+vf->current_link;
  150013. else
  150014. return vf->vi;
  150015. else
  150016. if(link>=vf->links)
  150017. return NULL;
  150018. else
  150019. return vf->vi+link;
  150020. }else{
  150021. return vf->vi;
  150022. }
  150023. }
  150024. /* grr, strong typing, grr, no templates/inheritence, grr */
  150025. vorbis_comment *ov_comment(OggVorbis_File *vf,int link){
  150026. if(vf->seekable){
  150027. if(link<0)
  150028. if(vf->ready_state>=STREAMSET)
  150029. return vf->vc+vf->current_link;
  150030. else
  150031. return vf->vc;
  150032. else
  150033. if(link>=vf->links)
  150034. return NULL;
  150035. else
  150036. return vf->vc+link;
  150037. }else{
  150038. return vf->vc;
  150039. }
  150040. }
  150041. static int host_is_big_endian() {
  150042. ogg_int32_t pattern = 0xfeedface; /* deadbeef */
  150043. unsigned char *bytewise = (unsigned char *)&pattern;
  150044. if (bytewise[0] == 0xfe) return 1;
  150045. return 0;
  150046. }
  150047. /* up to this point, everything could more or less hide the multiple
  150048. logical bitstream nature of chaining from the toplevel application
  150049. if the toplevel application didn't particularly care. However, at
  150050. the point that we actually read audio back, the multiple-section
  150051. nature must surface: Multiple bitstream sections do not necessarily
  150052. have to have the same number of channels or sampling rate.
  150053. ov_read returns the sequential logical bitstream number currently
  150054. being decoded along with the PCM data in order that the toplevel
  150055. application can take action on channel/sample rate changes. This
  150056. number will be incremented even for streamed (non-seekable) streams
  150057. (for seekable streams, it represents the actual logical bitstream
  150058. index within the physical bitstream. Note that the accessor
  150059. functions above are aware of this dichotomy).
  150060. input values: buffer) a buffer to hold packed PCM data for return
  150061. length) the byte length requested to be placed into buffer
  150062. bigendianp) should the data be packed LSB first (0) or
  150063. MSB first (1)
  150064. word) word size for output. currently 1 (byte) or
  150065. 2 (16 bit short)
  150066. return values: <0) error/hole in data (OV_HOLE), partial open (OV_EINVAL)
  150067. 0) EOF
  150068. n) number of bytes of PCM actually returned. The
  150069. below works on a packet-by-packet basis, so the
  150070. return length is not related to the 'length' passed
  150071. in, just guaranteed to fit.
  150072. *section) set to the logical bitstream number */
  150073. long ov_read(OggVorbis_File *vf,char *buffer,int length,
  150074. int bigendianp,int word,int sgned,int *bitstream){
  150075. int i,j;
  150076. int host_endian = host_is_big_endian();
  150077. float **pcm;
  150078. long samples;
  150079. if(vf->ready_state<OPENED)return(OV_EINVAL);
  150080. while(1){
  150081. if(vf->ready_state==INITSET){
  150082. samples=vorbis_synthesis_pcmout(&vf->vd,&pcm);
  150083. if(samples)break;
  150084. }
  150085. /* suck in another packet */
  150086. {
  150087. int ret=_fetch_and_process_packet(vf,NULL,1,1);
  150088. if(ret==OV_EOF)
  150089. return(0);
  150090. if(ret<=0)
  150091. return(ret);
  150092. }
  150093. }
  150094. if(samples>0){
  150095. /* yay! proceed to pack data into the byte buffer */
  150096. long channels=ov_info(vf,-1)->channels;
  150097. long bytespersample=word * channels;
  150098. vorbis_fpu_control fpu;
  150099. (void) fpu; // (to avoid a warning about it being unused)
  150100. if(samples>length/bytespersample)samples=length/bytespersample;
  150101. if(samples <= 0)
  150102. return OV_EINVAL;
  150103. /* a tight loop to pack each size */
  150104. {
  150105. int val;
  150106. if(word==1){
  150107. int off=(sgned?0:128);
  150108. vorbis_fpu_setround(&fpu);
  150109. for(j=0;j<samples;j++)
  150110. for(i=0;i<channels;i++){
  150111. val=vorbis_ftoi(pcm[i][j]*128.f);
  150112. if(val>127)val=127;
  150113. else if(val<-128)val=-128;
  150114. *buffer++=val+off;
  150115. }
  150116. vorbis_fpu_restore(fpu);
  150117. }else{
  150118. int off=(sgned?0:32768);
  150119. if(host_endian==bigendianp){
  150120. if(sgned){
  150121. vorbis_fpu_setround(&fpu);
  150122. for(i=0;i<channels;i++) { /* It's faster in this order */
  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;
  150130. dest+=channels;
  150131. }
  150132. }
  150133. vorbis_fpu_restore(fpu);
  150134. }else{
  150135. vorbis_fpu_setround(&fpu);
  150136. for(i=0;i<channels;i++) {
  150137. float *src=pcm[i];
  150138. short *dest=((short *)buffer)+i;
  150139. for(j=0;j<samples;j++) {
  150140. val=vorbis_ftoi(src[j]*32768.f);
  150141. if(val>32767)val=32767;
  150142. else if(val<-32768)val=-32768;
  150143. *dest=val+off;
  150144. dest+=channels;
  150145. }
  150146. }
  150147. vorbis_fpu_restore(fpu);
  150148. }
  150149. }else if(bigendianp){
  150150. vorbis_fpu_setround(&fpu);
  150151. for(j=0;j<samples;j++)
  150152. for(i=0;i<channels;i++){
  150153. val=vorbis_ftoi(pcm[i][j]*32768.f);
  150154. if(val>32767)val=32767;
  150155. else if(val<-32768)val=-32768;
  150156. val+=off;
  150157. *buffer++=(val>>8);
  150158. *buffer++=(val&0xff);
  150159. }
  150160. vorbis_fpu_restore(fpu);
  150161. }else{
  150162. int val;
  150163. vorbis_fpu_setround(&fpu);
  150164. for(j=0;j<samples;j++)
  150165. for(i=0;i<channels;i++){
  150166. val=vorbis_ftoi(pcm[i][j]*32768.f);
  150167. if(val>32767)val=32767;
  150168. else if(val<-32768)val=-32768;
  150169. val+=off;
  150170. *buffer++=(val&0xff);
  150171. *buffer++=(val>>8);
  150172. }
  150173. vorbis_fpu_restore(fpu);
  150174. }
  150175. }
  150176. }
  150177. vorbis_synthesis_read(&vf->vd,samples);
  150178. vf->pcm_offset+=samples;
  150179. if(bitstream)*bitstream=vf->current_link;
  150180. return(samples*bytespersample);
  150181. }else{
  150182. return(samples);
  150183. }
  150184. }
  150185. /* input values: pcm_channels) a float vector per channel of output
  150186. length) the sample length being read by the app
  150187. return values: <0) error/hole in data (OV_HOLE), partial open (OV_EINVAL)
  150188. 0) EOF
  150189. n) number of samples of PCM actually returned. The
  150190. below works on a packet-by-packet basis, so the
  150191. return length is not related to the 'length' passed
  150192. in, just guaranteed to fit.
  150193. *section) set to the logical bitstream number */
  150194. long ov_read_float(OggVorbis_File *vf,float ***pcm_channels,int length,
  150195. int *bitstream){
  150196. if(vf->ready_state<OPENED)return(OV_EINVAL);
  150197. while(1){
  150198. if(vf->ready_state==INITSET){
  150199. float **pcm;
  150200. long samples=vorbis_synthesis_pcmout(&vf->vd,&pcm);
  150201. if(samples){
  150202. if(pcm_channels)*pcm_channels=pcm;
  150203. if(samples>length)samples=length;
  150204. vorbis_synthesis_read(&vf->vd,samples);
  150205. vf->pcm_offset+=samples;
  150206. if(bitstream)*bitstream=vf->current_link;
  150207. return samples;
  150208. }
  150209. }
  150210. /* suck in another packet */
  150211. {
  150212. int ret=_fetch_and_process_packet(vf,NULL,1,1);
  150213. if(ret==OV_EOF)return(0);
  150214. if(ret<=0)return(ret);
  150215. }
  150216. }
  150217. }
  150218. extern float *vorbis_window(vorbis_dsp_state *v,int W);
  150219. extern void _analysis_output_always(char *base,int i,float *v,int n,int bark,int dB,
  150220. ogg_int64_t off);
  150221. static void _ov_splice(float **pcm,float **lappcm,
  150222. int n1, int n2,
  150223. int ch1, int ch2,
  150224. float *w1, float *w2){
  150225. int i,j;
  150226. float *w=w1;
  150227. int n=n1;
  150228. if(n1>n2){
  150229. n=n2;
  150230. w=w2;
  150231. }
  150232. /* splice */
  150233. for(j=0;j<ch1 && j<ch2;j++){
  150234. float *s=lappcm[j];
  150235. float *d=pcm[j];
  150236. for(i=0;i<n;i++){
  150237. float wd=w[i]*w[i];
  150238. float ws=1.-wd;
  150239. d[i]=d[i]*wd + s[i]*ws;
  150240. }
  150241. }
  150242. /* window from zero */
  150243. for(;j<ch2;j++){
  150244. float *d=pcm[j];
  150245. for(i=0;i<n;i++){
  150246. float wd=w[i]*w[i];
  150247. d[i]=d[i]*wd;
  150248. }
  150249. }
  150250. }
  150251. /* make sure vf is INITSET */
  150252. static int _ov_initset(OggVorbis_File *vf){
  150253. while(1){
  150254. if(vf->ready_state==INITSET)break;
  150255. /* suck in another packet */
  150256. {
  150257. int ret=_fetch_and_process_packet(vf,NULL,1,0);
  150258. if(ret<0 && ret!=OV_HOLE)return(ret);
  150259. }
  150260. }
  150261. return 0;
  150262. }
  150263. /* make sure vf is INITSET and that we have a primed buffer; if
  150264. we're crosslapping at a stream section boundary, this also makes
  150265. sure we're sanity checking against the right stream information */
  150266. static int _ov_initprime(OggVorbis_File *vf){
  150267. vorbis_dsp_state *vd=&vf->vd;
  150268. while(1){
  150269. if(vf->ready_state==INITSET)
  150270. if(vorbis_synthesis_pcmout(vd,NULL))break;
  150271. /* suck in another packet */
  150272. {
  150273. int ret=_fetch_and_process_packet(vf,NULL,1,0);
  150274. if(ret<0 && ret!=OV_HOLE)return(ret);
  150275. }
  150276. }
  150277. return 0;
  150278. }
  150279. /* grab enough data for lapping from vf; this may be in the form of
  150280. unreturned, already-decoded pcm, remaining PCM we will need to
  150281. decode, or synthetic postextrapolation from last packets. */
  150282. static void _ov_getlap(OggVorbis_File *vf,vorbis_info *vi,vorbis_dsp_state *vd,
  150283. float **lappcm,int lapsize){
  150284. int lapcount=0,i;
  150285. float **pcm;
  150286. /* try first to decode the lapping data */
  150287. while(lapcount<lapsize){
  150288. int samples=vorbis_synthesis_pcmout(vd,&pcm);
  150289. if(samples){
  150290. if(samples>lapsize-lapcount)samples=lapsize-lapcount;
  150291. for(i=0;i<vi->channels;i++)
  150292. memcpy(lappcm[i]+lapcount,pcm[i],sizeof(**pcm)*samples);
  150293. lapcount+=samples;
  150294. vorbis_synthesis_read(vd,samples);
  150295. }else{
  150296. /* suck in another packet */
  150297. int ret=_fetch_and_process_packet(vf,NULL,1,0); /* do *not* span */
  150298. if(ret==OV_EOF)break;
  150299. }
  150300. }
  150301. if(lapcount<lapsize){
  150302. /* failed to get lapping data from normal decode; pry it from the
  150303. postextrapolation buffering, or the second half of the MDCT
  150304. from the last packet */
  150305. int samples=vorbis_synthesis_lapout(&vf->vd,&pcm);
  150306. if(samples==0){
  150307. for(i=0;i<vi->channels;i++)
  150308. memset(lappcm[i]+lapcount,0,sizeof(**pcm)*lapsize-lapcount);
  150309. lapcount=lapsize;
  150310. }else{
  150311. if(samples>lapsize-lapcount)samples=lapsize-lapcount;
  150312. for(i=0;i<vi->channels;i++)
  150313. memcpy(lappcm[i]+lapcount,pcm[i],sizeof(**pcm)*samples);
  150314. lapcount+=samples;
  150315. }
  150316. }
  150317. }
  150318. /* this sets up crosslapping of a sample by using trailing data from
  150319. sample 1 and lapping it into the windowing buffer of sample 2 */
  150320. int ov_crosslap(OggVorbis_File *vf1, OggVorbis_File *vf2){
  150321. vorbis_info *vi1,*vi2;
  150322. float **lappcm;
  150323. float **pcm;
  150324. float *w1,*w2;
  150325. int n1,n2,i,ret,hs1,hs2;
  150326. if(vf1==vf2)return(0); /* degenerate case */
  150327. if(vf1->ready_state<OPENED)return(OV_EINVAL);
  150328. if(vf2->ready_state<OPENED)return(OV_EINVAL);
  150329. /* the relevant overlap buffers must be pre-checked and pre-primed
  150330. before looking at settings in the event that priming would cross
  150331. a bitstream boundary. So, do it now */
  150332. ret=_ov_initset(vf1);
  150333. if(ret)return(ret);
  150334. ret=_ov_initprime(vf2);
  150335. if(ret)return(ret);
  150336. vi1=ov_info(vf1,-1);
  150337. vi2=ov_info(vf2,-1);
  150338. hs1=ov_halfrate_p(vf1);
  150339. hs2=ov_halfrate_p(vf2);
  150340. lappcm=(float**) alloca(sizeof(*lappcm)*vi1->channels);
  150341. n1=vorbis_info_blocksize(vi1,0)>>(1+hs1);
  150342. n2=vorbis_info_blocksize(vi2,0)>>(1+hs2);
  150343. w1=vorbis_window(&vf1->vd,0);
  150344. w2=vorbis_window(&vf2->vd,0);
  150345. for(i=0;i<vi1->channels;i++)
  150346. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  150347. _ov_getlap(vf1,vi1,&vf1->vd,lappcm,n1);
  150348. /* have a lapping buffer from vf1; now to splice it into the lapping
  150349. buffer of vf2 */
  150350. /* consolidate and expose the buffer. */
  150351. vorbis_synthesis_lapout(&vf2->vd,&pcm);
  150352. _analysis_output_always("pcmL",0,pcm[0],n1*2,0,0,0);
  150353. _analysis_output_always("pcmR",0,pcm[1],n1*2,0,0,0);
  150354. /* splice */
  150355. _ov_splice(pcm,lappcm,n1,n2,vi1->channels,vi2->channels,w1,w2);
  150356. /* done */
  150357. return(0);
  150358. }
  150359. static int _ov_64_seek_lap(OggVorbis_File *vf,ogg_int64_t pos,
  150360. int (*localseek)(OggVorbis_File *,ogg_int64_t)){
  150361. vorbis_info *vi;
  150362. float **lappcm;
  150363. float **pcm;
  150364. float *w1,*w2;
  150365. int n1,n2,ch1,ch2,hs;
  150366. int i,ret;
  150367. if(vf->ready_state<OPENED)return(OV_EINVAL);
  150368. ret=_ov_initset(vf);
  150369. if(ret)return(ret);
  150370. vi=ov_info(vf,-1);
  150371. hs=ov_halfrate_p(vf);
  150372. ch1=vi->channels;
  150373. n1=vorbis_info_blocksize(vi,0)>>(1+hs);
  150374. w1=vorbis_window(&vf->vd,0); /* window arrays from libvorbis are
  150375. persistent; even if the decode state
  150376. from this link gets dumped, this
  150377. window array continues to exist */
  150378. lappcm=(float**) alloca(sizeof(*lappcm)*ch1);
  150379. for(i=0;i<ch1;i++)
  150380. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  150381. _ov_getlap(vf,vi,&vf->vd,lappcm,n1);
  150382. /* have lapping data; seek and prime the buffer */
  150383. ret=localseek(vf,pos);
  150384. if(ret)return ret;
  150385. ret=_ov_initprime(vf);
  150386. if(ret)return(ret);
  150387. /* Guard against cross-link changes; they're perfectly legal */
  150388. vi=ov_info(vf,-1);
  150389. ch2=vi->channels;
  150390. n2=vorbis_info_blocksize(vi,0)>>(1+hs);
  150391. w2=vorbis_window(&vf->vd,0);
  150392. /* consolidate and expose the buffer. */
  150393. vorbis_synthesis_lapout(&vf->vd,&pcm);
  150394. /* splice */
  150395. _ov_splice(pcm,lappcm,n1,n2,ch1,ch2,w1,w2);
  150396. /* done */
  150397. return(0);
  150398. }
  150399. int ov_raw_seek_lap(OggVorbis_File *vf,ogg_int64_t pos){
  150400. return _ov_64_seek_lap(vf,pos,ov_raw_seek);
  150401. }
  150402. int ov_pcm_seek_lap(OggVorbis_File *vf,ogg_int64_t pos){
  150403. return _ov_64_seek_lap(vf,pos,ov_pcm_seek);
  150404. }
  150405. int ov_pcm_seek_page_lap(OggVorbis_File *vf,ogg_int64_t pos){
  150406. return _ov_64_seek_lap(vf,pos,ov_pcm_seek_page);
  150407. }
  150408. static int _ov_d_seek_lap(OggVorbis_File *vf,double pos,
  150409. int (*localseek)(OggVorbis_File *,double)){
  150410. vorbis_info *vi;
  150411. float **lappcm;
  150412. float **pcm;
  150413. float *w1,*w2;
  150414. int n1,n2,ch1,ch2,hs;
  150415. int i,ret;
  150416. if(vf->ready_state<OPENED)return(OV_EINVAL);
  150417. ret=_ov_initset(vf);
  150418. if(ret)return(ret);
  150419. vi=ov_info(vf,-1);
  150420. hs=ov_halfrate_p(vf);
  150421. ch1=vi->channels;
  150422. n1=vorbis_info_blocksize(vi,0)>>(1+hs);
  150423. w1=vorbis_window(&vf->vd,0); /* window arrays from libvorbis are
  150424. persistent; even if the decode state
  150425. from this link gets dumped, this
  150426. window array continues to exist */
  150427. lappcm=(float**) alloca(sizeof(*lappcm)*ch1);
  150428. for(i=0;i<ch1;i++)
  150429. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  150430. _ov_getlap(vf,vi,&vf->vd,lappcm,n1);
  150431. /* have lapping data; seek and prime the buffer */
  150432. ret=localseek(vf,pos);
  150433. if(ret)return ret;
  150434. ret=_ov_initprime(vf);
  150435. if(ret)return(ret);
  150436. /* Guard against cross-link changes; they're perfectly legal */
  150437. vi=ov_info(vf,-1);
  150438. ch2=vi->channels;
  150439. n2=vorbis_info_blocksize(vi,0)>>(1+hs);
  150440. w2=vorbis_window(&vf->vd,0);
  150441. /* consolidate and expose the buffer. */
  150442. vorbis_synthesis_lapout(&vf->vd,&pcm);
  150443. /* splice */
  150444. _ov_splice(pcm,lappcm,n1,n2,ch1,ch2,w1,w2);
  150445. /* done */
  150446. return(0);
  150447. }
  150448. int ov_time_seek_lap(OggVorbis_File *vf,double pos){
  150449. return _ov_d_seek_lap(vf,pos,ov_time_seek);
  150450. }
  150451. int ov_time_seek_page_lap(OggVorbis_File *vf,double pos){
  150452. return _ov_d_seek_lap(vf,pos,ov_time_seek_page);
  150453. }
  150454. #endif
  150455. /********* End of inlined file: vorbisfile.c *********/
  150456. /********* Start of inlined file: window.c *********/
  150457. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  150458. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  150459. // tasks..
  150460. #ifdef _MSC_VER
  150461. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  150462. #endif
  150463. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  150464. #if JUCE_USE_OGGVORBIS
  150465. #include <stdlib.h>
  150466. #include <math.h>
  150467. static float vwin64[32] = {
  150468. 0.0009460463F, 0.0085006468F, 0.0235352254F, 0.0458950567F,
  150469. 0.0753351908F, 0.1115073077F, 0.1539457973F, 0.2020557475F,
  150470. 0.2551056759F, 0.3122276645F, 0.3724270287F, 0.4346027792F,
  150471. 0.4975789974F, 0.5601459521F, 0.6211085051F, 0.6793382689F,
  150472. 0.7338252629F, 0.7837245849F, 0.8283939355F, 0.8674186656F,
  150473. 0.9006222429F, 0.9280614787F, 0.9500073081F, 0.9669131782F,
  150474. 0.9793740220F, 0.9880792941F, 0.9937636139F, 0.9971582668F,
  150475. 0.9989462667F, 0.9997230082F, 0.9999638688F, 0.9999995525F,
  150476. };
  150477. static float vwin128[64] = {
  150478. 0.0002365472F, 0.0021280687F, 0.0059065254F, 0.0115626550F,
  150479. 0.0190823442F, 0.0284463735F, 0.0396300935F, 0.0526030430F,
  150480. 0.0673285281F, 0.0837631763F, 0.1018564887F, 0.1215504095F,
  150481. 0.1427789367F, 0.1654677960F, 0.1895342001F, 0.2148867160F,
  150482. 0.2414252576F, 0.2690412240F, 0.2976177952F, 0.3270303960F,
  150483. 0.3571473350F, 0.3878306189F, 0.4189369387F, 0.4503188188F,
  150484. 0.4818259135F, 0.5133064334F, 0.5446086751F, 0.5755826278F,
  150485. 0.6060816248F, 0.6359640047F, 0.6650947483F, 0.6933470543F,
  150486. 0.7206038179F, 0.7467589810F, 0.7717187213F, 0.7954024542F,
  150487. 0.8177436264F, 0.8386902831F, 0.8582053981F, 0.8762669622F,
  150488. 0.8928678298F, 0.9080153310F, 0.9217306608F, 0.9340480615F,
  150489. 0.9450138200F, 0.9546851041F, 0.9631286621F, 0.9704194171F,
  150490. 0.9766389810F, 0.9818741197F, 0.9862151938F, 0.9897546035F,
  150491. 0.9925852598F, 0.9947991032F, 0.9964856900F, 0.9977308602F,
  150492. 0.9986155015F, 0.9992144193F, 0.9995953200F, 0.9998179155F,
  150493. 0.9999331503F, 0.9999825563F, 0.9999977357F, 0.9999999720F,
  150494. };
  150495. static float vwin256[128] = {
  150496. 0.0000591390F, 0.0005321979F, 0.0014780301F, 0.0028960636F,
  150497. 0.0047854363F, 0.0071449926F, 0.0099732775F, 0.0132685298F,
  150498. 0.0170286741F, 0.0212513119F, 0.0259337111F, 0.0310727950F,
  150499. 0.0366651302F, 0.0427069140F, 0.0491939614F, 0.0561216907F,
  150500. 0.0634851102F, 0.0712788035F, 0.0794969160F, 0.0881331402F,
  150501. 0.0971807028F, 0.1066323515F, 0.1164803426F, 0.1267164297F,
  150502. 0.1373318534F, 0.1483173323F, 0.1596630553F, 0.1713586755F,
  150503. 0.1833933062F, 0.1957555184F, 0.2084333404F, 0.2214142599F,
  150504. 0.2346852280F, 0.2482326664F, 0.2620424757F, 0.2761000481F,
  150505. 0.2903902813F, 0.3048975959F, 0.3196059553F, 0.3344988887F,
  150506. 0.3495595160F, 0.3647705766F, 0.3801144597F, 0.3955732382F,
  150507. 0.4111287047F, 0.4267624093F, 0.4424557009F, 0.4581897696F,
  150508. 0.4739456913F, 0.4897044744F, 0.5054471075F, 0.5211546088F,
  150509. 0.5368080763F, 0.5523887395F, 0.5678780103F, 0.5832575361F,
  150510. 0.5985092508F, 0.6136154277F, 0.6285587300F, 0.6433222619F,
  150511. 0.6578896175F, 0.6722449294F, 0.6863729144F, 0.7002589187F,
  150512. 0.7138889597F, 0.7272497662F, 0.7403288154F, 0.7531143679F,
  150513. 0.7655954985F, 0.7777621249F, 0.7896050322F, 0.8011158947F,
  150514. 0.8122872932F, 0.8231127294F, 0.8335866365F, 0.8437043850F,
  150515. 0.8534622861F, 0.8628575905F, 0.8718884835F, 0.8805540765F,
  150516. 0.8888543947F, 0.8967903616F, 0.9043637797F, 0.9115773078F,
  150517. 0.9184344360F, 0.9249394562F, 0.9310974312F, 0.9369141608F,
  150518. 0.9423961446F, 0.9475505439F, 0.9523851406F, 0.9569082947F,
  150519. 0.9611289005F, 0.9650563408F, 0.9687004405F, 0.9720714191F,
  150520. 0.9751798427F, 0.9780365753F, 0.9806527301F, 0.9830396204F,
  150521. 0.9852087111F, 0.9871715701F, 0.9889398207F, 0.9905250941F,
  150522. 0.9919389832F, 0.9931929973F, 0.9942985174F, 0.9952667537F,
  150523. 0.9961087037F, 0.9968351119F, 0.9974564312F, 0.9979827858F,
  150524. 0.9984239359F, 0.9987892441F, 0.9990876435F, 0.9993276081F,
  150525. 0.9995171241F, 0.9996636648F, 0.9997741654F, 0.9998550016F,
  150526. 0.9999119692F, 0.9999502656F, 0.9999744742F, 0.9999885497F,
  150527. 0.9999958064F, 0.9999989077F, 0.9999998584F, 0.9999999983F,
  150528. };
  150529. static float vwin512[256] = {
  150530. 0.0000147849F, 0.0001330607F, 0.0003695946F, 0.0007243509F,
  150531. 0.0011972759F, 0.0017882983F, 0.0024973285F, 0.0033242588F,
  150532. 0.0042689632F, 0.0053312973F, 0.0065110982F, 0.0078081841F,
  150533. 0.0092223540F, 0.0107533880F, 0.0124010466F, 0.0141650703F,
  150534. 0.0160451800F, 0.0180410758F, 0.0201524373F, 0.0223789233F,
  150535. 0.0247201710F, 0.0271757958F, 0.0297453914F, 0.0324285286F,
  150536. 0.0352247556F, 0.0381335972F, 0.0411545545F, 0.0442871045F,
  150537. 0.0475306997F, 0.0508847676F, 0.0543487103F, 0.0579219038F,
  150538. 0.0616036982F, 0.0653934164F, 0.0692903546F, 0.0732937809F,
  150539. 0.0774029356F, 0.0816170305F, 0.0859352485F, 0.0903567428F,
  150540. 0.0948806375F, 0.0995060259F, 0.1042319712F, 0.1090575056F,
  150541. 0.1139816300F, 0.1190033137F, 0.1241214941F, 0.1293350764F,
  150542. 0.1346429333F, 0.1400439046F, 0.1455367974F, 0.1511203852F,
  150543. 0.1567934083F, 0.1625545735F, 0.1684025537F, 0.1743359881F,
  150544. 0.1803534820F, 0.1864536069F, 0.1926349000F, 0.1988958650F,
  150545. 0.2052349715F, 0.2116506555F, 0.2181413191F, 0.2247053313F,
  150546. 0.2313410275F, 0.2380467105F, 0.2448206500F, 0.2516610835F,
  150547. 0.2585662164F, 0.2655342226F, 0.2725632448F, 0.2796513950F,
  150548. 0.2867967551F, 0.2939973773F, 0.3012512852F, 0.3085564739F,
  150549. 0.3159109111F, 0.3233125375F, 0.3307592680F, 0.3382489922F,
  150550. 0.3457795756F, 0.3533488602F, 0.3609546657F, 0.3685947904F,
  150551. 0.3762670121F, 0.3839690896F, 0.3916987634F, 0.3994537572F,
  150552. 0.4072317788F, 0.4150305215F, 0.4228476653F, 0.4306808783F,
  150553. 0.4385278181F, 0.4463861329F, 0.4542534630F, 0.4621274424F,
  150554. 0.4700057001F, 0.4778858615F, 0.4857655502F, 0.4936423891F,
  150555. 0.5015140023F, 0.5093780165F, 0.5172320626F, 0.5250737772F,
  150556. 0.5329008043F, 0.5407107971F, 0.5485014192F, 0.5562703465F,
  150557. 0.5640152688F, 0.5717338914F, 0.5794239366F, 0.5870831457F,
  150558. 0.5947092801F, 0.6023001235F, 0.6098534829F, 0.6173671907F,
  150559. 0.6248391059F, 0.6322671161F, 0.6396491384F, 0.6469831217F,
  150560. 0.6542670475F, 0.6614989319F, 0.6686768267F, 0.6757988210F,
  150561. 0.6828630426F, 0.6898676592F, 0.6968108799F, 0.7036909564F,
  150562. 0.7105061843F, 0.7172549043F, 0.7239355032F, 0.7305464154F,
  150563. 0.7370861235F, 0.7435531598F, 0.7499461068F, 0.7562635986F,
  150564. 0.7625043214F, 0.7686670148F, 0.7747504721F, 0.7807535410F,
  150565. 0.7866751247F, 0.7925141825F, 0.7982697296F, 0.8039408387F,
  150566. 0.8095266395F, 0.8150263196F, 0.8204391248F, 0.8257643590F,
  150567. 0.8310013848F, 0.8361496236F, 0.8412085555F, 0.8461777194F,
  150568. 0.8510567129F, 0.8558451924F, 0.8605428730F, 0.8651495278F,
  150569. 0.8696649882F, 0.8740891432F, 0.8784219392F, 0.8826633797F,
  150570. 0.8868135244F, 0.8908724888F, 0.8948404441F, 0.8987176157F,
  150571. 0.9025042831F, 0.9062007791F, 0.9098074886F, 0.9133248482F,
  150572. 0.9167533451F, 0.9200935163F, 0.9233459472F, 0.9265112712F,
  150573. 0.9295901680F, 0.9325833632F, 0.9354916263F, 0.9383157705F,
  150574. 0.9410566504F, 0.9437151618F, 0.9462922398F, 0.9487888576F,
  150575. 0.9512060252F, 0.9535447882F, 0.9558062262F, 0.9579914516F,
  150576. 0.9601016078F, 0.9621378683F, 0.9641014348F, 0.9659935361F,
  150577. 0.9678154261F, 0.9695683830F, 0.9712537071F, 0.9728727198F,
  150578. 0.9744267618F, 0.9759171916F, 0.9773453842F, 0.9787127293F,
  150579. 0.9800206298F, 0.9812705006F, 0.9824637665F, 0.9836018613F,
  150580. 0.9846862258F, 0.9857183066F, 0.9866995544F, 0.9876314227F,
  150581. 0.9885153662F, 0.9893528393F, 0.9901452948F, 0.9908941823F,
  150582. 0.9916009470F, 0.9922670279F, 0.9928938570F, 0.9934828574F,
  150583. 0.9940354423F, 0.9945530133F, 0.9950369595F, 0.9954886562F,
  150584. 0.9959094633F, 0.9963007242F, 0.9966637649F, 0.9969998925F,
  150585. 0.9973103939F, 0.9975965351F, 0.9978595598F, 0.9981006885F,
  150586. 0.9983211172F, 0.9985220166F, 0.9987045311F, 0.9988697776F,
  150587. 0.9990188449F, 0.9991527924F, 0.9992726499F, 0.9993794157F,
  150588. 0.9994740570F, 0.9995575079F, 0.9996306699F, 0.9996944099F,
  150589. 0.9997495605F, 0.9997969190F, 0.9998372465F, 0.9998712678F,
  150590. 0.9998996704F, 0.9999231041F, 0.9999421807F, 0.9999574732F,
  150591. 0.9999695157F, 0.9999788026F, 0.9999857885F, 0.9999908879F,
  150592. 0.9999944746F, 0.9999968817F, 0.9999984010F, 0.9999992833F,
  150593. 0.9999997377F, 0.9999999317F, 0.9999999911F, 0.9999999999F,
  150594. };
  150595. static float vwin1024[512] = {
  150596. 0.0000036962F, 0.0000332659F, 0.0000924041F, 0.0001811086F,
  150597. 0.0002993761F, 0.0004472021F, 0.0006245811F, 0.0008315063F,
  150598. 0.0010679699F, 0.0013339631F, 0.0016294757F, 0.0019544965F,
  150599. 0.0023090133F, 0.0026930125F, 0.0031064797F, 0.0035493989F,
  150600. 0.0040217533F, 0.0045235250F, 0.0050546946F, 0.0056152418F,
  150601. 0.0062051451F, 0.0068243817F, 0.0074729278F, 0.0081507582F,
  150602. 0.0088578466F, 0.0095941655F, 0.0103596863F, 0.0111543789F,
  150603. 0.0119782122F, 0.0128311538F, 0.0137131701F, 0.0146242260F,
  150604. 0.0155642855F, 0.0165333111F, 0.0175312640F, 0.0185581042F,
  150605. 0.0196137903F, 0.0206982797F, 0.0218115284F, 0.0229534910F,
  150606. 0.0241241208F, 0.0253233698F, 0.0265511886F, 0.0278075263F,
  150607. 0.0290923308F, 0.0304055484F, 0.0317471241F, 0.0331170013F,
  150608. 0.0345151222F, 0.0359414274F, 0.0373958560F, 0.0388783456F,
  150609. 0.0403888325F, 0.0419272511F, 0.0434935347F, 0.0450876148F,
  150610. 0.0467094213F, 0.0483588828F, 0.0500359261F, 0.0517404765F,
  150611. 0.0534724575F, 0.0552317913F, 0.0570183983F, 0.0588321971F,
  150612. 0.0606731048F, 0.0625410369F, 0.0644359070F, 0.0663576272F,
  150613. 0.0683061077F, 0.0702812571F, 0.0722829821F, 0.0743111878F,
  150614. 0.0763657775F, 0.0784466526F, 0.0805537129F, 0.0826868561F,
  150615. 0.0848459782F, 0.0870309736F, 0.0892417345F, 0.0914781514F,
  150616. 0.0937401128F, 0.0960275056F, 0.0983402145F, 0.1006781223F,
  150617. 0.1030411101F, 0.1054290568F, 0.1078418397F, 0.1102793336F,
  150618. 0.1127414119F, 0.1152279457F, 0.1177388042F, 0.1202738544F,
  150619. 0.1228329618F, 0.1254159892F, 0.1280227980F, 0.1306532471F,
  150620. 0.1333071937F, 0.1359844927F, 0.1386849970F, 0.1414085575F,
  150621. 0.1441550230F, 0.1469242403F, 0.1497160539F, 0.1525303063F,
  150622. 0.1553668381F, 0.1582254875F, 0.1611060909F, 0.1640084822F,
  150623. 0.1669324936F, 0.1698779549F, 0.1728446939F, 0.1758325362F,
  150624. 0.1788413055F, 0.1818708232F, 0.1849209084F, 0.1879913785F,
  150625. 0.1910820485F, 0.1941927312F, 0.1973232376F, 0.2004733764F,
  150626. 0.2036429541F, 0.2068317752F, 0.2100396421F, 0.2132663552F,
  150627. 0.2165117125F, 0.2197755102F, 0.2230575422F, 0.2263576007F,
  150628. 0.2296754753F, 0.2330109540F, 0.2363638225F, 0.2397338646F,
  150629. 0.2431208619F, 0.2465245941F, 0.2499448389F, 0.2533813719F,
  150630. 0.2568339669F, 0.2603023956F, 0.2637864277F, 0.2672858312F,
  150631. 0.2708003718F, 0.2743298135F, 0.2778739186F, 0.2814324472F,
  150632. 0.2850051576F, 0.2885918065F, 0.2921921485F, 0.2958059366F,
  150633. 0.2994329219F, 0.3030728538F, 0.3067254799F, 0.3103905462F,
  150634. 0.3140677969F, 0.3177569747F, 0.3214578205F, 0.3251700736F,
  150635. 0.3288934718F, 0.3326277513F, 0.3363726468F, 0.3401278914F,
  150636. 0.3438932168F, 0.3476683533F, 0.3514530297F, 0.3552469734F,
  150637. 0.3590499106F, 0.3628615659F, 0.3666816630F, 0.3705099239F,
  150638. 0.3743460698F, 0.3781898204F, 0.3820408945F, 0.3858990095F,
  150639. 0.3897638820F, 0.3936352274F, 0.3975127601F, 0.4013961936F,
  150640. 0.4052852405F, 0.4091796123F, 0.4130790198F, 0.4169831732F,
  150641. 0.4208917815F, 0.4248045534F, 0.4287211965F, 0.4326414181F,
  150642. 0.4365649248F, 0.4404914225F, 0.4444206167F, 0.4483522125F,
  150643. 0.4522859146F, 0.4562214270F, 0.4601584538F, 0.4640966984F,
  150644. 0.4680358644F, 0.4719756548F, 0.4759157726F, 0.4798559209F,
  150645. 0.4837958024F, 0.4877351199F, 0.4916735765F, 0.4956108751F,
  150646. 0.4995467188F, 0.5034808109F, 0.5074128550F, 0.5113425550F,
  150647. 0.5152696149F, 0.5191937395F, 0.5231146336F, 0.5270320028F,
  150648. 0.5309455530F, 0.5348549910F, 0.5387600239F, 0.5426603597F,
  150649. 0.5465557070F, 0.5504457754F, 0.5543302752F, 0.5582089175F,
  150650. 0.5620814145F, 0.5659474793F, 0.5698068262F, 0.5736591704F,
  150651. 0.5775042283F, 0.5813417176F, 0.5851713571F, 0.5889928670F,
  150652. 0.5928059689F, 0.5966103856F, 0.6004058415F, 0.6041920626F,
  150653. 0.6079687761F, 0.6117357113F, 0.6154925986F, 0.6192391705F,
  150654. 0.6229751612F, 0.6267003064F, 0.6304143441F, 0.6341170137F,
  150655. 0.6378080569F, 0.6414872173F, 0.6451542405F, 0.6488088741F,
  150656. 0.6524508681F, 0.6560799742F, 0.6596959469F, 0.6632985424F,
  150657. 0.6668875197F, 0.6704626398F, 0.6740236662F, 0.6775703649F,
  150658. 0.6811025043F, 0.6846198554F, 0.6881221916F, 0.6916092892F,
  150659. 0.6950809269F, 0.6985368861F, 0.7019769510F, 0.7054009085F,
  150660. 0.7088085484F, 0.7121996632F, 0.7155740484F, 0.7189315023F,
  150661. 0.7222718263F, 0.7255948245F, 0.7289003043F, 0.7321880760F,
  150662. 0.7354579530F, 0.7387097518F, 0.7419432921F, 0.7451583966F,
  150663. 0.7483548915F, 0.7515326059F, 0.7546913723F, 0.7578310265F,
  150664. 0.7609514077F, 0.7640523581F, 0.7671337237F, 0.7701953535F,
  150665. 0.7732371001F, 0.7762588195F, 0.7792603711F, 0.7822416178F,
  150666. 0.7852024259F, 0.7881426654F, 0.7910622097F, 0.7939609356F,
  150667. 0.7968387237F, 0.7996954579F, 0.8025310261F, 0.8053453193F,
  150668. 0.8081382324F, 0.8109096638F, 0.8136595156F, 0.8163876936F,
  150669. 0.8190941071F, 0.8217786690F, 0.8244412960F, 0.8270819086F,
  150670. 0.8297004305F, 0.8322967896F, 0.8348709171F, 0.8374227481F,
  150671. 0.8399522213F, 0.8424592789F, 0.8449438672F, 0.8474059356F,
  150672. 0.8498454378F, 0.8522623306F, 0.8546565748F, 0.8570281348F,
  150673. 0.8593769787F, 0.8617030779F, 0.8640064080F, 0.8662869477F,
  150674. 0.8685446796F, 0.8707795899F, 0.8729916682F, 0.8751809079F,
  150675. 0.8773473059F, 0.8794908626F, 0.8816115819F, 0.8837094713F,
  150676. 0.8857845418F, 0.8878368079F, 0.8898662874F, 0.8918730019F,
  150677. 0.8938569760F, 0.8958182380F, 0.8977568194F, 0.8996727552F,
  150678. 0.9015660837F, 0.9034368465F, 0.9052850885F, 0.9071108577F,
  150679. 0.9089142057F, 0.9106951869F, 0.9124538591F, 0.9141902832F,
  150680. 0.9159045233F, 0.9175966464F, 0.9192667228F, 0.9209148257F,
  150681. 0.9225410313F, 0.9241454187F, 0.9257280701F, 0.9272890704F,
  150682. 0.9288285075F, 0.9303464720F, 0.9318430576F, 0.9333183603F,
  150683. 0.9347724792F, 0.9362055158F, 0.9376175745F, 0.9390087622F,
  150684. 0.9403791881F, 0.9417289644F, 0.9430582055F, 0.9443670283F,
  150685. 0.9456555521F, 0.9469238986F, 0.9481721917F, 0.9494005577F,
  150686. 0.9506091252F, 0.9517980248F, 0.9529673894F, 0.9541173540F,
  150687. 0.9552480557F, 0.9563596334F, 0.9574522282F, 0.9585259830F,
  150688. 0.9595810428F, 0.9606175542F, 0.9616356656F, 0.9626355274F,
  150689. 0.9636172915F, 0.9645811114F, 0.9655271425F, 0.9664555414F,
  150690. 0.9673664664F, 0.9682600774F, 0.9691365355F, 0.9699960034F,
  150691. 0.9708386448F, 0.9716646250F, 0.9724741103F, 0.9732672685F,
  150692. 0.9740442683F, 0.9748052795F, 0.9755504729F, 0.9762800205F,
  150693. 0.9769940950F, 0.9776928703F, 0.9783765210F, 0.9790452223F,
  150694. 0.9796991504F, 0.9803384823F, 0.9809633954F, 0.9815740679F,
  150695. 0.9821706784F, 0.9827534063F, 0.9833224312F, 0.9838779332F,
  150696. 0.9844200928F, 0.9849490910F, 0.9854651087F, 0.9859683274F,
  150697. 0.9864589286F, 0.9869370940F, 0.9874030054F, 0.9878568447F,
  150698. 0.9882987937F, 0.9887290343F, 0.9891477481F, 0.9895551169F,
  150699. 0.9899513220F, 0.9903365446F, 0.9907109658F, 0.9910747662F,
  150700. 0.9914281260F, 0.9917712252F, 0.9921042433F, 0.9924273593F,
  150701. 0.9927407516F, 0.9930445982F, 0.9933390763F, 0.9936243626F,
  150702. 0.9939006331F, 0.9941680631F, 0.9944268269F, 0.9946770982F,
  150703. 0.9949190498F, 0.9951528537F, 0.9953786808F, 0.9955967011F,
  150704. 0.9958070836F, 0.9960099963F, 0.9962056061F, 0.9963940787F,
  150705. 0.9965755786F, 0.9967502693F, 0.9969183129F, 0.9970798704F,
  150706. 0.9972351013F, 0.9973841640F, 0.9975272151F, 0.9976644103F,
  150707. 0.9977959036F, 0.9979218476F, 0.9980423932F, 0.9981576901F,
  150708. 0.9982678862F, 0.9983731278F, 0.9984735596F, 0.9985693247F,
  150709. 0.9986605645F, 0.9987474186F, 0.9988300248F, 0.9989085193F,
  150710. 0.9989830364F, 0.9990537085F, 0.9991206662F, 0.9991840382F,
  150711. 0.9992439513F, 0.9993005303F, 0.9993538982F, 0.9994041757F,
  150712. 0.9994514817F, 0.9994959330F, 0.9995376444F, 0.9995767286F,
  150713. 0.9996132960F, 0.9996474550F, 0.9996793121F, 0.9997089710F,
  150714. 0.9997365339F, 0.9997621003F, 0.9997857677F, 0.9998076311F,
  150715. 0.9998277836F, 0.9998463156F, 0.9998633155F, 0.9998788692F,
  150716. 0.9998930603F, 0.9999059701F, 0.9999176774F, 0.9999282586F,
  150717. 0.9999377880F, 0.9999463370F, 0.9999539749F, 0.9999607685F,
  150718. 0.9999667820F, 0.9999720773F, 0.9999767136F, 0.9999807479F,
  150719. 0.9999842344F, 0.9999872249F, 0.9999897688F, 0.9999919127F,
  150720. 0.9999937009F, 0.9999951749F, 0.9999963738F, 0.9999973342F,
  150721. 0.9999980900F, 0.9999986724F, 0.9999991103F, 0.9999994297F,
  150722. 0.9999996543F, 0.9999998049F, 0.9999999000F, 0.9999999552F,
  150723. 0.9999999836F, 0.9999999957F, 0.9999999994F, 1.0000000000F,
  150724. };
  150725. static float vwin2048[1024] = {
  150726. 0.0000009241F, 0.0000083165F, 0.0000231014F, 0.0000452785F,
  150727. 0.0000748476F, 0.0001118085F, 0.0001561608F, 0.0002079041F,
  150728. 0.0002670379F, 0.0003335617F, 0.0004074748F, 0.0004887765F,
  150729. 0.0005774661F, 0.0006735427F, 0.0007770054F, 0.0008878533F,
  150730. 0.0010060853F, 0.0011317002F, 0.0012646969F, 0.0014050742F,
  150731. 0.0015528307F, 0.0017079650F, 0.0018704756F, 0.0020403610F,
  150732. 0.0022176196F, 0.0024022497F, 0.0025942495F, 0.0027936173F,
  150733. 0.0030003511F, 0.0032144490F, 0.0034359088F, 0.0036647286F,
  150734. 0.0039009061F, 0.0041444391F, 0.0043953253F, 0.0046535621F,
  150735. 0.0049191472F, 0.0051920781F, 0.0054723520F, 0.0057599664F,
  150736. 0.0060549184F, 0.0063572052F, 0.0066668239F, 0.0069837715F,
  150737. 0.0073080449F, 0.0076396410F, 0.0079785566F, 0.0083247884F,
  150738. 0.0086783330F, 0.0090391871F, 0.0094073470F, 0.0097828092F,
  150739. 0.0101655700F, 0.0105556258F, 0.0109529726F, 0.0113576065F,
  150740. 0.0117695237F, 0.0121887200F, 0.0126151913F, 0.0130489335F,
  150741. 0.0134899422F, 0.0139382130F, 0.0143937415F, 0.0148565233F,
  150742. 0.0153265536F, 0.0158038279F, 0.0162883413F, 0.0167800889F,
  150743. 0.0172790660F, 0.0177852675F, 0.0182986882F, 0.0188193231F,
  150744. 0.0193471668F, 0.0198822141F, 0.0204244594F, 0.0209738974F,
  150745. 0.0215305225F, 0.0220943289F, 0.0226653109F, 0.0232434627F,
  150746. 0.0238287784F, 0.0244212519F, 0.0250208772F, 0.0256276481F,
  150747. 0.0262415582F, 0.0268626014F, 0.0274907711F, 0.0281260608F,
  150748. 0.0287684638F, 0.0294179736F, 0.0300745833F, 0.0307382859F,
  150749. 0.0314090747F, 0.0320869424F, 0.0327718819F, 0.0334638860F,
  150750. 0.0341629474F, 0.0348690586F, 0.0355822122F, 0.0363024004F,
  150751. 0.0370296157F, 0.0377638502F, 0.0385050960F, 0.0392533451F,
  150752. 0.0400085896F, 0.0407708211F, 0.0415400315F, 0.0423162123F,
  150753. 0.0430993552F, 0.0438894515F, 0.0446864926F, 0.0454904698F,
  150754. 0.0463013742F, 0.0471191969F, 0.0479439288F, 0.0487755607F,
  150755. 0.0496140836F, 0.0504594879F, 0.0513117642F, 0.0521709031F,
  150756. 0.0530368949F, 0.0539097297F, 0.0547893979F, 0.0556758894F,
  150757. 0.0565691941F, 0.0574693019F, 0.0583762026F, 0.0592898858F,
  150758. 0.0602103410F, 0.0611375576F, 0.0620715250F, 0.0630122324F,
  150759. 0.0639596688F, 0.0649138234F, 0.0658746848F, 0.0668422421F,
  150760. 0.0678164838F, 0.0687973985F, 0.0697849746F, 0.0707792005F,
  150761. 0.0717800645F, 0.0727875547F, 0.0738016591F, 0.0748223656F,
  150762. 0.0758496620F, 0.0768835359F, 0.0779239751F, 0.0789709668F,
  150763. 0.0800244985F, 0.0810845574F, 0.0821511306F, 0.0832242052F,
  150764. 0.0843037679F, 0.0853898056F, 0.0864823050F, 0.0875812525F,
  150765. 0.0886866347F, 0.0897984378F, 0.0909166480F, 0.0920412513F,
  150766. 0.0931722338F, 0.0943095813F, 0.0954532795F, 0.0966033140F,
  150767. 0.0977596702F, 0.0989223336F, 0.1000912894F, 0.1012665227F,
  150768. 0.1024480185F, 0.1036357616F, 0.1048297369F, 0.1060299290F,
  150769. 0.1072363224F, 0.1084489014F, 0.1096676504F, 0.1108925534F,
  150770. 0.1121235946F, 0.1133607577F, 0.1146040267F, 0.1158533850F,
  150771. 0.1171088163F, 0.1183703040F, 0.1196378312F, 0.1209113812F,
  150772. 0.1221909370F, 0.1234764815F, 0.1247679974F, 0.1260654674F,
  150773. 0.1273688740F, 0.1286781995F, 0.1299934263F, 0.1313145365F,
  150774. 0.1326415121F, 0.1339743349F, 0.1353129866F, 0.1366574490F,
  150775. 0.1380077035F, 0.1393637315F, 0.1407255141F, 0.1420930325F,
  150776. 0.1434662677F, 0.1448452004F, 0.1462298115F, 0.1476200814F,
  150777. 0.1490159906F, 0.1504175195F, 0.1518246482F, 0.1532373569F,
  150778. 0.1546556253F, 0.1560794333F, 0.1575087606F, 0.1589435866F,
  150779. 0.1603838909F, 0.1618296526F, 0.1632808509F, 0.1647374648F,
  150780. 0.1661994731F, 0.1676668546F, 0.1691395880F, 0.1706176516F,
  150781. 0.1721010238F, 0.1735896829F, 0.1750836068F, 0.1765827736F,
  150782. 0.1780871610F, 0.1795967468F, 0.1811115084F, 0.1826314234F,
  150783. 0.1841564689F, 0.1856866221F, 0.1872218600F, 0.1887621595F,
  150784. 0.1903074974F, 0.1918578503F, 0.1934131947F, 0.1949735068F,
  150785. 0.1965387630F, 0.1981089393F, 0.1996840117F, 0.2012639560F,
  150786. 0.2028487479F, 0.2044383630F, 0.2060327766F, 0.2076319642F,
  150787. 0.2092359007F, 0.2108445614F, 0.2124579211F, 0.2140759545F,
  150788. 0.2156986364F, 0.2173259411F, 0.2189578432F, 0.2205943168F,
  150789. 0.2222353361F, 0.2238808751F, 0.2255309076F, 0.2271854073F,
  150790. 0.2288443480F, 0.2305077030F, 0.2321754457F, 0.2338475493F,
  150791. 0.2355239869F, 0.2372047315F, 0.2388897560F, 0.2405790329F,
  150792. 0.2422725350F, 0.2439702347F, 0.2456721043F, 0.2473781159F,
  150793. 0.2490882418F, 0.2508024539F, 0.2525207240F, 0.2542430237F,
  150794. 0.2559693248F, 0.2576995986F, 0.2594338166F, 0.2611719498F,
  150795. 0.2629139695F, 0.2646598466F, 0.2664095520F, 0.2681630564F,
  150796. 0.2699203304F, 0.2716813445F, 0.2734460691F, 0.2752144744F,
  150797. 0.2769865307F, 0.2787622079F, 0.2805414760F, 0.2823243047F,
  150798. 0.2841106637F, 0.2859005227F, 0.2876938509F, 0.2894906179F,
  150799. 0.2912907928F, 0.2930943447F, 0.2949012426F, 0.2967114554F,
  150800. 0.2985249520F, 0.3003417009F, 0.3021616708F, 0.3039848301F,
  150801. 0.3058111471F, 0.3076405901F, 0.3094731273F, 0.3113087266F,
  150802. 0.3131473560F, 0.3149889833F, 0.3168335762F, 0.3186811024F,
  150803. 0.3205315294F, 0.3223848245F, 0.3242409552F, 0.3260998886F,
  150804. 0.3279615918F, 0.3298260319F, 0.3316931758F, 0.3335629903F,
  150805. 0.3354354423F, 0.3373104982F, 0.3391881247F, 0.3410682882F,
  150806. 0.3429509551F, 0.3448360917F, 0.3467236642F, 0.3486136387F,
  150807. 0.3505059811F, 0.3524006575F, 0.3542976336F, 0.3561968753F,
  150808. 0.3580983482F, 0.3600020179F, 0.3619078499F, 0.3638158096F,
  150809. 0.3657258625F, 0.3676379737F, 0.3695521086F, 0.3714682321F,
  150810. 0.3733863094F, 0.3753063055F, 0.3772281852F, 0.3791519134F,
  150811. 0.3810774548F, 0.3830047742F, 0.3849338362F, 0.3868646053F,
  150812. 0.3887970459F, 0.3907311227F, 0.3926667998F, 0.3946040417F,
  150813. 0.3965428125F, 0.3984830765F, 0.4004247978F, 0.4023679403F,
  150814. 0.4043124683F, 0.4062583455F, 0.4082055359F, 0.4101540034F,
  150815. 0.4121037117F, 0.4140546246F, 0.4160067058F, 0.4179599190F,
  150816. 0.4199142277F, 0.4218695956F, 0.4238259861F, 0.4257833627F,
  150817. 0.4277416888F, 0.4297009279F, 0.4316610433F, 0.4336219983F,
  150818. 0.4355837562F, 0.4375462803F, 0.4395095337F, 0.4414734797F,
  150819. 0.4434380815F, 0.4454033021F, 0.4473691046F, 0.4493354521F,
  150820. 0.4513023078F, 0.4532696345F, 0.4552373954F, 0.4572055533F,
  150821. 0.4591740713F, 0.4611429123F, 0.4631120393F, 0.4650814151F,
  150822. 0.4670510028F, 0.4690207650F, 0.4709906649F, 0.4729606651F,
  150823. 0.4749307287F, 0.4769008185F, 0.4788708972F, 0.4808409279F,
  150824. 0.4828108732F, 0.4847806962F, 0.4867503597F, 0.4887198264F,
  150825. 0.4906890593F, 0.4926580213F, 0.4946266753F, 0.4965949840F,
  150826. 0.4985629105F, 0.5005304176F, 0.5024974683F, 0.5044640255F,
  150827. 0.5064300522F, 0.5083955114F, 0.5103603659F, 0.5123245790F,
  150828. 0.5142881136F, 0.5162509328F, 0.5182129997F, 0.5201742774F,
  150829. 0.5221347290F, 0.5240943178F, 0.5260530070F, 0.5280107598F,
  150830. 0.5299675395F, 0.5319233095F, 0.5338780330F, 0.5358316736F,
  150831. 0.5377841946F, 0.5397355596F, 0.5416857320F, 0.5436346755F,
  150832. 0.5455823538F, 0.5475287304F, 0.5494737691F, 0.5514174337F,
  150833. 0.5533596881F, 0.5553004962F, 0.5572398218F, 0.5591776291F,
  150834. 0.5611138821F, 0.5630485449F, 0.5649815818F, 0.5669129570F,
  150835. 0.5688426349F, 0.5707705799F, 0.5726967564F, 0.5746211290F,
  150836. 0.5765436624F, 0.5784643212F, 0.5803830702F, 0.5822998743F,
  150837. 0.5842146984F, 0.5861275076F, 0.5880382669F, 0.5899469416F,
  150838. 0.5918534968F, 0.5937578981F, 0.5956601107F, 0.5975601004F,
  150839. 0.5994578326F, 0.6013532732F, 0.6032463880F, 0.6051371429F,
  150840. 0.6070255039F, 0.6089114372F, 0.6107949090F, 0.6126758856F,
  150841. 0.6145543334F, 0.6164302191F, 0.6183035092F, 0.6201741706F,
  150842. 0.6220421700F, 0.6239074745F, 0.6257700513F, 0.6276298674F,
  150843. 0.6294868903F, 0.6313410873F, 0.6331924262F, 0.6350408745F,
  150844. 0.6368864001F, 0.6387289710F, 0.6405685552F, 0.6424051209F,
  150845. 0.6442386364F, 0.6460690702F, 0.6478963910F, 0.6497205673F,
  150846. 0.6515415682F, 0.6533593625F, 0.6551739194F, 0.6569852082F,
  150847. 0.6587931984F, 0.6605978593F, 0.6623991609F, 0.6641970728F,
  150848. 0.6659915652F, 0.6677826081F, 0.6695701718F, 0.6713542268F,
  150849. 0.6731347437F, 0.6749116932F, 0.6766850461F, 0.6784547736F,
  150850. 0.6802208469F, 0.6819832374F, 0.6837419164F, 0.6854968559F,
  150851. 0.6872480275F, 0.6889954034F, 0.6907389556F, 0.6924786566F,
  150852. 0.6942144788F, 0.6959463950F, 0.6976743780F, 0.6993984008F,
  150853. 0.7011184365F, 0.7028344587F, 0.7045464407F, 0.7062543564F,
  150854. 0.7079581796F, 0.7096578844F, 0.7113534450F, 0.7130448359F,
  150855. 0.7147320316F, 0.7164150070F, 0.7180937371F, 0.7197681970F,
  150856. 0.7214383620F, 0.7231042077F, 0.7247657098F, 0.7264228443F,
  150857. 0.7280755871F, 0.7297239147F, 0.7313678035F, 0.7330072301F,
  150858. 0.7346421715F, 0.7362726046F, 0.7378985069F, 0.7395198556F,
  150859. 0.7411366285F, 0.7427488034F, 0.7443563584F, 0.7459592717F,
  150860. 0.7475575218F, 0.7491510873F, 0.7507399471F, 0.7523240803F,
  150861. 0.7539034661F, 0.7554780839F, 0.7570479136F, 0.7586129349F,
  150862. 0.7601731279F, 0.7617284730F, 0.7632789506F, 0.7648245416F,
  150863. 0.7663652267F, 0.7679009872F, 0.7694318044F, 0.7709576599F,
  150864. 0.7724785354F, 0.7739944130F, 0.7755052749F, 0.7770111035F,
  150865. 0.7785118815F, 0.7800075916F, 0.7814982170F, 0.7829837410F,
  150866. 0.7844641472F, 0.7859394191F, 0.7874095408F, 0.7888744965F,
  150867. 0.7903342706F, 0.7917888476F, 0.7932382124F, 0.7946823501F,
  150868. 0.7961212460F, 0.7975548855F, 0.7989832544F, 0.8004063386F,
  150869. 0.8018241244F, 0.8032365981F, 0.8046437463F, 0.8060455560F,
  150870. 0.8074420141F, 0.8088331080F, 0.8102188253F, 0.8115991536F,
  150871. 0.8129740810F, 0.8143435957F, 0.8157076861F, 0.8170663409F,
  150872. 0.8184195489F, 0.8197672994F, 0.8211095817F, 0.8224463853F,
  150873. 0.8237777001F, 0.8251035161F, 0.8264238235F, 0.8277386129F,
  150874. 0.8290478750F, 0.8303516008F, 0.8316497814F, 0.8329424083F,
  150875. 0.8342294731F, 0.8355109677F, 0.8367868841F, 0.8380572148F,
  150876. 0.8393219523F, 0.8405810893F, 0.8418346190F, 0.8430825345F,
  150877. 0.8443248294F, 0.8455614974F, 0.8467925323F, 0.8480179285F,
  150878. 0.8492376802F, 0.8504517822F, 0.8516602292F, 0.8528630164F,
  150879. 0.8540601391F, 0.8552515928F, 0.8564373733F, 0.8576174766F,
  150880. 0.8587918990F, 0.8599606368F, 0.8611236868F, 0.8622810460F,
  150881. 0.8634327113F, 0.8645786802F, 0.8657189504F, 0.8668535195F,
  150882. 0.8679823857F, 0.8691055472F, 0.8702230025F, 0.8713347503F,
  150883. 0.8724407896F, 0.8735411194F, 0.8746357394F, 0.8757246489F,
  150884. 0.8768078479F, 0.8778853364F, 0.8789571146F, 0.8800231832F,
  150885. 0.8810835427F, 0.8821381942F, 0.8831871387F, 0.8842303777F,
  150886. 0.8852679127F, 0.8862997456F, 0.8873258784F, 0.8883463132F,
  150887. 0.8893610527F, 0.8903700994F, 0.8913734562F, 0.8923711263F,
  150888. 0.8933631129F, 0.8943494196F, 0.8953300500F, 0.8963050083F,
  150889. 0.8972742985F, 0.8982379249F, 0.8991958922F, 0.9001482052F,
  150890. 0.9010948688F, 0.9020358883F, 0.9029712690F, 0.9039010165F,
  150891. 0.9048251367F, 0.9057436357F, 0.9066565195F, 0.9075637946F,
  150892. 0.9084654678F, 0.9093615456F, 0.9102520353F, 0.9111369440F,
  150893. 0.9120162792F, 0.9128900484F, 0.9137582595F, 0.9146209204F,
  150894. 0.9154780394F, 0.9163296248F, 0.9171756853F, 0.9180162296F,
  150895. 0.9188512667F, 0.9196808057F, 0.9205048559F, 0.9213234270F,
  150896. 0.9221365285F, 0.9229441704F, 0.9237463629F, 0.9245431160F,
  150897. 0.9253344404F, 0.9261203465F, 0.9269008453F, 0.9276759477F,
  150898. 0.9284456648F, 0.9292100080F, 0.9299689889F, 0.9307226190F,
  150899. 0.9314709103F, 0.9322138747F, 0.9329515245F, 0.9336838721F,
  150900. 0.9344109300F, 0.9351327108F, 0.9358492275F, 0.9365604931F,
  150901. 0.9372665208F, 0.9379673239F, 0.9386629160F, 0.9393533107F,
  150902. 0.9400385220F, 0.9407185637F, 0.9413934501F, 0.9420631954F,
  150903. 0.9427278141F, 0.9433873208F, 0.9440417304F, 0.9446910576F,
  150904. 0.9453353176F, 0.9459745255F, 0.9466086968F, 0.9472378469F,
  150905. 0.9478619915F, 0.9484811463F, 0.9490953274F, 0.9497045506F,
  150906. 0.9503088323F, 0.9509081888F, 0.9515026365F, 0.9520921921F,
  150907. 0.9526768723F, 0.9532566940F, 0.9538316742F, 0.9544018300F,
  150908. 0.9549671786F, 0.9555277375F, 0.9560835241F, 0.9566345562F,
  150909. 0.9571808513F, 0.9577224275F, 0.9582593027F, 0.9587914949F,
  150910. 0.9593190225F, 0.9598419038F, 0.9603601571F, 0.9608738012F,
  150911. 0.9613828546F, 0.9618873361F, 0.9623872646F, 0.9628826591F,
  150912. 0.9633735388F, 0.9638599227F, 0.9643418303F, 0.9648192808F,
  150913. 0.9652922939F, 0.9657608890F, 0.9662250860F, 0.9666849046F,
  150914. 0.9671403646F, 0.9675914861F, 0.9680382891F, 0.9684807937F,
  150915. 0.9689190202F, 0.9693529890F, 0.9697827203F, 0.9702082347F,
  150916. 0.9706295529F, 0.9710466953F, 0.9714596828F, 0.9718685362F,
  150917. 0.9722732762F, 0.9726739240F, 0.9730705005F, 0.9734630267F,
  150918. 0.9738515239F, 0.9742360134F, 0.9746165163F, 0.9749930540F,
  150919. 0.9753656481F, 0.9757343198F, 0.9760990909F, 0.9764599829F,
  150920. 0.9768170175F, 0.9771702164F, 0.9775196013F, 0.9778651941F,
  150921. 0.9782070167F, 0.9785450909F, 0.9788794388F, 0.9792100824F,
  150922. 0.9795370437F, 0.9798603449F, 0.9801800080F, 0.9804960554F,
  150923. 0.9808085092F, 0.9811173916F, 0.9814227251F, 0.9817245318F,
  150924. 0.9820228343F, 0.9823176549F, 0.9826090160F, 0.9828969402F,
  150925. 0.9831814498F, 0.9834625674F, 0.9837403156F, 0.9840147169F,
  150926. 0.9842857939F, 0.9845535692F, 0.9848180654F, 0.9850793052F,
  150927. 0.9853373113F, 0.9855921062F, 0.9858437127F, 0.9860921535F,
  150928. 0.9863374512F, 0.9865796287F, 0.9868187085F, 0.9870547136F,
  150929. 0.9872876664F, 0.9875175899F, 0.9877445067F, 0.9879684396F,
  150930. 0.9881894112F, 0.9884074444F, 0.9886225619F, 0.9888347863F,
  150931. 0.9890441404F, 0.9892506468F, 0.9894543284F, 0.9896552077F,
  150932. 0.9898533074F, 0.9900486502F, 0.9902412587F, 0.9904311555F,
  150933. 0.9906183633F, 0.9908029045F, 0.9909848019F, 0.9911640779F,
  150934. 0.9913407550F, 0.9915148557F, 0.9916864025F, 0.9918554179F,
  150935. 0.9920219241F, 0.9921859437F, 0.9923474989F, 0.9925066120F,
  150936. 0.9926633054F, 0.9928176012F, 0.9929695218F, 0.9931190891F,
  150937. 0.9932663254F, 0.9934112527F, 0.9935538932F, 0.9936942686F,
  150938. 0.9938324012F, 0.9939683126F, 0.9941020248F, 0.9942335597F,
  150939. 0.9943629388F, 0.9944901841F, 0.9946153170F, 0.9947383593F,
  150940. 0.9948593325F, 0.9949782579F, 0.9950951572F, 0.9952100516F,
  150941. 0.9953229625F, 0.9954339111F, 0.9955429186F, 0.9956500062F,
  150942. 0.9957551948F, 0.9958585056F, 0.9959599593F, 0.9960595769F,
  150943. 0.9961573792F, 0.9962533869F, 0.9963476206F, 0.9964401009F,
  150944. 0.9965308483F, 0.9966198833F, 0.9967072261F, 0.9967928971F,
  150945. 0.9968769164F, 0.9969593041F, 0.9970400804F, 0.9971192651F,
  150946. 0.9971968781F, 0.9972729391F, 0.9973474680F, 0.9974204842F,
  150947. 0.9974920074F, 0.9975620569F, 0.9976306521F, 0.9976978122F,
  150948. 0.9977635565F, 0.9978279039F, 0.9978908736F, 0.9979524842F,
  150949. 0.9980127547F, 0.9980717037F, 0.9981293499F, 0.9981857116F,
  150950. 0.9982408073F, 0.9982946554F, 0.9983472739F, 0.9983986810F,
  150951. 0.9984488947F, 0.9984979328F, 0.9985458132F, 0.9985925534F,
  150952. 0.9986381711F, 0.9986826838F, 0.9987261086F, 0.9987684630F,
  150953. 0.9988097640F, 0.9988500286F, 0.9988892738F, 0.9989275163F,
  150954. 0.9989647727F, 0.9990010597F, 0.9990363938F, 0.9990707911F,
  150955. 0.9991042679F, 0.9991368404F, 0.9991685244F, 0.9991993358F,
  150956. 0.9992292905F, 0.9992584038F, 0.9992866914F, 0.9993141686F,
  150957. 0.9993408506F, 0.9993667526F, 0.9993918895F, 0.9994162761F,
  150958. 0.9994399273F, 0.9994628576F, 0.9994850815F, 0.9995066133F,
  150959. 0.9995274672F, 0.9995476574F, 0.9995671978F, 0.9995861021F,
  150960. 0.9996043841F, 0.9996220573F, 0.9996391352F, 0.9996556310F,
  150961. 0.9996715579F, 0.9996869288F, 0.9997017568F, 0.9997160543F,
  150962. 0.9997298342F, 0.9997431088F, 0.9997558905F, 0.9997681914F,
  150963. 0.9997800236F, 0.9997913990F, 0.9998023292F, 0.9998128261F,
  150964. 0.9998229009F, 0.9998325650F, 0.9998418296F, 0.9998507058F,
  150965. 0.9998592044F, 0.9998673362F, 0.9998751117F, 0.9998825415F,
  150966. 0.9998896358F, 0.9998964047F, 0.9999028584F, 0.9999090066F,
  150967. 0.9999148590F, 0.9999204253F, 0.9999257148F, 0.9999307368F,
  150968. 0.9999355003F, 0.9999400144F, 0.9999442878F, 0.9999483293F,
  150969. 0.9999521472F, 0.9999557499F, 0.9999591457F, 0.9999623426F,
  150970. 0.9999653483F, 0.9999681708F, 0.9999708175F, 0.9999732959F,
  150971. 0.9999756132F, 0.9999777765F, 0.9999797928F, 0.9999816688F,
  150972. 0.9999834113F, 0.9999850266F, 0.9999865211F, 0.9999879009F,
  150973. 0.9999891721F, 0.9999903405F, 0.9999914118F, 0.9999923914F,
  150974. 0.9999932849F, 0.9999940972F, 0.9999948336F, 0.9999954989F,
  150975. 0.9999960978F, 0.9999966349F, 0.9999971146F, 0.9999975411F,
  150976. 0.9999979185F, 0.9999982507F, 0.9999985414F, 0.9999987944F,
  150977. 0.9999990129F, 0.9999992003F, 0.9999993596F, 0.9999994939F,
  150978. 0.9999996059F, 0.9999996981F, 0.9999997732F, 0.9999998333F,
  150979. 0.9999998805F, 0.9999999170F, 0.9999999444F, 0.9999999643F,
  150980. 0.9999999784F, 0.9999999878F, 0.9999999937F, 0.9999999972F,
  150981. 0.9999999990F, 0.9999999997F, 1.0000000000F, 1.0000000000F,
  150982. };
  150983. static float vwin4096[2048] = {
  150984. 0.0000002310F, 0.0000020791F, 0.0000057754F, 0.0000113197F,
  150985. 0.0000187121F, 0.0000279526F, 0.0000390412F, 0.0000519777F,
  150986. 0.0000667623F, 0.0000833949F, 0.0001018753F, 0.0001222036F,
  150987. 0.0001443798F, 0.0001684037F, 0.0001942754F, 0.0002219947F,
  150988. 0.0002515616F, 0.0002829761F, 0.0003162380F, 0.0003513472F,
  150989. 0.0003883038F, 0.0004271076F, 0.0004677584F, 0.0005102563F,
  150990. 0.0005546011F, 0.0006007928F, 0.0006488311F, 0.0006987160F,
  150991. 0.0007504474F, 0.0008040251F, 0.0008594490F, 0.0009167191F,
  150992. 0.0009758351F, 0.0010367969F, 0.0010996044F, 0.0011642574F,
  150993. 0.0012307558F, 0.0012990994F, 0.0013692880F, 0.0014413216F,
  150994. 0.0015151998F, 0.0015909226F, 0.0016684898F, 0.0017479011F,
  150995. 0.0018291565F, 0.0019122556F, 0.0019971983F, 0.0020839845F,
  150996. 0.0021726138F, 0.0022630861F, 0.0023554012F, 0.0024495588F,
  150997. 0.0025455588F, 0.0026434008F, 0.0027430847F, 0.0028446103F,
  150998. 0.0029479772F, 0.0030531853F, 0.0031602342F, 0.0032691238F,
  150999. 0.0033798538F, 0.0034924239F, 0.0036068338F, 0.0037230833F,
  151000. 0.0038411721F, 0.0039610999F, 0.0040828664F, 0.0042064714F,
  151001. 0.0043319145F, 0.0044591954F, 0.0045883139F, 0.0047192696F,
  151002. 0.0048520622F, 0.0049866914F, 0.0051231569F, 0.0052614583F,
  151003. 0.0054015953F, 0.0055435676F, 0.0056873748F, 0.0058330166F,
  151004. 0.0059804926F, 0.0061298026F, 0.0062809460F, 0.0064339226F,
  151005. 0.0065887320F, 0.0067453738F, 0.0069038476F, 0.0070641531F,
  151006. 0.0072262899F, 0.0073902575F, 0.0075560556F, 0.0077236838F,
  151007. 0.0078931417F, 0.0080644288F, 0.0082375447F, 0.0084124891F,
  151008. 0.0085892615F, 0.0087678614F, 0.0089482885F, 0.0091305422F,
  151009. 0.0093146223F, 0.0095005281F, 0.0096882592F, 0.0098778153F,
  151010. 0.0100691958F, 0.0102624002F, 0.0104574281F, 0.0106542791F,
  151011. 0.0108529525F, 0.0110534480F, 0.0112557651F, 0.0114599032F,
  151012. 0.0116658618F, 0.0118736405F, 0.0120832387F, 0.0122946560F,
  151013. 0.0125078917F, 0.0127229454F, 0.0129398166F, 0.0131585046F,
  151014. 0.0133790090F, 0.0136013292F, 0.0138254647F, 0.0140514149F,
  151015. 0.0142791792F, 0.0145087572F, 0.0147401481F, 0.0149733515F,
  151016. 0.0152083667F, 0.0154451932F, 0.0156838304F, 0.0159242777F,
  151017. 0.0161665345F, 0.0164106001F, 0.0166564741F, 0.0169041557F,
  151018. 0.0171536443F, 0.0174049393F, 0.0176580401F, 0.0179129461F,
  151019. 0.0181696565F, 0.0184281708F, 0.0186884883F, 0.0189506084F,
  151020. 0.0192145303F, 0.0194802535F, 0.0197477772F, 0.0200171008F,
  151021. 0.0202882236F, 0.0205611449F, 0.0208358639F, 0.0211123801F,
  151022. 0.0213906927F, 0.0216708011F, 0.0219527043F, 0.0222364019F,
  151023. 0.0225218930F, 0.0228091769F, 0.0230982529F, 0.0233891203F,
  151024. 0.0236817782F, 0.0239762259F, 0.0242724628F, 0.0245704880F,
  151025. 0.0248703007F, 0.0251719002F, 0.0254752858F, 0.0257804565F,
  151026. 0.0260874117F, 0.0263961506F, 0.0267066722F, 0.0270189760F,
  151027. 0.0273330609F, 0.0276489263F, 0.0279665712F, 0.0282859949F,
  151028. 0.0286071966F, 0.0289301753F, 0.0292549303F, 0.0295814607F,
  151029. 0.0299097656F, 0.0302398442F, 0.0305716957F, 0.0309053191F,
  151030. 0.0312407135F, 0.0315778782F, 0.0319168122F, 0.0322575145F,
  151031. 0.0325999844F, 0.0329442209F, 0.0332902231F, 0.0336379900F,
  151032. 0.0339875208F, 0.0343388146F, 0.0346918703F, 0.0350466871F,
  151033. 0.0354032640F, 0.0357616000F, 0.0361216943F, 0.0364835458F,
  151034. 0.0368471535F, 0.0372125166F, 0.0375796339F, 0.0379485046F,
  151035. 0.0383191276F, 0.0386915020F, 0.0390656267F, 0.0394415008F,
  151036. 0.0398191231F, 0.0401984927F, 0.0405796086F, 0.0409624698F,
  151037. 0.0413470751F, 0.0417334235F, 0.0421215141F, 0.0425113457F,
  151038. 0.0429029172F, 0.0432962277F, 0.0436912760F, 0.0440880610F,
  151039. 0.0444865817F, 0.0448868370F, 0.0452888257F, 0.0456925468F,
  151040. 0.0460979992F, 0.0465051816F, 0.0469140931F, 0.0473247325F,
  151041. 0.0477370986F, 0.0481511902F, 0.0485670064F, 0.0489845458F,
  151042. 0.0494038074F, 0.0498247899F, 0.0502474922F, 0.0506719131F,
  151043. 0.0510980514F, 0.0515259060F, 0.0519554756F, 0.0523867590F,
  151044. 0.0528197550F, 0.0532544624F, 0.0536908800F, 0.0541290066F,
  151045. 0.0545688408F, 0.0550103815F, 0.0554536274F, 0.0558985772F,
  151046. 0.0563452297F, 0.0567935837F, 0.0572436377F, 0.0576953907F,
  151047. 0.0581488412F, 0.0586039880F, 0.0590608297F, 0.0595193651F,
  151048. 0.0599795929F, 0.0604415117F, 0.0609051202F, 0.0613704170F,
  151049. 0.0618374009F, 0.0623060704F, 0.0627764243F, 0.0632484611F,
  151050. 0.0637221795F, 0.0641975781F, 0.0646746555F, 0.0651534104F,
  151051. 0.0656338413F, 0.0661159469F, 0.0665997257F, 0.0670851763F,
  151052. 0.0675722973F, 0.0680610873F, 0.0685515448F, 0.0690436684F,
  151053. 0.0695374567F, 0.0700329081F, 0.0705300213F, 0.0710287947F,
  151054. 0.0715292269F, 0.0720313163F, 0.0725350616F, 0.0730404612F,
  151055. 0.0735475136F, 0.0740562172F, 0.0745665707F, 0.0750785723F,
  151056. 0.0755922207F, 0.0761075143F, 0.0766244515F, 0.0771430307F,
  151057. 0.0776632505F, 0.0781851092F, 0.0787086052F, 0.0792337371F,
  151058. 0.0797605032F, 0.0802889018F, 0.0808189315F, 0.0813505905F,
  151059. 0.0818838773F, 0.0824187903F, 0.0829553277F, 0.0834934881F,
  151060. 0.0840332697F, 0.0845746708F, 0.0851176899F, 0.0856623252F,
  151061. 0.0862085751F, 0.0867564379F, 0.0873059119F, 0.0878569954F,
  151062. 0.0884096867F, 0.0889639840F, 0.0895198858F, 0.0900773902F,
  151063. 0.0906364955F, 0.0911972000F, 0.0917595019F, 0.0923233995F,
  151064. 0.0928888909F, 0.0934559745F, 0.0940246485F, 0.0945949110F,
  151065. 0.0951667604F, 0.0957401946F, 0.0963152121F, 0.0968918109F,
  151066. 0.0974699893F, 0.0980497454F, 0.0986310773F, 0.0992139832F,
  151067. 0.0997984614F, 0.1003845098F, 0.1009721267F, 0.1015613101F,
  151068. 0.1021520582F, 0.1027443692F, 0.1033382410F, 0.1039336718F,
  151069. 0.1045306597F, 0.1051292027F, 0.1057292990F, 0.1063309466F,
  151070. 0.1069341435F, 0.1075388878F, 0.1081451776F, 0.1087530108F,
  151071. 0.1093623856F, 0.1099732998F, 0.1105857516F, 0.1111997389F,
  151072. 0.1118152597F, 0.1124323121F, 0.1130508939F, 0.1136710032F,
  151073. 0.1142926379F, 0.1149157960F, 0.1155404755F, 0.1161666742F,
  151074. 0.1167943901F, 0.1174236211F, 0.1180543652F, 0.1186866202F,
  151075. 0.1193203841F, 0.1199556548F, 0.1205924300F, 0.1212307078F,
  151076. 0.1218704860F, 0.1225117624F, 0.1231545349F, 0.1237988013F,
  151077. 0.1244445596F, 0.1250918074F, 0.1257405427F, 0.1263907632F,
  151078. 0.1270424667F, 0.1276956512F, 0.1283503142F, 0.1290064537F,
  151079. 0.1296640674F, 0.1303231530F, 0.1309837084F, 0.1316457312F,
  151080. 0.1323092193F, 0.1329741703F, 0.1336405820F, 0.1343084520F,
  151081. 0.1349777782F, 0.1356485582F, 0.1363207897F, 0.1369944704F,
  151082. 0.1376695979F, 0.1383461700F, 0.1390241842F, 0.1397036384F,
  151083. 0.1403845300F, 0.1410668567F, 0.1417506162F, 0.1424358061F,
  151084. 0.1431224240F, 0.1438104674F, 0.1444999341F, 0.1451908216F,
  151085. 0.1458831274F, 0.1465768492F, 0.1472719844F, 0.1479685308F,
  151086. 0.1486664857F, 0.1493658468F, 0.1500666115F, 0.1507687775F,
  151087. 0.1514723422F, 0.1521773031F, 0.1528836577F, 0.1535914035F,
  151088. 0.1543005380F, 0.1550110587F, 0.1557229631F, 0.1564362485F,
  151089. 0.1571509124F, 0.1578669524F, 0.1585843657F, 0.1593031499F,
  151090. 0.1600233024F, 0.1607448205F, 0.1614677017F, 0.1621919433F,
  151091. 0.1629175428F, 0.1636444975F, 0.1643728047F, 0.1651024619F,
  151092. 0.1658334665F, 0.1665658156F, 0.1672995067F, 0.1680345371F,
  151093. 0.1687709041F, 0.1695086050F, 0.1702476372F, 0.1709879978F,
  151094. 0.1717296843F, 0.1724726938F, 0.1732170237F, 0.1739626711F,
  151095. 0.1747096335F, 0.1754579079F, 0.1762074916F, 0.1769583819F,
  151096. 0.1777105760F, 0.1784640710F, 0.1792188642F, 0.1799749529F,
  151097. 0.1807323340F, 0.1814910049F, 0.1822509628F, 0.1830122046F,
  151098. 0.1837747277F, 0.1845385292F, 0.1853036062F, 0.1860699558F,
  151099. 0.1868375751F, 0.1876064613F, 0.1883766114F, 0.1891480226F,
  151100. 0.1899206919F, 0.1906946164F, 0.1914697932F, 0.1922462194F,
  151101. 0.1930238919F, 0.1938028079F, 0.1945829643F, 0.1953643583F,
  151102. 0.1961469868F, 0.1969308468F, 0.1977159353F, 0.1985022494F,
  151103. 0.1992897859F, 0.2000785420F, 0.2008685145F, 0.2016597005F,
  151104. 0.2024520968F, 0.2032457005F, 0.2040405084F, 0.2048365175F,
  151105. 0.2056337247F, 0.2064321269F, 0.2072317211F, 0.2080325041F,
  151106. 0.2088344727F, 0.2096376240F, 0.2104419547F, 0.2112474618F,
  151107. 0.2120541420F, 0.2128619923F, 0.2136710094F, 0.2144811902F,
  151108. 0.2152925315F, 0.2161050301F, 0.2169186829F, 0.2177334866F,
  151109. 0.2185494381F, 0.2193665340F, 0.2201847712F, 0.2210041465F,
  151110. 0.2218246565F, 0.2226462981F, 0.2234690680F, 0.2242929629F,
  151111. 0.2251179796F, 0.2259441147F, 0.2267713650F, 0.2275997272F,
  151112. 0.2284291979F, 0.2292597739F, 0.2300914518F, 0.2309242283F,
  151113. 0.2317581001F, 0.2325930638F, 0.2334291160F, 0.2342662534F,
  151114. 0.2351044727F, 0.2359437703F, 0.2367841431F, 0.2376255875F,
  151115. 0.2384681001F, 0.2393116776F, 0.2401563165F, 0.2410020134F,
  151116. 0.2418487649F, 0.2426965675F, 0.2435454178F, 0.2443953122F,
  151117. 0.2452462474F, 0.2460982199F, 0.2469512262F, 0.2478052628F,
  151118. 0.2486603262F, 0.2495164129F, 0.2503735194F, 0.2512316421F,
  151119. 0.2520907776F, 0.2529509222F, 0.2538120726F, 0.2546742250F,
  151120. 0.2555373760F, 0.2564015219F, 0.2572666593F, 0.2581327845F,
  151121. 0.2589998939F, 0.2598679840F, 0.2607370510F, 0.2616070916F,
  151122. 0.2624781019F, 0.2633500783F, 0.2642230173F, 0.2650969152F,
  151123. 0.2659717684F, 0.2668475731F, 0.2677243257F, 0.2686020226F,
  151124. 0.2694806601F, 0.2703602344F, 0.2712407419F, 0.2721221789F,
  151125. 0.2730045417F, 0.2738878265F, 0.2747720297F, 0.2756571474F,
  151126. 0.2765431760F, 0.2774301117F, 0.2783179508F, 0.2792066895F,
  151127. 0.2800963240F, 0.2809868505F, 0.2818782654F, 0.2827705647F,
  151128. 0.2836637447F, 0.2845578016F, 0.2854527315F, 0.2863485307F,
  151129. 0.2872451953F, 0.2881427215F, 0.2890411055F, 0.2899403433F,
  151130. 0.2908404312F, 0.2917413654F, 0.2926431418F, 0.2935457567F,
  151131. 0.2944492061F, 0.2953534863F, 0.2962585932F, 0.2971645230F,
  151132. 0.2980712717F, 0.2989788356F, 0.2998872105F, 0.3007963927F,
  151133. 0.3017063781F, 0.3026171629F, 0.3035287430F, 0.3044411145F,
  151134. 0.3053542736F, 0.3062682161F, 0.3071829381F, 0.3080984356F,
  151135. 0.3090147047F, 0.3099317413F, 0.3108495414F, 0.3117681011F,
  151136. 0.3126874163F, 0.3136074830F, 0.3145282972F, 0.3154498548F,
  151137. 0.3163721517F, 0.3172951841F, 0.3182189477F, 0.3191434385F,
  151138. 0.3200686525F, 0.3209945856F, 0.3219212336F, 0.3228485927F,
  151139. 0.3237766585F, 0.3247054271F, 0.3256348943F, 0.3265650560F,
  151140. 0.3274959081F, 0.3284274465F, 0.3293596671F, 0.3302925657F,
  151141. 0.3312261382F, 0.3321603804F, 0.3330952882F, 0.3340308574F,
  151142. 0.3349670838F, 0.3359039634F, 0.3368414919F, 0.3377796651F,
  151143. 0.3387184789F, 0.3396579290F, 0.3405980113F, 0.3415387216F,
  151144. 0.3424800556F, 0.3434220091F, 0.3443645779F, 0.3453077578F,
  151145. 0.3462515446F, 0.3471959340F, 0.3481409217F, 0.3490865036F,
  151146. 0.3500326754F, 0.3509794328F, 0.3519267715F, 0.3528746873F,
  151147. 0.3538231759F, 0.3547722330F, 0.3557218544F, 0.3566720357F,
  151148. 0.3576227727F, 0.3585740610F, 0.3595258964F, 0.3604782745F,
  151149. 0.3614311910F, 0.3623846417F, 0.3633386221F, 0.3642931280F,
  151150. 0.3652481549F, 0.3662036987F, 0.3671597548F, 0.3681163191F,
  151151. 0.3690733870F, 0.3700309544F, 0.3709890167F, 0.3719475696F,
  151152. 0.3729066089F, 0.3738661299F, 0.3748261285F, 0.3757866002F,
  151153. 0.3767475406F, 0.3777089453F, 0.3786708100F, 0.3796331302F,
  151154. 0.3805959014F, 0.3815591194F, 0.3825227796F, 0.3834868777F,
  151155. 0.3844514093F, 0.3854163698F, 0.3863817549F, 0.3873475601F,
  151156. 0.3883137810F, 0.3892804131F, 0.3902474521F, 0.3912148933F,
  151157. 0.3921827325F, 0.3931509650F, 0.3941195865F, 0.3950885925F,
  151158. 0.3960579785F, 0.3970277400F, 0.3979978725F, 0.3989683716F,
  151159. 0.3999392328F, 0.4009104516F, 0.4018820234F, 0.4028539438F,
  151160. 0.4038262084F, 0.4047988125F, 0.4057717516F, 0.4067450214F,
  151161. 0.4077186172F, 0.4086925345F, 0.4096667688F, 0.4106413155F,
  151162. 0.4116161703F, 0.4125913284F, 0.4135667854F, 0.4145425368F,
  151163. 0.4155185780F, 0.4164949044F, 0.4174715116F, 0.4184483949F,
  151164. 0.4194255498F, 0.4204029718F, 0.4213806563F, 0.4223585987F,
  151165. 0.4233367946F, 0.4243152392F, 0.4252939281F, 0.4262728566F,
  151166. 0.4272520202F, 0.4282314144F, 0.4292110345F, 0.4301908760F,
  151167. 0.4311709343F, 0.4321512047F, 0.4331316828F, 0.4341123639F,
  151168. 0.4350932435F, 0.4360743168F, 0.4370555794F, 0.4380370267F,
  151169. 0.4390186540F, 0.4400004567F, 0.4409824303F, 0.4419645701F,
  151170. 0.4429468716F, 0.4439293300F, 0.4449119409F, 0.4458946996F,
  151171. 0.4468776014F, 0.4478606418F, 0.4488438162F, 0.4498271199F,
  151172. 0.4508105483F, 0.4517940967F, 0.4527777607F, 0.4537615355F,
  151173. 0.4547454165F, 0.4557293991F, 0.4567134786F, 0.4576976505F,
  151174. 0.4586819101F, 0.4596662527F, 0.4606506738F, 0.4616351687F,
  151175. 0.4626197328F, 0.4636043614F, 0.4645890499F, 0.4655737936F,
  151176. 0.4665585880F, 0.4675434284F, 0.4685283101F, 0.4695132286F,
  151177. 0.4704981791F, 0.4714831570F, 0.4724681577F, 0.4734531766F,
  151178. 0.4744382089F, 0.4754232501F, 0.4764082956F, 0.4773933406F,
  151179. 0.4783783806F, 0.4793634108F, 0.4803484267F, 0.4813334237F,
  151180. 0.4823183969F, 0.4833033419F, 0.4842882540F, 0.4852731285F,
  151181. 0.4862579608F, 0.4872427462F, 0.4882274802F, 0.4892121580F,
  151182. 0.4901967751F, 0.4911813267F, 0.4921658083F, 0.4931502151F,
  151183. 0.4941345427F, 0.4951187863F, 0.4961029412F, 0.4970870029F,
  151184. 0.4980709667F, 0.4990548280F, 0.5000385822F, 0.5010222245F,
  151185. 0.5020057505F, 0.5029891553F, 0.5039724345F, 0.5049555834F,
  151186. 0.5059385973F, 0.5069214716F, 0.5079042018F, 0.5088867831F,
  151187. 0.5098692110F, 0.5108514808F, 0.5118335879F, 0.5128155277F,
  151188. 0.5137972956F, 0.5147788869F, 0.5157602971F, 0.5167415215F,
  151189. 0.5177225555F, 0.5187033945F, 0.5196840339F, 0.5206644692F,
  151190. 0.5216446956F, 0.5226247086F, 0.5236045035F, 0.5245840759F,
  151191. 0.5255634211F, 0.5265425344F, 0.5275214114F, 0.5285000474F,
  151192. 0.5294784378F, 0.5304565781F, 0.5314344637F, 0.5324120899F,
  151193. 0.5333894522F, 0.5343665461F, 0.5353433670F, 0.5363199102F,
  151194. 0.5372961713F, 0.5382721457F, 0.5392478287F, 0.5402232159F,
  151195. 0.5411983027F, 0.5421730845F, 0.5431475569F, 0.5441217151F,
  151196. 0.5450955548F, 0.5460690714F, 0.5470422602F, 0.5480151169F,
  151197. 0.5489876368F, 0.5499598155F, 0.5509316484F, 0.5519031310F,
  151198. 0.5528742587F, 0.5538450271F, 0.5548154317F, 0.5557854680F,
  151199. 0.5567551314F, 0.5577244174F, 0.5586933216F, 0.5596618395F,
  151200. 0.5606299665F, 0.5615976983F, 0.5625650302F, 0.5635319580F,
  151201. 0.5644984770F, 0.5654645828F, 0.5664302709F, 0.5673955370F,
  151202. 0.5683603765F, 0.5693247850F, 0.5702887580F, 0.5712522912F,
  151203. 0.5722153800F, 0.5731780200F, 0.5741402069F, 0.5751019362F,
  151204. 0.5760632034F, 0.5770240042F, 0.5779843341F, 0.5789441889F,
  151205. 0.5799035639F, 0.5808624549F, 0.5818208575F, 0.5827787673F,
  151206. 0.5837361800F, 0.5846930910F, 0.5856494961F, 0.5866053910F,
  151207. 0.5875607712F, 0.5885156324F, 0.5894699703F, 0.5904237804F,
  151208. 0.5913770586F, 0.5923298004F, 0.5932820016F, 0.5942336578F,
  151209. 0.5951847646F, 0.5961353179F, 0.5970853132F, 0.5980347464F,
  151210. 0.5989836131F, 0.5999319090F, 0.6008796298F, 0.6018267713F,
  151211. 0.6027733292F, 0.6037192993F, 0.6046646773F, 0.6056094589F,
  151212. 0.6065536400F, 0.6074972162F, 0.6084401833F, 0.6093825372F,
  151213. 0.6103242736F, 0.6112653884F, 0.6122058772F, 0.6131457359F,
  151214. 0.6140849604F, 0.6150235464F, 0.6159614897F, 0.6168987862F,
  151215. 0.6178354318F, 0.6187714223F, 0.6197067535F, 0.6206414213F,
  151216. 0.6215754215F, 0.6225087501F, 0.6234414028F, 0.6243733757F,
  151217. 0.6253046646F, 0.6262352654F, 0.6271651739F, 0.6280943862F,
  151218. 0.6290228982F, 0.6299507057F, 0.6308778048F, 0.6318041913F,
  151219. 0.6327298612F, 0.6336548105F, 0.6345790352F, 0.6355025312F,
  151220. 0.6364252945F, 0.6373473211F, 0.6382686070F, 0.6391891483F,
  151221. 0.6401089409F, 0.6410279808F, 0.6419462642F, 0.6428637869F,
  151222. 0.6437805452F, 0.6446965350F, 0.6456117524F, 0.6465261935F,
  151223. 0.6474398544F, 0.6483527311F, 0.6492648197F, 0.6501761165F,
  151224. 0.6510866174F, 0.6519963186F, 0.6529052162F, 0.6538133064F,
  151225. 0.6547205854F, 0.6556270492F, 0.6565326941F, 0.6574375162F,
  151226. 0.6583415117F, 0.6592446769F, 0.6601470079F, 0.6610485009F,
  151227. 0.6619491521F, 0.6628489578F, 0.6637479143F, 0.6646460177F,
  151228. 0.6655432643F, 0.6664396505F, 0.6673351724F, 0.6682298264F,
  151229. 0.6691236087F, 0.6700165157F, 0.6709085436F, 0.6717996889F,
  151230. 0.6726899478F, 0.6735793167F, 0.6744677918F, 0.6753553697F,
  151231. 0.6762420466F, 0.6771278190F, 0.6780126832F, 0.6788966357F,
  151232. 0.6797796728F, 0.6806617909F, 0.6815429866F, 0.6824232562F,
  151233. 0.6833025961F, 0.6841810030F, 0.6850584731F, 0.6859350031F,
  151234. 0.6868105894F, 0.6876852284F, 0.6885589168F, 0.6894316510F,
  151235. 0.6903034275F, 0.6911742430F, 0.6920440939F, 0.6929129769F,
  151236. 0.6937808884F, 0.6946478251F, 0.6955137837F, 0.6963787606F,
  151237. 0.6972427525F, 0.6981057560F, 0.6989677678F, 0.6998287845F,
  151238. 0.7006888028F, 0.7015478194F, 0.7024058309F, 0.7032628340F,
  151239. 0.7041188254F, 0.7049738019F, 0.7058277601F, 0.7066806969F,
  151240. 0.7075326089F, 0.7083834929F, 0.7092333457F, 0.7100821640F,
  151241. 0.7109299447F, 0.7117766846F, 0.7126223804F, 0.7134670291F,
  151242. 0.7143106273F, 0.7151531721F, 0.7159946602F, 0.7168350885F,
  151243. 0.7176744539F, 0.7185127534F, 0.7193499837F, 0.7201861418F,
  151244. 0.7210212247F, 0.7218552293F, 0.7226881526F, 0.7235199914F,
  151245. 0.7243507428F, 0.7251804039F, 0.7260089715F, 0.7268364426F,
  151246. 0.7276628144F, 0.7284880839F, 0.7293122481F, 0.7301353040F,
  151247. 0.7309572487F, 0.7317780794F, 0.7325977930F, 0.7334163868F,
  151248. 0.7342338579F, 0.7350502033F, 0.7358654202F, 0.7366795059F,
  151249. 0.7374924573F, 0.7383042718F, 0.7391149465F, 0.7399244787F,
  151250. 0.7407328655F, 0.7415401041F, 0.7423461920F, 0.7431511261F,
  151251. 0.7439549040F, 0.7447575227F, 0.7455589797F, 0.7463592723F,
  151252. 0.7471583976F, 0.7479563532F, 0.7487531363F, 0.7495487443F,
  151253. 0.7503431745F, 0.7511364244F, 0.7519284913F, 0.7527193726F,
  151254. 0.7535090658F, 0.7542975683F, 0.7550848776F, 0.7558709910F,
  151255. 0.7566559062F, 0.7574396205F, 0.7582221314F, 0.7590034366F,
  151256. 0.7597835334F, 0.7605624194F, 0.7613400923F, 0.7621165495F,
  151257. 0.7628917886F, 0.7636658072F, 0.7644386030F, 0.7652101735F,
  151258. 0.7659805164F, 0.7667496292F, 0.7675175098F, 0.7682841556F,
  151259. 0.7690495645F, 0.7698137341F, 0.7705766622F, 0.7713383463F,
  151260. 0.7720987844F, 0.7728579741F, 0.7736159132F, 0.7743725994F,
  151261. 0.7751280306F, 0.7758822046F, 0.7766351192F, 0.7773867722F,
  151262. 0.7781371614F, 0.7788862848F, 0.7796341401F, 0.7803807253F,
  151263. 0.7811260383F, 0.7818700769F, 0.7826128392F, 0.7833543230F,
  151264. 0.7840945263F, 0.7848334471F, 0.7855710833F, 0.7863074330F,
  151265. 0.7870424941F, 0.7877762647F, 0.7885087428F, 0.7892399264F,
  151266. 0.7899698137F, 0.7906984026F, 0.7914256914F, 0.7921516780F,
  151267. 0.7928763607F, 0.7935997375F, 0.7943218065F, 0.7950425661F,
  151268. 0.7957620142F, 0.7964801492F, 0.7971969692F, 0.7979124724F,
  151269. 0.7986266570F, 0.7993395214F, 0.8000510638F, 0.8007612823F,
  151270. 0.8014701754F, 0.8021777413F, 0.8028839784F, 0.8035888849F,
  151271. 0.8042924592F, 0.8049946997F, 0.8056956048F, 0.8063951727F,
  151272. 0.8070934020F, 0.8077902910F, 0.8084858381F, 0.8091800419F,
  151273. 0.8098729007F, 0.8105644130F, 0.8112545774F, 0.8119433922F,
  151274. 0.8126308561F, 0.8133169676F, 0.8140017251F, 0.8146851272F,
  151275. 0.8153671726F, 0.8160478598F, 0.8167271874F, 0.8174051539F,
  151276. 0.8180817582F, 0.8187569986F, 0.8194308741F, 0.8201033831F,
  151277. 0.8207745244F, 0.8214442966F, 0.8221126986F, 0.8227797290F,
  151278. 0.8234453865F, 0.8241096700F, 0.8247725781F, 0.8254341097F,
  151279. 0.8260942636F, 0.8267530385F, 0.8274104334F, 0.8280664470F,
  151280. 0.8287210782F, 0.8293743259F, 0.8300261889F, 0.8306766662F,
  151281. 0.8313257566F, 0.8319734591F, 0.8326197727F, 0.8332646963F,
  151282. 0.8339082288F, 0.8345503692F, 0.8351911167F, 0.8358304700F,
  151283. 0.8364684284F, 0.8371049907F, 0.8377401562F, 0.8383739238F,
  151284. 0.8390062927F, 0.8396372618F, 0.8402668305F, 0.8408949977F,
  151285. 0.8415217626F, 0.8421471245F, 0.8427710823F, 0.8433936354F,
  151286. 0.8440147830F, 0.8446345242F, 0.8452528582F, 0.8458697844F,
  151287. 0.8464853020F, 0.8470994102F, 0.8477121084F, 0.8483233958F,
  151288. 0.8489332718F, 0.8495417356F, 0.8501487866F, 0.8507544243F,
  151289. 0.8513586479F, 0.8519614568F, 0.8525628505F, 0.8531628283F,
  151290. 0.8537613897F, 0.8543585341F, 0.8549542611F, 0.8555485699F,
  151291. 0.8561414603F, 0.8567329315F, 0.8573229832F, 0.8579116149F,
  151292. 0.8584988262F, 0.8590846165F, 0.8596689855F, 0.8602519327F,
  151293. 0.8608334577F, 0.8614135603F, 0.8619922399F, 0.8625694962F,
  151294. 0.8631453289F, 0.8637197377F, 0.8642927222F, 0.8648642821F,
  151295. 0.8654344172F, 0.8660031272F, 0.8665704118F, 0.8671362708F,
  151296. 0.8677007039F, 0.8682637109F, 0.8688252917F, 0.8693854460F,
  151297. 0.8699441737F, 0.8705014745F, 0.8710573485F, 0.8716117953F,
  151298. 0.8721648150F, 0.8727164073F, 0.8732665723F, 0.8738153098F,
  151299. 0.8743626197F, 0.8749085021F, 0.8754529569F, 0.8759959840F,
  151300. 0.8765375835F, 0.8770777553F, 0.8776164996F, 0.8781538162F,
  151301. 0.8786897054F, 0.8792241670F, 0.8797572013F, 0.8802888082F,
  151302. 0.8808189880F, 0.8813477407F, 0.8818750664F, 0.8824009653F,
  151303. 0.8829254375F, 0.8834484833F, 0.8839701028F, 0.8844902961F,
  151304. 0.8850090636F, 0.8855264054F, 0.8860423218F, 0.8865568131F,
  151305. 0.8870698794F, 0.8875815212F, 0.8880917386F, 0.8886005319F,
  151306. 0.8891079016F, 0.8896138479F, 0.8901183712F, 0.8906214719F,
  151307. 0.8911231503F, 0.8916234067F, 0.8921222417F, 0.8926196556F,
  151308. 0.8931156489F, 0.8936102219F, 0.8941033752F, 0.8945951092F,
  151309. 0.8950854244F, 0.8955743212F, 0.8960618003F, 0.8965478621F,
  151310. 0.8970325071F, 0.8975157359F, 0.8979975490F, 0.8984779471F,
  151311. 0.8989569307F, 0.8994345004F, 0.8999106568F, 0.9003854005F,
  151312. 0.9008587323F, 0.9013306526F, 0.9018011623F, 0.9022702619F,
  151313. 0.9027379521F, 0.9032042337F, 0.9036691074F, 0.9041325739F,
  151314. 0.9045946339F, 0.9050552882F, 0.9055145376F, 0.9059723828F,
  151315. 0.9064288246F, 0.9068838638F, 0.9073375013F, 0.9077897379F,
  151316. 0.9082405743F, 0.9086900115F, 0.9091380503F, 0.9095846917F,
  151317. 0.9100299364F, 0.9104737854F, 0.9109162397F, 0.9113573001F,
  151318. 0.9117969675F, 0.9122352430F, 0.9126721275F, 0.9131076219F,
  151319. 0.9135417273F, 0.9139744447F, 0.9144057750F, 0.9148357194F,
  151320. 0.9152642787F, 0.9156914542F, 0.9161172468F, 0.9165416576F,
  151321. 0.9169646877F, 0.9173863382F, 0.9178066102F, 0.9182255048F,
  151322. 0.9186430232F, 0.9190591665F, 0.9194739359F, 0.9198873324F,
  151323. 0.9202993574F, 0.9207100120F, 0.9211192973F, 0.9215272147F,
  151324. 0.9219337653F, 0.9223389504F, 0.9227427713F, 0.9231452290F,
  151325. 0.9235463251F, 0.9239460607F, 0.9243444371F, 0.9247414557F,
  151326. 0.9251371177F, 0.9255314245F, 0.9259243774F, 0.9263159778F,
  151327. 0.9267062270F, 0.9270951264F, 0.9274826774F, 0.9278688814F,
  151328. 0.9282537398F, 0.9286372540F, 0.9290194254F, 0.9294002555F,
  151329. 0.9297797458F, 0.9301578976F, 0.9305347125F, 0.9309101919F,
  151330. 0.9312843373F, 0.9316571503F, 0.9320286323F, 0.9323987849F,
  151331. 0.9327676097F, 0.9331351080F, 0.9335012816F, 0.9338661320F,
  151332. 0.9342296607F, 0.9345918694F, 0.9349527596F, 0.9353123330F,
  151333. 0.9356705911F, 0.9360275357F, 0.9363831683F, 0.9367374905F,
  151334. 0.9370905042F, 0.9374422108F, 0.9377926122F, 0.9381417099F,
  151335. 0.9384895057F, 0.9388360014F, 0.9391811985F, 0.9395250989F,
  151336. 0.9398677043F, 0.9402090165F, 0.9405490371F, 0.9408877680F,
  151337. 0.9412252110F, 0.9415613678F, 0.9418962402F, 0.9422298301F,
  151338. 0.9425621392F, 0.9428931695F, 0.9432229226F, 0.9435514005F,
  151339. 0.9438786050F, 0.9442045381F, 0.9445292014F, 0.9448525971F,
  151340. 0.9451747268F, 0.9454955926F, 0.9458151963F, 0.9461335399F,
  151341. 0.9464506253F, 0.9467664545F, 0.9470810293F, 0.9473943517F,
  151342. 0.9477064238F, 0.9480172474F, 0.9483268246F, 0.9486351573F,
  151343. 0.9489422475F, 0.9492480973F, 0.9495527087F, 0.9498560837F,
  151344. 0.9501582243F, 0.9504591325F, 0.9507588105F, 0.9510572603F,
  151345. 0.9513544839F, 0.9516504834F, 0.9519452609F, 0.9522388186F,
  151346. 0.9525311584F, 0.9528222826F, 0.9531121932F, 0.9534008923F,
  151347. 0.9536883821F, 0.9539746647F, 0.9542597424F, 0.9545436171F,
  151348. 0.9548262912F, 0.9551077667F, 0.9553880459F, 0.9556671309F,
  151349. 0.9559450239F, 0.9562217272F, 0.9564972429F, 0.9567715733F,
  151350. 0.9570447206F, 0.9573166871F, 0.9575874749F, 0.9578570863F,
  151351. 0.9581255236F, 0.9583927890F, 0.9586588849F, 0.9589238134F,
  151352. 0.9591875769F, 0.9594501777F, 0.9597116180F, 0.9599719003F,
  151353. 0.9602310267F, 0.9604889995F, 0.9607458213F, 0.9610014942F,
  151354. 0.9612560206F, 0.9615094028F, 0.9617616433F, 0.9620127443F,
  151355. 0.9622627083F, 0.9625115376F, 0.9627592345F, 0.9630058016F,
  151356. 0.9632512411F, 0.9634955555F, 0.9637387471F, 0.9639808185F,
  151357. 0.9642217720F, 0.9644616100F, 0.9647003349F, 0.9649379493F,
  151358. 0.9651744556F, 0.9654098561F, 0.9656441534F, 0.9658773499F,
  151359. 0.9661094480F, 0.9663404504F, 0.9665703593F, 0.9667991774F,
  151360. 0.9670269071F, 0.9672535509F, 0.9674791114F, 0.9677035909F,
  151361. 0.9679269921F, 0.9681493174F, 0.9683705694F, 0.9685907506F,
  151362. 0.9688098636F, 0.9690279108F, 0.9692448948F, 0.9694608182F,
  151363. 0.9696756836F, 0.9698894934F, 0.9701022503F, 0.9703139569F,
  151364. 0.9705246156F, 0.9707342291F, 0.9709428000F, 0.9711503309F,
  151365. 0.9713568243F, 0.9715622829F, 0.9717667093F, 0.9719701060F,
  151366. 0.9721724757F, 0.9723738210F, 0.9725741446F, 0.9727734490F,
  151367. 0.9729717369F, 0.9731690109F, 0.9733652737F, 0.9735605279F,
  151368. 0.9737547762F, 0.9739480212F, 0.9741402656F, 0.9743315120F,
  151369. 0.9745217631F, 0.9747110216F, 0.9748992901F, 0.9750865714F,
  151370. 0.9752728681F, 0.9754581829F, 0.9756425184F, 0.9758258775F,
  151371. 0.9760082627F, 0.9761896768F, 0.9763701224F, 0.9765496024F,
  151372. 0.9767281193F, 0.9769056760F, 0.9770822751F, 0.9772579193F,
  151373. 0.9774326114F, 0.9776063542F, 0.9777791502F, 0.9779510023F,
  151374. 0.9781219133F, 0.9782918858F, 0.9784609226F, 0.9786290264F,
  151375. 0.9787962000F, 0.9789624461F, 0.9791277676F, 0.9792921671F,
  151376. 0.9794556474F, 0.9796182113F, 0.9797798615F, 0.9799406009F,
  151377. 0.9801004321F, 0.9802593580F, 0.9804173813F, 0.9805745049F,
  151378. 0.9807307314F, 0.9808860637F, 0.9810405046F, 0.9811940568F,
  151379. 0.9813467232F, 0.9814985065F, 0.9816494095F, 0.9817994351F,
  151380. 0.9819485860F, 0.9820968650F, 0.9822442750F, 0.9823908186F,
  151381. 0.9825364988F, 0.9826813184F, 0.9828252801F, 0.9829683868F,
  151382. 0.9831106413F, 0.9832520463F, 0.9833926048F, 0.9835323195F,
  151383. 0.9836711932F, 0.9838092288F, 0.9839464291F, 0.9840827969F,
  151384. 0.9842183351F, 0.9843530464F, 0.9844869337F, 0.9846199998F,
  151385. 0.9847522475F, 0.9848836798F, 0.9850142993F, 0.9851441090F,
  151386. 0.9852731117F, 0.9854013101F, 0.9855287073F, 0.9856553058F,
  151387. 0.9857811087F, 0.9859061188F, 0.9860303388F, 0.9861537717F,
  151388. 0.9862764202F, 0.9863982872F, 0.9865193756F, 0.9866396882F,
  151389. 0.9867592277F, 0.9868779972F, 0.9869959993F, 0.9871132370F,
  151390. 0.9872297131F, 0.9873454304F, 0.9874603918F, 0.9875746001F,
  151391. 0.9876880581F, 0.9878007688F, 0.9879127348F, 0.9880239592F,
  151392. 0.9881344447F, 0.9882441941F, 0.9883532104F, 0.9884614962F,
  151393. 0.9885690546F, 0.9886758883F, 0.9887820001F, 0.9888873930F,
  151394. 0.9889920697F, 0.9890960331F, 0.9891992859F, 0.9893018312F,
  151395. 0.9894036716F, 0.9895048100F, 0.9896052493F, 0.9897049923F,
  151396. 0.9898040418F, 0.9899024006F, 0.9900000717F, 0.9900970577F,
  151397. 0.9901933616F, 0.9902889862F, 0.9903839343F, 0.9904782087F,
  151398. 0.9905718122F, 0.9906647477F, 0.9907570180F, 0.9908486259F,
  151399. 0.9909395742F, 0.9910298658F, 0.9911195034F, 0.9912084899F,
  151400. 0.9912968281F, 0.9913845208F, 0.9914715708F, 0.9915579810F,
  151401. 0.9916437540F, 0.9917288928F, 0.9918134001F, 0.9918972788F,
  151402. 0.9919805316F, 0.9920631613F, 0.9921451707F, 0.9922265626F,
  151403. 0.9923073399F, 0.9923875052F, 0.9924670615F, 0.9925460114F,
  151404. 0.9926243577F, 0.9927021033F, 0.9927792508F, 0.9928558032F,
  151405. 0.9929317631F, 0.9930071333F, 0.9930819167F, 0.9931561158F,
  151406. 0.9932297337F, 0.9933027728F, 0.9933752362F, 0.9934471264F,
  151407. 0.9935184462F, 0.9935891985F, 0.9936593859F, 0.9937290112F,
  151408. 0.9937980771F, 0.9938665864F, 0.9939345418F, 0.9940019460F,
  151409. 0.9940688018F, 0.9941351118F, 0.9942008789F, 0.9942661057F,
  151410. 0.9943307950F, 0.9943949494F, 0.9944585717F, 0.9945216645F,
  151411. 0.9945842307F, 0.9946462728F, 0.9947077936F, 0.9947687957F,
  151412. 0.9948292820F, 0.9948892550F, 0.9949487174F, 0.9950076719F,
  151413. 0.9950661212F, 0.9951240679F, 0.9951815148F, 0.9952384645F,
  151414. 0.9952949196F, 0.9953508828F, 0.9954063568F, 0.9954613442F,
  151415. 0.9955158476F, 0.9955698697F, 0.9956234132F, 0.9956764806F,
  151416. 0.9957290746F, 0.9957811978F, 0.9958328528F, 0.9958840423F,
  151417. 0.9959347688F, 0.9959850351F, 0.9960348435F, 0.9960841969F,
  151418. 0.9961330977F, 0.9961815486F, 0.9962295521F, 0.9962771108F,
  151419. 0.9963242274F, 0.9963709043F, 0.9964171441F, 0.9964629494F,
  151420. 0.9965083228F, 0.9965532668F, 0.9965977840F, 0.9966418768F,
  151421. 0.9966855479F, 0.9967287998F, 0.9967716350F, 0.9968140559F,
  151422. 0.9968560653F, 0.9968976655F, 0.9969388591F, 0.9969796485F,
  151423. 0.9970200363F, 0.9970600250F, 0.9970996170F, 0.9971388149F,
  151424. 0.9971776211F, 0.9972160380F, 0.9972540683F, 0.9972917142F,
  151425. 0.9973289783F, 0.9973658631F, 0.9974023709F, 0.9974385042F,
  151426. 0.9974742655F, 0.9975096571F, 0.9975446816F, 0.9975793413F,
  151427. 0.9976136386F, 0.9976475759F, 0.9976811557F, 0.9977143803F,
  151428. 0.9977472521F, 0.9977797736F, 0.9978119470F, 0.9978437748F,
  151429. 0.9978752593F, 0.9979064029F, 0.9979372079F, 0.9979676768F,
  151430. 0.9979978117F, 0.9980276151F, 0.9980570893F, 0.9980862367F,
  151431. 0.9981150595F, 0.9981435600F, 0.9981717406F, 0.9981996035F,
  151432. 0.9982271511F, 0.9982543856F, 0.9982813093F, 0.9983079246F,
  151433. 0.9983342336F, 0.9983602386F, 0.9983859418F, 0.9984113456F,
  151434. 0.9984364522F, 0.9984612638F, 0.9984857825F, 0.9985100108F,
  151435. 0.9985339507F, 0.9985576044F, 0.9985809743F, 0.9986040624F,
  151436. 0.9986268710F, 0.9986494022F, 0.9986716583F, 0.9986936413F,
  151437. 0.9987153535F, 0.9987367969F, 0.9987579738F, 0.9987788864F,
  151438. 0.9987995366F, 0.9988199267F, 0.9988400587F, 0.9988599348F,
  151439. 0.9988795572F, 0.9988989278F, 0.9989180487F, 0.9989369222F,
  151440. 0.9989555501F, 0.9989739347F, 0.9989920780F, 0.9990099820F,
  151441. 0.9990276487F, 0.9990450803F, 0.9990622787F, 0.9990792460F,
  151442. 0.9990959841F, 0.9991124952F, 0.9991287812F, 0.9991448440F,
  151443. 0.9991606858F, 0.9991763084F, 0.9991917139F, 0.9992069042F,
  151444. 0.9992218813F, 0.9992366471F, 0.9992512035F, 0.9992655525F,
  151445. 0.9992796961F, 0.9992936361F, 0.9993073744F, 0.9993209131F,
  151446. 0.9993342538F, 0.9993473987F, 0.9993603494F, 0.9993731080F,
  151447. 0.9993856762F, 0.9993980559F, 0.9994102490F, 0.9994222573F,
  151448. 0.9994340827F, 0.9994457269F, 0.9994571918F, 0.9994684793F,
  151449. 0.9994795910F, 0.9994905288F, 0.9995012945F, 0.9995118898F,
  151450. 0.9995223165F, 0.9995325765F, 0.9995426713F, 0.9995526029F,
  151451. 0.9995623728F, 0.9995719829F, 0.9995814349F, 0.9995907304F,
  151452. 0.9995998712F, 0.9996088590F, 0.9996176954F, 0.9996263821F,
  151453. 0.9996349208F, 0.9996433132F, 0.9996515609F, 0.9996596656F,
  151454. 0.9996676288F, 0.9996754522F, 0.9996831375F, 0.9996906862F,
  151455. 0.9996981000F, 0.9997053804F, 0.9997125290F, 0.9997195474F,
  151456. 0.9997264371F, 0.9997331998F, 0.9997398369F, 0.9997463500F,
  151457. 0.9997527406F, 0.9997590103F, 0.9997651606F, 0.9997711930F,
  151458. 0.9997771089F, 0.9997829098F, 0.9997885973F, 0.9997941728F,
  151459. 0.9997996378F, 0.9998049936F, 0.9998102419F, 0.9998153839F,
  151460. 0.9998204211F, 0.9998253550F, 0.9998301868F, 0.9998349182F,
  151461. 0.9998395503F, 0.9998440847F, 0.9998485226F, 0.9998528654F,
  151462. 0.9998571146F, 0.9998612713F, 0.9998653370F, 0.9998693130F,
  151463. 0.9998732007F, 0.9998770012F, 0.9998807159F, 0.9998843461F,
  151464. 0.9998878931F, 0.9998913581F, 0.9998947424F, 0.9998980473F,
  151465. 0.9999012740F, 0.9999044237F, 0.9999074976F, 0.9999104971F,
  151466. 0.9999134231F, 0.9999162771F, 0.9999190601F, 0.9999217733F,
  151467. 0.9999244179F, 0.9999269950F, 0.9999295058F, 0.9999319515F,
  151468. 0.9999343332F, 0.9999366519F, 0.9999389088F, 0.9999411050F,
  151469. 0.9999432416F, 0.9999453196F, 0.9999473402F, 0.9999493044F,
  151470. 0.9999512132F, 0.9999530677F, 0.9999548690F, 0.9999566180F,
  151471. 0.9999583157F, 0.9999599633F, 0.9999615616F, 0.9999631116F,
  151472. 0.9999646144F, 0.9999660709F, 0.9999674820F, 0.9999688487F,
  151473. 0.9999701719F, 0.9999714526F, 0.9999726917F, 0.9999738900F,
  151474. 0.9999750486F, 0.9999761682F, 0.9999772497F, 0.9999782941F,
  151475. 0.9999793021F, 0.9999802747F, 0.9999812126F, 0.9999821167F,
  151476. 0.9999829878F, 0.9999838268F, 0.9999846343F, 0.9999854113F,
  151477. 0.9999861584F, 0.9999868765F, 0.9999875664F, 0.9999882287F,
  151478. 0.9999888642F, 0.9999894736F, 0.9999900577F, 0.9999906172F,
  151479. 0.9999911528F, 0.9999916651F, 0.9999921548F, 0.9999926227F,
  151480. 0.9999930693F, 0.9999934954F, 0.9999939015F, 0.9999942883F,
  151481. 0.9999946564F, 0.9999950064F, 0.9999953390F, 0.9999956547F,
  151482. 0.9999959541F, 0.9999962377F, 0.9999965062F, 0.9999967601F,
  151483. 0.9999969998F, 0.9999972260F, 0.9999974392F, 0.9999976399F,
  151484. 0.9999978285F, 0.9999980056F, 0.9999981716F, 0.9999983271F,
  151485. 0.9999984724F, 0.9999986081F, 0.9999987345F, 0.9999988521F,
  151486. 0.9999989613F, 0.9999990625F, 0.9999991562F, 0.9999992426F,
  151487. 0.9999993223F, 0.9999993954F, 0.9999994625F, 0.9999995239F,
  151488. 0.9999995798F, 0.9999996307F, 0.9999996768F, 0.9999997184F,
  151489. 0.9999997559F, 0.9999997895F, 0.9999998195F, 0.9999998462F,
  151490. 0.9999998698F, 0.9999998906F, 0.9999999088F, 0.9999999246F,
  151491. 0.9999999383F, 0.9999999500F, 0.9999999600F, 0.9999999684F,
  151492. 0.9999999754F, 0.9999999811F, 0.9999999858F, 0.9999999896F,
  151493. 0.9999999925F, 0.9999999948F, 0.9999999965F, 0.9999999978F,
  151494. 0.9999999986F, 0.9999999992F, 0.9999999996F, 0.9999999998F,
  151495. 0.9999999999F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  151496. };
  151497. static float vwin8192[4096] = {
  151498. 0.0000000578F, 0.0000005198F, 0.0000014438F, 0.0000028299F,
  151499. 0.0000046780F, 0.0000069882F, 0.0000097604F, 0.0000129945F,
  151500. 0.0000166908F, 0.0000208490F, 0.0000254692F, 0.0000305515F,
  151501. 0.0000360958F, 0.0000421021F, 0.0000485704F, 0.0000555006F,
  151502. 0.0000628929F, 0.0000707472F, 0.0000790635F, 0.0000878417F,
  151503. 0.0000970820F, 0.0001067842F, 0.0001169483F, 0.0001275744F,
  151504. 0.0001386625F, 0.0001502126F, 0.0001622245F, 0.0001746984F,
  151505. 0.0001876343F, 0.0002010320F, 0.0002148917F, 0.0002292132F,
  151506. 0.0002439967F, 0.0002592421F, 0.0002749493F, 0.0002911184F,
  151507. 0.0003077493F, 0.0003248421F, 0.0003423967F, 0.0003604132F,
  151508. 0.0003788915F, 0.0003978316F, 0.0004172335F, 0.0004370971F,
  151509. 0.0004574226F, 0.0004782098F, 0.0004994587F, 0.0005211694F,
  151510. 0.0005433418F, 0.0005659759F, 0.0005890717F, 0.0006126292F,
  151511. 0.0006366484F, 0.0006611292F, 0.0006860716F, 0.0007114757F,
  151512. 0.0007373414F, 0.0007636687F, 0.0007904576F, 0.0008177080F,
  151513. 0.0008454200F, 0.0008735935F, 0.0009022285F, 0.0009313250F,
  151514. 0.0009608830F, 0.0009909025F, 0.0010213834F, 0.0010523257F,
  151515. 0.0010837295F, 0.0011155946F, 0.0011479211F, 0.0011807090F,
  151516. 0.0012139582F, 0.0012476687F, 0.0012818405F, 0.0013164736F,
  151517. 0.0013515679F, 0.0013871235F, 0.0014231402F, 0.0014596182F,
  151518. 0.0014965573F, 0.0015339576F, 0.0015718190F, 0.0016101415F,
  151519. 0.0016489251F, 0.0016881698F, 0.0017278754F, 0.0017680421F,
  151520. 0.0018086698F, 0.0018497584F, 0.0018913080F, 0.0019333185F,
  151521. 0.0019757898F, 0.0020187221F, 0.0020621151F, 0.0021059690F,
  151522. 0.0021502837F, 0.0021950591F, 0.0022402953F, 0.0022859921F,
  151523. 0.0023321497F, 0.0023787679F, 0.0024258467F, 0.0024733861F,
  151524. 0.0025213861F, 0.0025698466F, 0.0026187676F, 0.0026681491F,
  151525. 0.0027179911F, 0.0027682935F, 0.0028190562F, 0.0028702794F,
  151526. 0.0029219628F, 0.0029741066F, 0.0030267107F, 0.0030797749F,
  151527. 0.0031332994F, 0.0031872841F, 0.0032417289F, 0.0032966338F,
  151528. 0.0033519988F, 0.0034078238F, 0.0034641089F, 0.0035208539F,
  151529. 0.0035780589F, 0.0036357237F, 0.0036938485F, 0.0037524331F,
  151530. 0.0038114775F, 0.0038709817F, 0.0039309456F, 0.0039913692F,
  151531. 0.0040522524F, 0.0041135953F, 0.0041753978F, 0.0042376599F,
  151532. 0.0043003814F, 0.0043635624F, 0.0044272029F, 0.0044913028F,
  151533. 0.0045558620F, 0.0046208806F, 0.0046863585F, 0.0047522955F,
  151534. 0.0048186919F, 0.0048855473F, 0.0049528619F, 0.0050206356F,
  151535. 0.0050888684F, 0.0051575601F, 0.0052267108F, 0.0052963204F,
  151536. 0.0053663890F, 0.0054369163F, 0.0055079025F, 0.0055793474F,
  151537. 0.0056512510F, 0.0057236133F, 0.0057964342F, 0.0058697137F,
  151538. 0.0059434517F, 0.0060176482F, 0.0060923032F, 0.0061674166F,
  151539. 0.0062429883F, 0.0063190183F, 0.0063955066F, 0.0064724532F,
  151540. 0.0065498579F, 0.0066277207F, 0.0067060416F, 0.0067848205F,
  151541. 0.0068640575F, 0.0069437523F, 0.0070239051F, 0.0071045157F,
  151542. 0.0071855840F, 0.0072671102F, 0.0073490940F, 0.0074315355F,
  151543. 0.0075144345F, 0.0075977911F, 0.0076816052F, 0.0077658768F,
  151544. 0.0078506057F, 0.0079357920F, 0.0080214355F, 0.0081075363F,
  151545. 0.0081940943F, 0.0082811094F, 0.0083685816F, 0.0084565108F,
  151546. 0.0085448970F, 0.0086337401F, 0.0087230401F, 0.0088127969F,
  151547. 0.0089030104F, 0.0089936807F, 0.0090848076F, 0.0091763911F,
  151548. 0.0092684311F, 0.0093609276F, 0.0094538805F, 0.0095472898F,
  151549. 0.0096411554F, 0.0097354772F, 0.0098302552F, 0.0099254894F,
  151550. 0.0100211796F, 0.0101173259F, 0.0102139281F, 0.0103109863F,
  151551. 0.0104085002F, 0.0105064700F, 0.0106048955F, 0.0107037766F,
  151552. 0.0108031133F, 0.0109029056F, 0.0110031534F, 0.0111038565F,
  151553. 0.0112050151F, 0.0113066289F, 0.0114086980F, 0.0115112222F,
  151554. 0.0116142015F, 0.0117176359F, 0.0118215252F, 0.0119258695F,
  151555. 0.0120306686F, 0.0121359225F, 0.0122416312F, 0.0123477944F,
  151556. 0.0124544123F, 0.0125614847F, 0.0126690116F, 0.0127769928F,
  151557. 0.0128854284F, 0.0129943182F, 0.0131036623F, 0.0132134604F,
  151558. 0.0133237126F, 0.0134344188F, 0.0135455790F, 0.0136571929F,
  151559. 0.0137692607F, 0.0138817821F, 0.0139947572F, 0.0141081859F,
  151560. 0.0142220681F, 0.0143364037F, 0.0144511927F, 0.0145664350F,
  151561. 0.0146821304F, 0.0147982791F, 0.0149148808F, 0.0150319355F,
  151562. 0.0151494431F, 0.0152674036F, 0.0153858168F, 0.0155046828F,
  151563. 0.0156240014F, 0.0157437726F, 0.0158639962F, 0.0159846723F,
  151564. 0.0161058007F, 0.0162273814F, 0.0163494142F, 0.0164718991F,
  151565. 0.0165948361F, 0.0167182250F, 0.0168420658F, 0.0169663584F,
  151566. 0.0170911027F, 0.0172162987F, 0.0173419462F, 0.0174680452F,
  151567. 0.0175945956F, 0.0177215974F, 0.0178490504F, 0.0179769545F,
  151568. 0.0181053098F, 0.0182341160F, 0.0183633732F, 0.0184930812F,
  151569. 0.0186232399F, 0.0187538494F, 0.0188849094F, 0.0190164200F,
  151570. 0.0191483809F, 0.0192807923F, 0.0194136539F, 0.0195469656F,
  151571. 0.0196807275F, 0.0198149394F, 0.0199496012F, 0.0200847128F,
  151572. 0.0202202742F, 0.0203562853F, 0.0204927460F, 0.0206296561F,
  151573. 0.0207670157F, 0.0209048245F, 0.0210430826F, 0.0211817899F,
  151574. 0.0213209462F, 0.0214605515F, 0.0216006057F, 0.0217411086F,
  151575. 0.0218820603F, 0.0220234605F, 0.0221653093F, 0.0223076066F,
  151576. 0.0224503521F, 0.0225935459F, 0.0227371879F, 0.0228812779F,
  151577. 0.0230258160F, 0.0231708018F, 0.0233162355F, 0.0234621169F,
  151578. 0.0236084459F, 0.0237552224F, 0.0239024462F, 0.0240501175F,
  151579. 0.0241982359F, 0.0243468015F, 0.0244958141F, 0.0246452736F,
  151580. 0.0247951800F, 0.0249455331F, 0.0250963329F, 0.0252475792F,
  151581. 0.0253992720F, 0.0255514111F, 0.0257039965F, 0.0258570281F,
  151582. 0.0260105057F, 0.0261644293F, 0.0263187987F, 0.0264736139F,
  151583. 0.0266288747F, 0.0267845811F, 0.0269407330F, 0.0270973302F,
  151584. 0.0272543727F, 0.0274118604F, 0.0275697930F, 0.0277281707F,
  151585. 0.0278869932F, 0.0280462604F, 0.0282059723F, 0.0283661287F,
  151586. 0.0285267295F, 0.0286877747F, 0.0288492641F, 0.0290111976F,
  151587. 0.0291735751F, 0.0293363965F, 0.0294996617F, 0.0296633706F,
  151588. 0.0298275231F, 0.0299921190F, 0.0301571583F, 0.0303226409F,
  151589. 0.0304885667F, 0.0306549354F, 0.0308217472F, 0.0309890017F,
  151590. 0.0311566989F, 0.0313248388F, 0.0314934211F, 0.0316624459F,
  151591. 0.0318319128F, 0.0320018220F, 0.0321721732F, 0.0323429663F,
  151592. 0.0325142013F, 0.0326858779F, 0.0328579962F, 0.0330305559F,
  151593. 0.0332035570F, 0.0333769994F, 0.0335508829F, 0.0337252074F,
  151594. 0.0338999728F, 0.0340751790F, 0.0342508259F, 0.0344269134F,
  151595. 0.0346034412F, 0.0347804094F, 0.0349578178F, 0.0351356663F,
  151596. 0.0353139548F, 0.0354926831F, 0.0356718511F, 0.0358514588F,
  151597. 0.0360315059F, 0.0362119924F, 0.0363929182F, 0.0365742831F,
  151598. 0.0367560870F, 0.0369383297F, 0.0371210113F, 0.0373041315F,
  151599. 0.0374876902F, 0.0376716873F, 0.0378561226F, 0.0380409961F,
  151600. 0.0382263077F, 0.0384120571F, 0.0385982443F, 0.0387848691F,
  151601. 0.0389719315F, 0.0391594313F, 0.0393473683F, 0.0395357425F,
  151602. 0.0397245537F, 0.0399138017F, 0.0401034866F, 0.0402936080F,
  151603. 0.0404841660F, 0.0406751603F, 0.0408665909F, 0.0410584576F,
  151604. 0.0412507603F, 0.0414434988F, 0.0416366731F, 0.0418302829F,
  151605. 0.0420243282F, 0.0422188088F, 0.0424137246F, 0.0426090755F,
  151606. 0.0428048613F, 0.0430010819F, 0.0431977371F, 0.0433948269F,
  151607. 0.0435923511F, 0.0437903095F, 0.0439887020F, 0.0441875285F,
  151608. 0.0443867889F, 0.0445864830F, 0.0447866106F, 0.0449871717F,
  151609. 0.0451881661F, 0.0453895936F, 0.0455914542F, 0.0457937477F,
  151610. 0.0459964738F, 0.0461996326F, 0.0464032239F, 0.0466072475F,
  151611. 0.0468117032F, 0.0470165910F, 0.0472219107F, 0.0474276622F,
  151612. 0.0476338452F, 0.0478404597F, 0.0480475056F, 0.0482549827F,
  151613. 0.0484628907F, 0.0486712297F, 0.0488799994F, 0.0490891998F,
  151614. 0.0492988306F, 0.0495088917F, 0.0497193830F, 0.0499303043F,
  151615. 0.0501416554F, 0.0503534363F, 0.0505656468F, 0.0507782867F,
  151616. 0.0509913559F, 0.0512048542F, 0.0514187815F, 0.0516331376F,
  151617. 0.0518479225F, 0.0520631358F, 0.0522787775F, 0.0524948475F,
  151618. 0.0527113455F, 0.0529282715F, 0.0531456252F, 0.0533634066F,
  151619. 0.0535816154F, 0.0538002515F, 0.0540193148F, 0.0542388051F,
  151620. 0.0544587222F, 0.0546790660F, 0.0548998364F, 0.0551210331F,
  151621. 0.0553426561F, 0.0555647051F, 0.0557871801F, 0.0560100807F,
  151622. 0.0562334070F, 0.0564571587F, 0.0566813357F, 0.0569059378F,
  151623. 0.0571309649F, 0.0573564168F, 0.0575822933F, 0.0578085942F,
  151624. 0.0580353195F, 0.0582624689F, 0.0584900423F, 0.0587180396F,
  151625. 0.0589464605F, 0.0591753049F, 0.0594045726F, 0.0596342635F,
  151626. 0.0598643774F, 0.0600949141F, 0.0603258735F, 0.0605572555F,
  151627. 0.0607890597F, 0.0610212862F, 0.0612539346F, 0.0614870049F,
  151628. 0.0617204968F, 0.0619544103F, 0.0621887451F, 0.0624235010F,
  151629. 0.0626586780F, 0.0628942758F, 0.0631302942F, 0.0633667331F,
  151630. 0.0636035923F, 0.0638408717F, 0.0640785710F, 0.0643166901F,
  151631. 0.0645552288F, 0.0647941870F, 0.0650335645F, 0.0652733610F,
  151632. 0.0655135765F, 0.0657542108F, 0.0659952636F, 0.0662367348F,
  151633. 0.0664786242F, 0.0667209316F, 0.0669636570F, 0.0672068000F,
  151634. 0.0674503605F, 0.0676943384F, 0.0679387334F, 0.0681835454F,
  151635. 0.0684287742F, 0.0686744196F, 0.0689204814F, 0.0691669595F,
  151636. 0.0694138536F, 0.0696611637F, 0.0699088894F, 0.0701570307F,
  151637. 0.0704055873F, 0.0706545590F, 0.0709039458F, 0.0711537473F,
  151638. 0.0714039634F, 0.0716545939F, 0.0719056387F, 0.0721570975F,
  151639. 0.0724089702F, 0.0726612565F, 0.0729139563F, 0.0731670694F,
  151640. 0.0734205956F, 0.0736745347F, 0.0739288866F, 0.0741836510F,
  151641. 0.0744388277F, 0.0746944166F, 0.0749504175F, 0.0752068301F,
  151642. 0.0754636543F, 0.0757208899F, 0.0759785367F, 0.0762365946F,
  151643. 0.0764950632F, 0.0767539424F, 0.0770132320F, 0.0772729319F,
  151644. 0.0775330418F, 0.0777935616F, 0.0780544909F, 0.0783158298F,
  151645. 0.0785775778F, 0.0788397349F, 0.0791023009F, 0.0793652755F,
  151646. 0.0796286585F, 0.0798924498F, 0.0801566492F, 0.0804212564F,
  151647. 0.0806862712F, 0.0809516935F, 0.0812175231F, 0.0814837597F,
  151648. 0.0817504031F, 0.0820174532F, 0.0822849097F, 0.0825527724F,
  151649. 0.0828210412F, 0.0830897158F, 0.0833587960F, 0.0836282816F,
  151650. 0.0838981724F, 0.0841684682F, 0.0844391688F, 0.0847102740F,
  151651. 0.0849817835F, 0.0852536973F, 0.0855260150F, 0.0857987364F,
  151652. 0.0860718614F, 0.0863453897F, 0.0866193211F, 0.0868936554F,
  151653. 0.0871683924F, 0.0874435319F, 0.0877190737F, 0.0879950175F,
  151654. 0.0882713632F, 0.0885481105F, 0.0888252592F, 0.0891028091F,
  151655. 0.0893807600F, 0.0896591117F, 0.0899378639F, 0.0902170165F,
  151656. 0.0904965692F, 0.0907765218F, 0.0910568740F, 0.0913376258F,
  151657. 0.0916187767F, 0.0919003268F, 0.0921822756F, 0.0924646230F,
  151658. 0.0927473687F, 0.0930305126F, 0.0933140545F, 0.0935979940F,
  151659. 0.0938823310F, 0.0941670653F, 0.0944521966F, 0.0947377247F,
  151660. 0.0950236494F, 0.0953099704F, 0.0955966876F, 0.0958838007F,
  151661. 0.0961713094F, 0.0964592136F, 0.0967475131F, 0.0970362075F,
  151662. 0.0973252967F, 0.0976147805F, 0.0979046585F, 0.0981949307F,
  151663. 0.0984855967F, 0.0987766563F, 0.0990681093F, 0.0993599555F,
  151664. 0.0996521945F, 0.0999448263F, 0.1002378506F, 0.1005312671F,
  151665. 0.1008250755F, 0.1011192757F, 0.1014138675F, 0.1017088505F,
  151666. 0.1020042246F, 0.1022999895F, 0.1025961450F, 0.1028926909F,
  151667. 0.1031896268F, 0.1034869526F, 0.1037846680F, 0.1040827729F,
  151668. 0.1043812668F, 0.1046801497F, 0.1049794213F, 0.1052790813F,
  151669. 0.1055791294F, 0.1058795656F, 0.1061803894F, 0.1064816006F,
  151670. 0.1067831991F, 0.1070851846F, 0.1073875568F, 0.1076903155F,
  151671. 0.1079934604F, 0.1082969913F, 0.1086009079F, 0.1089052101F,
  151672. 0.1092098975F, 0.1095149699F, 0.1098204270F, 0.1101262687F,
  151673. 0.1104324946F, 0.1107391045F, 0.1110460982F, 0.1113534754F,
  151674. 0.1116612359F, 0.1119693793F, 0.1122779055F, 0.1125868142F,
  151675. 0.1128961052F, 0.1132057781F, 0.1135158328F, 0.1138262690F,
  151676. 0.1141370863F, 0.1144482847F, 0.1147598638F, 0.1150718233F,
  151677. 0.1153841631F, 0.1156968828F, 0.1160099822F, 0.1163234610F,
  151678. 0.1166373190F, 0.1169515559F, 0.1172661714F, 0.1175811654F,
  151679. 0.1178965374F, 0.1182122874F, 0.1185284149F, 0.1188449198F,
  151680. 0.1191618018F, 0.1194790606F, 0.1197966960F, 0.1201147076F,
  151681. 0.1204330953F, 0.1207518587F, 0.1210709976F, 0.1213905118F,
  151682. 0.1217104009F, 0.1220306647F, 0.1223513029F, 0.1226723153F,
  151683. 0.1229937016F, 0.1233154615F, 0.1236375948F, 0.1239601011F,
  151684. 0.1242829803F, 0.1246062319F, 0.1249298559F, 0.1252538518F,
  151685. 0.1255782195F, 0.1259029586F, 0.1262280689F, 0.1265535501F,
  151686. 0.1268794019F, 0.1272056241F, 0.1275322163F, 0.1278591784F,
  151687. 0.1281865099F, 0.1285142108F, 0.1288422805F, 0.1291707190F,
  151688. 0.1294995259F, 0.1298287009F, 0.1301582437F, 0.1304881542F,
  151689. 0.1308184319F, 0.1311490766F, 0.1314800881F, 0.1318114660F,
  151690. 0.1321432100F, 0.1324753200F, 0.1328077955F, 0.1331406364F,
  151691. 0.1334738422F, 0.1338074129F, 0.1341413479F, 0.1344756472F,
  151692. 0.1348103103F, 0.1351453370F, 0.1354807270F, 0.1358164801F,
  151693. 0.1361525959F, 0.1364890741F, 0.1368259145F, 0.1371631167F,
  151694. 0.1375006805F, 0.1378386056F, 0.1381768917F, 0.1385155384F,
  151695. 0.1388545456F, 0.1391939129F, 0.1395336400F, 0.1398737266F,
  151696. 0.1402141724F, 0.1405549772F, 0.1408961406F, 0.1412376623F,
  151697. 0.1415795421F, 0.1419217797F, 0.1422643746F, 0.1426073268F,
  151698. 0.1429506358F, 0.1432943013F, 0.1436383231F, 0.1439827008F,
  151699. 0.1443274342F, 0.1446725229F, 0.1450179667F, 0.1453637652F,
  151700. 0.1457099181F, 0.1460564252F, 0.1464032861F, 0.1467505006F,
  151701. 0.1470980682F, 0.1474459888F, 0.1477942620F, 0.1481428875F,
  151702. 0.1484918651F, 0.1488411942F, 0.1491908748F, 0.1495409065F,
  151703. 0.1498912889F, 0.1502420218F, 0.1505931048F, 0.1509445376F,
  151704. 0.1512963200F, 0.1516484516F, 0.1520009321F, 0.1523537612F,
  151705. 0.1527069385F, 0.1530604638F, 0.1534143368F, 0.1537685571F,
  151706. 0.1541231244F, 0.1544780384F, 0.1548332987F, 0.1551889052F,
  151707. 0.1555448574F, 0.1559011550F, 0.1562577978F, 0.1566147853F,
  151708. 0.1569721173F, 0.1573297935F, 0.1576878135F, 0.1580461771F,
  151709. 0.1584048838F, 0.1587639334F, 0.1591233255F, 0.1594830599F,
  151710. 0.1598431361F, 0.1602035540F, 0.1605643131F, 0.1609254131F,
  151711. 0.1612868537F, 0.1616486346F, 0.1620107555F, 0.1623732160F,
  151712. 0.1627360158F, 0.1630991545F, 0.1634626319F, 0.1638264476F,
  151713. 0.1641906013F, 0.1645550926F, 0.1649199212F, 0.1652850869F,
  151714. 0.1656505892F, 0.1660164278F, 0.1663826024F, 0.1667491127F,
  151715. 0.1671159583F, 0.1674831388F, 0.1678506541F, 0.1682185036F,
  151716. 0.1685866872F, 0.1689552044F, 0.1693240549F, 0.1696932384F,
  151717. 0.1700627545F, 0.1704326029F, 0.1708027833F, 0.1711732952F,
  151718. 0.1715441385F, 0.1719153127F, 0.1722868175F, 0.1726586526F,
  151719. 0.1730308176F, 0.1734033121F, 0.1737761359F, 0.1741492886F,
  151720. 0.1745227698F, 0.1748965792F, 0.1752707164F, 0.1756451812F,
  151721. 0.1760199731F, 0.1763950918F, 0.1767705370F, 0.1771463083F,
  151722. 0.1775224054F, 0.1778988279F, 0.1782755754F, 0.1786526477F,
  151723. 0.1790300444F, 0.1794077651F, 0.1797858094F, 0.1801641771F,
  151724. 0.1805428677F, 0.1809218810F, 0.1813012165F, 0.1816808739F,
  151725. 0.1820608528F, 0.1824411530F, 0.1828217739F, 0.1832027154F,
  151726. 0.1835839770F, 0.1839655584F, 0.1843474592F, 0.1847296790F,
  151727. 0.1851122175F, 0.1854950744F, 0.1858782492F, 0.1862617417F,
  151728. 0.1866455514F, 0.1870296780F, 0.1874141211F, 0.1877988804F,
  151729. 0.1881839555F, 0.1885693461F, 0.1889550517F, 0.1893410721F,
  151730. 0.1897274068F, 0.1901140555F, 0.1905010178F, 0.1908882933F,
  151731. 0.1912758818F, 0.1916637828F, 0.1920519959F, 0.1924405208F,
  151732. 0.1928293571F, 0.1932185044F, 0.1936079625F, 0.1939977308F,
  151733. 0.1943878091F, 0.1947781969F, 0.1951688939F, 0.1955598998F,
  151734. 0.1959512141F, 0.1963428364F, 0.1967347665F, 0.1971270038F,
  151735. 0.1975195482F, 0.1979123990F, 0.1983055561F, 0.1986990190F,
  151736. 0.1990927873F, 0.1994868607F, 0.1998812388F, 0.2002759212F,
  151737. 0.2006709075F, 0.2010661974F, 0.2014617904F, 0.2018576862F,
  151738. 0.2022538844F, 0.2026503847F, 0.2030471865F, 0.2034442897F,
  151739. 0.2038416937F, 0.2042393982F, 0.2046374028F, 0.2050357071F,
  151740. 0.2054343107F, 0.2058332133F, 0.2062324145F, 0.2066319138F,
  151741. 0.2070317110F, 0.2074318055F, 0.2078321970F, 0.2082328852F,
  151742. 0.2086338696F, 0.2090351498F, 0.2094367255F, 0.2098385962F,
  151743. 0.2102407617F, 0.2106432213F, 0.2110459749F, 0.2114490220F,
  151744. 0.2118523621F, 0.2122559950F, 0.2126599202F, 0.2130641373F,
  151745. 0.2134686459F, 0.2138734456F, 0.2142785361F, 0.2146839168F,
  151746. 0.2150895875F, 0.2154955478F, 0.2159017972F, 0.2163083353F,
  151747. 0.2167151617F, 0.2171222761F, 0.2175296780F, 0.2179373670F,
  151748. 0.2183453428F, 0.2187536049F, 0.2191621529F, 0.2195709864F,
  151749. 0.2199801051F, 0.2203895085F, 0.2207991961F, 0.2212091677F,
  151750. 0.2216194228F, 0.2220299610F, 0.2224407818F, 0.2228518850F,
  151751. 0.2232632699F, 0.2236749364F, 0.2240868839F, 0.2244991121F,
  151752. 0.2249116204F, 0.2253244086F, 0.2257374763F, 0.2261508229F,
  151753. 0.2265644481F, 0.2269783514F, 0.2273925326F, 0.2278069911F,
  151754. 0.2282217265F, 0.2286367384F, 0.2290520265F, 0.2294675902F,
  151755. 0.2298834292F, 0.2302995431F, 0.2307159314F, 0.2311325937F,
  151756. 0.2315495297F, 0.2319667388F, 0.2323842207F, 0.2328019749F,
  151757. 0.2332200011F, 0.2336382988F, 0.2340568675F, 0.2344757070F,
  151758. 0.2348948166F, 0.2353141961F, 0.2357338450F, 0.2361537629F,
  151759. 0.2365739493F, 0.2369944038F, 0.2374151261F, 0.2378361156F,
  151760. 0.2382573720F, 0.2386788948F, 0.2391006836F, 0.2395227380F,
  151761. 0.2399450575F, 0.2403676417F, 0.2407904902F, 0.2412136026F,
  151762. 0.2416369783F, 0.2420606171F, 0.2424845185F, 0.2429086820F,
  151763. 0.2433331072F, 0.2437577936F, 0.2441827409F, 0.2446079486F,
  151764. 0.2450334163F, 0.2454591435F, 0.2458851298F, 0.2463113747F,
  151765. 0.2467378779F, 0.2471646389F, 0.2475916573F, 0.2480189325F,
  151766. 0.2484464643F, 0.2488742521F, 0.2493022955F, 0.2497305940F,
  151767. 0.2501591473F, 0.2505879549F, 0.2510170163F, 0.2514463311F,
  151768. 0.2518758989F, 0.2523057193F, 0.2527357916F, 0.2531661157F,
  151769. 0.2535966909F, 0.2540275169F, 0.2544585931F, 0.2548899193F,
  151770. 0.2553214948F, 0.2557533193F, 0.2561853924F, 0.2566177135F,
  151771. 0.2570502822F, 0.2574830981F, 0.2579161608F, 0.2583494697F,
  151772. 0.2587830245F, 0.2592168246F, 0.2596508697F, 0.2600851593F,
  151773. 0.2605196929F, 0.2609544701F, 0.2613894904F, 0.2618247534F,
  151774. 0.2622602586F, 0.2626960055F, 0.2631319938F, 0.2635682230F,
  151775. 0.2640046925F, 0.2644414021F, 0.2648783511F, 0.2653155391F,
  151776. 0.2657529657F, 0.2661906305F, 0.2666285329F, 0.2670666725F,
  151777. 0.2675050489F, 0.2679436616F, 0.2683825101F, 0.2688215940F,
  151778. 0.2692609127F, 0.2697004660F, 0.2701402532F, 0.2705802739F,
  151779. 0.2710205278F, 0.2714610142F, 0.2719017327F, 0.2723426830F,
  151780. 0.2727838644F, 0.2732252766F, 0.2736669191F, 0.2741087914F,
  151781. 0.2745508930F, 0.2749932235F, 0.2754357824F, 0.2758785693F,
  151782. 0.2763215837F, 0.2767648251F, 0.2772082930F, 0.2776519870F,
  151783. 0.2780959066F, 0.2785400513F, 0.2789844207F, 0.2794290143F,
  151784. 0.2798738316F, 0.2803188722F, 0.2807641355F, 0.2812096211F,
  151785. 0.2816553286F, 0.2821012574F, 0.2825474071F, 0.2829937773F,
  151786. 0.2834403673F, 0.2838871768F, 0.2843342053F, 0.2847814523F,
  151787. 0.2852289174F, 0.2856765999F, 0.2861244996F, 0.2865726159F,
  151788. 0.2870209482F, 0.2874694962F, 0.2879182594F, 0.2883672372F,
  151789. 0.2888164293F, 0.2892658350F, 0.2897154540F, 0.2901652858F,
  151790. 0.2906153298F, 0.2910655856F, 0.2915160527F, 0.2919667306F,
  151791. 0.2924176189F, 0.2928687171F, 0.2933200246F, 0.2937715409F,
  151792. 0.2942232657F, 0.2946751984F, 0.2951273386F, 0.2955796856F,
  151793. 0.2960322391F, 0.2964849986F, 0.2969379636F, 0.2973911335F,
  151794. 0.2978445080F, 0.2982980864F, 0.2987518684F, 0.2992058534F,
  151795. 0.2996600409F, 0.3001144305F, 0.3005690217F, 0.3010238139F,
  151796. 0.3014788067F, 0.3019339995F, 0.3023893920F, 0.3028449835F,
  151797. 0.3033007736F, 0.3037567618F, 0.3042129477F, 0.3046693306F,
  151798. 0.3051259102F, 0.3055826859F, 0.3060396572F, 0.3064968236F,
  151799. 0.3069541847F, 0.3074117399F, 0.3078694887F, 0.3083274307F,
  151800. 0.3087855653F, 0.3092438920F, 0.3097024104F, 0.3101611199F,
  151801. 0.3106200200F, 0.3110791103F, 0.3115383902F, 0.3119978592F,
  151802. 0.3124575169F, 0.3129173627F, 0.3133773961F, 0.3138376166F,
  151803. 0.3142980238F, 0.3147586170F, 0.3152193959F, 0.3156803598F,
  151804. 0.3161415084F, 0.3166028410F, 0.3170643573F, 0.3175260566F,
  151805. 0.3179879384F, 0.3184500023F, 0.3189122478F, 0.3193746743F,
  151806. 0.3198372814F, 0.3203000685F, 0.3207630351F, 0.3212261807F,
  151807. 0.3216895048F, 0.3221530069F, 0.3226166865F, 0.3230805430F,
  151808. 0.3235445760F, 0.3240087849F, 0.3244731693F, 0.3249377285F,
  151809. 0.3254024622F, 0.3258673698F, 0.3263324507F, 0.3267977045F,
  151810. 0.3272631306F, 0.3277287286F, 0.3281944978F, 0.3286604379F,
  151811. 0.3291265482F, 0.3295928284F, 0.3300592777F, 0.3305258958F,
  151812. 0.3309926821F, 0.3314596361F, 0.3319267573F, 0.3323940451F,
  151813. 0.3328614990F, 0.3333291186F, 0.3337969033F, 0.3342648525F,
  151814. 0.3347329658F, 0.3352012427F, 0.3356696825F, 0.3361382849F,
  151815. 0.3366070492F, 0.3370759749F, 0.3375450616F, 0.3380143087F,
  151816. 0.3384837156F, 0.3389532819F, 0.3394230071F, 0.3398928905F,
  151817. 0.3403629317F, 0.3408331302F, 0.3413034854F, 0.3417739967F,
  151818. 0.3422446638F, 0.3427154860F, 0.3431864628F, 0.3436575938F,
  151819. 0.3441288782F, 0.3446003158F, 0.3450719058F, 0.3455436478F,
  151820. 0.3460155412F, 0.3464875856F, 0.3469597804F, 0.3474321250F,
  151821. 0.3479046189F, 0.3483772617F, 0.3488500527F, 0.3493229914F,
  151822. 0.3497960774F, 0.3502693100F, 0.3507426887F, 0.3512162131F,
  151823. 0.3516898825F, 0.3521636965F, 0.3526376545F, 0.3531117559F,
  151824. 0.3535860003F, 0.3540603870F, 0.3545349157F, 0.3550095856F,
  151825. 0.3554843964F, 0.3559593474F, 0.3564344381F, 0.3569096680F,
  151826. 0.3573850366F, 0.3578605432F, 0.3583361875F, 0.3588119687F,
  151827. 0.3592878865F, 0.3597639402F, 0.3602401293F, 0.3607164533F,
  151828. 0.3611929117F, 0.3616695038F, 0.3621462292F, 0.3626230873F,
  151829. 0.3631000776F, 0.3635771995F, 0.3640544525F, 0.3645318360F,
  151830. 0.3650093496F, 0.3654869926F, 0.3659647645F, 0.3664426648F,
  151831. 0.3669206930F, 0.3673988484F, 0.3678771306F, 0.3683555390F,
  151832. 0.3688340731F, 0.3693127322F, 0.3697915160F, 0.3702704237F,
  151833. 0.3707494549F, 0.3712286091F, 0.3717078857F, 0.3721872840F,
  151834. 0.3726668037F, 0.3731464441F, 0.3736262047F, 0.3741060850F,
  151835. 0.3745860843F, 0.3750662023F, 0.3755464382F, 0.3760267915F,
  151836. 0.3765072618F, 0.3769878484F, 0.3774685509F, 0.3779493686F,
  151837. 0.3784303010F, 0.3789113475F, 0.3793925076F, 0.3798737809F,
  151838. 0.3803551666F, 0.3808366642F, 0.3813182733F, 0.3817999932F,
  151839. 0.3822818234F, 0.3827637633F, 0.3832458124F, 0.3837279702F,
  151840. 0.3842102360F, 0.3846926093F, 0.3851750897F, 0.3856576764F,
  151841. 0.3861403690F, 0.3866231670F, 0.3871060696F, 0.3875890765F,
  151842. 0.3880721870F, 0.3885554007F, 0.3890387168F, 0.3895221349F,
  151843. 0.3900056544F, 0.3904892748F, 0.3909729955F, 0.3914568160F,
  151844. 0.3919407356F, 0.3924247539F, 0.3929088702F, 0.3933930841F,
  151845. 0.3938773949F, 0.3943618021F, 0.3948463052F, 0.3953309035F,
  151846. 0.3958155966F, 0.3963003838F, 0.3967852646F, 0.3972702385F,
  151847. 0.3977553048F, 0.3982404631F, 0.3987257127F, 0.3992110531F,
  151848. 0.3996964838F, 0.4001820041F, 0.4006676136F, 0.4011533116F,
  151849. 0.4016390976F, 0.4021249710F, 0.4026109313F, 0.4030969779F,
  151850. 0.4035831102F, 0.4040693277F, 0.4045556299F, 0.4050420160F,
  151851. 0.4055284857F, 0.4060150383F, 0.4065016732F, 0.4069883899F,
  151852. 0.4074751879F, 0.4079620665F, 0.4084490252F, 0.4089360635F,
  151853. 0.4094231807F, 0.4099103763F, 0.4103976498F, 0.4108850005F,
  151854. 0.4113724280F, 0.4118599315F, 0.4123475107F, 0.4128351648F,
  151855. 0.4133228934F, 0.4138106959F, 0.4142985716F, 0.4147865201F,
  151856. 0.4152745408F, 0.4157626330F, 0.4162507963F, 0.4167390301F,
  151857. 0.4172273337F, 0.4177157067F, 0.4182041484F, 0.4186926583F,
  151858. 0.4191812359F, 0.4196698805F, 0.4201585915F, 0.4206473685F,
  151859. 0.4211362108F, 0.4216251179F, 0.4221140892F, 0.4226031241F,
  151860. 0.4230922221F, 0.4235813826F, 0.4240706050F, 0.4245598887F,
  151861. 0.4250492332F, 0.4255386379F, 0.4260281022F, 0.4265176256F,
  151862. 0.4270072075F, 0.4274968473F, 0.4279865445F, 0.4284762984F,
  151863. 0.4289661086F, 0.4294559743F, 0.4299458951F, 0.4304358704F,
  151864. 0.4309258996F, 0.4314159822F, 0.4319061175F, 0.4323963050F,
  151865. 0.4328865441F, 0.4333768342F, 0.4338671749F, 0.4343575654F,
  151866. 0.4348480052F, 0.4353384938F, 0.4358290306F, 0.4363196149F,
  151867. 0.4368102463F, 0.4373009241F, 0.4377916478F, 0.4382824168F,
  151868. 0.4387732305F, 0.4392640884F, 0.4397549899F, 0.4402459343F,
  151869. 0.4407369212F, 0.4412279499F, 0.4417190198F, 0.4422101305F,
  151870. 0.4427012813F, 0.4431924717F, 0.4436837010F, 0.4441749686F,
  151871. 0.4446662742F, 0.4451576169F, 0.4456489963F, 0.4461404118F,
  151872. 0.4466318628F, 0.4471233487F, 0.4476148690F, 0.4481064230F,
  151873. 0.4485980103F, 0.4490896302F, 0.4495812821F, 0.4500729654F,
  151874. 0.4505646797F, 0.4510564243F, 0.4515481986F, 0.4520400021F,
  151875. 0.4525318341F, 0.4530236942F, 0.4535155816F, 0.4540074959F,
  151876. 0.4544994365F, 0.4549914028F, 0.4554833941F, 0.4559754100F,
  151877. 0.4564674499F, 0.4569595131F, 0.4574515991F, 0.4579437074F,
  151878. 0.4584358372F, 0.4589279881F, 0.4594201595F, 0.4599123508F,
  151879. 0.4604045615F, 0.4608967908F, 0.4613890383F, 0.4618813034F,
  151880. 0.4623735855F, 0.4628658841F, 0.4633581984F, 0.4638505281F,
  151881. 0.4643428724F, 0.4648352308F, 0.4653276028F, 0.4658199877F,
  151882. 0.4663123849F, 0.4668047940F, 0.4672972143F, 0.4677896451F,
  151883. 0.4682820861F, 0.4687745365F, 0.4692669958F, 0.4697594634F,
  151884. 0.4702519387F, 0.4707444211F, 0.4712369102F, 0.4717294052F,
  151885. 0.4722219056F, 0.4727144109F, 0.4732069204F, 0.4736994336F,
  151886. 0.4741919498F, 0.4746844686F, 0.4751769893F, 0.4756695113F,
  151887. 0.4761620341F, 0.4766545571F, 0.4771470797F, 0.4776396013F,
  151888. 0.4781321213F, 0.4786246392F, 0.4791171544F, 0.4796096663F,
  151889. 0.4801021744F, 0.4805946779F, 0.4810871765F, 0.4815796694F,
  151890. 0.4820721561F, 0.4825646360F, 0.4830571086F, 0.4835495732F,
  151891. 0.4840420293F, 0.4845344763F, 0.4850269136F, 0.4855193407F,
  151892. 0.4860117569F, 0.4865041617F, 0.4869965545F, 0.4874889347F,
  151893. 0.4879813018F, 0.4884736551F, 0.4889659941F, 0.4894583182F,
  151894. 0.4899506268F, 0.4904429193F, 0.4909351952F, 0.4914274538F,
  151895. 0.4919196947F, 0.4924119172F, 0.4929041207F, 0.4933963046F,
  151896. 0.4938884685F, 0.4943806116F, 0.4948727335F, 0.4953648335F,
  151897. 0.4958569110F, 0.4963489656F, 0.4968409965F, 0.4973330032F,
  151898. 0.4978249852F, 0.4983169419F, 0.4988088726F, 0.4993007768F,
  151899. 0.4997926539F, 0.5002845034F, 0.5007763247F, 0.5012681171F,
  151900. 0.5017598801F, 0.5022516132F, 0.5027433157F, 0.5032349871F,
  151901. 0.5037266268F, 0.5042182341F, 0.5047098086F, 0.5052013497F,
  151902. 0.5056928567F, 0.5061843292F, 0.5066757664F, 0.5071671679F,
  151903. 0.5076585330F, 0.5081498613F, 0.5086411520F, 0.5091324047F,
  151904. 0.5096236187F, 0.5101147934F, 0.5106059284F, 0.5110970230F,
  151905. 0.5115880766F, 0.5120790887F, 0.5125700587F, 0.5130609860F,
  151906. 0.5135518700F, 0.5140427102F, 0.5145335059F, 0.5150242566F,
  151907. 0.5155149618F, 0.5160056208F, 0.5164962331F, 0.5169867980F,
  151908. 0.5174773151F, 0.5179677837F, 0.5184582033F, 0.5189485733F,
  151909. 0.5194388931F, 0.5199291621F, 0.5204193798F, 0.5209095455F,
  151910. 0.5213996588F, 0.5218897190F, 0.5223797256F, 0.5228696779F,
  151911. 0.5233595755F, 0.5238494177F, 0.5243392039F, 0.5248289337F,
  151912. 0.5253186063F, 0.5258082213F, 0.5262977781F, 0.5267872760F,
  151913. 0.5272767146F, 0.5277660932F, 0.5282554112F, 0.5287446682F,
  151914. 0.5292338635F, 0.5297229965F, 0.5302120667F, 0.5307010736F,
  151915. 0.5311900164F, 0.5316788947F, 0.5321677079F, 0.5326564554F,
  151916. 0.5331451366F, 0.5336337511F, 0.5341222981F, 0.5346107771F,
  151917. 0.5350991876F, 0.5355875290F, 0.5360758007F, 0.5365640021F,
  151918. 0.5370521327F, 0.5375401920F, 0.5380281792F, 0.5385160939F,
  151919. 0.5390039355F, 0.5394917034F, 0.5399793971F, 0.5404670159F,
  151920. 0.5409545594F, 0.5414420269F, 0.5419294179F, 0.5424167318F,
  151921. 0.5429039680F, 0.5433911261F, 0.5438782053F, 0.5443652051F,
  151922. 0.5448521250F, 0.5453389644F, 0.5458257228F, 0.5463123995F,
  151923. 0.5467989940F, 0.5472855057F, 0.5477719341F, 0.5482582786F,
  151924. 0.5487445387F, 0.5492307137F, 0.5497168031F, 0.5502028063F,
  151925. 0.5506887228F, 0.5511745520F, 0.5516602934F, 0.5521459463F,
  151926. 0.5526315103F, 0.5531169847F, 0.5536023690F, 0.5540876626F,
  151927. 0.5545728649F, 0.5550579755F, 0.5555429937F, 0.5560279189F,
  151928. 0.5565127507F, 0.5569974884F, 0.5574821315F, 0.5579666794F,
  151929. 0.5584511316F, 0.5589354875F, 0.5594197465F, 0.5599039080F,
  151930. 0.5603879716F, 0.5608719367F, 0.5613558026F, 0.5618395689F,
  151931. 0.5623232350F, 0.5628068002F, 0.5632902642F, 0.5637736262F,
  151932. 0.5642568858F, 0.5647400423F, 0.5652230953F, 0.5657060442F,
  151933. 0.5661888883F, 0.5666716272F, 0.5671542603F, 0.5676367870F,
  151934. 0.5681192069F, 0.5686015192F, 0.5690837235F, 0.5695658192F,
  151935. 0.5700478058F, 0.5705296827F, 0.5710114494F, 0.5714931052F,
  151936. 0.5719746497F, 0.5724560822F, 0.5729374023F, 0.5734186094F,
  151937. 0.5738997029F, 0.5743806823F, 0.5748615470F, 0.5753422965F,
  151938. 0.5758229301F, 0.5763034475F, 0.5767838480F, 0.5772641310F,
  151939. 0.5777442960F, 0.5782243426F, 0.5787042700F, 0.5791840778F,
  151940. 0.5796637654F, 0.5801433322F, 0.5806227778F, 0.5811021016F,
  151941. 0.5815813029F, 0.5820603814F, 0.5825393363F, 0.5830181673F,
  151942. 0.5834968737F, 0.5839754549F, 0.5844539105F, 0.5849322399F,
  151943. 0.5854104425F, 0.5858885179F, 0.5863664653F, 0.5868442844F,
  151944. 0.5873219746F, 0.5877995353F, 0.5882769660F, 0.5887542661F,
  151945. 0.5892314351F, 0.5897084724F, 0.5901853776F, 0.5906621500F,
  151946. 0.5911387892F, 0.5916152945F, 0.5920916655F, 0.5925679016F,
  151947. 0.5930440022F, 0.5935199669F, 0.5939957950F, 0.5944714861F,
  151948. 0.5949470396F, 0.5954224550F, 0.5958977317F, 0.5963728692F,
  151949. 0.5968478669F, 0.5973227244F, 0.5977974411F, 0.5982720163F,
  151950. 0.5987464497F, 0.5992207407F, 0.5996948887F, 0.6001688932F,
  151951. 0.6006427537F, 0.6011164696F, 0.6015900405F, 0.6020634657F,
  151952. 0.6025367447F, 0.6030098770F, 0.6034828621F, 0.6039556995F,
  151953. 0.6044283885F, 0.6049009288F, 0.6053733196F, 0.6058455606F,
  151954. 0.6063176512F, 0.6067895909F, 0.6072613790F, 0.6077330152F,
  151955. 0.6082044989F, 0.6086758295F, 0.6091470065F, 0.6096180294F,
  151956. 0.6100888977F, 0.6105596108F, 0.6110301682F, 0.6115005694F,
  151957. 0.6119708139F, 0.6124409011F, 0.6129108305F, 0.6133806017F,
  151958. 0.6138502139F, 0.6143196669F, 0.6147889599F, 0.6152580926F,
  151959. 0.6157270643F, 0.6161958746F, 0.6166645230F, 0.6171330088F,
  151960. 0.6176013317F, 0.6180694910F, 0.6185374863F, 0.6190053171F,
  151961. 0.6194729827F, 0.6199404828F, 0.6204078167F, 0.6208749841F,
  151962. 0.6213419842F, 0.6218088168F, 0.6222754811F, 0.6227419768F,
  151963. 0.6232083032F, 0.6236744600F, 0.6241404465F, 0.6246062622F,
  151964. 0.6250719067F, 0.6255373795F, 0.6260026799F, 0.6264678076F,
  151965. 0.6269327619F, 0.6273975425F, 0.6278621487F, 0.6283265800F,
  151966. 0.6287908361F, 0.6292549163F, 0.6297188201F, 0.6301825471F,
  151967. 0.6306460966F, 0.6311094683F, 0.6315726617F, 0.6320356761F,
  151968. 0.6324985111F, 0.6329611662F, 0.6334236410F, 0.6338859348F,
  151969. 0.6343480472F, 0.6348099777F, 0.6352717257F, 0.6357332909F,
  151970. 0.6361946726F, 0.6366558704F, 0.6371168837F, 0.6375777122F,
  151971. 0.6380383552F, 0.6384988123F, 0.6389590830F, 0.6394191668F,
  151972. 0.6398790631F, 0.6403387716F, 0.6407982916F, 0.6412576228F,
  151973. 0.6417167645F, 0.6421757163F, 0.6426344778F, 0.6430930483F,
  151974. 0.6435514275F, 0.6440096149F, 0.6444676098F, 0.6449254119F,
  151975. 0.6453830207F, 0.6458404356F, 0.6462976562F, 0.6467546820F,
  151976. 0.6472115125F, 0.6476681472F, 0.6481245856F, 0.6485808273F,
  151977. 0.6490368717F, 0.6494927183F, 0.6499483667F, 0.6504038164F,
  151978. 0.6508590670F, 0.6513141178F, 0.6517689684F, 0.6522236185F,
  151979. 0.6526780673F, 0.6531323146F, 0.6535863598F, 0.6540402024F,
  151980. 0.6544938419F, 0.6549472779F, 0.6554005099F, 0.6558535373F,
  151981. 0.6563063598F, 0.6567589769F, 0.6572113880F, 0.6576635927F,
  151982. 0.6581155906F, 0.6585673810F, 0.6590189637F, 0.6594703380F,
  151983. 0.6599215035F, 0.6603724598F, 0.6608232064F, 0.6612737427F,
  151984. 0.6617240684F, 0.6621741829F, 0.6626240859F, 0.6630737767F,
  151985. 0.6635232550F, 0.6639725202F, 0.6644215720F, 0.6648704098F,
  151986. 0.6653190332F, 0.6657674417F, 0.6662156348F, 0.6666636121F,
  151987. 0.6671113731F, 0.6675589174F, 0.6680062445F, 0.6684533538F,
  151988. 0.6689002450F, 0.6693469177F, 0.6697933712F, 0.6702396052F,
  151989. 0.6706856193F, 0.6711314129F, 0.6715769855F, 0.6720223369F,
  151990. 0.6724674664F, 0.6729123736F, 0.6733570581F, 0.6738015194F,
  151991. 0.6742457570F, 0.6746897706F, 0.6751335596F, 0.6755771236F,
  151992. 0.6760204621F, 0.6764635747F, 0.6769064609F, 0.6773491204F,
  151993. 0.6777915525F, 0.6782337570F, 0.6786757332F, 0.6791174809F,
  151994. 0.6795589995F, 0.6800002886F, 0.6804413477F, 0.6808821765F,
  151995. 0.6813227743F, 0.6817631409F, 0.6822032758F, 0.6826431785F,
  151996. 0.6830828485F, 0.6835222855F, 0.6839614890F, 0.6844004585F,
  151997. 0.6848391936F, 0.6852776939F, 0.6857159589F, 0.6861539883F,
  151998. 0.6865917815F, 0.6870293381F, 0.6874666576F, 0.6879037398F,
  151999. 0.6883405840F, 0.6887771899F, 0.6892135571F, 0.6896496850F,
  152000. 0.6900855733F, 0.6905212216F, 0.6909566294F, 0.6913917963F,
  152001. 0.6918267218F, 0.6922614055F, 0.6926958471F, 0.6931300459F,
  152002. 0.6935640018F, 0.6939977141F, 0.6944311825F, 0.6948644066F,
  152003. 0.6952973859F, 0.6957301200F, 0.6961626085F, 0.6965948510F,
  152004. 0.6970268470F, 0.6974585961F, 0.6978900980F, 0.6983213521F,
  152005. 0.6987523580F, 0.6991831154F, 0.6996136238F, 0.7000438828F,
  152006. 0.7004738921F, 0.7009036510F, 0.7013331594F, 0.7017624166F,
  152007. 0.7021914224F, 0.7026201763F, 0.7030486779F, 0.7034769268F,
  152008. 0.7039049226F, 0.7043326648F, 0.7047601531F, 0.7051873870F,
  152009. 0.7056143662F, 0.7060410902F, 0.7064675586F, 0.7068937711F,
  152010. 0.7073197271F, 0.7077454264F, 0.7081708684F, 0.7085960529F,
  152011. 0.7090209793F, 0.7094456474F, 0.7098700566F, 0.7102942066F,
  152012. 0.7107180970F, 0.7111417274F, 0.7115650974F, 0.7119882066F,
  152013. 0.7124110545F, 0.7128336409F, 0.7132559653F, 0.7136780272F,
  152014. 0.7140998264F, 0.7145213624F, 0.7149426348F, 0.7153636433F,
  152015. 0.7157843874F, 0.7162048668F, 0.7166250810F, 0.7170450296F,
  152016. 0.7174647124F, 0.7178841289F, 0.7183032786F, 0.7187221613F,
  152017. 0.7191407765F, 0.7195591239F, 0.7199772030F, 0.7203950135F,
  152018. 0.7208125550F, 0.7212298271F, 0.7216468294F, 0.7220635616F,
  152019. 0.7224800233F, 0.7228962140F, 0.7233121335F, 0.7237277813F,
  152020. 0.7241431571F, 0.7245582604F, 0.7249730910F, 0.7253876484F,
  152021. 0.7258019322F, 0.7262159422F, 0.7266296778F, 0.7270431388F,
  152022. 0.7274563247F, 0.7278692353F, 0.7282818700F, 0.7286942287F,
  152023. 0.7291063108F, 0.7295181160F, 0.7299296440F, 0.7303408944F,
  152024. 0.7307518669F, 0.7311625609F, 0.7315729763F, 0.7319831126F,
  152025. 0.7323929695F, 0.7328025466F, 0.7332118435F, 0.7336208600F,
  152026. 0.7340295955F, 0.7344380499F, 0.7348462226F, 0.7352541134F,
  152027. 0.7356617220F, 0.7360690478F, 0.7364760907F, 0.7368828502F,
  152028. 0.7372893259F, 0.7376955176F, 0.7381014249F, 0.7385070475F,
  152029. 0.7389123849F, 0.7393174368F, 0.7397222029F, 0.7401266829F,
  152030. 0.7405308763F, 0.7409347829F, 0.7413384023F, 0.7417417341F,
  152031. 0.7421447780F, 0.7425475338F, 0.7429500009F, 0.7433521791F,
  152032. 0.7437540681F, 0.7441556674F, 0.7445569769F, 0.7449579960F,
  152033. 0.7453587245F, 0.7457591621F, 0.7461593084F, 0.7465591631F,
  152034. 0.7469587259F, 0.7473579963F, 0.7477569741F, 0.7481556590F,
  152035. 0.7485540506F, 0.7489521486F, 0.7493499526F, 0.7497474623F,
  152036. 0.7501446775F, 0.7505415977F, 0.7509382227F, 0.7513345521F,
  152037. 0.7517305856F, 0.7521263229F, 0.7525217636F, 0.7529169074F,
  152038. 0.7533117541F, 0.7537063032F, 0.7541005545F, 0.7544945076F,
  152039. 0.7548881623F, 0.7552815182F, 0.7556745749F, 0.7560673323F,
  152040. 0.7564597899F, 0.7568519474F, 0.7572438046F, 0.7576353611F,
  152041. 0.7580266166F, 0.7584175708F, 0.7588082235F, 0.7591985741F,
  152042. 0.7595886226F, 0.7599783685F, 0.7603678116F, 0.7607569515F,
  152043. 0.7611457879F, 0.7615343206F, 0.7619225493F, 0.7623104735F,
  152044. 0.7626980931F, 0.7630854078F, 0.7634724171F, 0.7638591209F,
  152045. 0.7642455188F, 0.7646316106F, 0.7650173959F, 0.7654028744F,
  152046. 0.7657880459F, 0.7661729100F, 0.7665574664F, 0.7669417150F,
  152047. 0.7673256553F, 0.7677092871F, 0.7680926100F, 0.7684756239F,
  152048. 0.7688583284F, 0.7692407232F, 0.7696228080F, 0.7700045826F,
  152049. 0.7703860467F, 0.7707671999F, 0.7711480420F, 0.7715285728F,
  152050. 0.7719087918F, 0.7722886989F, 0.7726682938F, 0.7730475762F,
  152051. 0.7734265458F, 0.7738052023F, 0.7741835454F, 0.7745615750F,
  152052. 0.7749392906F, 0.7753166921F, 0.7756937791F, 0.7760705514F,
  152053. 0.7764470087F, 0.7768231508F, 0.7771989773F, 0.7775744880F,
  152054. 0.7779496827F, 0.7783245610F, 0.7786991227F, 0.7790733676F,
  152055. 0.7794472953F, 0.7798209056F, 0.7801941982F, 0.7805671729F,
  152056. 0.7809398294F, 0.7813121675F, 0.7816841869F, 0.7820558873F,
  152057. 0.7824272684F, 0.7827983301F, 0.7831690720F, 0.7835394940F,
  152058. 0.7839095957F, 0.7842793768F, 0.7846488373F, 0.7850179767F,
  152059. 0.7853867948F, 0.7857552914F, 0.7861234663F, 0.7864913191F,
  152060. 0.7868588497F, 0.7872260578F, 0.7875929431F, 0.7879595055F,
  152061. 0.7883257445F, 0.7886916601F, 0.7890572520F, 0.7894225198F,
  152062. 0.7897874635F, 0.7901520827F, 0.7905163772F, 0.7908803468F,
  152063. 0.7912439912F, 0.7916073102F, 0.7919703035F, 0.7923329710F,
  152064. 0.7926953124F, 0.7930573274F, 0.7934190158F, 0.7937803774F,
  152065. 0.7941414120F, 0.7945021193F, 0.7948624991F, 0.7952225511F,
  152066. 0.7955822752F, 0.7959416711F, 0.7963007387F, 0.7966594775F,
  152067. 0.7970178875F, 0.7973759685F, 0.7977337201F, 0.7980911422F,
  152068. 0.7984482346F, 0.7988049970F, 0.7991614292F, 0.7995175310F,
  152069. 0.7998733022F, 0.8002287426F, 0.8005838519F, 0.8009386299F,
  152070. 0.8012930765F, 0.8016471914F, 0.8020009744F, 0.8023544253F,
  152071. 0.8027075438F, 0.8030603298F, 0.8034127831F, 0.8037649035F,
  152072. 0.8041166906F, 0.8044681445F, 0.8048192647F, 0.8051700512F,
  152073. 0.8055205038F, 0.8058706222F, 0.8062204062F, 0.8065698556F,
  152074. 0.8069189702F, 0.8072677499F, 0.8076161944F, 0.8079643036F,
  152075. 0.8083120772F, 0.8086595151F, 0.8090066170F, 0.8093533827F,
  152076. 0.8096998122F, 0.8100459051F, 0.8103916613F, 0.8107370806F,
  152077. 0.8110821628F, 0.8114269077F, 0.8117713151F, 0.8121153849F,
  152078. 0.8124591169F, 0.8128025108F, 0.8131455666F, 0.8134882839F,
  152079. 0.8138306627F, 0.8141727027F, 0.8145144038F, 0.8148557658F,
  152080. 0.8151967886F, 0.8155374718F, 0.8158778154F, 0.8162178192F,
  152081. 0.8165574830F, 0.8168968067F, 0.8172357900F, 0.8175744328F,
  152082. 0.8179127349F, 0.8182506962F, 0.8185883164F, 0.8189255955F,
  152083. 0.8192625332F, 0.8195991295F, 0.8199353840F, 0.8202712967F,
  152084. 0.8206068673F, 0.8209420958F, 0.8212769820F, 0.8216115256F,
  152085. 0.8219457266F, 0.8222795848F, 0.8226131000F, 0.8229462721F,
  152086. 0.8232791009F, 0.8236115863F, 0.8239437280F, 0.8242755260F,
  152087. 0.8246069801F, 0.8249380901F, 0.8252688559F, 0.8255992774F,
  152088. 0.8259293544F, 0.8262590867F, 0.8265884741F, 0.8269175167F,
  152089. 0.8272462141F, 0.8275745663F, 0.8279025732F, 0.8282302344F,
  152090. 0.8285575501F, 0.8288845199F, 0.8292111437F, 0.8295374215F,
  152091. 0.8298633530F, 0.8301889382F, 0.8305141768F, 0.8308390688F,
  152092. 0.8311636141F, 0.8314878124F, 0.8318116637F, 0.8321351678F,
  152093. 0.8324583246F, 0.8327811340F, 0.8331035957F, 0.8334257098F,
  152094. 0.8337474761F, 0.8340688944F, 0.8343899647F, 0.8347106867F,
  152095. 0.8350310605F, 0.8353510857F, 0.8356707624F, 0.8359900904F,
  152096. 0.8363090696F, 0.8366276999F, 0.8369459811F, 0.8372639131F,
  152097. 0.8375814958F, 0.8378987292F, 0.8382156130F, 0.8385321472F,
  152098. 0.8388483316F, 0.8391641662F, 0.8394796508F, 0.8397947853F,
  152099. 0.8401095697F, 0.8404240037F, 0.8407380873F, 0.8410518204F,
  152100. 0.8413652029F, 0.8416782347F, 0.8419909156F, 0.8423032456F,
  152101. 0.8426152245F, 0.8429268523F, 0.8432381289F, 0.8435490541F,
  152102. 0.8438596279F, 0.8441698502F, 0.8444797208F, 0.8447892396F,
  152103. 0.8450984067F, 0.8454072218F, 0.8457156849F, 0.8460237959F,
  152104. 0.8463315547F, 0.8466389612F, 0.8469460154F, 0.8472527170F,
  152105. 0.8475590661F, 0.8478650625F, 0.8481707063F, 0.8484759971F,
  152106. 0.8487809351F, 0.8490855201F, 0.8493897521F, 0.8496936308F,
  152107. 0.8499971564F, 0.8503003286F, 0.8506031474F, 0.8509056128F,
  152108. 0.8512077246F, 0.8515094828F, 0.8518108872F, 0.8521119379F,
  152109. 0.8524126348F, 0.8527129777F, 0.8530129666F, 0.8533126015F,
  152110. 0.8536118822F, 0.8539108087F, 0.8542093809F, 0.8545075988F,
  152111. 0.8548054623F, 0.8551029712F, 0.8554001257F, 0.8556969255F,
  152112. 0.8559933707F, 0.8562894611F, 0.8565851968F, 0.8568805775F,
  152113. 0.8571756034F, 0.8574702743F, 0.8577645902F, 0.8580585509F,
  152114. 0.8583521566F, 0.8586454070F, 0.8589383021F, 0.8592308420F,
  152115. 0.8595230265F, 0.8598148556F, 0.8601063292F, 0.8603974473F,
  152116. 0.8606882098F, 0.8609786167F, 0.8612686680F, 0.8615583636F,
  152117. 0.8618477034F, 0.8621366874F, 0.8624253156F, 0.8627135878F,
  152118. 0.8630015042F, 0.8632890646F, 0.8635762690F, 0.8638631173F,
  152119. 0.8641496096F, 0.8644357457F, 0.8647215257F, 0.8650069495F,
  152120. 0.8652920171F, 0.8655767283F, 0.8658610833F, 0.8661450820F,
  152121. 0.8664287243F, 0.8667120102F, 0.8669949397F, 0.8672775127F,
  152122. 0.8675597293F, 0.8678415894F, 0.8681230929F, 0.8684042398F,
  152123. 0.8686850302F, 0.8689654640F, 0.8692455412F, 0.8695252617F,
  152124. 0.8698046255F, 0.8700836327F, 0.8703622831F, 0.8706405768F,
  152125. 0.8709185138F, 0.8711960940F, 0.8714733174F, 0.8717501840F,
  152126. 0.8720266939F, 0.8723028469F, 0.8725786430F, 0.8728540824F,
  152127. 0.8731291648F, 0.8734038905F, 0.8736782592F, 0.8739522711F,
  152128. 0.8742259261F, 0.8744992242F, 0.8747721653F, 0.8750447496F,
  152129. 0.8753169770F, 0.8755888475F, 0.8758603611F, 0.8761315177F,
  152130. 0.8764023175F, 0.8766727603F, 0.8769428462F, 0.8772125752F,
  152131. 0.8774819474F, 0.8777509626F, 0.8780196209F, 0.8782879224F,
  152132. 0.8785558669F, 0.8788234546F, 0.8790906854F, 0.8793575594F,
  152133. 0.8796240765F, 0.8798902368F, 0.8801560403F, 0.8804214870F,
  152134. 0.8806865768F, 0.8809513099F, 0.8812156863F, 0.8814797059F,
  152135. 0.8817433687F, 0.8820066749F, 0.8822696243F, 0.8825322171F,
  152136. 0.8827944532F, 0.8830563327F, 0.8833178556F, 0.8835790219F,
  152137. 0.8838398316F, 0.8841002848F, 0.8843603815F, 0.8846201217F,
  152138. 0.8848795054F, 0.8851385327F, 0.8853972036F, 0.8856555182F,
  152139. 0.8859134764F, 0.8861710783F, 0.8864283239F, 0.8866852133F,
  152140. 0.8869417464F, 0.8871979234F, 0.8874537443F, 0.8877092090F,
  152141. 0.8879643177F, 0.8882190704F, 0.8884734671F, 0.8887275078F,
  152142. 0.8889811927F, 0.8892345216F, 0.8894874948F, 0.8897401122F,
  152143. 0.8899923738F, 0.8902442798F, 0.8904958301F, 0.8907470248F,
  152144. 0.8909978640F, 0.8912483477F, 0.8914984759F, 0.8917482487F,
  152145. 0.8919976662F, 0.8922467284F, 0.8924954353F, 0.8927437871F,
  152146. 0.8929917837F, 0.8932394252F, 0.8934867118F, 0.8937336433F,
  152147. 0.8939802199F, 0.8942264417F, 0.8944723087F, 0.8947178210F,
  152148. 0.8949629785F, 0.8952077815F, 0.8954522299F, 0.8956963239F,
  152149. 0.8959400634F, 0.8961834486F, 0.8964264795F, 0.8966691561F,
  152150. 0.8969114786F, 0.8971534470F, 0.8973950614F, 0.8976363219F,
  152151. 0.8978772284F, 0.8981177812F, 0.8983579802F, 0.8985978256F,
  152152. 0.8988373174F, 0.8990764556F, 0.8993152405F, 0.8995536720F,
  152153. 0.8997917502F, 0.9000294751F, 0.9002668470F, 0.9005038658F,
  152154. 0.9007405317F, 0.9009768446F, 0.9012128048F, 0.9014484123F,
  152155. 0.9016836671F, 0.9019185693F, 0.9021531191F, 0.9023873165F,
  152156. 0.9026211616F, 0.9028546546F, 0.9030877954F, 0.9033205841F,
  152157. 0.9035530210F, 0.9037851059F, 0.9040168392F, 0.9042482207F,
  152158. 0.9044792507F, 0.9047099293F, 0.9049402564F, 0.9051702323F,
  152159. 0.9053998569F, 0.9056291305F, 0.9058580531F, 0.9060866248F,
  152160. 0.9063148457F, 0.9065427159F, 0.9067702355F, 0.9069974046F,
  152161. 0.9072242233F, 0.9074506917F, 0.9076768100F, 0.9079025782F,
  152162. 0.9081279964F, 0.9083530647F, 0.9085777833F, 0.9088021523F,
  152163. 0.9090261717F, 0.9092498417F, 0.9094731623F, 0.9096961338F,
  152164. 0.9099187561F, 0.9101410295F, 0.9103629540F, 0.9105845297F,
  152165. 0.9108057568F, 0.9110266354F, 0.9112471656F, 0.9114673475F,
  152166. 0.9116871812F, 0.9119066668F, 0.9121258046F, 0.9123445945F,
  152167. 0.9125630367F, 0.9127811314F, 0.9129988786F, 0.9132162785F,
  152168. 0.9134333312F, 0.9136500368F, 0.9138663954F, 0.9140824073F,
  152169. 0.9142980724F, 0.9145133910F, 0.9147283632F, 0.9149429890F,
  152170. 0.9151572687F, 0.9153712023F, 0.9155847900F, 0.9157980319F,
  152171. 0.9160109282F, 0.9162234790F, 0.9164356844F, 0.9166475445F,
  152172. 0.9168590595F, 0.9170702296F, 0.9172810548F, 0.9174915354F,
  152173. 0.9177016714F, 0.9179114629F, 0.9181209102F, 0.9183300134F,
  152174. 0.9185387726F, 0.9187471879F, 0.9189552595F, 0.9191629876F,
  152175. 0.9193703723F, 0.9195774136F, 0.9197841119F, 0.9199904672F,
  152176. 0.9201964797F, 0.9204021495F, 0.9206074767F, 0.9208124616F,
  152177. 0.9210171043F, 0.9212214049F, 0.9214253636F, 0.9216289805F,
  152178. 0.9218322558F, 0.9220351896F, 0.9222377821F, 0.9224400335F,
  152179. 0.9226419439F, 0.9228435134F, 0.9230447423F, 0.9232456307F,
  152180. 0.9234461787F, 0.9236463865F, 0.9238462543F, 0.9240457822F,
  152181. 0.9242449704F, 0.9244438190F, 0.9246423282F, 0.9248404983F,
  152182. 0.9250383293F, 0.9252358214F, 0.9254329747F, 0.9256297896F,
  152183. 0.9258262660F, 0.9260224042F, 0.9262182044F, 0.9264136667F,
  152184. 0.9266087913F, 0.9268035783F, 0.9269980280F, 0.9271921405F,
  152185. 0.9273859160F, 0.9275793546F, 0.9277724566F, 0.9279652221F,
  152186. 0.9281576513F, 0.9283497443F, 0.9285415014F, 0.9287329227F,
  152187. 0.9289240084F, 0.9291147586F, 0.9293051737F, 0.9294952536F,
  152188. 0.9296849987F, 0.9298744091F, 0.9300634850F, 0.9302522266F,
  152189. 0.9304406340F, 0.9306287074F, 0.9308164471F, 0.9310038532F,
  152190. 0.9311909259F, 0.9313776654F, 0.9315640719F, 0.9317501455F,
  152191. 0.9319358865F, 0.9321212951F, 0.9323063713F, 0.9324911155F,
  152192. 0.9326755279F, 0.9328596085F, 0.9330433577F, 0.9332267756F,
  152193. 0.9334098623F, 0.9335926182F, 0.9337750434F, 0.9339571380F,
  152194. 0.9341389023F, 0.9343203366F, 0.9345014409F, 0.9346822155F,
  152195. 0.9348626606F, 0.9350427763F, 0.9352225630F, 0.9354020207F,
  152196. 0.9355811498F, 0.9357599503F, 0.9359384226F, 0.9361165667F,
  152197. 0.9362943830F, 0.9364718716F, 0.9366490327F, 0.9368258666F,
  152198. 0.9370023733F, 0.9371785533F, 0.9373544066F, 0.9375299335F,
  152199. 0.9377051341F, 0.9378800087F, 0.9380545576F, 0.9382287809F,
  152200. 0.9384026787F, 0.9385762515F, 0.9387494993F, 0.9389224223F,
  152201. 0.9390950209F, 0.9392672951F, 0.9394392453F, 0.9396108716F,
  152202. 0.9397821743F, 0.9399531536F, 0.9401238096F, 0.9402941427F,
  152203. 0.9404641530F, 0.9406338407F, 0.9408032061F, 0.9409722495F,
  152204. 0.9411409709F, 0.9413093707F, 0.9414774491F, 0.9416452062F,
  152205. 0.9418126424F, 0.9419797579F, 0.9421465528F, 0.9423130274F,
  152206. 0.9424791819F, 0.9426450166F, 0.9428105317F, 0.9429757274F,
  152207. 0.9431406039F, 0.9433051616F, 0.9434694005F, 0.9436333209F,
  152208. 0.9437969232F, 0.9439602074F, 0.9441231739F, 0.9442858229F,
  152209. 0.9444481545F, 0.9446101691F, 0.9447718669F, 0.9449332481F,
  152210. 0.9450943129F, 0.9452550617F, 0.9454154945F, 0.9455756118F,
  152211. 0.9457354136F, 0.9458949003F, 0.9460540721F, 0.9462129292F,
  152212. 0.9463714719F, 0.9465297003F, 0.9466876149F, 0.9468452157F,
  152213. 0.9470025031F, 0.9471594772F, 0.9473161384F, 0.9474724869F,
  152214. 0.9476285229F, 0.9477842466F, 0.9479396584F, 0.9480947585F,
  152215. 0.9482495470F, 0.9484040243F, 0.9485581906F, 0.9487120462F,
  152216. 0.9488655913F, 0.9490188262F, 0.9491717511F, 0.9493243662F,
  152217. 0.9494766718F, 0.9496286683F, 0.9497803557F, 0.9499317345F,
  152218. 0.9500828047F, 0.9502335668F, 0.9503840209F, 0.9505341673F,
  152219. 0.9506840062F, 0.9508335380F, 0.9509827629F, 0.9511316810F,
  152220. 0.9512802928F, 0.9514285984F, 0.9515765982F, 0.9517242923F,
  152221. 0.9518716810F, 0.9520187646F, 0.9521655434F, 0.9523120176F,
  152222. 0.9524581875F, 0.9526040534F, 0.9527496154F, 0.9528948739F,
  152223. 0.9530398292F, 0.9531844814F, 0.9533288310F, 0.9534728780F,
  152224. 0.9536166229F, 0.9537600659F, 0.9539032071F, 0.9540460470F,
  152225. 0.9541885858F, 0.9543308237F, 0.9544727611F, 0.9546143981F,
  152226. 0.9547557351F, 0.9548967723F, 0.9550375100F, 0.9551779485F,
  152227. 0.9553180881F, 0.9554579290F, 0.9555974714F, 0.9557367158F,
  152228. 0.9558756623F, 0.9560143112F, 0.9561526628F, 0.9562907174F,
  152229. 0.9564284752F, 0.9565659366F, 0.9567031017F, 0.9568399710F,
  152230. 0.9569765446F, 0.9571128229F, 0.9572488061F, 0.9573844944F,
  152231. 0.9575198883F, 0.9576549879F, 0.9577897936F, 0.9579243056F,
  152232. 0.9580585242F, 0.9581924497F, 0.9583260824F, 0.9584594226F,
  152233. 0.9585924705F, 0.9587252264F, 0.9588576906F, 0.9589898634F,
  152234. 0.9591217452F, 0.9592533360F, 0.9593846364F, 0.9595156465F,
  152235. 0.9596463666F, 0.9597767971F, 0.9599069382F, 0.9600367901F,
  152236. 0.9601663533F, 0.9602956279F, 0.9604246143F, 0.9605533128F,
  152237. 0.9606817236F, 0.9608098471F, 0.9609376835F, 0.9610652332F,
  152238. 0.9611924963F, 0.9613194733F, 0.9614461644F, 0.9615725699F,
  152239. 0.9616986901F, 0.9618245253F, 0.9619500757F, 0.9620753418F,
  152240. 0.9622003238F, 0.9623250219F, 0.9624494365F, 0.9625735679F,
  152241. 0.9626974163F, 0.9628209821F, 0.9629442656F, 0.9630672671F,
  152242. 0.9631899868F, 0.9633124251F, 0.9634345822F, 0.9635564585F,
  152243. 0.9636780543F, 0.9637993699F, 0.9639204056F, 0.9640411616F,
  152244. 0.9641616383F, 0.9642818359F, 0.9644017549F, 0.9645213955F,
  152245. 0.9646407579F, 0.9647598426F, 0.9648786497F, 0.9649971797F,
  152246. 0.9651154328F, 0.9652334092F, 0.9653511095F, 0.9654685337F,
  152247. 0.9655856823F, 0.9657025556F, 0.9658191538F, 0.9659354773F,
  152248. 0.9660515263F, 0.9661673013F, 0.9662828024F, 0.9663980300F,
  152249. 0.9665129845F, 0.9666276660F, 0.9667420750F, 0.9668562118F,
  152250. 0.9669700766F, 0.9670836698F, 0.9671969917F, 0.9673100425F,
  152251. 0.9674228227F, 0.9675353325F, 0.9676475722F, 0.9677595422F,
  152252. 0.9678712428F, 0.9679826742F, 0.9680938368F, 0.9682047309F,
  152253. 0.9683153569F, 0.9684257150F, 0.9685358056F, 0.9686456289F,
  152254. 0.9687551853F, 0.9688644752F, 0.9689734987F, 0.9690822564F,
  152255. 0.9691907483F, 0.9692989750F, 0.9694069367F, 0.9695146337F,
  152256. 0.9696220663F, 0.9697292349F, 0.9698361398F, 0.9699427813F,
  152257. 0.9700491597F, 0.9701552754F, 0.9702611286F, 0.9703667197F,
  152258. 0.9704720490F, 0.9705771169F, 0.9706819236F, 0.9707864695F,
  152259. 0.9708907549F, 0.9709947802F, 0.9710985456F, 0.9712020514F,
  152260. 0.9713052981F, 0.9714082859F, 0.9715110151F, 0.9716134862F,
  152261. 0.9717156993F, 0.9718176549F, 0.9719193532F, 0.9720207946F,
  152262. 0.9721219794F, 0.9722229080F, 0.9723235806F, 0.9724239976F,
  152263. 0.9725241593F, 0.9726240661F, 0.9727237183F, 0.9728231161F,
  152264. 0.9729222601F, 0.9730211503F, 0.9731197873F, 0.9732181713F,
  152265. 0.9733163027F, 0.9734141817F, 0.9735118088F, 0.9736091842F,
  152266. 0.9737063083F, 0.9738031814F, 0.9738998039F, 0.9739961760F,
  152267. 0.9740922981F, 0.9741881706F, 0.9742837938F, 0.9743791680F,
  152268. 0.9744742935F, 0.9745691707F, 0.9746637999F, 0.9747581814F,
  152269. 0.9748523157F, 0.9749462029F, 0.9750398435F, 0.9751332378F,
  152270. 0.9752263861F, 0.9753192887F, 0.9754119461F, 0.9755043585F,
  152271. 0.9755965262F, 0.9756884496F, 0.9757801291F, 0.9758715650F,
  152272. 0.9759627575F, 0.9760537071F, 0.9761444141F, 0.9762348789F,
  152273. 0.9763251016F, 0.9764150828F, 0.9765048228F, 0.9765943218F,
  152274. 0.9766835802F, 0.9767725984F, 0.9768613767F, 0.9769499154F,
  152275. 0.9770382149F, 0.9771262755F, 0.9772140976F, 0.9773016815F,
  152276. 0.9773890275F, 0.9774761360F, 0.9775630073F, 0.9776496418F,
  152277. 0.9777360398F, 0.9778222016F, 0.9779081277F, 0.9779938182F,
  152278. 0.9780792736F, 0.9781644943F, 0.9782494805F, 0.9783342326F,
  152279. 0.9784187509F, 0.9785030359F, 0.9785870877F, 0.9786709069F,
  152280. 0.9787544936F, 0.9788378484F, 0.9789209714F, 0.9790038631F,
  152281. 0.9790865238F, 0.9791689538F, 0.9792511535F, 0.9793331232F,
  152282. 0.9794148633F, 0.9794963742F, 0.9795776561F, 0.9796587094F,
  152283. 0.9797395345F, 0.9798201316F, 0.9799005013F, 0.9799806437F,
  152284. 0.9800605593F, 0.9801402483F, 0.9802197112F, 0.9802989483F,
  152285. 0.9803779600F, 0.9804567465F, 0.9805353082F, 0.9806136455F,
  152286. 0.9806917587F, 0.9807696482F, 0.9808473143F, 0.9809247574F,
  152287. 0.9810019778F, 0.9810789759F, 0.9811557519F, 0.9812323064F,
  152288. 0.9813086395F, 0.9813847517F, 0.9814606433F, 0.9815363147F,
  152289. 0.9816117662F, 0.9816869981F, 0.9817620108F, 0.9818368047F,
  152290. 0.9819113801F, 0.9819857374F, 0.9820598769F, 0.9821337989F,
  152291. 0.9822075038F, 0.9822809920F, 0.9823542638F, 0.9824273195F,
  152292. 0.9825001596F, 0.9825727843F, 0.9826451940F, 0.9827173891F,
  152293. 0.9827893700F, 0.9828611368F, 0.9829326901F, 0.9830040302F,
  152294. 0.9830751574F, 0.9831460720F, 0.9832167745F, 0.9832872652F,
  152295. 0.9833575444F, 0.9834276124F, 0.9834974697F, 0.9835671166F,
  152296. 0.9836365535F, 0.9837057806F, 0.9837747983F, 0.9838436071F,
  152297. 0.9839122072F, 0.9839805990F, 0.9840487829F, 0.9841167591F,
  152298. 0.9841845282F, 0.9842520903F, 0.9843194459F, 0.9843865953F,
  152299. 0.9844535389F, 0.9845202771F, 0.9845868101F, 0.9846531383F,
  152300. 0.9847192622F, 0.9847851820F, 0.9848508980F, 0.9849164108F,
  152301. 0.9849817205F, 0.9850468276F, 0.9851117324F, 0.9851764352F,
  152302. 0.9852409365F, 0.9853052366F, 0.9853693358F, 0.9854332344F,
  152303. 0.9854969330F, 0.9855604317F, 0.9856237309F, 0.9856868310F,
  152304. 0.9857497325F, 0.9858124355F, 0.9858749404F, 0.9859372477F,
  152305. 0.9859993577F, 0.9860612707F, 0.9861229871F, 0.9861845072F,
  152306. 0.9862458315F, 0.9863069601F, 0.9863678936F, 0.9864286322F,
  152307. 0.9864891764F, 0.9865495264F, 0.9866096826F, 0.9866696454F,
  152308. 0.9867294152F, 0.9867889922F, 0.9868483769F, 0.9869075695F,
  152309. 0.9869665706F, 0.9870253803F, 0.9870839991F, 0.9871424273F,
  152310. 0.9872006653F, 0.9872587135F, 0.9873165721F, 0.9873742415F,
  152311. 0.9874317222F, 0.9874890144F, 0.9875461185F, 0.9876030348F,
  152312. 0.9876597638F, 0.9877163057F, 0.9877726610F, 0.9878288300F,
  152313. 0.9878848130F, 0.9879406104F, 0.9879962225F, 0.9880516497F,
  152314. 0.9881068924F, 0.9881619509F, 0.9882168256F, 0.9882715168F,
  152315. 0.9883260249F, 0.9883803502F, 0.9884344931F, 0.9884884539F,
  152316. 0.9885422331F, 0.9885958309F, 0.9886492477F, 0.9887024838F,
  152317. 0.9887555397F, 0.9888084157F, 0.9888611120F, 0.9889136292F,
  152318. 0.9889659675F, 0.9890181273F, 0.9890701089F, 0.9891219128F,
  152319. 0.9891735392F, 0.9892249885F, 0.9892762610F, 0.9893273572F,
  152320. 0.9893782774F, 0.9894290219F, 0.9894795911F, 0.9895299853F,
  152321. 0.9895802049F, 0.9896302502F, 0.9896801217F, 0.9897298196F,
  152322. 0.9897793443F, 0.9898286961F, 0.9898778755F, 0.9899268828F,
  152323. 0.9899757183F, 0.9900243823F, 0.9900728753F, 0.9901211976F,
  152324. 0.9901693495F, 0.9902173314F, 0.9902651436F, 0.9903127865F,
  152325. 0.9903602605F, 0.9904075659F, 0.9904547031F, 0.9905016723F,
  152326. 0.9905484740F, 0.9905951086F, 0.9906415763F, 0.9906878775F,
  152327. 0.9907340126F, 0.9907799819F, 0.9908257858F, 0.9908714247F,
  152328. 0.9909168988F, 0.9909622086F, 0.9910073543F, 0.9910523364F,
  152329. 0.9910971552F, 0.9911418110F, 0.9911863042F, 0.9912306351F,
  152330. 0.9912748042F, 0.9913188117F, 0.9913626580F, 0.9914063435F,
  152331. 0.9914498684F, 0.9914932333F, 0.9915364383F, 0.9915794839F,
  152332. 0.9916223703F, 0.9916650981F, 0.9917076674F, 0.9917500787F,
  152333. 0.9917923323F, 0.9918344286F, 0.9918763679F, 0.9919181505F,
  152334. 0.9919597769F, 0.9920012473F, 0.9920425621F, 0.9920837217F,
  152335. 0.9921247263F, 0.9921655765F, 0.9922062724F, 0.9922468145F,
  152336. 0.9922872030F, 0.9923274385F, 0.9923675211F, 0.9924074513F,
  152337. 0.9924472294F, 0.9924868557F, 0.9925263306F, 0.9925656544F,
  152338. 0.9926048275F, 0.9926438503F, 0.9926827230F, 0.9927214461F,
  152339. 0.9927600199F, 0.9927984446F, 0.9928367208F, 0.9928748486F,
  152340. 0.9929128285F, 0.9929506608F, 0.9929883459F, 0.9930258841F,
  152341. 0.9930632757F, 0.9931005211F, 0.9931376207F, 0.9931745747F,
  152342. 0.9932113836F, 0.9932480476F, 0.9932845671F, 0.9933209425F,
  152343. 0.9933571742F, 0.9933932623F, 0.9934292074F, 0.9934650097F,
  152344. 0.9935006696F, 0.9935361874F, 0.9935715635F, 0.9936067982F,
  152345. 0.9936418919F, 0.9936768448F, 0.9937116574F, 0.9937463300F,
  152346. 0.9937808629F, 0.9938152565F, 0.9938495111F, 0.9938836271F,
  152347. 0.9939176047F, 0.9939514444F, 0.9939851465F, 0.9940187112F,
  152348. 0.9940521391F, 0.9940854303F, 0.9941185853F, 0.9941516044F,
  152349. 0.9941844879F, 0.9942172361F, 0.9942498495F, 0.9942823283F,
  152350. 0.9943146729F, 0.9943468836F, 0.9943789608F, 0.9944109047F,
  152351. 0.9944427158F, 0.9944743944F, 0.9945059408F, 0.9945373553F,
  152352. 0.9945686384F, 0.9945997902F, 0.9946308112F, 0.9946617017F,
  152353. 0.9946924621F, 0.9947230926F, 0.9947535937F, 0.9947839656F,
  152354. 0.9948142086F, 0.9948443232F, 0.9948743097F, 0.9949041683F,
  152355. 0.9949338995F, 0.9949635035F, 0.9949929807F, 0.9950223315F,
  152356. 0.9950515561F, 0.9950806549F, 0.9951096282F, 0.9951384764F,
  152357. 0.9951671998F, 0.9951957987F, 0.9952242735F, 0.9952526245F,
  152358. 0.9952808520F, 0.9953089564F, 0.9953369380F, 0.9953647971F,
  152359. 0.9953925340F, 0.9954201491F, 0.9954476428F, 0.9954750153F,
  152360. 0.9955022670F, 0.9955293981F, 0.9955564092F, 0.9955833003F,
  152361. 0.9956100720F, 0.9956367245F, 0.9956632582F, 0.9956896733F,
  152362. 0.9957159703F, 0.9957421494F, 0.9957682110F, 0.9957941553F,
  152363. 0.9958199828F, 0.9958456937F, 0.9958712884F, 0.9958967672F,
  152364. 0.9959221305F, 0.9959473784F, 0.9959725115F, 0.9959975300F,
  152365. 0.9960224342F, 0.9960472244F, 0.9960719011F, 0.9960964644F,
  152366. 0.9961209148F, 0.9961452525F, 0.9961694779F, 0.9961935913F,
  152367. 0.9962175930F, 0.9962414834F, 0.9962652627F, 0.9962889313F,
  152368. 0.9963124895F, 0.9963359377F, 0.9963592761F, 0.9963825051F,
  152369. 0.9964056250F, 0.9964286361F, 0.9964515387F, 0.9964743332F,
  152370. 0.9964970198F, 0.9965195990F, 0.9965420709F, 0.9965644360F,
  152371. 0.9965866946F, 0.9966088469F, 0.9966308932F, 0.9966528340F,
  152372. 0.9966746695F, 0.9966964001F, 0.9967180260F, 0.9967395475F,
  152373. 0.9967609651F, 0.9967822789F, 0.9968034894F, 0.9968245968F,
  152374. 0.9968456014F, 0.9968665036F, 0.9968873037F, 0.9969080019F,
  152375. 0.9969285987F, 0.9969490942F, 0.9969694889F, 0.9969897830F,
  152376. 0.9970099769F, 0.9970300708F, 0.9970500651F, 0.9970699601F,
  152377. 0.9970897561F, 0.9971094533F, 0.9971290522F, 0.9971485531F,
  152378. 0.9971679561F, 0.9971872617F, 0.9972064702F, 0.9972255818F,
  152379. 0.9972445968F, 0.9972635157F, 0.9972823386F, 0.9973010659F,
  152380. 0.9973196980F, 0.9973382350F, 0.9973566773F, 0.9973750253F,
  152381. 0.9973932791F, 0.9974114392F, 0.9974295059F, 0.9974474793F,
  152382. 0.9974653599F, 0.9974831480F, 0.9975008438F, 0.9975184476F,
  152383. 0.9975359598F, 0.9975533806F, 0.9975707104F, 0.9975879495F,
  152384. 0.9976050981F, 0.9976221566F, 0.9976391252F, 0.9976560043F,
  152385. 0.9976727941F, 0.9976894950F, 0.9977061073F, 0.9977226312F,
  152386. 0.9977390671F, 0.9977554152F, 0.9977716759F, 0.9977878495F,
  152387. 0.9978039361F, 0.9978199363F, 0.9978358501F, 0.9978516780F,
  152388. 0.9978674202F, 0.9978830771F, 0.9978986488F, 0.9979141358F,
  152389. 0.9979295383F, 0.9979448566F, 0.9979600909F, 0.9979752417F,
  152390. 0.9979903091F, 0.9980052936F, 0.9980201952F, 0.9980350145F,
  152391. 0.9980497515F, 0.9980644067F, 0.9980789804F, 0.9980934727F,
  152392. 0.9981078841F, 0.9981222147F, 0.9981364649F, 0.9981506350F,
  152393. 0.9981647253F, 0.9981787360F, 0.9981926674F, 0.9982065199F,
  152394. 0.9982202936F, 0.9982339890F, 0.9982476062F, 0.9982611456F,
  152395. 0.9982746074F, 0.9982879920F, 0.9983012996F, 0.9983145304F,
  152396. 0.9983276849F, 0.9983407632F, 0.9983537657F, 0.9983666926F,
  152397. 0.9983795442F, 0.9983923208F, 0.9984050226F, 0.9984176501F,
  152398. 0.9984302033F, 0.9984426827F, 0.9984550884F, 0.9984674208F,
  152399. 0.9984796802F, 0.9984918667F, 0.9985039808F, 0.9985160227F,
  152400. 0.9985279926F, 0.9985398909F, 0.9985517177F, 0.9985634734F,
  152401. 0.9985751583F, 0.9985867727F, 0.9985983167F, 0.9986097907F,
  152402. 0.9986211949F, 0.9986325297F, 0.9986437953F, 0.9986549919F,
  152403. 0.9986661199F, 0.9986771795F, 0.9986881710F, 0.9986990946F,
  152404. 0.9987099507F, 0.9987207394F, 0.9987314611F, 0.9987421161F,
  152405. 0.9987527045F, 0.9987632267F, 0.9987736829F, 0.9987840734F,
  152406. 0.9987943985F, 0.9988046584F, 0.9988148534F, 0.9988249838F,
  152407. 0.9988350498F, 0.9988450516F, 0.9988549897F, 0.9988648641F,
  152408. 0.9988746753F, 0.9988844233F, 0.9988941086F, 0.9989037313F,
  152409. 0.9989132918F, 0.9989227902F, 0.9989322269F, 0.9989416021F,
  152410. 0.9989509160F, 0.9989601690F, 0.9989693613F, 0.9989784931F,
  152411. 0.9989875647F, 0.9989965763F, 0.9990055283F, 0.9990144208F,
  152412. 0.9990232541F, 0.9990320286F, 0.9990407443F, 0.9990494016F,
  152413. 0.9990580008F, 0.9990665421F, 0.9990750257F, 0.9990834519F,
  152414. 0.9990918209F, 0.9991001331F, 0.9991083886F, 0.9991165877F,
  152415. 0.9991247307F, 0.9991328177F, 0.9991408491F, 0.9991488251F,
  152416. 0.9991567460F, 0.9991646119F, 0.9991724232F, 0.9991801801F,
  152417. 0.9991878828F, 0.9991955316F, 0.9992031267F, 0.9992106684F,
  152418. 0.9992181569F, 0.9992255925F, 0.9992329753F, 0.9992403057F,
  152419. 0.9992475839F, 0.9992548101F, 0.9992619846F, 0.9992691076F,
  152420. 0.9992761793F, 0.9992832001F, 0.9992901701F, 0.9992970895F,
  152421. 0.9993039587F, 0.9993107777F, 0.9993175470F, 0.9993242667F,
  152422. 0.9993309371F, 0.9993375583F, 0.9993441307F, 0.9993506545F,
  152423. 0.9993571298F, 0.9993635570F, 0.9993699362F, 0.9993762678F,
  152424. 0.9993825519F, 0.9993887887F, 0.9993949785F, 0.9994011216F,
  152425. 0.9994072181F, 0.9994132683F, 0.9994192725F, 0.9994252307F,
  152426. 0.9994311434F, 0.9994370107F, 0.9994428327F, 0.9994486099F,
  152427. 0.9994543423F, 0.9994600303F, 0.9994656739F, 0.9994712736F,
  152428. 0.9994768294F, 0.9994823417F, 0.9994878105F, 0.9994932363F,
  152429. 0.9994986191F, 0.9995039592F, 0.9995092568F, 0.9995145122F,
  152430. 0.9995197256F, 0.9995248971F, 0.9995300270F, 0.9995351156F,
  152431. 0.9995401630F, 0.9995451695F, 0.9995501352F, 0.9995550604F,
  152432. 0.9995599454F, 0.9995647903F, 0.9995695953F, 0.9995743607F,
  152433. 0.9995790866F, 0.9995837734F, 0.9995884211F, 0.9995930300F,
  152434. 0.9995976004F, 0.9996021324F, 0.9996066263F, 0.9996110822F,
  152435. 0.9996155004F, 0.9996198810F, 0.9996242244F, 0.9996285306F,
  152436. 0.9996327999F, 0.9996370326F, 0.9996412287F, 0.9996453886F,
  152437. 0.9996495125F, 0.9996536004F, 0.9996576527F, 0.9996616696F,
  152438. 0.9996656512F, 0.9996695977F, 0.9996735094F, 0.9996773865F,
  152439. 0.9996812291F, 0.9996850374F, 0.9996888118F, 0.9996925523F,
  152440. 0.9996962591F, 0.9996999325F, 0.9997035727F, 0.9997071798F,
  152441. 0.9997107541F, 0.9997142957F, 0.9997178049F, 0.9997212818F,
  152442. 0.9997247266F, 0.9997281396F, 0.9997315209F, 0.9997348708F,
  152443. 0.9997381893F, 0.9997414767F, 0.9997447333F, 0.9997479591F,
  152444. 0.9997511544F, 0.9997543194F, 0.9997574542F, 0.9997605591F,
  152445. 0.9997636342F, 0.9997666797F, 0.9997696958F, 0.9997726828F,
  152446. 0.9997756407F, 0.9997785698F, 0.9997814703F, 0.9997843423F,
  152447. 0.9997871860F, 0.9997900016F, 0.9997927894F, 0.9997955494F,
  152448. 0.9997982818F, 0.9998009869F, 0.9998036648F, 0.9998063157F,
  152449. 0.9998089398F, 0.9998115373F, 0.9998141082F, 0.9998166529F,
  152450. 0.9998191715F, 0.9998216642F, 0.9998241311F, 0.9998265724F,
  152451. 0.9998289884F, 0.9998313790F, 0.9998337447F, 0.9998360854F,
  152452. 0.9998384015F, 0.9998406930F, 0.9998429602F, 0.9998452031F,
  152453. 0.9998474221F, 0.9998496171F, 0.9998517885F, 0.9998539364F,
  152454. 0.9998560610F, 0.9998581624F, 0.9998602407F, 0.9998622962F,
  152455. 0.9998643291F, 0.9998663394F, 0.9998683274F, 0.9998702932F,
  152456. 0.9998722370F, 0.9998741589F, 0.9998760591F, 0.9998779378F,
  152457. 0.9998797952F, 0.9998816313F, 0.9998834464F, 0.9998852406F,
  152458. 0.9998870141F, 0.9998887670F, 0.9998904995F, 0.9998922117F,
  152459. 0.9998939039F, 0.9998955761F, 0.9998972285F, 0.9998988613F,
  152460. 0.9999004746F, 0.9999020686F, 0.9999036434F, 0.9999051992F,
  152461. 0.9999067362F, 0.9999082544F, 0.9999097541F, 0.9999112354F,
  152462. 0.9999126984F, 0.9999141433F, 0.9999155703F, 0.9999169794F,
  152463. 0.9999183709F, 0.9999197449F, 0.9999211014F, 0.9999224408F,
  152464. 0.9999237631F, 0.9999250684F, 0.9999263570F, 0.9999276289F,
  152465. 0.9999288843F, 0.9999301233F, 0.9999313461F, 0.9999325529F,
  152466. 0.9999337437F, 0.9999349187F, 0.9999360780F, 0.9999372218F,
  152467. 0.9999383503F, 0.9999394635F, 0.9999405616F, 0.9999416447F,
  152468. 0.9999427129F, 0.9999437665F, 0.9999448055F, 0.9999458301F,
  152469. 0.9999468404F, 0.9999478365F, 0.9999488185F, 0.9999497867F,
  152470. 0.9999507411F, 0.9999516819F, 0.9999526091F, 0.9999535230F,
  152471. 0.9999544236F, 0.9999553111F, 0.9999561856F, 0.9999570472F,
  152472. 0.9999578960F, 0.9999587323F, 0.9999595560F, 0.9999603674F,
  152473. 0.9999611666F, 0.9999619536F, 0.9999627286F, 0.9999634917F,
  152474. 0.9999642431F, 0.9999649828F, 0.9999657110F, 0.9999664278F,
  152475. 0.9999671334F, 0.9999678278F, 0.9999685111F, 0.9999691835F,
  152476. 0.9999698451F, 0.9999704960F, 0.9999711364F, 0.9999717662F,
  152477. 0.9999723858F, 0.9999729950F, 0.9999735942F, 0.9999741834F,
  152478. 0.9999747626F, 0.9999753321F, 0.9999758919F, 0.9999764421F,
  152479. 0.9999769828F, 0.9999775143F, 0.9999780364F, 0.9999785495F,
  152480. 0.9999790535F, 0.9999795485F, 0.9999800348F, 0.9999805124F,
  152481. 0.9999809813F, 0.9999814417F, 0.9999818938F, 0.9999823375F,
  152482. 0.9999827731F, 0.9999832005F, 0.9999836200F, 0.9999840316F,
  152483. 0.9999844353F, 0.9999848314F, 0.9999852199F, 0.9999856008F,
  152484. 0.9999859744F, 0.9999863407F, 0.9999866997F, 0.9999870516F,
  152485. 0.9999873965F, 0.9999877345F, 0.9999880656F, 0.9999883900F,
  152486. 0.9999887078F, 0.9999890190F, 0.9999893237F, 0.9999896220F,
  152487. 0.9999899140F, 0.9999901999F, 0.9999904796F, 0.9999907533F,
  152488. 0.9999910211F, 0.9999912830F, 0.9999915391F, 0.9999917896F,
  152489. 0.9999920345F, 0.9999922738F, 0.9999925077F, 0.9999927363F,
  152490. 0.9999929596F, 0.9999931777F, 0.9999933907F, 0.9999935987F,
  152491. 0.9999938018F, 0.9999940000F, 0.9999941934F, 0.9999943820F,
  152492. 0.9999945661F, 0.9999947456F, 0.9999949206F, 0.9999950912F,
  152493. 0.9999952575F, 0.9999954195F, 0.9999955773F, 0.9999957311F,
  152494. 0.9999958807F, 0.9999960265F, 0.9999961683F, 0.9999963063F,
  152495. 0.9999964405F, 0.9999965710F, 0.9999966979F, 0.9999968213F,
  152496. 0.9999969412F, 0.9999970576F, 0.9999971707F, 0.9999972805F,
  152497. 0.9999973871F, 0.9999974905F, 0.9999975909F, 0.9999976881F,
  152498. 0.9999977824F, 0.9999978738F, 0.9999979624F, 0.9999980481F,
  152499. 0.9999981311F, 0.9999982115F, 0.9999982892F, 0.9999983644F,
  152500. 0.9999984370F, 0.9999985072F, 0.9999985750F, 0.9999986405F,
  152501. 0.9999987037F, 0.9999987647F, 0.9999988235F, 0.9999988802F,
  152502. 0.9999989348F, 0.9999989873F, 0.9999990379F, 0.9999990866F,
  152503. 0.9999991334F, 0.9999991784F, 0.9999992217F, 0.9999992632F,
  152504. 0.9999993030F, 0.9999993411F, 0.9999993777F, 0.9999994128F,
  152505. 0.9999994463F, 0.9999994784F, 0.9999995091F, 0.9999995384F,
  152506. 0.9999995663F, 0.9999995930F, 0.9999996184F, 0.9999996426F,
  152507. 0.9999996657F, 0.9999996876F, 0.9999997084F, 0.9999997282F,
  152508. 0.9999997469F, 0.9999997647F, 0.9999997815F, 0.9999997973F,
  152509. 0.9999998123F, 0.9999998265F, 0.9999998398F, 0.9999998524F,
  152510. 0.9999998642F, 0.9999998753F, 0.9999998857F, 0.9999998954F,
  152511. 0.9999999045F, 0.9999999130F, 0.9999999209F, 0.9999999282F,
  152512. 0.9999999351F, 0.9999999414F, 0.9999999472F, 0.9999999526F,
  152513. 0.9999999576F, 0.9999999622F, 0.9999999664F, 0.9999999702F,
  152514. 0.9999999737F, 0.9999999769F, 0.9999999798F, 0.9999999824F,
  152515. 0.9999999847F, 0.9999999868F, 0.9999999887F, 0.9999999904F,
  152516. 0.9999999919F, 0.9999999932F, 0.9999999943F, 0.9999999953F,
  152517. 0.9999999961F, 0.9999999969F, 0.9999999975F, 0.9999999980F,
  152518. 0.9999999985F, 0.9999999988F, 0.9999999991F, 0.9999999993F,
  152519. 0.9999999995F, 0.9999999997F, 0.9999999998F, 0.9999999999F,
  152520. 0.9999999999F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  152521. 1.0000000000F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  152522. };
  152523. static float *vwin[8] = {
  152524. vwin64,
  152525. vwin128,
  152526. vwin256,
  152527. vwin512,
  152528. vwin1024,
  152529. vwin2048,
  152530. vwin4096,
  152531. vwin8192,
  152532. };
  152533. float *_vorbis_window_get(int n){
  152534. return vwin[n];
  152535. }
  152536. void _vorbis_apply_window(float *d,int *winno,long *blocksizes,
  152537. int lW,int W,int nW){
  152538. lW=(W?lW:0);
  152539. nW=(W?nW:0);
  152540. {
  152541. float *windowLW=vwin[winno[lW]];
  152542. float *windowNW=vwin[winno[nW]];
  152543. long n=blocksizes[W];
  152544. long ln=blocksizes[lW];
  152545. long rn=blocksizes[nW];
  152546. long leftbegin=n/4-ln/4;
  152547. long leftend=leftbegin+ln/2;
  152548. long rightbegin=n/2+n/4-rn/4;
  152549. long rightend=rightbegin+rn/2;
  152550. int i,p;
  152551. for(i=0;i<leftbegin;i++)
  152552. d[i]=0.f;
  152553. for(p=0;i<leftend;i++,p++)
  152554. d[i]*=windowLW[p];
  152555. for(i=rightbegin,p=rn/2-1;i<rightend;i++,p--)
  152556. d[i]*=windowNW[p];
  152557. for(;i<n;i++)
  152558. d[i]=0.f;
  152559. }
  152560. }
  152561. #endif
  152562. /********* End of inlined file: window.c *********/
  152563. }
  152564. BEGIN_JUCE_NAMESPACE
  152565. using namespace OggVorbisNamespace;
  152566. #define oggFormatName TRANS("Ogg-Vorbis file")
  152567. static const tchar* const oggExtensions[] = { T(".ogg"), 0 };
  152568. class OggReader : public AudioFormatReader
  152569. {
  152570. OggVorbis_File ovFile;
  152571. ov_callbacks callbacks;
  152572. AudioSampleBuffer reservoir;
  152573. int reservoirStart, samplesInReservoir;
  152574. public:
  152575. OggReader (InputStream* const inp)
  152576. : AudioFormatReader (inp, oggFormatName),
  152577. reservoir (2, 2048),
  152578. reservoirStart (0),
  152579. samplesInReservoir (0)
  152580. {
  152581. sampleRate = 0;
  152582. usesFloatingPointData = true;
  152583. callbacks.read_func = &oggReadCallback;
  152584. callbacks.seek_func = &oggSeekCallback;
  152585. callbacks.close_func = &oggCloseCallback;
  152586. callbacks.tell_func = &oggTellCallback;
  152587. const int err = ov_open_callbacks (input, &ovFile, 0, 0, callbacks);
  152588. if (err == 0)
  152589. {
  152590. vorbis_info* info = ov_info (&ovFile, -1);
  152591. lengthInSamples = (uint32) ov_pcm_total (&ovFile, -1);
  152592. numChannels = info->channels;
  152593. bitsPerSample = 16;
  152594. sampleRate = info->rate;
  152595. reservoir.setSize (numChannels,
  152596. (int) jmin (lengthInSamples, (int64) reservoir.getNumSamples()));
  152597. }
  152598. }
  152599. ~OggReader()
  152600. {
  152601. ov_clear (&ovFile);
  152602. }
  152603. bool read (int** destSamples,
  152604. int64 startSampleInFile,
  152605. int numSamples)
  152606. {
  152607. if (startSampleInFile < reservoirStart
  152608. || startSampleInFile + numSamples > reservoirStart + samplesInReservoir)
  152609. {
  152610. // buffer miss, so refill the reservoir
  152611. int bitStream = 0;
  152612. reservoirStart = (int) jmax ((int64) 0, startSampleInFile - 32);
  152613. samplesInReservoir = jmax (numSamples + 32, reservoir.getNumSamples());
  152614. reservoir.setSize (numChannels, samplesInReservoir, false, false, true);
  152615. if (reservoirStart != (int) ov_pcm_tell (&ovFile))
  152616. ov_pcm_seek (&ovFile, reservoirStart);
  152617. int offset = 0;
  152618. int numToRead = samplesInReservoir;
  152619. while (numToRead > 0)
  152620. {
  152621. float** dataIn = 0;
  152622. const int samps = ov_read_float (&ovFile, &dataIn, numToRead, &bitStream);
  152623. if (samps == 0)
  152624. break;
  152625. jassert (samps <= numToRead);
  152626. for (int i = jmin (numChannels, reservoir.getNumChannels()); --i >= 0;)
  152627. {
  152628. memcpy (reservoir.getSampleData (i, offset),
  152629. dataIn[i],
  152630. sizeof (float) * samps);
  152631. }
  152632. numToRead -= samps;
  152633. offset += samps;
  152634. }
  152635. if (numToRead > 0)
  152636. reservoir.clear (offset, numToRead);
  152637. }
  152638. if (numSamples > 0)
  152639. {
  152640. for (unsigned int i = 0; i < numChannels; ++i)
  152641. {
  152642. if (destSamples[i] == 0)
  152643. break;
  152644. memcpy (destSamples[i],
  152645. reservoir.getSampleData (jmin (i, reservoir.getNumChannels()),
  152646. (int) (startSampleInFile - reservoirStart)),
  152647. sizeof (float) * numSamples);
  152648. }
  152649. }
  152650. return true;
  152651. }
  152652. static size_t oggReadCallback (void* ptr, size_t size, size_t nmemb, void* datasource)
  152653. {
  152654. return (size_t) (((InputStream*) datasource)->read (ptr, (int) (size * nmemb)) / size);
  152655. }
  152656. static int oggSeekCallback (void* datasource, ogg_int64_t offset, int whence)
  152657. {
  152658. InputStream* const in = (InputStream*) datasource;
  152659. if (whence == SEEK_CUR)
  152660. offset += in->getPosition();
  152661. else if (whence == SEEK_END)
  152662. offset += in->getTotalLength();
  152663. in->setPosition (offset);
  152664. return 0;
  152665. }
  152666. static int oggCloseCallback (void*)
  152667. {
  152668. return 0;
  152669. }
  152670. static long oggTellCallback (void* datasource)
  152671. {
  152672. return (long) ((InputStream*) datasource)->getPosition();
  152673. }
  152674. juce_UseDebuggingNewOperator
  152675. };
  152676. class OggWriter : public AudioFormatWriter
  152677. {
  152678. ogg_stream_state os;
  152679. ogg_page og;
  152680. ogg_packet op;
  152681. vorbis_info vi;
  152682. vorbis_comment vc;
  152683. vorbis_dsp_state vd;
  152684. vorbis_block vb;
  152685. public:
  152686. bool ok;
  152687. OggWriter (OutputStream* const out,
  152688. const double sampleRate,
  152689. const int numChannels,
  152690. const int bitsPerSample,
  152691. const int qualityIndex)
  152692. : AudioFormatWriter (out, oggFormatName,
  152693. sampleRate,
  152694. numChannels,
  152695. bitsPerSample)
  152696. {
  152697. ok = false;
  152698. vorbis_info_init (&vi);
  152699. if (vorbis_encode_init_vbr (&vi,
  152700. numChannels,
  152701. (int) sampleRate,
  152702. jlimit (0.0f, 1.0f, qualityIndex * 0.5f)) == 0)
  152703. {
  152704. vorbis_comment_init (&vc);
  152705. if (JUCEApplication::getInstance() != 0)
  152706. vorbis_comment_add_tag (&vc, "ENCODER",
  152707. (char*) (const char*) JUCEApplication::getInstance()->getApplicationName());
  152708. vorbis_analysis_init (&vd, &vi);
  152709. vorbis_block_init (&vd, &vb);
  152710. ogg_stream_init (&os, Random::getSystemRandom().nextInt());
  152711. ogg_packet header;
  152712. ogg_packet header_comm;
  152713. ogg_packet header_code;
  152714. vorbis_analysis_headerout (&vd, &vc, &header, &header_comm, &header_code);
  152715. ogg_stream_packetin (&os, &header);
  152716. ogg_stream_packetin (&os, &header_comm);
  152717. ogg_stream_packetin (&os, &header_code);
  152718. for (;;)
  152719. {
  152720. if (ogg_stream_flush (&os, &og) == 0)
  152721. break;
  152722. output->write (og.header, og.header_len);
  152723. output->write (og.body, og.body_len);
  152724. }
  152725. ok = true;
  152726. }
  152727. }
  152728. ~OggWriter()
  152729. {
  152730. if (ok)
  152731. {
  152732. ogg_stream_clear (&os);
  152733. vorbis_block_clear (&vb);
  152734. vorbis_dsp_clear (&vd);
  152735. vorbis_comment_clear (&vc);
  152736. vorbis_info_clear (&vi);
  152737. output->flush();
  152738. }
  152739. else
  152740. {
  152741. vorbis_info_clear (&vi);
  152742. output = 0; // to stop the base class deleting this, as it needs to be returned
  152743. // to the caller of createWriter()
  152744. }
  152745. }
  152746. bool write (const int** samplesToWrite, int numSamples)
  152747. {
  152748. if (! ok)
  152749. return false;
  152750. if (numSamples > 0)
  152751. {
  152752. const double gain = 1.0 / 0x80000000u;
  152753. float** const vorbisBuffer = vorbis_analysis_buffer (&vd, numSamples);
  152754. for (int i = numChannels; --i >= 0;)
  152755. {
  152756. float* const dst = vorbisBuffer[i];
  152757. const int* const src = samplesToWrite [i];
  152758. if (src != 0 && dst != 0)
  152759. {
  152760. for (int j = 0; j < numSamples; ++j)
  152761. dst[j] = (float) (src[j] * gain);
  152762. }
  152763. }
  152764. }
  152765. vorbis_analysis_wrote (&vd, numSamples);
  152766. while (vorbis_analysis_blockout (&vd, &vb) == 1)
  152767. {
  152768. vorbis_analysis (&vb, 0);
  152769. vorbis_bitrate_addblock (&vb);
  152770. while (vorbis_bitrate_flushpacket (&vd, &op))
  152771. {
  152772. ogg_stream_packetin (&os, &op);
  152773. for (;;)
  152774. {
  152775. if (ogg_stream_pageout (&os, &og) == 0)
  152776. break;
  152777. output->write (og.header, og.header_len);
  152778. output->write (og.body, og.body_len);
  152779. if (ogg_page_eos (&og))
  152780. break;
  152781. }
  152782. }
  152783. }
  152784. return true;
  152785. }
  152786. juce_UseDebuggingNewOperator
  152787. };
  152788. OggVorbisAudioFormat::OggVorbisAudioFormat()
  152789. : AudioFormat (oggFormatName, (const tchar**) oggExtensions)
  152790. {
  152791. }
  152792. OggVorbisAudioFormat::~OggVorbisAudioFormat()
  152793. {
  152794. }
  152795. const Array <int> OggVorbisAudioFormat::getPossibleSampleRates()
  152796. {
  152797. const int rates[] = { 22050, 32000, 44100, 48000, 0 };
  152798. return Array <int> (rates);
  152799. }
  152800. const Array <int> OggVorbisAudioFormat::getPossibleBitDepths()
  152801. {
  152802. Array <int> depths;
  152803. depths.add (32);
  152804. return depths;
  152805. }
  152806. bool OggVorbisAudioFormat::canDoStereo()
  152807. {
  152808. return true;
  152809. }
  152810. bool OggVorbisAudioFormat::canDoMono()
  152811. {
  152812. return true;
  152813. }
  152814. AudioFormatReader* OggVorbisAudioFormat::createReaderFor (InputStream* in,
  152815. const bool deleteStreamIfOpeningFails)
  152816. {
  152817. OggReader* r = new OggReader (in);
  152818. if (r->sampleRate == 0)
  152819. {
  152820. if (! deleteStreamIfOpeningFails)
  152821. r->input = 0;
  152822. deleteAndZero (r);
  152823. }
  152824. return r;
  152825. }
  152826. AudioFormatWriter* OggVorbisAudioFormat::createWriterFor (OutputStream* out,
  152827. double sampleRate,
  152828. unsigned int numChannels,
  152829. int bitsPerSample,
  152830. const StringPairArray& /*metadataValues*/,
  152831. int qualityOptionIndex)
  152832. {
  152833. OggWriter* w = new OggWriter (out,
  152834. sampleRate,
  152835. numChannels,
  152836. bitsPerSample,
  152837. qualityOptionIndex);
  152838. if (! w->ok)
  152839. deleteAndZero (w);
  152840. return w;
  152841. }
  152842. bool OggVorbisAudioFormat::isCompressed()
  152843. {
  152844. return true;
  152845. }
  152846. const StringArray OggVorbisAudioFormat::getQualityOptions()
  152847. {
  152848. StringArray s;
  152849. s.add ("Low Quality");
  152850. s.add ("Medium Quality");
  152851. s.add ("High Quality");
  152852. return s;
  152853. }
  152854. int OggVorbisAudioFormat::estimateOggFileQuality (const File& source)
  152855. {
  152856. FileInputStream* const in = source.createInputStream();
  152857. if (in != 0)
  152858. {
  152859. AudioFormatReader* const r = createReaderFor (in, true);
  152860. if (r != 0)
  152861. {
  152862. const int64 numSamps = r->lengthInSamples;
  152863. delete r;
  152864. const int64 fileNumSamps = source.getSize() / 4;
  152865. const double ratio = numSamps / (double) fileNumSamps;
  152866. if (ratio > 12.0)
  152867. return 0;
  152868. else if (ratio > 6.0)
  152869. return 1;
  152870. else
  152871. return 2;
  152872. }
  152873. }
  152874. return 1;
  152875. }
  152876. END_JUCE_NAMESPACE
  152877. #endif
  152878. /********* End of inlined file: juce_OggVorbisAudioFormat.cpp *********/
  152879. /********* Start of inlined file: juce_JPEGLoader.cpp *********/
  152880. #if JUCE_MSVC
  152881. #pragma warning (push)
  152882. #endif
  152883. namespace jpeglibNamespace
  152884. {
  152885. extern "C"
  152886. {
  152887. #define JPEG_INTERNALS
  152888. #undef FAR
  152889. /********* Start of inlined file: jpeglib.h *********/
  152890. #ifndef JPEGLIB_H
  152891. #define JPEGLIB_H
  152892. /*
  152893. * First we include the configuration files that record how this
  152894. * installation of the JPEG library is set up. jconfig.h can be
  152895. * generated automatically for many systems. jmorecfg.h contains
  152896. * manual configuration options that most people need not worry about.
  152897. */
  152898. #ifndef JCONFIG_INCLUDED /* in case jinclude.h already did */
  152899. /********* Start of inlined file: jconfig.h *********/
  152900. /* see jconfig.doc for explanations */
  152901. // disable all the warnings under MSVC
  152902. #ifdef _MSC_VER
  152903. #pragma warning (disable: 4996 4267 4100 4127 4702 4244)
  152904. #endif
  152905. #ifdef __BORLANDC__
  152906. #pragma warn -8057
  152907. #pragma warn -8019
  152908. #pragma warn -8004
  152909. #pragma warn -8008
  152910. #endif
  152911. #define HAVE_PROTOTYPES
  152912. #define HAVE_UNSIGNED_CHAR
  152913. #define HAVE_UNSIGNED_SHORT
  152914. /* #define void char */
  152915. /* #define const */
  152916. #undef CHAR_IS_UNSIGNED
  152917. #define HAVE_STDDEF_H
  152918. #define HAVE_STDLIB_H
  152919. #undef NEED_BSD_STRINGS
  152920. #undef NEED_SYS_TYPES_H
  152921. #undef NEED_FAR_POINTERS /* we presume a 32-bit flat memory model */
  152922. #undef NEED_SHORT_EXTERNAL_NAMES
  152923. #undef INCOMPLETE_TYPES_BROKEN
  152924. /* Define "boolean" as unsigned char, not int, per Windows custom */
  152925. #ifndef __RPCNDR_H__ /* don't conflict if rpcndr.h already read */
  152926. typedef unsigned char boolean;
  152927. #endif
  152928. #define HAVE_BOOLEAN /* prevent jmorecfg.h from redefining it */
  152929. #ifdef JPEG_INTERNALS
  152930. #undef RIGHT_SHIFT_IS_UNSIGNED
  152931. #endif /* JPEG_INTERNALS */
  152932. #ifdef JPEG_CJPEG_DJPEG
  152933. #define BMP_SUPPORTED /* BMP image file format */
  152934. #define GIF_SUPPORTED /* GIF image file format */
  152935. #define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */
  152936. #undef RLE_SUPPORTED /* Utah RLE image file format */
  152937. #define TARGA_SUPPORTED /* Targa image file format */
  152938. #define TWO_FILE_COMMANDLINE /* optional */
  152939. #define USE_SETMODE /* Microsoft has setmode() */
  152940. #undef NEED_SIGNAL_CATCHER
  152941. #undef DONT_USE_B_MODE
  152942. #undef PROGRESS_REPORT /* optional */
  152943. #endif /* JPEG_CJPEG_DJPEG */
  152944. /********* End of inlined file: jconfig.h *********/
  152945. /* widely used configuration options */
  152946. #endif
  152947. /********* Start of inlined file: jmorecfg.h *********/
  152948. /*
  152949. * Define BITS_IN_JSAMPLE as either
  152950. * 8 for 8-bit sample values (the usual setting)
  152951. * 12 for 12-bit sample values
  152952. * Only 8 and 12 are legal data precisions for lossy JPEG according to the
  152953. * JPEG standard, and the IJG code does not support anything else!
  152954. * We do not support run-time selection of data precision, sorry.
  152955. */
  152956. #define BITS_IN_JSAMPLE 8 /* use 8 or 12 */
  152957. /*
  152958. * Maximum number of components (color channels) allowed in JPEG image.
  152959. * To meet the letter of the JPEG spec, set this to 255. However, darn
  152960. * few applications need more than 4 channels (maybe 5 for CMYK + alpha
  152961. * mask). We recommend 10 as a reasonable compromise; use 4 if you are
  152962. * really short on memory. (Each allowed component costs a hundred or so
  152963. * bytes of storage, whether actually used in an image or not.)
  152964. */
  152965. #define MAX_COMPONENTS 10 /* maximum number of image components */
  152966. /*
  152967. * Basic data types.
  152968. * You may need to change these if you have a machine with unusual data
  152969. * type sizes; for example, "char" not 8 bits, "short" not 16 bits,
  152970. * or "long" not 32 bits. We don't care whether "int" is 16 or 32 bits,
  152971. * but it had better be at least 16.
  152972. */
  152973. /* Representation of a single sample (pixel element value).
  152974. * We frequently allocate large arrays of these, so it's important to keep
  152975. * them small. But if you have memory to burn and access to char or short
  152976. * arrays is very slow on your hardware, you might want to change these.
  152977. */
  152978. #if BITS_IN_JSAMPLE == 8
  152979. /* JSAMPLE should be the smallest type that will hold the values 0..255.
  152980. * You can use a signed char by having GETJSAMPLE mask it with 0xFF.
  152981. */
  152982. #ifdef HAVE_UNSIGNED_CHAR
  152983. typedef unsigned char JSAMPLE;
  152984. #define GETJSAMPLE(value) ((int) (value))
  152985. #else /* not HAVE_UNSIGNED_CHAR */
  152986. typedef char JSAMPLE;
  152987. #ifdef CHAR_IS_UNSIGNED
  152988. #define GETJSAMPLE(value) ((int) (value))
  152989. #else
  152990. #define GETJSAMPLE(value) ((int) (value) & 0xFF)
  152991. #endif /* CHAR_IS_UNSIGNED */
  152992. #endif /* HAVE_UNSIGNED_CHAR */
  152993. #define MAXJSAMPLE 255
  152994. #define CENTERJSAMPLE 128
  152995. #endif /* BITS_IN_JSAMPLE == 8 */
  152996. #if BITS_IN_JSAMPLE == 12
  152997. /* JSAMPLE should be the smallest type that will hold the values 0..4095.
  152998. * On nearly all machines "short" will do nicely.
  152999. */
  153000. typedef short JSAMPLE;
  153001. #define GETJSAMPLE(value) ((int) (value))
  153002. #define MAXJSAMPLE 4095
  153003. #define CENTERJSAMPLE 2048
  153004. #endif /* BITS_IN_JSAMPLE == 12 */
  153005. /* Representation of a DCT frequency coefficient.
  153006. * This should be a signed value of at least 16 bits; "short" is usually OK.
  153007. * Again, we allocate large arrays of these, but you can change to int
  153008. * if you have memory to burn and "short" is really slow.
  153009. */
  153010. typedef short JCOEF;
  153011. /* Compressed datastreams are represented as arrays of JOCTET.
  153012. * These must be EXACTLY 8 bits wide, at least once they are written to
  153013. * external storage. Note that when using the stdio data source/destination
  153014. * managers, this is also the data type passed to fread/fwrite.
  153015. */
  153016. #ifdef HAVE_UNSIGNED_CHAR
  153017. typedef unsigned char JOCTET;
  153018. #define GETJOCTET(value) (value)
  153019. #else /* not HAVE_UNSIGNED_CHAR */
  153020. typedef char JOCTET;
  153021. #ifdef CHAR_IS_UNSIGNED
  153022. #define GETJOCTET(value) (value)
  153023. #else
  153024. #define GETJOCTET(value) ((value) & 0xFF)
  153025. #endif /* CHAR_IS_UNSIGNED */
  153026. #endif /* HAVE_UNSIGNED_CHAR */
  153027. /* These typedefs are used for various table entries and so forth.
  153028. * They must be at least as wide as specified; but making them too big
  153029. * won't cost a huge amount of memory, so we don't provide special
  153030. * extraction code like we did for JSAMPLE. (In other words, these
  153031. * typedefs live at a different point on the speed/space tradeoff curve.)
  153032. */
  153033. /* UINT8 must hold at least the values 0..255. */
  153034. #ifdef HAVE_UNSIGNED_CHAR
  153035. typedef unsigned char UINT8;
  153036. #else /* not HAVE_UNSIGNED_CHAR */
  153037. #ifdef CHAR_IS_UNSIGNED
  153038. typedef char UINT8;
  153039. #else /* not CHAR_IS_UNSIGNED */
  153040. typedef short UINT8;
  153041. #endif /* CHAR_IS_UNSIGNED */
  153042. #endif /* HAVE_UNSIGNED_CHAR */
  153043. /* UINT16 must hold at least the values 0..65535. */
  153044. #ifdef HAVE_UNSIGNED_SHORT
  153045. typedef unsigned short UINT16;
  153046. #else /* not HAVE_UNSIGNED_SHORT */
  153047. typedef unsigned int UINT16;
  153048. #endif /* HAVE_UNSIGNED_SHORT */
  153049. /* INT16 must hold at least the values -32768..32767. */
  153050. #ifndef XMD_H /* X11/xmd.h correctly defines INT16 */
  153051. typedef short INT16;
  153052. #endif
  153053. /* INT32 must hold at least signed 32-bit values. */
  153054. #ifndef XMD_H /* X11/xmd.h correctly defines INT32 */
  153055. typedef long INT32;
  153056. #endif
  153057. /* Datatype used for image dimensions. The JPEG standard only supports
  153058. * images up to 64K*64K due to 16-bit fields in SOF markers. Therefore
  153059. * "unsigned int" is sufficient on all machines. However, if you need to
  153060. * handle larger images and you don't mind deviating from the spec, you
  153061. * can change this datatype.
  153062. */
  153063. typedef unsigned int JDIMENSION;
  153064. #define JPEG_MAX_DIMENSION 65500L /* a tad under 64K to prevent overflows */
  153065. /* These macros are used in all function definitions and extern declarations.
  153066. * You could modify them if you need to change function linkage conventions;
  153067. * in particular, you'll need to do that to make the library a Windows DLL.
  153068. * Another application is to make all functions global for use with debuggers
  153069. * or code profilers that require it.
  153070. */
  153071. /* a function called through method pointers: */
  153072. #define METHODDEF(type) static type
  153073. /* a function used only in its module: */
  153074. #define LOCAL(type) static type
  153075. /* a function referenced thru EXTERNs: */
  153076. #define GLOBAL(type) type
  153077. /* a reference to a GLOBAL function: */
  153078. #define EXTERN(type) extern type
  153079. /* This macro is used to declare a "method", that is, a function pointer.
  153080. * We want to supply prototype parameters if the compiler can cope.
  153081. * Note that the arglist parameter must be parenthesized!
  153082. * Again, you can customize this if you need special linkage keywords.
  153083. */
  153084. #ifdef HAVE_PROTOTYPES
  153085. #define JMETHOD(type,methodname,arglist) type (*methodname) arglist
  153086. #else
  153087. #define JMETHOD(type,methodname,arglist) type (*methodname) ()
  153088. #endif
  153089. /* Here is the pseudo-keyword for declaring pointers that must be "far"
  153090. * on 80x86 machines. Most of the specialized coding for 80x86 is handled
  153091. * by just saying "FAR *" where such a pointer is needed. In a few places
  153092. * explicit coding is needed; see uses of the NEED_FAR_POINTERS symbol.
  153093. */
  153094. #ifdef NEED_FAR_POINTERS
  153095. #define FAR far
  153096. #else
  153097. #define FAR
  153098. #endif
  153099. /*
  153100. * On a few systems, type boolean and/or its values FALSE, TRUE may appear
  153101. * in standard header files. Or you may have conflicts with application-
  153102. * specific header files that you want to include together with these files.
  153103. * Defining HAVE_BOOLEAN before including jpeglib.h should make it work.
  153104. */
  153105. #ifndef HAVE_BOOLEAN
  153106. typedef int boolean;
  153107. #endif
  153108. #ifndef FALSE /* in case these macros already exist */
  153109. #define FALSE 0 /* values of boolean */
  153110. #endif
  153111. #ifndef TRUE
  153112. #define TRUE 1
  153113. #endif
  153114. /*
  153115. * The remaining options affect code selection within the JPEG library,
  153116. * but they don't need to be visible to most applications using the library.
  153117. * To minimize application namespace pollution, the symbols won't be
  153118. * defined unless JPEG_INTERNALS or JPEG_INTERNAL_OPTIONS has been defined.
  153119. */
  153120. #ifdef JPEG_INTERNALS
  153121. #define JPEG_INTERNAL_OPTIONS
  153122. #endif
  153123. #ifdef JPEG_INTERNAL_OPTIONS
  153124. /*
  153125. * These defines indicate whether to include various optional functions.
  153126. * Undefining some of these symbols will produce a smaller but less capable
  153127. * library. Note that you can leave certain source files out of the
  153128. * compilation/linking process if you've #undef'd the corresponding symbols.
  153129. * (You may HAVE to do that if your compiler doesn't like null source files.)
  153130. */
  153131. /* Arithmetic coding is unsupported for legal reasons. Complaints to IBM. */
  153132. /* Capability options common to encoder and decoder: */
  153133. #define DCT_ISLOW_SUPPORTED /* slow but accurate integer algorithm */
  153134. #define DCT_IFAST_SUPPORTED /* faster, less accurate integer method */
  153135. #define DCT_FLOAT_SUPPORTED /* floating-point: accurate, fast on fast HW */
  153136. /* Encoder capability options: */
  153137. #undef C_ARITH_CODING_SUPPORTED /* Arithmetic coding back end? */
  153138. #define C_MULTISCAN_FILES_SUPPORTED /* Multiple-scan JPEG files? */
  153139. #define C_PROGRESSIVE_SUPPORTED /* Progressive JPEG? (Requires MULTISCAN)*/
  153140. #define ENTROPY_OPT_SUPPORTED /* Optimization of entropy coding parms? */
  153141. /* Note: if you selected 12-bit data precision, it is dangerous to turn off
  153142. * ENTROPY_OPT_SUPPORTED. The standard Huffman tables are only good for 8-bit
  153143. * precision, so jchuff.c normally uses entropy optimization to compute
  153144. * usable tables for higher precision. If you don't want to do optimization,
  153145. * you'll have to supply different default Huffman tables.
  153146. * The exact same statements apply for progressive JPEG: the default tables
  153147. * don't work for progressive mode. (This may get fixed, however.)
  153148. */
  153149. #define INPUT_SMOOTHING_SUPPORTED /* Input image smoothing option? */
  153150. /* Decoder capability options: */
  153151. #undef D_ARITH_CODING_SUPPORTED /* Arithmetic coding back end? */
  153152. #define D_MULTISCAN_FILES_SUPPORTED /* Multiple-scan JPEG files? */
  153153. #define D_PROGRESSIVE_SUPPORTED /* Progressive JPEG? (Requires MULTISCAN)*/
  153154. #define SAVE_MARKERS_SUPPORTED /* jpeg_save_markers() needed? */
  153155. #define BLOCK_SMOOTHING_SUPPORTED /* Block smoothing? (Progressive only) */
  153156. #define IDCT_SCALING_SUPPORTED /* Output rescaling via IDCT? */
  153157. #undef UPSAMPLE_SCALING_SUPPORTED /* Output rescaling at upsample stage? */
  153158. #define UPSAMPLE_MERGING_SUPPORTED /* Fast path for sloppy upsampling? */
  153159. #define QUANT_1PASS_SUPPORTED /* 1-pass color quantization? */
  153160. #define QUANT_2PASS_SUPPORTED /* 2-pass color quantization? */
  153161. /* more capability options later, no doubt */
  153162. /*
  153163. * Ordering of RGB data in scanlines passed to or from the application.
  153164. * If your application wants to deal with data in the order B,G,R, just
  153165. * change these macros. You can also deal with formats such as R,G,B,X
  153166. * (one extra byte per pixel) by changing RGB_PIXELSIZE. Note that changing
  153167. * the offsets will also change the order in which colormap data is organized.
  153168. * RESTRICTIONS:
  153169. * 1. The sample applications cjpeg,djpeg do NOT support modified RGB formats.
  153170. * 2. These macros only affect RGB<=>YCbCr color conversion, so they are not
  153171. * useful if you are using JPEG color spaces other than YCbCr or grayscale.
  153172. * 3. The color quantizer modules will not behave desirably if RGB_PIXELSIZE
  153173. * is not 3 (they don't understand about dummy color components!). So you
  153174. * can't use color quantization if you change that value.
  153175. */
  153176. #define RGB_RED 0 /* Offset of Red in an RGB scanline element */
  153177. #define RGB_GREEN 1 /* Offset of Green */
  153178. #define RGB_BLUE 2 /* Offset of Blue */
  153179. #define RGB_PIXELSIZE 3 /* JSAMPLEs per RGB scanline element */
  153180. /* Definitions for speed-related optimizations. */
  153181. /* If your compiler supports inline functions, define INLINE
  153182. * as the inline keyword; otherwise define it as empty.
  153183. */
  153184. #ifndef INLINE
  153185. #ifdef __GNUC__ /* for instance, GNU C knows about inline */
  153186. #define INLINE __inline__
  153187. #endif
  153188. #ifndef INLINE
  153189. #define INLINE /* default is to define it as empty */
  153190. #endif
  153191. #endif
  153192. /* On some machines (notably 68000 series) "int" is 32 bits, but multiplying
  153193. * two 16-bit shorts is faster than multiplying two ints. Define MULTIPLIER
  153194. * as short on such a machine. MULTIPLIER must be at least 16 bits wide.
  153195. */
  153196. #ifndef MULTIPLIER
  153197. #define MULTIPLIER int /* type for fastest integer multiply */
  153198. #endif
  153199. /* FAST_FLOAT should be either float or double, whichever is done faster
  153200. * by your compiler. (Note that this type is only used in the floating point
  153201. * DCT routines, so it only matters if you've defined DCT_FLOAT_SUPPORTED.)
  153202. * Typically, float is faster in ANSI C compilers, while double is faster in
  153203. * pre-ANSI compilers (because they insist on converting to double anyway).
  153204. * The code below therefore chooses float if we have ANSI-style prototypes.
  153205. */
  153206. #ifndef FAST_FLOAT
  153207. #ifdef HAVE_PROTOTYPES
  153208. #define FAST_FLOAT float
  153209. #else
  153210. #define FAST_FLOAT double
  153211. #endif
  153212. #endif
  153213. #endif /* JPEG_INTERNAL_OPTIONS */
  153214. /********* End of inlined file: jmorecfg.h *********/
  153215. /* seldom changed options */
  153216. /* Version ID for the JPEG library.
  153217. * Might be useful for tests like "#if JPEG_LIB_VERSION >= 60".
  153218. */
  153219. #define JPEG_LIB_VERSION 62 /* Version 6b */
  153220. /* Various constants determining the sizes of things.
  153221. * All of these are specified by the JPEG standard, so don't change them
  153222. * if you want to be compatible.
  153223. */
  153224. #define DCTSIZE 8 /* The basic DCT block is 8x8 samples */
  153225. #define DCTSIZE2 64 /* DCTSIZE squared; # of elements in a block */
  153226. #define NUM_QUANT_TBLS 4 /* Quantization tables are numbered 0..3 */
  153227. #define NUM_HUFF_TBLS 4 /* Huffman tables are numbered 0..3 */
  153228. #define NUM_ARITH_TBLS 16 /* Arith-coding tables are numbered 0..15 */
  153229. #define MAX_COMPS_IN_SCAN 4 /* JPEG limit on # of components in one scan */
  153230. #define MAX_SAMP_FACTOR 4 /* JPEG limit on sampling factors */
  153231. /* Unfortunately, some bozo at Adobe saw no reason to be bound by the standard;
  153232. * the PostScript DCT filter can emit files with many more than 10 blocks/MCU.
  153233. * If you happen to run across such a file, you can up D_MAX_BLOCKS_IN_MCU
  153234. * to handle it. We even let you do this from the jconfig.h file. However,
  153235. * we strongly discourage changing C_MAX_BLOCKS_IN_MCU; just because Adobe
  153236. * sometimes emits noncompliant files doesn't mean you should too.
  153237. */
  153238. #define C_MAX_BLOCKS_IN_MCU 10 /* compressor's limit on blocks per MCU */
  153239. #ifndef D_MAX_BLOCKS_IN_MCU
  153240. #define D_MAX_BLOCKS_IN_MCU 10 /* decompressor's limit on blocks per MCU */
  153241. #endif
  153242. /* Data structures for images (arrays of samples and of DCT coefficients).
  153243. * On 80x86 machines, the image arrays are too big for near pointers,
  153244. * but the pointer arrays can fit in near memory.
  153245. */
  153246. typedef JSAMPLE FAR *JSAMPROW; /* ptr to one image row of pixel samples. */
  153247. typedef JSAMPROW *JSAMPARRAY; /* ptr to some rows (a 2-D sample array) */
  153248. typedef JSAMPARRAY *JSAMPIMAGE; /* a 3-D sample array: top index is color */
  153249. typedef JCOEF JBLOCK[DCTSIZE2]; /* one block of coefficients */
  153250. typedef JBLOCK FAR *JBLOCKROW; /* pointer to one row of coefficient blocks */
  153251. typedef JBLOCKROW *JBLOCKARRAY; /* a 2-D array of coefficient blocks */
  153252. typedef JBLOCKARRAY *JBLOCKIMAGE; /* a 3-D array of coefficient blocks */
  153253. typedef JCOEF FAR *JCOEFPTR; /* useful in a couple of places */
  153254. /* Types for JPEG compression parameters and working tables. */
  153255. /* DCT coefficient quantization tables. */
  153256. typedef struct {
  153257. /* This array gives the coefficient quantizers in natural array order
  153258. * (not the zigzag order in which they are stored in a JPEG DQT marker).
  153259. * CAUTION: IJG versions prior to v6a kept this array in zigzag order.
  153260. */
  153261. UINT16 quantval[DCTSIZE2]; /* quantization step for each coefficient */
  153262. /* This field is used only during compression. It's initialized FALSE when
  153263. * the table is created, and set TRUE when it's been output to the file.
  153264. * You could suppress output of a table by setting this to TRUE.
  153265. * (See jpeg_suppress_tables for an example.)
  153266. */
  153267. boolean sent_table; /* TRUE when table has been output */
  153268. } JQUANT_TBL;
  153269. /* Huffman coding tables. */
  153270. typedef struct {
  153271. /* These two fields directly represent the contents of a JPEG DHT marker */
  153272. UINT8 bits[17]; /* bits[k] = # of symbols with codes of */
  153273. /* length k bits; bits[0] is unused */
  153274. UINT8 huffval[256]; /* The symbols, in order of incr code length */
  153275. /* This field is used only during compression. It's initialized FALSE when
  153276. * the table is created, and set TRUE when it's been output to the file.
  153277. * You could suppress output of a table by setting this to TRUE.
  153278. * (See jpeg_suppress_tables for an example.)
  153279. */
  153280. boolean sent_table; /* TRUE when table has been output */
  153281. } JHUFF_TBL;
  153282. /* Basic info about one component (color channel). */
  153283. typedef struct {
  153284. /* These values are fixed over the whole image. */
  153285. /* For compression, they must be supplied by parameter setup; */
  153286. /* for decompression, they are read from the SOF marker. */
  153287. int component_id; /* identifier for this component (0..255) */
  153288. int component_index; /* its index in SOF or cinfo->comp_info[] */
  153289. int h_samp_factor; /* horizontal sampling factor (1..4) */
  153290. int v_samp_factor; /* vertical sampling factor (1..4) */
  153291. int quant_tbl_no; /* quantization table selector (0..3) */
  153292. /* These values may vary between scans. */
  153293. /* For compression, they must be supplied by parameter setup; */
  153294. /* for decompression, they are read from the SOS marker. */
  153295. /* The decompressor output side may not use these variables. */
  153296. int dc_tbl_no; /* DC entropy table selector (0..3) */
  153297. int ac_tbl_no; /* AC entropy table selector (0..3) */
  153298. /* Remaining fields should be treated as private by applications. */
  153299. /* These values are computed during compression or decompression startup: */
  153300. /* Component's size in DCT blocks.
  153301. * Any dummy blocks added to complete an MCU are not counted; therefore
  153302. * these values do not depend on whether a scan is interleaved or not.
  153303. */
  153304. JDIMENSION width_in_blocks;
  153305. JDIMENSION height_in_blocks;
  153306. /* Size of a DCT block in samples. Always DCTSIZE for compression.
  153307. * For decompression this is the size of the output from one DCT block,
  153308. * reflecting any scaling we choose to apply during the IDCT step.
  153309. * Values of 1,2,4,8 are likely to be supported. Note that different
  153310. * components may receive different IDCT scalings.
  153311. */
  153312. int DCT_scaled_size;
  153313. /* The downsampled dimensions are the component's actual, unpadded number
  153314. * of samples at the main buffer (preprocessing/compression interface), thus
  153315. * downsampled_width = ceil(image_width * Hi/Hmax)
  153316. * and similarly for height. For decompression, IDCT scaling is included, so
  153317. * downsampled_width = ceil(image_width * Hi/Hmax * DCT_scaled_size/DCTSIZE)
  153318. */
  153319. JDIMENSION downsampled_width; /* actual width in samples */
  153320. JDIMENSION downsampled_height; /* actual height in samples */
  153321. /* This flag is used only for decompression. In cases where some of the
  153322. * components will be ignored (eg grayscale output from YCbCr image),
  153323. * we can skip most computations for the unused components.
  153324. */
  153325. boolean component_needed; /* do we need the value of this component? */
  153326. /* These values are computed before starting a scan of the component. */
  153327. /* The decompressor output side may not use these variables. */
  153328. int MCU_width; /* number of blocks per MCU, horizontally */
  153329. int MCU_height; /* number of blocks per MCU, vertically */
  153330. int MCU_blocks; /* MCU_width * MCU_height */
  153331. int MCU_sample_width; /* MCU width in samples, MCU_width*DCT_scaled_size */
  153332. int last_col_width; /* # of non-dummy blocks across in last MCU */
  153333. int last_row_height; /* # of non-dummy blocks down in last MCU */
  153334. /* Saved quantization table for component; NULL if none yet saved.
  153335. * See jdinput.c comments about the need for this information.
  153336. * This field is currently used only for decompression.
  153337. */
  153338. JQUANT_TBL * quant_table;
  153339. /* Private per-component storage for DCT or IDCT subsystem. */
  153340. void * dct_table;
  153341. } jpeg_component_info;
  153342. /* The script for encoding a multiple-scan file is an array of these: */
  153343. typedef struct {
  153344. int comps_in_scan; /* number of components encoded in this scan */
  153345. int component_index[MAX_COMPS_IN_SCAN]; /* their SOF/comp_info[] indexes */
  153346. int Ss, Se; /* progressive JPEG spectral selection parms */
  153347. int Ah, Al; /* progressive JPEG successive approx. parms */
  153348. } jpeg_scan_info;
  153349. /* The decompressor can save APPn and COM markers in a list of these: */
  153350. typedef struct jpeg_marker_struct FAR * jpeg_saved_marker_ptr;
  153351. struct jpeg_marker_struct {
  153352. jpeg_saved_marker_ptr next; /* next in list, or NULL */
  153353. UINT8 marker; /* marker code: JPEG_COM, or JPEG_APP0+n */
  153354. unsigned int original_length; /* # bytes of data in the file */
  153355. unsigned int data_length; /* # bytes of data saved at data[] */
  153356. JOCTET FAR * data; /* the data contained in the marker */
  153357. /* the marker length word is not counted in data_length or original_length */
  153358. };
  153359. /* Known color spaces. */
  153360. typedef enum {
  153361. JCS_UNKNOWN, /* error/unspecified */
  153362. JCS_GRAYSCALE, /* monochrome */
  153363. JCS_RGB, /* red/green/blue */
  153364. JCS_YCbCr, /* Y/Cb/Cr (also known as YUV) */
  153365. JCS_CMYK, /* C/M/Y/K */
  153366. JCS_YCCK /* Y/Cb/Cr/K */
  153367. } J_COLOR_SPACE;
  153368. /* DCT/IDCT algorithm options. */
  153369. typedef enum {
  153370. JDCT_ISLOW, /* slow but accurate integer algorithm */
  153371. JDCT_IFAST, /* faster, less accurate integer method */
  153372. JDCT_FLOAT /* floating-point: accurate, fast on fast HW */
  153373. } J_DCT_METHOD;
  153374. #ifndef JDCT_DEFAULT /* may be overridden in jconfig.h */
  153375. #define JDCT_DEFAULT JDCT_ISLOW
  153376. #endif
  153377. #ifndef JDCT_FASTEST /* may be overridden in jconfig.h */
  153378. #define JDCT_FASTEST JDCT_IFAST
  153379. #endif
  153380. /* Dithering options for decompression. */
  153381. typedef enum {
  153382. JDITHER_NONE, /* no dithering */
  153383. JDITHER_ORDERED, /* simple ordered dither */
  153384. JDITHER_FS /* Floyd-Steinberg error diffusion dither */
  153385. } J_DITHER_MODE;
  153386. /* Common fields between JPEG compression and decompression master structs. */
  153387. #define jpeg_common_fields \
  153388. struct jpeg_error_mgr * err; /* Error handler module */\
  153389. struct jpeg_memory_mgr * mem; /* Memory manager module */\
  153390. struct jpeg_progress_mgr * progress; /* Progress monitor, or NULL if none */\
  153391. void * client_data; /* Available for use by application */\
  153392. boolean is_decompressor; /* So common code can tell which is which */\
  153393. int global_state /* For checking call sequence validity */
  153394. /* Routines that are to be used by both halves of the library are declared
  153395. * to receive a pointer to this structure. There are no actual instances of
  153396. * jpeg_common_struct, only of jpeg_compress_struct and jpeg_decompress_struct.
  153397. */
  153398. struct jpeg_common_struct {
  153399. jpeg_common_fields; /* Fields common to both master struct types */
  153400. /* Additional fields follow in an actual jpeg_compress_struct or
  153401. * jpeg_decompress_struct. All three structs must agree on these
  153402. * initial fields! (This would be a lot cleaner in C++.)
  153403. */
  153404. };
  153405. typedef struct jpeg_common_struct * j_common_ptr;
  153406. typedef struct jpeg_compress_struct * j_compress_ptr;
  153407. typedef struct jpeg_decompress_struct * j_decompress_ptr;
  153408. /* Master record for a compression instance */
  153409. struct jpeg_compress_struct {
  153410. jpeg_common_fields; /* Fields shared with jpeg_decompress_struct */
  153411. /* Destination for compressed data */
  153412. struct jpeg_destination_mgr * dest;
  153413. /* Description of source image --- these fields must be filled in by
  153414. * outer application before starting compression. in_color_space must
  153415. * be correct before you can even call jpeg_set_defaults().
  153416. */
  153417. JDIMENSION image_width; /* input image width */
  153418. JDIMENSION image_height; /* input image height */
  153419. int input_components; /* # of color components in input image */
  153420. J_COLOR_SPACE in_color_space; /* colorspace of input image */
  153421. double input_gamma; /* image gamma of input image */
  153422. /* Compression parameters --- these fields must be set before calling
  153423. * jpeg_start_compress(). We recommend calling jpeg_set_defaults() to
  153424. * initialize everything to reasonable defaults, then changing anything
  153425. * the application specifically wants to change. That way you won't get
  153426. * burnt when new parameters are added. Also note that there are several
  153427. * helper routines to simplify changing parameters.
  153428. */
  153429. int data_precision; /* bits of precision in image data */
  153430. int num_components; /* # of color components in JPEG image */
  153431. J_COLOR_SPACE jpeg_color_space; /* colorspace of JPEG image */
  153432. jpeg_component_info * comp_info;
  153433. /* comp_info[i] describes component that appears i'th in SOF */
  153434. JQUANT_TBL * quant_tbl_ptrs[NUM_QUANT_TBLS];
  153435. /* ptrs to coefficient quantization tables, or NULL if not defined */
  153436. JHUFF_TBL * dc_huff_tbl_ptrs[NUM_HUFF_TBLS];
  153437. JHUFF_TBL * ac_huff_tbl_ptrs[NUM_HUFF_TBLS];
  153438. /* ptrs to Huffman coding tables, or NULL if not defined */
  153439. UINT8 arith_dc_L[NUM_ARITH_TBLS]; /* L values for DC arith-coding tables */
  153440. UINT8 arith_dc_U[NUM_ARITH_TBLS]; /* U values for DC arith-coding tables */
  153441. UINT8 arith_ac_K[NUM_ARITH_TBLS]; /* Kx values for AC arith-coding tables */
  153442. int num_scans; /* # of entries in scan_info array */
  153443. const jpeg_scan_info * scan_info; /* script for multi-scan file, or NULL */
  153444. /* The default value of scan_info is NULL, which causes a single-scan
  153445. * sequential JPEG file to be emitted. To create a multi-scan file,
  153446. * set num_scans and scan_info to point to an array of scan definitions.
  153447. */
  153448. boolean raw_data_in; /* TRUE=caller supplies downsampled data */
  153449. boolean arith_code; /* TRUE=arithmetic coding, FALSE=Huffman */
  153450. boolean optimize_coding; /* TRUE=optimize entropy encoding parms */
  153451. boolean CCIR601_sampling; /* TRUE=first samples are cosited */
  153452. int smoothing_factor; /* 1..100, or 0 for no input smoothing */
  153453. J_DCT_METHOD dct_method; /* DCT algorithm selector */
  153454. /* The restart interval can be specified in absolute MCUs by setting
  153455. * restart_interval, or in MCU rows by setting restart_in_rows
  153456. * (in which case the correct restart_interval will be figured
  153457. * for each scan).
  153458. */
  153459. unsigned int restart_interval; /* MCUs per restart, or 0 for no restart */
  153460. int restart_in_rows; /* if > 0, MCU rows per restart interval */
  153461. /* Parameters controlling emission of special markers. */
  153462. boolean write_JFIF_header; /* should a JFIF marker be written? */
  153463. UINT8 JFIF_major_version; /* What to write for the JFIF version number */
  153464. UINT8 JFIF_minor_version;
  153465. /* These three values are not used by the JPEG code, merely copied */
  153466. /* into the JFIF APP0 marker. density_unit can be 0 for unknown, */
  153467. /* 1 for dots/inch, or 2 for dots/cm. Note that the pixel aspect */
  153468. /* ratio is defined by X_density/Y_density even when density_unit=0. */
  153469. UINT8 density_unit; /* JFIF code for pixel size units */
  153470. UINT16 X_density; /* Horizontal pixel density */
  153471. UINT16 Y_density; /* Vertical pixel density */
  153472. boolean write_Adobe_marker; /* should an Adobe marker be written? */
  153473. /* State variable: index of next scanline to be written to
  153474. * jpeg_write_scanlines(). Application may use this to control its
  153475. * processing loop, e.g., "while (next_scanline < image_height)".
  153476. */
  153477. JDIMENSION next_scanline; /* 0 .. image_height-1 */
  153478. /* Remaining fields are known throughout compressor, but generally
  153479. * should not be touched by a surrounding application.
  153480. */
  153481. /*
  153482. * These fields are computed during compression startup
  153483. */
  153484. boolean progressive_mode; /* TRUE if scan script uses progressive mode */
  153485. int max_h_samp_factor; /* largest h_samp_factor */
  153486. int max_v_samp_factor; /* largest v_samp_factor */
  153487. JDIMENSION total_iMCU_rows; /* # of iMCU rows to be input to coef ctlr */
  153488. /* The coefficient controller receives data in units of MCU rows as defined
  153489. * for fully interleaved scans (whether the JPEG file is interleaved or not).
  153490. * There are v_samp_factor * DCTSIZE sample rows of each component in an
  153491. * "iMCU" (interleaved MCU) row.
  153492. */
  153493. /*
  153494. * These fields are valid during any one scan.
  153495. * They describe the components and MCUs actually appearing in the scan.
  153496. */
  153497. int comps_in_scan; /* # of JPEG components in this scan */
  153498. jpeg_component_info * cur_comp_info[MAX_COMPS_IN_SCAN];
  153499. /* *cur_comp_info[i] describes component that appears i'th in SOS */
  153500. JDIMENSION MCUs_per_row; /* # of MCUs across the image */
  153501. JDIMENSION MCU_rows_in_scan; /* # of MCU rows in the image */
  153502. int blocks_in_MCU; /* # of DCT blocks per MCU */
  153503. int MCU_membership[C_MAX_BLOCKS_IN_MCU];
  153504. /* MCU_membership[i] is index in cur_comp_info of component owning */
  153505. /* i'th block in an MCU */
  153506. int Ss, Se, Ah, Al; /* progressive JPEG parameters for scan */
  153507. /*
  153508. * Links to compression subobjects (methods and private variables of modules)
  153509. */
  153510. struct jpeg_comp_master * master;
  153511. struct jpeg_c_main_controller * main;
  153512. struct jpeg_c_prep_controller * prep;
  153513. struct jpeg_c_coef_controller * coef;
  153514. struct jpeg_marker_writer * marker;
  153515. struct jpeg_color_converter * cconvert;
  153516. struct jpeg_downsampler * downsample;
  153517. struct jpeg_forward_dct * fdct;
  153518. struct jpeg_entropy_encoder * entropy;
  153519. jpeg_scan_info * script_space; /* workspace for jpeg_simple_progression */
  153520. int script_space_size;
  153521. };
  153522. /* Master record for a decompression instance */
  153523. struct jpeg_decompress_struct {
  153524. jpeg_common_fields; /* Fields shared with jpeg_compress_struct */
  153525. /* Source of compressed data */
  153526. struct jpeg_source_mgr * src;
  153527. /* Basic description of image --- filled in by jpeg_read_header(). */
  153528. /* Application may inspect these values to decide how to process image. */
  153529. JDIMENSION image_width; /* nominal image width (from SOF marker) */
  153530. JDIMENSION image_height; /* nominal image height */
  153531. int num_components; /* # of color components in JPEG image */
  153532. J_COLOR_SPACE jpeg_color_space; /* colorspace of JPEG image */
  153533. /* Decompression processing parameters --- these fields must be set before
  153534. * calling jpeg_start_decompress(). Note that jpeg_read_header() initializes
  153535. * them to default values.
  153536. */
  153537. J_COLOR_SPACE out_color_space; /* colorspace for output */
  153538. unsigned int scale_num, scale_denom; /* fraction by which to scale image */
  153539. double output_gamma; /* image gamma wanted in output */
  153540. boolean buffered_image; /* TRUE=multiple output passes */
  153541. boolean raw_data_out; /* TRUE=downsampled data wanted */
  153542. J_DCT_METHOD dct_method; /* IDCT algorithm selector */
  153543. boolean do_fancy_upsampling; /* TRUE=apply fancy upsampling */
  153544. boolean do_block_smoothing; /* TRUE=apply interblock smoothing */
  153545. boolean quantize_colors; /* TRUE=colormapped output wanted */
  153546. /* the following are ignored if not quantize_colors: */
  153547. J_DITHER_MODE dither_mode; /* type of color dithering to use */
  153548. boolean two_pass_quantize; /* TRUE=use two-pass color quantization */
  153549. int desired_number_of_colors; /* max # colors to use in created colormap */
  153550. /* these are significant only in buffered-image mode: */
  153551. boolean enable_1pass_quant; /* enable future use of 1-pass quantizer */
  153552. boolean enable_external_quant;/* enable future use of external colormap */
  153553. boolean enable_2pass_quant; /* enable future use of 2-pass quantizer */
  153554. /* Description of actual output image that will be returned to application.
  153555. * These fields are computed by jpeg_start_decompress().
  153556. * You can also use jpeg_calc_output_dimensions() to determine these values
  153557. * in advance of calling jpeg_start_decompress().
  153558. */
  153559. JDIMENSION output_width; /* scaled image width */
  153560. JDIMENSION output_height; /* scaled image height */
  153561. int out_color_components; /* # of color components in out_color_space */
  153562. int output_components; /* # of color components returned */
  153563. /* output_components is 1 (a colormap index) when quantizing colors;
  153564. * otherwise it equals out_color_components.
  153565. */
  153566. int rec_outbuf_height; /* min recommended height of scanline buffer */
  153567. /* If the buffer passed to jpeg_read_scanlines() is less than this many rows
  153568. * high, space and time will be wasted due to unnecessary data copying.
  153569. * Usually rec_outbuf_height will be 1 or 2, at most 4.
  153570. */
  153571. /* When quantizing colors, the output colormap is described by these fields.
  153572. * The application can supply a colormap by setting colormap non-NULL before
  153573. * calling jpeg_start_decompress; otherwise a colormap is created during
  153574. * jpeg_start_decompress or jpeg_start_output.
  153575. * The map has out_color_components rows and actual_number_of_colors columns.
  153576. */
  153577. int actual_number_of_colors; /* number of entries in use */
  153578. JSAMPARRAY colormap; /* The color map as a 2-D pixel array */
  153579. /* State variables: these variables indicate the progress of decompression.
  153580. * The application may examine these but must not modify them.
  153581. */
  153582. /* Row index of next scanline to be read from jpeg_read_scanlines().
  153583. * Application may use this to control its processing loop, e.g.,
  153584. * "while (output_scanline < output_height)".
  153585. */
  153586. JDIMENSION output_scanline; /* 0 .. output_height-1 */
  153587. /* Current input scan number and number of iMCU rows completed in scan.
  153588. * These indicate the progress of the decompressor input side.
  153589. */
  153590. int input_scan_number; /* Number of SOS markers seen so far */
  153591. JDIMENSION input_iMCU_row; /* Number of iMCU rows completed */
  153592. /* The "output scan number" is the notional scan being displayed by the
  153593. * output side. The decompressor will not allow output scan/row number
  153594. * to get ahead of input scan/row, but it can fall arbitrarily far behind.
  153595. */
  153596. int output_scan_number; /* Nominal scan number being displayed */
  153597. JDIMENSION output_iMCU_row; /* Number of iMCU rows read */
  153598. /* Current progression status. coef_bits[c][i] indicates the precision
  153599. * with which component c's DCT coefficient i (in zigzag order) is known.
  153600. * It is -1 when no data has yet been received, otherwise it is the point
  153601. * transform (shift) value for the most recent scan of the coefficient
  153602. * (thus, 0 at completion of the progression).
  153603. * This pointer is NULL when reading a non-progressive file.
  153604. */
  153605. int (*coef_bits)[DCTSIZE2]; /* -1 or current Al value for each coef */
  153606. /* Internal JPEG parameters --- the application usually need not look at
  153607. * these fields. Note that the decompressor output side may not use
  153608. * any parameters that can change between scans.
  153609. */
  153610. /* Quantization and Huffman tables are carried forward across input
  153611. * datastreams when processing abbreviated JPEG datastreams.
  153612. */
  153613. JQUANT_TBL * quant_tbl_ptrs[NUM_QUANT_TBLS];
  153614. /* ptrs to coefficient quantization tables, or NULL if not defined */
  153615. JHUFF_TBL * dc_huff_tbl_ptrs[NUM_HUFF_TBLS];
  153616. JHUFF_TBL * ac_huff_tbl_ptrs[NUM_HUFF_TBLS];
  153617. /* ptrs to Huffman coding tables, or NULL if not defined */
  153618. /* These parameters are never carried across datastreams, since they
  153619. * are given in SOF/SOS markers or defined to be reset by SOI.
  153620. */
  153621. int data_precision; /* bits of precision in image data */
  153622. jpeg_component_info * comp_info;
  153623. /* comp_info[i] describes component that appears i'th in SOF */
  153624. boolean progressive_mode; /* TRUE if SOFn specifies progressive mode */
  153625. boolean arith_code; /* TRUE=arithmetic coding, FALSE=Huffman */
  153626. UINT8 arith_dc_L[NUM_ARITH_TBLS]; /* L values for DC arith-coding tables */
  153627. UINT8 arith_dc_U[NUM_ARITH_TBLS]; /* U values for DC arith-coding tables */
  153628. UINT8 arith_ac_K[NUM_ARITH_TBLS]; /* Kx values for AC arith-coding tables */
  153629. unsigned int restart_interval; /* MCUs per restart interval, or 0 for no restart */
  153630. /* These fields record data obtained from optional markers recognized by
  153631. * the JPEG library.
  153632. */
  153633. boolean saw_JFIF_marker; /* TRUE iff a JFIF APP0 marker was found */
  153634. /* Data copied from JFIF marker; only valid if saw_JFIF_marker is TRUE: */
  153635. UINT8 JFIF_major_version; /* JFIF version number */
  153636. UINT8 JFIF_minor_version;
  153637. UINT8 density_unit; /* JFIF code for pixel size units */
  153638. UINT16 X_density; /* Horizontal pixel density */
  153639. UINT16 Y_density; /* Vertical pixel density */
  153640. boolean saw_Adobe_marker; /* TRUE iff an Adobe APP14 marker was found */
  153641. UINT8 Adobe_transform; /* Color transform code from Adobe marker */
  153642. boolean CCIR601_sampling; /* TRUE=first samples are cosited */
  153643. /* Aside from the specific data retained from APPn markers known to the
  153644. * library, the uninterpreted contents of any or all APPn and COM markers
  153645. * can be saved in a list for examination by the application.
  153646. */
  153647. jpeg_saved_marker_ptr marker_list; /* Head of list of saved markers */
  153648. /* Remaining fields are known throughout decompressor, but generally
  153649. * should not be touched by a surrounding application.
  153650. */
  153651. /*
  153652. * These fields are computed during decompression startup
  153653. */
  153654. int max_h_samp_factor; /* largest h_samp_factor */
  153655. int max_v_samp_factor; /* largest v_samp_factor */
  153656. int min_DCT_scaled_size; /* smallest DCT_scaled_size of any component */
  153657. JDIMENSION total_iMCU_rows; /* # of iMCU rows in image */
  153658. /* The coefficient controller's input and output progress is measured in
  153659. * units of "iMCU" (interleaved MCU) rows. These are the same as MCU rows
  153660. * in fully interleaved JPEG scans, but are used whether the scan is
  153661. * interleaved or not. We define an iMCU row as v_samp_factor DCT block
  153662. * rows of each component. Therefore, the IDCT output contains
  153663. * v_samp_factor*DCT_scaled_size sample rows of a component per iMCU row.
  153664. */
  153665. JSAMPLE * sample_range_limit; /* table for fast range-limiting */
  153666. /*
  153667. * These fields are valid during any one scan.
  153668. * They describe the components and MCUs actually appearing in the scan.
  153669. * Note that the decompressor output side must not use these fields.
  153670. */
  153671. int comps_in_scan; /* # of JPEG components in this scan */
  153672. jpeg_component_info * cur_comp_info[MAX_COMPS_IN_SCAN];
  153673. /* *cur_comp_info[i] describes component that appears i'th in SOS */
  153674. JDIMENSION MCUs_per_row; /* # of MCUs across the image */
  153675. JDIMENSION MCU_rows_in_scan; /* # of MCU rows in the image */
  153676. int blocks_in_MCU; /* # of DCT blocks per MCU */
  153677. int MCU_membership[D_MAX_BLOCKS_IN_MCU];
  153678. /* MCU_membership[i] is index in cur_comp_info of component owning */
  153679. /* i'th block in an MCU */
  153680. int Ss, Se, Ah, Al; /* progressive JPEG parameters for scan */
  153681. /* This field is shared between entropy decoder and marker parser.
  153682. * It is either zero or the code of a JPEG marker that has been
  153683. * read from the data source, but has not yet been processed.
  153684. */
  153685. int unread_marker;
  153686. /*
  153687. * Links to decompression subobjects (methods, private variables of modules)
  153688. */
  153689. struct jpeg_decomp_master * master;
  153690. struct jpeg_d_main_controller * main;
  153691. struct jpeg_d_coef_controller * coef;
  153692. struct jpeg_d_post_controller * post;
  153693. struct jpeg_input_controller * inputctl;
  153694. struct jpeg_marker_reader * marker;
  153695. struct jpeg_entropy_decoder * entropy;
  153696. struct jpeg_inverse_dct * idct;
  153697. struct jpeg_upsampler * upsample;
  153698. struct jpeg_color_deconverter * cconvert;
  153699. struct jpeg_color_quantizer * cquantize;
  153700. };
  153701. /* "Object" declarations for JPEG modules that may be supplied or called
  153702. * directly by the surrounding application.
  153703. * As with all objects in the JPEG library, these structs only define the
  153704. * publicly visible methods and state variables of a module. Additional
  153705. * private fields may exist after the public ones.
  153706. */
  153707. /* Error handler object */
  153708. struct jpeg_error_mgr {
  153709. /* Error exit handler: does not return to caller */
  153710. JMETHOD(void, error_exit, (j_common_ptr cinfo));
  153711. /* Conditionally emit a trace or warning message */
  153712. JMETHOD(void, emit_message, (j_common_ptr cinfo, int msg_level));
  153713. /* Routine that actually outputs a trace or error message */
  153714. JMETHOD(void, output_message, (j_common_ptr cinfo));
  153715. /* Format a message string for the most recent JPEG error or message */
  153716. JMETHOD(void, format_message, (j_common_ptr cinfo, char * buffer));
  153717. #define JMSG_LENGTH_MAX 200 /* recommended size of format_message buffer */
  153718. /* Reset error state variables at start of a new image */
  153719. JMETHOD(void, reset_error_mgr, (j_common_ptr cinfo));
  153720. /* The message ID code and any parameters are saved here.
  153721. * A message can have one string parameter or up to 8 int parameters.
  153722. */
  153723. int msg_code;
  153724. #define JMSG_STR_PARM_MAX 80
  153725. union {
  153726. int i[8];
  153727. char s[JMSG_STR_PARM_MAX];
  153728. } msg_parm;
  153729. /* Standard state variables for error facility */
  153730. int trace_level; /* max msg_level that will be displayed */
  153731. /* For recoverable corrupt-data errors, we emit a warning message,
  153732. * but keep going unless emit_message chooses to abort. emit_message
  153733. * should count warnings in num_warnings. The surrounding application
  153734. * can check for bad data by seeing if num_warnings is nonzero at the
  153735. * end of processing.
  153736. */
  153737. long num_warnings; /* number of corrupt-data warnings */
  153738. /* These fields point to the table(s) of error message strings.
  153739. * An application can change the table pointer to switch to a different
  153740. * message list (typically, to change the language in which errors are
  153741. * reported). Some applications may wish to add additional error codes
  153742. * that will be handled by the JPEG library error mechanism; the second
  153743. * table pointer is used for this purpose.
  153744. *
  153745. * First table includes all errors generated by JPEG library itself.
  153746. * Error code 0 is reserved for a "no such error string" message.
  153747. */
  153748. const char * const * jpeg_message_table; /* Library errors */
  153749. int last_jpeg_message; /* Table contains strings 0..last_jpeg_message */
  153750. /* Second table can be added by application (see cjpeg/djpeg for example).
  153751. * It contains strings numbered first_addon_message..last_addon_message.
  153752. */
  153753. const char * const * addon_message_table; /* Non-library errors */
  153754. int first_addon_message; /* code for first string in addon table */
  153755. int last_addon_message; /* code for last string in addon table */
  153756. };
  153757. /* Progress monitor object */
  153758. struct jpeg_progress_mgr {
  153759. JMETHOD(void, progress_monitor, (j_common_ptr cinfo));
  153760. long pass_counter; /* work units completed in this pass */
  153761. long pass_limit; /* total number of work units in this pass */
  153762. int completed_passes; /* passes completed so far */
  153763. int total_passes; /* total number of passes expected */
  153764. };
  153765. /* Data destination object for compression */
  153766. struct jpeg_destination_mgr {
  153767. JOCTET * next_output_byte; /* => next byte to write in buffer */
  153768. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  153769. JMETHOD(void, init_destination, (j_compress_ptr cinfo));
  153770. JMETHOD(boolean, empty_output_buffer, (j_compress_ptr cinfo));
  153771. JMETHOD(void, term_destination, (j_compress_ptr cinfo));
  153772. };
  153773. /* Data source object for decompression */
  153774. struct jpeg_source_mgr {
  153775. const JOCTET * next_input_byte; /* => next byte to read from buffer */
  153776. size_t bytes_in_buffer; /* # of bytes remaining in buffer */
  153777. JMETHOD(void, init_source, (j_decompress_ptr cinfo));
  153778. JMETHOD(boolean, fill_input_buffer, (j_decompress_ptr cinfo));
  153779. JMETHOD(void, skip_input_data, (j_decompress_ptr cinfo, long num_bytes));
  153780. JMETHOD(boolean, resync_to_restart, (j_decompress_ptr cinfo, int desired));
  153781. JMETHOD(void, term_source, (j_decompress_ptr cinfo));
  153782. };
  153783. /* Memory manager object.
  153784. * Allocates "small" objects (a few K total), "large" objects (tens of K),
  153785. * and "really big" objects (virtual arrays with backing store if needed).
  153786. * The memory manager does not allow individual objects to be freed; rather,
  153787. * each created object is assigned to a pool, and whole pools can be freed
  153788. * at once. This is faster and more convenient than remembering exactly what
  153789. * to free, especially where malloc()/free() are not too speedy.
  153790. * NB: alloc routines never return NULL. They exit to error_exit if not
  153791. * successful.
  153792. */
  153793. #define JPOOL_PERMANENT 0 /* lasts until master record is destroyed */
  153794. #define JPOOL_IMAGE 1 /* lasts until done with image/datastream */
  153795. #define JPOOL_NUMPOOLS 2
  153796. typedef struct jvirt_sarray_control * jvirt_sarray_ptr;
  153797. typedef struct jvirt_barray_control * jvirt_barray_ptr;
  153798. struct jpeg_memory_mgr {
  153799. /* Method pointers */
  153800. JMETHOD(void *, alloc_small, (j_common_ptr cinfo, int pool_id,
  153801. size_t sizeofobject));
  153802. JMETHOD(void FAR *, alloc_large, (j_common_ptr cinfo, int pool_id,
  153803. size_t sizeofobject));
  153804. JMETHOD(JSAMPARRAY, alloc_sarray, (j_common_ptr cinfo, int pool_id,
  153805. JDIMENSION samplesperrow,
  153806. JDIMENSION numrows));
  153807. JMETHOD(JBLOCKARRAY, alloc_barray, (j_common_ptr cinfo, int pool_id,
  153808. JDIMENSION blocksperrow,
  153809. JDIMENSION numrows));
  153810. JMETHOD(jvirt_sarray_ptr, request_virt_sarray, (j_common_ptr cinfo,
  153811. int pool_id,
  153812. boolean pre_zero,
  153813. JDIMENSION samplesperrow,
  153814. JDIMENSION numrows,
  153815. JDIMENSION maxaccess));
  153816. JMETHOD(jvirt_barray_ptr, request_virt_barray, (j_common_ptr cinfo,
  153817. int pool_id,
  153818. boolean pre_zero,
  153819. JDIMENSION blocksperrow,
  153820. JDIMENSION numrows,
  153821. JDIMENSION maxaccess));
  153822. JMETHOD(void, realize_virt_arrays, (j_common_ptr cinfo));
  153823. JMETHOD(JSAMPARRAY, access_virt_sarray, (j_common_ptr cinfo,
  153824. jvirt_sarray_ptr ptr,
  153825. JDIMENSION start_row,
  153826. JDIMENSION num_rows,
  153827. boolean writable));
  153828. JMETHOD(JBLOCKARRAY, access_virt_barray, (j_common_ptr cinfo,
  153829. jvirt_barray_ptr ptr,
  153830. JDIMENSION start_row,
  153831. JDIMENSION num_rows,
  153832. boolean writable));
  153833. JMETHOD(void, free_pool, (j_common_ptr cinfo, int pool_id));
  153834. JMETHOD(void, self_destruct, (j_common_ptr cinfo));
  153835. /* Limit on memory allocation for this JPEG object. (Note that this is
  153836. * merely advisory, not a guaranteed maximum; it only affects the space
  153837. * used for virtual-array buffers.) May be changed by outer application
  153838. * after creating the JPEG object.
  153839. */
  153840. long max_memory_to_use;
  153841. /* Maximum allocation request accepted by alloc_large. */
  153842. long max_alloc_chunk;
  153843. };
  153844. /* Routine signature for application-supplied marker processing methods.
  153845. * Need not pass marker code since it is stored in cinfo->unread_marker.
  153846. */
  153847. typedef JMETHOD(boolean, jpeg_marker_parser_method, (j_decompress_ptr cinfo));
  153848. /* Declarations for routines called by application.
  153849. * The JPP macro hides prototype parameters from compilers that can't cope.
  153850. * Note JPP requires double parentheses.
  153851. */
  153852. #ifdef HAVE_PROTOTYPES
  153853. #define JPP(arglist) arglist
  153854. #else
  153855. #define JPP(arglist) ()
  153856. #endif
  153857. /* Short forms of external names for systems with brain-damaged linkers.
  153858. * We shorten external names to be unique in the first six letters, which
  153859. * is good enough for all known systems.
  153860. * (If your compiler itself needs names to be unique in less than 15
  153861. * characters, you are out of luck. Get a better compiler.)
  153862. */
  153863. #ifdef NEED_SHORT_EXTERNAL_NAMES
  153864. #define jpeg_std_error jStdError
  153865. #define jpeg_CreateCompress jCreaCompress
  153866. #define jpeg_CreateDecompress jCreaDecompress
  153867. #define jpeg_destroy_compress jDestCompress
  153868. #define jpeg_destroy_decompress jDestDecompress
  153869. #define jpeg_stdio_dest jStdDest
  153870. #define jpeg_stdio_src jStdSrc
  153871. #define jpeg_set_defaults jSetDefaults
  153872. #define jpeg_set_colorspace jSetColorspace
  153873. #define jpeg_default_colorspace jDefColorspace
  153874. #define jpeg_set_quality jSetQuality
  153875. #define jpeg_set_linear_quality jSetLQuality
  153876. #define jpeg_add_quant_table jAddQuantTable
  153877. #define jpeg_quality_scaling jQualityScaling
  153878. #define jpeg_simple_progression jSimProgress
  153879. #define jpeg_suppress_tables jSuppressTables
  153880. #define jpeg_alloc_quant_table jAlcQTable
  153881. #define jpeg_alloc_huff_table jAlcHTable
  153882. #define jpeg_start_compress jStrtCompress
  153883. #define jpeg_write_scanlines jWrtScanlines
  153884. #define jpeg_finish_compress jFinCompress
  153885. #define jpeg_write_raw_data jWrtRawData
  153886. #define jpeg_write_marker jWrtMarker
  153887. #define jpeg_write_m_header jWrtMHeader
  153888. #define jpeg_write_m_byte jWrtMByte
  153889. #define jpeg_write_tables jWrtTables
  153890. #define jpeg_read_header jReadHeader
  153891. #define jpeg_start_decompress jStrtDecompress
  153892. #define jpeg_read_scanlines jReadScanlines
  153893. #define jpeg_finish_decompress jFinDecompress
  153894. #define jpeg_read_raw_data jReadRawData
  153895. #define jpeg_has_multiple_scans jHasMultScn
  153896. #define jpeg_start_output jStrtOutput
  153897. #define jpeg_finish_output jFinOutput
  153898. #define jpeg_input_complete jInComplete
  153899. #define jpeg_new_colormap jNewCMap
  153900. #define jpeg_consume_input jConsumeInput
  153901. #define jpeg_calc_output_dimensions jCalcDimensions
  153902. #define jpeg_save_markers jSaveMarkers
  153903. #define jpeg_set_marker_processor jSetMarker
  153904. #define jpeg_read_coefficients jReadCoefs
  153905. #define jpeg_write_coefficients jWrtCoefs
  153906. #define jpeg_copy_critical_parameters jCopyCrit
  153907. #define jpeg_abort_compress jAbrtCompress
  153908. #define jpeg_abort_decompress jAbrtDecompress
  153909. #define jpeg_abort jAbort
  153910. #define jpeg_destroy jDestroy
  153911. #define jpeg_resync_to_restart jResyncRestart
  153912. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  153913. /* Default error-management setup */
  153914. EXTERN(struct jpeg_error_mgr *) jpeg_std_error
  153915. JPP((struct jpeg_error_mgr * err));
  153916. /* Initialization of JPEG compression objects.
  153917. * jpeg_create_compress() and jpeg_create_decompress() are the exported
  153918. * names that applications should call. These expand to calls on
  153919. * jpeg_CreateCompress and jpeg_CreateDecompress with additional information
  153920. * passed for version mismatch checking.
  153921. * NB: you must set up the error-manager BEFORE calling jpeg_create_xxx.
  153922. */
  153923. #define jpeg_create_compress(cinfo) \
  153924. jpeg_CreateCompress((cinfo), JPEG_LIB_VERSION, \
  153925. (size_t) sizeof(struct jpeg_compress_struct))
  153926. #define jpeg_create_decompress(cinfo) \
  153927. jpeg_CreateDecompress((cinfo), JPEG_LIB_VERSION, \
  153928. (size_t) sizeof(struct jpeg_decompress_struct))
  153929. EXTERN(void) jpeg_CreateCompress JPP((j_compress_ptr cinfo,
  153930. int version, size_t structsize));
  153931. EXTERN(void) jpeg_CreateDecompress JPP((j_decompress_ptr cinfo,
  153932. int version, size_t structsize));
  153933. /* Destruction of JPEG compression objects */
  153934. EXTERN(void) jpeg_destroy_compress JPP((j_compress_ptr cinfo));
  153935. EXTERN(void) jpeg_destroy_decompress JPP((j_decompress_ptr cinfo));
  153936. /* Standard data source and destination managers: stdio streams. */
  153937. /* Caller is responsible for opening the file before and closing after. */
  153938. EXTERN(void) jpeg_stdio_dest JPP((j_compress_ptr cinfo, FILE * outfile));
  153939. EXTERN(void) jpeg_stdio_src JPP((j_decompress_ptr cinfo, FILE * infile));
  153940. /* Default parameter setup for compression */
  153941. EXTERN(void) jpeg_set_defaults JPP((j_compress_ptr cinfo));
  153942. /* Compression parameter setup aids */
  153943. EXTERN(void) jpeg_set_colorspace JPP((j_compress_ptr cinfo,
  153944. J_COLOR_SPACE colorspace));
  153945. EXTERN(void) jpeg_default_colorspace JPP((j_compress_ptr cinfo));
  153946. EXTERN(void) jpeg_set_quality JPP((j_compress_ptr cinfo, int quality,
  153947. boolean force_baseline));
  153948. EXTERN(void) jpeg_set_linear_quality JPP((j_compress_ptr cinfo,
  153949. int scale_factor,
  153950. boolean force_baseline));
  153951. EXTERN(void) jpeg_add_quant_table JPP((j_compress_ptr cinfo, int which_tbl,
  153952. const unsigned int *basic_table,
  153953. int scale_factor,
  153954. boolean force_baseline));
  153955. EXTERN(int) jpeg_quality_scaling JPP((int quality));
  153956. EXTERN(void) jpeg_simple_progression JPP((j_compress_ptr cinfo));
  153957. EXTERN(void) jpeg_suppress_tables JPP((j_compress_ptr cinfo,
  153958. boolean suppress));
  153959. EXTERN(JQUANT_TBL *) jpeg_alloc_quant_table JPP((j_common_ptr cinfo));
  153960. EXTERN(JHUFF_TBL *) jpeg_alloc_huff_table JPP((j_common_ptr cinfo));
  153961. /* Main entry points for compression */
  153962. EXTERN(void) jpeg_start_compress JPP((j_compress_ptr cinfo,
  153963. boolean write_all_tables));
  153964. EXTERN(JDIMENSION) jpeg_write_scanlines JPP((j_compress_ptr cinfo,
  153965. JSAMPARRAY scanlines,
  153966. JDIMENSION num_lines));
  153967. EXTERN(void) jpeg_finish_compress JPP((j_compress_ptr cinfo));
  153968. /* Replaces jpeg_write_scanlines when writing raw downsampled data. */
  153969. EXTERN(JDIMENSION) jpeg_write_raw_data JPP((j_compress_ptr cinfo,
  153970. JSAMPIMAGE data,
  153971. JDIMENSION num_lines));
  153972. /* Write a special marker. See libjpeg.doc concerning safe usage. */
  153973. EXTERN(void) jpeg_write_marker
  153974. JPP((j_compress_ptr cinfo, int marker,
  153975. const JOCTET * dataptr, unsigned int datalen));
  153976. /* Same, but piecemeal. */
  153977. EXTERN(void) jpeg_write_m_header
  153978. JPP((j_compress_ptr cinfo, int marker, unsigned int datalen));
  153979. EXTERN(void) jpeg_write_m_byte
  153980. JPP((j_compress_ptr cinfo, int val));
  153981. /* Alternate compression function: just write an abbreviated table file */
  153982. EXTERN(void) jpeg_write_tables JPP((j_compress_ptr cinfo));
  153983. /* Decompression startup: read start of JPEG datastream to see what's there */
  153984. EXTERN(int) jpeg_read_header JPP((j_decompress_ptr cinfo,
  153985. boolean require_image));
  153986. /* Return value is one of: */
  153987. #define JPEG_SUSPENDED 0 /* Suspended due to lack of input data */
  153988. #define JPEG_HEADER_OK 1 /* Found valid image datastream */
  153989. #define JPEG_HEADER_TABLES_ONLY 2 /* Found valid table-specs-only datastream */
  153990. /* If you pass require_image = TRUE (normal case), you need not check for
  153991. * a TABLES_ONLY return code; an abbreviated file will cause an error exit.
  153992. * JPEG_SUSPENDED is only possible if you use a data source module that can
  153993. * give a suspension return (the stdio source module doesn't).
  153994. */
  153995. /* Main entry points for decompression */
  153996. EXTERN(boolean) jpeg_start_decompress JPP((j_decompress_ptr cinfo));
  153997. EXTERN(JDIMENSION) jpeg_read_scanlines JPP((j_decompress_ptr cinfo,
  153998. JSAMPARRAY scanlines,
  153999. JDIMENSION max_lines));
  154000. EXTERN(boolean) jpeg_finish_decompress JPP((j_decompress_ptr cinfo));
  154001. /* Replaces jpeg_read_scanlines when reading raw downsampled data. */
  154002. EXTERN(JDIMENSION) jpeg_read_raw_data JPP((j_decompress_ptr cinfo,
  154003. JSAMPIMAGE data,
  154004. JDIMENSION max_lines));
  154005. /* Additional entry points for buffered-image mode. */
  154006. EXTERN(boolean) jpeg_has_multiple_scans JPP((j_decompress_ptr cinfo));
  154007. EXTERN(boolean) jpeg_start_output JPP((j_decompress_ptr cinfo,
  154008. int scan_number));
  154009. EXTERN(boolean) jpeg_finish_output JPP((j_decompress_ptr cinfo));
  154010. EXTERN(boolean) jpeg_input_complete JPP((j_decompress_ptr cinfo));
  154011. EXTERN(void) jpeg_new_colormap JPP((j_decompress_ptr cinfo));
  154012. EXTERN(int) jpeg_consume_input JPP((j_decompress_ptr cinfo));
  154013. /* Return value is one of: */
  154014. /* #define JPEG_SUSPENDED 0 Suspended due to lack of input data */
  154015. #define JPEG_REACHED_SOS 1 /* Reached start of new scan */
  154016. #define JPEG_REACHED_EOI 2 /* Reached end of image */
  154017. #define JPEG_ROW_COMPLETED 3 /* Completed one iMCU row */
  154018. #define JPEG_SCAN_COMPLETED 4 /* Completed last iMCU row of a scan */
  154019. /* Precalculate output dimensions for current decompression parameters. */
  154020. EXTERN(void) jpeg_calc_output_dimensions JPP((j_decompress_ptr cinfo));
  154021. /* Control saving of COM and APPn markers into marker_list. */
  154022. EXTERN(void) jpeg_save_markers
  154023. JPP((j_decompress_ptr cinfo, int marker_code,
  154024. unsigned int length_limit));
  154025. /* Install a special processing method for COM or APPn markers. */
  154026. EXTERN(void) jpeg_set_marker_processor
  154027. JPP((j_decompress_ptr cinfo, int marker_code,
  154028. jpeg_marker_parser_method routine));
  154029. /* Read or write raw DCT coefficients --- useful for lossless transcoding. */
  154030. EXTERN(jvirt_barray_ptr *) jpeg_read_coefficients JPP((j_decompress_ptr cinfo));
  154031. EXTERN(void) jpeg_write_coefficients JPP((j_compress_ptr cinfo,
  154032. jvirt_barray_ptr * coef_arrays));
  154033. EXTERN(void) jpeg_copy_critical_parameters JPP((j_decompress_ptr srcinfo,
  154034. j_compress_ptr dstinfo));
  154035. /* If you choose to abort compression or decompression before completing
  154036. * jpeg_finish_(de)compress, then you need to clean up to release memory,
  154037. * temporary files, etc. You can just call jpeg_destroy_(de)compress
  154038. * if you're done with the JPEG object, but if you want to clean it up and
  154039. * reuse it, call this:
  154040. */
  154041. EXTERN(void) jpeg_abort_compress JPP((j_compress_ptr cinfo));
  154042. EXTERN(void) jpeg_abort_decompress JPP((j_decompress_ptr cinfo));
  154043. /* Generic versions of jpeg_abort and jpeg_destroy that work on either
  154044. * flavor of JPEG object. These may be more convenient in some places.
  154045. */
  154046. EXTERN(void) jpeg_abort JPP((j_common_ptr cinfo));
  154047. EXTERN(void) jpeg_destroy JPP((j_common_ptr cinfo));
  154048. /* Default restart-marker-resync procedure for use by data source modules */
  154049. EXTERN(boolean) jpeg_resync_to_restart JPP((j_decompress_ptr cinfo,
  154050. int desired));
  154051. /* These marker codes are exported since applications and data source modules
  154052. * are likely to want to use them.
  154053. */
  154054. #define JPEG_RST0 0xD0 /* RST0 marker code */
  154055. #define JPEG_EOI 0xD9 /* EOI marker code */
  154056. #define JPEG_APP0 0xE0 /* APP0 marker code */
  154057. #define JPEG_COM 0xFE /* COM marker code */
  154058. /* If we have a brain-damaged compiler that emits warnings (or worse, errors)
  154059. * for structure definitions that are never filled in, keep it quiet by
  154060. * supplying dummy definitions for the various substructures.
  154061. */
  154062. #ifdef INCOMPLETE_TYPES_BROKEN
  154063. #ifndef JPEG_INTERNALS /* will be defined in jpegint.h */
  154064. struct jvirt_sarray_control { long dummy; };
  154065. struct jvirt_barray_control { long dummy; };
  154066. struct jpeg_comp_master { long dummy; };
  154067. struct jpeg_c_main_controller { long dummy; };
  154068. struct jpeg_c_prep_controller { long dummy; };
  154069. struct jpeg_c_coef_controller { long dummy; };
  154070. struct jpeg_marker_writer { long dummy; };
  154071. struct jpeg_color_converter { long dummy; };
  154072. struct jpeg_downsampler { long dummy; };
  154073. struct jpeg_forward_dct { long dummy; };
  154074. struct jpeg_entropy_encoder { long dummy; };
  154075. struct jpeg_decomp_master { long dummy; };
  154076. struct jpeg_d_main_controller { long dummy; };
  154077. struct jpeg_d_coef_controller { long dummy; };
  154078. struct jpeg_d_post_controller { long dummy; };
  154079. struct jpeg_input_controller { long dummy; };
  154080. struct jpeg_marker_reader { long dummy; };
  154081. struct jpeg_entropy_decoder { long dummy; };
  154082. struct jpeg_inverse_dct { long dummy; };
  154083. struct jpeg_upsampler { long dummy; };
  154084. struct jpeg_color_deconverter { long dummy; };
  154085. struct jpeg_color_quantizer { long dummy; };
  154086. #endif /* JPEG_INTERNALS */
  154087. #endif /* INCOMPLETE_TYPES_BROKEN */
  154088. /*
  154089. * The JPEG library modules define JPEG_INTERNALS before including this file.
  154090. * The internal structure declarations are read only when that is true.
  154091. * Applications using the library should not include jpegint.h, but may wish
  154092. * to include jerror.h.
  154093. */
  154094. #ifdef JPEG_INTERNALS
  154095. /********* Start of inlined file: jpegint.h *********/
  154096. /* Declarations for both compression & decompression */
  154097. typedef enum { /* Operating modes for buffer controllers */
  154098. JBUF_PASS_THRU, /* Plain stripwise operation */
  154099. /* Remaining modes require a full-image buffer to have been created */
  154100. JBUF_SAVE_SOURCE, /* Run source subobject only, save output */
  154101. JBUF_CRANK_DEST, /* Run dest subobject only, using saved data */
  154102. JBUF_SAVE_AND_PASS /* Run both subobjects, save output */
  154103. } J_BUF_MODE;
  154104. /* Values of global_state field (jdapi.c has some dependencies on ordering!) */
  154105. #define CSTATE_START 100 /* after create_compress */
  154106. #define CSTATE_SCANNING 101 /* start_compress done, write_scanlines OK */
  154107. #define CSTATE_RAW_OK 102 /* start_compress done, write_raw_data OK */
  154108. #define CSTATE_WRCOEFS 103 /* jpeg_write_coefficients done */
  154109. #define DSTATE_START 200 /* after create_decompress */
  154110. #define DSTATE_INHEADER 201 /* reading header markers, no SOS yet */
  154111. #define DSTATE_READY 202 /* found SOS, ready for start_decompress */
  154112. #define DSTATE_PRELOAD 203 /* reading multiscan file in start_decompress*/
  154113. #define DSTATE_PRESCAN 204 /* performing dummy pass for 2-pass quant */
  154114. #define DSTATE_SCANNING 205 /* start_decompress done, read_scanlines OK */
  154115. #define DSTATE_RAW_OK 206 /* start_decompress done, read_raw_data OK */
  154116. #define DSTATE_BUFIMAGE 207 /* expecting jpeg_start_output */
  154117. #define DSTATE_BUFPOST 208 /* looking for SOS/EOI in jpeg_finish_output */
  154118. #define DSTATE_RDCOEFS 209 /* reading file in jpeg_read_coefficients */
  154119. #define DSTATE_STOPPING 210 /* looking for EOI in jpeg_finish_decompress */
  154120. /* Declarations for compression modules */
  154121. /* Master control module */
  154122. struct jpeg_comp_master {
  154123. JMETHOD(void, prepare_for_pass, (j_compress_ptr cinfo));
  154124. JMETHOD(void, pass_startup, (j_compress_ptr cinfo));
  154125. JMETHOD(void, finish_pass, (j_compress_ptr cinfo));
  154126. /* State variables made visible to other modules */
  154127. boolean call_pass_startup; /* True if pass_startup must be called */
  154128. boolean is_last_pass; /* True during last pass */
  154129. };
  154130. /* Main buffer control (downsampled-data buffer) */
  154131. struct jpeg_c_main_controller {
  154132. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  154133. JMETHOD(void, process_data, (j_compress_ptr cinfo,
  154134. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  154135. JDIMENSION in_rows_avail));
  154136. };
  154137. /* Compression preprocessing (downsampling input buffer control) */
  154138. struct jpeg_c_prep_controller {
  154139. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  154140. JMETHOD(void, pre_process_data, (j_compress_ptr cinfo,
  154141. JSAMPARRAY input_buf,
  154142. JDIMENSION *in_row_ctr,
  154143. JDIMENSION in_rows_avail,
  154144. JSAMPIMAGE output_buf,
  154145. JDIMENSION *out_row_group_ctr,
  154146. JDIMENSION out_row_groups_avail));
  154147. };
  154148. /* Coefficient buffer control */
  154149. struct jpeg_c_coef_controller {
  154150. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  154151. JMETHOD(boolean, compress_data, (j_compress_ptr cinfo,
  154152. JSAMPIMAGE input_buf));
  154153. };
  154154. /* Colorspace conversion */
  154155. struct jpeg_color_converter {
  154156. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  154157. JMETHOD(void, color_convert, (j_compress_ptr cinfo,
  154158. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  154159. JDIMENSION output_row, int num_rows));
  154160. };
  154161. /* Downsampling */
  154162. struct jpeg_downsampler {
  154163. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  154164. JMETHOD(void, downsample, (j_compress_ptr cinfo,
  154165. JSAMPIMAGE input_buf, JDIMENSION in_row_index,
  154166. JSAMPIMAGE output_buf,
  154167. JDIMENSION out_row_group_index));
  154168. boolean need_context_rows; /* TRUE if need rows above & below */
  154169. };
  154170. /* Forward DCT (also controls coefficient quantization) */
  154171. struct jpeg_forward_dct {
  154172. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  154173. /* perhaps this should be an array??? */
  154174. JMETHOD(void, forward_DCT, (j_compress_ptr cinfo,
  154175. jpeg_component_info * compptr,
  154176. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  154177. JDIMENSION start_row, JDIMENSION start_col,
  154178. JDIMENSION num_blocks));
  154179. };
  154180. /* Entropy encoding */
  154181. struct jpeg_entropy_encoder {
  154182. JMETHOD(void, start_pass, (j_compress_ptr cinfo, boolean gather_statistics));
  154183. JMETHOD(boolean, encode_mcu, (j_compress_ptr cinfo, JBLOCKROW *MCU_data));
  154184. JMETHOD(void, finish_pass, (j_compress_ptr cinfo));
  154185. };
  154186. /* Marker writing */
  154187. struct jpeg_marker_writer {
  154188. JMETHOD(void, write_file_header, (j_compress_ptr cinfo));
  154189. JMETHOD(void, write_frame_header, (j_compress_ptr cinfo));
  154190. JMETHOD(void, write_scan_header, (j_compress_ptr cinfo));
  154191. JMETHOD(void, write_file_trailer, (j_compress_ptr cinfo));
  154192. JMETHOD(void, write_tables_only, (j_compress_ptr cinfo));
  154193. /* These routines are exported to allow insertion of extra markers */
  154194. /* Probably only COM and APPn markers should be written this way */
  154195. JMETHOD(void, write_marker_header, (j_compress_ptr cinfo, int marker,
  154196. unsigned int datalen));
  154197. JMETHOD(void, write_marker_byte, (j_compress_ptr cinfo, int val));
  154198. };
  154199. /* Declarations for decompression modules */
  154200. /* Master control module */
  154201. struct jpeg_decomp_master {
  154202. JMETHOD(void, prepare_for_output_pass, (j_decompress_ptr cinfo));
  154203. JMETHOD(void, finish_output_pass, (j_decompress_ptr cinfo));
  154204. /* State variables made visible to other modules */
  154205. boolean is_dummy_pass; /* True during 1st pass for 2-pass quant */
  154206. };
  154207. /* Input control module */
  154208. struct jpeg_input_controller {
  154209. JMETHOD(int, consume_input, (j_decompress_ptr cinfo));
  154210. JMETHOD(void, reset_input_controller, (j_decompress_ptr cinfo));
  154211. JMETHOD(void, start_input_pass, (j_decompress_ptr cinfo));
  154212. JMETHOD(void, finish_input_pass, (j_decompress_ptr cinfo));
  154213. /* State variables made visible to other modules */
  154214. boolean has_multiple_scans; /* True if file has multiple scans */
  154215. boolean eoi_reached; /* True when EOI has been consumed */
  154216. };
  154217. /* Main buffer control (downsampled-data buffer) */
  154218. struct jpeg_d_main_controller {
  154219. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, J_BUF_MODE pass_mode));
  154220. JMETHOD(void, process_data, (j_decompress_ptr cinfo,
  154221. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  154222. JDIMENSION out_rows_avail));
  154223. };
  154224. /* Coefficient buffer control */
  154225. struct jpeg_d_coef_controller {
  154226. JMETHOD(void, start_input_pass, (j_decompress_ptr cinfo));
  154227. JMETHOD(int, consume_data, (j_decompress_ptr cinfo));
  154228. JMETHOD(void, start_output_pass, (j_decompress_ptr cinfo));
  154229. JMETHOD(int, decompress_data, (j_decompress_ptr cinfo,
  154230. JSAMPIMAGE output_buf));
  154231. /* Pointer to array of coefficient virtual arrays, or NULL if none */
  154232. jvirt_barray_ptr *coef_arrays;
  154233. };
  154234. /* Decompression postprocessing (color quantization buffer control) */
  154235. struct jpeg_d_post_controller {
  154236. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, J_BUF_MODE pass_mode));
  154237. JMETHOD(void, post_process_data, (j_decompress_ptr cinfo,
  154238. JSAMPIMAGE input_buf,
  154239. JDIMENSION *in_row_group_ctr,
  154240. JDIMENSION in_row_groups_avail,
  154241. JSAMPARRAY output_buf,
  154242. JDIMENSION *out_row_ctr,
  154243. JDIMENSION out_rows_avail));
  154244. };
  154245. /* Marker reading & parsing */
  154246. struct jpeg_marker_reader {
  154247. JMETHOD(void, reset_marker_reader, (j_decompress_ptr cinfo));
  154248. /* Read markers until SOS or EOI.
  154249. * Returns same codes as are defined for jpeg_consume_input:
  154250. * JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  154251. */
  154252. JMETHOD(int, read_markers, (j_decompress_ptr cinfo));
  154253. /* Read a restart marker --- exported for use by entropy decoder only */
  154254. jpeg_marker_parser_method read_restart_marker;
  154255. /* State of marker reader --- nominally internal, but applications
  154256. * supplying COM or APPn handlers might like to know the state.
  154257. */
  154258. boolean saw_SOI; /* found SOI? */
  154259. boolean saw_SOF; /* found SOF? */
  154260. int next_restart_num; /* next restart number expected (0-7) */
  154261. unsigned int discarded_bytes; /* # of bytes skipped looking for a marker */
  154262. };
  154263. /* Entropy decoding */
  154264. struct jpeg_entropy_decoder {
  154265. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  154266. JMETHOD(boolean, decode_mcu, (j_decompress_ptr cinfo,
  154267. JBLOCKROW *MCU_data));
  154268. /* This is here to share code between baseline and progressive decoders; */
  154269. /* other modules probably should not use it */
  154270. boolean insufficient_data; /* set TRUE after emitting warning */
  154271. };
  154272. /* Inverse DCT (also performs dequantization) */
  154273. typedef JMETHOD(void, inverse_DCT_method_ptr,
  154274. (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  154275. JCOEFPTR coef_block,
  154276. JSAMPARRAY output_buf, JDIMENSION output_col));
  154277. struct jpeg_inverse_dct {
  154278. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  154279. /* It is useful to allow each component to have a separate IDCT method. */
  154280. inverse_DCT_method_ptr inverse_DCT[MAX_COMPONENTS];
  154281. };
  154282. /* Upsampling (note that upsampler must also call color converter) */
  154283. struct jpeg_upsampler {
  154284. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  154285. JMETHOD(void, upsample, (j_decompress_ptr cinfo,
  154286. JSAMPIMAGE input_buf,
  154287. JDIMENSION *in_row_group_ctr,
  154288. JDIMENSION in_row_groups_avail,
  154289. JSAMPARRAY output_buf,
  154290. JDIMENSION *out_row_ctr,
  154291. JDIMENSION out_rows_avail));
  154292. boolean need_context_rows; /* TRUE if need rows above & below */
  154293. };
  154294. /* Colorspace conversion */
  154295. struct jpeg_color_deconverter {
  154296. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  154297. JMETHOD(void, color_convert, (j_decompress_ptr cinfo,
  154298. JSAMPIMAGE input_buf, JDIMENSION input_row,
  154299. JSAMPARRAY output_buf, int num_rows));
  154300. };
  154301. /* Color quantization or color precision reduction */
  154302. struct jpeg_color_quantizer {
  154303. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, boolean is_pre_scan));
  154304. JMETHOD(void, color_quantize, (j_decompress_ptr cinfo,
  154305. JSAMPARRAY input_buf, JSAMPARRAY output_buf,
  154306. int num_rows));
  154307. JMETHOD(void, finish_pass, (j_decompress_ptr cinfo));
  154308. JMETHOD(void, new_color_map, (j_decompress_ptr cinfo));
  154309. };
  154310. /* Miscellaneous useful macros */
  154311. #undef MAX
  154312. #define MAX(a,b) ((a) > (b) ? (a) : (b))
  154313. #undef MIN
  154314. #define MIN(a,b) ((a) < (b) ? (a) : (b))
  154315. /* We assume that right shift corresponds to signed division by 2 with
  154316. * rounding towards minus infinity. This is correct for typical "arithmetic
  154317. * shift" instructions that shift in copies of the sign bit. But some
  154318. * C compilers implement >> with an unsigned shift. For these machines you
  154319. * must define RIGHT_SHIFT_IS_UNSIGNED.
  154320. * RIGHT_SHIFT provides a proper signed right shift of an INT32 quantity.
  154321. * It is only applied with constant shift counts. SHIFT_TEMPS must be
  154322. * included in the variables of any routine using RIGHT_SHIFT.
  154323. */
  154324. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  154325. #define SHIFT_TEMPS INT32 shift_temp;
  154326. #define RIGHT_SHIFT(x,shft) \
  154327. ((shift_temp = (x)) < 0 ? \
  154328. (shift_temp >> (shft)) | ((~((INT32) 0)) << (32-(shft))) : \
  154329. (shift_temp >> (shft)))
  154330. #else
  154331. #define SHIFT_TEMPS
  154332. #define RIGHT_SHIFT(x,shft) ((x) >> (shft))
  154333. #endif
  154334. /* Short forms of external names for systems with brain-damaged linkers. */
  154335. #ifdef NEED_SHORT_EXTERNAL_NAMES
  154336. #define jinit_compress_master jICompress
  154337. #define jinit_c_master_control jICMaster
  154338. #define jinit_c_main_controller jICMainC
  154339. #define jinit_c_prep_controller jICPrepC
  154340. #define jinit_c_coef_controller jICCoefC
  154341. #define jinit_color_converter jICColor
  154342. #define jinit_downsampler jIDownsampler
  154343. #define jinit_forward_dct jIFDCT
  154344. #define jinit_huff_encoder jIHEncoder
  154345. #define jinit_phuff_encoder jIPHEncoder
  154346. #define jinit_marker_writer jIMWriter
  154347. #define jinit_master_decompress jIDMaster
  154348. #define jinit_d_main_controller jIDMainC
  154349. #define jinit_d_coef_controller jIDCoefC
  154350. #define jinit_d_post_controller jIDPostC
  154351. #define jinit_input_controller jIInCtlr
  154352. #define jinit_marker_reader jIMReader
  154353. #define jinit_huff_decoder jIHDecoder
  154354. #define jinit_phuff_decoder jIPHDecoder
  154355. #define jinit_inverse_dct jIIDCT
  154356. #define jinit_upsampler jIUpsampler
  154357. #define jinit_color_deconverter jIDColor
  154358. #define jinit_1pass_quantizer jI1Quant
  154359. #define jinit_2pass_quantizer jI2Quant
  154360. #define jinit_merged_upsampler jIMUpsampler
  154361. #define jinit_memory_mgr jIMemMgr
  154362. #define jdiv_round_up jDivRound
  154363. #define jround_up jRound
  154364. #define jcopy_sample_rows jCopySamples
  154365. #define jcopy_block_row jCopyBlocks
  154366. #define jzero_far jZeroFar
  154367. #define jpeg_zigzag_order jZIGTable
  154368. #define jpeg_natural_order jZAGTable
  154369. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  154370. /* Compression module initialization routines */
  154371. EXTERN(void) jinit_compress_master JPP((j_compress_ptr cinfo));
  154372. EXTERN(void) jinit_c_master_control JPP((j_compress_ptr cinfo,
  154373. boolean transcode_only));
  154374. EXTERN(void) jinit_c_main_controller JPP((j_compress_ptr cinfo,
  154375. boolean need_full_buffer));
  154376. EXTERN(void) jinit_c_prep_controller JPP((j_compress_ptr cinfo,
  154377. boolean need_full_buffer));
  154378. EXTERN(void) jinit_c_coef_controller JPP((j_compress_ptr cinfo,
  154379. boolean need_full_buffer));
  154380. EXTERN(void) jinit_color_converter JPP((j_compress_ptr cinfo));
  154381. EXTERN(void) jinit_downsampler JPP((j_compress_ptr cinfo));
  154382. EXTERN(void) jinit_forward_dct JPP((j_compress_ptr cinfo));
  154383. EXTERN(void) jinit_huff_encoder JPP((j_compress_ptr cinfo));
  154384. EXTERN(void) jinit_phuff_encoder JPP((j_compress_ptr cinfo));
  154385. EXTERN(void) jinit_marker_writer JPP((j_compress_ptr cinfo));
  154386. /* Decompression module initialization routines */
  154387. EXTERN(void) jinit_master_decompress JPP((j_decompress_ptr cinfo));
  154388. EXTERN(void) jinit_d_main_controller JPP((j_decompress_ptr cinfo,
  154389. boolean need_full_buffer));
  154390. EXTERN(void) jinit_d_coef_controller JPP((j_decompress_ptr cinfo,
  154391. boolean need_full_buffer));
  154392. EXTERN(void) jinit_d_post_controller JPP((j_decompress_ptr cinfo,
  154393. boolean need_full_buffer));
  154394. EXTERN(void) jinit_input_controller JPP((j_decompress_ptr cinfo));
  154395. EXTERN(void) jinit_marker_reader JPP((j_decompress_ptr cinfo));
  154396. EXTERN(void) jinit_huff_decoder JPP((j_decompress_ptr cinfo));
  154397. EXTERN(void) jinit_phuff_decoder JPP((j_decompress_ptr cinfo));
  154398. EXTERN(void) jinit_inverse_dct JPP((j_decompress_ptr cinfo));
  154399. EXTERN(void) jinit_upsampler JPP((j_decompress_ptr cinfo));
  154400. EXTERN(void) jinit_color_deconverter JPP((j_decompress_ptr cinfo));
  154401. EXTERN(void) jinit_1pass_quantizer JPP((j_decompress_ptr cinfo));
  154402. EXTERN(void) jinit_2pass_quantizer JPP((j_decompress_ptr cinfo));
  154403. EXTERN(void) jinit_merged_upsampler JPP((j_decompress_ptr cinfo));
  154404. /* Memory manager initialization */
  154405. EXTERN(void) jinit_memory_mgr JPP((j_common_ptr cinfo));
  154406. /* Utility routines in jutils.c */
  154407. EXTERN(long) jdiv_round_up JPP((long a, long b));
  154408. EXTERN(long) jround_up JPP((long a, long b));
  154409. EXTERN(void) jcopy_sample_rows JPP((JSAMPARRAY input_array, int source_row,
  154410. JSAMPARRAY output_array, int dest_row,
  154411. int num_rows, JDIMENSION num_cols));
  154412. EXTERN(void) jcopy_block_row JPP((JBLOCKROW input_row, JBLOCKROW output_row,
  154413. JDIMENSION num_blocks));
  154414. EXTERN(void) jzero_far JPP((void FAR * target, size_t bytestozero));
  154415. /* Constant tables in jutils.c */
  154416. #if 0 /* This table is not actually needed in v6a */
  154417. extern const int jpeg_zigzag_order[]; /* natural coef order to zigzag order */
  154418. #endif
  154419. extern const int jpeg_natural_order[]; /* zigzag coef order to natural order */
  154420. /* Suppress undefined-structure complaints if necessary. */
  154421. #ifdef INCOMPLETE_TYPES_BROKEN
  154422. #ifndef AM_MEMORY_MANAGER /* only jmemmgr.c defines these */
  154423. struct jvirt_sarray_control { long dummy; };
  154424. struct jvirt_barray_control { long dummy; };
  154425. #endif
  154426. #endif /* INCOMPLETE_TYPES_BROKEN */
  154427. /********* End of inlined file: jpegint.h *********/
  154428. /* fetch private declarations */
  154429. /********* Start of inlined file: jerror.h *********/
  154430. /*
  154431. * To define the enum list of message codes, include this file without
  154432. * defining macro JMESSAGE. To create a message string table, include it
  154433. * again with a suitable JMESSAGE definition (see jerror.c for an example).
  154434. */
  154435. #ifndef JMESSAGE
  154436. #ifndef JERROR_H
  154437. /* First time through, define the enum list */
  154438. #define JMAKE_ENUM_LIST
  154439. #else
  154440. /* Repeated inclusions of this file are no-ops unless JMESSAGE is defined */
  154441. #define JMESSAGE(code,string)
  154442. #endif /* JERROR_H */
  154443. #endif /* JMESSAGE */
  154444. #ifdef JMAKE_ENUM_LIST
  154445. typedef enum {
  154446. #define JMESSAGE(code,string) code ,
  154447. #endif /* JMAKE_ENUM_LIST */
  154448. JMESSAGE(JMSG_NOMESSAGE, "Bogus message code %d") /* Must be first entry! */
  154449. /* For maintenance convenience, list is alphabetical by message code name */
  154450. JMESSAGE(JERR_ARITH_NOTIMPL,
  154451. "Sorry, there are legal restrictions on arithmetic coding")
  154452. JMESSAGE(JERR_BAD_ALIGN_TYPE, "ALIGN_TYPE is wrong, please fix")
  154453. JMESSAGE(JERR_BAD_ALLOC_CHUNK, "MAX_ALLOC_CHUNK is wrong, please fix")
  154454. JMESSAGE(JERR_BAD_BUFFER_MODE, "Bogus buffer control mode")
  154455. JMESSAGE(JERR_BAD_COMPONENT_ID, "Invalid component ID %d in SOS")
  154456. JMESSAGE(JERR_BAD_DCT_COEF, "DCT coefficient out of range")
  154457. JMESSAGE(JERR_BAD_DCTSIZE, "IDCT output block size %d not supported")
  154458. JMESSAGE(JERR_BAD_HUFF_TABLE, "Bogus Huffman table definition")
  154459. JMESSAGE(JERR_BAD_IN_COLORSPACE, "Bogus input colorspace")
  154460. JMESSAGE(JERR_BAD_J_COLORSPACE, "Bogus JPEG colorspace")
  154461. JMESSAGE(JERR_BAD_LENGTH, "Bogus marker length")
  154462. JMESSAGE(JERR_BAD_LIB_VERSION,
  154463. "Wrong JPEG library version: library is %d, caller expects %d")
  154464. JMESSAGE(JERR_BAD_MCU_SIZE, "Sampling factors too large for interleaved scan")
  154465. JMESSAGE(JERR_BAD_POOL_ID, "Invalid memory pool code %d")
  154466. JMESSAGE(JERR_BAD_PRECISION, "Unsupported JPEG data precision %d")
  154467. JMESSAGE(JERR_BAD_PROGRESSION,
  154468. "Invalid progressive parameters Ss=%d Se=%d Ah=%d Al=%d")
  154469. JMESSAGE(JERR_BAD_PROG_SCRIPT,
  154470. "Invalid progressive parameters at scan script entry %d")
  154471. JMESSAGE(JERR_BAD_SAMPLING, "Bogus sampling factors")
  154472. JMESSAGE(JERR_BAD_SCAN_SCRIPT, "Invalid scan script at entry %d")
  154473. JMESSAGE(JERR_BAD_STATE, "Improper call to JPEG library in state %d")
  154474. JMESSAGE(JERR_BAD_STRUCT_SIZE,
  154475. "JPEG parameter struct mismatch: library thinks size is %u, caller expects %u")
  154476. JMESSAGE(JERR_BAD_VIRTUAL_ACCESS, "Bogus virtual array access")
  154477. JMESSAGE(JERR_BUFFER_SIZE, "Buffer passed to JPEG library is too small")
  154478. JMESSAGE(JERR_CANT_SUSPEND, "Suspension not allowed here")
  154479. JMESSAGE(JERR_CCIR601_NOTIMPL, "CCIR601 sampling not implemented yet")
  154480. JMESSAGE(JERR_COMPONENT_COUNT, "Too many color components: %d, max %d")
  154481. JMESSAGE(JERR_CONVERSION_NOTIMPL, "Unsupported color conversion request")
  154482. JMESSAGE(JERR_DAC_INDEX, "Bogus DAC index %d")
  154483. JMESSAGE(JERR_DAC_VALUE, "Bogus DAC value 0x%x")
  154484. JMESSAGE(JERR_DHT_INDEX, "Bogus DHT index %d")
  154485. JMESSAGE(JERR_DQT_INDEX, "Bogus DQT index %d")
  154486. JMESSAGE(JERR_EMPTY_IMAGE, "Empty JPEG image (DNL not supported)")
  154487. JMESSAGE(JERR_EMS_READ, "Read from EMS failed")
  154488. JMESSAGE(JERR_EMS_WRITE, "Write to EMS failed")
  154489. JMESSAGE(JERR_EOI_EXPECTED, "Didn't expect more than one scan")
  154490. JMESSAGE(JERR_FILE_READ, "Input file read error")
  154491. JMESSAGE(JERR_FILE_WRITE, "Output file write error --- out of disk space?")
  154492. JMESSAGE(JERR_FRACT_SAMPLE_NOTIMPL, "Fractional sampling not implemented yet")
  154493. JMESSAGE(JERR_HUFF_CLEN_OVERFLOW, "Huffman code size table overflow")
  154494. JMESSAGE(JERR_HUFF_MISSING_CODE, "Missing Huffman code table entry")
  154495. JMESSAGE(JERR_IMAGE_TOO_BIG, "Maximum supported image dimension is %u pixels")
  154496. JMESSAGE(JERR_INPUT_EMPTY, "Empty input file")
  154497. JMESSAGE(JERR_INPUT_EOF, "Premature end of input file")
  154498. JMESSAGE(JERR_MISMATCHED_QUANT_TABLE,
  154499. "Cannot transcode due to multiple use of quantization table %d")
  154500. JMESSAGE(JERR_MISSING_DATA, "Scan script does not transmit all data")
  154501. JMESSAGE(JERR_MODE_CHANGE, "Invalid color quantization mode change")
  154502. JMESSAGE(JERR_NOTIMPL, "Not implemented yet")
  154503. JMESSAGE(JERR_NOT_COMPILED, "Requested feature was omitted at compile time")
  154504. JMESSAGE(JERR_NO_BACKING_STORE, "Backing store not supported")
  154505. JMESSAGE(JERR_NO_HUFF_TABLE, "Huffman table 0x%02x was not defined")
  154506. JMESSAGE(JERR_NO_IMAGE, "JPEG datastream contains no image")
  154507. JMESSAGE(JERR_NO_QUANT_TABLE, "Quantization table 0x%02x was not defined")
  154508. JMESSAGE(JERR_NO_SOI, "Not a JPEG file: starts with 0x%02x 0x%02x")
  154509. JMESSAGE(JERR_OUT_OF_MEMORY, "Insufficient memory (case %d)")
  154510. JMESSAGE(JERR_QUANT_COMPONENTS,
  154511. "Cannot quantize more than %d color components")
  154512. JMESSAGE(JERR_QUANT_FEW_COLORS, "Cannot quantize to fewer than %d colors")
  154513. JMESSAGE(JERR_QUANT_MANY_COLORS, "Cannot quantize to more than %d colors")
  154514. JMESSAGE(JERR_SOF_DUPLICATE, "Invalid JPEG file structure: two SOF markers")
  154515. JMESSAGE(JERR_SOF_NO_SOS, "Invalid JPEG file structure: missing SOS marker")
  154516. JMESSAGE(JERR_SOF_UNSUPPORTED, "Unsupported JPEG process: SOF type 0x%02x")
  154517. JMESSAGE(JERR_SOI_DUPLICATE, "Invalid JPEG file structure: two SOI markers")
  154518. JMESSAGE(JERR_SOS_NO_SOF, "Invalid JPEG file structure: SOS before SOF")
  154519. JMESSAGE(JERR_TFILE_CREATE, "Failed to create temporary file %s")
  154520. JMESSAGE(JERR_TFILE_READ, "Read failed on temporary file")
  154521. JMESSAGE(JERR_TFILE_SEEK, "Seek failed on temporary file")
  154522. JMESSAGE(JERR_TFILE_WRITE,
  154523. "Write failed on temporary file --- out of disk space?")
  154524. JMESSAGE(JERR_TOO_LITTLE_DATA, "Application transferred too few scanlines")
  154525. JMESSAGE(JERR_UNKNOWN_MARKER, "Unsupported marker type 0x%02x")
  154526. JMESSAGE(JERR_VIRTUAL_BUG, "Virtual array controller messed up")
  154527. JMESSAGE(JERR_WIDTH_OVERFLOW, "Image too wide for this implementation")
  154528. JMESSAGE(JERR_XMS_READ, "Read from XMS failed")
  154529. JMESSAGE(JERR_XMS_WRITE, "Write to XMS failed")
  154530. JMESSAGE(JMSG_COPYRIGHT, JCOPYRIGHT)
  154531. JMESSAGE(JMSG_VERSION, JVERSION)
  154532. JMESSAGE(JTRC_16BIT_TABLES,
  154533. "Caution: quantization tables are too coarse for baseline JPEG")
  154534. JMESSAGE(JTRC_ADOBE,
  154535. "Adobe APP14 marker: version %d, flags 0x%04x 0x%04x, transform %d")
  154536. JMESSAGE(JTRC_APP0, "Unknown APP0 marker (not JFIF), length %u")
  154537. JMESSAGE(JTRC_APP14, "Unknown APP14 marker (not Adobe), length %u")
  154538. JMESSAGE(JTRC_DAC, "Define Arithmetic Table 0x%02x: 0x%02x")
  154539. JMESSAGE(JTRC_DHT, "Define Huffman Table 0x%02x")
  154540. JMESSAGE(JTRC_DQT, "Define Quantization Table %d precision %d")
  154541. JMESSAGE(JTRC_DRI, "Define Restart Interval %u")
  154542. JMESSAGE(JTRC_EMS_CLOSE, "Freed EMS handle %u")
  154543. JMESSAGE(JTRC_EMS_OPEN, "Obtained EMS handle %u")
  154544. JMESSAGE(JTRC_EOI, "End Of Image")
  154545. JMESSAGE(JTRC_HUFFBITS, " %3d %3d %3d %3d %3d %3d %3d %3d")
  154546. JMESSAGE(JTRC_JFIF, "JFIF APP0 marker: version %d.%02d, density %dx%d %d")
  154547. JMESSAGE(JTRC_JFIF_BADTHUMBNAILSIZE,
  154548. "Warning: thumbnail image size does not match data length %u")
  154549. JMESSAGE(JTRC_JFIF_EXTENSION,
  154550. "JFIF extension marker: type 0x%02x, length %u")
  154551. JMESSAGE(JTRC_JFIF_THUMBNAIL, " with %d x %d thumbnail image")
  154552. JMESSAGE(JTRC_MISC_MARKER, "Miscellaneous marker 0x%02x, length %u")
  154553. JMESSAGE(JTRC_PARMLESS_MARKER, "Unexpected marker 0x%02x")
  154554. JMESSAGE(JTRC_QUANTVALS, " %4u %4u %4u %4u %4u %4u %4u %4u")
  154555. JMESSAGE(JTRC_QUANT_3_NCOLORS, "Quantizing to %d = %d*%d*%d colors")
  154556. JMESSAGE(JTRC_QUANT_NCOLORS, "Quantizing to %d colors")
  154557. JMESSAGE(JTRC_QUANT_SELECTED, "Selected %d colors for quantization")
  154558. JMESSAGE(JTRC_RECOVERY_ACTION, "At marker 0x%02x, recovery action %d")
  154559. JMESSAGE(JTRC_RST, "RST%d")
  154560. JMESSAGE(JTRC_SMOOTH_NOTIMPL,
  154561. "Smoothing not supported with nonstandard sampling ratios")
  154562. JMESSAGE(JTRC_SOF, "Start Of Frame 0x%02x: width=%u, height=%u, components=%d")
  154563. JMESSAGE(JTRC_SOF_COMPONENT, " Component %d: %dhx%dv q=%d")
  154564. JMESSAGE(JTRC_SOI, "Start of Image")
  154565. JMESSAGE(JTRC_SOS, "Start Of Scan: %d components")
  154566. JMESSAGE(JTRC_SOS_COMPONENT, " Component %d: dc=%d ac=%d")
  154567. JMESSAGE(JTRC_SOS_PARAMS, " Ss=%d, Se=%d, Ah=%d, Al=%d")
  154568. JMESSAGE(JTRC_TFILE_CLOSE, "Closed temporary file %s")
  154569. JMESSAGE(JTRC_TFILE_OPEN, "Opened temporary file %s")
  154570. JMESSAGE(JTRC_THUMB_JPEG,
  154571. "JFIF extension marker: JPEG-compressed thumbnail image, length %u")
  154572. JMESSAGE(JTRC_THUMB_PALETTE,
  154573. "JFIF extension marker: palette thumbnail image, length %u")
  154574. JMESSAGE(JTRC_THUMB_RGB,
  154575. "JFIF extension marker: RGB thumbnail image, length %u")
  154576. JMESSAGE(JTRC_UNKNOWN_IDS,
  154577. "Unrecognized component IDs %d %d %d, assuming YCbCr")
  154578. JMESSAGE(JTRC_XMS_CLOSE, "Freed XMS handle %u")
  154579. JMESSAGE(JTRC_XMS_OPEN, "Obtained XMS handle %u")
  154580. JMESSAGE(JWRN_ADOBE_XFORM, "Unknown Adobe color transform code %d")
  154581. JMESSAGE(JWRN_BOGUS_PROGRESSION,
  154582. "Inconsistent progression sequence for component %d coefficient %d")
  154583. JMESSAGE(JWRN_EXTRANEOUS_DATA,
  154584. "Corrupt JPEG data: %u extraneous bytes before marker 0x%02x")
  154585. JMESSAGE(JWRN_HIT_MARKER, "Corrupt JPEG data: premature end of data segment")
  154586. JMESSAGE(JWRN_HUFF_BAD_CODE, "Corrupt JPEG data: bad Huffman code")
  154587. JMESSAGE(JWRN_JFIF_MAJOR, "Warning: unknown JFIF revision number %d.%02d")
  154588. JMESSAGE(JWRN_JPEG_EOF, "Premature end of JPEG file")
  154589. JMESSAGE(JWRN_MUST_RESYNC,
  154590. "Corrupt JPEG data: found marker 0x%02x instead of RST%d")
  154591. JMESSAGE(JWRN_NOT_SEQUENTIAL, "Invalid SOS parameters for sequential JPEG")
  154592. JMESSAGE(JWRN_TOO_MUCH_DATA, "Application transferred too many scanlines")
  154593. #ifdef JMAKE_ENUM_LIST
  154594. JMSG_LASTMSGCODE
  154595. } J_MESSAGE_CODE;
  154596. #undef JMAKE_ENUM_LIST
  154597. #endif /* JMAKE_ENUM_LIST */
  154598. /* Zap JMESSAGE macro so that future re-inclusions do nothing by default */
  154599. #undef JMESSAGE
  154600. #ifndef JERROR_H
  154601. #define JERROR_H
  154602. /* Macros to simplify using the error and trace message stuff */
  154603. /* The first parameter is either type of cinfo pointer */
  154604. /* Fatal errors (print message and exit) */
  154605. #define ERREXIT(cinfo,code) \
  154606. ((cinfo)->err->msg_code = (code), \
  154607. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  154608. #define ERREXIT1(cinfo,code,p1) \
  154609. ((cinfo)->err->msg_code = (code), \
  154610. (cinfo)->err->msg_parm.i[0] = (p1), \
  154611. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  154612. #define ERREXIT2(cinfo,code,p1,p2) \
  154613. ((cinfo)->err->msg_code = (code), \
  154614. (cinfo)->err->msg_parm.i[0] = (p1), \
  154615. (cinfo)->err->msg_parm.i[1] = (p2), \
  154616. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  154617. #define ERREXIT3(cinfo,code,p1,p2,p3) \
  154618. ((cinfo)->err->msg_code = (code), \
  154619. (cinfo)->err->msg_parm.i[0] = (p1), \
  154620. (cinfo)->err->msg_parm.i[1] = (p2), \
  154621. (cinfo)->err->msg_parm.i[2] = (p3), \
  154622. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  154623. #define ERREXIT4(cinfo,code,p1,p2,p3,p4) \
  154624. ((cinfo)->err->msg_code = (code), \
  154625. (cinfo)->err->msg_parm.i[0] = (p1), \
  154626. (cinfo)->err->msg_parm.i[1] = (p2), \
  154627. (cinfo)->err->msg_parm.i[2] = (p3), \
  154628. (cinfo)->err->msg_parm.i[3] = (p4), \
  154629. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  154630. #define ERREXITS(cinfo,code,str) \
  154631. ((cinfo)->err->msg_code = (code), \
  154632. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  154633. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  154634. #define MAKESTMT(stuff) do { stuff } while (0)
  154635. /* Nonfatal errors (we can keep going, but the data is probably corrupt) */
  154636. #define WARNMS(cinfo,code) \
  154637. ((cinfo)->err->msg_code = (code), \
  154638. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  154639. #define WARNMS1(cinfo,code,p1) \
  154640. ((cinfo)->err->msg_code = (code), \
  154641. (cinfo)->err->msg_parm.i[0] = (p1), \
  154642. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  154643. #define WARNMS2(cinfo,code,p1,p2) \
  154644. ((cinfo)->err->msg_code = (code), \
  154645. (cinfo)->err->msg_parm.i[0] = (p1), \
  154646. (cinfo)->err->msg_parm.i[1] = (p2), \
  154647. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  154648. /* Informational/debugging messages */
  154649. #define TRACEMS(cinfo,lvl,code) \
  154650. ((cinfo)->err->msg_code = (code), \
  154651. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  154652. #define TRACEMS1(cinfo,lvl,code,p1) \
  154653. ((cinfo)->err->msg_code = (code), \
  154654. (cinfo)->err->msg_parm.i[0] = (p1), \
  154655. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  154656. #define TRACEMS2(cinfo,lvl,code,p1,p2) \
  154657. ((cinfo)->err->msg_code = (code), \
  154658. (cinfo)->err->msg_parm.i[0] = (p1), \
  154659. (cinfo)->err->msg_parm.i[1] = (p2), \
  154660. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  154661. #define TRACEMS3(cinfo,lvl,code,p1,p2,p3) \
  154662. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  154663. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); \
  154664. (cinfo)->err->msg_code = (code); \
  154665. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  154666. #define TRACEMS4(cinfo,lvl,code,p1,p2,p3,p4) \
  154667. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  154668. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  154669. (cinfo)->err->msg_code = (code); \
  154670. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  154671. #define TRACEMS5(cinfo,lvl,code,p1,p2,p3,p4,p5) \
  154672. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  154673. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  154674. _mp[4] = (p5); \
  154675. (cinfo)->err->msg_code = (code); \
  154676. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  154677. #define TRACEMS8(cinfo,lvl,code,p1,p2,p3,p4,p5,p6,p7,p8) \
  154678. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  154679. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  154680. _mp[4] = (p5); _mp[5] = (p6); _mp[6] = (p7); _mp[7] = (p8); \
  154681. (cinfo)->err->msg_code = (code); \
  154682. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  154683. #define TRACEMSS(cinfo,lvl,code,str) \
  154684. ((cinfo)->err->msg_code = (code), \
  154685. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  154686. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  154687. #endif /* JERROR_H */
  154688. /********* End of inlined file: jerror.h *********/
  154689. /* fetch error codes too */
  154690. #endif
  154691. #endif /* JPEGLIB_H */
  154692. /********* End of inlined file: jpeglib.h *********/
  154693. /********* Start of inlined file: jcapimin.c *********/
  154694. #define JPEG_INTERNALS
  154695. /********* Start of inlined file: jinclude.h *********/
  154696. /* Include auto-config file to find out which system include files we need. */
  154697. #ifndef __jinclude_h__
  154698. #define __jinclude_h__
  154699. /********* Start of inlined file: jconfig.h *********/
  154700. /* see jconfig.doc for explanations */
  154701. // disable all the warnings under MSVC
  154702. #ifdef _MSC_VER
  154703. #pragma warning (disable: 4996 4267 4100 4127 4702 4244)
  154704. #endif
  154705. #ifdef __BORLANDC__
  154706. #pragma warn -8057
  154707. #pragma warn -8019
  154708. #pragma warn -8004
  154709. #pragma warn -8008
  154710. #endif
  154711. #define HAVE_PROTOTYPES
  154712. #define HAVE_UNSIGNED_CHAR
  154713. #define HAVE_UNSIGNED_SHORT
  154714. /* #define void char */
  154715. /* #define const */
  154716. #undef CHAR_IS_UNSIGNED
  154717. #define HAVE_STDDEF_H
  154718. #define HAVE_STDLIB_H
  154719. #undef NEED_BSD_STRINGS
  154720. #undef NEED_SYS_TYPES_H
  154721. #undef NEED_FAR_POINTERS /* we presume a 32-bit flat memory model */
  154722. #undef NEED_SHORT_EXTERNAL_NAMES
  154723. #undef INCOMPLETE_TYPES_BROKEN
  154724. /* Define "boolean" as unsigned char, not int, per Windows custom */
  154725. #ifndef __RPCNDR_H__ /* don't conflict if rpcndr.h already read */
  154726. typedef unsigned char boolean;
  154727. #endif
  154728. #define HAVE_BOOLEAN /* prevent jmorecfg.h from redefining it */
  154729. #ifdef JPEG_INTERNALS
  154730. #undef RIGHT_SHIFT_IS_UNSIGNED
  154731. #endif /* JPEG_INTERNALS */
  154732. #ifdef JPEG_CJPEG_DJPEG
  154733. #define BMP_SUPPORTED /* BMP image file format */
  154734. #define GIF_SUPPORTED /* GIF image file format */
  154735. #define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */
  154736. #undef RLE_SUPPORTED /* Utah RLE image file format */
  154737. #define TARGA_SUPPORTED /* Targa image file format */
  154738. #define TWO_FILE_COMMANDLINE /* optional */
  154739. #define USE_SETMODE /* Microsoft has setmode() */
  154740. #undef NEED_SIGNAL_CATCHER
  154741. #undef DONT_USE_B_MODE
  154742. #undef PROGRESS_REPORT /* optional */
  154743. #endif /* JPEG_CJPEG_DJPEG */
  154744. /********* End of inlined file: jconfig.h *********/
  154745. /* auto configuration options */
  154746. #define JCONFIG_INCLUDED /* so that jpeglib.h doesn't do it again */
  154747. /*
  154748. * We need the NULL macro and size_t typedef.
  154749. * On an ANSI-conforming system it is sufficient to include <stddef.h>.
  154750. * Otherwise, we get them from <stdlib.h> or <stdio.h>; we may have to
  154751. * pull in <sys/types.h> as well.
  154752. * Note that the core JPEG library does not require <stdio.h>;
  154753. * only the default error handler and data source/destination modules do.
  154754. * But we must pull it in because of the references to FILE in jpeglib.h.
  154755. * You can remove those references if you want to compile without <stdio.h>.
  154756. */
  154757. #ifdef HAVE_STDDEF_H
  154758. #include <stddef.h>
  154759. #endif
  154760. #ifdef HAVE_STDLIB_H
  154761. #include <stdlib.h>
  154762. #endif
  154763. #ifdef NEED_SYS_TYPES_H
  154764. #include <sys/types.h>
  154765. #endif
  154766. #include <stdio.h>
  154767. /*
  154768. * We need memory copying and zeroing functions, plus strncpy().
  154769. * ANSI and System V implementations declare these in <string.h>.
  154770. * BSD doesn't have the mem() functions, but it does have bcopy()/bzero().
  154771. * Some systems may declare memset and memcpy in <memory.h>.
  154772. *
  154773. * NOTE: we assume the size parameters to these functions are of type size_t.
  154774. * Change the casts in these macros if not!
  154775. */
  154776. #ifdef NEED_BSD_STRINGS
  154777. #include <strings.h>
  154778. #define MEMZERO(target,size) bzero((void *)(target), (size_t)(size))
  154779. #define MEMCOPY(dest,src,size) bcopy((const void *)(src), (void *)(dest), (size_t)(size))
  154780. #else /* not BSD, assume ANSI/SysV string lib */
  154781. #include <string.h>
  154782. #define MEMZERO(target,size) memset((void *)(target), 0, (size_t)(size))
  154783. #define MEMCOPY(dest,src,size) memcpy((void *)(dest), (const void *)(src), (size_t)(size))
  154784. #endif
  154785. /*
  154786. * In ANSI C, and indeed any rational implementation, size_t is also the
  154787. * type returned by sizeof(). However, it seems there are some irrational
  154788. * implementations out there, in which sizeof() returns an int even though
  154789. * size_t is defined as long or unsigned long. To ensure consistent results
  154790. * we always use this SIZEOF() macro in place of using sizeof() directly.
  154791. */
  154792. #define SIZEOF(object) ((size_t) sizeof(object))
  154793. /*
  154794. * The modules that use fread() and fwrite() always invoke them through
  154795. * these macros. On some systems you may need to twiddle the argument casts.
  154796. * CAUTION: argument order is different from underlying functions!
  154797. */
  154798. #define JFREAD(file,buf,sizeofbuf) \
  154799. ((size_t) fread((void *) (buf), (size_t) 1, (size_t) (sizeofbuf), (file)))
  154800. #define JFWRITE(file,buf,sizeofbuf) \
  154801. ((size_t) fwrite((const void *) (buf), (size_t) 1, (size_t) (sizeofbuf), (file)))
  154802. typedef enum { /* JPEG marker codes */
  154803. M_SOF0 = 0xc0,
  154804. M_SOF1 = 0xc1,
  154805. M_SOF2 = 0xc2,
  154806. M_SOF3 = 0xc3,
  154807. M_SOF5 = 0xc5,
  154808. M_SOF6 = 0xc6,
  154809. M_SOF7 = 0xc7,
  154810. M_JPG = 0xc8,
  154811. M_SOF9 = 0xc9,
  154812. M_SOF10 = 0xca,
  154813. M_SOF11 = 0xcb,
  154814. M_SOF13 = 0xcd,
  154815. M_SOF14 = 0xce,
  154816. M_SOF15 = 0xcf,
  154817. M_DHT = 0xc4,
  154818. M_DAC = 0xcc,
  154819. M_RST0 = 0xd0,
  154820. M_RST1 = 0xd1,
  154821. M_RST2 = 0xd2,
  154822. M_RST3 = 0xd3,
  154823. M_RST4 = 0xd4,
  154824. M_RST5 = 0xd5,
  154825. M_RST6 = 0xd6,
  154826. M_RST7 = 0xd7,
  154827. M_SOI = 0xd8,
  154828. M_EOI = 0xd9,
  154829. M_SOS = 0xda,
  154830. M_DQT = 0xdb,
  154831. M_DNL = 0xdc,
  154832. M_DRI = 0xdd,
  154833. M_DHP = 0xde,
  154834. M_EXP = 0xdf,
  154835. M_APP0 = 0xe0,
  154836. M_APP1 = 0xe1,
  154837. M_APP2 = 0xe2,
  154838. M_APP3 = 0xe3,
  154839. M_APP4 = 0xe4,
  154840. M_APP5 = 0xe5,
  154841. M_APP6 = 0xe6,
  154842. M_APP7 = 0xe7,
  154843. M_APP8 = 0xe8,
  154844. M_APP9 = 0xe9,
  154845. M_APP10 = 0xea,
  154846. M_APP11 = 0xeb,
  154847. M_APP12 = 0xec,
  154848. M_APP13 = 0xed,
  154849. M_APP14 = 0xee,
  154850. M_APP15 = 0xef,
  154851. M_JPG0 = 0xf0,
  154852. M_JPG13 = 0xfd,
  154853. M_COM = 0xfe,
  154854. M_TEM = 0x01,
  154855. M_ERROR = 0x100
  154856. } JPEG_MARKER;
  154857. /*
  154858. * Figure F.12: extend sign bit.
  154859. * On some machines, a shift and add will be faster than a table lookup.
  154860. */
  154861. #ifdef AVOID_TABLES
  154862. #define HUFF_EXTEND(x,s) ((x) < (1<<((s)-1)) ? (x) + (((-1)<<(s)) + 1) : (x))
  154863. #else
  154864. #define HUFF_EXTEND(x,s) ((x) < extend_test[s] ? (x) + extend_offset[s] : (x))
  154865. static const int extend_test[16] = /* entry n is 2**(n-1) */
  154866. { 0, 0x0001, 0x0002, 0x0004, 0x0008, 0x0010, 0x0020, 0x0040, 0x0080,
  154867. 0x0100, 0x0200, 0x0400, 0x0800, 0x1000, 0x2000, 0x4000 };
  154868. static const int extend_offset[16] = /* entry n is (-1 << n) + 1 */
  154869. { 0, ((-1)<<1) + 1, ((-1)<<2) + 1, ((-1)<<3) + 1, ((-1)<<4) + 1,
  154870. ((-1)<<5) + 1, ((-1)<<6) + 1, ((-1)<<7) + 1, ((-1)<<8) + 1,
  154871. ((-1)<<9) + 1, ((-1)<<10) + 1, ((-1)<<11) + 1, ((-1)<<12) + 1,
  154872. ((-1)<<13) + 1, ((-1)<<14) + 1, ((-1)<<15) + 1 };
  154873. #endif /* AVOID_TABLES */
  154874. #endif
  154875. /********* End of inlined file: jinclude.h *********/
  154876. /*
  154877. * Initialization of a JPEG compression object.
  154878. * The error manager must already be set up (in case memory manager fails).
  154879. */
  154880. GLOBAL(void)
  154881. jpeg_CreateCompress (j_compress_ptr cinfo, int version, size_t structsize)
  154882. {
  154883. int i;
  154884. /* Guard against version mismatches between library and caller. */
  154885. cinfo->mem = NULL; /* so jpeg_destroy knows mem mgr not called */
  154886. if (version != JPEG_LIB_VERSION)
  154887. ERREXIT2(cinfo, JERR_BAD_LIB_VERSION, JPEG_LIB_VERSION, version);
  154888. if (structsize != SIZEOF(struct jpeg_compress_struct))
  154889. ERREXIT2(cinfo, JERR_BAD_STRUCT_SIZE,
  154890. (int) SIZEOF(struct jpeg_compress_struct), (int) structsize);
  154891. /* For debugging purposes, we zero the whole master structure.
  154892. * But the application has already set the err pointer, and may have set
  154893. * client_data, so we have to save and restore those fields.
  154894. * Note: if application hasn't set client_data, tools like Purify may
  154895. * complain here.
  154896. */
  154897. {
  154898. struct jpeg_error_mgr * err = cinfo->err;
  154899. void * client_data = cinfo->client_data; /* ignore Purify complaint here */
  154900. MEMZERO(cinfo, SIZEOF(struct jpeg_compress_struct));
  154901. cinfo->err = err;
  154902. cinfo->client_data = client_data;
  154903. }
  154904. cinfo->is_decompressor = FALSE;
  154905. /* Initialize a memory manager instance for this object */
  154906. jinit_memory_mgr((j_common_ptr) cinfo);
  154907. /* Zero out pointers to permanent structures. */
  154908. cinfo->progress = NULL;
  154909. cinfo->dest = NULL;
  154910. cinfo->comp_info = NULL;
  154911. for (i = 0; i < NUM_QUANT_TBLS; i++)
  154912. cinfo->quant_tbl_ptrs[i] = NULL;
  154913. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  154914. cinfo->dc_huff_tbl_ptrs[i] = NULL;
  154915. cinfo->ac_huff_tbl_ptrs[i] = NULL;
  154916. }
  154917. cinfo->script_space = NULL;
  154918. cinfo->input_gamma = 1.0; /* in case application forgets */
  154919. /* OK, I'm ready */
  154920. cinfo->global_state = CSTATE_START;
  154921. }
  154922. /*
  154923. * Destruction of a JPEG compression object
  154924. */
  154925. GLOBAL(void)
  154926. jpeg_destroy_compress (j_compress_ptr cinfo)
  154927. {
  154928. jpeg_destroy((j_common_ptr) cinfo); /* use common routine */
  154929. }
  154930. /*
  154931. * Abort processing of a JPEG compression operation,
  154932. * but don't destroy the object itself.
  154933. */
  154934. GLOBAL(void)
  154935. jpeg_abort_compress (j_compress_ptr cinfo)
  154936. {
  154937. jpeg_abort((j_common_ptr) cinfo); /* use common routine */
  154938. }
  154939. /*
  154940. * Forcibly suppress or un-suppress all quantization and Huffman tables.
  154941. * Marks all currently defined tables as already written (if suppress)
  154942. * or not written (if !suppress). This will control whether they get emitted
  154943. * by a subsequent jpeg_start_compress call.
  154944. *
  154945. * This routine is exported for use by applications that want to produce
  154946. * abbreviated JPEG datastreams. It logically belongs in jcparam.c, but
  154947. * since it is called by jpeg_start_compress, we put it here --- otherwise
  154948. * jcparam.o would be linked whether the application used it or not.
  154949. */
  154950. GLOBAL(void)
  154951. jpeg_suppress_tables (j_compress_ptr cinfo, boolean suppress)
  154952. {
  154953. int i;
  154954. JQUANT_TBL * qtbl;
  154955. JHUFF_TBL * htbl;
  154956. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  154957. if ((qtbl = cinfo->quant_tbl_ptrs[i]) != NULL)
  154958. qtbl->sent_table = suppress;
  154959. }
  154960. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  154961. if ((htbl = cinfo->dc_huff_tbl_ptrs[i]) != NULL)
  154962. htbl->sent_table = suppress;
  154963. if ((htbl = cinfo->ac_huff_tbl_ptrs[i]) != NULL)
  154964. htbl->sent_table = suppress;
  154965. }
  154966. }
  154967. /*
  154968. * Finish JPEG compression.
  154969. *
  154970. * If a multipass operating mode was selected, this may do a great deal of
  154971. * work including most of the actual output.
  154972. */
  154973. GLOBAL(void)
  154974. jpeg_finish_compress (j_compress_ptr cinfo)
  154975. {
  154976. JDIMENSION iMCU_row;
  154977. if (cinfo->global_state == CSTATE_SCANNING ||
  154978. cinfo->global_state == CSTATE_RAW_OK) {
  154979. /* Terminate first pass */
  154980. if (cinfo->next_scanline < cinfo->image_height)
  154981. ERREXIT(cinfo, JERR_TOO_LITTLE_DATA);
  154982. (*cinfo->master->finish_pass) (cinfo);
  154983. } else if (cinfo->global_state != CSTATE_WRCOEFS)
  154984. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  154985. /* Perform any remaining passes */
  154986. while (! cinfo->master->is_last_pass) {
  154987. (*cinfo->master->prepare_for_pass) (cinfo);
  154988. for (iMCU_row = 0; iMCU_row < cinfo->total_iMCU_rows; iMCU_row++) {
  154989. if (cinfo->progress != NULL) {
  154990. cinfo->progress->pass_counter = (long) iMCU_row;
  154991. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows;
  154992. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  154993. }
  154994. /* We bypass the main controller and invoke coef controller directly;
  154995. * all work is being done from the coefficient buffer.
  154996. */
  154997. if (! (*cinfo->coef->compress_data) (cinfo, (JSAMPIMAGE) NULL))
  154998. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  154999. }
  155000. (*cinfo->master->finish_pass) (cinfo);
  155001. }
  155002. /* Write EOI, do final cleanup */
  155003. (*cinfo->marker->write_file_trailer) (cinfo);
  155004. (*cinfo->dest->term_destination) (cinfo);
  155005. /* We can use jpeg_abort to release memory and reset global_state */
  155006. jpeg_abort((j_common_ptr) cinfo);
  155007. }
  155008. /*
  155009. * Write a special marker.
  155010. * This is only recommended for writing COM or APPn markers.
  155011. * Must be called after jpeg_start_compress() and before
  155012. * first call to jpeg_write_scanlines() or jpeg_write_raw_data().
  155013. */
  155014. GLOBAL(void)
  155015. jpeg_write_marker (j_compress_ptr cinfo, int marker,
  155016. const JOCTET *dataptr, unsigned int datalen)
  155017. {
  155018. JMETHOD(void, write_marker_byte, (j_compress_ptr info, int val));
  155019. if (cinfo->next_scanline != 0 ||
  155020. (cinfo->global_state != CSTATE_SCANNING &&
  155021. cinfo->global_state != CSTATE_RAW_OK &&
  155022. cinfo->global_state != CSTATE_WRCOEFS))
  155023. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  155024. (*cinfo->marker->write_marker_header) (cinfo, marker, datalen);
  155025. write_marker_byte = cinfo->marker->write_marker_byte; /* copy for speed */
  155026. while (datalen--) {
  155027. (*write_marker_byte) (cinfo, *dataptr);
  155028. dataptr++;
  155029. }
  155030. }
  155031. /* Same, but piecemeal. */
  155032. GLOBAL(void)
  155033. jpeg_write_m_header (j_compress_ptr cinfo, int marker, unsigned int datalen)
  155034. {
  155035. if (cinfo->next_scanline != 0 ||
  155036. (cinfo->global_state != CSTATE_SCANNING &&
  155037. cinfo->global_state != CSTATE_RAW_OK &&
  155038. cinfo->global_state != CSTATE_WRCOEFS))
  155039. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  155040. (*cinfo->marker->write_marker_header) (cinfo, marker, datalen);
  155041. }
  155042. GLOBAL(void)
  155043. jpeg_write_m_byte (j_compress_ptr cinfo, int val)
  155044. {
  155045. (*cinfo->marker->write_marker_byte) (cinfo, val);
  155046. }
  155047. /*
  155048. * Alternate compression function: just write an abbreviated table file.
  155049. * Before calling this, all parameters and a data destination must be set up.
  155050. *
  155051. * To produce a pair of files containing abbreviated tables and abbreviated
  155052. * image data, one would proceed as follows:
  155053. *
  155054. * initialize JPEG object
  155055. * set JPEG parameters
  155056. * set destination to table file
  155057. * jpeg_write_tables(cinfo);
  155058. * set destination to image file
  155059. * jpeg_start_compress(cinfo, FALSE);
  155060. * write data...
  155061. * jpeg_finish_compress(cinfo);
  155062. *
  155063. * jpeg_write_tables has the side effect of marking all tables written
  155064. * (same as jpeg_suppress_tables(..., TRUE)). Thus a subsequent start_compress
  155065. * will not re-emit the tables unless it is passed write_all_tables=TRUE.
  155066. */
  155067. GLOBAL(void)
  155068. jpeg_write_tables (j_compress_ptr cinfo)
  155069. {
  155070. if (cinfo->global_state != CSTATE_START)
  155071. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  155072. /* (Re)initialize error mgr and destination modules */
  155073. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  155074. (*cinfo->dest->init_destination) (cinfo);
  155075. /* Initialize the marker writer ... bit of a crock to do it here. */
  155076. jinit_marker_writer(cinfo);
  155077. /* Write them tables! */
  155078. (*cinfo->marker->write_tables_only) (cinfo);
  155079. /* And clean up. */
  155080. (*cinfo->dest->term_destination) (cinfo);
  155081. /*
  155082. * In library releases up through v6a, we called jpeg_abort() here to free
  155083. * any working memory allocated by the destination manager and marker
  155084. * writer. Some applications had a problem with that: they allocated space
  155085. * of their own from the library memory manager, and didn't want it to go
  155086. * away during write_tables. So now we do nothing. This will cause a
  155087. * memory leak if an app calls write_tables repeatedly without doing a full
  155088. * compression cycle or otherwise resetting the JPEG object. However, that
  155089. * seems less bad than unexpectedly freeing memory in the normal case.
  155090. * An app that prefers the old behavior can call jpeg_abort for itself after
  155091. * each call to jpeg_write_tables().
  155092. */
  155093. }
  155094. /********* End of inlined file: jcapimin.c *********/
  155095. /********* Start of inlined file: jcapistd.c *********/
  155096. #define JPEG_INTERNALS
  155097. /*
  155098. * Compression initialization.
  155099. * Before calling this, all parameters and a data destination must be set up.
  155100. *
  155101. * We require a write_all_tables parameter as a failsafe check when writing
  155102. * multiple datastreams from the same compression object. Since prior runs
  155103. * will have left all the tables marked sent_table=TRUE, a subsequent run
  155104. * would emit an abbreviated stream (no tables) by default. This may be what
  155105. * is wanted, but for safety's sake it should not be the default behavior:
  155106. * programmers should have to make a deliberate choice to emit abbreviated
  155107. * images. Therefore the documentation and examples should encourage people
  155108. * to pass write_all_tables=TRUE; then it will take active thought to do the
  155109. * wrong thing.
  155110. */
  155111. GLOBAL(void)
  155112. jpeg_start_compress (j_compress_ptr cinfo, boolean write_all_tables)
  155113. {
  155114. if (cinfo->global_state != CSTATE_START)
  155115. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  155116. if (write_all_tables)
  155117. jpeg_suppress_tables(cinfo, FALSE); /* mark all tables to be written */
  155118. /* (Re)initialize error mgr and destination modules */
  155119. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  155120. (*cinfo->dest->init_destination) (cinfo);
  155121. /* Perform master selection of active modules */
  155122. jinit_compress_master(cinfo);
  155123. /* Set up for the first pass */
  155124. (*cinfo->master->prepare_for_pass) (cinfo);
  155125. /* Ready for application to drive first pass through jpeg_write_scanlines
  155126. * or jpeg_write_raw_data.
  155127. */
  155128. cinfo->next_scanline = 0;
  155129. cinfo->global_state = (cinfo->raw_data_in ? CSTATE_RAW_OK : CSTATE_SCANNING);
  155130. }
  155131. /*
  155132. * Write some scanlines of data to the JPEG compressor.
  155133. *
  155134. * The return value will be the number of lines actually written.
  155135. * This should be less than the supplied num_lines only in case that
  155136. * the data destination module has requested suspension of the compressor,
  155137. * or if more than image_height scanlines are passed in.
  155138. *
  155139. * Note: we warn about excess calls to jpeg_write_scanlines() since
  155140. * this likely signals an application programmer error. However,
  155141. * excess scanlines passed in the last valid call are *silently* ignored,
  155142. * so that the application need not adjust num_lines for end-of-image
  155143. * when using a multiple-scanline buffer.
  155144. */
  155145. GLOBAL(JDIMENSION)
  155146. jpeg_write_scanlines (j_compress_ptr cinfo, JSAMPARRAY scanlines,
  155147. JDIMENSION num_lines)
  155148. {
  155149. JDIMENSION row_ctr, rows_left;
  155150. if (cinfo->global_state != CSTATE_SCANNING)
  155151. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  155152. if (cinfo->next_scanline >= cinfo->image_height)
  155153. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  155154. /* Call progress monitor hook if present */
  155155. if (cinfo->progress != NULL) {
  155156. cinfo->progress->pass_counter = (long) cinfo->next_scanline;
  155157. cinfo->progress->pass_limit = (long) cinfo->image_height;
  155158. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  155159. }
  155160. /* Give master control module another chance if this is first call to
  155161. * jpeg_write_scanlines. This lets output of the frame/scan headers be
  155162. * delayed so that application can write COM, etc, markers between
  155163. * jpeg_start_compress and jpeg_write_scanlines.
  155164. */
  155165. if (cinfo->master->call_pass_startup)
  155166. (*cinfo->master->pass_startup) (cinfo);
  155167. /* Ignore any extra scanlines at bottom of image. */
  155168. rows_left = cinfo->image_height - cinfo->next_scanline;
  155169. if (num_lines > rows_left)
  155170. num_lines = rows_left;
  155171. row_ctr = 0;
  155172. (*cinfo->main->process_data) (cinfo, scanlines, &row_ctr, num_lines);
  155173. cinfo->next_scanline += row_ctr;
  155174. return row_ctr;
  155175. }
  155176. /*
  155177. * Alternate entry point to write raw data.
  155178. * Processes exactly one iMCU row per call, unless suspended.
  155179. */
  155180. GLOBAL(JDIMENSION)
  155181. jpeg_write_raw_data (j_compress_ptr cinfo, JSAMPIMAGE data,
  155182. JDIMENSION num_lines)
  155183. {
  155184. JDIMENSION lines_per_iMCU_row;
  155185. if (cinfo->global_state != CSTATE_RAW_OK)
  155186. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  155187. if (cinfo->next_scanline >= cinfo->image_height) {
  155188. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  155189. return 0;
  155190. }
  155191. /* Call progress monitor hook if present */
  155192. if (cinfo->progress != NULL) {
  155193. cinfo->progress->pass_counter = (long) cinfo->next_scanline;
  155194. cinfo->progress->pass_limit = (long) cinfo->image_height;
  155195. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  155196. }
  155197. /* Give master control module another chance if this is first call to
  155198. * jpeg_write_raw_data. This lets output of the frame/scan headers be
  155199. * delayed so that application can write COM, etc, markers between
  155200. * jpeg_start_compress and jpeg_write_raw_data.
  155201. */
  155202. if (cinfo->master->call_pass_startup)
  155203. (*cinfo->master->pass_startup) (cinfo);
  155204. /* Verify that at least one iMCU row has been passed. */
  155205. lines_per_iMCU_row = cinfo->max_v_samp_factor * DCTSIZE;
  155206. if (num_lines < lines_per_iMCU_row)
  155207. ERREXIT(cinfo, JERR_BUFFER_SIZE);
  155208. /* Directly compress the row. */
  155209. if (! (*cinfo->coef->compress_data) (cinfo, data)) {
  155210. /* If compressor did not consume the whole row, suspend processing. */
  155211. return 0;
  155212. }
  155213. /* OK, we processed one iMCU row. */
  155214. cinfo->next_scanline += lines_per_iMCU_row;
  155215. return lines_per_iMCU_row;
  155216. }
  155217. /********* End of inlined file: jcapistd.c *********/
  155218. /********* Start of inlined file: jccoefct.c *********/
  155219. #define JPEG_INTERNALS
  155220. /* We use a full-image coefficient buffer when doing Huffman optimization,
  155221. * and also for writing multiple-scan JPEG files. In all cases, the DCT
  155222. * step is run during the first pass, and subsequent passes need only read
  155223. * the buffered coefficients.
  155224. */
  155225. #ifdef ENTROPY_OPT_SUPPORTED
  155226. #define FULL_COEF_BUFFER_SUPPORTED
  155227. #else
  155228. #ifdef C_MULTISCAN_FILES_SUPPORTED
  155229. #define FULL_COEF_BUFFER_SUPPORTED
  155230. #endif
  155231. #endif
  155232. /* Private buffer controller object */
  155233. typedef struct {
  155234. struct jpeg_c_coef_controller pub; /* public fields */
  155235. JDIMENSION iMCU_row_num; /* iMCU row # within image */
  155236. JDIMENSION mcu_ctr; /* counts MCUs processed in current row */
  155237. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  155238. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  155239. /* For single-pass compression, it's sufficient to buffer just one MCU
  155240. * (although this may prove a bit slow in practice). We allocate a
  155241. * workspace of C_MAX_BLOCKS_IN_MCU coefficient blocks, and reuse it for each
  155242. * MCU constructed and sent. (On 80x86, the workspace is FAR even though
  155243. * it's not really very big; this is to keep the module interfaces unchanged
  155244. * when a large coefficient buffer is necessary.)
  155245. * In multi-pass modes, this array points to the current MCU's blocks
  155246. * within the virtual arrays.
  155247. */
  155248. JBLOCKROW MCU_buffer[C_MAX_BLOCKS_IN_MCU];
  155249. /* In multi-pass modes, we need a virtual block array for each component. */
  155250. jvirt_barray_ptr whole_image[MAX_COMPONENTS];
  155251. } my_coef_controller;
  155252. typedef my_coef_controller * my_coef_ptr;
  155253. /* Forward declarations */
  155254. METHODDEF(boolean) compress_data
  155255. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  155256. #ifdef FULL_COEF_BUFFER_SUPPORTED
  155257. METHODDEF(boolean) compress_first_pass
  155258. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  155259. METHODDEF(boolean) compress_output
  155260. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  155261. #endif
  155262. LOCAL(void)
  155263. start_iMCU_row (j_compress_ptr cinfo)
  155264. /* Reset within-iMCU-row counters for a new row */
  155265. {
  155266. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  155267. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  155268. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  155269. * But at the bottom of the image, process only what's left.
  155270. */
  155271. if (cinfo->comps_in_scan > 1) {
  155272. coef->MCU_rows_per_iMCU_row = 1;
  155273. } else {
  155274. if (coef->iMCU_row_num < (cinfo->total_iMCU_rows-1))
  155275. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  155276. else
  155277. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  155278. }
  155279. coef->mcu_ctr = 0;
  155280. coef->MCU_vert_offset = 0;
  155281. }
  155282. /*
  155283. * Initialize for a processing pass.
  155284. */
  155285. METHODDEF(void)
  155286. start_pass_coef (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  155287. {
  155288. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  155289. coef->iMCU_row_num = 0;
  155290. start_iMCU_row(cinfo);
  155291. switch (pass_mode) {
  155292. case JBUF_PASS_THRU:
  155293. if (coef->whole_image[0] != NULL)
  155294. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  155295. coef->pub.compress_data = compress_data;
  155296. break;
  155297. #ifdef FULL_COEF_BUFFER_SUPPORTED
  155298. case JBUF_SAVE_AND_PASS:
  155299. if (coef->whole_image[0] == NULL)
  155300. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  155301. coef->pub.compress_data = compress_first_pass;
  155302. break;
  155303. case JBUF_CRANK_DEST:
  155304. if (coef->whole_image[0] == NULL)
  155305. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  155306. coef->pub.compress_data = compress_output;
  155307. break;
  155308. #endif
  155309. default:
  155310. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  155311. break;
  155312. }
  155313. }
  155314. /*
  155315. * Process some data in the single-pass case.
  155316. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  155317. * per call, ie, v_samp_factor block rows for each component in the image.
  155318. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  155319. *
  155320. * NB: input_buf contains a plane for each component in image,
  155321. * which we index according to the component's SOF position.
  155322. */
  155323. METHODDEF(boolean)
  155324. compress_data (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
  155325. {
  155326. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  155327. JDIMENSION MCU_col_num; /* index of current MCU within row */
  155328. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  155329. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  155330. int blkn, bi, ci, yindex, yoffset, blockcnt;
  155331. JDIMENSION ypos, xpos;
  155332. jpeg_component_info *compptr;
  155333. /* Loop to write as much as one whole iMCU row */
  155334. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  155335. yoffset++) {
  155336. for (MCU_col_num = coef->mcu_ctr; MCU_col_num <= last_MCU_col;
  155337. MCU_col_num++) {
  155338. /* Determine where data comes from in input_buf and do the DCT thing.
  155339. * Each call on forward_DCT processes a horizontal row of DCT blocks
  155340. * as wide as an MCU; we rely on having allocated the MCU_buffer[] blocks
  155341. * sequentially. Dummy blocks at the right or bottom edge are filled in
  155342. * specially. The data in them does not matter for image reconstruction,
  155343. * so we fill them with values that will encode to the smallest amount of
  155344. * data, viz: all zeroes in the AC entries, DC entries equal to previous
  155345. * block's DC value. (Thanks to Thomas Kinsman for this idea.)
  155346. */
  155347. blkn = 0;
  155348. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  155349. compptr = cinfo->cur_comp_info[ci];
  155350. blockcnt = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  155351. : compptr->last_col_width;
  155352. xpos = MCU_col_num * compptr->MCU_sample_width;
  155353. ypos = yoffset * DCTSIZE; /* ypos == (yoffset+yindex) * DCTSIZE */
  155354. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  155355. if (coef->iMCU_row_num < last_iMCU_row ||
  155356. yoffset+yindex < compptr->last_row_height) {
  155357. (*cinfo->fdct->forward_DCT) (cinfo, compptr,
  155358. input_buf[compptr->component_index],
  155359. coef->MCU_buffer[blkn],
  155360. ypos, xpos, (JDIMENSION) blockcnt);
  155361. if (blockcnt < compptr->MCU_width) {
  155362. /* Create some dummy blocks at the right edge of the image. */
  155363. jzero_far((void FAR *) coef->MCU_buffer[blkn + blockcnt],
  155364. (compptr->MCU_width - blockcnt) * SIZEOF(JBLOCK));
  155365. for (bi = blockcnt; bi < compptr->MCU_width; bi++) {
  155366. coef->MCU_buffer[blkn+bi][0][0] = coef->MCU_buffer[blkn+bi-1][0][0];
  155367. }
  155368. }
  155369. } else {
  155370. /* Create a row of dummy blocks at the bottom of the image. */
  155371. jzero_far((void FAR *) coef->MCU_buffer[blkn],
  155372. compptr->MCU_width * SIZEOF(JBLOCK));
  155373. for (bi = 0; bi < compptr->MCU_width; bi++) {
  155374. coef->MCU_buffer[blkn+bi][0][0] = coef->MCU_buffer[blkn-1][0][0];
  155375. }
  155376. }
  155377. blkn += compptr->MCU_width;
  155378. ypos += DCTSIZE;
  155379. }
  155380. }
  155381. /* Try to write the MCU. In event of a suspension failure, we will
  155382. * re-DCT the MCU on restart (a bit inefficient, could be fixed...)
  155383. */
  155384. if (! (*cinfo->entropy->encode_mcu) (cinfo, coef->MCU_buffer)) {
  155385. /* Suspension forced; update state counters and exit */
  155386. coef->MCU_vert_offset = yoffset;
  155387. coef->mcu_ctr = MCU_col_num;
  155388. return FALSE;
  155389. }
  155390. }
  155391. /* Completed an MCU row, but perhaps not an iMCU row */
  155392. coef->mcu_ctr = 0;
  155393. }
  155394. /* Completed the iMCU row, advance counters for next one */
  155395. coef->iMCU_row_num++;
  155396. start_iMCU_row(cinfo);
  155397. return TRUE;
  155398. }
  155399. #ifdef FULL_COEF_BUFFER_SUPPORTED
  155400. /*
  155401. * Process some data in the first pass of a multi-pass case.
  155402. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  155403. * per call, ie, v_samp_factor block rows for each component in the image.
  155404. * This amount of data is read from the source buffer, DCT'd and quantized,
  155405. * and saved into the virtual arrays. We also generate suitable dummy blocks
  155406. * as needed at the right and lower edges. (The dummy blocks are constructed
  155407. * in the virtual arrays, which have been padded appropriately.) This makes
  155408. * it possible for subsequent passes not to worry about real vs. dummy blocks.
  155409. *
  155410. * We must also emit the data to the entropy encoder. This is conveniently
  155411. * done by calling compress_output() after we've loaded the current strip
  155412. * of the virtual arrays.
  155413. *
  155414. * NB: input_buf contains a plane for each component in image. All
  155415. * components are DCT'd and loaded into the virtual arrays in this pass.
  155416. * However, it may be that only a subset of the components are emitted to
  155417. * the entropy encoder during this first pass; be careful about looking
  155418. * at the scan-dependent variables (MCU dimensions, etc).
  155419. */
  155420. METHODDEF(boolean)
  155421. compress_first_pass (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
  155422. {
  155423. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  155424. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  155425. JDIMENSION blocks_across, MCUs_across, MCUindex;
  155426. int bi, ci, h_samp_factor, block_row, block_rows, ndummy;
  155427. JCOEF lastDC;
  155428. jpeg_component_info *compptr;
  155429. JBLOCKARRAY buffer;
  155430. JBLOCKROW thisblockrow, lastblockrow;
  155431. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  155432. ci++, compptr++) {
  155433. /* Align the virtual buffer for this component. */
  155434. buffer = (*cinfo->mem->access_virt_barray)
  155435. ((j_common_ptr) cinfo, coef->whole_image[ci],
  155436. coef->iMCU_row_num * compptr->v_samp_factor,
  155437. (JDIMENSION) compptr->v_samp_factor, TRUE);
  155438. /* Count non-dummy DCT block rows in this iMCU row. */
  155439. if (coef->iMCU_row_num < last_iMCU_row)
  155440. block_rows = compptr->v_samp_factor;
  155441. else {
  155442. /* NB: can't use last_row_height here, since may not be set! */
  155443. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  155444. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  155445. }
  155446. blocks_across = compptr->width_in_blocks;
  155447. h_samp_factor = compptr->h_samp_factor;
  155448. /* Count number of dummy blocks to be added at the right margin. */
  155449. ndummy = (int) (blocks_across % h_samp_factor);
  155450. if (ndummy > 0)
  155451. ndummy = h_samp_factor - ndummy;
  155452. /* Perform DCT for all non-dummy blocks in this iMCU row. Each call
  155453. * on forward_DCT processes a complete horizontal row of DCT blocks.
  155454. */
  155455. for (block_row = 0; block_row < block_rows; block_row++) {
  155456. thisblockrow = buffer[block_row];
  155457. (*cinfo->fdct->forward_DCT) (cinfo, compptr,
  155458. input_buf[ci], thisblockrow,
  155459. (JDIMENSION) (block_row * DCTSIZE),
  155460. (JDIMENSION) 0, blocks_across);
  155461. if (ndummy > 0) {
  155462. /* Create dummy blocks at the right edge of the image. */
  155463. thisblockrow += blocks_across; /* => first dummy block */
  155464. jzero_far((void FAR *) thisblockrow, ndummy * SIZEOF(JBLOCK));
  155465. lastDC = thisblockrow[-1][0];
  155466. for (bi = 0; bi < ndummy; bi++) {
  155467. thisblockrow[bi][0] = lastDC;
  155468. }
  155469. }
  155470. }
  155471. /* If at end of image, create dummy block rows as needed.
  155472. * The tricky part here is that within each MCU, we want the DC values
  155473. * of the dummy blocks to match the last real block's DC value.
  155474. * This squeezes a few more bytes out of the resulting file...
  155475. */
  155476. if (coef->iMCU_row_num == last_iMCU_row) {
  155477. blocks_across += ndummy; /* include lower right corner */
  155478. MCUs_across = blocks_across / h_samp_factor;
  155479. for (block_row = block_rows; block_row < compptr->v_samp_factor;
  155480. block_row++) {
  155481. thisblockrow = buffer[block_row];
  155482. lastblockrow = buffer[block_row-1];
  155483. jzero_far((void FAR *) thisblockrow,
  155484. (size_t) (blocks_across * SIZEOF(JBLOCK)));
  155485. for (MCUindex = 0; MCUindex < MCUs_across; MCUindex++) {
  155486. lastDC = lastblockrow[h_samp_factor-1][0];
  155487. for (bi = 0; bi < h_samp_factor; bi++) {
  155488. thisblockrow[bi][0] = lastDC;
  155489. }
  155490. thisblockrow += h_samp_factor; /* advance to next MCU in row */
  155491. lastblockrow += h_samp_factor;
  155492. }
  155493. }
  155494. }
  155495. }
  155496. /* NB: compress_output will increment iMCU_row_num if successful.
  155497. * A suspension return will result in redoing all the work above next time.
  155498. */
  155499. /* Emit data to the entropy encoder, sharing code with subsequent passes */
  155500. return compress_output(cinfo, input_buf);
  155501. }
  155502. /*
  155503. * Process some data in subsequent passes of a multi-pass case.
  155504. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  155505. * per call, ie, v_samp_factor block rows for each component in the scan.
  155506. * The data is obtained from the virtual arrays and fed to the entropy coder.
  155507. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  155508. *
  155509. * NB: input_buf is ignored; it is likely to be a NULL pointer.
  155510. */
  155511. METHODDEF(boolean)
  155512. compress_output (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
  155513. {
  155514. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  155515. JDIMENSION MCU_col_num; /* index of current MCU within row */
  155516. int blkn, ci, xindex, yindex, yoffset;
  155517. JDIMENSION start_col;
  155518. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  155519. JBLOCKROW buffer_ptr;
  155520. jpeg_component_info *compptr;
  155521. /* Align the virtual buffers for the components used in this scan.
  155522. * NB: during first pass, this is safe only because the buffers will
  155523. * already be aligned properly, so jmemmgr.c won't need to do any I/O.
  155524. */
  155525. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  155526. compptr = cinfo->cur_comp_info[ci];
  155527. buffer[ci] = (*cinfo->mem->access_virt_barray)
  155528. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  155529. coef->iMCU_row_num * compptr->v_samp_factor,
  155530. (JDIMENSION) compptr->v_samp_factor, FALSE);
  155531. }
  155532. /* Loop to process one whole iMCU row */
  155533. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  155534. yoffset++) {
  155535. for (MCU_col_num = coef->mcu_ctr; MCU_col_num < cinfo->MCUs_per_row;
  155536. MCU_col_num++) {
  155537. /* Construct list of pointers to DCT blocks belonging to this MCU */
  155538. blkn = 0; /* index of current DCT block within MCU */
  155539. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  155540. compptr = cinfo->cur_comp_info[ci];
  155541. start_col = MCU_col_num * compptr->MCU_width;
  155542. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  155543. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  155544. for (xindex = 0; xindex < compptr->MCU_width; xindex++) {
  155545. coef->MCU_buffer[blkn++] = buffer_ptr++;
  155546. }
  155547. }
  155548. }
  155549. /* Try to write the MCU. */
  155550. if (! (*cinfo->entropy->encode_mcu) (cinfo, coef->MCU_buffer)) {
  155551. /* Suspension forced; update state counters and exit */
  155552. coef->MCU_vert_offset = yoffset;
  155553. coef->mcu_ctr = MCU_col_num;
  155554. return FALSE;
  155555. }
  155556. }
  155557. /* Completed an MCU row, but perhaps not an iMCU row */
  155558. coef->mcu_ctr = 0;
  155559. }
  155560. /* Completed the iMCU row, advance counters for next one */
  155561. coef->iMCU_row_num++;
  155562. start_iMCU_row(cinfo);
  155563. return TRUE;
  155564. }
  155565. #endif /* FULL_COEF_BUFFER_SUPPORTED */
  155566. /*
  155567. * Initialize coefficient buffer controller.
  155568. */
  155569. GLOBAL(void)
  155570. jinit_c_coef_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  155571. {
  155572. my_coef_ptr coef;
  155573. coef = (my_coef_ptr)
  155574. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  155575. SIZEOF(my_coef_controller));
  155576. cinfo->coef = (struct jpeg_c_coef_controller *) coef;
  155577. coef->pub.start_pass = start_pass_coef;
  155578. /* Create the coefficient buffer. */
  155579. if (need_full_buffer) {
  155580. #ifdef FULL_COEF_BUFFER_SUPPORTED
  155581. /* Allocate a full-image virtual array for each component, */
  155582. /* padded to a multiple of samp_factor DCT blocks in each direction. */
  155583. int ci;
  155584. jpeg_component_info *compptr;
  155585. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  155586. ci++, compptr++) {
  155587. coef->whole_image[ci] = (*cinfo->mem->request_virt_barray)
  155588. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  155589. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  155590. (long) compptr->h_samp_factor),
  155591. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  155592. (long) compptr->v_samp_factor),
  155593. (JDIMENSION) compptr->v_samp_factor);
  155594. }
  155595. #else
  155596. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  155597. #endif
  155598. } else {
  155599. /* We only need a single-MCU buffer. */
  155600. JBLOCKROW buffer;
  155601. int i;
  155602. buffer = (JBLOCKROW)
  155603. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  155604. C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  155605. for (i = 0; i < C_MAX_BLOCKS_IN_MCU; i++) {
  155606. coef->MCU_buffer[i] = buffer + i;
  155607. }
  155608. coef->whole_image[0] = NULL; /* flag for no virtual arrays */
  155609. }
  155610. }
  155611. /********* End of inlined file: jccoefct.c *********/
  155612. /********* Start of inlined file: jccolor.c *********/
  155613. #define JPEG_INTERNALS
  155614. /* Private subobject */
  155615. typedef struct {
  155616. struct jpeg_color_converter pub; /* public fields */
  155617. /* Private state for RGB->YCC conversion */
  155618. INT32 * rgb_ycc_tab; /* => table for RGB to YCbCr conversion */
  155619. } my_color_converter;
  155620. typedef my_color_converter * my_cconvert_ptr;
  155621. /**************** RGB -> YCbCr conversion: most common case **************/
  155622. /*
  155623. * YCbCr is defined per CCIR 601-1, except that Cb and Cr are
  155624. * normalized to the range 0..MAXJSAMPLE rather than -0.5 .. 0.5.
  155625. * The conversion equations to be implemented are therefore
  155626. * Y = 0.29900 * R + 0.58700 * G + 0.11400 * B
  155627. * Cb = -0.16874 * R - 0.33126 * G + 0.50000 * B + CENTERJSAMPLE
  155628. * Cr = 0.50000 * R - 0.41869 * G - 0.08131 * B + CENTERJSAMPLE
  155629. * (These numbers are derived from TIFF 6.0 section 21, dated 3-June-92.)
  155630. * Note: older versions of the IJG code used a zero offset of MAXJSAMPLE/2,
  155631. * rather than CENTERJSAMPLE, for Cb and Cr. This gave equal positive and
  155632. * negative swings for Cb/Cr, but meant that grayscale values (Cb=Cr=0)
  155633. * were not represented exactly. Now we sacrifice exact representation of
  155634. * maximum red and maximum blue in order to get exact grayscales.
  155635. *
  155636. * To avoid floating-point arithmetic, we represent the fractional constants
  155637. * as integers scaled up by 2^16 (about 4 digits precision); we have to divide
  155638. * the products by 2^16, with appropriate rounding, to get the correct answer.
  155639. *
  155640. * For even more speed, we avoid doing any multiplications in the inner loop
  155641. * by precalculating the constants times R,G,B for all possible values.
  155642. * For 8-bit JSAMPLEs this is very reasonable (only 256 entries per table);
  155643. * for 12-bit samples it is still acceptable. It's not very reasonable for
  155644. * 16-bit samples, but if you want lossless storage you shouldn't be changing
  155645. * colorspace anyway.
  155646. * The CENTERJSAMPLE offsets and the rounding fudge-factor of 0.5 are included
  155647. * in the tables to save adding them separately in the inner loop.
  155648. */
  155649. #define SCALEBITS 16 /* speediest right-shift on some machines */
  155650. #define CBCR_OFFSET ((INT32) CENTERJSAMPLE << SCALEBITS)
  155651. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  155652. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  155653. /* We allocate one big table and divide it up into eight parts, instead of
  155654. * doing eight alloc_small requests. This lets us use a single table base
  155655. * address, which can be held in a register in the inner loops on many
  155656. * machines (more than can hold all eight addresses, anyway).
  155657. */
  155658. #define R_Y_OFF 0 /* offset to R => Y section */
  155659. #define G_Y_OFF (1*(MAXJSAMPLE+1)) /* offset to G => Y section */
  155660. #define B_Y_OFF (2*(MAXJSAMPLE+1)) /* etc. */
  155661. #define R_CB_OFF (3*(MAXJSAMPLE+1))
  155662. #define G_CB_OFF (4*(MAXJSAMPLE+1))
  155663. #define B_CB_OFF (5*(MAXJSAMPLE+1))
  155664. #define R_CR_OFF B_CB_OFF /* B=>Cb, R=>Cr are the same */
  155665. #define G_CR_OFF (6*(MAXJSAMPLE+1))
  155666. #define B_CR_OFF (7*(MAXJSAMPLE+1))
  155667. #define TABLE_SIZE (8*(MAXJSAMPLE+1))
  155668. /*
  155669. * Initialize for RGB->YCC colorspace conversion.
  155670. */
  155671. METHODDEF(void)
  155672. rgb_ycc_start (j_compress_ptr cinfo)
  155673. {
  155674. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  155675. INT32 * rgb_ycc_tab;
  155676. INT32 i;
  155677. /* Allocate and fill in the conversion tables. */
  155678. cconvert->rgb_ycc_tab = rgb_ycc_tab = (INT32 *)
  155679. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  155680. (TABLE_SIZE * SIZEOF(INT32)));
  155681. for (i = 0; i <= MAXJSAMPLE; i++) {
  155682. rgb_ycc_tab[i+R_Y_OFF] = FIX(0.29900) * i;
  155683. rgb_ycc_tab[i+G_Y_OFF] = FIX(0.58700) * i;
  155684. rgb_ycc_tab[i+B_Y_OFF] = FIX(0.11400) * i + ONE_HALF;
  155685. rgb_ycc_tab[i+R_CB_OFF] = (-FIX(0.16874)) * i;
  155686. rgb_ycc_tab[i+G_CB_OFF] = (-FIX(0.33126)) * i;
  155687. /* We use a rounding fudge-factor of 0.5-epsilon for Cb and Cr.
  155688. * This ensures that the maximum output will round to MAXJSAMPLE
  155689. * not MAXJSAMPLE+1, and thus that we don't have to range-limit.
  155690. */
  155691. rgb_ycc_tab[i+B_CB_OFF] = FIX(0.50000) * i + CBCR_OFFSET + ONE_HALF-1;
  155692. /* B=>Cb and R=>Cr tables are the same
  155693. rgb_ycc_tab[i+R_CR_OFF] = FIX(0.50000) * i + CBCR_OFFSET + ONE_HALF-1;
  155694. */
  155695. rgb_ycc_tab[i+G_CR_OFF] = (-FIX(0.41869)) * i;
  155696. rgb_ycc_tab[i+B_CR_OFF] = (-FIX(0.08131)) * i;
  155697. }
  155698. }
  155699. /*
  155700. * Convert some rows of samples to the JPEG colorspace.
  155701. *
  155702. * Note that we change from the application's interleaved-pixel format
  155703. * to our internal noninterleaved, one-plane-per-component format.
  155704. * The input buffer is therefore three times as wide as the output buffer.
  155705. *
  155706. * A starting row offset is provided only for the output buffer. The caller
  155707. * can easily adjust the passed input_buf value to accommodate any row
  155708. * offset required on that side.
  155709. */
  155710. METHODDEF(void)
  155711. rgb_ycc_convert (j_compress_ptr cinfo,
  155712. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  155713. JDIMENSION output_row, int num_rows)
  155714. {
  155715. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  155716. register int r, g, b;
  155717. register INT32 * ctab = cconvert->rgb_ycc_tab;
  155718. register JSAMPROW inptr;
  155719. register JSAMPROW outptr0, outptr1, outptr2;
  155720. register JDIMENSION col;
  155721. JDIMENSION num_cols = cinfo->image_width;
  155722. while (--num_rows >= 0) {
  155723. inptr = *input_buf++;
  155724. outptr0 = output_buf[0][output_row];
  155725. outptr1 = output_buf[1][output_row];
  155726. outptr2 = output_buf[2][output_row];
  155727. output_row++;
  155728. for (col = 0; col < num_cols; col++) {
  155729. r = GETJSAMPLE(inptr[RGB_RED]);
  155730. g = GETJSAMPLE(inptr[RGB_GREEN]);
  155731. b = GETJSAMPLE(inptr[RGB_BLUE]);
  155732. inptr += RGB_PIXELSIZE;
  155733. /* If the inputs are 0..MAXJSAMPLE, the outputs of these equations
  155734. * must be too; we do not need an explicit range-limiting operation.
  155735. * Hence the value being shifted is never negative, and we don't
  155736. * need the general RIGHT_SHIFT macro.
  155737. */
  155738. /* Y */
  155739. outptr0[col] = (JSAMPLE)
  155740. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  155741. >> SCALEBITS);
  155742. /* Cb */
  155743. outptr1[col] = (JSAMPLE)
  155744. ((ctab[r+R_CB_OFF] + ctab[g+G_CB_OFF] + ctab[b+B_CB_OFF])
  155745. >> SCALEBITS);
  155746. /* Cr */
  155747. outptr2[col] = (JSAMPLE)
  155748. ((ctab[r+R_CR_OFF] + ctab[g+G_CR_OFF] + ctab[b+B_CR_OFF])
  155749. >> SCALEBITS);
  155750. }
  155751. }
  155752. }
  155753. /**************** Cases other than RGB -> YCbCr **************/
  155754. /*
  155755. * Convert some rows of samples to the JPEG colorspace.
  155756. * This version handles RGB->grayscale conversion, which is the same
  155757. * as the RGB->Y portion of RGB->YCbCr.
  155758. * We assume rgb_ycc_start has been called (we only use the Y tables).
  155759. */
  155760. METHODDEF(void)
  155761. rgb_gray_convert (j_compress_ptr cinfo,
  155762. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  155763. JDIMENSION output_row, int num_rows)
  155764. {
  155765. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  155766. register int r, g, b;
  155767. register INT32 * ctab = cconvert->rgb_ycc_tab;
  155768. register JSAMPROW inptr;
  155769. register JSAMPROW outptr;
  155770. register JDIMENSION col;
  155771. JDIMENSION num_cols = cinfo->image_width;
  155772. while (--num_rows >= 0) {
  155773. inptr = *input_buf++;
  155774. outptr = output_buf[0][output_row];
  155775. output_row++;
  155776. for (col = 0; col < num_cols; col++) {
  155777. r = GETJSAMPLE(inptr[RGB_RED]);
  155778. g = GETJSAMPLE(inptr[RGB_GREEN]);
  155779. b = GETJSAMPLE(inptr[RGB_BLUE]);
  155780. inptr += RGB_PIXELSIZE;
  155781. /* Y */
  155782. outptr[col] = (JSAMPLE)
  155783. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  155784. >> SCALEBITS);
  155785. }
  155786. }
  155787. }
  155788. /*
  155789. * Convert some rows of samples to the JPEG colorspace.
  155790. * This version handles Adobe-style CMYK->YCCK conversion,
  155791. * where we convert R=1-C, G=1-M, and B=1-Y to YCbCr using the same
  155792. * conversion as above, while passing K (black) unchanged.
  155793. * We assume rgb_ycc_start has been called.
  155794. */
  155795. METHODDEF(void)
  155796. cmyk_ycck_convert (j_compress_ptr cinfo,
  155797. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  155798. JDIMENSION output_row, int num_rows)
  155799. {
  155800. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  155801. register int r, g, b;
  155802. register INT32 * ctab = cconvert->rgb_ycc_tab;
  155803. register JSAMPROW inptr;
  155804. register JSAMPROW outptr0, outptr1, outptr2, outptr3;
  155805. register JDIMENSION col;
  155806. JDIMENSION num_cols = cinfo->image_width;
  155807. while (--num_rows >= 0) {
  155808. inptr = *input_buf++;
  155809. outptr0 = output_buf[0][output_row];
  155810. outptr1 = output_buf[1][output_row];
  155811. outptr2 = output_buf[2][output_row];
  155812. outptr3 = output_buf[3][output_row];
  155813. output_row++;
  155814. for (col = 0; col < num_cols; col++) {
  155815. r = MAXJSAMPLE - GETJSAMPLE(inptr[0]);
  155816. g = MAXJSAMPLE - GETJSAMPLE(inptr[1]);
  155817. b = MAXJSAMPLE - GETJSAMPLE(inptr[2]);
  155818. /* K passes through as-is */
  155819. outptr3[col] = inptr[3]; /* don't need GETJSAMPLE here */
  155820. inptr += 4;
  155821. /* If the inputs are 0..MAXJSAMPLE, the outputs of these equations
  155822. * must be too; we do not need an explicit range-limiting operation.
  155823. * Hence the value being shifted is never negative, and we don't
  155824. * need the general RIGHT_SHIFT macro.
  155825. */
  155826. /* Y */
  155827. outptr0[col] = (JSAMPLE)
  155828. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  155829. >> SCALEBITS);
  155830. /* Cb */
  155831. outptr1[col] = (JSAMPLE)
  155832. ((ctab[r+R_CB_OFF] + ctab[g+G_CB_OFF] + ctab[b+B_CB_OFF])
  155833. >> SCALEBITS);
  155834. /* Cr */
  155835. outptr2[col] = (JSAMPLE)
  155836. ((ctab[r+R_CR_OFF] + ctab[g+G_CR_OFF] + ctab[b+B_CR_OFF])
  155837. >> SCALEBITS);
  155838. }
  155839. }
  155840. }
  155841. /*
  155842. * Convert some rows of samples to the JPEG colorspace.
  155843. * This version handles grayscale output with no conversion.
  155844. * The source can be either plain grayscale or YCbCr (since Y == gray).
  155845. */
  155846. METHODDEF(void)
  155847. grayscale_convert (j_compress_ptr cinfo,
  155848. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  155849. JDIMENSION output_row, int num_rows)
  155850. {
  155851. register JSAMPROW inptr;
  155852. register JSAMPROW outptr;
  155853. register JDIMENSION col;
  155854. JDIMENSION num_cols = cinfo->image_width;
  155855. int instride = cinfo->input_components;
  155856. while (--num_rows >= 0) {
  155857. inptr = *input_buf++;
  155858. outptr = output_buf[0][output_row];
  155859. output_row++;
  155860. for (col = 0; col < num_cols; col++) {
  155861. outptr[col] = inptr[0]; /* don't need GETJSAMPLE() here */
  155862. inptr += instride;
  155863. }
  155864. }
  155865. }
  155866. /*
  155867. * Convert some rows of samples to the JPEG colorspace.
  155868. * This version handles multi-component colorspaces without conversion.
  155869. * We assume input_components == num_components.
  155870. */
  155871. METHODDEF(void)
  155872. null_convert (j_compress_ptr cinfo,
  155873. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  155874. JDIMENSION output_row, int num_rows)
  155875. {
  155876. register JSAMPROW inptr;
  155877. register JSAMPROW outptr;
  155878. register JDIMENSION col;
  155879. register int ci;
  155880. int nc = cinfo->num_components;
  155881. JDIMENSION num_cols = cinfo->image_width;
  155882. while (--num_rows >= 0) {
  155883. /* It seems fastest to make a separate pass for each component. */
  155884. for (ci = 0; ci < nc; ci++) {
  155885. inptr = *input_buf;
  155886. outptr = output_buf[ci][output_row];
  155887. for (col = 0; col < num_cols; col++) {
  155888. outptr[col] = inptr[ci]; /* don't need GETJSAMPLE() here */
  155889. inptr += nc;
  155890. }
  155891. }
  155892. input_buf++;
  155893. output_row++;
  155894. }
  155895. }
  155896. /*
  155897. * Empty method for start_pass.
  155898. */
  155899. METHODDEF(void)
  155900. null_method (j_compress_ptr cinfo)
  155901. {
  155902. /* no work needed */
  155903. }
  155904. /*
  155905. * Module initialization routine for input colorspace conversion.
  155906. */
  155907. GLOBAL(void)
  155908. jinit_color_converter (j_compress_ptr cinfo)
  155909. {
  155910. my_cconvert_ptr cconvert;
  155911. cconvert = (my_cconvert_ptr)
  155912. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  155913. SIZEOF(my_color_converter));
  155914. cinfo->cconvert = (struct jpeg_color_converter *) cconvert;
  155915. /* set start_pass to null method until we find out differently */
  155916. cconvert->pub.start_pass = null_method;
  155917. /* Make sure input_components agrees with in_color_space */
  155918. switch (cinfo->in_color_space) {
  155919. case JCS_GRAYSCALE:
  155920. if (cinfo->input_components != 1)
  155921. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  155922. break;
  155923. case JCS_RGB:
  155924. #if RGB_PIXELSIZE != 3
  155925. if (cinfo->input_components != RGB_PIXELSIZE)
  155926. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  155927. break;
  155928. #endif /* else share code with YCbCr */
  155929. case JCS_YCbCr:
  155930. if (cinfo->input_components != 3)
  155931. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  155932. break;
  155933. case JCS_CMYK:
  155934. case JCS_YCCK:
  155935. if (cinfo->input_components != 4)
  155936. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  155937. break;
  155938. default: /* JCS_UNKNOWN can be anything */
  155939. if (cinfo->input_components < 1)
  155940. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  155941. break;
  155942. }
  155943. /* Check num_components, set conversion method based on requested space */
  155944. switch (cinfo->jpeg_color_space) {
  155945. case JCS_GRAYSCALE:
  155946. if (cinfo->num_components != 1)
  155947. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  155948. if (cinfo->in_color_space == JCS_GRAYSCALE)
  155949. cconvert->pub.color_convert = grayscale_convert;
  155950. else if (cinfo->in_color_space == JCS_RGB) {
  155951. cconvert->pub.start_pass = rgb_ycc_start;
  155952. cconvert->pub.color_convert = rgb_gray_convert;
  155953. } else if (cinfo->in_color_space == JCS_YCbCr)
  155954. cconvert->pub.color_convert = grayscale_convert;
  155955. else
  155956. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  155957. break;
  155958. case JCS_RGB:
  155959. if (cinfo->num_components != 3)
  155960. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  155961. if (cinfo->in_color_space == JCS_RGB && RGB_PIXELSIZE == 3)
  155962. cconvert->pub.color_convert = null_convert;
  155963. else
  155964. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  155965. break;
  155966. case JCS_YCbCr:
  155967. if (cinfo->num_components != 3)
  155968. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  155969. if (cinfo->in_color_space == JCS_RGB) {
  155970. cconvert->pub.start_pass = rgb_ycc_start;
  155971. cconvert->pub.color_convert = rgb_ycc_convert;
  155972. } else if (cinfo->in_color_space == JCS_YCbCr)
  155973. cconvert->pub.color_convert = null_convert;
  155974. else
  155975. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  155976. break;
  155977. case JCS_CMYK:
  155978. if (cinfo->num_components != 4)
  155979. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  155980. if (cinfo->in_color_space == JCS_CMYK)
  155981. cconvert->pub.color_convert = null_convert;
  155982. else
  155983. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  155984. break;
  155985. case JCS_YCCK:
  155986. if (cinfo->num_components != 4)
  155987. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  155988. if (cinfo->in_color_space == JCS_CMYK) {
  155989. cconvert->pub.start_pass = rgb_ycc_start;
  155990. cconvert->pub.color_convert = cmyk_ycck_convert;
  155991. } else if (cinfo->in_color_space == JCS_YCCK)
  155992. cconvert->pub.color_convert = null_convert;
  155993. else
  155994. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  155995. break;
  155996. default: /* allow null conversion of JCS_UNKNOWN */
  155997. if (cinfo->jpeg_color_space != cinfo->in_color_space ||
  155998. cinfo->num_components != cinfo->input_components)
  155999. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  156000. cconvert->pub.color_convert = null_convert;
  156001. break;
  156002. }
  156003. }
  156004. /********* End of inlined file: jccolor.c *********/
  156005. #undef FIX
  156006. /********* Start of inlined file: jcdctmgr.c *********/
  156007. #define JPEG_INTERNALS
  156008. /********* Start of inlined file: jdct.h *********/
  156009. /*
  156010. * A forward DCT routine is given a pointer to a work area of type DCTELEM[];
  156011. * the DCT is to be performed in-place in that buffer. Type DCTELEM is int
  156012. * for 8-bit samples, INT32 for 12-bit samples. (NOTE: Floating-point DCT
  156013. * implementations use an array of type FAST_FLOAT, instead.)
  156014. * The DCT inputs are expected to be signed (range +-CENTERJSAMPLE).
  156015. * The DCT outputs are returned scaled up by a factor of 8; they therefore
  156016. * have a range of +-8K for 8-bit data, +-128K for 12-bit data. This
  156017. * convention improves accuracy in integer implementations and saves some
  156018. * work in floating-point ones.
  156019. * Quantization of the output coefficients is done by jcdctmgr.c.
  156020. */
  156021. #ifndef __jdct_h__
  156022. #define __jdct_h__
  156023. #if BITS_IN_JSAMPLE == 8
  156024. typedef int DCTELEM; /* 16 or 32 bits is fine */
  156025. #else
  156026. typedef INT32 DCTELEM; /* must have 32 bits */
  156027. #endif
  156028. typedef JMETHOD(void, forward_DCT_method_ptr, (DCTELEM * data));
  156029. typedef JMETHOD(void, float_DCT_method_ptr, (FAST_FLOAT * data));
  156030. /*
  156031. * An inverse DCT routine is given a pointer to the input JBLOCK and a pointer
  156032. * to an output sample array. The routine must dequantize the input data as
  156033. * well as perform the IDCT; for dequantization, it uses the multiplier table
  156034. * pointed to by compptr->dct_table. The output data is to be placed into the
  156035. * sample array starting at a specified column. (Any row offset needed will
  156036. * be applied to the array pointer before it is passed to the IDCT code.)
  156037. * Note that the number of samples emitted by the IDCT routine is
  156038. * DCT_scaled_size * DCT_scaled_size.
  156039. */
  156040. /* typedef inverse_DCT_method_ptr is declared in jpegint.h */
  156041. /*
  156042. * Each IDCT routine has its own ideas about the best dct_table element type.
  156043. */
  156044. typedef MULTIPLIER ISLOW_MULT_TYPE; /* short or int, whichever is faster */
  156045. #if BITS_IN_JSAMPLE == 8
  156046. typedef MULTIPLIER IFAST_MULT_TYPE; /* 16 bits is OK, use short if faster */
  156047. #define IFAST_SCALE_BITS 2 /* fractional bits in scale factors */
  156048. #else
  156049. typedef INT32 IFAST_MULT_TYPE; /* need 32 bits for scaled quantizers */
  156050. #define IFAST_SCALE_BITS 13 /* fractional bits in scale factors */
  156051. #endif
  156052. typedef FAST_FLOAT FLOAT_MULT_TYPE; /* preferred floating type */
  156053. /*
  156054. * Each IDCT routine is responsible for range-limiting its results and
  156055. * converting them to unsigned form (0..MAXJSAMPLE). The raw outputs could
  156056. * be quite far out of range if the input data is corrupt, so a bulletproof
  156057. * range-limiting step is required. We use a mask-and-table-lookup method
  156058. * to do the combined operations quickly. See the comments with
  156059. * prepare_range_limit_table (in jdmaster.c) for more info.
  156060. */
  156061. #define IDCT_range_limit(cinfo) ((cinfo)->sample_range_limit + CENTERJSAMPLE)
  156062. #define RANGE_MASK (MAXJSAMPLE * 4 + 3) /* 2 bits wider than legal samples */
  156063. /* Short forms of external names for systems with brain-damaged linkers. */
  156064. #ifdef NEED_SHORT_EXTERNAL_NAMES
  156065. #define jpeg_fdct_islow jFDislow
  156066. #define jpeg_fdct_ifast jFDifast
  156067. #define jpeg_fdct_float jFDfloat
  156068. #define jpeg_idct_islow jRDislow
  156069. #define jpeg_idct_ifast jRDifast
  156070. #define jpeg_idct_float jRDfloat
  156071. #define jpeg_idct_4x4 jRD4x4
  156072. #define jpeg_idct_2x2 jRD2x2
  156073. #define jpeg_idct_1x1 jRD1x1
  156074. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  156075. /* Extern declarations for the forward and inverse DCT routines. */
  156076. EXTERN(void) jpeg_fdct_islow JPP((DCTELEM * data));
  156077. EXTERN(void) jpeg_fdct_ifast JPP((DCTELEM * data));
  156078. EXTERN(void) jpeg_fdct_float JPP((FAST_FLOAT * data));
  156079. EXTERN(void) jpeg_idct_islow
  156080. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  156081. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  156082. EXTERN(void) jpeg_idct_ifast
  156083. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  156084. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  156085. EXTERN(void) jpeg_idct_float
  156086. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  156087. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  156088. EXTERN(void) jpeg_idct_4x4
  156089. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  156090. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  156091. EXTERN(void) jpeg_idct_2x2
  156092. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  156093. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  156094. EXTERN(void) jpeg_idct_1x1
  156095. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  156096. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  156097. /*
  156098. * Macros for handling fixed-point arithmetic; these are used by many
  156099. * but not all of the DCT/IDCT modules.
  156100. *
  156101. * All values are expected to be of type INT32.
  156102. * Fractional constants are scaled left by CONST_BITS bits.
  156103. * CONST_BITS is defined within each module using these macros,
  156104. * and may differ from one module to the next.
  156105. */
  156106. #define ONE ((INT32) 1)
  156107. #define CONST_SCALE (ONE << CONST_BITS)
  156108. /* Convert a positive real constant to an integer scaled by CONST_SCALE.
  156109. * Caution: some C compilers fail to reduce "FIX(constant)" at compile time,
  156110. * thus causing a lot of useless floating-point operations at run time.
  156111. */
  156112. #define FIX(x) ((INT32) ((x) * CONST_SCALE + 0.5))
  156113. /* Descale and correctly round an INT32 value that's scaled by N bits.
  156114. * We assume RIGHT_SHIFT rounds towards minus infinity, so adding
  156115. * the fudge factor is correct for either sign of X.
  156116. */
  156117. #define DESCALE(x,n) RIGHT_SHIFT((x) + (ONE << ((n)-1)), n)
  156118. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  156119. * This macro is used only when the two inputs will actually be no more than
  156120. * 16 bits wide, so that a 16x16->32 bit multiply can be used instead of a
  156121. * full 32x32 multiply. This provides a useful speedup on many machines.
  156122. * Unfortunately there is no way to specify a 16x16->32 multiply portably
  156123. * in C, but some C compilers will do the right thing if you provide the
  156124. * correct combination of casts.
  156125. */
  156126. #ifdef SHORTxSHORT_32 /* may work if 'int' is 32 bits */
  156127. #define MULTIPLY16C16(var,const) (((INT16) (var)) * ((INT16) (const)))
  156128. #endif
  156129. #ifdef SHORTxLCONST_32 /* known to work with Microsoft C 6.0 */
  156130. #define MULTIPLY16C16(var,const) (((INT16) (var)) * ((INT32) (const)))
  156131. #endif
  156132. #ifndef MULTIPLY16C16 /* default definition */
  156133. #define MULTIPLY16C16(var,const) ((var) * (const))
  156134. #endif
  156135. /* Same except both inputs are variables. */
  156136. #ifdef SHORTxSHORT_32 /* may work if 'int' is 32 bits */
  156137. #define MULTIPLY16V16(var1,var2) (((INT16) (var1)) * ((INT16) (var2)))
  156138. #endif
  156139. #ifndef MULTIPLY16V16 /* default definition */
  156140. #define MULTIPLY16V16(var1,var2) ((var1) * (var2))
  156141. #endif
  156142. #endif
  156143. /********* End of inlined file: jdct.h *********/
  156144. /* Private declarations for DCT subsystem */
  156145. /* Private subobject for this module */
  156146. typedef struct {
  156147. struct jpeg_forward_dct pub; /* public fields */
  156148. /* Pointer to the DCT routine actually in use */
  156149. forward_DCT_method_ptr do_dct;
  156150. /* The actual post-DCT divisors --- not identical to the quant table
  156151. * entries, because of scaling (especially for an unnormalized DCT).
  156152. * Each table is given in normal array order.
  156153. */
  156154. DCTELEM * divisors[NUM_QUANT_TBLS];
  156155. #ifdef DCT_FLOAT_SUPPORTED
  156156. /* Same as above for the floating-point case. */
  156157. float_DCT_method_ptr do_float_dct;
  156158. FAST_FLOAT * float_divisors[NUM_QUANT_TBLS];
  156159. #endif
  156160. } my_fdct_controller;
  156161. typedef my_fdct_controller * my_fdct_ptr;
  156162. /*
  156163. * Initialize for a processing pass.
  156164. * Verify that all referenced Q-tables are present, and set up
  156165. * the divisor table for each one.
  156166. * In the current implementation, DCT of all components is done during
  156167. * the first pass, even if only some components will be output in the
  156168. * first scan. Hence all components should be examined here.
  156169. */
  156170. METHODDEF(void)
  156171. start_pass_fdctmgr (j_compress_ptr cinfo)
  156172. {
  156173. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  156174. int ci, qtblno, i;
  156175. jpeg_component_info *compptr;
  156176. JQUANT_TBL * qtbl;
  156177. DCTELEM * dtbl;
  156178. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  156179. ci++, compptr++) {
  156180. qtblno = compptr->quant_tbl_no;
  156181. /* Make sure specified quantization table is present */
  156182. if (qtblno < 0 || qtblno >= NUM_QUANT_TBLS ||
  156183. cinfo->quant_tbl_ptrs[qtblno] == NULL)
  156184. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, qtblno);
  156185. qtbl = cinfo->quant_tbl_ptrs[qtblno];
  156186. /* Compute divisors for this quant table */
  156187. /* We may do this more than once for same table, but it's not a big deal */
  156188. switch (cinfo->dct_method) {
  156189. #ifdef DCT_ISLOW_SUPPORTED
  156190. case JDCT_ISLOW:
  156191. /* For LL&M IDCT method, divisors are equal to raw quantization
  156192. * coefficients multiplied by 8 (to counteract scaling).
  156193. */
  156194. if (fdct->divisors[qtblno] == NULL) {
  156195. fdct->divisors[qtblno] = (DCTELEM *)
  156196. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  156197. DCTSIZE2 * SIZEOF(DCTELEM));
  156198. }
  156199. dtbl = fdct->divisors[qtblno];
  156200. for (i = 0; i < DCTSIZE2; i++) {
  156201. dtbl[i] = ((DCTELEM) qtbl->quantval[i]) << 3;
  156202. }
  156203. break;
  156204. #endif
  156205. #ifdef DCT_IFAST_SUPPORTED
  156206. case JDCT_IFAST:
  156207. {
  156208. /* For AA&N IDCT method, divisors are equal to quantization
  156209. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  156210. * scalefactor[0] = 1
  156211. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  156212. * We apply a further scale factor of 8.
  156213. */
  156214. #define CONST_BITS 14
  156215. static const INT16 aanscales[DCTSIZE2] = {
  156216. /* precomputed values scaled up by 14 bits */
  156217. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  156218. 22725, 31521, 29692, 26722, 22725, 17855, 12299, 6270,
  156219. 21407, 29692, 27969, 25172, 21407, 16819, 11585, 5906,
  156220. 19266, 26722, 25172, 22654, 19266, 15137, 10426, 5315,
  156221. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  156222. 12873, 17855, 16819, 15137, 12873, 10114, 6967, 3552,
  156223. 8867, 12299, 11585, 10426, 8867, 6967, 4799, 2446,
  156224. 4520, 6270, 5906, 5315, 4520, 3552, 2446, 1247
  156225. };
  156226. SHIFT_TEMPS
  156227. if (fdct->divisors[qtblno] == NULL) {
  156228. fdct->divisors[qtblno] = (DCTELEM *)
  156229. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  156230. DCTSIZE2 * SIZEOF(DCTELEM));
  156231. }
  156232. dtbl = fdct->divisors[qtblno];
  156233. for (i = 0; i < DCTSIZE2; i++) {
  156234. dtbl[i] = (DCTELEM)
  156235. DESCALE(MULTIPLY16V16((INT32) qtbl->quantval[i],
  156236. (INT32) aanscales[i]),
  156237. CONST_BITS-3);
  156238. }
  156239. }
  156240. break;
  156241. #endif
  156242. #ifdef DCT_FLOAT_SUPPORTED
  156243. case JDCT_FLOAT:
  156244. {
  156245. /* For float AA&N IDCT method, divisors are equal to quantization
  156246. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  156247. * scalefactor[0] = 1
  156248. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  156249. * We apply a further scale factor of 8.
  156250. * What's actually stored is 1/divisor so that the inner loop can
  156251. * use a multiplication rather than a division.
  156252. */
  156253. FAST_FLOAT * fdtbl;
  156254. int row, col;
  156255. static const double aanscalefactor[DCTSIZE] = {
  156256. 1.0, 1.387039845, 1.306562965, 1.175875602,
  156257. 1.0, 0.785694958, 0.541196100, 0.275899379
  156258. };
  156259. if (fdct->float_divisors[qtblno] == NULL) {
  156260. fdct->float_divisors[qtblno] = (FAST_FLOAT *)
  156261. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  156262. DCTSIZE2 * SIZEOF(FAST_FLOAT));
  156263. }
  156264. fdtbl = fdct->float_divisors[qtblno];
  156265. i = 0;
  156266. for (row = 0; row < DCTSIZE; row++) {
  156267. for (col = 0; col < DCTSIZE; col++) {
  156268. fdtbl[i] = (FAST_FLOAT)
  156269. (1.0 / (((double) qtbl->quantval[i] *
  156270. aanscalefactor[row] * aanscalefactor[col] * 8.0)));
  156271. i++;
  156272. }
  156273. }
  156274. }
  156275. break;
  156276. #endif
  156277. default:
  156278. ERREXIT(cinfo, JERR_NOT_COMPILED);
  156279. break;
  156280. }
  156281. }
  156282. }
  156283. /*
  156284. * Perform forward DCT on one or more blocks of a component.
  156285. *
  156286. * The input samples are taken from the sample_data[] array starting at
  156287. * position start_row/start_col, and moving to the right for any additional
  156288. * blocks. The quantized coefficients are returned in coef_blocks[].
  156289. */
  156290. METHODDEF(void)
  156291. forward_DCT (j_compress_ptr cinfo, jpeg_component_info * compptr,
  156292. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  156293. JDIMENSION start_row, JDIMENSION start_col,
  156294. JDIMENSION num_blocks)
  156295. /* This version is used for integer DCT implementations. */
  156296. {
  156297. /* This routine is heavily used, so it's worth coding it tightly. */
  156298. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  156299. forward_DCT_method_ptr do_dct = fdct->do_dct;
  156300. DCTELEM * divisors = fdct->divisors[compptr->quant_tbl_no];
  156301. DCTELEM workspace[DCTSIZE2]; /* work area for FDCT subroutine */
  156302. JDIMENSION bi;
  156303. sample_data += start_row; /* fold in the vertical offset once */
  156304. for (bi = 0; bi < num_blocks; bi++, start_col += DCTSIZE) {
  156305. /* Load data into workspace, applying unsigned->signed conversion */
  156306. { register DCTELEM *workspaceptr;
  156307. register JSAMPROW elemptr;
  156308. register int elemr;
  156309. workspaceptr = workspace;
  156310. for (elemr = 0; elemr < DCTSIZE; elemr++) {
  156311. elemptr = sample_data[elemr] + start_col;
  156312. #if DCTSIZE == 8 /* unroll the inner loop */
  156313. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  156314. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  156315. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  156316. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  156317. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  156318. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  156319. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  156320. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  156321. #else
  156322. { register int elemc;
  156323. for (elemc = DCTSIZE; elemc > 0; elemc--) {
  156324. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  156325. }
  156326. }
  156327. #endif
  156328. }
  156329. }
  156330. /* Perform the DCT */
  156331. (*do_dct) (workspace);
  156332. /* Quantize/descale the coefficients, and store into coef_blocks[] */
  156333. { register DCTELEM temp, qval;
  156334. register int i;
  156335. register JCOEFPTR output_ptr = coef_blocks[bi];
  156336. for (i = 0; i < DCTSIZE2; i++) {
  156337. qval = divisors[i];
  156338. temp = workspace[i];
  156339. /* Divide the coefficient value by qval, ensuring proper rounding.
  156340. * Since C does not specify the direction of rounding for negative
  156341. * quotients, we have to force the dividend positive for portability.
  156342. *
  156343. * In most files, at least half of the output values will be zero
  156344. * (at default quantization settings, more like three-quarters...)
  156345. * so we should ensure that this case is fast. On many machines,
  156346. * a comparison is enough cheaper than a divide to make a special test
  156347. * a win. Since both inputs will be nonnegative, we need only test
  156348. * for a < b to discover whether a/b is 0.
  156349. * If your machine's division is fast enough, define FAST_DIVIDE.
  156350. */
  156351. #ifdef FAST_DIVIDE
  156352. #define DIVIDE_BY(a,b) a /= b
  156353. #else
  156354. #define DIVIDE_BY(a,b) if (a >= b) a /= b; else a = 0
  156355. #endif
  156356. if (temp < 0) {
  156357. temp = -temp;
  156358. temp += qval>>1; /* for rounding */
  156359. DIVIDE_BY(temp, qval);
  156360. temp = -temp;
  156361. } else {
  156362. temp += qval>>1; /* for rounding */
  156363. DIVIDE_BY(temp, qval);
  156364. }
  156365. output_ptr[i] = (JCOEF) temp;
  156366. }
  156367. }
  156368. }
  156369. }
  156370. #ifdef DCT_FLOAT_SUPPORTED
  156371. METHODDEF(void)
  156372. forward_DCT_float (j_compress_ptr cinfo, jpeg_component_info * compptr,
  156373. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  156374. JDIMENSION start_row, JDIMENSION start_col,
  156375. JDIMENSION num_blocks)
  156376. /* This version is used for floating-point DCT implementations. */
  156377. {
  156378. /* This routine is heavily used, so it's worth coding it tightly. */
  156379. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  156380. float_DCT_method_ptr do_dct = fdct->do_float_dct;
  156381. FAST_FLOAT * divisors = fdct->float_divisors[compptr->quant_tbl_no];
  156382. FAST_FLOAT workspace[DCTSIZE2]; /* work area for FDCT subroutine */
  156383. JDIMENSION bi;
  156384. sample_data += start_row; /* fold in the vertical offset once */
  156385. for (bi = 0; bi < num_blocks; bi++, start_col += DCTSIZE) {
  156386. /* Load data into workspace, applying unsigned->signed conversion */
  156387. { register FAST_FLOAT *workspaceptr;
  156388. register JSAMPROW elemptr;
  156389. register int elemr;
  156390. workspaceptr = workspace;
  156391. for (elemr = 0; elemr < DCTSIZE; elemr++) {
  156392. elemptr = sample_data[elemr] + start_col;
  156393. #if DCTSIZE == 8 /* unroll the inner loop */
  156394. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  156395. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  156396. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  156397. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  156398. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  156399. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  156400. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  156401. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  156402. #else
  156403. { register int elemc;
  156404. for (elemc = DCTSIZE; elemc > 0; elemc--) {
  156405. *workspaceptr++ = (FAST_FLOAT)
  156406. (GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  156407. }
  156408. }
  156409. #endif
  156410. }
  156411. }
  156412. /* Perform the DCT */
  156413. (*do_dct) (workspace);
  156414. /* Quantize/descale the coefficients, and store into coef_blocks[] */
  156415. { register FAST_FLOAT temp;
  156416. register int i;
  156417. register JCOEFPTR output_ptr = coef_blocks[bi];
  156418. for (i = 0; i < DCTSIZE2; i++) {
  156419. /* Apply the quantization and scaling factor */
  156420. temp = workspace[i] * divisors[i];
  156421. /* Round to nearest integer.
  156422. * Since C does not specify the direction of rounding for negative
  156423. * quotients, we have to force the dividend positive for portability.
  156424. * The maximum coefficient size is +-16K (for 12-bit data), so this
  156425. * code should work for either 16-bit or 32-bit ints.
  156426. */
  156427. output_ptr[i] = (JCOEF) ((int) (temp + (FAST_FLOAT) 16384.5) - 16384);
  156428. }
  156429. }
  156430. }
  156431. }
  156432. #endif /* DCT_FLOAT_SUPPORTED */
  156433. /*
  156434. * Initialize FDCT manager.
  156435. */
  156436. GLOBAL(void)
  156437. jinit_forward_dct (j_compress_ptr cinfo)
  156438. {
  156439. my_fdct_ptr fdct;
  156440. int i;
  156441. fdct = (my_fdct_ptr)
  156442. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  156443. SIZEOF(my_fdct_controller));
  156444. cinfo->fdct = (struct jpeg_forward_dct *) fdct;
  156445. fdct->pub.start_pass = start_pass_fdctmgr;
  156446. switch (cinfo->dct_method) {
  156447. #ifdef DCT_ISLOW_SUPPORTED
  156448. case JDCT_ISLOW:
  156449. fdct->pub.forward_DCT = forward_DCT;
  156450. fdct->do_dct = jpeg_fdct_islow;
  156451. break;
  156452. #endif
  156453. #ifdef DCT_IFAST_SUPPORTED
  156454. case JDCT_IFAST:
  156455. fdct->pub.forward_DCT = forward_DCT;
  156456. fdct->do_dct = jpeg_fdct_ifast;
  156457. break;
  156458. #endif
  156459. #ifdef DCT_FLOAT_SUPPORTED
  156460. case JDCT_FLOAT:
  156461. fdct->pub.forward_DCT = forward_DCT_float;
  156462. fdct->do_float_dct = jpeg_fdct_float;
  156463. break;
  156464. #endif
  156465. default:
  156466. ERREXIT(cinfo, JERR_NOT_COMPILED);
  156467. break;
  156468. }
  156469. /* Mark divisor tables unallocated */
  156470. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  156471. fdct->divisors[i] = NULL;
  156472. #ifdef DCT_FLOAT_SUPPORTED
  156473. fdct->float_divisors[i] = NULL;
  156474. #endif
  156475. }
  156476. }
  156477. /********* End of inlined file: jcdctmgr.c *********/
  156478. #undef CONST_BITS
  156479. /********* Start of inlined file: jchuff.c *********/
  156480. #define JPEG_INTERNALS
  156481. /********* Start of inlined file: jchuff.h *********/
  156482. /* The legal range of a DCT coefficient is
  156483. * -1024 .. +1023 for 8-bit data;
  156484. * -16384 .. +16383 for 12-bit data.
  156485. * Hence the magnitude should always fit in 10 or 14 bits respectively.
  156486. */
  156487. #ifndef _jchuff_h_
  156488. #define _jchuff_h_
  156489. #if BITS_IN_JSAMPLE == 8
  156490. #define MAX_COEF_BITS 10
  156491. #else
  156492. #define MAX_COEF_BITS 14
  156493. #endif
  156494. /* Derived data constructed for each Huffman table */
  156495. typedef struct {
  156496. unsigned int ehufco[256]; /* code for each symbol */
  156497. char ehufsi[256]; /* length of code for each symbol */
  156498. /* If no code has been allocated for a symbol S, ehufsi[S] contains 0 */
  156499. } c_derived_tbl;
  156500. /* Short forms of external names for systems with brain-damaged linkers. */
  156501. #ifdef NEED_SHORT_EXTERNAL_NAMES
  156502. #define jpeg_make_c_derived_tbl jMkCDerived
  156503. #define jpeg_gen_optimal_table jGenOptTbl
  156504. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  156505. /* Expand a Huffman table definition into the derived format */
  156506. EXTERN(void) jpeg_make_c_derived_tbl
  156507. JPP((j_compress_ptr cinfo, boolean isDC, int tblno,
  156508. c_derived_tbl ** pdtbl));
  156509. /* Generate an optimal table definition given the specified counts */
  156510. EXTERN(void) jpeg_gen_optimal_table
  156511. JPP((j_compress_ptr cinfo, JHUFF_TBL * htbl, long freq[]));
  156512. #endif
  156513. /********* End of inlined file: jchuff.h *********/
  156514. /* Declarations shared with jcphuff.c */
  156515. /* Expanded entropy encoder object for Huffman encoding.
  156516. *
  156517. * The savable_state subrecord contains fields that change within an MCU,
  156518. * but must not be updated permanently until we complete the MCU.
  156519. */
  156520. typedef struct {
  156521. INT32 put_buffer; /* current bit-accumulation buffer */
  156522. int put_bits; /* # of bits now in it */
  156523. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  156524. } savable_state;
  156525. /* This macro is to work around compilers with missing or broken
  156526. * structure assignment. You'll need to fix this code if you have
  156527. * such a compiler and you change MAX_COMPS_IN_SCAN.
  156528. */
  156529. #ifndef NO_STRUCT_ASSIGN
  156530. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  156531. #else
  156532. #if MAX_COMPS_IN_SCAN == 4
  156533. #define ASSIGN_STATE(dest,src) \
  156534. ((dest).put_buffer = (src).put_buffer, \
  156535. (dest).put_bits = (src).put_bits, \
  156536. (dest).last_dc_val[0] = (src).last_dc_val[0], \
  156537. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  156538. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  156539. (dest).last_dc_val[3] = (src).last_dc_val[3])
  156540. #endif
  156541. #endif
  156542. typedef struct {
  156543. struct jpeg_entropy_encoder pub; /* public fields */
  156544. savable_state saved; /* Bit buffer & DC state at start of MCU */
  156545. /* These fields are NOT loaded into local working state. */
  156546. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  156547. int next_restart_num; /* next restart number to write (0-7) */
  156548. /* Pointers to derived tables (these workspaces have image lifespan) */
  156549. c_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
  156550. c_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
  156551. #ifdef ENTROPY_OPT_SUPPORTED /* Statistics tables for optimization */
  156552. long * dc_count_ptrs[NUM_HUFF_TBLS];
  156553. long * ac_count_ptrs[NUM_HUFF_TBLS];
  156554. #endif
  156555. } huff_entropy_encoder;
  156556. typedef huff_entropy_encoder * huff_entropy_ptr;
  156557. /* Working state while writing an MCU.
  156558. * This struct contains all the fields that are needed by subroutines.
  156559. */
  156560. typedef struct {
  156561. JOCTET * next_output_byte; /* => next byte to write in buffer */
  156562. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  156563. savable_state cur; /* Current bit buffer & DC state */
  156564. j_compress_ptr cinfo; /* dump_buffer needs access to this */
  156565. } working_state;
  156566. /* Forward declarations */
  156567. METHODDEF(boolean) encode_mcu_huff JPP((j_compress_ptr cinfo,
  156568. JBLOCKROW *MCU_data));
  156569. METHODDEF(void) finish_pass_huff JPP((j_compress_ptr cinfo));
  156570. #ifdef ENTROPY_OPT_SUPPORTED
  156571. METHODDEF(boolean) encode_mcu_gather JPP((j_compress_ptr cinfo,
  156572. JBLOCKROW *MCU_data));
  156573. METHODDEF(void) finish_pass_gather JPP((j_compress_ptr cinfo));
  156574. #endif
  156575. /*
  156576. * Initialize for a Huffman-compressed scan.
  156577. * If gather_statistics is TRUE, we do not output anything during the scan,
  156578. * just count the Huffman symbols used and generate Huffman code tables.
  156579. */
  156580. METHODDEF(void)
  156581. start_pass_huff (j_compress_ptr cinfo, boolean gather_statistics)
  156582. {
  156583. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  156584. int ci, dctbl, actbl;
  156585. jpeg_component_info * compptr;
  156586. if (gather_statistics) {
  156587. #ifdef ENTROPY_OPT_SUPPORTED
  156588. entropy->pub.encode_mcu = encode_mcu_gather;
  156589. entropy->pub.finish_pass = finish_pass_gather;
  156590. #else
  156591. ERREXIT(cinfo, JERR_NOT_COMPILED);
  156592. #endif
  156593. } else {
  156594. entropy->pub.encode_mcu = encode_mcu_huff;
  156595. entropy->pub.finish_pass = finish_pass_huff;
  156596. }
  156597. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  156598. compptr = cinfo->cur_comp_info[ci];
  156599. dctbl = compptr->dc_tbl_no;
  156600. actbl = compptr->ac_tbl_no;
  156601. if (gather_statistics) {
  156602. #ifdef ENTROPY_OPT_SUPPORTED
  156603. /* Check for invalid table indexes */
  156604. /* (make_c_derived_tbl does this in the other path) */
  156605. if (dctbl < 0 || dctbl >= NUM_HUFF_TBLS)
  156606. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, dctbl);
  156607. if (actbl < 0 || actbl >= NUM_HUFF_TBLS)
  156608. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, actbl);
  156609. /* Allocate and zero the statistics tables */
  156610. /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
  156611. if (entropy->dc_count_ptrs[dctbl] == NULL)
  156612. entropy->dc_count_ptrs[dctbl] = (long *)
  156613. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  156614. 257 * SIZEOF(long));
  156615. MEMZERO(entropy->dc_count_ptrs[dctbl], 257 * SIZEOF(long));
  156616. if (entropy->ac_count_ptrs[actbl] == NULL)
  156617. entropy->ac_count_ptrs[actbl] = (long *)
  156618. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  156619. 257 * SIZEOF(long));
  156620. MEMZERO(entropy->ac_count_ptrs[actbl], 257 * SIZEOF(long));
  156621. #endif
  156622. } else {
  156623. /* Compute derived values for Huffman tables */
  156624. /* We may do this more than once for a table, but it's not expensive */
  156625. jpeg_make_c_derived_tbl(cinfo, TRUE, dctbl,
  156626. & entropy->dc_derived_tbls[dctbl]);
  156627. jpeg_make_c_derived_tbl(cinfo, FALSE, actbl,
  156628. & entropy->ac_derived_tbls[actbl]);
  156629. }
  156630. /* Initialize DC predictions to 0 */
  156631. entropy->saved.last_dc_val[ci] = 0;
  156632. }
  156633. /* Initialize bit buffer to empty */
  156634. entropy->saved.put_buffer = 0;
  156635. entropy->saved.put_bits = 0;
  156636. /* Initialize restart stuff */
  156637. entropy->restarts_to_go = cinfo->restart_interval;
  156638. entropy->next_restart_num = 0;
  156639. }
  156640. /*
  156641. * Compute the derived values for a Huffman table.
  156642. * This routine also performs some validation checks on the table.
  156643. *
  156644. * Note this is also used by jcphuff.c.
  156645. */
  156646. GLOBAL(void)
  156647. jpeg_make_c_derived_tbl (j_compress_ptr cinfo, boolean isDC, int tblno,
  156648. c_derived_tbl ** pdtbl)
  156649. {
  156650. JHUFF_TBL *htbl;
  156651. c_derived_tbl *dtbl;
  156652. int p, i, l, lastp, si, maxsymbol;
  156653. char huffsize[257];
  156654. unsigned int huffcode[257];
  156655. unsigned int code;
  156656. /* Note that huffsize[] and huffcode[] are filled in code-length order,
  156657. * paralleling the order of the symbols themselves in htbl->huffval[].
  156658. */
  156659. /* Find the input Huffman table */
  156660. if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
  156661. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  156662. htbl =
  156663. isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];
  156664. if (htbl == NULL)
  156665. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  156666. /* Allocate a workspace if we haven't already done so. */
  156667. if (*pdtbl == NULL)
  156668. *pdtbl = (c_derived_tbl *)
  156669. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  156670. SIZEOF(c_derived_tbl));
  156671. dtbl = *pdtbl;
  156672. /* Figure C.1: make table of Huffman code length for each symbol */
  156673. p = 0;
  156674. for (l = 1; l <= 16; l++) {
  156675. i = (int) htbl->bits[l];
  156676. if (i < 0 || p + i > 256) /* protect against table overrun */
  156677. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  156678. while (i--)
  156679. huffsize[p++] = (char) l;
  156680. }
  156681. huffsize[p] = 0;
  156682. lastp = p;
  156683. /* Figure C.2: generate the codes themselves */
  156684. /* We also validate that the counts represent a legal Huffman code tree. */
  156685. code = 0;
  156686. si = huffsize[0];
  156687. p = 0;
  156688. while (huffsize[p]) {
  156689. while (((int) huffsize[p]) == si) {
  156690. huffcode[p++] = code;
  156691. code++;
  156692. }
  156693. /* code is now 1 more than the last code used for codelength si; but
  156694. * it must still fit in si bits, since no code is allowed to be all ones.
  156695. */
  156696. if (((INT32) code) >= (((INT32) 1) << si))
  156697. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  156698. code <<= 1;
  156699. si++;
  156700. }
  156701. /* Figure C.3: generate encoding tables */
  156702. /* These are code and size indexed by symbol value */
  156703. /* Set all codeless symbols to have code length 0;
  156704. * this lets us detect duplicate VAL entries here, and later
  156705. * allows emit_bits to detect any attempt to emit such symbols.
  156706. */
  156707. MEMZERO(dtbl->ehufsi, SIZEOF(dtbl->ehufsi));
  156708. /* This is also a convenient place to check for out-of-range
  156709. * and duplicated VAL entries. We allow 0..255 for AC symbols
  156710. * but only 0..15 for DC. (We could constrain them further
  156711. * based on data depth and mode, but this seems enough.)
  156712. */
  156713. maxsymbol = isDC ? 15 : 255;
  156714. for (p = 0; p < lastp; p++) {
  156715. i = htbl->huffval[p];
  156716. if (i < 0 || i > maxsymbol || dtbl->ehufsi[i])
  156717. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  156718. dtbl->ehufco[i] = huffcode[p];
  156719. dtbl->ehufsi[i] = huffsize[p];
  156720. }
  156721. }
  156722. /* Outputting bytes to the file */
  156723. /* Emit a byte, taking 'action' if must suspend. */
  156724. #define emit_byte(state,val,action) \
  156725. { *(state)->next_output_byte++ = (JOCTET) (val); \
  156726. if (--(state)->free_in_buffer == 0) \
  156727. if (! dump_buffer(state)) \
  156728. { action; } }
  156729. LOCAL(boolean)
  156730. dump_buffer (working_state * state)
  156731. /* Empty the output buffer; return TRUE if successful, FALSE if must suspend */
  156732. {
  156733. struct jpeg_destination_mgr * dest = state->cinfo->dest;
  156734. if (! (*dest->empty_output_buffer) (state->cinfo))
  156735. return FALSE;
  156736. /* After a successful buffer dump, must reset buffer pointers */
  156737. state->next_output_byte = dest->next_output_byte;
  156738. state->free_in_buffer = dest->free_in_buffer;
  156739. return TRUE;
  156740. }
  156741. /* Outputting bits to the file */
  156742. /* Only the right 24 bits of put_buffer are used; the valid bits are
  156743. * left-justified in this part. At most 16 bits can be passed to emit_bits
  156744. * in one call, and we never retain more than 7 bits in put_buffer
  156745. * between calls, so 24 bits are sufficient.
  156746. */
  156747. INLINE
  156748. LOCAL(boolean)
  156749. emit_bits (working_state * state, unsigned int code, int size)
  156750. /* Emit some bits; return TRUE if successful, FALSE if must suspend */
  156751. {
  156752. /* This routine is heavily used, so it's worth coding tightly. */
  156753. register INT32 put_buffer = (INT32) code;
  156754. register int put_bits = state->cur.put_bits;
  156755. /* if size is 0, caller used an invalid Huffman table entry */
  156756. if (size == 0)
  156757. ERREXIT(state->cinfo, JERR_HUFF_MISSING_CODE);
  156758. put_buffer &= (((INT32) 1)<<size) - 1; /* mask off any extra bits in code */
  156759. put_bits += size; /* new number of bits in buffer */
  156760. put_buffer <<= 24 - put_bits; /* align incoming bits */
  156761. put_buffer |= state->cur.put_buffer; /* and merge with old buffer contents */
  156762. while (put_bits >= 8) {
  156763. int c = (int) ((put_buffer >> 16) & 0xFF);
  156764. emit_byte(state, c, return FALSE);
  156765. if (c == 0xFF) { /* need to stuff a zero byte? */
  156766. emit_byte(state, 0, return FALSE);
  156767. }
  156768. put_buffer <<= 8;
  156769. put_bits -= 8;
  156770. }
  156771. state->cur.put_buffer = put_buffer; /* update state variables */
  156772. state->cur.put_bits = put_bits;
  156773. return TRUE;
  156774. }
  156775. LOCAL(boolean)
  156776. flush_bits (working_state * state)
  156777. {
  156778. if (! emit_bits(state, 0x7F, 7)) /* fill any partial byte with ones */
  156779. return FALSE;
  156780. state->cur.put_buffer = 0; /* and reset bit-buffer to empty */
  156781. state->cur.put_bits = 0;
  156782. return TRUE;
  156783. }
  156784. /* Encode a single block's worth of coefficients */
  156785. LOCAL(boolean)
  156786. encode_one_block (working_state * state, JCOEFPTR block, int last_dc_val,
  156787. c_derived_tbl *dctbl, c_derived_tbl *actbl)
  156788. {
  156789. register int temp, temp2;
  156790. register int nbits;
  156791. register int k, r, i;
  156792. /* Encode the DC coefficient difference per section F.1.2.1 */
  156793. temp = temp2 = block[0] - last_dc_val;
  156794. if (temp < 0) {
  156795. temp = -temp; /* temp is abs value of input */
  156796. /* For a negative input, want temp2 = bitwise complement of abs(input) */
  156797. /* This code assumes we are on a two's complement machine */
  156798. temp2--;
  156799. }
  156800. /* Find the number of bits needed for the magnitude of the coefficient */
  156801. nbits = 0;
  156802. while (temp) {
  156803. nbits++;
  156804. temp >>= 1;
  156805. }
  156806. /* Check for out-of-range coefficient values.
  156807. * Since we're encoding a difference, the range limit is twice as much.
  156808. */
  156809. if (nbits > MAX_COEF_BITS+1)
  156810. ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);
  156811. /* Emit the Huffman-coded symbol for the number of bits */
  156812. if (! emit_bits(state, dctbl->ehufco[nbits], dctbl->ehufsi[nbits]))
  156813. return FALSE;
  156814. /* Emit that number of bits of the value, if positive, */
  156815. /* or the complement of its magnitude, if negative. */
  156816. if (nbits) /* emit_bits rejects calls with size 0 */
  156817. if (! emit_bits(state, (unsigned int) temp2, nbits))
  156818. return FALSE;
  156819. /* Encode the AC coefficients per section F.1.2.2 */
  156820. r = 0; /* r = run length of zeros */
  156821. for (k = 1; k < DCTSIZE2; k++) {
  156822. if ((temp = block[jpeg_natural_order[k]]) == 0) {
  156823. r++;
  156824. } else {
  156825. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  156826. while (r > 15) {
  156827. if (! emit_bits(state, actbl->ehufco[0xF0], actbl->ehufsi[0xF0]))
  156828. return FALSE;
  156829. r -= 16;
  156830. }
  156831. temp2 = temp;
  156832. if (temp < 0) {
  156833. temp = -temp; /* temp is abs value of input */
  156834. /* This code assumes we are on a two's complement machine */
  156835. temp2--;
  156836. }
  156837. /* Find the number of bits needed for the magnitude of the coefficient */
  156838. nbits = 1; /* there must be at least one 1 bit */
  156839. while ((temp >>= 1))
  156840. nbits++;
  156841. /* Check for out-of-range coefficient values */
  156842. if (nbits > MAX_COEF_BITS)
  156843. ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);
  156844. /* Emit Huffman symbol for run length / number of bits */
  156845. i = (r << 4) + nbits;
  156846. if (! emit_bits(state, actbl->ehufco[i], actbl->ehufsi[i]))
  156847. return FALSE;
  156848. /* Emit that number of bits of the value, if positive, */
  156849. /* or the complement of its magnitude, if negative. */
  156850. if (! emit_bits(state, (unsigned int) temp2, nbits))
  156851. return FALSE;
  156852. r = 0;
  156853. }
  156854. }
  156855. /* If the last coef(s) were zero, emit an end-of-block code */
  156856. if (r > 0)
  156857. if (! emit_bits(state, actbl->ehufco[0], actbl->ehufsi[0]))
  156858. return FALSE;
  156859. return TRUE;
  156860. }
  156861. /*
  156862. * Emit a restart marker & resynchronize predictions.
  156863. */
  156864. LOCAL(boolean)
  156865. emit_restart (working_state * state, int restart_num)
  156866. {
  156867. int ci;
  156868. if (! flush_bits(state))
  156869. return FALSE;
  156870. emit_byte(state, 0xFF, return FALSE);
  156871. emit_byte(state, JPEG_RST0 + restart_num, return FALSE);
  156872. /* Re-initialize DC predictions to 0 */
  156873. for (ci = 0; ci < state->cinfo->comps_in_scan; ci++)
  156874. state->cur.last_dc_val[ci] = 0;
  156875. /* The restart counter is not updated until we successfully write the MCU. */
  156876. return TRUE;
  156877. }
  156878. /*
  156879. * Encode and output one MCU's worth of Huffman-compressed coefficients.
  156880. */
  156881. METHODDEF(boolean)
  156882. encode_mcu_huff (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  156883. {
  156884. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  156885. working_state state;
  156886. int blkn, ci;
  156887. jpeg_component_info * compptr;
  156888. /* Load up working state */
  156889. state.next_output_byte = cinfo->dest->next_output_byte;
  156890. state.free_in_buffer = cinfo->dest->free_in_buffer;
  156891. ASSIGN_STATE(state.cur, entropy->saved);
  156892. state.cinfo = cinfo;
  156893. /* Emit restart marker if needed */
  156894. if (cinfo->restart_interval) {
  156895. if (entropy->restarts_to_go == 0)
  156896. if (! emit_restart(&state, entropy->next_restart_num))
  156897. return FALSE;
  156898. }
  156899. /* Encode the MCU data blocks */
  156900. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  156901. ci = cinfo->MCU_membership[blkn];
  156902. compptr = cinfo->cur_comp_info[ci];
  156903. if (! encode_one_block(&state,
  156904. MCU_data[blkn][0], state.cur.last_dc_val[ci],
  156905. entropy->dc_derived_tbls[compptr->dc_tbl_no],
  156906. entropy->ac_derived_tbls[compptr->ac_tbl_no]))
  156907. return FALSE;
  156908. /* Update last_dc_val */
  156909. state.cur.last_dc_val[ci] = MCU_data[blkn][0][0];
  156910. }
  156911. /* Completed MCU, so update state */
  156912. cinfo->dest->next_output_byte = state.next_output_byte;
  156913. cinfo->dest->free_in_buffer = state.free_in_buffer;
  156914. ASSIGN_STATE(entropy->saved, state.cur);
  156915. /* Update restart-interval state too */
  156916. if (cinfo->restart_interval) {
  156917. if (entropy->restarts_to_go == 0) {
  156918. entropy->restarts_to_go = cinfo->restart_interval;
  156919. entropy->next_restart_num++;
  156920. entropy->next_restart_num &= 7;
  156921. }
  156922. entropy->restarts_to_go--;
  156923. }
  156924. return TRUE;
  156925. }
  156926. /*
  156927. * Finish up at the end of a Huffman-compressed scan.
  156928. */
  156929. METHODDEF(void)
  156930. finish_pass_huff (j_compress_ptr cinfo)
  156931. {
  156932. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  156933. working_state state;
  156934. /* Load up working state ... flush_bits needs it */
  156935. state.next_output_byte = cinfo->dest->next_output_byte;
  156936. state.free_in_buffer = cinfo->dest->free_in_buffer;
  156937. ASSIGN_STATE(state.cur, entropy->saved);
  156938. state.cinfo = cinfo;
  156939. /* Flush out the last data */
  156940. if (! flush_bits(&state))
  156941. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  156942. /* Update state */
  156943. cinfo->dest->next_output_byte = state.next_output_byte;
  156944. cinfo->dest->free_in_buffer = state.free_in_buffer;
  156945. ASSIGN_STATE(entropy->saved, state.cur);
  156946. }
  156947. /*
  156948. * Huffman coding optimization.
  156949. *
  156950. * We first scan the supplied data and count the number of uses of each symbol
  156951. * that is to be Huffman-coded. (This process MUST agree with the code above.)
  156952. * Then we build a Huffman coding tree for the observed counts.
  156953. * Symbols which are not needed at all for the particular image are not
  156954. * assigned any code, which saves space in the DHT marker as well as in
  156955. * the compressed data.
  156956. */
  156957. #ifdef ENTROPY_OPT_SUPPORTED
  156958. /* Process a single block's worth of coefficients */
  156959. LOCAL(void)
  156960. htest_one_block (j_compress_ptr cinfo, JCOEFPTR block, int last_dc_val,
  156961. long dc_counts[], long ac_counts[])
  156962. {
  156963. register int temp;
  156964. register int nbits;
  156965. register int k, r;
  156966. /* Encode the DC coefficient difference per section F.1.2.1 */
  156967. temp = block[0] - last_dc_val;
  156968. if (temp < 0)
  156969. temp = -temp;
  156970. /* Find the number of bits needed for the magnitude of the coefficient */
  156971. nbits = 0;
  156972. while (temp) {
  156973. nbits++;
  156974. temp >>= 1;
  156975. }
  156976. /* Check for out-of-range coefficient values.
  156977. * Since we're encoding a difference, the range limit is twice as much.
  156978. */
  156979. if (nbits > MAX_COEF_BITS+1)
  156980. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  156981. /* Count the Huffman symbol for the number of bits */
  156982. dc_counts[nbits]++;
  156983. /* Encode the AC coefficients per section F.1.2.2 */
  156984. r = 0; /* r = run length of zeros */
  156985. for (k = 1; k < DCTSIZE2; k++) {
  156986. if ((temp = block[jpeg_natural_order[k]]) == 0) {
  156987. r++;
  156988. } else {
  156989. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  156990. while (r > 15) {
  156991. ac_counts[0xF0]++;
  156992. r -= 16;
  156993. }
  156994. /* Find the number of bits needed for the magnitude of the coefficient */
  156995. if (temp < 0)
  156996. temp = -temp;
  156997. /* Find the number of bits needed for the magnitude of the coefficient */
  156998. nbits = 1; /* there must be at least one 1 bit */
  156999. while ((temp >>= 1))
  157000. nbits++;
  157001. /* Check for out-of-range coefficient values */
  157002. if (nbits > MAX_COEF_BITS)
  157003. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  157004. /* Count Huffman symbol for run length / number of bits */
  157005. ac_counts[(r << 4) + nbits]++;
  157006. r = 0;
  157007. }
  157008. }
  157009. /* If the last coef(s) were zero, emit an end-of-block code */
  157010. if (r > 0)
  157011. ac_counts[0]++;
  157012. }
  157013. /*
  157014. * Trial-encode one MCU's worth of Huffman-compressed coefficients.
  157015. * No data is actually output, so no suspension return is possible.
  157016. */
  157017. METHODDEF(boolean)
  157018. encode_mcu_gather (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  157019. {
  157020. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  157021. int blkn, ci;
  157022. jpeg_component_info * compptr;
  157023. /* Take care of restart intervals if needed */
  157024. if (cinfo->restart_interval) {
  157025. if (entropy->restarts_to_go == 0) {
  157026. /* Re-initialize DC predictions to 0 */
  157027. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  157028. entropy->saved.last_dc_val[ci] = 0;
  157029. /* Update restart state */
  157030. entropy->restarts_to_go = cinfo->restart_interval;
  157031. }
  157032. entropy->restarts_to_go--;
  157033. }
  157034. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  157035. ci = cinfo->MCU_membership[blkn];
  157036. compptr = cinfo->cur_comp_info[ci];
  157037. htest_one_block(cinfo, MCU_data[blkn][0], entropy->saved.last_dc_val[ci],
  157038. entropy->dc_count_ptrs[compptr->dc_tbl_no],
  157039. entropy->ac_count_ptrs[compptr->ac_tbl_no]);
  157040. entropy->saved.last_dc_val[ci] = MCU_data[blkn][0][0];
  157041. }
  157042. return TRUE;
  157043. }
  157044. /*
  157045. * Generate the best Huffman code table for the given counts, fill htbl.
  157046. * Note this is also used by jcphuff.c.
  157047. *
  157048. * The JPEG standard requires that no symbol be assigned a codeword of all
  157049. * one bits (so that padding bits added at the end of a compressed segment
  157050. * can't look like a valid code). Because of the canonical ordering of
  157051. * codewords, this just means that there must be an unused slot in the
  157052. * longest codeword length category. Section K.2 of the JPEG spec suggests
  157053. * reserving such a slot by pretending that symbol 256 is a valid symbol
  157054. * with count 1. In theory that's not optimal; giving it count zero but
  157055. * including it in the symbol set anyway should give a better Huffman code.
  157056. * But the theoretically better code actually seems to come out worse in
  157057. * practice, because it produces more all-ones bytes (which incur stuffed
  157058. * zero bytes in the final file). In any case the difference is tiny.
  157059. *
  157060. * The JPEG standard requires Huffman codes to be no more than 16 bits long.
  157061. * If some symbols have a very small but nonzero probability, the Huffman tree
  157062. * must be adjusted to meet the code length restriction. We currently use
  157063. * the adjustment method suggested in JPEG section K.2. This method is *not*
  157064. * optimal; it may not choose the best possible limited-length code. But
  157065. * typically only very-low-frequency symbols will be given less-than-optimal
  157066. * lengths, so the code is almost optimal. Experimental comparisons against
  157067. * an optimal limited-length-code algorithm indicate that the difference is
  157068. * microscopic --- usually less than a hundredth of a percent of total size.
  157069. * So the extra complexity of an optimal algorithm doesn't seem worthwhile.
  157070. */
  157071. GLOBAL(void)
  157072. jpeg_gen_optimal_table (j_compress_ptr cinfo, JHUFF_TBL * htbl, long freq[])
  157073. {
  157074. #define MAX_CLEN 32 /* assumed maximum initial code length */
  157075. UINT8 bits[MAX_CLEN+1]; /* bits[k] = # of symbols with code length k */
  157076. int codesize[257]; /* codesize[k] = code length of symbol k */
  157077. int others[257]; /* next symbol in current branch of tree */
  157078. int c1, c2;
  157079. int p, i, j;
  157080. long v;
  157081. /* This algorithm is explained in section K.2 of the JPEG standard */
  157082. MEMZERO(bits, SIZEOF(bits));
  157083. MEMZERO(codesize, SIZEOF(codesize));
  157084. for (i = 0; i < 257; i++)
  157085. others[i] = -1; /* init links to empty */
  157086. freq[256] = 1; /* make sure 256 has a nonzero count */
  157087. /* Including the pseudo-symbol 256 in the Huffman procedure guarantees
  157088. * that no real symbol is given code-value of all ones, because 256
  157089. * will be placed last in the largest codeword category.
  157090. */
  157091. /* Huffman's basic algorithm to assign optimal code lengths to symbols */
  157092. for (;;) {
  157093. /* Find the smallest nonzero frequency, set c1 = its symbol */
  157094. /* In case of ties, take the larger symbol number */
  157095. c1 = -1;
  157096. v = 1000000000L;
  157097. for (i = 0; i <= 256; i++) {
  157098. if (freq[i] && freq[i] <= v) {
  157099. v = freq[i];
  157100. c1 = i;
  157101. }
  157102. }
  157103. /* Find the next smallest nonzero frequency, set c2 = its symbol */
  157104. /* In case of ties, take the larger symbol number */
  157105. c2 = -1;
  157106. v = 1000000000L;
  157107. for (i = 0; i <= 256; i++) {
  157108. if (freq[i] && freq[i] <= v && i != c1) {
  157109. v = freq[i];
  157110. c2 = i;
  157111. }
  157112. }
  157113. /* Done if we've merged everything into one frequency */
  157114. if (c2 < 0)
  157115. break;
  157116. /* Else merge the two counts/trees */
  157117. freq[c1] += freq[c2];
  157118. freq[c2] = 0;
  157119. /* Increment the codesize of everything in c1's tree branch */
  157120. codesize[c1]++;
  157121. while (others[c1] >= 0) {
  157122. c1 = others[c1];
  157123. codesize[c1]++;
  157124. }
  157125. others[c1] = c2; /* chain c2 onto c1's tree branch */
  157126. /* Increment the codesize of everything in c2's tree branch */
  157127. codesize[c2]++;
  157128. while (others[c2] >= 0) {
  157129. c2 = others[c2];
  157130. codesize[c2]++;
  157131. }
  157132. }
  157133. /* Now count the number of symbols of each code length */
  157134. for (i = 0; i <= 256; i++) {
  157135. if (codesize[i]) {
  157136. /* The JPEG standard seems to think that this can't happen, */
  157137. /* but I'm paranoid... */
  157138. if (codesize[i] > MAX_CLEN)
  157139. ERREXIT(cinfo, JERR_HUFF_CLEN_OVERFLOW);
  157140. bits[codesize[i]]++;
  157141. }
  157142. }
  157143. /* JPEG doesn't allow symbols with code lengths over 16 bits, so if the pure
  157144. * Huffman procedure assigned any such lengths, we must adjust the coding.
  157145. * Here is what the JPEG spec says about how this next bit works:
  157146. * Since symbols are paired for the longest Huffman code, the symbols are
  157147. * removed from this length category two at a time. The prefix for the pair
  157148. * (which is one bit shorter) is allocated to one of the pair; then,
  157149. * skipping the BITS entry for that prefix length, a code word from the next
  157150. * shortest nonzero BITS entry is converted into a prefix for two code words
  157151. * one bit longer.
  157152. */
  157153. for (i = MAX_CLEN; i > 16; i--) {
  157154. while (bits[i] > 0) {
  157155. j = i - 2; /* find length of new prefix to be used */
  157156. while (bits[j] == 0)
  157157. j--;
  157158. bits[i] -= 2; /* remove two symbols */
  157159. bits[i-1]++; /* one goes in this length */
  157160. bits[j+1] += 2; /* two new symbols in this length */
  157161. bits[j]--; /* symbol of this length is now a prefix */
  157162. }
  157163. }
  157164. /* Remove the count for the pseudo-symbol 256 from the largest codelength */
  157165. while (bits[i] == 0) /* find largest codelength still in use */
  157166. i--;
  157167. bits[i]--;
  157168. /* Return final symbol counts (only for lengths 0..16) */
  157169. MEMCOPY(htbl->bits, bits, SIZEOF(htbl->bits));
  157170. /* Return a list of the symbols sorted by code length */
  157171. /* It's not real clear to me why we don't need to consider the codelength
  157172. * changes made above, but the JPEG spec seems to think this works.
  157173. */
  157174. p = 0;
  157175. for (i = 1; i <= MAX_CLEN; i++) {
  157176. for (j = 0; j <= 255; j++) {
  157177. if (codesize[j] == i) {
  157178. htbl->huffval[p] = (UINT8) j;
  157179. p++;
  157180. }
  157181. }
  157182. }
  157183. /* Set sent_table FALSE so updated table will be written to JPEG file. */
  157184. htbl->sent_table = FALSE;
  157185. }
  157186. /*
  157187. * Finish up a statistics-gathering pass and create the new Huffman tables.
  157188. */
  157189. METHODDEF(void)
  157190. finish_pass_gather (j_compress_ptr cinfo)
  157191. {
  157192. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  157193. int ci, dctbl, actbl;
  157194. jpeg_component_info * compptr;
  157195. JHUFF_TBL **htblptr;
  157196. boolean did_dc[NUM_HUFF_TBLS];
  157197. boolean did_ac[NUM_HUFF_TBLS];
  157198. /* It's important not to apply jpeg_gen_optimal_table more than once
  157199. * per table, because it clobbers the input frequency counts!
  157200. */
  157201. MEMZERO(did_dc, SIZEOF(did_dc));
  157202. MEMZERO(did_ac, SIZEOF(did_ac));
  157203. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  157204. compptr = cinfo->cur_comp_info[ci];
  157205. dctbl = compptr->dc_tbl_no;
  157206. actbl = compptr->ac_tbl_no;
  157207. if (! did_dc[dctbl]) {
  157208. htblptr = & cinfo->dc_huff_tbl_ptrs[dctbl];
  157209. if (*htblptr == NULL)
  157210. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  157211. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->dc_count_ptrs[dctbl]);
  157212. did_dc[dctbl] = TRUE;
  157213. }
  157214. if (! did_ac[actbl]) {
  157215. htblptr = & cinfo->ac_huff_tbl_ptrs[actbl];
  157216. if (*htblptr == NULL)
  157217. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  157218. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->ac_count_ptrs[actbl]);
  157219. did_ac[actbl] = TRUE;
  157220. }
  157221. }
  157222. }
  157223. #endif /* ENTROPY_OPT_SUPPORTED */
  157224. /*
  157225. * Module initialization routine for Huffman entropy encoding.
  157226. */
  157227. GLOBAL(void)
  157228. jinit_huff_encoder (j_compress_ptr cinfo)
  157229. {
  157230. huff_entropy_ptr entropy;
  157231. int i;
  157232. entropy = (huff_entropy_ptr)
  157233. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  157234. SIZEOF(huff_entropy_encoder));
  157235. cinfo->entropy = (struct jpeg_entropy_encoder *) entropy;
  157236. entropy->pub.start_pass = start_pass_huff;
  157237. /* Mark tables unallocated */
  157238. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  157239. entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
  157240. #ifdef ENTROPY_OPT_SUPPORTED
  157241. entropy->dc_count_ptrs[i] = entropy->ac_count_ptrs[i] = NULL;
  157242. #endif
  157243. }
  157244. }
  157245. /********* End of inlined file: jchuff.c *********/
  157246. #undef emit_byte
  157247. /********* Start of inlined file: jcinit.c *********/
  157248. #define JPEG_INTERNALS
  157249. /*
  157250. * Master selection of compression modules.
  157251. * This is done once at the start of processing an image. We determine
  157252. * which modules will be used and give them appropriate initialization calls.
  157253. */
  157254. GLOBAL(void)
  157255. jinit_compress_master (j_compress_ptr cinfo)
  157256. {
  157257. /* Initialize master control (includes parameter checking/processing) */
  157258. jinit_c_master_control(cinfo, FALSE /* full compression */);
  157259. /* Preprocessing */
  157260. if (! cinfo->raw_data_in) {
  157261. jinit_color_converter(cinfo);
  157262. jinit_downsampler(cinfo);
  157263. jinit_c_prep_controller(cinfo, FALSE /* never need full buffer here */);
  157264. }
  157265. /* Forward DCT */
  157266. jinit_forward_dct(cinfo);
  157267. /* Entropy encoding: either Huffman or arithmetic coding. */
  157268. if (cinfo->arith_code) {
  157269. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  157270. } else {
  157271. if (cinfo->progressive_mode) {
  157272. #ifdef C_PROGRESSIVE_SUPPORTED
  157273. jinit_phuff_encoder(cinfo);
  157274. #else
  157275. ERREXIT(cinfo, JERR_NOT_COMPILED);
  157276. #endif
  157277. } else
  157278. jinit_huff_encoder(cinfo);
  157279. }
  157280. /* Need a full-image coefficient buffer in any multi-pass mode. */
  157281. jinit_c_coef_controller(cinfo,
  157282. (boolean) (cinfo->num_scans > 1 || cinfo->optimize_coding));
  157283. jinit_c_main_controller(cinfo, FALSE /* never need full buffer here */);
  157284. jinit_marker_writer(cinfo);
  157285. /* We can now tell the memory manager to allocate virtual arrays. */
  157286. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  157287. /* Write the datastream header (SOI) immediately.
  157288. * Frame and scan headers are postponed till later.
  157289. * This lets application insert special markers after the SOI.
  157290. */
  157291. (*cinfo->marker->write_file_header) (cinfo);
  157292. }
  157293. /********* End of inlined file: jcinit.c *********/
  157294. /********* Start of inlined file: jcmainct.c *********/
  157295. #define JPEG_INTERNALS
  157296. /* Note: currently, there is no operating mode in which a full-image buffer
  157297. * is needed at this step. If there were, that mode could not be used with
  157298. * "raw data" input, since this module is bypassed in that case. However,
  157299. * we've left the code here for possible use in special applications.
  157300. */
  157301. #undef FULL_MAIN_BUFFER_SUPPORTED
  157302. /* Private buffer controller object */
  157303. typedef struct {
  157304. struct jpeg_c_main_controller pub; /* public fields */
  157305. JDIMENSION cur_iMCU_row; /* number of current iMCU row */
  157306. JDIMENSION rowgroup_ctr; /* counts row groups received in iMCU row */
  157307. boolean suspended; /* remember if we suspended output */
  157308. J_BUF_MODE pass_mode; /* current operating mode */
  157309. /* If using just a strip buffer, this points to the entire set of buffers
  157310. * (we allocate one for each component). In the full-image case, this
  157311. * points to the currently accessible strips of the virtual arrays.
  157312. */
  157313. JSAMPARRAY buffer[MAX_COMPONENTS];
  157314. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  157315. /* If using full-image storage, this array holds pointers to virtual-array
  157316. * control blocks for each component. Unused if not full-image storage.
  157317. */
  157318. jvirt_sarray_ptr whole_image[MAX_COMPONENTS];
  157319. #endif
  157320. } my_main_controller;
  157321. typedef my_main_controller * my_main_ptr;
  157322. /* Forward declarations */
  157323. METHODDEF(void) process_data_simple_main
  157324. JPP((j_compress_ptr cinfo, JSAMPARRAY input_buf,
  157325. JDIMENSION *in_row_ctr, JDIMENSION in_rows_avail));
  157326. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  157327. METHODDEF(void) process_data_buffer_main
  157328. JPP((j_compress_ptr cinfo, JSAMPARRAY input_buf,
  157329. JDIMENSION *in_row_ctr, JDIMENSION in_rows_avail));
  157330. #endif
  157331. /*
  157332. * Initialize for a processing pass.
  157333. */
  157334. METHODDEF(void)
  157335. start_pass_main (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  157336. {
  157337. my_main_ptr main_ = (my_main_ptr) cinfo->main;
  157338. /* Do nothing in raw-data mode. */
  157339. if (cinfo->raw_data_in)
  157340. return;
  157341. main_->cur_iMCU_row = 0; /* initialize counters */
  157342. main_->rowgroup_ctr = 0;
  157343. main_->suspended = FALSE;
  157344. main_->pass_mode = pass_mode; /* save mode for use by process_data */
  157345. switch (pass_mode) {
  157346. case JBUF_PASS_THRU:
  157347. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  157348. if (main_->whole_image[0] != NULL)
  157349. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  157350. #endif
  157351. main_->pub.process_data = process_data_simple_main;
  157352. break;
  157353. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  157354. case JBUF_SAVE_SOURCE:
  157355. case JBUF_CRANK_DEST:
  157356. case JBUF_SAVE_AND_PASS:
  157357. if (main_->whole_image[0] == NULL)
  157358. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  157359. main_->pub.process_data = process_data_buffer_main;
  157360. break;
  157361. #endif
  157362. default:
  157363. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  157364. break;
  157365. }
  157366. }
  157367. /*
  157368. * Process some data.
  157369. * This routine handles the simple pass-through mode,
  157370. * where we have only a strip buffer.
  157371. */
  157372. METHODDEF(void)
  157373. process_data_simple_main (j_compress_ptr cinfo,
  157374. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  157375. JDIMENSION in_rows_avail)
  157376. {
  157377. my_main_ptr main_ = (my_main_ptr) cinfo->main;
  157378. while (main_->cur_iMCU_row < cinfo->total_iMCU_rows) {
  157379. /* Read input data if we haven't filled the main buffer yet */
  157380. if (main_->rowgroup_ctr < DCTSIZE)
  157381. (*cinfo->prep->pre_process_data) (cinfo,
  157382. input_buf, in_row_ctr, in_rows_avail,
  157383. main_->buffer, &main_->rowgroup_ctr,
  157384. (JDIMENSION) DCTSIZE);
  157385. /* If we don't have a full iMCU row buffered, return to application for
  157386. * more data. Note that preprocessor will always pad to fill the iMCU row
  157387. * at the bottom of the image.
  157388. */
  157389. if (main_->rowgroup_ctr != DCTSIZE)
  157390. return;
  157391. /* Send the completed row to the compressor */
  157392. if (! (*cinfo->coef->compress_data) (cinfo, main_->buffer)) {
  157393. /* If compressor did not consume the whole row, then we must need to
  157394. * suspend processing and return to the application. In this situation
  157395. * we pretend we didn't yet consume the last input row; otherwise, if
  157396. * it happened to be the last row of the image, the application would
  157397. * think we were done.
  157398. */
  157399. if (! main_->suspended) {
  157400. (*in_row_ctr)--;
  157401. main_->suspended = TRUE;
  157402. }
  157403. return;
  157404. }
  157405. /* We did finish the row. Undo our little suspension hack if a previous
  157406. * call suspended; then mark the main buffer empty.
  157407. */
  157408. if (main_->suspended) {
  157409. (*in_row_ctr)++;
  157410. main_->suspended = FALSE;
  157411. }
  157412. main_->rowgroup_ctr = 0;
  157413. main_->cur_iMCU_row++;
  157414. }
  157415. }
  157416. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  157417. /*
  157418. * Process some data.
  157419. * This routine handles all of the modes that use a full-size buffer.
  157420. */
  157421. METHODDEF(void)
  157422. process_data_buffer_main (j_compress_ptr cinfo,
  157423. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  157424. JDIMENSION in_rows_avail)
  157425. {
  157426. my_main_ptr main = (my_main_ptr) cinfo->main;
  157427. int ci;
  157428. jpeg_component_info *compptr;
  157429. boolean writing = (main->pass_mode != JBUF_CRANK_DEST);
  157430. while (main->cur_iMCU_row < cinfo->total_iMCU_rows) {
  157431. /* Realign the virtual buffers if at the start of an iMCU row. */
  157432. if (main->rowgroup_ctr == 0) {
  157433. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  157434. ci++, compptr++) {
  157435. main->buffer[ci] = (*cinfo->mem->access_virt_sarray)
  157436. ((j_common_ptr) cinfo, main->whole_image[ci],
  157437. main->cur_iMCU_row * (compptr->v_samp_factor * DCTSIZE),
  157438. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE), writing);
  157439. }
  157440. /* In a read pass, pretend we just read some source data. */
  157441. if (! writing) {
  157442. *in_row_ctr += cinfo->max_v_samp_factor * DCTSIZE;
  157443. main->rowgroup_ctr = DCTSIZE;
  157444. }
  157445. }
  157446. /* If a write pass, read input data until the current iMCU row is full. */
  157447. /* Note: preprocessor will pad if necessary to fill the last iMCU row. */
  157448. if (writing) {
  157449. (*cinfo->prep->pre_process_data) (cinfo,
  157450. input_buf, in_row_ctr, in_rows_avail,
  157451. main->buffer, &main->rowgroup_ctr,
  157452. (JDIMENSION) DCTSIZE);
  157453. /* Return to application if we need more data to fill the iMCU row. */
  157454. if (main->rowgroup_ctr < DCTSIZE)
  157455. return;
  157456. }
  157457. /* Emit data, unless this is a sink-only pass. */
  157458. if (main->pass_mode != JBUF_SAVE_SOURCE) {
  157459. if (! (*cinfo->coef->compress_data) (cinfo, main->buffer)) {
  157460. /* If compressor did not consume the whole row, then we must need to
  157461. * suspend processing and return to the application. In this situation
  157462. * we pretend we didn't yet consume the last input row; otherwise, if
  157463. * it happened to be the last row of the image, the application would
  157464. * think we were done.
  157465. */
  157466. if (! main->suspended) {
  157467. (*in_row_ctr)--;
  157468. main->suspended = TRUE;
  157469. }
  157470. return;
  157471. }
  157472. /* We did finish the row. Undo our little suspension hack if a previous
  157473. * call suspended; then mark the main buffer empty.
  157474. */
  157475. if (main->suspended) {
  157476. (*in_row_ctr)++;
  157477. main->suspended = FALSE;
  157478. }
  157479. }
  157480. /* If get here, we are done with this iMCU row. Mark buffer empty. */
  157481. main->rowgroup_ctr = 0;
  157482. main->cur_iMCU_row++;
  157483. }
  157484. }
  157485. #endif /* FULL_MAIN_BUFFER_SUPPORTED */
  157486. /*
  157487. * Initialize main buffer controller.
  157488. */
  157489. GLOBAL(void)
  157490. jinit_c_main_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  157491. {
  157492. my_main_ptr main_;
  157493. int ci;
  157494. jpeg_component_info *compptr;
  157495. main_ = (my_main_ptr)
  157496. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  157497. SIZEOF(my_main_controller));
  157498. cinfo->main = (struct jpeg_c_main_controller *) main_;
  157499. main_->pub.start_pass = start_pass_main;
  157500. /* We don't need to create a buffer in raw-data mode. */
  157501. if (cinfo->raw_data_in)
  157502. return;
  157503. /* Create the buffer. It holds downsampled data, so each component
  157504. * may be of a different size.
  157505. */
  157506. if (need_full_buffer) {
  157507. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  157508. /* Allocate a full-image virtual array for each component */
  157509. /* Note we pad the bottom to a multiple of the iMCU height */
  157510. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  157511. ci++, compptr++) {
  157512. main->whole_image[ci] = (*cinfo->mem->request_virt_sarray)
  157513. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  157514. compptr->width_in_blocks * DCTSIZE,
  157515. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  157516. (long) compptr->v_samp_factor) * DCTSIZE,
  157517. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE));
  157518. }
  157519. #else
  157520. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  157521. #endif
  157522. } else {
  157523. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  157524. main_->whole_image[0] = NULL; /* flag for no virtual arrays */
  157525. #endif
  157526. /* Allocate a strip buffer for each component */
  157527. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  157528. ci++, compptr++) {
  157529. main_->buffer[ci] = (*cinfo->mem->alloc_sarray)
  157530. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  157531. compptr->width_in_blocks * DCTSIZE,
  157532. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE));
  157533. }
  157534. }
  157535. }
  157536. /********* End of inlined file: jcmainct.c *********/
  157537. /********* Start of inlined file: jcmarker.c *********/
  157538. #define JPEG_INTERNALS
  157539. /* Private state */
  157540. typedef struct {
  157541. struct jpeg_marker_writer pub; /* public fields */
  157542. unsigned int last_restart_interval; /* last DRI value emitted; 0 after SOI */
  157543. } my_marker_writer;
  157544. typedef my_marker_writer * my_marker_ptr;
  157545. /*
  157546. * Basic output routines.
  157547. *
  157548. * Note that we do not support suspension while writing a marker.
  157549. * Therefore, an application using suspension must ensure that there is
  157550. * enough buffer space for the initial markers (typ. 600-700 bytes) before
  157551. * calling jpeg_start_compress, and enough space to write the trailing EOI
  157552. * (a few bytes) before calling jpeg_finish_compress. Multipass compression
  157553. * modes are not supported at all with suspension, so those two are the only
  157554. * points where markers will be written.
  157555. */
  157556. LOCAL(void)
  157557. emit_byte (j_compress_ptr cinfo, int val)
  157558. /* Emit a byte */
  157559. {
  157560. struct jpeg_destination_mgr * dest = cinfo->dest;
  157561. *(dest->next_output_byte)++ = (JOCTET) val;
  157562. if (--dest->free_in_buffer == 0) {
  157563. if (! (*dest->empty_output_buffer) (cinfo))
  157564. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  157565. }
  157566. }
  157567. LOCAL(void)
  157568. emit_marker (j_compress_ptr cinfo, JPEG_MARKER mark)
  157569. /* Emit a marker code */
  157570. {
  157571. emit_byte(cinfo, 0xFF);
  157572. emit_byte(cinfo, (int) mark);
  157573. }
  157574. LOCAL(void)
  157575. emit_2bytes (j_compress_ptr cinfo, int value)
  157576. /* Emit a 2-byte integer; these are always MSB first in JPEG files */
  157577. {
  157578. emit_byte(cinfo, (value >> 8) & 0xFF);
  157579. emit_byte(cinfo, value & 0xFF);
  157580. }
  157581. /*
  157582. * Routines to write specific marker types.
  157583. */
  157584. LOCAL(int)
  157585. emit_dqt (j_compress_ptr cinfo, int index)
  157586. /* Emit a DQT marker */
  157587. /* Returns the precision used (0 = 8bits, 1 = 16bits) for baseline checking */
  157588. {
  157589. JQUANT_TBL * qtbl = cinfo->quant_tbl_ptrs[index];
  157590. int prec;
  157591. int i;
  157592. if (qtbl == NULL)
  157593. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, index);
  157594. prec = 0;
  157595. for (i = 0; i < DCTSIZE2; i++) {
  157596. if (qtbl->quantval[i] > 255)
  157597. prec = 1;
  157598. }
  157599. if (! qtbl->sent_table) {
  157600. emit_marker(cinfo, M_DQT);
  157601. emit_2bytes(cinfo, prec ? DCTSIZE2*2 + 1 + 2 : DCTSIZE2 + 1 + 2);
  157602. emit_byte(cinfo, index + (prec<<4));
  157603. for (i = 0; i < DCTSIZE2; i++) {
  157604. /* The table entries must be emitted in zigzag order. */
  157605. unsigned int qval = qtbl->quantval[jpeg_natural_order[i]];
  157606. if (prec)
  157607. emit_byte(cinfo, (int) (qval >> 8));
  157608. emit_byte(cinfo, (int) (qval & 0xFF));
  157609. }
  157610. qtbl->sent_table = TRUE;
  157611. }
  157612. return prec;
  157613. }
  157614. LOCAL(void)
  157615. emit_dht (j_compress_ptr cinfo, int index, boolean is_ac)
  157616. /* Emit a DHT marker */
  157617. {
  157618. JHUFF_TBL * htbl;
  157619. int length, i;
  157620. if (is_ac) {
  157621. htbl = cinfo->ac_huff_tbl_ptrs[index];
  157622. index += 0x10; /* output index has AC bit set */
  157623. } else {
  157624. htbl = cinfo->dc_huff_tbl_ptrs[index];
  157625. }
  157626. if (htbl == NULL)
  157627. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, index);
  157628. if (! htbl->sent_table) {
  157629. emit_marker(cinfo, M_DHT);
  157630. length = 0;
  157631. for (i = 1; i <= 16; i++)
  157632. length += htbl->bits[i];
  157633. emit_2bytes(cinfo, length + 2 + 1 + 16);
  157634. emit_byte(cinfo, index);
  157635. for (i = 1; i <= 16; i++)
  157636. emit_byte(cinfo, htbl->bits[i]);
  157637. for (i = 0; i < length; i++)
  157638. emit_byte(cinfo, htbl->huffval[i]);
  157639. htbl->sent_table = TRUE;
  157640. }
  157641. }
  157642. LOCAL(void)
  157643. emit_dac (j_compress_ptr cinfo)
  157644. /* Emit a DAC marker */
  157645. /* Since the useful info is so small, we want to emit all the tables in */
  157646. /* one DAC marker. Therefore this routine does its own scan of the table. */
  157647. {
  157648. #ifdef C_ARITH_CODING_SUPPORTED
  157649. char dc_in_use[NUM_ARITH_TBLS];
  157650. char ac_in_use[NUM_ARITH_TBLS];
  157651. int length, i;
  157652. jpeg_component_info *compptr;
  157653. for (i = 0; i < NUM_ARITH_TBLS; i++)
  157654. dc_in_use[i] = ac_in_use[i] = 0;
  157655. for (i = 0; i < cinfo->comps_in_scan; i++) {
  157656. compptr = cinfo->cur_comp_info[i];
  157657. dc_in_use[compptr->dc_tbl_no] = 1;
  157658. ac_in_use[compptr->ac_tbl_no] = 1;
  157659. }
  157660. length = 0;
  157661. for (i = 0; i < NUM_ARITH_TBLS; i++)
  157662. length += dc_in_use[i] + ac_in_use[i];
  157663. emit_marker(cinfo, M_DAC);
  157664. emit_2bytes(cinfo, length*2 + 2);
  157665. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  157666. if (dc_in_use[i]) {
  157667. emit_byte(cinfo, i);
  157668. emit_byte(cinfo, cinfo->arith_dc_L[i] + (cinfo->arith_dc_U[i]<<4));
  157669. }
  157670. if (ac_in_use[i]) {
  157671. emit_byte(cinfo, i + 0x10);
  157672. emit_byte(cinfo, cinfo->arith_ac_K[i]);
  157673. }
  157674. }
  157675. #endif /* C_ARITH_CODING_SUPPORTED */
  157676. }
  157677. LOCAL(void)
  157678. emit_dri (j_compress_ptr cinfo)
  157679. /* Emit a DRI marker */
  157680. {
  157681. emit_marker(cinfo, M_DRI);
  157682. emit_2bytes(cinfo, 4); /* fixed length */
  157683. emit_2bytes(cinfo, (int) cinfo->restart_interval);
  157684. }
  157685. LOCAL(void)
  157686. emit_sof (j_compress_ptr cinfo, JPEG_MARKER code)
  157687. /* Emit a SOF marker */
  157688. {
  157689. int ci;
  157690. jpeg_component_info *compptr;
  157691. emit_marker(cinfo, code);
  157692. emit_2bytes(cinfo, 3 * cinfo->num_components + 2 + 5 + 1); /* length */
  157693. /* Make sure image isn't bigger than SOF field can handle */
  157694. if ((long) cinfo->image_height > 65535L ||
  157695. (long) cinfo->image_width > 65535L)
  157696. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) 65535);
  157697. emit_byte(cinfo, cinfo->data_precision);
  157698. emit_2bytes(cinfo, (int) cinfo->image_height);
  157699. emit_2bytes(cinfo, (int) cinfo->image_width);
  157700. emit_byte(cinfo, cinfo->num_components);
  157701. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  157702. ci++, compptr++) {
  157703. emit_byte(cinfo, compptr->component_id);
  157704. emit_byte(cinfo, (compptr->h_samp_factor << 4) + compptr->v_samp_factor);
  157705. emit_byte(cinfo, compptr->quant_tbl_no);
  157706. }
  157707. }
  157708. LOCAL(void)
  157709. emit_sos (j_compress_ptr cinfo)
  157710. /* Emit a SOS marker */
  157711. {
  157712. int i, td, ta;
  157713. jpeg_component_info *compptr;
  157714. emit_marker(cinfo, M_SOS);
  157715. emit_2bytes(cinfo, 2 * cinfo->comps_in_scan + 2 + 1 + 3); /* length */
  157716. emit_byte(cinfo, cinfo->comps_in_scan);
  157717. for (i = 0; i < cinfo->comps_in_scan; i++) {
  157718. compptr = cinfo->cur_comp_info[i];
  157719. emit_byte(cinfo, compptr->component_id);
  157720. td = compptr->dc_tbl_no;
  157721. ta = compptr->ac_tbl_no;
  157722. if (cinfo->progressive_mode) {
  157723. /* Progressive mode: only DC or only AC tables are used in one scan;
  157724. * furthermore, Huffman coding of DC refinement uses no table at all.
  157725. * We emit 0 for unused field(s); this is recommended by the P&M text
  157726. * but does not seem to be specified in the standard.
  157727. */
  157728. if (cinfo->Ss == 0) {
  157729. ta = 0; /* DC scan */
  157730. if (cinfo->Ah != 0 && !cinfo->arith_code)
  157731. td = 0; /* no DC table either */
  157732. } else {
  157733. td = 0; /* AC scan */
  157734. }
  157735. }
  157736. emit_byte(cinfo, (td << 4) + ta);
  157737. }
  157738. emit_byte(cinfo, cinfo->Ss);
  157739. emit_byte(cinfo, cinfo->Se);
  157740. emit_byte(cinfo, (cinfo->Ah << 4) + cinfo->Al);
  157741. }
  157742. LOCAL(void)
  157743. emit_jfif_app0 (j_compress_ptr cinfo)
  157744. /* Emit a JFIF-compliant APP0 marker */
  157745. {
  157746. /*
  157747. * Length of APP0 block (2 bytes)
  157748. * Block ID (4 bytes - ASCII "JFIF")
  157749. * Zero byte (1 byte to terminate the ID string)
  157750. * Version Major, Minor (2 bytes - major first)
  157751. * Units (1 byte - 0x00 = none, 0x01 = inch, 0x02 = cm)
  157752. * Xdpu (2 bytes - dots per unit horizontal)
  157753. * Ydpu (2 bytes - dots per unit vertical)
  157754. * Thumbnail X size (1 byte)
  157755. * Thumbnail Y size (1 byte)
  157756. */
  157757. emit_marker(cinfo, M_APP0);
  157758. emit_2bytes(cinfo, 2 + 4 + 1 + 2 + 1 + 2 + 2 + 1 + 1); /* length */
  157759. emit_byte(cinfo, 0x4A); /* Identifier: ASCII "JFIF" */
  157760. emit_byte(cinfo, 0x46);
  157761. emit_byte(cinfo, 0x49);
  157762. emit_byte(cinfo, 0x46);
  157763. emit_byte(cinfo, 0);
  157764. emit_byte(cinfo, cinfo->JFIF_major_version); /* Version fields */
  157765. emit_byte(cinfo, cinfo->JFIF_minor_version);
  157766. emit_byte(cinfo, cinfo->density_unit); /* Pixel size information */
  157767. emit_2bytes(cinfo, (int) cinfo->X_density);
  157768. emit_2bytes(cinfo, (int) cinfo->Y_density);
  157769. emit_byte(cinfo, 0); /* No thumbnail image */
  157770. emit_byte(cinfo, 0);
  157771. }
  157772. LOCAL(void)
  157773. emit_adobe_app14 (j_compress_ptr cinfo)
  157774. /* Emit an Adobe APP14 marker */
  157775. {
  157776. /*
  157777. * Length of APP14 block (2 bytes)
  157778. * Block ID (5 bytes - ASCII "Adobe")
  157779. * Version Number (2 bytes - currently 100)
  157780. * Flags0 (2 bytes - currently 0)
  157781. * Flags1 (2 bytes - currently 0)
  157782. * Color transform (1 byte)
  157783. *
  157784. * Although Adobe TN 5116 mentions Version = 101, all the Adobe files
  157785. * now in circulation seem to use Version = 100, so that's what we write.
  157786. *
  157787. * We write the color transform byte as 1 if the JPEG color space is
  157788. * YCbCr, 2 if it's YCCK, 0 otherwise. Adobe's definition has to do with
  157789. * whether the encoder performed a transformation, which is pretty useless.
  157790. */
  157791. emit_marker(cinfo, M_APP14);
  157792. emit_2bytes(cinfo, 2 + 5 + 2 + 2 + 2 + 1); /* length */
  157793. emit_byte(cinfo, 0x41); /* Identifier: ASCII "Adobe" */
  157794. emit_byte(cinfo, 0x64);
  157795. emit_byte(cinfo, 0x6F);
  157796. emit_byte(cinfo, 0x62);
  157797. emit_byte(cinfo, 0x65);
  157798. emit_2bytes(cinfo, 100); /* Version */
  157799. emit_2bytes(cinfo, 0); /* Flags0 */
  157800. emit_2bytes(cinfo, 0); /* Flags1 */
  157801. switch (cinfo->jpeg_color_space) {
  157802. case JCS_YCbCr:
  157803. emit_byte(cinfo, 1); /* Color transform = 1 */
  157804. break;
  157805. case JCS_YCCK:
  157806. emit_byte(cinfo, 2); /* Color transform = 2 */
  157807. break;
  157808. default:
  157809. emit_byte(cinfo, 0); /* Color transform = 0 */
  157810. break;
  157811. }
  157812. }
  157813. /*
  157814. * These routines allow writing an arbitrary marker with parameters.
  157815. * The only intended use is to emit COM or APPn markers after calling
  157816. * write_file_header and before calling write_frame_header.
  157817. * Other uses are not guaranteed to produce desirable results.
  157818. * Counting the parameter bytes properly is the caller's responsibility.
  157819. */
  157820. METHODDEF(void)
  157821. write_marker_header (j_compress_ptr cinfo, int marker, unsigned int datalen)
  157822. /* Emit an arbitrary marker header */
  157823. {
  157824. if (datalen > (unsigned int) 65533) /* safety check */
  157825. ERREXIT(cinfo, JERR_BAD_LENGTH);
  157826. emit_marker(cinfo, (JPEG_MARKER) marker);
  157827. emit_2bytes(cinfo, (int) (datalen + 2)); /* total length */
  157828. }
  157829. METHODDEF(void)
  157830. write_marker_byte (j_compress_ptr cinfo, int val)
  157831. /* Emit one byte of marker parameters following write_marker_header */
  157832. {
  157833. emit_byte(cinfo, val);
  157834. }
  157835. /*
  157836. * Write datastream header.
  157837. * This consists of an SOI and optional APPn markers.
  157838. * We recommend use of the JFIF marker, but not the Adobe marker,
  157839. * when using YCbCr or grayscale data. The JFIF marker should NOT
  157840. * be used for any other JPEG colorspace. The Adobe marker is helpful
  157841. * to distinguish RGB, CMYK, and YCCK colorspaces.
  157842. * Note that an application can write additional header markers after
  157843. * jpeg_start_compress returns.
  157844. */
  157845. METHODDEF(void)
  157846. write_file_header (j_compress_ptr cinfo)
  157847. {
  157848. my_marker_ptr marker = (my_marker_ptr) cinfo->marker;
  157849. emit_marker(cinfo, M_SOI); /* first the SOI */
  157850. /* SOI is defined to reset restart interval to 0 */
  157851. marker->last_restart_interval = 0;
  157852. if (cinfo->write_JFIF_header) /* next an optional JFIF APP0 */
  157853. emit_jfif_app0(cinfo);
  157854. if (cinfo->write_Adobe_marker) /* next an optional Adobe APP14 */
  157855. emit_adobe_app14(cinfo);
  157856. }
  157857. /*
  157858. * Write frame header.
  157859. * This consists of DQT and SOFn markers.
  157860. * Note that we do not emit the SOF until we have emitted the DQT(s).
  157861. * This avoids compatibility problems with incorrect implementations that
  157862. * try to error-check the quant table numbers as soon as they see the SOF.
  157863. */
  157864. METHODDEF(void)
  157865. write_frame_header (j_compress_ptr cinfo)
  157866. {
  157867. int ci, prec;
  157868. boolean is_baseline;
  157869. jpeg_component_info *compptr;
  157870. /* Emit DQT for each quantization table.
  157871. * Note that emit_dqt() suppresses any duplicate tables.
  157872. */
  157873. prec = 0;
  157874. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  157875. ci++, compptr++) {
  157876. prec += emit_dqt(cinfo, compptr->quant_tbl_no);
  157877. }
  157878. /* now prec is nonzero iff there are any 16-bit quant tables. */
  157879. /* Check for a non-baseline specification.
  157880. * Note we assume that Huffman table numbers won't be changed later.
  157881. */
  157882. if (cinfo->arith_code || cinfo->progressive_mode ||
  157883. cinfo->data_precision != 8) {
  157884. is_baseline = FALSE;
  157885. } else {
  157886. is_baseline = TRUE;
  157887. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  157888. ci++, compptr++) {
  157889. if (compptr->dc_tbl_no > 1 || compptr->ac_tbl_no > 1)
  157890. is_baseline = FALSE;
  157891. }
  157892. if (prec && is_baseline) {
  157893. is_baseline = FALSE;
  157894. /* If it's baseline except for quantizer size, warn the user */
  157895. TRACEMS(cinfo, 0, JTRC_16BIT_TABLES);
  157896. }
  157897. }
  157898. /* Emit the proper SOF marker */
  157899. if (cinfo->arith_code) {
  157900. emit_sof(cinfo, M_SOF9); /* SOF code for arithmetic coding */
  157901. } else {
  157902. if (cinfo->progressive_mode)
  157903. emit_sof(cinfo, M_SOF2); /* SOF code for progressive Huffman */
  157904. else if (is_baseline)
  157905. emit_sof(cinfo, M_SOF0); /* SOF code for baseline implementation */
  157906. else
  157907. emit_sof(cinfo, M_SOF1); /* SOF code for non-baseline Huffman file */
  157908. }
  157909. }
  157910. /*
  157911. * Write scan header.
  157912. * This consists of DHT or DAC markers, optional DRI, and SOS.
  157913. * Compressed data will be written following the SOS.
  157914. */
  157915. METHODDEF(void)
  157916. write_scan_header (j_compress_ptr cinfo)
  157917. {
  157918. my_marker_ptr marker = (my_marker_ptr) cinfo->marker;
  157919. int i;
  157920. jpeg_component_info *compptr;
  157921. if (cinfo->arith_code) {
  157922. /* Emit arith conditioning info. We may have some duplication
  157923. * if the file has multiple scans, but it's so small it's hardly
  157924. * worth worrying about.
  157925. */
  157926. emit_dac(cinfo);
  157927. } else {
  157928. /* Emit Huffman tables.
  157929. * Note that emit_dht() suppresses any duplicate tables.
  157930. */
  157931. for (i = 0; i < cinfo->comps_in_scan; i++) {
  157932. compptr = cinfo->cur_comp_info[i];
  157933. if (cinfo->progressive_mode) {
  157934. /* Progressive mode: only DC or only AC tables are used in one scan */
  157935. if (cinfo->Ss == 0) {
  157936. if (cinfo->Ah == 0) /* DC needs no table for refinement scan */
  157937. emit_dht(cinfo, compptr->dc_tbl_no, FALSE);
  157938. } else {
  157939. emit_dht(cinfo, compptr->ac_tbl_no, TRUE);
  157940. }
  157941. } else {
  157942. /* Sequential mode: need both DC and AC tables */
  157943. emit_dht(cinfo, compptr->dc_tbl_no, FALSE);
  157944. emit_dht(cinfo, compptr->ac_tbl_no, TRUE);
  157945. }
  157946. }
  157947. }
  157948. /* Emit DRI if required --- note that DRI value could change for each scan.
  157949. * We avoid wasting space with unnecessary DRIs, however.
  157950. */
  157951. if (cinfo->restart_interval != marker->last_restart_interval) {
  157952. emit_dri(cinfo);
  157953. marker->last_restart_interval = cinfo->restart_interval;
  157954. }
  157955. emit_sos(cinfo);
  157956. }
  157957. /*
  157958. * Write datastream trailer.
  157959. */
  157960. METHODDEF(void)
  157961. write_file_trailer (j_compress_ptr cinfo)
  157962. {
  157963. emit_marker(cinfo, M_EOI);
  157964. }
  157965. /*
  157966. * Write an abbreviated table-specification datastream.
  157967. * This consists of SOI, DQT and DHT tables, and EOI.
  157968. * Any table that is defined and not marked sent_table = TRUE will be
  157969. * emitted. Note that all tables will be marked sent_table = TRUE at exit.
  157970. */
  157971. METHODDEF(void)
  157972. write_tables_only (j_compress_ptr cinfo)
  157973. {
  157974. int i;
  157975. emit_marker(cinfo, M_SOI);
  157976. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  157977. if (cinfo->quant_tbl_ptrs[i] != NULL)
  157978. (void) emit_dqt(cinfo, i);
  157979. }
  157980. if (! cinfo->arith_code) {
  157981. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  157982. if (cinfo->dc_huff_tbl_ptrs[i] != NULL)
  157983. emit_dht(cinfo, i, FALSE);
  157984. if (cinfo->ac_huff_tbl_ptrs[i] != NULL)
  157985. emit_dht(cinfo, i, TRUE);
  157986. }
  157987. }
  157988. emit_marker(cinfo, M_EOI);
  157989. }
  157990. /*
  157991. * Initialize the marker writer module.
  157992. */
  157993. GLOBAL(void)
  157994. jinit_marker_writer (j_compress_ptr cinfo)
  157995. {
  157996. my_marker_ptr marker;
  157997. /* Create the subobject */
  157998. marker = (my_marker_ptr)
  157999. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  158000. SIZEOF(my_marker_writer));
  158001. cinfo->marker = (struct jpeg_marker_writer *) marker;
  158002. /* Initialize method pointers */
  158003. marker->pub.write_file_header = write_file_header;
  158004. marker->pub.write_frame_header = write_frame_header;
  158005. marker->pub.write_scan_header = write_scan_header;
  158006. marker->pub.write_file_trailer = write_file_trailer;
  158007. marker->pub.write_tables_only = write_tables_only;
  158008. marker->pub.write_marker_header = write_marker_header;
  158009. marker->pub.write_marker_byte = write_marker_byte;
  158010. /* Initialize private state */
  158011. marker->last_restart_interval = 0;
  158012. }
  158013. /********* End of inlined file: jcmarker.c *********/
  158014. /********* Start of inlined file: jcmaster.c *********/
  158015. #define JPEG_INTERNALS
  158016. /* Private state */
  158017. typedef enum {
  158018. main_pass, /* input data, also do first output step */
  158019. huff_opt_pass, /* Huffman code optimization pass */
  158020. output_pass /* data output pass */
  158021. } c_pass_type;
  158022. typedef struct {
  158023. struct jpeg_comp_master pub; /* public fields */
  158024. c_pass_type pass_type; /* the type of the current pass */
  158025. int pass_number; /* # of passes completed */
  158026. int total_passes; /* total # of passes needed */
  158027. int scan_number; /* current index in scan_info[] */
  158028. } my_comp_master;
  158029. typedef my_comp_master * my_master_ptr;
  158030. /*
  158031. * Support routines that do various essential calculations.
  158032. */
  158033. LOCAL(void)
  158034. initial_setup (j_compress_ptr cinfo)
  158035. /* Do computations that are needed before master selection phase */
  158036. {
  158037. int ci;
  158038. jpeg_component_info *compptr;
  158039. long samplesperrow;
  158040. JDIMENSION jd_samplesperrow;
  158041. /* Sanity check on image dimensions */
  158042. if (cinfo->image_height <= 0 || cinfo->image_width <= 0
  158043. || cinfo->num_components <= 0 || cinfo->input_components <= 0)
  158044. ERREXIT(cinfo, JERR_EMPTY_IMAGE);
  158045. /* Make sure image isn't bigger than I can handle */
  158046. if ((long) cinfo->image_height > (long) JPEG_MAX_DIMENSION ||
  158047. (long) cinfo->image_width > (long) JPEG_MAX_DIMENSION)
  158048. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) JPEG_MAX_DIMENSION);
  158049. /* Width of an input scanline must be representable as JDIMENSION. */
  158050. samplesperrow = (long) cinfo->image_width * (long) cinfo->input_components;
  158051. jd_samplesperrow = (JDIMENSION) samplesperrow;
  158052. if ((long) jd_samplesperrow != samplesperrow)
  158053. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  158054. /* For now, precision must match compiled-in value... */
  158055. if (cinfo->data_precision != BITS_IN_JSAMPLE)
  158056. ERREXIT1(cinfo, JERR_BAD_PRECISION, cinfo->data_precision);
  158057. /* Check that number of components won't exceed internal array sizes */
  158058. if (cinfo->num_components > MAX_COMPONENTS)
  158059. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  158060. MAX_COMPONENTS);
  158061. /* Compute maximum sampling factors; check factor validity */
  158062. cinfo->max_h_samp_factor = 1;
  158063. cinfo->max_v_samp_factor = 1;
  158064. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  158065. ci++, compptr++) {
  158066. if (compptr->h_samp_factor<=0 || compptr->h_samp_factor>MAX_SAMP_FACTOR ||
  158067. compptr->v_samp_factor<=0 || compptr->v_samp_factor>MAX_SAMP_FACTOR)
  158068. ERREXIT(cinfo, JERR_BAD_SAMPLING);
  158069. cinfo->max_h_samp_factor = MAX(cinfo->max_h_samp_factor,
  158070. compptr->h_samp_factor);
  158071. cinfo->max_v_samp_factor = MAX(cinfo->max_v_samp_factor,
  158072. compptr->v_samp_factor);
  158073. }
  158074. /* Compute dimensions of components */
  158075. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  158076. ci++, compptr++) {
  158077. /* Fill in the correct component_index value; don't rely on application */
  158078. compptr->component_index = ci;
  158079. /* For compression, we never do DCT scaling. */
  158080. compptr->DCT_scaled_size = DCTSIZE;
  158081. /* Size in DCT blocks */
  158082. compptr->width_in_blocks = (JDIMENSION)
  158083. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  158084. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  158085. compptr->height_in_blocks = (JDIMENSION)
  158086. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  158087. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  158088. /* Size in samples */
  158089. compptr->downsampled_width = (JDIMENSION)
  158090. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  158091. (long) cinfo->max_h_samp_factor);
  158092. compptr->downsampled_height = (JDIMENSION)
  158093. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  158094. (long) cinfo->max_v_samp_factor);
  158095. /* Mark component needed (this flag isn't actually used for compression) */
  158096. compptr->component_needed = TRUE;
  158097. }
  158098. /* Compute number of fully interleaved MCU rows (number of times that
  158099. * main controller will call coefficient controller).
  158100. */
  158101. cinfo->total_iMCU_rows = (JDIMENSION)
  158102. jdiv_round_up((long) cinfo->image_height,
  158103. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  158104. }
  158105. #ifdef C_MULTISCAN_FILES_SUPPORTED
  158106. LOCAL(void)
  158107. validate_script (j_compress_ptr cinfo)
  158108. /* Verify that the scan script in cinfo->scan_info[] is valid; also
  158109. * determine whether it uses progressive JPEG, and set cinfo->progressive_mode.
  158110. */
  158111. {
  158112. const jpeg_scan_info * scanptr;
  158113. int scanno, ncomps, ci, coefi, thisi;
  158114. int Ss, Se, Ah, Al;
  158115. boolean component_sent[MAX_COMPONENTS];
  158116. #ifdef C_PROGRESSIVE_SUPPORTED
  158117. int * last_bitpos_ptr;
  158118. int last_bitpos[MAX_COMPONENTS][DCTSIZE2];
  158119. /* -1 until that coefficient has been seen; then last Al for it */
  158120. #endif
  158121. if (cinfo->num_scans <= 0)
  158122. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, 0);
  158123. /* For sequential JPEG, all scans must have Ss=0, Se=DCTSIZE2-1;
  158124. * for progressive JPEG, no scan can have this.
  158125. */
  158126. scanptr = cinfo->scan_info;
  158127. if (scanptr->Ss != 0 || scanptr->Se != DCTSIZE2-1) {
  158128. #ifdef C_PROGRESSIVE_SUPPORTED
  158129. cinfo->progressive_mode = TRUE;
  158130. last_bitpos_ptr = & last_bitpos[0][0];
  158131. for (ci = 0; ci < cinfo->num_components; ci++)
  158132. for (coefi = 0; coefi < DCTSIZE2; coefi++)
  158133. *last_bitpos_ptr++ = -1;
  158134. #else
  158135. ERREXIT(cinfo, JERR_NOT_COMPILED);
  158136. #endif
  158137. } else {
  158138. cinfo->progressive_mode = FALSE;
  158139. for (ci = 0; ci < cinfo->num_components; ci++)
  158140. component_sent[ci] = FALSE;
  158141. }
  158142. for (scanno = 1; scanno <= cinfo->num_scans; scanptr++, scanno++) {
  158143. /* Validate component indexes */
  158144. ncomps = scanptr->comps_in_scan;
  158145. if (ncomps <= 0 || ncomps > MAX_COMPS_IN_SCAN)
  158146. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, ncomps, MAX_COMPS_IN_SCAN);
  158147. for (ci = 0; ci < ncomps; ci++) {
  158148. thisi = scanptr->component_index[ci];
  158149. if (thisi < 0 || thisi >= cinfo->num_components)
  158150. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  158151. /* Components must appear in SOF order within each scan */
  158152. if (ci > 0 && thisi <= scanptr->component_index[ci-1])
  158153. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  158154. }
  158155. /* Validate progression parameters */
  158156. Ss = scanptr->Ss;
  158157. Se = scanptr->Se;
  158158. Ah = scanptr->Ah;
  158159. Al = scanptr->Al;
  158160. if (cinfo->progressive_mode) {
  158161. #ifdef C_PROGRESSIVE_SUPPORTED
  158162. /* The JPEG spec simply gives the ranges 0..13 for Ah and Al, but that
  158163. * seems wrong: the upper bound ought to depend on data precision.
  158164. * Perhaps they really meant 0..N+1 for N-bit precision.
  158165. * Here we allow 0..10 for 8-bit data; Al larger than 10 results in
  158166. * out-of-range reconstructed DC values during the first DC scan,
  158167. * which might cause problems for some decoders.
  158168. */
  158169. #if BITS_IN_JSAMPLE == 8
  158170. #define MAX_AH_AL 10
  158171. #else
  158172. #define MAX_AH_AL 13
  158173. #endif
  158174. if (Ss < 0 || Ss >= DCTSIZE2 || Se < Ss || Se >= DCTSIZE2 ||
  158175. Ah < 0 || Ah > MAX_AH_AL || Al < 0 || Al > MAX_AH_AL)
  158176. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  158177. if (Ss == 0) {
  158178. if (Se != 0) /* DC and AC together not OK */
  158179. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  158180. } else {
  158181. if (ncomps != 1) /* AC scans must be for only one component */
  158182. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  158183. }
  158184. for (ci = 0; ci < ncomps; ci++) {
  158185. last_bitpos_ptr = & last_bitpos[scanptr->component_index[ci]][0];
  158186. if (Ss != 0 && last_bitpos_ptr[0] < 0) /* AC without prior DC scan */
  158187. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  158188. for (coefi = Ss; coefi <= Se; coefi++) {
  158189. if (last_bitpos_ptr[coefi] < 0) {
  158190. /* first scan of this coefficient */
  158191. if (Ah != 0)
  158192. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  158193. } else {
  158194. /* not first scan */
  158195. if (Ah != last_bitpos_ptr[coefi] || Al != Ah-1)
  158196. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  158197. }
  158198. last_bitpos_ptr[coefi] = Al;
  158199. }
  158200. }
  158201. #endif
  158202. } else {
  158203. /* For sequential JPEG, all progression parameters must be these: */
  158204. if (Ss != 0 || Se != DCTSIZE2-1 || Ah != 0 || Al != 0)
  158205. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  158206. /* Make sure components are not sent twice */
  158207. for (ci = 0; ci < ncomps; ci++) {
  158208. thisi = scanptr->component_index[ci];
  158209. if (component_sent[thisi])
  158210. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  158211. component_sent[thisi] = TRUE;
  158212. }
  158213. }
  158214. }
  158215. /* Now verify that everything got sent. */
  158216. if (cinfo->progressive_mode) {
  158217. #ifdef C_PROGRESSIVE_SUPPORTED
  158218. /* For progressive mode, we only check that at least some DC data
  158219. * got sent for each component; the spec does not require that all bits
  158220. * of all coefficients be transmitted. Would it be wiser to enforce
  158221. * transmission of all coefficient bits??
  158222. */
  158223. for (ci = 0; ci < cinfo->num_components; ci++) {
  158224. if (last_bitpos[ci][0] < 0)
  158225. ERREXIT(cinfo, JERR_MISSING_DATA);
  158226. }
  158227. #endif
  158228. } else {
  158229. for (ci = 0; ci < cinfo->num_components; ci++) {
  158230. if (! component_sent[ci])
  158231. ERREXIT(cinfo, JERR_MISSING_DATA);
  158232. }
  158233. }
  158234. }
  158235. #endif /* C_MULTISCAN_FILES_SUPPORTED */
  158236. LOCAL(void)
  158237. select_scan_parameters (j_compress_ptr cinfo)
  158238. /* Set up the scan parameters for the current scan */
  158239. {
  158240. int ci;
  158241. #ifdef C_MULTISCAN_FILES_SUPPORTED
  158242. if (cinfo->scan_info != NULL) {
  158243. /* Prepare for current scan --- the script is already validated */
  158244. my_master_ptr master = (my_master_ptr) cinfo->master;
  158245. const jpeg_scan_info * scanptr = cinfo->scan_info + master->scan_number;
  158246. cinfo->comps_in_scan = scanptr->comps_in_scan;
  158247. for (ci = 0; ci < scanptr->comps_in_scan; ci++) {
  158248. cinfo->cur_comp_info[ci] =
  158249. &cinfo->comp_info[scanptr->component_index[ci]];
  158250. }
  158251. cinfo->Ss = scanptr->Ss;
  158252. cinfo->Se = scanptr->Se;
  158253. cinfo->Ah = scanptr->Ah;
  158254. cinfo->Al = scanptr->Al;
  158255. }
  158256. else
  158257. #endif
  158258. {
  158259. /* Prepare for single sequential-JPEG scan containing all components */
  158260. if (cinfo->num_components > MAX_COMPS_IN_SCAN)
  158261. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  158262. MAX_COMPS_IN_SCAN);
  158263. cinfo->comps_in_scan = cinfo->num_components;
  158264. for (ci = 0; ci < cinfo->num_components; ci++) {
  158265. cinfo->cur_comp_info[ci] = &cinfo->comp_info[ci];
  158266. }
  158267. cinfo->Ss = 0;
  158268. cinfo->Se = DCTSIZE2-1;
  158269. cinfo->Ah = 0;
  158270. cinfo->Al = 0;
  158271. }
  158272. }
  158273. LOCAL(void)
  158274. per_scan_setup (j_compress_ptr cinfo)
  158275. /* Do computations that are needed before processing a JPEG scan */
  158276. /* cinfo->comps_in_scan and cinfo->cur_comp_info[] are already set */
  158277. {
  158278. int ci, mcublks, tmp;
  158279. jpeg_component_info *compptr;
  158280. if (cinfo->comps_in_scan == 1) {
  158281. /* Noninterleaved (single-component) scan */
  158282. compptr = cinfo->cur_comp_info[0];
  158283. /* Overall image size in MCUs */
  158284. cinfo->MCUs_per_row = compptr->width_in_blocks;
  158285. cinfo->MCU_rows_in_scan = compptr->height_in_blocks;
  158286. /* For noninterleaved scan, always one block per MCU */
  158287. compptr->MCU_width = 1;
  158288. compptr->MCU_height = 1;
  158289. compptr->MCU_blocks = 1;
  158290. compptr->MCU_sample_width = DCTSIZE;
  158291. compptr->last_col_width = 1;
  158292. /* For noninterleaved scans, it is convenient to define last_row_height
  158293. * as the number of block rows present in the last iMCU row.
  158294. */
  158295. tmp = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  158296. if (tmp == 0) tmp = compptr->v_samp_factor;
  158297. compptr->last_row_height = tmp;
  158298. /* Prepare array describing MCU composition */
  158299. cinfo->blocks_in_MCU = 1;
  158300. cinfo->MCU_membership[0] = 0;
  158301. } else {
  158302. /* Interleaved (multi-component) scan */
  158303. if (cinfo->comps_in_scan <= 0 || cinfo->comps_in_scan > MAX_COMPS_IN_SCAN)
  158304. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->comps_in_scan,
  158305. MAX_COMPS_IN_SCAN);
  158306. /* Overall image size in MCUs */
  158307. cinfo->MCUs_per_row = (JDIMENSION)
  158308. jdiv_round_up((long) cinfo->image_width,
  158309. (long) (cinfo->max_h_samp_factor*DCTSIZE));
  158310. cinfo->MCU_rows_in_scan = (JDIMENSION)
  158311. jdiv_round_up((long) cinfo->image_height,
  158312. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  158313. cinfo->blocks_in_MCU = 0;
  158314. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  158315. compptr = cinfo->cur_comp_info[ci];
  158316. /* Sampling factors give # of blocks of component in each MCU */
  158317. compptr->MCU_width = compptr->h_samp_factor;
  158318. compptr->MCU_height = compptr->v_samp_factor;
  158319. compptr->MCU_blocks = compptr->MCU_width * compptr->MCU_height;
  158320. compptr->MCU_sample_width = compptr->MCU_width * DCTSIZE;
  158321. /* Figure number of non-dummy blocks in last MCU column & row */
  158322. tmp = (int) (compptr->width_in_blocks % compptr->MCU_width);
  158323. if (tmp == 0) tmp = compptr->MCU_width;
  158324. compptr->last_col_width = tmp;
  158325. tmp = (int) (compptr->height_in_blocks % compptr->MCU_height);
  158326. if (tmp == 0) tmp = compptr->MCU_height;
  158327. compptr->last_row_height = tmp;
  158328. /* Prepare array describing MCU composition */
  158329. mcublks = compptr->MCU_blocks;
  158330. if (cinfo->blocks_in_MCU + mcublks > C_MAX_BLOCKS_IN_MCU)
  158331. ERREXIT(cinfo, JERR_BAD_MCU_SIZE);
  158332. while (mcublks-- > 0) {
  158333. cinfo->MCU_membership[cinfo->blocks_in_MCU++] = ci;
  158334. }
  158335. }
  158336. }
  158337. /* Convert restart specified in rows to actual MCU count. */
  158338. /* Note that count must fit in 16 bits, so we provide limiting. */
  158339. if (cinfo->restart_in_rows > 0) {
  158340. long nominal = (long) cinfo->restart_in_rows * (long) cinfo->MCUs_per_row;
  158341. cinfo->restart_interval = (unsigned int) MIN(nominal, 65535L);
  158342. }
  158343. }
  158344. /*
  158345. * Per-pass setup.
  158346. * This is called at the beginning of each pass. We determine which modules
  158347. * will be active during this pass and give them appropriate start_pass calls.
  158348. * We also set is_last_pass to indicate whether any more passes will be
  158349. * required.
  158350. */
  158351. METHODDEF(void)
  158352. prepare_for_pass (j_compress_ptr cinfo)
  158353. {
  158354. my_master_ptr master = (my_master_ptr) cinfo->master;
  158355. switch (master->pass_type) {
  158356. case main_pass:
  158357. /* Initial pass: will collect input data, and do either Huffman
  158358. * optimization or data output for the first scan.
  158359. */
  158360. select_scan_parameters(cinfo);
  158361. per_scan_setup(cinfo);
  158362. if (! cinfo->raw_data_in) {
  158363. (*cinfo->cconvert->start_pass) (cinfo);
  158364. (*cinfo->downsample->start_pass) (cinfo);
  158365. (*cinfo->prep->start_pass) (cinfo, JBUF_PASS_THRU);
  158366. }
  158367. (*cinfo->fdct->start_pass) (cinfo);
  158368. (*cinfo->entropy->start_pass) (cinfo, cinfo->optimize_coding);
  158369. (*cinfo->coef->start_pass) (cinfo,
  158370. (master->total_passes > 1 ?
  158371. JBUF_SAVE_AND_PASS : JBUF_PASS_THRU));
  158372. (*cinfo->main->start_pass) (cinfo, JBUF_PASS_THRU);
  158373. if (cinfo->optimize_coding) {
  158374. /* No immediate data output; postpone writing frame/scan headers */
  158375. master->pub.call_pass_startup = FALSE;
  158376. } else {
  158377. /* Will write frame/scan headers at first jpeg_write_scanlines call */
  158378. master->pub.call_pass_startup = TRUE;
  158379. }
  158380. break;
  158381. #ifdef ENTROPY_OPT_SUPPORTED
  158382. case huff_opt_pass:
  158383. /* Do Huffman optimization for a scan after the first one. */
  158384. select_scan_parameters(cinfo);
  158385. per_scan_setup(cinfo);
  158386. if (cinfo->Ss != 0 || cinfo->Ah == 0 || cinfo->arith_code) {
  158387. (*cinfo->entropy->start_pass) (cinfo, TRUE);
  158388. (*cinfo->coef->start_pass) (cinfo, JBUF_CRANK_DEST);
  158389. master->pub.call_pass_startup = FALSE;
  158390. break;
  158391. }
  158392. /* Special case: Huffman DC refinement scans need no Huffman table
  158393. * and therefore we can skip the optimization pass for them.
  158394. */
  158395. master->pass_type = output_pass;
  158396. master->pass_number++;
  158397. /*FALLTHROUGH*/
  158398. #endif
  158399. case output_pass:
  158400. /* Do a data-output pass. */
  158401. /* We need not repeat per-scan setup if prior optimization pass did it. */
  158402. if (! cinfo->optimize_coding) {
  158403. select_scan_parameters(cinfo);
  158404. per_scan_setup(cinfo);
  158405. }
  158406. (*cinfo->entropy->start_pass) (cinfo, FALSE);
  158407. (*cinfo->coef->start_pass) (cinfo, JBUF_CRANK_DEST);
  158408. /* We emit frame/scan headers now */
  158409. if (master->scan_number == 0)
  158410. (*cinfo->marker->write_frame_header) (cinfo);
  158411. (*cinfo->marker->write_scan_header) (cinfo);
  158412. master->pub.call_pass_startup = FALSE;
  158413. break;
  158414. default:
  158415. ERREXIT(cinfo, JERR_NOT_COMPILED);
  158416. }
  158417. master->pub.is_last_pass = (master->pass_number == master->total_passes-1);
  158418. /* Set up progress monitor's pass info if present */
  158419. if (cinfo->progress != NULL) {
  158420. cinfo->progress->completed_passes = master->pass_number;
  158421. cinfo->progress->total_passes = master->total_passes;
  158422. }
  158423. }
  158424. /*
  158425. * Special start-of-pass hook.
  158426. * This is called by jpeg_write_scanlines if call_pass_startup is TRUE.
  158427. * In single-pass processing, we need this hook because we don't want to
  158428. * write frame/scan headers during jpeg_start_compress; we want to let the
  158429. * application write COM markers etc. between jpeg_start_compress and the
  158430. * jpeg_write_scanlines loop.
  158431. * In multi-pass processing, this routine is not used.
  158432. */
  158433. METHODDEF(void)
  158434. pass_startup (j_compress_ptr cinfo)
  158435. {
  158436. cinfo->master->call_pass_startup = FALSE; /* reset flag so call only once */
  158437. (*cinfo->marker->write_frame_header) (cinfo);
  158438. (*cinfo->marker->write_scan_header) (cinfo);
  158439. }
  158440. /*
  158441. * Finish up at end of pass.
  158442. */
  158443. METHODDEF(void)
  158444. finish_pass_master (j_compress_ptr cinfo)
  158445. {
  158446. my_master_ptr master = (my_master_ptr) cinfo->master;
  158447. /* The entropy coder always needs an end-of-pass call,
  158448. * either to analyze statistics or to flush its output buffer.
  158449. */
  158450. (*cinfo->entropy->finish_pass) (cinfo);
  158451. /* Update state for next pass */
  158452. switch (master->pass_type) {
  158453. case main_pass:
  158454. /* next pass is either output of scan 0 (after optimization)
  158455. * or output of scan 1 (if no optimization).
  158456. */
  158457. master->pass_type = output_pass;
  158458. if (! cinfo->optimize_coding)
  158459. master->scan_number++;
  158460. break;
  158461. case huff_opt_pass:
  158462. /* next pass is always output of current scan */
  158463. master->pass_type = output_pass;
  158464. break;
  158465. case output_pass:
  158466. /* next pass is either optimization or output of next scan */
  158467. if (cinfo->optimize_coding)
  158468. master->pass_type = huff_opt_pass;
  158469. master->scan_number++;
  158470. break;
  158471. }
  158472. master->pass_number++;
  158473. }
  158474. /*
  158475. * Initialize master compression control.
  158476. */
  158477. GLOBAL(void)
  158478. jinit_c_master_control (j_compress_ptr cinfo, boolean transcode_only)
  158479. {
  158480. my_master_ptr master;
  158481. master = (my_master_ptr)
  158482. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  158483. SIZEOF(my_comp_master));
  158484. cinfo->master = (struct jpeg_comp_master *) master;
  158485. master->pub.prepare_for_pass = prepare_for_pass;
  158486. master->pub.pass_startup = pass_startup;
  158487. master->pub.finish_pass = finish_pass_master;
  158488. master->pub.is_last_pass = FALSE;
  158489. /* Validate parameters, determine derived values */
  158490. initial_setup(cinfo);
  158491. if (cinfo->scan_info != NULL) {
  158492. #ifdef C_MULTISCAN_FILES_SUPPORTED
  158493. validate_script(cinfo);
  158494. #else
  158495. ERREXIT(cinfo, JERR_NOT_COMPILED);
  158496. #endif
  158497. } else {
  158498. cinfo->progressive_mode = FALSE;
  158499. cinfo->num_scans = 1;
  158500. }
  158501. if (cinfo->progressive_mode) /* TEMPORARY HACK ??? */
  158502. cinfo->optimize_coding = TRUE; /* assume default tables no good for progressive mode */
  158503. /* Initialize my private state */
  158504. if (transcode_only) {
  158505. /* no main pass in transcoding */
  158506. if (cinfo->optimize_coding)
  158507. master->pass_type = huff_opt_pass;
  158508. else
  158509. master->pass_type = output_pass;
  158510. } else {
  158511. /* for normal compression, first pass is always this type: */
  158512. master->pass_type = main_pass;
  158513. }
  158514. master->scan_number = 0;
  158515. master->pass_number = 0;
  158516. if (cinfo->optimize_coding)
  158517. master->total_passes = cinfo->num_scans * 2;
  158518. else
  158519. master->total_passes = cinfo->num_scans;
  158520. }
  158521. /********* End of inlined file: jcmaster.c *********/
  158522. /********* Start of inlined file: jcomapi.c *********/
  158523. #define JPEG_INTERNALS
  158524. /*
  158525. * Abort processing of a JPEG compression or decompression operation,
  158526. * but don't destroy the object itself.
  158527. *
  158528. * For this, we merely clean up all the nonpermanent memory pools.
  158529. * Note that temp files (virtual arrays) are not allowed to belong to
  158530. * the permanent pool, so we will be able to close all temp files here.
  158531. * Closing a data source or destination, if necessary, is the application's
  158532. * responsibility.
  158533. */
  158534. GLOBAL(void)
  158535. jpeg_abort (j_common_ptr cinfo)
  158536. {
  158537. int pool;
  158538. /* Do nothing if called on a not-initialized or destroyed JPEG object. */
  158539. if (cinfo->mem == NULL)
  158540. return;
  158541. /* Releasing pools in reverse order might help avoid fragmentation
  158542. * with some (brain-damaged) malloc libraries.
  158543. */
  158544. for (pool = JPOOL_NUMPOOLS-1; pool > JPOOL_PERMANENT; pool--) {
  158545. (*cinfo->mem->free_pool) (cinfo, pool);
  158546. }
  158547. /* Reset overall state for possible reuse of object */
  158548. if (cinfo->is_decompressor) {
  158549. cinfo->global_state = DSTATE_START;
  158550. /* Try to keep application from accessing now-deleted marker list.
  158551. * A bit kludgy to do it here, but this is the most central place.
  158552. */
  158553. ((j_decompress_ptr) cinfo)->marker_list = NULL;
  158554. } else {
  158555. cinfo->global_state = CSTATE_START;
  158556. }
  158557. }
  158558. /*
  158559. * Destruction of a JPEG object.
  158560. *
  158561. * Everything gets deallocated except the master jpeg_compress_struct itself
  158562. * and the error manager struct. Both of these are supplied by the application
  158563. * and must be freed, if necessary, by the application. (Often they are on
  158564. * the stack and so don't need to be freed anyway.)
  158565. * Closing a data source or destination, if necessary, is the application's
  158566. * responsibility.
  158567. */
  158568. GLOBAL(void)
  158569. jpeg_destroy (j_common_ptr cinfo)
  158570. {
  158571. /* We need only tell the memory manager to release everything. */
  158572. /* NB: mem pointer is NULL if memory mgr failed to initialize. */
  158573. if (cinfo->mem != NULL)
  158574. (*cinfo->mem->self_destruct) (cinfo);
  158575. cinfo->mem = NULL; /* be safe if jpeg_destroy is called twice */
  158576. cinfo->global_state = 0; /* mark it destroyed */
  158577. }
  158578. /*
  158579. * Convenience routines for allocating quantization and Huffman tables.
  158580. * (Would jutils.c be a more reasonable place to put these?)
  158581. */
  158582. GLOBAL(JQUANT_TBL *)
  158583. jpeg_alloc_quant_table (j_common_ptr cinfo)
  158584. {
  158585. JQUANT_TBL *tbl;
  158586. tbl = (JQUANT_TBL *)
  158587. (*cinfo->mem->alloc_small) (cinfo, JPOOL_PERMANENT, SIZEOF(JQUANT_TBL));
  158588. tbl->sent_table = FALSE; /* make sure this is false in any new table */
  158589. return tbl;
  158590. }
  158591. GLOBAL(JHUFF_TBL *)
  158592. jpeg_alloc_huff_table (j_common_ptr cinfo)
  158593. {
  158594. JHUFF_TBL *tbl;
  158595. tbl = (JHUFF_TBL *)
  158596. (*cinfo->mem->alloc_small) (cinfo, JPOOL_PERMANENT, SIZEOF(JHUFF_TBL));
  158597. tbl->sent_table = FALSE; /* make sure this is false in any new table */
  158598. return tbl;
  158599. }
  158600. /********* End of inlined file: jcomapi.c *********/
  158601. /********* Start of inlined file: jcparam.c *********/
  158602. #define JPEG_INTERNALS
  158603. /*
  158604. * Quantization table setup routines
  158605. */
  158606. GLOBAL(void)
  158607. jpeg_add_quant_table (j_compress_ptr cinfo, int which_tbl,
  158608. const unsigned int *basic_table,
  158609. int scale_factor, boolean force_baseline)
  158610. /* Define a quantization table equal to the basic_table times
  158611. * a scale factor (given as a percentage).
  158612. * If force_baseline is TRUE, the computed quantization table entries
  158613. * are limited to 1..255 for JPEG baseline compatibility.
  158614. */
  158615. {
  158616. JQUANT_TBL ** qtblptr;
  158617. int i;
  158618. long temp;
  158619. /* Safety check to ensure start_compress not called yet. */
  158620. if (cinfo->global_state != CSTATE_START)
  158621. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  158622. if (which_tbl < 0 || which_tbl >= NUM_QUANT_TBLS)
  158623. ERREXIT1(cinfo, JERR_DQT_INDEX, which_tbl);
  158624. qtblptr = & cinfo->quant_tbl_ptrs[which_tbl];
  158625. if (*qtblptr == NULL)
  158626. *qtblptr = jpeg_alloc_quant_table((j_common_ptr) cinfo);
  158627. for (i = 0; i < DCTSIZE2; i++) {
  158628. temp = ((long) basic_table[i] * scale_factor + 50L) / 100L;
  158629. /* limit the values to the valid range */
  158630. if (temp <= 0L) temp = 1L;
  158631. if (temp > 32767L) temp = 32767L; /* max quantizer needed for 12 bits */
  158632. if (force_baseline && temp > 255L)
  158633. temp = 255L; /* limit to baseline range if requested */
  158634. (*qtblptr)->quantval[i] = (UINT16) temp;
  158635. }
  158636. /* Initialize sent_table FALSE so table will be written to JPEG file. */
  158637. (*qtblptr)->sent_table = FALSE;
  158638. }
  158639. GLOBAL(void)
  158640. jpeg_set_linear_quality (j_compress_ptr cinfo, int scale_factor,
  158641. boolean force_baseline)
  158642. /* Set or change the 'quality' (quantization) setting, using default tables
  158643. * and a straight percentage-scaling quality scale. In most cases it's better
  158644. * to use jpeg_set_quality (below); this entry point is provided for
  158645. * applications that insist on a linear percentage scaling.
  158646. */
  158647. {
  158648. /* These are the sample quantization tables given in JPEG spec section K.1.
  158649. * The spec says that the values given produce "good" quality, and
  158650. * when divided by 2, "very good" quality.
  158651. */
  158652. static const unsigned int std_luminance_quant_tbl[DCTSIZE2] = {
  158653. 16, 11, 10, 16, 24, 40, 51, 61,
  158654. 12, 12, 14, 19, 26, 58, 60, 55,
  158655. 14, 13, 16, 24, 40, 57, 69, 56,
  158656. 14, 17, 22, 29, 51, 87, 80, 62,
  158657. 18, 22, 37, 56, 68, 109, 103, 77,
  158658. 24, 35, 55, 64, 81, 104, 113, 92,
  158659. 49, 64, 78, 87, 103, 121, 120, 101,
  158660. 72, 92, 95, 98, 112, 100, 103, 99
  158661. };
  158662. static const unsigned int std_chrominance_quant_tbl[DCTSIZE2] = {
  158663. 17, 18, 24, 47, 99, 99, 99, 99,
  158664. 18, 21, 26, 66, 99, 99, 99, 99,
  158665. 24, 26, 56, 99, 99, 99, 99, 99,
  158666. 47, 66, 99, 99, 99, 99, 99, 99,
  158667. 99, 99, 99, 99, 99, 99, 99, 99,
  158668. 99, 99, 99, 99, 99, 99, 99, 99,
  158669. 99, 99, 99, 99, 99, 99, 99, 99,
  158670. 99, 99, 99, 99, 99, 99, 99, 99
  158671. };
  158672. /* Set up two quantization tables using the specified scaling */
  158673. jpeg_add_quant_table(cinfo, 0, std_luminance_quant_tbl,
  158674. scale_factor, force_baseline);
  158675. jpeg_add_quant_table(cinfo, 1, std_chrominance_quant_tbl,
  158676. scale_factor, force_baseline);
  158677. }
  158678. GLOBAL(int)
  158679. jpeg_quality_scaling (int quality)
  158680. /* Convert a user-specified quality rating to a percentage scaling factor
  158681. * for an underlying quantization table, using our recommended scaling curve.
  158682. * The input 'quality' factor should be 0 (terrible) to 100 (very good).
  158683. */
  158684. {
  158685. /* Safety limit on quality factor. Convert 0 to 1 to avoid zero divide. */
  158686. if (quality <= 0) quality = 1;
  158687. if (quality > 100) quality = 100;
  158688. /* The basic table is used as-is (scaling 100) for a quality of 50.
  158689. * Qualities 50..100 are converted to scaling percentage 200 - 2*Q;
  158690. * note that at Q=100 the scaling is 0, which will cause jpeg_add_quant_table
  158691. * to make all the table entries 1 (hence, minimum quantization loss).
  158692. * Qualities 1..50 are converted to scaling percentage 5000/Q.
  158693. */
  158694. if (quality < 50)
  158695. quality = 5000 / quality;
  158696. else
  158697. quality = 200 - quality*2;
  158698. return quality;
  158699. }
  158700. GLOBAL(void)
  158701. jpeg_set_quality (j_compress_ptr cinfo, int quality, boolean force_baseline)
  158702. /* Set or change the 'quality' (quantization) setting, using default tables.
  158703. * This is the standard quality-adjusting entry point for typical user
  158704. * interfaces; only those who want detailed control over quantization tables
  158705. * would use the preceding three routines directly.
  158706. */
  158707. {
  158708. /* Convert user 0-100 rating to percentage scaling */
  158709. quality = jpeg_quality_scaling(quality);
  158710. /* Set up standard quality tables */
  158711. jpeg_set_linear_quality(cinfo, quality, force_baseline);
  158712. }
  158713. /*
  158714. * Huffman table setup routines
  158715. */
  158716. LOCAL(void)
  158717. add_huff_table (j_compress_ptr cinfo,
  158718. JHUFF_TBL **htblptr, const UINT8 *bits, const UINT8 *val)
  158719. /* Define a Huffman table */
  158720. {
  158721. int nsymbols, len;
  158722. if (*htblptr == NULL)
  158723. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  158724. /* Copy the number-of-symbols-of-each-code-length counts */
  158725. MEMCOPY((*htblptr)->bits, bits, SIZEOF((*htblptr)->bits));
  158726. /* Validate the counts. We do this here mainly so we can copy the right
  158727. * number of symbols from the val[] array, without risking marching off
  158728. * the end of memory. jchuff.c will do a more thorough test later.
  158729. */
  158730. nsymbols = 0;
  158731. for (len = 1; len <= 16; len++)
  158732. nsymbols += bits[len];
  158733. if (nsymbols < 1 || nsymbols > 256)
  158734. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  158735. MEMCOPY((*htblptr)->huffval, val, nsymbols * SIZEOF(UINT8));
  158736. /* Initialize sent_table FALSE so table will be written to JPEG file. */
  158737. (*htblptr)->sent_table = FALSE;
  158738. }
  158739. LOCAL(void)
  158740. std_huff_tables (j_compress_ptr cinfo)
  158741. /* Set up the standard Huffman tables (cf. JPEG standard section K.3) */
  158742. /* IMPORTANT: these are only valid for 8-bit data precision! */
  158743. {
  158744. static const UINT8 bits_dc_luminance[17] =
  158745. { /* 0-base */ 0, 0, 1, 5, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0 };
  158746. static const UINT8 val_dc_luminance[] =
  158747. { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
  158748. static const UINT8 bits_dc_chrominance[17] =
  158749. { /* 0-base */ 0, 0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0 };
  158750. static const UINT8 val_dc_chrominance[] =
  158751. { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
  158752. static const UINT8 bits_ac_luminance[17] =
  158753. { /* 0-base */ 0, 0, 2, 1, 3, 3, 2, 4, 3, 5, 5, 4, 4, 0, 0, 1, 0x7d };
  158754. static const UINT8 val_ac_luminance[] =
  158755. { 0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12,
  158756. 0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07,
  158757. 0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xa1, 0x08,
  158758. 0x23, 0x42, 0xb1, 0xc1, 0x15, 0x52, 0xd1, 0xf0,
  158759. 0x24, 0x33, 0x62, 0x72, 0x82, 0x09, 0x0a, 0x16,
  158760. 0x17, 0x18, 0x19, 0x1a, 0x25, 0x26, 0x27, 0x28,
  158761. 0x29, 0x2a, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39,
  158762. 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49,
  158763. 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59,
  158764. 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69,
  158765. 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79,
  158766. 0x7a, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89,
  158767. 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98,
  158768. 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
  158769. 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6,
  158770. 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5,
  158771. 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4,
  158772. 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe1, 0xe2,
  158773. 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea,
  158774. 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
  158775. 0xf9, 0xfa };
  158776. static const UINT8 bits_ac_chrominance[17] =
  158777. { /* 0-base */ 0, 0, 2, 1, 2, 4, 4, 3, 4, 7, 5, 4, 4, 0, 1, 2, 0x77 };
  158778. static const UINT8 val_ac_chrominance[] =
  158779. { 0x00, 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21,
  158780. 0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71,
  158781. 0x13, 0x22, 0x32, 0x81, 0x08, 0x14, 0x42, 0x91,
  158782. 0xa1, 0xb1, 0xc1, 0x09, 0x23, 0x33, 0x52, 0xf0,
  158783. 0x15, 0x62, 0x72, 0xd1, 0x0a, 0x16, 0x24, 0x34,
  158784. 0xe1, 0x25, 0xf1, 0x17, 0x18, 0x19, 0x1a, 0x26,
  158785. 0x27, 0x28, 0x29, 0x2a, 0x35, 0x36, 0x37, 0x38,
  158786. 0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48,
  158787. 0x49, 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58,
  158788. 0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68,
  158789. 0x69, 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78,
  158790. 0x79, 0x7a, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
  158791. 0x88, 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96,
  158792. 0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5,
  158793. 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4,
  158794. 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3,
  158795. 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2,
  158796. 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda,
  158797. 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9,
  158798. 0xea, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
  158799. 0xf9, 0xfa };
  158800. add_huff_table(cinfo, &cinfo->dc_huff_tbl_ptrs[0],
  158801. bits_dc_luminance, val_dc_luminance);
  158802. add_huff_table(cinfo, &cinfo->ac_huff_tbl_ptrs[0],
  158803. bits_ac_luminance, val_ac_luminance);
  158804. add_huff_table(cinfo, &cinfo->dc_huff_tbl_ptrs[1],
  158805. bits_dc_chrominance, val_dc_chrominance);
  158806. add_huff_table(cinfo, &cinfo->ac_huff_tbl_ptrs[1],
  158807. bits_ac_chrominance, val_ac_chrominance);
  158808. }
  158809. /*
  158810. * Default parameter setup for compression.
  158811. *
  158812. * Applications that don't choose to use this routine must do their
  158813. * own setup of all these parameters. Alternately, you can call this
  158814. * to establish defaults and then alter parameters selectively. This
  158815. * is the recommended approach since, if we add any new parameters,
  158816. * your code will still work (they'll be set to reasonable defaults).
  158817. */
  158818. GLOBAL(void)
  158819. jpeg_set_defaults (j_compress_ptr cinfo)
  158820. {
  158821. int i;
  158822. /* Safety check to ensure start_compress not called yet. */
  158823. if (cinfo->global_state != CSTATE_START)
  158824. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  158825. /* Allocate comp_info array large enough for maximum component count.
  158826. * Array is made permanent in case application wants to compress
  158827. * multiple images at same param settings.
  158828. */
  158829. if (cinfo->comp_info == NULL)
  158830. cinfo->comp_info = (jpeg_component_info *)
  158831. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  158832. MAX_COMPONENTS * SIZEOF(jpeg_component_info));
  158833. /* Initialize everything not dependent on the color space */
  158834. cinfo->data_precision = BITS_IN_JSAMPLE;
  158835. /* Set up two quantization tables using default quality of 75 */
  158836. jpeg_set_quality(cinfo, 75, TRUE);
  158837. /* Set up two Huffman tables */
  158838. std_huff_tables(cinfo);
  158839. /* Initialize default arithmetic coding conditioning */
  158840. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  158841. cinfo->arith_dc_L[i] = 0;
  158842. cinfo->arith_dc_U[i] = 1;
  158843. cinfo->arith_ac_K[i] = 5;
  158844. }
  158845. /* Default is no multiple-scan output */
  158846. cinfo->scan_info = NULL;
  158847. cinfo->num_scans = 0;
  158848. /* Expect normal source image, not raw downsampled data */
  158849. cinfo->raw_data_in = FALSE;
  158850. /* Use Huffman coding, not arithmetic coding, by default */
  158851. cinfo->arith_code = FALSE;
  158852. /* By default, don't do extra passes to optimize entropy coding */
  158853. cinfo->optimize_coding = FALSE;
  158854. /* The standard Huffman tables are only valid for 8-bit data precision.
  158855. * If the precision is higher, force optimization on so that usable
  158856. * tables will be computed. This test can be removed if default tables
  158857. * are supplied that are valid for the desired precision.
  158858. */
  158859. if (cinfo->data_precision > 8)
  158860. cinfo->optimize_coding = TRUE;
  158861. /* By default, use the simpler non-cosited sampling alignment */
  158862. cinfo->CCIR601_sampling = FALSE;
  158863. /* No input smoothing */
  158864. cinfo->smoothing_factor = 0;
  158865. /* DCT algorithm preference */
  158866. cinfo->dct_method = JDCT_DEFAULT;
  158867. /* No restart markers */
  158868. cinfo->restart_interval = 0;
  158869. cinfo->restart_in_rows = 0;
  158870. /* Fill in default JFIF marker parameters. Note that whether the marker
  158871. * will actually be written is determined by jpeg_set_colorspace.
  158872. *
  158873. * By default, the library emits JFIF version code 1.01.
  158874. * An application that wants to emit JFIF 1.02 extension markers should set
  158875. * JFIF_minor_version to 2. We could probably get away with just defaulting
  158876. * to 1.02, but there may still be some decoders in use that will complain
  158877. * about that; saying 1.01 should minimize compatibility problems.
  158878. */
  158879. cinfo->JFIF_major_version = 1; /* Default JFIF version = 1.01 */
  158880. cinfo->JFIF_minor_version = 1;
  158881. cinfo->density_unit = 0; /* Pixel size is unknown by default */
  158882. cinfo->X_density = 1; /* Pixel aspect ratio is square by default */
  158883. cinfo->Y_density = 1;
  158884. /* Choose JPEG colorspace based on input space, set defaults accordingly */
  158885. jpeg_default_colorspace(cinfo);
  158886. }
  158887. /*
  158888. * Select an appropriate JPEG colorspace for in_color_space.
  158889. */
  158890. GLOBAL(void)
  158891. jpeg_default_colorspace (j_compress_ptr cinfo)
  158892. {
  158893. switch (cinfo->in_color_space) {
  158894. case JCS_GRAYSCALE:
  158895. jpeg_set_colorspace(cinfo, JCS_GRAYSCALE);
  158896. break;
  158897. case JCS_RGB:
  158898. jpeg_set_colorspace(cinfo, JCS_YCbCr);
  158899. break;
  158900. case JCS_YCbCr:
  158901. jpeg_set_colorspace(cinfo, JCS_YCbCr);
  158902. break;
  158903. case JCS_CMYK:
  158904. jpeg_set_colorspace(cinfo, JCS_CMYK); /* By default, no translation */
  158905. break;
  158906. case JCS_YCCK:
  158907. jpeg_set_colorspace(cinfo, JCS_YCCK);
  158908. break;
  158909. case JCS_UNKNOWN:
  158910. jpeg_set_colorspace(cinfo, JCS_UNKNOWN);
  158911. break;
  158912. default:
  158913. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  158914. }
  158915. }
  158916. /*
  158917. * Set the JPEG colorspace, and choose colorspace-dependent default values.
  158918. */
  158919. GLOBAL(void)
  158920. jpeg_set_colorspace (j_compress_ptr cinfo, J_COLOR_SPACE colorspace)
  158921. {
  158922. jpeg_component_info * compptr;
  158923. int ci;
  158924. #define SET_COMP(index,id,hsamp,vsamp,quant,dctbl,actbl) \
  158925. (compptr = &cinfo->comp_info[index], \
  158926. compptr->component_id = (id), \
  158927. compptr->h_samp_factor = (hsamp), \
  158928. compptr->v_samp_factor = (vsamp), \
  158929. compptr->quant_tbl_no = (quant), \
  158930. compptr->dc_tbl_no = (dctbl), \
  158931. compptr->ac_tbl_no = (actbl) )
  158932. /* Safety check to ensure start_compress not called yet. */
  158933. if (cinfo->global_state != CSTATE_START)
  158934. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  158935. /* For all colorspaces, we use Q and Huff tables 0 for luminance components,
  158936. * tables 1 for chrominance components.
  158937. */
  158938. cinfo->jpeg_color_space = colorspace;
  158939. cinfo->write_JFIF_header = FALSE; /* No marker for non-JFIF colorspaces */
  158940. cinfo->write_Adobe_marker = FALSE; /* write no Adobe marker by default */
  158941. switch (colorspace) {
  158942. case JCS_GRAYSCALE:
  158943. cinfo->write_JFIF_header = TRUE; /* Write a JFIF marker */
  158944. cinfo->num_components = 1;
  158945. /* JFIF specifies component ID 1 */
  158946. SET_COMP(0, 1, 1,1, 0, 0,0);
  158947. break;
  158948. case JCS_RGB:
  158949. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag RGB */
  158950. cinfo->num_components = 3;
  158951. SET_COMP(0, 0x52 /* 'R' */, 1,1, 0, 0,0);
  158952. SET_COMP(1, 0x47 /* 'G' */, 1,1, 0, 0,0);
  158953. SET_COMP(2, 0x42 /* 'B' */, 1,1, 0, 0,0);
  158954. break;
  158955. case JCS_YCbCr:
  158956. cinfo->write_JFIF_header = TRUE; /* Write a JFIF marker */
  158957. cinfo->num_components = 3;
  158958. /* JFIF specifies component IDs 1,2,3 */
  158959. /* We default to 2x2 subsamples of chrominance */
  158960. SET_COMP(0, 1, 2,2, 0, 0,0);
  158961. SET_COMP(1, 2, 1,1, 1, 1,1);
  158962. SET_COMP(2, 3, 1,1, 1, 1,1);
  158963. break;
  158964. case JCS_CMYK:
  158965. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag CMYK */
  158966. cinfo->num_components = 4;
  158967. SET_COMP(0, 0x43 /* 'C' */, 1,1, 0, 0,0);
  158968. SET_COMP(1, 0x4D /* 'M' */, 1,1, 0, 0,0);
  158969. SET_COMP(2, 0x59 /* 'Y' */, 1,1, 0, 0,0);
  158970. SET_COMP(3, 0x4B /* 'K' */, 1,1, 0, 0,0);
  158971. break;
  158972. case JCS_YCCK:
  158973. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag YCCK */
  158974. cinfo->num_components = 4;
  158975. SET_COMP(0, 1, 2,2, 0, 0,0);
  158976. SET_COMP(1, 2, 1,1, 1, 1,1);
  158977. SET_COMP(2, 3, 1,1, 1, 1,1);
  158978. SET_COMP(3, 4, 2,2, 0, 0,0);
  158979. break;
  158980. case JCS_UNKNOWN:
  158981. cinfo->num_components = cinfo->input_components;
  158982. if (cinfo->num_components < 1 || cinfo->num_components > MAX_COMPONENTS)
  158983. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  158984. MAX_COMPONENTS);
  158985. for (ci = 0; ci < cinfo->num_components; ci++) {
  158986. SET_COMP(ci, ci, 1,1, 0, 0,0);
  158987. }
  158988. break;
  158989. default:
  158990. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  158991. }
  158992. }
  158993. #ifdef C_PROGRESSIVE_SUPPORTED
  158994. LOCAL(jpeg_scan_info *)
  158995. fill_a_scan (jpeg_scan_info * scanptr, int ci,
  158996. int Ss, int Se, int Ah, int Al)
  158997. /* Support routine: generate one scan for specified component */
  158998. {
  158999. scanptr->comps_in_scan = 1;
  159000. scanptr->component_index[0] = ci;
  159001. scanptr->Ss = Ss;
  159002. scanptr->Se = Se;
  159003. scanptr->Ah = Ah;
  159004. scanptr->Al = Al;
  159005. scanptr++;
  159006. return scanptr;
  159007. }
  159008. LOCAL(jpeg_scan_info *)
  159009. fill_scans (jpeg_scan_info * scanptr, int ncomps,
  159010. int Ss, int Se, int Ah, int Al)
  159011. /* Support routine: generate one scan for each component */
  159012. {
  159013. int ci;
  159014. for (ci = 0; ci < ncomps; ci++) {
  159015. scanptr->comps_in_scan = 1;
  159016. scanptr->component_index[0] = ci;
  159017. scanptr->Ss = Ss;
  159018. scanptr->Se = Se;
  159019. scanptr->Ah = Ah;
  159020. scanptr->Al = Al;
  159021. scanptr++;
  159022. }
  159023. return scanptr;
  159024. }
  159025. LOCAL(jpeg_scan_info *)
  159026. fill_dc_scans (jpeg_scan_info * scanptr, int ncomps, int Ah, int Al)
  159027. /* Support routine: generate interleaved DC scan if possible, else N scans */
  159028. {
  159029. int ci;
  159030. if (ncomps <= MAX_COMPS_IN_SCAN) {
  159031. /* Single interleaved DC scan */
  159032. scanptr->comps_in_scan = ncomps;
  159033. for (ci = 0; ci < ncomps; ci++)
  159034. scanptr->component_index[ci] = ci;
  159035. scanptr->Ss = scanptr->Se = 0;
  159036. scanptr->Ah = Ah;
  159037. scanptr->Al = Al;
  159038. scanptr++;
  159039. } else {
  159040. /* Noninterleaved DC scan for each component */
  159041. scanptr = fill_scans(scanptr, ncomps, 0, 0, Ah, Al);
  159042. }
  159043. return scanptr;
  159044. }
  159045. /*
  159046. * Create a recommended progressive-JPEG script.
  159047. * cinfo->num_components and cinfo->jpeg_color_space must be correct.
  159048. */
  159049. GLOBAL(void)
  159050. jpeg_simple_progression (j_compress_ptr cinfo)
  159051. {
  159052. int ncomps = cinfo->num_components;
  159053. int nscans;
  159054. jpeg_scan_info * scanptr;
  159055. /* Safety check to ensure start_compress not called yet. */
  159056. if (cinfo->global_state != CSTATE_START)
  159057. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  159058. /* Figure space needed for script. Calculation must match code below! */
  159059. if (ncomps == 3 && cinfo->jpeg_color_space == JCS_YCbCr) {
  159060. /* Custom script for YCbCr color images. */
  159061. nscans = 10;
  159062. } else {
  159063. /* All-purpose script for other color spaces. */
  159064. if (ncomps > MAX_COMPS_IN_SCAN)
  159065. nscans = 6 * ncomps; /* 2 DC + 4 AC scans per component */
  159066. else
  159067. nscans = 2 + 4 * ncomps; /* 2 DC scans; 4 AC scans per component */
  159068. }
  159069. /* Allocate space for script.
  159070. * We need to put it in the permanent pool in case the application performs
  159071. * multiple compressions without changing the settings. To avoid a memory
  159072. * leak if jpeg_simple_progression is called repeatedly for the same JPEG
  159073. * object, we try to re-use previously allocated space, and we allocate
  159074. * enough space to handle YCbCr even if initially asked for grayscale.
  159075. */
  159076. if (cinfo->script_space == NULL || cinfo->script_space_size < nscans) {
  159077. cinfo->script_space_size = MAX(nscans, 10);
  159078. cinfo->script_space = (jpeg_scan_info *)
  159079. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  159080. cinfo->script_space_size * SIZEOF(jpeg_scan_info));
  159081. }
  159082. scanptr = cinfo->script_space;
  159083. cinfo->scan_info = scanptr;
  159084. cinfo->num_scans = nscans;
  159085. if (ncomps == 3 && cinfo->jpeg_color_space == JCS_YCbCr) {
  159086. /* Custom script for YCbCr color images. */
  159087. /* Initial DC scan */
  159088. scanptr = fill_dc_scans(scanptr, ncomps, 0, 1);
  159089. /* Initial AC scan: get some luma data out in a hurry */
  159090. scanptr = fill_a_scan(scanptr, 0, 1, 5, 0, 2);
  159091. /* Chroma data is too small to be worth expending many scans on */
  159092. scanptr = fill_a_scan(scanptr, 2, 1, 63, 0, 1);
  159093. scanptr = fill_a_scan(scanptr, 1, 1, 63, 0, 1);
  159094. /* Complete spectral selection for luma AC */
  159095. scanptr = fill_a_scan(scanptr, 0, 6, 63, 0, 2);
  159096. /* Refine next bit of luma AC */
  159097. scanptr = fill_a_scan(scanptr, 0, 1, 63, 2, 1);
  159098. /* Finish DC successive approximation */
  159099. scanptr = fill_dc_scans(scanptr, ncomps, 1, 0);
  159100. /* Finish AC successive approximation */
  159101. scanptr = fill_a_scan(scanptr, 2, 1, 63, 1, 0);
  159102. scanptr = fill_a_scan(scanptr, 1, 1, 63, 1, 0);
  159103. /* Luma bottom bit comes last since it's usually largest scan */
  159104. scanptr = fill_a_scan(scanptr, 0, 1, 63, 1, 0);
  159105. } else {
  159106. /* All-purpose script for other color spaces. */
  159107. /* Successive approximation first pass */
  159108. scanptr = fill_dc_scans(scanptr, ncomps, 0, 1);
  159109. scanptr = fill_scans(scanptr, ncomps, 1, 5, 0, 2);
  159110. scanptr = fill_scans(scanptr, ncomps, 6, 63, 0, 2);
  159111. /* Successive approximation second pass */
  159112. scanptr = fill_scans(scanptr, ncomps, 1, 63, 2, 1);
  159113. /* Successive approximation final pass */
  159114. scanptr = fill_dc_scans(scanptr, ncomps, 1, 0);
  159115. scanptr = fill_scans(scanptr, ncomps, 1, 63, 1, 0);
  159116. }
  159117. }
  159118. #endif /* C_PROGRESSIVE_SUPPORTED */
  159119. /********* End of inlined file: jcparam.c *********/
  159120. /********* Start of inlined file: jcphuff.c *********/
  159121. #define JPEG_INTERNALS
  159122. #ifdef C_PROGRESSIVE_SUPPORTED
  159123. /* Expanded entropy encoder object for progressive Huffman encoding. */
  159124. typedef struct {
  159125. struct jpeg_entropy_encoder pub; /* public fields */
  159126. /* Mode flag: TRUE for optimization, FALSE for actual data output */
  159127. boolean gather_statistics;
  159128. /* Bit-level coding status.
  159129. * next_output_byte/free_in_buffer are local copies of cinfo->dest fields.
  159130. */
  159131. JOCTET * next_output_byte; /* => next byte to write in buffer */
  159132. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  159133. INT32 put_buffer; /* current bit-accumulation buffer */
  159134. int put_bits; /* # of bits now in it */
  159135. j_compress_ptr cinfo; /* link to cinfo (needed for dump_buffer) */
  159136. /* Coding status for DC components */
  159137. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  159138. /* Coding status for AC components */
  159139. int ac_tbl_no; /* the table number of the single component */
  159140. unsigned int EOBRUN; /* run length of EOBs */
  159141. unsigned int BE; /* # of buffered correction bits before MCU */
  159142. char * bit_buffer; /* buffer for correction bits (1 per char) */
  159143. /* packing correction bits tightly would save some space but cost time... */
  159144. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  159145. int next_restart_num; /* next restart number to write (0-7) */
  159146. /* Pointers to derived tables (these workspaces have image lifespan).
  159147. * Since any one scan codes only DC or only AC, we only need one set
  159148. * of tables, not one for DC and one for AC.
  159149. */
  159150. c_derived_tbl * derived_tbls[NUM_HUFF_TBLS];
  159151. /* Statistics tables for optimization; again, one set is enough */
  159152. long * count_ptrs[NUM_HUFF_TBLS];
  159153. } phuff_entropy_encoder;
  159154. typedef phuff_entropy_encoder * phuff_entropy_ptr;
  159155. /* MAX_CORR_BITS is the number of bits the AC refinement correction-bit
  159156. * buffer can hold. Larger sizes may slightly improve compression, but
  159157. * 1000 is already well into the realm of overkill.
  159158. * The minimum safe size is 64 bits.
  159159. */
  159160. #define MAX_CORR_BITS 1000 /* Max # of correction bits I can buffer */
  159161. /* IRIGHT_SHIFT is like RIGHT_SHIFT, but works on int rather than INT32.
  159162. * We assume that int right shift is unsigned if INT32 right shift is,
  159163. * which should be safe.
  159164. */
  159165. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  159166. #define ISHIFT_TEMPS int ishift_temp;
  159167. #define IRIGHT_SHIFT(x,shft) \
  159168. ((ishift_temp = (x)) < 0 ? \
  159169. (ishift_temp >> (shft)) | ((~0) << (16-(shft))) : \
  159170. (ishift_temp >> (shft)))
  159171. #else
  159172. #define ISHIFT_TEMPS
  159173. #define IRIGHT_SHIFT(x,shft) ((x) >> (shft))
  159174. #endif
  159175. /* Forward declarations */
  159176. METHODDEF(boolean) encode_mcu_DC_first JPP((j_compress_ptr cinfo,
  159177. JBLOCKROW *MCU_data));
  159178. METHODDEF(boolean) encode_mcu_AC_first JPP((j_compress_ptr cinfo,
  159179. JBLOCKROW *MCU_data));
  159180. METHODDEF(boolean) encode_mcu_DC_refine JPP((j_compress_ptr cinfo,
  159181. JBLOCKROW *MCU_data));
  159182. METHODDEF(boolean) encode_mcu_AC_refine JPP((j_compress_ptr cinfo,
  159183. JBLOCKROW *MCU_data));
  159184. METHODDEF(void) finish_pass_phuff JPP((j_compress_ptr cinfo));
  159185. METHODDEF(void) finish_pass_gather_phuff JPP((j_compress_ptr cinfo));
  159186. /*
  159187. * Initialize for a Huffman-compressed scan using progressive JPEG.
  159188. */
  159189. METHODDEF(void)
  159190. start_pass_phuff (j_compress_ptr cinfo, boolean gather_statistics)
  159191. {
  159192. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  159193. boolean is_DC_band;
  159194. int ci, tbl;
  159195. jpeg_component_info * compptr;
  159196. entropy->cinfo = cinfo;
  159197. entropy->gather_statistics = gather_statistics;
  159198. is_DC_band = (cinfo->Ss == 0);
  159199. /* We assume jcmaster.c already validated the scan parameters. */
  159200. /* Select execution routines */
  159201. if (cinfo->Ah == 0) {
  159202. if (is_DC_band)
  159203. entropy->pub.encode_mcu = encode_mcu_DC_first;
  159204. else
  159205. entropy->pub.encode_mcu = encode_mcu_AC_first;
  159206. } else {
  159207. if (is_DC_band)
  159208. entropy->pub.encode_mcu = encode_mcu_DC_refine;
  159209. else {
  159210. entropy->pub.encode_mcu = encode_mcu_AC_refine;
  159211. /* AC refinement needs a correction bit buffer */
  159212. if (entropy->bit_buffer == NULL)
  159213. entropy->bit_buffer = (char *)
  159214. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  159215. MAX_CORR_BITS * SIZEOF(char));
  159216. }
  159217. }
  159218. if (gather_statistics)
  159219. entropy->pub.finish_pass = finish_pass_gather_phuff;
  159220. else
  159221. entropy->pub.finish_pass = finish_pass_phuff;
  159222. /* Only DC coefficients may be interleaved, so cinfo->comps_in_scan = 1
  159223. * for AC coefficients.
  159224. */
  159225. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  159226. compptr = cinfo->cur_comp_info[ci];
  159227. /* Initialize DC predictions to 0 */
  159228. entropy->last_dc_val[ci] = 0;
  159229. /* Get table index */
  159230. if (is_DC_band) {
  159231. if (cinfo->Ah != 0) /* DC refinement needs no table */
  159232. continue;
  159233. tbl = compptr->dc_tbl_no;
  159234. } else {
  159235. entropy->ac_tbl_no = tbl = compptr->ac_tbl_no;
  159236. }
  159237. if (gather_statistics) {
  159238. /* Check for invalid table index */
  159239. /* (make_c_derived_tbl does this in the other path) */
  159240. if (tbl < 0 || tbl >= NUM_HUFF_TBLS)
  159241. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tbl);
  159242. /* Allocate and zero the statistics tables */
  159243. /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
  159244. if (entropy->count_ptrs[tbl] == NULL)
  159245. entropy->count_ptrs[tbl] = (long *)
  159246. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  159247. 257 * SIZEOF(long));
  159248. MEMZERO(entropy->count_ptrs[tbl], 257 * SIZEOF(long));
  159249. } else {
  159250. /* Compute derived values for Huffman table */
  159251. /* We may do this more than once for a table, but it's not expensive */
  159252. jpeg_make_c_derived_tbl(cinfo, is_DC_band, tbl,
  159253. & entropy->derived_tbls[tbl]);
  159254. }
  159255. }
  159256. /* Initialize AC stuff */
  159257. entropy->EOBRUN = 0;
  159258. entropy->BE = 0;
  159259. /* Initialize bit buffer to empty */
  159260. entropy->put_buffer = 0;
  159261. entropy->put_bits = 0;
  159262. /* Initialize restart stuff */
  159263. entropy->restarts_to_go = cinfo->restart_interval;
  159264. entropy->next_restart_num = 0;
  159265. }
  159266. /* Outputting bytes to the file.
  159267. * NB: these must be called only when actually outputting,
  159268. * that is, entropy->gather_statistics == FALSE.
  159269. */
  159270. /* Emit a byte */
  159271. #define emit_byte(entropy,val) \
  159272. { *(entropy)->next_output_byte++ = (JOCTET) (val); \
  159273. if (--(entropy)->free_in_buffer == 0) \
  159274. dump_buffer_p(entropy); }
  159275. LOCAL(void)
  159276. dump_buffer_p (phuff_entropy_ptr entropy)
  159277. /* Empty the output buffer; we do not support suspension in this module. */
  159278. {
  159279. struct jpeg_destination_mgr * dest = entropy->cinfo->dest;
  159280. if (! (*dest->empty_output_buffer) (entropy->cinfo))
  159281. ERREXIT(entropy->cinfo, JERR_CANT_SUSPEND);
  159282. /* After a successful buffer dump, must reset buffer pointers */
  159283. entropy->next_output_byte = dest->next_output_byte;
  159284. entropy->free_in_buffer = dest->free_in_buffer;
  159285. }
  159286. /* Outputting bits to the file */
  159287. /* Only the right 24 bits of put_buffer are used; the valid bits are
  159288. * left-justified in this part. At most 16 bits can be passed to emit_bits
  159289. * in one call, and we never retain more than 7 bits in put_buffer
  159290. * between calls, so 24 bits are sufficient.
  159291. */
  159292. INLINE
  159293. LOCAL(void)
  159294. emit_bits_p (phuff_entropy_ptr entropy, unsigned int code, int size)
  159295. /* Emit some bits, unless we are in gather mode */
  159296. {
  159297. /* This routine is heavily used, so it's worth coding tightly. */
  159298. register INT32 put_buffer = (INT32) code;
  159299. register int put_bits = entropy->put_bits;
  159300. /* if size is 0, caller used an invalid Huffman table entry */
  159301. if (size == 0)
  159302. ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE);
  159303. if (entropy->gather_statistics)
  159304. return; /* do nothing if we're only getting stats */
  159305. put_buffer &= (((INT32) 1)<<size) - 1; /* mask off any extra bits in code */
  159306. put_bits += size; /* new number of bits in buffer */
  159307. put_buffer <<= 24 - put_bits; /* align incoming bits */
  159308. put_buffer |= entropy->put_buffer; /* and merge with old buffer contents */
  159309. while (put_bits >= 8) {
  159310. int c = (int) ((put_buffer >> 16) & 0xFF);
  159311. emit_byte(entropy, c);
  159312. if (c == 0xFF) { /* need to stuff a zero byte? */
  159313. emit_byte(entropy, 0);
  159314. }
  159315. put_buffer <<= 8;
  159316. put_bits -= 8;
  159317. }
  159318. entropy->put_buffer = put_buffer; /* update variables */
  159319. entropy->put_bits = put_bits;
  159320. }
  159321. LOCAL(void)
  159322. flush_bits_p (phuff_entropy_ptr entropy)
  159323. {
  159324. emit_bits_p(entropy, 0x7F, 7); /* fill any partial byte with ones */
  159325. entropy->put_buffer = 0; /* and reset bit-buffer to empty */
  159326. entropy->put_bits = 0;
  159327. }
  159328. /*
  159329. * Emit (or just count) a Huffman symbol.
  159330. */
  159331. INLINE
  159332. LOCAL(void)
  159333. emit_symbol (phuff_entropy_ptr entropy, int tbl_no, int symbol)
  159334. {
  159335. if (entropy->gather_statistics)
  159336. entropy->count_ptrs[tbl_no][symbol]++;
  159337. else {
  159338. c_derived_tbl * tbl = entropy->derived_tbls[tbl_no];
  159339. emit_bits_p(entropy, tbl->ehufco[symbol], tbl->ehufsi[symbol]);
  159340. }
  159341. }
  159342. /*
  159343. * Emit bits from a correction bit buffer.
  159344. */
  159345. LOCAL(void)
  159346. emit_buffered_bits (phuff_entropy_ptr entropy, char * bufstart,
  159347. unsigned int nbits)
  159348. {
  159349. if (entropy->gather_statistics)
  159350. return; /* no real work */
  159351. while (nbits > 0) {
  159352. emit_bits_p(entropy, (unsigned int) (*bufstart), 1);
  159353. bufstart++;
  159354. nbits--;
  159355. }
  159356. }
  159357. /*
  159358. * Emit any pending EOBRUN symbol.
  159359. */
  159360. LOCAL(void)
  159361. emit_eobrun (phuff_entropy_ptr entropy)
  159362. {
  159363. register int temp, nbits;
  159364. if (entropy->EOBRUN > 0) { /* if there is any pending EOBRUN */
  159365. temp = entropy->EOBRUN;
  159366. nbits = 0;
  159367. while ((temp >>= 1))
  159368. nbits++;
  159369. /* safety check: shouldn't happen given limited correction-bit buffer */
  159370. if (nbits > 14)
  159371. ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE);
  159372. emit_symbol(entropy, entropy->ac_tbl_no, nbits << 4);
  159373. if (nbits)
  159374. emit_bits_p(entropy, entropy->EOBRUN, nbits);
  159375. entropy->EOBRUN = 0;
  159376. /* Emit any buffered correction bits */
  159377. emit_buffered_bits(entropy, entropy->bit_buffer, entropy->BE);
  159378. entropy->BE = 0;
  159379. }
  159380. }
  159381. /*
  159382. * Emit a restart marker & resynchronize predictions.
  159383. */
  159384. LOCAL(void)
  159385. emit_restart_p (phuff_entropy_ptr entropy, int restart_num)
  159386. {
  159387. int ci;
  159388. emit_eobrun(entropy);
  159389. if (! entropy->gather_statistics) {
  159390. flush_bits_p(entropy);
  159391. emit_byte(entropy, 0xFF);
  159392. emit_byte(entropy, JPEG_RST0 + restart_num);
  159393. }
  159394. if (entropy->cinfo->Ss == 0) {
  159395. /* Re-initialize DC predictions to 0 */
  159396. for (ci = 0; ci < entropy->cinfo->comps_in_scan; ci++)
  159397. entropy->last_dc_val[ci] = 0;
  159398. } else {
  159399. /* Re-initialize all AC-related fields to 0 */
  159400. entropy->EOBRUN = 0;
  159401. entropy->BE = 0;
  159402. }
  159403. }
  159404. /*
  159405. * MCU encoding for DC initial scan (either spectral selection,
  159406. * or first pass of successive approximation).
  159407. */
  159408. METHODDEF(boolean)
  159409. encode_mcu_DC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  159410. {
  159411. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  159412. register int temp, temp2;
  159413. register int nbits;
  159414. int blkn, ci;
  159415. int Al = cinfo->Al;
  159416. JBLOCKROW block;
  159417. jpeg_component_info * compptr;
  159418. ISHIFT_TEMPS
  159419. entropy->next_output_byte = cinfo->dest->next_output_byte;
  159420. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  159421. /* Emit restart marker if needed */
  159422. if (cinfo->restart_interval)
  159423. if (entropy->restarts_to_go == 0)
  159424. emit_restart_p(entropy, entropy->next_restart_num);
  159425. /* Encode the MCU data blocks */
  159426. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  159427. block = MCU_data[blkn];
  159428. ci = cinfo->MCU_membership[blkn];
  159429. compptr = cinfo->cur_comp_info[ci];
  159430. /* Compute the DC value after the required point transform by Al.
  159431. * This is simply an arithmetic right shift.
  159432. */
  159433. temp2 = IRIGHT_SHIFT((int) ((*block)[0]), Al);
  159434. /* DC differences are figured on the point-transformed values. */
  159435. temp = temp2 - entropy->last_dc_val[ci];
  159436. entropy->last_dc_val[ci] = temp2;
  159437. /* Encode the DC coefficient difference per section G.1.2.1 */
  159438. temp2 = temp;
  159439. if (temp < 0) {
  159440. temp = -temp; /* temp is abs value of input */
  159441. /* For a negative input, want temp2 = bitwise complement of abs(input) */
  159442. /* This code assumes we are on a two's complement machine */
  159443. temp2--;
  159444. }
  159445. /* Find the number of bits needed for the magnitude of the coefficient */
  159446. nbits = 0;
  159447. while (temp) {
  159448. nbits++;
  159449. temp >>= 1;
  159450. }
  159451. /* Check for out-of-range coefficient values.
  159452. * Since we're encoding a difference, the range limit is twice as much.
  159453. */
  159454. if (nbits > MAX_COEF_BITS+1)
  159455. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  159456. /* Count/emit the Huffman-coded symbol for the number of bits */
  159457. emit_symbol(entropy, compptr->dc_tbl_no, nbits);
  159458. /* Emit that number of bits of the value, if positive, */
  159459. /* or the complement of its magnitude, if negative. */
  159460. if (nbits) /* emit_bits rejects calls with size 0 */
  159461. emit_bits_p(entropy, (unsigned int) temp2, nbits);
  159462. }
  159463. cinfo->dest->next_output_byte = entropy->next_output_byte;
  159464. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  159465. /* Update restart-interval state too */
  159466. if (cinfo->restart_interval) {
  159467. if (entropy->restarts_to_go == 0) {
  159468. entropy->restarts_to_go = cinfo->restart_interval;
  159469. entropy->next_restart_num++;
  159470. entropy->next_restart_num &= 7;
  159471. }
  159472. entropy->restarts_to_go--;
  159473. }
  159474. return TRUE;
  159475. }
  159476. /*
  159477. * MCU encoding for AC initial scan (either spectral selection,
  159478. * or first pass of successive approximation).
  159479. */
  159480. METHODDEF(boolean)
  159481. encode_mcu_AC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  159482. {
  159483. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  159484. register int temp, temp2;
  159485. register int nbits;
  159486. register int r, k;
  159487. int Se = cinfo->Se;
  159488. int Al = cinfo->Al;
  159489. JBLOCKROW block;
  159490. entropy->next_output_byte = cinfo->dest->next_output_byte;
  159491. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  159492. /* Emit restart marker if needed */
  159493. if (cinfo->restart_interval)
  159494. if (entropy->restarts_to_go == 0)
  159495. emit_restart_p(entropy, entropy->next_restart_num);
  159496. /* Encode the MCU data block */
  159497. block = MCU_data[0];
  159498. /* Encode the AC coefficients per section G.1.2.2, fig. G.3 */
  159499. r = 0; /* r = run length of zeros */
  159500. for (k = cinfo->Ss; k <= Se; k++) {
  159501. if ((temp = (*block)[jpeg_natural_order[k]]) == 0) {
  159502. r++;
  159503. continue;
  159504. }
  159505. /* We must apply the point transform by Al. For AC coefficients this
  159506. * is an integer division with rounding towards 0. To do this portably
  159507. * in C, we shift after obtaining the absolute value; so the code is
  159508. * interwoven with finding the abs value (temp) and output bits (temp2).
  159509. */
  159510. if (temp < 0) {
  159511. temp = -temp; /* temp is abs value of input */
  159512. temp >>= Al; /* apply the point transform */
  159513. /* For a negative coef, want temp2 = bitwise complement of abs(coef) */
  159514. temp2 = ~temp;
  159515. } else {
  159516. temp >>= Al; /* apply the point transform */
  159517. temp2 = temp;
  159518. }
  159519. /* Watch out for case that nonzero coef is zero after point transform */
  159520. if (temp == 0) {
  159521. r++;
  159522. continue;
  159523. }
  159524. /* Emit any pending EOBRUN */
  159525. if (entropy->EOBRUN > 0)
  159526. emit_eobrun(entropy);
  159527. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  159528. while (r > 15) {
  159529. emit_symbol(entropy, entropy->ac_tbl_no, 0xF0);
  159530. r -= 16;
  159531. }
  159532. /* Find the number of bits needed for the magnitude of the coefficient */
  159533. nbits = 1; /* there must be at least one 1 bit */
  159534. while ((temp >>= 1))
  159535. nbits++;
  159536. /* Check for out-of-range coefficient values */
  159537. if (nbits > MAX_COEF_BITS)
  159538. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  159539. /* Count/emit Huffman symbol for run length / number of bits */
  159540. emit_symbol(entropy, entropy->ac_tbl_no, (r << 4) + nbits);
  159541. /* Emit that number of bits of the value, if positive, */
  159542. /* or the complement of its magnitude, if negative. */
  159543. emit_bits_p(entropy, (unsigned int) temp2, nbits);
  159544. r = 0; /* reset zero run length */
  159545. }
  159546. if (r > 0) { /* If there are trailing zeroes, */
  159547. entropy->EOBRUN++; /* count an EOB */
  159548. if (entropy->EOBRUN == 0x7FFF)
  159549. emit_eobrun(entropy); /* force it out to avoid overflow */
  159550. }
  159551. cinfo->dest->next_output_byte = entropy->next_output_byte;
  159552. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  159553. /* Update restart-interval state too */
  159554. if (cinfo->restart_interval) {
  159555. if (entropy->restarts_to_go == 0) {
  159556. entropy->restarts_to_go = cinfo->restart_interval;
  159557. entropy->next_restart_num++;
  159558. entropy->next_restart_num &= 7;
  159559. }
  159560. entropy->restarts_to_go--;
  159561. }
  159562. return TRUE;
  159563. }
  159564. /*
  159565. * MCU encoding for DC successive approximation refinement scan.
  159566. * Note: we assume such scans can be multi-component, although the spec
  159567. * is not very clear on the point.
  159568. */
  159569. METHODDEF(boolean)
  159570. encode_mcu_DC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  159571. {
  159572. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  159573. register int temp;
  159574. int blkn;
  159575. int Al = cinfo->Al;
  159576. JBLOCKROW block;
  159577. entropy->next_output_byte = cinfo->dest->next_output_byte;
  159578. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  159579. /* Emit restart marker if needed */
  159580. if (cinfo->restart_interval)
  159581. if (entropy->restarts_to_go == 0)
  159582. emit_restart_p(entropy, entropy->next_restart_num);
  159583. /* Encode the MCU data blocks */
  159584. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  159585. block = MCU_data[blkn];
  159586. /* We simply emit the Al'th bit of the DC coefficient value. */
  159587. temp = (*block)[0];
  159588. emit_bits_p(entropy, (unsigned int) (temp >> Al), 1);
  159589. }
  159590. cinfo->dest->next_output_byte = entropy->next_output_byte;
  159591. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  159592. /* Update restart-interval state too */
  159593. if (cinfo->restart_interval) {
  159594. if (entropy->restarts_to_go == 0) {
  159595. entropy->restarts_to_go = cinfo->restart_interval;
  159596. entropy->next_restart_num++;
  159597. entropy->next_restart_num &= 7;
  159598. }
  159599. entropy->restarts_to_go--;
  159600. }
  159601. return TRUE;
  159602. }
  159603. /*
  159604. * MCU encoding for AC successive approximation refinement scan.
  159605. */
  159606. METHODDEF(boolean)
  159607. encode_mcu_AC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  159608. {
  159609. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  159610. register int temp;
  159611. register int r, k;
  159612. int EOB;
  159613. char *BR_buffer;
  159614. unsigned int BR;
  159615. int Se = cinfo->Se;
  159616. int Al = cinfo->Al;
  159617. JBLOCKROW block;
  159618. int absvalues[DCTSIZE2];
  159619. entropy->next_output_byte = cinfo->dest->next_output_byte;
  159620. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  159621. /* Emit restart marker if needed */
  159622. if (cinfo->restart_interval)
  159623. if (entropy->restarts_to_go == 0)
  159624. emit_restart_p(entropy, entropy->next_restart_num);
  159625. /* Encode the MCU data block */
  159626. block = MCU_data[0];
  159627. /* It is convenient to make a pre-pass to determine the transformed
  159628. * coefficients' absolute values and the EOB position.
  159629. */
  159630. EOB = 0;
  159631. for (k = cinfo->Ss; k <= Se; k++) {
  159632. temp = (*block)[jpeg_natural_order[k]];
  159633. /* We must apply the point transform by Al. For AC coefficients this
  159634. * is an integer division with rounding towards 0. To do this portably
  159635. * in C, we shift after obtaining the absolute value.
  159636. */
  159637. if (temp < 0)
  159638. temp = -temp; /* temp is abs value of input */
  159639. temp >>= Al; /* apply the point transform */
  159640. absvalues[k] = temp; /* save abs value for main pass */
  159641. if (temp == 1)
  159642. EOB = k; /* EOB = index of last newly-nonzero coef */
  159643. }
  159644. /* Encode the AC coefficients per section G.1.2.3, fig. G.7 */
  159645. r = 0; /* r = run length of zeros */
  159646. BR = 0; /* BR = count of buffered bits added now */
  159647. BR_buffer = entropy->bit_buffer + entropy->BE; /* Append bits to buffer */
  159648. for (k = cinfo->Ss; k <= Se; k++) {
  159649. if ((temp = absvalues[k]) == 0) {
  159650. r++;
  159651. continue;
  159652. }
  159653. /* Emit any required ZRLs, but not if they can be folded into EOB */
  159654. while (r > 15 && k <= EOB) {
  159655. /* emit any pending EOBRUN and the BE correction bits */
  159656. emit_eobrun(entropy);
  159657. /* Emit ZRL */
  159658. emit_symbol(entropy, entropy->ac_tbl_no, 0xF0);
  159659. r -= 16;
  159660. /* Emit buffered correction bits that must be associated with ZRL */
  159661. emit_buffered_bits(entropy, BR_buffer, BR);
  159662. BR_buffer = entropy->bit_buffer; /* BE bits are gone now */
  159663. BR = 0;
  159664. }
  159665. /* If the coef was previously nonzero, it only needs a correction bit.
  159666. * NOTE: a straight translation of the spec's figure G.7 would suggest
  159667. * that we also need to test r > 15. But if r > 15, we can only get here
  159668. * if k > EOB, which implies that this coefficient is not 1.
  159669. */
  159670. if (temp > 1) {
  159671. /* The correction bit is the next bit of the absolute value. */
  159672. BR_buffer[BR++] = (char) (temp & 1);
  159673. continue;
  159674. }
  159675. /* Emit any pending EOBRUN and the BE correction bits */
  159676. emit_eobrun(entropy);
  159677. /* Count/emit Huffman symbol for run length / number of bits */
  159678. emit_symbol(entropy, entropy->ac_tbl_no, (r << 4) + 1);
  159679. /* Emit output bit for newly-nonzero coef */
  159680. temp = ((*block)[jpeg_natural_order[k]] < 0) ? 0 : 1;
  159681. emit_bits_p(entropy, (unsigned int) temp, 1);
  159682. /* Emit buffered correction bits that must be associated with this code */
  159683. emit_buffered_bits(entropy, BR_buffer, BR);
  159684. BR_buffer = entropy->bit_buffer; /* BE bits are gone now */
  159685. BR = 0;
  159686. r = 0; /* reset zero run length */
  159687. }
  159688. if (r > 0 || BR > 0) { /* If there are trailing zeroes, */
  159689. entropy->EOBRUN++; /* count an EOB */
  159690. entropy->BE += BR; /* concat my correction bits to older ones */
  159691. /* We force out the EOB if we risk either:
  159692. * 1. overflow of the EOB counter;
  159693. * 2. overflow of the correction bit buffer during the next MCU.
  159694. */
  159695. if (entropy->EOBRUN == 0x7FFF || entropy->BE > (MAX_CORR_BITS-DCTSIZE2+1))
  159696. emit_eobrun(entropy);
  159697. }
  159698. cinfo->dest->next_output_byte = entropy->next_output_byte;
  159699. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  159700. /* Update restart-interval state too */
  159701. if (cinfo->restart_interval) {
  159702. if (entropy->restarts_to_go == 0) {
  159703. entropy->restarts_to_go = cinfo->restart_interval;
  159704. entropy->next_restart_num++;
  159705. entropy->next_restart_num &= 7;
  159706. }
  159707. entropy->restarts_to_go--;
  159708. }
  159709. return TRUE;
  159710. }
  159711. /*
  159712. * Finish up at the end of a Huffman-compressed progressive scan.
  159713. */
  159714. METHODDEF(void)
  159715. finish_pass_phuff (j_compress_ptr cinfo)
  159716. {
  159717. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  159718. entropy->next_output_byte = cinfo->dest->next_output_byte;
  159719. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  159720. /* Flush out any buffered data */
  159721. emit_eobrun(entropy);
  159722. flush_bits_p(entropy);
  159723. cinfo->dest->next_output_byte = entropy->next_output_byte;
  159724. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  159725. }
  159726. /*
  159727. * Finish up a statistics-gathering pass and create the new Huffman tables.
  159728. */
  159729. METHODDEF(void)
  159730. finish_pass_gather_phuff (j_compress_ptr cinfo)
  159731. {
  159732. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  159733. boolean is_DC_band;
  159734. int ci, tbl;
  159735. jpeg_component_info * compptr;
  159736. JHUFF_TBL **htblptr;
  159737. boolean did[NUM_HUFF_TBLS];
  159738. /* Flush out buffered data (all we care about is counting the EOB symbol) */
  159739. emit_eobrun(entropy);
  159740. is_DC_band = (cinfo->Ss == 0);
  159741. /* It's important not to apply jpeg_gen_optimal_table more than once
  159742. * per table, because it clobbers the input frequency counts!
  159743. */
  159744. MEMZERO(did, SIZEOF(did));
  159745. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  159746. compptr = cinfo->cur_comp_info[ci];
  159747. if (is_DC_band) {
  159748. if (cinfo->Ah != 0) /* DC refinement needs no table */
  159749. continue;
  159750. tbl = compptr->dc_tbl_no;
  159751. } else {
  159752. tbl = compptr->ac_tbl_no;
  159753. }
  159754. if (! did[tbl]) {
  159755. if (is_DC_band)
  159756. htblptr = & cinfo->dc_huff_tbl_ptrs[tbl];
  159757. else
  159758. htblptr = & cinfo->ac_huff_tbl_ptrs[tbl];
  159759. if (*htblptr == NULL)
  159760. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  159761. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->count_ptrs[tbl]);
  159762. did[tbl] = TRUE;
  159763. }
  159764. }
  159765. }
  159766. /*
  159767. * Module initialization routine for progressive Huffman entropy encoding.
  159768. */
  159769. GLOBAL(void)
  159770. jinit_phuff_encoder (j_compress_ptr cinfo)
  159771. {
  159772. phuff_entropy_ptr entropy;
  159773. int i;
  159774. entropy = (phuff_entropy_ptr)
  159775. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  159776. SIZEOF(phuff_entropy_encoder));
  159777. cinfo->entropy = (struct jpeg_entropy_encoder *) entropy;
  159778. entropy->pub.start_pass = start_pass_phuff;
  159779. /* Mark tables unallocated */
  159780. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  159781. entropy->derived_tbls[i] = NULL;
  159782. entropy->count_ptrs[i] = NULL;
  159783. }
  159784. entropy->bit_buffer = NULL; /* needed only in AC refinement scan */
  159785. }
  159786. #endif /* C_PROGRESSIVE_SUPPORTED */
  159787. /********* End of inlined file: jcphuff.c *********/
  159788. /********* Start of inlined file: jcprepct.c *********/
  159789. #define JPEG_INTERNALS
  159790. /* At present, jcsample.c can request context rows only for smoothing.
  159791. * In the future, we might also need context rows for CCIR601 sampling
  159792. * or other more-complex downsampling procedures. The code to support
  159793. * context rows should be compiled only if needed.
  159794. */
  159795. #ifdef INPUT_SMOOTHING_SUPPORTED
  159796. #define CONTEXT_ROWS_SUPPORTED
  159797. #endif
  159798. /*
  159799. * For the simple (no-context-row) case, we just need to buffer one
  159800. * row group's worth of pixels for the downsampling step. At the bottom of
  159801. * the image, we pad to a full row group by replicating the last pixel row.
  159802. * The downsampler's last output row is then replicated if needed to pad
  159803. * out to a full iMCU row.
  159804. *
  159805. * When providing context rows, we must buffer three row groups' worth of
  159806. * pixels. Three row groups are physically allocated, but the row pointer
  159807. * arrays are made five row groups high, with the extra pointers above and
  159808. * below "wrapping around" to point to the last and first real row groups.
  159809. * This allows the downsampler to access the proper context rows.
  159810. * At the top and bottom of the image, we create dummy context rows by
  159811. * copying the first or last real pixel row. This copying could be avoided
  159812. * by pointer hacking as is done in jdmainct.c, but it doesn't seem worth the
  159813. * trouble on the compression side.
  159814. */
  159815. /* Private buffer controller object */
  159816. typedef struct {
  159817. struct jpeg_c_prep_controller pub; /* public fields */
  159818. /* Downsampling input buffer. This buffer holds color-converted data
  159819. * until we have enough to do a downsample step.
  159820. */
  159821. JSAMPARRAY color_buf[MAX_COMPONENTS];
  159822. JDIMENSION rows_to_go; /* counts rows remaining in source image */
  159823. int next_buf_row; /* index of next row to store in color_buf */
  159824. #ifdef CONTEXT_ROWS_SUPPORTED /* only needed for context case */
  159825. int this_row_group; /* starting row index of group to process */
  159826. int next_buf_stop; /* downsample when we reach this index */
  159827. #endif
  159828. } my_prep_controller;
  159829. typedef my_prep_controller * my_prep_ptr;
  159830. /*
  159831. * Initialize for a processing pass.
  159832. */
  159833. METHODDEF(void)
  159834. start_pass_prep (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  159835. {
  159836. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  159837. if (pass_mode != JBUF_PASS_THRU)
  159838. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  159839. /* Initialize total-height counter for detecting bottom of image */
  159840. prep->rows_to_go = cinfo->image_height;
  159841. /* Mark the conversion buffer empty */
  159842. prep->next_buf_row = 0;
  159843. #ifdef CONTEXT_ROWS_SUPPORTED
  159844. /* Preset additional state variables for context mode.
  159845. * These aren't used in non-context mode, so we needn't test which mode.
  159846. */
  159847. prep->this_row_group = 0;
  159848. /* Set next_buf_stop to stop after two row groups have been read in. */
  159849. prep->next_buf_stop = 2 * cinfo->max_v_samp_factor;
  159850. #endif
  159851. }
  159852. /*
  159853. * Expand an image vertically from height input_rows to height output_rows,
  159854. * by duplicating the bottom row.
  159855. */
  159856. LOCAL(void)
  159857. expand_bottom_edge (JSAMPARRAY image_data, JDIMENSION num_cols,
  159858. int input_rows, int output_rows)
  159859. {
  159860. register int row;
  159861. for (row = input_rows; row < output_rows; row++) {
  159862. jcopy_sample_rows(image_data, input_rows-1, image_data, row,
  159863. 1, num_cols);
  159864. }
  159865. }
  159866. /*
  159867. * Process some data in the simple no-context case.
  159868. *
  159869. * Preprocessor output data is counted in "row groups". A row group
  159870. * is defined to be v_samp_factor sample rows of each component.
  159871. * Downsampling will produce this much data from each max_v_samp_factor
  159872. * input rows.
  159873. */
  159874. METHODDEF(void)
  159875. pre_process_data (j_compress_ptr cinfo,
  159876. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  159877. JDIMENSION in_rows_avail,
  159878. JSAMPIMAGE output_buf, JDIMENSION *out_row_group_ctr,
  159879. JDIMENSION out_row_groups_avail)
  159880. {
  159881. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  159882. int numrows, ci;
  159883. JDIMENSION inrows;
  159884. jpeg_component_info * compptr;
  159885. while (*in_row_ctr < in_rows_avail &&
  159886. *out_row_group_ctr < out_row_groups_avail) {
  159887. /* Do color conversion to fill the conversion buffer. */
  159888. inrows = in_rows_avail - *in_row_ctr;
  159889. numrows = cinfo->max_v_samp_factor - prep->next_buf_row;
  159890. numrows = (int) MIN((JDIMENSION) numrows, inrows);
  159891. (*cinfo->cconvert->color_convert) (cinfo, input_buf + *in_row_ctr,
  159892. prep->color_buf,
  159893. (JDIMENSION) prep->next_buf_row,
  159894. numrows);
  159895. *in_row_ctr += numrows;
  159896. prep->next_buf_row += numrows;
  159897. prep->rows_to_go -= numrows;
  159898. /* If at bottom of image, pad to fill the conversion buffer. */
  159899. if (prep->rows_to_go == 0 &&
  159900. prep->next_buf_row < cinfo->max_v_samp_factor) {
  159901. for (ci = 0; ci < cinfo->num_components; ci++) {
  159902. expand_bottom_edge(prep->color_buf[ci], cinfo->image_width,
  159903. prep->next_buf_row, cinfo->max_v_samp_factor);
  159904. }
  159905. prep->next_buf_row = cinfo->max_v_samp_factor;
  159906. }
  159907. /* If we've filled the conversion buffer, empty it. */
  159908. if (prep->next_buf_row == cinfo->max_v_samp_factor) {
  159909. (*cinfo->downsample->downsample) (cinfo,
  159910. prep->color_buf, (JDIMENSION) 0,
  159911. output_buf, *out_row_group_ctr);
  159912. prep->next_buf_row = 0;
  159913. (*out_row_group_ctr)++;
  159914. }
  159915. /* If at bottom of image, pad the output to a full iMCU height.
  159916. * Note we assume the caller is providing a one-iMCU-height output buffer!
  159917. */
  159918. if (prep->rows_to_go == 0 &&
  159919. *out_row_group_ctr < out_row_groups_avail) {
  159920. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  159921. ci++, compptr++) {
  159922. expand_bottom_edge(output_buf[ci],
  159923. compptr->width_in_blocks * DCTSIZE,
  159924. (int) (*out_row_group_ctr * compptr->v_samp_factor),
  159925. (int) (out_row_groups_avail * compptr->v_samp_factor));
  159926. }
  159927. *out_row_group_ctr = out_row_groups_avail;
  159928. break; /* can exit outer loop without test */
  159929. }
  159930. }
  159931. }
  159932. #ifdef CONTEXT_ROWS_SUPPORTED
  159933. /*
  159934. * Process some data in the context case.
  159935. */
  159936. METHODDEF(void)
  159937. pre_process_context (j_compress_ptr cinfo,
  159938. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  159939. JDIMENSION in_rows_avail,
  159940. JSAMPIMAGE output_buf, JDIMENSION *out_row_group_ctr,
  159941. JDIMENSION out_row_groups_avail)
  159942. {
  159943. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  159944. int numrows, ci;
  159945. int buf_height = cinfo->max_v_samp_factor * 3;
  159946. JDIMENSION inrows;
  159947. while (*out_row_group_ctr < out_row_groups_avail) {
  159948. if (*in_row_ctr < in_rows_avail) {
  159949. /* Do color conversion to fill the conversion buffer. */
  159950. inrows = in_rows_avail - *in_row_ctr;
  159951. numrows = prep->next_buf_stop - prep->next_buf_row;
  159952. numrows = (int) MIN((JDIMENSION) numrows, inrows);
  159953. (*cinfo->cconvert->color_convert) (cinfo, input_buf + *in_row_ctr,
  159954. prep->color_buf,
  159955. (JDIMENSION) prep->next_buf_row,
  159956. numrows);
  159957. /* Pad at top of image, if first time through */
  159958. if (prep->rows_to_go == cinfo->image_height) {
  159959. for (ci = 0; ci < cinfo->num_components; ci++) {
  159960. int row;
  159961. for (row = 1; row <= cinfo->max_v_samp_factor; row++) {
  159962. jcopy_sample_rows(prep->color_buf[ci], 0,
  159963. prep->color_buf[ci], -row,
  159964. 1, cinfo->image_width);
  159965. }
  159966. }
  159967. }
  159968. *in_row_ctr += numrows;
  159969. prep->next_buf_row += numrows;
  159970. prep->rows_to_go -= numrows;
  159971. } else {
  159972. /* Return for more data, unless we are at the bottom of the image. */
  159973. if (prep->rows_to_go != 0)
  159974. break;
  159975. /* When at bottom of image, pad to fill the conversion buffer. */
  159976. if (prep->next_buf_row < prep->next_buf_stop) {
  159977. for (ci = 0; ci < cinfo->num_components; ci++) {
  159978. expand_bottom_edge(prep->color_buf[ci], cinfo->image_width,
  159979. prep->next_buf_row, prep->next_buf_stop);
  159980. }
  159981. prep->next_buf_row = prep->next_buf_stop;
  159982. }
  159983. }
  159984. /* If we've gotten enough data, downsample a row group. */
  159985. if (prep->next_buf_row == prep->next_buf_stop) {
  159986. (*cinfo->downsample->downsample) (cinfo,
  159987. prep->color_buf,
  159988. (JDIMENSION) prep->this_row_group,
  159989. output_buf, *out_row_group_ctr);
  159990. (*out_row_group_ctr)++;
  159991. /* Advance pointers with wraparound as necessary. */
  159992. prep->this_row_group += cinfo->max_v_samp_factor;
  159993. if (prep->this_row_group >= buf_height)
  159994. prep->this_row_group = 0;
  159995. if (prep->next_buf_row >= buf_height)
  159996. prep->next_buf_row = 0;
  159997. prep->next_buf_stop = prep->next_buf_row + cinfo->max_v_samp_factor;
  159998. }
  159999. }
  160000. }
  160001. /*
  160002. * Create the wrapped-around downsampling input buffer needed for context mode.
  160003. */
  160004. LOCAL(void)
  160005. create_context_buffer (j_compress_ptr cinfo)
  160006. {
  160007. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  160008. int rgroup_height = cinfo->max_v_samp_factor;
  160009. int ci, i;
  160010. jpeg_component_info * compptr;
  160011. JSAMPARRAY true_buffer, fake_buffer;
  160012. /* Grab enough space for fake row pointers for all the components;
  160013. * we need five row groups' worth of pointers for each component.
  160014. */
  160015. fake_buffer = (JSAMPARRAY)
  160016. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  160017. (cinfo->num_components * 5 * rgroup_height) *
  160018. SIZEOF(JSAMPROW));
  160019. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  160020. ci++, compptr++) {
  160021. /* Allocate the actual buffer space (3 row groups) for this component.
  160022. * We make the buffer wide enough to allow the downsampler to edge-expand
  160023. * horizontally within the buffer, if it so chooses.
  160024. */
  160025. true_buffer = (*cinfo->mem->alloc_sarray)
  160026. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  160027. (JDIMENSION) (((long) compptr->width_in_blocks * DCTSIZE *
  160028. cinfo->max_h_samp_factor) / compptr->h_samp_factor),
  160029. (JDIMENSION) (3 * rgroup_height));
  160030. /* Copy true buffer row pointers into the middle of the fake row array */
  160031. MEMCOPY(fake_buffer + rgroup_height, true_buffer,
  160032. 3 * rgroup_height * SIZEOF(JSAMPROW));
  160033. /* Fill in the above and below wraparound pointers */
  160034. for (i = 0; i < rgroup_height; i++) {
  160035. fake_buffer[i] = true_buffer[2 * rgroup_height + i];
  160036. fake_buffer[4 * rgroup_height + i] = true_buffer[i];
  160037. }
  160038. prep->color_buf[ci] = fake_buffer + rgroup_height;
  160039. fake_buffer += 5 * rgroup_height; /* point to space for next component */
  160040. }
  160041. }
  160042. #endif /* CONTEXT_ROWS_SUPPORTED */
  160043. /*
  160044. * Initialize preprocessing controller.
  160045. */
  160046. GLOBAL(void)
  160047. jinit_c_prep_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  160048. {
  160049. my_prep_ptr prep;
  160050. int ci;
  160051. jpeg_component_info * compptr;
  160052. if (need_full_buffer) /* safety check */
  160053. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  160054. prep = (my_prep_ptr)
  160055. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  160056. SIZEOF(my_prep_controller));
  160057. cinfo->prep = (struct jpeg_c_prep_controller *) prep;
  160058. prep->pub.start_pass = start_pass_prep;
  160059. /* Allocate the color conversion buffer.
  160060. * We make the buffer wide enough to allow the downsampler to edge-expand
  160061. * horizontally within the buffer, if it so chooses.
  160062. */
  160063. if (cinfo->downsample->need_context_rows) {
  160064. /* Set up to provide context rows */
  160065. #ifdef CONTEXT_ROWS_SUPPORTED
  160066. prep->pub.pre_process_data = pre_process_context;
  160067. create_context_buffer(cinfo);
  160068. #else
  160069. ERREXIT(cinfo, JERR_NOT_COMPILED);
  160070. #endif
  160071. } else {
  160072. /* No context, just make it tall enough for one row group */
  160073. prep->pub.pre_process_data = pre_process_data;
  160074. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  160075. ci++, compptr++) {
  160076. prep->color_buf[ci] = (*cinfo->mem->alloc_sarray)
  160077. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  160078. (JDIMENSION) (((long) compptr->width_in_blocks * DCTSIZE *
  160079. cinfo->max_h_samp_factor) / compptr->h_samp_factor),
  160080. (JDIMENSION) cinfo->max_v_samp_factor);
  160081. }
  160082. }
  160083. }
  160084. /********* End of inlined file: jcprepct.c *********/
  160085. /********* Start of inlined file: jcsample.c *********/
  160086. #define JPEG_INTERNALS
  160087. /* Pointer to routine to downsample a single component */
  160088. typedef JMETHOD(void, downsample1_ptr,
  160089. (j_compress_ptr cinfo, jpeg_component_info * compptr,
  160090. JSAMPARRAY input_data, JSAMPARRAY output_data));
  160091. /* Private subobject */
  160092. typedef struct {
  160093. struct jpeg_downsampler pub; /* public fields */
  160094. /* Downsampling method pointers, one per component */
  160095. downsample1_ptr methods[MAX_COMPONENTS];
  160096. } my_downsampler;
  160097. typedef my_downsampler * my_downsample_ptr;
  160098. /*
  160099. * Initialize for a downsampling pass.
  160100. */
  160101. METHODDEF(void)
  160102. start_pass_downsample (j_compress_ptr cinfo)
  160103. {
  160104. /* no work for now */
  160105. }
  160106. /*
  160107. * Expand a component horizontally from width input_cols to width output_cols,
  160108. * by duplicating the rightmost samples.
  160109. */
  160110. LOCAL(void)
  160111. expand_right_edge (JSAMPARRAY image_data, int num_rows,
  160112. JDIMENSION input_cols, JDIMENSION output_cols)
  160113. {
  160114. register JSAMPROW ptr;
  160115. register JSAMPLE pixval;
  160116. register int count;
  160117. int row;
  160118. int numcols = (int) (output_cols - input_cols);
  160119. if (numcols > 0) {
  160120. for (row = 0; row < num_rows; row++) {
  160121. ptr = image_data[row] + input_cols;
  160122. pixval = ptr[-1]; /* don't need GETJSAMPLE() here */
  160123. for (count = numcols; count > 0; count--)
  160124. *ptr++ = pixval;
  160125. }
  160126. }
  160127. }
  160128. /*
  160129. * Do downsampling for a whole row group (all components).
  160130. *
  160131. * In this version we simply downsample each component independently.
  160132. */
  160133. METHODDEF(void)
  160134. sep_downsample (j_compress_ptr cinfo,
  160135. JSAMPIMAGE input_buf, JDIMENSION in_row_index,
  160136. JSAMPIMAGE output_buf, JDIMENSION out_row_group_index)
  160137. {
  160138. my_downsample_ptr downsample = (my_downsample_ptr) cinfo->downsample;
  160139. int ci;
  160140. jpeg_component_info * compptr;
  160141. JSAMPARRAY in_ptr, out_ptr;
  160142. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  160143. ci++, compptr++) {
  160144. in_ptr = input_buf[ci] + in_row_index;
  160145. out_ptr = output_buf[ci] + (out_row_group_index * compptr->v_samp_factor);
  160146. (*downsample->methods[ci]) (cinfo, compptr, in_ptr, out_ptr);
  160147. }
  160148. }
  160149. /*
  160150. * Downsample pixel values of a single component.
  160151. * One row group is processed per call.
  160152. * This version handles arbitrary integral sampling ratios, without smoothing.
  160153. * Note that this version is not actually used for customary sampling ratios.
  160154. */
  160155. METHODDEF(void)
  160156. int_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  160157. JSAMPARRAY input_data, JSAMPARRAY output_data)
  160158. {
  160159. int inrow, outrow, h_expand, v_expand, numpix, numpix2, h, v;
  160160. JDIMENSION outcol, outcol_h; /* outcol_h == outcol*h_expand */
  160161. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  160162. JSAMPROW inptr, outptr;
  160163. INT32 outvalue;
  160164. h_expand = cinfo->max_h_samp_factor / compptr->h_samp_factor;
  160165. v_expand = cinfo->max_v_samp_factor / compptr->v_samp_factor;
  160166. numpix = h_expand * v_expand;
  160167. numpix2 = numpix/2;
  160168. /* Expand input data enough to let all the output samples be generated
  160169. * by the standard loop. Special-casing padded output would be more
  160170. * efficient.
  160171. */
  160172. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  160173. cinfo->image_width, output_cols * h_expand);
  160174. inrow = 0;
  160175. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  160176. outptr = output_data[outrow];
  160177. for (outcol = 0, outcol_h = 0; outcol < output_cols;
  160178. outcol++, outcol_h += h_expand) {
  160179. outvalue = 0;
  160180. for (v = 0; v < v_expand; v++) {
  160181. inptr = input_data[inrow+v] + outcol_h;
  160182. for (h = 0; h < h_expand; h++) {
  160183. outvalue += (INT32) GETJSAMPLE(*inptr++);
  160184. }
  160185. }
  160186. *outptr++ = (JSAMPLE) ((outvalue + numpix2) / numpix);
  160187. }
  160188. inrow += v_expand;
  160189. }
  160190. }
  160191. /*
  160192. * Downsample pixel values of a single component.
  160193. * This version handles the special case of a full-size component,
  160194. * without smoothing.
  160195. */
  160196. METHODDEF(void)
  160197. fullsize_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  160198. JSAMPARRAY input_data, JSAMPARRAY output_data)
  160199. {
  160200. /* Copy the data */
  160201. jcopy_sample_rows(input_data, 0, output_data, 0,
  160202. cinfo->max_v_samp_factor, cinfo->image_width);
  160203. /* Edge-expand */
  160204. expand_right_edge(output_data, cinfo->max_v_samp_factor,
  160205. cinfo->image_width, compptr->width_in_blocks * DCTSIZE);
  160206. }
  160207. /*
  160208. * Downsample pixel values of a single component.
  160209. * This version handles the common case of 2:1 horizontal and 1:1 vertical,
  160210. * without smoothing.
  160211. *
  160212. * A note about the "bias" calculations: when rounding fractional values to
  160213. * integer, we do not want to always round 0.5 up to the next integer.
  160214. * If we did that, we'd introduce a noticeable bias towards larger values.
  160215. * Instead, this code is arranged so that 0.5 will be rounded up or down at
  160216. * alternate pixel locations (a simple ordered dither pattern).
  160217. */
  160218. METHODDEF(void)
  160219. h2v1_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  160220. JSAMPARRAY input_data, JSAMPARRAY output_data)
  160221. {
  160222. int outrow;
  160223. JDIMENSION outcol;
  160224. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  160225. register JSAMPROW inptr, outptr;
  160226. register int bias;
  160227. /* Expand input data enough to let all the output samples be generated
  160228. * by the standard loop. Special-casing padded output would be more
  160229. * efficient.
  160230. */
  160231. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  160232. cinfo->image_width, output_cols * 2);
  160233. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  160234. outptr = output_data[outrow];
  160235. inptr = input_data[outrow];
  160236. bias = 0; /* bias = 0,1,0,1,... for successive samples */
  160237. for (outcol = 0; outcol < output_cols; outcol++) {
  160238. *outptr++ = (JSAMPLE) ((GETJSAMPLE(*inptr) + GETJSAMPLE(inptr[1])
  160239. + bias) >> 1);
  160240. bias ^= 1; /* 0=>1, 1=>0 */
  160241. inptr += 2;
  160242. }
  160243. }
  160244. }
  160245. /*
  160246. * Downsample pixel values of a single component.
  160247. * This version handles the standard case of 2:1 horizontal and 2:1 vertical,
  160248. * without smoothing.
  160249. */
  160250. METHODDEF(void)
  160251. h2v2_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  160252. JSAMPARRAY input_data, JSAMPARRAY output_data)
  160253. {
  160254. int inrow, outrow;
  160255. JDIMENSION outcol;
  160256. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  160257. register JSAMPROW inptr0, inptr1, outptr;
  160258. register int bias;
  160259. /* Expand input data enough to let all the output samples be generated
  160260. * by the standard loop. Special-casing padded output would be more
  160261. * efficient.
  160262. */
  160263. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  160264. cinfo->image_width, output_cols * 2);
  160265. inrow = 0;
  160266. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  160267. outptr = output_data[outrow];
  160268. inptr0 = input_data[inrow];
  160269. inptr1 = input_data[inrow+1];
  160270. bias = 1; /* bias = 1,2,1,2,... for successive samples */
  160271. for (outcol = 0; outcol < output_cols; outcol++) {
  160272. *outptr++ = (JSAMPLE) ((GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  160273. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1])
  160274. + bias) >> 2);
  160275. bias ^= 3; /* 1=>2, 2=>1 */
  160276. inptr0 += 2; inptr1 += 2;
  160277. }
  160278. inrow += 2;
  160279. }
  160280. }
  160281. #ifdef INPUT_SMOOTHING_SUPPORTED
  160282. /*
  160283. * Downsample pixel values of a single component.
  160284. * This version handles the standard case of 2:1 horizontal and 2:1 vertical,
  160285. * with smoothing. One row of context is required.
  160286. */
  160287. METHODDEF(void)
  160288. h2v2_smooth_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  160289. JSAMPARRAY input_data, JSAMPARRAY output_data)
  160290. {
  160291. int inrow, outrow;
  160292. JDIMENSION colctr;
  160293. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  160294. register JSAMPROW inptr0, inptr1, above_ptr, below_ptr, outptr;
  160295. INT32 membersum, neighsum, memberscale, neighscale;
  160296. /* Expand input data enough to let all the output samples be generated
  160297. * by the standard loop. Special-casing padded output would be more
  160298. * efficient.
  160299. */
  160300. expand_right_edge(input_data - 1, cinfo->max_v_samp_factor + 2,
  160301. cinfo->image_width, output_cols * 2);
  160302. /* We don't bother to form the individual "smoothed" input pixel values;
  160303. * we can directly compute the output which is the average of the four
  160304. * smoothed values. Each of the four member pixels contributes a fraction
  160305. * (1-8*SF) to its own smoothed image and a fraction SF to each of the three
  160306. * other smoothed pixels, therefore a total fraction (1-5*SF)/4 to the final
  160307. * output. The four corner-adjacent neighbor pixels contribute a fraction
  160308. * SF to just one smoothed pixel, or SF/4 to the final output; while the
  160309. * eight edge-adjacent neighbors contribute SF to each of two smoothed
  160310. * pixels, or SF/2 overall. In order to use integer arithmetic, these
  160311. * factors are scaled by 2^16 = 65536.
  160312. * Also recall that SF = smoothing_factor / 1024.
  160313. */
  160314. memberscale = 16384 - cinfo->smoothing_factor * 80; /* scaled (1-5*SF)/4 */
  160315. neighscale = cinfo->smoothing_factor * 16; /* scaled SF/4 */
  160316. inrow = 0;
  160317. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  160318. outptr = output_data[outrow];
  160319. inptr0 = input_data[inrow];
  160320. inptr1 = input_data[inrow+1];
  160321. above_ptr = input_data[inrow-1];
  160322. below_ptr = input_data[inrow+2];
  160323. /* Special case for first column: pretend column -1 is same as column 0 */
  160324. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  160325. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  160326. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  160327. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  160328. GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[2]) +
  160329. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[2]);
  160330. neighsum += neighsum;
  160331. neighsum += GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[2]) +
  160332. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[2]);
  160333. membersum = membersum * memberscale + neighsum * neighscale;
  160334. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  160335. inptr0 += 2; inptr1 += 2; above_ptr += 2; below_ptr += 2;
  160336. for (colctr = output_cols - 2; colctr > 0; colctr--) {
  160337. /* sum of pixels directly mapped to this output element */
  160338. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  160339. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  160340. /* sum of edge-neighbor pixels */
  160341. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  160342. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  160343. GETJSAMPLE(inptr0[-1]) + GETJSAMPLE(inptr0[2]) +
  160344. GETJSAMPLE(inptr1[-1]) + GETJSAMPLE(inptr1[2]);
  160345. /* The edge-neighbors count twice as much as corner-neighbors */
  160346. neighsum += neighsum;
  160347. /* Add in the corner-neighbors */
  160348. neighsum += GETJSAMPLE(above_ptr[-1]) + GETJSAMPLE(above_ptr[2]) +
  160349. GETJSAMPLE(below_ptr[-1]) + GETJSAMPLE(below_ptr[2]);
  160350. /* form final output scaled up by 2^16 */
  160351. membersum = membersum * memberscale + neighsum * neighscale;
  160352. /* round, descale and output it */
  160353. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  160354. inptr0 += 2; inptr1 += 2; above_ptr += 2; below_ptr += 2;
  160355. }
  160356. /* Special case for last column */
  160357. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  160358. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  160359. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  160360. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  160361. GETJSAMPLE(inptr0[-1]) + GETJSAMPLE(inptr0[1]) +
  160362. GETJSAMPLE(inptr1[-1]) + GETJSAMPLE(inptr1[1]);
  160363. neighsum += neighsum;
  160364. neighsum += GETJSAMPLE(above_ptr[-1]) + GETJSAMPLE(above_ptr[1]) +
  160365. GETJSAMPLE(below_ptr[-1]) + GETJSAMPLE(below_ptr[1]);
  160366. membersum = membersum * memberscale + neighsum * neighscale;
  160367. *outptr = (JSAMPLE) ((membersum + 32768) >> 16);
  160368. inrow += 2;
  160369. }
  160370. }
  160371. /*
  160372. * Downsample pixel values of a single component.
  160373. * This version handles the special case of a full-size component,
  160374. * with smoothing. One row of context is required.
  160375. */
  160376. METHODDEF(void)
  160377. fullsize_smooth_downsample (j_compress_ptr cinfo, jpeg_component_info *compptr,
  160378. JSAMPARRAY input_data, JSAMPARRAY output_data)
  160379. {
  160380. int outrow;
  160381. JDIMENSION colctr;
  160382. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  160383. register JSAMPROW inptr, above_ptr, below_ptr, outptr;
  160384. INT32 membersum, neighsum, memberscale, neighscale;
  160385. int colsum, lastcolsum, nextcolsum;
  160386. /* Expand input data enough to let all the output samples be generated
  160387. * by the standard loop. Special-casing padded output would be more
  160388. * efficient.
  160389. */
  160390. expand_right_edge(input_data - 1, cinfo->max_v_samp_factor + 2,
  160391. cinfo->image_width, output_cols);
  160392. /* Each of the eight neighbor pixels contributes a fraction SF to the
  160393. * smoothed pixel, while the main pixel contributes (1-8*SF). In order
  160394. * to use integer arithmetic, these factors are multiplied by 2^16 = 65536.
  160395. * Also recall that SF = smoothing_factor / 1024.
  160396. */
  160397. memberscale = 65536L - cinfo->smoothing_factor * 512L; /* scaled 1-8*SF */
  160398. neighscale = cinfo->smoothing_factor * 64; /* scaled SF */
  160399. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  160400. outptr = output_data[outrow];
  160401. inptr = input_data[outrow];
  160402. above_ptr = input_data[outrow-1];
  160403. below_ptr = input_data[outrow+1];
  160404. /* Special case for first column */
  160405. colsum = GETJSAMPLE(*above_ptr++) + GETJSAMPLE(*below_ptr++) +
  160406. GETJSAMPLE(*inptr);
  160407. membersum = GETJSAMPLE(*inptr++);
  160408. nextcolsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(*below_ptr) +
  160409. GETJSAMPLE(*inptr);
  160410. neighsum = colsum + (colsum - membersum) + nextcolsum;
  160411. membersum = membersum * memberscale + neighsum * neighscale;
  160412. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  160413. lastcolsum = colsum; colsum = nextcolsum;
  160414. for (colctr = output_cols - 2; colctr > 0; colctr--) {
  160415. membersum = GETJSAMPLE(*inptr++);
  160416. above_ptr++; below_ptr++;
  160417. nextcolsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(*below_ptr) +
  160418. GETJSAMPLE(*inptr);
  160419. neighsum = lastcolsum + (colsum - membersum) + nextcolsum;
  160420. membersum = membersum * memberscale + neighsum * neighscale;
  160421. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  160422. lastcolsum = colsum; colsum = nextcolsum;
  160423. }
  160424. /* Special case for last column */
  160425. membersum = GETJSAMPLE(*inptr);
  160426. neighsum = lastcolsum + (colsum - membersum) + colsum;
  160427. membersum = membersum * memberscale + neighsum * neighscale;
  160428. *outptr = (JSAMPLE) ((membersum + 32768) >> 16);
  160429. }
  160430. }
  160431. #endif /* INPUT_SMOOTHING_SUPPORTED */
  160432. /*
  160433. * Module initialization routine for downsampling.
  160434. * Note that we must select a routine for each component.
  160435. */
  160436. GLOBAL(void)
  160437. jinit_downsampler (j_compress_ptr cinfo)
  160438. {
  160439. my_downsample_ptr downsample;
  160440. int ci;
  160441. jpeg_component_info * compptr;
  160442. boolean smoothok = TRUE;
  160443. downsample = (my_downsample_ptr)
  160444. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  160445. SIZEOF(my_downsampler));
  160446. cinfo->downsample = (struct jpeg_downsampler *) downsample;
  160447. downsample->pub.start_pass = start_pass_downsample;
  160448. downsample->pub.downsample = sep_downsample;
  160449. downsample->pub.need_context_rows = FALSE;
  160450. if (cinfo->CCIR601_sampling)
  160451. ERREXIT(cinfo, JERR_CCIR601_NOTIMPL);
  160452. /* Verify we can handle the sampling factors, and set up method pointers */
  160453. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  160454. ci++, compptr++) {
  160455. if (compptr->h_samp_factor == cinfo->max_h_samp_factor &&
  160456. compptr->v_samp_factor == cinfo->max_v_samp_factor) {
  160457. #ifdef INPUT_SMOOTHING_SUPPORTED
  160458. if (cinfo->smoothing_factor) {
  160459. downsample->methods[ci] = fullsize_smooth_downsample;
  160460. downsample->pub.need_context_rows = TRUE;
  160461. } else
  160462. #endif
  160463. downsample->methods[ci] = fullsize_downsample;
  160464. } else if (compptr->h_samp_factor * 2 == cinfo->max_h_samp_factor &&
  160465. compptr->v_samp_factor == cinfo->max_v_samp_factor) {
  160466. smoothok = FALSE;
  160467. downsample->methods[ci] = h2v1_downsample;
  160468. } else if (compptr->h_samp_factor * 2 == cinfo->max_h_samp_factor &&
  160469. compptr->v_samp_factor * 2 == cinfo->max_v_samp_factor) {
  160470. #ifdef INPUT_SMOOTHING_SUPPORTED
  160471. if (cinfo->smoothing_factor) {
  160472. downsample->methods[ci] = h2v2_smooth_downsample;
  160473. downsample->pub.need_context_rows = TRUE;
  160474. } else
  160475. #endif
  160476. downsample->methods[ci] = h2v2_downsample;
  160477. } else if ((cinfo->max_h_samp_factor % compptr->h_samp_factor) == 0 &&
  160478. (cinfo->max_v_samp_factor % compptr->v_samp_factor) == 0) {
  160479. smoothok = FALSE;
  160480. downsample->methods[ci] = int_downsample;
  160481. } else
  160482. ERREXIT(cinfo, JERR_FRACT_SAMPLE_NOTIMPL);
  160483. }
  160484. #ifdef INPUT_SMOOTHING_SUPPORTED
  160485. if (cinfo->smoothing_factor && !smoothok)
  160486. TRACEMS(cinfo, 0, JTRC_SMOOTH_NOTIMPL);
  160487. #endif
  160488. }
  160489. /********* End of inlined file: jcsample.c *********/
  160490. /********* Start of inlined file: jctrans.c *********/
  160491. #define JPEG_INTERNALS
  160492. /* Forward declarations */
  160493. LOCAL(void) transencode_master_selection
  160494. JPP((j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays));
  160495. LOCAL(void) transencode_coef_controller
  160496. JPP((j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays));
  160497. /*
  160498. * Compression initialization for writing raw-coefficient data.
  160499. * Before calling this, all parameters and a data destination must be set up.
  160500. * Call jpeg_finish_compress() to actually write the data.
  160501. *
  160502. * The number of passed virtual arrays must match cinfo->num_components.
  160503. * Note that the virtual arrays need not be filled or even realized at
  160504. * the time write_coefficients is called; indeed, if the virtual arrays
  160505. * were requested from this compression object's memory manager, they
  160506. * typically will be realized during this routine and filled afterwards.
  160507. */
  160508. GLOBAL(void)
  160509. jpeg_write_coefficients (j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays)
  160510. {
  160511. if (cinfo->global_state != CSTATE_START)
  160512. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  160513. /* Mark all tables to be written */
  160514. jpeg_suppress_tables(cinfo, FALSE);
  160515. /* (Re)initialize error mgr and destination modules */
  160516. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  160517. (*cinfo->dest->init_destination) (cinfo);
  160518. /* Perform master selection of active modules */
  160519. transencode_master_selection(cinfo, coef_arrays);
  160520. /* Wait for jpeg_finish_compress() call */
  160521. cinfo->next_scanline = 0; /* so jpeg_write_marker works */
  160522. cinfo->global_state = CSTATE_WRCOEFS;
  160523. }
  160524. /*
  160525. * Initialize the compression object with default parameters,
  160526. * then copy from the source object all parameters needed for lossless
  160527. * transcoding. Parameters that can be varied without loss (such as
  160528. * scan script and Huffman optimization) are left in their default states.
  160529. */
  160530. GLOBAL(void)
  160531. jpeg_copy_critical_parameters (j_decompress_ptr srcinfo,
  160532. j_compress_ptr dstinfo)
  160533. {
  160534. JQUANT_TBL ** qtblptr;
  160535. jpeg_component_info *incomp, *outcomp;
  160536. JQUANT_TBL *c_quant, *slot_quant;
  160537. int tblno, ci, coefi;
  160538. /* Safety check to ensure start_compress not called yet. */
  160539. if (dstinfo->global_state != CSTATE_START)
  160540. ERREXIT1(dstinfo, JERR_BAD_STATE, dstinfo->global_state);
  160541. /* Copy fundamental image dimensions */
  160542. dstinfo->image_width = srcinfo->image_width;
  160543. dstinfo->image_height = srcinfo->image_height;
  160544. dstinfo->input_components = srcinfo->num_components;
  160545. dstinfo->in_color_space = srcinfo->jpeg_color_space;
  160546. /* Initialize all parameters to default values */
  160547. jpeg_set_defaults(dstinfo);
  160548. /* jpeg_set_defaults may choose wrong colorspace, eg YCbCr if input is RGB.
  160549. * Fix it to get the right header markers for the image colorspace.
  160550. */
  160551. jpeg_set_colorspace(dstinfo, srcinfo->jpeg_color_space);
  160552. dstinfo->data_precision = srcinfo->data_precision;
  160553. dstinfo->CCIR601_sampling = srcinfo->CCIR601_sampling;
  160554. /* Copy the source's quantization tables. */
  160555. for (tblno = 0; tblno < NUM_QUANT_TBLS; tblno++) {
  160556. if (srcinfo->quant_tbl_ptrs[tblno] != NULL) {
  160557. qtblptr = & dstinfo->quant_tbl_ptrs[tblno];
  160558. if (*qtblptr == NULL)
  160559. *qtblptr = jpeg_alloc_quant_table((j_common_ptr) dstinfo);
  160560. MEMCOPY((*qtblptr)->quantval,
  160561. srcinfo->quant_tbl_ptrs[tblno]->quantval,
  160562. SIZEOF((*qtblptr)->quantval));
  160563. (*qtblptr)->sent_table = FALSE;
  160564. }
  160565. }
  160566. /* Copy the source's per-component info.
  160567. * Note we assume jpeg_set_defaults has allocated the dest comp_info array.
  160568. */
  160569. dstinfo->num_components = srcinfo->num_components;
  160570. if (dstinfo->num_components < 1 || dstinfo->num_components > MAX_COMPONENTS)
  160571. ERREXIT2(dstinfo, JERR_COMPONENT_COUNT, dstinfo->num_components,
  160572. MAX_COMPONENTS);
  160573. for (ci = 0, incomp = srcinfo->comp_info, outcomp = dstinfo->comp_info;
  160574. ci < dstinfo->num_components; ci++, incomp++, outcomp++) {
  160575. outcomp->component_id = incomp->component_id;
  160576. outcomp->h_samp_factor = incomp->h_samp_factor;
  160577. outcomp->v_samp_factor = incomp->v_samp_factor;
  160578. outcomp->quant_tbl_no = incomp->quant_tbl_no;
  160579. /* Make sure saved quantization table for component matches the qtable
  160580. * slot. If not, the input file re-used this qtable slot.
  160581. * IJG encoder currently cannot duplicate this.
  160582. */
  160583. tblno = outcomp->quant_tbl_no;
  160584. if (tblno < 0 || tblno >= NUM_QUANT_TBLS ||
  160585. srcinfo->quant_tbl_ptrs[tblno] == NULL)
  160586. ERREXIT1(dstinfo, JERR_NO_QUANT_TABLE, tblno);
  160587. slot_quant = srcinfo->quant_tbl_ptrs[tblno];
  160588. c_quant = incomp->quant_table;
  160589. if (c_quant != NULL) {
  160590. for (coefi = 0; coefi < DCTSIZE2; coefi++) {
  160591. if (c_quant->quantval[coefi] != slot_quant->quantval[coefi])
  160592. ERREXIT1(dstinfo, JERR_MISMATCHED_QUANT_TABLE, tblno);
  160593. }
  160594. }
  160595. /* Note: we do not copy the source's Huffman table assignments;
  160596. * instead we rely on jpeg_set_colorspace to have made a suitable choice.
  160597. */
  160598. }
  160599. /* Also copy JFIF version and resolution information, if available.
  160600. * Strictly speaking this isn't "critical" info, but it's nearly
  160601. * always appropriate to copy it if available. In particular,
  160602. * if the application chooses to copy JFIF 1.02 extension markers from
  160603. * the source file, we need to copy the version to make sure we don't
  160604. * emit a file that has 1.02 extensions but a claimed version of 1.01.
  160605. * We will *not*, however, copy version info from mislabeled "2.01" files.
  160606. */
  160607. if (srcinfo->saw_JFIF_marker) {
  160608. if (srcinfo->JFIF_major_version == 1) {
  160609. dstinfo->JFIF_major_version = srcinfo->JFIF_major_version;
  160610. dstinfo->JFIF_minor_version = srcinfo->JFIF_minor_version;
  160611. }
  160612. dstinfo->density_unit = srcinfo->density_unit;
  160613. dstinfo->X_density = srcinfo->X_density;
  160614. dstinfo->Y_density = srcinfo->Y_density;
  160615. }
  160616. }
  160617. /*
  160618. * Master selection of compression modules for transcoding.
  160619. * This substitutes for jcinit.c's initialization of the full compressor.
  160620. */
  160621. LOCAL(void)
  160622. transencode_master_selection (j_compress_ptr cinfo,
  160623. jvirt_barray_ptr * coef_arrays)
  160624. {
  160625. /* Although we don't actually use input_components for transcoding,
  160626. * jcmaster.c's initial_setup will complain if input_components is 0.
  160627. */
  160628. cinfo->input_components = 1;
  160629. /* Initialize master control (includes parameter checking/processing) */
  160630. jinit_c_master_control(cinfo, TRUE /* transcode only */);
  160631. /* Entropy encoding: either Huffman or arithmetic coding. */
  160632. if (cinfo->arith_code) {
  160633. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  160634. } else {
  160635. if (cinfo->progressive_mode) {
  160636. #ifdef C_PROGRESSIVE_SUPPORTED
  160637. jinit_phuff_encoder(cinfo);
  160638. #else
  160639. ERREXIT(cinfo, JERR_NOT_COMPILED);
  160640. #endif
  160641. } else
  160642. jinit_huff_encoder(cinfo);
  160643. }
  160644. /* We need a special coefficient buffer controller. */
  160645. transencode_coef_controller(cinfo, coef_arrays);
  160646. jinit_marker_writer(cinfo);
  160647. /* We can now tell the memory manager to allocate virtual arrays. */
  160648. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  160649. /* Write the datastream header (SOI, JFIF) immediately.
  160650. * Frame and scan headers are postponed till later.
  160651. * This lets application insert special markers after the SOI.
  160652. */
  160653. (*cinfo->marker->write_file_header) (cinfo);
  160654. }
  160655. /*
  160656. * The rest of this file is a special implementation of the coefficient
  160657. * buffer controller. This is similar to jccoefct.c, but it handles only
  160658. * output from presupplied virtual arrays. Furthermore, we generate any
  160659. * dummy padding blocks on-the-fly rather than expecting them to be present
  160660. * in the arrays.
  160661. */
  160662. /* Private buffer controller object */
  160663. typedef struct {
  160664. struct jpeg_c_coef_controller pub; /* public fields */
  160665. JDIMENSION iMCU_row_num; /* iMCU row # within image */
  160666. JDIMENSION mcu_ctr; /* counts MCUs processed in current row */
  160667. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  160668. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  160669. /* Virtual block array for each component. */
  160670. jvirt_barray_ptr * whole_image;
  160671. /* Workspace for constructing dummy blocks at right/bottom edges. */
  160672. JBLOCKROW dummy_buffer[C_MAX_BLOCKS_IN_MCU];
  160673. } my_coef_controller2;
  160674. typedef my_coef_controller2 * my_coef_ptr2;
  160675. LOCAL(void)
  160676. start_iMCU_row2 (j_compress_ptr cinfo)
  160677. /* Reset within-iMCU-row counters for a new row */
  160678. {
  160679. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  160680. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  160681. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  160682. * But at the bottom of the image, process only what's left.
  160683. */
  160684. if (cinfo->comps_in_scan > 1) {
  160685. coef->MCU_rows_per_iMCU_row = 1;
  160686. } else {
  160687. if (coef->iMCU_row_num < (cinfo->total_iMCU_rows-1))
  160688. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  160689. else
  160690. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  160691. }
  160692. coef->mcu_ctr = 0;
  160693. coef->MCU_vert_offset = 0;
  160694. }
  160695. /*
  160696. * Initialize for a processing pass.
  160697. */
  160698. METHODDEF(void)
  160699. start_pass_coef2 (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  160700. {
  160701. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  160702. if (pass_mode != JBUF_CRANK_DEST)
  160703. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  160704. coef->iMCU_row_num = 0;
  160705. start_iMCU_row2(cinfo);
  160706. }
  160707. /*
  160708. * Process some data.
  160709. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  160710. * per call, ie, v_samp_factor block rows for each component in the scan.
  160711. * The data is obtained from the virtual arrays and fed to the entropy coder.
  160712. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  160713. *
  160714. * NB: input_buf is ignored; it is likely to be a NULL pointer.
  160715. */
  160716. METHODDEF(boolean)
  160717. compress_output2 (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
  160718. {
  160719. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  160720. JDIMENSION MCU_col_num; /* index of current MCU within row */
  160721. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  160722. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  160723. int blkn, ci, xindex, yindex, yoffset, blockcnt;
  160724. JDIMENSION start_col;
  160725. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  160726. JBLOCKROW MCU_buffer[C_MAX_BLOCKS_IN_MCU];
  160727. JBLOCKROW buffer_ptr;
  160728. jpeg_component_info *compptr;
  160729. /* Align the virtual buffers for the components used in this scan. */
  160730. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  160731. compptr = cinfo->cur_comp_info[ci];
  160732. buffer[ci] = (*cinfo->mem->access_virt_barray)
  160733. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  160734. coef->iMCU_row_num * compptr->v_samp_factor,
  160735. (JDIMENSION) compptr->v_samp_factor, FALSE);
  160736. }
  160737. /* Loop to process one whole iMCU row */
  160738. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  160739. yoffset++) {
  160740. for (MCU_col_num = coef->mcu_ctr; MCU_col_num < cinfo->MCUs_per_row;
  160741. MCU_col_num++) {
  160742. /* Construct list of pointers to DCT blocks belonging to this MCU */
  160743. blkn = 0; /* index of current DCT block within MCU */
  160744. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  160745. compptr = cinfo->cur_comp_info[ci];
  160746. start_col = MCU_col_num * compptr->MCU_width;
  160747. blockcnt = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  160748. : compptr->last_col_width;
  160749. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  160750. if (coef->iMCU_row_num < last_iMCU_row ||
  160751. yindex+yoffset < compptr->last_row_height) {
  160752. /* Fill in pointers to real blocks in this row */
  160753. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  160754. for (xindex = 0; xindex < blockcnt; xindex++)
  160755. MCU_buffer[blkn++] = buffer_ptr++;
  160756. } else {
  160757. /* At bottom of image, need a whole row of dummy blocks */
  160758. xindex = 0;
  160759. }
  160760. /* Fill in any dummy blocks needed in this row.
  160761. * Dummy blocks are filled in the same way as in jccoefct.c:
  160762. * all zeroes in the AC entries, DC entries equal to previous
  160763. * block's DC value. The init routine has already zeroed the
  160764. * AC entries, so we need only set the DC entries correctly.
  160765. */
  160766. for (; xindex < compptr->MCU_width; xindex++) {
  160767. MCU_buffer[blkn] = coef->dummy_buffer[blkn];
  160768. MCU_buffer[blkn][0][0] = MCU_buffer[blkn-1][0][0];
  160769. blkn++;
  160770. }
  160771. }
  160772. }
  160773. /* Try to write the MCU. */
  160774. if (! (*cinfo->entropy->encode_mcu) (cinfo, MCU_buffer)) {
  160775. /* Suspension forced; update state counters and exit */
  160776. coef->MCU_vert_offset = yoffset;
  160777. coef->mcu_ctr = MCU_col_num;
  160778. return FALSE;
  160779. }
  160780. }
  160781. /* Completed an MCU row, but perhaps not an iMCU row */
  160782. coef->mcu_ctr = 0;
  160783. }
  160784. /* Completed the iMCU row, advance counters for next one */
  160785. coef->iMCU_row_num++;
  160786. start_iMCU_row2(cinfo);
  160787. return TRUE;
  160788. }
  160789. /*
  160790. * Initialize coefficient buffer controller.
  160791. *
  160792. * Each passed coefficient array must be the right size for that
  160793. * coefficient: width_in_blocks wide and height_in_blocks high,
  160794. * with unitheight at least v_samp_factor.
  160795. */
  160796. LOCAL(void)
  160797. transencode_coef_controller (j_compress_ptr cinfo,
  160798. jvirt_barray_ptr * coef_arrays)
  160799. {
  160800. my_coef_ptr2 coef;
  160801. JBLOCKROW buffer;
  160802. int i;
  160803. coef = (my_coef_ptr2)
  160804. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  160805. SIZEOF(my_coef_controller2));
  160806. cinfo->coef = (struct jpeg_c_coef_controller *) coef;
  160807. coef->pub.start_pass = start_pass_coef2;
  160808. coef->pub.compress_data = compress_output2;
  160809. /* Save pointer to virtual arrays */
  160810. coef->whole_image = coef_arrays;
  160811. /* Allocate and pre-zero space for dummy DCT blocks. */
  160812. buffer = (JBLOCKROW)
  160813. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  160814. C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  160815. jzero_far((void FAR *) buffer, C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  160816. for (i = 0; i < C_MAX_BLOCKS_IN_MCU; i++) {
  160817. coef->dummy_buffer[i] = buffer + i;
  160818. }
  160819. }
  160820. /********* End of inlined file: jctrans.c *********/
  160821. /********* Start of inlined file: jdapistd.c *********/
  160822. #define JPEG_INTERNALS
  160823. /* Forward declarations */
  160824. LOCAL(boolean) output_pass_setup JPP((j_decompress_ptr cinfo));
  160825. /*
  160826. * Decompression initialization.
  160827. * jpeg_read_header must be completed before calling this.
  160828. *
  160829. * If a multipass operating mode was selected, this will do all but the
  160830. * last pass, and thus may take a great deal of time.
  160831. *
  160832. * Returns FALSE if suspended. The return value need be inspected only if
  160833. * a suspending data source is used.
  160834. */
  160835. GLOBAL(boolean)
  160836. jpeg_start_decompress (j_decompress_ptr cinfo)
  160837. {
  160838. if (cinfo->global_state == DSTATE_READY) {
  160839. /* First call: initialize master control, select active modules */
  160840. jinit_master_decompress(cinfo);
  160841. if (cinfo->buffered_image) {
  160842. /* No more work here; expecting jpeg_start_output next */
  160843. cinfo->global_state = DSTATE_BUFIMAGE;
  160844. return TRUE;
  160845. }
  160846. cinfo->global_state = DSTATE_PRELOAD;
  160847. }
  160848. if (cinfo->global_state == DSTATE_PRELOAD) {
  160849. /* If file has multiple scans, absorb them all into the coef buffer */
  160850. if (cinfo->inputctl->has_multiple_scans) {
  160851. #ifdef D_MULTISCAN_FILES_SUPPORTED
  160852. for (;;) {
  160853. int retcode;
  160854. /* Call progress monitor hook if present */
  160855. if (cinfo->progress != NULL)
  160856. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  160857. /* Absorb some more input */
  160858. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  160859. if (retcode == JPEG_SUSPENDED)
  160860. return FALSE;
  160861. if (retcode == JPEG_REACHED_EOI)
  160862. break;
  160863. /* Advance progress counter if appropriate */
  160864. if (cinfo->progress != NULL &&
  160865. (retcode == JPEG_ROW_COMPLETED || retcode == JPEG_REACHED_SOS)) {
  160866. if (++cinfo->progress->pass_counter >= cinfo->progress->pass_limit) {
  160867. /* jdmaster underestimated number of scans; ratchet up one scan */
  160868. cinfo->progress->pass_limit += (long) cinfo->total_iMCU_rows;
  160869. }
  160870. }
  160871. }
  160872. #else
  160873. ERREXIT(cinfo, JERR_NOT_COMPILED);
  160874. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  160875. }
  160876. cinfo->output_scan_number = cinfo->input_scan_number;
  160877. } else if (cinfo->global_state != DSTATE_PRESCAN)
  160878. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  160879. /* Perform any dummy output passes, and set up for the final pass */
  160880. return output_pass_setup(cinfo);
  160881. }
  160882. /*
  160883. * Set up for an output pass, and perform any dummy pass(es) needed.
  160884. * Common subroutine for jpeg_start_decompress and jpeg_start_output.
  160885. * Entry: global_state = DSTATE_PRESCAN only if previously suspended.
  160886. * Exit: If done, returns TRUE and sets global_state for proper output mode.
  160887. * If suspended, returns FALSE and sets global_state = DSTATE_PRESCAN.
  160888. */
  160889. LOCAL(boolean)
  160890. output_pass_setup (j_decompress_ptr cinfo)
  160891. {
  160892. if (cinfo->global_state != DSTATE_PRESCAN) {
  160893. /* First call: do pass setup */
  160894. (*cinfo->master->prepare_for_output_pass) (cinfo);
  160895. cinfo->output_scanline = 0;
  160896. cinfo->global_state = DSTATE_PRESCAN;
  160897. }
  160898. /* Loop over any required dummy passes */
  160899. while (cinfo->master->is_dummy_pass) {
  160900. #ifdef QUANT_2PASS_SUPPORTED
  160901. /* Crank through the dummy pass */
  160902. while (cinfo->output_scanline < cinfo->output_height) {
  160903. JDIMENSION last_scanline;
  160904. /* Call progress monitor hook if present */
  160905. if (cinfo->progress != NULL) {
  160906. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  160907. cinfo->progress->pass_limit = (long) cinfo->output_height;
  160908. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  160909. }
  160910. /* Process some data */
  160911. last_scanline = cinfo->output_scanline;
  160912. (*cinfo->main->process_data) (cinfo, (JSAMPARRAY) NULL,
  160913. &cinfo->output_scanline, (JDIMENSION) 0);
  160914. if (cinfo->output_scanline == last_scanline)
  160915. return FALSE; /* No progress made, must suspend */
  160916. }
  160917. /* Finish up dummy pass, and set up for another one */
  160918. (*cinfo->master->finish_output_pass) (cinfo);
  160919. (*cinfo->master->prepare_for_output_pass) (cinfo);
  160920. cinfo->output_scanline = 0;
  160921. #else
  160922. ERREXIT(cinfo, JERR_NOT_COMPILED);
  160923. #endif /* QUANT_2PASS_SUPPORTED */
  160924. }
  160925. /* Ready for application to drive output pass through
  160926. * jpeg_read_scanlines or jpeg_read_raw_data.
  160927. */
  160928. cinfo->global_state = cinfo->raw_data_out ? DSTATE_RAW_OK : DSTATE_SCANNING;
  160929. return TRUE;
  160930. }
  160931. /*
  160932. * Read some scanlines of data from the JPEG decompressor.
  160933. *
  160934. * The return value will be the number of lines actually read.
  160935. * This may be less than the number requested in several cases,
  160936. * including bottom of image, data source suspension, and operating
  160937. * modes that emit multiple scanlines at a time.
  160938. *
  160939. * Note: we warn about excess calls to jpeg_read_scanlines() since
  160940. * this likely signals an application programmer error. However,
  160941. * an oversize buffer (max_lines > scanlines remaining) is not an error.
  160942. */
  160943. GLOBAL(JDIMENSION)
  160944. jpeg_read_scanlines (j_decompress_ptr cinfo, JSAMPARRAY scanlines,
  160945. JDIMENSION max_lines)
  160946. {
  160947. JDIMENSION row_ctr;
  160948. if (cinfo->global_state != DSTATE_SCANNING)
  160949. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  160950. if (cinfo->output_scanline >= cinfo->output_height) {
  160951. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  160952. return 0;
  160953. }
  160954. /* Call progress monitor hook if present */
  160955. if (cinfo->progress != NULL) {
  160956. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  160957. cinfo->progress->pass_limit = (long) cinfo->output_height;
  160958. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  160959. }
  160960. /* Process some data */
  160961. row_ctr = 0;
  160962. (*cinfo->main->process_data) (cinfo, scanlines, &row_ctr, max_lines);
  160963. cinfo->output_scanline += row_ctr;
  160964. return row_ctr;
  160965. }
  160966. /*
  160967. * Alternate entry point to read raw data.
  160968. * Processes exactly one iMCU row per call, unless suspended.
  160969. */
  160970. GLOBAL(JDIMENSION)
  160971. jpeg_read_raw_data (j_decompress_ptr cinfo, JSAMPIMAGE data,
  160972. JDIMENSION max_lines)
  160973. {
  160974. JDIMENSION lines_per_iMCU_row;
  160975. if (cinfo->global_state != DSTATE_RAW_OK)
  160976. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  160977. if (cinfo->output_scanline >= cinfo->output_height) {
  160978. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  160979. return 0;
  160980. }
  160981. /* Call progress monitor hook if present */
  160982. if (cinfo->progress != NULL) {
  160983. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  160984. cinfo->progress->pass_limit = (long) cinfo->output_height;
  160985. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  160986. }
  160987. /* Verify that at least one iMCU row can be returned. */
  160988. lines_per_iMCU_row = cinfo->max_v_samp_factor * cinfo->min_DCT_scaled_size;
  160989. if (max_lines < lines_per_iMCU_row)
  160990. ERREXIT(cinfo, JERR_BUFFER_SIZE);
  160991. /* Decompress directly into user's buffer. */
  160992. if (! (*cinfo->coef->decompress_data) (cinfo, data))
  160993. return 0; /* suspension forced, can do nothing more */
  160994. /* OK, we processed one iMCU row. */
  160995. cinfo->output_scanline += lines_per_iMCU_row;
  160996. return lines_per_iMCU_row;
  160997. }
  160998. /* Additional entry points for buffered-image mode. */
  160999. #ifdef D_MULTISCAN_FILES_SUPPORTED
  161000. /*
  161001. * Initialize for an output pass in buffered-image mode.
  161002. */
  161003. GLOBAL(boolean)
  161004. jpeg_start_output (j_decompress_ptr cinfo, int scan_number)
  161005. {
  161006. if (cinfo->global_state != DSTATE_BUFIMAGE &&
  161007. cinfo->global_state != DSTATE_PRESCAN)
  161008. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161009. /* Limit scan number to valid range */
  161010. if (scan_number <= 0)
  161011. scan_number = 1;
  161012. if (cinfo->inputctl->eoi_reached &&
  161013. scan_number > cinfo->input_scan_number)
  161014. scan_number = cinfo->input_scan_number;
  161015. cinfo->output_scan_number = scan_number;
  161016. /* Perform any dummy output passes, and set up for the real pass */
  161017. return output_pass_setup(cinfo);
  161018. }
  161019. /*
  161020. * Finish up after an output pass in buffered-image mode.
  161021. *
  161022. * Returns FALSE if suspended. The return value need be inspected only if
  161023. * a suspending data source is used.
  161024. */
  161025. GLOBAL(boolean)
  161026. jpeg_finish_output (j_decompress_ptr cinfo)
  161027. {
  161028. if ((cinfo->global_state == DSTATE_SCANNING ||
  161029. cinfo->global_state == DSTATE_RAW_OK) && cinfo->buffered_image) {
  161030. /* Terminate this pass. */
  161031. /* We do not require the whole pass to have been completed. */
  161032. (*cinfo->master->finish_output_pass) (cinfo);
  161033. cinfo->global_state = DSTATE_BUFPOST;
  161034. } else if (cinfo->global_state != DSTATE_BUFPOST) {
  161035. /* BUFPOST = repeat call after a suspension, anything else is error */
  161036. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161037. }
  161038. /* Read markers looking for SOS or EOI */
  161039. while (cinfo->input_scan_number <= cinfo->output_scan_number &&
  161040. ! cinfo->inputctl->eoi_reached) {
  161041. if ((*cinfo->inputctl->consume_input) (cinfo) == JPEG_SUSPENDED)
  161042. return FALSE; /* Suspend, come back later */
  161043. }
  161044. cinfo->global_state = DSTATE_BUFIMAGE;
  161045. return TRUE;
  161046. }
  161047. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  161048. /********* End of inlined file: jdapistd.c *********/
  161049. /********* Start of inlined file: jdapimin.c *********/
  161050. #define JPEG_INTERNALS
  161051. /*
  161052. * Initialization of a JPEG decompression object.
  161053. * The error manager must already be set up (in case memory manager fails).
  161054. */
  161055. GLOBAL(void)
  161056. jpeg_CreateDecompress (j_decompress_ptr cinfo, int version, size_t structsize)
  161057. {
  161058. int i;
  161059. /* Guard against version mismatches between library and caller. */
  161060. cinfo->mem = NULL; /* so jpeg_destroy knows mem mgr not called */
  161061. if (version != JPEG_LIB_VERSION)
  161062. ERREXIT2(cinfo, JERR_BAD_LIB_VERSION, JPEG_LIB_VERSION, version);
  161063. if (structsize != SIZEOF(struct jpeg_decompress_struct))
  161064. ERREXIT2(cinfo, JERR_BAD_STRUCT_SIZE,
  161065. (int) SIZEOF(struct jpeg_decompress_struct), (int) structsize);
  161066. /* For debugging purposes, we zero the whole master structure.
  161067. * But the application has already set the err pointer, and may have set
  161068. * client_data, so we have to save and restore those fields.
  161069. * Note: if application hasn't set client_data, tools like Purify may
  161070. * complain here.
  161071. */
  161072. {
  161073. struct jpeg_error_mgr * err = cinfo->err;
  161074. void * client_data = cinfo->client_data; /* ignore Purify complaint here */
  161075. MEMZERO(cinfo, SIZEOF(struct jpeg_decompress_struct));
  161076. cinfo->err = err;
  161077. cinfo->client_data = client_data;
  161078. }
  161079. cinfo->is_decompressor = TRUE;
  161080. /* Initialize a memory manager instance for this object */
  161081. jinit_memory_mgr((j_common_ptr) cinfo);
  161082. /* Zero out pointers to permanent structures. */
  161083. cinfo->progress = NULL;
  161084. cinfo->src = NULL;
  161085. for (i = 0; i < NUM_QUANT_TBLS; i++)
  161086. cinfo->quant_tbl_ptrs[i] = NULL;
  161087. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  161088. cinfo->dc_huff_tbl_ptrs[i] = NULL;
  161089. cinfo->ac_huff_tbl_ptrs[i] = NULL;
  161090. }
  161091. /* Initialize marker processor so application can override methods
  161092. * for COM, APPn markers before calling jpeg_read_header.
  161093. */
  161094. cinfo->marker_list = NULL;
  161095. jinit_marker_reader(cinfo);
  161096. /* And initialize the overall input controller. */
  161097. jinit_input_controller(cinfo);
  161098. /* OK, I'm ready */
  161099. cinfo->global_state = DSTATE_START;
  161100. }
  161101. /*
  161102. * Destruction of a JPEG decompression object
  161103. */
  161104. GLOBAL(void)
  161105. jpeg_destroy_decompress (j_decompress_ptr cinfo)
  161106. {
  161107. jpeg_destroy((j_common_ptr) cinfo); /* use common routine */
  161108. }
  161109. /*
  161110. * Abort processing of a JPEG decompression operation,
  161111. * but don't destroy the object itself.
  161112. */
  161113. GLOBAL(void)
  161114. jpeg_abort_decompress (j_decompress_ptr cinfo)
  161115. {
  161116. jpeg_abort((j_common_ptr) cinfo); /* use common routine */
  161117. }
  161118. /*
  161119. * Set default decompression parameters.
  161120. */
  161121. LOCAL(void)
  161122. default_decompress_parms (j_decompress_ptr cinfo)
  161123. {
  161124. /* Guess the input colorspace, and set output colorspace accordingly. */
  161125. /* (Wish JPEG committee had provided a real way to specify this...) */
  161126. /* Note application may override our guesses. */
  161127. switch (cinfo->num_components) {
  161128. case 1:
  161129. cinfo->jpeg_color_space = JCS_GRAYSCALE;
  161130. cinfo->out_color_space = JCS_GRAYSCALE;
  161131. break;
  161132. case 3:
  161133. if (cinfo->saw_JFIF_marker) {
  161134. cinfo->jpeg_color_space = JCS_YCbCr; /* JFIF implies YCbCr */
  161135. } else if (cinfo->saw_Adobe_marker) {
  161136. switch (cinfo->Adobe_transform) {
  161137. case 0:
  161138. cinfo->jpeg_color_space = JCS_RGB;
  161139. break;
  161140. case 1:
  161141. cinfo->jpeg_color_space = JCS_YCbCr;
  161142. break;
  161143. default:
  161144. WARNMS1(cinfo, JWRN_ADOBE_XFORM, cinfo->Adobe_transform);
  161145. cinfo->jpeg_color_space = JCS_YCbCr; /* assume it's YCbCr */
  161146. break;
  161147. }
  161148. } else {
  161149. /* Saw no special markers, try to guess from the component IDs */
  161150. int cid0 = cinfo->comp_info[0].component_id;
  161151. int cid1 = cinfo->comp_info[1].component_id;
  161152. int cid2 = cinfo->comp_info[2].component_id;
  161153. if (cid0 == 1 && cid1 == 2 && cid2 == 3)
  161154. cinfo->jpeg_color_space = JCS_YCbCr; /* assume JFIF w/out marker */
  161155. else if (cid0 == 82 && cid1 == 71 && cid2 == 66)
  161156. cinfo->jpeg_color_space = JCS_RGB; /* ASCII 'R', 'G', 'B' */
  161157. else {
  161158. TRACEMS3(cinfo, 1, JTRC_UNKNOWN_IDS, cid0, cid1, cid2);
  161159. cinfo->jpeg_color_space = JCS_YCbCr; /* assume it's YCbCr */
  161160. }
  161161. }
  161162. /* Always guess RGB is proper output colorspace. */
  161163. cinfo->out_color_space = JCS_RGB;
  161164. break;
  161165. case 4:
  161166. if (cinfo->saw_Adobe_marker) {
  161167. switch (cinfo->Adobe_transform) {
  161168. case 0:
  161169. cinfo->jpeg_color_space = JCS_CMYK;
  161170. break;
  161171. case 2:
  161172. cinfo->jpeg_color_space = JCS_YCCK;
  161173. break;
  161174. default:
  161175. WARNMS1(cinfo, JWRN_ADOBE_XFORM, cinfo->Adobe_transform);
  161176. cinfo->jpeg_color_space = JCS_YCCK; /* assume it's YCCK */
  161177. break;
  161178. }
  161179. } else {
  161180. /* No special markers, assume straight CMYK. */
  161181. cinfo->jpeg_color_space = JCS_CMYK;
  161182. }
  161183. cinfo->out_color_space = JCS_CMYK;
  161184. break;
  161185. default:
  161186. cinfo->jpeg_color_space = JCS_UNKNOWN;
  161187. cinfo->out_color_space = JCS_UNKNOWN;
  161188. break;
  161189. }
  161190. /* Set defaults for other decompression parameters. */
  161191. cinfo->scale_num = 1; /* 1:1 scaling */
  161192. cinfo->scale_denom = 1;
  161193. cinfo->output_gamma = 1.0;
  161194. cinfo->buffered_image = FALSE;
  161195. cinfo->raw_data_out = FALSE;
  161196. cinfo->dct_method = JDCT_DEFAULT;
  161197. cinfo->do_fancy_upsampling = TRUE;
  161198. cinfo->do_block_smoothing = TRUE;
  161199. cinfo->quantize_colors = FALSE;
  161200. /* We set these in case application only sets quantize_colors. */
  161201. cinfo->dither_mode = JDITHER_FS;
  161202. #ifdef QUANT_2PASS_SUPPORTED
  161203. cinfo->two_pass_quantize = TRUE;
  161204. #else
  161205. cinfo->two_pass_quantize = FALSE;
  161206. #endif
  161207. cinfo->desired_number_of_colors = 256;
  161208. cinfo->colormap = NULL;
  161209. /* Initialize for no mode change in buffered-image mode. */
  161210. cinfo->enable_1pass_quant = FALSE;
  161211. cinfo->enable_external_quant = FALSE;
  161212. cinfo->enable_2pass_quant = FALSE;
  161213. }
  161214. /*
  161215. * Decompression startup: read start of JPEG datastream to see what's there.
  161216. * Need only initialize JPEG object and supply a data source before calling.
  161217. *
  161218. * This routine will read as far as the first SOS marker (ie, actual start of
  161219. * compressed data), and will save all tables and parameters in the JPEG
  161220. * object. It will also initialize the decompression parameters to default
  161221. * values, and finally return JPEG_HEADER_OK. On return, the application may
  161222. * adjust the decompression parameters and then call jpeg_start_decompress.
  161223. * (Or, if the application only wanted to determine the image parameters,
  161224. * the data need not be decompressed. In that case, call jpeg_abort or
  161225. * jpeg_destroy to release any temporary space.)
  161226. * If an abbreviated (tables only) datastream is presented, the routine will
  161227. * return JPEG_HEADER_TABLES_ONLY upon reaching EOI. The application may then
  161228. * re-use the JPEG object to read the abbreviated image datastream(s).
  161229. * It is unnecessary (but OK) to call jpeg_abort in this case.
  161230. * The JPEG_SUSPENDED return code only occurs if the data source module
  161231. * requests suspension of the decompressor. In this case the application
  161232. * should load more source data and then re-call jpeg_read_header to resume
  161233. * processing.
  161234. * If a non-suspending data source is used and require_image is TRUE, then the
  161235. * return code need not be inspected since only JPEG_HEADER_OK is possible.
  161236. *
  161237. * This routine is now just a front end to jpeg_consume_input, with some
  161238. * extra error checking.
  161239. */
  161240. GLOBAL(int)
  161241. jpeg_read_header (j_decompress_ptr cinfo, boolean require_image)
  161242. {
  161243. int retcode;
  161244. if (cinfo->global_state != DSTATE_START &&
  161245. cinfo->global_state != DSTATE_INHEADER)
  161246. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161247. retcode = jpeg_consume_input(cinfo);
  161248. switch (retcode) {
  161249. case JPEG_REACHED_SOS:
  161250. retcode = JPEG_HEADER_OK;
  161251. break;
  161252. case JPEG_REACHED_EOI:
  161253. if (require_image) /* Complain if application wanted an image */
  161254. ERREXIT(cinfo, JERR_NO_IMAGE);
  161255. /* Reset to start state; it would be safer to require the application to
  161256. * call jpeg_abort, but we can't change it now for compatibility reasons.
  161257. * A side effect is to free any temporary memory (there shouldn't be any).
  161258. */
  161259. jpeg_abort((j_common_ptr) cinfo); /* sets state = DSTATE_START */
  161260. retcode = JPEG_HEADER_TABLES_ONLY;
  161261. break;
  161262. case JPEG_SUSPENDED:
  161263. /* no work */
  161264. break;
  161265. }
  161266. return retcode;
  161267. }
  161268. /*
  161269. * Consume data in advance of what the decompressor requires.
  161270. * This can be called at any time once the decompressor object has
  161271. * been created and a data source has been set up.
  161272. *
  161273. * This routine is essentially a state machine that handles a couple
  161274. * of critical state-transition actions, namely initial setup and
  161275. * transition from header scanning to ready-for-start_decompress.
  161276. * All the actual input is done via the input controller's consume_input
  161277. * method.
  161278. */
  161279. GLOBAL(int)
  161280. jpeg_consume_input (j_decompress_ptr cinfo)
  161281. {
  161282. int retcode = JPEG_SUSPENDED;
  161283. /* NB: every possible DSTATE value should be listed in this switch */
  161284. switch (cinfo->global_state) {
  161285. case DSTATE_START:
  161286. /* Start-of-datastream actions: reset appropriate modules */
  161287. (*cinfo->inputctl->reset_input_controller) (cinfo);
  161288. /* Initialize application's data source module */
  161289. (*cinfo->src->init_source) (cinfo);
  161290. cinfo->global_state = DSTATE_INHEADER;
  161291. /*FALLTHROUGH*/
  161292. case DSTATE_INHEADER:
  161293. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  161294. if (retcode == JPEG_REACHED_SOS) { /* Found SOS, prepare to decompress */
  161295. /* Set up default parameters based on header data */
  161296. default_decompress_parms(cinfo);
  161297. /* Set global state: ready for start_decompress */
  161298. cinfo->global_state = DSTATE_READY;
  161299. }
  161300. break;
  161301. case DSTATE_READY:
  161302. /* Can't advance past first SOS until start_decompress is called */
  161303. retcode = JPEG_REACHED_SOS;
  161304. break;
  161305. case DSTATE_PRELOAD:
  161306. case DSTATE_PRESCAN:
  161307. case DSTATE_SCANNING:
  161308. case DSTATE_RAW_OK:
  161309. case DSTATE_BUFIMAGE:
  161310. case DSTATE_BUFPOST:
  161311. case DSTATE_STOPPING:
  161312. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  161313. break;
  161314. default:
  161315. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161316. }
  161317. return retcode;
  161318. }
  161319. /*
  161320. * Have we finished reading the input file?
  161321. */
  161322. GLOBAL(boolean)
  161323. jpeg_input_complete (j_decompress_ptr cinfo)
  161324. {
  161325. /* Check for valid jpeg object */
  161326. if (cinfo->global_state < DSTATE_START ||
  161327. cinfo->global_state > DSTATE_STOPPING)
  161328. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161329. return cinfo->inputctl->eoi_reached;
  161330. }
  161331. /*
  161332. * Is there more than one scan?
  161333. */
  161334. GLOBAL(boolean)
  161335. jpeg_has_multiple_scans (j_decompress_ptr cinfo)
  161336. {
  161337. /* Only valid after jpeg_read_header completes */
  161338. if (cinfo->global_state < DSTATE_READY ||
  161339. cinfo->global_state > DSTATE_STOPPING)
  161340. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161341. return cinfo->inputctl->has_multiple_scans;
  161342. }
  161343. /*
  161344. * Finish JPEG decompression.
  161345. *
  161346. * This will normally just verify the file trailer and release temp storage.
  161347. *
  161348. * Returns FALSE if suspended. The return value need be inspected only if
  161349. * a suspending data source is used.
  161350. */
  161351. GLOBAL(boolean)
  161352. jpeg_finish_decompress (j_decompress_ptr cinfo)
  161353. {
  161354. if ((cinfo->global_state == DSTATE_SCANNING ||
  161355. cinfo->global_state == DSTATE_RAW_OK) && ! cinfo->buffered_image) {
  161356. /* Terminate final pass of non-buffered mode */
  161357. if (cinfo->output_scanline < cinfo->output_height)
  161358. ERREXIT(cinfo, JERR_TOO_LITTLE_DATA);
  161359. (*cinfo->master->finish_output_pass) (cinfo);
  161360. cinfo->global_state = DSTATE_STOPPING;
  161361. } else if (cinfo->global_state == DSTATE_BUFIMAGE) {
  161362. /* Finishing after a buffered-image operation */
  161363. cinfo->global_state = DSTATE_STOPPING;
  161364. } else if (cinfo->global_state != DSTATE_STOPPING) {
  161365. /* STOPPING = repeat call after a suspension, anything else is error */
  161366. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161367. }
  161368. /* Read until EOI */
  161369. while (! cinfo->inputctl->eoi_reached) {
  161370. if ((*cinfo->inputctl->consume_input) (cinfo) == JPEG_SUSPENDED)
  161371. return FALSE; /* Suspend, come back later */
  161372. }
  161373. /* Do final cleanup */
  161374. (*cinfo->src->term_source) (cinfo);
  161375. /* We can use jpeg_abort to release memory and reset global_state */
  161376. jpeg_abort((j_common_ptr) cinfo);
  161377. return TRUE;
  161378. }
  161379. /********* End of inlined file: jdapimin.c *********/
  161380. /********* Start of inlined file: jdatasrc.c *********/
  161381. /* this is not a core library module, so it doesn't define JPEG_INTERNALS */
  161382. /********* Start of inlined file: jerror.h *********/
  161383. /*
  161384. * To define the enum list of message codes, include this file without
  161385. * defining macro JMESSAGE. To create a message string table, include it
  161386. * again with a suitable JMESSAGE definition (see jerror.c for an example).
  161387. */
  161388. #ifndef JMESSAGE
  161389. #ifndef JERROR_H
  161390. /* First time through, define the enum list */
  161391. #define JMAKE_ENUM_LIST
  161392. #else
  161393. /* Repeated inclusions of this file are no-ops unless JMESSAGE is defined */
  161394. #define JMESSAGE(code,string)
  161395. #endif /* JERROR_H */
  161396. #endif /* JMESSAGE */
  161397. #ifdef JMAKE_ENUM_LIST
  161398. typedef enum {
  161399. #define JMESSAGE(code,string) code ,
  161400. #endif /* JMAKE_ENUM_LIST */
  161401. JMESSAGE(JMSG_NOMESSAGE, "Bogus message code %d") /* Must be first entry! */
  161402. /* For maintenance convenience, list is alphabetical by message code name */
  161403. JMESSAGE(JERR_ARITH_NOTIMPL,
  161404. "Sorry, there are legal restrictions on arithmetic coding")
  161405. JMESSAGE(JERR_BAD_ALIGN_TYPE, "ALIGN_TYPE is wrong, please fix")
  161406. JMESSAGE(JERR_BAD_ALLOC_CHUNK, "MAX_ALLOC_CHUNK is wrong, please fix")
  161407. JMESSAGE(JERR_BAD_BUFFER_MODE, "Bogus buffer control mode")
  161408. JMESSAGE(JERR_BAD_COMPONENT_ID, "Invalid component ID %d in SOS")
  161409. JMESSAGE(JERR_BAD_DCT_COEF, "DCT coefficient out of range")
  161410. JMESSAGE(JERR_BAD_DCTSIZE, "IDCT output block size %d not supported")
  161411. JMESSAGE(JERR_BAD_HUFF_TABLE, "Bogus Huffman table definition")
  161412. JMESSAGE(JERR_BAD_IN_COLORSPACE, "Bogus input colorspace")
  161413. JMESSAGE(JERR_BAD_J_COLORSPACE, "Bogus JPEG colorspace")
  161414. JMESSAGE(JERR_BAD_LENGTH, "Bogus marker length")
  161415. JMESSAGE(JERR_BAD_LIB_VERSION,
  161416. "Wrong JPEG library version: library is %d, caller expects %d")
  161417. JMESSAGE(JERR_BAD_MCU_SIZE, "Sampling factors too large for interleaved scan")
  161418. JMESSAGE(JERR_BAD_POOL_ID, "Invalid memory pool code %d")
  161419. JMESSAGE(JERR_BAD_PRECISION, "Unsupported JPEG data precision %d")
  161420. JMESSAGE(JERR_BAD_PROGRESSION,
  161421. "Invalid progressive parameters Ss=%d Se=%d Ah=%d Al=%d")
  161422. JMESSAGE(JERR_BAD_PROG_SCRIPT,
  161423. "Invalid progressive parameters at scan script entry %d")
  161424. JMESSAGE(JERR_BAD_SAMPLING, "Bogus sampling factors")
  161425. JMESSAGE(JERR_BAD_SCAN_SCRIPT, "Invalid scan script at entry %d")
  161426. JMESSAGE(JERR_BAD_STATE, "Improper call to JPEG library in state %d")
  161427. JMESSAGE(JERR_BAD_STRUCT_SIZE,
  161428. "JPEG parameter struct mismatch: library thinks size is %u, caller expects %u")
  161429. JMESSAGE(JERR_BAD_VIRTUAL_ACCESS, "Bogus virtual array access")
  161430. JMESSAGE(JERR_BUFFER_SIZE, "Buffer passed to JPEG library is too small")
  161431. JMESSAGE(JERR_CANT_SUSPEND, "Suspension not allowed here")
  161432. JMESSAGE(JERR_CCIR601_NOTIMPL, "CCIR601 sampling not implemented yet")
  161433. JMESSAGE(JERR_COMPONENT_COUNT, "Too many color components: %d, max %d")
  161434. JMESSAGE(JERR_CONVERSION_NOTIMPL, "Unsupported color conversion request")
  161435. JMESSAGE(JERR_DAC_INDEX, "Bogus DAC index %d")
  161436. JMESSAGE(JERR_DAC_VALUE, "Bogus DAC value 0x%x")
  161437. JMESSAGE(JERR_DHT_INDEX, "Bogus DHT index %d")
  161438. JMESSAGE(JERR_DQT_INDEX, "Bogus DQT index %d")
  161439. JMESSAGE(JERR_EMPTY_IMAGE, "Empty JPEG image (DNL not supported)")
  161440. JMESSAGE(JERR_EMS_READ, "Read from EMS failed")
  161441. JMESSAGE(JERR_EMS_WRITE, "Write to EMS failed")
  161442. JMESSAGE(JERR_EOI_EXPECTED, "Didn't expect more than one scan")
  161443. JMESSAGE(JERR_FILE_READ, "Input file read error")
  161444. JMESSAGE(JERR_FILE_WRITE, "Output file write error --- out of disk space?")
  161445. JMESSAGE(JERR_FRACT_SAMPLE_NOTIMPL, "Fractional sampling not implemented yet")
  161446. JMESSAGE(JERR_HUFF_CLEN_OVERFLOW, "Huffman code size table overflow")
  161447. JMESSAGE(JERR_HUFF_MISSING_CODE, "Missing Huffman code table entry")
  161448. JMESSAGE(JERR_IMAGE_TOO_BIG, "Maximum supported image dimension is %u pixels")
  161449. JMESSAGE(JERR_INPUT_EMPTY, "Empty input file")
  161450. JMESSAGE(JERR_INPUT_EOF, "Premature end of input file")
  161451. JMESSAGE(JERR_MISMATCHED_QUANT_TABLE,
  161452. "Cannot transcode due to multiple use of quantization table %d")
  161453. JMESSAGE(JERR_MISSING_DATA, "Scan script does not transmit all data")
  161454. JMESSAGE(JERR_MODE_CHANGE, "Invalid color quantization mode change")
  161455. JMESSAGE(JERR_NOTIMPL, "Not implemented yet")
  161456. JMESSAGE(JERR_NOT_COMPILED, "Requested feature was omitted at compile time")
  161457. JMESSAGE(JERR_NO_BACKING_STORE, "Backing store not supported")
  161458. JMESSAGE(JERR_NO_HUFF_TABLE, "Huffman table 0x%02x was not defined")
  161459. JMESSAGE(JERR_NO_IMAGE, "JPEG datastream contains no image")
  161460. JMESSAGE(JERR_NO_QUANT_TABLE, "Quantization table 0x%02x was not defined")
  161461. JMESSAGE(JERR_NO_SOI, "Not a JPEG file: starts with 0x%02x 0x%02x")
  161462. JMESSAGE(JERR_OUT_OF_MEMORY, "Insufficient memory (case %d)")
  161463. JMESSAGE(JERR_QUANT_COMPONENTS,
  161464. "Cannot quantize more than %d color components")
  161465. JMESSAGE(JERR_QUANT_FEW_COLORS, "Cannot quantize to fewer than %d colors")
  161466. JMESSAGE(JERR_QUANT_MANY_COLORS, "Cannot quantize to more than %d colors")
  161467. JMESSAGE(JERR_SOF_DUPLICATE, "Invalid JPEG file structure: two SOF markers")
  161468. JMESSAGE(JERR_SOF_NO_SOS, "Invalid JPEG file structure: missing SOS marker")
  161469. JMESSAGE(JERR_SOF_UNSUPPORTED, "Unsupported JPEG process: SOF type 0x%02x")
  161470. JMESSAGE(JERR_SOI_DUPLICATE, "Invalid JPEG file structure: two SOI markers")
  161471. JMESSAGE(JERR_SOS_NO_SOF, "Invalid JPEG file structure: SOS before SOF")
  161472. JMESSAGE(JERR_TFILE_CREATE, "Failed to create temporary file %s")
  161473. JMESSAGE(JERR_TFILE_READ, "Read failed on temporary file")
  161474. JMESSAGE(JERR_TFILE_SEEK, "Seek failed on temporary file")
  161475. JMESSAGE(JERR_TFILE_WRITE,
  161476. "Write failed on temporary file --- out of disk space?")
  161477. JMESSAGE(JERR_TOO_LITTLE_DATA, "Application transferred too few scanlines")
  161478. JMESSAGE(JERR_UNKNOWN_MARKER, "Unsupported marker type 0x%02x")
  161479. JMESSAGE(JERR_VIRTUAL_BUG, "Virtual array controller messed up")
  161480. JMESSAGE(JERR_WIDTH_OVERFLOW, "Image too wide for this implementation")
  161481. JMESSAGE(JERR_XMS_READ, "Read from XMS failed")
  161482. JMESSAGE(JERR_XMS_WRITE, "Write to XMS failed")
  161483. JMESSAGE(JMSG_COPYRIGHT, JCOPYRIGHT)
  161484. JMESSAGE(JMSG_VERSION, JVERSION)
  161485. JMESSAGE(JTRC_16BIT_TABLES,
  161486. "Caution: quantization tables are too coarse for baseline JPEG")
  161487. JMESSAGE(JTRC_ADOBE,
  161488. "Adobe APP14 marker: version %d, flags 0x%04x 0x%04x, transform %d")
  161489. JMESSAGE(JTRC_APP0, "Unknown APP0 marker (not JFIF), length %u")
  161490. JMESSAGE(JTRC_APP14, "Unknown APP14 marker (not Adobe), length %u")
  161491. JMESSAGE(JTRC_DAC, "Define Arithmetic Table 0x%02x: 0x%02x")
  161492. JMESSAGE(JTRC_DHT, "Define Huffman Table 0x%02x")
  161493. JMESSAGE(JTRC_DQT, "Define Quantization Table %d precision %d")
  161494. JMESSAGE(JTRC_DRI, "Define Restart Interval %u")
  161495. JMESSAGE(JTRC_EMS_CLOSE, "Freed EMS handle %u")
  161496. JMESSAGE(JTRC_EMS_OPEN, "Obtained EMS handle %u")
  161497. JMESSAGE(JTRC_EOI, "End Of Image")
  161498. JMESSAGE(JTRC_HUFFBITS, " %3d %3d %3d %3d %3d %3d %3d %3d")
  161499. JMESSAGE(JTRC_JFIF, "JFIF APP0 marker: version %d.%02d, density %dx%d %d")
  161500. JMESSAGE(JTRC_JFIF_BADTHUMBNAILSIZE,
  161501. "Warning: thumbnail image size does not match data length %u")
  161502. JMESSAGE(JTRC_JFIF_EXTENSION,
  161503. "JFIF extension marker: type 0x%02x, length %u")
  161504. JMESSAGE(JTRC_JFIF_THUMBNAIL, " with %d x %d thumbnail image")
  161505. JMESSAGE(JTRC_MISC_MARKER, "Miscellaneous marker 0x%02x, length %u")
  161506. JMESSAGE(JTRC_PARMLESS_MARKER, "Unexpected marker 0x%02x")
  161507. JMESSAGE(JTRC_QUANTVALS, " %4u %4u %4u %4u %4u %4u %4u %4u")
  161508. JMESSAGE(JTRC_QUANT_3_NCOLORS, "Quantizing to %d = %d*%d*%d colors")
  161509. JMESSAGE(JTRC_QUANT_NCOLORS, "Quantizing to %d colors")
  161510. JMESSAGE(JTRC_QUANT_SELECTED, "Selected %d colors for quantization")
  161511. JMESSAGE(JTRC_RECOVERY_ACTION, "At marker 0x%02x, recovery action %d")
  161512. JMESSAGE(JTRC_RST, "RST%d")
  161513. JMESSAGE(JTRC_SMOOTH_NOTIMPL,
  161514. "Smoothing not supported with nonstandard sampling ratios")
  161515. JMESSAGE(JTRC_SOF, "Start Of Frame 0x%02x: width=%u, height=%u, components=%d")
  161516. JMESSAGE(JTRC_SOF_COMPONENT, " Component %d: %dhx%dv q=%d")
  161517. JMESSAGE(JTRC_SOI, "Start of Image")
  161518. JMESSAGE(JTRC_SOS, "Start Of Scan: %d components")
  161519. JMESSAGE(JTRC_SOS_COMPONENT, " Component %d: dc=%d ac=%d")
  161520. JMESSAGE(JTRC_SOS_PARAMS, " Ss=%d, Se=%d, Ah=%d, Al=%d")
  161521. JMESSAGE(JTRC_TFILE_CLOSE, "Closed temporary file %s")
  161522. JMESSAGE(JTRC_TFILE_OPEN, "Opened temporary file %s")
  161523. JMESSAGE(JTRC_THUMB_JPEG,
  161524. "JFIF extension marker: JPEG-compressed thumbnail image, length %u")
  161525. JMESSAGE(JTRC_THUMB_PALETTE,
  161526. "JFIF extension marker: palette thumbnail image, length %u")
  161527. JMESSAGE(JTRC_THUMB_RGB,
  161528. "JFIF extension marker: RGB thumbnail image, length %u")
  161529. JMESSAGE(JTRC_UNKNOWN_IDS,
  161530. "Unrecognized component IDs %d %d %d, assuming YCbCr")
  161531. JMESSAGE(JTRC_XMS_CLOSE, "Freed XMS handle %u")
  161532. JMESSAGE(JTRC_XMS_OPEN, "Obtained XMS handle %u")
  161533. JMESSAGE(JWRN_ADOBE_XFORM, "Unknown Adobe color transform code %d")
  161534. JMESSAGE(JWRN_BOGUS_PROGRESSION,
  161535. "Inconsistent progression sequence for component %d coefficient %d")
  161536. JMESSAGE(JWRN_EXTRANEOUS_DATA,
  161537. "Corrupt JPEG data: %u extraneous bytes before marker 0x%02x")
  161538. JMESSAGE(JWRN_HIT_MARKER, "Corrupt JPEG data: premature end of data segment")
  161539. JMESSAGE(JWRN_HUFF_BAD_CODE, "Corrupt JPEG data: bad Huffman code")
  161540. JMESSAGE(JWRN_JFIF_MAJOR, "Warning: unknown JFIF revision number %d.%02d")
  161541. JMESSAGE(JWRN_JPEG_EOF, "Premature end of JPEG file")
  161542. JMESSAGE(JWRN_MUST_RESYNC,
  161543. "Corrupt JPEG data: found marker 0x%02x instead of RST%d")
  161544. JMESSAGE(JWRN_NOT_SEQUENTIAL, "Invalid SOS parameters for sequential JPEG")
  161545. JMESSAGE(JWRN_TOO_MUCH_DATA, "Application transferred too many scanlines")
  161546. #ifdef JMAKE_ENUM_LIST
  161547. JMSG_LASTMSGCODE
  161548. } J_MESSAGE_CODE;
  161549. #undef JMAKE_ENUM_LIST
  161550. #endif /* JMAKE_ENUM_LIST */
  161551. /* Zap JMESSAGE macro so that future re-inclusions do nothing by default */
  161552. #undef JMESSAGE
  161553. #ifndef JERROR_H
  161554. #define JERROR_H
  161555. /* Macros to simplify using the error and trace message stuff */
  161556. /* The first parameter is either type of cinfo pointer */
  161557. /* Fatal errors (print message and exit) */
  161558. #define ERREXIT(cinfo,code) \
  161559. ((cinfo)->err->msg_code = (code), \
  161560. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161561. #define ERREXIT1(cinfo,code,p1) \
  161562. ((cinfo)->err->msg_code = (code), \
  161563. (cinfo)->err->msg_parm.i[0] = (p1), \
  161564. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161565. #define ERREXIT2(cinfo,code,p1,p2) \
  161566. ((cinfo)->err->msg_code = (code), \
  161567. (cinfo)->err->msg_parm.i[0] = (p1), \
  161568. (cinfo)->err->msg_parm.i[1] = (p2), \
  161569. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161570. #define ERREXIT3(cinfo,code,p1,p2,p3) \
  161571. ((cinfo)->err->msg_code = (code), \
  161572. (cinfo)->err->msg_parm.i[0] = (p1), \
  161573. (cinfo)->err->msg_parm.i[1] = (p2), \
  161574. (cinfo)->err->msg_parm.i[2] = (p3), \
  161575. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161576. #define ERREXIT4(cinfo,code,p1,p2,p3,p4) \
  161577. ((cinfo)->err->msg_code = (code), \
  161578. (cinfo)->err->msg_parm.i[0] = (p1), \
  161579. (cinfo)->err->msg_parm.i[1] = (p2), \
  161580. (cinfo)->err->msg_parm.i[2] = (p3), \
  161581. (cinfo)->err->msg_parm.i[3] = (p4), \
  161582. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161583. #define ERREXITS(cinfo,code,str) \
  161584. ((cinfo)->err->msg_code = (code), \
  161585. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  161586. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161587. #define MAKESTMT(stuff) do { stuff } while (0)
  161588. /* Nonfatal errors (we can keep going, but the data is probably corrupt) */
  161589. #define WARNMS(cinfo,code) \
  161590. ((cinfo)->err->msg_code = (code), \
  161591. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  161592. #define WARNMS1(cinfo,code,p1) \
  161593. ((cinfo)->err->msg_code = (code), \
  161594. (cinfo)->err->msg_parm.i[0] = (p1), \
  161595. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  161596. #define WARNMS2(cinfo,code,p1,p2) \
  161597. ((cinfo)->err->msg_code = (code), \
  161598. (cinfo)->err->msg_parm.i[0] = (p1), \
  161599. (cinfo)->err->msg_parm.i[1] = (p2), \
  161600. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  161601. /* Informational/debugging messages */
  161602. #define TRACEMS(cinfo,lvl,code) \
  161603. ((cinfo)->err->msg_code = (code), \
  161604. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  161605. #define TRACEMS1(cinfo,lvl,code,p1) \
  161606. ((cinfo)->err->msg_code = (code), \
  161607. (cinfo)->err->msg_parm.i[0] = (p1), \
  161608. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  161609. #define TRACEMS2(cinfo,lvl,code,p1,p2) \
  161610. ((cinfo)->err->msg_code = (code), \
  161611. (cinfo)->err->msg_parm.i[0] = (p1), \
  161612. (cinfo)->err->msg_parm.i[1] = (p2), \
  161613. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  161614. #define TRACEMS3(cinfo,lvl,code,p1,p2,p3) \
  161615. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  161616. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); \
  161617. (cinfo)->err->msg_code = (code); \
  161618. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  161619. #define TRACEMS4(cinfo,lvl,code,p1,p2,p3,p4) \
  161620. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  161621. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  161622. (cinfo)->err->msg_code = (code); \
  161623. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  161624. #define TRACEMS5(cinfo,lvl,code,p1,p2,p3,p4,p5) \
  161625. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  161626. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  161627. _mp[4] = (p5); \
  161628. (cinfo)->err->msg_code = (code); \
  161629. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  161630. #define TRACEMS8(cinfo,lvl,code,p1,p2,p3,p4,p5,p6,p7,p8) \
  161631. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  161632. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  161633. _mp[4] = (p5); _mp[5] = (p6); _mp[6] = (p7); _mp[7] = (p8); \
  161634. (cinfo)->err->msg_code = (code); \
  161635. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  161636. #define TRACEMSS(cinfo,lvl,code,str) \
  161637. ((cinfo)->err->msg_code = (code), \
  161638. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  161639. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  161640. #endif /* JERROR_H */
  161641. /********* End of inlined file: jerror.h *********/
  161642. /* Expanded data source object for stdio input */
  161643. typedef struct {
  161644. struct jpeg_source_mgr pub; /* public fields */
  161645. FILE * infile; /* source stream */
  161646. JOCTET * buffer; /* start of buffer */
  161647. boolean start_of_file; /* have we gotten any data yet? */
  161648. } my_source_mgr;
  161649. typedef my_source_mgr * my_src_ptr;
  161650. #define INPUT_BUF_SIZE 4096 /* choose an efficiently fread'able size */
  161651. /*
  161652. * Initialize source --- called by jpeg_read_header
  161653. * before any data is actually read.
  161654. */
  161655. METHODDEF(void)
  161656. init_source (j_decompress_ptr cinfo)
  161657. {
  161658. my_src_ptr src = (my_src_ptr) cinfo->src;
  161659. /* We reset the empty-input-file flag for each image,
  161660. * but we don't clear the input buffer.
  161661. * This is correct behavior for reading a series of images from one source.
  161662. */
  161663. src->start_of_file = TRUE;
  161664. }
  161665. /*
  161666. * Fill the input buffer --- called whenever buffer is emptied.
  161667. *
  161668. * In typical applications, this should read fresh data into the buffer
  161669. * (ignoring the current state of next_input_byte & bytes_in_buffer),
  161670. * reset the pointer & count to the start of the buffer, and return TRUE
  161671. * indicating that the buffer has been reloaded. It is not necessary to
  161672. * fill the buffer entirely, only to obtain at least one more byte.
  161673. *
  161674. * There is no such thing as an EOF return. If the end of the file has been
  161675. * reached, the routine has a choice of ERREXIT() or inserting fake data into
  161676. * the buffer. In most cases, generating a warning message and inserting a
  161677. * fake EOI marker is the best course of action --- this will allow the
  161678. * decompressor to output however much of the image is there. However,
  161679. * the resulting error message is misleading if the real problem is an empty
  161680. * input file, so we handle that case specially.
  161681. *
  161682. * In applications that need to be able to suspend compression due to input
  161683. * not being available yet, a FALSE return indicates that no more data can be
  161684. * obtained right now, but more may be forthcoming later. In this situation,
  161685. * the decompressor will return to its caller (with an indication of the
  161686. * number of scanlines it has read, if any). The application should resume
  161687. * decompression after it has loaded more data into the input buffer. Note
  161688. * that there are substantial restrictions on the use of suspension --- see
  161689. * the documentation.
  161690. *
  161691. * When suspending, the decompressor will back up to a convenient restart point
  161692. * (typically the start of the current MCU). next_input_byte & bytes_in_buffer
  161693. * indicate where the restart point will be if the current call returns FALSE.
  161694. * Data beyond this point must be rescanned after resumption, so move it to
  161695. * the front of the buffer rather than discarding it.
  161696. */
  161697. METHODDEF(boolean)
  161698. fill_input_buffer (j_decompress_ptr cinfo)
  161699. {
  161700. my_src_ptr src = (my_src_ptr) cinfo->src;
  161701. size_t nbytes;
  161702. nbytes = JFREAD(src->infile, src->buffer, INPUT_BUF_SIZE);
  161703. if (nbytes <= 0) {
  161704. if (src->start_of_file) /* Treat empty input file as fatal error */
  161705. ERREXIT(cinfo, JERR_INPUT_EMPTY);
  161706. WARNMS(cinfo, JWRN_JPEG_EOF);
  161707. /* Insert a fake EOI marker */
  161708. src->buffer[0] = (JOCTET) 0xFF;
  161709. src->buffer[1] = (JOCTET) JPEG_EOI;
  161710. nbytes = 2;
  161711. }
  161712. src->pub.next_input_byte = src->buffer;
  161713. src->pub.bytes_in_buffer = nbytes;
  161714. src->start_of_file = FALSE;
  161715. return TRUE;
  161716. }
  161717. /*
  161718. * Skip data --- used to skip over a potentially large amount of
  161719. * uninteresting data (such as an APPn marker).
  161720. *
  161721. * Writers of suspendable-input applications must note that skip_input_data
  161722. * is not granted the right to give a suspension return. If the skip extends
  161723. * beyond the data currently in the buffer, the buffer can be marked empty so
  161724. * that the next read will cause a fill_input_buffer call that can suspend.
  161725. * Arranging for additional bytes to be discarded before reloading the input
  161726. * buffer is the application writer's problem.
  161727. */
  161728. METHODDEF(void)
  161729. skip_input_data (j_decompress_ptr cinfo, long num_bytes)
  161730. {
  161731. my_src_ptr src = (my_src_ptr) cinfo->src;
  161732. /* Just a dumb implementation for now. Could use fseek() except
  161733. * it doesn't work on pipes. Not clear that being smart is worth
  161734. * any trouble anyway --- large skips are infrequent.
  161735. */
  161736. if (num_bytes > 0) {
  161737. while (num_bytes > (long) src->pub.bytes_in_buffer) {
  161738. num_bytes -= (long) src->pub.bytes_in_buffer;
  161739. (void) fill_input_buffer(cinfo);
  161740. /* note we assume that fill_input_buffer will never return FALSE,
  161741. * so suspension need not be handled.
  161742. */
  161743. }
  161744. src->pub.next_input_byte += (size_t) num_bytes;
  161745. src->pub.bytes_in_buffer -= (size_t) num_bytes;
  161746. }
  161747. }
  161748. /*
  161749. * An additional method that can be provided by data source modules is the
  161750. * resync_to_restart method for error recovery in the presence of RST markers.
  161751. * For the moment, this source module just uses the default resync method
  161752. * provided by the JPEG library. That method assumes that no backtracking
  161753. * is possible.
  161754. */
  161755. /*
  161756. * Terminate source --- called by jpeg_finish_decompress
  161757. * after all data has been read. Often a no-op.
  161758. *
  161759. * NB: *not* called by jpeg_abort or jpeg_destroy; surrounding
  161760. * application must deal with any cleanup that should happen even
  161761. * for error exit.
  161762. */
  161763. METHODDEF(void)
  161764. term_source (j_decompress_ptr cinfo)
  161765. {
  161766. /* no work necessary here */
  161767. }
  161768. /*
  161769. * Prepare for input from a stdio stream.
  161770. * The caller must have already opened the stream, and is responsible
  161771. * for closing it after finishing decompression.
  161772. */
  161773. GLOBAL(void)
  161774. jpeg_stdio_src (j_decompress_ptr cinfo, FILE * infile)
  161775. {
  161776. my_src_ptr src;
  161777. /* The source object and input buffer are made permanent so that a series
  161778. * of JPEG images can be read from the same file by calling jpeg_stdio_src
  161779. * only before the first one. (If we discarded the buffer at the end of
  161780. * one image, we'd likely lose the start of the next one.)
  161781. * This makes it unsafe to use this manager and a different source
  161782. * manager serially with the same JPEG object. Caveat programmer.
  161783. */
  161784. if (cinfo->src == NULL) { /* first time for this JPEG object? */
  161785. cinfo->src = (struct jpeg_source_mgr *)
  161786. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  161787. SIZEOF(my_source_mgr));
  161788. src = (my_src_ptr) cinfo->src;
  161789. src->buffer = (JOCTET *)
  161790. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  161791. INPUT_BUF_SIZE * SIZEOF(JOCTET));
  161792. }
  161793. src = (my_src_ptr) cinfo->src;
  161794. src->pub.init_source = init_source;
  161795. src->pub.fill_input_buffer = fill_input_buffer;
  161796. src->pub.skip_input_data = skip_input_data;
  161797. src->pub.resync_to_restart = jpeg_resync_to_restart; /* use default method */
  161798. src->pub.term_source = term_source;
  161799. src->infile = infile;
  161800. src->pub.bytes_in_buffer = 0; /* forces fill_input_buffer on first read */
  161801. src->pub.next_input_byte = NULL; /* until buffer loaded */
  161802. }
  161803. /********* End of inlined file: jdatasrc.c *********/
  161804. /********* Start of inlined file: jdcoefct.c *********/
  161805. #define JPEG_INTERNALS
  161806. /* Block smoothing is only applicable for progressive JPEG, so: */
  161807. #ifndef D_PROGRESSIVE_SUPPORTED
  161808. #undef BLOCK_SMOOTHING_SUPPORTED
  161809. #endif
  161810. /* Private buffer controller object */
  161811. typedef struct {
  161812. struct jpeg_d_coef_controller pub; /* public fields */
  161813. /* These variables keep track of the current location of the input side. */
  161814. /* cinfo->input_iMCU_row is also used for this. */
  161815. JDIMENSION MCU_ctr; /* counts MCUs processed in current row */
  161816. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  161817. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  161818. /* The output side's location is represented by cinfo->output_iMCU_row. */
  161819. /* In single-pass modes, it's sufficient to buffer just one MCU.
  161820. * We allocate a workspace of D_MAX_BLOCKS_IN_MCU coefficient blocks,
  161821. * and let the entropy decoder write into that workspace each time.
  161822. * (On 80x86, the workspace is FAR even though it's not really very big;
  161823. * this is to keep the module interfaces unchanged when a large coefficient
  161824. * buffer is necessary.)
  161825. * In multi-pass modes, this array points to the current MCU's blocks
  161826. * within the virtual arrays; it is used only by the input side.
  161827. */
  161828. JBLOCKROW MCU_buffer[D_MAX_BLOCKS_IN_MCU];
  161829. #ifdef D_MULTISCAN_FILES_SUPPORTED
  161830. /* In multi-pass modes, we need a virtual block array for each component. */
  161831. jvirt_barray_ptr whole_image[MAX_COMPONENTS];
  161832. #endif
  161833. #ifdef BLOCK_SMOOTHING_SUPPORTED
  161834. /* When doing block smoothing, we latch coefficient Al values here */
  161835. int * coef_bits_latch;
  161836. #define SAVED_COEFS 6 /* we save coef_bits[0..5] */
  161837. #endif
  161838. } my_coef_controller3;
  161839. typedef my_coef_controller3 * my_coef_ptr3;
  161840. /* Forward declarations */
  161841. METHODDEF(int) decompress_onepass
  161842. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  161843. #ifdef D_MULTISCAN_FILES_SUPPORTED
  161844. METHODDEF(int) decompress_data
  161845. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  161846. #endif
  161847. #ifdef BLOCK_SMOOTHING_SUPPORTED
  161848. LOCAL(boolean) smoothing_ok JPP((j_decompress_ptr cinfo));
  161849. METHODDEF(int) decompress_smooth_data
  161850. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  161851. #endif
  161852. LOCAL(void)
  161853. start_iMCU_row3 (j_decompress_ptr cinfo)
  161854. /* Reset within-iMCU-row counters for a new row (input side) */
  161855. {
  161856. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  161857. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  161858. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  161859. * But at the bottom of the image, process only what's left.
  161860. */
  161861. if (cinfo->comps_in_scan > 1) {
  161862. coef->MCU_rows_per_iMCU_row = 1;
  161863. } else {
  161864. if (cinfo->input_iMCU_row < (cinfo->total_iMCU_rows-1))
  161865. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  161866. else
  161867. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  161868. }
  161869. coef->MCU_ctr = 0;
  161870. coef->MCU_vert_offset = 0;
  161871. }
  161872. /*
  161873. * Initialize for an input processing pass.
  161874. */
  161875. METHODDEF(void)
  161876. start_input_pass (j_decompress_ptr cinfo)
  161877. {
  161878. cinfo->input_iMCU_row = 0;
  161879. start_iMCU_row3(cinfo);
  161880. }
  161881. /*
  161882. * Initialize for an output processing pass.
  161883. */
  161884. METHODDEF(void)
  161885. start_output_pass (j_decompress_ptr cinfo)
  161886. {
  161887. #ifdef BLOCK_SMOOTHING_SUPPORTED
  161888. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  161889. /* If multipass, check to see whether to use block smoothing on this pass */
  161890. if (coef->pub.coef_arrays != NULL) {
  161891. if (cinfo->do_block_smoothing && smoothing_ok(cinfo))
  161892. coef->pub.decompress_data = decompress_smooth_data;
  161893. else
  161894. coef->pub.decompress_data = decompress_data;
  161895. }
  161896. #endif
  161897. cinfo->output_iMCU_row = 0;
  161898. }
  161899. /*
  161900. * Decompress and return some data in the single-pass case.
  161901. * Always attempts to emit one fully interleaved MCU row ("iMCU" row).
  161902. * Input and output must run in lockstep since we have only a one-MCU buffer.
  161903. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  161904. *
  161905. * NB: output_buf contains a plane for each component in image,
  161906. * which we index according to the component's SOF position.
  161907. */
  161908. METHODDEF(int)
  161909. decompress_onepass (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  161910. {
  161911. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  161912. JDIMENSION MCU_col_num; /* index of current MCU within row */
  161913. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  161914. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  161915. int blkn, ci, xindex, yindex, yoffset, useful_width;
  161916. JSAMPARRAY output_ptr;
  161917. JDIMENSION start_col, output_col;
  161918. jpeg_component_info *compptr;
  161919. inverse_DCT_method_ptr inverse_DCT;
  161920. /* Loop to process as much as one whole iMCU row */
  161921. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  161922. yoffset++) {
  161923. for (MCU_col_num = coef->MCU_ctr; MCU_col_num <= last_MCU_col;
  161924. MCU_col_num++) {
  161925. /* Try to fetch an MCU. Entropy decoder expects buffer to be zeroed. */
  161926. jzero_far((void FAR *) coef->MCU_buffer[0],
  161927. (size_t) (cinfo->blocks_in_MCU * SIZEOF(JBLOCK)));
  161928. if (! (*cinfo->entropy->decode_mcu) (cinfo, coef->MCU_buffer)) {
  161929. /* Suspension forced; update state counters and exit */
  161930. coef->MCU_vert_offset = yoffset;
  161931. coef->MCU_ctr = MCU_col_num;
  161932. return JPEG_SUSPENDED;
  161933. }
  161934. /* Determine where data should go in output_buf and do the IDCT thing.
  161935. * We skip dummy blocks at the right and bottom edges (but blkn gets
  161936. * incremented past them!). Note the inner loop relies on having
  161937. * allocated the MCU_buffer[] blocks sequentially.
  161938. */
  161939. blkn = 0; /* index of current DCT block within MCU */
  161940. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  161941. compptr = cinfo->cur_comp_info[ci];
  161942. /* Don't bother to IDCT an uninteresting component. */
  161943. if (! compptr->component_needed) {
  161944. blkn += compptr->MCU_blocks;
  161945. continue;
  161946. }
  161947. inverse_DCT = cinfo->idct->inverse_DCT[compptr->component_index];
  161948. useful_width = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  161949. : compptr->last_col_width;
  161950. output_ptr = output_buf[compptr->component_index] +
  161951. yoffset * compptr->DCT_scaled_size;
  161952. start_col = MCU_col_num * compptr->MCU_sample_width;
  161953. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  161954. if (cinfo->input_iMCU_row < last_iMCU_row ||
  161955. yoffset+yindex < compptr->last_row_height) {
  161956. output_col = start_col;
  161957. for (xindex = 0; xindex < useful_width; xindex++) {
  161958. (*inverse_DCT) (cinfo, compptr,
  161959. (JCOEFPTR) coef->MCU_buffer[blkn+xindex],
  161960. output_ptr, output_col);
  161961. output_col += compptr->DCT_scaled_size;
  161962. }
  161963. }
  161964. blkn += compptr->MCU_width;
  161965. output_ptr += compptr->DCT_scaled_size;
  161966. }
  161967. }
  161968. }
  161969. /* Completed an MCU row, but perhaps not an iMCU row */
  161970. coef->MCU_ctr = 0;
  161971. }
  161972. /* Completed the iMCU row, advance counters for next one */
  161973. cinfo->output_iMCU_row++;
  161974. if (++(cinfo->input_iMCU_row) < cinfo->total_iMCU_rows) {
  161975. start_iMCU_row3(cinfo);
  161976. return JPEG_ROW_COMPLETED;
  161977. }
  161978. /* Completed the scan */
  161979. (*cinfo->inputctl->finish_input_pass) (cinfo);
  161980. return JPEG_SCAN_COMPLETED;
  161981. }
  161982. /*
  161983. * Dummy consume-input routine for single-pass operation.
  161984. */
  161985. METHODDEF(int)
  161986. dummy_consume_data (j_decompress_ptr cinfo)
  161987. {
  161988. return JPEG_SUSPENDED; /* Always indicate nothing was done */
  161989. }
  161990. #ifdef D_MULTISCAN_FILES_SUPPORTED
  161991. /*
  161992. * Consume input data and store it in the full-image coefficient buffer.
  161993. * We read as much as one fully interleaved MCU row ("iMCU" row) per call,
  161994. * ie, v_samp_factor block rows for each component in the scan.
  161995. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  161996. */
  161997. METHODDEF(int)
  161998. consume_data (j_decompress_ptr cinfo)
  161999. {
  162000. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  162001. JDIMENSION MCU_col_num; /* index of current MCU within row */
  162002. int blkn, ci, xindex, yindex, yoffset;
  162003. JDIMENSION start_col;
  162004. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  162005. JBLOCKROW buffer_ptr;
  162006. jpeg_component_info *compptr;
  162007. /* Align the virtual buffers for the components used in this scan. */
  162008. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  162009. compptr = cinfo->cur_comp_info[ci];
  162010. buffer[ci] = (*cinfo->mem->access_virt_barray)
  162011. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  162012. cinfo->input_iMCU_row * compptr->v_samp_factor,
  162013. (JDIMENSION) compptr->v_samp_factor, TRUE);
  162014. /* Note: entropy decoder expects buffer to be zeroed,
  162015. * but this is handled automatically by the memory manager
  162016. * because we requested a pre-zeroed array.
  162017. */
  162018. }
  162019. /* Loop to process one whole iMCU row */
  162020. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  162021. yoffset++) {
  162022. for (MCU_col_num = coef->MCU_ctr; MCU_col_num < cinfo->MCUs_per_row;
  162023. MCU_col_num++) {
  162024. /* Construct list of pointers to DCT blocks belonging to this MCU */
  162025. blkn = 0; /* index of current DCT block within MCU */
  162026. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  162027. compptr = cinfo->cur_comp_info[ci];
  162028. start_col = MCU_col_num * compptr->MCU_width;
  162029. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  162030. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  162031. for (xindex = 0; xindex < compptr->MCU_width; xindex++) {
  162032. coef->MCU_buffer[blkn++] = buffer_ptr++;
  162033. }
  162034. }
  162035. }
  162036. /* Try to fetch the MCU. */
  162037. if (! (*cinfo->entropy->decode_mcu) (cinfo, coef->MCU_buffer)) {
  162038. /* Suspension forced; update state counters and exit */
  162039. coef->MCU_vert_offset = yoffset;
  162040. coef->MCU_ctr = MCU_col_num;
  162041. return JPEG_SUSPENDED;
  162042. }
  162043. }
  162044. /* Completed an MCU row, but perhaps not an iMCU row */
  162045. coef->MCU_ctr = 0;
  162046. }
  162047. /* Completed the iMCU row, advance counters for next one */
  162048. if (++(cinfo->input_iMCU_row) < cinfo->total_iMCU_rows) {
  162049. start_iMCU_row3(cinfo);
  162050. return JPEG_ROW_COMPLETED;
  162051. }
  162052. /* Completed the scan */
  162053. (*cinfo->inputctl->finish_input_pass) (cinfo);
  162054. return JPEG_SCAN_COMPLETED;
  162055. }
  162056. /*
  162057. * Decompress and return some data in the multi-pass case.
  162058. * Always attempts to emit one fully interleaved MCU row ("iMCU" row).
  162059. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  162060. *
  162061. * NB: output_buf contains a plane for each component in image.
  162062. */
  162063. METHODDEF(int)
  162064. decompress_data (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  162065. {
  162066. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  162067. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  162068. JDIMENSION block_num;
  162069. int ci, block_row, block_rows;
  162070. JBLOCKARRAY buffer;
  162071. JBLOCKROW buffer_ptr;
  162072. JSAMPARRAY output_ptr;
  162073. JDIMENSION output_col;
  162074. jpeg_component_info *compptr;
  162075. inverse_DCT_method_ptr inverse_DCT;
  162076. /* Force some input to be done if we are getting ahead of the input. */
  162077. while (cinfo->input_scan_number < cinfo->output_scan_number ||
  162078. (cinfo->input_scan_number == cinfo->output_scan_number &&
  162079. cinfo->input_iMCU_row <= cinfo->output_iMCU_row)) {
  162080. if ((*cinfo->inputctl->consume_input)(cinfo) == JPEG_SUSPENDED)
  162081. return JPEG_SUSPENDED;
  162082. }
  162083. /* OK, output from the virtual arrays. */
  162084. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  162085. ci++, compptr++) {
  162086. /* Don't bother to IDCT an uninteresting component. */
  162087. if (! compptr->component_needed)
  162088. continue;
  162089. /* Align the virtual buffer for this component. */
  162090. buffer = (*cinfo->mem->access_virt_barray)
  162091. ((j_common_ptr) cinfo, coef->whole_image[ci],
  162092. cinfo->output_iMCU_row * compptr->v_samp_factor,
  162093. (JDIMENSION) compptr->v_samp_factor, FALSE);
  162094. /* Count non-dummy DCT block rows in this iMCU row. */
  162095. if (cinfo->output_iMCU_row < last_iMCU_row)
  162096. block_rows = compptr->v_samp_factor;
  162097. else {
  162098. /* NB: can't use last_row_height here; it is input-side-dependent! */
  162099. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  162100. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  162101. }
  162102. inverse_DCT = cinfo->idct->inverse_DCT[ci];
  162103. output_ptr = output_buf[ci];
  162104. /* Loop over all DCT blocks to be processed. */
  162105. for (block_row = 0; block_row < block_rows; block_row++) {
  162106. buffer_ptr = buffer[block_row];
  162107. output_col = 0;
  162108. for (block_num = 0; block_num < compptr->width_in_blocks; block_num++) {
  162109. (*inverse_DCT) (cinfo, compptr, (JCOEFPTR) buffer_ptr,
  162110. output_ptr, output_col);
  162111. buffer_ptr++;
  162112. output_col += compptr->DCT_scaled_size;
  162113. }
  162114. output_ptr += compptr->DCT_scaled_size;
  162115. }
  162116. }
  162117. if (++(cinfo->output_iMCU_row) < cinfo->total_iMCU_rows)
  162118. return JPEG_ROW_COMPLETED;
  162119. return JPEG_SCAN_COMPLETED;
  162120. }
  162121. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  162122. #ifdef BLOCK_SMOOTHING_SUPPORTED
  162123. /*
  162124. * This code applies interblock smoothing as described by section K.8
  162125. * of the JPEG standard: the first 5 AC coefficients are estimated from
  162126. * the DC values of a DCT block and its 8 neighboring blocks.
  162127. * We apply smoothing only for progressive JPEG decoding, and only if
  162128. * the coefficients it can estimate are not yet known to full precision.
  162129. */
  162130. /* Natural-order array positions of the first 5 zigzag-order coefficients */
  162131. #define Q01_POS 1
  162132. #define Q10_POS 8
  162133. #define Q20_POS 16
  162134. #define Q11_POS 9
  162135. #define Q02_POS 2
  162136. /*
  162137. * Determine whether block smoothing is applicable and safe.
  162138. * We also latch the current states of the coef_bits[] entries for the
  162139. * AC coefficients; otherwise, if the input side of the decompressor
  162140. * advances into a new scan, we might think the coefficients are known
  162141. * more accurately than they really are.
  162142. */
  162143. LOCAL(boolean)
  162144. smoothing_ok (j_decompress_ptr cinfo)
  162145. {
  162146. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  162147. boolean smoothing_useful = FALSE;
  162148. int ci, coefi;
  162149. jpeg_component_info *compptr;
  162150. JQUANT_TBL * qtable;
  162151. int * coef_bits;
  162152. int * coef_bits_latch;
  162153. if (! cinfo->progressive_mode || cinfo->coef_bits == NULL)
  162154. return FALSE;
  162155. /* Allocate latch area if not already done */
  162156. if (coef->coef_bits_latch == NULL)
  162157. coef->coef_bits_latch = (int *)
  162158. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162159. cinfo->num_components *
  162160. (SAVED_COEFS * SIZEOF(int)));
  162161. coef_bits_latch = coef->coef_bits_latch;
  162162. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  162163. ci++, compptr++) {
  162164. /* All components' quantization values must already be latched. */
  162165. if ((qtable = compptr->quant_table) == NULL)
  162166. return FALSE;
  162167. /* Verify DC & first 5 AC quantizers are nonzero to avoid zero-divide. */
  162168. if (qtable->quantval[0] == 0 ||
  162169. qtable->quantval[Q01_POS] == 0 ||
  162170. qtable->quantval[Q10_POS] == 0 ||
  162171. qtable->quantval[Q20_POS] == 0 ||
  162172. qtable->quantval[Q11_POS] == 0 ||
  162173. qtable->quantval[Q02_POS] == 0)
  162174. return FALSE;
  162175. /* DC values must be at least partly known for all components. */
  162176. coef_bits = cinfo->coef_bits[ci];
  162177. if (coef_bits[0] < 0)
  162178. return FALSE;
  162179. /* Block smoothing is helpful if some AC coefficients remain inaccurate. */
  162180. for (coefi = 1; coefi <= 5; coefi++) {
  162181. coef_bits_latch[coefi] = coef_bits[coefi];
  162182. if (coef_bits[coefi] != 0)
  162183. smoothing_useful = TRUE;
  162184. }
  162185. coef_bits_latch += SAVED_COEFS;
  162186. }
  162187. return smoothing_useful;
  162188. }
  162189. /*
  162190. * Variant of decompress_data for use when doing block smoothing.
  162191. */
  162192. METHODDEF(int)
  162193. decompress_smooth_data (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  162194. {
  162195. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  162196. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  162197. JDIMENSION block_num, last_block_column;
  162198. int ci, block_row, block_rows, access_rows;
  162199. JBLOCKARRAY buffer;
  162200. JBLOCKROW buffer_ptr, prev_block_row, next_block_row;
  162201. JSAMPARRAY output_ptr;
  162202. JDIMENSION output_col;
  162203. jpeg_component_info *compptr;
  162204. inverse_DCT_method_ptr inverse_DCT;
  162205. boolean first_row, last_row;
  162206. JBLOCK workspace;
  162207. int *coef_bits;
  162208. JQUANT_TBL *quanttbl;
  162209. INT32 Q00,Q01,Q02,Q10,Q11,Q20, num;
  162210. int DC1,DC2,DC3,DC4,DC5,DC6,DC7,DC8,DC9;
  162211. int Al, pred;
  162212. /* Force some input to be done if we are getting ahead of the input. */
  162213. while (cinfo->input_scan_number <= cinfo->output_scan_number &&
  162214. ! cinfo->inputctl->eoi_reached) {
  162215. if (cinfo->input_scan_number == cinfo->output_scan_number) {
  162216. /* If input is working on current scan, we ordinarily want it to
  162217. * have completed the current row. But if input scan is DC,
  162218. * we want it to keep one row ahead so that next block row's DC
  162219. * values are up to date.
  162220. */
  162221. JDIMENSION delta = (cinfo->Ss == 0) ? 1 : 0;
  162222. if (cinfo->input_iMCU_row > cinfo->output_iMCU_row+delta)
  162223. break;
  162224. }
  162225. if ((*cinfo->inputctl->consume_input)(cinfo) == JPEG_SUSPENDED)
  162226. return JPEG_SUSPENDED;
  162227. }
  162228. /* OK, output from the virtual arrays. */
  162229. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  162230. ci++, compptr++) {
  162231. /* Don't bother to IDCT an uninteresting component. */
  162232. if (! compptr->component_needed)
  162233. continue;
  162234. /* Count non-dummy DCT block rows in this iMCU row. */
  162235. if (cinfo->output_iMCU_row < last_iMCU_row) {
  162236. block_rows = compptr->v_samp_factor;
  162237. access_rows = block_rows * 2; /* this and next iMCU row */
  162238. last_row = FALSE;
  162239. } else {
  162240. /* NB: can't use last_row_height here; it is input-side-dependent! */
  162241. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  162242. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  162243. access_rows = block_rows; /* this iMCU row only */
  162244. last_row = TRUE;
  162245. }
  162246. /* Align the virtual buffer for this component. */
  162247. if (cinfo->output_iMCU_row > 0) {
  162248. access_rows += compptr->v_samp_factor; /* prior iMCU row too */
  162249. buffer = (*cinfo->mem->access_virt_barray)
  162250. ((j_common_ptr) cinfo, coef->whole_image[ci],
  162251. (cinfo->output_iMCU_row - 1) * compptr->v_samp_factor,
  162252. (JDIMENSION) access_rows, FALSE);
  162253. buffer += compptr->v_samp_factor; /* point to current iMCU row */
  162254. first_row = FALSE;
  162255. } else {
  162256. buffer = (*cinfo->mem->access_virt_barray)
  162257. ((j_common_ptr) cinfo, coef->whole_image[ci],
  162258. (JDIMENSION) 0, (JDIMENSION) access_rows, FALSE);
  162259. first_row = TRUE;
  162260. }
  162261. /* Fetch component-dependent info */
  162262. coef_bits = coef->coef_bits_latch + (ci * SAVED_COEFS);
  162263. quanttbl = compptr->quant_table;
  162264. Q00 = quanttbl->quantval[0];
  162265. Q01 = quanttbl->quantval[Q01_POS];
  162266. Q10 = quanttbl->quantval[Q10_POS];
  162267. Q20 = quanttbl->quantval[Q20_POS];
  162268. Q11 = quanttbl->quantval[Q11_POS];
  162269. Q02 = quanttbl->quantval[Q02_POS];
  162270. inverse_DCT = cinfo->idct->inverse_DCT[ci];
  162271. output_ptr = output_buf[ci];
  162272. /* Loop over all DCT blocks to be processed. */
  162273. for (block_row = 0; block_row < block_rows; block_row++) {
  162274. buffer_ptr = buffer[block_row];
  162275. if (first_row && block_row == 0)
  162276. prev_block_row = buffer_ptr;
  162277. else
  162278. prev_block_row = buffer[block_row-1];
  162279. if (last_row && block_row == block_rows-1)
  162280. next_block_row = buffer_ptr;
  162281. else
  162282. next_block_row = buffer[block_row+1];
  162283. /* We fetch the surrounding DC values using a sliding-register approach.
  162284. * Initialize all nine here so as to do the right thing on narrow pics.
  162285. */
  162286. DC1 = DC2 = DC3 = (int) prev_block_row[0][0];
  162287. DC4 = DC5 = DC6 = (int) buffer_ptr[0][0];
  162288. DC7 = DC8 = DC9 = (int) next_block_row[0][0];
  162289. output_col = 0;
  162290. last_block_column = compptr->width_in_blocks - 1;
  162291. for (block_num = 0; block_num <= last_block_column; block_num++) {
  162292. /* Fetch current DCT block into workspace so we can modify it. */
  162293. jcopy_block_row(buffer_ptr, (JBLOCKROW) workspace, (JDIMENSION) 1);
  162294. /* Update DC values */
  162295. if (block_num < last_block_column) {
  162296. DC3 = (int) prev_block_row[1][0];
  162297. DC6 = (int) buffer_ptr[1][0];
  162298. DC9 = (int) next_block_row[1][0];
  162299. }
  162300. /* Compute coefficient estimates per K.8.
  162301. * An estimate is applied only if coefficient is still zero,
  162302. * and is not known to be fully accurate.
  162303. */
  162304. /* AC01 */
  162305. if ((Al=coef_bits[1]) != 0 && workspace[1] == 0) {
  162306. num = 36 * Q00 * (DC4 - DC6);
  162307. if (num >= 0) {
  162308. pred = (int) (((Q01<<7) + num) / (Q01<<8));
  162309. if (Al > 0 && pred >= (1<<Al))
  162310. pred = (1<<Al)-1;
  162311. } else {
  162312. pred = (int) (((Q01<<7) - num) / (Q01<<8));
  162313. if (Al > 0 && pred >= (1<<Al))
  162314. pred = (1<<Al)-1;
  162315. pred = -pred;
  162316. }
  162317. workspace[1] = (JCOEF) pred;
  162318. }
  162319. /* AC10 */
  162320. if ((Al=coef_bits[2]) != 0 && workspace[8] == 0) {
  162321. num = 36 * Q00 * (DC2 - DC8);
  162322. if (num >= 0) {
  162323. pred = (int) (((Q10<<7) + num) / (Q10<<8));
  162324. if (Al > 0 && pred >= (1<<Al))
  162325. pred = (1<<Al)-1;
  162326. } else {
  162327. pred = (int) (((Q10<<7) - num) / (Q10<<8));
  162328. if (Al > 0 && pred >= (1<<Al))
  162329. pred = (1<<Al)-1;
  162330. pred = -pred;
  162331. }
  162332. workspace[8] = (JCOEF) pred;
  162333. }
  162334. /* AC20 */
  162335. if ((Al=coef_bits[3]) != 0 && workspace[16] == 0) {
  162336. num = 9 * Q00 * (DC2 + DC8 - 2*DC5);
  162337. if (num >= 0) {
  162338. pred = (int) (((Q20<<7) + num) / (Q20<<8));
  162339. if (Al > 0 && pred >= (1<<Al))
  162340. pred = (1<<Al)-1;
  162341. } else {
  162342. pred = (int) (((Q20<<7) - num) / (Q20<<8));
  162343. if (Al > 0 && pred >= (1<<Al))
  162344. pred = (1<<Al)-1;
  162345. pred = -pred;
  162346. }
  162347. workspace[16] = (JCOEF) pred;
  162348. }
  162349. /* AC11 */
  162350. if ((Al=coef_bits[4]) != 0 && workspace[9] == 0) {
  162351. num = 5 * Q00 * (DC1 - DC3 - DC7 + DC9);
  162352. if (num >= 0) {
  162353. pred = (int) (((Q11<<7) + num) / (Q11<<8));
  162354. if (Al > 0 && pred >= (1<<Al))
  162355. pred = (1<<Al)-1;
  162356. } else {
  162357. pred = (int) (((Q11<<7) - num) / (Q11<<8));
  162358. if (Al > 0 && pred >= (1<<Al))
  162359. pred = (1<<Al)-1;
  162360. pred = -pred;
  162361. }
  162362. workspace[9] = (JCOEF) pred;
  162363. }
  162364. /* AC02 */
  162365. if ((Al=coef_bits[5]) != 0 && workspace[2] == 0) {
  162366. num = 9 * Q00 * (DC4 + DC6 - 2*DC5);
  162367. if (num >= 0) {
  162368. pred = (int) (((Q02<<7) + num) / (Q02<<8));
  162369. if (Al > 0 && pred >= (1<<Al))
  162370. pred = (1<<Al)-1;
  162371. } else {
  162372. pred = (int) (((Q02<<7) - num) / (Q02<<8));
  162373. if (Al > 0 && pred >= (1<<Al))
  162374. pred = (1<<Al)-1;
  162375. pred = -pred;
  162376. }
  162377. workspace[2] = (JCOEF) pred;
  162378. }
  162379. /* OK, do the IDCT */
  162380. (*inverse_DCT) (cinfo, compptr, (JCOEFPTR) workspace,
  162381. output_ptr, output_col);
  162382. /* Advance for next column */
  162383. DC1 = DC2; DC2 = DC3;
  162384. DC4 = DC5; DC5 = DC6;
  162385. DC7 = DC8; DC8 = DC9;
  162386. buffer_ptr++, prev_block_row++, next_block_row++;
  162387. output_col += compptr->DCT_scaled_size;
  162388. }
  162389. output_ptr += compptr->DCT_scaled_size;
  162390. }
  162391. }
  162392. if (++(cinfo->output_iMCU_row) < cinfo->total_iMCU_rows)
  162393. return JPEG_ROW_COMPLETED;
  162394. return JPEG_SCAN_COMPLETED;
  162395. }
  162396. #endif /* BLOCK_SMOOTHING_SUPPORTED */
  162397. /*
  162398. * Initialize coefficient buffer controller.
  162399. */
  162400. GLOBAL(void)
  162401. jinit_d_coef_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  162402. {
  162403. my_coef_ptr3 coef;
  162404. coef = (my_coef_ptr3)
  162405. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162406. SIZEOF(my_coef_controller3));
  162407. cinfo->coef = (struct jpeg_d_coef_controller *) coef;
  162408. coef->pub.start_input_pass = start_input_pass;
  162409. coef->pub.start_output_pass = start_output_pass;
  162410. #ifdef BLOCK_SMOOTHING_SUPPORTED
  162411. coef->coef_bits_latch = NULL;
  162412. #endif
  162413. /* Create the coefficient buffer. */
  162414. if (need_full_buffer) {
  162415. #ifdef D_MULTISCAN_FILES_SUPPORTED
  162416. /* Allocate a full-image virtual array for each component, */
  162417. /* padded to a multiple of samp_factor DCT blocks in each direction. */
  162418. /* Note we ask for a pre-zeroed array. */
  162419. int ci, access_rows;
  162420. jpeg_component_info *compptr;
  162421. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  162422. ci++, compptr++) {
  162423. access_rows = compptr->v_samp_factor;
  162424. #ifdef BLOCK_SMOOTHING_SUPPORTED
  162425. /* If block smoothing could be used, need a bigger window */
  162426. if (cinfo->progressive_mode)
  162427. access_rows *= 3;
  162428. #endif
  162429. coef->whole_image[ci] = (*cinfo->mem->request_virt_barray)
  162430. ((j_common_ptr) cinfo, JPOOL_IMAGE, TRUE,
  162431. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  162432. (long) compptr->h_samp_factor),
  162433. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  162434. (long) compptr->v_samp_factor),
  162435. (JDIMENSION) access_rows);
  162436. }
  162437. coef->pub.consume_data = consume_data;
  162438. coef->pub.decompress_data = decompress_data;
  162439. coef->pub.coef_arrays = coef->whole_image; /* link to virtual arrays */
  162440. #else
  162441. ERREXIT(cinfo, JERR_NOT_COMPILED);
  162442. #endif
  162443. } else {
  162444. /* We only need a single-MCU buffer. */
  162445. JBLOCKROW buffer;
  162446. int i;
  162447. buffer = (JBLOCKROW)
  162448. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162449. D_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  162450. for (i = 0; i < D_MAX_BLOCKS_IN_MCU; i++) {
  162451. coef->MCU_buffer[i] = buffer + i;
  162452. }
  162453. coef->pub.consume_data = dummy_consume_data;
  162454. coef->pub.decompress_data = decompress_onepass;
  162455. coef->pub.coef_arrays = NULL; /* flag for no virtual arrays */
  162456. }
  162457. }
  162458. /********* End of inlined file: jdcoefct.c *********/
  162459. #undef FIX
  162460. /********* Start of inlined file: jdcolor.c *********/
  162461. #define JPEG_INTERNALS
  162462. /* Private subobject */
  162463. typedef struct {
  162464. struct jpeg_color_deconverter pub; /* public fields */
  162465. /* Private state for YCC->RGB conversion */
  162466. int * Cr_r_tab; /* => table for Cr to R conversion */
  162467. int * Cb_b_tab; /* => table for Cb to B conversion */
  162468. INT32 * Cr_g_tab; /* => table for Cr to G conversion */
  162469. INT32 * Cb_g_tab; /* => table for Cb to G conversion */
  162470. } my_color_deconverter2;
  162471. typedef my_color_deconverter2 * my_cconvert_ptr2;
  162472. /**************** YCbCr -> RGB conversion: most common case **************/
  162473. /*
  162474. * YCbCr is defined per CCIR 601-1, except that Cb and Cr are
  162475. * normalized to the range 0..MAXJSAMPLE rather than -0.5 .. 0.5.
  162476. * The conversion equations to be implemented are therefore
  162477. * R = Y + 1.40200 * Cr
  162478. * G = Y - 0.34414 * Cb - 0.71414 * Cr
  162479. * B = Y + 1.77200 * Cb
  162480. * where Cb and Cr represent the incoming values less CENTERJSAMPLE.
  162481. * (These numbers are derived from TIFF 6.0 section 21, dated 3-June-92.)
  162482. *
  162483. * To avoid floating-point arithmetic, we represent the fractional constants
  162484. * as integers scaled up by 2^16 (about 4 digits precision); we have to divide
  162485. * the products by 2^16, with appropriate rounding, to get the correct answer.
  162486. * Notice that Y, being an integral input, does not contribute any fraction
  162487. * so it need not participate in the rounding.
  162488. *
  162489. * For even more speed, we avoid doing any multiplications in the inner loop
  162490. * by precalculating the constants times Cb and Cr for all possible values.
  162491. * For 8-bit JSAMPLEs this is very reasonable (only 256 entries per table);
  162492. * for 12-bit samples it is still acceptable. It's not very reasonable for
  162493. * 16-bit samples, but if you want lossless storage you shouldn't be changing
  162494. * colorspace anyway.
  162495. * The Cr=>R and Cb=>B values can be rounded to integers in advance; the
  162496. * values for the G calculation are left scaled up, since we must add them
  162497. * together before rounding.
  162498. */
  162499. #define SCALEBITS 16 /* speediest right-shift on some machines */
  162500. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  162501. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  162502. /*
  162503. * Initialize tables for YCC->RGB colorspace conversion.
  162504. */
  162505. LOCAL(void)
  162506. build_ycc_rgb_table (j_decompress_ptr cinfo)
  162507. {
  162508. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  162509. int i;
  162510. INT32 x;
  162511. SHIFT_TEMPS
  162512. cconvert->Cr_r_tab = (int *)
  162513. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162514. (MAXJSAMPLE+1) * SIZEOF(int));
  162515. cconvert->Cb_b_tab = (int *)
  162516. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162517. (MAXJSAMPLE+1) * SIZEOF(int));
  162518. cconvert->Cr_g_tab = (INT32 *)
  162519. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162520. (MAXJSAMPLE+1) * SIZEOF(INT32));
  162521. cconvert->Cb_g_tab = (INT32 *)
  162522. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162523. (MAXJSAMPLE+1) * SIZEOF(INT32));
  162524. for (i = 0, x = -CENTERJSAMPLE; i <= MAXJSAMPLE; i++, x++) {
  162525. /* i is the actual input pixel value, in the range 0..MAXJSAMPLE */
  162526. /* The Cb or Cr value we are thinking of is x = i - CENTERJSAMPLE */
  162527. /* Cr=>R value is nearest int to 1.40200 * x */
  162528. cconvert->Cr_r_tab[i] = (int)
  162529. RIGHT_SHIFT(FIX(1.40200) * x + ONE_HALF, SCALEBITS);
  162530. /* Cb=>B value is nearest int to 1.77200 * x */
  162531. cconvert->Cb_b_tab[i] = (int)
  162532. RIGHT_SHIFT(FIX(1.77200) * x + ONE_HALF, SCALEBITS);
  162533. /* Cr=>G value is scaled-up -0.71414 * x */
  162534. cconvert->Cr_g_tab[i] = (- FIX(0.71414)) * x;
  162535. /* Cb=>G value is scaled-up -0.34414 * x */
  162536. /* We also add in ONE_HALF so that need not do it in inner loop */
  162537. cconvert->Cb_g_tab[i] = (- FIX(0.34414)) * x + ONE_HALF;
  162538. }
  162539. }
  162540. /*
  162541. * Convert some rows of samples to the output colorspace.
  162542. *
  162543. * Note that we change from noninterleaved, one-plane-per-component format
  162544. * to interleaved-pixel format. The output buffer is therefore three times
  162545. * as wide as the input buffer.
  162546. * A starting row offset is provided only for the input buffer. The caller
  162547. * can easily adjust the passed output_buf value to accommodate any row
  162548. * offset required on that side.
  162549. */
  162550. METHODDEF(void)
  162551. ycc_rgb_convert (j_decompress_ptr cinfo,
  162552. JSAMPIMAGE input_buf, JDIMENSION input_row,
  162553. JSAMPARRAY output_buf, int num_rows)
  162554. {
  162555. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  162556. register int y, cb, cr;
  162557. register JSAMPROW outptr;
  162558. register JSAMPROW inptr0, inptr1, inptr2;
  162559. register JDIMENSION col;
  162560. JDIMENSION num_cols = cinfo->output_width;
  162561. /* copy these pointers into registers if possible */
  162562. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  162563. register int * Crrtab = cconvert->Cr_r_tab;
  162564. register int * Cbbtab = cconvert->Cb_b_tab;
  162565. register INT32 * Crgtab = cconvert->Cr_g_tab;
  162566. register INT32 * Cbgtab = cconvert->Cb_g_tab;
  162567. SHIFT_TEMPS
  162568. while (--num_rows >= 0) {
  162569. inptr0 = input_buf[0][input_row];
  162570. inptr1 = input_buf[1][input_row];
  162571. inptr2 = input_buf[2][input_row];
  162572. input_row++;
  162573. outptr = *output_buf++;
  162574. for (col = 0; col < num_cols; col++) {
  162575. y = GETJSAMPLE(inptr0[col]);
  162576. cb = GETJSAMPLE(inptr1[col]);
  162577. cr = GETJSAMPLE(inptr2[col]);
  162578. /* Range-limiting is essential due to noise introduced by DCT losses. */
  162579. outptr[RGB_RED] = range_limit[y + Crrtab[cr]];
  162580. outptr[RGB_GREEN] = range_limit[y +
  162581. ((int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr],
  162582. SCALEBITS))];
  162583. outptr[RGB_BLUE] = range_limit[y + Cbbtab[cb]];
  162584. outptr += RGB_PIXELSIZE;
  162585. }
  162586. }
  162587. }
  162588. /**************** Cases other than YCbCr -> RGB **************/
  162589. /*
  162590. * Color conversion for no colorspace change: just copy the data,
  162591. * converting from separate-planes to interleaved representation.
  162592. */
  162593. METHODDEF(void)
  162594. null_convert2 (j_decompress_ptr cinfo,
  162595. JSAMPIMAGE input_buf, JDIMENSION input_row,
  162596. JSAMPARRAY output_buf, int num_rows)
  162597. {
  162598. register JSAMPROW inptr, outptr;
  162599. register JDIMENSION count;
  162600. register int num_components = cinfo->num_components;
  162601. JDIMENSION num_cols = cinfo->output_width;
  162602. int ci;
  162603. while (--num_rows >= 0) {
  162604. for (ci = 0; ci < num_components; ci++) {
  162605. inptr = input_buf[ci][input_row];
  162606. outptr = output_buf[0] + ci;
  162607. for (count = num_cols; count > 0; count--) {
  162608. *outptr = *inptr++; /* needn't bother with GETJSAMPLE() here */
  162609. outptr += num_components;
  162610. }
  162611. }
  162612. input_row++;
  162613. output_buf++;
  162614. }
  162615. }
  162616. /*
  162617. * Color conversion for grayscale: just copy the data.
  162618. * This also works for YCbCr -> grayscale conversion, in which
  162619. * we just copy the Y (luminance) component and ignore chrominance.
  162620. */
  162621. METHODDEF(void)
  162622. grayscale_convert2 (j_decompress_ptr cinfo,
  162623. JSAMPIMAGE input_buf, JDIMENSION input_row,
  162624. JSAMPARRAY output_buf, int num_rows)
  162625. {
  162626. jcopy_sample_rows(input_buf[0], (int) input_row, output_buf, 0,
  162627. num_rows, cinfo->output_width);
  162628. }
  162629. /*
  162630. * Convert grayscale to RGB: just duplicate the graylevel three times.
  162631. * This is provided to support applications that don't want to cope
  162632. * with grayscale as a separate case.
  162633. */
  162634. METHODDEF(void)
  162635. gray_rgb_convert (j_decompress_ptr cinfo,
  162636. JSAMPIMAGE input_buf, JDIMENSION input_row,
  162637. JSAMPARRAY output_buf, int num_rows)
  162638. {
  162639. register JSAMPROW inptr, outptr;
  162640. register JDIMENSION col;
  162641. JDIMENSION num_cols = cinfo->output_width;
  162642. while (--num_rows >= 0) {
  162643. inptr = input_buf[0][input_row++];
  162644. outptr = *output_buf++;
  162645. for (col = 0; col < num_cols; col++) {
  162646. /* We can dispense with GETJSAMPLE() here */
  162647. outptr[RGB_RED] = outptr[RGB_GREEN] = outptr[RGB_BLUE] = inptr[col];
  162648. outptr += RGB_PIXELSIZE;
  162649. }
  162650. }
  162651. }
  162652. /*
  162653. * Adobe-style YCCK->CMYK conversion.
  162654. * We convert YCbCr to R=1-C, G=1-M, and B=1-Y using the same
  162655. * conversion as above, while passing K (black) unchanged.
  162656. * We assume build_ycc_rgb_table has been called.
  162657. */
  162658. METHODDEF(void)
  162659. ycck_cmyk_convert (j_decompress_ptr cinfo,
  162660. JSAMPIMAGE input_buf, JDIMENSION input_row,
  162661. JSAMPARRAY output_buf, int num_rows)
  162662. {
  162663. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  162664. register int y, cb, cr;
  162665. register JSAMPROW outptr;
  162666. register JSAMPROW inptr0, inptr1, inptr2, inptr3;
  162667. register JDIMENSION col;
  162668. JDIMENSION num_cols = cinfo->output_width;
  162669. /* copy these pointers into registers if possible */
  162670. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  162671. register int * Crrtab = cconvert->Cr_r_tab;
  162672. register int * Cbbtab = cconvert->Cb_b_tab;
  162673. register INT32 * Crgtab = cconvert->Cr_g_tab;
  162674. register INT32 * Cbgtab = cconvert->Cb_g_tab;
  162675. SHIFT_TEMPS
  162676. while (--num_rows >= 0) {
  162677. inptr0 = input_buf[0][input_row];
  162678. inptr1 = input_buf[1][input_row];
  162679. inptr2 = input_buf[2][input_row];
  162680. inptr3 = input_buf[3][input_row];
  162681. input_row++;
  162682. outptr = *output_buf++;
  162683. for (col = 0; col < num_cols; col++) {
  162684. y = GETJSAMPLE(inptr0[col]);
  162685. cb = GETJSAMPLE(inptr1[col]);
  162686. cr = GETJSAMPLE(inptr2[col]);
  162687. /* Range-limiting is essential due to noise introduced by DCT losses. */
  162688. outptr[0] = range_limit[MAXJSAMPLE - (y + Crrtab[cr])]; /* red */
  162689. outptr[1] = range_limit[MAXJSAMPLE - (y + /* green */
  162690. ((int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr],
  162691. SCALEBITS)))];
  162692. outptr[2] = range_limit[MAXJSAMPLE - (y + Cbbtab[cb])]; /* blue */
  162693. /* K passes through unchanged */
  162694. outptr[3] = inptr3[col]; /* don't need GETJSAMPLE here */
  162695. outptr += 4;
  162696. }
  162697. }
  162698. }
  162699. /*
  162700. * Empty method for start_pass.
  162701. */
  162702. METHODDEF(void)
  162703. start_pass_dcolor (j_decompress_ptr cinfo)
  162704. {
  162705. /* no work needed */
  162706. }
  162707. /*
  162708. * Module initialization routine for output colorspace conversion.
  162709. */
  162710. GLOBAL(void)
  162711. jinit_color_deconverter (j_decompress_ptr cinfo)
  162712. {
  162713. my_cconvert_ptr2 cconvert;
  162714. int ci;
  162715. cconvert = (my_cconvert_ptr2)
  162716. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162717. SIZEOF(my_color_deconverter2));
  162718. cinfo->cconvert = (struct jpeg_color_deconverter *) cconvert;
  162719. cconvert->pub.start_pass = start_pass_dcolor;
  162720. /* Make sure num_components agrees with jpeg_color_space */
  162721. switch (cinfo->jpeg_color_space) {
  162722. case JCS_GRAYSCALE:
  162723. if (cinfo->num_components != 1)
  162724. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162725. break;
  162726. case JCS_RGB:
  162727. case JCS_YCbCr:
  162728. if (cinfo->num_components != 3)
  162729. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162730. break;
  162731. case JCS_CMYK:
  162732. case JCS_YCCK:
  162733. if (cinfo->num_components != 4)
  162734. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162735. break;
  162736. default: /* JCS_UNKNOWN can be anything */
  162737. if (cinfo->num_components < 1)
  162738. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162739. break;
  162740. }
  162741. /* Set out_color_components and conversion method based on requested space.
  162742. * Also clear the component_needed flags for any unused components,
  162743. * so that earlier pipeline stages can avoid useless computation.
  162744. */
  162745. switch (cinfo->out_color_space) {
  162746. case JCS_GRAYSCALE:
  162747. cinfo->out_color_components = 1;
  162748. if (cinfo->jpeg_color_space == JCS_GRAYSCALE ||
  162749. cinfo->jpeg_color_space == JCS_YCbCr) {
  162750. cconvert->pub.color_convert = grayscale_convert2;
  162751. /* For color->grayscale conversion, only the Y (0) component is needed */
  162752. for (ci = 1; ci < cinfo->num_components; ci++)
  162753. cinfo->comp_info[ci].component_needed = FALSE;
  162754. } else
  162755. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162756. break;
  162757. case JCS_RGB:
  162758. cinfo->out_color_components = RGB_PIXELSIZE;
  162759. if (cinfo->jpeg_color_space == JCS_YCbCr) {
  162760. cconvert->pub.color_convert = ycc_rgb_convert;
  162761. build_ycc_rgb_table(cinfo);
  162762. } else if (cinfo->jpeg_color_space == JCS_GRAYSCALE) {
  162763. cconvert->pub.color_convert = gray_rgb_convert;
  162764. } else if (cinfo->jpeg_color_space == JCS_RGB && RGB_PIXELSIZE == 3) {
  162765. cconvert->pub.color_convert = null_convert2;
  162766. } else
  162767. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162768. break;
  162769. case JCS_CMYK:
  162770. cinfo->out_color_components = 4;
  162771. if (cinfo->jpeg_color_space == JCS_YCCK) {
  162772. cconvert->pub.color_convert = ycck_cmyk_convert;
  162773. build_ycc_rgb_table(cinfo);
  162774. } else if (cinfo->jpeg_color_space == JCS_CMYK) {
  162775. cconvert->pub.color_convert = null_convert2;
  162776. } else
  162777. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162778. break;
  162779. default:
  162780. /* Permit null conversion to same output space */
  162781. if (cinfo->out_color_space == cinfo->jpeg_color_space) {
  162782. cinfo->out_color_components = cinfo->num_components;
  162783. cconvert->pub.color_convert = null_convert2;
  162784. } else /* unsupported non-null conversion */
  162785. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162786. break;
  162787. }
  162788. if (cinfo->quantize_colors)
  162789. cinfo->output_components = 1; /* single colormapped output component */
  162790. else
  162791. cinfo->output_components = cinfo->out_color_components;
  162792. }
  162793. /********* End of inlined file: jdcolor.c *********/
  162794. #undef FIX
  162795. /********* Start of inlined file: jddctmgr.c *********/
  162796. #define JPEG_INTERNALS
  162797. /*
  162798. * The decompressor input side (jdinput.c) saves away the appropriate
  162799. * quantization table for each component at the start of the first scan
  162800. * involving that component. (This is necessary in order to correctly
  162801. * decode files that reuse Q-table slots.)
  162802. * When we are ready to make an output pass, the saved Q-table is converted
  162803. * to a multiplier table that will actually be used by the IDCT routine.
  162804. * The multiplier table contents are IDCT-method-dependent. To support
  162805. * application changes in IDCT method between scans, we can remake the
  162806. * multiplier tables if necessary.
  162807. * In buffered-image mode, the first output pass may occur before any data
  162808. * has been seen for some components, and thus before their Q-tables have
  162809. * been saved away. To handle this case, multiplier tables are preset
  162810. * to zeroes; the result of the IDCT will be a neutral gray level.
  162811. */
  162812. /* Private subobject for this module */
  162813. typedef struct {
  162814. struct jpeg_inverse_dct pub; /* public fields */
  162815. /* This array contains the IDCT method code that each multiplier table
  162816. * is currently set up for, or -1 if it's not yet set up.
  162817. * The actual multiplier tables are pointed to by dct_table in the
  162818. * per-component comp_info structures.
  162819. */
  162820. int cur_method[MAX_COMPONENTS];
  162821. } my_idct_controller;
  162822. typedef my_idct_controller * my_idct_ptr;
  162823. /* Allocated multiplier tables: big enough for any supported variant */
  162824. typedef union {
  162825. ISLOW_MULT_TYPE islow_array[DCTSIZE2];
  162826. #ifdef DCT_IFAST_SUPPORTED
  162827. IFAST_MULT_TYPE ifast_array[DCTSIZE2];
  162828. #endif
  162829. #ifdef DCT_FLOAT_SUPPORTED
  162830. FLOAT_MULT_TYPE float_array[DCTSIZE2];
  162831. #endif
  162832. } multiplier_table;
  162833. /* The current scaled-IDCT routines require ISLOW-style multiplier tables,
  162834. * so be sure to compile that code if either ISLOW or SCALING is requested.
  162835. */
  162836. #ifdef DCT_ISLOW_SUPPORTED
  162837. #define PROVIDE_ISLOW_TABLES
  162838. #else
  162839. #ifdef IDCT_SCALING_SUPPORTED
  162840. #define PROVIDE_ISLOW_TABLES
  162841. #endif
  162842. #endif
  162843. /*
  162844. * Prepare for an output pass.
  162845. * Here we select the proper IDCT routine for each component and build
  162846. * a matching multiplier table.
  162847. */
  162848. METHODDEF(void)
  162849. start_pass (j_decompress_ptr cinfo)
  162850. {
  162851. my_idct_ptr idct = (my_idct_ptr) cinfo->idct;
  162852. int ci, i;
  162853. jpeg_component_info *compptr;
  162854. int method = 0;
  162855. inverse_DCT_method_ptr method_ptr = NULL;
  162856. JQUANT_TBL * qtbl;
  162857. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  162858. ci++, compptr++) {
  162859. /* Select the proper IDCT routine for this component's scaling */
  162860. switch (compptr->DCT_scaled_size) {
  162861. #ifdef IDCT_SCALING_SUPPORTED
  162862. case 1:
  162863. method_ptr = jpeg_idct_1x1;
  162864. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  162865. break;
  162866. case 2:
  162867. method_ptr = jpeg_idct_2x2;
  162868. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  162869. break;
  162870. case 4:
  162871. method_ptr = jpeg_idct_4x4;
  162872. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  162873. break;
  162874. #endif
  162875. case DCTSIZE:
  162876. switch (cinfo->dct_method) {
  162877. #ifdef DCT_ISLOW_SUPPORTED
  162878. case JDCT_ISLOW:
  162879. method_ptr = jpeg_idct_islow;
  162880. method = JDCT_ISLOW;
  162881. break;
  162882. #endif
  162883. #ifdef DCT_IFAST_SUPPORTED
  162884. case JDCT_IFAST:
  162885. method_ptr = jpeg_idct_ifast;
  162886. method = JDCT_IFAST;
  162887. break;
  162888. #endif
  162889. #ifdef DCT_FLOAT_SUPPORTED
  162890. case JDCT_FLOAT:
  162891. method_ptr = jpeg_idct_float;
  162892. method = JDCT_FLOAT;
  162893. break;
  162894. #endif
  162895. default:
  162896. ERREXIT(cinfo, JERR_NOT_COMPILED);
  162897. break;
  162898. }
  162899. break;
  162900. default:
  162901. ERREXIT1(cinfo, JERR_BAD_DCTSIZE, compptr->DCT_scaled_size);
  162902. break;
  162903. }
  162904. idct->pub.inverse_DCT[ci] = method_ptr;
  162905. /* Create multiplier table from quant table.
  162906. * However, we can skip this if the component is uninteresting
  162907. * or if we already built the table. Also, if no quant table
  162908. * has yet been saved for the component, we leave the
  162909. * multiplier table all-zero; we'll be reading zeroes from the
  162910. * coefficient controller's buffer anyway.
  162911. */
  162912. if (! compptr->component_needed || idct->cur_method[ci] == method)
  162913. continue;
  162914. qtbl = compptr->quant_table;
  162915. if (qtbl == NULL) /* happens if no data yet for component */
  162916. continue;
  162917. idct->cur_method[ci] = method;
  162918. switch (method) {
  162919. #ifdef PROVIDE_ISLOW_TABLES
  162920. case JDCT_ISLOW:
  162921. {
  162922. /* For LL&M IDCT method, multipliers are equal to raw quantization
  162923. * coefficients, but are stored as ints to ensure access efficiency.
  162924. */
  162925. ISLOW_MULT_TYPE * ismtbl = (ISLOW_MULT_TYPE *) compptr->dct_table;
  162926. for (i = 0; i < DCTSIZE2; i++) {
  162927. ismtbl[i] = (ISLOW_MULT_TYPE) qtbl->quantval[i];
  162928. }
  162929. }
  162930. break;
  162931. #endif
  162932. #ifdef DCT_IFAST_SUPPORTED
  162933. case JDCT_IFAST:
  162934. {
  162935. /* For AA&N IDCT method, multipliers are equal to quantization
  162936. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  162937. * scalefactor[0] = 1
  162938. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  162939. * For integer operation, the multiplier table is to be scaled by
  162940. * IFAST_SCALE_BITS.
  162941. */
  162942. IFAST_MULT_TYPE * ifmtbl = (IFAST_MULT_TYPE *) compptr->dct_table;
  162943. #define CONST_BITS 14
  162944. static const INT16 aanscales[DCTSIZE2] = {
  162945. /* precomputed values scaled up by 14 bits */
  162946. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  162947. 22725, 31521, 29692, 26722, 22725, 17855, 12299, 6270,
  162948. 21407, 29692, 27969, 25172, 21407, 16819, 11585, 5906,
  162949. 19266, 26722, 25172, 22654, 19266, 15137, 10426, 5315,
  162950. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  162951. 12873, 17855, 16819, 15137, 12873, 10114, 6967, 3552,
  162952. 8867, 12299, 11585, 10426, 8867, 6967, 4799, 2446,
  162953. 4520, 6270, 5906, 5315, 4520, 3552, 2446, 1247
  162954. };
  162955. SHIFT_TEMPS
  162956. for (i = 0; i < DCTSIZE2; i++) {
  162957. ifmtbl[i] = (IFAST_MULT_TYPE)
  162958. DESCALE(MULTIPLY16V16((INT32) qtbl->quantval[i],
  162959. (INT32) aanscales[i]),
  162960. CONST_BITS-IFAST_SCALE_BITS);
  162961. }
  162962. }
  162963. break;
  162964. #endif
  162965. #ifdef DCT_FLOAT_SUPPORTED
  162966. case JDCT_FLOAT:
  162967. {
  162968. /* For float AA&N IDCT method, multipliers are equal to quantization
  162969. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  162970. * scalefactor[0] = 1
  162971. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  162972. */
  162973. FLOAT_MULT_TYPE * fmtbl = (FLOAT_MULT_TYPE *) compptr->dct_table;
  162974. int row, col;
  162975. static const double aanscalefactor[DCTSIZE] = {
  162976. 1.0, 1.387039845, 1.306562965, 1.175875602,
  162977. 1.0, 0.785694958, 0.541196100, 0.275899379
  162978. };
  162979. i = 0;
  162980. for (row = 0; row < DCTSIZE; row++) {
  162981. for (col = 0; col < DCTSIZE; col++) {
  162982. fmtbl[i] = (FLOAT_MULT_TYPE)
  162983. ((double) qtbl->quantval[i] *
  162984. aanscalefactor[row] * aanscalefactor[col]);
  162985. i++;
  162986. }
  162987. }
  162988. }
  162989. break;
  162990. #endif
  162991. default:
  162992. ERREXIT(cinfo, JERR_NOT_COMPILED);
  162993. break;
  162994. }
  162995. }
  162996. }
  162997. /*
  162998. * Initialize IDCT manager.
  162999. */
  163000. GLOBAL(void)
  163001. jinit_inverse_dct (j_decompress_ptr cinfo)
  163002. {
  163003. my_idct_ptr idct;
  163004. int ci;
  163005. jpeg_component_info *compptr;
  163006. idct = (my_idct_ptr)
  163007. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163008. SIZEOF(my_idct_controller));
  163009. cinfo->idct = (struct jpeg_inverse_dct *) idct;
  163010. idct->pub.start_pass = start_pass;
  163011. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  163012. ci++, compptr++) {
  163013. /* Allocate and pre-zero a multiplier table for each component */
  163014. compptr->dct_table =
  163015. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163016. SIZEOF(multiplier_table));
  163017. MEMZERO(compptr->dct_table, SIZEOF(multiplier_table));
  163018. /* Mark multiplier table not yet set up for any method */
  163019. idct->cur_method[ci] = -1;
  163020. }
  163021. }
  163022. /********* End of inlined file: jddctmgr.c *********/
  163023. #undef CONST_BITS
  163024. #undef ASSIGN_STATE
  163025. /********* Start of inlined file: jdhuff.c *********/
  163026. #define JPEG_INTERNALS
  163027. /********* Start of inlined file: jdhuff.h *********/
  163028. /* Short forms of external names for systems with brain-damaged linkers. */
  163029. #ifndef __jdhuff_h__
  163030. #define __jdhuff_h__
  163031. #ifdef NEED_SHORT_EXTERNAL_NAMES
  163032. #define jpeg_make_d_derived_tbl jMkDDerived
  163033. #define jpeg_fill_bit_buffer jFilBitBuf
  163034. #define jpeg_huff_decode jHufDecode
  163035. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  163036. /* Derived data constructed for each Huffman table */
  163037. #define HUFF_LOOKAHEAD 8 /* # of bits of lookahead */
  163038. typedef struct {
  163039. /* Basic tables: (element [0] of each array is unused) */
  163040. INT32 maxcode[18]; /* largest code of length k (-1 if none) */
  163041. /* (maxcode[17] is a sentinel to ensure jpeg_huff_decode terminates) */
  163042. INT32 valoffset[17]; /* huffval[] offset for codes of length k */
  163043. /* valoffset[k] = huffval[] index of 1st symbol of code length k, less
  163044. * the smallest code of length k; so given a code of length k, the
  163045. * corresponding symbol is huffval[code + valoffset[k]]
  163046. */
  163047. /* Link to public Huffman table (needed only in jpeg_huff_decode) */
  163048. JHUFF_TBL *pub;
  163049. /* Lookahead tables: indexed by the next HUFF_LOOKAHEAD bits of
  163050. * the input data stream. If the next Huffman code is no more
  163051. * than HUFF_LOOKAHEAD bits long, we can obtain its length and
  163052. * the corresponding symbol directly from these tables.
  163053. */
  163054. int look_nbits[1<<HUFF_LOOKAHEAD]; /* # bits, or 0 if too long */
  163055. UINT8 look_sym[1<<HUFF_LOOKAHEAD]; /* symbol, or unused */
  163056. } d_derived_tbl;
  163057. /* Expand a Huffman table definition into the derived format */
  163058. EXTERN(void) jpeg_make_d_derived_tbl
  163059. JPP((j_decompress_ptr cinfo, boolean isDC, int tblno,
  163060. d_derived_tbl ** pdtbl));
  163061. /*
  163062. * Fetching the next N bits from the input stream is a time-critical operation
  163063. * for the Huffman decoders. We implement it with a combination of inline
  163064. * macros and out-of-line subroutines. Note that N (the number of bits
  163065. * demanded at one time) never exceeds 15 for JPEG use.
  163066. *
  163067. * We read source bytes into get_buffer and dole out bits as needed.
  163068. * If get_buffer already contains enough bits, they are fetched in-line
  163069. * by the macros CHECK_BIT_BUFFER and GET_BITS. When there aren't enough
  163070. * bits, jpeg_fill_bit_buffer is called; it will attempt to fill get_buffer
  163071. * as full as possible (not just to the number of bits needed; this
  163072. * prefetching reduces the overhead cost of calling jpeg_fill_bit_buffer).
  163073. * Note that jpeg_fill_bit_buffer may return FALSE to indicate suspension.
  163074. * On TRUE return, jpeg_fill_bit_buffer guarantees that get_buffer contains
  163075. * at least the requested number of bits --- dummy zeroes are inserted if
  163076. * necessary.
  163077. */
  163078. typedef INT32 bit_buf_type; /* type of bit-extraction buffer */
  163079. #define BIT_BUF_SIZE 32 /* size of buffer in bits */
  163080. /* If long is > 32 bits on your machine, and shifting/masking longs is
  163081. * reasonably fast, making bit_buf_type be long and setting BIT_BUF_SIZE
  163082. * appropriately should be a win. Unfortunately we can't define the size
  163083. * with something like #define BIT_BUF_SIZE (sizeof(bit_buf_type)*8)
  163084. * because not all machines measure sizeof in 8-bit bytes.
  163085. */
  163086. typedef struct { /* Bitreading state saved across MCUs */
  163087. bit_buf_type get_buffer; /* current bit-extraction buffer */
  163088. int bits_left; /* # of unused bits in it */
  163089. } bitread_perm_state;
  163090. typedef struct { /* Bitreading working state within an MCU */
  163091. /* Current data source location */
  163092. /* We need a copy, rather than munging the original, in case of suspension */
  163093. const JOCTET * next_input_byte; /* => next byte to read from source */
  163094. size_t bytes_in_buffer; /* # of bytes remaining in source buffer */
  163095. /* Bit input buffer --- note these values are kept in register variables,
  163096. * not in this struct, inside the inner loops.
  163097. */
  163098. bit_buf_type get_buffer; /* current bit-extraction buffer */
  163099. int bits_left; /* # of unused bits in it */
  163100. /* Pointer needed by jpeg_fill_bit_buffer. */
  163101. j_decompress_ptr cinfo; /* back link to decompress master record */
  163102. } bitread_working_state;
  163103. /* Macros to declare and load/save bitread local variables. */
  163104. #define BITREAD_STATE_VARS \
  163105. register bit_buf_type get_buffer; \
  163106. register int bits_left; \
  163107. bitread_working_state br_state
  163108. #define BITREAD_LOAD_STATE(cinfop,permstate) \
  163109. br_state.cinfo = cinfop; \
  163110. br_state.next_input_byte = cinfop->src->next_input_byte; \
  163111. br_state.bytes_in_buffer = cinfop->src->bytes_in_buffer; \
  163112. get_buffer = permstate.get_buffer; \
  163113. bits_left = permstate.bits_left;
  163114. #define BITREAD_SAVE_STATE(cinfop,permstate) \
  163115. cinfop->src->next_input_byte = br_state.next_input_byte; \
  163116. cinfop->src->bytes_in_buffer = br_state.bytes_in_buffer; \
  163117. permstate.get_buffer = get_buffer; \
  163118. permstate.bits_left = bits_left
  163119. /*
  163120. * These macros provide the in-line portion of bit fetching.
  163121. * Use CHECK_BIT_BUFFER to ensure there are N bits in get_buffer
  163122. * before using GET_BITS, PEEK_BITS, or DROP_BITS.
  163123. * The variables get_buffer and bits_left are assumed to be locals,
  163124. * but the state struct might not be (jpeg_huff_decode needs this).
  163125. * CHECK_BIT_BUFFER(state,n,action);
  163126. * Ensure there are N bits in get_buffer; if suspend, take action.
  163127. * val = GET_BITS(n);
  163128. * Fetch next N bits.
  163129. * val = PEEK_BITS(n);
  163130. * Fetch next N bits without removing them from the buffer.
  163131. * DROP_BITS(n);
  163132. * Discard next N bits.
  163133. * The value N should be a simple variable, not an expression, because it
  163134. * is evaluated multiple times.
  163135. */
  163136. #define CHECK_BIT_BUFFER(state,nbits,action) \
  163137. { if (bits_left < (nbits)) { \
  163138. if (! jpeg_fill_bit_buffer(&(state),get_buffer,bits_left,nbits)) \
  163139. { action; } \
  163140. get_buffer = (state).get_buffer; bits_left = (state).bits_left; } }
  163141. #define GET_BITS(nbits) \
  163142. (((int) (get_buffer >> (bits_left -= (nbits)))) & ((1<<(nbits))-1))
  163143. #define PEEK_BITS(nbits) \
  163144. (((int) (get_buffer >> (bits_left - (nbits)))) & ((1<<(nbits))-1))
  163145. #define DROP_BITS(nbits) \
  163146. (bits_left -= (nbits))
  163147. /* Load up the bit buffer to a depth of at least nbits */
  163148. EXTERN(boolean) jpeg_fill_bit_buffer
  163149. JPP((bitread_working_state * state, register bit_buf_type get_buffer,
  163150. register int bits_left, int nbits));
  163151. /*
  163152. * Code for extracting next Huffman-coded symbol from input bit stream.
  163153. * Again, this is time-critical and we make the main paths be macros.
  163154. *
  163155. * We use a lookahead table to process codes of up to HUFF_LOOKAHEAD bits
  163156. * without looping. Usually, more than 95% of the Huffman codes will be 8
  163157. * or fewer bits long. The few overlength codes are handled with a loop,
  163158. * which need not be inline code.
  163159. *
  163160. * Notes about the HUFF_DECODE macro:
  163161. * 1. Near the end of the data segment, we may fail to get enough bits
  163162. * for a lookahead. In that case, we do it the hard way.
  163163. * 2. If the lookahead table contains no entry, the next code must be
  163164. * more than HUFF_LOOKAHEAD bits long.
  163165. * 3. jpeg_huff_decode returns -1 if forced to suspend.
  163166. */
  163167. #define HUFF_DECODE(result,state,htbl,failaction,slowlabel) \
  163168. { register int nb, look; \
  163169. if (bits_left < HUFF_LOOKAHEAD) { \
  163170. if (! jpeg_fill_bit_buffer(&state,get_buffer,bits_left, 0)) {failaction;} \
  163171. get_buffer = state.get_buffer; bits_left = state.bits_left; \
  163172. if (bits_left < HUFF_LOOKAHEAD) { \
  163173. nb = 1; goto slowlabel; \
  163174. } \
  163175. } \
  163176. look = PEEK_BITS(HUFF_LOOKAHEAD); \
  163177. if ((nb = htbl->look_nbits[look]) != 0) { \
  163178. DROP_BITS(nb); \
  163179. result = htbl->look_sym[look]; \
  163180. } else { \
  163181. nb = HUFF_LOOKAHEAD+1; \
  163182. slowlabel: \
  163183. if ((result=jpeg_huff_decode(&state,get_buffer,bits_left,htbl,nb)) < 0) \
  163184. { failaction; } \
  163185. get_buffer = state.get_buffer; bits_left = state.bits_left; \
  163186. } \
  163187. }
  163188. /* Out-of-line case for Huffman code fetching */
  163189. EXTERN(int) jpeg_huff_decode
  163190. JPP((bitread_working_state * state, register bit_buf_type get_buffer,
  163191. register int bits_left, d_derived_tbl * htbl, int min_bits));
  163192. #endif
  163193. /********* End of inlined file: jdhuff.h *********/
  163194. /* Declarations shared with jdphuff.c */
  163195. /*
  163196. * Expanded entropy decoder object for Huffman decoding.
  163197. *
  163198. * The savable_state subrecord contains fields that change within an MCU,
  163199. * but must not be updated permanently until we complete the MCU.
  163200. */
  163201. typedef struct {
  163202. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  163203. } savable_state2;
  163204. /* This macro is to work around compilers with missing or broken
  163205. * structure assignment. You'll need to fix this code if you have
  163206. * such a compiler and you change MAX_COMPS_IN_SCAN.
  163207. */
  163208. #ifndef NO_STRUCT_ASSIGN
  163209. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  163210. #else
  163211. #if MAX_COMPS_IN_SCAN == 4
  163212. #define ASSIGN_STATE(dest,src) \
  163213. ((dest).last_dc_val[0] = (src).last_dc_val[0], \
  163214. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  163215. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  163216. (dest).last_dc_val[3] = (src).last_dc_val[3])
  163217. #endif
  163218. #endif
  163219. typedef struct {
  163220. struct jpeg_entropy_decoder pub; /* public fields */
  163221. /* These fields are loaded into local variables at start of each MCU.
  163222. * In case of suspension, we exit WITHOUT updating them.
  163223. */
  163224. bitread_perm_state bitstate; /* Bit buffer at start of MCU */
  163225. savable_state2 saved; /* Other state at start of MCU */
  163226. /* These fields are NOT loaded into local working state. */
  163227. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  163228. /* Pointers to derived tables (these workspaces have image lifespan) */
  163229. d_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
  163230. d_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
  163231. /* Precalculated info set up by start_pass for use in decode_mcu: */
  163232. /* Pointers to derived tables to be used for each block within an MCU */
  163233. d_derived_tbl * dc_cur_tbls[D_MAX_BLOCKS_IN_MCU];
  163234. d_derived_tbl * ac_cur_tbls[D_MAX_BLOCKS_IN_MCU];
  163235. /* Whether we care about the DC and AC coefficient values for each block */
  163236. boolean dc_needed[D_MAX_BLOCKS_IN_MCU];
  163237. boolean ac_needed[D_MAX_BLOCKS_IN_MCU];
  163238. } huff_entropy_decoder2;
  163239. typedef huff_entropy_decoder2 * huff_entropy_ptr2;
  163240. /*
  163241. * Initialize for a Huffman-compressed scan.
  163242. */
  163243. METHODDEF(void)
  163244. start_pass_huff_decoder (j_decompress_ptr cinfo)
  163245. {
  163246. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  163247. int ci, blkn, dctbl, actbl;
  163248. jpeg_component_info * compptr;
  163249. /* Check that the scan parameters Ss, Se, Ah/Al are OK for sequential JPEG.
  163250. * This ought to be an error condition, but we make it a warning because
  163251. * there are some baseline files out there with all zeroes in these bytes.
  163252. */
  163253. if (cinfo->Ss != 0 || cinfo->Se != DCTSIZE2-1 ||
  163254. cinfo->Ah != 0 || cinfo->Al != 0)
  163255. WARNMS(cinfo, JWRN_NOT_SEQUENTIAL);
  163256. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  163257. compptr = cinfo->cur_comp_info[ci];
  163258. dctbl = compptr->dc_tbl_no;
  163259. actbl = compptr->ac_tbl_no;
  163260. /* Compute derived values for Huffman tables */
  163261. /* We may do this more than once for a table, but it's not expensive */
  163262. jpeg_make_d_derived_tbl(cinfo, TRUE, dctbl,
  163263. & entropy->dc_derived_tbls[dctbl]);
  163264. jpeg_make_d_derived_tbl(cinfo, FALSE, actbl,
  163265. & entropy->ac_derived_tbls[actbl]);
  163266. /* Initialize DC predictions to 0 */
  163267. entropy->saved.last_dc_val[ci] = 0;
  163268. }
  163269. /* Precalculate decoding info for each block in an MCU of this scan */
  163270. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  163271. ci = cinfo->MCU_membership[blkn];
  163272. compptr = cinfo->cur_comp_info[ci];
  163273. /* Precalculate which table to use for each block */
  163274. entropy->dc_cur_tbls[blkn] = entropy->dc_derived_tbls[compptr->dc_tbl_no];
  163275. entropy->ac_cur_tbls[blkn] = entropy->ac_derived_tbls[compptr->ac_tbl_no];
  163276. /* Decide whether we really care about the coefficient values */
  163277. if (compptr->component_needed) {
  163278. entropy->dc_needed[blkn] = TRUE;
  163279. /* we don't need the ACs if producing a 1/8th-size image */
  163280. entropy->ac_needed[blkn] = (compptr->DCT_scaled_size > 1);
  163281. } else {
  163282. entropy->dc_needed[blkn] = entropy->ac_needed[blkn] = FALSE;
  163283. }
  163284. }
  163285. /* Initialize bitread state variables */
  163286. entropy->bitstate.bits_left = 0;
  163287. entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
  163288. entropy->pub.insufficient_data = FALSE;
  163289. /* Initialize restart counter */
  163290. entropy->restarts_to_go = cinfo->restart_interval;
  163291. }
  163292. /*
  163293. * Compute the derived values for a Huffman table.
  163294. * This routine also performs some validation checks on the table.
  163295. *
  163296. * Note this is also used by jdphuff.c.
  163297. */
  163298. GLOBAL(void)
  163299. jpeg_make_d_derived_tbl (j_decompress_ptr cinfo, boolean isDC, int tblno,
  163300. d_derived_tbl ** pdtbl)
  163301. {
  163302. JHUFF_TBL *htbl;
  163303. d_derived_tbl *dtbl;
  163304. int p, i, l, si, numsymbols;
  163305. int lookbits, ctr;
  163306. char huffsize[257];
  163307. unsigned int huffcode[257];
  163308. unsigned int code;
  163309. /* Note that huffsize[] and huffcode[] are filled in code-length order,
  163310. * paralleling the order of the symbols themselves in htbl->huffval[].
  163311. */
  163312. /* Find the input Huffman table */
  163313. if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
  163314. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  163315. htbl =
  163316. isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];
  163317. if (htbl == NULL)
  163318. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  163319. /* Allocate a workspace if we haven't already done so. */
  163320. if (*pdtbl == NULL)
  163321. *pdtbl = (d_derived_tbl *)
  163322. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163323. SIZEOF(d_derived_tbl));
  163324. dtbl = *pdtbl;
  163325. dtbl->pub = htbl; /* fill in back link */
  163326. /* Figure C.1: make table of Huffman code length for each symbol */
  163327. p = 0;
  163328. for (l = 1; l <= 16; l++) {
  163329. i = (int) htbl->bits[l];
  163330. if (i < 0 || p + i > 256) /* protect against table overrun */
  163331. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  163332. while (i--)
  163333. huffsize[p++] = (char) l;
  163334. }
  163335. huffsize[p] = 0;
  163336. numsymbols = p;
  163337. /* Figure C.2: generate the codes themselves */
  163338. /* We also validate that the counts represent a legal Huffman code tree. */
  163339. code = 0;
  163340. si = huffsize[0];
  163341. p = 0;
  163342. while (huffsize[p]) {
  163343. while (((int) huffsize[p]) == si) {
  163344. huffcode[p++] = code;
  163345. code++;
  163346. }
  163347. /* code is now 1 more than the last code used for codelength si; but
  163348. * it must still fit in si bits, since no code is allowed to be all ones.
  163349. */
  163350. if (((INT32) code) >= (((INT32) 1) << si))
  163351. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  163352. code <<= 1;
  163353. si++;
  163354. }
  163355. /* Figure F.15: generate decoding tables for bit-sequential decoding */
  163356. p = 0;
  163357. for (l = 1; l <= 16; l++) {
  163358. if (htbl->bits[l]) {
  163359. /* valoffset[l] = huffval[] index of 1st symbol of code length l,
  163360. * minus the minimum code of length l
  163361. */
  163362. dtbl->valoffset[l] = (INT32) p - (INT32) huffcode[p];
  163363. p += htbl->bits[l];
  163364. dtbl->maxcode[l] = huffcode[p-1]; /* maximum code of length l */
  163365. } else {
  163366. dtbl->maxcode[l] = -1; /* -1 if no codes of this length */
  163367. }
  163368. }
  163369. dtbl->maxcode[17] = 0xFFFFFL; /* ensures jpeg_huff_decode terminates */
  163370. /* Compute lookahead tables to speed up decoding.
  163371. * First we set all the table entries to 0, indicating "too long";
  163372. * then we iterate through the Huffman codes that are short enough and
  163373. * fill in all the entries that correspond to bit sequences starting
  163374. * with that code.
  163375. */
  163376. MEMZERO(dtbl->look_nbits, SIZEOF(dtbl->look_nbits));
  163377. p = 0;
  163378. for (l = 1; l <= HUFF_LOOKAHEAD; l++) {
  163379. for (i = 1; i <= (int) htbl->bits[l]; i++, p++) {
  163380. /* l = current code's length, p = its index in huffcode[] & huffval[]. */
  163381. /* Generate left-justified code followed by all possible bit sequences */
  163382. lookbits = huffcode[p] << (HUFF_LOOKAHEAD-l);
  163383. for (ctr = 1 << (HUFF_LOOKAHEAD-l); ctr > 0; ctr--) {
  163384. dtbl->look_nbits[lookbits] = l;
  163385. dtbl->look_sym[lookbits] = htbl->huffval[p];
  163386. lookbits++;
  163387. }
  163388. }
  163389. }
  163390. /* Validate symbols as being reasonable.
  163391. * For AC tables, we make no check, but accept all byte values 0..255.
  163392. * For DC tables, we require the symbols to be in range 0..15.
  163393. * (Tighter bounds could be applied depending on the data depth and mode,
  163394. * but this is sufficient to ensure safe decoding.)
  163395. */
  163396. if (isDC) {
  163397. for (i = 0; i < numsymbols; i++) {
  163398. int sym = htbl->huffval[i];
  163399. if (sym < 0 || sym > 15)
  163400. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  163401. }
  163402. }
  163403. }
  163404. /*
  163405. * Out-of-line code for bit fetching (shared with jdphuff.c).
  163406. * See jdhuff.h for info about usage.
  163407. * Note: current values of get_buffer and bits_left are passed as parameters,
  163408. * but are returned in the corresponding fields of the state struct.
  163409. *
  163410. * On most machines MIN_GET_BITS should be 25 to allow the full 32-bit width
  163411. * of get_buffer to be used. (On machines with wider words, an even larger
  163412. * buffer could be used.) However, on some machines 32-bit shifts are
  163413. * quite slow and take time proportional to the number of places shifted.
  163414. * (This is true with most PC compilers, for instance.) In this case it may
  163415. * be a win to set MIN_GET_BITS to the minimum value of 15. This reduces the
  163416. * average shift distance at the cost of more calls to jpeg_fill_bit_buffer.
  163417. */
  163418. #ifdef SLOW_SHIFT_32
  163419. #define MIN_GET_BITS 15 /* minimum allowable value */
  163420. #else
  163421. #define MIN_GET_BITS (BIT_BUF_SIZE-7)
  163422. #endif
  163423. GLOBAL(boolean)
  163424. jpeg_fill_bit_buffer (bitread_working_state * state,
  163425. register bit_buf_type get_buffer, register int bits_left,
  163426. int nbits)
  163427. /* Load up the bit buffer to a depth of at least nbits */
  163428. {
  163429. /* Copy heavily used state fields into locals (hopefully registers) */
  163430. register const JOCTET * next_input_byte = state->next_input_byte;
  163431. register size_t bytes_in_buffer = state->bytes_in_buffer;
  163432. j_decompress_ptr cinfo = state->cinfo;
  163433. /* Attempt to load at least MIN_GET_BITS bits into get_buffer. */
  163434. /* (It is assumed that no request will be for more than that many bits.) */
  163435. /* We fail to do so only if we hit a marker or are forced to suspend. */
  163436. if (cinfo->unread_marker == 0) { /* cannot advance past a marker */
  163437. while (bits_left < MIN_GET_BITS) {
  163438. register int c;
  163439. /* Attempt to read a byte */
  163440. if (bytes_in_buffer == 0) {
  163441. if (! (*cinfo->src->fill_input_buffer) (cinfo))
  163442. return FALSE;
  163443. next_input_byte = cinfo->src->next_input_byte;
  163444. bytes_in_buffer = cinfo->src->bytes_in_buffer;
  163445. }
  163446. bytes_in_buffer--;
  163447. c = GETJOCTET(*next_input_byte++);
  163448. /* If it's 0xFF, check and discard stuffed zero byte */
  163449. if (c == 0xFF) {
  163450. /* Loop here to discard any padding FF's on terminating marker,
  163451. * so that we can save a valid unread_marker value. NOTE: we will
  163452. * accept multiple FF's followed by a 0 as meaning a single FF data
  163453. * byte. This data pattern is not valid according to the standard.
  163454. */
  163455. do {
  163456. if (bytes_in_buffer == 0) {
  163457. if (! (*cinfo->src->fill_input_buffer) (cinfo))
  163458. return FALSE;
  163459. next_input_byte = cinfo->src->next_input_byte;
  163460. bytes_in_buffer = cinfo->src->bytes_in_buffer;
  163461. }
  163462. bytes_in_buffer--;
  163463. c = GETJOCTET(*next_input_byte++);
  163464. } while (c == 0xFF);
  163465. if (c == 0) {
  163466. /* Found FF/00, which represents an FF data byte */
  163467. c = 0xFF;
  163468. } else {
  163469. /* Oops, it's actually a marker indicating end of compressed data.
  163470. * Save the marker code for later use.
  163471. * Fine point: it might appear that we should save the marker into
  163472. * bitread working state, not straight into permanent state. But
  163473. * once we have hit a marker, we cannot need to suspend within the
  163474. * current MCU, because we will read no more bytes from the data
  163475. * source. So it is OK to update permanent state right away.
  163476. */
  163477. cinfo->unread_marker = c;
  163478. /* See if we need to insert some fake zero bits. */
  163479. goto no_more_bytes;
  163480. }
  163481. }
  163482. /* OK, load c into get_buffer */
  163483. get_buffer = (get_buffer << 8) | c;
  163484. bits_left += 8;
  163485. } /* end while */
  163486. } else {
  163487. no_more_bytes:
  163488. /* We get here if we've read the marker that terminates the compressed
  163489. * data segment. There should be enough bits in the buffer register
  163490. * to satisfy the request; if so, no problem.
  163491. */
  163492. if (nbits > bits_left) {
  163493. /* Uh-oh. Report corrupted data to user and stuff zeroes into
  163494. * the data stream, so that we can produce some kind of image.
  163495. * We use a nonvolatile flag to ensure that only one warning message
  163496. * appears per data segment.
  163497. */
  163498. if (! cinfo->entropy->insufficient_data) {
  163499. WARNMS(cinfo, JWRN_HIT_MARKER);
  163500. cinfo->entropy->insufficient_data = TRUE;
  163501. }
  163502. /* Fill the buffer with zero bits */
  163503. get_buffer <<= MIN_GET_BITS - bits_left;
  163504. bits_left = MIN_GET_BITS;
  163505. }
  163506. }
  163507. /* Unload the local registers */
  163508. state->next_input_byte = next_input_byte;
  163509. state->bytes_in_buffer = bytes_in_buffer;
  163510. state->get_buffer = get_buffer;
  163511. state->bits_left = bits_left;
  163512. return TRUE;
  163513. }
  163514. /*
  163515. * Out-of-line code for Huffman code decoding.
  163516. * See jdhuff.h for info about usage.
  163517. */
  163518. GLOBAL(int)
  163519. jpeg_huff_decode (bitread_working_state * state,
  163520. register bit_buf_type get_buffer, register int bits_left,
  163521. d_derived_tbl * htbl, int min_bits)
  163522. {
  163523. register int l = min_bits;
  163524. register INT32 code;
  163525. /* HUFF_DECODE has determined that the code is at least min_bits */
  163526. /* bits long, so fetch that many bits in one swoop. */
  163527. CHECK_BIT_BUFFER(*state, l, return -1);
  163528. code = GET_BITS(l);
  163529. /* Collect the rest of the Huffman code one bit at a time. */
  163530. /* This is per Figure F.16 in the JPEG spec. */
  163531. while (code > htbl->maxcode[l]) {
  163532. code <<= 1;
  163533. CHECK_BIT_BUFFER(*state, 1, return -1);
  163534. code |= GET_BITS(1);
  163535. l++;
  163536. }
  163537. /* Unload the local registers */
  163538. state->get_buffer = get_buffer;
  163539. state->bits_left = bits_left;
  163540. /* With garbage input we may reach the sentinel value l = 17. */
  163541. if (l > 16) {
  163542. WARNMS(state->cinfo, JWRN_HUFF_BAD_CODE);
  163543. return 0; /* fake a zero as the safest result */
  163544. }
  163545. return htbl->pub->huffval[ (int) (code + htbl->valoffset[l]) ];
  163546. }
  163547. /*
  163548. * Check for a restart marker & resynchronize decoder.
  163549. * Returns FALSE if must suspend.
  163550. */
  163551. LOCAL(boolean)
  163552. process_restart (j_decompress_ptr cinfo)
  163553. {
  163554. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  163555. int ci;
  163556. /* Throw away any unused bits remaining in bit buffer; */
  163557. /* include any full bytes in next_marker's count of discarded bytes */
  163558. cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
  163559. entropy->bitstate.bits_left = 0;
  163560. /* Advance past the RSTn marker */
  163561. if (! (*cinfo->marker->read_restart_marker) (cinfo))
  163562. return FALSE;
  163563. /* Re-initialize DC predictions to 0 */
  163564. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  163565. entropy->saved.last_dc_val[ci] = 0;
  163566. /* Reset restart counter */
  163567. entropy->restarts_to_go = cinfo->restart_interval;
  163568. /* Reset out-of-data flag, unless read_restart_marker left us smack up
  163569. * against a marker. In that case we will end up treating the next data
  163570. * segment as empty, and we can avoid producing bogus output pixels by
  163571. * leaving the flag set.
  163572. */
  163573. if (cinfo->unread_marker == 0)
  163574. entropy->pub.insufficient_data = FALSE;
  163575. return TRUE;
  163576. }
  163577. /*
  163578. * Decode and return one MCU's worth of Huffman-compressed coefficients.
  163579. * The coefficients are reordered from zigzag order into natural array order,
  163580. * but are not dequantized.
  163581. *
  163582. * The i'th block of the MCU is stored into the block pointed to by
  163583. * MCU_data[i]. WE ASSUME THIS AREA HAS BEEN ZEROED BY THE CALLER.
  163584. * (Wholesale zeroing is usually a little faster than retail...)
  163585. *
  163586. * Returns FALSE if data source requested suspension. In that case no
  163587. * changes have been made to permanent state. (Exception: some output
  163588. * coefficients may already have been assigned. This is harmless for
  163589. * this module, since we'll just re-assign them on the next call.)
  163590. */
  163591. METHODDEF(boolean)
  163592. decode_mcu (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  163593. {
  163594. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  163595. int blkn;
  163596. BITREAD_STATE_VARS;
  163597. savable_state2 state;
  163598. /* Process restart marker if needed; may have to suspend */
  163599. if (cinfo->restart_interval) {
  163600. if (entropy->restarts_to_go == 0)
  163601. if (! process_restart(cinfo))
  163602. return FALSE;
  163603. }
  163604. /* If we've run out of data, just leave the MCU set to zeroes.
  163605. * This way, we return uniform gray for the remainder of the segment.
  163606. */
  163607. if (! entropy->pub.insufficient_data) {
  163608. /* Load up working state */
  163609. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  163610. ASSIGN_STATE(state, entropy->saved);
  163611. /* Outer loop handles each block in the MCU */
  163612. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  163613. JBLOCKROW block = MCU_data[blkn];
  163614. d_derived_tbl * dctbl = entropy->dc_cur_tbls[blkn];
  163615. d_derived_tbl * actbl = entropy->ac_cur_tbls[blkn];
  163616. register int s, k, r;
  163617. /* Decode a single block's worth of coefficients */
  163618. /* Section F.2.2.1: decode the DC coefficient difference */
  163619. HUFF_DECODE(s, br_state, dctbl, return FALSE, label1);
  163620. if (s) {
  163621. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  163622. r = GET_BITS(s);
  163623. s = HUFF_EXTEND(r, s);
  163624. }
  163625. if (entropy->dc_needed[blkn]) {
  163626. /* Convert DC difference to actual value, update last_dc_val */
  163627. int ci = cinfo->MCU_membership[blkn];
  163628. s += state.last_dc_val[ci];
  163629. state.last_dc_val[ci] = s;
  163630. /* Output the DC coefficient (assumes jpeg_natural_order[0] = 0) */
  163631. (*block)[0] = (JCOEF) s;
  163632. }
  163633. if (entropy->ac_needed[blkn]) {
  163634. /* Section F.2.2.2: decode the AC coefficients */
  163635. /* Since zeroes are skipped, output area must be cleared beforehand */
  163636. for (k = 1; k < DCTSIZE2; k++) {
  163637. HUFF_DECODE(s, br_state, actbl, return FALSE, label2);
  163638. r = s >> 4;
  163639. s &= 15;
  163640. if (s) {
  163641. k += r;
  163642. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  163643. r = GET_BITS(s);
  163644. s = HUFF_EXTEND(r, s);
  163645. /* Output coefficient in natural (dezigzagged) order.
  163646. * Note: the extra entries in jpeg_natural_order[] will save us
  163647. * if k >= DCTSIZE2, which could happen if the data is corrupted.
  163648. */
  163649. (*block)[jpeg_natural_order[k]] = (JCOEF) s;
  163650. } else {
  163651. if (r != 15)
  163652. break;
  163653. k += 15;
  163654. }
  163655. }
  163656. } else {
  163657. /* Section F.2.2.2: decode the AC coefficients */
  163658. /* In this path we just discard the values */
  163659. for (k = 1; k < DCTSIZE2; k++) {
  163660. HUFF_DECODE(s, br_state, actbl, return FALSE, label3);
  163661. r = s >> 4;
  163662. s &= 15;
  163663. if (s) {
  163664. k += r;
  163665. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  163666. DROP_BITS(s);
  163667. } else {
  163668. if (r != 15)
  163669. break;
  163670. k += 15;
  163671. }
  163672. }
  163673. }
  163674. }
  163675. /* Completed MCU, so update state */
  163676. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  163677. ASSIGN_STATE(entropy->saved, state);
  163678. }
  163679. /* Account for restart interval (no-op if not using restarts) */
  163680. entropy->restarts_to_go--;
  163681. return TRUE;
  163682. }
  163683. /*
  163684. * Module initialization routine for Huffman entropy decoding.
  163685. */
  163686. GLOBAL(void)
  163687. jinit_huff_decoder (j_decompress_ptr cinfo)
  163688. {
  163689. huff_entropy_ptr2 entropy;
  163690. int i;
  163691. entropy = (huff_entropy_ptr2)
  163692. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163693. SIZEOF(huff_entropy_decoder2));
  163694. cinfo->entropy = (struct jpeg_entropy_decoder *) entropy;
  163695. entropy->pub.start_pass = start_pass_huff_decoder;
  163696. entropy->pub.decode_mcu = decode_mcu;
  163697. /* Mark tables unallocated */
  163698. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  163699. entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
  163700. }
  163701. }
  163702. /********* End of inlined file: jdhuff.c *********/
  163703. /********* Start of inlined file: jdinput.c *********/
  163704. #define JPEG_INTERNALS
  163705. /* Private state */
  163706. typedef struct {
  163707. struct jpeg_input_controller pub; /* public fields */
  163708. boolean inheaders; /* TRUE until first SOS is reached */
  163709. } my_input_controller;
  163710. typedef my_input_controller * my_inputctl_ptr;
  163711. /* Forward declarations */
  163712. METHODDEF(int) consume_markers JPP((j_decompress_ptr cinfo));
  163713. /*
  163714. * Routines to calculate various quantities related to the size of the image.
  163715. */
  163716. LOCAL(void)
  163717. initial_setup2 (j_decompress_ptr cinfo)
  163718. /* Called once, when first SOS marker is reached */
  163719. {
  163720. int ci;
  163721. jpeg_component_info *compptr;
  163722. /* Make sure image isn't bigger than I can handle */
  163723. if ((long) cinfo->image_height > (long) JPEG_MAX_DIMENSION ||
  163724. (long) cinfo->image_width > (long) JPEG_MAX_DIMENSION)
  163725. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) JPEG_MAX_DIMENSION);
  163726. /* For now, precision must match compiled-in value... */
  163727. if (cinfo->data_precision != BITS_IN_JSAMPLE)
  163728. ERREXIT1(cinfo, JERR_BAD_PRECISION, cinfo->data_precision);
  163729. /* Check that number of components won't exceed internal array sizes */
  163730. if (cinfo->num_components > MAX_COMPONENTS)
  163731. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  163732. MAX_COMPONENTS);
  163733. /* Compute maximum sampling factors; check factor validity */
  163734. cinfo->max_h_samp_factor = 1;
  163735. cinfo->max_v_samp_factor = 1;
  163736. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  163737. ci++, compptr++) {
  163738. if (compptr->h_samp_factor<=0 || compptr->h_samp_factor>MAX_SAMP_FACTOR ||
  163739. compptr->v_samp_factor<=0 || compptr->v_samp_factor>MAX_SAMP_FACTOR)
  163740. ERREXIT(cinfo, JERR_BAD_SAMPLING);
  163741. cinfo->max_h_samp_factor = MAX(cinfo->max_h_samp_factor,
  163742. compptr->h_samp_factor);
  163743. cinfo->max_v_samp_factor = MAX(cinfo->max_v_samp_factor,
  163744. compptr->v_samp_factor);
  163745. }
  163746. /* We initialize DCT_scaled_size and min_DCT_scaled_size to DCTSIZE.
  163747. * In the full decompressor, this will be overridden by jdmaster.c;
  163748. * but in the transcoder, jdmaster.c is not used, so we must do it here.
  163749. */
  163750. cinfo->min_DCT_scaled_size = DCTSIZE;
  163751. /* Compute dimensions of components */
  163752. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  163753. ci++, compptr++) {
  163754. compptr->DCT_scaled_size = DCTSIZE;
  163755. /* Size in DCT blocks */
  163756. compptr->width_in_blocks = (JDIMENSION)
  163757. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  163758. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  163759. compptr->height_in_blocks = (JDIMENSION)
  163760. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  163761. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  163762. /* downsampled_width and downsampled_height will also be overridden by
  163763. * jdmaster.c if we are doing full decompression. The transcoder library
  163764. * doesn't use these values, but the calling application might.
  163765. */
  163766. /* Size in samples */
  163767. compptr->downsampled_width = (JDIMENSION)
  163768. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  163769. (long) cinfo->max_h_samp_factor);
  163770. compptr->downsampled_height = (JDIMENSION)
  163771. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  163772. (long) cinfo->max_v_samp_factor);
  163773. /* Mark component needed, until color conversion says otherwise */
  163774. compptr->component_needed = TRUE;
  163775. /* Mark no quantization table yet saved for component */
  163776. compptr->quant_table = NULL;
  163777. }
  163778. /* Compute number of fully interleaved MCU rows. */
  163779. cinfo->total_iMCU_rows = (JDIMENSION)
  163780. jdiv_round_up((long) cinfo->image_height,
  163781. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  163782. /* Decide whether file contains multiple scans */
  163783. if (cinfo->comps_in_scan < cinfo->num_components || cinfo->progressive_mode)
  163784. cinfo->inputctl->has_multiple_scans = TRUE;
  163785. else
  163786. cinfo->inputctl->has_multiple_scans = FALSE;
  163787. }
  163788. LOCAL(void)
  163789. per_scan_setup2 (j_decompress_ptr cinfo)
  163790. /* Do computations that are needed before processing a JPEG scan */
  163791. /* cinfo->comps_in_scan and cinfo->cur_comp_info[] were set from SOS marker */
  163792. {
  163793. int ci, mcublks, tmp;
  163794. jpeg_component_info *compptr;
  163795. if (cinfo->comps_in_scan == 1) {
  163796. /* Noninterleaved (single-component) scan */
  163797. compptr = cinfo->cur_comp_info[0];
  163798. /* Overall image size in MCUs */
  163799. cinfo->MCUs_per_row = compptr->width_in_blocks;
  163800. cinfo->MCU_rows_in_scan = compptr->height_in_blocks;
  163801. /* For noninterleaved scan, always one block per MCU */
  163802. compptr->MCU_width = 1;
  163803. compptr->MCU_height = 1;
  163804. compptr->MCU_blocks = 1;
  163805. compptr->MCU_sample_width = compptr->DCT_scaled_size;
  163806. compptr->last_col_width = 1;
  163807. /* For noninterleaved scans, it is convenient to define last_row_height
  163808. * as the number of block rows present in the last iMCU row.
  163809. */
  163810. tmp = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  163811. if (tmp == 0) tmp = compptr->v_samp_factor;
  163812. compptr->last_row_height = tmp;
  163813. /* Prepare array describing MCU composition */
  163814. cinfo->blocks_in_MCU = 1;
  163815. cinfo->MCU_membership[0] = 0;
  163816. } else {
  163817. /* Interleaved (multi-component) scan */
  163818. if (cinfo->comps_in_scan <= 0 || cinfo->comps_in_scan > MAX_COMPS_IN_SCAN)
  163819. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->comps_in_scan,
  163820. MAX_COMPS_IN_SCAN);
  163821. /* Overall image size in MCUs */
  163822. cinfo->MCUs_per_row = (JDIMENSION)
  163823. jdiv_round_up((long) cinfo->image_width,
  163824. (long) (cinfo->max_h_samp_factor*DCTSIZE));
  163825. cinfo->MCU_rows_in_scan = (JDIMENSION)
  163826. jdiv_round_up((long) cinfo->image_height,
  163827. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  163828. cinfo->blocks_in_MCU = 0;
  163829. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  163830. compptr = cinfo->cur_comp_info[ci];
  163831. /* Sampling factors give # of blocks of component in each MCU */
  163832. compptr->MCU_width = compptr->h_samp_factor;
  163833. compptr->MCU_height = compptr->v_samp_factor;
  163834. compptr->MCU_blocks = compptr->MCU_width * compptr->MCU_height;
  163835. compptr->MCU_sample_width = compptr->MCU_width * compptr->DCT_scaled_size;
  163836. /* Figure number of non-dummy blocks in last MCU column & row */
  163837. tmp = (int) (compptr->width_in_blocks % compptr->MCU_width);
  163838. if (tmp == 0) tmp = compptr->MCU_width;
  163839. compptr->last_col_width = tmp;
  163840. tmp = (int) (compptr->height_in_blocks % compptr->MCU_height);
  163841. if (tmp == 0) tmp = compptr->MCU_height;
  163842. compptr->last_row_height = tmp;
  163843. /* Prepare array describing MCU composition */
  163844. mcublks = compptr->MCU_blocks;
  163845. if (cinfo->blocks_in_MCU + mcublks > D_MAX_BLOCKS_IN_MCU)
  163846. ERREXIT(cinfo, JERR_BAD_MCU_SIZE);
  163847. while (mcublks-- > 0) {
  163848. cinfo->MCU_membership[cinfo->blocks_in_MCU++] = ci;
  163849. }
  163850. }
  163851. }
  163852. }
  163853. /*
  163854. * Save away a copy of the Q-table referenced by each component present
  163855. * in the current scan, unless already saved during a prior scan.
  163856. *
  163857. * In a multiple-scan JPEG file, the encoder could assign different components
  163858. * the same Q-table slot number, but change table definitions between scans
  163859. * so that each component uses a different Q-table. (The IJG encoder is not
  163860. * currently capable of doing this, but other encoders might.) Since we want
  163861. * to be able to dequantize all the components at the end of the file, this
  163862. * means that we have to save away the table actually used for each component.
  163863. * We do this by copying the table at the start of the first scan containing
  163864. * the component.
  163865. * The JPEG spec prohibits the encoder from changing the contents of a Q-table
  163866. * slot between scans of a component using that slot. If the encoder does so
  163867. * anyway, this decoder will simply use the Q-table values that were current
  163868. * at the start of the first scan for the component.
  163869. *
  163870. * The decompressor output side looks only at the saved quant tables,
  163871. * not at the current Q-table slots.
  163872. */
  163873. LOCAL(void)
  163874. latch_quant_tables (j_decompress_ptr cinfo)
  163875. {
  163876. int ci, qtblno;
  163877. jpeg_component_info *compptr;
  163878. JQUANT_TBL * qtbl;
  163879. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  163880. compptr = cinfo->cur_comp_info[ci];
  163881. /* No work if we already saved Q-table for this component */
  163882. if (compptr->quant_table != NULL)
  163883. continue;
  163884. /* Make sure specified quantization table is present */
  163885. qtblno = compptr->quant_tbl_no;
  163886. if (qtblno < 0 || qtblno >= NUM_QUANT_TBLS ||
  163887. cinfo->quant_tbl_ptrs[qtblno] == NULL)
  163888. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, qtblno);
  163889. /* OK, save away the quantization table */
  163890. qtbl = (JQUANT_TBL *)
  163891. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163892. SIZEOF(JQUANT_TBL));
  163893. MEMCOPY(qtbl, cinfo->quant_tbl_ptrs[qtblno], SIZEOF(JQUANT_TBL));
  163894. compptr->quant_table = qtbl;
  163895. }
  163896. }
  163897. /*
  163898. * Initialize the input modules to read a scan of compressed data.
  163899. * The first call to this is done by jdmaster.c after initializing
  163900. * the entire decompressor (during jpeg_start_decompress).
  163901. * Subsequent calls come from consume_markers, below.
  163902. */
  163903. METHODDEF(void)
  163904. start_input_pass2 (j_decompress_ptr cinfo)
  163905. {
  163906. per_scan_setup2(cinfo);
  163907. latch_quant_tables(cinfo);
  163908. (*cinfo->entropy->start_pass) (cinfo);
  163909. (*cinfo->coef->start_input_pass) (cinfo);
  163910. cinfo->inputctl->consume_input = cinfo->coef->consume_data;
  163911. }
  163912. /*
  163913. * Finish up after inputting a compressed-data scan.
  163914. * This is called by the coefficient controller after it's read all
  163915. * the expected data of the scan.
  163916. */
  163917. METHODDEF(void)
  163918. finish_input_pass (j_decompress_ptr cinfo)
  163919. {
  163920. cinfo->inputctl->consume_input = consume_markers;
  163921. }
  163922. /*
  163923. * Read JPEG markers before, between, or after compressed-data scans.
  163924. * Change state as necessary when a new scan is reached.
  163925. * Return value is JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  163926. *
  163927. * The consume_input method pointer points either here or to the
  163928. * coefficient controller's consume_data routine, depending on whether
  163929. * we are reading a compressed data segment or inter-segment markers.
  163930. */
  163931. METHODDEF(int)
  163932. consume_markers (j_decompress_ptr cinfo)
  163933. {
  163934. my_inputctl_ptr inputctl = (my_inputctl_ptr) cinfo->inputctl;
  163935. int val;
  163936. if (inputctl->pub.eoi_reached) /* After hitting EOI, read no further */
  163937. return JPEG_REACHED_EOI;
  163938. val = (*cinfo->marker->read_markers) (cinfo);
  163939. switch (val) {
  163940. case JPEG_REACHED_SOS: /* Found SOS */
  163941. if (inputctl->inheaders) { /* 1st SOS */
  163942. initial_setup2(cinfo);
  163943. inputctl->inheaders = FALSE;
  163944. /* Note: start_input_pass must be called by jdmaster.c
  163945. * before any more input can be consumed. jdapimin.c is
  163946. * responsible for enforcing this sequencing.
  163947. */
  163948. } else { /* 2nd or later SOS marker */
  163949. if (! inputctl->pub.has_multiple_scans)
  163950. ERREXIT(cinfo, JERR_EOI_EXPECTED); /* Oops, I wasn't expecting this! */
  163951. start_input_pass2(cinfo);
  163952. }
  163953. break;
  163954. case JPEG_REACHED_EOI: /* Found EOI */
  163955. inputctl->pub.eoi_reached = TRUE;
  163956. if (inputctl->inheaders) { /* Tables-only datastream, apparently */
  163957. if (cinfo->marker->saw_SOF)
  163958. ERREXIT(cinfo, JERR_SOF_NO_SOS);
  163959. } else {
  163960. /* Prevent infinite loop in coef ctlr's decompress_data routine
  163961. * if user set output_scan_number larger than number of scans.
  163962. */
  163963. if (cinfo->output_scan_number > cinfo->input_scan_number)
  163964. cinfo->output_scan_number = cinfo->input_scan_number;
  163965. }
  163966. break;
  163967. case JPEG_SUSPENDED:
  163968. break;
  163969. }
  163970. return val;
  163971. }
  163972. /*
  163973. * Reset state to begin a fresh datastream.
  163974. */
  163975. METHODDEF(void)
  163976. reset_input_controller (j_decompress_ptr cinfo)
  163977. {
  163978. my_inputctl_ptr inputctl = (my_inputctl_ptr) cinfo->inputctl;
  163979. inputctl->pub.consume_input = consume_markers;
  163980. inputctl->pub.has_multiple_scans = FALSE; /* "unknown" would be better */
  163981. inputctl->pub.eoi_reached = FALSE;
  163982. inputctl->inheaders = TRUE;
  163983. /* Reset other modules */
  163984. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  163985. (*cinfo->marker->reset_marker_reader) (cinfo);
  163986. /* Reset progression state -- would be cleaner if entropy decoder did this */
  163987. cinfo->coef_bits = NULL;
  163988. }
  163989. /*
  163990. * Initialize the input controller module.
  163991. * This is called only once, when the decompression object is created.
  163992. */
  163993. GLOBAL(void)
  163994. jinit_input_controller (j_decompress_ptr cinfo)
  163995. {
  163996. my_inputctl_ptr inputctl;
  163997. /* Create subobject in permanent pool */
  163998. inputctl = (my_inputctl_ptr)
  163999. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  164000. SIZEOF(my_input_controller));
  164001. cinfo->inputctl = (struct jpeg_input_controller *) inputctl;
  164002. /* Initialize method pointers */
  164003. inputctl->pub.consume_input = consume_markers;
  164004. inputctl->pub.reset_input_controller = reset_input_controller;
  164005. inputctl->pub.start_input_pass = start_input_pass2;
  164006. inputctl->pub.finish_input_pass = finish_input_pass;
  164007. /* Initialize state: can't use reset_input_controller since we don't
  164008. * want to try to reset other modules yet.
  164009. */
  164010. inputctl->pub.has_multiple_scans = FALSE; /* "unknown" would be better */
  164011. inputctl->pub.eoi_reached = FALSE;
  164012. inputctl->inheaders = TRUE;
  164013. }
  164014. /********* End of inlined file: jdinput.c *********/
  164015. /********* Start of inlined file: jdmainct.c *********/
  164016. #define JPEG_INTERNALS
  164017. /*
  164018. * In the current system design, the main buffer need never be a full-image
  164019. * buffer; any full-height buffers will be found inside the coefficient or
  164020. * postprocessing controllers. Nonetheless, the main controller is not
  164021. * trivial. Its responsibility is to provide context rows for upsampling/
  164022. * rescaling, and doing this in an efficient fashion is a bit tricky.
  164023. *
  164024. * Postprocessor input data is counted in "row groups". A row group
  164025. * is defined to be (v_samp_factor * DCT_scaled_size / min_DCT_scaled_size)
  164026. * sample rows of each component. (We require DCT_scaled_size values to be
  164027. * chosen such that these numbers are integers. In practice DCT_scaled_size
  164028. * values will likely be powers of two, so we actually have the stronger
  164029. * condition that DCT_scaled_size / min_DCT_scaled_size is an integer.)
  164030. * Upsampling will typically produce max_v_samp_factor pixel rows from each
  164031. * row group (times any additional scale factor that the upsampler is
  164032. * applying).
  164033. *
  164034. * The coefficient controller will deliver data to us one iMCU row at a time;
  164035. * each iMCU row contains v_samp_factor * DCT_scaled_size sample rows, or
  164036. * exactly min_DCT_scaled_size row groups. (This amount of data corresponds
  164037. * to one row of MCUs when the image is fully interleaved.) Note that the
  164038. * number of sample rows varies across components, but the number of row
  164039. * groups does not. Some garbage sample rows may be included in the last iMCU
  164040. * row at the bottom of the image.
  164041. *
  164042. * Depending on the vertical scaling algorithm used, the upsampler may need
  164043. * access to the sample row(s) above and below its current input row group.
  164044. * The upsampler is required to set need_context_rows TRUE at global selection
  164045. * time if so. When need_context_rows is FALSE, this controller can simply
  164046. * obtain one iMCU row at a time from the coefficient controller and dole it
  164047. * out as row groups to the postprocessor.
  164048. *
  164049. * When need_context_rows is TRUE, this controller guarantees that the buffer
  164050. * passed to postprocessing contains at least one row group's worth of samples
  164051. * above and below the row group(s) being processed. Note that the context
  164052. * rows "above" the first passed row group appear at negative row offsets in
  164053. * the passed buffer. At the top and bottom of the image, the required
  164054. * context rows are manufactured by duplicating the first or last real sample
  164055. * row; this avoids having special cases in the upsampling inner loops.
  164056. *
  164057. * The amount of context is fixed at one row group just because that's a
  164058. * convenient number for this controller to work with. The existing
  164059. * upsamplers really only need one sample row of context. An upsampler
  164060. * supporting arbitrary output rescaling might wish for more than one row
  164061. * group of context when shrinking the image; tough, we don't handle that.
  164062. * (This is justified by the assumption that downsizing will be handled mostly
  164063. * by adjusting the DCT_scaled_size values, so that the actual scale factor at
  164064. * the upsample step needn't be much less than one.)
  164065. *
  164066. * To provide the desired context, we have to retain the last two row groups
  164067. * of one iMCU row while reading in the next iMCU row. (The last row group
  164068. * can't be processed until we have another row group for its below-context,
  164069. * and so we have to save the next-to-last group too for its above-context.)
  164070. * We could do this most simply by copying data around in our buffer, but
  164071. * that'd be very slow. We can avoid copying any data by creating a rather
  164072. * strange pointer structure. Here's how it works. We allocate a workspace
  164073. * consisting of M+2 row groups (where M = min_DCT_scaled_size is the number
  164074. * of row groups per iMCU row). We create two sets of redundant pointers to
  164075. * the workspace. Labeling the physical row groups 0 to M+1, the synthesized
  164076. * pointer lists look like this:
  164077. * M+1 M-1
  164078. * master pointer --> 0 master pointer --> 0
  164079. * 1 1
  164080. * ... ...
  164081. * M-3 M-3
  164082. * M-2 M
  164083. * M-1 M+1
  164084. * M M-2
  164085. * M+1 M-1
  164086. * 0 0
  164087. * We read alternate iMCU rows using each master pointer; thus the last two
  164088. * row groups of the previous iMCU row remain un-overwritten in the workspace.
  164089. * The pointer lists are set up so that the required context rows appear to
  164090. * be adjacent to the proper places when we pass the pointer lists to the
  164091. * upsampler.
  164092. *
  164093. * The above pictures describe the normal state of the pointer lists.
  164094. * At top and bottom of the image, we diddle the pointer lists to duplicate
  164095. * the first or last sample row as necessary (this is cheaper than copying
  164096. * sample rows around).
  164097. *
  164098. * This scheme breaks down if M < 2, ie, min_DCT_scaled_size is 1. In that
  164099. * situation each iMCU row provides only one row group so the buffering logic
  164100. * must be different (eg, we must read two iMCU rows before we can emit the
  164101. * first row group). For now, we simply do not support providing context
  164102. * rows when min_DCT_scaled_size is 1. That combination seems unlikely to
  164103. * be worth providing --- if someone wants a 1/8th-size preview, they probably
  164104. * want it quick and dirty, so a context-free upsampler is sufficient.
  164105. */
  164106. /* Private buffer controller object */
  164107. typedef struct {
  164108. struct jpeg_d_main_controller pub; /* public fields */
  164109. /* Pointer to allocated workspace (M or M+2 row groups). */
  164110. JSAMPARRAY buffer[MAX_COMPONENTS];
  164111. boolean buffer_full; /* Have we gotten an iMCU row from decoder? */
  164112. JDIMENSION rowgroup_ctr; /* counts row groups output to postprocessor */
  164113. /* Remaining fields are only used in the context case. */
  164114. /* These are the master pointers to the funny-order pointer lists. */
  164115. JSAMPIMAGE xbuffer[2]; /* pointers to weird pointer lists */
  164116. int whichptr; /* indicates which pointer set is now in use */
  164117. int context_state; /* process_data state machine status */
  164118. JDIMENSION rowgroups_avail; /* row groups available to postprocessor */
  164119. JDIMENSION iMCU_row_ctr; /* counts iMCU rows to detect image top/bot */
  164120. } my_main_controller4;
  164121. typedef my_main_controller4 * my_main_ptr4;
  164122. /* context_state values: */
  164123. #define CTX_PREPARE_FOR_IMCU 0 /* need to prepare for MCU row */
  164124. #define CTX_PROCESS_IMCU 1 /* feeding iMCU to postprocessor */
  164125. #define CTX_POSTPONED_ROW 2 /* feeding postponed row group */
  164126. /* Forward declarations */
  164127. METHODDEF(void) process_data_simple_main2
  164128. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  164129. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  164130. METHODDEF(void) process_data_context_main
  164131. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  164132. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  164133. #ifdef QUANT_2PASS_SUPPORTED
  164134. METHODDEF(void) process_data_crank_post
  164135. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  164136. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  164137. #endif
  164138. LOCAL(void)
  164139. alloc_funny_pointers (j_decompress_ptr cinfo)
  164140. /* Allocate space for the funny pointer lists.
  164141. * This is done only once, not once per pass.
  164142. */
  164143. {
  164144. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  164145. int ci, rgroup;
  164146. int M = cinfo->min_DCT_scaled_size;
  164147. jpeg_component_info *compptr;
  164148. JSAMPARRAY xbuf;
  164149. /* Get top-level space for component array pointers.
  164150. * We alloc both arrays with one call to save a few cycles.
  164151. */
  164152. main_->xbuffer[0] = (JSAMPIMAGE)
  164153. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164154. cinfo->num_components * 2 * SIZEOF(JSAMPARRAY));
  164155. main_->xbuffer[1] = main_->xbuffer[0] + cinfo->num_components;
  164156. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164157. ci++, compptr++) {
  164158. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  164159. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  164160. /* Get space for pointer lists --- M+4 row groups in each list.
  164161. * We alloc both pointer lists with one call to save a few cycles.
  164162. */
  164163. xbuf = (JSAMPARRAY)
  164164. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164165. 2 * (rgroup * (M + 4)) * SIZEOF(JSAMPROW));
  164166. xbuf += rgroup; /* want one row group at negative offsets */
  164167. main_->xbuffer[0][ci] = xbuf;
  164168. xbuf += rgroup * (M + 4);
  164169. main_->xbuffer[1][ci] = xbuf;
  164170. }
  164171. }
  164172. LOCAL(void)
  164173. make_funny_pointers (j_decompress_ptr cinfo)
  164174. /* Create the funny pointer lists discussed in the comments above.
  164175. * The actual workspace is already allocated (in main->buffer),
  164176. * and the space for the pointer lists is allocated too.
  164177. * This routine just fills in the curiously ordered lists.
  164178. * This will be repeated at the beginning of each pass.
  164179. */
  164180. {
  164181. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  164182. int ci, i, rgroup;
  164183. int M = cinfo->min_DCT_scaled_size;
  164184. jpeg_component_info *compptr;
  164185. JSAMPARRAY buf, xbuf0, xbuf1;
  164186. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164187. ci++, compptr++) {
  164188. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  164189. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  164190. xbuf0 = main_->xbuffer[0][ci];
  164191. xbuf1 = main_->xbuffer[1][ci];
  164192. /* First copy the workspace pointers as-is */
  164193. buf = main_->buffer[ci];
  164194. for (i = 0; i < rgroup * (M + 2); i++) {
  164195. xbuf0[i] = xbuf1[i] = buf[i];
  164196. }
  164197. /* In the second list, put the last four row groups in swapped order */
  164198. for (i = 0; i < rgroup * 2; i++) {
  164199. xbuf1[rgroup*(M-2) + i] = buf[rgroup*M + i];
  164200. xbuf1[rgroup*M + i] = buf[rgroup*(M-2) + i];
  164201. }
  164202. /* The wraparound pointers at top and bottom will be filled later
  164203. * (see set_wraparound_pointers, below). Initially we want the "above"
  164204. * pointers to duplicate the first actual data line. This only needs
  164205. * to happen in xbuffer[0].
  164206. */
  164207. for (i = 0; i < rgroup; i++) {
  164208. xbuf0[i - rgroup] = xbuf0[0];
  164209. }
  164210. }
  164211. }
  164212. LOCAL(void)
  164213. set_wraparound_pointers (j_decompress_ptr cinfo)
  164214. /* Set up the "wraparound" pointers at top and bottom of the pointer lists.
  164215. * This changes the pointer list state from top-of-image to the normal state.
  164216. */
  164217. {
  164218. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  164219. int ci, i, rgroup;
  164220. int M = cinfo->min_DCT_scaled_size;
  164221. jpeg_component_info *compptr;
  164222. JSAMPARRAY xbuf0, xbuf1;
  164223. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164224. ci++, compptr++) {
  164225. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  164226. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  164227. xbuf0 = main_->xbuffer[0][ci];
  164228. xbuf1 = main_->xbuffer[1][ci];
  164229. for (i = 0; i < rgroup; i++) {
  164230. xbuf0[i - rgroup] = xbuf0[rgroup*(M+1) + i];
  164231. xbuf1[i - rgroup] = xbuf1[rgroup*(M+1) + i];
  164232. xbuf0[rgroup*(M+2) + i] = xbuf0[i];
  164233. xbuf1[rgroup*(M+2) + i] = xbuf1[i];
  164234. }
  164235. }
  164236. }
  164237. LOCAL(void)
  164238. set_bottom_pointers (j_decompress_ptr cinfo)
  164239. /* Change the pointer lists to duplicate the last sample row at the bottom
  164240. * of the image. whichptr indicates which xbuffer holds the final iMCU row.
  164241. * Also sets rowgroups_avail to indicate number of nondummy row groups in row.
  164242. */
  164243. {
  164244. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  164245. int ci, i, rgroup, iMCUheight, rows_left;
  164246. jpeg_component_info *compptr;
  164247. JSAMPARRAY xbuf;
  164248. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164249. ci++, compptr++) {
  164250. /* Count sample rows in one iMCU row and in one row group */
  164251. iMCUheight = compptr->v_samp_factor * compptr->DCT_scaled_size;
  164252. rgroup = iMCUheight / cinfo->min_DCT_scaled_size;
  164253. /* Count nondummy sample rows remaining for this component */
  164254. rows_left = (int) (compptr->downsampled_height % (JDIMENSION) iMCUheight);
  164255. if (rows_left == 0) rows_left = iMCUheight;
  164256. /* Count nondummy row groups. Should get same answer for each component,
  164257. * so we need only do it once.
  164258. */
  164259. if (ci == 0) {
  164260. main_->rowgroups_avail = (JDIMENSION) ((rows_left-1) / rgroup + 1);
  164261. }
  164262. /* Duplicate the last real sample row rgroup*2 times; this pads out the
  164263. * last partial rowgroup and ensures at least one full rowgroup of context.
  164264. */
  164265. xbuf = main_->xbuffer[main_->whichptr][ci];
  164266. for (i = 0; i < rgroup * 2; i++) {
  164267. xbuf[rows_left + i] = xbuf[rows_left-1];
  164268. }
  164269. }
  164270. }
  164271. /*
  164272. * Initialize for a processing pass.
  164273. */
  164274. METHODDEF(void)
  164275. start_pass_main2 (j_decompress_ptr cinfo, J_BUF_MODE pass_mode)
  164276. {
  164277. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  164278. switch (pass_mode) {
  164279. case JBUF_PASS_THRU:
  164280. if (cinfo->upsample->need_context_rows) {
  164281. main_->pub.process_data = process_data_context_main;
  164282. make_funny_pointers(cinfo); /* Create the xbuffer[] lists */
  164283. main_->whichptr = 0; /* Read first iMCU row into xbuffer[0] */
  164284. main_->context_state = CTX_PREPARE_FOR_IMCU;
  164285. main_->iMCU_row_ctr = 0;
  164286. } else {
  164287. /* Simple case with no context needed */
  164288. main_->pub.process_data = process_data_simple_main2;
  164289. }
  164290. main_->buffer_full = FALSE; /* Mark buffer empty */
  164291. main_->rowgroup_ctr = 0;
  164292. break;
  164293. #ifdef QUANT_2PASS_SUPPORTED
  164294. case JBUF_CRANK_DEST:
  164295. /* For last pass of 2-pass quantization, just crank the postprocessor */
  164296. main_->pub.process_data = process_data_crank_post;
  164297. break;
  164298. #endif
  164299. default:
  164300. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  164301. break;
  164302. }
  164303. }
  164304. /*
  164305. * Process some data.
  164306. * This handles the simple case where no context is required.
  164307. */
  164308. METHODDEF(void)
  164309. process_data_simple_main2 (j_decompress_ptr cinfo,
  164310. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  164311. JDIMENSION out_rows_avail)
  164312. {
  164313. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  164314. JDIMENSION rowgroups_avail;
  164315. /* Read input data if we haven't filled the main buffer yet */
  164316. if (! main_->buffer_full) {
  164317. if (! (*cinfo->coef->decompress_data) (cinfo, main_->buffer))
  164318. return; /* suspension forced, can do nothing more */
  164319. main_->buffer_full = TRUE; /* OK, we have an iMCU row to work with */
  164320. }
  164321. /* There are always min_DCT_scaled_size row groups in an iMCU row. */
  164322. rowgroups_avail = (JDIMENSION) cinfo->min_DCT_scaled_size;
  164323. /* Note: at the bottom of the image, we may pass extra garbage row groups
  164324. * to the postprocessor. The postprocessor has to check for bottom
  164325. * of image anyway (at row resolution), so no point in us doing it too.
  164326. */
  164327. /* Feed the postprocessor */
  164328. (*cinfo->post->post_process_data) (cinfo, main_->buffer,
  164329. &main_->rowgroup_ctr, rowgroups_avail,
  164330. output_buf, out_row_ctr, out_rows_avail);
  164331. /* Has postprocessor consumed all the data yet? If so, mark buffer empty */
  164332. if (main_->rowgroup_ctr >= rowgroups_avail) {
  164333. main_->buffer_full = FALSE;
  164334. main_->rowgroup_ctr = 0;
  164335. }
  164336. }
  164337. /*
  164338. * Process some data.
  164339. * This handles the case where context rows must be provided.
  164340. */
  164341. METHODDEF(void)
  164342. process_data_context_main (j_decompress_ptr cinfo,
  164343. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  164344. JDIMENSION out_rows_avail)
  164345. {
  164346. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  164347. /* Read input data if we haven't filled the main buffer yet */
  164348. if (! main_->buffer_full) {
  164349. if (! (*cinfo->coef->decompress_data) (cinfo,
  164350. main_->xbuffer[main_->whichptr]))
  164351. return; /* suspension forced, can do nothing more */
  164352. main_->buffer_full = TRUE; /* OK, we have an iMCU row to work with */
  164353. main_->iMCU_row_ctr++; /* count rows received */
  164354. }
  164355. /* Postprocessor typically will not swallow all the input data it is handed
  164356. * in one call (due to filling the output buffer first). Must be prepared
  164357. * to exit and restart. This switch lets us keep track of how far we got.
  164358. * Note that each case falls through to the next on successful completion.
  164359. */
  164360. switch (main_->context_state) {
  164361. case CTX_POSTPONED_ROW:
  164362. /* Call postprocessor using previously set pointers for postponed row */
  164363. (*cinfo->post->post_process_data) (cinfo, main_->xbuffer[main_->whichptr],
  164364. &main_->rowgroup_ctr, main_->rowgroups_avail,
  164365. output_buf, out_row_ctr, out_rows_avail);
  164366. if (main_->rowgroup_ctr < main_->rowgroups_avail)
  164367. return; /* Need to suspend */
  164368. main_->context_state = CTX_PREPARE_FOR_IMCU;
  164369. if (*out_row_ctr >= out_rows_avail)
  164370. return; /* Postprocessor exactly filled output buf */
  164371. /*FALLTHROUGH*/
  164372. case CTX_PREPARE_FOR_IMCU:
  164373. /* Prepare to process first M-1 row groups of this iMCU row */
  164374. main_->rowgroup_ctr = 0;
  164375. main_->rowgroups_avail = (JDIMENSION) (cinfo->min_DCT_scaled_size - 1);
  164376. /* Check for bottom of image: if so, tweak pointers to "duplicate"
  164377. * the last sample row, and adjust rowgroups_avail to ignore padding rows.
  164378. */
  164379. if (main_->iMCU_row_ctr == cinfo->total_iMCU_rows)
  164380. set_bottom_pointers(cinfo);
  164381. main_->context_state = CTX_PROCESS_IMCU;
  164382. /*FALLTHROUGH*/
  164383. case CTX_PROCESS_IMCU:
  164384. /* Call postprocessor using previously set pointers */
  164385. (*cinfo->post->post_process_data) (cinfo, main_->xbuffer[main_->whichptr],
  164386. &main_->rowgroup_ctr, main_->rowgroups_avail,
  164387. output_buf, out_row_ctr, out_rows_avail);
  164388. if (main_->rowgroup_ctr < main_->rowgroups_avail)
  164389. return; /* Need to suspend */
  164390. /* After the first iMCU, change wraparound pointers to normal state */
  164391. if (main_->iMCU_row_ctr == 1)
  164392. set_wraparound_pointers(cinfo);
  164393. /* Prepare to load new iMCU row using other xbuffer list */
  164394. main_->whichptr ^= 1; /* 0=>1 or 1=>0 */
  164395. main_->buffer_full = FALSE;
  164396. /* Still need to process last row group of this iMCU row, */
  164397. /* which is saved at index M+1 of the other xbuffer */
  164398. main_->rowgroup_ctr = (JDIMENSION) (cinfo->min_DCT_scaled_size + 1);
  164399. main_->rowgroups_avail = (JDIMENSION) (cinfo->min_DCT_scaled_size + 2);
  164400. main_->context_state = CTX_POSTPONED_ROW;
  164401. }
  164402. }
  164403. /*
  164404. * Process some data.
  164405. * Final pass of two-pass quantization: just call the postprocessor.
  164406. * Source data will be the postprocessor controller's internal buffer.
  164407. */
  164408. #ifdef QUANT_2PASS_SUPPORTED
  164409. METHODDEF(void)
  164410. process_data_crank_post (j_decompress_ptr cinfo,
  164411. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  164412. JDIMENSION out_rows_avail)
  164413. {
  164414. (*cinfo->post->post_process_data) (cinfo, (JSAMPIMAGE) NULL,
  164415. (JDIMENSION *) NULL, (JDIMENSION) 0,
  164416. output_buf, out_row_ctr, out_rows_avail);
  164417. }
  164418. #endif /* QUANT_2PASS_SUPPORTED */
  164419. /*
  164420. * Initialize main buffer controller.
  164421. */
  164422. GLOBAL(void)
  164423. jinit_d_main_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  164424. {
  164425. my_main_ptr4 main_;
  164426. int ci, rgroup, ngroups;
  164427. jpeg_component_info *compptr;
  164428. main_ = (my_main_ptr4)
  164429. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164430. SIZEOF(my_main_controller4));
  164431. cinfo->main = (struct jpeg_d_main_controller *) main_;
  164432. main_->pub.start_pass = start_pass_main2;
  164433. if (need_full_buffer) /* shouldn't happen */
  164434. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  164435. /* Allocate the workspace.
  164436. * ngroups is the number of row groups we need.
  164437. */
  164438. if (cinfo->upsample->need_context_rows) {
  164439. if (cinfo->min_DCT_scaled_size < 2) /* unsupported, see comments above */
  164440. ERREXIT(cinfo, JERR_NOTIMPL);
  164441. alloc_funny_pointers(cinfo); /* Alloc space for xbuffer[] lists */
  164442. ngroups = cinfo->min_DCT_scaled_size + 2;
  164443. } else {
  164444. ngroups = cinfo->min_DCT_scaled_size;
  164445. }
  164446. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164447. ci++, compptr++) {
  164448. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  164449. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  164450. main_->buffer[ci] = (*cinfo->mem->alloc_sarray)
  164451. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164452. compptr->width_in_blocks * compptr->DCT_scaled_size,
  164453. (JDIMENSION) (rgroup * ngroups));
  164454. }
  164455. }
  164456. /********* End of inlined file: jdmainct.c *********/
  164457. /********* Start of inlined file: jdmarker.c *********/
  164458. #define JPEG_INTERNALS
  164459. /* Private state */
  164460. typedef struct {
  164461. struct jpeg_marker_reader pub; /* public fields */
  164462. /* Application-overridable marker processing methods */
  164463. jpeg_marker_parser_method process_COM;
  164464. jpeg_marker_parser_method process_APPn[16];
  164465. /* Limit on marker data length to save for each marker type */
  164466. unsigned int length_limit_COM;
  164467. unsigned int length_limit_APPn[16];
  164468. /* Status of COM/APPn marker saving */
  164469. jpeg_saved_marker_ptr cur_marker; /* NULL if not processing a marker */
  164470. unsigned int bytes_read; /* data bytes read so far in marker */
  164471. /* Note: cur_marker is not linked into marker_list until it's all read. */
  164472. } my_marker_reader;
  164473. typedef my_marker_reader * my_marker_ptr2;
  164474. /*
  164475. * Macros for fetching data from the data source module.
  164476. *
  164477. * At all times, cinfo->src->next_input_byte and ->bytes_in_buffer reflect
  164478. * the current restart point; we update them only when we have reached a
  164479. * suitable place to restart if a suspension occurs.
  164480. */
  164481. /* Declare and initialize local copies of input pointer/count */
  164482. #define INPUT_VARS(cinfo) \
  164483. struct jpeg_source_mgr * datasrc = (cinfo)->src; \
  164484. const JOCTET * next_input_byte = datasrc->next_input_byte; \
  164485. size_t bytes_in_buffer = datasrc->bytes_in_buffer
  164486. /* Unload the local copies --- do this only at a restart boundary */
  164487. #define INPUT_SYNC(cinfo) \
  164488. ( datasrc->next_input_byte = next_input_byte, \
  164489. datasrc->bytes_in_buffer = bytes_in_buffer )
  164490. /* Reload the local copies --- used only in MAKE_BYTE_AVAIL */
  164491. #define INPUT_RELOAD(cinfo) \
  164492. ( next_input_byte = datasrc->next_input_byte, \
  164493. bytes_in_buffer = datasrc->bytes_in_buffer )
  164494. /* Internal macro for INPUT_BYTE and INPUT_2BYTES: make a byte available.
  164495. * Note we do *not* do INPUT_SYNC before calling fill_input_buffer,
  164496. * but we must reload the local copies after a successful fill.
  164497. */
  164498. #define MAKE_BYTE_AVAIL(cinfo,action) \
  164499. if (bytes_in_buffer == 0) { \
  164500. if (! (*datasrc->fill_input_buffer) (cinfo)) \
  164501. { action; } \
  164502. INPUT_RELOAD(cinfo); \
  164503. }
  164504. /* Read a byte into variable V.
  164505. * If must suspend, take the specified action (typically "return FALSE").
  164506. */
  164507. #define INPUT_BYTE(cinfo,V,action) \
  164508. MAKESTMT( MAKE_BYTE_AVAIL(cinfo,action); \
  164509. bytes_in_buffer--; \
  164510. V = GETJOCTET(*next_input_byte++); )
  164511. /* As above, but read two bytes interpreted as an unsigned 16-bit integer.
  164512. * V should be declared unsigned int or perhaps INT32.
  164513. */
  164514. #define INPUT_2BYTES(cinfo,V,action) \
  164515. MAKESTMT( MAKE_BYTE_AVAIL(cinfo,action); \
  164516. bytes_in_buffer--; \
  164517. V = ((unsigned int) GETJOCTET(*next_input_byte++)) << 8; \
  164518. MAKE_BYTE_AVAIL(cinfo,action); \
  164519. bytes_in_buffer--; \
  164520. V += GETJOCTET(*next_input_byte++); )
  164521. /*
  164522. * Routines to process JPEG markers.
  164523. *
  164524. * Entry condition: JPEG marker itself has been read and its code saved
  164525. * in cinfo->unread_marker; input restart point is just after the marker.
  164526. *
  164527. * Exit: if return TRUE, have read and processed any parameters, and have
  164528. * updated the restart point to point after the parameters.
  164529. * If return FALSE, was forced to suspend before reaching end of
  164530. * marker parameters; restart point has not been moved. Same routine
  164531. * will be called again after application supplies more input data.
  164532. *
  164533. * This approach to suspension assumes that all of a marker's parameters
  164534. * can fit into a single input bufferload. This should hold for "normal"
  164535. * markers. Some COM/APPn markers might have large parameter segments
  164536. * that might not fit. If we are simply dropping such a marker, we use
  164537. * skip_input_data to get past it, and thereby put the problem on the
  164538. * source manager's shoulders. If we are saving the marker's contents
  164539. * into memory, we use a slightly different convention: when forced to
  164540. * suspend, the marker processor updates the restart point to the end of
  164541. * what it's consumed (ie, the end of the buffer) before returning FALSE.
  164542. * On resumption, cinfo->unread_marker still contains the marker code,
  164543. * but the data source will point to the next chunk of marker data.
  164544. * The marker processor must retain internal state to deal with this.
  164545. *
  164546. * Note that we don't bother to avoid duplicate trace messages if a
  164547. * suspension occurs within marker parameters. Other side effects
  164548. * require more care.
  164549. */
  164550. LOCAL(boolean)
  164551. get_soi (j_decompress_ptr cinfo)
  164552. /* Process an SOI marker */
  164553. {
  164554. int i;
  164555. TRACEMS(cinfo, 1, JTRC_SOI);
  164556. if (cinfo->marker->saw_SOI)
  164557. ERREXIT(cinfo, JERR_SOI_DUPLICATE);
  164558. /* Reset all parameters that are defined to be reset by SOI */
  164559. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  164560. cinfo->arith_dc_L[i] = 0;
  164561. cinfo->arith_dc_U[i] = 1;
  164562. cinfo->arith_ac_K[i] = 5;
  164563. }
  164564. cinfo->restart_interval = 0;
  164565. /* Set initial assumptions for colorspace etc */
  164566. cinfo->jpeg_color_space = JCS_UNKNOWN;
  164567. cinfo->CCIR601_sampling = FALSE; /* Assume non-CCIR sampling??? */
  164568. cinfo->saw_JFIF_marker = FALSE;
  164569. cinfo->JFIF_major_version = 1; /* set default JFIF APP0 values */
  164570. cinfo->JFIF_minor_version = 1;
  164571. cinfo->density_unit = 0;
  164572. cinfo->X_density = 1;
  164573. cinfo->Y_density = 1;
  164574. cinfo->saw_Adobe_marker = FALSE;
  164575. cinfo->Adobe_transform = 0;
  164576. cinfo->marker->saw_SOI = TRUE;
  164577. return TRUE;
  164578. }
  164579. LOCAL(boolean)
  164580. get_sof (j_decompress_ptr cinfo, boolean is_prog, boolean is_arith)
  164581. /* Process a SOFn marker */
  164582. {
  164583. INT32 length;
  164584. int c, ci;
  164585. jpeg_component_info * compptr;
  164586. INPUT_VARS(cinfo);
  164587. cinfo->progressive_mode = is_prog;
  164588. cinfo->arith_code = is_arith;
  164589. INPUT_2BYTES(cinfo, length, return FALSE);
  164590. INPUT_BYTE(cinfo, cinfo->data_precision, return FALSE);
  164591. INPUT_2BYTES(cinfo, cinfo->image_height, return FALSE);
  164592. INPUT_2BYTES(cinfo, cinfo->image_width, return FALSE);
  164593. INPUT_BYTE(cinfo, cinfo->num_components, return FALSE);
  164594. length -= 8;
  164595. TRACEMS4(cinfo, 1, JTRC_SOF, cinfo->unread_marker,
  164596. (int) cinfo->image_width, (int) cinfo->image_height,
  164597. cinfo->num_components);
  164598. if (cinfo->marker->saw_SOF)
  164599. ERREXIT(cinfo, JERR_SOF_DUPLICATE);
  164600. /* We don't support files in which the image height is initially specified */
  164601. /* as 0 and is later redefined by DNL. As long as we have to check that, */
  164602. /* might as well have a general sanity check. */
  164603. if (cinfo->image_height <= 0 || cinfo->image_width <= 0
  164604. || cinfo->num_components <= 0)
  164605. ERREXIT(cinfo, JERR_EMPTY_IMAGE);
  164606. if (length != (cinfo->num_components * 3))
  164607. ERREXIT(cinfo, JERR_BAD_LENGTH);
  164608. if (cinfo->comp_info == NULL) /* do only once, even if suspend */
  164609. cinfo->comp_info = (jpeg_component_info *) (*cinfo->mem->alloc_small)
  164610. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164611. cinfo->num_components * SIZEOF(jpeg_component_info));
  164612. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164613. ci++, compptr++) {
  164614. compptr->component_index = ci;
  164615. INPUT_BYTE(cinfo, compptr->component_id, return FALSE);
  164616. INPUT_BYTE(cinfo, c, return FALSE);
  164617. compptr->h_samp_factor = (c >> 4) & 15;
  164618. compptr->v_samp_factor = (c ) & 15;
  164619. INPUT_BYTE(cinfo, compptr->quant_tbl_no, return FALSE);
  164620. TRACEMS4(cinfo, 1, JTRC_SOF_COMPONENT,
  164621. compptr->component_id, compptr->h_samp_factor,
  164622. compptr->v_samp_factor, compptr->quant_tbl_no);
  164623. }
  164624. cinfo->marker->saw_SOF = TRUE;
  164625. INPUT_SYNC(cinfo);
  164626. return TRUE;
  164627. }
  164628. LOCAL(boolean)
  164629. get_sos (j_decompress_ptr cinfo)
  164630. /* Process a SOS marker */
  164631. {
  164632. INT32 length;
  164633. int i, ci, n, c, cc;
  164634. jpeg_component_info * compptr;
  164635. INPUT_VARS(cinfo);
  164636. if (! cinfo->marker->saw_SOF)
  164637. ERREXIT(cinfo, JERR_SOS_NO_SOF);
  164638. INPUT_2BYTES(cinfo, length, return FALSE);
  164639. INPUT_BYTE(cinfo, n, return FALSE); /* Number of components */
  164640. TRACEMS1(cinfo, 1, JTRC_SOS, n);
  164641. if (length != (n * 2 + 6) || n < 1 || n > MAX_COMPS_IN_SCAN)
  164642. ERREXIT(cinfo, JERR_BAD_LENGTH);
  164643. cinfo->comps_in_scan = n;
  164644. /* Collect the component-spec parameters */
  164645. for (i = 0; i < n; i++) {
  164646. INPUT_BYTE(cinfo, cc, return FALSE);
  164647. INPUT_BYTE(cinfo, c, return FALSE);
  164648. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164649. ci++, compptr++) {
  164650. if (cc == compptr->component_id)
  164651. goto id_found;
  164652. }
  164653. ERREXIT1(cinfo, JERR_BAD_COMPONENT_ID, cc);
  164654. id_found:
  164655. cinfo->cur_comp_info[i] = compptr;
  164656. compptr->dc_tbl_no = (c >> 4) & 15;
  164657. compptr->ac_tbl_no = (c ) & 15;
  164658. TRACEMS3(cinfo, 1, JTRC_SOS_COMPONENT, cc,
  164659. compptr->dc_tbl_no, compptr->ac_tbl_no);
  164660. }
  164661. /* Collect the additional scan parameters Ss, Se, Ah/Al. */
  164662. INPUT_BYTE(cinfo, c, return FALSE);
  164663. cinfo->Ss = c;
  164664. INPUT_BYTE(cinfo, c, return FALSE);
  164665. cinfo->Se = c;
  164666. INPUT_BYTE(cinfo, c, return FALSE);
  164667. cinfo->Ah = (c >> 4) & 15;
  164668. cinfo->Al = (c ) & 15;
  164669. TRACEMS4(cinfo, 1, JTRC_SOS_PARAMS, cinfo->Ss, cinfo->Se,
  164670. cinfo->Ah, cinfo->Al);
  164671. /* Prepare to scan data & restart markers */
  164672. cinfo->marker->next_restart_num = 0;
  164673. /* Count another SOS marker */
  164674. cinfo->input_scan_number++;
  164675. INPUT_SYNC(cinfo);
  164676. return TRUE;
  164677. }
  164678. #ifdef D_ARITH_CODING_SUPPORTED
  164679. LOCAL(boolean)
  164680. get_dac (j_decompress_ptr cinfo)
  164681. /* Process a DAC marker */
  164682. {
  164683. INT32 length;
  164684. int index, val;
  164685. INPUT_VARS(cinfo);
  164686. INPUT_2BYTES(cinfo, length, return FALSE);
  164687. length -= 2;
  164688. while (length > 0) {
  164689. INPUT_BYTE(cinfo, index, return FALSE);
  164690. INPUT_BYTE(cinfo, val, return FALSE);
  164691. length -= 2;
  164692. TRACEMS2(cinfo, 1, JTRC_DAC, index, val);
  164693. if (index < 0 || index >= (2*NUM_ARITH_TBLS))
  164694. ERREXIT1(cinfo, JERR_DAC_INDEX, index);
  164695. if (index >= NUM_ARITH_TBLS) { /* define AC table */
  164696. cinfo->arith_ac_K[index-NUM_ARITH_TBLS] = (UINT8) val;
  164697. } else { /* define DC table */
  164698. cinfo->arith_dc_L[index] = (UINT8) (val & 0x0F);
  164699. cinfo->arith_dc_U[index] = (UINT8) (val >> 4);
  164700. if (cinfo->arith_dc_L[index] > cinfo->arith_dc_U[index])
  164701. ERREXIT1(cinfo, JERR_DAC_VALUE, val);
  164702. }
  164703. }
  164704. if (length != 0)
  164705. ERREXIT(cinfo, JERR_BAD_LENGTH);
  164706. INPUT_SYNC(cinfo);
  164707. return TRUE;
  164708. }
  164709. #else /* ! D_ARITH_CODING_SUPPORTED */
  164710. #define get_dac(cinfo) skip_variable(cinfo)
  164711. #endif /* D_ARITH_CODING_SUPPORTED */
  164712. LOCAL(boolean)
  164713. get_dht (j_decompress_ptr cinfo)
  164714. /* Process a DHT marker */
  164715. {
  164716. INT32 length;
  164717. UINT8 bits[17];
  164718. UINT8 huffval[256];
  164719. int i, index, count;
  164720. JHUFF_TBL **htblptr;
  164721. INPUT_VARS(cinfo);
  164722. INPUT_2BYTES(cinfo, length, return FALSE);
  164723. length -= 2;
  164724. while (length > 16) {
  164725. INPUT_BYTE(cinfo, index, return FALSE);
  164726. TRACEMS1(cinfo, 1, JTRC_DHT, index);
  164727. bits[0] = 0;
  164728. count = 0;
  164729. for (i = 1; i <= 16; i++) {
  164730. INPUT_BYTE(cinfo, bits[i], return FALSE);
  164731. count += bits[i];
  164732. }
  164733. length -= 1 + 16;
  164734. TRACEMS8(cinfo, 2, JTRC_HUFFBITS,
  164735. bits[1], bits[2], bits[3], bits[4],
  164736. bits[5], bits[6], bits[7], bits[8]);
  164737. TRACEMS8(cinfo, 2, JTRC_HUFFBITS,
  164738. bits[9], bits[10], bits[11], bits[12],
  164739. bits[13], bits[14], bits[15], bits[16]);
  164740. /* Here we just do minimal validation of the counts to avoid walking
  164741. * off the end of our table space. jdhuff.c will check more carefully.
  164742. */
  164743. if (count > 256 || ((INT32) count) > length)
  164744. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  164745. for (i = 0; i < count; i++)
  164746. INPUT_BYTE(cinfo, huffval[i], return FALSE);
  164747. length -= count;
  164748. if (index & 0x10) { /* AC table definition */
  164749. index -= 0x10;
  164750. htblptr = &cinfo->ac_huff_tbl_ptrs[index];
  164751. } else { /* DC table definition */
  164752. htblptr = &cinfo->dc_huff_tbl_ptrs[index];
  164753. }
  164754. if (index < 0 || index >= NUM_HUFF_TBLS)
  164755. ERREXIT1(cinfo, JERR_DHT_INDEX, index);
  164756. if (*htblptr == NULL)
  164757. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  164758. MEMCOPY((*htblptr)->bits, bits, SIZEOF((*htblptr)->bits));
  164759. MEMCOPY((*htblptr)->huffval, huffval, SIZEOF((*htblptr)->huffval));
  164760. }
  164761. if (length != 0)
  164762. ERREXIT(cinfo, JERR_BAD_LENGTH);
  164763. INPUT_SYNC(cinfo);
  164764. return TRUE;
  164765. }
  164766. LOCAL(boolean)
  164767. get_dqt (j_decompress_ptr cinfo)
  164768. /* Process a DQT marker */
  164769. {
  164770. INT32 length;
  164771. int n, i, prec;
  164772. unsigned int tmp;
  164773. JQUANT_TBL *quant_ptr;
  164774. INPUT_VARS(cinfo);
  164775. INPUT_2BYTES(cinfo, length, return FALSE);
  164776. length -= 2;
  164777. while (length > 0) {
  164778. INPUT_BYTE(cinfo, n, return FALSE);
  164779. prec = n >> 4;
  164780. n &= 0x0F;
  164781. TRACEMS2(cinfo, 1, JTRC_DQT, n, prec);
  164782. if (n >= NUM_QUANT_TBLS)
  164783. ERREXIT1(cinfo, JERR_DQT_INDEX, n);
  164784. if (cinfo->quant_tbl_ptrs[n] == NULL)
  164785. cinfo->quant_tbl_ptrs[n] = jpeg_alloc_quant_table((j_common_ptr) cinfo);
  164786. quant_ptr = cinfo->quant_tbl_ptrs[n];
  164787. for (i = 0; i < DCTSIZE2; i++) {
  164788. if (prec)
  164789. INPUT_2BYTES(cinfo, tmp, return FALSE);
  164790. else
  164791. INPUT_BYTE(cinfo, tmp, return FALSE);
  164792. /* We convert the zigzag-order table to natural array order. */
  164793. quant_ptr->quantval[jpeg_natural_order[i]] = (UINT16) tmp;
  164794. }
  164795. if (cinfo->err->trace_level >= 2) {
  164796. for (i = 0; i < DCTSIZE2; i += 8) {
  164797. TRACEMS8(cinfo, 2, JTRC_QUANTVALS,
  164798. quant_ptr->quantval[i], quant_ptr->quantval[i+1],
  164799. quant_ptr->quantval[i+2], quant_ptr->quantval[i+3],
  164800. quant_ptr->quantval[i+4], quant_ptr->quantval[i+5],
  164801. quant_ptr->quantval[i+6], quant_ptr->quantval[i+7]);
  164802. }
  164803. }
  164804. length -= DCTSIZE2+1;
  164805. if (prec) length -= DCTSIZE2;
  164806. }
  164807. if (length != 0)
  164808. ERREXIT(cinfo, JERR_BAD_LENGTH);
  164809. INPUT_SYNC(cinfo);
  164810. return TRUE;
  164811. }
  164812. LOCAL(boolean)
  164813. get_dri (j_decompress_ptr cinfo)
  164814. /* Process a DRI marker */
  164815. {
  164816. INT32 length;
  164817. unsigned int tmp;
  164818. INPUT_VARS(cinfo);
  164819. INPUT_2BYTES(cinfo, length, return FALSE);
  164820. if (length != 4)
  164821. ERREXIT(cinfo, JERR_BAD_LENGTH);
  164822. INPUT_2BYTES(cinfo, tmp, return FALSE);
  164823. TRACEMS1(cinfo, 1, JTRC_DRI, tmp);
  164824. cinfo->restart_interval = tmp;
  164825. INPUT_SYNC(cinfo);
  164826. return TRUE;
  164827. }
  164828. /*
  164829. * Routines for processing APPn and COM markers.
  164830. * These are either saved in memory or discarded, per application request.
  164831. * APP0 and APP14 are specially checked to see if they are
  164832. * JFIF and Adobe markers, respectively.
  164833. */
  164834. #define APP0_DATA_LEN 14 /* Length of interesting data in APP0 */
  164835. #define APP14_DATA_LEN 12 /* Length of interesting data in APP14 */
  164836. #define APPN_DATA_LEN 14 /* Must be the largest of the above!! */
  164837. LOCAL(void)
  164838. examine_app0 (j_decompress_ptr cinfo, JOCTET FAR * data,
  164839. unsigned int datalen, INT32 remaining)
  164840. /* Examine first few bytes from an APP0.
  164841. * Take appropriate action if it is a JFIF marker.
  164842. * datalen is # of bytes at data[], remaining is length of rest of marker data.
  164843. */
  164844. {
  164845. INT32 totallen = (INT32) datalen + remaining;
  164846. if (datalen >= APP0_DATA_LEN &&
  164847. GETJOCTET(data[0]) == 0x4A &&
  164848. GETJOCTET(data[1]) == 0x46 &&
  164849. GETJOCTET(data[2]) == 0x49 &&
  164850. GETJOCTET(data[3]) == 0x46 &&
  164851. GETJOCTET(data[4]) == 0) {
  164852. /* Found JFIF APP0 marker: save info */
  164853. cinfo->saw_JFIF_marker = TRUE;
  164854. cinfo->JFIF_major_version = GETJOCTET(data[5]);
  164855. cinfo->JFIF_minor_version = GETJOCTET(data[6]);
  164856. cinfo->density_unit = GETJOCTET(data[7]);
  164857. cinfo->X_density = (GETJOCTET(data[8]) << 8) + GETJOCTET(data[9]);
  164858. cinfo->Y_density = (GETJOCTET(data[10]) << 8) + GETJOCTET(data[11]);
  164859. /* Check version.
  164860. * Major version must be 1, anything else signals an incompatible change.
  164861. * (We used to treat this as an error, but now it's a nonfatal warning,
  164862. * because some bozo at Hijaak couldn't read the spec.)
  164863. * Minor version should be 0..2, but process anyway if newer.
  164864. */
  164865. if (cinfo->JFIF_major_version != 1)
  164866. WARNMS2(cinfo, JWRN_JFIF_MAJOR,
  164867. cinfo->JFIF_major_version, cinfo->JFIF_minor_version);
  164868. /* Generate trace messages */
  164869. TRACEMS5(cinfo, 1, JTRC_JFIF,
  164870. cinfo->JFIF_major_version, cinfo->JFIF_minor_version,
  164871. cinfo->X_density, cinfo->Y_density, cinfo->density_unit);
  164872. /* Validate thumbnail dimensions and issue appropriate messages */
  164873. if (GETJOCTET(data[12]) | GETJOCTET(data[13]))
  164874. TRACEMS2(cinfo, 1, JTRC_JFIF_THUMBNAIL,
  164875. GETJOCTET(data[12]), GETJOCTET(data[13]));
  164876. totallen -= APP0_DATA_LEN;
  164877. if (totallen !=
  164878. ((INT32)GETJOCTET(data[12]) * (INT32)GETJOCTET(data[13]) * (INT32) 3))
  164879. TRACEMS1(cinfo, 1, JTRC_JFIF_BADTHUMBNAILSIZE, (int) totallen);
  164880. } else if (datalen >= 6 &&
  164881. GETJOCTET(data[0]) == 0x4A &&
  164882. GETJOCTET(data[1]) == 0x46 &&
  164883. GETJOCTET(data[2]) == 0x58 &&
  164884. GETJOCTET(data[3]) == 0x58 &&
  164885. GETJOCTET(data[4]) == 0) {
  164886. /* Found JFIF "JFXX" extension APP0 marker */
  164887. /* The library doesn't actually do anything with these,
  164888. * but we try to produce a helpful trace message.
  164889. */
  164890. switch (GETJOCTET(data[5])) {
  164891. case 0x10:
  164892. TRACEMS1(cinfo, 1, JTRC_THUMB_JPEG, (int) totallen);
  164893. break;
  164894. case 0x11:
  164895. TRACEMS1(cinfo, 1, JTRC_THUMB_PALETTE, (int) totallen);
  164896. break;
  164897. case 0x13:
  164898. TRACEMS1(cinfo, 1, JTRC_THUMB_RGB, (int) totallen);
  164899. break;
  164900. default:
  164901. TRACEMS2(cinfo, 1, JTRC_JFIF_EXTENSION,
  164902. GETJOCTET(data[5]), (int) totallen);
  164903. break;
  164904. }
  164905. } else {
  164906. /* Start of APP0 does not match "JFIF" or "JFXX", or too short */
  164907. TRACEMS1(cinfo, 1, JTRC_APP0, (int) totallen);
  164908. }
  164909. }
  164910. LOCAL(void)
  164911. examine_app14 (j_decompress_ptr cinfo, JOCTET FAR * data,
  164912. unsigned int datalen, INT32 remaining)
  164913. /* Examine first few bytes from an APP14.
  164914. * Take appropriate action if it is an Adobe marker.
  164915. * datalen is # of bytes at data[], remaining is length of rest of marker data.
  164916. */
  164917. {
  164918. unsigned int version, flags0, flags1, transform;
  164919. if (datalen >= APP14_DATA_LEN &&
  164920. GETJOCTET(data[0]) == 0x41 &&
  164921. GETJOCTET(data[1]) == 0x64 &&
  164922. GETJOCTET(data[2]) == 0x6F &&
  164923. GETJOCTET(data[3]) == 0x62 &&
  164924. GETJOCTET(data[4]) == 0x65) {
  164925. /* Found Adobe APP14 marker */
  164926. version = (GETJOCTET(data[5]) << 8) + GETJOCTET(data[6]);
  164927. flags0 = (GETJOCTET(data[7]) << 8) + GETJOCTET(data[8]);
  164928. flags1 = (GETJOCTET(data[9]) << 8) + GETJOCTET(data[10]);
  164929. transform = GETJOCTET(data[11]);
  164930. TRACEMS4(cinfo, 1, JTRC_ADOBE, version, flags0, flags1, transform);
  164931. cinfo->saw_Adobe_marker = TRUE;
  164932. cinfo->Adobe_transform = (UINT8) transform;
  164933. } else {
  164934. /* Start of APP14 does not match "Adobe", or too short */
  164935. TRACEMS1(cinfo, 1, JTRC_APP14, (int) (datalen + remaining));
  164936. }
  164937. }
  164938. METHODDEF(boolean)
  164939. get_interesting_appn (j_decompress_ptr cinfo)
  164940. /* Process an APP0 or APP14 marker without saving it */
  164941. {
  164942. INT32 length;
  164943. JOCTET b[APPN_DATA_LEN];
  164944. unsigned int i, numtoread;
  164945. INPUT_VARS(cinfo);
  164946. INPUT_2BYTES(cinfo, length, return FALSE);
  164947. length -= 2;
  164948. /* get the interesting part of the marker data */
  164949. if (length >= APPN_DATA_LEN)
  164950. numtoread = APPN_DATA_LEN;
  164951. else if (length > 0)
  164952. numtoread = (unsigned int) length;
  164953. else
  164954. numtoread = 0;
  164955. for (i = 0; i < numtoread; i++)
  164956. INPUT_BYTE(cinfo, b[i], return FALSE);
  164957. length -= numtoread;
  164958. /* process it */
  164959. switch (cinfo->unread_marker) {
  164960. case M_APP0:
  164961. examine_app0(cinfo, (JOCTET FAR *) b, numtoread, length);
  164962. break;
  164963. case M_APP14:
  164964. examine_app14(cinfo, (JOCTET FAR *) b, numtoread, length);
  164965. break;
  164966. default:
  164967. /* can't get here unless jpeg_save_markers chooses wrong processor */
  164968. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, cinfo->unread_marker);
  164969. break;
  164970. }
  164971. /* skip any remaining data -- could be lots */
  164972. INPUT_SYNC(cinfo);
  164973. if (length > 0)
  164974. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  164975. return TRUE;
  164976. }
  164977. #ifdef SAVE_MARKERS_SUPPORTED
  164978. METHODDEF(boolean)
  164979. save_marker (j_decompress_ptr cinfo)
  164980. /* Save an APPn or COM marker into the marker list */
  164981. {
  164982. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  164983. jpeg_saved_marker_ptr cur_marker = marker->cur_marker;
  164984. unsigned int bytes_read, data_length;
  164985. JOCTET FAR * data;
  164986. INT32 length = 0;
  164987. INPUT_VARS(cinfo);
  164988. if (cur_marker == NULL) {
  164989. /* begin reading a marker */
  164990. INPUT_2BYTES(cinfo, length, return FALSE);
  164991. length -= 2;
  164992. if (length >= 0) { /* watch out for bogus length word */
  164993. /* figure out how much we want to save */
  164994. unsigned int limit;
  164995. if (cinfo->unread_marker == (int) M_COM)
  164996. limit = marker->length_limit_COM;
  164997. else
  164998. limit = marker->length_limit_APPn[cinfo->unread_marker - (int) M_APP0];
  164999. if ((unsigned int) length < limit)
  165000. limit = (unsigned int) length;
  165001. /* allocate and initialize the marker item */
  165002. cur_marker = (jpeg_saved_marker_ptr)
  165003. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165004. SIZEOF(struct jpeg_marker_struct) + limit);
  165005. cur_marker->next = NULL;
  165006. cur_marker->marker = (UINT8) cinfo->unread_marker;
  165007. cur_marker->original_length = (unsigned int) length;
  165008. cur_marker->data_length = limit;
  165009. /* data area is just beyond the jpeg_marker_struct */
  165010. data = cur_marker->data = (JOCTET FAR *) (cur_marker + 1);
  165011. marker->cur_marker = cur_marker;
  165012. marker->bytes_read = 0;
  165013. bytes_read = 0;
  165014. data_length = limit;
  165015. } else {
  165016. /* deal with bogus length word */
  165017. bytes_read = data_length = 0;
  165018. data = NULL;
  165019. }
  165020. } else {
  165021. /* resume reading a marker */
  165022. bytes_read = marker->bytes_read;
  165023. data_length = cur_marker->data_length;
  165024. data = cur_marker->data + bytes_read;
  165025. }
  165026. while (bytes_read < data_length) {
  165027. INPUT_SYNC(cinfo); /* move the restart point to here */
  165028. marker->bytes_read = bytes_read;
  165029. /* If there's not at least one byte in buffer, suspend */
  165030. MAKE_BYTE_AVAIL(cinfo, return FALSE);
  165031. /* Copy bytes with reasonable rapidity */
  165032. while (bytes_read < data_length && bytes_in_buffer > 0) {
  165033. *data++ = *next_input_byte++;
  165034. bytes_in_buffer--;
  165035. bytes_read++;
  165036. }
  165037. }
  165038. /* Done reading what we want to read */
  165039. if (cur_marker != NULL) { /* will be NULL if bogus length word */
  165040. /* Add new marker to end of list */
  165041. if (cinfo->marker_list == NULL) {
  165042. cinfo->marker_list = cur_marker;
  165043. } else {
  165044. jpeg_saved_marker_ptr prev = cinfo->marker_list;
  165045. while (prev->next != NULL)
  165046. prev = prev->next;
  165047. prev->next = cur_marker;
  165048. }
  165049. /* Reset pointer & calc remaining data length */
  165050. data = cur_marker->data;
  165051. length = cur_marker->original_length - data_length;
  165052. }
  165053. /* Reset to initial state for next marker */
  165054. marker->cur_marker = NULL;
  165055. /* Process the marker if interesting; else just make a generic trace msg */
  165056. switch (cinfo->unread_marker) {
  165057. case M_APP0:
  165058. examine_app0(cinfo, data, data_length, length);
  165059. break;
  165060. case M_APP14:
  165061. examine_app14(cinfo, data, data_length, length);
  165062. break;
  165063. default:
  165064. TRACEMS2(cinfo, 1, JTRC_MISC_MARKER, cinfo->unread_marker,
  165065. (int) (data_length + length));
  165066. break;
  165067. }
  165068. /* skip any remaining data -- could be lots */
  165069. INPUT_SYNC(cinfo); /* do before skip_input_data */
  165070. if (length > 0)
  165071. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  165072. return TRUE;
  165073. }
  165074. #endif /* SAVE_MARKERS_SUPPORTED */
  165075. METHODDEF(boolean)
  165076. skip_variable (j_decompress_ptr cinfo)
  165077. /* Skip over an unknown or uninteresting variable-length marker */
  165078. {
  165079. INT32 length;
  165080. INPUT_VARS(cinfo);
  165081. INPUT_2BYTES(cinfo, length, return FALSE);
  165082. length -= 2;
  165083. TRACEMS2(cinfo, 1, JTRC_MISC_MARKER, cinfo->unread_marker, (int) length);
  165084. INPUT_SYNC(cinfo); /* do before skip_input_data */
  165085. if (length > 0)
  165086. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  165087. return TRUE;
  165088. }
  165089. /*
  165090. * Find the next JPEG marker, save it in cinfo->unread_marker.
  165091. * Returns FALSE if had to suspend before reaching a marker;
  165092. * in that case cinfo->unread_marker is unchanged.
  165093. *
  165094. * Note that the result might not be a valid marker code,
  165095. * but it will never be 0 or FF.
  165096. */
  165097. LOCAL(boolean)
  165098. next_marker (j_decompress_ptr cinfo)
  165099. {
  165100. int c;
  165101. INPUT_VARS(cinfo);
  165102. for (;;) {
  165103. INPUT_BYTE(cinfo, c, return FALSE);
  165104. /* Skip any non-FF bytes.
  165105. * This may look a bit inefficient, but it will not occur in a valid file.
  165106. * We sync after each discarded byte so that a suspending data source
  165107. * can discard the byte from its buffer.
  165108. */
  165109. while (c != 0xFF) {
  165110. cinfo->marker->discarded_bytes++;
  165111. INPUT_SYNC(cinfo);
  165112. INPUT_BYTE(cinfo, c, return FALSE);
  165113. }
  165114. /* This loop swallows any duplicate FF bytes. Extra FFs are legal as
  165115. * pad bytes, so don't count them in discarded_bytes. We assume there
  165116. * will not be so many consecutive FF bytes as to overflow a suspending
  165117. * data source's input buffer.
  165118. */
  165119. do {
  165120. INPUT_BYTE(cinfo, c, return FALSE);
  165121. } while (c == 0xFF);
  165122. if (c != 0)
  165123. break; /* found a valid marker, exit loop */
  165124. /* Reach here if we found a stuffed-zero data sequence (FF/00).
  165125. * Discard it and loop back to try again.
  165126. */
  165127. cinfo->marker->discarded_bytes += 2;
  165128. INPUT_SYNC(cinfo);
  165129. }
  165130. if (cinfo->marker->discarded_bytes != 0) {
  165131. WARNMS2(cinfo, JWRN_EXTRANEOUS_DATA, cinfo->marker->discarded_bytes, c);
  165132. cinfo->marker->discarded_bytes = 0;
  165133. }
  165134. cinfo->unread_marker = c;
  165135. INPUT_SYNC(cinfo);
  165136. return TRUE;
  165137. }
  165138. LOCAL(boolean)
  165139. first_marker (j_decompress_ptr cinfo)
  165140. /* Like next_marker, but used to obtain the initial SOI marker. */
  165141. /* For this marker, we do not allow preceding garbage or fill; otherwise,
  165142. * we might well scan an entire input file before realizing it ain't JPEG.
  165143. * If an application wants to process non-JFIF files, it must seek to the
  165144. * SOI before calling the JPEG library.
  165145. */
  165146. {
  165147. int c, c2;
  165148. INPUT_VARS(cinfo);
  165149. INPUT_BYTE(cinfo, c, return FALSE);
  165150. INPUT_BYTE(cinfo, c2, return FALSE);
  165151. if (c != 0xFF || c2 != (int) M_SOI)
  165152. ERREXIT2(cinfo, JERR_NO_SOI, c, c2);
  165153. cinfo->unread_marker = c2;
  165154. INPUT_SYNC(cinfo);
  165155. return TRUE;
  165156. }
  165157. /*
  165158. * Read markers until SOS or EOI.
  165159. *
  165160. * Returns same codes as are defined for jpeg_consume_input:
  165161. * JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  165162. */
  165163. METHODDEF(int)
  165164. read_markers (j_decompress_ptr cinfo)
  165165. {
  165166. /* Outer loop repeats once for each marker. */
  165167. for (;;) {
  165168. /* Collect the marker proper, unless we already did. */
  165169. /* NB: first_marker() enforces the requirement that SOI appear first. */
  165170. if (cinfo->unread_marker == 0) {
  165171. if (! cinfo->marker->saw_SOI) {
  165172. if (! first_marker(cinfo))
  165173. return JPEG_SUSPENDED;
  165174. } else {
  165175. if (! next_marker(cinfo))
  165176. return JPEG_SUSPENDED;
  165177. }
  165178. }
  165179. /* At this point cinfo->unread_marker contains the marker code and the
  165180. * input point is just past the marker proper, but before any parameters.
  165181. * A suspension will cause us to return with this state still true.
  165182. */
  165183. switch (cinfo->unread_marker) {
  165184. case M_SOI:
  165185. if (! get_soi(cinfo))
  165186. return JPEG_SUSPENDED;
  165187. break;
  165188. case M_SOF0: /* Baseline */
  165189. case M_SOF1: /* Extended sequential, Huffman */
  165190. if (! get_sof(cinfo, FALSE, FALSE))
  165191. return JPEG_SUSPENDED;
  165192. break;
  165193. case M_SOF2: /* Progressive, Huffman */
  165194. if (! get_sof(cinfo, TRUE, FALSE))
  165195. return JPEG_SUSPENDED;
  165196. break;
  165197. case M_SOF9: /* Extended sequential, arithmetic */
  165198. if (! get_sof(cinfo, FALSE, TRUE))
  165199. return JPEG_SUSPENDED;
  165200. break;
  165201. case M_SOF10: /* Progressive, arithmetic */
  165202. if (! get_sof(cinfo, TRUE, TRUE))
  165203. return JPEG_SUSPENDED;
  165204. break;
  165205. /* Currently unsupported SOFn types */
  165206. case M_SOF3: /* Lossless, Huffman */
  165207. case M_SOF5: /* Differential sequential, Huffman */
  165208. case M_SOF6: /* Differential progressive, Huffman */
  165209. case M_SOF7: /* Differential lossless, Huffman */
  165210. case M_JPG: /* Reserved for JPEG extensions */
  165211. case M_SOF11: /* Lossless, arithmetic */
  165212. case M_SOF13: /* Differential sequential, arithmetic */
  165213. case M_SOF14: /* Differential progressive, arithmetic */
  165214. case M_SOF15: /* Differential lossless, arithmetic */
  165215. ERREXIT1(cinfo, JERR_SOF_UNSUPPORTED, cinfo->unread_marker);
  165216. break;
  165217. case M_SOS:
  165218. if (! get_sos(cinfo))
  165219. return JPEG_SUSPENDED;
  165220. cinfo->unread_marker = 0; /* processed the marker */
  165221. return JPEG_REACHED_SOS;
  165222. case M_EOI:
  165223. TRACEMS(cinfo, 1, JTRC_EOI);
  165224. cinfo->unread_marker = 0; /* processed the marker */
  165225. return JPEG_REACHED_EOI;
  165226. case M_DAC:
  165227. if (! get_dac(cinfo))
  165228. return JPEG_SUSPENDED;
  165229. break;
  165230. case M_DHT:
  165231. if (! get_dht(cinfo))
  165232. return JPEG_SUSPENDED;
  165233. break;
  165234. case M_DQT:
  165235. if (! get_dqt(cinfo))
  165236. return JPEG_SUSPENDED;
  165237. break;
  165238. case M_DRI:
  165239. if (! get_dri(cinfo))
  165240. return JPEG_SUSPENDED;
  165241. break;
  165242. case M_APP0:
  165243. case M_APP1:
  165244. case M_APP2:
  165245. case M_APP3:
  165246. case M_APP4:
  165247. case M_APP5:
  165248. case M_APP6:
  165249. case M_APP7:
  165250. case M_APP8:
  165251. case M_APP9:
  165252. case M_APP10:
  165253. case M_APP11:
  165254. case M_APP12:
  165255. case M_APP13:
  165256. case M_APP14:
  165257. case M_APP15:
  165258. if (! (*((my_marker_ptr2) cinfo->marker)->process_APPn[
  165259. cinfo->unread_marker - (int) M_APP0]) (cinfo))
  165260. return JPEG_SUSPENDED;
  165261. break;
  165262. case M_COM:
  165263. if (! (*((my_marker_ptr2) cinfo->marker)->process_COM) (cinfo))
  165264. return JPEG_SUSPENDED;
  165265. break;
  165266. case M_RST0: /* these are all parameterless */
  165267. case M_RST1:
  165268. case M_RST2:
  165269. case M_RST3:
  165270. case M_RST4:
  165271. case M_RST5:
  165272. case M_RST6:
  165273. case M_RST7:
  165274. case M_TEM:
  165275. TRACEMS1(cinfo, 1, JTRC_PARMLESS_MARKER, cinfo->unread_marker);
  165276. break;
  165277. case M_DNL: /* Ignore DNL ... perhaps the wrong thing */
  165278. if (! skip_variable(cinfo))
  165279. return JPEG_SUSPENDED;
  165280. break;
  165281. default: /* must be DHP, EXP, JPGn, or RESn */
  165282. /* For now, we treat the reserved markers as fatal errors since they are
  165283. * likely to be used to signal incompatible JPEG Part 3 extensions.
  165284. * Once the JPEG 3 version-number marker is well defined, this code
  165285. * ought to change!
  165286. */
  165287. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, cinfo->unread_marker);
  165288. break;
  165289. }
  165290. /* Successfully processed marker, so reset state variable */
  165291. cinfo->unread_marker = 0;
  165292. } /* end loop */
  165293. }
  165294. /*
  165295. * Read a restart marker, which is expected to appear next in the datastream;
  165296. * if the marker is not there, take appropriate recovery action.
  165297. * Returns FALSE if suspension is required.
  165298. *
  165299. * This is called by the entropy decoder after it has read an appropriate
  165300. * number of MCUs. cinfo->unread_marker may be nonzero if the entropy decoder
  165301. * has already read a marker from the data source. Under normal conditions
  165302. * cinfo->unread_marker will be reset to 0 before returning; if not reset,
  165303. * it holds a marker which the decoder will be unable to read past.
  165304. */
  165305. METHODDEF(boolean)
  165306. read_restart_marker (j_decompress_ptr cinfo)
  165307. {
  165308. /* Obtain a marker unless we already did. */
  165309. /* Note that next_marker will complain if it skips any data. */
  165310. if (cinfo->unread_marker == 0) {
  165311. if (! next_marker(cinfo))
  165312. return FALSE;
  165313. }
  165314. if (cinfo->unread_marker ==
  165315. ((int) M_RST0 + cinfo->marker->next_restart_num)) {
  165316. /* Normal case --- swallow the marker and let entropy decoder continue */
  165317. TRACEMS1(cinfo, 3, JTRC_RST, cinfo->marker->next_restart_num);
  165318. cinfo->unread_marker = 0;
  165319. } else {
  165320. /* Uh-oh, the restart markers have been messed up. */
  165321. /* Let the data source manager determine how to resync. */
  165322. if (! (*cinfo->src->resync_to_restart) (cinfo,
  165323. cinfo->marker->next_restart_num))
  165324. return FALSE;
  165325. }
  165326. /* Update next-restart state */
  165327. cinfo->marker->next_restart_num = (cinfo->marker->next_restart_num + 1) & 7;
  165328. return TRUE;
  165329. }
  165330. /*
  165331. * This is the default resync_to_restart method for data source managers
  165332. * to use if they don't have any better approach. Some data source managers
  165333. * may be able to back up, or may have additional knowledge about the data
  165334. * which permits a more intelligent recovery strategy; such managers would
  165335. * presumably supply their own resync method.
  165336. *
  165337. * read_restart_marker calls resync_to_restart if it finds a marker other than
  165338. * the restart marker it was expecting. (This code is *not* used unless
  165339. * a nonzero restart interval has been declared.) cinfo->unread_marker is
  165340. * the marker code actually found (might be anything, except 0 or FF).
  165341. * The desired restart marker number (0..7) is passed as a parameter.
  165342. * This routine is supposed to apply whatever error recovery strategy seems
  165343. * appropriate in order to position the input stream to the next data segment.
  165344. * Note that cinfo->unread_marker is treated as a marker appearing before
  165345. * the current data-source input point; usually it should be reset to zero
  165346. * before returning.
  165347. * Returns FALSE if suspension is required.
  165348. *
  165349. * This implementation is substantially constrained by wanting to treat the
  165350. * input as a data stream; this means we can't back up. Therefore, we have
  165351. * only the following actions to work with:
  165352. * 1. Simply discard the marker and let the entropy decoder resume at next
  165353. * byte of file.
  165354. * 2. Read forward until we find another marker, discarding intervening
  165355. * data. (In theory we could look ahead within the current bufferload,
  165356. * without having to discard data if we don't find the desired marker.
  165357. * This idea is not implemented here, in part because it makes behavior
  165358. * dependent on buffer size and chance buffer-boundary positions.)
  165359. * 3. Leave the marker unread (by failing to zero cinfo->unread_marker).
  165360. * This will cause the entropy decoder to process an empty data segment,
  165361. * inserting dummy zeroes, and then we will reprocess the marker.
  165362. *
  165363. * #2 is appropriate if we think the desired marker lies ahead, while #3 is
  165364. * appropriate if the found marker is a future restart marker (indicating
  165365. * that we have missed the desired restart marker, probably because it got
  165366. * corrupted).
  165367. * We apply #2 or #3 if the found marker is a restart marker no more than
  165368. * two counts behind or ahead of the expected one. We also apply #2 if the
  165369. * found marker is not a legal JPEG marker code (it's certainly bogus data).
  165370. * If the found marker is a restart marker more than 2 counts away, we do #1
  165371. * (too much risk that the marker is erroneous; with luck we will be able to
  165372. * resync at some future point).
  165373. * For any valid non-restart JPEG marker, we apply #3. This keeps us from
  165374. * overrunning the end of a scan. An implementation limited to single-scan
  165375. * files might find it better to apply #2 for markers other than EOI, since
  165376. * any other marker would have to be bogus data in that case.
  165377. */
  165378. GLOBAL(boolean)
  165379. jpeg_resync_to_restart (j_decompress_ptr cinfo, int desired)
  165380. {
  165381. int marker = cinfo->unread_marker;
  165382. int action = 1;
  165383. /* Always put up a warning. */
  165384. WARNMS2(cinfo, JWRN_MUST_RESYNC, marker, desired);
  165385. /* Outer loop handles repeated decision after scanning forward. */
  165386. for (;;) {
  165387. if (marker < (int) M_SOF0)
  165388. action = 2; /* invalid marker */
  165389. else if (marker < (int) M_RST0 || marker > (int) M_RST7)
  165390. action = 3; /* valid non-restart marker */
  165391. else {
  165392. if (marker == ((int) M_RST0 + ((desired+1) & 7)) ||
  165393. marker == ((int) M_RST0 + ((desired+2) & 7)))
  165394. action = 3; /* one of the next two expected restarts */
  165395. else if (marker == ((int) M_RST0 + ((desired-1) & 7)) ||
  165396. marker == ((int) M_RST0 + ((desired-2) & 7)))
  165397. action = 2; /* a prior restart, so advance */
  165398. else
  165399. action = 1; /* desired restart or too far away */
  165400. }
  165401. TRACEMS2(cinfo, 4, JTRC_RECOVERY_ACTION, marker, action);
  165402. switch (action) {
  165403. case 1:
  165404. /* Discard marker and let entropy decoder resume processing. */
  165405. cinfo->unread_marker = 0;
  165406. return TRUE;
  165407. case 2:
  165408. /* Scan to the next marker, and repeat the decision loop. */
  165409. if (! next_marker(cinfo))
  165410. return FALSE;
  165411. marker = cinfo->unread_marker;
  165412. break;
  165413. case 3:
  165414. /* Return without advancing past this marker. */
  165415. /* Entropy decoder will be forced to process an empty segment. */
  165416. return TRUE;
  165417. }
  165418. } /* end loop */
  165419. }
  165420. /*
  165421. * Reset marker processing state to begin a fresh datastream.
  165422. */
  165423. METHODDEF(void)
  165424. reset_marker_reader (j_decompress_ptr cinfo)
  165425. {
  165426. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  165427. cinfo->comp_info = NULL; /* until allocated by get_sof */
  165428. cinfo->input_scan_number = 0; /* no SOS seen yet */
  165429. cinfo->unread_marker = 0; /* no pending marker */
  165430. marker->pub.saw_SOI = FALSE; /* set internal state too */
  165431. marker->pub.saw_SOF = FALSE;
  165432. marker->pub.discarded_bytes = 0;
  165433. marker->cur_marker = NULL;
  165434. }
  165435. /*
  165436. * Initialize the marker reader module.
  165437. * This is called only once, when the decompression object is created.
  165438. */
  165439. GLOBAL(void)
  165440. jinit_marker_reader (j_decompress_ptr cinfo)
  165441. {
  165442. my_marker_ptr2 marker;
  165443. int i;
  165444. /* Create subobject in permanent pool */
  165445. marker = (my_marker_ptr2)
  165446. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  165447. SIZEOF(my_marker_reader));
  165448. cinfo->marker = (struct jpeg_marker_reader *) marker;
  165449. /* Initialize public method pointers */
  165450. marker->pub.reset_marker_reader = reset_marker_reader;
  165451. marker->pub.read_markers = read_markers;
  165452. marker->pub.read_restart_marker = read_restart_marker;
  165453. /* Initialize COM/APPn processing.
  165454. * By default, we examine and then discard APP0 and APP14,
  165455. * but simply discard COM and all other APPn.
  165456. */
  165457. marker->process_COM = skip_variable;
  165458. marker->length_limit_COM = 0;
  165459. for (i = 0; i < 16; i++) {
  165460. marker->process_APPn[i] = skip_variable;
  165461. marker->length_limit_APPn[i] = 0;
  165462. }
  165463. marker->process_APPn[0] = get_interesting_appn;
  165464. marker->process_APPn[14] = get_interesting_appn;
  165465. /* Reset marker processing state */
  165466. reset_marker_reader(cinfo);
  165467. }
  165468. /*
  165469. * Control saving of COM and APPn markers into marker_list.
  165470. */
  165471. #ifdef SAVE_MARKERS_SUPPORTED
  165472. GLOBAL(void)
  165473. jpeg_save_markers (j_decompress_ptr cinfo, int marker_code,
  165474. unsigned int length_limit)
  165475. {
  165476. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  165477. long maxlength;
  165478. jpeg_marker_parser_method processor;
  165479. /* Length limit mustn't be larger than what we can allocate
  165480. * (should only be a concern in a 16-bit environment).
  165481. */
  165482. maxlength = cinfo->mem->max_alloc_chunk - SIZEOF(struct jpeg_marker_struct);
  165483. if (((long) length_limit) > maxlength)
  165484. length_limit = (unsigned int) maxlength;
  165485. /* Choose processor routine to use.
  165486. * APP0/APP14 have special requirements.
  165487. */
  165488. if (length_limit) {
  165489. processor = save_marker;
  165490. /* If saving APP0/APP14, save at least enough for our internal use. */
  165491. if (marker_code == (int) M_APP0 && length_limit < APP0_DATA_LEN)
  165492. length_limit = APP0_DATA_LEN;
  165493. else if (marker_code == (int) M_APP14 && length_limit < APP14_DATA_LEN)
  165494. length_limit = APP14_DATA_LEN;
  165495. } else {
  165496. processor = skip_variable;
  165497. /* If discarding APP0/APP14, use our regular on-the-fly processor. */
  165498. if (marker_code == (int) M_APP0 || marker_code == (int) M_APP14)
  165499. processor = get_interesting_appn;
  165500. }
  165501. if (marker_code == (int) M_COM) {
  165502. marker->process_COM = processor;
  165503. marker->length_limit_COM = length_limit;
  165504. } else if (marker_code >= (int) M_APP0 && marker_code <= (int) M_APP15) {
  165505. marker->process_APPn[marker_code - (int) M_APP0] = processor;
  165506. marker->length_limit_APPn[marker_code - (int) M_APP0] = length_limit;
  165507. } else
  165508. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, marker_code);
  165509. }
  165510. #endif /* SAVE_MARKERS_SUPPORTED */
  165511. /*
  165512. * Install a special processing method for COM or APPn markers.
  165513. */
  165514. GLOBAL(void)
  165515. jpeg_set_marker_processor (j_decompress_ptr cinfo, int marker_code,
  165516. jpeg_marker_parser_method routine)
  165517. {
  165518. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  165519. if (marker_code == (int) M_COM)
  165520. marker->process_COM = routine;
  165521. else if (marker_code >= (int) M_APP0 && marker_code <= (int) M_APP15)
  165522. marker->process_APPn[marker_code - (int) M_APP0] = routine;
  165523. else
  165524. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, marker_code);
  165525. }
  165526. /********* End of inlined file: jdmarker.c *********/
  165527. /********* Start of inlined file: jdmaster.c *********/
  165528. #define JPEG_INTERNALS
  165529. /* Private state */
  165530. typedef struct {
  165531. struct jpeg_decomp_master pub; /* public fields */
  165532. int pass_number; /* # of passes completed */
  165533. boolean using_merged_upsample; /* TRUE if using merged upsample/cconvert */
  165534. /* Saved references to initialized quantizer modules,
  165535. * in case we need to switch modes.
  165536. */
  165537. struct jpeg_color_quantizer * quantizer_1pass;
  165538. struct jpeg_color_quantizer * quantizer_2pass;
  165539. } my_decomp_master;
  165540. typedef my_decomp_master * my_master_ptr6;
  165541. /*
  165542. * Determine whether merged upsample/color conversion should be used.
  165543. * CRUCIAL: this must match the actual capabilities of jdmerge.c!
  165544. */
  165545. LOCAL(boolean)
  165546. use_merged_upsample (j_decompress_ptr cinfo)
  165547. {
  165548. #ifdef UPSAMPLE_MERGING_SUPPORTED
  165549. /* Merging is the equivalent of plain box-filter upsampling */
  165550. if (cinfo->do_fancy_upsampling || cinfo->CCIR601_sampling)
  165551. return FALSE;
  165552. /* jdmerge.c only supports YCC=>RGB color conversion */
  165553. if (cinfo->jpeg_color_space != JCS_YCbCr || cinfo->num_components != 3 ||
  165554. cinfo->out_color_space != JCS_RGB ||
  165555. cinfo->out_color_components != RGB_PIXELSIZE)
  165556. return FALSE;
  165557. /* and it only handles 2h1v or 2h2v sampling ratios */
  165558. if (cinfo->comp_info[0].h_samp_factor != 2 ||
  165559. cinfo->comp_info[1].h_samp_factor != 1 ||
  165560. cinfo->comp_info[2].h_samp_factor != 1 ||
  165561. cinfo->comp_info[0].v_samp_factor > 2 ||
  165562. cinfo->comp_info[1].v_samp_factor != 1 ||
  165563. cinfo->comp_info[2].v_samp_factor != 1)
  165564. return FALSE;
  165565. /* furthermore, it doesn't work if we've scaled the IDCTs differently */
  165566. if (cinfo->comp_info[0].DCT_scaled_size != cinfo->min_DCT_scaled_size ||
  165567. cinfo->comp_info[1].DCT_scaled_size != cinfo->min_DCT_scaled_size ||
  165568. cinfo->comp_info[2].DCT_scaled_size != cinfo->min_DCT_scaled_size)
  165569. return FALSE;
  165570. /* ??? also need to test for upsample-time rescaling, when & if supported */
  165571. return TRUE; /* by golly, it'll work... */
  165572. #else
  165573. return FALSE;
  165574. #endif
  165575. }
  165576. /*
  165577. * Compute output image dimensions and related values.
  165578. * NOTE: this is exported for possible use by application.
  165579. * Hence it mustn't do anything that can't be done twice.
  165580. * Also note that it may be called before the master module is initialized!
  165581. */
  165582. GLOBAL(void)
  165583. jpeg_calc_output_dimensions (j_decompress_ptr cinfo)
  165584. /* Do computations that are needed before master selection phase */
  165585. {
  165586. #ifdef IDCT_SCALING_SUPPORTED
  165587. int ci;
  165588. jpeg_component_info *compptr;
  165589. #endif
  165590. /* Prevent application from calling me at wrong times */
  165591. if (cinfo->global_state != DSTATE_READY)
  165592. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  165593. #ifdef IDCT_SCALING_SUPPORTED
  165594. /* Compute actual output image dimensions and DCT scaling choices. */
  165595. if (cinfo->scale_num * 8 <= cinfo->scale_denom) {
  165596. /* Provide 1/8 scaling */
  165597. cinfo->output_width = (JDIMENSION)
  165598. jdiv_round_up((long) cinfo->image_width, 8L);
  165599. cinfo->output_height = (JDIMENSION)
  165600. jdiv_round_up((long) cinfo->image_height, 8L);
  165601. cinfo->min_DCT_scaled_size = 1;
  165602. } else if (cinfo->scale_num * 4 <= cinfo->scale_denom) {
  165603. /* Provide 1/4 scaling */
  165604. cinfo->output_width = (JDIMENSION)
  165605. jdiv_round_up((long) cinfo->image_width, 4L);
  165606. cinfo->output_height = (JDIMENSION)
  165607. jdiv_round_up((long) cinfo->image_height, 4L);
  165608. cinfo->min_DCT_scaled_size = 2;
  165609. } else if (cinfo->scale_num * 2 <= cinfo->scale_denom) {
  165610. /* Provide 1/2 scaling */
  165611. cinfo->output_width = (JDIMENSION)
  165612. jdiv_round_up((long) cinfo->image_width, 2L);
  165613. cinfo->output_height = (JDIMENSION)
  165614. jdiv_round_up((long) cinfo->image_height, 2L);
  165615. cinfo->min_DCT_scaled_size = 4;
  165616. } else {
  165617. /* Provide 1/1 scaling */
  165618. cinfo->output_width = cinfo->image_width;
  165619. cinfo->output_height = cinfo->image_height;
  165620. cinfo->min_DCT_scaled_size = DCTSIZE;
  165621. }
  165622. /* In selecting the actual DCT scaling for each component, we try to
  165623. * scale up the chroma components via IDCT scaling rather than upsampling.
  165624. * This saves time if the upsampler gets to use 1:1 scaling.
  165625. * Note this code assumes that the supported DCT scalings are powers of 2.
  165626. */
  165627. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  165628. ci++, compptr++) {
  165629. int ssize = cinfo->min_DCT_scaled_size;
  165630. while (ssize < DCTSIZE &&
  165631. (compptr->h_samp_factor * ssize * 2 <=
  165632. cinfo->max_h_samp_factor * cinfo->min_DCT_scaled_size) &&
  165633. (compptr->v_samp_factor * ssize * 2 <=
  165634. cinfo->max_v_samp_factor * cinfo->min_DCT_scaled_size)) {
  165635. ssize = ssize * 2;
  165636. }
  165637. compptr->DCT_scaled_size = ssize;
  165638. }
  165639. /* Recompute downsampled dimensions of components;
  165640. * application needs to know these if using raw downsampled data.
  165641. */
  165642. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  165643. ci++, compptr++) {
  165644. /* Size in samples, after IDCT scaling */
  165645. compptr->downsampled_width = (JDIMENSION)
  165646. jdiv_round_up((long) cinfo->image_width *
  165647. (long) (compptr->h_samp_factor * compptr->DCT_scaled_size),
  165648. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  165649. compptr->downsampled_height = (JDIMENSION)
  165650. jdiv_round_up((long) cinfo->image_height *
  165651. (long) (compptr->v_samp_factor * compptr->DCT_scaled_size),
  165652. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  165653. }
  165654. #else /* !IDCT_SCALING_SUPPORTED */
  165655. /* Hardwire it to "no scaling" */
  165656. cinfo->output_width = cinfo->image_width;
  165657. cinfo->output_height = cinfo->image_height;
  165658. /* jdinput.c has already initialized DCT_scaled_size to DCTSIZE,
  165659. * and has computed unscaled downsampled_width and downsampled_height.
  165660. */
  165661. #endif /* IDCT_SCALING_SUPPORTED */
  165662. /* Report number of components in selected colorspace. */
  165663. /* Probably this should be in the color conversion module... */
  165664. switch (cinfo->out_color_space) {
  165665. case JCS_GRAYSCALE:
  165666. cinfo->out_color_components = 1;
  165667. break;
  165668. case JCS_RGB:
  165669. #if RGB_PIXELSIZE != 3
  165670. cinfo->out_color_components = RGB_PIXELSIZE;
  165671. break;
  165672. #endif /* else share code with YCbCr */
  165673. case JCS_YCbCr:
  165674. cinfo->out_color_components = 3;
  165675. break;
  165676. case JCS_CMYK:
  165677. case JCS_YCCK:
  165678. cinfo->out_color_components = 4;
  165679. break;
  165680. default: /* else must be same colorspace as in file */
  165681. cinfo->out_color_components = cinfo->num_components;
  165682. break;
  165683. }
  165684. cinfo->output_components = (cinfo->quantize_colors ? 1 :
  165685. cinfo->out_color_components);
  165686. /* See if upsampler will want to emit more than one row at a time */
  165687. if (use_merged_upsample(cinfo))
  165688. cinfo->rec_outbuf_height = cinfo->max_v_samp_factor;
  165689. else
  165690. cinfo->rec_outbuf_height = 1;
  165691. }
  165692. /*
  165693. * Several decompression processes need to range-limit values to the range
  165694. * 0..MAXJSAMPLE; the input value may fall somewhat outside this range
  165695. * due to noise introduced by quantization, roundoff error, etc. These
  165696. * processes are inner loops and need to be as fast as possible. On most
  165697. * machines, particularly CPUs with pipelines or instruction prefetch,
  165698. * a (subscript-check-less) C table lookup
  165699. * x = sample_range_limit[x];
  165700. * is faster than explicit tests
  165701. * if (x < 0) x = 0;
  165702. * else if (x > MAXJSAMPLE) x = MAXJSAMPLE;
  165703. * These processes all use a common table prepared by the routine below.
  165704. *
  165705. * For most steps we can mathematically guarantee that the initial value
  165706. * of x is within MAXJSAMPLE+1 of the legal range, so a table running from
  165707. * -(MAXJSAMPLE+1) to 2*MAXJSAMPLE+1 is sufficient. But for the initial
  165708. * limiting step (just after the IDCT), a wildly out-of-range value is
  165709. * possible if the input data is corrupt. To avoid any chance of indexing
  165710. * off the end of memory and getting a bad-pointer trap, we perform the
  165711. * post-IDCT limiting thus:
  165712. * x = range_limit[x & MASK];
  165713. * where MASK is 2 bits wider than legal sample data, ie 10 bits for 8-bit
  165714. * samples. Under normal circumstances this is more than enough range and
  165715. * a correct output will be generated; with bogus input data the mask will
  165716. * cause wraparound, and we will safely generate a bogus-but-in-range output.
  165717. * For the post-IDCT step, we want to convert the data from signed to unsigned
  165718. * representation by adding CENTERJSAMPLE at the same time that we limit it.
  165719. * So the post-IDCT limiting table ends up looking like this:
  165720. * CENTERJSAMPLE,CENTERJSAMPLE+1,...,MAXJSAMPLE,
  165721. * MAXJSAMPLE (repeat 2*(MAXJSAMPLE+1)-CENTERJSAMPLE times),
  165722. * 0 (repeat 2*(MAXJSAMPLE+1)-CENTERJSAMPLE times),
  165723. * 0,1,...,CENTERJSAMPLE-1
  165724. * Negative inputs select values from the upper half of the table after
  165725. * masking.
  165726. *
  165727. * We can save some space by overlapping the start of the post-IDCT table
  165728. * with the simpler range limiting table. The post-IDCT table begins at
  165729. * sample_range_limit + CENTERJSAMPLE.
  165730. *
  165731. * Note that the table is allocated in near data space on PCs; it's small
  165732. * enough and used often enough to justify this.
  165733. */
  165734. LOCAL(void)
  165735. prepare_range_limit_table (j_decompress_ptr cinfo)
  165736. /* Allocate and fill in the sample_range_limit table */
  165737. {
  165738. JSAMPLE * table;
  165739. int i;
  165740. table = (JSAMPLE *)
  165741. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165742. (5 * (MAXJSAMPLE+1) + CENTERJSAMPLE) * SIZEOF(JSAMPLE));
  165743. table += (MAXJSAMPLE+1); /* allow negative subscripts of simple table */
  165744. cinfo->sample_range_limit = table;
  165745. /* First segment of "simple" table: limit[x] = 0 for x < 0 */
  165746. MEMZERO(table - (MAXJSAMPLE+1), (MAXJSAMPLE+1) * SIZEOF(JSAMPLE));
  165747. /* Main part of "simple" table: limit[x] = x */
  165748. for (i = 0; i <= MAXJSAMPLE; i++)
  165749. table[i] = (JSAMPLE) i;
  165750. table += CENTERJSAMPLE; /* Point to where post-IDCT table starts */
  165751. /* End of simple table, rest of first half of post-IDCT table */
  165752. for (i = CENTERJSAMPLE; i < 2*(MAXJSAMPLE+1); i++)
  165753. table[i] = MAXJSAMPLE;
  165754. /* Second half of post-IDCT table */
  165755. MEMZERO(table + (2 * (MAXJSAMPLE+1)),
  165756. (2 * (MAXJSAMPLE+1) - CENTERJSAMPLE) * SIZEOF(JSAMPLE));
  165757. MEMCOPY(table + (4 * (MAXJSAMPLE+1) - CENTERJSAMPLE),
  165758. cinfo->sample_range_limit, CENTERJSAMPLE * SIZEOF(JSAMPLE));
  165759. }
  165760. /*
  165761. * Master selection of decompression modules.
  165762. * This is done once at jpeg_start_decompress time. We determine
  165763. * which modules will be used and give them appropriate initialization calls.
  165764. * We also initialize the decompressor input side to begin consuming data.
  165765. *
  165766. * Since jpeg_read_header has finished, we know what is in the SOF
  165767. * and (first) SOS markers. We also have all the application parameter
  165768. * settings.
  165769. */
  165770. LOCAL(void)
  165771. master_selection (j_decompress_ptr cinfo)
  165772. {
  165773. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  165774. boolean use_c_buffer;
  165775. long samplesperrow;
  165776. JDIMENSION jd_samplesperrow;
  165777. /* Initialize dimensions and other stuff */
  165778. jpeg_calc_output_dimensions(cinfo);
  165779. prepare_range_limit_table(cinfo);
  165780. /* Width of an output scanline must be representable as JDIMENSION. */
  165781. samplesperrow = (long) cinfo->output_width * (long) cinfo->out_color_components;
  165782. jd_samplesperrow = (JDIMENSION) samplesperrow;
  165783. if ((long) jd_samplesperrow != samplesperrow)
  165784. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  165785. /* Initialize my private state */
  165786. master->pass_number = 0;
  165787. master->using_merged_upsample = use_merged_upsample(cinfo);
  165788. /* Color quantizer selection */
  165789. master->quantizer_1pass = NULL;
  165790. master->quantizer_2pass = NULL;
  165791. /* No mode changes if not using buffered-image mode. */
  165792. if (! cinfo->quantize_colors || ! cinfo->buffered_image) {
  165793. cinfo->enable_1pass_quant = FALSE;
  165794. cinfo->enable_external_quant = FALSE;
  165795. cinfo->enable_2pass_quant = FALSE;
  165796. }
  165797. if (cinfo->quantize_colors) {
  165798. if (cinfo->raw_data_out)
  165799. ERREXIT(cinfo, JERR_NOTIMPL);
  165800. /* 2-pass quantizer only works in 3-component color space. */
  165801. if (cinfo->out_color_components != 3) {
  165802. cinfo->enable_1pass_quant = TRUE;
  165803. cinfo->enable_external_quant = FALSE;
  165804. cinfo->enable_2pass_quant = FALSE;
  165805. cinfo->colormap = NULL;
  165806. } else if (cinfo->colormap != NULL) {
  165807. cinfo->enable_external_quant = TRUE;
  165808. } else if (cinfo->two_pass_quantize) {
  165809. cinfo->enable_2pass_quant = TRUE;
  165810. } else {
  165811. cinfo->enable_1pass_quant = TRUE;
  165812. }
  165813. if (cinfo->enable_1pass_quant) {
  165814. #ifdef QUANT_1PASS_SUPPORTED
  165815. jinit_1pass_quantizer(cinfo);
  165816. master->quantizer_1pass = cinfo->cquantize;
  165817. #else
  165818. ERREXIT(cinfo, JERR_NOT_COMPILED);
  165819. #endif
  165820. }
  165821. /* We use the 2-pass code to map to external colormaps. */
  165822. if (cinfo->enable_2pass_quant || cinfo->enable_external_quant) {
  165823. #ifdef QUANT_2PASS_SUPPORTED
  165824. jinit_2pass_quantizer(cinfo);
  165825. master->quantizer_2pass = cinfo->cquantize;
  165826. #else
  165827. ERREXIT(cinfo, JERR_NOT_COMPILED);
  165828. #endif
  165829. }
  165830. /* If both quantizers are initialized, the 2-pass one is left active;
  165831. * this is necessary for starting with quantization to an external map.
  165832. */
  165833. }
  165834. /* Post-processing: in particular, color conversion first */
  165835. if (! cinfo->raw_data_out) {
  165836. if (master->using_merged_upsample) {
  165837. #ifdef UPSAMPLE_MERGING_SUPPORTED
  165838. jinit_merged_upsampler(cinfo); /* does color conversion too */
  165839. #else
  165840. ERREXIT(cinfo, JERR_NOT_COMPILED);
  165841. #endif
  165842. } else {
  165843. jinit_color_deconverter(cinfo);
  165844. jinit_upsampler(cinfo);
  165845. }
  165846. jinit_d_post_controller(cinfo, cinfo->enable_2pass_quant);
  165847. }
  165848. /* Inverse DCT */
  165849. jinit_inverse_dct(cinfo);
  165850. /* Entropy decoding: either Huffman or arithmetic coding. */
  165851. if (cinfo->arith_code) {
  165852. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  165853. } else {
  165854. if (cinfo->progressive_mode) {
  165855. #ifdef D_PROGRESSIVE_SUPPORTED
  165856. jinit_phuff_decoder(cinfo);
  165857. #else
  165858. ERREXIT(cinfo, JERR_NOT_COMPILED);
  165859. #endif
  165860. } else
  165861. jinit_huff_decoder(cinfo);
  165862. }
  165863. /* Initialize principal buffer controllers. */
  165864. use_c_buffer = cinfo->inputctl->has_multiple_scans || cinfo->buffered_image;
  165865. jinit_d_coef_controller(cinfo, use_c_buffer);
  165866. if (! cinfo->raw_data_out)
  165867. jinit_d_main_controller(cinfo, FALSE /* never need full buffer here */);
  165868. /* We can now tell the memory manager to allocate virtual arrays. */
  165869. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  165870. /* Initialize input side of decompressor to consume first scan. */
  165871. (*cinfo->inputctl->start_input_pass) (cinfo);
  165872. #ifdef D_MULTISCAN_FILES_SUPPORTED
  165873. /* If jpeg_start_decompress will read the whole file, initialize
  165874. * progress monitoring appropriately. The input step is counted
  165875. * as one pass.
  165876. */
  165877. if (cinfo->progress != NULL && ! cinfo->buffered_image &&
  165878. cinfo->inputctl->has_multiple_scans) {
  165879. int nscans;
  165880. /* Estimate number of scans to set pass_limit. */
  165881. if (cinfo->progressive_mode) {
  165882. /* Arbitrarily estimate 2 interleaved DC scans + 3 AC scans/component. */
  165883. nscans = 2 + 3 * cinfo->num_components;
  165884. } else {
  165885. /* For a nonprogressive multiscan file, estimate 1 scan per component. */
  165886. nscans = cinfo->num_components;
  165887. }
  165888. cinfo->progress->pass_counter = 0L;
  165889. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows * nscans;
  165890. cinfo->progress->completed_passes = 0;
  165891. cinfo->progress->total_passes = (cinfo->enable_2pass_quant ? 3 : 2);
  165892. /* Count the input pass as done */
  165893. master->pass_number++;
  165894. }
  165895. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  165896. }
  165897. /*
  165898. * Per-pass setup.
  165899. * This is called at the beginning of each output pass. We determine which
  165900. * modules will be active during this pass and give them appropriate
  165901. * start_pass calls. We also set is_dummy_pass to indicate whether this
  165902. * is a "real" output pass or a dummy pass for color quantization.
  165903. * (In the latter case, jdapistd.c will crank the pass to completion.)
  165904. */
  165905. METHODDEF(void)
  165906. prepare_for_output_pass (j_decompress_ptr cinfo)
  165907. {
  165908. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  165909. if (master->pub.is_dummy_pass) {
  165910. #ifdef QUANT_2PASS_SUPPORTED
  165911. /* Final pass of 2-pass quantization */
  165912. master->pub.is_dummy_pass = FALSE;
  165913. (*cinfo->cquantize->start_pass) (cinfo, FALSE);
  165914. (*cinfo->post->start_pass) (cinfo, JBUF_CRANK_DEST);
  165915. (*cinfo->main->start_pass) (cinfo, JBUF_CRANK_DEST);
  165916. #else
  165917. ERREXIT(cinfo, JERR_NOT_COMPILED);
  165918. #endif /* QUANT_2PASS_SUPPORTED */
  165919. } else {
  165920. if (cinfo->quantize_colors && cinfo->colormap == NULL) {
  165921. /* Select new quantization method */
  165922. if (cinfo->two_pass_quantize && cinfo->enable_2pass_quant) {
  165923. cinfo->cquantize = master->quantizer_2pass;
  165924. master->pub.is_dummy_pass = TRUE;
  165925. } else if (cinfo->enable_1pass_quant) {
  165926. cinfo->cquantize = master->quantizer_1pass;
  165927. } else {
  165928. ERREXIT(cinfo, JERR_MODE_CHANGE);
  165929. }
  165930. }
  165931. (*cinfo->idct->start_pass) (cinfo);
  165932. (*cinfo->coef->start_output_pass) (cinfo);
  165933. if (! cinfo->raw_data_out) {
  165934. if (! master->using_merged_upsample)
  165935. (*cinfo->cconvert->start_pass) (cinfo);
  165936. (*cinfo->upsample->start_pass) (cinfo);
  165937. if (cinfo->quantize_colors)
  165938. (*cinfo->cquantize->start_pass) (cinfo, master->pub.is_dummy_pass);
  165939. (*cinfo->post->start_pass) (cinfo,
  165940. (master->pub.is_dummy_pass ? JBUF_SAVE_AND_PASS : JBUF_PASS_THRU));
  165941. (*cinfo->main->start_pass) (cinfo, JBUF_PASS_THRU);
  165942. }
  165943. }
  165944. /* Set up progress monitor's pass info if present */
  165945. if (cinfo->progress != NULL) {
  165946. cinfo->progress->completed_passes = master->pass_number;
  165947. cinfo->progress->total_passes = master->pass_number +
  165948. (master->pub.is_dummy_pass ? 2 : 1);
  165949. /* In buffered-image mode, we assume one more output pass if EOI not
  165950. * yet reached, but no more passes if EOI has been reached.
  165951. */
  165952. if (cinfo->buffered_image && ! cinfo->inputctl->eoi_reached) {
  165953. cinfo->progress->total_passes += (cinfo->enable_2pass_quant ? 2 : 1);
  165954. }
  165955. }
  165956. }
  165957. /*
  165958. * Finish up at end of an output pass.
  165959. */
  165960. METHODDEF(void)
  165961. finish_output_pass (j_decompress_ptr cinfo)
  165962. {
  165963. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  165964. if (cinfo->quantize_colors)
  165965. (*cinfo->cquantize->finish_pass) (cinfo);
  165966. master->pass_number++;
  165967. }
  165968. #ifdef D_MULTISCAN_FILES_SUPPORTED
  165969. /*
  165970. * Switch to a new external colormap between output passes.
  165971. */
  165972. GLOBAL(void)
  165973. jpeg_new_colormap (j_decompress_ptr cinfo)
  165974. {
  165975. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  165976. /* Prevent application from calling me at wrong times */
  165977. if (cinfo->global_state != DSTATE_BUFIMAGE)
  165978. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  165979. if (cinfo->quantize_colors && cinfo->enable_external_quant &&
  165980. cinfo->colormap != NULL) {
  165981. /* Select 2-pass quantizer for external colormap use */
  165982. cinfo->cquantize = master->quantizer_2pass;
  165983. /* Notify quantizer of colormap change */
  165984. (*cinfo->cquantize->new_color_map) (cinfo);
  165985. master->pub.is_dummy_pass = FALSE; /* just in case */
  165986. } else
  165987. ERREXIT(cinfo, JERR_MODE_CHANGE);
  165988. }
  165989. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  165990. /*
  165991. * Initialize master decompression control and select active modules.
  165992. * This is performed at the start of jpeg_start_decompress.
  165993. */
  165994. GLOBAL(void)
  165995. jinit_master_decompress (j_decompress_ptr cinfo)
  165996. {
  165997. my_master_ptr6 master;
  165998. master = (my_master_ptr6)
  165999. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166000. SIZEOF(my_decomp_master));
  166001. cinfo->master = (struct jpeg_decomp_master *) master;
  166002. master->pub.prepare_for_output_pass = prepare_for_output_pass;
  166003. master->pub.finish_output_pass = finish_output_pass;
  166004. master->pub.is_dummy_pass = FALSE;
  166005. master_selection(cinfo);
  166006. }
  166007. /********* End of inlined file: jdmaster.c *********/
  166008. #undef FIX
  166009. /********* Start of inlined file: jdmerge.c *********/
  166010. #define JPEG_INTERNALS
  166011. #ifdef UPSAMPLE_MERGING_SUPPORTED
  166012. /* Private subobject */
  166013. typedef struct {
  166014. struct jpeg_upsampler pub; /* public fields */
  166015. /* Pointer to routine to do actual upsampling/conversion of one row group */
  166016. JMETHOD(void, upmethod, (j_decompress_ptr cinfo,
  166017. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  166018. JSAMPARRAY output_buf));
  166019. /* Private state for YCC->RGB conversion */
  166020. int * Cr_r_tab; /* => table for Cr to R conversion */
  166021. int * Cb_b_tab; /* => table for Cb to B conversion */
  166022. INT32 * Cr_g_tab; /* => table for Cr to G conversion */
  166023. INT32 * Cb_g_tab; /* => table for Cb to G conversion */
  166024. /* For 2:1 vertical sampling, we produce two output rows at a time.
  166025. * We need a "spare" row buffer to hold the second output row if the
  166026. * application provides just a one-row buffer; we also use the spare
  166027. * to discard the dummy last row if the image height is odd.
  166028. */
  166029. JSAMPROW spare_row;
  166030. boolean spare_full; /* T if spare buffer is occupied */
  166031. JDIMENSION out_row_width; /* samples per output row */
  166032. JDIMENSION rows_to_go; /* counts rows remaining in image */
  166033. } my_upsampler;
  166034. typedef my_upsampler * my_upsample_ptr;
  166035. #define SCALEBITS 16 /* speediest right-shift on some machines */
  166036. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  166037. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  166038. /*
  166039. * Initialize tables for YCC->RGB colorspace conversion.
  166040. * This is taken directly from jdcolor.c; see that file for more info.
  166041. */
  166042. LOCAL(void)
  166043. build_ycc_rgb_table2 (j_decompress_ptr cinfo)
  166044. {
  166045. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  166046. int i;
  166047. INT32 x;
  166048. SHIFT_TEMPS
  166049. upsample->Cr_r_tab = (int *)
  166050. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166051. (MAXJSAMPLE+1) * SIZEOF(int));
  166052. upsample->Cb_b_tab = (int *)
  166053. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166054. (MAXJSAMPLE+1) * SIZEOF(int));
  166055. upsample->Cr_g_tab = (INT32 *)
  166056. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166057. (MAXJSAMPLE+1) * SIZEOF(INT32));
  166058. upsample->Cb_g_tab = (INT32 *)
  166059. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166060. (MAXJSAMPLE+1) * SIZEOF(INT32));
  166061. for (i = 0, x = -CENTERJSAMPLE; i <= MAXJSAMPLE; i++, x++) {
  166062. /* i is the actual input pixel value, in the range 0..MAXJSAMPLE */
  166063. /* The Cb or Cr value we are thinking of is x = i - CENTERJSAMPLE */
  166064. /* Cr=>R value is nearest int to 1.40200 * x */
  166065. upsample->Cr_r_tab[i] = (int)
  166066. RIGHT_SHIFT(FIX(1.40200) * x + ONE_HALF, SCALEBITS);
  166067. /* Cb=>B value is nearest int to 1.77200 * x */
  166068. upsample->Cb_b_tab[i] = (int)
  166069. RIGHT_SHIFT(FIX(1.77200) * x + ONE_HALF, SCALEBITS);
  166070. /* Cr=>G value is scaled-up -0.71414 * x */
  166071. upsample->Cr_g_tab[i] = (- FIX(0.71414)) * x;
  166072. /* Cb=>G value is scaled-up -0.34414 * x */
  166073. /* We also add in ONE_HALF so that need not do it in inner loop */
  166074. upsample->Cb_g_tab[i] = (- FIX(0.34414)) * x + ONE_HALF;
  166075. }
  166076. }
  166077. /*
  166078. * Initialize for an upsampling pass.
  166079. */
  166080. METHODDEF(void)
  166081. start_pass_merged_upsample (j_decompress_ptr cinfo)
  166082. {
  166083. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  166084. /* Mark the spare buffer empty */
  166085. upsample->spare_full = FALSE;
  166086. /* Initialize total-height counter for detecting bottom of image */
  166087. upsample->rows_to_go = cinfo->output_height;
  166088. }
  166089. /*
  166090. * Control routine to do upsampling (and color conversion).
  166091. *
  166092. * The control routine just handles the row buffering considerations.
  166093. */
  166094. METHODDEF(void)
  166095. merged_2v_upsample (j_decompress_ptr cinfo,
  166096. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  166097. JDIMENSION in_row_groups_avail,
  166098. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  166099. JDIMENSION out_rows_avail)
  166100. /* 2:1 vertical sampling case: may need a spare row. */
  166101. {
  166102. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  166103. JSAMPROW work_ptrs[2];
  166104. JDIMENSION num_rows; /* number of rows returned to caller */
  166105. if (upsample->spare_full) {
  166106. /* If we have a spare row saved from a previous cycle, just return it. */
  166107. jcopy_sample_rows(& upsample->spare_row, 0, output_buf + *out_row_ctr, 0,
  166108. 1, upsample->out_row_width);
  166109. num_rows = 1;
  166110. upsample->spare_full = FALSE;
  166111. } else {
  166112. /* Figure number of rows to return to caller. */
  166113. num_rows = 2;
  166114. /* Not more than the distance to the end of the image. */
  166115. if (num_rows > upsample->rows_to_go)
  166116. num_rows = upsample->rows_to_go;
  166117. /* And not more than what the client can accept: */
  166118. out_rows_avail -= *out_row_ctr;
  166119. if (num_rows > out_rows_avail)
  166120. num_rows = out_rows_avail;
  166121. /* Create output pointer array for upsampler. */
  166122. work_ptrs[0] = output_buf[*out_row_ctr];
  166123. if (num_rows > 1) {
  166124. work_ptrs[1] = output_buf[*out_row_ctr + 1];
  166125. } else {
  166126. work_ptrs[1] = upsample->spare_row;
  166127. upsample->spare_full = TRUE;
  166128. }
  166129. /* Now do the upsampling. */
  166130. (*upsample->upmethod) (cinfo, input_buf, *in_row_group_ctr, work_ptrs);
  166131. }
  166132. /* Adjust counts */
  166133. *out_row_ctr += num_rows;
  166134. upsample->rows_to_go -= num_rows;
  166135. /* When the buffer is emptied, declare this input row group consumed */
  166136. if (! upsample->spare_full)
  166137. (*in_row_group_ctr)++;
  166138. }
  166139. METHODDEF(void)
  166140. merged_1v_upsample (j_decompress_ptr cinfo,
  166141. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  166142. JDIMENSION in_row_groups_avail,
  166143. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  166144. JDIMENSION out_rows_avail)
  166145. /* 1:1 vertical sampling case: much easier, never need a spare row. */
  166146. {
  166147. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  166148. /* Just do the upsampling. */
  166149. (*upsample->upmethod) (cinfo, input_buf, *in_row_group_ctr,
  166150. output_buf + *out_row_ctr);
  166151. /* Adjust counts */
  166152. (*out_row_ctr)++;
  166153. (*in_row_group_ctr)++;
  166154. }
  166155. /*
  166156. * These are the routines invoked by the control routines to do
  166157. * the actual upsampling/conversion. One row group is processed per call.
  166158. *
  166159. * Note: since we may be writing directly into application-supplied buffers,
  166160. * we have to be honest about the output width; we can't assume the buffer
  166161. * has been rounded up to an even width.
  166162. */
  166163. /*
  166164. * Upsample and color convert for the case of 2:1 horizontal and 1:1 vertical.
  166165. */
  166166. METHODDEF(void)
  166167. h2v1_merged_upsample (j_decompress_ptr cinfo,
  166168. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  166169. JSAMPARRAY output_buf)
  166170. {
  166171. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  166172. register int y, cred, cgreen, cblue;
  166173. int cb, cr;
  166174. register JSAMPROW outptr;
  166175. JSAMPROW inptr0, inptr1, inptr2;
  166176. JDIMENSION col;
  166177. /* copy these pointers into registers if possible */
  166178. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  166179. int * Crrtab = upsample->Cr_r_tab;
  166180. int * Cbbtab = upsample->Cb_b_tab;
  166181. INT32 * Crgtab = upsample->Cr_g_tab;
  166182. INT32 * Cbgtab = upsample->Cb_g_tab;
  166183. SHIFT_TEMPS
  166184. inptr0 = input_buf[0][in_row_group_ctr];
  166185. inptr1 = input_buf[1][in_row_group_ctr];
  166186. inptr2 = input_buf[2][in_row_group_ctr];
  166187. outptr = output_buf[0];
  166188. /* Loop for each pair of output pixels */
  166189. for (col = cinfo->output_width >> 1; col > 0; col--) {
  166190. /* Do the chroma part of the calculation */
  166191. cb = GETJSAMPLE(*inptr1++);
  166192. cr = GETJSAMPLE(*inptr2++);
  166193. cred = Crrtab[cr];
  166194. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  166195. cblue = Cbbtab[cb];
  166196. /* Fetch 2 Y values and emit 2 pixels */
  166197. y = GETJSAMPLE(*inptr0++);
  166198. outptr[RGB_RED] = range_limit[y + cred];
  166199. outptr[RGB_GREEN] = range_limit[y + cgreen];
  166200. outptr[RGB_BLUE] = range_limit[y + cblue];
  166201. outptr += RGB_PIXELSIZE;
  166202. y = GETJSAMPLE(*inptr0++);
  166203. outptr[RGB_RED] = range_limit[y + cred];
  166204. outptr[RGB_GREEN] = range_limit[y + cgreen];
  166205. outptr[RGB_BLUE] = range_limit[y + cblue];
  166206. outptr += RGB_PIXELSIZE;
  166207. }
  166208. /* If image width is odd, do the last output column separately */
  166209. if (cinfo->output_width & 1) {
  166210. cb = GETJSAMPLE(*inptr1);
  166211. cr = GETJSAMPLE(*inptr2);
  166212. cred = Crrtab[cr];
  166213. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  166214. cblue = Cbbtab[cb];
  166215. y = GETJSAMPLE(*inptr0);
  166216. outptr[RGB_RED] = range_limit[y + cred];
  166217. outptr[RGB_GREEN] = range_limit[y + cgreen];
  166218. outptr[RGB_BLUE] = range_limit[y + cblue];
  166219. }
  166220. }
  166221. /*
  166222. * Upsample and color convert for the case of 2:1 horizontal and 2:1 vertical.
  166223. */
  166224. METHODDEF(void)
  166225. h2v2_merged_upsample (j_decompress_ptr cinfo,
  166226. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  166227. JSAMPARRAY output_buf)
  166228. {
  166229. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  166230. register int y, cred, cgreen, cblue;
  166231. int cb, cr;
  166232. register JSAMPROW outptr0, outptr1;
  166233. JSAMPROW inptr00, inptr01, inptr1, inptr2;
  166234. JDIMENSION col;
  166235. /* copy these pointers into registers if possible */
  166236. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  166237. int * Crrtab = upsample->Cr_r_tab;
  166238. int * Cbbtab = upsample->Cb_b_tab;
  166239. INT32 * Crgtab = upsample->Cr_g_tab;
  166240. INT32 * Cbgtab = upsample->Cb_g_tab;
  166241. SHIFT_TEMPS
  166242. inptr00 = input_buf[0][in_row_group_ctr*2];
  166243. inptr01 = input_buf[0][in_row_group_ctr*2 + 1];
  166244. inptr1 = input_buf[1][in_row_group_ctr];
  166245. inptr2 = input_buf[2][in_row_group_ctr];
  166246. outptr0 = output_buf[0];
  166247. outptr1 = output_buf[1];
  166248. /* Loop for each group of output pixels */
  166249. for (col = cinfo->output_width >> 1; col > 0; col--) {
  166250. /* Do the chroma part of the calculation */
  166251. cb = GETJSAMPLE(*inptr1++);
  166252. cr = GETJSAMPLE(*inptr2++);
  166253. cred = Crrtab[cr];
  166254. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  166255. cblue = Cbbtab[cb];
  166256. /* Fetch 4 Y values and emit 4 pixels */
  166257. y = GETJSAMPLE(*inptr00++);
  166258. outptr0[RGB_RED] = range_limit[y + cred];
  166259. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  166260. outptr0[RGB_BLUE] = range_limit[y + cblue];
  166261. outptr0 += RGB_PIXELSIZE;
  166262. y = GETJSAMPLE(*inptr00++);
  166263. outptr0[RGB_RED] = range_limit[y + cred];
  166264. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  166265. outptr0[RGB_BLUE] = range_limit[y + cblue];
  166266. outptr0 += RGB_PIXELSIZE;
  166267. y = GETJSAMPLE(*inptr01++);
  166268. outptr1[RGB_RED] = range_limit[y + cred];
  166269. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  166270. outptr1[RGB_BLUE] = range_limit[y + cblue];
  166271. outptr1 += RGB_PIXELSIZE;
  166272. y = GETJSAMPLE(*inptr01++);
  166273. outptr1[RGB_RED] = range_limit[y + cred];
  166274. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  166275. outptr1[RGB_BLUE] = range_limit[y + cblue];
  166276. outptr1 += RGB_PIXELSIZE;
  166277. }
  166278. /* If image width is odd, do the last output column separately */
  166279. if (cinfo->output_width & 1) {
  166280. cb = GETJSAMPLE(*inptr1);
  166281. cr = GETJSAMPLE(*inptr2);
  166282. cred = Crrtab[cr];
  166283. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  166284. cblue = Cbbtab[cb];
  166285. y = GETJSAMPLE(*inptr00);
  166286. outptr0[RGB_RED] = range_limit[y + cred];
  166287. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  166288. outptr0[RGB_BLUE] = range_limit[y + cblue];
  166289. y = GETJSAMPLE(*inptr01);
  166290. outptr1[RGB_RED] = range_limit[y + cred];
  166291. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  166292. outptr1[RGB_BLUE] = range_limit[y + cblue];
  166293. }
  166294. }
  166295. /*
  166296. * Module initialization routine for merged upsampling/color conversion.
  166297. *
  166298. * NB: this is called under the conditions determined by use_merged_upsample()
  166299. * in jdmaster.c. That routine MUST correspond to the actual capabilities
  166300. * of this module; no safety checks are made here.
  166301. */
  166302. GLOBAL(void)
  166303. jinit_merged_upsampler (j_decompress_ptr cinfo)
  166304. {
  166305. my_upsample_ptr upsample;
  166306. upsample = (my_upsample_ptr)
  166307. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166308. SIZEOF(my_upsampler));
  166309. cinfo->upsample = (struct jpeg_upsampler *) upsample;
  166310. upsample->pub.start_pass = start_pass_merged_upsample;
  166311. upsample->pub.need_context_rows = FALSE;
  166312. upsample->out_row_width = cinfo->output_width * cinfo->out_color_components;
  166313. if (cinfo->max_v_samp_factor == 2) {
  166314. upsample->pub.upsample = merged_2v_upsample;
  166315. upsample->upmethod = h2v2_merged_upsample;
  166316. /* Allocate a spare row buffer */
  166317. upsample->spare_row = (JSAMPROW)
  166318. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166319. (size_t) (upsample->out_row_width * SIZEOF(JSAMPLE)));
  166320. } else {
  166321. upsample->pub.upsample = merged_1v_upsample;
  166322. upsample->upmethod = h2v1_merged_upsample;
  166323. /* No spare row needed */
  166324. upsample->spare_row = NULL;
  166325. }
  166326. build_ycc_rgb_table2(cinfo);
  166327. }
  166328. #endif /* UPSAMPLE_MERGING_SUPPORTED */
  166329. /********* End of inlined file: jdmerge.c *********/
  166330. #undef ASSIGN_STATE
  166331. /********* Start of inlined file: jdphuff.c *********/
  166332. #define JPEG_INTERNALS
  166333. #ifdef D_PROGRESSIVE_SUPPORTED
  166334. /*
  166335. * Expanded entropy decoder object for progressive Huffman decoding.
  166336. *
  166337. * The savable_state subrecord contains fields that change within an MCU,
  166338. * but must not be updated permanently until we complete the MCU.
  166339. */
  166340. typedef struct {
  166341. unsigned int EOBRUN; /* remaining EOBs in EOBRUN */
  166342. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  166343. } savable_state3;
  166344. /* This macro is to work around compilers with missing or broken
  166345. * structure assignment. You'll need to fix this code if you have
  166346. * such a compiler and you change MAX_COMPS_IN_SCAN.
  166347. */
  166348. #ifndef NO_STRUCT_ASSIGN
  166349. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  166350. #else
  166351. #if MAX_COMPS_IN_SCAN == 4
  166352. #define ASSIGN_STATE(dest,src) \
  166353. ((dest).EOBRUN = (src).EOBRUN, \
  166354. (dest).last_dc_val[0] = (src).last_dc_val[0], \
  166355. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  166356. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  166357. (dest).last_dc_val[3] = (src).last_dc_val[3])
  166358. #endif
  166359. #endif
  166360. typedef struct {
  166361. struct jpeg_entropy_decoder pub; /* public fields */
  166362. /* These fields are loaded into local variables at start of each MCU.
  166363. * In case of suspension, we exit WITHOUT updating them.
  166364. */
  166365. bitread_perm_state bitstate; /* Bit buffer at start of MCU */
  166366. savable_state3 saved; /* Other state at start of MCU */
  166367. /* These fields are NOT loaded into local working state. */
  166368. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  166369. /* Pointers to derived tables (these workspaces have image lifespan) */
  166370. d_derived_tbl * derived_tbls[NUM_HUFF_TBLS];
  166371. d_derived_tbl * ac_derived_tbl; /* active table during an AC scan */
  166372. } phuff_entropy_decoder;
  166373. typedef phuff_entropy_decoder * phuff_entropy_ptr2;
  166374. /* Forward declarations */
  166375. METHODDEF(boolean) decode_mcu_DC_first JPP((j_decompress_ptr cinfo,
  166376. JBLOCKROW *MCU_data));
  166377. METHODDEF(boolean) decode_mcu_AC_first JPP((j_decompress_ptr cinfo,
  166378. JBLOCKROW *MCU_data));
  166379. METHODDEF(boolean) decode_mcu_DC_refine JPP((j_decompress_ptr cinfo,
  166380. JBLOCKROW *MCU_data));
  166381. METHODDEF(boolean) decode_mcu_AC_refine JPP((j_decompress_ptr cinfo,
  166382. JBLOCKROW *MCU_data));
  166383. /*
  166384. * Initialize for a Huffman-compressed scan.
  166385. */
  166386. METHODDEF(void)
  166387. start_pass_phuff_decoder (j_decompress_ptr cinfo)
  166388. {
  166389. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  166390. boolean is_DC_band, bad;
  166391. int ci, coefi, tbl;
  166392. int *coef_bit_ptr;
  166393. jpeg_component_info * compptr;
  166394. is_DC_band = (cinfo->Ss == 0);
  166395. /* Validate scan parameters */
  166396. bad = FALSE;
  166397. if (is_DC_band) {
  166398. if (cinfo->Se != 0)
  166399. bad = TRUE;
  166400. } else {
  166401. /* need not check Ss/Se < 0 since they came from unsigned bytes */
  166402. if (cinfo->Ss > cinfo->Se || cinfo->Se >= DCTSIZE2)
  166403. bad = TRUE;
  166404. /* AC scans may have only one component */
  166405. if (cinfo->comps_in_scan != 1)
  166406. bad = TRUE;
  166407. }
  166408. if (cinfo->Ah != 0) {
  166409. /* Successive approximation refinement scan: must have Al = Ah-1. */
  166410. if (cinfo->Al != cinfo->Ah-1)
  166411. bad = TRUE;
  166412. }
  166413. if (cinfo->Al > 13) /* need not check for < 0 */
  166414. bad = TRUE;
  166415. /* Arguably the maximum Al value should be less than 13 for 8-bit precision,
  166416. * but the spec doesn't say so, and we try to be liberal about what we
  166417. * accept. Note: large Al values could result in out-of-range DC
  166418. * coefficients during early scans, leading to bizarre displays due to
  166419. * overflows in the IDCT math. But we won't crash.
  166420. */
  166421. if (bad)
  166422. ERREXIT4(cinfo, JERR_BAD_PROGRESSION,
  166423. cinfo->Ss, cinfo->Se, cinfo->Ah, cinfo->Al);
  166424. /* Update progression status, and verify that scan order is legal.
  166425. * Note that inter-scan inconsistencies are treated as warnings
  166426. * not fatal errors ... not clear if this is right way to behave.
  166427. */
  166428. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  166429. int cindex = cinfo->cur_comp_info[ci]->component_index;
  166430. coef_bit_ptr = & cinfo->coef_bits[cindex][0];
  166431. if (!is_DC_band && coef_bit_ptr[0] < 0) /* AC without prior DC scan */
  166432. WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, 0);
  166433. for (coefi = cinfo->Ss; coefi <= cinfo->Se; coefi++) {
  166434. int expected = (coef_bit_ptr[coefi] < 0) ? 0 : coef_bit_ptr[coefi];
  166435. if (cinfo->Ah != expected)
  166436. WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, coefi);
  166437. coef_bit_ptr[coefi] = cinfo->Al;
  166438. }
  166439. }
  166440. /* Select MCU decoding routine */
  166441. if (cinfo->Ah == 0) {
  166442. if (is_DC_band)
  166443. entropy->pub.decode_mcu = decode_mcu_DC_first;
  166444. else
  166445. entropy->pub.decode_mcu = decode_mcu_AC_first;
  166446. } else {
  166447. if (is_DC_band)
  166448. entropy->pub.decode_mcu = decode_mcu_DC_refine;
  166449. else
  166450. entropy->pub.decode_mcu = decode_mcu_AC_refine;
  166451. }
  166452. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  166453. compptr = cinfo->cur_comp_info[ci];
  166454. /* Make sure requested tables are present, and compute derived tables.
  166455. * We may build same derived table more than once, but it's not expensive.
  166456. */
  166457. if (is_DC_band) {
  166458. if (cinfo->Ah == 0) { /* DC refinement needs no table */
  166459. tbl = compptr->dc_tbl_no;
  166460. jpeg_make_d_derived_tbl(cinfo, TRUE, tbl,
  166461. & entropy->derived_tbls[tbl]);
  166462. }
  166463. } else {
  166464. tbl = compptr->ac_tbl_no;
  166465. jpeg_make_d_derived_tbl(cinfo, FALSE, tbl,
  166466. & entropy->derived_tbls[tbl]);
  166467. /* remember the single active table */
  166468. entropy->ac_derived_tbl = entropy->derived_tbls[tbl];
  166469. }
  166470. /* Initialize DC predictions to 0 */
  166471. entropy->saved.last_dc_val[ci] = 0;
  166472. }
  166473. /* Initialize bitread state variables */
  166474. entropy->bitstate.bits_left = 0;
  166475. entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
  166476. entropy->pub.insufficient_data = FALSE;
  166477. /* Initialize private state variables */
  166478. entropy->saved.EOBRUN = 0;
  166479. /* Initialize restart counter */
  166480. entropy->restarts_to_go = cinfo->restart_interval;
  166481. }
  166482. /*
  166483. * Check for a restart marker & resynchronize decoder.
  166484. * Returns FALSE if must suspend.
  166485. */
  166486. LOCAL(boolean)
  166487. process_restartp (j_decompress_ptr cinfo)
  166488. {
  166489. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  166490. int ci;
  166491. /* Throw away any unused bits remaining in bit buffer; */
  166492. /* include any full bytes in next_marker's count of discarded bytes */
  166493. cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
  166494. entropy->bitstate.bits_left = 0;
  166495. /* Advance past the RSTn marker */
  166496. if (! (*cinfo->marker->read_restart_marker) (cinfo))
  166497. return FALSE;
  166498. /* Re-initialize DC predictions to 0 */
  166499. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  166500. entropy->saved.last_dc_val[ci] = 0;
  166501. /* Re-init EOB run count, too */
  166502. entropy->saved.EOBRUN = 0;
  166503. /* Reset restart counter */
  166504. entropy->restarts_to_go = cinfo->restart_interval;
  166505. /* Reset out-of-data flag, unless read_restart_marker left us smack up
  166506. * against a marker. In that case we will end up treating the next data
  166507. * segment as empty, and we can avoid producing bogus output pixels by
  166508. * leaving the flag set.
  166509. */
  166510. if (cinfo->unread_marker == 0)
  166511. entropy->pub.insufficient_data = FALSE;
  166512. return TRUE;
  166513. }
  166514. /*
  166515. * Huffman MCU decoding.
  166516. * Each of these routines decodes and returns one MCU's worth of
  166517. * Huffman-compressed coefficients.
  166518. * The coefficients are reordered from zigzag order into natural array order,
  166519. * but are not dequantized.
  166520. *
  166521. * The i'th block of the MCU is stored into the block pointed to by
  166522. * MCU_data[i]. WE ASSUME THIS AREA IS INITIALLY ZEROED BY THE CALLER.
  166523. *
  166524. * We return FALSE if data source requested suspension. In that case no
  166525. * changes have been made to permanent state. (Exception: some output
  166526. * coefficients may already have been assigned. This is harmless for
  166527. * spectral selection, since we'll just re-assign them on the next call.
  166528. * Successive approximation AC refinement has to be more careful, however.)
  166529. */
  166530. /*
  166531. * MCU decoding for DC initial scan (either spectral selection,
  166532. * or first pass of successive approximation).
  166533. */
  166534. METHODDEF(boolean)
  166535. decode_mcu_DC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  166536. {
  166537. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  166538. int Al = cinfo->Al;
  166539. register int s, r;
  166540. int blkn, ci;
  166541. JBLOCKROW block;
  166542. BITREAD_STATE_VARS;
  166543. savable_state3 state;
  166544. d_derived_tbl * tbl;
  166545. jpeg_component_info * compptr;
  166546. /* Process restart marker if needed; may have to suspend */
  166547. if (cinfo->restart_interval) {
  166548. if (entropy->restarts_to_go == 0)
  166549. if (! process_restartp(cinfo))
  166550. return FALSE;
  166551. }
  166552. /* If we've run out of data, just leave the MCU set to zeroes.
  166553. * This way, we return uniform gray for the remainder of the segment.
  166554. */
  166555. if (! entropy->pub.insufficient_data) {
  166556. /* Load up working state */
  166557. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  166558. ASSIGN_STATE(state, entropy->saved);
  166559. /* Outer loop handles each block in the MCU */
  166560. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  166561. block = MCU_data[blkn];
  166562. ci = cinfo->MCU_membership[blkn];
  166563. compptr = cinfo->cur_comp_info[ci];
  166564. tbl = entropy->derived_tbls[compptr->dc_tbl_no];
  166565. /* Decode a single block's worth of coefficients */
  166566. /* Section F.2.2.1: decode the DC coefficient difference */
  166567. HUFF_DECODE(s, br_state, tbl, return FALSE, label1);
  166568. if (s) {
  166569. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  166570. r = GET_BITS(s);
  166571. s = HUFF_EXTEND(r, s);
  166572. }
  166573. /* Convert DC difference to actual value, update last_dc_val */
  166574. s += state.last_dc_val[ci];
  166575. state.last_dc_val[ci] = s;
  166576. /* Scale and output the coefficient (assumes jpeg_natural_order[0]=0) */
  166577. (*block)[0] = (JCOEF) (s << Al);
  166578. }
  166579. /* Completed MCU, so update state */
  166580. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  166581. ASSIGN_STATE(entropy->saved, state);
  166582. }
  166583. /* Account for restart interval (no-op if not using restarts) */
  166584. entropy->restarts_to_go--;
  166585. return TRUE;
  166586. }
  166587. /*
  166588. * MCU decoding for AC initial scan (either spectral selection,
  166589. * or first pass of successive approximation).
  166590. */
  166591. METHODDEF(boolean)
  166592. decode_mcu_AC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  166593. {
  166594. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  166595. int Se = cinfo->Se;
  166596. int Al = cinfo->Al;
  166597. register int s, k, r;
  166598. unsigned int EOBRUN;
  166599. JBLOCKROW block;
  166600. BITREAD_STATE_VARS;
  166601. d_derived_tbl * tbl;
  166602. /* Process restart marker if needed; may have to suspend */
  166603. if (cinfo->restart_interval) {
  166604. if (entropy->restarts_to_go == 0)
  166605. if (! process_restartp(cinfo))
  166606. return FALSE;
  166607. }
  166608. /* If we've run out of data, just leave the MCU set to zeroes.
  166609. * This way, we return uniform gray for the remainder of the segment.
  166610. */
  166611. if (! entropy->pub.insufficient_data) {
  166612. /* Load up working state.
  166613. * We can avoid loading/saving bitread state if in an EOB run.
  166614. */
  166615. EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */
  166616. /* There is always only one block per MCU */
  166617. if (EOBRUN > 0) /* if it's a band of zeroes... */
  166618. EOBRUN--; /* ...process it now (we do nothing) */
  166619. else {
  166620. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  166621. block = MCU_data[0];
  166622. tbl = entropy->ac_derived_tbl;
  166623. for (k = cinfo->Ss; k <= Se; k++) {
  166624. HUFF_DECODE(s, br_state, tbl, return FALSE, label2);
  166625. r = s >> 4;
  166626. s &= 15;
  166627. if (s) {
  166628. k += r;
  166629. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  166630. r = GET_BITS(s);
  166631. s = HUFF_EXTEND(r, s);
  166632. /* Scale and output coefficient in natural (dezigzagged) order */
  166633. (*block)[jpeg_natural_order[k]] = (JCOEF) (s << Al);
  166634. } else {
  166635. if (r == 15) { /* ZRL */
  166636. k += 15; /* skip 15 zeroes in band */
  166637. } else { /* EOBr, run length is 2^r + appended bits */
  166638. EOBRUN = 1 << r;
  166639. if (r) { /* EOBr, r > 0 */
  166640. CHECK_BIT_BUFFER(br_state, r, return FALSE);
  166641. r = GET_BITS(r);
  166642. EOBRUN += r;
  166643. }
  166644. EOBRUN--; /* this band is processed at this moment */
  166645. break; /* force end-of-band */
  166646. }
  166647. }
  166648. }
  166649. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  166650. }
  166651. /* Completed MCU, so update state */
  166652. entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */
  166653. }
  166654. /* Account for restart interval (no-op if not using restarts) */
  166655. entropy->restarts_to_go--;
  166656. return TRUE;
  166657. }
  166658. /*
  166659. * MCU decoding for DC successive approximation refinement scan.
  166660. * Note: we assume such scans can be multi-component, although the spec
  166661. * is not very clear on the point.
  166662. */
  166663. METHODDEF(boolean)
  166664. decode_mcu_DC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  166665. {
  166666. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  166667. int p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
  166668. int blkn;
  166669. JBLOCKROW block;
  166670. BITREAD_STATE_VARS;
  166671. /* Process restart marker if needed; may have to suspend */
  166672. if (cinfo->restart_interval) {
  166673. if (entropy->restarts_to_go == 0)
  166674. if (! process_restartp(cinfo))
  166675. return FALSE;
  166676. }
  166677. /* Not worth the cycles to check insufficient_data here,
  166678. * since we will not change the data anyway if we read zeroes.
  166679. */
  166680. /* Load up working state */
  166681. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  166682. /* Outer loop handles each block in the MCU */
  166683. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  166684. block = MCU_data[blkn];
  166685. /* Encoded data is simply the next bit of the two's-complement DC value */
  166686. CHECK_BIT_BUFFER(br_state, 1, return FALSE);
  166687. if (GET_BITS(1))
  166688. (*block)[0] |= p1;
  166689. /* Note: since we use |=, repeating the assignment later is safe */
  166690. }
  166691. /* Completed MCU, so update state */
  166692. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  166693. /* Account for restart interval (no-op if not using restarts) */
  166694. entropy->restarts_to_go--;
  166695. return TRUE;
  166696. }
  166697. /*
  166698. * MCU decoding for AC successive approximation refinement scan.
  166699. */
  166700. METHODDEF(boolean)
  166701. decode_mcu_AC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  166702. {
  166703. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  166704. int Se = cinfo->Se;
  166705. int p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
  166706. int m1 = (-1) << cinfo->Al; /* -1 in the bit position being coded */
  166707. register int s, k, r;
  166708. unsigned int EOBRUN;
  166709. JBLOCKROW block;
  166710. JCOEFPTR thiscoef;
  166711. BITREAD_STATE_VARS;
  166712. d_derived_tbl * tbl;
  166713. int num_newnz;
  166714. int newnz_pos[DCTSIZE2];
  166715. /* Process restart marker if needed; may have to suspend */
  166716. if (cinfo->restart_interval) {
  166717. if (entropy->restarts_to_go == 0)
  166718. if (! process_restartp(cinfo))
  166719. return FALSE;
  166720. }
  166721. /* If we've run out of data, don't modify the MCU.
  166722. */
  166723. if (! entropy->pub.insufficient_data) {
  166724. /* Load up working state */
  166725. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  166726. EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */
  166727. /* There is always only one block per MCU */
  166728. block = MCU_data[0];
  166729. tbl = entropy->ac_derived_tbl;
  166730. /* If we are forced to suspend, we must undo the assignments to any newly
  166731. * nonzero coefficients in the block, because otherwise we'd get confused
  166732. * next time about which coefficients were already nonzero.
  166733. * But we need not undo addition of bits to already-nonzero coefficients;
  166734. * instead, we can test the current bit to see if we already did it.
  166735. */
  166736. num_newnz = 0;
  166737. /* initialize coefficient loop counter to start of band */
  166738. k = cinfo->Ss;
  166739. if (EOBRUN == 0) {
  166740. for (; k <= Se; k++) {
  166741. HUFF_DECODE(s, br_state, tbl, goto undoit, label3);
  166742. r = s >> 4;
  166743. s &= 15;
  166744. if (s) {
  166745. if (s != 1) /* size of new coef should always be 1 */
  166746. WARNMS(cinfo, JWRN_HUFF_BAD_CODE);
  166747. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  166748. if (GET_BITS(1))
  166749. s = p1; /* newly nonzero coef is positive */
  166750. else
  166751. s = m1; /* newly nonzero coef is negative */
  166752. } else {
  166753. if (r != 15) {
  166754. EOBRUN = 1 << r; /* EOBr, run length is 2^r + appended bits */
  166755. if (r) {
  166756. CHECK_BIT_BUFFER(br_state, r, goto undoit);
  166757. r = GET_BITS(r);
  166758. EOBRUN += r;
  166759. }
  166760. break; /* rest of block is handled by EOB logic */
  166761. }
  166762. /* note s = 0 for processing ZRL */
  166763. }
  166764. /* Advance over already-nonzero coefs and r still-zero coefs,
  166765. * appending correction bits to the nonzeroes. A correction bit is 1
  166766. * if the absolute value of the coefficient must be increased.
  166767. */
  166768. do {
  166769. thiscoef = *block + jpeg_natural_order[k];
  166770. if (*thiscoef != 0) {
  166771. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  166772. if (GET_BITS(1)) {
  166773. if ((*thiscoef & p1) == 0) { /* do nothing if already set it */
  166774. if (*thiscoef >= 0)
  166775. *thiscoef += p1;
  166776. else
  166777. *thiscoef += m1;
  166778. }
  166779. }
  166780. } else {
  166781. if (--r < 0)
  166782. break; /* reached target zero coefficient */
  166783. }
  166784. k++;
  166785. } while (k <= Se);
  166786. if (s) {
  166787. int pos = jpeg_natural_order[k];
  166788. /* Output newly nonzero coefficient */
  166789. (*block)[pos] = (JCOEF) s;
  166790. /* Remember its position in case we have to suspend */
  166791. newnz_pos[num_newnz++] = pos;
  166792. }
  166793. }
  166794. }
  166795. if (EOBRUN > 0) {
  166796. /* Scan any remaining coefficient positions after the end-of-band
  166797. * (the last newly nonzero coefficient, if any). Append a correction
  166798. * bit to each already-nonzero coefficient. A correction bit is 1
  166799. * if the absolute value of the coefficient must be increased.
  166800. */
  166801. for (; k <= Se; k++) {
  166802. thiscoef = *block + jpeg_natural_order[k];
  166803. if (*thiscoef != 0) {
  166804. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  166805. if (GET_BITS(1)) {
  166806. if ((*thiscoef & p1) == 0) { /* do nothing if already changed it */
  166807. if (*thiscoef >= 0)
  166808. *thiscoef += p1;
  166809. else
  166810. *thiscoef += m1;
  166811. }
  166812. }
  166813. }
  166814. }
  166815. /* Count one block completed in EOB run */
  166816. EOBRUN--;
  166817. }
  166818. /* Completed MCU, so update state */
  166819. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  166820. entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */
  166821. }
  166822. /* Account for restart interval (no-op if not using restarts) */
  166823. entropy->restarts_to_go--;
  166824. return TRUE;
  166825. undoit:
  166826. /* Re-zero any output coefficients that we made newly nonzero */
  166827. while (num_newnz > 0)
  166828. (*block)[newnz_pos[--num_newnz]] = 0;
  166829. return FALSE;
  166830. }
  166831. /*
  166832. * Module initialization routine for progressive Huffman entropy decoding.
  166833. */
  166834. GLOBAL(void)
  166835. jinit_phuff_decoder (j_decompress_ptr cinfo)
  166836. {
  166837. phuff_entropy_ptr2 entropy;
  166838. int *coef_bit_ptr;
  166839. int ci, i;
  166840. entropy = (phuff_entropy_ptr2)
  166841. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166842. SIZEOF(phuff_entropy_decoder));
  166843. cinfo->entropy = (struct jpeg_entropy_decoder *) entropy;
  166844. entropy->pub.start_pass = start_pass_phuff_decoder;
  166845. /* Mark derived tables unallocated */
  166846. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  166847. entropy->derived_tbls[i] = NULL;
  166848. }
  166849. /* Create progression status table */
  166850. cinfo->coef_bits = (int (*)[DCTSIZE2])
  166851. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166852. cinfo->num_components*DCTSIZE2*SIZEOF(int));
  166853. coef_bit_ptr = & cinfo->coef_bits[0][0];
  166854. for (ci = 0; ci < cinfo->num_components; ci++)
  166855. for (i = 0; i < DCTSIZE2; i++)
  166856. *coef_bit_ptr++ = -1;
  166857. }
  166858. #endif /* D_PROGRESSIVE_SUPPORTED */
  166859. /********* End of inlined file: jdphuff.c *********/
  166860. /********* Start of inlined file: jdpostct.c *********/
  166861. #define JPEG_INTERNALS
  166862. /* Private buffer controller object */
  166863. typedef struct {
  166864. struct jpeg_d_post_controller pub; /* public fields */
  166865. /* Color quantization source buffer: this holds output data from
  166866. * the upsample/color conversion step to be passed to the quantizer.
  166867. * For two-pass color quantization, we need a full-image buffer;
  166868. * for one-pass operation, a strip buffer is sufficient.
  166869. */
  166870. jvirt_sarray_ptr whole_image; /* virtual array, or NULL if one-pass */
  166871. JSAMPARRAY buffer; /* strip buffer, or current strip of virtual */
  166872. JDIMENSION strip_height; /* buffer size in rows */
  166873. /* for two-pass mode only: */
  166874. JDIMENSION starting_row; /* row # of first row in current strip */
  166875. JDIMENSION next_row; /* index of next row to fill/empty in strip */
  166876. } my_post_controller;
  166877. typedef my_post_controller * my_post_ptr;
  166878. /* Forward declarations */
  166879. METHODDEF(void) post_process_1pass
  166880. JPP((j_decompress_ptr cinfo,
  166881. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  166882. JDIMENSION in_row_groups_avail,
  166883. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  166884. JDIMENSION out_rows_avail));
  166885. #ifdef QUANT_2PASS_SUPPORTED
  166886. METHODDEF(void) post_process_prepass
  166887. JPP((j_decompress_ptr cinfo,
  166888. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  166889. JDIMENSION in_row_groups_avail,
  166890. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  166891. JDIMENSION out_rows_avail));
  166892. METHODDEF(void) post_process_2pass
  166893. JPP((j_decompress_ptr cinfo,
  166894. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  166895. JDIMENSION in_row_groups_avail,
  166896. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  166897. JDIMENSION out_rows_avail));
  166898. #endif
  166899. /*
  166900. * Initialize for a processing pass.
  166901. */
  166902. METHODDEF(void)
  166903. start_pass_dpost (j_decompress_ptr cinfo, J_BUF_MODE pass_mode)
  166904. {
  166905. my_post_ptr post = (my_post_ptr) cinfo->post;
  166906. switch (pass_mode) {
  166907. case JBUF_PASS_THRU:
  166908. if (cinfo->quantize_colors) {
  166909. /* Single-pass processing with color quantization. */
  166910. post->pub.post_process_data = post_process_1pass;
  166911. /* We could be doing buffered-image output before starting a 2-pass
  166912. * color quantization; in that case, jinit_d_post_controller did not
  166913. * allocate a strip buffer. Use the virtual-array buffer as workspace.
  166914. */
  166915. if (post->buffer == NULL) {
  166916. post->buffer = (*cinfo->mem->access_virt_sarray)
  166917. ((j_common_ptr) cinfo, post->whole_image,
  166918. (JDIMENSION) 0, post->strip_height, TRUE);
  166919. }
  166920. } else {
  166921. /* For single-pass processing without color quantization,
  166922. * I have no work to do; just call the upsampler directly.
  166923. */
  166924. post->pub.post_process_data = cinfo->upsample->upsample;
  166925. }
  166926. break;
  166927. #ifdef QUANT_2PASS_SUPPORTED
  166928. case JBUF_SAVE_AND_PASS:
  166929. /* First pass of 2-pass quantization */
  166930. if (post->whole_image == NULL)
  166931. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  166932. post->pub.post_process_data = post_process_prepass;
  166933. break;
  166934. case JBUF_CRANK_DEST:
  166935. /* Second pass of 2-pass quantization */
  166936. if (post->whole_image == NULL)
  166937. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  166938. post->pub.post_process_data = post_process_2pass;
  166939. break;
  166940. #endif /* QUANT_2PASS_SUPPORTED */
  166941. default:
  166942. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  166943. break;
  166944. }
  166945. post->starting_row = post->next_row = 0;
  166946. }
  166947. /*
  166948. * Process some data in the one-pass (strip buffer) case.
  166949. * This is used for color precision reduction as well as one-pass quantization.
  166950. */
  166951. METHODDEF(void)
  166952. post_process_1pass (j_decompress_ptr cinfo,
  166953. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  166954. JDIMENSION in_row_groups_avail,
  166955. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  166956. JDIMENSION out_rows_avail)
  166957. {
  166958. my_post_ptr post = (my_post_ptr) cinfo->post;
  166959. JDIMENSION num_rows, max_rows;
  166960. /* Fill the buffer, but not more than what we can dump out in one go. */
  166961. /* Note we rely on the upsampler to detect bottom of image. */
  166962. max_rows = out_rows_avail - *out_row_ctr;
  166963. if (max_rows > post->strip_height)
  166964. max_rows = post->strip_height;
  166965. num_rows = 0;
  166966. (*cinfo->upsample->upsample) (cinfo,
  166967. input_buf, in_row_group_ctr, in_row_groups_avail,
  166968. post->buffer, &num_rows, max_rows);
  166969. /* Quantize and emit data. */
  166970. (*cinfo->cquantize->color_quantize) (cinfo,
  166971. post->buffer, output_buf + *out_row_ctr, (int) num_rows);
  166972. *out_row_ctr += num_rows;
  166973. }
  166974. #ifdef QUANT_2PASS_SUPPORTED
  166975. /*
  166976. * Process some data in the first pass of 2-pass quantization.
  166977. */
  166978. METHODDEF(void)
  166979. post_process_prepass (j_decompress_ptr cinfo,
  166980. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  166981. JDIMENSION in_row_groups_avail,
  166982. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  166983. JDIMENSION out_rows_avail)
  166984. {
  166985. my_post_ptr post = (my_post_ptr) cinfo->post;
  166986. JDIMENSION old_next_row, num_rows;
  166987. /* Reposition virtual buffer if at start of strip. */
  166988. if (post->next_row == 0) {
  166989. post->buffer = (*cinfo->mem->access_virt_sarray)
  166990. ((j_common_ptr) cinfo, post->whole_image,
  166991. post->starting_row, post->strip_height, TRUE);
  166992. }
  166993. /* Upsample some data (up to a strip height's worth). */
  166994. old_next_row = post->next_row;
  166995. (*cinfo->upsample->upsample) (cinfo,
  166996. input_buf, in_row_group_ctr, in_row_groups_avail,
  166997. post->buffer, &post->next_row, post->strip_height);
  166998. /* Allow quantizer to scan new data. No data is emitted, */
  166999. /* but we advance out_row_ctr so outer loop can tell when we're done. */
  167000. if (post->next_row > old_next_row) {
  167001. num_rows = post->next_row - old_next_row;
  167002. (*cinfo->cquantize->color_quantize) (cinfo, post->buffer + old_next_row,
  167003. (JSAMPARRAY) NULL, (int) num_rows);
  167004. *out_row_ctr += num_rows;
  167005. }
  167006. /* Advance if we filled the strip. */
  167007. if (post->next_row >= post->strip_height) {
  167008. post->starting_row += post->strip_height;
  167009. post->next_row = 0;
  167010. }
  167011. }
  167012. /*
  167013. * Process some data in the second pass of 2-pass quantization.
  167014. */
  167015. METHODDEF(void)
  167016. post_process_2pass (j_decompress_ptr cinfo,
  167017. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  167018. JDIMENSION in_row_groups_avail,
  167019. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  167020. JDIMENSION out_rows_avail)
  167021. {
  167022. my_post_ptr post = (my_post_ptr) cinfo->post;
  167023. JDIMENSION num_rows, max_rows;
  167024. /* Reposition virtual buffer if at start of strip. */
  167025. if (post->next_row == 0) {
  167026. post->buffer = (*cinfo->mem->access_virt_sarray)
  167027. ((j_common_ptr) cinfo, post->whole_image,
  167028. post->starting_row, post->strip_height, FALSE);
  167029. }
  167030. /* Determine number of rows to emit. */
  167031. num_rows = post->strip_height - post->next_row; /* available in strip */
  167032. max_rows = out_rows_avail - *out_row_ctr; /* available in output area */
  167033. if (num_rows > max_rows)
  167034. num_rows = max_rows;
  167035. /* We have to check bottom of image here, can't depend on upsampler. */
  167036. max_rows = cinfo->output_height - post->starting_row;
  167037. if (num_rows > max_rows)
  167038. num_rows = max_rows;
  167039. /* Quantize and emit data. */
  167040. (*cinfo->cquantize->color_quantize) (cinfo,
  167041. post->buffer + post->next_row, output_buf + *out_row_ctr,
  167042. (int) num_rows);
  167043. *out_row_ctr += num_rows;
  167044. /* Advance if we filled the strip. */
  167045. post->next_row += num_rows;
  167046. if (post->next_row >= post->strip_height) {
  167047. post->starting_row += post->strip_height;
  167048. post->next_row = 0;
  167049. }
  167050. }
  167051. #endif /* QUANT_2PASS_SUPPORTED */
  167052. /*
  167053. * Initialize postprocessing controller.
  167054. */
  167055. GLOBAL(void)
  167056. jinit_d_post_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  167057. {
  167058. my_post_ptr post;
  167059. post = (my_post_ptr)
  167060. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167061. SIZEOF(my_post_controller));
  167062. cinfo->post = (struct jpeg_d_post_controller *) post;
  167063. post->pub.start_pass = start_pass_dpost;
  167064. post->whole_image = NULL; /* flag for no virtual arrays */
  167065. post->buffer = NULL; /* flag for no strip buffer */
  167066. /* Create the quantization buffer, if needed */
  167067. if (cinfo->quantize_colors) {
  167068. /* The buffer strip height is max_v_samp_factor, which is typically
  167069. * an efficient number of rows for upsampling to return.
  167070. * (In the presence of output rescaling, we might want to be smarter?)
  167071. */
  167072. post->strip_height = (JDIMENSION) cinfo->max_v_samp_factor;
  167073. if (need_full_buffer) {
  167074. /* Two-pass color quantization: need full-image storage. */
  167075. /* We round up the number of rows to a multiple of the strip height. */
  167076. #ifdef QUANT_2PASS_SUPPORTED
  167077. post->whole_image = (*cinfo->mem->request_virt_sarray)
  167078. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  167079. cinfo->output_width * cinfo->out_color_components,
  167080. (JDIMENSION) jround_up((long) cinfo->output_height,
  167081. (long) post->strip_height),
  167082. post->strip_height);
  167083. #else
  167084. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  167085. #endif /* QUANT_2PASS_SUPPORTED */
  167086. } else {
  167087. /* One-pass color quantization: just make a strip buffer. */
  167088. post->buffer = (*cinfo->mem->alloc_sarray)
  167089. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167090. cinfo->output_width * cinfo->out_color_components,
  167091. post->strip_height);
  167092. }
  167093. }
  167094. }
  167095. /********* End of inlined file: jdpostct.c *********/
  167096. #undef FIX
  167097. /********* Start of inlined file: jdsample.c *********/
  167098. #define JPEG_INTERNALS
  167099. /* Pointer to routine to upsample a single component */
  167100. typedef JMETHOD(void, upsample1_ptr,
  167101. (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  167102. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr));
  167103. /* Private subobject */
  167104. typedef struct {
  167105. struct jpeg_upsampler pub; /* public fields */
  167106. /* Color conversion buffer. When using separate upsampling and color
  167107. * conversion steps, this buffer holds one upsampled row group until it
  167108. * has been color converted and output.
  167109. * Note: we do not allocate any storage for component(s) which are full-size,
  167110. * ie do not need rescaling. The corresponding entry of color_buf[] is
  167111. * simply set to point to the input data array, thereby avoiding copying.
  167112. */
  167113. JSAMPARRAY color_buf[MAX_COMPONENTS];
  167114. /* Per-component upsampling method pointers */
  167115. upsample1_ptr methods[MAX_COMPONENTS];
  167116. int next_row_out; /* counts rows emitted from color_buf */
  167117. JDIMENSION rows_to_go; /* counts rows remaining in image */
  167118. /* Height of an input row group for each component. */
  167119. int rowgroup_height[MAX_COMPONENTS];
  167120. /* These arrays save pixel expansion factors so that int_expand need not
  167121. * recompute them each time. They are unused for other upsampling methods.
  167122. */
  167123. UINT8 h_expand[MAX_COMPONENTS];
  167124. UINT8 v_expand[MAX_COMPONENTS];
  167125. } my_upsampler2;
  167126. typedef my_upsampler2 * my_upsample_ptr2;
  167127. /*
  167128. * Initialize for an upsampling pass.
  167129. */
  167130. METHODDEF(void)
  167131. start_pass_upsample (j_decompress_ptr cinfo)
  167132. {
  167133. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  167134. /* Mark the conversion buffer empty */
  167135. upsample->next_row_out = cinfo->max_v_samp_factor;
  167136. /* Initialize total-height counter for detecting bottom of image */
  167137. upsample->rows_to_go = cinfo->output_height;
  167138. }
  167139. /*
  167140. * Control routine to do upsampling (and color conversion).
  167141. *
  167142. * In this version we upsample each component independently.
  167143. * We upsample one row group into the conversion buffer, then apply
  167144. * color conversion a row at a time.
  167145. */
  167146. METHODDEF(void)
  167147. sep_upsample (j_decompress_ptr cinfo,
  167148. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  167149. JDIMENSION in_row_groups_avail,
  167150. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  167151. JDIMENSION out_rows_avail)
  167152. {
  167153. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  167154. int ci;
  167155. jpeg_component_info * compptr;
  167156. JDIMENSION num_rows;
  167157. /* Fill the conversion buffer, if it's empty */
  167158. if (upsample->next_row_out >= cinfo->max_v_samp_factor) {
  167159. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  167160. ci++, compptr++) {
  167161. /* Invoke per-component upsample method. Notice we pass a POINTER
  167162. * to color_buf[ci], so that fullsize_upsample can change it.
  167163. */
  167164. (*upsample->methods[ci]) (cinfo, compptr,
  167165. input_buf[ci] + (*in_row_group_ctr * upsample->rowgroup_height[ci]),
  167166. upsample->color_buf + ci);
  167167. }
  167168. upsample->next_row_out = 0;
  167169. }
  167170. /* Color-convert and emit rows */
  167171. /* How many we have in the buffer: */
  167172. num_rows = (JDIMENSION) (cinfo->max_v_samp_factor - upsample->next_row_out);
  167173. /* Not more than the distance to the end of the image. Need this test
  167174. * in case the image height is not a multiple of max_v_samp_factor:
  167175. */
  167176. if (num_rows > upsample->rows_to_go)
  167177. num_rows = upsample->rows_to_go;
  167178. /* And not more than what the client can accept: */
  167179. out_rows_avail -= *out_row_ctr;
  167180. if (num_rows > out_rows_avail)
  167181. num_rows = out_rows_avail;
  167182. (*cinfo->cconvert->color_convert) (cinfo, upsample->color_buf,
  167183. (JDIMENSION) upsample->next_row_out,
  167184. output_buf + *out_row_ctr,
  167185. (int) num_rows);
  167186. /* Adjust counts */
  167187. *out_row_ctr += num_rows;
  167188. upsample->rows_to_go -= num_rows;
  167189. upsample->next_row_out += num_rows;
  167190. /* When the buffer is emptied, declare this input row group consumed */
  167191. if (upsample->next_row_out >= cinfo->max_v_samp_factor)
  167192. (*in_row_group_ctr)++;
  167193. }
  167194. /*
  167195. * These are the routines invoked by sep_upsample to upsample pixel values
  167196. * of a single component. One row group is processed per call.
  167197. */
  167198. /*
  167199. * For full-size components, we just make color_buf[ci] point at the
  167200. * input buffer, and thus avoid copying any data. Note that this is
  167201. * safe only because sep_upsample doesn't declare the input row group
  167202. * "consumed" until we are done color converting and emitting it.
  167203. */
  167204. METHODDEF(void)
  167205. fullsize_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  167206. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  167207. {
  167208. *output_data_ptr = input_data;
  167209. }
  167210. /*
  167211. * This is a no-op version used for "uninteresting" components.
  167212. * These components will not be referenced by color conversion.
  167213. */
  167214. METHODDEF(void)
  167215. noop_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  167216. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  167217. {
  167218. *output_data_ptr = NULL; /* safety check */
  167219. }
  167220. /*
  167221. * This version handles any integral sampling ratios.
  167222. * This is not used for typical JPEG files, so it need not be fast.
  167223. * Nor, for that matter, is it particularly accurate: the algorithm is
  167224. * simple replication of the input pixel onto the corresponding output
  167225. * pixels. The hi-falutin sampling literature refers to this as a
  167226. * "box filter". A box filter tends to introduce visible artifacts,
  167227. * so if you are actually going to use 3:1 or 4:1 sampling ratios
  167228. * you would be well advised to improve this code.
  167229. */
  167230. METHODDEF(void)
  167231. int_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  167232. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  167233. {
  167234. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  167235. JSAMPARRAY output_data = *output_data_ptr;
  167236. register JSAMPROW inptr, outptr;
  167237. register JSAMPLE invalue;
  167238. register int h;
  167239. JSAMPROW outend;
  167240. int h_expand, v_expand;
  167241. int inrow, outrow;
  167242. h_expand = upsample->h_expand[compptr->component_index];
  167243. v_expand = upsample->v_expand[compptr->component_index];
  167244. inrow = outrow = 0;
  167245. while (outrow < cinfo->max_v_samp_factor) {
  167246. /* Generate one output row with proper horizontal expansion */
  167247. inptr = input_data[inrow];
  167248. outptr = output_data[outrow];
  167249. outend = outptr + cinfo->output_width;
  167250. while (outptr < outend) {
  167251. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  167252. for (h = h_expand; h > 0; h--) {
  167253. *outptr++ = invalue;
  167254. }
  167255. }
  167256. /* Generate any additional output rows by duplicating the first one */
  167257. if (v_expand > 1) {
  167258. jcopy_sample_rows(output_data, outrow, output_data, outrow+1,
  167259. v_expand-1, cinfo->output_width);
  167260. }
  167261. inrow++;
  167262. outrow += v_expand;
  167263. }
  167264. }
  167265. /*
  167266. * Fast processing for the common case of 2:1 horizontal and 1:1 vertical.
  167267. * It's still a box filter.
  167268. */
  167269. METHODDEF(void)
  167270. h2v1_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  167271. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  167272. {
  167273. JSAMPARRAY output_data = *output_data_ptr;
  167274. register JSAMPROW inptr, outptr;
  167275. register JSAMPLE invalue;
  167276. JSAMPROW outend;
  167277. int inrow;
  167278. for (inrow = 0; inrow < cinfo->max_v_samp_factor; inrow++) {
  167279. inptr = input_data[inrow];
  167280. outptr = output_data[inrow];
  167281. outend = outptr + cinfo->output_width;
  167282. while (outptr < outend) {
  167283. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  167284. *outptr++ = invalue;
  167285. *outptr++ = invalue;
  167286. }
  167287. }
  167288. }
  167289. /*
  167290. * Fast processing for the common case of 2:1 horizontal and 2:1 vertical.
  167291. * It's still a box filter.
  167292. */
  167293. METHODDEF(void)
  167294. h2v2_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  167295. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  167296. {
  167297. JSAMPARRAY output_data = *output_data_ptr;
  167298. register JSAMPROW inptr, outptr;
  167299. register JSAMPLE invalue;
  167300. JSAMPROW outend;
  167301. int inrow, outrow;
  167302. inrow = outrow = 0;
  167303. while (outrow < cinfo->max_v_samp_factor) {
  167304. inptr = input_data[inrow];
  167305. outptr = output_data[outrow];
  167306. outend = outptr + cinfo->output_width;
  167307. while (outptr < outend) {
  167308. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  167309. *outptr++ = invalue;
  167310. *outptr++ = invalue;
  167311. }
  167312. jcopy_sample_rows(output_data, outrow, output_data, outrow+1,
  167313. 1, cinfo->output_width);
  167314. inrow++;
  167315. outrow += 2;
  167316. }
  167317. }
  167318. /*
  167319. * Fancy processing for the common case of 2:1 horizontal and 1:1 vertical.
  167320. *
  167321. * The upsampling algorithm is linear interpolation between pixel centers,
  167322. * also known as a "triangle filter". This is a good compromise between
  167323. * speed and visual quality. The centers of the output pixels are 1/4 and 3/4
  167324. * of the way between input pixel centers.
  167325. *
  167326. * A note about the "bias" calculations: when rounding fractional values to
  167327. * integer, we do not want to always round 0.5 up to the next integer.
  167328. * If we did that, we'd introduce a noticeable bias towards larger values.
  167329. * Instead, this code is arranged so that 0.5 will be rounded up or down at
  167330. * alternate pixel locations (a simple ordered dither pattern).
  167331. */
  167332. METHODDEF(void)
  167333. h2v1_fancy_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  167334. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  167335. {
  167336. JSAMPARRAY output_data = *output_data_ptr;
  167337. register JSAMPROW inptr, outptr;
  167338. register int invalue;
  167339. register JDIMENSION colctr;
  167340. int inrow;
  167341. for (inrow = 0; inrow < cinfo->max_v_samp_factor; inrow++) {
  167342. inptr = input_data[inrow];
  167343. outptr = output_data[inrow];
  167344. /* Special case for first column */
  167345. invalue = GETJSAMPLE(*inptr++);
  167346. *outptr++ = (JSAMPLE) invalue;
  167347. *outptr++ = (JSAMPLE) ((invalue * 3 + GETJSAMPLE(*inptr) + 2) >> 2);
  167348. for (colctr = compptr->downsampled_width - 2; colctr > 0; colctr--) {
  167349. /* General case: 3/4 * nearer pixel + 1/4 * further pixel */
  167350. invalue = GETJSAMPLE(*inptr++) * 3;
  167351. *outptr++ = (JSAMPLE) ((invalue + GETJSAMPLE(inptr[-2]) + 1) >> 2);
  167352. *outptr++ = (JSAMPLE) ((invalue + GETJSAMPLE(*inptr) + 2) >> 2);
  167353. }
  167354. /* Special case for last column */
  167355. invalue = GETJSAMPLE(*inptr);
  167356. *outptr++ = (JSAMPLE) ((invalue * 3 + GETJSAMPLE(inptr[-1]) + 1) >> 2);
  167357. *outptr++ = (JSAMPLE) invalue;
  167358. }
  167359. }
  167360. /*
  167361. * Fancy processing for the common case of 2:1 horizontal and 2:1 vertical.
  167362. * Again a triangle filter; see comments for h2v1 case, above.
  167363. *
  167364. * It is OK for us to reference the adjacent input rows because we demanded
  167365. * context from the main buffer controller (see initialization code).
  167366. */
  167367. METHODDEF(void)
  167368. h2v2_fancy_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  167369. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  167370. {
  167371. JSAMPARRAY output_data = *output_data_ptr;
  167372. register JSAMPROW inptr0, inptr1, outptr;
  167373. #if BITS_IN_JSAMPLE == 8
  167374. register int thiscolsum, lastcolsum, nextcolsum;
  167375. #else
  167376. register INT32 thiscolsum, lastcolsum, nextcolsum;
  167377. #endif
  167378. register JDIMENSION colctr;
  167379. int inrow, outrow, v;
  167380. inrow = outrow = 0;
  167381. while (outrow < cinfo->max_v_samp_factor) {
  167382. for (v = 0; v < 2; v++) {
  167383. /* inptr0 points to nearest input row, inptr1 points to next nearest */
  167384. inptr0 = input_data[inrow];
  167385. if (v == 0) /* next nearest is row above */
  167386. inptr1 = input_data[inrow-1];
  167387. else /* next nearest is row below */
  167388. inptr1 = input_data[inrow+1];
  167389. outptr = output_data[outrow++];
  167390. /* Special case for first column */
  167391. thiscolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  167392. nextcolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  167393. *outptr++ = (JSAMPLE) ((thiscolsum * 4 + 8) >> 4);
  167394. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + nextcolsum + 7) >> 4);
  167395. lastcolsum = thiscolsum; thiscolsum = nextcolsum;
  167396. for (colctr = compptr->downsampled_width - 2; colctr > 0; colctr--) {
  167397. /* General case: 3/4 * nearer pixel + 1/4 * further pixel in each */
  167398. /* dimension, thus 9/16, 3/16, 3/16, 1/16 overall */
  167399. nextcolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  167400. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + lastcolsum + 8) >> 4);
  167401. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + nextcolsum + 7) >> 4);
  167402. lastcolsum = thiscolsum; thiscolsum = nextcolsum;
  167403. }
  167404. /* Special case for last column */
  167405. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + lastcolsum + 8) >> 4);
  167406. *outptr++ = (JSAMPLE) ((thiscolsum * 4 + 7) >> 4);
  167407. }
  167408. inrow++;
  167409. }
  167410. }
  167411. /*
  167412. * Module initialization routine for upsampling.
  167413. */
  167414. GLOBAL(void)
  167415. jinit_upsampler (j_decompress_ptr cinfo)
  167416. {
  167417. my_upsample_ptr2 upsample;
  167418. int ci;
  167419. jpeg_component_info * compptr;
  167420. boolean need_buffer, do_fancy;
  167421. int h_in_group, v_in_group, h_out_group, v_out_group;
  167422. upsample = (my_upsample_ptr2)
  167423. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167424. SIZEOF(my_upsampler2));
  167425. cinfo->upsample = (struct jpeg_upsampler *) upsample;
  167426. upsample->pub.start_pass = start_pass_upsample;
  167427. upsample->pub.upsample = sep_upsample;
  167428. upsample->pub.need_context_rows = FALSE; /* until we find out differently */
  167429. if (cinfo->CCIR601_sampling) /* this isn't supported */
  167430. ERREXIT(cinfo, JERR_CCIR601_NOTIMPL);
  167431. /* jdmainct.c doesn't support context rows when min_DCT_scaled_size = 1,
  167432. * so don't ask for it.
  167433. */
  167434. do_fancy = cinfo->do_fancy_upsampling && cinfo->min_DCT_scaled_size > 1;
  167435. /* Verify we can handle the sampling factors, select per-component methods,
  167436. * and create storage as needed.
  167437. */
  167438. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  167439. ci++, compptr++) {
  167440. /* Compute size of an "input group" after IDCT scaling. This many samples
  167441. * are to be converted to max_h_samp_factor * max_v_samp_factor pixels.
  167442. */
  167443. h_in_group = (compptr->h_samp_factor * compptr->DCT_scaled_size) /
  167444. cinfo->min_DCT_scaled_size;
  167445. v_in_group = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  167446. cinfo->min_DCT_scaled_size;
  167447. h_out_group = cinfo->max_h_samp_factor;
  167448. v_out_group = cinfo->max_v_samp_factor;
  167449. upsample->rowgroup_height[ci] = v_in_group; /* save for use later */
  167450. need_buffer = TRUE;
  167451. if (! compptr->component_needed) {
  167452. /* Don't bother to upsample an uninteresting component. */
  167453. upsample->methods[ci] = noop_upsample;
  167454. need_buffer = FALSE;
  167455. } else if (h_in_group == h_out_group && v_in_group == v_out_group) {
  167456. /* Fullsize components can be processed without any work. */
  167457. upsample->methods[ci] = fullsize_upsample;
  167458. need_buffer = FALSE;
  167459. } else if (h_in_group * 2 == h_out_group &&
  167460. v_in_group == v_out_group) {
  167461. /* Special cases for 2h1v upsampling */
  167462. if (do_fancy && compptr->downsampled_width > 2)
  167463. upsample->methods[ci] = h2v1_fancy_upsample;
  167464. else
  167465. upsample->methods[ci] = h2v1_upsample;
  167466. } else if (h_in_group * 2 == h_out_group &&
  167467. v_in_group * 2 == v_out_group) {
  167468. /* Special cases for 2h2v upsampling */
  167469. if (do_fancy && compptr->downsampled_width > 2) {
  167470. upsample->methods[ci] = h2v2_fancy_upsample;
  167471. upsample->pub.need_context_rows = TRUE;
  167472. } else
  167473. upsample->methods[ci] = h2v2_upsample;
  167474. } else if ((h_out_group % h_in_group) == 0 &&
  167475. (v_out_group % v_in_group) == 0) {
  167476. /* Generic integral-factors upsampling method */
  167477. upsample->methods[ci] = int_upsample;
  167478. upsample->h_expand[ci] = (UINT8) (h_out_group / h_in_group);
  167479. upsample->v_expand[ci] = (UINT8) (v_out_group / v_in_group);
  167480. } else
  167481. ERREXIT(cinfo, JERR_FRACT_SAMPLE_NOTIMPL);
  167482. if (need_buffer) {
  167483. upsample->color_buf[ci] = (*cinfo->mem->alloc_sarray)
  167484. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167485. (JDIMENSION) jround_up((long) cinfo->output_width,
  167486. (long) cinfo->max_h_samp_factor),
  167487. (JDIMENSION) cinfo->max_v_samp_factor);
  167488. }
  167489. }
  167490. }
  167491. /********* End of inlined file: jdsample.c *********/
  167492. /********* Start of inlined file: jdtrans.c *********/
  167493. #define JPEG_INTERNALS
  167494. /* Forward declarations */
  167495. LOCAL(void) transdecode_master_selection JPP((j_decompress_ptr cinfo));
  167496. /*
  167497. * Read the coefficient arrays from a JPEG file.
  167498. * jpeg_read_header must be completed before calling this.
  167499. *
  167500. * The entire image is read into a set of virtual coefficient-block arrays,
  167501. * one per component. The return value is a pointer to the array of
  167502. * virtual-array descriptors. These can be manipulated directly via the
  167503. * JPEG memory manager, or handed off to jpeg_write_coefficients().
  167504. * To release the memory occupied by the virtual arrays, call
  167505. * jpeg_finish_decompress() when done with the data.
  167506. *
  167507. * An alternative usage is to simply obtain access to the coefficient arrays
  167508. * during a buffered-image-mode decompression operation. This is allowed
  167509. * after any jpeg_finish_output() call. The arrays can be accessed until
  167510. * jpeg_finish_decompress() is called. (Note that any call to the library
  167511. * may reposition the arrays, so don't rely on access_virt_barray() results
  167512. * to stay valid across library calls.)
  167513. *
  167514. * Returns NULL if suspended. This case need be checked only if
  167515. * a suspending data source is used.
  167516. */
  167517. GLOBAL(jvirt_barray_ptr *)
  167518. jpeg_read_coefficients (j_decompress_ptr cinfo)
  167519. {
  167520. if (cinfo->global_state == DSTATE_READY) {
  167521. /* First call: initialize active modules */
  167522. transdecode_master_selection(cinfo);
  167523. cinfo->global_state = DSTATE_RDCOEFS;
  167524. }
  167525. if (cinfo->global_state == DSTATE_RDCOEFS) {
  167526. /* Absorb whole file into the coef buffer */
  167527. for (;;) {
  167528. int retcode;
  167529. /* Call progress monitor hook if present */
  167530. if (cinfo->progress != NULL)
  167531. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  167532. /* Absorb some more input */
  167533. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  167534. if (retcode == JPEG_SUSPENDED)
  167535. return NULL;
  167536. if (retcode == JPEG_REACHED_EOI)
  167537. break;
  167538. /* Advance progress counter if appropriate */
  167539. if (cinfo->progress != NULL &&
  167540. (retcode == JPEG_ROW_COMPLETED || retcode == JPEG_REACHED_SOS)) {
  167541. if (++cinfo->progress->pass_counter >= cinfo->progress->pass_limit) {
  167542. /* startup underestimated number of scans; ratchet up one scan */
  167543. cinfo->progress->pass_limit += (long) cinfo->total_iMCU_rows;
  167544. }
  167545. }
  167546. }
  167547. /* Set state so that jpeg_finish_decompress does the right thing */
  167548. cinfo->global_state = DSTATE_STOPPING;
  167549. }
  167550. /* At this point we should be in state DSTATE_STOPPING if being used
  167551. * standalone, or in state DSTATE_BUFIMAGE if being invoked to get access
  167552. * to the coefficients during a full buffered-image-mode decompression.
  167553. */
  167554. if ((cinfo->global_state == DSTATE_STOPPING ||
  167555. cinfo->global_state == DSTATE_BUFIMAGE) && cinfo->buffered_image) {
  167556. return cinfo->coef->coef_arrays;
  167557. }
  167558. /* Oops, improper usage */
  167559. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167560. return NULL; /* keep compiler happy */
  167561. }
  167562. /*
  167563. * Master selection of decompression modules for transcoding.
  167564. * This substitutes for jdmaster.c's initialization of the full decompressor.
  167565. */
  167566. LOCAL(void)
  167567. transdecode_master_selection (j_decompress_ptr cinfo)
  167568. {
  167569. /* This is effectively a buffered-image operation. */
  167570. cinfo->buffered_image = TRUE;
  167571. /* Entropy decoding: either Huffman or arithmetic coding. */
  167572. if (cinfo->arith_code) {
  167573. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  167574. } else {
  167575. if (cinfo->progressive_mode) {
  167576. #ifdef D_PROGRESSIVE_SUPPORTED
  167577. jinit_phuff_decoder(cinfo);
  167578. #else
  167579. ERREXIT(cinfo, JERR_NOT_COMPILED);
  167580. #endif
  167581. } else
  167582. jinit_huff_decoder(cinfo);
  167583. }
  167584. /* Always get a full-image coefficient buffer. */
  167585. jinit_d_coef_controller(cinfo, TRUE);
  167586. /* We can now tell the memory manager to allocate virtual arrays. */
  167587. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  167588. /* Initialize input side of decompressor to consume first scan. */
  167589. (*cinfo->inputctl->start_input_pass) (cinfo);
  167590. /* Initialize progress monitoring. */
  167591. if (cinfo->progress != NULL) {
  167592. int nscans;
  167593. /* Estimate number of scans to set pass_limit. */
  167594. if (cinfo->progressive_mode) {
  167595. /* Arbitrarily estimate 2 interleaved DC scans + 3 AC scans/component. */
  167596. nscans = 2 + 3 * cinfo->num_components;
  167597. } else if (cinfo->inputctl->has_multiple_scans) {
  167598. /* For a nonprogressive multiscan file, estimate 1 scan per component. */
  167599. nscans = cinfo->num_components;
  167600. } else {
  167601. nscans = 1;
  167602. }
  167603. cinfo->progress->pass_counter = 0L;
  167604. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows * nscans;
  167605. cinfo->progress->completed_passes = 0;
  167606. cinfo->progress->total_passes = 1;
  167607. }
  167608. }
  167609. /********* End of inlined file: jdtrans.c *********/
  167610. /********* Start of inlined file: jfdctflt.c *********/
  167611. #define JPEG_INTERNALS
  167612. #ifdef DCT_FLOAT_SUPPORTED
  167613. /*
  167614. * This module is specialized to the case DCTSIZE = 8.
  167615. */
  167616. #if DCTSIZE != 8
  167617. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  167618. #endif
  167619. /*
  167620. * Perform the forward DCT on one block of samples.
  167621. */
  167622. GLOBAL(void)
  167623. jpeg_fdct_float (FAST_FLOAT * data)
  167624. {
  167625. FAST_FLOAT tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  167626. FAST_FLOAT tmp10, tmp11, tmp12, tmp13;
  167627. FAST_FLOAT z1, z2, z3, z4, z5, z11, z13;
  167628. FAST_FLOAT *dataptr;
  167629. int ctr;
  167630. /* Pass 1: process rows. */
  167631. dataptr = data;
  167632. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  167633. tmp0 = dataptr[0] + dataptr[7];
  167634. tmp7 = dataptr[0] - dataptr[7];
  167635. tmp1 = dataptr[1] + dataptr[6];
  167636. tmp6 = dataptr[1] - dataptr[6];
  167637. tmp2 = dataptr[2] + dataptr[5];
  167638. tmp5 = dataptr[2] - dataptr[5];
  167639. tmp3 = dataptr[3] + dataptr[4];
  167640. tmp4 = dataptr[3] - dataptr[4];
  167641. /* Even part */
  167642. tmp10 = tmp0 + tmp3; /* phase 2 */
  167643. tmp13 = tmp0 - tmp3;
  167644. tmp11 = tmp1 + tmp2;
  167645. tmp12 = tmp1 - tmp2;
  167646. dataptr[0] = tmp10 + tmp11; /* phase 3 */
  167647. dataptr[4] = tmp10 - tmp11;
  167648. z1 = (tmp12 + tmp13) * ((FAST_FLOAT) 0.707106781); /* c4 */
  167649. dataptr[2] = tmp13 + z1; /* phase 5 */
  167650. dataptr[6] = tmp13 - z1;
  167651. /* Odd part */
  167652. tmp10 = tmp4 + tmp5; /* phase 2 */
  167653. tmp11 = tmp5 + tmp6;
  167654. tmp12 = tmp6 + tmp7;
  167655. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  167656. z5 = (tmp10 - tmp12) * ((FAST_FLOAT) 0.382683433); /* c6 */
  167657. z2 = ((FAST_FLOAT) 0.541196100) * tmp10 + z5; /* c2-c6 */
  167658. z4 = ((FAST_FLOAT) 1.306562965) * tmp12 + z5; /* c2+c6 */
  167659. z3 = tmp11 * ((FAST_FLOAT) 0.707106781); /* c4 */
  167660. z11 = tmp7 + z3; /* phase 5 */
  167661. z13 = tmp7 - z3;
  167662. dataptr[5] = z13 + z2; /* phase 6 */
  167663. dataptr[3] = z13 - z2;
  167664. dataptr[1] = z11 + z4;
  167665. dataptr[7] = z11 - z4;
  167666. dataptr += DCTSIZE; /* advance pointer to next row */
  167667. }
  167668. /* Pass 2: process columns. */
  167669. dataptr = data;
  167670. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  167671. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  167672. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  167673. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  167674. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  167675. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  167676. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  167677. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  167678. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  167679. /* Even part */
  167680. tmp10 = tmp0 + tmp3; /* phase 2 */
  167681. tmp13 = tmp0 - tmp3;
  167682. tmp11 = tmp1 + tmp2;
  167683. tmp12 = tmp1 - tmp2;
  167684. dataptr[DCTSIZE*0] = tmp10 + tmp11; /* phase 3 */
  167685. dataptr[DCTSIZE*4] = tmp10 - tmp11;
  167686. z1 = (tmp12 + tmp13) * ((FAST_FLOAT) 0.707106781); /* c4 */
  167687. dataptr[DCTSIZE*2] = tmp13 + z1; /* phase 5 */
  167688. dataptr[DCTSIZE*6] = tmp13 - z1;
  167689. /* Odd part */
  167690. tmp10 = tmp4 + tmp5; /* phase 2 */
  167691. tmp11 = tmp5 + tmp6;
  167692. tmp12 = tmp6 + tmp7;
  167693. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  167694. z5 = (tmp10 - tmp12) * ((FAST_FLOAT) 0.382683433); /* c6 */
  167695. z2 = ((FAST_FLOAT) 0.541196100) * tmp10 + z5; /* c2-c6 */
  167696. z4 = ((FAST_FLOAT) 1.306562965) * tmp12 + z5; /* c2+c6 */
  167697. z3 = tmp11 * ((FAST_FLOAT) 0.707106781); /* c4 */
  167698. z11 = tmp7 + z3; /* phase 5 */
  167699. z13 = tmp7 - z3;
  167700. dataptr[DCTSIZE*5] = z13 + z2; /* phase 6 */
  167701. dataptr[DCTSIZE*3] = z13 - z2;
  167702. dataptr[DCTSIZE*1] = z11 + z4;
  167703. dataptr[DCTSIZE*7] = z11 - z4;
  167704. dataptr++; /* advance pointer to next column */
  167705. }
  167706. }
  167707. #endif /* DCT_FLOAT_SUPPORTED */
  167708. /********* End of inlined file: jfdctflt.c *********/
  167709. /********* Start of inlined file: jfdctint.c *********/
  167710. #define JPEG_INTERNALS
  167711. #ifdef DCT_ISLOW_SUPPORTED
  167712. /*
  167713. * This module is specialized to the case DCTSIZE = 8.
  167714. */
  167715. #if DCTSIZE != 8
  167716. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  167717. #endif
  167718. /*
  167719. * The poop on this scaling stuff is as follows:
  167720. *
  167721. * Each 1-D DCT step produces outputs which are a factor of sqrt(N)
  167722. * larger than the true DCT outputs. The final outputs are therefore
  167723. * a factor of N larger than desired; since N=8 this can be cured by
  167724. * a simple right shift at the end of the algorithm. The advantage of
  167725. * this arrangement is that we save two multiplications per 1-D DCT,
  167726. * because the y0 and y4 outputs need not be divided by sqrt(N).
  167727. * In the IJG code, this factor of 8 is removed by the quantization step
  167728. * (in jcdctmgr.c), NOT in this module.
  167729. *
  167730. * We have to do addition and subtraction of the integer inputs, which
  167731. * is no problem, and multiplication by fractional constants, which is
  167732. * a problem to do in integer arithmetic. We multiply all the constants
  167733. * by CONST_SCALE and convert them to integer constants (thus retaining
  167734. * CONST_BITS bits of precision in the constants). After doing a
  167735. * multiplication we have to divide the product by CONST_SCALE, with proper
  167736. * rounding, to produce the correct output. This division can be done
  167737. * cheaply as a right shift of CONST_BITS bits. We postpone shifting
  167738. * as long as possible so that partial sums can be added together with
  167739. * full fractional precision.
  167740. *
  167741. * The outputs of the first pass are scaled up by PASS1_BITS bits so that
  167742. * they are represented to better-than-integral precision. These outputs
  167743. * require BITS_IN_JSAMPLE + PASS1_BITS + 3 bits; this fits in a 16-bit word
  167744. * with the recommended scaling. (For 12-bit sample data, the intermediate
  167745. * array is INT32 anyway.)
  167746. *
  167747. * To avoid overflow of the 32-bit intermediate results in pass 2, we must
  167748. * have BITS_IN_JSAMPLE + CONST_BITS + PASS1_BITS <= 26. Error analysis
  167749. * shows that the values given below are the most effective.
  167750. */
  167751. #if BITS_IN_JSAMPLE == 8
  167752. #define CONST_BITS 13
  167753. #define PASS1_BITS 2
  167754. #else
  167755. #define CONST_BITS 13
  167756. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  167757. #endif
  167758. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  167759. * causing a lot of useless floating-point operations at run time.
  167760. * To get around this we use the following pre-calculated constants.
  167761. * If you change CONST_BITS you may want to add appropriate values.
  167762. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  167763. */
  167764. #if CONST_BITS == 13
  167765. #define FIX_0_298631336 ((INT32) 2446) /* FIX(0.298631336) */
  167766. #define FIX_0_390180644 ((INT32) 3196) /* FIX(0.390180644) */
  167767. #define FIX_0_541196100 ((INT32) 4433) /* FIX(0.541196100) */
  167768. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  167769. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  167770. #define FIX_1_175875602 ((INT32) 9633) /* FIX(1.175875602) */
  167771. #define FIX_1_501321110 ((INT32) 12299) /* FIX(1.501321110) */
  167772. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  167773. #define FIX_1_961570560 ((INT32) 16069) /* FIX(1.961570560) */
  167774. #define FIX_2_053119869 ((INT32) 16819) /* FIX(2.053119869) */
  167775. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  167776. #define FIX_3_072711026 ((INT32) 25172) /* FIX(3.072711026) */
  167777. #else
  167778. #define FIX_0_298631336 FIX(0.298631336)
  167779. #define FIX_0_390180644 FIX(0.390180644)
  167780. #define FIX_0_541196100 FIX(0.541196100)
  167781. #define FIX_0_765366865 FIX(0.765366865)
  167782. #define FIX_0_899976223 FIX(0.899976223)
  167783. #define FIX_1_175875602 FIX(1.175875602)
  167784. #define FIX_1_501321110 FIX(1.501321110)
  167785. #define FIX_1_847759065 FIX(1.847759065)
  167786. #define FIX_1_961570560 FIX(1.961570560)
  167787. #define FIX_2_053119869 FIX(2.053119869)
  167788. #define FIX_2_562915447 FIX(2.562915447)
  167789. #define FIX_3_072711026 FIX(3.072711026)
  167790. #endif
  167791. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  167792. * For 8-bit samples with the recommended scaling, all the variable
  167793. * and constant values involved are no more than 16 bits wide, so a
  167794. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  167795. * For 12-bit samples, a full 32-bit multiplication will be needed.
  167796. */
  167797. #if BITS_IN_JSAMPLE == 8
  167798. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  167799. #else
  167800. #define MULTIPLY(var,const) ((var) * (const))
  167801. #endif
  167802. /*
  167803. * Perform the forward DCT on one block of samples.
  167804. */
  167805. GLOBAL(void)
  167806. jpeg_fdct_islow (DCTELEM * data)
  167807. {
  167808. INT32 tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  167809. INT32 tmp10, tmp11, tmp12, tmp13;
  167810. INT32 z1, z2, z3, z4, z5;
  167811. DCTELEM *dataptr;
  167812. int ctr;
  167813. SHIFT_TEMPS
  167814. /* Pass 1: process rows. */
  167815. /* Note results are scaled up by sqrt(8) compared to a true DCT; */
  167816. /* furthermore, we scale the results by 2**PASS1_BITS. */
  167817. dataptr = data;
  167818. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  167819. tmp0 = dataptr[0] + dataptr[7];
  167820. tmp7 = dataptr[0] - dataptr[7];
  167821. tmp1 = dataptr[1] + dataptr[6];
  167822. tmp6 = dataptr[1] - dataptr[6];
  167823. tmp2 = dataptr[2] + dataptr[5];
  167824. tmp5 = dataptr[2] - dataptr[5];
  167825. tmp3 = dataptr[3] + dataptr[4];
  167826. tmp4 = dataptr[3] - dataptr[4];
  167827. /* Even part per LL&M figure 1 --- note that published figure is faulty;
  167828. * rotator "sqrt(2)*c1" should be "sqrt(2)*c6".
  167829. */
  167830. tmp10 = tmp0 + tmp3;
  167831. tmp13 = tmp0 - tmp3;
  167832. tmp11 = tmp1 + tmp2;
  167833. tmp12 = tmp1 - tmp2;
  167834. dataptr[0] = (DCTELEM) ((tmp10 + tmp11) << PASS1_BITS);
  167835. dataptr[4] = (DCTELEM) ((tmp10 - tmp11) << PASS1_BITS);
  167836. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_541196100);
  167837. dataptr[2] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp13, FIX_0_765366865),
  167838. CONST_BITS-PASS1_BITS);
  167839. dataptr[6] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp12, - FIX_1_847759065),
  167840. CONST_BITS-PASS1_BITS);
  167841. /* Odd part per figure 8 --- note paper omits factor of sqrt(2).
  167842. * cK represents cos(K*pi/16).
  167843. * i0..i3 in the paper are tmp4..tmp7 here.
  167844. */
  167845. z1 = tmp4 + tmp7;
  167846. z2 = tmp5 + tmp6;
  167847. z3 = tmp4 + tmp6;
  167848. z4 = tmp5 + tmp7;
  167849. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  167850. tmp4 = MULTIPLY(tmp4, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  167851. tmp5 = MULTIPLY(tmp5, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  167852. tmp6 = MULTIPLY(tmp6, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  167853. tmp7 = MULTIPLY(tmp7, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  167854. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  167855. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  167856. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  167857. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  167858. z3 += z5;
  167859. z4 += z5;
  167860. dataptr[7] = (DCTELEM) DESCALE(tmp4 + z1 + z3, CONST_BITS-PASS1_BITS);
  167861. dataptr[5] = (DCTELEM) DESCALE(tmp5 + z2 + z4, CONST_BITS-PASS1_BITS);
  167862. dataptr[3] = (DCTELEM) DESCALE(tmp6 + z2 + z3, CONST_BITS-PASS1_BITS);
  167863. dataptr[1] = (DCTELEM) DESCALE(tmp7 + z1 + z4, CONST_BITS-PASS1_BITS);
  167864. dataptr += DCTSIZE; /* advance pointer to next row */
  167865. }
  167866. /* Pass 2: process columns.
  167867. * We remove the PASS1_BITS scaling, but leave the results scaled up
  167868. * by an overall factor of 8.
  167869. */
  167870. dataptr = data;
  167871. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  167872. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  167873. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  167874. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  167875. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  167876. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  167877. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  167878. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  167879. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  167880. /* Even part per LL&M figure 1 --- note that published figure is faulty;
  167881. * rotator "sqrt(2)*c1" should be "sqrt(2)*c6".
  167882. */
  167883. tmp10 = tmp0 + tmp3;
  167884. tmp13 = tmp0 - tmp3;
  167885. tmp11 = tmp1 + tmp2;
  167886. tmp12 = tmp1 - tmp2;
  167887. dataptr[DCTSIZE*0] = (DCTELEM) DESCALE(tmp10 + tmp11, PASS1_BITS);
  167888. dataptr[DCTSIZE*4] = (DCTELEM) DESCALE(tmp10 - tmp11, PASS1_BITS);
  167889. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_541196100);
  167890. dataptr[DCTSIZE*2] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp13, FIX_0_765366865),
  167891. CONST_BITS+PASS1_BITS);
  167892. dataptr[DCTSIZE*6] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp12, - FIX_1_847759065),
  167893. CONST_BITS+PASS1_BITS);
  167894. /* Odd part per figure 8 --- note paper omits factor of sqrt(2).
  167895. * cK represents cos(K*pi/16).
  167896. * i0..i3 in the paper are tmp4..tmp7 here.
  167897. */
  167898. z1 = tmp4 + tmp7;
  167899. z2 = tmp5 + tmp6;
  167900. z3 = tmp4 + tmp6;
  167901. z4 = tmp5 + tmp7;
  167902. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  167903. tmp4 = MULTIPLY(tmp4, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  167904. tmp5 = MULTIPLY(tmp5, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  167905. tmp6 = MULTIPLY(tmp6, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  167906. tmp7 = MULTIPLY(tmp7, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  167907. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  167908. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  167909. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  167910. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  167911. z3 += z5;
  167912. z4 += z5;
  167913. dataptr[DCTSIZE*7] = (DCTELEM) DESCALE(tmp4 + z1 + z3,
  167914. CONST_BITS+PASS1_BITS);
  167915. dataptr[DCTSIZE*5] = (DCTELEM) DESCALE(tmp5 + z2 + z4,
  167916. CONST_BITS+PASS1_BITS);
  167917. dataptr[DCTSIZE*3] = (DCTELEM) DESCALE(tmp6 + z2 + z3,
  167918. CONST_BITS+PASS1_BITS);
  167919. dataptr[DCTSIZE*1] = (DCTELEM) DESCALE(tmp7 + z1 + z4,
  167920. CONST_BITS+PASS1_BITS);
  167921. dataptr++; /* advance pointer to next column */
  167922. }
  167923. }
  167924. #endif /* DCT_ISLOW_SUPPORTED */
  167925. /********* End of inlined file: jfdctint.c *********/
  167926. #undef CONST_BITS
  167927. #undef MULTIPLY
  167928. #undef FIX_0_541196100
  167929. /********* Start of inlined file: jfdctfst.c *********/
  167930. #define JPEG_INTERNALS
  167931. #ifdef DCT_IFAST_SUPPORTED
  167932. /*
  167933. * This module is specialized to the case DCTSIZE = 8.
  167934. */
  167935. #if DCTSIZE != 8
  167936. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  167937. #endif
  167938. /* Scaling decisions are generally the same as in the LL&M algorithm;
  167939. * see jfdctint.c for more details. However, we choose to descale
  167940. * (right shift) multiplication products as soon as they are formed,
  167941. * rather than carrying additional fractional bits into subsequent additions.
  167942. * This compromises accuracy slightly, but it lets us save a few shifts.
  167943. * More importantly, 16-bit arithmetic is then adequate (for 8-bit samples)
  167944. * everywhere except in the multiplications proper; this saves a good deal
  167945. * of work on 16-bit-int machines.
  167946. *
  167947. * Again to save a few shifts, the intermediate results between pass 1 and
  167948. * pass 2 are not upscaled, but are represented only to integral precision.
  167949. *
  167950. * A final compromise is to represent the multiplicative constants to only
  167951. * 8 fractional bits, rather than 13. This saves some shifting work on some
  167952. * machines, and may also reduce the cost of multiplication (since there
  167953. * are fewer one-bits in the constants).
  167954. */
  167955. #define CONST_BITS 8
  167956. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  167957. * causing a lot of useless floating-point operations at run time.
  167958. * To get around this we use the following pre-calculated constants.
  167959. * If you change CONST_BITS you may want to add appropriate values.
  167960. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  167961. */
  167962. #if CONST_BITS == 8
  167963. #define FIX_0_382683433 ((INT32) 98) /* FIX(0.382683433) */
  167964. #define FIX_0_541196100 ((INT32) 139) /* FIX(0.541196100) */
  167965. #define FIX_0_707106781 ((INT32) 181) /* FIX(0.707106781) */
  167966. #define FIX_1_306562965 ((INT32) 334) /* FIX(1.306562965) */
  167967. #else
  167968. #define FIX_0_382683433 FIX(0.382683433)
  167969. #define FIX_0_541196100 FIX(0.541196100)
  167970. #define FIX_0_707106781 FIX(0.707106781)
  167971. #define FIX_1_306562965 FIX(1.306562965)
  167972. #endif
  167973. /* We can gain a little more speed, with a further compromise in accuracy,
  167974. * by omitting the addition in a descaling shift. This yields an incorrectly
  167975. * rounded result half the time...
  167976. */
  167977. #ifndef USE_ACCURATE_ROUNDING
  167978. #undef DESCALE
  167979. #define DESCALE(x,n) RIGHT_SHIFT(x, n)
  167980. #endif
  167981. /* Multiply a DCTELEM variable by an INT32 constant, and immediately
  167982. * descale to yield a DCTELEM result.
  167983. */
  167984. #define MULTIPLY(var,const) ((DCTELEM) DESCALE((var) * (const), CONST_BITS))
  167985. /*
  167986. * Perform the forward DCT on one block of samples.
  167987. */
  167988. GLOBAL(void)
  167989. jpeg_fdct_ifast (DCTELEM * data)
  167990. {
  167991. DCTELEM tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  167992. DCTELEM tmp10, tmp11, tmp12, tmp13;
  167993. DCTELEM z1, z2, z3, z4, z5, z11, z13;
  167994. DCTELEM *dataptr;
  167995. int ctr;
  167996. SHIFT_TEMPS
  167997. /* Pass 1: process rows. */
  167998. dataptr = data;
  167999. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  168000. tmp0 = dataptr[0] + dataptr[7];
  168001. tmp7 = dataptr[0] - dataptr[7];
  168002. tmp1 = dataptr[1] + dataptr[6];
  168003. tmp6 = dataptr[1] - dataptr[6];
  168004. tmp2 = dataptr[2] + dataptr[5];
  168005. tmp5 = dataptr[2] - dataptr[5];
  168006. tmp3 = dataptr[3] + dataptr[4];
  168007. tmp4 = dataptr[3] - dataptr[4];
  168008. /* Even part */
  168009. tmp10 = tmp0 + tmp3; /* phase 2 */
  168010. tmp13 = tmp0 - tmp3;
  168011. tmp11 = tmp1 + tmp2;
  168012. tmp12 = tmp1 - tmp2;
  168013. dataptr[0] = tmp10 + tmp11; /* phase 3 */
  168014. dataptr[4] = tmp10 - tmp11;
  168015. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_707106781); /* c4 */
  168016. dataptr[2] = tmp13 + z1; /* phase 5 */
  168017. dataptr[6] = tmp13 - z1;
  168018. /* Odd part */
  168019. tmp10 = tmp4 + tmp5; /* phase 2 */
  168020. tmp11 = tmp5 + tmp6;
  168021. tmp12 = tmp6 + tmp7;
  168022. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  168023. z5 = MULTIPLY(tmp10 - tmp12, FIX_0_382683433); /* c6 */
  168024. z2 = MULTIPLY(tmp10, FIX_0_541196100) + z5; /* c2-c6 */
  168025. z4 = MULTIPLY(tmp12, FIX_1_306562965) + z5; /* c2+c6 */
  168026. z3 = MULTIPLY(tmp11, FIX_0_707106781); /* c4 */
  168027. z11 = tmp7 + z3; /* phase 5 */
  168028. z13 = tmp7 - z3;
  168029. dataptr[5] = z13 + z2; /* phase 6 */
  168030. dataptr[3] = z13 - z2;
  168031. dataptr[1] = z11 + z4;
  168032. dataptr[7] = z11 - z4;
  168033. dataptr += DCTSIZE; /* advance pointer to next row */
  168034. }
  168035. /* Pass 2: process columns. */
  168036. dataptr = data;
  168037. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  168038. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  168039. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  168040. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  168041. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  168042. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  168043. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  168044. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  168045. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  168046. /* Even part */
  168047. tmp10 = tmp0 + tmp3; /* phase 2 */
  168048. tmp13 = tmp0 - tmp3;
  168049. tmp11 = tmp1 + tmp2;
  168050. tmp12 = tmp1 - tmp2;
  168051. dataptr[DCTSIZE*0] = tmp10 + tmp11; /* phase 3 */
  168052. dataptr[DCTSIZE*4] = tmp10 - tmp11;
  168053. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_707106781); /* c4 */
  168054. dataptr[DCTSIZE*2] = tmp13 + z1; /* phase 5 */
  168055. dataptr[DCTSIZE*6] = tmp13 - z1;
  168056. /* Odd part */
  168057. tmp10 = tmp4 + tmp5; /* phase 2 */
  168058. tmp11 = tmp5 + tmp6;
  168059. tmp12 = tmp6 + tmp7;
  168060. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  168061. z5 = MULTIPLY(tmp10 - tmp12, FIX_0_382683433); /* c6 */
  168062. z2 = MULTIPLY(tmp10, FIX_0_541196100) + z5; /* c2-c6 */
  168063. z4 = MULTIPLY(tmp12, FIX_1_306562965) + z5; /* c2+c6 */
  168064. z3 = MULTIPLY(tmp11, FIX_0_707106781); /* c4 */
  168065. z11 = tmp7 + z3; /* phase 5 */
  168066. z13 = tmp7 - z3;
  168067. dataptr[DCTSIZE*5] = z13 + z2; /* phase 6 */
  168068. dataptr[DCTSIZE*3] = z13 - z2;
  168069. dataptr[DCTSIZE*1] = z11 + z4;
  168070. dataptr[DCTSIZE*7] = z11 - z4;
  168071. dataptr++; /* advance pointer to next column */
  168072. }
  168073. }
  168074. #endif /* DCT_IFAST_SUPPORTED */
  168075. /********* End of inlined file: jfdctfst.c *********/
  168076. #undef FIX_0_541196100
  168077. /********* Start of inlined file: jidctflt.c *********/
  168078. #define JPEG_INTERNALS
  168079. #ifdef DCT_FLOAT_SUPPORTED
  168080. /*
  168081. * This module is specialized to the case DCTSIZE = 8.
  168082. */
  168083. #if DCTSIZE != 8
  168084. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  168085. #endif
  168086. /* Dequantize a coefficient by multiplying it by the multiplier-table
  168087. * entry; produce a float result.
  168088. */
  168089. #define DEQUANTIZE(coef,quantval) (((FAST_FLOAT) (coef)) * (quantval))
  168090. /*
  168091. * Perform dequantization and inverse DCT on one block of coefficients.
  168092. */
  168093. GLOBAL(void)
  168094. jpeg_idct_float (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  168095. JCOEFPTR coef_block,
  168096. JSAMPARRAY output_buf, JDIMENSION output_col)
  168097. {
  168098. FAST_FLOAT tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  168099. FAST_FLOAT tmp10, tmp11, tmp12, tmp13;
  168100. FAST_FLOAT z5, z10, z11, z12, z13;
  168101. JCOEFPTR inptr;
  168102. FLOAT_MULT_TYPE * quantptr;
  168103. FAST_FLOAT * wsptr;
  168104. JSAMPROW outptr;
  168105. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  168106. int ctr;
  168107. FAST_FLOAT workspace[DCTSIZE2]; /* buffers data between passes */
  168108. SHIFT_TEMPS
  168109. /* Pass 1: process columns from input, store into work array. */
  168110. inptr = coef_block;
  168111. quantptr = (FLOAT_MULT_TYPE *) compptr->dct_table;
  168112. wsptr = workspace;
  168113. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  168114. /* Due to quantization, we will usually find that many of the input
  168115. * coefficients are zero, especially the AC terms. We can exploit this
  168116. * by short-circuiting the IDCT calculation for any column in which all
  168117. * the AC terms are zero. In that case each output is equal to the
  168118. * DC coefficient (with scale factor as needed).
  168119. * With typical images and quantization tables, half or more of the
  168120. * column DCT calculations can be simplified this way.
  168121. */
  168122. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  168123. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  168124. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  168125. inptr[DCTSIZE*7] == 0) {
  168126. /* AC terms all zero */
  168127. FAST_FLOAT dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  168128. wsptr[DCTSIZE*0] = dcval;
  168129. wsptr[DCTSIZE*1] = dcval;
  168130. wsptr[DCTSIZE*2] = dcval;
  168131. wsptr[DCTSIZE*3] = dcval;
  168132. wsptr[DCTSIZE*4] = dcval;
  168133. wsptr[DCTSIZE*5] = dcval;
  168134. wsptr[DCTSIZE*6] = dcval;
  168135. wsptr[DCTSIZE*7] = dcval;
  168136. inptr++; /* advance pointers to next column */
  168137. quantptr++;
  168138. wsptr++;
  168139. continue;
  168140. }
  168141. /* Even part */
  168142. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  168143. tmp1 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  168144. tmp2 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  168145. tmp3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  168146. tmp10 = tmp0 + tmp2; /* phase 3 */
  168147. tmp11 = tmp0 - tmp2;
  168148. tmp13 = tmp1 + tmp3; /* phases 5-3 */
  168149. tmp12 = (tmp1 - tmp3) * ((FAST_FLOAT) 1.414213562) - tmp13; /* 2*c4 */
  168150. tmp0 = tmp10 + tmp13; /* phase 2 */
  168151. tmp3 = tmp10 - tmp13;
  168152. tmp1 = tmp11 + tmp12;
  168153. tmp2 = tmp11 - tmp12;
  168154. /* Odd part */
  168155. tmp4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  168156. tmp5 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  168157. tmp6 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  168158. tmp7 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  168159. z13 = tmp6 + tmp5; /* phase 6 */
  168160. z10 = tmp6 - tmp5;
  168161. z11 = tmp4 + tmp7;
  168162. z12 = tmp4 - tmp7;
  168163. tmp7 = z11 + z13; /* phase 5 */
  168164. tmp11 = (z11 - z13) * ((FAST_FLOAT) 1.414213562); /* 2*c4 */
  168165. z5 = (z10 + z12) * ((FAST_FLOAT) 1.847759065); /* 2*c2 */
  168166. tmp10 = ((FAST_FLOAT) 1.082392200) * z12 - z5; /* 2*(c2-c6) */
  168167. tmp12 = ((FAST_FLOAT) -2.613125930) * z10 + z5; /* -2*(c2+c6) */
  168168. tmp6 = tmp12 - tmp7; /* phase 2 */
  168169. tmp5 = tmp11 - tmp6;
  168170. tmp4 = tmp10 + tmp5;
  168171. wsptr[DCTSIZE*0] = tmp0 + tmp7;
  168172. wsptr[DCTSIZE*7] = tmp0 - tmp7;
  168173. wsptr[DCTSIZE*1] = tmp1 + tmp6;
  168174. wsptr[DCTSIZE*6] = tmp1 - tmp6;
  168175. wsptr[DCTSIZE*2] = tmp2 + tmp5;
  168176. wsptr[DCTSIZE*5] = tmp2 - tmp5;
  168177. wsptr[DCTSIZE*4] = tmp3 + tmp4;
  168178. wsptr[DCTSIZE*3] = tmp3 - tmp4;
  168179. inptr++; /* advance pointers to next column */
  168180. quantptr++;
  168181. wsptr++;
  168182. }
  168183. /* Pass 2: process rows from work array, store into output array. */
  168184. /* Note that we must descale the results by a factor of 8 == 2**3. */
  168185. wsptr = workspace;
  168186. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  168187. outptr = output_buf[ctr] + output_col;
  168188. /* Rows of zeroes can be exploited in the same way as we did with columns.
  168189. * However, the column calculation has created many nonzero AC terms, so
  168190. * the simplification applies less often (typically 5% to 10% of the time).
  168191. * And testing floats for zero is relatively expensive, so we don't bother.
  168192. */
  168193. /* Even part */
  168194. tmp10 = wsptr[0] + wsptr[4];
  168195. tmp11 = wsptr[0] - wsptr[4];
  168196. tmp13 = wsptr[2] + wsptr[6];
  168197. tmp12 = (wsptr[2] - wsptr[6]) * ((FAST_FLOAT) 1.414213562) - tmp13;
  168198. tmp0 = tmp10 + tmp13;
  168199. tmp3 = tmp10 - tmp13;
  168200. tmp1 = tmp11 + tmp12;
  168201. tmp2 = tmp11 - tmp12;
  168202. /* Odd part */
  168203. z13 = wsptr[5] + wsptr[3];
  168204. z10 = wsptr[5] - wsptr[3];
  168205. z11 = wsptr[1] + wsptr[7];
  168206. z12 = wsptr[1] - wsptr[7];
  168207. tmp7 = z11 + z13;
  168208. tmp11 = (z11 - z13) * ((FAST_FLOAT) 1.414213562);
  168209. z5 = (z10 + z12) * ((FAST_FLOAT) 1.847759065); /* 2*c2 */
  168210. tmp10 = ((FAST_FLOAT) 1.082392200) * z12 - z5; /* 2*(c2-c6) */
  168211. tmp12 = ((FAST_FLOAT) -2.613125930) * z10 + z5; /* -2*(c2+c6) */
  168212. tmp6 = tmp12 - tmp7;
  168213. tmp5 = tmp11 - tmp6;
  168214. tmp4 = tmp10 + tmp5;
  168215. /* Final output stage: scale down by a factor of 8 and range-limit */
  168216. outptr[0] = range_limit[(int) DESCALE((INT32) (tmp0 + tmp7), 3)
  168217. & RANGE_MASK];
  168218. outptr[7] = range_limit[(int) DESCALE((INT32) (tmp0 - tmp7), 3)
  168219. & RANGE_MASK];
  168220. outptr[1] = range_limit[(int) DESCALE((INT32) (tmp1 + tmp6), 3)
  168221. & RANGE_MASK];
  168222. outptr[6] = range_limit[(int) DESCALE((INT32) (tmp1 - tmp6), 3)
  168223. & RANGE_MASK];
  168224. outptr[2] = range_limit[(int) DESCALE((INT32) (tmp2 + tmp5), 3)
  168225. & RANGE_MASK];
  168226. outptr[5] = range_limit[(int) DESCALE((INT32) (tmp2 - tmp5), 3)
  168227. & RANGE_MASK];
  168228. outptr[4] = range_limit[(int) DESCALE((INT32) (tmp3 + tmp4), 3)
  168229. & RANGE_MASK];
  168230. outptr[3] = range_limit[(int) DESCALE((INT32) (tmp3 - tmp4), 3)
  168231. & RANGE_MASK];
  168232. wsptr += DCTSIZE; /* advance pointer to next row */
  168233. }
  168234. }
  168235. #endif /* DCT_FLOAT_SUPPORTED */
  168236. /********* End of inlined file: jidctflt.c *********/
  168237. #undef CONST_BITS
  168238. #undef FIX_1_847759065
  168239. #undef MULTIPLY
  168240. #undef DEQUANTIZE
  168241. #undef DESCALE
  168242. /********* Start of inlined file: jidctfst.c *********/
  168243. #define JPEG_INTERNALS
  168244. #ifdef DCT_IFAST_SUPPORTED
  168245. /*
  168246. * This module is specialized to the case DCTSIZE = 8.
  168247. */
  168248. #if DCTSIZE != 8
  168249. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  168250. #endif
  168251. /* Scaling decisions are generally the same as in the LL&M algorithm;
  168252. * see jidctint.c for more details. However, we choose to descale
  168253. * (right shift) multiplication products as soon as they are formed,
  168254. * rather than carrying additional fractional bits into subsequent additions.
  168255. * This compromises accuracy slightly, but it lets us save a few shifts.
  168256. * More importantly, 16-bit arithmetic is then adequate (for 8-bit samples)
  168257. * everywhere except in the multiplications proper; this saves a good deal
  168258. * of work on 16-bit-int machines.
  168259. *
  168260. * The dequantized coefficients are not integers because the AA&N scaling
  168261. * factors have been incorporated. We represent them scaled up by PASS1_BITS,
  168262. * so that the first and second IDCT rounds have the same input scaling.
  168263. * For 8-bit JSAMPLEs, we choose IFAST_SCALE_BITS = PASS1_BITS so as to
  168264. * avoid a descaling shift; this compromises accuracy rather drastically
  168265. * for small quantization table entries, but it saves a lot of shifts.
  168266. * For 12-bit JSAMPLEs, there's no hope of using 16x16 multiplies anyway,
  168267. * so we use a much larger scaling factor to preserve accuracy.
  168268. *
  168269. * A final compromise is to represent the multiplicative constants to only
  168270. * 8 fractional bits, rather than 13. This saves some shifting work on some
  168271. * machines, and may also reduce the cost of multiplication (since there
  168272. * are fewer one-bits in the constants).
  168273. */
  168274. #if BITS_IN_JSAMPLE == 8
  168275. #define CONST_BITS 8
  168276. #define PASS1_BITS 2
  168277. #else
  168278. #define CONST_BITS 8
  168279. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  168280. #endif
  168281. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  168282. * causing a lot of useless floating-point operations at run time.
  168283. * To get around this we use the following pre-calculated constants.
  168284. * If you change CONST_BITS you may want to add appropriate values.
  168285. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  168286. */
  168287. #if CONST_BITS == 8
  168288. #define FIX_1_082392200 ((INT32) 277) /* FIX(1.082392200) */
  168289. #define FIX_1_414213562 ((INT32) 362) /* FIX(1.414213562) */
  168290. #define FIX_1_847759065 ((INT32) 473) /* FIX(1.847759065) */
  168291. #define FIX_2_613125930 ((INT32) 669) /* FIX(2.613125930) */
  168292. #else
  168293. #define FIX_1_082392200 FIX(1.082392200)
  168294. #define FIX_1_414213562 FIX(1.414213562)
  168295. #define FIX_1_847759065 FIX(1.847759065)
  168296. #define FIX_2_613125930 FIX(2.613125930)
  168297. #endif
  168298. /* We can gain a little more speed, with a further compromise in accuracy,
  168299. * by omitting the addition in a descaling shift. This yields an incorrectly
  168300. * rounded result half the time...
  168301. */
  168302. #ifndef USE_ACCURATE_ROUNDING
  168303. #undef DESCALE
  168304. #define DESCALE(x,n) RIGHT_SHIFT(x, n)
  168305. #endif
  168306. /* Multiply a DCTELEM variable by an INT32 constant, and immediately
  168307. * descale to yield a DCTELEM result.
  168308. */
  168309. #define MULTIPLY(var,const) ((DCTELEM) DESCALE((var) * (const), CONST_BITS))
  168310. /* Dequantize a coefficient by multiplying it by the multiplier-table
  168311. * entry; produce a DCTELEM result. For 8-bit data a 16x16->16
  168312. * multiplication will do. For 12-bit data, the multiplier table is
  168313. * declared INT32, so a 32-bit multiply will be used.
  168314. */
  168315. #if BITS_IN_JSAMPLE == 8
  168316. #define DEQUANTIZE(coef,quantval) (((IFAST_MULT_TYPE) (coef)) * (quantval))
  168317. #else
  168318. #define DEQUANTIZE(coef,quantval) \
  168319. DESCALE((coef)*(quantval), IFAST_SCALE_BITS-PASS1_BITS)
  168320. #endif
  168321. /* Like DESCALE, but applies to a DCTELEM and produces an int.
  168322. * We assume that int right shift is unsigned if INT32 right shift is.
  168323. */
  168324. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  168325. #define ISHIFT_TEMPS DCTELEM ishift_temp;
  168326. #if BITS_IN_JSAMPLE == 8
  168327. #define DCTELEMBITS 16 /* DCTELEM may be 16 or 32 bits */
  168328. #else
  168329. #define DCTELEMBITS 32 /* DCTELEM must be 32 bits */
  168330. #endif
  168331. #define IRIGHT_SHIFT(x,shft) \
  168332. ((ishift_temp = (x)) < 0 ? \
  168333. (ishift_temp >> (shft)) | ((~((DCTELEM) 0)) << (DCTELEMBITS-(shft))) : \
  168334. (ishift_temp >> (shft)))
  168335. #else
  168336. #define ISHIFT_TEMPS
  168337. #define IRIGHT_SHIFT(x,shft) ((x) >> (shft))
  168338. #endif
  168339. #ifdef USE_ACCURATE_ROUNDING
  168340. #define IDESCALE(x,n) ((int) IRIGHT_SHIFT((x) + (1 << ((n)-1)), n))
  168341. #else
  168342. #define IDESCALE(x,n) ((int) IRIGHT_SHIFT(x, n))
  168343. #endif
  168344. /*
  168345. * Perform dequantization and inverse DCT on one block of coefficients.
  168346. */
  168347. GLOBAL(void)
  168348. jpeg_idct_ifast (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  168349. JCOEFPTR coef_block,
  168350. JSAMPARRAY output_buf, JDIMENSION output_col)
  168351. {
  168352. DCTELEM tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  168353. DCTELEM tmp10, tmp11, tmp12, tmp13;
  168354. DCTELEM z5, z10, z11, z12, z13;
  168355. JCOEFPTR inptr;
  168356. IFAST_MULT_TYPE * quantptr;
  168357. int * wsptr;
  168358. JSAMPROW outptr;
  168359. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  168360. int ctr;
  168361. int workspace[DCTSIZE2]; /* buffers data between passes */
  168362. SHIFT_TEMPS /* for DESCALE */
  168363. ISHIFT_TEMPS /* for IDESCALE */
  168364. /* Pass 1: process columns from input, store into work array. */
  168365. inptr = coef_block;
  168366. quantptr = (IFAST_MULT_TYPE *) compptr->dct_table;
  168367. wsptr = workspace;
  168368. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  168369. /* Due to quantization, we will usually find that many of the input
  168370. * coefficients are zero, especially the AC terms. We can exploit this
  168371. * by short-circuiting the IDCT calculation for any column in which all
  168372. * the AC terms are zero. In that case each output is equal to the
  168373. * DC coefficient (with scale factor as needed).
  168374. * With typical images and quantization tables, half or more of the
  168375. * column DCT calculations can be simplified this way.
  168376. */
  168377. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  168378. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  168379. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  168380. inptr[DCTSIZE*7] == 0) {
  168381. /* AC terms all zero */
  168382. int dcval = (int) DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  168383. wsptr[DCTSIZE*0] = dcval;
  168384. wsptr[DCTSIZE*1] = dcval;
  168385. wsptr[DCTSIZE*2] = dcval;
  168386. wsptr[DCTSIZE*3] = dcval;
  168387. wsptr[DCTSIZE*4] = dcval;
  168388. wsptr[DCTSIZE*5] = dcval;
  168389. wsptr[DCTSIZE*6] = dcval;
  168390. wsptr[DCTSIZE*7] = dcval;
  168391. inptr++; /* advance pointers to next column */
  168392. quantptr++;
  168393. wsptr++;
  168394. continue;
  168395. }
  168396. /* Even part */
  168397. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  168398. tmp1 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  168399. tmp2 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  168400. tmp3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  168401. tmp10 = tmp0 + tmp2; /* phase 3 */
  168402. tmp11 = tmp0 - tmp2;
  168403. tmp13 = tmp1 + tmp3; /* phases 5-3 */
  168404. tmp12 = MULTIPLY(tmp1 - tmp3, FIX_1_414213562) - tmp13; /* 2*c4 */
  168405. tmp0 = tmp10 + tmp13; /* phase 2 */
  168406. tmp3 = tmp10 - tmp13;
  168407. tmp1 = tmp11 + tmp12;
  168408. tmp2 = tmp11 - tmp12;
  168409. /* Odd part */
  168410. tmp4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  168411. tmp5 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  168412. tmp6 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  168413. tmp7 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  168414. z13 = tmp6 + tmp5; /* phase 6 */
  168415. z10 = tmp6 - tmp5;
  168416. z11 = tmp4 + tmp7;
  168417. z12 = tmp4 - tmp7;
  168418. tmp7 = z11 + z13; /* phase 5 */
  168419. tmp11 = MULTIPLY(z11 - z13, FIX_1_414213562); /* 2*c4 */
  168420. z5 = MULTIPLY(z10 + z12, FIX_1_847759065); /* 2*c2 */
  168421. tmp10 = MULTIPLY(z12, FIX_1_082392200) - z5; /* 2*(c2-c6) */
  168422. tmp12 = MULTIPLY(z10, - FIX_2_613125930) + z5; /* -2*(c2+c6) */
  168423. tmp6 = tmp12 - tmp7; /* phase 2 */
  168424. tmp5 = tmp11 - tmp6;
  168425. tmp4 = tmp10 + tmp5;
  168426. wsptr[DCTSIZE*0] = (int) (tmp0 + tmp7);
  168427. wsptr[DCTSIZE*7] = (int) (tmp0 - tmp7);
  168428. wsptr[DCTSIZE*1] = (int) (tmp1 + tmp6);
  168429. wsptr[DCTSIZE*6] = (int) (tmp1 - tmp6);
  168430. wsptr[DCTSIZE*2] = (int) (tmp2 + tmp5);
  168431. wsptr[DCTSIZE*5] = (int) (tmp2 - tmp5);
  168432. wsptr[DCTSIZE*4] = (int) (tmp3 + tmp4);
  168433. wsptr[DCTSIZE*3] = (int) (tmp3 - tmp4);
  168434. inptr++; /* advance pointers to next column */
  168435. quantptr++;
  168436. wsptr++;
  168437. }
  168438. /* Pass 2: process rows from work array, store into output array. */
  168439. /* Note that we must descale the results by a factor of 8 == 2**3, */
  168440. /* and also undo the PASS1_BITS scaling. */
  168441. wsptr = workspace;
  168442. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  168443. outptr = output_buf[ctr] + output_col;
  168444. /* Rows of zeroes can be exploited in the same way as we did with columns.
  168445. * However, the column calculation has created many nonzero AC terms, so
  168446. * the simplification applies less often (typically 5% to 10% of the time).
  168447. * On machines with very fast multiplication, it's possible that the
  168448. * test takes more time than it's worth. In that case this section
  168449. * may be commented out.
  168450. */
  168451. #ifndef NO_ZERO_ROW_TEST
  168452. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 && wsptr[4] == 0 &&
  168453. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  168454. /* AC terms all zero */
  168455. JSAMPLE dcval = range_limit[IDESCALE(wsptr[0], PASS1_BITS+3)
  168456. & RANGE_MASK];
  168457. outptr[0] = dcval;
  168458. outptr[1] = dcval;
  168459. outptr[2] = dcval;
  168460. outptr[3] = dcval;
  168461. outptr[4] = dcval;
  168462. outptr[5] = dcval;
  168463. outptr[6] = dcval;
  168464. outptr[7] = dcval;
  168465. wsptr += DCTSIZE; /* advance pointer to next row */
  168466. continue;
  168467. }
  168468. #endif
  168469. /* Even part */
  168470. tmp10 = ((DCTELEM) wsptr[0] + (DCTELEM) wsptr[4]);
  168471. tmp11 = ((DCTELEM) wsptr[0] - (DCTELEM) wsptr[4]);
  168472. tmp13 = ((DCTELEM) wsptr[2] + (DCTELEM) wsptr[6]);
  168473. tmp12 = MULTIPLY((DCTELEM) wsptr[2] - (DCTELEM) wsptr[6], FIX_1_414213562)
  168474. - tmp13;
  168475. tmp0 = tmp10 + tmp13;
  168476. tmp3 = tmp10 - tmp13;
  168477. tmp1 = tmp11 + tmp12;
  168478. tmp2 = tmp11 - tmp12;
  168479. /* Odd part */
  168480. z13 = (DCTELEM) wsptr[5] + (DCTELEM) wsptr[3];
  168481. z10 = (DCTELEM) wsptr[5] - (DCTELEM) wsptr[3];
  168482. z11 = (DCTELEM) wsptr[1] + (DCTELEM) wsptr[7];
  168483. z12 = (DCTELEM) wsptr[1] - (DCTELEM) wsptr[7];
  168484. tmp7 = z11 + z13; /* phase 5 */
  168485. tmp11 = MULTIPLY(z11 - z13, FIX_1_414213562); /* 2*c4 */
  168486. z5 = MULTIPLY(z10 + z12, FIX_1_847759065); /* 2*c2 */
  168487. tmp10 = MULTIPLY(z12, FIX_1_082392200) - z5; /* 2*(c2-c6) */
  168488. tmp12 = MULTIPLY(z10, - FIX_2_613125930) + z5; /* -2*(c2+c6) */
  168489. tmp6 = tmp12 - tmp7; /* phase 2 */
  168490. tmp5 = tmp11 - tmp6;
  168491. tmp4 = tmp10 + tmp5;
  168492. /* Final output stage: scale down by a factor of 8 and range-limit */
  168493. outptr[0] = range_limit[IDESCALE(tmp0 + tmp7, PASS1_BITS+3)
  168494. & RANGE_MASK];
  168495. outptr[7] = range_limit[IDESCALE(tmp0 - tmp7, PASS1_BITS+3)
  168496. & RANGE_MASK];
  168497. outptr[1] = range_limit[IDESCALE(tmp1 + tmp6, PASS1_BITS+3)
  168498. & RANGE_MASK];
  168499. outptr[6] = range_limit[IDESCALE(tmp1 - tmp6, PASS1_BITS+3)
  168500. & RANGE_MASK];
  168501. outptr[2] = range_limit[IDESCALE(tmp2 + tmp5, PASS1_BITS+3)
  168502. & RANGE_MASK];
  168503. outptr[5] = range_limit[IDESCALE(tmp2 - tmp5, PASS1_BITS+3)
  168504. & RANGE_MASK];
  168505. outptr[4] = range_limit[IDESCALE(tmp3 + tmp4, PASS1_BITS+3)
  168506. & RANGE_MASK];
  168507. outptr[3] = range_limit[IDESCALE(tmp3 - tmp4, PASS1_BITS+3)
  168508. & RANGE_MASK];
  168509. wsptr += DCTSIZE; /* advance pointer to next row */
  168510. }
  168511. }
  168512. #endif /* DCT_IFAST_SUPPORTED */
  168513. /********* End of inlined file: jidctfst.c *********/
  168514. #undef CONST_BITS
  168515. #undef FIX_1_847759065
  168516. #undef MULTIPLY
  168517. #undef DEQUANTIZE
  168518. /********* Start of inlined file: jidctint.c *********/
  168519. #define JPEG_INTERNALS
  168520. #ifdef DCT_ISLOW_SUPPORTED
  168521. /*
  168522. * This module is specialized to the case DCTSIZE = 8.
  168523. */
  168524. #if DCTSIZE != 8
  168525. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  168526. #endif
  168527. /*
  168528. * The poop on this scaling stuff is as follows:
  168529. *
  168530. * Each 1-D IDCT step produces outputs which are a factor of sqrt(N)
  168531. * larger than the true IDCT outputs. The final outputs are therefore
  168532. * a factor of N larger than desired; since N=8 this can be cured by
  168533. * a simple right shift at the end of the algorithm. The advantage of
  168534. * this arrangement is that we save two multiplications per 1-D IDCT,
  168535. * because the y0 and y4 inputs need not be divided by sqrt(N).
  168536. *
  168537. * We have to do addition and subtraction of the integer inputs, which
  168538. * is no problem, and multiplication by fractional constants, which is
  168539. * a problem to do in integer arithmetic. We multiply all the constants
  168540. * by CONST_SCALE and convert them to integer constants (thus retaining
  168541. * CONST_BITS bits of precision in the constants). After doing a
  168542. * multiplication we have to divide the product by CONST_SCALE, with proper
  168543. * rounding, to produce the correct output. This division can be done
  168544. * cheaply as a right shift of CONST_BITS bits. We postpone shifting
  168545. * as long as possible so that partial sums can be added together with
  168546. * full fractional precision.
  168547. *
  168548. * The outputs of the first pass are scaled up by PASS1_BITS bits so that
  168549. * they are represented to better-than-integral precision. These outputs
  168550. * require BITS_IN_JSAMPLE + PASS1_BITS + 3 bits; this fits in a 16-bit word
  168551. * with the recommended scaling. (To scale up 12-bit sample data further, an
  168552. * intermediate INT32 array would be needed.)
  168553. *
  168554. * To avoid overflow of the 32-bit intermediate results in pass 2, we must
  168555. * have BITS_IN_JSAMPLE + CONST_BITS + PASS1_BITS <= 26. Error analysis
  168556. * shows that the values given below are the most effective.
  168557. */
  168558. #if BITS_IN_JSAMPLE == 8
  168559. #define CONST_BITS 13
  168560. #define PASS1_BITS 2
  168561. #else
  168562. #define CONST_BITS 13
  168563. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  168564. #endif
  168565. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  168566. * causing a lot of useless floating-point operations at run time.
  168567. * To get around this we use the following pre-calculated constants.
  168568. * If you change CONST_BITS you may want to add appropriate values.
  168569. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  168570. */
  168571. #if CONST_BITS == 13
  168572. #define FIX_0_298631336 ((INT32) 2446) /* FIX(0.298631336) */
  168573. #define FIX_0_390180644 ((INT32) 3196) /* FIX(0.390180644) */
  168574. #define FIX_0_541196100 ((INT32) 4433) /* FIX(0.541196100) */
  168575. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  168576. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  168577. #define FIX_1_175875602 ((INT32) 9633) /* FIX(1.175875602) */
  168578. #define FIX_1_501321110 ((INT32) 12299) /* FIX(1.501321110) */
  168579. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  168580. #define FIX_1_961570560 ((INT32) 16069) /* FIX(1.961570560) */
  168581. #define FIX_2_053119869 ((INT32) 16819) /* FIX(2.053119869) */
  168582. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  168583. #define FIX_3_072711026 ((INT32) 25172) /* FIX(3.072711026) */
  168584. #else
  168585. #define FIX_0_298631336 FIX(0.298631336)
  168586. #define FIX_0_390180644 FIX(0.390180644)
  168587. #define FIX_0_541196100 FIX(0.541196100)
  168588. #define FIX_0_765366865 FIX(0.765366865)
  168589. #define FIX_0_899976223 FIX(0.899976223)
  168590. #define FIX_1_175875602 FIX(1.175875602)
  168591. #define FIX_1_501321110 FIX(1.501321110)
  168592. #define FIX_1_847759065 FIX(1.847759065)
  168593. #define FIX_1_961570560 FIX(1.961570560)
  168594. #define FIX_2_053119869 FIX(2.053119869)
  168595. #define FIX_2_562915447 FIX(2.562915447)
  168596. #define FIX_3_072711026 FIX(3.072711026)
  168597. #endif
  168598. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  168599. * For 8-bit samples with the recommended scaling, all the variable
  168600. * and constant values involved are no more than 16 bits wide, so a
  168601. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  168602. * For 12-bit samples, a full 32-bit multiplication will be needed.
  168603. */
  168604. #if BITS_IN_JSAMPLE == 8
  168605. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  168606. #else
  168607. #define MULTIPLY(var,const) ((var) * (const))
  168608. #endif
  168609. /* Dequantize a coefficient by multiplying it by the multiplier-table
  168610. * entry; produce an int result. In this module, both inputs and result
  168611. * are 16 bits or less, so either int or short multiply will work.
  168612. */
  168613. #define DEQUANTIZE(coef,quantval) (((ISLOW_MULT_TYPE) (coef)) * (quantval))
  168614. /*
  168615. * Perform dequantization and inverse DCT on one block of coefficients.
  168616. */
  168617. GLOBAL(void)
  168618. jpeg_idct_islow (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  168619. JCOEFPTR coef_block,
  168620. JSAMPARRAY output_buf, JDIMENSION output_col)
  168621. {
  168622. INT32 tmp0, tmp1, tmp2, tmp3;
  168623. INT32 tmp10, tmp11, tmp12, tmp13;
  168624. INT32 z1, z2, z3, z4, z5;
  168625. JCOEFPTR inptr;
  168626. ISLOW_MULT_TYPE * quantptr;
  168627. int * wsptr;
  168628. JSAMPROW outptr;
  168629. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  168630. int ctr;
  168631. int workspace[DCTSIZE2]; /* buffers data between passes */
  168632. SHIFT_TEMPS
  168633. /* Pass 1: process columns from input, store into work array. */
  168634. /* Note results are scaled up by sqrt(8) compared to a true IDCT; */
  168635. /* furthermore, we scale the results by 2**PASS1_BITS. */
  168636. inptr = coef_block;
  168637. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  168638. wsptr = workspace;
  168639. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  168640. /* Due to quantization, we will usually find that many of the input
  168641. * coefficients are zero, especially the AC terms. We can exploit this
  168642. * by short-circuiting the IDCT calculation for any column in which all
  168643. * the AC terms are zero. In that case each output is equal to the
  168644. * DC coefficient (with scale factor as needed).
  168645. * With typical images and quantization tables, half or more of the
  168646. * column DCT calculations can be simplified this way.
  168647. */
  168648. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  168649. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  168650. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  168651. inptr[DCTSIZE*7] == 0) {
  168652. /* AC terms all zero */
  168653. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  168654. wsptr[DCTSIZE*0] = dcval;
  168655. wsptr[DCTSIZE*1] = dcval;
  168656. wsptr[DCTSIZE*2] = dcval;
  168657. wsptr[DCTSIZE*3] = dcval;
  168658. wsptr[DCTSIZE*4] = dcval;
  168659. wsptr[DCTSIZE*5] = dcval;
  168660. wsptr[DCTSIZE*6] = dcval;
  168661. wsptr[DCTSIZE*7] = dcval;
  168662. inptr++; /* advance pointers to next column */
  168663. quantptr++;
  168664. wsptr++;
  168665. continue;
  168666. }
  168667. /* Even part: reverse the even part of the forward DCT. */
  168668. /* The rotator is sqrt(2)*c(-6). */
  168669. z2 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  168670. z3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  168671. z1 = MULTIPLY(z2 + z3, FIX_0_541196100);
  168672. tmp2 = z1 + MULTIPLY(z3, - FIX_1_847759065);
  168673. tmp3 = z1 + MULTIPLY(z2, FIX_0_765366865);
  168674. z2 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  168675. z3 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  168676. tmp0 = (z2 + z3) << CONST_BITS;
  168677. tmp1 = (z2 - z3) << CONST_BITS;
  168678. tmp10 = tmp0 + tmp3;
  168679. tmp13 = tmp0 - tmp3;
  168680. tmp11 = tmp1 + tmp2;
  168681. tmp12 = tmp1 - tmp2;
  168682. /* Odd part per figure 8; the matrix is unitary and hence its
  168683. * transpose is its inverse. i0..i3 are y7,y5,y3,y1 respectively.
  168684. */
  168685. tmp0 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  168686. tmp1 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  168687. tmp2 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  168688. tmp3 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  168689. z1 = tmp0 + tmp3;
  168690. z2 = tmp1 + tmp2;
  168691. z3 = tmp0 + tmp2;
  168692. z4 = tmp1 + tmp3;
  168693. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  168694. tmp0 = MULTIPLY(tmp0, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  168695. tmp1 = MULTIPLY(tmp1, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  168696. tmp2 = MULTIPLY(tmp2, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  168697. tmp3 = MULTIPLY(tmp3, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  168698. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  168699. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  168700. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  168701. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  168702. z3 += z5;
  168703. z4 += z5;
  168704. tmp0 += z1 + z3;
  168705. tmp1 += z2 + z4;
  168706. tmp2 += z2 + z3;
  168707. tmp3 += z1 + z4;
  168708. /* Final output stage: inputs are tmp10..tmp13, tmp0..tmp3 */
  168709. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp3, CONST_BITS-PASS1_BITS);
  168710. wsptr[DCTSIZE*7] = (int) DESCALE(tmp10 - tmp3, CONST_BITS-PASS1_BITS);
  168711. wsptr[DCTSIZE*1] = (int) DESCALE(tmp11 + tmp2, CONST_BITS-PASS1_BITS);
  168712. wsptr[DCTSIZE*6] = (int) DESCALE(tmp11 - tmp2, CONST_BITS-PASS1_BITS);
  168713. wsptr[DCTSIZE*2] = (int) DESCALE(tmp12 + tmp1, CONST_BITS-PASS1_BITS);
  168714. wsptr[DCTSIZE*5] = (int) DESCALE(tmp12 - tmp1, CONST_BITS-PASS1_BITS);
  168715. wsptr[DCTSIZE*3] = (int) DESCALE(tmp13 + tmp0, CONST_BITS-PASS1_BITS);
  168716. wsptr[DCTSIZE*4] = (int) DESCALE(tmp13 - tmp0, CONST_BITS-PASS1_BITS);
  168717. inptr++; /* advance pointers to next column */
  168718. quantptr++;
  168719. wsptr++;
  168720. }
  168721. /* Pass 2: process rows from work array, store into output array. */
  168722. /* Note that we must descale the results by a factor of 8 == 2**3, */
  168723. /* and also undo the PASS1_BITS scaling. */
  168724. wsptr = workspace;
  168725. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  168726. outptr = output_buf[ctr] + output_col;
  168727. /* Rows of zeroes can be exploited in the same way as we did with columns.
  168728. * However, the column calculation has created many nonzero AC terms, so
  168729. * the simplification applies less often (typically 5% to 10% of the time).
  168730. * On machines with very fast multiplication, it's possible that the
  168731. * test takes more time than it's worth. In that case this section
  168732. * may be commented out.
  168733. */
  168734. #ifndef NO_ZERO_ROW_TEST
  168735. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 && wsptr[4] == 0 &&
  168736. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  168737. /* AC terms all zero */
  168738. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  168739. & RANGE_MASK];
  168740. outptr[0] = dcval;
  168741. outptr[1] = dcval;
  168742. outptr[2] = dcval;
  168743. outptr[3] = dcval;
  168744. outptr[4] = dcval;
  168745. outptr[5] = dcval;
  168746. outptr[6] = dcval;
  168747. outptr[7] = dcval;
  168748. wsptr += DCTSIZE; /* advance pointer to next row */
  168749. continue;
  168750. }
  168751. #endif
  168752. /* Even part: reverse the even part of the forward DCT. */
  168753. /* The rotator is sqrt(2)*c(-6). */
  168754. z2 = (INT32) wsptr[2];
  168755. z3 = (INT32) wsptr[6];
  168756. z1 = MULTIPLY(z2 + z3, FIX_0_541196100);
  168757. tmp2 = z1 + MULTIPLY(z3, - FIX_1_847759065);
  168758. tmp3 = z1 + MULTIPLY(z2, FIX_0_765366865);
  168759. tmp0 = ((INT32) wsptr[0] + (INT32) wsptr[4]) << CONST_BITS;
  168760. tmp1 = ((INT32) wsptr[0] - (INT32) wsptr[4]) << CONST_BITS;
  168761. tmp10 = tmp0 + tmp3;
  168762. tmp13 = tmp0 - tmp3;
  168763. tmp11 = tmp1 + tmp2;
  168764. tmp12 = tmp1 - tmp2;
  168765. /* Odd part per figure 8; the matrix is unitary and hence its
  168766. * transpose is its inverse. i0..i3 are y7,y5,y3,y1 respectively.
  168767. */
  168768. tmp0 = (INT32) wsptr[7];
  168769. tmp1 = (INT32) wsptr[5];
  168770. tmp2 = (INT32) wsptr[3];
  168771. tmp3 = (INT32) wsptr[1];
  168772. z1 = tmp0 + tmp3;
  168773. z2 = tmp1 + tmp2;
  168774. z3 = tmp0 + tmp2;
  168775. z4 = tmp1 + tmp3;
  168776. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  168777. tmp0 = MULTIPLY(tmp0, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  168778. tmp1 = MULTIPLY(tmp1, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  168779. tmp2 = MULTIPLY(tmp2, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  168780. tmp3 = MULTIPLY(tmp3, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  168781. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  168782. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  168783. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  168784. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  168785. z3 += z5;
  168786. z4 += z5;
  168787. tmp0 += z1 + z3;
  168788. tmp1 += z2 + z4;
  168789. tmp2 += z2 + z3;
  168790. tmp3 += z1 + z4;
  168791. /* Final output stage: inputs are tmp10..tmp13, tmp0..tmp3 */
  168792. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp3,
  168793. CONST_BITS+PASS1_BITS+3)
  168794. & RANGE_MASK];
  168795. outptr[7] = range_limit[(int) DESCALE(tmp10 - tmp3,
  168796. CONST_BITS+PASS1_BITS+3)
  168797. & RANGE_MASK];
  168798. outptr[1] = range_limit[(int) DESCALE(tmp11 + tmp2,
  168799. CONST_BITS+PASS1_BITS+3)
  168800. & RANGE_MASK];
  168801. outptr[6] = range_limit[(int) DESCALE(tmp11 - tmp2,
  168802. CONST_BITS+PASS1_BITS+3)
  168803. & RANGE_MASK];
  168804. outptr[2] = range_limit[(int) DESCALE(tmp12 + tmp1,
  168805. CONST_BITS+PASS1_BITS+3)
  168806. & RANGE_MASK];
  168807. outptr[5] = range_limit[(int) DESCALE(tmp12 - tmp1,
  168808. CONST_BITS+PASS1_BITS+3)
  168809. & RANGE_MASK];
  168810. outptr[3] = range_limit[(int) DESCALE(tmp13 + tmp0,
  168811. CONST_BITS+PASS1_BITS+3)
  168812. & RANGE_MASK];
  168813. outptr[4] = range_limit[(int) DESCALE(tmp13 - tmp0,
  168814. CONST_BITS+PASS1_BITS+3)
  168815. & RANGE_MASK];
  168816. wsptr += DCTSIZE; /* advance pointer to next row */
  168817. }
  168818. }
  168819. #endif /* DCT_ISLOW_SUPPORTED */
  168820. /********* End of inlined file: jidctint.c *********/
  168821. /********* Start of inlined file: jidctred.c *********/
  168822. #define JPEG_INTERNALS
  168823. #ifdef IDCT_SCALING_SUPPORTED
  168824. /*
  168825. * This module is specialized to the case DCTSIZE = 8.
  168826. */
  168827. #if DCTSIZE != 8
  168828. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  168829. #endif
  168830. /* Scaling is the same as in jidctint.c. */
  168831. #if BITS_IN_JSAMPLE == 8
  168832. #define CONST_BITS 13
  168833. #define PASS1_BITS 2
  168834. #else
  168835. #define CONST_BITS 13
  168836. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  168837. #endif
  168838. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  168839. * causing a lot of useless floating-point operations at run time.
  168840. * To get around this we use the following pre-calculated constants.
  168841. * If you change CONST_BITS you may want to add appropriate values.
  168842. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  168843. */
  168844. #if CONST_BITS == 13
  168845. #define FIX_0_211164243 ((INT32) 1730) /* FIX(0.211164243) */
  168846. #define FIX_0_509795579 ((INT32) 4176) /* FIX(0.509795579) */
  168847. #define FIX_0_601344887 ((INT32) 4926) /* FIX(0.601344887) */
  168848. #define FIX_0_720959822 ((INT32) 5906) /* FIX(0.720959822) */
  168849. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  168850. #define FIX_0_850430095 ((INT32) 6967) /* FIX(0.850430095) */
  168851. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  168852. #define FIX_1_061594337 ((INT32) 8697) /* FIX(1.061594337) */
  168853. #define FIX_1_272758580 ((INT32) 10426) /* FIX(1.272758580) */
  168854. #define FIX_1_451774981 ((INT32) 11893) /* FIX(1.451774981) */
  168855. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  168856. #define FIX_2_172734803 ((INT32) 17799) /* FIX(2.172734803) */
  168857. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  168858. #define FIX_3_624509785 ((INT32) 29692) /* FIX(3.624509785) */
  168859. #else
  168860. #define FIX_0_211164243 FIX(0.211164243)
  168861. #define FIX_0_509795579 FIX(0.509795579)
  168862. #define FIX_0_601344887 FIX(0.601344887)
  168863. #define FIX_0_720959822 FIX(0.720959822)
  168864. #define FIX_0_765366865 FIX(0.765366865)
  168865. #define FIX_0_850430095 FIX(0.850430095)
  168866. #define FIX_0_899976223 FIX(0.899976223)
  168867. #define FIX_1_061594337 FIX(1.061594337)
  168868. #define FIX_1_272758580 FIX(1.272758580)
  168869. #define FIX_1_451774981 FIX(1.451774981)
  168870. #define FIX_1_847759065 FIX(1.847759065)
  168871. #define FIX_2_172734803 FIX(2.172734803)
  168872. #define FIX_2_562915447 FIX(2.562915447)
  168873. #define FIX_3_624509785 FIX(3.624509785)
  168874. #endif
  168875. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  168876. * For 8-bit samples with the recommended scaling, all the variable
  168877. * and constant values involved are no more than 16 bits wide, so a
  168878. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  168879. * For 12-bit samples, a full 32-bit multiplication will be needed.
  168880. */
  168881. #if BITS_IN_JSAMPLE == 8
  168882. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  168883. #else
  168884. #define MULTIPLY(var,const) ((var) * (const))
  168885. #endif
  168886. /* Dequantize a coefficient by multiplying it by the multiplier-table
  168887. * entry; produce an int result. In this module, both inputs and result
  168888. * are 16 bits or less, so either int or short multiply will work.
  168889. */
  168890. #define DEQUANTIZE(coef,quantval) (((ISLOW_MULT_TYPE) (coef)) * (quantval))
  168891. /*
  168892. * Perform dequantization and inverse DCT on one block of coefficients,
  168893. * producing a reduced-size 4x4 output block.
  168894. */
  168895. GLOBAL(void)
  168896. jpeg_idct_4x4 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  168897. JCOEFPTR coef_block,
  168898. JSAMPARRAY output_buf, JDIMENSION output_col)
  168899. {
  168900. INT32 tmp0, tmp2, tmp10, tmp12;
  168901. INT32 z1, z2, z3, z4;
  168902. JCOEFPTR inptr;
  168903. ISLOW_MULT_TYPE * quantptr;
  168904. int * wsptr;
  168905. JSAMPROW outptr;
  168906. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  168907. int ctr;
  168908. int workspace[DCTSIZE*4]; /* buffers data between passes */
  168909. SHIFT_TEMPS
  168910. /* Pass 1: process columns from input, store into work array. */
  168911. inptr = coef_block;
  168912. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  168913. wsptr = workspace;
  168914. for (ctr = DCTSIZE; ctr > 0; inptr++, quantptr++, wsptr++, ctr--) {
  168915. /* Don't bother to process column 4, because second pass won't use it */
  168916. if (ctr == DCTSIZE-4)
  168917. continue;
  168918. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  168919. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*5] == 0 &&
  168920. inptr[DCTSIZE*6] == 0 && inptr[DCTSIZE*7] == 0) {
  168921. /* AC terms all zero; we need not examine term 4 for 4x4 output */
  168922. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  168923. wsptr[DCTSIZE*0] = dcval;
  168924. wsptr[DCTSIZE*1] = dcval;
  168925. wsptr[DCTSIZE*2] = dcval;
  168926. wsptr[DCTSIZE*3] = dcval;
  168927. continue;
  168928. }
  168929. /* Even part */
  168930. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  168931. tmp0 <<= (CONST_BITS+1);
  168932. z2 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  168933. z3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  168934. tmp2 = MULTIPLY(z2, FIX_1_847759065) + MULTIPLY(z3, - FIX_0_765366865);
  168935. tmp10 = tmp0 + tmp2;
  168936. tmp12 = tmp0 - tmp2;
  168937. /* Odd part */
  168938. z1 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  168939. z2 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  168940. z3 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  168941. z4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  168942. tmp0 = MULTIPLY(z1, - FIX_0_211164243) /* sqrt(2) * (c3-c1) */
  168943. + MULTIPLY(z2, FIX_1_451774981) /* sqrt(2) * (c3+c7) */
  168944. + MULTIPLY(z3, - FIX_2_172734803) /* sqrt(2) * (-c1-c5) */
  168945. + MULTIPLY(z4, FIX_1_061594337); /* sqrt(2) * (c5+c7) */
  168946. tmp2 = MULTIPLY(z1, - FIX_0_509795579) /* sqrt(2) * (c7-c5) */
  168947. + MULTIPLY(z2, - FIX_0_601344887) /* sqrt(2) * (c5-c1) */
  168948. + MULTIPLY(z3, FIX_0_899976223) /* sqrt(2) * (c3-c7) */
  168949. + MULTIPLY(z4, FIX_2_562915447); /* sqrt(2) * (c1+c3) */
  168950. /* Final output stage */
  168951. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp2, CONST_BITS-PASS1_BITS+1);
  168952. wsptr[DCTSIZE*3] = (int) DESCALE(tmp10 - tmp2, CONST_BITS-PASS1_BITS+1);
  168953. wsptr[DCTSIZE*1] = (int) DESCALE(tmp12 + tmp0, CONST_BITS-PASS1_BITS+1);
  168954. wsptr[DCTSIZE*2] = (int) DESCALE(tmp12 - tmp0, CONST_BITS-PASS1_BITS+1);
  168955. }
  168956. /* Pass 2: process 4 rows from work array, store into output array. */
  168957. wsptr = workspace;
  168958. for (ctr = 0; ctr < 4; ctr++) {
  168959. outptr = output_buf[ctr] + output_col;
  168960. /* It's not clear whether a zero row test is worthwhile here ... */
  168961. #ifndef NO_ZERO_ROW_TEST
  168962. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 &&
  168963. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  168964. /* AC terms all zero */
  168965. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  168966. & RANGE_MASK];
  168967. outptr[0] = dcval;
  168968. outptr[1] = dcval;
  168969. outptr[2] = dcval;
  168970. outptr[3] = dcval;
  168971. wsptr += DCTSIZE; /* advance pointer to next row */
  168972. continue;
  168973. }
  168974. #endif
  168975. /* Even part */
  168976. tmp0 = ((INT32) wsptr[0]) << (CONST_BITS+1);
  168977. tmp2 = MULTIPLY((INT32) wsptr[2], FIX_1_847759065)
  168978. + MULTIPLY((INT32) wsptr[6], - FIX_0_765366865);
  168979. tmp10 = tmp0 + tmp2;
  168980. tmp12 = tmp0 - tmp2;
  168981. /* Odd part */
  168982. z1 = (INT32) wsptr[7];
  168983. z2 = (INT32) wsptr[5];
  168984. z3 = (INT32) wsptr[3];
  168985. z4 = (INT32) wsptr[1];
  168986. tmp0 = MULTIPLY(z1, - FIX_0_211164243) /* sqrt(2) * (c3-c1) */
  168987. + MULTIPLY(z2, FIX_1_451774981) /* sqrt(2) * (c3+c7) */
  168988. + MULTIPLY(z3, - FIX_2_172734803) /* sqrt(2) * (-c1-c5) */
  168989. + MULTIPLY(z4, FIX_1_061594337); /* sqrt(2) * (c5+c7) */
  168990. tmp2 = MULTIPLY(z1, - FIX_0_509795579) /* sqrt(2) * (c7-c5) */
  168991. + MULTIPLY(z2, - FIX_0_601344887) /* sqrt(2) * (c5-c1) */
  168992. + MULTIPLY(z3, FIX_0_899976223) /* sqrt(2) * (c3-c7) */
  168993. + MULTIPLY(z4, FIX_2_562915447); /* sqrt(2) * (c1+c3) */
  168994. /* Final output stage */
  168995. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp2,
  168996. CONST_BITS+PASS1_BITS+3+1)
  168997. & RANGE_MASK];
  168998. outptr[3] = range_limit[(int) DESCALE(tmp10 - tmp2,
  168999. CONST_BITS+PASS1_BITS+3+1)
  169000. & RANGE_MASK];
  169001. outptr[1] = range_limit[(int) DESCALE(tmp12 + tmp0,
  169002. CONST_BITS+PASS1_BITS+3+1)
  169003. & RANGE_MASK];
  169004. outptr[2] = range_limit[(int) DESCALE(tmp12 - tmp0,
  169005. CONST_BITS+PASS1_BITS+3+1)
  169006. & RANGE_MASK];
  169007. wsptr += DCTSIZE; /* advance pointer to next row */
  169008. }
  169009. }
  169010. /*
  169011. * Perform dequantization and inverse DCT on one block of coefficients,
  169012. * producing a reduced-size 2x2 output block.
  169013. */
  169014. GLOBAL(void)
  169015. jpeg_idct_2x2 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  169016. JCOEFPTR coef_block,
  169017. JSAMPARRAY output_buf, JDIMENSION output_col)
  169018. {
  169019. INT32 tmp0, tmp10, z1;
  169020. JCOEFPTR inptr;
  169021. ISLOW_MULT_TYPE * quantptr;
  169022. int * wsptr;
  169023. JSAMPROW outptr;
  169024. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  169025. int ctr;
  169026. int workspace[DCTSIZE*2]; /* buffers data between passes */
  169027. SHIFT_TEMPS
  169028. /* Pass 1: process columns from input, store into work array. */
  169029. inptr = coef_block;
  169030. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  169031. wsptr = workspace;
  169032. for (ctr = DCTSIZE; ctr > 0; inptr++, quantptr++, wsptr++, ctr--) {
  169033. /* Don't bother to process columns 2,4,6 */
  169034. if (ctr == DCTSIZE-2 || ctr == DCTSIZE-4 || ctr == DCTSIZE-6)
  169035. continue;
  169036. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*3] == 0 &&
  169037. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*7] == 0) {
  169038. /* AC terms all zero; we need not examine terms 2,4,6 for 2x2 output */
  169039. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  169040. wsptr[DCTSIZE*0] = dcval;
  169041. wsptr[DCTSIZE*1] = dcval;
  169042. continue;
  169043. }
  169044. /* Even part */
  169045. z1 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  169046. tmp10 = z1 << (CONST_BITS+2);
  169047. /* Odd part */
  169048. z1 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  169049. tmp0 = MULTIPLY(z1, - FIX_0_720959822); /* sqrt(2) * (c7-c5+c3-c1) */
  169050. z1 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  169051. tmp0 += MULTIPLY(z1, FIX_0_850430095); /* sqrt(2) * (-c1+c3+c5+c7) */
  169052. z1 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  169053. tmp0 += MULTIPLY(z1, - FIX_1_272758580); /* sqrt(2) * (-c1+c3-c5-c7) */
  169054. z1 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  169055. tmp0 += MULTIPLY(z1, FIX_3_624509785); /* sqrt(2) * (c1+c3+c5+c7) */
  169056. /* Final output stage */
  169057. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp0, CONST_BITS-PASS1_BITS+2);
  169058. wsptr[DCTSIZE*1] = (int) DESCALE(tmp10 - tmp0, CONST_BITS-PASS1_BITS+2);
  169059. }
  169060. /* Pass 2: process 2 rows from work array, store into output array. */
  169061. wsptr = workspace;
  169062. for (ctr = 0; ctr < 2; ctr++) {
  169063. outptr = output_buf[ctr] + output_col;
  169064. /* It's not clear whether a zero row test is worthwhile here ... */
  169065. #ifndef NO_ZERO_ROW_TEST
  169066. if (wsptr[1] == 0 && wsptr[3] == 0 && wsptr[5] == 0 && wsptr[7] == 0) {
  169067. /* AC terms all zero */
  169068. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  169069. & RANGE_MASK];
  169070. outptr[0] = dcval;
  169071. outptr[1] = dcval;
  169072. wsptr += DCTSIZE; /* advance pointer to next row */
  169073. continue;
  169074. }
  169075. #endif
  169076. /* Even part */
  169077. tmp10 = ((INT32) wsptr[0]) << (CONST_BITS+2);
  169078. /* Odd part */
  169079. tmp0 = MULTIPLY((INT32) wsptr[7], - FIX_0_720959822) /* sqrt(2) * (c7-c5+c3-c1) */
  169080. + MULTIPLY((INT32) wsptr[5], FIX_0_850430095) /* sqrt(2) * (-c1+c3+c5+c7) */
  169081. + MULTIPLY((INT32) wsptr[3], - FIX_1_272758580) /* sqrt(2) * (-c1+c3-c5-c7) */
  169082. + MULTIPLY((INT32) wsptr[1], FIX_3_624509785); /* sqrt(2) * (c1+c3+c5+c7) */
  169083. /* Final output stage */
  169084. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp0,
  169085. CONST_BITS+PASS1_BITS+3+2)
  169086. & RANGE_MASK];
  169087. outptr[1] = range_limit[(int) DESCALE(tmp10 - tmp0,
  169088. CONST_BITS+PASS1_BITS+3+2)
  169089. & RANGE_MASK];
  169090. wsptr += DCTSIZE; /* advance pointer to next row */
  169091. }
  169092. }
  169093. /*
  169094. * Perform dequantization and inverse DCT on one block of coefficients,
  169095. * producing a reduced-size 1x1 output block.
  169096. */
  169097. GLOBAL(void)
  169098. jpeg_idct_1x1 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  169099. JCOEFPTR coef_block,
  169100. JSAMPARRAY output_buf, JDIMENSION output_col)
  169101. {
  169102. int dcval;
  169103. ISLOW_MULT_TYPE * quantptr;
  169104. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  169105. SHIFT_TEMPS
  169106. /* We hardly need an inverse DCT routine for this: just take the
  169107. * average pixel value, which is one-eighth of the DC coefficient.
  169108. */
  169109. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  169110. dcval = DEQUANTIZE(coef_block[0], quantptr[0]);
  169111. dcval = (int) DESCALE((INT32) dcval, 3);
  169112. output_buf[0][output_col] = range_limit[dcval & RANGE_MASK];
  169113. }
  169114. #endif /* IDCT_SCALING_SUPPORTED */
  169115. /********* End of inlined file: jidctred.c *********/
  169116. /********* Start of inlined file: jmemmgr.c *********/
  169117. #define JPEG_INTERNALS
  169118. #define AM_MEMORY_MANAGER /* we define jvirt_Xarray_control structs */
  169119. /********* Start of inlined file: jmemsys.h *********/
  169120. #ifndef __jmemsys_h__
  169121. #define __jmemsys_h__
  169122. /* Short forms of external names for systems with brain-damaged linkers. */
  169123. #ifdef NEED_SHORT_EXTERNAL_NAMES
  169124. #define jpeg_get_small jGetSmall
  169125. #define jpeg_free_small jFreeSmall
  169126. #define jpeg_get_large jGetLarge
  169127. #define jpeg_free_large jFreeLarge
  169128. #define jpeg_mem_available jMemAvail
  169129. #define jpeg_open_backing_store jOpenBackStore
  169130. #define jpeg_mem_init jMemInit
  169131. #define jpeg_mem_term jMemTerm
  169132. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  169133. /*
  169134. * These two functions are used to allocate and release small chunks of
  169135. * memory. (Typically the total amount requested through jpeg_get_small is
  169136. * no more than 20K or so; this will be requested in chunks of a few K each.)
  169137. * Behavior should be the same as for the standard library functions malloc
  169138. * and free; in particular, jpeg_get_small must return NULL on failure.
  169139. * On most systems, these ARE malloc and free. jpeg_free_small is passed the
  169140. * size of the object being freed, just in case it's needed.
  169141. * On an 80x86 machine using small-data memory model, these manage near heap.
  169142. */
  169143. EXTERN(void *) jpeg_get_small JPP((j_common_ptr cinfo, size_t sizeofobject));
  169144. EXTERN(void) jpeg_free_small JPP((j_common_ptr cinfo, void * object,
  169145. size_t sizeofobject));
  169146. /*
  169147. * These two functions are used to allocate and release large chunks of
  169148. * memory (up to the total free space designated by jpeg_mem_available).
  169149. * The interface is the same as above, except that on an 80x86 machine,
  169150. * far pointers are used. On most other machines these are identical to
  169151. * the jpeg_get/free_small routines; but we keep them separate anyway,
  169152. * in case a different allocation strategy is desirable for large chunks.
  169153. */
  169154. EXTERN(void FAR *) jpeg_get_large JPP((j_common_ptr cinfo,
  169155. size_t sizeofobject));
  169156. EXTERN(void) jpeg_free_large JPP((j_common_ptr cinfo, void FAR * object,
  169157. size_t sizeofobject));
  169158. /*
  169159. * The macro MAX_ALLOC_CHUNK designates the maximum number of bytes that may
  169160. * be requested in a single call to jpeg_get_large (and jpeg_get_small for that
  169161. * matter, but that case should never come into play). This macro is needed
  169162. * to model the 64Kb-segment-size limit of far addressing on 80x86 machines.
  169163. * On those machines, we expect that jconfig.h will provide a proper value.
  169164. * On machines with 32-bit flat address spaces, any large constant may be used.
  169165. *
  169166. * NB: jmemmgr.c expects that MAX_ALLOC_CHUNK will be representable as type
  169167. * size_t and will be a multiple of sizeof(align_type).
  169168. */
  169169. #ifndef MAX_ALLOC_CHUNK /* may be overridden in jconfig.h */
  169170. #define MAX_ALLOC_CHUNK 1000000000L
  169171. #endif
  169172. /*
  169173. * This routine computes the total space still available for allocation by
  169174. * jpeg_get_large. If more space than this is needed, backing store will be
  169175. * used. NOTE: any memory already allocated must not be counted.
  169176. *
  169177. * There is a minimum space requirement, corresponding to the minimum
  169178. * feasible buffer sizes; jmemmgr.c will request that much space even if
  169179. * jpeg_mem_available returns zero. The maximum space needed, enough to hold
  169180. * all working storage in memory, is also passed in case it is useful.
  169181. * Finally, the total space already allocated is passed. If no better
  169182. * method is available, cinfo->mem->max_memory_to_use - already_allocated
  169183. * is often a suitable calculation.
  169184. *
  169185. * It is OK for jpeg_mem_available to underestimate the space available
  169186. * (that'll just lead to more backing-store access than is really necessary).
  169187. * However, an overestimate will lead to failure. Hence it's wise to subtract
  169188. * a slop factor from the true available space. 5% should be enough.
  169189. *
  169190. * On machines with lots of virtual memory, any large constant may be returned.
  169191. * Conversely, zero may be returned to always use the minimum amount of memory.
  169192. */
  169193. EXTERN(long) jpeg_mem_available JPP((j_common_ptr cinfo,
  169194. long min_bytes_needed,
  169195. long max_bytes_needed,
  169196. long already_allocated));
  169197. /*
  169198. * This structure holds whatever state is needed to access a single
  169199. * backing-store object. The read/write/close method pointers are called
  169200. * by jmemmgr.c to manipulate the backing-store object; all other fields
  169201. * are private to the system-dependent backing store routines.
  169202. */
  169203. #define TEMP_NAME_LENGTH 64 /* max length of a temporary file's name */
  169204. #ifdef USE_MSDOS_MEMMGR /* DOS-specific junk */
  169205. typedef unsigned short XMSH; /* type of extended-memory handles */
  169206. typedef unsigned short EMSH; /* type of expanded-memory handles */
  169207. typedef union {
  169208. short file_handle; /* DOS file handle if it's a temp file */
  169209. XMSH xms_handle; /* handle if it's a chunk of XMS */
  169210. EMSH ems_handle; /* handle if it's a chunk of EMS */
  169211. } handle_union;
  169212. #endif /* USE_MSDOS_MEMMGR */
  169213. #ifdef USE_MAC_MEMMGR /* Mac-specific junk */
  169214. #include <Files.h>
  169215. #endif /* USE_MAC_MEMMGR */
  169216. //typedef struct backing_store_struct * backing_store_ptr;
  169217. typedef struct backing_store_struct {
  169218. /* Methods for reading/writing/closing this backing-store object */
  169219. JMETHOD(void, read_backing_store, (j_common_ptr cinfo,
  169220. struct backing_store_struct *info,
  169221. void FAR * buffer_address,
  169222. long file_offset, long byte_count));
  169223. JMETHOD(void, write_backing_store, (j_common_ptr cinfo,
  169224. struct backing_store_struct *info,
  169225. void FAR * buffer_address,
  169226. long file_offset, long byte_count));
  169227. JMETHOD(void, close_backing_store, (j_common_ptr cinfo,
  169228. struct backing_store_struct *info));
  169229. /* Private fields for system-dependent backing-store management */
  169230. #ifdef USE_MSDOS_MEMMGR
  169231. /* For the MS-DOS manager (jmemdos.c), we need: */
  169232. handle_union handle; /* reference to backing-store storage object */
  169233. char temp_name[TEMP_NAME_LENGTH]; /* name if it's a file */
  169234. #else
  169235. #ifdef USE_MAC_MEMMGR
  169236. /* For the Mac manager (jmemmac.c), we need: */
  169237. short temp_file; /* file reference number to temp file */
  169238. FSSpec tempSpec; /* the FSSpec for the temp file */
  169239. char temp_name[TEMP_NAME_LENGTH]; /* name if it's a file */
  169240. #else
  169241. /* For a typical implementation with temp files, we need: */
  169242. FILE * temp_file; /* stdio reference to temp file */
  169243. char temp_name[TEMP_NAME_LENGTH]; /* name of temp file */
  169244. #endif
  169245. #endif
  169246. } backing_store_info;
  169247. /*
  169248. * Initial opening of a backing-store object. This must fill in the
  169249. * read/write/close pointers in the object. The read/write routines
  169250. * may take an error exit if the specified maximum file size is exceeded.
  169251. * (If jpeg_mem_available always returns a large value, this routine can
  169252. * just take an error exit.)
  169253. */
  169254. EXTERN(void) jpeg_open_backing_store JPP((j_common_ptr cinfo,
  169255. struct backing_store_struct *info,
  169256. long total_bytes_needed));
  169257. /*
  169258. * These routines take care of any system-dependent initialization and
  169259. * cleanup required. jpeg_mem_init will be called before anything is
  169260. * allocated (and, therefore, nothing in cinfo is of use except the error
  169261. * manager pointer). It should return a suitable default value for
  169262. * max_memory_to_use; this may subsequently be overridden by the surrounding
  169263. * application. (Note that max_memory_to_use is only important if
  169264. * jpeg_mem_available chooses to consult it ... no one else will.)
  169265. * jpeg_mem_term may assume that all requested memory has been freed and that
  169266. * all opened backing-store objects have been closed.
  169267. */
  169268. EXTERN(long) jpeg_mem_init JPP((j_common_ptr cinfo));
  169269. EXTERN(void) jpeg_mem_term JPP((j_common_ptr cinfo));
  169270. #endif
  169271. /********* End of inlined file: jmemsys.h *********/
  169272. /* import the system-dependent declarations */
  169273. #ifndef NO_GETENV
  169274. #ifndef HAVE_STDLIB_H /* <stdlib.h> should declare getenv() */
  169275. extern char * getenv JPP((const char * name));
  169276. #endif
  169277. #endif
  169278. /*
  169279. * Some important notes:
  169280. * The allocation routines provided here must never return NULL.
  169281. * They should exit to error_exit if unsuccessful.
  169282. *
  169283. * It's not a good idea to try to merge the sarray and barray routines,
  169284. * even though they are textually almost the same, because samples are
  169285. * usually stored as bytes while coefficients are shorts or ints. Thus,
  169286. * in machines where byte pointers have a different representation from
  169287. * word pointers, the resulting machine code could not be the same.
  169288. */
  169289. /*
  169290. * Many machines require storage alignment: longs must start on 4-byte
  169291. * boundaries, doubles on 8-byte boundaries, etc. On such machines, malloc()
  169292. * always returns pointers that are multiples of the worst-case alignment
  169293. * requirement, and we had better do so too.
  169294. * There isn't any really portable way to determine the worst-case alignment
  169295. * requirement. This module assumes that the alignment requirement is
  169296. * multiples of sizeof(ALIGN_TYPE).
  169297. * By default, we define ALIGN_TYPE as double. This is necessary on some
  169298. * workstations (where doubles really do need 8-byte alignment) and will work
  169299. * fine on nearly everything. If your machine has lesser alignment needs,
  169300. * you can save a few bytes by making ALIGN_TYPE smaller.
  169301. * The only place I know of where this will NOT work is certain Macintosh
  169302. * 680x0 compilers that define double as a 10-byte IEEE extended float.
  169303. * Doing 10-byte alignment is counterproductive because longwords won't be
  169304. * aligned well. Put "#define ALIGN_TYPE long" in jconfig.h if you have
  169305. * such a compiler.
  169306. */
  169307. #ifndef ALIGN_TYPE /* so can override from jconfig.h */
  169308. #define ALIGN_TYPE double
  169309. #endif
  169310. /*
  169311. * We allocate objects from "pools", where each pool is gotten with a single
  169312. * request to jpeg_get_small() or jpeg_get_large(). There is no per-object
  169313. * overhead within a pool, except for alignment padding. Each pool has a
  169314. * header with a link to the next pool of the same class.
  169315. * Small and large pool headers are identical except that the latter's
  169316. * link pointer must be FAR on 80x86 machines.
  169317. * Notice that the "real" header fields are union'ed with a dummy ALIGN_TYPE
  169318. * field. This forces the compiler to make SIZEOF(small_pool_hdr) a multiple
  169319. * of the alignment requirement of ALIGN_TYPE.
  169320. */
  169321. typedef union small_pool_struct * small_pool_ptr;
  169322. typedef union small_pool_struct {
  169323. struct {
  169324. small_pool_ptr next; /* next in list of pools */
  169325. size_t bytes_used; /* how many bytes already used within pool */
  169326. size_t bytes_left; /* bytes still available in this pool */
  169327. } hdr;
  169328. ALIGN_TYPE dummy; /* included in union to ensure alignment */
  169329. } small_pool_hdr;
  169330. typedef union large_pool_struct FAR * large_pool_ptr;
  169331. typedef union large_pool_struct {
  169332. struct {
  169333. large_pool_ptr next; /* next in list of pools */
  169334. size_t bytes_used; /* how many bytes already used within pool */
  169335. size_t bytes_left; /* bytes still available in this pool */
  169336. } hdr;
  169337. ALIGN_TYPE dummy; /* included in union to ensure alignment */
  169338. } large_pool_hdr;
  169339. /*
  169340. * Here is the full definition of a memory manager object.
  169341. */
  169342. typedef struct {
  169343. struct jpeg_memory_mgr pub; /* public fields */
  169344. /* Each pool identifier (lifetime class) names a linked list of pools. */
  169345. small_pool_ptr small_list[JPOOL_NUMPOOLS];
  169346. large_pool_ptr large_list[JPOOL_NUMPOOLS];
  169347. /* Since we only have one lifetime class of virtual arrays, only one
  169348. * linked list is necessary (for each datatype). Note that the virtual
  169349. * array control blocks being linked together are actually stored somewhere
  169350. * in the small-pool list.
  169351. */
  169352. jvirt_sarray_ptr virt_sarray_list;
  169353. jvirt_barray_ptr virt_barray_list;
  169354. /* This counts total space obtained from jpeg_get_small/large */
  169355. long total_space_allocated;
  169356. /* alloc_sarray and alloc_barray set this value for use by virtual
  169357. * array routines.
  169358. */
  169359. JDIMENSION last_rowsperchunk; /* from most recent alloc_sarray/barray */
  169360. } my_memory_mgr;
  169361. typedef my_memory_mgr * my_mem_ptr;
  169362. /*
  169363. * The control blocks for virtual arrays.
  169364. * Note that these blocks are allocated in the "small" pool area.
  169365. * System-dependent info for the associated backing store (if any) is hidden
  169366. * inside the backing_store_info struct.
  169367. */
  169368. struct jvirt_sarray_control {
  169369. JSAMPARRAY mem_buffer; /* => the in-memory buffer */
  169370. JDIMENSION rows_in_array; /* total virtual array height */
  169371. JDIMENSION samplesperrow; /* width of array (and of memory buffer) */
  169372. JDIMENSION maxaccess; /* max rows accessed by access_virt_sarray */
  169373. JDIMENSION rows_in_mem; /* height of memory buffer */
  169374. JDIMENSION rowsperchunk; /* allocation chunk size in mem_buffer */
  169375. JDIMENSION cur_start_row; /* first logical row # in the buffer */
  169376. JDIMENSION first_undef_row; /* row # of first uninitialized row */
  169377. boolean pre_zero; /* pre-zero mode requested? */
  169378. boolean dirty; /* do current buffer contents need written? */
  169379. boolean b_s_open; /* is backing-store data valid? */
  169380. jvirt_sarray_ptr next; /* link to next virtual sarray control block */
  169381. backing_store_info b_s_info; /* System-dependent control info */
  169382. };
  169383. struct jvirt_barray_control {
  169384. JBLOCKARRAY mem_buffer; /* => the in-memory buffer */
  169385. JDIMENSION rows_in_array; /* total virtual array height */
  169386. JDIMENSION blocksperrow; /* width of array (and of memory buffer) */
  169387. JDIMENSION maxaccess; /* max rows accessed by access_virt_barray */
  169388. JDIMENSION rows_in_mem; /* height of memory buffer */
  169389. JDIMENSION rowsperchunk; /* allocation chunk size in mem_buffer */
  169390. JDIMENSION cur_start_row; /* first logical row # in the buffer */
  169391. JDIMENSION first_undef_row; /* row # of first uninitialized row */
  169392. boolean pre_zero; /* pre-zero mode requested? */
  169393. boolean dirty; /* do current buffer contents need written? */
  169394. boolean b_s_open; /* is backing-store data valid? */
  169395. jvirt_barray_ptr next; /* link to next virtual barray control block */
  169396. backing_store_info b_s_info; /* System-dependent control info */
  169397. };
  169398. #ifdef MEM_STATS /* optional extra stuff for statistics */
  169399. LOCAL(void)
  169400. print_mem_stats (j_common_ptr cinfo, int pool_id)
  169401. {
  169402. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  169403. small_pool_ptr shdr_ptr;
  169404. large_pool_ptr lhdr_ptr;
  169405. /* Since this is only a debugging stub, we can cheat a little by using
  169406. * fprintf directly rather than going through the trace message code.
  169407. * This is helpful because message parm array can't handle longs.
  169408. */
  169409. fprintf(stderr, "Freeing pool %d, total space = %ld\n",
  169410. pool_id, mem->total_space_allocated);
  169411. for (lhdr_ptr = mem->large_list[pool_id]; lhdr_ptr != NULL;
  169412. lhdr_ptr = lhdr_ptr->hdr.next) {
  169413. fprintf(stderr, " Large chunk used %ld\n",
  169414. (long) lhdr_ptr->hdr.bytes_used);
  169415. }
  169416. for (shdr_ptr = mem->small_list[pool_id]; shdr_ptr != NULL;
  169417. shdr_ptr = shdr_ptr->hdr.next) {
  169418. fprintf(stderr, " Small chunk used %ld free %ld\n",
  169419. (long) shdr_ptr->hdr.bytes_used,
  169420. (long) shdr_ptr->hdr.bytes_left);
  169421. }
  169422. }
  169423. #endif /* MEM_STATS */
  169424. LOCAL(void)
  169425. out_of_memory (j_common_ptr cinfo, int which)
  169426. /* Report an out-of-memory error and stop execution */
  169427. /* If we compiled MEM_STATS support, report alloc requests before dying */
  169428. {
  169429. #ifdef MEM_STATS
  169430. cinfo->err->trace_level = 2; /* force self_destruct to report stats */
  169431. #endif
  169432. ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, which);
  169433. }
  169434. /*
  169435. * Allocation of "small" objects.
  169436. *
  169437. * For these, we use pooled storage. When a new pool must be created,
  169438. * we try to get enough space for the current request plus a "slop" factor,
  169439. * where the slop will be the amount of leftover space in the new pool.
  169440. * The speed vs. space tradeoff is largely determined by the slop values.
  169441. * A different slop value is provided for each pool class (lifetime),
  169442. * and we also distinguish the first pool of a class from later ones.
  169443. * NOTE: the values given work fairly well on both 16- and 32-bit-int
  169444. * machines, but may be too small if longs are 64 bits or more.
  169445. */
  169446. static const size_t first_pool_slop[JPOOL_NUMPOOLS] =
  169447. {
  169448. 1600, /* first PERMANENT pool */
  169449. 16000 /* first IMAGE pool */
  169450. };
  169451. static const size_t extra_pool_slop[JPOOL_NUMPOOLS] =
  169452. {
  169453. 0, /* additional PERMANENT pools */
  169454. 5000 /* additional IMAGE pools */
  169455. };
  169456. #define MIN_SLOP 50 /* greater than 0 to avoid futile looping */
  169457. METHODDEF(void *)
  169458. alloc_small (j_common_ptr cinfo, int pool_id, size_t sizeofobject)
  169459. /* Allocate a "small" object */
  169460. {
  169461. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  169462. small_pool_ptr hdr_ptr, prev_hdr_ptr;
  169463. char * data_ptr;
  169464. size_t odd_bytes, min_request, slop;
  169465. /* Check for unsatisfiable request (do now to ensure no overflow below) */
  169466. if (sizeofobject > (size_t) (MAX_ALLOC_CHUNK-SIZEOF(small_pool_hdr)))
  169467. out_of_memory(cinfo, 1); /* request exceeds malloc's ability */
  169468. /* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */
  169469. odd_bytes = sizeofobject % SIZEOF(ALIGN_TYPE);
  169470. if (odd_bytes > 0)
  169471. sizeofobject += SIZEOF(ALIGN_TYPE) - odd_bytes;
  169472. /* See if space is available in any existing pool */
  169473. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  169474. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  169475. prev_hdr_ptr = NULL;
  169476. hdr_ptr = mem->small_list[pool_id];
  169477. while (hdr_ptr != NULL) {
  169478. if (hdr_ptr->hdr.bytes_left >= sizeofobject)
  169479. break; /* found pool with enough space */
  169480. prev_hdr_ptr = hdr_ptr;
  169481. hdr_ptr = hdr_ptr->hdr.next;
  169482. }
  169483. /* Time to make a new pool? */
  169484. if (hdr_ptr == NULL) {
  169485. /* min_request is what we need now, slop is what will be leftover */
  169486. min_request = sizeofobject + SIZEOF(small_pool_hdr);
  169487. if (prev_hdr_ptr == NULL) /* first pool in class? */
  169488. slop = first_pool_slop[pool_id];
  169489. else
  169490. slop = extra_pool_slop[pool_id];
  169491. /* Don't ask for more than MAX_ALLOC_CHUNK */
  169492. if (slop > (size_t) (MAX_ALLOC_CHUNK-min_request))
  169493. slop = (size_t) (MAX_ALLOC_CHUNK-min_request);
  169494. /* Try to get space, if fail reduce slop and try again */
  169495. for (;;) {
  169496. hdr_ptr = (small_pool_ptr) jpeg_get_small(cinfo, min_request + slop);
  169497. if (hdr_ptr != NULL)
  169498. break;
  169499. slop /= 2;
  169500. if (slop < MIN_SLOP) /* give up when it gets real small */
  169501. out_of_memory(cinfo, 2); /* jpeg_get_small failed */
  169502. }
  169503. mem->total_space_allocated += min_request + slop;
  169504. /* Success, initialize the new pool header and add to end of list */
  169505. hdr_ptr->hdr.next = NULL;
  169506. hdr_ptr->hdr.bytes_used = 0;
  169507. hdr_ptr->hdr.bytes_left = sizeofobject + slop;
  169508. if (prev_hdr_ptr == NULL) /* first pool in class? */
  169509. mem->small_list[pool_id] = hdr_ptr;
  169510. else
  169511. prev_hdr_ptr->hdr.next = hdr_ptr;
  169512. }
  169513. /* OK, allocate the object from the current pool */
  169514. data_ptr = (char *) (hdr_ptr + 1); /* point to first data byte in pool */
  169515. data_ptr += hdr_ptr->hdr.bytes_used; /* point to place for object */
  169516. hdr_ptr->hdr.bytes_used += sizeofobject;
  169517. hdr_ptr->hdr.bytes_left -= sizeofobject;
  169518. return (void *) data_ptr;
  169519. }
  169520. /*
  169521. * Allocation of "large" objects.
  169522. *
  169523. * The external semantics of these are the same as "small" objects,
  169524. * except that FAR pointers are used on 80x86. However the pool
  169525. * management heuristics are quite different. We assume that each
  169526. * request is large enough that it may as well be passed directly to
  169527. * jpeg_get_large; the pool management just links everything together
  169528. * so that we can free it all on demand.
  169529. * Note: the major use of "large" objects is in JSAMPARRAY and JBLOCKARRAY
  169530. * structures. The routines that create these structures (see below)
  169531. * deliberately bunch rows together to ensure a large request size.
  169532. */
  169533. METHODDEF(void FAR *)
  169534. alloc_large (j_common_ptr cinfo, int pool_id, size_t sizeofobject)
  169535. /* Allocate a "large" object */
  169536. {
  169537. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  169538. large_pool_ptr hdr_ptr;
  169539. size_t odd_bytes;
  169540. /* Check for unsatisfiable request (do now to ensure no overflow below) */
  169541. if (sizeofobject > (size_t) (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)))
  169542. out_of_memory(cinfo, 3); /* request exceeds malloc's ability */
  169543. /* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */
  169544. odd_bytes = sizeofobject % SIZEOF(ALIGN_TYPE);
  169545. if (odd_bytes > 0)
  169546. sizeofobject += SIZEOF(ALIGN_TYPE) - odd_bytes;
  169547. /* Always make a new pool */
  169548. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  169549. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  169550. hdr_ptr = (large_pool_ptr) jpeg_get_large(cinfo, sizeofobject +
  169551. SIZEOF(large_pool_hdr));
  169552. if (hdr_ptr == NULL)
  169553. out_of_memory(cinfo, 4); /* jpeg_get_large failed */
  169554. mem->total_space_allocated += sizeofobject + SIZEOF(large_pool_hdr);
  169555. /* Success, initialize the new pool header and add to list */
  169556. hdr_ptr->hdr.next = mem->large_list[pool_id];
  169557. /* We maintain space counts in each pool header for statistical purposes,
  169558. * even though they are not needed for allocation.
  169559. */
  169560. hdr_ptr->hdr.bytes_used = sizeofobject;
  169561. hdr_ptr->hdr.bytes_left = 0;
  169562. mem->large_list[pool_id] = hdr_ptr;
  169563. return (void FAR *) (hdr_ptr + 1); /* point to first data byte in pool */
  169564. }
  169565. /*
  169566. * Creation of 2-D sample arrays.
  169567. * The pointers are in near heap, the samples themselves in FAR heap.
  169568. *
  169569. * To minimize allocation overhead and to allow I/O of large contiguous
  169570. * blocks, we allocate the sample rows in groups of as many rows as possible
  169571. * without exceeding MAX_ALLOC_CHUNK total bytes per allocation request.
  169572. * NB: the virtual array control routines, later in this file, know about
  169573. * this chunking of rows. The rowsperchunk value is left in the mem manager
  169574. * object so that it can be saved away if this sarray is the workspace for
  169575. * a virtual array.
  169576. */
  169577. METHODDEF(JSAMPARRAY)
  169578. alloc_sarray (j_common_ptr cinfo, int pool_id,
  169579. JDIMENSION samplesperrow, JDIMENSION numrows)
  169580. /* Allocate a 2-D sample array */
  169581. {
  169582. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  169583. JSAMPARRAY result;
  169584. JSAMPROW workspace;
  169585. JDIMENSION rowsperchunk, currow, i;
  169586. long ltemp;
  169587. /* Calculate max # of rows allowed in one allocation chunk */
  169588. ltemp = (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)) /
  169589. ((long) samplesperrow * SIZEOF(JSAMPLE));
  169590. if (ltemp <= 0)
  169591. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  169592. if (ltemp < (long) numrows)
  169593. rowsperchunk = (JDIMENSION) ltemp;
  169594. else
  169595. rowsperchunk = numrows;
  169596. mem->last_rowsperchunk = rowsperchunk;
  169597. /* Get space for row pointers (small object) */
  169598. result = (JSAMPARRAY) alloc_small(cinfo, pool_id,
  169599. (size_t) (numrows * SIZEOF(JSAMPROW)));
  169600. /* Get the rows themselves (large objects) */
  169601. currow = 0;
  169602. while (currow < numrows) {
  169603. rowsperchunk = MIN(rowsperchunk, numrows - currow);
  169604. workspace = (JSAMPROW) alloc_large(cinfo, pool_id,
  169605. (size_t) ((size_t) rowsperchunk * (size_t) samplesperrow
  169606. * SIZEOF(JSAMPLE)));
  169607. for (i = rowsperchunk; i > 0; i--) {
  169608. result[currow++] = workspace;
  169609. workspace += samplesperrow;
  169610. }
  169611. }
  169612. return result;
  169613. }
  169614. /*
  169615. * Creation of 2-D coefficient-block arrays.
  169616. * This is essentially the same as the code for sample arrays, above.
  169617. */
  169618. METHODDEF(JBLOCKARRAY)
  169619. alloc_barray (j_common_ptr cinfo, int pool_id,
  169620. JDIMENSION blocksperrow, JDIMENSION numrows)
  169621. /* Allocate a 2-D coefficient-block array */
  169622. {
  169623. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  169624. JBLOCKARRAY result;
  169625. JBLOCKROW workspace;
  169626. JDIMENSION rowsperchunk, currow, i;
  169627. long ltemp;
  169628. /* Calculate max # of rows allowed in one allocation chunk */
  169629. ltemp = (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)) /
  169630. ((long) blocksperrow * SIZEOF(JBLOCK));
  169631. if (ltemp <= 0)
  169632. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  169633. if (ltemp < (long) numrows)
  169634. rowsperchunk = (JDIMENSION) ltemp;
  169635. else
  169636. rowsperchunk = numrows;
  169637. mem->last_rowsperchunk = rowsperchunk;
  169638. /* Get space for row pointers (small object) */
  169639. result = (JBLOCKARRAY) alloc_small(cinfo, pool_id,
  169640. (size_t) (numrows * SIZEOF(JBLOCKROW)));
  169641. /* Get the rows themselves (large objects) */
  169642. currow = 0;
  169643. while (currow < numrows) {
  169644. rowsperchunk = MIN(rowsperchunk, numrows - currow);
  169645. workspace = (JBLOCKROW) alloc_large(cinfo, pool_id,
  169646. (size_t) ((size_t) rowsperchunk * (size_t) blocksperrow
  169647. * SIZEOF(JBLOCK)));
  169648. for (i = rowsperchunk; i > 0; i--) {
  169649. result[currow++] = workspace;
  169650. workspace += blocksperrow;
  169651. }
  169652. }
  169653. return result;
  169654. }
  169655. /*
  169656. * About virtual array management:
  169657. *
  169658. * The above "normal" array routines are only used to allocate strip buffers
  169659. * (as wide as the image, but just a few rows high). Full-image-sized buffers
  169660. * are handled as "virtual" arrays. The array is still accessed a strip at a
  169661. * time, but the memory manager must save the whole array for repeated
  169662. * accesses. The intended implementation is that there is a strip buffer in
  169663. * memory (as high as is possible given the desired memory limit), plus a
  169664. * backing file that holds the rest of the array.
  169665. *
  169666. * The request_virt_array routines are told the total size of the image and
  169667. * the maximum number of rows that will be accessed at once. The in-memory
  169668. * buffer must be at least as large as the maxaccess value.
  169669. *
  169670. * The request routines create control blocks but not the in-memory buffers.
  169671. * That is postponed until realize_virt_arrays is called. At that time the
  169672. * total amount of space needed is known (approximately, anyway), so free
  169673. * memory can be divided up fairly.
  169674. *
  169675. * The access_virt_array routines are responsible for making a specific strip
  169676. * area accessible (after reading or writing the backing file, if necessary).
  169677. * Note that the access routines are told whether the caller intends to modify
  169678. * the accessed strip; during a read-only pass this saves having to rewrite
  169679. * data to disk. The access routines are also responsible for pre-zeroing
  169680. * any newly accessed rows, if pre-zeroing was requested.
  169681. *
  169682. * In current usage, the access requests are usually for nonoverlapping
  169683. * strips; that is, successive access start_row numbers differ by exactly
  169684. * num_rows = maxaccess. This means we can get good performance with simple
  169685. * buffer dump/reload logic, by making the in-memory buffer be a multiple
  169686. * of the access height; then there will never be accesses across bufferload
  169687. * boundaries. The code will still work with overlapping access requests,
  169688. * but it doesn't handle bufferload overlaps very efficiently.
  169689. */
  169690. METHODDEF(jvirt_sarray_ptr)
  169691. request_virt_sarray (j_common_ptr cinfo, int pool_id, boolean pre_zero,
  169692. JDIMENSION samplesperrow, JDIMENSION numrows,
  169693. JDIMENSION maxaccess)
  169694. /* Request a virtual 2-D sample array */
  169695. {
  169696. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  169697. jvirt_sarray_ptr result;
  169698. /* Only IMAGE-lifetime virtual arrays are currently supported */
  169699. if (pool_id != JPOOL_IMAGE)
  169700. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  169701. /* get control block */
  169702. result = (jvirt_sarray_ptr) alloc_small(cinfo, pool_id,
  169703. SIZEOF(struct jvirt_sarray_control));
  169704. result->mem_buffer = NULL; /* marks array not yet realized */
  169705. result->rows_in_array = numrows;
  169706. result->samplesperrow = samplesperrow;
  169707. result->maxaccess = maxaccess;
  169708. result->pre_zero = pre_zero;
  169709. result->b_s_open = FALSE; /* no associated backing-store object */
  169710. result->next = mem->virt_sarray_list; /* add to list of virtual arrays */
  169711. mem->virt_sarray_list = result;
  169712. return result;
  169713. }
  169714. METHODDEF(jvirt_barray_ptr)
  169715. request_virt_barray (j_common_ptr cinfo, int pool_id, boolean pre_zero,
  169716. JDIMENSION blocksperrow, JDIMENSION numrows,
  169717. JDIMENSION maxaccess)
  169718. /* Request a virtual 2-D coefficient-block array */
  169719. {
  169720. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  169721. jvirt_barray_ptr result;
  169722. /* Only IMAGE-lifetime virtual arrays are currently supported */
  169723. if (pool_id != JPOOL_IMAGE)
  169724. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  169725. /* get control block */
  169726. result = (jvirt_barray_ptr) alloc_small(cinfo, pool_id,
  169727. SIZEOF(struct jvirt_barray_control));
  169728. result->mem_buffer = NULL; /* marks array not yet realized */
  169729. result->rows_in_array = numrows;
  169730. result->blocksperrow = blocksperrow;
  169731. result->maxaccess = maxaccess;
  169732. result->pre_zero = pre_zero;
  169733. result->b_s_open = FALSE; /* no associated backing-store object */
  169734. result->next = mem->virt_barray_list; /* add to list of virtual arrays */
  169735. mem->virt_barray_list = result;
  169736. return result;
  169737. }
  169738. METHODDEF(void)
  169739. realize_virt_arrays (j_common_ptr cinfo)
  169740. /* Allocate the in-memory buffers for any unrealized virtual arrays */
  169741. {
  169742. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  169743. long space_per_minheight, maximum_space, avail_mem;
  169744. long minheights, max_minheights;
  169745. jvirt_sarray_ptr sptr;
  169746. jvirt_barray_ptr bptr;
  169747. /* Compute the minimum space needed (maxaccess rows in each buffer)
  169748. * and the maximum space needed (full image height in each buffer).
  169749. * These may be of use to the system-dependent jpeg_mem_available routine.
  169750. */
  169751. space_per_minheight = 0;
  169752. maximum_space = 0;
  169753. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  169754. if (sptr->mem_buffer == NULL) { /* if not realized yet */
  169755. space_per_minheight += (long) sptr->maxaccess *
  169756. (long) sptr->samplesperrow * SIZEOF(JSAMPLE);
  169757. maximum_space += (long) sptr->rows_in_array *
  169758. (long) sptr->samplesperrow * SIZEOF(JSAMPLE);
  169759. }
  169760. }
  169761. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  169762. if (bptr->mem_buffer == NULL) { /* if not realized yet */
  169763. space_per_minheight += (long) bptr->maxaccess *
  169764. (long) bptr->blocksperrow * SIZEOF(JBLOCK);
  169765. maximum_space += (long) bptr->rows_in_array *
  169766. (long) bptr->blocksperrow * SIZEOF(JBLOCK);
  169767. }
  169768. }
  169769. if (space_per_minheight <= 0)
  169770. return; /* no unrealized arrays, no work */
  169771. /* Determine amount of memory to actually use; this is system-dependent. */
  169772. avail_mem = jpeg_mem_available(cinfo, space_per_minheight, maximum_space,
  169773. mem->total_space_allocated);
  169774. /* If the maximum space needed is available, make all the buffers full
  169775. * height; otherwise parcel it out with the same number of minheights
  169776. * in each buffer.
  169777. */
  169778. if (avail_mem >= maximum_space)
  169779. max_minheights = 1000000000L;
  169780. else {
  169781. max_minheights = avail_mem / space_per_minheight;
  169782. /* If there doesn't seem to be enough space, try to get the minimum
  169783. * anyway. This allows a "stub" implementation of jpeg_mem_available().
  169784. */
  169785. if (max_minheights <= 0)
  169786. max_minheights = 1;
  169787. }
  169788. /* Allocate the in-memory buffers and initialize backing store as needed. */
  169789. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  169790. if (sptr->mem_buffer == NULL) { /* if not realized yet */
  169791. minheights = ((long) sptr->rows_in_array - 1L) / sptr->maxaccess + 1L;
  169792. if (minheights <= max_minheights) {
  169793. /* This buffer fits in memory */
  169794. sptr->rows_in_mem = sptr->rows_in_array;
  169795. } else {
  169796. /* It doesn't fit in memory, create backing store. */
  169797. sptr->rows_in_mem = (JDIMENSION) (max_minheights * sptr->maxaccess);
  169798. jpeg_open_backing_store(cinfo, & sptr->b_s_info,
  169799. (long) sptr->rows_in_array *
  169800. (long) sptr->samplesperrow *
  169801. (long) SIZEOF(JSAMPLE));
  169802. sptr->b_s_open = TRUE;
  169803. }
  169804. sptr->mem_buffer = alloc_sarray(cinfo, JPOOL_IMAGE,
  169805. sptr->samplesperrow, sptr->rows_in_mem);
  169806. sptr->rowsperchunk = mem->last_rowsperchunk;
  169807. sptr->cur_start_row = 0;
  169808. sptr->first_undef_row = 0;
  169809. sptr->dirty = FALSE;
  169810. }
  169811. }
  169812. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  169813. if (bptr->mem_buffer == NULL) { /* if not realized yet */
  169814. minheights = ((long) bptr->rows_in_array - 1L) / bptr->maxaccess + 1L;
  169815. if (minheights <= max_minheights) {
  169816. /* This buffer fits in memory */
  169817. bptr->rows_in_mem = bptr->rows_in_array;
  169818. } else {
  169819. /* It doesn't fit in memory, create backing store. */
  169820. bptr->rows_in_mem = (JDIMENSION) (max_minheights * bptr->maxaccess);
  169821. jpeg_open_backing_store(cinfo, & bptr->b_s_info,
  169822. (long) bptr->rows_in_array *
  169823. (long) bptr->blocksperrow *
  169824. (long) SIZEOF(JBLOCK));
  169825. bptr->b_s_open = TRUE;
  169826. }
  169827. bptr->mem_buffer = alloc_barray(cinfo, JPOOL_IMAGE,
  169828. bptr->blocksperrow, bptr->rows_in_mem);
  169829. bptr->rowsperchunk = mem->last_rowsperchunk;
  169830. bptr->cur_start_row = 0;
  169831. bptr->first_undef_row = 0;
  169832. bptr->dirty = FALSE;
  169833. }
  169834. }
  169835. }
  169836. LOCAL(void)
  169837. do_sarray_io (j_common_ptr cinfo, jvirt_sarray_ptr ptr, boolean writing)
  169838. /* Do backing store read or write of a virtual sample array */
  169839. {
  169840. long bytesperrow, file_offset, byte_count, rows, thisrow, i;
  169841. bytesperrow = (long) ptr->samplesperrow * SIZEOF(JSAMPLE);
  169842. file_offset = ptr->cur_start_row * bytesperrow;
  169843. /* Loop to read or write each allocation chunk in mem_buffer */
  169844. for (i = 0; i < (long) ptr->rows_in_mem; i += ptr->rowsperchunk) {
  169845. /* One chunk, but check for short chunk at end of buffer */
  169846. rows = MIN((long) ptr->rowsperchunk, (long) ptr->rows_in_mem - i);
  169847. /* Transfer no more than is currently defined */
  169848. thisrow = (long) ptr->cur_start_row + i;
  169849. rows = MIN(rows, (long) ptr->first_undef_row - thisrow);
  169850. /* Transfer no more than fits in file */
  169851. rows = MIN(rows, (long) ptr->rows_in_array - thisrow);
  169852. if (rows <= 0) /* this chunk might be past end of file! */
  169853. break;
  169854. byte_count = rows * bytesperrow;
  169855. if (writing)
  169856. (*ptr->b_s_info.write_backing_store) (cinfo, & ptr->b_s_info,
  169857. (void FAR *) ptr->mem_buffer[i],
  169858. file_offset, byte_count);
  169859. else
  169860. (*ptr->b_s_info.read_backing_store) (cinfo, & ptr->b_s_info,
  169861. (void FAR *) ptr->mem_buffer[i],
  169862. file_offset, byte_count);
  169863. file_offset += byte_count;
  169864. }
  169865. }
  169866. LOCAL(void)
  169867. do_barray_io (j_common_ptr cinfo, jvirt_barray_ptr ptr, boolean writing)
  169868. /* Do backing store read or write of a virtual coefficient-block array */
  169869. {
  169870. long bytesperrow, file_offset, byte_count, rows, thisrow, i;
  169871. bytesperrow = (long) ptr->blocksperrow * SIZEOF(JBLOCK);
  169872. file_offset = ptr->cur_start_row * bytesperrow;
  169873. /* Loop to read or write each allocation chunk in mem_buffer */
  169874. for (i = 0; i < (long) ptr->rows_in_mem; i += ptr->rowsperchunk) {
  169875. /* One chunk, but check for short chunk at end of buffer */
  169876. rows = MIN((long) ptr->rowsperchunk, (long) ptr->rows_in_mem - i);
  169877. /* Transfer no more than is currently defined */
  169878. thisrow = (long) ptr->cur_start_row + i;
  169879. rows = MIN(rows, (long) ptr->first_undef_row - thisrow);
  169880. /* Transfer no more than fits in file */
  169881. rows = MIN(rows, (long) ptr->rows_in_array - thisrow);
  169882. if (rows <= 0) /* this chunk might be past end of file! */
  169883. break;
  169884. byte_count = rows * bytesperrow;
  169885. if (writing)
  169886. (*ptr->b_s_info.write_backing_store) (cinfo, & ptr->b_s_info,
  169887. (void FAR *) ptr->mem_buffer[i],
  169888. file_offset, byte_count);
  169889. else
  169890. (*ptr->b_s_info.read_backing_store) (cinfo, & ptr->b_s_info,
  169891. (void FAR *) ptr->mem_buffer[i],
  169892. file_offset, byte_count);
  169893. file_offset += byte_count;
  169894. }
  169895. }
  169896. METHODDEF(JSAMPARRAY)
  169897. access_virt_sarray (j_common_ptr cinfo, jvirt_sarray_ptr ptr,
  169898. JDIMENSION start_row, JDIMENSION num_rows,
  169899. boolean writable)
  169900. /* Access the part of a virtual sample array starting at start_row */
  169901. /* and extending for num_rows rows. writable is true if */
  169902. /* caller intends to modify the accessed area. */
  169903. {
  169904. JDIMENSION end_row = start_row + num_rows;
  169905. JDIMENSION undef_row;
  169906. /* debugging check */
  169907. if (end_row > ptr->rows_in_array || num_rows > ptr->maxaccess ||
  169908. ptr->mem_buffer == NULL)
  169909. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  169910. /* Make the desired part of the virtual array accessible */
  169911. if (start_row < ptr->cur_start_row ||
  169912. end_row > ptr->cur_start_row+ptr->rows_in_mem) {
  169913. if (! ptr->b_s_open)
  169914. ERREXIT(cinfo, JERR_VIRTUAL_BUG);
  169915. /* Flush old buffer contents if necessary */
  169916. if (ptr->dirty) {
  169917. do_sarray_io(cinfo, ptr, TRUE);
  169918. ptr->dirty = FALSE;
  169919. }
  169920. /* Decide what part of virtual array to access.
  169921. * Algorithm: if target address > current window, assume forward scan,
  169922. * load starting at target address. If target address < current window,
  169923. * assume backward scan, load so that target area is top of window.
  169924. * Note that when switching from forward write to forward read, will have
  169925. * start_row = 0, so the limiting case applies and we load from 0 anyway.
  169926. */
  169927. if (start_row > ptr->cur_start_row) {
  169928. ptr->cur_start_row = start_row;
  169929. } else {
  169930. /* use long arithmetic here to avoid overflow & unsigned problems */
  169931. long ltemp;
  169932. ltemp = (long) end_row - (long) ptr->rows_in_mem;
  169933. if (ltemp < 0)
  169934. ltemp = 0; /* don't fall off front end of file */
  169935. ptr->cur_start_row = (JDIMENSION) ltemp;
  169936. }
  169937. /* Read in the selected part of the array.
  169938. * During the initial write pass, we will do no actual read
  169939. * because the selected part is all undefined.
  169940. */
  169941. do_sarray_io(cinfo, ptr, FALSE);
  169942. }
  169943. /* Ensure the accessed part of the array is defined; prezero if needed.
  169944. * To improve locality of access, we only prezero the part of the array
  169945. * that the caller is about to access, not the entire in-memory array.
  169946. */
  169947. if (ptr->first_undef_row < end_row) {
  169948. if (ptr->first_undef_row < start_row) {
  169949. if (writable) /* writer skipped over a section of array */
  169950. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  169951. undef_row = start_row; /* but reader is allowed to read ahead */
  169952. } else {
  169953. undef_row = ptr->first_undef_row;
  169954. }
  169955. if (writable)
  169956. ptr->first_undef_row = end_row;
  169957. if (ptr->pre_zero) {
  169958. size_t bytesperrow = (size_t) ptr->samplesperrow * SIZEOF(JSAMPLE);
  169959. undef_row -= ptr->cur_start_row; /* make indexes relative to buffer */
  169960. end_row -= ptr->cur_start_row;
  169961. while (undef_row < end_row) {
  169962. jzero_far((void FAR *) ptr->mem_buffer[undef_row], bytesperrow);
  169963. undef_row++;
  169964. }
  169965. } else {
  169966. if (! writable) /* reader looking at undefined data */
  169967. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  169968. }
  169969. }
  169970. /* Flag the buffer dirty if caller will write in it */
  169971. if (writable)
  169972. ptr->dirty = TRUE;
  169973. /* Return address of proper part of the buffer */
  169974. return ptr->mem_buffer + (start_row - ptr->cur_start_row);
  169975. }
  169976. METHODDEF(JBLOCKARRAY)
  169977. access_virt_barray (j_common_ptr cinfo, jvirt_barray_ptr ptr,
  169978. JDIMENSION start_row, JDIMENSION num_rows,
  169979. boolean writable)
  169980. /* Access the part of a virtual block array starting at start_row */
  169981. /* and extending for num_rows rows. writable is true if */
  169982. /* caller intends to modify the accessed area. */
  169983. {
  169984. JDIMENSION end_row = start_row + num_rows;
  169985. JDIMENSION undef_row;
  169986. /* debugging check */
  169987. if (end_row > ptr->rows_in_array || num_rows > ptr->maxaccess ||
  169988. ptr->mem_buffer == NULL)
  169989. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  169990. /* Make the desired part of the virtual array accessible */
  169991. if (start_row < ptr->cur_start_row ||
  169992. end_row > ptr->cur_start_row+ptr->rows_in_mem) {
  169993. if (! ptr->b_s_open)
  169994. ERREXIT(cinfo, JERR_VIRTUAL_BUG);
  169995. /* Flush old buffer contents if necessary */
  169996. if (ptr->dirty) {
  169997. do_barray_io(cinfo, ptr, TRUE);
  169998. ptr->dirty = FALSE;
  169999. }
  170000. /* Decide what part of virtual array to access.
  170001. * Algorithm: if target address > current window, assume forward scan,
  170002. * load starting at target address. If target address < current window,
  170003. * assume backward scan, load so that target area is top of window.
  170004. * Note that when switching from forward write to forward read, will have
  170005. * start_row = 0, so the limiting case applies and we load from 0 anyway.
  170006. */
  170007. if (start_row > ptr->cur_start_row) {
  170008. ptr->cur_start_row = start_row;
  170009. } else {
  170010. /* use long arithmetic here to avoid overflow & unsigned problems */
  170011. long ltemp;
  170012. ltemp = (long) end_row - (long) ptr->rows_in_mem;
  170013. if (ltemp < 0)
  170014. ltemp = 0; /* don't fall off front end of file */
  170015. ptr->cur_start_row = (JDIMENSION) ltemp;
  170016. }
  170017. /* Read in the selected part of the array.
  170018. * During the initial write pass, we will do no actual read
  170019. * because the selected part is all undefined.
  170020. */
  170021. do_barray_io(cinfo, ptr, FALSE);
  170022. }
  170023. /* Ensure the accessed part of the array is defined; prezero if needed.
  170024. * To improve locality of access, we only prezero the part of the array
  170025. * that the caller is about to access, not the entire in-memory array.
  170026. */
  170027. if (ptr->first_undef_row < end_row) {
  170028. if (ptr->first_undef_row < start_row) {
  170029. if (writable) /* writer skipped over a section of array */
  170030. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  170031. undef_row = start_row; /* but reader is allowed to read ahead */
  170032. } else {
  170033. undef_row = ptr->first_undef_row;
  170034. }
  170035. if (writable)
  170036. ptr->first_undef_row = end_row;
  170037. if (ptr->pre_zero) {
  170038. size_t bytesperrow = (size_t) ptr->blocksperrow * SIZEOF(JBLOCK);
  170039. undef_row -= ptr->cur_start_row; /* make indexes relative to buffer */
  170040. end_row -= ptr->cur_start_row;
  170041. while (undef_row < end_row) {
  170042. jzero_far((void FAR *) ptr->mem_buffer[undef_row], bytesperrow);
  170043. undef_row++;
  170044. }
  170045. } else {
  170046. if (! writable) /* reader looking at undefined data */
  170047. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  170048. }
  170049. }
  170050. /* Flag the buffer dirty if caller will write in it */
  170051. if (writable)
  170052. ptr->dirty = TRUE;
  170053. /* Return address of proper part of the buffer */
  170054. return ptr->mem_buffer + (start_row - ptr->cur_start_row);
  170055. }
  170056. /*
  170057. * Release all objects belonging to a specified pool.
  170058. */
  170059. METHODDEF(void)
  170060. free_pool (j_common_ptr cinfo, int pool_id)
  170061. {
  170062. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  170063. small_pool_ptr shdr_ptr;
  170064. large_pool_ptr lhdr_ptr;
  170065. size_t space_freed;
  170066. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  170067. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  170068. #ifdef MEM_STATS
  170069. if (cinfo->err->trace_level > 1)
  170070. print_mem_stats(cinfo, pool_id); /* print pool's memory usage statistics */
  170071. #endif
  170072. /* If freeing IMAGE pool, close any virtual arrays first */
  170073. if (pool_id == JPOOL_IMAGE) {
  170074. jvirt_sarray_ptr sptr;
  170075. jvirt_barray_ptr bptr;
  170076. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  170077. if (sptr->b_s_open) { /* there may be no backing store */
  170078. sptr->b_s_open = FALSE; /* prevent recursive close if error */
  170079. (*sptr->b_s_info.close_backing_store) (cinfo, & sptr->b_s_info);
  170080. }
  170081. }
  170082. mem->virt_sarray_list = NULL;
  170083. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  170084. if (bptr->b_s_open) { /* there may be no backing store */
  170085. bptr->b_s_open = FALSE; /* prevent recursive close if error */
  170086. (*bptr->b_s_info.close_backing_store) (cinfo, & bptr->b_s_info);
  170087. }
  170088. }
  170089. mem->virt_barray_list = NULL;
  170090. }
  170091. /* Release large objects */
  170092. lhdr_ptr = mem->large_list[pool_id];
  170093. mem->large_list[pool_id] = NULL;
  170094. while (lhdr_ptr != NULL) {
  170095. large_pool_ptr next_lhdr_ptr = lhdr_ptr->hdr.next;
  170096. space_freed = lhdr_ptr->hdr.bytes_used +
  170097. lhdr_ptr->hdr.bytes_left +
  170098. SIZEOF(large_pool_hdr);
  170099. jpeg_free_large(cinfo, (void FAR *) lhdr_ptr, space_freed);
  170100. mem->total_space_allocated -= space_freed;
  170101. lhdr_ptr = next_lhdr_ptr;
  170102. }
  170103. /* Release small objects */
  170104. shdr_ptr = mem->small_list[pool_id];
  170105. mem->small_list[pool_id] = NULL;
  170106. while (shdr_ptr != NULL) {
  170107. small_pool_ptr next_shdr_ptr = shdr_ptr->hdr.next;
  170108. space_freed = shdr_ptr->hdr.bytes_used +
  170109. shdr_ptr->hdr.bytes_left +
  170110. SIZEOF(small_pool_hdr);
  170111. jpeg_free_small(cinfo, (void *) shdr_ptr, space_freed);
  170112. mem->total_space_allocated -= space_freed;
  170113. shdr_ptr = next_shdr_ptr;
  170114. }
  170115. }
  170116. /*
  170117. * Close up shop entirely.
  170118. * Note that this cannot be called unless cinfo->mem is non-NULL.
  170119. */
  170120. METHODDEF(void)
  170121. self_destruct (j_common_ptr cinfo)
  170122. {
  170123. int pool;
  170124. /* Close all backing store, release all memory.
  170125. * Releasing pools in reverse order might help avoid fragmentation
  170126. * with some (brain-damaged) malloc libraries.
  170127. */
  170128. for (pool = JPOOL_NUMPOOLS-1; pool >= JPOOL_PERMANENT; pool--) {
  170129. free_pool(cinfo, pool);
  170130. }
  170131. /* Release the memory manager control block too. */
  170132. jpeg_free_small(cinfo, (void *) cinfo->mem, SIZEOF(my_memory_mgr));
  170133. cinfo->mem = NULL; /* ensures I will be called only once */
  170134. jpeg_mem_term(cinfo); /* system-dependent cleanup */
  170135. }
  170136. /*
  170137. * Memory manager initialization.
  170138. * When this is called, only the error manager pointer is valid in cinfo!
  170139. */
  170140. GLOBAL(void)
  170141. jinit_memory_mgr (j_common_ptr cinfo)
  170142. {
  170143. my_mem_ptr mem;
  170144. long max_to_use;
  170145. int pool;
  170146. size_t test_mac;
  170147. cinfo->mem = NULL; /* for safety if init fails */
  170148. /* Check for configuration errors.
  170149. * SIZEOF(ALIGN_TYPE) should be a power of 2; otherwise, it probably
  170150. * doesn't reflect any real hardware alignment requirement.
  170151. * The test is a little tricky: for X>0, X and X-1 have no one-bits
  170152. * in common if and only if X is a power of 2, ie has only one one-bit.
  170153. * Some compilers may give an "unreachable code" warning here; ignore it.
  170154. */
  170155. if ((SIZEOF(ALIGN_TYPE) & (SIZEOF(ALIGN_TYPE)-1)) != 0)
  170156. ERREXIT(cinfo, JERR_BAD_ALIGN_TYPE);
  170157. /* MAX_ALLOC_CHUNK must be representable as type size_t, and must be
  170158. * a multiple of SIZEOF(ALIGN_TYPE).
  170159. * Again, an "unreachable code" warning may be ignored here.
  170160. * But a "constant too large" warning means you need to fix MAX_ALLOC_CHUNK.
  170161. */
  170162. test_mac = (size_t) MAX_ALLOC_CHUNK;
  170163. if ((long) test_mac != MAX_ALLOC_CHUNK ||
  170164. (MAX_ALLOC_CHUNK % SIZEOF(ALIGN_TYPE)) != 0)
  170165. ERREXIT(cinfo, JERR_BAD_ALLOC_CHUNK);
  170166. max_to_use = jpeg_mem_init(cinfo); /* system-dependent initialization */
  170167. /* Attempt to allocate memory manager's control block */
  170168. mem = (my_mem_ptr) jpeg_get_small(cinfo, SIZEOF(my_memory_mgr));
  170169. if (mem == NULL) {
  170170. jpeg_mem_term(cinfo); /* system-dependent cleanup */
  170171. ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, 0);
  170172. }
  170173. /* OK, fill in the method pointers */
  170174. mem->pub.alloc_small = alloc_small;
  170175. mem->pub.alloc_large = alloc_large;
  170176. mem->pub.alloc_sarray = alloc_sarray;
  170177. mem->pub.alloc_barray = alloc_barray;
  170178. mem->pub.request_virt_sarray = request_virt_sarray;
  170179. mem->pub.request_virt_barray = request_virt_barray;
  170180. mem->pub.realize_virt_arrays = realize_virt_arrays;
  170181. mem->pub.access_virt_sarray = access_virt_sarray;
  170182. mem->pub.access_virt_barray = access_virt_barray;
  170183. mem->pub.free_pool = free_pool;
  170184. mem->pub.self_destruct = self_destruct;
  170185. /* Make MAX_ALLOC_CHUNK accessible to other modules */
  170186. mem->pub.max_alloc_chunk = MAX_ALLOC_CHUNK;
  170187. /* Initialize working state */
  170188. mem->pub.max_memory_to_use = max_to_use;
  170189. for (pool = JPOOL_NUMPOOLS-1; pool >= JPOOL_PERMANENT; pool--) {
  170190. mem->small_list[pool] = NULL;
  170191. mem->large_list[pool] = NULL;
  170192. }
  170193. mem->virt_sarray_list = NULL;
  170194. mem->virt_barray_list = NULL;
  170195. mem->total_space_allocated = SIZEOF(my_memory_mgr);
  170196. /* Declare ourselves open for business */
  170197. cinfo->mem = & mem->pub;
  170198. /* Check for an environment variable JPEGMEM; if found, override the
  170199. * default max_memory setting from jpeg_mem_init. Note that the
  170200. * surrounding application may again override this value.
  170201. * If your system doesn't support getenv(), define NO_GETENV to disable
  170202. * this feature.
  170203. */
  170204. #ifndef NO_GETENV
  170205. { char * memenv;
  170206. if ((memenv = getenv("JPEGMEM")) != NULL) {
  170207. char ch = 'x';
  170208. if (sscanf(memenv, "%ld%c", &max_to_use, &ch) > 0) {
  170209. if (ch == 'm' || ch == 'M')
  170210. max_to_use *= 1000L;
  170211. mem->pub.max_memory_to_use = max_to_use * 1000L;
  170212. }
  170213. }
  170214. }
  170215. #endif
  170216. }
  170217. /********* End of inlined file: jmemmgr.c *********/
  170218. /********* Start of inlined file: jmemnobs.c *********/
  170219. #define JPEG_INTERNALS
  170220. #ifndef HAVE_STDLIB_H /* <stdlib.h> should declare malloc(),free() */
  170221. extern void * malloc JPP((size_t size));
  170222. extern void free JPP((void *ptr));
  170223. #endif
  170224. /*
  170225. * Memory allocation and freeing are controlled by the regular library
  170226. * routines malloc() and free().
  170227. */
  170228. GLOBAL(void *)
  170229. jpeg_get_small (j_common_ptr cinfo, size_t sizeofobject)
  170230. {
  170231. return (void *) malloc(sizeofobject);
  170232. }
  170233. GLOBAL(void)
  170234. jpeg_free_small (j_common_ptr cinfo, void * object, size_t sizeofobject)
  170235. {
  170236. free(object);
  170237. }
  170238. /*
  170239. * "Large" objects are treated the same as "small" ones.
  170240. * NB: although we include FAR keywords in the routine declarations,
  170241. * this file won't actually work in 80x86 small/medium model; at least,
  170242. * you probably won't be able to process useful-size images in only 64KB.
  170243. */
  170244. GLOBAL(void FAR *)
  170245. jpeg_get_large (j_common_ptr cinfo, size_t sizeofobject)
  170246. {
  170247. return (void FAR *) malloc(sizeofobject);
  170248. }
  170249. GLOBAL(void)
  170250. jpeg_free_large (j_common_ptr cinfo, void FAR * object, size_t sizeofobject)
  170251. {
  170252. free(object);
  170253. }
  170254. /*
  170255. * This routine computes the total memory space available for allocation.
  170256. * Here we always say, "we got all you want bud!"
  170257. */
  170258. GLOBAL(long)
  170259. jpeg_mem_available (j_common_ptr cinfo, long min_bytes_needed,
  170260. long max_bytes_needed, long already_allocated)
  170261. {
  170262. return max_bytes_needed;
  170263. }
  170264. /*
  170265. * Backing store (temporary file) management.
  170266. * Since jpeg_mem_available always promised the moon,
  170267. * this should never be called and we can just error out.
  170268. */
  170269. GLOBAL(void)
  170270. jpeg_open_backing_store (j_common_ptr cinfo, struct backing_store_struct *info,
  170271. long total_bytes_needed)
  170272. {
  170273. ERREXIT(cinfo, JERR_NO_BACKING_STORE);
  170274. }
  170275. /*
  170276. * These routines take care of any system-dependent initialization and
  170277. * cleanup required. Here, there isn't any.
  170278. */
  170279. GLOBAL(long)
  170280. jpeg_mem_init (j_common_ptr cinfo)
  170281. {
  170282. return 0; /* just set max_memory_to_use to 0 */
  170283. }
  170284. GLOBAL(void)
  170285. jpeg_mem_term (j_common_ptr cinfo)
  170286. {
  170287. /* no work */
  170288. }
  170289. /********* End of inlined file: jmemnobs.c *********/
  170290. /********* Start of inlined file: jquant1.c *********/
  170291. #define JPEG_INTERNALS
  170292. #ifdef QUANT_1PASS_SUPPORTED
  170293. /*
  170294. * The main purpose of 1-pass quantization is to provide a fast, if not very
  170295. * high quality, colormapped output capability. A 2-pass quantizer usually
  170296. * gives better visual quality; however, for quantized grayscale output this
  170297. * quantizer is perfectly adequate. Dithering is highly recommended with this
  170298. * quantizer, though you can turn it off if you really want to.
  170299. *
  170300. * In 1-pass quantization the colormap must be chosen in advance of seeing the
  170301. * image. We use a map consisting of all combinations of Ncolors[i] color
  170302. * values for the i'th component. The Ncolors[] values are chosen so that
  170303. * their product, the total number of colors, is no more than that requested.
  170304. * (In most cases, the product will be somewhat less.)
  170305. *
  170306. * Since the colormap is orthogonal, the representative value for each color
  170307. * component can be determined without considering the other components;
  170308. * then these indexes can be combined into a colormap index by a standard
  170309. * N-dimensional-array-subscript calculation. Most of the arithmetic involved
  170310. * can be precalculated and stored in the lookup table colorindex[].
  170311. * colorindex[i][j] maps pixel value j in component i to the nearest
  170312. * representative value (grid plane) for that component; this index is
  170313. * multiplied by the array stride for component i, so that the
  170314. * index of the colormap entry closest to a given pixel value is just
  170315. * sum( colorindex[component-number][pixel-component-value] )
  170316. * Aside from being fast, this scheme allows for variable spacing between
  170317. * representative values with no additional lookup cost.
  170318. *
  170319. * If gamma correction has been applied in color conversion, it might be wise
  170320. * to adjust the color grid spacing so that the representative colors are
  170321. * equidistant in linear space. At this writing, gamma correction is not
  170322. * implemented by jdcolor, so nothing is done here.
  170323. */
  170324. /* Declarations for ordered dithering.
  170325. *
  170326. * We use a standard 16x16 ordered dither array. The basic concept of ordered
  170327. * dithering is described in many references, for instance Dale Schumacher's
  170328. * chapter II.2 of Graphics Gems II (James Arvo, ed. Academic Press, 1991).
  170329. * In place of Schumacher's comparisons against a "threshold" value, we add a
  170330. * "dither" value to the input pixel and then round the result to the nearest
  170331. * output value. The dither value is equivalent to (0.5 - threshold) times
  170332. * the distance between output values. For ordered dithering, we assume that
  170333. * the output colors are equally spaced; if not, results will probably be
  170334. * worse, since the dither may be too much or too little at a given point.
  170335. *
  170336. * The normal calculation would be to form pixel value + dither, range-limit
  170337. * this to 0..MAXJSAMPLE, and then index into the colorindex table as usual.
  170338. * We can skip the separate range-limiting step by extending the colorindex
  170339. * table in both directions.
  170340. */
  170341. #define ODITHER_SIZE 16 /* dimension of dither matrix */
  170342. /* NB: if ODITHER_SIZE is not a power of 2, ODITHER_MASK uses will break */
  170343. #define ODITHER_CELLS (ODITHER_SIZE*ODITHER_SIZE) /* # cells in matrix */
  170344. #define ODITHER_MASK (ODITHER_SIZE-1) /* mask for wrapping around counters */
  170345. typedef int ODITHER_MATRIX[ODITHER_SIZE][ODITHER_SIZE];
  170346. typedef int (*ODITHER_MATRIX_PTR)[ODITHER_SIZE];
  170347. static const UINT8 base_dither_matrix[ODITHER_SIZE][ODITHER_SIZE] = {
  170348. /* Bayer's order-4 dither array. Generated by the code given in
  170349. * Stephen Hawley's article "Ordered Dithering" in Graphics Gems I.
  170350. * The values in this array must range from 0 to ODITHER_CELLS-1.
  170351. */
  170352. { 0,192, 48,240, 12,204, 60,252, 3,195, 51,243, 15,207, 63,255 },
  170353. { 128, 64,176,112,140, 76,188,124,131, 67,179,115,143, 79,191,127 },
  170354. { 32,224, 16,208, 44,236, 28,220, 35,227, 19,211, 47,239, 31,223 },
  170355. { 160, 96,144, 80,172,108,156, 92,163, 99,147, 83,175,111,159, 95 },
  170356. { 8,200, 56,248, 4,196, 52,244, 11,203, 59,251, 7,199, 55,247 },
  170357. { 136, 72,184,120,132, 68,180,116,139, 75,187,123,135, 71,183,119 },
  170358. { 40,232, 24,216, 36,228, 20,212, 43,235, 27,219, 39,231, 23,215 },
  170359. { 168,104,152, 88,164,100,148, 84,171,107,155, 91,167,103,151, 87 },
  170360. { 2,194, 50,242, 14,206, 62,254, 1,193, 49,241, 13,205, 61,253 },
  170361. { 130, 66,178,114,142, 78,190,126,129, 65,177,113,141, 77,189,125 },
  170362. { 34,226, 18,210, 46,238, 30,222, 33,225, 17,209, 45,237, 29,221 },
  170363. { 162, 98,146, 82,174,110,158, 94,161, 97,145, 81,173,109,157, 93 },
  170364. { 10,202, 58,250, 6,198, 54,246, 9,201, 57,249, 5,197, 53,245 },
  170365. { 138, 74,186,122,134, 70,182,118,137, 73,185,121,133, 69,181,117 },
  170366. { 42,234, 26,218, 38,230, 22,214, 41,233, 25,217, 37,229, 21,213 },
  170367. { 170,106,154, 90,166,102,150, 86,169,105,153, 89,165,101,149, 85 }
  170368. };
  170369. /* Declarations for Floyd-Steinberg dithering.
  170370. *
  170371. * Errors are accumulated into the array fserrors[], at a resolution of
  170372. * 1/16th of a pixel count. The error at a given pixel is propagated
  170373. * to its not-yet-processed neighbors using the standard F-S fractions,
  170374. * ... (here) 7/16
  170375. * 3/16 5/16 1/16
  170376. * We work left-to-right on even rows, right-to-left on odd rows.
  170377. *
  170378. * We can get away with a single array (holding one row's worth of errors)
  170379. * by using it to store the current row's errors at pixel columns not yet
  170380. * processed, but the next row's errors at columns already processed. We
  170381. * need only a few extra variables to hold the errors immediately around the
  170382. * current column. (If we are lucky, those variables are in registers, but
  170383. * even if not, they're probably cheaper to access than array elements are.)
  170384. *
  170385. * The fserrors[] array is indexed [component#][position].
  170386. * We provide (#columns + 2) entries per component; the extra entry at each
  170387. * end saves us from special-casing the first and last pixels.
  170388. *
  170389. * Note: on a wide image, we might not have enough room in a PC's near data
  170390. * segment to hold the error array; so it is allocated with alloc_large.
  170391. */
  170392. #if BITS_IN_JSAMPLE == 8
  170393. typedef INT16 FSERROR; /* 16 bits should be enough */
  170394. typedef int LOCFSERROR; /* use 'int' for calculation temps */
  170395. #else
  170396. typedef INT32 FSERROR; /* may need more than 16 bits */
  170397. typedef INT32 LOCFSERROR; /* be sure calculation temps are big enough */
  170398. #endif
  170399. typedef FSERROR FAR *FSERRPTR; /* pointer to error array (in FAR storage!) */
  170400. /* Private subobject */
  170401. #define MAX_Q_COMPS 4 /* max components I can handle */
  170402. typedef struct {
  170403. struct jpeg_color_quantizer pub; /* public fields */
  170404. /* Initially allocated colormap is saved here */
  170405. JSAMPARRAY sv_colormap; /* The color map as a 2-D pixel array */
  170406. int sv_actual; /* number of entries in use */
  170407. JSAMPARRAY colorindex; /* Precomputed mapping for speed */
  170408. /* colorindex[i][j] = index of color closest to pixel value j in component i,
  170409. * premultiplied as described above. Since colormap indexes must fit into
  170410. * JSAMPLEs, the entries of this array will too.
  170411. */
  170412. boolean is_padded; /* is the colorindex padded for odither? */
  170413. int Ncolors[MAX_Q_COMPS]; /* # of values alloced to each component */
  170414. /* Variables for ordered dithering */
  170415. int row_index; /* cur row's vertical index in dither matrix */
  170416. ODITHER_MATRIX_PTR odither[MAX_Q_COMPS]; /* one dither array per component */
  170417. /* Variables for Floyd-Steinberg dithering */
  170418. FSERRPTR fserrors[MAX_Q_COMPS]; /* accumulated errors */
  170419. boolean on_odd_row; /* flag to remember which row we are on */
  170420. } my_cquantizer;
  170421. typedef my_cquantizer * my_cquantize_ptr;
  170422. /*
  170423. * Policy-making subroutines for create_colormap and create_colorindex.
  170424. * These routines determine the colormap to be used. The rest of the module
  170425. * only assumes that the colormap is orthogonal.
  170426. *
  170427. * * select_ncolors decides how to divvy up the available colors
  170428. * among the components.
  170429. * * output_value defines the set of representative values for a component.
  170430. * * largest_input_value defines the mapping from input values to
  170431. * representative values for a component.
  170432. * Note that the latter two routines may impose different policies for
  170433. * different components, though this is not currently done.
  170434. */
  170435. LOCAL(int)
  170436. select_ncolors (j_decompress_ptr cinfo, int Ncolors[])
  170437. /* Determine allocation of desired colors to components, */
  170438. /* and fill in Ncolors[] array to indicate choice. */
  170439. /* Return value is total number of colors (product of Ncolors[] values). */
  170440. {
  170441. int nc = cinfo->out_color_components; /* number of color components */
  170442. int max_colors = cinfo->desired_number_of_colors;
  170443. int total_colors, iroot, i, j;
  170444. boolean changed;
  170445. long temp;
  170446. static const int RGB_order[3] = { RGB_GREEN, RGB_RED, RGB_BLUE };
  170447. /* We can allocate at least the nc'th root of max_colors per component. */
  170448. /* Compute floor(nc'th root of max_colors). */
  170449. iroot = 1;
  170450. do {
  170451. iroot++;
  170452. temp = iroot; /* set temp = iroot ** nc */
  170453. for (i = 1; i < nc; i++)
  170454. temp *= iroot;
  170455. } while (temp <= (long) max_colors); /* repeat till iroot exceeds root */
  170456. iroot--; /* now iroot = floor(root) */
  170457. /* Must have at least 2 color values per component */
  170458. if (iroot < 2)
  170459. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, (int) temp);
  170460. /* Initialize to iroot color values for each component */
  170461. total_colors = 1;
  170462. for (i = 0; i < nc; i++) {
  170463. Ncolors[i] = iroot;
  170464. total_colors *= iroot;
  170465. }
  170466. /* We may be able to increment the count for one or more components without
  170467. * exceeding max_colors, though we know not all can be incremented.
  170468. * Sometimes, the first component can be incremented more than once!
  170469. * (Example: for 16 colors, we start at 2*2*2, go to 3*2*2, then 4*2*2.)
  170470. * In RGB colorspace, try to increment G first, then R, then B.
  170471. */
  170472. do {
  170473. changed = FALSE;
  170474. for (i = 0; i < nc; i++) {
  170475. j = (cinfo->out_color_space == JCS_RGB ? RGB_order[i] : i);
  170476. /* calculate new total_colors if Ncolors[j] is incremented */
  170477. temp = total_colors / Ncolors[j];
  170478. temp *= Ncolors[j]+1; /* done in long arith to avoid oflo */
  170479. if (temp > (long) max_colors)
  170480. break; /* won't fit, done with this pass */
  170481. Ncolors[j]++; /* OK, apply the increment */
  170482. total_colors = (int) temp;
  170483. changed = TRUE;
  170484. }
  170485. } while (changed);
  170486. return total_colors;
  170487. }
  170488. LOCAL(int)
  170489. output_value (j_decompress_ptr cinfo, int ci, int j, int maxj)
  170490. /* Return j'th output value, where j will range from 0 to maxj */
  170491. /* The output values must fall in 0..MAXJSAMPLE in increasing order */
  170492. {
  170493. /* We always provide values 0 and MAXJSAMPLE for each component;
  170494. * any additional values are equally spaced between these limits.
  170495. * (Forcing the upper and lower values to the limits ensures that
  170496. * dithering can't produce a color outside the selected gamut.)
  170497. */
  170498. return (int) (((INT32) j * MAXJSAMPLE + maxj/2) / maxj);
  170499. }
  170500. LOCAL(int)
  170501. largest_input_value (j_decompress_ptr cinfo, int ci, int j, int maxj)
  170502. /* Return largest input value that should map to j'th output value */
  170503. /* Must have largest(j=0) >= 0, and largest(j=maxj) >= MAXJSAMPLE */
  170504. {
  170505. /* Breakpoints are halfway between values returned by output_value */
  170506. return (int) (((INT32) (2*j + 1) * MAXJSAMPLE + maxj) / (2*maxj));
  170507. }
  170508. /*
  170509. * Create the colormap.
  170510. */
  170511. LOCAL(void)
  170512. create_colormap (j_decompress_ptr cinfo)
  170513. {
  170514. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  170515. JSAMPARRAY colormap; /* Created colormap */
  170516. int total_colors; /* Number of distinct output colors */
  170517. int i,j,k, nci, blksize, blkdist, ptr, val;
  170518. /* Select number of colors for each component */
  170519. total_colors = select_ncolors(cinfo, cquantize->Ncolors);
  170520. /* Report selected color counts */
  170521. if (cinfo->out_color_components == 3)
  170522. TRACEMS4(cinfo, 1, JTRC_QUANT_3_NCOLORS,
  170523. total_colors, cquantize->Ncolors[0],
  170524. cquantize->Ncolors[1], cquantize->Ncolors[2]);
  170525. else
  170526. TRACEMS1(cinfo, 1, JTRC_QUANT_NCOLORS, total_colors);
  170527. /* Allocate and fill in the colormap. */
  170528. /* The colors are ordered in the map in standard row-major order, */
  170529. /* i.e. rightmost (highest-indexed) color changes most rapidly. */
  170530. colormap = (*cinfo->mem->alloc_sarray)
  170531. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170532. (JDIMENSION) total_colors, (JDIMENSION) cinfo->out_color_components);
  170533. /* blksize is number of adjacent repeated entries for a component */
  170534. /* blkdist is distance between groups of identical entries for a component */
  170535. blkdist = total_colors;
  170536. for (i = 0; i < cinfo->out_color_components; i++) {
  170537. /* fill in colormap entries for i'th color component */
  170538. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  170539. blksize = blkdist / nci;
  170540. for (j = 0; j < nci; j++) {
  170541. /* Compute j'th output value (out of nci) for component */
  170542. val = output_value(cinfo, i, j, nci-1);
  170543. /* Fill in all colormap entries that have this value of this component */
  170544. for (ptr = j * blksize; ptr < total_colors; ptr += blkdist) {
  170545. /* fill in blksize entries beginning at ptr */
  170546. for (k = 0; k < blksize; k++)
  170547. colormap[i][ptr+k] = (JSAMPLE) val;
  170548. }
  170549. }
  170550. blkdist = blksize; /* blksize of this color is blkdist of next */
  170551. }
  170552. /* Save the colormap in private storage,
  170553. * where it will survive color quantization mode changes.
  170554. */
  170555. cquantize->sv_colormap = colormap;
  170556. cquantize->sv_actual = total_colors;
  170557. }
  170558. /*
  170559. * Create the color index table.
  170560. */
  170561. LOCAL(void)
  170562. create_colorindex (j_decompress_ptr cinfo)
  170563. {
  170564. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  170565. JSAMPROW indexptr;
  170566. int i,j,k, nci, blksize, val, pad;
  170567. /* For ordered dither, we pad the color index tables by MAXJSAMPLE in
  170568. * each direction (input index values can be -MAXJSAMPLE .. 2*MAXJSAMPLE).
  170569. * This is not necessary in the other dithering modes. However, we
  170570. * flag whether it was done in case user changes dithering mode.
  170571. */
  170572. if (cinfo->dither_mode == JDITHER_ORDERED) {
  170573. pad = MAXJSAMPLE*2;
  170574. cquantize->is_padded = TRUE;
  170575. } else {
  170576. pad = 0;
  170577. cquantize->is_padded = FALSE;
  170578. }
  170579. cquantize->colorindex = (*cinfo->mem->alloc_sarray)
  170580. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170581. (JDIMENSION) (MAXJSAMPLE+1 + pad),
  170582. (JDIMENSION) cinfo->out_color_components);
  170583. /* blksize is number of adjacent repeated entries for a component */
  170584. blksize = cquantize->sv_actual;
  170585. for (i = 0; i < cinfo->out_color_components; i++) {
  170586. /* fill in colorindex entries for i'th color component */
  170587. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  170588. blksize = blksize / nci;
  170589. /* adjust colorindex pointers to provide padding at negative indexes. */
  170590. if (pad)
  170591. cquantize->colorindex[i] += MAXJSAMPLE;
  170592. /* in loop, val = index of current output value, */
  170593. /* and k = largest j that maps to current val */
  170594. indexptr = cquantize->colorindex[i];
  170595. val = 0;
  170596. k = largest_input_value(cinfo, i, 0, nci-1);
  170597. for (j = 0; j <= MAXJSAMPLE; j++) {
  170598. while (j > k) /* advance val if past boundary */
  170599. k = largest_input_value(cinfo, i, ++val, nci-1);
  170600. /* premultiply so that no multiplication needed in main processing */
  170601. indexptr[j] = (JSAMPLE) (val * blksize);
  170602. }
  170603. /* Pad at both ends if necessary */
  170604. if (pad)
  170605. for (j = 1; j <= MAXJSAMPLE; j++) {
  170606. indexptr[-j] = indexptr[0];
  170607. indexptr[MAXJSAMPLE+j] = indexptr[MAXJSAMPLE];
  170608. }
  170609. }
  170610. }
  170611. /*
  170612. * Create an ordered-dither array for a component having ncolors
  170613. * distinct output values.
  170614. */
  170615. LOCAL(ODITHER_MATRIX_PTR)
  170616. make_odither_array (j_decompress_ptr cinfo, int ncolors)
  170617. {
  170618. ODITHER_MATRIX_PTR odither;
  170619. int j,k;
  170620. INT32 num,den;
  170621. odither = (ODITHER_MATRIX_PTR)
  170622. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170623. SIZEOF(ODITHER_MATRIX));
  170624. /* The inter-value distance for this color is MAXJSAMPLE/(ncolors-1).
  170625. * Hence the dither value for the matrix cell with fill order f
  170626. * (f=0..N-1) should be (N-1-2*f)/(2*N) * MAXJSAMPLE/(ncolors-1).
  170627. * On 16-bit-int machine, be careful to avoid overflow.
  170628. */
  170629. den = 2 * ODITHER_CELLS * ((INT32) (ncolors - 1));
  170630. for (j = 0; j < ODITHER_SIZE; j++) {
  170631. for (k = 0; k < ODITHER_SIZE; k++) {
  170632. num = ((INT32) (ODITHER_CELLS-1 - 2*((int)base_dither_matrix[j][k])))
  170633. * MAXJSAMPLE;
  170634. /* Ensure round towards zero despite C's lack of consistency
  170635. * about rounding negative values in integer division...
  170636. */
  170637. odither[j][k] = (int) (num<0 ? -((-num)/den) : num/den);
  170638. }
  170639. }
  170640. return odither;
  170641. }
  170642. /*
  170643. * Create the ordered-dither tables.
  170644. * Components having the same number of representative colors may
  170645. * share a dither table.
  170646. */
  170647. LOCAL(void)
  170648. create_odither_tables (j_decompress_ptr cinfo)
  170649. {
  170650. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  170651. ODITHER_MATRIX_PTR odither;
  170652. int i, j, nci;
  170653. for (i = 0; i < cinfo->out_color_components; i++) {
  170654. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  170655. odither = NULL; /* search for matching prior component */
  170656. for (j = 0; j < i; j++) {
  170657. if (nci == cquantize->Ncolors[j]) {
  170658. odither = cquantize->odither[j];
  170659. break;
  170660. }
  170661. }
  170662. if (odither == NULL) /* need a new table? */
  170663. odither = make_odither_array(cinfo, nci);
  170664. cquantize->odither[i] = odither;
  170665. }
  170666. }
  170667. /*
  170668. * Map some rows of pixels to the output colormapped representation.
  170669. */
  170670. METHODDEF(void)
  170671. color_quantize (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  170672. JSAMPARRAY output_buf, int num_rows)
  170673. /* General case, no dithering */
  170674. {
  170675. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  170676. JSAMPARRAY colorindex = cquantize->colorindex;
  170677. register int pixcode, ci;
  170678. register JSAMPROW ptrin, ptrout;
  170679. int row;
  170680. JDIMENSION col;
  170681. JDIMENSION width = cinfo->output_width;
  170682. register int nc = cinfo->out_color_components;
  170683. for (row = 0; row < num_rows; row++) {
  170684. ptrin = input_buf[row];
  170685. ptrout = output_buf[row];
  170686. for (col = width; col > 0; col--) {
  170687. pixcode = 0;
  170688. for (ci = 0; ci < nc; ci++) {
  170689. pixcode += GETJSAMPLE(colorindex[ci][GETJSAMPLE(*ptrin++)]);
  170690. }
  170691. *ptrout++ = (JSAMPLE) pixcode;
  170692. }
  170693. }
  170694. }
  170695. METHODDEF(void)
  170696. color_quantize3 (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  170697. JSAMPARRAY output_buf, int num_rows)
  170698. /* Fast path for out_color_components==3, no dithering */
  170699. {
  170700. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  170701. register int pixcode;
  170702. register JSAMPROW ptrin, ptrout;
  170703. JSAMPROW colorindex0 = cquantize->colorindex[0];
  170704. JSAMPROW colorindex1 = cquantize->colorindex[1];
  170705. JSAMPROW colorindex2 = cquantize->colorindex[2];
  170706. int row;
  170707. JDIMENSION col;
  170708. JDIMENSION width = cinfo->output_width;
  170709. for (row = 0; row < num_rows; row++) {
  170710. ptrin = input_buf[row];
  170711. ptrout = output_buf[row];
  170712. for (col = width; col > 0; col--) {
  170713. pixcode = GETJSAMPLE(colorindex0[GETJSAMPLE(*ptrin++)]);
  170714. pixcode += GETJSAMPLE(colorindex1[GETJSAMPLE(*ptrin++)]);
  170715. pixcode += GETJSAMPLE(colorindex2[GETJSAMPLE(*ptrin++)]);
  170716. *ptrout++ = (JSAMPLE) pixcode;
  170717. }
  170718. }
  170719. }
  170720. METHODDEF(void)
  170721. quantize_ord_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  170722. JSAMPARRAY output_buf, int num_rows)
  170723. /* General case, with ordered dithering */
  170724. {
  170725. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  170726. register JSAMPROW input_ptr;
  170727. register JSAMPROW output_ptr;
  170728. JSAMPROW colorindex_ci;
  170729. int * dither; /* points to active row of dither matrix */
  170730. int row_index, col_index; /* current indexes into dither matrix */
  170731. int nc = cinfo->out_color_components;
  170732. int ci;
  170733. int row;
  170734. JDIMENSION col;
  170735. JDIMENSION width = cinfo->output_width;
  170736. for (row = 0; row < num_rows; row++) {
  170737. /* Initialize output values to 0 so can process components separately */
  170738. jzero_far((void FAR *) output_buf[row],
  170739. (size_t) (width * SIZEOF(JSAMPLE)));
  170740. row_index = cquantize->row_index;
  170741. for (ci = 0; ci < nc; ci++) {
  170742. input_ptr = input_buf[row] + ci;
  170743. output_ptr = output_buf[row];
  170744. colorindex_ci = cquantize->colorindex[ci];
  170745. dither = cquantize->odither[ci][row_index];
  170746. col_index = 0;
  170747. for (col = width; col > 0; col--) {
  170748. /* Form pixel value + dither, range-limit to 0..MAXJSAMPLE,
  170749. * select output value, accumulate into output code for this pixel.
  170750. * Range-limiting need not be done explicitly, as we have extended
  170751. * the colorindex table to produce the right answers for out-of-range
  170752. * inputs. The maximum dither is +- MAXJSAMPLE; this sets the
  170753. * required amount of padding.
  170754. */
  170755. *output_ptr += colorindex_ci[GETJSAMPLE(*input_ptr)+dither[col_index]];
  170756. input_ptr += nc;
  170757. output_ptr++;
  170758. col_index = (col_index + 1) & ODITHER_MASK;
  170759. }
  170760. }
  170761. /* Advance row index for next row */
  170762. row_index = (row_index + 1) & ODITHER_MASK;
  170763. cquantize->row_index = row_index;
  170764. }
  170765. }
  170766. METHODDEF(void)
  170767. quantize3_ord_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  170768. JSAMPARRAY output_buf, int num_rows)
  170769. /* Fast path for out_color_components==3, with ordered dithering */
  170770. {
  170771. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  170772. register int pixcode;
  170773. register JSAMPROW input_ptr;
  170774. register JSAMPROW output_ptr;
  170775. JSAMPROW colorindex0 = cquantize->colorindex[0];
  170776. JSAMPROW colorindex1 = cquantize->colorindex[1];
  170777. JSAMPROW colorindex2 = cquantize->colorindex[2];
  170778. int * dither0; /* points to active row of dither matrix */
  170779. int * dither1;
  170780. int * dither2;
  170781. int row_index, col_index; /* current indexes into dither matrix */
  170782. int row;
  170783. JDIMENSION col;
  170784. JDIMENSION width = cinfo->output_width;
  170785. for (row = 0; row < num_rows; row++) {
  170786. row_index = cquantize->row_index;
  170787. input_ptr = input_buf[row];
  170788. output_ptr = output_buf[row];
  170789. dither0 = cquantize->odither[0][row_index];
  170790. dither1 = cquantize->odither[1][row_index];
  170791. dither2 = cquantize->odither[2][row_index];
  170792. col_index = 0;
  170793. for (col = width; col > 0; col--) {
  170794. pixcode = GETJSAMPLE(colorindex0[GETJSAMPLE(*input_ptr++) +
  170795. dither0[col_index]]);
  170796. pixcode += GETJSAMPLE(colorindex1[GETJSAMPLE(*input_ptr++) +
  170797. dither1[col_index]]);
  170798. pixcode += GETJSAMPLE(colorindex2[GETJSAMPLE(*input_ptr++) +
  170799. dither2[col_index]]);
  170800. *output_ptr++ = (JSAMPLE) pixcode;
  170801. col_index = (col_index + 1) & ODITHER_MASK;
  170802. }
  170803. row_index = (row_index + 1) & ODITHER_MASK;
  170804. cquantize->row_index = row_index;
  170805. }
  170806. }
  170807. METHODDEF(void)
  170808. quantize_fs_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  170809. JSAMPARRAY output_buf, int num_rows)
  170810. /* General case, with Floyd-Steinberg dithering */
  170811. {
  170812. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  170813. register LOCFSERROR cur; /* current error or pixel value */
  170814. LOCFSERROR belowerr; /* error for pixel below cur */
  170815. LOCFSERROR bpreverr; /* error for below/prev col */
  170816. LOCFSERROR bnexterr; /* error for below/next col */
  170817. LOCFSERROR delta;
  170818. register FSERRPTR errorptr; /* => fserrors[] at column before current */
  170819. register JSAMPROW input_ptr;
  170820. register JSAMPROW output_ptr;
  170821. JSAMPROW colorindex_ci;
  170822. JSAMPROW colormap_ci;
  170823. int pixcode;
  170824. int nc = cinfo->out_color_components;
  170825. int dir; /* 1 for left-to-right, -1 for right-to-left */
  170826. int dirnc; /* dir * nc */
  170827. int ci;
  170828. int row;
  170829. JDIMENSION col;
  170830. JDIMENSION width = cinfo->output_width;
  170831. JSAMPLE *range_limit = cinfo->sample_range_limit;
  170832. SHIFT_TEMPS
  170833. for (row = 0; row < num_rows; row++) {
  170834. /* Initialize output values to 0 so can process components separately */
  170835. jzero_far((void FAR *) output_buf[row],
  170836. (size_t) (width * SIZEOF(JSAMPLE)));
  170837. for (ci = 0; ci < nc; ci++) {
  170838. input_ptr = input_buf[row] + ci;
  170839. output_ptr = output_buf[row];
  170840. if (cquantize->on_odd_row) {
  170841. /* work right to left in this row */
  170842. input_ptr += (width-1) * nc; /* so point to rightmost pixel */
  170843. output_ptr += width-1;
  170844. dir = -1;
  170845. dirnc = -nc;
  170846. errorptr = cquantize->fserrors[ci] + (width+1); /* => entry after last column */
  170847. } else {
  170848. /* work left to right in this row */
  170849. dir = 1;
  170850. dirnc = nc;
  170851. errorptr = cquantize->fserrors[ci]; /* => entry before first column */
  170852. }
  170853. colorindex_ci = cquantize->colorindex[ci];
  170854. colormap_ci = cquantize->sv_colormap[ci];
  170855. /* Preset error values: no error propagated to first pixel from left */
  170856. cur = 0;
  170857. /* and no error propagated to row below yet */
  170858. belowerr = bpreverr = 0;
  170859. for (col = width; col > 0; col--) {
  170860. /* cur holds the error propagated from the previous pixel on the
  170861. * current line. Add the error propagated from the previous line
  170862. * to form the complete error correction term for this pixel, and
  170863. * round the error term (which is expressed * 16) to an integer.
  170864. * RIGHT_SHIFT rounds towards minus infinity, so adding 8 is correct
  170865. * for either sign of the error value.
  170866. * Note: errorptr points to *previous* column's array entry.
  170867. */
  170868. cur = RIGHT_SHIFT(cur + errorptr[dir] + 8, 4);
  170869. /* Form pixel value + error, and range-limit to 0..MAXJSAMPLE.
  170870. * The maximum error is +- MAXJSAMPLE; this sets the required size
  170871. * of the range_limit array.
  170872. */
  170873. cur += GETJSAMPLE(*input_ptr);
  170874. cur = GETJSAMPLE(range_limit[cur]);
  170875. /* Select output value, accumulate into output code for this pixel */
  170876. pixcode = GETJSAMPLE(colorindex_ci[cur]);
  170877. *output_ptr += (JSAMPLE) pixcode;
  170878. /* Compute actual representation error at this pixel */
  170879. /* Note: we can do this even though we don't have the final */
  170880. /* pixel code, because the colormap is orthogonal. */
  170881. cur -= GETJSAMPLE(colormap_ci[pixcode]);
  170882. /* Compute error fractions to be propagated to adjacent pixels.
  170883. * Add these into the running sums, and simultaneously shift the
  170884. * next-line error sums left by 1 column.
  170885. */
  170886. bnexterr = cur;
  170887. delta = cur * 2;
  170888. cur += delta; /* form error * 3 */
  170889. errorptr[0] = (FSERROR) (bpreverr + cur);
  170890. cur += delta; /* form error * 5 */
  170891. bpreverr = belowerr + cur;
  170892. belowerr = bnexterr;
  170893. cur += delta; /* form error * 7 */
  170894. /* At this point cur contains the 7/16 error value to be propagated
  170895. * to the next pixel on the current line, and all the errors for the
  170896. * next line have been shifted over. We are therefore ready to move on.
  170897. */
  170898. input_ptr += dirnc; /* advance input ptr to next column */
  170899. output_ptr += dir; /* advance output ptr to next column */
  170900. errorptr += dir; /* advance errorptr to current column */
  170901. }
  170902. /* Post-loop cleanup: we must unload the final error value into the
  170903. * final fserrors[] entry. Note we need not unload belowerr because
  170904. * it is for the dummy column before or after the actual array.
  170905. */
  170906. errorptr[0] = (FSERROR) bpreverr; /* unload prev err into array */
  170907. }
  170908. cquantize->on_odd_row = (cquantize->on_odd_row ? FALSE : TRUE);
  170909. }
  170910. }
  170911. /*
  170912. * Allocate workspace for Floyd-Steinberg errors.
  170913. */
  170914. LOCAL(void)
  170915. alloc_fs_workspace (j_decompress_ptr cinfo)
  170916. {
  170917. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  170918. size_t arraysize;
  170919. int i;
  170920. arraysize = (size_t) ((cinfo->output_width + 2) * SIZEOF(FSERROR));
  170921. for (i = 0; i < cinfo->out_color_components; i++) {
  170922. cquantize->fserrors[i] = (FSERRPTR)
  170923. (*cinfo->mem->alloc_large)((j_common_ptr) cinfo, JPOOL_IMAGE, arraysize);
  170924. }
  170925. }
  170926. /*
  170927. * Initialize for one-pass color quantization.
  170928. */
  170929. METHODDEF(void)
  170930. start_pass_1_quant (j_decompress_ptr cinfo, boolean is_pre_scan)
  170931. {
  170932. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  170933. size_t arraysize;
  170934. int i;
  170935. /* Install my colormap. */
  170936. cinfo->colormap = cquantize->sv_colormap;
  170937. cinfo->actual_number_of_colors = cquantize->sv_actual;
  170938. /* Initialize for desired dithering mode. */
  170939. switch (cinfo->dither_mode) {
  170940. case JDITHER_NONE:
  170941. if (cinfo->out_color_components == 3)
  170942. cquantize->pub.color_quantize = color_quantize3;
  170943. else
  170944. cquantize->pub.color_quantize = color_quantize;
  170945. break;
  170946. case JDITHER_ORDERED:
  170947. if (cinfo->out_color_components == 3)
  170948. cquantize->pub.color_quantize = quantize3_ord_dither;
  170949. else
  170950. cquantize->pub.color_quantize = quantize_ord_dither;
  170951. cquantize->row_index = 0; /* initialize state for ordered dither */
  170952. /* If user changed to ordered dither from another mode,
  170953. * we must recreate the color index table with padding.
  170954. * This will cost extra space, but probably isn't very likely.
  170955. */
  170956. if (! cquantize->is_padded)
  170957. create_colorindex(cinfo);
  170958. /* Create ordered-dither tables if we didn't already. */
  170959. if (cquantize->odither[0] == NULL)
  170960. create_odither_tables(cinfo);
  170961. break;
  170962. case JDITHER_FS:
  170963. cquantize->pub.color_quantize = quantize_fs_dither;
  170964. cquantize->on_odd_row = FALSE; /* initialize state for F-S dither */
  170965. /* Allocate Floyd-Steinberg workspace if didn't already. */
  170966. if (cquantize->fserrors[0] == NULL)
  170967. alloc_fs_workspace(cinfo);
  170968. /* Initialize the propagated errors to zero. */
  170969. arraysize = (size_t) ((cinfo->output_width + 2) * SIZEOF(FSERROR));
  170970. for (i = 0; i < cinfo->out_color_components; i++)
  170971. jzero_far((void FAR *) cquantize->fserrors[i], arraysize);
  170972. break;
  170973. default:
  170974. ERREXIT(cinfo, JERR_NOT_COMPILED);
  170975. break;
  170976. }
  170977. }
  170978. /*
  170979. * Finish up at the end of the pass.
  170980. */
  170981. METHODDEF(void)
  170982. finish_pass_1_quant (j_decompress_ptr cinfo)
  170983. {
  170984. /* no work in 1-pass case */
  170985. }
  170986. /*
  170987. * Switch to a new external colormap between output passes.
  170988. * Shouldn't get to this module!
  170989. */
  170990. METHODDEF(void)
  170991. new_color_map_1_quant (j_decompress_ptr cinfo)
  170992. {
  170993. ERREXIT(cinfo, JERR_MODE_CHANGE);
  170994. }
  170995. /*
  170996. * Module initialization routine for 1-pass color quantization.
  170997. */
  170998. GLOBAL(void)
  170999. jinit_1pass_quantizer (j_decompress_ptr cinfo)
  171000. {
  171001. my_cquantize_ptr cquantize;
  171002. cquantize = (my_cquantize_ptr)
  171003. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171004. SIZEOF(my_cquantizer));
  171005. cinfo->cquantize = (struct jpeg_color_quantizer *) cquantize;
  171006. cquantize->pub.start_pass = start_pass_1_quant;
  171007. cquantize->pub.finish_pass = finish_pass_1_quant;
  171008. cquantize->pub.new_color_map = new_color_map_1_quant;
  171009. cquantize->fserrors[0] = NULL; /* Flag FS workspace not allocated */
  171010. cquantize->odither[0] = NULL; /* Also flag odither arrays not allocated */
  171011. /* Make sure my internal arrays won't overflow */
  171012. if (cinfo->out_color_components > MAX_Q_COMPS)
  171013. ERREXIT1(cinfo, JERR_QUANT_COMPONENTS, MAX_Q_COMPS);
  171014. /* Make sure colormap indexes can be represented by JSAMPLEs */
  171015. if (cinfo->desired_number_of_colors > (MAXJSAMPLE+1))
  171016. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXJSAMPLE+1);
  171017. /* Create the colormap and color index table. */
  171018. create_colormap(cinfo);
  171019. create_colorindex(cinfo);
  171020. /* Allocate Floyd-Steinberg workspace now if requested.
  171021. * We do this now since it is FAR storage and may affect the memory
  171022. * manager's space calculations. If the user changes to FS dither
  171023. * mode in a later pass, we will allocate the space then, and will
  171024. * possibly overrun the max_memory_to_use setting.
  171025. */
  171026. if (cinfo->dither_mode == JDITHER_FS)
  171027. alloc_fs_workspace(cinfo);
  171028. }
  171029. #endif /* QUANT_1PASS_SUPPORTED */
  171030. /********* End of inlined file: jquant1.c *********/
  171031. /********* Start of inlined file: jquant2.c *********/
  171032. #define JPEG_INTERNALS
  171033. #ifdef QUANT_2PASS_SUPPORTED
  171034. /*
  171035. * This module implements the well-known Heckbert paradigm for color
  171036. * quantization. Most of the ideas used here can be traced back to
  171037. * Heckbert's seminal paper
  171038. * Heckbert, Paul. "Color Image Quantization for Frame Buffer Display",
  171039. * Proc. SIGGRAPH '82, Computer Graphics v.16 #3 (July 1982), pp 297-304.
  171040. *
  171041. * In the first pass over the image, we accumulate a histogram showing the
  171042. * usage count of each possible color. To keep the histogram to a reasonable
  171043. * size, we reduce the precision of the input; typical practice is to retain
  171044. * 5 or 6 bits per color, so that 8 or 4 different input values are counted
  171045. * in the same histogram cell.
  171046. *
  171047. * Next, the color-selection step begins with a box representing the whole
  171048. * color space, and repeatedly splits the "largest" remaining box until we
  171049. * have as many boxes as desired colors. Then the mean color in each
  171050. * remaining box becomes one of the possible output colors.
  171051. *
  171052. * The second pass over the image maps each input pixel to the closest output
  171053. * color (optionally after applying a Floyd-Steinberg dithering correction).
  171054. * This mapping is logically trivial, but making it go fast enough requires
  171055. * considerable care.
  171056. *
  171057. * Heckbert-style quantizers vary a good deal in their policies for choosing
  171058. * the "largest" box and deciding where to cut it. The particular policies
  171059. * used here have proved out well in experimental comparisons, but better ones
  171060. * may yet be found.
  171061. *
  171062. * In earlier versions of the IJG code, this module quantized in YCbCr color
  171063. * space, processing the raw upsampled data without a color conversion step.
  171064. * This allowed the color conversion math to be done only once per colormap
  171065. * entry, not once per pixel. However, that optimization precluded other
  171066. * useful optimizations (such as merging color conversion with upsampling)
  171067. * and it also interfered with desired capabilities such as quantizing to an
  171068. * externally-supplied colormap. We have therefore abandoned that approach.
  171069. * The present code works in the post-conversion color space, typically RGB.
  171070. *
  171071. * To improve the visual quality of the results, we actually work in scaled
  171072. * RGB space, giving G distances more weight than R, and R in turn more than
  171073. * B. To do everything in integer math, we must use integer scale factors.
  171074. * The 2/3/1 scale factors used here correspond loosely to the relative
  171075. * weights of the colors in the NTSC grayscale equation.
  171076. * If you want to use this code to quantize a non-RGB color space, you'll
  171077. * probably need to change these scale factors.
  171078. */
  171079. #define R_SCALE 2 /* scale R distances by this much */
  171080. #define G_SCALE 3 /* scale G distances by this much */
  171081. #define B_SCALE 1 /* and B by this much */
  171082. /* Relabel R/G/B as components 0/1/2, respecting the RGB ordering defined
  171083. * in jmorecfg.h. As the code stands, it will do the right thing for R,G,B
  171084. * and B,G,R orders. If you define some other weird order in jmorecfg.h,
  171085. * you'll get compile errors until you extend this logic. In that case
  171086. * you'll probably want to tweak the histogram sizes too.
  171087. */
  171088. #if RGB_RED == 0
  171089. #define C0_SCALE R_SCALE
  171090. #endif
  171091. #if RGB_BLUE == 0
  171092. #define C0_SCALE B_SCALE
  171093. #endif
  171094. #if RGB_GREEN == 1
  171095. #define C1_SCALE G_SCALE
  171096. #endif
  171097. #if RGB_RED == 2
  171098. #define C2_SCALE R_SCALE
  171099. #endif
  171100. #if RGB_BLUE == 2
  171101. #define C2_SCALE B_SCALE
  171102. #endif
  171103. /*
  171104. * First we have the histogram data structure and routines for creating it.
  171105. *
  171106. * The number of bits of precision can be adjusted by changing these symbols.
  171107. * We recommend keeping 6 bits for G and 5 each for R and B.
  171108. * If you have plenty of memory and cycles, 6 bits all around gives marginally
  171109. * better results; if you are short of memory, 5 bits all around will save
  171110. * some space but degrade the results.
  171111. * To maintain a fully accurate histogram, we'd need to allocate a "long"
  171112. * (preferably unsigned long) for each cell. In practice this is overkill;
  171113. * we can get by with 16 bits per cell. Few of the cell counts will overflow,
  171114. * and clamping those that do overflow to the maximum value will give close-
  171115. * enough results. This reduces the recommended histogram size from 256Kb
  171116. * to 128Kb, which is a useful savings on PC-class machines.
  171117. * (In the second pass the histogram space is re-used for pixel mapping data;
  171118. * in that capacity, each cell must be able to store zero to the number of
  171119. * desired colors. 16 bits/cell is plenty for that too.)
  171120. * Since the JPEG code is intended to run in small memory model on 80x86
  171121. * machines, we can't just allocate the histogram in one chunk. Instead
  171122. * of a true 3-D array, we use a row of pointers to 2-D arrays. Each
  171123. * pointer corresponds to a C0 value (typically 2^5 = 32 pointers) and
  171124. * each 2-D array has 2^6*2^5 = 2048 or 2^6*2^6 = 4096 entries. Note that
  171125. * on 80x86 machines, the pointer row is in near memory but the actual
  171126. * arrays are in far memory (same arrangement as we use for image arrays).
  171127. */
  171128. #define MAXNUMCOLORS (MAXJSAMPLE+1) /* maximum size of colormap */
  171129. /* These will do the right thing for either R,G,B or B,G,R color order,
  171130. * but you may not like the results for other color orders.
  171131. */
  171132. #define HIST_C0_BITS 5 /* bits of precision in R/B histogram */
  171133. #define HIST_C1_BITS 6 /* bits of precision in G histogram */
  171134. #define HIST_C2_BITS 5 /* bits of precision in B/R histogram */
  171135. /* Number of elements along histogram axes. */
  171136. #define HIST_C0_ELEMS (1<<HIST_C0_BITS)
  171137. #define HIST_C1_ELEMS (1<<HIST_C1_BITS)
  171138. #define HIST_C2_ELEMS (1<<HIST_C2_BITS)
  171139. /* These are the amounts to shift an input value to get a histogram index. */
  171140. #define C0_SHIFT (BITS_IN_JSAMPLE-HIST_C0_BITS)
  171141. #define C1_SHIFT (BITS_IN_JSAMPLE-HIST_C1_BITS)
  171142. #define C2_SHIFT (BITS_IN_JSAMPLE-HIST_C2_BITS)
  171143. typedef UINT16 histcell; /* histogram cell; prefer an unsigned type */
  171144. typedef histcell FAR * histptr; /* for pointers to histogram cells */
  171145. typedef histcell hist1d[HIST_C2_ELEMS]; /* typedefs for the array */
  171146. typedef hist1d FAR * hist2d; /* type for the 2nd-level pointers */
  171147. typedef hist2d * hist3d; /* type for top-level pointer */
  171148. /* Declarations for Floyd-Steinberg dithering.
  171149. *
  171150. * Errors are accumulated into the array fserrors[], at a resolution of
  171151. * 1/16th of a pixel count. The error at a given pixel is propagated
  171152. * to its not-yet-processed neighbors using the standard F-S fractions,
  171153. * ... (here) 7/16
  171154. * 3/16 5/16 1/16
  171155. * We work left-to-right on even rows, right-to-left on odd rows.
  171156. *
  171157. * We can get away with a single array (holding one row's worth of errors)
  171158. * by using it to store the current row's errors at pixel columns not yet
  171159. * processed, but the next row's errors at columns already processed. We
  171160. * need only a few extra variables to hold the errors immediately around the
  171161. * current column. (If we are lucky, those variables are in registers, but
  171162. * even if not, they're probably cheaper to access than array elements are.)
  171163. *
  171164. * The fserrors[] array has (#columns + 2) entries; the extra entry at
  171165. * each end saves us from special-casing the first and last pixels.
  171166. * Each entry is three values long, one value for each color component.
  171167. *
  171168. * Note: on a wide image, we might not have enough room in a PC's near data
  171169. * segment to hold the error array; so it is allocated with alloc_large.
  171170. */
  171171. #if BITS_IN_JSAMPLE == 8
  171172. typedef INT16 FSERROR; /* 16 bits should be enough */
  171173. typedef int LOCFSERROR; /* use 'int' for calculation temps */
  171174. #else
  171175. typedef INT32 FSERROR; /* may need more than 16 bits */
  171176. typedef INT32 LOCFSERROR; /* be sure calculation temps are big enough */
  171177. #endif
  171178. typedef FSERROR FAR *FSERRPTR; /* pointer to error array (in FAR storage!) */
  171179. /* Private subobject */
  171180. typedef struct {
  171181. struct jpeg_color_quantizer pub; /* public fields */
  171182. /* Space for the eventually created colormap is stashed here */
  171183. JSAMPARRAY sv_colormap; /* colormap allocated at init time */
  171184. int desired; /* desired # of colors = size of colormap */
  171185. /* Variables for accumulating image statistics */
  171186. hist3d histogram; /* pointer to the histogram */
  171187. boolean needs_zeroed; /* TRUE if next pass must zero histogram */
  171188. /* Variables for Floyd-Steinberg dithering */
  171189. FSERRPTR fserrors; /* accumulated errors */
  171190. boolean on_odd_row; /* flag to remember which row we are on */
  171191. int * error_limiter; /* table for clamping the applied error */
  171192. } my_cquantizer2;
  171193. typedef my_cquantizer2 * my_cquantize_ptr2;
  171194. /*
  171195. * Prescan some rows of pixels.
  171196. * In this module the prescan simply updates the histogram, which has been
  171197. * initialized to zeroes by start_pass.
  171198. * An output_buf parameter is required by the method signature, but no data
  171199. * is actually output (in fact the buffer controller is probably passing a
  171200. * NULL pointer).
  171201. */
  171202. METHODDEF(void)
  171203. prescan_quantize (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  171204. JSAMPARRAY output_buf, int num_rows)
  171205. {
  171206. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  171207. register JSAMPROW ptr;
  171208. register histptr histp;
  171209. register hist3d histogram = cquantize->histogram;
  171210. int row;
  171211. JDIMENSION col;
  171212. JDIMENSION width = cinfo->output_width;
  171213. for (row = 0; row < num_rows; row++) {
  171214. ptr = input_buf[row];
  171215. for (col = width; col > 0; col--) {
  171216. /* get pixel value and index into the histogram */
  171217. histp = & histogram[GETJSAMPLE(ptr[0]) >> C0_SHIFT]
  171218. [GETJSAMPLE(ptr[1]) >> C1_SHIFT]
  171219. [GETJSAMPLE(ptr[2]) >> C2_SHIFT];
  171220. /* increment, check for overflow and undo increment if so. */
  171221. if (++(*histp) <= 0)
  171222. (*histp)--;
  171223. ptr += 3;
  171224. }
  171225. }
  171226. }
  171227. /*
  171228. * Next we have the really interesting routines: selection of a colormap
  171229. * given the completed histogram.
  171230. * These routines work with a list of "boxes", each representing a rectangular
  171231. * subset of the input color space (to histogram precision).
  171232. */
  171233. typedef struct {
  171234. /* The bounds of the box (inclusive); expressed as histogram indexes */
  171235. int c0min, c0max;
  171236. int c1min, c1max;
  171237. int c2min, c2max;
  171238. /* The volume (actually 2-norm) of the box */
  171239. INT32 volume;
  171240. /* The number of nonzero histogram cells within this box */
  171241. long colorcount;
  171242. } box;
  171243. typedef box * boxptr;
  171244. LOCAL(boxptr)
  171245. find_biggest_color_pop (boxptr boxlist, int numboxes)
  171246. /* Find the splittable box with the largest color population */
  171247. /* Returns NULL if no splittable boxes remain */
  171248. {
  171249. register boxptr boxp;
  171250. register int i;
  171251. register long maxc = 0;
  171252. boxptr which = NULL;
  171253. for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) {
  171254. if (boxp->colorcount > maxc && boxp->volume > 0) {
  171255. which = boxp;
  171256. maxc = boxp->colorcount;
  171257. }
  171258. }
  171259. return which;
  171260. }
  171261. LOCAL(boxptr)
  171262. find_biggest_volume (boxptr boxlist, int numboxes)
  171263. /* Find the splittable box with the largest (scaled) volume */
  171264. /* Returns NULL if no splittable boxes remain */
  171265. {
  171266. register boxptr boxp;
  171267. register int i;
  171268. register INT32 maxv = 0;
  171269. boxptr which = NULL;
  171270. for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) {
  171271. if (boxp->volume > maxv) {
  171272. which = boxp;
  171273. maxv = boxp->volume;
  171274. }
  171275. }
  171276. return which;
  171277. }
  171278. LOCAL(void)
  171279. update_box (j_decompress_ptr cinfo, boxptr boxp)
  171280. /* Shrink the min/max bounds of a box to enclose only nonzero elements, */
  171281. /* and recompute its volume and population */
  171282. {
  171283. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  171284. hist3d histogram = cquantize->histogram;
  171285. histptr histp;
  171286. int c0,c1,c2;
  171287. int c0min,c0max,c1min,c1max,c2min,c2max;
  171288. INT32 dist0,dist1,dist2;
  171289. long ccount;
  171290. c0min = boxp->c0min; c0max = boxp->c0max;
  171291. c1min = boxp->c1min; c1max = boxp->c1max;
  171292. c2min = boxp->c2min; c2max = boxp->c2max;
  171293. if (c0max > c0min)
  171294. for (c0 = c0min; c0 <= c0max; c0++)
  171295. for (c1 = c1min; c1 <= c1max; c1++) {
  171296. histp = & histogram[c0][c1][c2min];
  171297. for (c2 = c2min; c2 <= c2max; c2++)
  171298. if (*histp++ != 0) {
  171299. boxp->c0min = c0min = c0;
  171300. goto have_c0min;
  171301. }
  171302. }
  171303. have_c0min:
  171304. if (c0max > c0min)
  171305. for (c0 = c0max; c0 >= c0min; c0--)
  171306. for (c1 = c1min; c1 <= c1max; c1++) {
  171307. histp = & histogram[c0][c1][c2min];
  171308. for (c2 = c2min; c2 <= c2max; c2++)
  171309. if (*histp++ != 0) {
  171310. boxp->c0max = c0max = c0;
  171311. goto have_c0max;
  171312. }
  171313. }
  171314. have_c0max:
  171315. if (c1max > c1min)
  171316. for (c1 = c1min; c1 <= c1max; c1++)
  171317. for (c0 = c0min; c0 <= c0max; c0++) {
  171318. histp = & histogram[c0][c1][c2min];
  171319. for (c2 = c2min; c2 <= c2max; c2++)
  171320. if (*histp++ != 0) {
  171321. boxp->c1min = c1min = c1;
  171322. goto have_c1min;
  171323. }
  171324. }
  171325. have_c1min:
  171326. if (c1max > c1min)
  171327. for (c1 = c1max; c1 >= c1min; c1--)
  171328. for (c0 = c0min; c0 <= c0max; c0++) {
  171329. histp = & histogram[c0][c1][c2min];
  171330. for (c2 = c2min; c2 <= c2max; c2++)
  171331. if (*histp++ != 0) {
  171332. boxp->c1max = c1max = c1;
  171333. goto have_c1max;
  171334. }
  171335. }
  171336. have_c1max:
  171337. if (c2max > c2min)
  171338. for (c2 = c2min; c2 <= c2max; c2++)
  171339. for (c0 = c0min; c0 <= c0max; c0++) {
  171340. histp = & histogram[c0][c1min][c2];
  171341. for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS)
  171342. if (*histp != 0) {
  171343. boxp->c2min = c2min = c2;
  171344. goto have_c2min;
  171345. }
  171346. }
  171347. have_c2min:
  171348. if (c2max > c2min)
  171349. for (c2 = c2max; c2 >= c2min; c2--)
  171350. for (c0 = c0min; c0 <= c0max; c0++) {
  171351. histp = & histogram[c0][c1min][c2];
  171352. for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS)
  171353. if (*histp != 0) {
  171354. boxp->c2max = c2max = c2;
  171355. goto have_c2max;
  171356. }
  171357. }
  171358. have_c2max:
  171359. /* Update box volume.
  171360. * We use 2-norm rather than real volume here; this biases the method
  171361. * against making long narrow boxes, and it has the side benefit that
  171362. * a box is splittable iff norm > 0.
  171363. * Since the differences are expressed in histogram-cell units,
  171364. * we have to shift back to JSAMPLE units to get consistent distances;
  171365. * after which, we scale according to the selected distance scale factors.
  171366. */
  171367. dist0 = ((c0max - c0min) << C0_SHIFT) * C0_SCALE;
  171368. dist1 = ((c1max - c1min) << C1_SHIFT) * C1_SCALE;
  171369. dist2 = ((c2max - c2min) << C2_SHIFT) * C2_SCALE;
  171370. boxp->volume = dist0*dist0 + dist1*dist1 + dist2*dist2;
  171371. /* Now scan remaining volume of box and compute population */
  171372. ccount = 0;
  171373. for (c0 = c0min; c0 <= c0max; c0++)
  171374. for (c1 = c1min; c1 <= c1max; c1++) {
  171375. histp = & histogram[c0][c1][c2min];
  171376. for (c2 = c2min; c2 <= c2max; c2++, histp++)
  171377. if (*histp != 0) {
  171378. ccount++;
  171379. }
  171380. }
  171381. boxp->colorcount = ccount;
  171382. }
  171383. LOCAL(int)
  171384. median_cut (j_decompress_ptr cinfo, boxptr boxlist, int numboxes,
  171385. int desired_colors)
  171386. /* Repeatedly select and split the largest box until we have enough boxes */
  171387. {
  171388. int n,lb;
  171389. int c0,c1,c2,cmax;
  171390. register boxptr b1,b2;
  171391. while (numboxes < desired_colors) {
  171392. /* Select box to split.
  171393. * Current algorithm: by population for first half, then by volume.
  171394. */
  171395. if (numboxes*2 <= desired_colors) {
  171396. b1 = find_biggest_color_pop(boxlist, numboxes);
  171397. } else {
  171398. b1 = find_biggest_volume(boxlist, numboxes);
  171399. }
  171400. if (b1 == NULL) /* no splittable boxes left! */
  171401. break;
  171402. b2 = &boxlist[numboxes]; /* where new box will go */
  171403. /* Copy the color bounds to the new box. */
  171404. b2->c0max = b1->c0max; b2->c1max = b1->c1max; b2->c2max = b1->c2max;
  171405. b2->c0min = b1->c0min; b2->c1min = b1->c1min; b2->c2min = b1->c2min;
  171406. /* Choose which axis to split the box on.
  171407. * Current algorithm: longest scaled axis.
  171408. * See notes in update_box about scaling distances.
  171409. */
  171410. c0 = ((b1->c0max - b1->c0min) << C0_SHIFT) * C0_SCALE;
  171411. c1 = ((b1->c1max - b1->c1min) << C1_SHIFT) * C1_SCALE;
  171412. c2 = ((b1->c2max - b1->c2min) << C2_SHIFT) * C2_SCALE;
  171413. /* We want to break any ties in favor of green, then red, blue last.
  171414. * This code does the right thing for R,G,B or B,G,R color orders only.
  171415. */
  171416. #if RGB_RED == 0
  171417. cmax = c1; n = 1;
  171418. if (c0 > cmax) { cmax = c0; n = 0; }
  171419. if (c2 > cmax) { n = 2; }
  171420. #else
  171421. cmax = c1; n = 1;
  171422. if (c2 > cmax) { cmax = c2; n = 2; }
  171423. if (c0 > cmax) { n = 0; }
  171424. #endif
  171425. /* Choose split point along selected axis, and update box bounds.
  171426. * Current algorithm: split at halfway point.
  171427. * (Since the box has been shrunk to minimum volume,
  171428. * any split will produce two nonempty subboxes.)
  171429. * Note that lb value is max for lower box, so must be < old max.
  171430. */
  171431. switch (n) {
  171432. case 0:
  171433. lb = (b1->c0max + b1->c0min) / 2;
  171434. b1->c0max = lb;
  171435. b2->c0min = lb+1;
  171436. break;
  171437. case 1:
  171438. lb = (b1->c1max + b1->c1min) / 2;
  171439. b1->c1max = lb;
  171440. b2->c1min = lb+1;
  171441. break;
  171442. case 2:
  171443. lb = (b1->c2max + b1->c2min) / 2;
  171444. b1->c2max = lb;
  171445. b2->c2min = lb+1;
  171446. break;
  171447. }
  171448. /* Update stats for boxes */
  171449. update_box(cinfo, b1);
  171450. update_box(cinfo, b2);
  171451. numboxes++;
  171452. }
  171453. return numboxes;
  171454. }
  171455. LOCAL(void)
  171456. compute_color (j_decompress_ptr cinfo, boxptr boxp, int icolor)
  171457. /* Compute representative color for a box, put it in colormap[icolor] */
  171458. {
  171459. /* Current algorithm: mean weighted by pixels (not colors) */
  171460. /* Note it is important to get the rounding correct! */
  171461. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  171462. hist3d histogram = cquantize->histogram;
  171463. histptr histp;
  171464. int c0,c1,c2;
  171465. int c0min,c0max,c1min,c1max,c2min,c2max;
  171466. long count;
  171467. long total = 0;
  171468. long c0total = 0;
  171469. long c1total = 0;
  171470. long c2total = 0;
  171471. c0min = boxp->c0min; c0max = boxp->c0max;
  171472. c1min = boxp->c1min; c1max = boxp->c1max;
  171473. c2min = boxp->c2min; c2max = boxp->c2max;
  171474. for (c0 = c0min; c0 <= c0max; c0++)
  171475. for (c1 = c1min; c1 <= c1max; c1++) {
  171476. histp = & histogram[c0][c1][c2min];
  171477. for (c2 = c2min; c2 <= c2max; c2++) {
  171478. if ((count = *histp++) != 0) {
  171479. total += count;
  171480. c0total += ((c0 << C0_SHIFT) + ((1<<C0_SHIFT)>>1)) * count;
  171481. c1total += ((c1 << C1_SHIFT) + ((1<<C1_SHIFT)>>1)) * count;
  171482. c2total += ((c2 << C2_SHIFT) + ((1<<C2_SHIFT)>>1)) * count;
  171483. }
  171484. }
  171485. }
  171486. cinfo->colormap[0][icolor] = (JSAMPLE) ((c0total + (total>>1)) / total);
  171487. cinfo->colormap[1][icolor] = (JSAMPLE) ((c1total + (total>>1)) / total);
  171488. cinfo->colormap[2][icolor] = (JSAMPLE) ((c2total + (total>>1)) / total);
  171489. }
  171490. LOCAL(void)
  171491. select_colors (j_decompress_ptr cinfo, int desired_colors)
  171492. /* Master routine for color selection */
  171493. {
  171494. boxptr boxlist;
  171495. int numboxes;
  171496. int i;
  171497. /* Allocate workspace for box list */
  171498. boxlist = (boxptr) (*cinfo->mem->alloc_small)
  171499. ((j_common_ptr) cinfo, JPOOL_IMAGE, desired_colors * SIZEOF(box));
  171500. /* Initialize one box containing whole space */
  171501. numboxes = 1;
  171502. boxlist[0].c0min = 0;
  171503. boxlist[0].c0max = MAXJSAMPLE >> C0_SHIFT;
  171504. boxlist[0].c1min = 0;
  171505. boxlist[0].c1max = MAXJSAMPLE >> C1_SHIFT;
  171506. boxlist[0].c2min = 0;
  171507. boxlist[0].c2max = MAXJSAMPLE >> C2_SHIFT;
  171508. /* Shrink it to actually-used volume and set its statistics */
  171509. update_box(cinfo, & boxlist[0]);
  171510. /* Perform median-cut to produce final box list */
  171511. numboxes = median_cut(cinfo, boxlist, numboxes, desired_colors);
  171512. /* Compute the representative color for each box, fill colormap */
  171513. for (i = 0; i < numboxes; i++)
  171514. compute_color(cinfo, & boxlist[i], i);
  171515. cinfo->actual_number_of_colors = numboxes;
  171516. TRACEMS1(cinfo, 1, JTRC_QUANT_SELECTED, numboxes);
  171517. }
  171518. /*
  171519. * These routines are concerned with the time-critical task of mapping input
  171520. * colors to the nearest color in the selected colormap.
  171521. *
  171522. * We re-use the histogram space as an "inverse color map", essentially a
  171523. * cache for the results of nearest-color searches. All colors within a
  171524. * histogram cell will be mapped to the same colormap entry, namely the one
  171525. * closest to the cell's center. This may not be quite the closest entry to
  171526. * the actual input color, but it's almost as good. A zero in the cache
  171527. * indicates we haven't found the nearest color for that cell yet; the array
  171528. * is cleared to zeroes before starting the mapping pass. When we find the
  171529. * nearest color for a cell, its colormap index plus one is recorded in the
  171530. * cache for future use. The pass2 scanning routines call fill_inverse_cmap
  171531. * when they need to use an unfilled entry in the cache.
  171532. *
  171533. * Our method of efficiently finding nearest colors is based on the "locally
  171534. * sorted search" idea described by Heckbert and on the incremental distance
  171535. * calculation described by Spencer W. Thomas in chapter III.1 of Graphics
  171536. * Gems II (James Arvo, ed. Academic Press, 1991). Thomas points out that
  171537. * the distances from a given colormap entry to each cell of the histogram can
  171538. * be computed quickly using an incremental method: the differences between
  171539. * distances to adjacent cells themselves differ by a constant. This allows a
  171540. * fairly fast implementation of the "brute force" approach of computing the
  171541. * distance from every colormap entry to every histogram cell. Unfortunately,
  171542. * it needs a work array to hold the best-distance-so-far for each histogram
  171543. * cell (because the inner loop has to be over cells, not colormap entries).
  171544. * The work array elements have to be INT32s, so the work array would need
  171545. * 256Kb at our recommended precision. This is not feasible in DOS machines.
  171546. *
  171547. * To get around these problems, we apply Thomas' method to compute the
  171548. * nearest colors for only the cells within a small subbox of the histogram.
  171549. * The work array need be only as big as the subbox, so the memory usage
  171550. * problem is solved. Furthermore, we need not fill subboxes that are never
  171551. * referenced in pass2; many images use only part of the color gamut, so a
  171552. * fair amount of work is saved. An additional advantage of this
  171553. * approach is that we can apply Heckbert's locality criterion to quickly
  171554. * eliminate colormap entries that are far away from the subbox; typically
  171555. * three-fourths of the colormap entries are rejected by Heckbert's criterion,
  171556. * and we need not compute their distances to individual cells in the subbox.
  171557. * The speed of this approach is heavily influenced by the subbox size: too
  171558. * small means too much overhead, too big loses because Heckbert's criterion
  171559. * can't eliminate as many colormap entries. Empirically the best subbox
  171560. * size seems to be about 1/512th of the histogram (1/8th in each direction).
  171561. *
  171562. * Thomas' article also describes a refined method which is asymptotically
  171563. * faster than the brute-force method, but it is also far more complex and
  171564. * cannot efficiently be applied to small subboxes. It is therefore not
  171565. * useful for programs intended to be portable to DOS machines. On machines
  171566. * with plenty of memory, filling the whole histogram in one shot with Thomas'
  171567. * refined method might be faster than the present code --- but then again,
  171568. * it might not be any faster, and it's certainly more complicated.
  171569. */
  171570. /* log2(histogram cells in update box) for each axis; this can be adjusted */
  171571. #define BOX_C0_LOG (HIST_C0_BITS-3)
  171572. #define BOX_C1_LOG (HIST_C1_BITS-3)
  171573. #define BOX_C2_LOG (HIST_C2_BITS-3)
  171574. #define BOX_C0_ELEMS (1<<BOX_C0_LOG) /* # of hist cells in update box */
  171575. #define BOX_C1_ELEMS (1<<BOX_C1_LOG)
  171576. #define BOX_C2_ELEMS (1<<BOX_C2_LOG)
  171577. #define BOX_C0_SHIFT (C0_SHIFT + BOX_C0_LOG)
  171578. #define BOX_C1_SHIFT (C1_SHIFT + BOX_C1_LOG)
  171579. #define BOX_C2_SHIFT (C2_SHIFT + BOX_C2_LOG)
  171580. /*
  171581. * The next three routines implement inverse colormap filling. They could
  171582. * all be folded into one big routine, but splitting them up this way saves
  171583. * some stack space (the mindist[] and bestdist[] arrays need not coexist)
  171584. * and may allow some compilers to produce better code by registerizing more
  171585. * inner-loop variables.
  171586. */
  171587. LOCAL(int)
  171588. find_nearby_colors (j_decompress_ptr cinfo, int minc0, int minc1, int minc2,
  171589. JSAMPLE colorlist[])
  171590. /* Locate the colormap entries close enough to an update box to be candidates
  171591. * for the nearest entry to some cell(s) in the update box. The update box
  171592. * is specified by the center coordinates of its first cell. The number of
  171593. * candidate colormap entries is returned, and their colormap indexes are
  171594. * placed in colorlist[].
  171595. * This routine uses Heckbert's "locally sorted search" criterion to select
  171596. * the colors that need further consideration.
  171597. */
  171598. {
  171599. int numcolors = cinfo->actual_number_of_colors;
  171600. int maxc0, maxc1, maxc2;
  171601. int centerc0, centerc1, centerc2;
  171602. int i, x, ncolors;
  171603. INT32 minmaxdist, min_dist, max_dist, tdist;
  171604. INT32 mindist[MAXNUMCOLORS]; /* min distance to colormap entry i */
  171605. /* Compute true coordinates of update box's upper corner and center.
  171606. * Actually we compute the coordinates of the center of the upper-corner
  171607. * histogram cell, which are the upper bounds of the volume we care about.
  171608. * Note that since ">>" rounds down, the "center" values may be closer to
  171609. * min than to max; hence comparisons to them must be "<=", not "<".
  171610. */
  171611. maxc0 = minc0 + ((1 << BOX_C0_SHIFT) - (1 << C0_SHIFT));
  171612. centerc0 = (minc0 + maxc0) >> 1;
  171613. maxc1 = minc1 + ((1 << BOX_C1_SHIFT) - (1 << C1_SHIFT));
  171614. centerc1 = (minc1 + maxc1) >> 1;
  171615. maxc2 = minc2 + ((1 << BOX_C2_SHIFT) - (1 << C2_SHIFT));
  171616. centerc2 = (minc2 + maxc2) >> 1;
  171617. /* For each color in colormap, find:
  171618. * 1. its minimum squared-distance to any point in the update box
  171619. * (zero if color is within update box);
  171620. * 2. its maximum squared-distance to any point in the update box.
  171621. * Both of these can be found by considering only the corners of the box.
  171622. * We save the minimum distance for each color in mindist[];
  171623. * only the smallest maximum distance is of interest.
  171624. */
  171625. minmaxdist = 0x7FFFFFFFL;
  171626. for (i = 0; i < numcolors; i++) {
  171627. /* We compute the squared-c0-distance term, then add in the other two. */
  171628. x = GETJSAMPLE(cinfo->colormap[0][i]);
  171629. if (x < minc0) {
  171630. tdist = (x - minc0) * C0_SCALE;
  171631. min_dist = tdist*tdist;
  171632. tdist = (x - maxc0) * C0_SCALE;
  171633. max_dist = tdist*tdist;
  171634. } else if (x > maxc0) {
  171635. tdist = (x - maxc0) * C0_SCALE;
  171636. min_dist = tdist*tdist;
  171637. tdist = (x - minc0) * C0_SCALE;
  171638. max_dist = tdist*tdist;
  171639. } else {
  171640. /* within cell range so no contribution to min_dist */
  171641. min_dist = 0;
  171642. if (x <= centerc0) {
  171643. tdist = (x - maxc0) * C0_SCALE;
  171644. max_dist = tdist*tdist;
  171645. } else {
  171646. tdist = (x - minc0) * C0_SCALE;
  171647. max_dist = tdist*tdist;
  171648. }
  171649. }
  171650. x = GETJSAMPLE(cinfo->colormap[1][i]);
  171651. if (x < minc1) {
  171652. tdist = (x - minc1) * C1_SCALE;
  171653. min_dist += tdist*tdist;
  171654. tdist = (x - maxc1) * C1_SCALE;
  171655. max_dist += tdist*tdist;
  171656. } else if (x > maxc1) {
  171657. tdist = (x - maxc1) * C1_SCALE;
  171658. min_dist += tdist*tdist;
  171659. tdist = (x - minc1) * C1_SCALE;
  171660. max_dist += tdist*tdist;
  171661. } else {
  171662. /* within cell range so no contribution to min_dist */
  171663. if (x <= centerc1) {
  171664. tdist = (x - maxc1) * C1_SCALE;
  171665. max_dist += tdist*tdist;
  171666. } else {
  171667. tdist = (x - minc1) * C1_SCALE;
  171668. max_dist += tdist*tdist;
  171669. }
  171670. }
  171671. x = GETJSAMPLE(cinfo->colormap[2][i]);
  171672. if (x < minc2) {
  171673. tdist = (x - minc2) * C2_SCALE;
  171674. min_dist += tdist*tdist;
  171675. tdist = (x - maxc2) * C2_SCALE;
  171676. max_dist += tdist*tdist;
  171677. } else if (x > maxc2) {
  171678. tdist = (x - maxc2) * C2_SCALE;
  171679. min_dist += tdist*tdist;
  171680. tdist = (x - minc2) * C2_SCALE;
  171681. max_dist += tdist*tdist;
  171682. } else {
  171683. /* within cell range so no contribution to min_dist */
  171684. if (x <= centerc2) {
  171685. tdist = (x - maxc2) * C2_SCALE;
  171686. max_dist += tdist*tdist;
  171687. } else {
  171688. tdist = (x - minc2) * C2_SCALE;
  171689. max_dist += tdist*tdist;
  171690. }
  171691. }
  171692. mindist[i] = min_dist; /* save away the results */
  171693. if (max_dist < minmaxdist)
  171694. minmaxdist = max_dist;
  171695. }
  171696. /* Now we know that no cell in the update box is more than minmaxdist
  171697. * away from some colormap entry. Therefore, only colors that are
  171698. * within minmaxdist of some part of the box need be considered.
  171699. */
  171700. ncolors = 0;
  171701. for (i = 0; i < numcolors; i++) {
  171702. if (mindist[i] <= minmaxdist)
  171703. colorlist[ncolors++] = (JSAMPLE) i;
  171704. }
  171705. return ncolors;
  171706. }
  171707. LOCAL(void)
  171708. find_best_colors (j_decompress_ptr cinfo, int minc0, int minc1, int minc2,
  171709. int numcolors, JSAMPLE colorlist[], JSAMPLE bestcolor[])
  171710. /* Find the closest colormap entry for each cell in the update box,
  171711. * given the list of candidate colors prepared by find_nearby_colors.
  171712. * Return the indexes of the closest entries in the bestcolor[] array.
  171713. * This routine uses Thomas' incremental distance calculation method to
  171714. * find the distance from a colormap entry to successive cells in the box.
  171715. */
  171716. {
  171717. int ic0, ic1, ic2;
  171718. int i, icolor;
  171719. register INT32 * bptr; /* pointer into bestdist[] array */
  171720. JSAMPLE * cptr; /* pointer into bestcolor[] array */
  171721. INT32 dist0, dist1; /* initial distance values */
  171722. register INT32 dist2; /* current distance in inner loop */
  171723. INT32 xx0, xx1; /* distance increments */
  171724. register INT32 xx2;
  171725. INT32 inc0, inc1, inc2; /* initial values for increments */
  171726. /* This array holds the distance to the nearest-so-far color for each cell */
  171727. INT32 bestdist[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS];
  171728. /* Initialize best-distance for each cell of the update box */
  171729. bptr = bestdist;
  171730. for (i = BOX_C0_ELEMS*BOX_C1_ELEMS*BOX_C2_ELEMS-1; i >= 0; i--)
  171731. *bptr++ = 0x7FFFFFFFL;
  171732. /* For each color selected by find_nearby_colors,
  171733. * compute its distance to the center of each cell in the box.
  171734. * If that's less than best-so-far, update best distance and color number.
  171735. */
  171736. /* Nominal steps between cell centers ("x" in Thomas article) */
  171737. #define STEP_C0 ((1 << C0_SHIFT) * C0_SCALE)
  171738. #define STEP_C1 ((1 << C1_SHIFT) * C1_SCALE)
  171739. #define STEP_C2 ((1 << C2_SHIFT) * C2_SCALE)
  171740. for (i = 0; i < numcolors; i++) {
  171741. icolor = GETJSAMPLE(colorlist[i]);
  171742. /* Compute (square of) distance from minc0/c1/c2 to this color */
  171743. inc0 = (minc0 - GETJSAMPLE(cinfo->colormap[0][icolor])) * C0_SCALE;
  171744. dist0 = inc0*inc0;
  171745. inc1 = (minc1 - GETJSAMPLE(cinfo->colormap[1][icolor])) * C1_SCALE;
  171746. dist0 += inc1*inc1;
  171747. inc2 = (minc2 - GETJSAMPLE(cinfo->colormap[2][icolor])) * C2_SCALE;
  171748. dist0 += inc2*inc2;
  171749. /* Form the initial difference increments */
  171750. inc0 = inc0 * (2 * STEP_C0) + STEP_C0 * STEP_C0;
  171751. inc1 = inc1 * (2 * STEP_C1) + STEP_C1 * STEP_C1;
  171752. inc2 = inc2 * (2 * STEP_C2) + STEP_C2 * STEP_C2;
  171753. /* Now loop over all cells in box, updating distance per Thomas method */
  171754. bptr = bestdist;
  171755. cptr = bestcolor;
  171756. xx0 = inc0;
  171757. for (ic0 = BOX_C0_ELEMS-1; ic0 >= 0; ic0--) {
  171758. dist1 = dist0;
  171759. xx1 = inc1;
  171760. for (ic1 = BOX_C1_ELEMS-1; ic1 >= 0; ic1--) {
  171761. dist2 = dist1;
  171762. xx2 = inc2;
  171763. for (ic2 = BOX_C2_ELEMS-1; ic2 >= 0; ic2--) {
  171764. if (dist2 < *bptr) {
  171765. *bptr = dist2;
  171766. *cptr = (JSAMPLE) icolor;
  171767. }
  171768. dist2 += xx2;
  171769. xx2 += 2 * STEP_C2 * STEP_C2;
  171770. bptr++;
  171771. cptr++;
  171772. }
  171773. dist1 += xx1;
  171774. xx1 += 2 * STEP_C1 * STEP_C1;
  171775. }
  171776. dist0 += xx0;
  171777. xx0 += 2 * STEP_C0 * STEP_C0;
  171778. }
  171779. }
  171780. }
  171781. LOCAL(void)
  171782. fill_inverse_cmap (j_decompress_ptr cinfo, int c0, int c1, int c2)
  171783. /* Fill the inverse-colormap entries in the update box that contains */
  171784. /* histogram cell c0/c1/c2. (Only that one cell MUST be filled, but */
  171785. /* we can fill as many others as we wish.) */
  171786. {
  171787. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  171788. hist3d histogram = cquantize->histogram;
  171789. int minc0, minc1, minc2; /* lower left corner of update box */
  171790. int ic0, ic1, ic2;
  171791. register JSAMPLE * cptr; /* pointer into bestcolor[] array */
  171792. register histptr cachep; /* pointer into main cache array */
  171793. /* This array lists the candidate colormap indexes. */
  171794. JSAMPLE colorlist[MAXNUMCOLORS];
  171795. int numcolors; /* number of candidate colors */
  171796. /* This array holds the actually closest colormap index for each cell. */
  171797. JSAMPLE bestcolor[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS];
  171798. /* Convert cell coordinates to update box ID */
  171799. c0 >>= BOX_C0_LOG;
  171800. c1 >>= BOX_C1_LOG;
  171801. c2 >>= BOX_C2_LOG;
  171802. /* Compute true coordinates of update box's origin corner.
  171803. * Actually we compute the coordinates of the center of the corner
  171804. * histogram cell, which are the lower bounds of the volume we care about.
  171805. */
  171806. minc0 = (c0 << BOX_C0_SHIFT) + ((1 << C0_SHIFT) >> 1);
  171807. minc1 = (c1 << BOX_C1_SHIFT) + ((1 << C1_SHIFT) >> 1);
  171808. minc2 = (c2 << BOX_C2_SHIFT) + ((1 << C2_SHIFT) >> 1);
  171809. /* Determine which colormap entries are close enough to be candidates
  171810. * for the nearest entry to some cell in the update box.
  171811. */
  171812. numcolors = find_nearby_colors(cinfo, minc0, minc1, minc2, colorlist);
  171813. /* Determine the actually nearest colors. */
  171814. find_best_colors(cinfo, minc0, minc1, minc2, numcolors, colorlist,
  171815. bestcolor);
  171816. /* Save the best color numbers (plus 1) in the main cache array */
  171817. c0 <<= BOX_C0_LOG; /* convert ID back to base cell indexes */
  171818. c1 <<= BOX_C1_LOG;
  171819. c2 <<= BOX_C2_LOG;
  171820. cptr = bestcolor;
  171821. for (ic0 = 0; ic0 < BOX_C0_ELEMS; ic0++) {
  171822. for (ic1 = 0; ic1 < BOX_C1_ELEMS; ic1++) {
  171823. cachep = & histogram[c0+ic0][c1+ic1][c2];
  171824. for (ic2 = 0; ic2 < BOX_C2_ELEMS; ic2++) {
  171825. *cachep++ = (histcell) (GETJSAMPLE(*cptr++) + 1);
  171826. }
  171827. }
  171828. }
  171829. }
  171830. /*
  171831. * Map some rows of pixels to the output colormapped representation.
  171832. */
  171833. METHODDEF(void)
  171834. pass2_no_dither (j_decompress_ptr cinfo,
  171835. JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows)
  171836. /* This version performs no dithering */
  171837. {
  171838. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  171839. hist3d histogram = cquantize->histogram;
  171840. register JSAMPROW inptr, outptr;
  171841. register histptr cachep;
  171842. register int c0, c1, c2;
  171843. int row;
  171844. JDIMENSION col;
  171845. JDIMENSION width = cinfo->output_width;
  171846. for (row = 0; row < num_rows; row++) {
  171847. inptr = input_buf[row];
  171848. outptr = output_buf[row];
  171849. for (col = width; col > 0; col--) {
  171850. /* get pixel value and index into the cache */
  171851. c0 = GETJSAMPLE(*inptr++) >> C0_SHIFT;
  171852. c1 = GETJSAMPLE(*inptr++) >> C1_SHIFT;
  171853. c2 = GETJSAMPLE(*inptr++) >> C2_SHIFT;
  171854. cachep = & histogram[c0][c1][c2];
  171855. /* If we have not seen this color before, find nearest colormap entry */
  171856. /* and update the cache */
  171857. if (*cachep == 0)
  171858. fill_inverse_cmap(cinfo, c0,c1,c2);
  171859. /* Now emit the colormap index for this cell */
  171860. *outptr++ = (JSAMPLE) (*cachep - 1);
  171861. }
  171862. }
  171863. }
  171864. METHODDEF(void)
  171865. pass2_fs_dither (j_decompress_ptr cinfo,
  171866. JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows)
  171867. /* This version performs Floyd-Steinberg dithering */
  171868. {
  171869. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  171870. hist3d histogram = cquantize->histogram;
  171871. register LOCFSERROR cur0, cur1, cur2; /* current error or pixel value */
  171872. LOCFSERROR belowerr0, belowerr1, belowerr2; /* error for pixel below cur */
  171873. LOCFSERROR bpreverr0, bpreverr1, bpreverr2; /* error for below/prev col */
  171874. register FSERRPTR errorptr; /* => fserrors[] at column before current */
  171875. JSAMPROW inptr; /* => current input pixel */
  171876. JSAMPROW outptr; /* => current output pixel */
  171877. histptr cachep;
  171878. int dir; /* +1 or -1 depending on direction */
  171879. int dir3; /* 3*dir, for advancing inptr & errorptr */
  171880. int row;
  171881. JDIMENSION col;
  171882. JDIMENSION width = cinfo->output_width;
  171883. JSAMPLE *range_limit = cinfo->sample_range_limit;
  171884. int *error_limit = cquantize->error_limiter;
  171885. JSAMPROW colormap0 = cinfo->colormap[0];
  171886. JSAMPROW colormap1 = cinfo->colormap[1];
  171887. JSAMPROW colormap2 = cinfo->colormap[2];
  171888. SHIFT_TEMPS
  171889. for (row = 0; row < num_rows; row++) {
  171890. inptr = input_buf[row];
  171891. outptr = output_buf[row];
  171892. if (cquantize->on_odd_row) {
  171893. /* work right to left in this row */
  171894. inptr += (width-1) * 3; /* so point to rightmost pixel */
  171895. outptr += width-1;
  171896. dir = -1;
  171897. dir3 = -3;
  171898. errorptr = cquantize->fserrors + (width+1)*3; /* => entry after last column */
  171899. cquantize->on_odd_row = FALSE; /* flip for next time */
  171900. } else {
  171901. /* work left to right in this row */
  171902. dir = 1;
  171903. dir3 = 3;
  171904. errorptr = cquantize->fserrors; /* => entry before first real column */
  171905. cquantize->on_odd_row = TRUE; /* flip for next time */
  171906. }
  171907. /* Preset error values: no error propagated to first pixel from left */
  171908. cur0 = cur1 = cur2 = 0;
  171909. /* and no error propagated to row below yet */
  171910. belowerr0 = belowerr1 = belowerr2 = 0;
  171911. bpreverr0 = bpreverr1 = bpreverr2 = 0;
  171912. for (col = width; col > 0; col--) {
  171913. /* curN holds the error propagated from the previous pixel on the
  171914. * current line. Add the error propagated from the previous line
  171915. * to form the complete error correction term for this pixel, and
  171916. * round the error term (which is expressed * 16) to an integer.
  171917. * RIGHT_SHIFT rounds towards minus infinity, so adding 8 is correct
  171918. * for either sign of the error value.
  171919. * Note: errorptr points to *previous* column's array entry.
  171920. */
  171921. cur0 = RIGHT_SHIFT(cur0 + errorptr[dir3+0] + 8, 4);
  171922. cur1 = RIGHT_SHIFT(cur1 + errorptr[dir3+1] + 8, 4);
  171923. cur2 = RIGHT_SHIFT(cur2 + errorptr[dir3+2] + 8, 4);
  171924. /* Limit the error using transfer function set by init_error_limit.
  171925. * See comments with init_error_limit for rationale.
  171926. */
  171927. cur0 = error_limit[cur0];
  171928. cur1 = error_limit[cur1];
  171929. cur2 = error_limit[cur2];
  171930. /* Form pixel value + error, and range-limit to 0..MAXJSAMPLE.
  171931. * The maximum error is +- MAXJSAMPLE (or less with error limiting);
  171932. * this sets the required size of the range_limit array.
  171933. */
  171934. cur0 += GETJSAMPLE(inptr[0]);
  171935. cur1 += GETJSAMPLE(inptr[1]);
  171936. cur2 += GETJSAMPLE(inptr[2]);
  171937. cur0 = GETJSAMPLE(range_limit[cur0]);
  171938. cur1 = GETJSAMPLE(range_limit[cur1]);
  171939. cur2 = GETJSAMPLE(range_limit[cur2]);
  171940. /* Index into the cache with adjusted pixel value */
  171941. cachep = & histogram[cur0>>C0_SHIFT][cur1>>C1_SHIFT][cur2>>C2_SHIFT];
  171942. /* If we have not seen this color before, find nearest colormap */
  171943. /* entry and update the cache */
  171944. if (*cachep == 0)
  171945. fill_inverse_cmap(cinfo, cur0>>C0_SHIFT,cur1>>C1_SHIFT,cur2>>C2_SHIFT);
  171946. /* Now emit the colormap index for this cell */
  171947. { register int pixcode = *cachep - 1;
  171948. *outptr = (JSAMPLE) pixcode;
  171949. /* Compute representation error for this pixel */
  171950. cur0 -= GETJSAMPLE(colormap0[pixcode]);
  171951. cur1 -= GETJSAMPLE(colormap1[pixcode]);
  171952. cur2 -= GETJSAMPLE(colormap2[pixcode]);
  171953. }
  171954. /* Compute error fractions to be propagated to adjacent pixels.
  171955. * Add these into the running sums, and simultaneously shift the
  171956. * next-line error sums left by 1 column.
  171957. */
  171958. { register LOCFSERROR bnexterr, delta;
  171959. bnexterr = cur0; /* Process component 0 */
  171960. delta = cur0 * 2;
  171961. cur0 += delta; /* form error * 3 */
  171962. errorptr[0] = (FSERROR) (bpreverr0 + cur0);
  171963. cur0 += delta; /* form error * 5 */
  171964. bpreverr0 = belowerr0 + cur0;
  171965. belowerr0 = bnexterr;
  171966. cur0 += delta; /* form error * 7 */
  171967. bnexterr = cur1; /* Process component 1 */
  171968. delta = cur1 * 2;
  171969. cur1 += delta; /* form error * 3 */
  171970. errorptr[1] = (FSERROR) (bpreverr1 + cur1);
  171971. cur1 += delta; /* form error * 5 */
  171972. bpreverr1 = belowerr1 + cur1;
  171973. belowerr1 = bnexterr;
  171974. cur1 += delta; /* form error * 7 */
  171975. bnexterr = cur2; /* Process component 2 */
  171976. delta = cur2 * 2;
  171977. cur2 += delta; /* form error * 3 */
  171978. errorptr[2] = (FSERROR) (bpreverr2 + cur2);
  171979. cur2 += delta; /* form error * 5 */
  171980. bpreverr2 = belowerr2 + cur2;
  171981. belowerr2 = bnexterr;
  171982. cur2 += delta; /* form error * 7 */
  171983. }
  171984. /* At this point curN contains the 7/16 error value to be propagated
  171985. * to the next pixel on the current line, and all the errors for the
  171986. * next line have been shifted over. We are therefore ready to move on.
  171987. */
  171988. inptr += dir3; /* Advance pixel pointers to next column */
  171989. outptr += dir;
  171990. errorptr += dir3; /* advance errorptr to current column */
  171991. }
  171992. /* Post-loop cleanup: we must unload the final error values into the
  171993. * final fserrors[] entry. Note we need not unload belowerrN because
  171994. * it is for the dummy column before or after the actual array.
  171995. */
  171996. errorptr[0] = (FSERROR) bpreverr0; /* unload prev errs into array */
  171997. errorptr[1] = (FSERROR) bpreverr1;
  171998. errorptr[2] = (FSERROR) bpreverr2;
  171999. }
  172000. }
  172001. /*
  172002. * Initialize the error-limiting transfer function (lookup table).
  172003. * The raw F-S error computation can potentially compute error values of up to
  172004. * +- MAXJSAMPLE. But we want the maximum correction applied to a pixel to be
  172005. * much less, otherwise obviously wrong pixels will be created. (Typical
  172006. * effects include weird fringes at color-area boundaries, isolated bright
  172007. * pixels in a dark area, etc.) The standard advice for avoiding this problem
  172008. * is to ensure that the "corners" of the color cube are allocated as output
  172009. * colors; then repeated errors in the same direction cannot cause cascading
  172010. * error buildup. However, that only prevents the error from getting
  172011. * completely out of hand; Aaron Giles reports that error limiting improves
  172012. * the results even with corner colors allocated.
  172013. * A simple clamping of the error values to about +- MAXJSAMPLE/8 works pretty
  172014. * well, but the smoother transfer function used below is even better. Thanks
  172015. * to Aaron Giles for this idea.
  172016. */
  172017. LOCAL(void)
  172018. init_error_limit (j_decompress_ptr cinfo)
  172019. /* Allocate and fill in the error_limiter table */
  172020. {
  172021. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  172022. int * table;
  172023. int in, out;
  172024. table = (int *) (*cinfo->mem->alloc_small)
  172025. ((j_common_ptr) cinfo, JPOOL_IMAGE, (MAXJSAMPLE*2+1) * SIZEOF(int));
  172026. table += MAXJSAMPLE; /* so can index -MAXJSAMPLE .. +MAXJSAMPLE */
  172027. cquantize->error_limiter = table;
  172028. #define STEPSIZE ((MAXJSAMPLE+1)/16)
  172029. /* Map errors 1:1 up to +- MAXJSAMPLE/16 */
  172030. out = 0;
  172031. for (in = 0; in < STEPSIZE; in++, out++) {
  172032. table[in] = out; table[-in] = -out;
  172033. }
  172034. /* Map errors 1:2 up to +- 3*MAXJSAMPLE/16 */
  172035. for (; in < STEPSIZE*3; in++, out += (in&1) ? 0 : 1) {
  172036. table[in] = out; table[-in] = -out;
  172037. }
  172038. /* Clamp the rest to final out value (which is (MAXJSAMPLE+1)/8) */
  172039. for (; in <= MAXJSAMPLE; in++) {
  172040. table[in] = out; table[-in] = -out;
  172041. }
  172042. #undef STEPSIZE
  172043. }
  172044. /*
  172045. * Finish up at the end of each pass.
  172046. */
  172047. METHODDEF(void)
  172048. finish_pass1 (j_decompress_ptr cinfo)
  172049. {
  172050. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  172051. /* Select the representative colors and fill in cinfo->colormap */
  172052. cinfo->colormap = cquantize->sv_colormap;
  172053. select_colors(cinfo, cquantize->desired);
  172054. /* Force next pass to zero the color index table */
  172055. cquantize->needs_zeroed = TRUE;
  172056. }
  172057. METHODDEF(void)
  172058. finish_pass2 (j_decompress_ptr cinfo)
  172059. {
  172060. /* no work */
  172061. }
  172062. /*
  172063. * Initialize for each processing pass.
  172064. */
  172065. METHODDEF(void)
  172066. start_pass_2_quant (j_decompress_ptr cinfo, boolean is_pre_scan)
  172067. {
  172068. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  172069. hist3d histogram = cquantize->histogram;
  172070. int i;
  172071. /* Only F-S dithering or no dithering is supported. */
  172072. /* If user asks for ordered dither, give him F-S. */
  172073. if (cinfo->dither_mode != JDITHER_NONE)
  172074. cinfo->dither_mode = JDITHER_FS;
  172075. if (is_pre_scan) {
  172076. /* Set up method pointers */
  172077. cquantize->pub.color_quantize = prescan_quantize;
  172078. cquantize->pub.finish_pass = finish_pass1;
  172079. cquantize->needs_zeroed = TRUE; /* Always zero histogram */
  172080. } else {
  172081. /* Set up method pointers */
  172082. if (cinfo->dither_mode == JDITHER_FS)
  172083. cquantize->pub.color_quantize = pass2_fs_dither;
  172084. else
  172085. cquantize->pub.color_quantize = pass2_no_dither;
  172086. cquantize->pub.finish_pass = finish_pass2;
  172087. /* Make sure color count is acceptable */
  172088. i = cinfo->actual_number_of_colors;
  172089. if (i < 1)
  172090. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, 1);
  172091. if (i > MAXNUMCOLORS)
  172092. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXNUMCOLORS);
  172093. if (cinfo->dither_mode == JDITHER_FS) {
  172094. size_t arraysize = (size_t) ((cinfo->output_width + 2) *
  172095. (3 * SIZEOF(FSERROR)));
  172096. /* Allocate Floyd-Steinberg workspace if we didn't already. */
  172097. if (cquantize->fserrors == NULL)
  172098. cquantize->fserrors = (FSERRPTR) (*cinfo->mem->alloc_large)
  172099. ((j_common_ptr) cinfo, JPOOL_IMAGE, arraysize);
  172100. /* Initialize the propagated errors to zero. */
  172101. jzero_far((void FAR *) cquantize->fserrors, arraysize);
  172102. /* Make the error-limit table if we didn't already. */
  172103. if (cquantize->error_limiter == NULL)
  172104. init_error_limit(cinfo);
  172105. cquantize->on_odd_row = FALSE;
  172106. }
  172107. }
  172108. /* Zero the histogram or inverse color map, if necessary */
  172109. if (cquantize->needs_zeroed) {
  172110. for (i = 0; i < HIST_C0_ELEMS; i++) {
  172111. jzero_far((void FAR *) histogram[i],
  172112. HIST_C1_ELEMS*HIST_C2_ELEMS * SIZEOF(histcell));
  172113. }
  172114. cquantize->needs_zeroed = FALSE;
  172115. }
  172116. }
  172117. /*
  172118. * Switch to a new external colormap between output passes.
  172119. */
  172120. METHODDEF(void)
  172121. new_color_map_2_quant (j_decompress_ptr cinfo)
  172122. {
  172123. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  172124. /* Reset the inverse color map */
  172125. cquantize->needs_zeroed = TRUE;
  172126. }
  172127. /*
  172128. * Module initialization routine for 2-pass color quantization.
  172129. */
  172130. GLOBAL(void)
  172131. jinit_2pass_quantizer (j_decompress_ptr cinfo)
  172132. {
  172133. my_cquantize_ptr2 cquantize;
  172134. int i;
  172135. cquantize = (my_cquantize_ptr2)
  172136. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172137. SIZEOF(my_cquantizer2));
  172138. cinfo->cquantize = (struct jpeg_color_quantizer *) cquantize;
  172139. cquantize->pub.start_pass = start_pass_2_quant;
  172140. cquantize->pub.new_color_map = new_color_map_2_quant;
  172141. cquantize->fserrors = NULL; /* flag optional arrays not allocated */
  172142. cquantize->error_limiter = NULL;
  172143. /* Make sure jdmaster didn't give me a case I can't handle */
  172144. if (cinfo->out_color_components != 3)
  172145. ERREXIT(cinfo, JERR_NOTIMPL);
  172146. /* Allocate the histogram/inverse colormap storage */
  172147. cquantize->histogram = (hist3d) (*cinfo->mem->alloc_small)
  172148. ((j_common_ptr) cinfo, JPOOL_IMAGE, HIST_C0_ELEMS * SIZEOF(hist2d));
  172149. for (i = 0; i < HIST_C0_ELEMS; i++) {
  172150. cquantize->histogram[i] = (hist2d) (*cinfo->mem->alloc_large)
  172151. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172152. HIST_C1_ELEMS*HIST_C2_ELEMS * SIZEOF(histcell));
  172153. }
  172154. cquantize->needs_zeroed = TRUE; /* histogram is garbage now */
  172155. /* Allocate storage for the completed colormap, if required.
  172156. * We do this now since it is FAR storage and may affect
  172157. * the memory manager's space calculations.
  172158. */
  172159. if (cinfo->enable_2pass_quant) {
  172160. /* Make sure color count is acceptable */
  172161. int desired = cinfo->desired_number_of_colors;
  172162. /* Lower bound on # of colors ... somewhat arbitrary as long as > 0 */
  172163. if (desired < 8)
  172164. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, 8);
  172165. /* Make sure colormap indexes can be represented by JSAMPLEs */
  172166. if (desired > MAXNUMCOLORS)
  172167. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXNUMCOLORS);
  172168. cquantize->sv_colormap = (*cinfo->mem->alloc_sarray)
  172169. ((j_common_ptr) cinfo,JPOOL_IMAGE, (JDIMENSION) desired, (JDIMENSION) 3);
  172170. cquantize->desired = desired;
  172171. } else
  172172. cquantize->sv_colormap = NULL;
  172173. /* Only F-S dithering or no dithering is supported. */
  172174. /* If user asks for ordered dither, give him F-S. */
  172175. if (cinfo->dither_mode != JDITHER_NONE)
  172176. cinfo->dither_mode = JDITHER_FS;
  172177. /* Allocate Floyd-Steinberg workspace if necessary.
  172178. * This isn't really needed until pass 2, but again it is FAR storage.
  172179. * Although we will cope with a later change in dither_mode,
  172180. * we do not promise to honor max_memory_to_use if dither_mode changes.
  172181. */
  172182. if (cinfo->dither_mode == JDITHER_FS) {
  172183. cquantize->fserrors = (FSERRPTR) (*cinfo->mem->alloc_large)
  172184. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172185. (size_t) ((cinfo->output_width + 2) * (3 * SIZEOF(FSERROR))));
  172186. /* Might as well create the error-limiting table too. */
  172187. init_error_limit(cinfo);
  172188. }
  172189. }
  172190. #endif /* QUANT_2PASS_SUPPORTED */
  172191. /********* End of inlined file: jquant2.c *********/
  172192. /********* Start of inlined file: jutils.c *********/
  172193. #define JPEG_INTERNALS
  172194. /*
  172195. * jpeg_zigzag_order[i] is the zigzag-order position of the i'th element
  172196. * of a DCT block read in natural order (left to right, top to bottom).
  172197. */
  172198. #if 0 /* This table is not actually needed in v6a */
  172199. const int jpeg_zigzag_order[DCTSIZE2] = {
  172200. 0, 1, 5, 6, 14, 15, 27, 28,
  172201. 2, 4, 7, 13, 16, 26, 29, 42,
  172202. 3, 8, 12, 17, 25, 30, 41, 43,
  172203. 9, 11, 18, 24, 31, 40, 44, 53,
  172204. 10, 19, 23, 32, 39, 45, 52, 54,
  172205. 20, 22, 33, 38, 46, 51, 55, 60,
  172206. 21, 34, 37, 47, 50, 56, 59, 61,
  172207. 35, 36, 48, 49, 57, 58, 62, 63
  172208. };
  172209. #endif
  172210. /*
  172211. * jpeg_natural_order[i] is the natural-order position of the i'th element
  172212. * of zigzag order.
  172213. *
  172214. * When reading corrupted data, the Huffman decoders could attempt
  172215. * to reference an entry beyond the end of this array (if the decoded
  172216. * zero run length reaches past the end of the block). To prevent
  172217. * wild stores without adding an inner-loop test, we put some extra
  172218. * "63"s after the real entries. This will cause the extra coefficient
  172219. * to be stored in location 63 of the block, not somewhere random.
  172220. * The worst case would be a run-length of 15, which means we need 16
  172221. * fake entries.
  172222. */
  172223. const int jpeg_natural_order[DCTSIZE2+16] = {
  172224. 0, 1, 8, 16, 9, 2, 3, 10,
  172225. 17, 24, 32, 25, 18, 11, 4, 5,
  172226. 12, 19, 26, 33, 40, 48, 41, 34,
  172227. 27, 20, 13, 6, 7, 14, 21, 28,
  172228. 35, 42, 49, 56, 57, 50, 43, 36,
  172229. 29, 22, 15, 23, 30, 37, 44, 51,
  172230. 58, 59, 52, 45, 38, 31, 39, 46,
  172231. 53, 60, 61, 54, 47, 55, 62, 63,
  172232. 63, 63, 63, 63, 63, 63, 63, 63, /* extra entries for safety in decoder */
  172233. 63, 63, 63, 63, 63, 63, 63, 63
  172234. };
  172235. /*
  172236. * Arithmetic utilities
  172237. */
  172238. GLOBAL(long)
  172239. jdiv_round_up (long a, long b)
  172240. /* Compute a/b rounded up to next integer, ie, ceil(a/b) */
  172241. /* Assumes a >= 0, b > 0 */
  172242. {
  172243. return (a + b - 1L) / b;
  172244. }
  172245. GLOBAL(long)
  172246. jround_up (long a, long b)
  172247. /* Compute a rounded up to next multiple of b, ie, ceil(a/b)*b */
  172248. /* Assumes a >= 0, b > 0 */
  172249. {
  172250. a += b - 1L;
  172251. return a - (a % b);
  172252. }
  172253. /* On normal machines we can apply MEMCOPY() and MEMZERO() to sample arrays
  172254. * and coefficient-block arrays. This won't work on 80x86 because the arrays
  172255. * are FAR and we're assuming a small-pointer memory model. However, some
  172256. * DOS compilers provide far-pointer versions of memcpy() and memset() even
  172257. * in the small-model libraries. These will be used if USE_FMEM is defined.
  172258. * Otherwise, the routines below do it the hard way. (The performance cost
  172259. * is not all that great, because these routines aren't very heavily used.)
  172260. */
  172261. #ifndef NEED_FAR_POINTERS /* normal case, same as regular macros */
  172262. #define FMEMCOPY(dest,src,size) MEMCOPY(dest,src,size)
  172263. #define FMEMZERO(target,size) MEMZERO(target,size)
  172264. #else /* 80x86 case, define if we can */
  172265. #ifdef USE_FMEM
  172266. #define FMEMCOPY(dest,src,size) _fmemcpy((void FAR *)(dest), (const void FAR *)(src), (size_t)(size))
  172267. #define FMEMZERO(target,size) _fmemset((void FAR *)(target), 0, (size_t)(size))
  172268. #endif
  172269. #endif
  172270. GLOBAL(void)
  172271. jcopy_sample_rows (JSAMPARRAY input_array, int source_row,
  172272. JSAMPARRAY output_array, int dest_row,
  172273. int num_rows, JDIMENSION num_cols)
  172274. /* Copy some rows of samples from one place to another.
  172275. * num_rows rows are copied from input_array[source_row++]
  172276. * to output_array[dest_row++]; these areas may overlap for duplication.
  172277. * The source and destination arrays must be at least as wide as num_cols.
  172278. */
  172279. {
  172280. register JSAMPROW inptr, outptr;
  172281. #ifdef FMEMCOPY
  172282. register size_t count = (size_t) (num_cols * SIZEOF(JSAMPLE));
  172283. #else
  172284. register JDIMENSION count;
  172285. #endif
  172286. register int row;
  172287. input_array += source_row;
  172288. output_array += dest_row;
  172289. for (row = num_rows; row > 0; row--) {
  172290. inptr = *input_array++;
  172291. outptr = *output_array++;
  172292. #ifdef FMEMCOPY
  172293. FMEMCOPY(outptr, inptr, count);
  172294. #else
  172295. for (count = num_cols; count > 0; count--)
  172296. *outptr++ = *inptr++; /* needn't bother with GETJSAMPLE() here */
  172297. #endif
  172298. }
  172299. }
  172300. GLOBAL(void)
  172301. jcopy_block_row (JBLOCKROW input_row, JBLOCKROW output_row,
  172302. JDIMENSION num_blocks)
  172303. /* Copy a row of coefficient blocks from one place to another. */
  172304. {
  172305. #ifdef FMEMCOPY
  172306. FMEMCOPY(output_row, input_row, num_blocks * (DCTSIZE2 * SIZEOF(JCOEF)));
  172307. #else
  172308. register JCOEFPTR inptr, outptr;
  172309. register long count;
  172310. inptr = (JCOEFPTR) input_row;
  172311. outptr = (JCOEFPTR) output_row;
  172312. for (count = (long) num_blocks * DCTSIZE2; count > 0; count--) {
  172313. *outptr++ = *inptr++;
  172314. }
  172315. #endif
  172316. }
  172317. GLOBAL(void)
  172318. jzero_far (void FAR * target, size_t bytestozero)
  172319. /* Zero out a chunk of FAR memory. */
  172320. /* This might be sample-array data, block-array data, or alloc_large data. */
  172321. {
  172322. #ifdef FMEMZERO
  172323. FMEMZERO(target, bytestozero);
  172324. #else
  172325. register char FAR * ptr = (char FAR *) target;
  172326. register size_t count;
  172327. for (count = bytestozero; count > 0; count--) {
  172328. *ptr++ = 0;
  172329. }
  172330. #endif
  172331. }
  172332. /********* End of inlined file: jutils.c *********/
  172333. /********* Start of inlined file: transupp.c *********/
  172334. /* Although this file really shouldn't have access to the library internals,
  172335. * it's helpful to let it call jround_up() and jcopy_block_row().
  172336. */
  172337. #define JPEG_INTERNALS
  172338. /********* Start of inlined file: transupp.h *********/
  172339. /* If you happen not to want the image transform support, disable it here */
  172340. #ifndef TRANSFORMS_SUPPORTED
  172341. #define TRANSFORMS_SUPPORTED 1 /* 0 disables transform code */
  172342. #endif
  172343. /* Short forms of external names for systems with brain-damaged linkers. */
  172344. #ifdef NEED_SHORT_EXTERNAL_NAMES
  172345. #define jtransform_request_workspace jTrRequest
  172346. #define jtransform_adjust_parameters jTrAdjust
  172347. #define jtransform_execute_transformation jTrExec
  172348. #define jcopy_markers_setup jCMrkSetup
  172349. #define jcopy_markers_execute jCMrkExec
  172350. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  172351. /*
  172352. * Codes for supported types of image transformations.
  172353. */
  172354. typedef enum {
  172355. JXFORM_NONE, /* no transformation */
  172356. JXFORM_FLIP_H, /* horizontal flip */
  172357. JXFORM_FLIP_V, /* vertical flip */
  172358. JXFORM_TRANSPOSE, /* transpose across UL-to-LR axis */
  172359. JXFORM_TRANSVERSE, /* transpose across UR-to-LL axis */
  172360. JXFORM_ROT_90, /* 90-degree clockwise rotation */
  172361. JXFORM_ROT_180, /* 180-degree rotation */
  172362. JXFORM_ROT_270 /* 270-degree clockwise (or 90 ccw) */
  172363. } JXFORM_CODE;
  172364. /*
  172365. * Although rotating and flipping data expressed as DCT coefficients is not
  172366. * hard, there is an asymmetry in the JPEG format specification for images
  172367. * whose dimensions aren't multiples of the iMCU size. The right and bottom
  172368. * image edges are padded out to the next iMCU boundary with junk data; but
  172369. * no padding is possible at the top and left edges. If we were to flip
  172370. * the whole image including the pad data, then pad garbage would become
  172371. * visible at the top and/or left, and real pixels would disappear into the
  172372. * pad margins --- perhaps permanently, since encoders & decoders may not
  172373. * bother to preserve DCT blocks that appear to be completely outside the
  172374. * nominal image area. So, we have to exclude any partial iMCUs from the
  172375. * basic transformation.
  172376. *
  172377. * Transpose is the only transformation that can handle partial iMCUs at the
  172378. * right and bottom edges completely cleanly. flip_h can flip partial iMCUs
  172379. * at the bottom, but leaves any partial iMCUs at the right edge untouched.
  172380. * Similarly flip_v leaves any partial iMCUs at the bottom edge untouched.
  172381. * The other transforms are defined as combinations of these basic transforms
  172382. * and process edge blocks in a way that preserves the equivalence.
  172383. *
  172384. * The "trim" option causes untransformable partial iMCUs to be dropped;
  172385. * this is not strictly lossless, but it usually gives the best-looking
  172386. * result for odd-size images. Note that when this option is active,
  172387. * the expected mathematical equivalences between the transforms may not hold.
  172388. * (For example, -rot 270 -trim trims only the bottom edge, but -rot 90 -trim
  172389. * followed by -rot 180 -trim trims both edges.)
  172390. *
  172391. * We also offer a "force to grayscale" option, which simply discards the
  172392. * chrominance channels of a YCbCr image. This is lossless in the sense that
  172393. * the luminance channel is preserved exactly. It's not the same kind of
  172394. * thing as the rotate/flip transformations, but it's convenient to handle it
  172395. * as part of this package, mainly because the transformation routines have to
  172396. * be aware of the option to know how many components to work on.
  172397. */
  172398. typedef struct {
  172399. /* Options: set by caller */
  172400. JXFORM_CODE transform; /* image transform operator */
  172401. boolean trim; /* if TRUE, trim partial MCUs as needed */
  172402. boolean force_grayscale; /* if TRUE, convert color image to grayscale */
  172403. /* Internal workspace: caller should not touch these */
  172404. int num_components; /* # of components in workspace */
  172405. jvirt_barray_ptr * workspace_coef_arrays; /* workspace for transformations */
  172406. } jpeg_transform_info;
  172407. #if TRANSFORMS_SUPPORTED
  172408. /* Request any required workspace */
  172409. EXTERN(void) jtransform_request_workspace
  172410. JPP((j_decompress_ptr srcinfo, jpeg_transform_info *info));
  172411. /* Adjust output image parameters */
  172412. EXTERN(jvirt_barray_ptr *) jtransform_adjust_parameters
  172413. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  172414. jvirt_barray_ptr *src_coef_arrays,
  172415. jpeg_transform_info *info));
  172416. /* Execute the actual transformation, if any */
  172417. EXTERN(void) jtransform_execute_transformation
  172418. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  172419. jvirt_barray_ptr *src_coef_arrays,
  172420. jpeg_transform_info *info));
  172421. #endif /* TRANSFORMS_SUPPORTED */
  172422. /*
  172423. * Support for copying optional markers from source to destination file.
  172424. */
  172425. typedef enum {
  172426. JCOPYOPT_NONE, /* copy no optional markers */
  172427. JCOPYOPT_COMMENTS, /* copy only comment (COM) markers */
  172428. JCOPYOPT_ALL /* copy all optional markers */
  172429. } JCOPY_OPTION;
  172430. #define JCOPYOPT_DEFAULT JCOPYOPT_COMMENTS /* recommended default */
  172431. /* Setup decompression object to save desired markers in memory */
  172432. EXTERN(void) jcopy_markers_setup
  172433. JPP((j_decompress_ptr srcinfo, JCOPY_OPTION option));
  172434. /* Copy markers saved in the given source object to the destination object */
  172435. EXTERN(void) jcopy_markers_execute
  172436. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  172437. JCOPY_OPTION option));
  172438. /********* End of inlined file: transupp.h *********/
  172439. /* My own external interface */
  172440. #if TRANSFORMS_SUPPORTED
  172441. /*
  172442. * Lossless image transformation routines. These routines work on DCT
  172443. * coefficient arrays and thus do not require any lossy decompression
  172444. * or recompression of the image.
  172445. * Thanks to Guido Vollbeding for the initial design and code of this feature.
  172446. *
  172447. * Horizontal flipping is done in-place, using a single top-to-bottom
  172448. * pass through the virtual source array. It will thus be much the
  172449. * fastest option for images larger than main memory.
  172450. *
  172451. * The other routines require a set of destination virtual arrays, so they
  172452. * need twice as much memory as jpegtran normally does. The destination
  172453. * arrays are always written in normal scan order (top to bottom) because
  172454. * the virtual array manager expects this. The source arrays will be scanned
  172455. * in the corresponding order, which means multiple passes through the source
  172456. * arrays for most of the transforms. That could result in much thrashing
  172457. * if the image is larger than main memory.
  172458. *
  172459. * Some notes about the operating environment of the individual transform
  172460. * routines:
  172461. * 1. Both the source and destination virtual arrays are allocated from the
  172462. * source JPEG object, and therefore should be manipulated by calling the
  172463. * source's memory manager.
  172464. * 2. The destination's component count should be used. It may be smaller
  172465. * than the source's when forcing to grayscale.
  172466. * 3. Likewise the destination's sampling factors should be used. When
  172467. * forcing to grayscale the destination's sampling factors will be all 1,
  172468. * and we may as well take that as the effective iMCU size.
  172469. * 4. When "trim" is in effect, the destination's dimensions will be the
  172470. * trimmed values but the source's will be untrimmed.
  172471. * 5. All the routines assume that the source and destination buffers are
  172472. * padded out to a full iMCU boundary. This is true, although for the
  172473. * source buffer it is an undocumented property of jdcoefct.c.
  172474. * Notes 2,3,4 boil down to this: generally we should use the destination's
  172475. * dimensions and ignore the source's.
  172476. */
  172477. LOCAL(void)
  172478. do_flip_h (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  172479. jvirt_barray_ptr *src_coef_arrays)
  172480. /* Horizontal flip; done in-place, so no separate dest array is required */
  172481. {
  172482. JDIMENSION MCU_cols, comp_width, blk_x, blk_y;
  172483. int ci, k, offset_y;
  172484. JBLOCKARRAY buffer;
  172485. JCOEFPTR ptr1, ptr2;
  172486. JCOEF temp1, temp2;
  172487. jpeg_component_info *compptr;
  172488. /* Horizontal mirroring of DCT blocks is accomplished by swapping
  172489. * pairs of blocks in-place. Within a DCT block, we perform horizontal
  172490. * mirroring by changing the signs of odd-numbered columns.
  172491. * Partial iMCUs at the right edge are left untouched.
  172492. */
  172493. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  172494. for (ci = 0; ci < dstinfo->num_components; ci++) {
  172495. compptr = dstinfo->comp_info + ci;
  172496. comp_width = MCU_cols * compptr->h_samp_factor;
  172497. for (blk_y = 0; blk_y < compptr->height_in_blocks;
  172498. blk_y += compptr->v_samp_factor) {
  172499. buffer = (*srcinfo->mem->access_virt_barray)
  172500. ((j_common_ptr) srcinfo, src_coef_arrays[ci], blk_y,
  172501. (JDIMENSION) compptr->v_samp_factor, TRUE);
  172502. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  172503. for (blk_x = 0; blk_x * 2 < comp_width; blk_x++) {
  172504. ptr1 = buffer[offset_y][blk_x];
  172505. ptr2 = buffer[offset_y][comp_width - blk_x - 1];
  172506. /* this unrolled loop doesn't need to know which row it's on... */
  172507. for (k = 0; k < DCTSIZE2; k += 2) {
  172508. temp1 = *ptr1; /* swap even column */
  172509. temp2 = *ptr2;
  172510. *ptr1++ = temp2;
  172511. *ptr2++ = temp1;
  172512. temp1 = *ptr1; /* swap odd column with sign change */
  172513. temp2 = *ptr2;
  172514. *ptr1++ = -temp2;
  172515. *ptr2++ = -temp1;
  172516. }
  172517. }
  172518. }
  172519. }
  172520. }
  172521. }
  172522. LOCAL(void)
  172523. do_flip_v (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  172524. jvirt_barray_ptr *src_coef_arrays,
  172525. jvirt_barray_ptr *dst_coef_arrays)
  172526. /* Vertical flip */
  172527. {
  172528. JDIMENSION MCU_rows, comp_height, dst_blk_x, dst_blk_y;
  172529. int ci, i, j, offset_y;
  172530. JBLOCKARRAY src_buffer, dst_buffer;
  172531. JBLOCKROW src_row_ptr, dst_row_ptr;
  172532. JCOEFPTR src_ptr, dst_ptr;
  172533. jpeg_component_info *compptr;
  172534. /* We output into a separate array because we can't touch different
  172535. * rows of the source virtual array simultaneously. Otherwise, this
  172536. * is a pretty straightforward analog of horizontal flip.
  172537. * Within a DCT block, vertical mirroring is done by changing the signs
  172538. * of odd-numbered rows.
  172539. * Partial iMCUs at the bottom edge are copied verbatim.
  172540. */
  172541. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  172542. for (ci = 0; ci < dstinfo->num_components; ci++) {
  172543. compptr = dstinfo->comp_info + ci;
  172544. comp_height = MCU_rows * compptr->v_samp_factor;
  172545. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  172546. dst_blk_y += compptr->v_samp_factor) {
  172547. dst_buffer = (*srcinfo->mem->access_virt_barray)
  172548. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  172549. (JDIMENSION) compptr->v_samp_factor, TRUE);
  172550. if (dst_blk_y < comp_height) {
  172551. /* Row is within the mirrorable area. */
  172552. src_buffer = (*srcinfo->mem->access_virt_barray)
  172553. ((j_common_ptr) srcinfo, src_coef_arrays[ci],
  172554. comp_height - dst_blk_y - (JDIMENSION) compptr->v_samp_factor,
  172555. (JDIMENSION) compptr->v_samp_factor, FALSE);
  172556. } else {
  172557. /* Bottom-edge blocks will be copied verbatim. */
  172558. src_buffer = (*srcinfo->mem->access_virt_barray)
  172559. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_y,
  172560. (JDIMENSION) compptr->v_samp_factor, FALSE);
  172561. }
  172562. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  172563. if (dst_blk_y < comp_height) {
  172564. /* Row is within the mirrorable area. */
  172565. dst_row_ptr = dst_buffer[offset_y];
  172566. src_row_ptr = src_buffer[compptr->v_samp_factor - offset_y - 1];
  172567. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  172568. dst_blk_x++) {
  172569. dst_ptr = dst_row_ptr[dst_blk_x];
  172570. src_ptr = src_row_ptr[dst_blk_x];
  172571. for (i = 0; i < DCTSIZE; i += 2) {
  172572. /* copy even row */
  172573. for (j = 0; j < DCTSIZE; j++)
  172574. *dst_ptr++ = *src_ptr++;
  172575. /* copy odd row with sign change */
  172576. for (j = 0; j < DCTSIZE; j++)
  172577. *dst_ptr++ = - *src_ptr++;
  172578. }
  172579. }
  172580. } else {
  172581. /* Just copy row verbatim. */
  172582. jcopy_block_row(src_buffer[offset_y], dst_buffer[offset_y],
  172583. compptr->width_in_blocks);
  172584. }
  172585. }
  172586. }
  172587. }
  172588. }
  172589. LOCAL(void)
  172590. do_transpose (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  172591. jvirt_barray_ptr *src_coef_arrays,
  172592. jvirt_barray_ptr *dst_coef_arrays)
  172593. /* Transpose source into destination */
  172594. {
  172595. JDIMENSION dst_blk_x, dst_blk_y;
  172596. int ci, i, j, offset_x, offset_y;
  172597. JBLOCKARRAY src_buffer, dst_buffer;
  172598. JCOEFPTR src_ptr, dst_ptr;
  172599. jpeg_component_info *compptr;
  172600. /* Transposing pixels within a block just requires transposing the
  172601. * DCT coefficients.
  172602. * Partial iMCUs at the edges require no special treatment; we simply
  172603. * process all the available DCT blocks for every component.
  172604. */
  172605. for (ci = 0; ci < dstinfo->num_components; ci++) {
  172606. compptr = dstinfo->comp_info + ci;
  172607. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  172608. dst_blk_y += compptr->v_samp_factor) {
  172609. dst_buffer = (*srcinfo->mem->access_virt_barray)
  172610. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  172611. (JDIMENSION) compptr->v_samp_factor, TRUE);
  172612. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  172613. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  172614. dst_blk_x += compptr->h_samp_factor) {
  172615. src_buffer = (*srcinfo->mem->access_virt_barray)
  172616. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  172617. (JDIMENSION) compptr->h_samp_factor, FALSE);
  172618. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  172619. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  172620. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  172621. for (i = 0; i < DCTSIZE; i++)
  172622. for (j = 0; j < DCTSIZE; j++)
  172623. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  172624. }
  172625. }
  172626. }
  172627. }
  172628. }
  172629. }
  172630. LOCAL(void)
  172631. do_rot_90 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  172632. jvirt_barray_ptr *src_coef_arrays,
  172633. jvirt_barray_ptr *dst_coef_arrays)
  172634. /* 90 degree rotation is equivalent to
  172635. * 1. Transposing the image;
  172636. * 2. Horizontal mirroring.
  172637. * These two steps are merged into a single processing routine.
  172638. */
  172639. {
  172640. JDIMENSION MCU_cols, comp_width, dst_blk_x, dst_blk_y;
  172641. int ci, i, j, offset_x, offset_y;
  172642. JBLOCKARRAY src_buffer, dst_buffer;
  172643. JCOEFPTR src_ptr, dst_ptr;
  172644. jpeg_component_info *compptr;
  172645. /* Because of the horizontal mirror step, we can't process partial iMCUs
  172646. * at the (output) right edge properly. They just get transposed and
  172647. * not mirrored.
  172648. */
  172649. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  172650. for (ci = 0; ci < dstinfo->num_components; ci++) {
  172651. compptr = dstinfo->comp_info + ci;
  172652. comp_width = MCU_cols * compptr->h_samp_factor;
  172653. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  172654. dst_blk_y += compptr->v_samp_factor) {
  172655. dst_buffer = (*srcinfo->mem->access_virt_barray)
  172656. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  172657. (JDIMENSION) compptr->v_samp_factor, TRUE);
  172658. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  172659. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  172660. dst_blk_x += compptr->h_samp_factor) {
  172661. src_buffer = (*srcinfo->mem->access_virt_barray)
  172662. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  172663. (JDIMENSION) compptr->h_samp_factor, FALSE);
  172664. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  172665. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  172666. if (dst_blk_x < comp_width) {
  172667. /* Block is within the mirrorable area. */
  172668. dst_ptr = dst_buffer[offset_y]
  172669. [comp_width - dst_blk_x - offset_x - 1];
  172670. for (i = 0; i < DCTSIZE; i++) {
  172671. for (j = 0; j < DCTSIZE; j++)
  172672. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  172673. i++;
  172674. for (j = 0; j < DCTSIZE; j++)
  172675. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  172676. }
  172677. } else {
  172678. /* Edge blocks are transposed but not mirrored. */
  172679. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  172680. for (i = 0; i < DCTSIZE; i++)
  172681. for (j = 0; j < DCTSIZE; j++)
  172682. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  172683. }
  172684. }
  172685. }
  172686. }
  172687. }
  172688. }
  172689. }
  172690. LOCAL(void)
  172691. do_rot_270 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  172692. jvirt_barray_ptr *src_coef_arrays,
  172693. jvirt_barray_ptr *dst_coef_arrays)
  172694. /* 270 degree rotation is equivalent to
  172695. * 1. Horizontal mirroring;
  172696. * 2. Transposing the image.
  172697. * These two steps are merged into a single processing routine.
  172698. */
  172699. {
  172700. JDIMENSION MCU_rows, comp_height, dst_blk_x, dst_blk_y;
  172701. int ci, i, j, offset_x, offset_y;
  172702. JBLOCKARRAY src_buffer, dst_buffer;
  172703. JCOEFPTR src_ptr, dst_ptr;
  172704. jpeg_component_info *compptr;
  172705. /* Because of the horizontal mirror step, we can't process partial iMCUs
  172706. * at the (output) bottom edge properly. They just get transposed and
  172707. * not mirrored.
  172708. */
  172709. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  172710. for (ci = 0; ci < dstinfo->num_components; ci++) {
  172711. compptr = dstinfo->comp_info + ci;
  172712. comp_height = MCU_rows * compptr->v_samp_factor;
  172713. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  172714. dst_blk_y += compptr->v_samp_factor) {
  172715. dst_buffer = (*srcinfo->mem->access_virt_barray)
  172716. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  172717. (JDIMENSION) compptr->v_samp_factor, TRUE);
  172718. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  172719. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  172720. dst_blk_x += compptr->h_samp_factor) {
  172721. src_buffer = (*srcinfo->mem->access_virt_barray)
  172722. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  172723. (JDIMENSION) compptr->h_samp_factor, FALSE);
  172724. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  172725. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  172726. if (dst_blk_y < comp_height) {
  172727. /* Block is within the mirrorable area. */
  172728. src_ptr = src_buffer[offset_x]
  172729. [comp_height - dst_blk_y - offset_y - 1];
  172730. for (i = 0; i < DCTSIZE; i++) {
  172731. for (j = 0; j < DCTSIZE; j++) {
  172732. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  172733. j++;
  172734. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  172735. }
  172736. }
  172737. } else {
  172738. /* Edge blocks are transposed but not mirrored. */
  172739. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  172740. for (i = 0; i < DCTSIZE; i++)
  172741. for (j = 0; j < DCTSIZE; j++)
  172742. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  172743. }
  172744. }
  172745. }
  172746. }
  172747. }
  172748. }
  172749. }
  172750. LOCAL(void)
  172751. do_rot_180 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  172752. jvirt_barray_ptr *src_coef_arrays,
  172753. jvirt_barray_ptr *dst_coef_arrays)
  172754. /* 180 degree rotation is equivalent to
  172755. * 1. Vertical mirroring;
  172756. * 2. Horizontal mirroring.
  172757. * These two steps are merged into a single processing routine.
  172758. */
  172759. {
  172760. JDIMENSION MCU_cols, MCU_rows, comp_width, comp_height, dst_blk_x, dst_blk_y;
  172761. int ci, i, j, offset_y;
  172762. JBLOCKARRAY src_buffer, dst_buffer;
  172763. JBLOCKROW src_row_ptr, dst_row_ptr;
  172764. JCOEFPTR src_ptr, dst_ptr;
  172765. jpeg_component_info *compptr;
  172766. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  172767. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  172768. for (ci = 0; ci < dstinfo->num_components; ci++) {
  172769. compptr = dstinfo->comp_info + ci;
  172770. comp_width = MCU_cols * compptr->h_samp_factor;
  172771. comp_height = MCU_rows * compptr->v_samp_factor;
  172772. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  172773. dst_blk_y += compptr->v_samp_factor) {
  172774. dst_buffer = (*srcinfo->mem->access_virt_barray)
  172775. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  172776. (JDIMENSION) compptr->v_samp_factor, TRUE);
  172777. if (dst_blk_y < comp_height) {
  172778. /* Row is within the vertically mirrorable area. */
  172779. src_buffer = (*srcinfo->mem->access_virt_barray)
  172780. ((j_common_ptr) srcinfo, src_coef_arrays[ci],
  172781. comp_height - dst_blk_y - (JDIMENSION) compptr->v_samp_factor,
  172782. (JDIMENSION) compptr->v_samp_factor, FALSE);
  172783. } else {
  172784. /* Bottom-edge rows are only mirrored horizontally. */
  172785. src_buffer = (*srcinfo->mem->access_virt_barray)
  172786. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_y,
  172787. (JDIMENSION) compptr->v_samp_factor, FALSE);
  172788. }
  172789. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  172790. if (dst_blk_y < comp_height) {
  172791. /* Row is within the mirrorable area. */
  172792. dst_row_ptr = dst_buffer[offset_y];
  172793. src_row_ptr = src_buffer[compptr->v_samp_factor - offset_y - 1];
  172794. /* Process the blocks that can be mirrored both ways. */
  172795. for (dst_blk_x = 0; dst_blk_x < comp_width; dst_blk_x++) {
  172796. dst_ptr = dst_row_ptr[dst_blk_x];
  172797. src_ptr = src_row_ptr[comp_width - dst_blk_x - 1];
  172798. for (i = 0; i < DCTSIZE; i += 2) {
  172799. /* For even row, negate every odd column. */
  172800. for (j = 0; j < DCTSIZE; j += 2) {
  172801. *dst_ptr++ = *src_ptr++;
  172802. *dst_ptr++ = - *src_ptr++;
  172803. }
  172804. /* For odd row, negate every even column. */
  172805. for (j = 0; j < DCTSIZE; j += 2) {
  172806. *dst_ptr++ = - *src_ptr++;
  172807. *dst_ptr++ = *src_ptr++;
  172808. }
  172809. }
  172810. }
  172811. /* Any remaining right-edge blocks are only mirrored vertically. */
  172812. for (; dst_blk_x < compptr->width_in_blocks; dst_blk_x++) {
  172813. dst_ptr = dst_row_ptr[dst_blk_x];
  172814. src_ptr = src_row_ptr[dst_blk_x];
  172815. for (i = 0; i < DCTSIZE; i += 2) {
  172816. for (j = 0; j < DCTSIZE; j++)
  172817. *dst_ptr++ = *src_ptr++;
  172818. for (j = 0; j < DCTSIZE; j++)
  172819. *dst_ptr++ = - *src_ptr++;
  172820. }
  172821. }
  172822. } else {
  172823. /* Remaining rows are just mirrored horizontally. */
  172824. dst_row_ptr = dst_buffer[offset_y];
  172825. src_row_ptr = src_buffer[offset_y];
  172826. /* Process the blocks that can be mirrored. */
  172827. for (dst_blk_x = 0; dst_blk_x < comp_width; dst_blk_x++) {
  172828. dst_ptr = dst_row_ptr[dst_blk_x];
  172829. src_ptr = src_row_ptr[comp_width - dst_blk_x - 1];
  172830. for (i = 0; i < DCTSIZE2; i += 2) {
  172831. *dst_ptr++ = *src_ptr++;
  172832. *dst_ptr++ = - *src_ptr++;
  172833. }
  172834. }
  172835. /* Any remaining right-edge blocks are only copied. */
  172836. for (; dst_blk_x < compptr->width_in_blocks; dst_blk_x++) {
  172837. dst_ptr = dst_row_ptr[dst_blk_x];
  172838. src_ptr = src_row_ptr[dst_blk_x];
  172839. for (i = 0; i < DCTSIZE2; i++)
  172840. *dst_ptr++ = *src_ptr++;
  172841. }
  172842. }
  172843. }
  172844. }
  172845. }
  172846. }
  172847. LOCAL(void)
  172848. do_transverse (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  172849. jvirt_barray_ptr *src_coef_arrays,
  172850. jvirt_barray_ptr *dst_coef_arrays)
  172851. /* Transverse transpose is equivalent to
  172852. * 1. 180 degree rotation;
  172853. * 2. Transposition;
  172854. * or
  172855. * 1. Horizontal mirroring;
  172856. * 2. Transposition;
  172857. * 3. Horizontal mirroring.
  172858. * These steps are merged into a single processing routine.
  172859. */
  172860. {
  172861. JDIMENSION MCU_cols, MCU_rows, comp_width, comp_height, dst_blk_x, dst_blk_y;
  172862. int ci, i, j, offset_x, offset_y;
  172863. JBLOCKARRAY src_buffer, dst_buffer;
  172864. JCOEFPTR src_ptr, dst_ptr;
  172865. jpeg_component_info *compptr;
  172866. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  172867. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  172868. for (ci = 0; ci < dstinfo->num_components; ci++) {
  172869. compptr = dstinfo->comp_info + ci;
  172870. comp_width = MCU_cols * compptr->h_samp_factor;
  172871. comp_height = MCU_rows * compptr->v_samp_factor;
  172872. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  172873. dst_blk_y += compptr->v_samp_factor) {
  172874. dst_buffer = (*srcinfo->mem->access_virt_barray)
  172875. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  172876. (JDIMENSION) compptr->v_samp_factor, TRUE);
  172877. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  172878. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  172879. dst_blk_x += compptr->h_samp_factor) {
  172880. src_buffer = (*srcinfo->mem->access_virt_barray)
  172881. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  172882. (JDIMENSION) compptr->h_samp_factor, FALSE);
  172883. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  172884. if (dst_blk_y < comp_height) {
  172885. src_ptr = src_buffer[offset_x]
  172886. [comp_height - dst_blk_y - offset_y - 1];
  172887. if (dst_blk_x < comp_width) {
  172888. /* Block is within the mirrorable area. */
  172889. dst_ptr = dst_buffer[offset_y]
  172890. [comp_width - dst_blk_x - offset_x - 1];
  172891. for (i = 0; i < DCTSIZE; i++) {
  172892. for (j = 0; j < DCTSIZE; j++) {
  172893. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  172894. j++;
  172895. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  172896. }
  172897. i++;
  172898. for (j = 0; j < DCTSIZE; j++) {
  172899. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  172900. j++;
  172901. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  172902. }
  172903. }
  172904. } else {
  172905. /* Right-edge blocks are mirrored in y only */
  172906. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  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. j++;
  172911. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  172912. }
  172913. }
  172914. }
  172915. } else {
  172916. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  172917. if (dst_blk_x < comp_width) {
  172918. /* Bottom-edge blocks are mirrored in x only */
  172919. dst_ptr = dst_buffer[offset_y]
  172920. [comp_width - dst_blk_x - offset_x - 1];
  172921. for (i = 0; i < DCTSIZE; i++) {
  172922. for (j = 0; j < DCTSIZE; j++)
  172923. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  172924. i++;
  172925. for (j = 0; j < DCTSIZE; j++)
  172926. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  172927. }
  172928. } else {
  172929. /* At lower right corner, just transpose, no mirroring */
  172930. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  172931. for (i = 0; i < DCTSIZE; i++)
  172932. for (j = 0; j < DCTSIZE; j++)
  172933. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  172934. }
  172935. }
  172936. }
  172937. }
  172938. }
  172939. }
  172940. }
  172941. }
  172942. /* Request any required workspace.
  172943. *
  172944. * We allocate the workspace virtual arrays from the source decompression
  172945. * object, so that all the arrays (both the original data and the workspace)
  172946. * will be taken into account while making memory management decisions.
  172947. * Hence, this routine must be called after jpeg_read_header (which reads
  172948. * the image dimensions) and before jpeg_read_coefficients (which realizes
  172949. * the source's virtual arrays).
  172950. */
  172951. GLOBAL(void)
  172952. jtransform_request_workspace (j_decompress_ptr srcinfo,
  172953. jpeg_transform_info *info)
  172954. {
  172955. jvirt_barray_ptr *coef_arrays = NULL;
  172956. jpeg_component_info *compptr;
  172957. int ci;
  172958. if (info->force_grayscale &&
  172959. srcinfo->jpeg_color_space == JCS_YCbCr &&
  172960. srcinfo->num_components == 3) {
  172961. /* We'll only process the first component */
  172962. info->num_components = 1;
  172963. } else {
  172964. /* Process all the components */
  172965. info->num_components = srcinfo->num_components;
  172966. }
  172967. switch (info->transform) {
  172968. case JXFORM_NONE:
  172969. case JXFORM_FLIP_H:
  172970. /* Don't need a workspace array */
  172971. break;
  172972. case JXFORM_FLIP_V:
  172973. case JXFORM_ROT_180:
  172974. /* Need workspace arrays having same dimensions as source image.
  172975. * Note that we allocate arrays padded out to the next iMCU boundary,
  172976. * so that transform routines need not worry about missing edge blocks.
  172977. */
  172978. coef_arrays = (jvirt_barray_ptr *)
  172979. (*srcinfo->mem->alloc_small) ((j_common_ptr) srcinfo, JPOOL_IMAGE,
  172980. SIZEOF(jvirt_barray_ptr) * info->num_components);
  172981. for (ci = 0; ci < info->num_components; ci++) {
  172982. compptr = srcinfo->comp_info + ci;
  172983. coef_arrays[ci] = (*srcinfo->mem->request_virt_barray)
  172984. ((j_common_ptr) srcinfo, JPOOL_IMAGE, FALSE,
  172985. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  172986. (long) compptr->h_samp_factor),
  172987. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  172988. (long) compptr->v_samp_factor),
  172989. (JDIMENSION) compptr->v_samp_factor);
  172990. }
  172991. break;
  172992. case JXFORM_TRANSPOSE:
  172993. case JXFORM_TRANSVERSE:
  172994. case JXFORM_ROT_90:
  172995. case JXFORM_ROT_270:
  172996. /* Need workspace arrays having transposed dimensions.
  172997. * Note that we allocate arrays padded out to the next iMCU boundary,
  172998. * so that transform routines need not worry about missing edge blocks.
  172999. */
  173000. coef_arrays = (jvirt_barray_ptr *)
  173001. (*srcinfo->mem->alloc_small) ((j_common_ptr) srcinfo, JPOOL_IMAGE,
  173002. SIZEOF(jvirt_barray_ptr) * info->num_components);
  173003. for (ci = 0; ci < info->num_components; ci++) {
  173004. compptr = srcinfo->comp_info + ci;
  173005. coef_arrays[ci] = (*srcinfo->mem->request_virt_barray)
  173006. ((j_common_ptr) srcinfo, JPOOL_IMAGE, FALSE,
  173007. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  173008. (long) compptr->v_samp_factor),
  173009. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  173010. (long) compptr->h_samp_factor),
  173011. (JDIMENSION) compptr->h_samp_factor);
  173012. }
  173013. break;
  173014. }
  173015. info->workspace_coef_arrays = coef_arrays;
  173016. }
  173017. /* Transpose destination image parameters */
  173018. LOCAL(void)
  173019. transpose_critical_parameters (j_compress_ptr dstinfo)
  173020. {
  173021. int tblno, i, j, ci, itemp;
  173022. jpeg_component_info *compptr;
  173023. JQUANT_TBL *qtblptr;
  173024. JDIMENSION dtemp;
  173025. UINT16 qtemp;
  173026. /* Transpose basic image dimensions */
  173027. dtemp = dstinfo->image_width;
  173028. dstinfo->image_width = dstinfo->image_height;
  173029. dstinfo->image_height = dtemp;
  173030. /* Transpose sampling factors */
  173031. for (ci = 0; ci < dstinfo->num_components; ci++) {
  173032. compptr = dstinfo->comp_info + ci;
  173033. itemp = compptr->h_samp_factor;
  173034. compptr->h_samp_factor = compptr->v_samp_factor;
  173035. compptr->v_samp_factor = itemp;
  173036. }
  173037. /* Transpose quantization tables */
  173038. for (tblno = 0; tblno < NUM_QUANT_TBLS; tblno++) {
  173039. qtblptr = dstinfo->quant_tbl_ptrs[tblno];
  173040. if (qtblptr != NULL) {
  173041. for (i = 0; i < DCTSIZE; i++) {
  173042. for (j = 0; j < i; j++) {
  173043. qtemp = qtblptr->quantval[i*DCTSIZE+j];
  173044. qtblptr->quantval[i*DCTSIZE+j] = qtblptr->quantval[j*DCTSIZE+i];
  173045. qtblptr->quantval[j*DCTSIZE+i] = qtemp;
  173046. }
  173047. }
  173048. }
  173049. }
  173050. }
  173051. /* Trim off any partial iMCUs on the indicated destination edge */
  173052. LOCAL(void)
  173053. trim_right_edge (j_compress_ptr dstinfo)
  173054. {
  173055. int ci, max_h_samp_factor;
  173056. JDIMENSION MCU_cols;
  173057. /* We have to compute max_h_samp_factor ourselves,
  173058. * because it hasn't been set yet in the destination
  173059. * (and we don't want to use the source's value).
  173060. */
  173061. max_h_samp_factor = 1;
  173062. for (ci = 0; ci < dstinfo->num_components; ci++) {
  173063. int h_samp_factor = dstinfo->comp_info[ci].h_samp_factor;
  173064. max_h_samp_factor = MAX(max_h_samp_factor, h_samp_factor);
  173065. }
  173066. MCU_cols = dstinfo->image_width / (max_h_samp_factor * DCTSIZE);
  173067. if (MCU_cols > 0) /* can't trim to 0 pixels */
  173068. dstinfo->image_width = MCU_cols * (max_h_samp_factor * DCTSIZE);
  173069. }
  173070. LOCAL(void)
  173071. trim_bottom_edge (j_compress_ptr dstinfo)
  173072. {
  173073. int ci, max_v_samp_factor;
  173074. JDIMENSION MCU_rows;
  173075. /* We have to compute max_v_samp_factor ourselves,
  173076. * because it hasn't been set yet in the destination
  173077. * (and we don't want to use the source's value).
  173078. */
  173079. max_v_samp_factor = 1;
  173080. for (ci = 0; ci < dstinfo->num_components; ci++) {
  173081. int v_samp_factor = dstinfo->comp_info[ci].v_samp_factor;
  173082. max_v_samp_factor = MAX(max_v_samp_factor, v_samp_factor);
  173083. }
  173084. MCU_rows = dstinfo->image_height / (max_v_samp_factor * DCTSIZE);
  173085. if (MCU_rows > 0) /* can't trim to 0 pixels */
  173086. dstinfo->image_height = MCU_rows * (max_v_samp_factor * DCTSIZE);
  173087. }
  173088. /* Adjust output image parameters as needed.
  173089. *
  173090. * This must be called after jpeg_copy_critical_parameters()
  173091. * and before jpeg_write_coefficients().
  173092. *
  173093. * The return value is the set of virtual coefficient arrays to be written
  173094. * (either the ones allocated by jtransform_request_workspace, or the
  173095. * original source data arrays). The caller will need to pass this value
  173096. * to jpeg_write_coefficients().
  173097. */
  173098. GLOBAL(jvirt_barray_ptr *)
  173099. jtransform_adjust_parameters (j_decompress_ptr srcinfo,
  173100. j_compress_ptr dstinfo,
  173101. jvirt_barray_ptr *src_coef_arrays,
  173102. jpeg_transform_info *info)
  173103. {
  173104. /* If force-to-grayscale is requested, adjust destination parameters */
  173105. if (info->force_grayscale) {
  173106. /* We use jpeg_set_colorspace to make sure subsidiary settings get fixed
  173107. * properly. Among other things, the target h_samp_factor & v_samp_factor
  173108. * will get set to 1, which typically won't match the source.
  173109. * In fact we do this even if the source is already grayscale; that
  173110. * provides an easy way of coercing a grayscale JPEG with funny sampling
  173111. * factors to the customary 1,1. (Some decoders fail on other factors.)
  173112. */
  173113. if ((dstinfo->jpeg_color_space == JCS_YCbCr &&
  173114. dstinfo->num_components == 3) ||
  173115. (dstinfo->jpeg_color_space == JCS_GRAYSCALE &&
  173116. dstinfo->num_components == 1)) {
  173117. /* We have to preserve the source's quantization table number. */
  173118. int sv_quant_tbl_no = dstinfo->comp_info[0].quant_tbl_no;
  173119. jpeg_set_colorspace(dstinfo, JCS_GRAYSCALE);
  173120. dstinfo->comp_info[0].quant_tbl_no = sv_quant_tbl_no;
  173121. } else {
  173122. /* Sorry, can't do it */
  173123. ERREXIT(dstinfo, JERR_CONVERSION_NOTIMPL);
  173124. }
  173125. }
  173126. /* Correct the destination's image dimensions etc if necessary */
  173127. switch (info->transform) {
  173128. case JXFORM_NONE:
  173129. /* Nothing to do */
  173130. break;
  173131. case JXFORM_FLIP_H:
  173132. if (info->trim)
  173133. trim_right_edge(dstinfo);
  173134. break;
  173135. case JXFORM_FLIP_V:
  173136. if (info->trim)
  173137. trim_bottom_edge(dstinfo);
  173138. break;
  173139. case JXFORM_TRANSPOSE:
  173140. transpose_critical_parameters(dstinfo);
  173141. /* transpose does NOT have to trim anything */
  173142. break;
  173143. case JXFORM_TRANSVERSE:
  173144. transpose_critical_parameters(dstinfo);
  173145. if (info->trim) {
  173146. trim_right_edge(dstinfo);
  173147. trim_bottom_edge(dstinfo);
  173148. }
  173149. break;
  173150. case JXFORM_ROT_90:
  173151. transpose_critical_parameters(dstinfo);
  173152. if (info->trim)
  173153. trim_right_edge(dstinfo);
  173154. break;
  173155. case JXFORM_ROT_180:
  173156. if (info->trim) {
  173157. trim_right_edge(dstinfo);
  173158. trim_bottom_edge(dstinfo);
  173159. }
  173160. break;
  173161. case JXFORM_ROT_270:
  173162. transpose_critical_parameters(dstinfo);
  173163. if (info->trim)
  173164. trim_bottom_edge(dstinfo);
  173165. break;
  173166. }
  173167. /* Return the appropriate output data set */
  173168. if (info->workspace_coef_arrays != NULL)
  173169. return info->workspace_coef_arrays;
  173170. return src_coef_arrays;
  173171. }
  173172. /* Execute the actual transformation, if any.
  173173. *
  173174. * This must be called *after* jpeg_write_coefficients, because it depends
  173175. * on jpeg_write_coefficients to have computed subsidiary values such as
  173176. * the per-component width and height fields in the destination object.
  173177. *
  173178. * Note that some transformations will modify the source data arrays!
  173179. */
  173180. GLOBAL(void)
  173181. jtransform_execute_transformation (j_decompress_ptr srcinfo,
  173182. j_compress_ptr dstinfo,
  173183. jvirt_barray_ptr *src_coef_arrays,
  173184. jpeg_transform_info *info)
  173185. {
  173186. jvirt_barray_ptr *dst_coef_arrays = info->workspace_coef_arrays;
  173187. switch (info->transform) {
  173188. case JXFORM_NONE:
  173189. break;
  173190. case JXFORM_FLIP_H:
  173191. do_flip_h(srcinfo, dstinfo, src_coef_arrays);
  173192. break;
  173193. case JXFORM_FLIP_V:
  173194. do_flip_v(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  173195. break;
  173196. case JXFORM_TRANSPOSE:
  173197. do_transpose(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  173198. break;
  173199. case JXFORM_TRANSVERSE:
  173200. do_transverse(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  173201. break;
  173202. case JXFORM_ROT_90:
  173203. do_rot_90(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  173204. break;
  173205. case JXFORM_ROT_180:
  173206. do_rot_180(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  173207. break;
  173208. case JXFORM_ROT_270:
  173209. do_rot_270(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  173210. break;
  173211. }
  173212. }
  173213. #endif /* TRANSFORMS_SUPPORTED */
  173214. /* Setup decompression object to save desired markers in memory.
  173215. * This must be called before jpeg_read_header() to have the desired effect.
  173216. */
  173217. GLOBAL(void)
  173218. jcopy_markers_setup (j_decompress_ptr srcinfo, JCOPY_OPTION option)
  173219. {
  173220. #ifdef SAVE_MARKERS_SUPPORTED
  173221. int m;
  173222. /* Save comments except under NONE option */
  173223. if (option != JCOPYOPT_NONE) {
  173224. jpeg_save_markers(srcinfo, JPEG_COM, 0xFFFF);
  173225. }
  173226. /* Save all types of APPn markers iff ALL option */
  173227. if (option == JCOPYOPT_ALL) {
  173228. for (m = 0; m < 16; m++)
  173229. jpeg_save_markers(srcinfo, JPEG_APP0 + m, 0xFFFF);
  173230. }
  173231. #endif /* SAVE_MARKERS_SUPPORTED */
  173232. }
  173233. /* Copy markers saved in the given source object to the destination object.
  173234. * This should be called just after jpeg_start_compress() or
  173235. * jpeg_write_coefficients().
  173236. * Note that those routines will have written the SOI, and also the
  173237. * JFIF APP0 or Adobe APP14 markers if selected.
  173238. */
  173239. GLOBAL(void)
  173240. jcopy_markers_execute (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  173241. JCOPY_OPTION option)
  173242. {
  173243. jpeg_saved_marker_ptr marker;
  173244. /* In the current implementation, we don't actually need to examine the
  173245. * option flag here; we just copy everything that got saved.
  173246. * But to avoid confusion, we do not output JFIF and Adobe APP14 markers
  173247. * if the encoder library already wrote one.
  173248. */
  173249. for (marker = srcinfo->marker_list; marker != NULL; marker = marker->next) {
  173250. if (dstinfo->write_JFIF_header &&
  173251. marker->marker == JPEG_APP0 &&
  173252. marker->data_length >= 5 &&
  173253. GETJOCTET(marker->data[0]) == 0x4A &&
  173254. GETJOCTET(marker->data[1]) == 0x46 &&
  173255. GETJOCTET(marker->data[2]) == 0x49 &&
  173256. GETJOCTET(marker->data[3]) == 0x46 &&
  173257. GETJOCTET(marker->data[4]) == 0)
  173258. continue; /* reject duplicate JFIF */
  173259. if (dstinfo->write_Adobe_marker &&
  173260. marker->marker == JPEG_APP0+14 &&
  173261. marker->data_length >= 5 &&
  173262. GETJOCTET(marker->data[0]) == 0x41 &&
  173263. GETJOCTET(marker->data[1]) == 0x64 &&
  173264. GETJOCTET(marker->data[2]) == 0x6F &&
  173265. GETJOCTET(marker->data[3]) == 0x62 &&
  173266. GETJOCTET(marker->data[4]) == 0x65)
  173267. continue; /* reject duplicate Adobe */
  173268. #ifdef NEED_FAR_POINTERS
  173269. /* We could use jpeg_write_marker if the data weren't FAR... */
  173270. {
  173271. unsigned int i;
  173272. jpeg_write_m_header(dstinfo, marker->marker, marker->data_length);
  173273. for (i = 0; i < marker->data_length; i++)
  173274. jpeg_write_m_byte(dstinfo, marker->data[i]);
  173275. }
  173276. #else
  173277. jpeg_write_marker(dstinfo, marker->marker,
  173278. marker->data, marker->data_length);
  173279. #endif
  173280. }
  173281. }
  173282. /********* End of inlined file: transupp.c *********/
  173283. }
  173284. }
  173285. #if JUCE_MSVC
  173286. #pragma warning (pop)
  173287. #endif
  173288. BEGIN_JUCE_NAMESPACE
  173289. using namespace jpeglibNamespace;
  173290. struct JPEGDecodingFailure {};
  173291. static void fatalErrorHandler (j_common_ptr)
  173292. {
  173293. throw JPEGDecodingFailure();
  173294. }
  173295. static void silentErrorCallback1 (j_common_ptr) {}
  173296. static void silentErrorCallback2 (j_common_ptr, int) {}
  173297. static void silentErrorCallback3 (j_common_ptr, char*) {}
  173298. static void setupSilentErrorHandler (struct jpeg_error_mgr& err)
  173299. {
  173300. zerostruct (err);
  173301. err.error_exit = fatalErrorHandler;
  173302. err.emit_message = silentErrorCallback2;
  173303. err.output_message = silentErrorCallback1;
  173304. err.format_message = silentErrorCallback3;
  173305. err.reset_error_mgr = silentErrorCallback1;
  173306. }
  173307. static void dummyCallback1 (j_decompress_ptr) throw()
  173308. {
  173309. }
  173310. static void jpegSkip (j_decompress_ptr decompStruct, long num) throw()
  173311. {
  173312. decompStruct->src->next_input_byte += num;
  173313. num = jmin (num, (int) decompStruct->src->bytes_in_buffer);
  173314. decompStruct->src->bytes_in_buffer -= num;
  173315. }
  173316. static boolean jpegFill (j_decompress_ptr) throw()
  173317. {
  173318. return 0;
  173319. }
  173320. Image* juce_loadJPEGImageFromStream (InputStream& in) throw()
  173321. {
  173322. MemoryBlock mb;
  173323. in.readIntoMemoryBlock (mb);
  173324. Image* image = 0;
  173325. if (mb.getSize() > 16)
  173326. {
  173327. struct jpeg_decompress_struct jpegDecompStruct;
  173328. struct jpeg_error_mgr jerr;
  173329. setupSilentErrorHandler (jerr);
  173330. jpegDecompStruct.err = &jerr;
  173331. jpeg_create_decompress (&jpegDecompStruct);
  173332. jpegDecompStruct.src = (jpeg_source_mgr*)(jpegDecompStruct.mem->alloc_small)
  173333. ((j_common_ptr)(&jpegDecompStruct), JPOOL_PERMANENT, sizeof (jpeg_source_mgr));
  173334. jpegDecompStruct.src->init_source = dummyCallback1;
  173335. jpegDecompStruct.src->fill_input_buffer = jpegFill;
  173336. jpegDecompStruct.src->skip_input_data = jpegSkip;
  173337. jpegDecompStruct.src->resync_to_restart = jpeg_resync_to_restart;
  173338. jpegDecompStruct.src->term_source = dummyCallback1;
  173339. jpegDecompStruct.src->next_input_byte = (const unsigned char*) mb.getData();
  173340. jpegDecompStruct.src->bytes_in_buffer = mb.getSize();
  173341. try
  173342. {
  173343. jpeg_read_header (&jpegDecompStruct, TRUE);
  173344. jpeg_calc_output_dimensions (&jpegDecompStruct);
  173345. const int width = jpegDecompStruct.output_width;
  173346. const int height = jpegDecompStruct.output_height;
  173347. jpegDecompStruct.out_color_space = JCS_RGB;
  173348. JSAMPARRAY buffer
  173349. = (*jpegDecompStruct.mem->alloc_sarray) ((j_common_ptr) &jpegDecompStruct,
  173350. JPOOL_IMAGE,
  173351. width * 3, 1);
  173352. if (jpeg_start_decompress (&jpegDecompStruct))
  173353. {
  173354. image = new Image (Image::RGB, width, height, false);
  173355. for (int y = 0; y < height; ++y)
  173356. {
  173357. jpeg_read_scanlines (&jpegDecompStruct, buffer, 1);
  173358. int stride, pixelStride;
  173359. uint8* pixels = image->lockPixelDataReadWrite (0, y, width, 1, stride, pixelStride);
  173360. const uint8* src = *buffer;
  173361. uint8* dest = pixels;
  173362. for (int i = width; --i >= 0;)
  173363. {
  173364. ((PixelRGB*) dest)->setARGB (0, src[0], src[1], src[2]);
  173365. dest += pixelStride;
  173366. src += 3;
  173367. }
  173368. image->releasePixelDataReadWrite (pixels);
  173369. }
  173370. jpeg_finish_decompress (&jpegDecompStruct);
  173371. }
  173372. jpeg_destroy_decompress (&jpegDecompStruct);
  173373. }
  173374. catch (...)
  173375. {}
  173376. }
  173377. return image;
  173378. }
  173379. static const int bufferSize = 512;
  173380. struct JuceJpegDest : public jpeg_destination_mgr
  173381. {
  173382. OutputStream* output;
  173383. char* buffer;
  173384. };
  173385. static void jpegWriteInit (j_compress_ptr) throw()
  173386. {
  173387. }
  173388. static void jpegWriteTerminate (j_compress_ptr cinfo) throw()
  173389. {
  173390. JuceJpegDest* const dest = (JuceJpegDest*) cinfo->dest;
  173391. const int numToWrite = bufferSize - dest->free_in_buffer;
  173392. dest->output->write (dest->buffer, numToWrite);
  173393. }
  173394. static boolean jpegWriteFlush (j_compress_ptr cinfo) throw()
  173395. {
  173396. JuceJpegDest* const dest = (JuceJpegDest*) cinfo->dest;
  173397. const int numToWrite = bufferSize;
  173398. dest->next_output_byte = (JOCTET*) dest->buffer;
  173399. dest->free_in_buffer = bufferSize;
  173400. return dest->output->write (dest->buffer, numToWrite);
  173401. }
  173402. bool juce_writeJPEGImageToStream (const Image& image,
  173403. OutputStream& out,
  173404. float quality) throw()
  173405. {
  173406. if (image.hasAlphaChannel())
  173407. {
  173408. // this method could fill the background in white and still save the image..
  173409. jassertfalse
  173410. return true;
  173411. }
  173412. struct jpeg_compress_struct jpegCompStruct;
  173413. struct jpeg_error_mgr jerr;
  173414. setupSilentErrorHandler (jerr);
  173415. jpegCompStruct.err = &jerr;
  173416. jpeg_create_compress (&jpegCompStruct);
  173417. JuceJpegDest dest;
  173418. jpegCompStruct.dest = &dest;
  173419. dest.output = &out;
  173420. dest.buffer = (char*) juce_malloc (bufferSize);
  173421. dest.next_output_byte = (JOCTET*) dest.buffer;
  173422. dest.free_in_buffer = bufferSize;
  173423. dest.init_destination = jpegWriteInit;
  173424. dest.empty_output_buffer = jpegWriteFlush;
  173425. dest.term_destination = jpegWriteTerminate;
  173426. jpegCompStruct.image_width = image.getWidth();
  173427. jpegCompStruct.image_height = image.getHeight();
  173428. jpegCompStruct.input_components = 3;
  173429. jpegCompStruct.in_color_space = JCS_RGB;
  173430. jpegCompStruct.write_JFIF_header = 1;
  173431. jpegCompStruct.X_density = 72;
  173432. jpegCompStruct.Y_density = 72;
  173433. jpeg_set_defaults (&jpegCompStruct);
  173434. jpegCompStruct.dct_method = JDCT_FLOAT;
  173435. jpegCompStruct.optimize_coding = 1;
  173436. // jpegCompStruct.smoothing_factor = 10;
  173437. if (quality < 0.0f)
  173438. quality = 6.0f;
  173439. jpeg_set_quality (&jpegCompStruct, jlimit (0, 100, roundFloatToInt (quality * 100.0f)), TRUE);
  173440. jpeg_start_compress (&jpegCompStruct, TRUE);
  173441. const int strideBytes = jpegCompStruct.image_width * jpegCompStruct.input_components;
  173442. JSAMPARRAY buffer = (*jpegCompStruct.mem->alloc_sarray) ((j_common_ptr) &jpegCompStruct,
  173443. JPOOL_IMAGE,
  173444. strideBytes, 1);
  173445. while (jpegCompStruct.next_scanline < jpegCompStruct.image_height)
  173446. {
  173447. int stride, pixelStride;
  173448. const uint8* pixels = image.lockPixelDataReadOnly (0, jpegCompStruct.next_scanline, jpegCompStruct.image_width, 1, stride, pixelStride);
  173449. const uint8* src = pixels;
  173450. uint8* dst = *buffer;
  173451. for (int i = jpegCompStruct.image_width; --i >= 0;)
  173452. {
  173453. *dst++ = ((const PixelRGB*) src)->getRed();
  173454. *dst++ = ((const PixelRGB*) src)->getGreen();
  173455. *dst++ = ((const PixelRGB*) src)->getBlue();
  173456. src += pixelStride;
  173457. }
  173458. jpeg_write_scanlines (&jpegCompStruct, buffer, 1);
  173459. image.releasePixelDataReadOnly (pixels);
  173460. }
  173461. jpeg_finish_compress (&jpegCompStruct);
  173462. jpeg_destroy_compress (&jpegCompStruct);
  173463. juce_free (dest.buffer);
  173464. out.flush();
  173465. return true;
  173466. }
  173467. END_JUCE_NAMESPACE
  173468. /********* End of inlined file: juce_JPEGLoader.cpp *********/
  173469. /********* Start of inlined file: juce_PNGLoader.cpp *********/
  173470. #ifdef _MSC_VER
  173471. #pragma warning (push)
  173472. #pragma warning (disable: 4390 4611)
  173473. #endif
  173474. namespace zlibNamespace
  173475. {
  173476. #undef OS_CODE
  173477. #undef fdopen
  173478. #undef OS_CODE
  173479. }
  173480. namespace pnglibNamespace
  173481. {
  173482. using namespace zlibNamespace;
  173483. using ::malloc;
  173484. using ::free;
  173485. extern "C"
  173486. {
  173487. using ::abs;
  173488. #define PNG_INTERNAL
  173489. #define NO_DUMMY_DECL
  173490. #define PNG_SETJMP_NOT_SUPPORTED
  173491. /********* Start of inlined file: png.h *********/
  173492. /* png.h - header file for PNG reference library
  173493. *
  173494. * libpng version 1.2.21 - October 4, 2007
  173495. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  173496. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  173497. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  173498. *
  173499. * Authors and maintainers:
  173500. * libpng versions 0.71, May 1995, through 0.88, January 1996: Guy Schalnat
  173501. * libpng versions 0.89c, June 1996, through 0.96, May 1997: Andreas Dilger
  173502. * libpng versions 0.97, January 1998, through 1.2.21 - October 4, 2007: Glenn
  173503. * See also "Contributing Authors", below.
  173504. *
  173505. * Note about libpng version numbers:
  173506. *
  173507. * Due to various miscommunications, unforeseen code incompatibilities
  173508. * and occasional factors outside the authors' control, version numbering
  173509. * on the library has not always been consistent and straightforward.
  173510. * The following table summarizes matters since version 0.89c, which was
  173511. * the first widely used release:
  173512. *
  173513. * source png.h png.h shared-lib
  173514. * version string int version
  173515. * ------- ------ ----- ----------
  173516. * 0.89c "1.0 beta 3" 0.89 89 1.0.89
  173517. * 0.90 "1.0 beta 4" 0.90 90 0.90 [should have been 2.0.90]
  173518. * 0.95 "1.0 beta 5" 0.95 95 0.95 [should have been 2.0.95]
  173519. * 0.96 "1.0 beta 6" 0.96 96 0.96 [should have been 2.0.96]
  173520. * 0.97b "1.00.97 beta 7" 1.00.97 97 1.0.1 [should have been 2.0.97]
  173521. * 0.97c 0.97 97 2.0.97
  173522. * 0.98 0.98 98 2.0.98
  173523. * 0.99 0.99 98 2.0.99
  173524. * 0.99a-m 0.99 99 2.0.99
  173525. * 1.00 1.00 100 2.1.0 [100 should be 10000]
  173526. * 1.0.0 (from here on, the 100 2.1.0 [100 should be 10000]
  173527. * 1.0.1 png.h string is 10001 2.1.0
  173528. * 1.0.1a-e identical to the 10002 from here on, the shared library
  173529. * 1.0.2 source version) 10002 is 2.V where V is the source code
  173530. * 1.0.2a-b 10003 version, except as noted.
  173531. * 1.0.3 10003
  173532. * 1.0.3a-d 10004
  173533. * 1.0.4 10004
  173534. * 1.0.4a-f 10005
  173535. * 1.0.5 (+ 2 patches) 10005
  173536. * 1.0.5a-d 10006
  173537. * 1.0.5e-r 10100 (not source compatible)
  173538. * 1.0.5s-v 10006 (not binary compatible)
  173539. * 1.0.6 (+ 3 patches) 10006 (still binary incompatible)
  173540. * 1.0.6d-f 10007 (still binary incompatible)
  173541. * 1.0.6g 10007
  173542. * 1.0.6h 10007 10.6h (testing xy.z so-numbering)
  173543. * 1.0.6i 10007 10.6i
  173544. * 1.0.6j 10007 2.1.0.6j (incompatible with 1.0.0)
  173545. * 1.0.7beta11-14 DLLNUM 10007 2.1.0.7beta11-14 (binary compatible)
  173546. * 1.0.7beta15-18 1 10007 2.1.0.7beta15-18 (binary compatible)
  173547. * 1.0.7rc1-2 1 10007 2.1.0.7rc1-2 (binary compatible)
  173548. * 1.0.7 1 10007 (still compatible)
  173549. * 1.0.8beta1-4 1 10008 2.1.0.8beta1-4
  173550. * 1.0.8rc1 1 10008 2.1.0.8rc1
  173551. * 1.0.8 1 10008 2.1.0.8
  173552. * 1.0.9beta1-6 1 10009 2.1.0.9beta1-6
  173553. * 1.0.9rc1 1 10009 2.1.0.9rc1
  173554. * 1.0.9beta7-10 1 10009 2.1.0.9beta7-10
  173555. * 1.0.9rc2 1 10009 2.1.0.9rc2
  173556. * 1.0.9 1 10009 2.1.0.9
  173557. * 1.0.10beta1 1 10010 2.1.0.10beta1
  173558. * 1.0.10rc1 1 10010 2.1.0.10rc1
  173559. * 1.0.10 1 10010 2.1.0.10
  173560. * 1.0.11beta1-3 1 10011 2.1.0.11beta1-3
  173561. * 1.0.11rc1 1 10011 2.1.0.11rc1
  173562. * 1.0.11 1 10011 2.1.0.11
  173563. * 1.0.12beta1-2 2 10012 2.1.0.12beta1-2
  173564. * 1.0.12rc1 2 10012 2.1.0.12rc1
  173565. * 1.0.12 2 10012 2.1.0.12
  173566. * 1.1.0a-f - 10100 2.1.1.0a-f (branch abandoned)
  173567. * 1.2.0beta1-2 2 10200 2.1.2.0beta1-2
  173568. * 1.2.0beta3-5 3 10200 3.1.2.0beta3-5
  173569. * 1.2.0rc1 3 10200 3.1.2.0rc1
  173570. * 1.2.0 3 10200 3.1.2.0
  173571. * 1.2.1beta1-4 3 10201 3.1.2.1beta1-4
  173572. * 1.2.1rc1-2 3 10201 3.1.2.1rc1-2
  173573. * 1.2.1 3 10201 3.1.2.1
  173574. * 1.2.2beta1-6 12 10202 12.so.0.1.2.2beta1-6
  173575. * 1.0.13beta1 10 10013 10.so.0.1.0.13beta1
  173576. * 1.0.13rc1 10 10013 10.so.0.1.0.13rc1
  173577. * 1.2.2rc1 12 10202 12.so.0.1.2.2rc1
  173578. * 1.0.13 10 10013 10.so.0.1.0.13
  173579. * 1.2.2 12 10202 12.so.0.1.2.2
  173580. * 1.2.3rc1-6 12 10203 12.so.0.1.2.3rc1-6
  173581. * 1.2.3 12 10203 12.so.0.1.2.3
  173582. * 1.2.4beta1-3 13 10204 12.so.0.1.2.4beta1-3
  173583. * 1.0.14rc1 13 10014 10.so.0.1.0.14rc1
  173584. * 1.2.4rc1 13 10204 12.so.0.1.2.4rc1
  173585. * 1.0.14 10 10014 10.so.0.1.0.14
  173586. * 1.2.4 13 10204 12.so.0.1.2.4
  173587. * 1.2.5beta1-2 13 10205 12.so.0.1.2.5beta1-2
  173588. * 1.0.15rc1-3 10 10015 10.so.0.1.0.15rc1-3
  173589. * 1.2.5rc1-3 13 10205 12.so.0.1.2.5rc1-3
  173590. * 1.0.15 10 10015 10.so.0.1.0.15
  173591. * 1.2.5 13 10205 12.so.0.1.2.5
  173592. * 1.2.6beta1-4 13 10206 12.so.0.1.2.6beta1-4
  173593. * 1.0.16 10 10016 10.so.0.1.0.16
  173594. * 1.2.6 13 10206 12.so.0.1.2.6
  173595. * 1.2.7beta1-2 13 10207 12.so.0.1.2.7beta1-2
  173596. * 1.0.17rc1 10 10017 10.so.0.1.0.17rc1
  173597. * 1.2.7rc1 13 10207 12.so.0.1.2.7rc1
  173598. * 1.0.17 10 10017 10.so.0.1.0.17
  173599. * 1.2.7 13 10207 12.so.0.1.2.7
  173600. * 1.2.8beta1-5 13 10208 12.so.0.1.2.8beta1-5
  173601. * 1.0.18rc1-5 10 10018 10.so.0.1.0.18rc1-5
  173602. * 1.2.8rc1-5 13 10208 12.so.0.1.2.8rc1-5
  173603. * 1.0.18 10 10018 10.so.0.1.0.18
  173604. * 1.2.8 13 10208 12.so.0.1.2.8
  173605. * 1.2.9beta1-3 13 10209 12.so.0.1.2.9beta1-3
  173606. * 1.2.9beta4-11 13 10209 12.so.0.9[.0]
  173607. * 1.2.9rc1 13 10209 12.so.0.9[.0]
  173608. * 1.2.9 13 10209 12.so.0.9[.0]
  173609. * 1.2.10beta1-8 13 10210 12.so.0.10[.0]
  173610. * 1.2.10rc1-3 13 10210 12.so.0.10[.0]
  173611. * 1.2.10 13 10210 12.so.0.10[.0]
  173612. * 1.2.11beta1-4 13 10211 12.so.0.11[.0]
  173613. * 1.0.19rc1-5 10 10019 10.so.0.19[.0]
  173614. * 1.2.11rc1-5 13 10211 12.so.0.11[.0]
  173615. * 1.0.19 10 10019 10.so.0.19[.0]
  173616. * 1.2.11 13 10211 12.so.0.11[.0]
  173617. * 1.0.20 10 10020 10.so.0.20[.0]
  173618. * 1.2.12 13 10212 12.so.0.12[.0]
  173619. * 1.2.13beta1 13 10213 12.so.0.13[.0]
  173620. * 1.0.21 10 10021 10.so.0.21[.0]
  173621. * 1.2.13 13 10213 12.so.0.13[.0]
  173622. * 1.2.14beta1-2 13 10214 12.so.0.14[.0]
  173623. * 1.0.22rc1 10 10022 10.so.0.22[.0]
  173624. * 1.2.14rc1 13 10214 12.so.0.14[.0]
  173625. * 1.0.22 10 10022 10.so.0.22[.0]
  173626. * 1.2.14 13 10214 12.so.0.14[.0]
  173627. * 1.2.15beta1-6 13 10215 12.so.0.15[.0]
  173628. * 1.0.23rc1-5 10 10023 10.so.0.23[.0]
  173629. * 1.2.15rc1-5 13 10215 12.so.0.15[.0]
  173630. * 1.0.23 10 10023 10.so.0.23[.0]
  173631. * 1.2.15 13 10215 12.so.0.15[.0]
  173632. * 1.2.16beta1-2 13 10216 12.so.0.16[.0]
  173633. * 1.2.16rc1 13 10216 12.so.0.16[.0]
  173634. * 1.0.24 10 10024 10.so.0.24[.0]
  173635. * 1.2.16 13 10216 12.so.0.16[.0]
  173636. * 1.2.17beta1-2 13 10217 12.so.0.17[.0]
  173637. * 1.0.25rc1 10 10025 10.so.0.25[.0]
  173638. * 1.2.17rc1-3 13 10217 12.so.0.17[.0]
  173639. * 1.0.25 10 10025 10.so.0.25[.0]
  173640. * 1.2.17 13 10217 12.so.0.17[.0]
  173641. * 1.0.26 10 10026 10.so.0.26[.0]
  173642. * 1.2.18 13 10218 12.so.0.18[.0]
  173643. * 1.2.19beta1-31 13 10219 12.so.0.19[.0]
  173644. * 1.0.27rc1-6 10 10027 10.so.0.27[.0]
  173645. * 1.2.19rc1-6 13 10219 12.so.0.19[.0]
  173646. * 1.0.27 10 10027 10.so.0.27[.0]
  173647. * 1.2.19 13 10219 12.so.0.19[.0]
  173648. * 1.2.20beta01-04 13 10220 12.so.0.20[.0]
  173649. * 1.0.28rc1-6 10 10028 10.so.0.28[.0]
  173650. * 1.2.20rc1-6 13 10220 12.so.0.20[.0]
  173651. * 1.0.28 10 10028 10.so.0.28[.0]
  173652. * 1.2.20 13 10220 12.so.0.20[.0]
  173653. * 1.2.21beta1-2 13 10221 12.so.0.21[.0]
  173654. * 1.2.21rc1-3 13 10221 12.so.0.21[.0]
  173655. * 1.0.29 10 10029 10.so.0.29[.0]
  173656. * 1.2.21 13 10221 12.so.0.21[.0]
  173657. *
  173658. * Henceforth the source version will match the shared-library major
  173659. * and minor numbers; the shared-library major version number will be
  173660. * used for changes in backward compatibility, as it is intended. The
  173661. * PNG_LIBPNG_VER macro, which is not used within libpng but is available
  173662. * for applications, is an unsigned integer of the form xyyzz corresponding
  173663. * to the source version x.y.z (leading zeros in y and z). Beta versions
  173664. * were given the previous public release number plus a letter, until
  173665. * version 1.0.6j; from then on they were given the upcoming public
  173666. * release number plus "betaNN" or "rcN".
  173667. *
  173668. * Binary incompatibility exists only when applications make direct access
  173669. * to the info_ptr or png_ptr members through png.h, and the compiled
  173670. * application is loaded with a different version of the library.
  173671. *
  173672. * DLLNUM will change each time there are forward or backward changes
  173673. * in binary compatibility (e.g., when a new feature is added).
  173674. *
  173675. * See libpng.txt or libpng.3 for more information. The PNG specification
  173676. * is available as a W3C Recommendation and as an ISO Specification,
  173677. * <http://www.w3.org/TR/2003/REC-PNG-20031110/
  173678. */
  173679. /*
  173680. * COPYRIGHT NOTICE, DISCLAIMER, and LICENSE:
  173681. *
  173682. * If you modify libpng you may insert additional notices immediately following
  173683. * this sentence.
  173684. *
  173685. * libpng versions 1.2.6, August 15, 2004, through 1.2.21, October 4, 2007, are
  173686. * Copyright (c) 2004, 2006-2007 Glenn Randers-Pehrson, and are
  173687. * distributed according to the same disclaimer and license as libpng-1.2.5
  173688. * with the following individual added to the list of Contributing Authors:
  173689. *
  173690. * Cosmin Truta
  173691. *
  173692. * libpng versions 1.0.7, July 1, 2000, through 1.2.5, October 3, 2002, are
  173693. * Copyright (c) 2000-2002 Glenn Randers-Pehrson, and are
  173694. * distributed according to the same disclaimer and license as libpng-1.0.6
  173695. * with the following individuals added to the list of Contributing Authors:
  173696. *
  173697. * Simon-Pierre Cadieux
  173698. * Eric S. Raymond
  173699. * Gilles Vollant
  173700. *
  173701. * and with the following additions to the disclaimer:
  173702. *
  173703. * There is no warranty against interference with your enjoyment of the
  173704. * library or against infringement. There is no warranty that our
  173705. * efforts or the library will fulfill any of your particular purposes
  173706. * or needs. This library is provided with all faults, and the entire
  173707. * risk of satisfactory quality, performance, accuracy, and effort is with
  173708. * the user.
  173709. *
  173710. * libpng versions 0.97, January 1998, through 1.0.6, March 20, 2000, are
  173711. * Copyright (c) 1998, 1999, 2000 Glenn Randers-Pehrson, and are
  173712. * distributed according to the same disclaimer and license as libpng-0.96,
  173713. * with the following individuals added to the list of Contributing Authors:
  173714. *
  173715. * Tom Lane
  173716. * Glenn Randers-Pehrson
  173717. * Willem van Schaik
  173718. *
  173719. * libpng versions 0.89, June 1996, through 0.96, May 1997, are
  173720. * Copyright (c) 1996, 1997 Andreas Dilger
  173721. * Distributed according to the same disclaimer and license as libpng-0.88,
  173722. * with the following individuals added to the list of Contributing Authors:
  173723. *
  173724. * John Bowler
  173725. * Kevin Bracey
  173726. * Sam Bushell
  173727. * Magnus Holmgren
  173728. * Greg Roelofs
  173729. * Tom Tanner
  173730. *
  173731. * libpng versions 0.5, May 1995, through 0.88, January 1996, are
  173732. * Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.
  173733. *
  173734. * For the purposes of this copyright and license, "Contributing Authors"
  173735. * is defined as the following set of individuals:
  173736. *
  173737. * Andreas Dilger
  173738. * Dave Martindale
  173739. * Guy Eric Schalnat
  173740. * Paul Schmidt
  173741. * Tim Wegner
  173742. *
  173743. * The PNG Reference Library is supplied "AS IS". The Contributing Authors
  173744. * and Group 42, Inc. disclaim all warranties, expressed or implied,
  173745. * including, without limitation, the warranties of merchantability and of
  173746. * fitness for any purpose. The Contributing Authors and Group 42, Inc.
  173747. * assume no liability for direct, indirect, incidental, special, exemplary,
  173748. * or consequential damages, which may result from the use of the PNG
  173749. * Reference Library, even if advised of the possibility of such damage.
  173750. *
  173751. * Permission is hereby granted to use, copy, modify, and distribute this
  173752. * source code, or portions hereof, for any purpose, without fee, subject
  173753. * to the following restrictions:
  173754. *
  173755. * 1. The origin of this source code must not be misrepresented.
  173756. *
  173757. * 2. Altered versions must be plainly marked as such and
  173758. * must not be misrepresented as being the original source.
  173759. *
  173760. * 3. This Copyright notice may not be removed or altered from
  173761. * any source or altered source distribution.
  173762. *
  173763. * The Contributing Authors and Group 42, Inc. specifically permit, without
  173764. * fee, and encourage the use of this source code as a component to
  173765. * supporting the PNG file format in commercial products. If you use this
  173766. * source code in a product, acknowledgment is not required but would be
  173767. * appreciated.
  173768. */
  173769. /*
  173770. * A "png_get_copyright" function is available, for convenient use in "about"
  173771. * boxes and the like:
  173772. *
  173773. * printf("%s",png_get_copyright(NULL));
  173774. *
  173775. * Also, the PNG logo (in PNG format, of course) is supplied in the
  173776. * files "pngbar.png" and "pngbar.jpg (88x31) and "pngnow.png" (98x31).
  173777. */
  173778. /*
  173779. * Libpng is OSI Certified Open Source Software. OSI Certified is a
  173780. * certification mark of the Open Source Initiative.
  173781. */
  173782. /*
  173783. * The contributing authors would like to thank all those who helped
  173784. * with testing, bug fixes, and patience. This wouldn't have been
  173785. * possible without all of you.
  173786. *
  173787. * Thanks to Frank J. T. Wojcik for helping with the documentation.
  173788. */
  173789. /*
  173790. * Y2K compliance in libpng:
  173791. * =========================
  173792. *
  173793. * October 4, 2007
  173794. *
  173795. * Since the PNG Development group is an ad-hoc body, we can't make
  173796. * an official declaration.
  173797. *
  173798. * This is your unofficial assurance that libpng from version 0.71 and
  173799. * upward through 1.2.21 are Y2K compliant. It is my belief that earlier
  173800. * versions were also Y2K compliant.
  173801. *
  173802. * Libpng only has three year fields. One is a 2-byte unsigned integer
  173803. * that will hold years up to 65535. The other two hold the date in text
  173804. * format, and will hold years up to 9999.
  173805. *
  173806. * The integer is
  173807. * "png_uint_16 year" in png_time_struct.
  173808. *
  173809. * The strings are
  173810. * "png_charp time_buffer" in png_struct and
  173811. * "near_time_buffer", which is a local character string in png.c.
  173812. *
  173813. * There are seven time-related functions:
  173814. * png.c: png_convert_to_rfc_1123() in png.c
  173815. * (formerly png_convert_to_rfc_1152() in error)
  173816. * png_convert_from_struct_tm() in pngwrite.c, called in pngwrite.c
  173817. * png_convert_from_time_t() in pngwrite.c
  173818. * png_get_tIME() in pngget.c
  173819. * png_handle_tIME() in pngrutil.c, called in pngread.c
  173820. * png_set_tIME() in pngset.c
  173821. * png_write_tIME() in pngwutil.c, called in pngwrite.c
  173822. *
  173823. * All handle dates properly in a Y2K environment. The
  173824. * png_convert_from_time_t() function calls gmtime() to convert from system
  173825. * clock time, which returns (year - 1900), which we properly convert to
  173826. * the full 4-digit year. There is a possibility that applications using
  173827. * libpng are not passing 4-digit years into the png_convert_to_rfc_1123()
  173828. * function, or that they are incorrectly passing only a 2-digit year
  173829. * instead of "year - 1900" into the png_convert_from_struct_tm() function,
  173830. * but this is not under our control. The libpng documentation has always
  173831. * stated that it works with 4-digit years, and the APIs have been
  173832. * documented as such.
  173833. *
  173834. * The tIME chunk itself is also Y2K compliant. It uses a 2-byte unsigned
  173835. * integer to hold the year, and can hold years as large as 65535.
  173836. *
  173837. * zlib, upon which libpng depends, is also Y2K compliant. It contains
  173838. * no date-related code.
  173839. *
  173840. * Glenn Randers-Pehrson
  173841. * libpng maintainer
  173842. * PNG Development Group
  173843. */
  173844. #ifndef PNG_H
  173845. #define PNG_H
  173846. /* This is not the place to learn how to use libpng. The file libpng.txt
  173847. * describes how to use libpng, and the file example.c summarizes it
  173848. * with some code on which to build. This file is useful for looking
  173849. * at the actual function definitions and structure components.
  173850. */
  173851. /* Version information for png.h - this should match the version in png.c */
  173852. #define PNG_LIBPNG_VER_STRING "1.2.21"
  173853. #define PNG_HEADER_VERSION_STRING \
  173854. " libpng version 1.2.21 - October 4, 2007\n"
  173855. #define PNG_LIBPNG_VER_SONUM 0
  173856. #define PNG_LIBPNG_VER_DLLNUM 13
  173857. /* These should match the first 3 components of PNG_LIBPNG_VER_STRING: */
  173858. #define PNG_LIBPNG_VER_MAJOR 1
  173859. #define PNG_LIBPNG_VER_MINOR 2
  173860. #define PNG_LIBPNG_VER_RELEASE 21
  173861. /* This should match the numeric part of the final component of
  173862. * PNG_LIBPNG_VER_STRING, omitting any leading zero: */
  173863. #define PNG_LIBPNG_VER_BUILD 0
  173864. /* Release Status */
  173865. #define PNG_LIBPNG_BUILD_ALPHA 1
  173866. #define PNG_LIBPNG_BUILD_BETA 2
  173867. #define PNG_LIBPNG_BUILD_RC 3
  173868. #define PNG_LIBPNG_BUILD_STABLE 4
  173869. #define PNG_LIBPNG_BUILD_RELEASE_STATUS_MASK 7
  173870. /* Release-Specific Flags */
  173871. #define PNG_LIBPNG_BUILD_PATCH 8 /* Can be OR'ed with
  173872. PNG_LIBPNG_BUILD_STABLE only */
  173873. #define PNG_LIBPNG_BUILD_PRIVATE 16 /* Cannot be OR'ed with
  173874. PNG_LIBPNG_BUILD_SPECIAL */
  173875. #define PNG_LIBPNG_BUILD_SPECIAL 32 /* Cannot be OR'ed with
  173876. PNG_LIBPNG_BUILD_PRIVATE */
  173877. #define PNG_LIBPNG_BUILD_BASE_TYPE PNG_LIBPNG_BUILD_STABLE
  173878. /* Careful here. At one time, Guy wanted to use 082, but that would be octal.
  173879. * We must not include leading zeros.
  173880. * Versions 0.7 through 1.0.0 were in the range 0 to 100 here (only
  173881. * version 1.0.0 was mis-numbered 100 instead of 10000). From
  173882. * version 1.0.1 it's xxyyzz, where x=major, y=minor, z=release */
  173883. #define PNG_LIBPNG_VER 10221 /* 1.2.21 */
  173884. #ifndef PNG_VERSION_INFO_ONLY
  173885. /* include the compression library's header */
  173886. #endif
  173887. /* include all user configurable info, including optional assembler routines */
  173888. /********* Start of inlined file: pngconf.h *********/
  173889. /* pngconf.h - machine configurable file for libpng
  173890. *
  173891. * libpng version 1.2.21 - October 4, 2007
  173892. * For conditions of distribution and use, see copyright notice in png.h
  173893. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  173894. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  173895. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  173896. */
  173897. /* Any machine specific code is near the front of this file, so if you
  173898. * are configuring libpng for a machine, you may want to read the section
  173899. * starting here down to where it starts to typedef png_color, png_text,
  173900. * and png_info.
  173901. */
  173902. #ifndef PNGCONF_H
  173903. #define PNGCONF_H
  173904. #define PNG_1_2_X
  173905. // These are some Juce config settings that should remove any unnecessary code bloat..
  173906. #define PNG_NO_STDIO 1
  173907. #define PNG_DEBUG 0
  173908. #define PNG_NO_WARNINGS 1
  173909. #define PNG_NO_ERROR_TEXT 1
  173910. #define PNG_NO_ERROR_NUMBERS 1
  173911. #define PNG_NO_USER_MEM 1
  173912. #define PNG_NO_READ_iCCP 1
  173913. #define PNG_NO_READ_UNKNOWN_CHUNKS 1
  173914. #define PNG_NO_READ_USER_CHUNKS 1
  173915. #define PNG_NO_READ_iTXt 1
  173916. #define PNG_NO_READ_sCAL 1
  173917. #define PNG_NO_READ_sPLT 1
  173918. #define png_error(a, b) png_err(a)
  173919. #define png_warning(a, b)
  173920. #define png_chunk_error(a, b) png_err(a)
  173921. #define png_chunk_warning(a, b)
  173922. /*
  173923. * PNG_USER_CONFIG has to be defined on the compiler command line. This
  173924. * includes the resource compiler for Windows DLL configurations.
  173925. */
  173926. #ifdef PNG_USER_CONFIG
  173927. # ifndef PNG_USER_PRIVATEBUILD
  173928. # define PNG_USER_PRIVATEBUILD
  173929. # endif
  173930. #include "pngusr.h"
  173931. #endif
  173932. /* PNG_CONFIGURE_LIBPNG is set by the "configure" script. */
  173933. #ifdef PNG_CONFIGURE_LIBPNG
  173934. #ifdef HAVE_CONFIG_H
  173935. #include "config.h"
  173936. #endif
  173937. #endif
  173938. /*
  173939. * Added at libpng-1.2.8
  173940. *
  173941. * If you create a private DLL you need to define in "pngusr.h" the followings:
  173942. * #define PNG_USER_PRIVATEBUILD <Describes by whom and why this version of
  173943. * the DLL was built>
  173944. * e.g. #define PNG_USER_PRIVATEBUILD "Build by MyCompany for xyz reasons."
  173945. * #define PNG_USER_DLLFNAME_POSTFIX <two-letter postfix that serve to
  173946. * distinguish your DLL from those of the official release. These
  173947. * correspond to the trailing letters that come after the version
  173948. * number and must match your private DLL name>
  173949. * e.g. // private DLL "libpng13gx.dll"
  173950. * #define PNG_USER_DLLFNAME_POSTFIX "gx"
  173951. *
  173952. * The following macros are also at your disposal if you want to complete the
  173953. * DLL VERSIONINFO structure.
  173954. * - PNG_USER_VERSIONINFO_COMMENTS
  173955. * - PNG_USER_VERSIONINFO_COMPANYNAME
  173956. * - PNG_USER_VERSIONINFO_LEGALTRADEMARKS
  173957. */
  173958. #ifdef __STDC__
  173959. #ifdef SPECIALBUILD
  173960. # pragma message("PNG_LIBPNG_SPECIALBUILD (and deprecated SPECIALBUILD)\
  173961. are now LIBPNG reserved macros. Use PNG_USER_PRIVATEBUILD instead.")
  173962. #endif
  173963. #ifdef PRIVATEBUILD
  173964. # pragma message("PRIVATEBUILD is deprecated.\
  173965. Use PNG_USER_PRIVATEBUILD instead.")
  173966. # define PNG_USER_PRIVATEBUILD PRIVATEBUILD
  173967. #endif
  173968. #endif /* __STDC__ */
  173969. #ifndef PNG_VERSION_INFO_ONLY
  173970. /* End of material added to libpng-1.2.8 */
  173971. /* Added at libpng-1.2.19, removed at libpng-1.2.20 because it caused trouble
  173972. Restored at libpng-1.2.21 */
  173973. # define PNG_WARN_UNINITIALIZED_ROW 1
  173974. /* End of material added at libpng-1.2.19/1.2.21 */
  173975. /* This is the size of the compression buffer, and thus the size of
  173976. * an IDAT chunk. Make this whatever size you feel is best for your
  173977. * machine. One of these will be allocated per png_struct. When this
  173978. * is full, it writes the data to the disk, and does some other
  173979. * calculations. Making this an extremely small size will slow
  173980. * the library down, but you may want to experiment to determine
  173981. * where it becomes significant, if you are concerned with memory
  173982. * usage. Note that zlib allocates at least 32Kb also. For readers,
  173983. * this describes the size of the buffer available to read the data in.
  173984. * Unless this gets smaller than the size of a row (compressed),
  173985. * it should not make much difference how big this is.
  173986. */
  173987. #ifndef PNG_ZBUF_SIZE
  173988. # define PNG_ZBUF_SIZE 8192
  173989. #endif
  173990. /* Enable if you want a write-only libpng */
  173991. #ifndef PNG_NO_READ_SUPPORTED
  173992. # define PNG_READ_SUPPORTED
  173993. #endif
  173994. /* Enable if you want a read-only libpng */
  173995. #ifndef PNG_NO_WRITE_SUPPORTED
  173996. # define PNG_WRITE_SUPPORTED
  173997. #endif
  173998. /* Enabled by default in 1.2.0. You can disable this if you don't need to
  173999. support PNGs that are embedded in MNG datastreams */
  174000. #if !defined(PNG_1_0_X) && !defined(PNG_NO_MNG_FEATURES)
  174001. # ifndef PNG_MNG_FEATURES_SUPPORTED
  174002. # define PNG_MNG_FEATURES_SUPPORTED
  174003. # endif
  174004. #endif
  174005. #ifndef PNG_NO_FLOATING_POINT_SUPPORTED
  174006. # ifndef PNG_FLOATING_POINT_SUPPORTED
  174007. # define PNG_FLOATING_POINT_SUPPORTED
  174008. # endif
  174009. #endif
  174010. /* If you are running on a machine where you cannot allocate more
  174011. * than 64K of memory at once, uncomment this. While libpng will not
  174012. * normally need that much memory in a chunk (unless you load up a very
  174013. * large file), zlib needs to know how big of a chunk it can use, and
  174014. * libpng thus makes sure to check any memory allocation to verify it
  174015. * will fit into memory.
  174016. #define PNG_MAX_MALLOC_64K
  174017. */
  174018. #if defined(MAXSEG_64K) && !defined(PNG_MAX_MALLOC_64K)
  174019. # define PNG_MAX_MALLOC_64K
  174020. #endif
  174021. /* Special munging to support doing things the 'cygwin' way:
  174022. * 'Normal' png-on-win32 defines/defaults:
  174023. * PNG_BUILD_DLL -- building dll
  174024. * PNG_USE_DLL -- building an application, linking to dll
  174025. * (no define) -- building static library, or building an
  174026. * application and linking to the static lib
  174027. * 'Cygwin' defines/defaults:
  174028. * PNG_BUILD_DLL -- (ignored) building the dll
  174029. * (no define) -- (ignored) building an application, linking to the dll
  174030. * PNG_STATIC -- (ignored) building the static lib, or building an
  174031. * application that links to the static lib.
  174032. * ALL_STATIC -- (ignored) building various static libs, or building an
  174033. * application that links to the static libs.
  174034. * Thus,
  174035. * a cygwin user should define either PNG_BUILD_DLL or PNG_STATIC, and
  174036. * this bit of #ifdefs will define the 'correct' config variables based on
  174037. * that. If a cygwin user *wants* to define 'PNG_USE_DLL' that's okay, but
  174038. * unnecessary.
  174039. *
  174040. * Also, the precedence order is:
  174041. * ALL_STATIC (since we can't #undef something outside our namespace)
  174042. * PNG_BUILD_DLL
  174043. * PNG_STATIC
  174044. * (nothing) == PNG_USE_DLL
  174045. *
  174046. * CYGWIN (2002-01-20): The preceding is now obsolete. With the advent
  174047. * of auto-import in binutils, we no longer need to worry about
  174048. * __declspec(dllexport) / __declspec(dllimport) and friends. Therefore,
  174049. * we don't need to worry about PNG_STATIC or ALL_STATIC when it comes
  174050. * to __declspec() stuff. However, we DO need to worry about
  174051. * PNG_BUILD_DLL and PNG_STATIC because those change some defaults
  174052. * such as CONSOLE_IO and whether GLOBAL_ARRAYS are allowed.
  174053. */
  174054. #if defined(__CYGWIN__)
  174055. # if defined(ALL_STATIC)
  174056. # if defined(PNG_BUILD_DLL)
  174057. # undef PNG_BUILD_DLL
  174058. # endif
  174059. # if defined(PNG_USE_DLL)
  174060. # undef PNG_USE_DLL
  174061. # endif
  174062. # if defined(PNG_DLL)
  174063. # undef PNG_DLL
  174064. # endif
  174065. # if !defined(PNG_STATIC)
  174066. # define PNG_STATIC
  174067. # endif
  174068. # else
  174069. # if defined (PNG_BUILD_DLL)
  174070. # if defined(PNG_STATIC)
  174071. # undef PNG_STATIC
  174072. # endif
  174073. # if defined(PNG_USE_DLL)
  174074. # undef PNG_USE_DLL
  174075. # endif
  174076. # if !defined(PNG_DLL)
  174077. # define PNG_DLL
  174078. # endif
  174079. # else
  174080. # if defined(PNG_STATIC)
  174081. # if defined(PNG_USE_DLL)
  174082. # undef PNG_USE_DLL
  174083. # endif
  174084. # if defined(PNG_DLL)
  174085. # undef PNG_DLL
  174086. # endif
  174087. # else
  174088. # if !defined(PNG_USE_DLL)
  174089. # define PNG_USE_DLL
  174090. # endif
  174091. # if !defined(PNG_DLL)
  174092. # define PNG_DLL
  174093. # endif
  174094. # endif
  174095. # endif
  174096. # endif
  174097. #endif
  174098. /* This protects us against compilers that run on a windowing system
  174099. * and thus don't have or would rather us not use the stdio types:
  174100. * stdin, stdout, and stderr. The only one currently used is stderr
  174101. * in png_error() and png_warning(). #defining PNG_NO_CONSOLE_IO will
  174102. * prevent these from being compiled and used. #defining PNG_NO_STDIO
  174103. * will also prevent these, plus will prevent the entire set of stdio
  174104. * macros and functions (FILE *, printf, etc.) from being compiled and used,
  174105. * unless (PNG_DEBUG > 0) has been #defined.
  174106. *
  174107. * #define PNG_NO_CONSOLE_IO
  174108. * #define PNG_NO_STDIO
  174109. */
  174110. #if defined(_WIN32_WCE)
  174111. # include <windows.h>
  174112. /* Console I/O functions are not supported on WindowsCE */
  174113. # define PNG_NO_CONSOLE_IO
  174114. # ifdef PNG_DEBUG
  174115. # undef PNG_DEBUG
  174116. # endif
  174117. #endif
  174118. #ifdef PNG_BUILD_DLL
  174119. # ifndef PNG_CONSOLE_IO_SUPPORTED
  174120. # ifndef PNG_NO_CONSOLE_IO
  174121. # define PNG_NO_CONSOLE_IO
  174122. # endif
  174123. # endif
  174124. #endif
  174125. # ifdef PNG_NO_STDIO
  174126. # ifndef PNG_NO_CONSOLE_IO
  174127. # define PNG_NO_CONSOLE_IO
  174128. # endif
  174129. # ifdef PNG_DEBUG
  174130. # if (PNG_DEBUG > 0)
  174131. # include <stdio.h>
  174132. # endif
  174133. # endif
  174134. # else
  174135. # if !defined(_WIN32_WCE)
  174136. /* "stdio.h" functions are not supported on WindowsCE */
  174137. # include <stdio.h>
  174138. # endif
  174139. # endif
  174140. /* This macro protects us against machines that don't have function
  174141. * prototypes (ie K&R style headers). If your compiler does not handle
  174142. * function prototypes, define this macro and use the included ansi2knr.
  174143. * I've always been able to use _NO_PROTO as the indicator, but you may
  174144. * need to drag the empty declaration out in front of here, or change the
  174145. * ifdef to suit your own needs.
  174146. */
  174147. #ifndef PNGARG
  174148. #ifdef OF /* zlib prototype munger */
  174149. # define PNGARG(arglist) OF(arglist)
  174150. #else
  174151. #ifdef _NO_PROTO
  174152. # define PNGARG(arglist) ()
  174153. # ifndef PNG_TYPECAST_NULL
  174154. # define PNG_TYPECAST_NULL
  174155. # endif
  174156. #else
  174157. # define PNGARG(arglist) arglist
  174158. #endif /* _NO_PROTO */
  174159. #endif /* OF */
  174160. #endif /* PNGARG */
  174161. /* Try to determine if we are compiling on a Mac. Note that testing for
  174162. * just __MWERKS__ is not good enough, because the Codewarrior is now used
  174163. * on non-Mac platforms.
  174164. */
  174165. #ifndef MACOS
  174166. # if (defined(__MWERKS__) && defined(macintosh)) || defined(applec) || \
  174167. defined(THINK_C) || defined(__SC__) || defined(TARGET_OS_MAC)
  174168. # define MACOS
  174169. # endif
  174170. #endif
  174171. /* enough people need this for various reasons to include it here */
  174172. #if !defined(MACOS) && !defined(RISCOS) && !defined(_WIN32_WCE)
  174173. # include <sys/types.h>
  174174. #endif
  174175. #if !defined(PNG_SETJMP_NOT_SUPPORTED) && !defined(PNG_NO_SETJMP_SUPPORTED)
  174176. # define PNG_SETJMP_SUPPORTED
  174177. #endif
  174178. #ifdef PNG_SETJMP_SUPPORTED
  174179. /* This is an attempt to force a single setjmp behaviour on Linux. If
  174180. * the X config stuff didn't define _BSD_SOURCE we wouldn't need this.
  174181. */
  174182. # ifdef __linux__
  174183. # ifdef _BSD_SOURCE
  174184. # define PNG_SAVE_BSD_SOURCE
  174185. # undef _BSD_SOURCE
  174186. # endif
  174187. # ifdef _SETJMP_H
  174188. /* If you encounter a compiler error here, see the explanation
  174189. * near the end of INSTALL.
  174190. */
  174191. __png.h__ already includes setjmp.h;
  174192. __dont__ include it again.;
  174193. # endif
  174194. # endif /* __linux__ */
  174195. /* include setjmp.h for error handling */
  174196. # include <setjmp.h>
  174197. # ifdef __linux__
  174198. # ifdef PNG_SAVE_BSD_SOURCE
  174199. # define _BSD_SOURCE
  174200. # undef PNG_SAVE_BSD_SOURCE
  174201. # endif
  174202. # endif /* __linux__ */
  174203. #endif /* PNG_SETJMP_SUPPORTED */
  174204. #ifdef BSD
  174205. # include <strings.h>
  174206. #else
  174207. # include <string.h>
  174208. #endif
  174209. /* Other defines for things like memory and the like can go here. */
  174210. #ifdef PNG_INTERNAL
  174211. #include <stdlib.h>
  174212. /* The functions exported by PNG_EXTERN are PNG_INTERNAL functions, which
  174213. * aren't usually used outside the library (as far as I know), so it is
  174214. * debatable if they should be exported at all. In the future, when it is
  174215. * possible to have run-time registry of chunk-handling functions, some of
  174216. * these will be made available again.
  174217. #define PNG_EXTERN extern
  174218. */
  174219. #define PNG_EXTERN
  174220. /* Other defines specific to compilers can go here. Try to keep
  174221. * them inside an appropriate ifdef/endif pair for portability.
  174222. */
  174223. #if defined(PNG_FLOATING_POINT_SUPPORTED)
  174224. # if defined(MACOS)
  174225. /* We need to check that <math.h> hasn't already been included earlier
  174226. * as it seems it doesn't agree with <fp.h>, yet we should really use
  174227. * <fp.h> if possible.
  174228. */
  174229. # if !defined(__MATH_H__) && !defined(__MATH_H) && !defined(__cmath__)
  174230. # include <fp.h>
  174231. # endif
  174232. # else
  174233. # include <math.h>
  174234. # endif
  174235. # if defined(_AMIGA) && defined(__SASC) && defined(_M68881)
  174236. /* Amiga SAS/C: We must include builtin FPU functions when compiling using
  174237. * MATH=68881
  174238. */
  174239. # include <m68881.h>
  174240. # endif
  174241. #endif
  174242. /* Codewarrior on NT has linking problems without this. */
  174243. #if (defined(__MWERKS__) && defined(WIN32)) || defined(__STDC__)
  174244. # define PNG_ALWAYS_EXTERN
  174245. #endif
  174246. /* This provides the non-ANSI (far) memory allocation routines. */
  174247. #if defined(__TURBOC__) && defined(__MSDOS__)
  174248. # include <mem.h>
  174249. # include <alloc.h>
  174250. #endif
  174251. /* I have no idea why is this necessary... */
  174252. #if defined(_MSC_VER) && (defined(WIN32) || defined(_Windows) || \
  174253. defined(_WINDOWS) || defined(_WIN32) || defined(__WIN32__))
  174254. # include <malloc.h>
  174255. #endif
  174256. /* This controls how fine the dithering gets. As this allocates
  174257. * a largish chunk of memory (32K), those who are not as concerned
  174258. * with dithering quality can decrease some or all of these.
  174259. */
  174260. #ifndef PNG_DITHER_RED_BITS
  174261. # define PNG_DITHER_RED_BITS 5
  174262. #endif
  174263. #ifndef PNG_DITHER_GREEN_BITS
  174264. # define PNG_DITHER_GREEN_BITS 5
  174265. #endif
  174266. #ifndef PNG_DITHER_BLUE_BITS
  174267. # define PNG_DITHER_BLUE_BITS 5
  174268. #endif
  174269. /* This controls how fine the gamma correction becomes when you
  174270. * are only interested in 8 bits anyway. Increasing this value
  174271. * results in more memory being used, and more pow() functions
  174272. * being called to fill in the gamma tables. Don't set this value
  174273. * less then 8, and even that may not work (I haven't tested it).
  174274. */
  174275. #ifndef PNG_MAX_GAMMA_8
  174276. # define PNG_MAX_GAMMA_8 11
  174277. #endif
  174278. /* This controls how much a difference in gamma we can tolerate before
  174279. * we actually start doing gamma conversion.
  174280. */
  174281. #ifndef PNG_GAMMA_THRESHOLD
  174282. # define PNG_GAMMA_THRESHOLD 0.05
  174283. #endif
  174284. #endif /* PNG_INTERNAL */
  174285. /* The following uses const char * instead of char * for error
  174286. * and warning message functions, so some compilers won't complain.
  174287. * If you do not want to use const, define PNG_NO_CONST here.
  174288. */
  174289. #ifndef PNG_NO_CONST
  174290. # define PNG_CONST const
  174291. #else
  174292. # define PNG_CONST
  174293. #endif
  174294. /* The following defines give you the ability to remove code from the
  174295. * library that you will not be using. I wish I could figure out how to
  174296. * automate this, but I can't do that without making it seriously hard
  174297. * on the users. So if you are not using an ability, change the #define
  174298. * to and #undef, and that part of the library will not be compiled. If
  174299. * your linker can't find a function, you may want to make sure the
  174300. * ability is defined here. Some of these depend upon some others being
  174301. * defined. I haven't figured out all the interactions here, so you may
  174302. * have to experiment awhile to get everything to compile. If you are
  174303. * creating or using a shared library, you probably shouldn't touch this,
  174304. * as it will affect the size of the structures, and this will cause bad
  174305. * things to happen if the library and/or application ever change.
  174306. */
  174307. /* Any features you will not be using can be undef'ed here */
  174308. /* GR-P, 0.96a: Set "*TRANSFORMS_SUPPORTED as default but allow user
  174309. * to turn it off with "*TRANSFORMS_NOT_SUPPORTED" or *PNG_NO_*_TRANSFORMS
  174310. * on the compile line, then pick and choose which ones to define without
  174311. * having to edit this file. It is safe to use the *TRANSFORMS_NOT_SUPPORTED
  174312. * if you only want to have a png-compliant reader/writer but don't need
  174313. * any of the extra transformations. This saves about 80 kbytes in a
  174314. * typical installation of the library. (PNG_NO_* form added in version
  174315. * 1.0.1c, for consistency)
  174316. */
  174317. /* The size of the png_text structure changed in libpng-1.0.6 when
  174318. * iTXt support was added. iTXt support was turned off by default through
  174319. * libpng-1.2.x, to support old apps that malloc the png_text structure
  174320. * instead of calling png_set_text() and letting libpng malloc it. It
  174321. * was turned on by default in libpng-1.3.0.
  174322. */
  174323. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  174324. # ifndef PNG_NO_iTXt_SUPPORTED
  174325. # define PNG_NO_iTXt_SUPPORTED
  174326. # endif
  174327. # ifndef PNG_NO_READ_iTXt
  174328. # define PNG_NO_READ_iTXt
  174329. # endif
  174330. # ifndef PNG_NO_WRITE_iTXt
  174331. # define PNG_NO_WRITE_iTXt
  174332. # endif
  174333. #endif
  174334. #if !defined(PNG_NO_iTXt_SUPPORTED)
  174335. # if !defined(PNG_READ_iTXt_SUPPORTED) && !defined(PNG_NO_READ_iTXt)
  174336. # define PNG_READ_iTXt
  174337. # endif
  174338. # if !defined(PNG_WRITE_iTXt_SUPPORTED) && !defined(PNG_NO_WRITE_iTXt)
  174339. # define PNG_WRITE_iTXt
  174340. # endif
  174341. #endif
  174342. /* The following support, added after version 1.0.0, can be turned off here en
  174343. * masse by defining PNG_LEGACY_SUPPORTED in case you need binary compatibility
  174344. * with old applications that require the length of png_struct and png_info
  174345. * to remain unchanged.
  174346. */
  174347. #ifdef PNG_LEGACY_SUPPORTED
  174348. # define PNG_NO_FREE_ME
  174349. # define PNG_NO_READ_UNKNOWN_CHUNKS
  174350. # define PNG_NO_WRITE_UNKNOWN_CHUNKS
  174351. # define PNG_NO_READ_USER_CHUNKS
  174352. # define PNG_NO_READ_iCCP
  174353. # define PNG_NO_WRITE_iCCP
  174354. # define PNG_NO_READ_iTXt
  174355. # define PNG_NO_WRITE_iTXt
  174356. # define PNG_NO_READ_sCAL
  174357. # define PNG_NO_WRITE_sCAL
  174358. # define PNG_NO_READ_sPLT
  174359. # define PNG_NO_WRITE_sPLT
  174360. # define PNG_NO_INFO_IMAGE
  174361. # define PNG_NO_READ_RGB_TO_GRAY
  174362. # define PNG_NO_READ_USER_TRANSFORM
  174363. # define PNG_NO_WRITE_USER_TRANSFORM
  174364. # define PNG_NO_USER_MEM
  174365. # define PNG_NO_READ_EMPTY_PLTE
  174366. # define PNG_NO_MNG_FEATURES
  174367. # define PNG_NO_FIXED_POINT_SUPPORTED
  174368. #endif
  174369. /* Ignore attempt to turn off both floating and fixed point support */
  174370. #if !defined(PNG_FLOATING_POINT_SUPPORTED) || \
  174371. !defined(PNG_NO_FIXED_POINT_SUPPORTED)
  174372. # define PNG_FIXED_POINT_SUPPORTED
  174373. #endif
  174374. #ifndef PNG_NO_FREE_ME
  174375. # define PNG_FREE_ME_SUPPORTED
  174376. #endif
  174377. #if defined(PNG_READ_SUPPORTED)
  174378. #if !defined(PNG_READ_TRANSFORMS_NOT_SUPPORTED) && \
  174379. !defined(PNG_NO_READ_TRANSFORMS)
  174380. # define PNG_READ_TRANSFORMS_SUPPORTED
  174381. #endif
  174382. #ifdef PNG_READ_TRANSFORMS_SUPPORTED
  174383. # ifndef PNG_NO_READ_EXPAND
  174384. # define PNG_READ_EXPAND_SUPPORTED
  174385. # endif
  174386. # ifndef PNG_NO_READ_SHIFT
  174387. # define PNG_READ_SHIFT_SUPPORTED
  174388. # endif
  174389. # ifndef PNG_NO_READ_PACK
  174390. # define PNG_READ_PACK_SUPPORTED
  174391. # endif
  174392. # ifndef PNG_NO_READ_BGR
  174393. # define PNG_READ_BGR_SUPPORTED
  174394. # endif
  174395. # ifndef PNG_NO_READ_SWAP
  174396. # define PNG_READ_SWAP_SUPPORTED
  174397. # endif
  174398. # ifndef PNG_NO_READ_PACKSWAP
  174399. # define PNG_READ_PACKSWAP_SUPPORTED
  174400. # endif
  174401. # ifndef PNG_NO_READ_INVERT
  174402. # define PNG_READ_INVERT_SUPPORTED
  174403. # endif
  174404. # ifndef PNG_NO_READ_DITHER
  174405. # define PNG_READ_DITHER_SUPPORTED
  174406. # endif
  174407. # ifndef PNG_NO_READ_BACKGROUND
  174408. # define PNG_READ_BACKGROUND_SUPPORTED
  174409. # endif
  174410. # ifndef PNG_NO_READ_16_TO_8
  174411. # define PNG_READ_16_TO_8_SUPPORTED
  174412. # endif
  174413. # ifndef PNG_NO_READ_FILLER
  174414. # define PNG_READ_FILLER_SUPPORTED
  174415. # endif
  174416. # ifndef PNG_NO_READ_GAMMA
  174417. # define PNG_READ_GAMMA_SUPPORTED
  174418. # endif
  174419. # ifndef PNG_NO_READ_GRAY_TO_RGB
  174420. # define PNG_READ_GRAY_TO_RGB_SUPPORTED
  174421. # endif
  174422. # ifndef PNG_NO_READ_SWAP_ALPHA
  174423. # define PNG_READ_SWAP_ALPHA_SUPPORTED
  174424. # endif
  174425. # ifndef PNG_NO_READ_INVERT_ALPHA
  174426. # define PNG_READ_INVERT_ALPHA_SUPPORTED
  174427. # endif
  174428. # ifndef PNG_NO_READ_STRIP_ALPHA
  174429. # define PNG_READ_STRIP_ALPHA_SUPPORTED
  174430. # endif
  174431. # ifndef PNG_NO_READ_USER_TRANSFORM
  174432. # define PNG_READ_USER_TRANSFORM_SUPPORTED
  174433. # endif
  174434. # ifndef PNG_NO_READ_RGB_TO_GRAY
  174435. # define PNG_READ_RGB_TO_GRAY_SUPPORTED
  174436. # endif
  174437. #endif /* PNG_READ_TRANSFORMS_SUPPORTED */
  174438. #if !defined(PNG_NO_PROGRESSIVE_READ) && \
  174439. !defined(PNG_PROGRESSIVE_READ_SUPPORTED) /* if you don't do progressive */
  174440. # define PNG_PROGRESSIVE_READ_SUPPORTED /* reading. This is not talking */
  174441. #endif /* about interlacing capability! You'll */
  174442. /* still have interlacing unless you change the following line: */
  174443. #define PNG_READ_INTERLACING_SUPPORTED /* required in PNG-compliant decoders */
  174444. #ifndef PNG_NO_READ_COMPOSITE_NODIV
  174445. # ifndef PNG_NO_READ_COMPOSITED_NODIV /* libpng-1.0.x misspelling */
  174446. # define PNG_READ_COMPOSITE_NODIV_SUPPORTED /* well tested on Intel, SGI */
  174447. # endif
  174448. #endif
  174449. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  174450. /* Deprecated, will be removed from version 2.0.0.
  174451. Use PNG_MNG_FEATURES_SUPPORTED instead. */
  174452. #ifndef PNG_NO_READ_EMPTY_PLTE
  174453. # define PNG_READ_EMPTY_PLTE_SUPPORTED
  174454. #endif
  174455. #endif
  174456. #endif /* PNG_READ_SUPPORTED */
  174457. #if defined(PNG_WRITE_SUPPORTED)
  174458. # if !defined(PNG_WRITE_TRANSFORMS_NOT_SUPPORTED) && \
  174459. !defined(PNG_NO_WRITE_TRANSFORMS)
  174460. # define PNG_WRITE_TRANSFORMS_SUPPORTED
  174461. #endif
  174462. #ifdef PNG_WRITE_TRANSFORMS_SUPPORTED
  174463. # ifndef PNG_NO_WRITE_SHIFT
  174464. # define PNG_WRITE_SHIFT_SUPPORTED
  174465. # endif
  174466. # ifndef PNG_NO_WRITE_PACK
  174467. # define PNG_WRITE_PACK_SUPPORTED
  174468. # endif
  174469. # ifndef PNG_NO_WRITE_BGR
  174470. # define PNG_WRITE_BGR_SUPPORTED
  174471. # endif
  174472. # ifndef PNG_NO_WRITE_SWAP
  174473. # define PNG_WRITE_SWAP_SUPPORTED
  174474. # endif
  174475. # ifndef PNG_NO_WRITE_PACKSWAP
  174476. # define PNG_WRITE_PACKSWAP_SUPPORTED
  174477. # endif
  174478. # ifndef PNG_NO_WRITE_INVERT
  174479. # define PNG_WRITE_INVERT_SUPPORTED
  174480. # endif
  174481. # ifndef PNG_NO_WRITE_FILLER
  174482. # define PNG_WRITE_FILLER_SUPPORTED /* same as WRITE_STRIP_ALPHA */
  174483. # endif
  174484. # ifndef PNG_NO_WRITE_SWAP_ALPHA
  174485. # define PNG_WRITE_SWAP_ALPHA_SUPPORTED
  174486. # endif
  174487. # ifndef PNG_NO_WRITE_INVERT_ALPHA
  174488. # define PNG_WRITE_INVERT_ALPHA_SUPPORTED
  174489. # endif
  174490. # ifndef PNG_NO_WRITE_USER_TRANSFORM
  174491. # define PNG_WRITE_USER_TRANSFORM_SUPPORTED
  174492. # endif
  174493. #endif /* PNG_WRITE_TRANSFORMS_SUPPORTED */
  174494. #if !defined(PNG_NO_WRITE_INTERLACING_SUPPORTED) && \
  174495. !defined(PNG_WRITE_INTERLACING_SUPPORTED)
  174496. #define PNG_WRITE_INTERLACING_SUPPORTED /* not required for PNG-compliant
  174497. encoders, but can cause trouble
  174498. if left undefined */
  174499. #endif
  174500. #if !defined(PNG_NO_WRITE_WEIGHTED_FILTER) && \
  174501. !defined(PNG_WRITE_WEIGHTED_FILTER) && \
  174502. defined(PNG_FLOATING_POINT_SUPPORTED)
  174503. # define PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
  174504. #endif
  174505. #ifndef PNG_NO_WRITE_FLUSH
  174506. # define PNG_WRITE_FLUSH_SUPPORTED
  174507. #endif
  174508. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  174509. /* Deprecated, see PNG_MNG_FEATURES_SUPPORTED, above */
  174510. #ifndef PNG_NO_WRITE_EMPTY_PLTE
  174511. # define PNG_WRITE_EMPTY_PLTE_SUPPORTED
  174512. #endif
  174513. #endif
  174514. #endif /* PNG_WRITE_SUPPORTED */
  174515. #ifndef PNG_1_0_X
  174516. # ifndef PNG_NO_ERROR_NUMBERS
  174517. # define PNG_ERROR_NUMBERS_SUPPORTED
  174518. # endif
  174519. #endif /* PNG_1_0_X */
  174520. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  174521. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  174522. # ifndef PNG_NO_USER_TRANSFORM_PTR
  174523. # define PNG_USER_TRANSFORM_PTR_SUPPORTED
  174524. # endif
  174525. #endif
  174526. #ifndef PNG_NO_STDIO
  174527. # define PNG_TIME_RFC1123_SUPPORTED
  174528. #endif
  174529. /* This adds extra functions in pngget.c for accessing data from the
  174530. * info pointer (added in version 0.99)
  174531. * png_get_image_width()
  174532. * png_get_image_height()
  174533. * png_get_bit_depth()
  174534. * png_get_color_type()
  174535. * png_get_compression_type()
  174536. * png_get_filter_type()
  174537. * png_get_interlace_type()
  174538. * png_get_pixel_aspect_ratio()
  174539. * png_get_pixels_per_meter()
  174540. * png_get_x_offset_pixels()
  174541. * png_get_y_offset_pixels()
  174542. * png_get_x_offset_microns()
  174543. * png_get_y_offset_microns()
  174544. */
  174545. #if !defined(PNG_NO_EASY_ACCESS) && !defined(PNG_EASY_ACCESS_SUPPORTED)
  174546. # define PNG_EASY_ACCESS_SUPPORTED
  174547. #endif
  174548. /* PNG_ASSEMBLER_CODE was enabled by default in version 1.2.0
  174549. * and removed from version 1.2.20. The following will be removed
  174550. * from libpng-1.4.0
  174551. */
  174552. #if defined(PNG_READ_SUPPORTED) && !defined(PNG_NO_OPTIMIZED_CODE)
  174553. # ifndef PNG_OPTIMIZED_CODE_SUPPORTED
  174554. # define PNG_OPTIMIZED_CODE_SUPPORTED
  174555. # endif
  174556. #endif
  174557. #if defined(PNG_READ_SUPPORTED) && !defined(PNG_NO_ASSEMBLER_CODE)
  174558. # ifndef PNG_ASSEMBLER_CODE_SUPPORTED
  174559. # define PNG_ASSEMBLER_CODE_SUPPORTED
  174560. # endif
  174561. # if defined(__GNUC__) && defined(__x86_64__) && (__GNUC__ < 4)
  174562. /* work around 64-bit gcc compiler bugs in gcc-3.x */
  174563. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  174564. # define PNG_NO_MMX_CODE
  174565. # endif
  174566. # endif
  174567. # if defined(__APPLE__)
  174568. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  174569. # define PNG_NO_MMX_CODE
  174570. # endif
  174571. # endif
  174572. # if (defined(__MWERKS__) && ((__MWERKS__ < 0x0900) || macintosh))
  174573. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  174574. # define PNG_NO_MMX_CODE
  174575. # endif
  174576. # endif
  174577. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  174578. # define PNG_MMX_CODE_SUPPORTED
  174579. # endif
  174580. #endif
  174581. /* end of obsolete code to be removed from libpng-1.4.0 */
  174582. #if !defined(PNG_1_0_X)
  174583. #if !defined(PNG_NO_USER_MEM) && !defined(PNG_USER_MEM_SUPPORTED)
  174584. # define PNG_USER_MEM_SUPPORTED
  174585. #endif
  174586. #endif /* PNG_1_0_X */
  174587. /* Added at libpng-1.2.6 */
  174588. #if !defined(PNG_1_0_X)
  174589. #ifndef PNG_SET_USER_LIMITS_SUPPORTED
  174590. #if !defined(PNG_NO_SET_USER_LIMITS) && !defined(PNG_SET_USER_LIMITS_SUPPORTED)
  174591. # define PNG_SET_USER_LIMITS_SUPPORTED
  174592. #endif
  174593. #endif
  174594. #endif /* PNG_1_0_X */
  174595. /* Added at libpng-1.0.16 and 1.2.6. To accept all valid PNGS no matter
  174596. * how large, set these limits to 0x7fffffffL
  174597. */
  174598. #ifndef PNG_USER_WIDTH_MAX
  174599. # define PNG_USER_WIDTH_MAX 1000000L
  174600. #endif
  174601. #ifndef PNG_USER_HEIGHT_MAX
  174602. # define PNG_USER_HEIGHT_MAX 1000000L
  174603. #endif
  174604. /* These are currently experimental features, define them if you want */
  174605. /* very little testing */
  174606. /*
  174607. #ifdef PNG_READ_SUPPORTED
  174608. # ifndef PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED
  174609. # define PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED
  174610. # endif
  174611. #endif
  174612. */
  174613. /* This is only for PowerPC big-endian and 680x0 systems */
  174614. /* some testing */
  174615. /*
  174616. #ifndef PNG_READ_BIG_ENDIAN_SUPPORTED
  174617. # define PNG_READ_BIG_ENDIAN_SUPPORTED
  174618. #endif
  174619. */
  174620. /* Buggy compilers (e.g., gcc 2.7.2.2) need this */
  174621. /*
  174622. #define PNG_NO_POINTER_INDEXING
  174623. */
  174624. /* These functions are turned off by default, as they will be phased out. */
  174625. /*
  174626. #define PNG_USELESS_TESTS_SUPPORTED
  174627. #define PNG_CORRECT_PALETTE_SUPPORTED
  174628. */
  174629. /* Any chunks you are not interested in, you can undef here. The
  174630. * ones that allocate memory may be expecially important (hIST,
  174631. * tEXt, zTXt, tRNS, pCAL). Others will just save time and make png_info
  174632. * a bit smaller.
  174633. */
  174634. #if defined(PNG_READ_SUPPORTED) && \
  174635. !defined(PNG_READ_ANCILLARY_CHUNKS_NOT_SUPPORTED) && \
  174636. !defined(PNG_NO_READ_ANCILLARY_CHUNKS)
  174637. # define PNG_READ_ANCILLARY_CHUNKS_SUPPORTED
  174638. #endif
  174639. #if defined(PNG_WRITE_SUPPORTED) && \
  174640. !defined(PNG_WRITE_ANCILLARY_CHUNKS_NOT_SUPPORTED) && \
  174641. !defined(PNG_NO_WRITE_ANCILLARY_CHUNKS)
  174642. # define PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED
  174643. #endif
  174644. #ifdef PNG_READ_ANCILLARY_CHUNKS_SUPPORTED
  174645. #ifdef PNG_NO_READ_TEXT
  174646. # define PNG_NO_READ_iTXt
  174647. # define PNG_NO_READ_tEXt
  174648. # define PNG_NO_READ_zTXt
  174649. #endif
  174650. #ifndef PNG_NO_READ_bKGD
  174651. # define PNG_READ_bKGD_SUPPORTED
  174652. # define PNG_bKGD_SUPPORTED
  174653. #endif
  174654. #ifndef PNG_NO_READ_cHRM
  174655. # define PNG_READ_cHRM_SUPPORTED
  174656. # define PNG_cHRM_SUPPORTED
  174657. #endif
  174658. #ifndef PNG_NO_READ_gAMA
  174659. # define PNG_READ_gAMA_SUPPORTED
  174660. # define PNG_gAMA_SUPPORTED
  174661. #endif
  174662. #ifndef PNG_NO_READ_hIST
  174663. # define PNG_READ_hIST_SUPPORTED
  174664. # define PNG_hIST_SUPPORTED
  174665. #endif
  174666. #ifndef PNG_NO_READ_iCCP
  174667. # define PNG_READ_iCCP_SUPPORTED
  174668. # define PNG_iCCP_SUPPORTED
  174669. #endif
  174670. #ifndef PNG_NO_READ_iTXt
  174671. # ifndef PNG_READ_iTXt_SUPPORTED
  174672. # define PNG_READ_iTXt_SUPPORTED
  174673. # endif
  174674. # ifndef PNG_iTXt_SUPPORTED
  174675. # define PNG_iTXt_SUPPORTED
  174676. # endif
  174677. #endif
  174678. #ifndef PNG_NO_READ_oFFs
  174679. # define PNG_READ_oFFs_SUPPORTED
  174680. # define PNG_oFFs_SUPPORTED
  174681. #endif
  174682. #ifndef PNG_NO_READ_pCAL
  174683. # define PNG_READ_pCAL_SUPPORTED
  174684. # define PNG_pCAL_SUPPORTED
  174685. #endif
  174686. #ifndef PNG_NO_READ_sCAL
  174687. # define PNG_READ_sCAL_SUPPORTED
  174688. # define PNG_sCAL_SUPPORTED
  174689. #endif
  174690. #ifndef PNG_NO_READ_pHYs
  174691. # define PNG_READ_pHYs_SUPPORTED
  174692. # define PNG_pHYs_SUPPORTED
  174693. #endif
  174694. #ifndef PNG_NO_READ_sBIT
  174695. # define PNG_READ_sBIT_SUPPORTED
  174696. # define PNG_sBIT_SUPPORTED
  174697. #endif
  174698. #ifndef PNG_NO_READ_sPLT
  174699. # define PNG_READ_sPLT_SUPPORTED
  174700. # define PNG_sPLT_SUPPORTED
  174701. #endif
  174702. #ifndef PNG_NO_READ_sRGB
  174703. # define PNG_READ_sRGB_SUPPORTED
  174704. # define PNG_sRGB_SUPPORTED
  174705. #endif
  174706. #ifndef PNG_NO_READ_tEXt
  174707. # define PNG_READ_tEXt_SUPPORTED
  174708. # define PNG_tEXt_SUPPORTED
  174709. #endif
  174710. #ifndef PNG_NO_READ_tIME
  174711. # define PNG_READ_tIME_SUPPORTED
  174712. # define PNG_tIME_SUPPORTED
  174713. #endif
  174714. #ifndef PNG_NO_READ_tRNS
  174715. # define PNG_READ_tRNS_SUPPORTED
  174716. # define PNG_tRNS_SUPPORTED
  174717. #endif
  174718. #ifndef PNG_NO_READ_zTXt
  174719. # define PNG_READ_zTXt_SUPPORTED
  174720. # define PNG_zTXt_SUPPORTED
  174721. #endif
  174722. #ifndef PNG_NO_READ_UNKNOWN_CHUNKS
  174723. # define PNG_READ_UNKNOWN_CHUNKS_SUPPORTED
  174724. # ifndef PNG_UNKNOWN_CHUNKS_SUPPORTED
  174725. # define PNG_UNKNOWN_CHUNKS_SUPPORTED
  174726. # endif
  174727. # ifndef PNG_NO_HANDLE_AS_UNKNOWN
  174728. # define PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  174729. # endif
  174730. #endif
  174731. #if !defined(PNG_NO_READ_USER_CHUNKS) && \
  174732. defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  174733. # define PNG_READ_USER_CHUNKS_SUPPORTED
  174734. # define PNG_USER_CHUNKS_SUPPORTED
  174735. # ifdef PNG_NO_READ_UNKNOWN_CHUNKS
  174736. # undef PNG_NO_READ_UNKNOWN_CHUNKS
  174737. # endif
  174738. # ifdef PNG_NO_HANDLE_AS_UNKNOWN
  174739. # undef PNG_NO_HANDLE_AS_UNKNOWN
  174740. # endif
  174741. #endif
  174742. #ifndef PNG_NO_READ_OPT_PLTE
  174743. # define PNG_READ_OPT_PLTE_SUPPORTED /* only affects support of the */
  174744. #endif /* optional PLTE chunk in RGB and RGBA images */
  174745. #if defined(PNG_READ_iTXt_SUPPORTED) || defined(PNG_READ_tEXt_SUPPORTED) || \
  174746. defined(PNG_READ_zTXt_SUPPORTED)
  174747. # define PNG_READ_TEXT_SUPPORTED
  174748. # define PNG_TEXT_SUPPORTED
  174749. #endif
  174750. #endif /* PNG_READ_ANCILLARY_CHUNKS_SUPPORTED */
  174751. #ifdef PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED
  174752. #ifdef PNG_NO_WRITE_TEXT
  174753. # define PNG_NO_WRITE_iTXt
  174754. # define PNG_NO_WRITE_tEXt
  174755. # define PNG_NO_WRITE_zTXt
  174756. #endif
  174757. #ifndef PNG_NO_WRITE_bKGD
  174758. # define PNG_WRITE_bKGD_SUPPORTED
  174759. # ifndef PNG_bKGD_SUPPORTED
  174760. # define PNG_bKGD_SUPPORTED
  174761. # endif
  174762. #endif
  174763. #ifndef PNG_NO_WRITE_cHRM
  174764. # define PNG_WRITE_cHRM_SUPPORTED
  174765. # ifndef PNG_cHRM_SUPPORTED
  174766. # define PNG_cHRM_SUPPORTED
  174767. # endif
  174768. #endif
  174769. #ifndef PNG_NO_WRITE_gAMA
  174770. # define PNG_WRITE_gAMA_SUPPORTED
  174771. # ifndef PNG_gAMA_SUPPORTED
  174772. # define PNG_gAMA_SUPPORTED
  174773. # endif
  174774. #endif
  174775. #ifndef PNG_NO_WRITE_hIST
  174776. # define PNG_WRITE_hIST_SUPPORTED
  174777. # ifndef PNG_hIST_SUPPORTED
  174778. # define PNG_hIST_SUPPORTED
  174779. # endif
  174780. #endif
  174781. #ifndef PNG_NO_WRITE_iCCP
  174782. # define PNG_WRITE_iCCP_SUPPORTED
  174783. # ifndef PNG_iCCP_SUPPORTED
  174784. # define PNG_iCCP_SUPPORTED
  174785. # endif
  174786. #endif
  174787. #ifndef PNG_NO_WRITE_iTXt
  174788. # ifndef PNG_WRITE_iTXt_SUPPORTED
  174789. # define PNG_WRITE_iTXt_SUPPORTED
  174790. # endif
  174791. # ifndef PNG_iTXt_SUPPORTED
  174792. # define PNG_iTXt_SUPPORTED
  174793. # endif
  174794. #endif
  174795. #ifndef PNG_NO_WRITE_oFFs
  174796. # define PNG_WRITE_oFFs_SUPPORTED
  174797. # ifndef PNG_oFFs_SUPPORTED
  174798. # define PNG_oFFs_SUPPORTED
  174799. # endif
  174800. #endif
  174801. #ifndef PNG_NO_WRITE_pCAL
  174802. # define PNG_WRITE_pCAL_SUPPORTED
  174803. # ifndef PNG_pCAL_SUPPORTED
  174804. # define PNG_pCAL_SUPPORTED
  174805. # endif
  174806. #endif
  174807. #ifndef PNG_NO_WRITE_sCAL
  174808. # define PNG_WRITE_sCAL_SUPPORTED
  174809. # ifndef PNG_sCAL_SUPPORTED
  174810. # define PNG_sCAL_SUPPORTED
  174811. # endif
  174812. #endif
  174813. #ifndef PNG_NO_WRITE_pHYs
  174814. # define PNG_WRITE_pHYs_SUPPORTED
  174815. # ifndef PNG_pHYs_SUPPORTED
  174816. # define PNG_pHYs_SUPPORTED
  174817. # endif
  174818. #endif
  174819. #ifndef PNG_NO_WRITE_sBIT
  174820. # define PNG_WRITE_sBIT_SUPPORTED
  174821. # ifndef PNG_sBIT_SUPPORTED
  174822. # define PNG_sBIT_SUPPORTED
  174823. # endif
  174824. #endif
  174825. #ifndef PNG_NO_WRITE_sPLT
  174826. # define PNG_WRITE_sPLT_SUPPORTED
  174827. # ifndef PNG_sPLT_SUPPORTED
  174828. # define PNG_sPLT_SUPPORTED
  174829. # endif
  174830. #endif
  174831. #ifndef PNG_NO_WRITE_sRGB
  174832. # define PNG_WRITE_sRGB_SUPPORTED
  174833. # ifndef PNG_sRGB_SUPPORTED
  174834. # define PNG_sRGB_SUPPORTED
  174835. # endif
  174836. #endif
  174837. #ifndef PNG_NO_WRITE_tEXt
  174838. # define PNG_WRITE_tEXt_SUPPORTED
  174839. # ifndef PNG_tEXt_SUPPORTED
  174840. # define PNG_tEXt_SUPPORTED
  174841. # endif
  174842. #endif
  174843. #ifndef PNG_NO_WRITE_tIME
  174844. # define PNG_WRITE_tIME_SUPPORTED
  174845. # ifndef PNG_tIME_SUPPORTED
  174846. # define PNG_tIME_SUPPORTED
  174847. # endif
  174848. #endif
  174849. #ifndef PNG_NO_WRITE_tRNS
  174850. # define PNG_WRITE_tRNS_SUPPORTED
  174851. # ifndef PNG_tRNS_SUPPORTED
  174852. # define PNG_tRNS_SUPPORTED
  174853. # endif
  174854. #endif
  174855. #ifndef PNG_NO_WRITE_zTXt
  174856. # define PNG_WRITE_zTXt_SUPPORTED
  174857. # ifndef PNG_zTXt_SUPPORTED
  174858. # define PNG_zTXt_SUPPORTED
  174859. # endif
  174860. #endif
  174861. #ifndef PNG_NO_WRITE_UNKNOWN_CHUNKS
  174862. # define PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED
  174863. # ifndef PNG_UNKNOWN_CHUNKS_SUPPORTED
  174864. # define PNG_UNKNOWN_CHUNKS_SUPPORTED
  174865. # endif
  174866. # ifndef PNG_NO_HANDLE_AS_UNKNOWN
  174867. # ifndef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  174868. # define PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  174869. # endif
  174870. # endif
  174871. #endif
  174872. #if defined(PNG_WRITE_iTXt_SUPPORTED) || defined(PNG_WRITE_tEXt_SUPPORTED) || \
  174873. defined(PNG_WRITE_zTXt_SUPPORTED)
  174874. # define PNG_WRITE_TEXT_SUPPORTED
  174875. # ifndef PNG_TEXT_SUPPORTED
  174876. # define PNG_TEXT_SUPPORTED
  174877. # endif
  174878. #endif
  174879. #endif /* PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED */
  174880. /* Turn this off to disable png_read_png() and
  174881. * png_write_png() and leave the row_pointers member
  174882. * out of the info structure.
  174883. */
  174884. #ifndef PNG_NO_INFO_IMAGE
  174885. # define PNG_INFO_IMAGE_SUPPORTED
  174886. #endif
  174887. /* need the time information for reading tIME chunks */
  174888. #if defined(PNG_tIME_SUPPORTED)
  174889. # if !defined(_WIN32_WCE)
  174890. /* "time.h" functions are not supported on WindowsCE */
  174891. # include <time.h>
  174892. # endif
  174893. #endif
  174894. /* Some typedefs to get us started. These should be safe on most of the
  174895. * common platforms. The typedefs should be at least as large as the
  174896. * numbers suggest (a png_uint_32 must be at least 32 bits long), but they
  174897. * don't have to be exactly that size. Some compilers dislike passing
  174898. * unsigned shorts as function parameters, so you may be better off using
  174899. * unsigned int for png_uint_16. Likewise, for 64-bit systems, you may
  174900. * want to have unsigned int for png_uint_32 instead of unsigned long.
  174901. */
  174902. typedef unsigned long png_uint_32;
  174903. typedef long png_int_32;
  174904. typedef unsigned short png_uint_16;
  174905. typedef short png_int_16;
  174906. typedef unsigned char png_byte;
  174907. /* This is usually size_t. It is typedef'ed just in case you need it to
  174908. change (I'm not sure if you will or not, so I thought I'd be safe) */
  174909. #ifdef PNG_SIZE_T
  174910. typedef PNG_SIZE_T png_size_t;
  174911. # define png_sizeof(x) png_convert_size(sizeof (x))
  174912. #else
  174913. typedef size_t png_size_t;
  174914. # define png_sizeof(x) sizeof (x)
  174915. #endif
  174916. /* The following is needed for medium model support. It cannot be in the
  174917. * PNG_INTERNAL section. Needs modification for other compilers besides
  174918. * MSC. Model independent support declares all arrays and pointers to be
  174919. * large using the far keyword. The zlib version used must also support
  174920. * model independent data. As of version zlib 1.0.4, the necessary changes
  174921. * have been made in zlib. The USE_FAR_KEYWORD define triggers other
  174922. * changes that are needed. (Tim Wegner)
  174923. */
  174924. /* Separate compiler dependencies (problem here is that zlib.h always
  174925. defines FAR. (SJT) */
  174926. #ifdef __BORLANDC__
  174927. # if defined(__LARGE__) || defined(__HUGE__) || defined(__COMPACT__)
  174928. # define LDATA 1
  174929. # else
  174930. # define LDATA 0
  174931. # endif
  174932. /* GRR: why is Cygwin in here? Cygwin is not Borland C... */
  174933. # if !defined(__WIN32__) && !defined(__FLAT__) && !defined(__CYGWIN__)
  174934. # define PNG_MAX_MALLOC_64K
  174935. # if (LDATA != 1)
  174936. # ifndef FAR
  174937. # define FAR __far
  174938. # endif
  174939. # define USE_FAR_KEYWORD
  174940. # endif /* LDATA != 1 */
  174941. /* Possibly useful for moving data out of default segment.
  174942. * Uncomment it if you want. Could also define FARDATA as
  174943. * const if your compiler supports it. (SJT)
  174944. # define FARDATA FAR
  174945. */
  174946. # endif /* __WIN32__, __FLAT__, __CYGWIN__ */
  174947. #endif /* __BORLANDC__ */
  174948. /* Suggest testing for specific compiler first before testing for
  174949. * FAR. The Watcom compiler defines both __MEDIUM__ and M_I86MM,
  174950. * making reliance oncertain keywords suspect. (SJT)
  174951. */
  174952. /* MSC Medium model */
  174953. #if defined(FAR)
  174954. # if defined(M_I86MM)
  174955. # define USE_FAR_KEYWORD
  174956. # define FARDATA FAR
  174957. # include <dos.h>
  174958. # endif
  174959. #endif
  174960. /* SJT: default case */
  174961. #ifndef FAR
  174962. # define FAR
  174963. #endif
  174964. /* At this point FAR is always defined */
  174965. #ifndef FARDATA
  174966. # define FARDATA
  174967. #endif
  174968. /* Typedef for floating-point numbers that are converted
  174969. to fixed-point with a multiple of 100,000, e.g., int_gamma */
  174970. typedef png_int_32 png_fixed_point;
  174971. /* Add typedefs for pointers */
  174972. typedef void FAR * png_voidp;
  174973. typedef png_byte FAR * png_bytep;
  174974. typedef png_uint_32 FAR * png_uint_32p;
  174975. typedef png_int_32 FAR * png_int_32p;
  174976. typedef png_uint_16 FAR * png_uint_16p;
  174977. typedef png_int_16 FAR * png_int_16p;
  174978. typedef PNG_CONST char FAR * png_const_charp;
  174979. typedef char FAR * png_charp;
  174980. typedef png_fixed_point FAR * png_fixed_point_p;
  174981. #ifndef PNG_NO_STDIO
  174982. #if defined(_WIN32_WCE)
  174983. typedef HANDLE png_FILE_p;
  174984. #else
  174985. typedef FILE * png_FILE_p;
  174986. #endif
  174987. #endif
  174988. #ifdef PNG_FLOATING_POINT_SUPPORTED
  174989. typedef double FAR * png_doublep;
  174990. #endif
  174991. /* Pointers to pointers; i.e. arrays */
  174992. typedef png_byte FAR * FAR * png_bytepp;
  174993. typedef png_uint_32 FAR * FAR * png_uint_32pp;
  174994. typedef png_int_32 FAR * FAR * png_int_32pp;
  174995. typedef png_uint_16 FAR * FAR * png_uint_16pp;
  174996. typedef png_int_16 FAR * FAR * png_int_16pp;
  174997. typedef PNG_CONST char FAR * FAR * png_const_charpp;
  174998. typedef char FAR * FAR * png_charpp;
  174999. typedef png_fixed_point FAR * FAR * png_fixed_point_pp;
  175000. #ifdef PNG_FLOATING_POINT_SUPPORTED
  175001. typedef double FAR * FAR * png_doublepp;
  175002. #endif
  175003. /* Pointers to pointers to pointers; i.e., pointer to array */
  175004. typedef char FAR * FAR * FAR * png_charppp;
  175005. #if 0
  175006. /* SPC - Is this stuff deprecated? */
  175007. /* It'll be removed as of libpng-1.3.0 - GR-P */
  175008. /* libpng typedefs for types in zlib. If zlib changes
  175009. * or another compression library is used, then change these.
  175010. * Eliminates need to change all the source files.
  175011. */
  175012. typedef charf * png_zcharp;
  175013. typedef charf * FAR * png_zcharpp;
  175014. typedef z_stream FAR * png_zstreamp;
  175015. #endif /* (PNG_1_0_X) || defined(PNG_1_2_X) */
  175016. /*
  175017. * Define PNG_BUILD_DLL if the module being built is a Windows
  175018. * LIBPNG DLL.
  175019. *
  175020. * Define PNG_USE_DLL if you want to *link* to the Windows LIBPNG DLL.
  175021. * It is equivalent to Microsoft predefined macro _DLL that is
  175022. * automatically defined when you compile using the share
  175023. * version of the CRT (C Run-Time library)
  175024. *
  175025. * The cygwin mods make this behavior a little different:
  175026. * Define PNG_BUILD_DLL if you are building a dll for use with cygwin
  175027. * Define PNG_STATIC if you are building a static library for use with cygwin,
  175028. * -or- if you are building an application that you want to link to the
  175029. * static library.
  175030. * PNG_USE_DLL is defined by default (no user action needed) unless one of
  175031. * the other flags is defined.
  175032. */
  175033. #if !defined(PNG_DLL) && (defined(PNG_BUILD_DLL) || defined(PNG_USE_DLL))
  175034. # define PNG_DLL
  175035. #endif
  175036. /* If CYGWIN, then disallow GLOBAL ARRAYS unless building a static lib.
  175037. * When building a static lib, default to no GLOBAL ARRAYS, but allow
  175038. * command-line override
  175039. */
  175040. #if defined(__CYGWIN__)
  175041. # if !defined(PNG_STATIC)
  175042. # if defined(PNG_USE_GLOBAL_ARRAYS)
  175043. # undef PNG_USE_GLOBAL_ARRAYS
  175044. # endif
  175045. # if !defined(PNG_USE_LOCAL_ARRAYS)
  175046. # define PNG_USE_LOCAL_ARRAYS
  175047. # endif
  175048. # else
  175049. # if defined(PNG_USE_LOCAL_ARRAYS) || defined(PNG_NO_GLOBAL_ARRAYS)
  175050. # if defined(PNG_USE_GLOBAL_ARRAYS)
  175051. # undef PNG_USE_GLOBAL_ARRAYS
  175052. # endif
  175053. # endif
  175054. # endif
  175055. # if !defined(PNG_USE_LOCAL_ARRAYS) && !defined(PNG_USE_GLOBAL_ARRAYS)
  175056. # define PNG_USE_LOCAL_ARRAYS
  175057. # endif
  175058. #endif
  175059. /* Do not use global arrays (helps with building DLL's)
  175060. * They are no longer used in libpng itself, since version 1.0.5c,
  175061. * but might be required for some pre-1.0.5c applications.
  175062. */
  175063. #if !defined(PNG_USE_LOCAL_ARRAYS) && !defined(PNG_USE_GLOBAL_ARRAYS)
  175064. # if defined(PNG_NO_GLOBAL_ARRAYS) || \
  175065. (defined(__GNUC__) && defined(PNG_DLL)) || defined(_MSC_VER)
  175066. # define PNG_USE_LOCAL_ARRAYS
  175067. # else
  175068. # define PNG_USE_GLOBAL_ARRAYS
  175069. # endif
  175070. #endif
  175071. #if defined(__CYGWIN__)
  175072. # undef PNGAPI
  175073. # define PNGAPI __cdecl
  175074. # undef PNG_IMPEXP
  175075. # define PNG_IMPEXP
  175076. #endif
  175077. /* If you define PNGAPI, e.g., with compiler option "-DPNGAPI=__stdcall",
  175078. * you may get warnings regarding the linkage of png_zalloc and png_zfree.
  175079. * Don't ignore those warnings; you must also reset the default calling
  175080. * convention in your compiler to match your PNGAPI, and you must build
  175081. * zlib and your applications the same way you build libpng.
  175082. */
  175083. #if defined(__MINGW32__) && !defined(PNG_MODULEDEF)
  175084. # ifndef PNG_NO_MODULEDEF
  175085. # define PNG_NO_MODULEDEF
  175086. # endif
  175087. #endif
  175088. #if !defined(PNG_IMPEXP) && defined(PNG_BUILD_DLL) && !defined(PNG_NO_MODULEDEF)
  175089. # define PNG_IMPEXP
  175090. #endif
  175091. #if defined(PNG_DLL) || defined(_DLL) || defined(__DLL__ ) || \
  175092. (( defined(_Windows) || defined(_WINDOWS) || \
  175093. defined(WIN32) || defined(_WIN32) || defined(__WIN32__) ))
  175094. # ifndef PNGAPI
  175095. # if defined(__GNUC__) || (defined (_MSC_VER) && (_MSC_VER >= 800))
  175096. # define PNGAPI __cdecl
  175097. # else
  175098. # define PNGAPI _cdecl
  175099. # endif
  175100. # endif
  175101. # if !defined(PNG_IMPEXP) && (!defined(PNG_DLL) || \
  175102. 0 /* WINCOMPILER_WITH_NO_SUPPORT_FOR_DECLIMPEXP */)
  175103. # define PNG_IMPEXP
  175104. # endif
  175105. # if !defined(PNG_IMPEXP)
  175106. # define PNG_EXPORT_TYPE1(type,symbol) PNG_IMPEXP type PNGAPI symbol
  175107. # define PNG_EXPORT_TYPE2(type,symbol) type PNG_IMPEXP PNGAPI symbol
  175108. /* Borland/Microsoft */
  175109. # if defined(_MSC_VER) || defined(__BORLANDC__)
  175110. # if (_MSC_VER >= 800) || (__BORLANDC__ >= 0x500)
  175111. # define PNG_EXPORT PNG_EXPORT_TYPE1
  175112. # else
  175113. # define PNG_EXPORT PNG_EXPORT_TYPE2
  175114. # if defined(PNG_BUILD_DLL)
  175115. # define PNG_IMPEXP __export
  175116. # else
  175117. # define PNG_IMPEXP /*__import */ /* doesn't exist AFAIK in
  175118. VC++ */
  175119. # endif /* Exists in Borland C++ for
  175120. C++ classes (== huge) */
  175121. # endif
  175122. # endif
  175123. # if !defined(PNG_IMPEXP)
  175124. # if defined(PNG_BUILD_DLL)
  175125. # define PNG_IMPEXP __declspec(dllexport)
  175126. # else
  175127. # define PNG_IMPEXP __declspec(dllimport)
  175128. # endif
  175129. # endif
  175130. # endif /* PNG_IMPEXP */
  175131. #else /* !(DLL || non-cygwin WINDOWS) */
  175132. # if (defined(__IBMC__) || defined(__IBMCPP__)) && defined(__OS2__)
  175133. # ifndef PNGAPI
  175134. # define PNGAPI _System
  175135. # endif
  175136. # else
  175137. # if 0 /* ... other platforms, with other meanings */
  175138. # endif
  175139. # endif
  175140. #endif
  175141. #ifndef PNGAPI
  175142. # define PNGAPI
  175143. #endif
  175144. #ifndef PNG_IMPEXP
  175145. # define PNG_IMPEXP
  175146. #endif
  175147. #ifdef PNG_BUILDSYMS
  175148. # ifndef PNG_EXPORT
  175149. # define PNG_EXPORT(type,symbol) PNG_FUNCTION_EXPORT symbol END
  175150. # endif
  175151. # ifdef PNG_USE_GLOBAL_ARRAYS
  175152. # ifndef PNG_EXPORT_VAR
  175153. # define PNG_EXPORT_VAR(type) PNG_DATA_EXPORT
  175154. # endif
  175155. # endif
  175156. #endif
  175157. #ifndef PNG_EXPORT
  175158. # define PNG_EXPORT(type,symbol) PNG_IMPEXP type PNGAPI symbol
  175159. #endif
  175160. #ifdef PNG_USE_GLOBAL_ARRAYS
  175161. # ifndef PNG_EXPORT_VAR
  175162. # define PNG_EXPORT_VAR(type) extern PNG_IMPEXP type
  175163. # endif
  175164. #endif
  175165. /* User may want to use these so they are not in PNG_INTERNAL. Any library
  175166. * functions that are passed far data must be model independent.
  175167. */
  175168. #ifndef PNG_ABORT
  175169. # define PNG_ABORT() abort()
  175170. #endif
  175171. #ifdef PNG_SETJMP_SUPPORTED
  175172. # define png_jmpbuf(png_ptr) ((png_ptr)->jmpbuf)
  175173. #else
  175174. # define png_jmpbuf(png_ptr) \
  175175. (LIBPNG_WAS_COMPILED_WITH__PNG_SETJMP_NOT_SUPPORTED)
  175176. #endif
  175177. #if defined(USE_FAR_KEYWORD) /* memory model independent fns */
  175178. /* use this to make far-to-near assignments */
  175179. # define CHECK 1
  175180. # define NOCHECK 0
  175181. # define CVT_PTR(ptr) (png_far_to_near(png_ptr,ptr,CHECK))
  175182. # define CVT_PTR_NOCHECK(ptr) (png_far_to_near(png_ptr,ptr,NOCHECK))
  175183. # define png_snprintf _fsnprintf /* Added to v 1.2.19 */
  175184. # define png_strcpy _fstrcpy
  175185. # define png_strncpy _fstrncpy /* Added to v 1.2.6 */
  175186. # define png_strlen _fstrlen
  175187. # define png_memcmp _fmemcmp /* SJT: added */
  175188. # define png_memcpy _fmemcpy
  175189. # define png_memset _fmemset
  175190. #else /* use the usual functions */
  175191. # define CVT_PTR(ptr) (ptr)
  175192. # define CVT_PTR_NOCHECK(ptr) (ptr)
  175193. # ifndef PNG_NO_SNPRINTF
  175194. # ifdef _MSC_VER
  175195. # define png_snprintf _snprintf /* Added to v 1.2.19 */
  175196. # define png_snprintf2 _snprintf
  175197. # define png_snprintf6 _snprintf
  175198. # else
  175199. # define png_snprintf snprintf /* Added to v 1.2.19 */
  175200. # define png_snprintf2 snprintf
  175201. # define png_snprintf6 snprintf
  175202. # endif
  175203. # else
  175204. /* You don't have or don't want to use snprintf(). Caution: Using
  175205. * sprintf instead of snprintf exposes your application to accidental
  175206. * or malevolent buffer overflows. If you don't have snprintf()
  175207. * as a general rule you should provide one (you can get one from
  175208. * Portable OpenSSH). */
  175209. # define png_snprintf(s1,n,fmt,x1) sprintf(s1,fmt,x1)
  175210. # define png_snprintf2(s1,n,fmt,x1,x2) sprintf(s1,fmt,x1,x2)
  175211. # define png_snprintf6(s1,n,fmt,x1,x2,x3,x4,x5,x6) \
  175212. sprintf(s1,fmt,x1,x2,x3,x4,x5,x6)
  175213. # endif
  175214. # define png_strcpy strcpy
  175215. # define png_strncpy strncpy /* Added to v 1.2.6 */
  175216. # define png_strlen strlen
  175217. # define png_memcmp memcmp /* SJT: added */
  175218. # define png_memcpy memcpy
  175219. # define png_memset memset
  175220. #endif
  175221. /* End of memory model independent support */
  175222. /* Just a little check that someone hasn't tried to define something
  175223. * contradictory.
  175224. */
  175225. #if (PNG_ZBUF_SIZE > 65536L) && defined(PNG_MAX_MALLOC_64K)
  175226. # undef PNG_ZBUF_SIZE
  175227. # define PNG_ZBUF_SIZE 65536L
  175228. #endif
  175229. /* Added at libpng-1.2.8 */
  175230. #endif /* PNG_VERSION_INFO_ONLY */
  175231. #endif /* PNGCONF_H */
  175232. /********* End of inlined file: pngconf.h *********/
  175233. #ifdef _MSC_VER
  175234. #pragma warning (disable: 4996 4100)
  175235. #endif
  175236. /*
  175237. * Added at libpng-1.2.8 */
  175238. /* Ref MSDN: Private as priority over Special
  175239. * VS_FF_PRIVATEBUILD File *was not* built using standard release
  175240. * procedures. If this value is given, the StringFileInfo block must
  175241. * contain a PrivateBuild string.
  175242. *
  175243. * VS_FF_SPECIALBUILD File *was* built by the original company using
  175244. * standard release procedures but is a variation of the standard
  175245. * file of the same version number. If this value is given, the
  175246. * StringFileInfo block must contain a SpecialBuild string.
  175247. */
  175248. #if defined(PNG_USER_PRIVATEBUILD)
  175249. # define PNG_LIBPNG_BUILD_TYPE \
  175250. (PNG_LIBPNG_BUILD_BASE_TYPE | PNG_LIBPNG_BUILD_PRIVATE)
  175251. #else
  175252. # if defined(PNG_LIBPNG_SPECIALBUILD)
  175253. # define PNG_LIBPNG_BUILD_TYPE \
  175254. (PNG_LIBPNG_BUILD_BASE_TYPE | PNG_LIBPNG_BUILD_SPECIAL)
  175255. # else
  175256. # define PNG_LIBPNG_BUILD_TYPE (PNG_LIBPNG_BUILD_BASE_TYPE)
  175257. # endif
  175258. #endif
  175259. #ifndef PNG_VERSION_INFO_ONLY
  175260. /* Inhibit C++ name-mangling for libpng functions but not for system calls. */
  175261. #ifdef __cplusplus
  175262. extern "C" {
  175263. #endif /* __cplusplus */
  175264. /* This file is arranged in several sections. The first section contains
  175265. * structure and type definitions. The second section contains the external
  175266. * library functions, while the third has the internal library functions,
  175267. * which applications aren't expected to use directly.
  175268. */
  175269. #ifndef PNG_NO_TYPECAST_NULL
  175270. #define int_p_NULL (int *)NULL
  175271. #define png_bytep_NULL (png_bytep)NULL
  175272. #define png_bytepp_NULL (png_bytepp)NULL
  175273. #define png_doublep_NULL (png_doublep)NULL
  175274. #define png_error_ptr_NULL (png_error_ptr)NULL
  175275. #define png_flush_ptr_NULL (png_flush_ptr)NULL
  175276. #define png_free_ptr_NULL (png_free_ptr)NULL
  175277. #define png_infopp_NULL (png_infopp)NULL
  175278. #define png_malloc_ptr_NULL (png_malloc_ptr)NULL
  175279. #define png_read_status_ptr_NULL (png_read_status_ptr)NULL
  175280. #define png_rw_ptr_NULL (png_rw_ptr)NULL
  175281. #define png_structp_NULL (png_structp)NULL
  175282. #define png_uint_16p_NULL (png_uint_16p)NULL
  175283. #define png_voidp_NULL (png_voidp)NULL
  175284. #define png_write_status_ptr_NULL (png_write_status_ptr)NULL
  175285. #else
  175286. #define int_p_NULL NULL
  175287. #define png_bytep_NULL NULL
  175288. #define png_bytepp_NULL NULL
  175289. #define png_doublep_NULL NULL
  175290. #define png_error_ptr_NULL NULL
  175291. #define png_flush_ptr_NULL NULL
  175292. #define png_free_ptr_NULL NULL
  175293. #define png_infopp_NULL NULL
  175294. #define png_malloc_ptr_NULL NULL
  175295. #define png_read_status_ptr_NULL NULL
  175296. #define png_rw_ptr_NULL NULL
  175297. #define png_structp_NULL NULL
  175298. #define png_uint_16p_NULL NULL
  175299. #define png_voidp_NULL NULL
  175300. #define png_write_status_ptr_NULL NULL
  175301. #endif
  175302. /* variables declared in png.c - only it needs to define PNG_NO_EXTERN */
  175303. #if !defined(PNG_NO_EXTERN) || defined(PNG_ALWAYS_EXTERN)
  175304. /* Version information for C files, stored in png.c. This had better match
  175305. * the version above.
  175306. */
  175307. #ifdef PNG_USE_GLOBAL_ARRAYS
  175308. PNG_EXPORT_VAR (PNG_CONST char) png_libpng_ver[18];
  175309. /* need room for 99.99.99beta99z */
  175310. #else
  175311. #define png_libpng_ver png_get_header_ver(NULL)
  175312. #endif
  175313. #ifdef PNG_USE_GLOBAL_ARRAYS
  175314. /* This was removed in version 1.0.5c */
  175315. /* Structures to facilitate easy interlacing. See png.c for more details */
  175316. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_start[7];
  175317. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_inc[7];
  175318. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_ystart[7];
  175319. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_yinc[7];
  175320. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_mask[7];
  175321. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_dsp_mask[7];
  175322. /* This isn't currently used. If you need it, see png.c for more details.
  175323. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_height[7];
  175324. */
  175325. #endif
  175326. #endif /* PNG_NO_EXTERN */
  175327. /* Three color definitions. The order of the red, green, and blue, (and the
  175328. * exact size) is not important, although the size of the fields need to
  175329. * be png_byte or png_uint_16 (as defined below).
  175330. */
  175331. typedef struct png_color_struct
  175332. {
  175333. png_byte red;
  175334. png_byte green;
  175335. png_byte blue;
  175336. } png_color;
  175337. typedef png_color FAR * png_colorp;
  175338. typedef png_color FAR * FAR * png_colorpp;
  175339. typedef struct png_color_16_struct
  175340. {
  175341. png_byte index; /* used for palette files */
  175342. png_uint_16 red; /* for use in red green blue files */
  175343. png_uint_16 green;
  175344. png_uint_16 blue;
  175345. png_uint_16 gray; /* for use in grayscale files */
  175346. } png_color_16;
  175347. typedef png_color_16 FAR * png_color_16p;
  175348. typedef png_color_16 FAR * FAR * png_color_16pp;
  175349. typedef struct png_color_8_struct
  175350. {
  175351. png_byte red; /* for use in red green blue files */
  175352. png_byte green;
  175353. png_byte blue;
  175354. png_byte gray; /* for use in grayscale files */
  175355. png_byte alpha; /* for alpha channel files */
  175356. } png_color_8;
  175357. typedef png_color_8 FAR * png_color_8p;
  175358. typedef png_color_8 FAR * FAR * png_color_8pp;
  175359. /*
  175360. * The following two structures are used for the in-core representation
  175361. * of sPLT chunks.
  175362. */
  175363. typedef struct png_sPLT_entry_struct
  175364. {
  175365. png_uint_16 red;
  175366. png_uint_16 green;
  175367. png_uint_16 blue;
  175368. png_uint_16 alpha;
  175369. png_uint_16 frequency;
  175370. } png_sPLT_entry;
  175371. typedef png_sPLT_entry FAR * png_sPLT_entryp;
  175372. typedef png_sPLT_entry FAR * FAR * png_sPLT_entrypp;
  175373. /* When the depth of the sPLT palette is 8 bits, the color and alpha samples
  175374. * occupy the LSB of their respective members, and the MSB of each member
  175375. * is zero-filled. The frequency member always occupies the full 16 bits.
  175376. */
  175377. typedef struct png_sPLT_struct
  175378. {
  175379. png_charp name; /* palette name */
  175380. png_byte depth; /* depth of palette samples */
  175381. png_sPLT_entryp entries; /* palette entries */
  175382. png_int_32 nentries; /* number of palette entries */
  175383. } png_sPLT_t;
  175384. typedef png_sPLT_t FAR * png_sPLT_tp;
  175385. typedef png_sPLT_t FAR * FAR * png_sPLT_tpp;
  175386. #ifdef PNG_TEXT_SUPPORTED
  175387. /* png_text holds the contents of a text/ztxt/itxt chunk in a PNG file,
  175388. * and whether that contents is compressed or not. The "key" field
  175389. * points to a regular zero-terminated C string. The "text", "lang", and
  175390. * "lang_key" fields can be regular C strings, empty strings, or NULL pointers.
  175391. * However, the * structure returned by png_get_text() will always contain
  175392. * regular zero-terminated C strings (possibly empty), never NULL pointers,
  175393. * so they can be safely used in printf() and other string-handling functions.
  175394. */
  175395. typedef struct png_text_struct
  175396. {
  175397. int compression; /* compression value:
  175398. -1: tEXt, none
  175399. 0: zTXt, deflate
  175400. 1: iTXt, none
  175401. 2: iTXt, deflate */
  175402. png_charp key; /* keyword, 1-79 character description of "text" */
  175403. png_charp text; /* comment, may be an empty string (ie "")
  175404. or a NULL pointer */
  175405. png_size_t text_length; /* length of the text string */
  175406. #ifdef PNG_iTXt_SUPPORTED
  175407. png_size_t itxt_length; /* length of the itxt string */
  175408. png_charp lang; /* language code, 0-79 characters
  175409. or a NULL pointer */
  175410. png_charp lang_key; /* keyword translated UTF-8 string, 0 or more
  175411. chars or a NULL pointer */
  175412. #endif
  175413. } png_text;
  175414. typedef png_text FAR * png_textp;
  175415. typedef png_text FAR * FAR * png_textpp;
  175416. #endif
  175417. /* Supported compression types for text in PNG files (tEXt, and zTXt).
  175418. * The values of the PNG_TEXT_COMPRESSION_ defines should NOT be changed. */
  175419. #define PNG_TEXT_COMPRESSION_NONE_WR -3
  175420. #define PNG_TEXT_COMPRESSION_zTXt_WR -2
  175421. #define PNG_TEXT_COMPRESSION_NONE -1
  175422. #define PNG_TEXT_COMPRESSION_zTXt 0
  175423. #define PNG_ITXT_COMPRESSION_NONE 1
  175424. #define PNG_ITXT_COMPRESSION_zTXt 2
  175425. #define PNG_TEXT_COMPRESSION_LAST 3 /* Not a valid value */
  175426. /* png_time is a way to hold the time in an machine independent way.
  175427. * Two conversions are provided, both from time_t and struct tm. There
  175428. * is no portable way to convert to either of these structures, as far
  175429. * as I know. If you know of a portable way, send it to me. As a side
  175430. * note - PNG has always been Year 2000 compliant!
  175431. */
  175432. typedef struct png_time_struct
  175433. {
  175434. png_uint_16 year; /* full year, as in, 1995 */
  175435. png_byte month; /* month of year, 1 - 12 */
  175436. png_byte day; /* day of month, 1 - 31 */
  175437. png_byte hour; /* hour of day, 0 - 23 */
  175438. png_byte minute; /* minute of hour, 0 - 59 */
  175439. png_byte second; /* second of minute, 0 - 60 (for leap seconds) */
  175440. } png_time;
  175441. typedef png_time FAR * png_timep;
  175442. typedef png_time FAR * FAR * png_timepp;
  175443. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  175444. /* png_unknown_chunk is a structure to hold queued chunks for which there is
  175445. * no specific support. The idea is that we can use this to queue
  175446. * up private chunks for output even though the library doesn't actually
  175447. * know about their semantics.
  175448. */
  175449. typedef struct png_unknown_chunk_t
  175450. {
  175451. png_byte name[5];
  175452. png_byte *data;
  175453. png_size_t size;
  175454. /* libpng-using applications should NOT directly modify this byte. */
  175455. png_byte location; /* mode of operation at read time */
  175456. }
  175457. png_unknown_chunk;
  175458. typedef png_unknown_chunk FAR * png_unknown_chunkp;
  175459. typedef png_unknown_chunk FAR * FAR * png_unknown_chunkpp;
  175460. #endif
  175461. /* png_info is a structure that holds the information in a PNG file so
  175462. * that the application can find out the characteristics of the image.
  175463. * If you are reading the file, this structure will tell you what is
  175464. * in the PNG file. If you are writing the file, fill in the information
  175465. * you want to put into the PNG file, then call png_write_info().
  175466. * The names chosen should be very close to the PNG specification, so
  175467. * consult that document for information about the meaning of each field.
  175468. *
  175469. * With libpng < 0.95, it was only possible to directly set and read the
  175470. * the values in the png_info_struct, which meant that the contents and
  175471. * order of the values had to remain fixed. With libpng 0.95 and later,
  175472. * however, there are now functions that abstract the contents of
  175473. * png_info_struct from the application, so this makes it easier to use
  175474. * libpng with dynamic libraries, and even makes it possible to use
  175475. * libraries that don't have all of the libpng ancillary chunk-handing
  175476. * functionality.
  175477. *
  175478. * In any case, the order of the parameters in png_info_struct should NOT
  175479. * be changed for as long as possible to keep compatibility with applications
  175480. * that use the old direct-access method with png_info_struct.
  175481. *
  175482. * The following members may have allocated storage attached that should be
  175483. * cleaned up before the structure is discarded: palette, trans, text,
  175484. * pcal_purpose, pcal_units, pcal_params, hist, iccp_name, iccp_profile,
  175485. * splt_palettes, scal_unit, row_pointers, and unknowns. By default, these
  175486. * are automatically freed when the info structure is deallocated, if they were
  175487. * allocated internally by libpng. This behavior can be changed by means
  175488. * of the png_data_freer() function.
  175489. *
  175490. * More allocation details: all the chunk-reading functions that
  175491. * change these members go through the corresponding png_set_*
  175492. * functions. A function to clear these members is available: see
  175493. * png_free_data(). The png_set_* functions do not depend on being
  175494. * able to point info structure members to any of the storage they are
  175495. * passed (they make their own copies), EXCEPT that the png_set_text
  175496. * functions use the same storage passed to them in the text_ptr or
  175497. * itxt_ptr structure argument, and the png_set_rows and png_set_unknowns
  175498. * functions do not make their own copies.
  175499. */
  175500. typedef struct png_info_struct
  175501. {
  175502. /* the following are necessary for every PNG file */
  175503. png_uint_32 width; /* width of image in pixels (from IHDR) */
  175504. png_uint_32 height; /* height of image in pixels (from IHDR) */
  175505. png_uint_32 valid; /* valid chunk data (see PNG_INFO_ below) */
  175506. png_uint_32 rowbytes; /* bytes needed to hold an untransformed row */
  175507. png_colorp palette; /* array of color values (valid & PNG_INFO_PLTE) */
  175508. png_uint_16 num_palette; /* number of color entries in "palette" (PLTE) */
  175509. png_uint_16 num_trans; /* number of transparent palette color (tRNS) */
  175510. png_byte bit_depth; /* 1, 2, 4, 8, or 16 bits/channel (from IHDR) */
  175511. png_byte color_type; /* see PNG_COLOR_TYPE_ below (from IHDR) */
  175512. /* The following three should have been named *_method not *_type */
  175513. png_byte compression_type; /* must be PNG_COMPRESSION_TYPE_BASE (IHDR) */
  175514. png_byte filter_type; /* must be PNG_FILTER_TYPE_BASE (from IHDR) */
  175515. png_byte interlace_type; /* One of PNG_INTERLACE_NONE, PNG_INTERLACE_ADAM7 */
  175516. /* The following is informational only on read, and not used on writes. */
  175517. png_byte channels; /* number of data channels per pixel (1, 2, 3, 4) */
  175518. png_byte pixel_depth; /* number of bits per pixel */
  175519. png_byte spare_byte; /* to align the data, and for future use */
  175520. png_byte signature[8]; /* magic bytes read by libpng from start of file */
  175521. /* The rest of the data is optional. If you are reading, check the
  175522. * valid field to see if the information in these are valid. If you
  175523. * are writing, set the valid field to those chunks you want written,
  175524. * and initialize the appropriate fields below.
  175525. */
  175526. #if defined(PNG_gAMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  175527. /* The gAMA chunk describes the gamma characteristics of the system
  175528. * on which the image was created, normally in the range [1.0, 2.5].
  175529. * Data is valid if (valid & PNG_INFO_gAMA) is non-zero.
  175530. */
  175531. float gamma; /* gamma value of image, if (valid & PNG_INFO_gAMA) */
  175532. #endif
  175533. #if defined(PNG_sRGB_SUPPORTED)
  175534. /* GR-P, 0.96a */
  175535. /* Data valid if (valid & PNG_INFO_sRGB) non-zero. */
  175536. png_byte srgb_intent; /* sRGB rendering intent [0, 1, 2, or 3] */
  175537. #endif
  175538. #if defined(PNG_TEXT_SUPPORTED)
  175539. /* The tEXt, and zTXt chunks contain human-readable textual data in
  175540. * uncompressed, compressed, and optionally compressed forms, respectively.
  175541. * The data in "text" is an array of pointers to uncompressed,
  175542. * null-terminated C strings. Each chunk has a keyword that describes the
  175543. * textual data contained in that chunk. Keywords are not required to be
  175544. * unique, and the text string may be empty. Any number of text chunks may
  175545. * be in an image.
  175546. */
  175547. int num_text; /* number of comments read/to write */
  175548. int max_text; /* current size of text array */
  175549. png_textp text; /* array of comments read/to write */
  175550. #endif /* PNG_TEXT_SUPPORTED */
  175551. #if defined(PNG_tIME_SUPPORTED)
  175552. /* The tIME chunk holds the last time the displayed image data was
  175553. * modified. See the png_time struct for the contents of this struct.
  175554. */
  175555. png_time mod_time;
  175556. #endif
  175557. #if defined(PNG_sBIT_SUPPORTED)
  175558. /* The sBIT chunk specifies the number of significant high-order bits
  175559. * in the pixel data. Values are in the range [1, bit_depth], and are
  175560. * only specified for the channels in the pixel data. The contents of
  175561. * the low-order bits is not specified. Data is valid if
  175562. * (valid & PNG_INFO_sBIT) is non-zero.
  175563. */
  175564. png_color_8 sig_bit; /* significant bits in color channels */
  175565. #endif
  175566. #if defined(PNG_tRNS_SUPPORTED) || defined(PNG_READ_EXPAND_SUPPORTED) || \
  175567. defined(PNG_READ_BACKGROUND_SUPPORTED)
  175568. /* The tRNS chunk supplies transparency data for paletted images and
  175569. * other image types that don't need a full alpha channel. There are
  175570. * "num_trans" transparency values for a paletted image, stored in the
  175571. * same order as the palette colors, starting from index 0. Values
  175572. * for the data are in the range [0, 255], ranging from fully transparent
  175573. * to fully opaque, respectively. For non-paletted images, there is a
  175574. * single color specified that should be treated as fully transparent.
  175575. * Data is valid if (valid & PNG_INFO_tRNS) is non-zero.
  175576. */
  175577. png_bytep trans; /* transparent values for paletted image */
  175578. png_color_16 trans_values; /* transparent color for non-palette image */
  175579. #endif
  175580. #if defined(PNG_bKGD_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  175581. /* The bKGD chunk gives the suggested image background color if the
  175582. * display program does not have its own background color and the image
  175583. * is needs to composited onto a background before display. The colors
  175584. * in "background" are normally in the same color space/depth as the
  175585. * pixel data. Data is valid if (valid & PNG_INFO_bKGD) is non-zero.
  175586. */
  175587. png_color_16 background;
  175588. #endif
  175589. #if defined(PNG_oFFs_SUPPORTED)
  175590. /* The oFFs chunk gives the offset in "offset_unit_type" units rightwards
  175591. * and downwards from the top-left corner of the display, page, or other
  175592. * application-specific co-ordinate space. See the PNG_OFFSET_ defines
  175593. * below for the unit types. Valid if (valid & PNG_INFO_oFFs) non-zero.
  175594. */
  175595. png_int_32 x_offset; /* x offset on page */
  175596. png_int_32 y_offset; /* y offset on page */
  175597. png_byte offset_unit_type; /* offset units type */
  175598. #endif
  175599. #if defined(PNG_pHYs_SUPPORTED)
  175600. /* The pHYs chunk gives the physical pixel density of the image for
  175601. * display or printing in "phys_unit_type" units (see PNG_RESOLUTION_
  175602. * defines below). Data is valid if (valid & PNG_INFO_pHYs) is non-zero.
  175603. */
  175604. png_uint_32 x_pixels_per_unit; /* horizontal pixel density */
  175605. png_uint_32 y_pixels_per_unit; /* vertical pixel density */
  175606. png_byte phys_unit_type; /* resolution type (see PNG_RESOLUTION_ below) */
  175607. #endif
  175608. #if defined(PNG_hIST_SUPPORTED)
  175609. /* The hIST chunk contains the relative frequency or importance of the
  175610. * various palette entries, so that a viewer can intelligently select a
  175611. * reduced-color palette, if required. Data is an array of "num_palette"
  175612. * values in the range [0,65535]. Data valid if (valid & PNG_INFO_hIST)
  175613. * is non-zero.
  175614. */
  175615. png_uint_16p hist;
  175616. #endif
  175617. #ifdef PNG_cHRM_SUPPORTED
  175618. /* The cHRM chunk describes the CIE color characteristics of the monitor
  175619. * on which the PNG was created. This data allows the viewer to do gamut
  175620. * mapping of the input image to ensure that the viewer sees the same
  175621. * colors in the image as the creator. Values are in the range
  175622. * [0.0, 0.8]. Data valid if (valid & PNG_INFO_cHRM) non-zero.
  175623. */
  175624. #ifdef PNG_FLOATING_POINT_SUPPORTED
  175625. float x_white;
  175626. float y_white;
  175627. float x_red;
  175628. float y_red;
  175629. float x_green;
  175630. float y_green;
  175631. float x_blue;
  175632. float y_blue;
  175633. #endif
  175634. #endif
  175635. #if defined(PNG_pCAL_SUPPORTED)
  175636. /* The pCAL chunk describes a transformation between the stored pixel
  175637. * values and original physical data values used to create the image.
  175638. * The integer range [0, 2^bit_depth - 1] maps to the floating-point
  175639. * range given by [pcal_X0, pcal_X1], and are further transformed by a
  175640. * (possibly non-linear) transformation function given by "pcal_type"
  175641. * and "pcal_params" into "pcal_units". Please see the PNG_EQUATION_
  175642. * defines below, and the PNG-Group's PNG extensions document for a
  175643. * complete description of the transformations and how they should be
  175644. * implemented, and for a description of the ASCII parameter strings.
  175645. * Data values are valid if (valid & PNG_INFO_pCAL) non-zero.
  175646. */
  175647. png_charp pcal_purpose; /* pCAL chunk description string */
  175648. png_int_32 pcal_X0; /* minimum value */
  175649. png_int_32 pcal_X1; /* maximum value */
  175650. png_charp pcal_units; /* Latin-1 string giving physical units */
  175651. png_charpp pcal_params; /* ASCII strings containing parameter values */
  175652. png_byte pcal_type; /* equation type (see PNG_EQUATION_ below) */
  175653. png_byte pcal_nparams; /* number of parameters given in pcal_params */
  175654. #endif
  175655. /* New members added in libpng-1.0.6 */
  175656. #ifdef PNG_FREE_ME_SUPPORTED
  175657. png_uint_32 free_me; /* flags items libpng is responsible for freeing */
  175658. #endif
  175659. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  175660. /* storage for unknown chunks that the library doesn't recognize. */
  175661. png_unknown_chunkp unknown_chunks;
  175662. png_size_t unknown_chunks_num;
  175663. #endif
  175664. #if defined(PNG_iCCP_SUPPORTED)
  175665. /* iCCP chunk data. */
  175666. png_charp iccp_name; /* profile name */
  175667. png_charp iccp_profile; /* International Color Consortium profile data */
  175668. /* Note to maintainer: should be png_bytep */
  175669. png_uint_32 iccp_proflen; /* ICC profile data length */
  175670. png_byte iccp_compression; /* Always zero */
  175671. #endif
  175672. #if defined(PNG_sPLT_SUPPORTED)
  175673. /* data on sPLT chunks (there may be more than one). */
  175674. png_sPLT_tp splt_palettes;
  175675. png_uint_32 splt_palettes_num;
  175676. #endif
  175677. #if defined(PNG_sCAL_SUPPORTED)
  175678. /* The sCAL chunk describes the actual physical dimensions of the
  175679. * subject matter of the graphic. The chunk contains a unit specification
  175680. * a byte value, and two ASCII strings representing floating-point
  175681. * values. The values are width and height corresponsing to one pixel
  175682. * in the image. This external representation is converted to double
  175683. * here. Data values are valid if (valid & PNG_INFO_sCAL) is non-zero.
  175684. */
  175685. png_byte scal_unit; /* unit of physical scale */
  175686. #ifdef PNG_FLOATING_POINT_SUPPORTED
  175687. double scal_pixel_width; /* width of one pixel */
  175688. double scal_pixel_height; /* height of one pixel */
  175689. #endif
  175690. #ifdef PNG_FIXED_POINT_SUPPORTED
  175691. png_charp scal_s_width; /* string containing height */
  175692. png_charp scal_s_height; /* string containing width */
  175693. #endif
  175694. #endif
  175695. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  175696. /* Memory has been allocated if (valid & PNG_ALLOCATED_INFO_ROWS) non-zero */
  175697. /* Data valid if (valid & PNG_INFO_IDAT) non-zero */
  175698. png_bytepp row_pointers; /* the image bits */
  175699. #endif
  175700. #if defined(PNG_FIXED_POINT_SUPPORTED) && defined(PNG_gAMA_SUPPORTED)
  175701. png_fixed_point int_gamma; /* gamma of image, if (valid & PNG_INFO_gAMA) */
  175702. #endif
  175703. #if defined(PNG_cHRM_SUPPORTED) && defined(PNG_FIXED_POINT_SUPPORTED)
  175704. png_fixed_point int_x_white;
  175705. png_fixed_point int_y_white;
  175706. png_fixed_point int_x_red;
  175707. png_fixed_point int_y_red;
  175708. png_fixed_point int_x_green;
  175709. png_fixed_point int_y_green;
  175710. png_fixed_point int_x_blue;
  175711. png_fixed_point int_y_blue;
  175712. #endif
  175713. } png_info;
  175714. typedef png_info FAR * png_infop;
  175715. typedef png_info FAR * FAR * png_infopp;
  175716. /* Maximum positive integer used in PNG is (2^31)-1 */
  175717. #define PNG_UINT_31_MAX ((png_uint_32)0x7fffffffL)
  175718. #define PNG_UINT_32_MAX ((png_uint_32)(-1))
  175719. #define PNG_SIZE_MAX ((png_size_t)(-1))
  175720. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  175721. /* PNG_MAX_UINT is deprecated; use PNG_UINT_31_MAX instead. */
  175722. #define PNG_MAX_UINT PNG_UINT_31_MAX
  175723. #endif
  175724. /* These describe the color_type field in png_info. */
  175725. /* color type masks */
  175726. #define PNG_COLOR_MASK_PALETTE 1
  175727. #define PNG_COLOR_MASK_COLOR 2
  175728. #define PNG_COLOR_MASK_ALPHA 4
  175729. /* color types. Note that not all combinations are legal */
  175730. #define PNG_COLOR_TYPE_GRAY 0
  175731. #define PNG_COLOR_TYPE_PALETTE (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_PALETTE)
  175732. #define PNG_COLOR_TYPE_RGB (PNG_COLOR_MASK_COLOR)
  175733. #define PNG_COLOR_TYPE_RGB_ALPHA (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_ALPHA)
  175734. #define PNG_COLOR_TYPE_GRAY_ALPHA (PNG_COLOR_MASK_ALPHA)
  175735. /* aliases */
  175736. #define PNG_COLOR_TYPE_RGBA PNG_COLOR_TYPE_RGB_ALPHA
  175737. #define PNG_COLOR_TYPE_GA PNG_COLOR_TYPE_GRAY_ALPHA
  175738. /* This is for compression type. PNG 1.0-1.2 only define the single type. */
  175739. #define PNG_COMPRESSION_TYPE_BASE 0 /* Deflate method 8, 32K window */
  175740. #define PNG_COMPRESSION_TYPE_DEFAULT PNG_COMPRESSION_TYPE_BASE
  175741. /* This is for filter type. PNG 1.0-1.2 only define the single type. */
  175742. #define PNG_FILTER_TYPE_BASE 0 /* Single row per-byte filtering */
  175743. #define PNG_INTRAPIXEL_DIFFERENCING 64 /* Used only in MNG datastreams */
  175744. #define PNG_FILTER_TYPE_DEFAULT PNG_FILTER_TYPE_BASE
  175745. /* These are for the interlacing type. These values should NOT be changed. */
  175746. #define PNG_INTERLACE_NONE 0 /* Non-interlaced image */
  175747. #define PNG_INTERLACE_ADAM7 1 /* Adam7 interlacing */
  175748. #define PNG_INTERLACE_LAST 2 /* Not a valid value */
  175749. /* These are for the oFFs chunk. These values should NOT be changed. */
  175750. #define PNG_OFFSET_PIXEL 0 /* Offset in pixels */
  175751. #define PNG_OFFSET_MICROMETER 1 /* Offset in micrometers (1/10^6 meter) */
  175752. #define PNG_OFFSET_LAST 2 /* Not a valid value */
  175753. /* These are for the pCAL chunk. These values should NOT be changed. */
  175754. #define PNG_EQUATION_LINEAR 0 /* Linear transformation */
  175755. #define PNG_EQUATION_BASE_E 1 /* Exponential base e transform */
  175756. #define PNG_EQUATION_ARBITRARY 2 /* Arbitrary base exponential transform */
  175757. #define PNG_EQUATION_HYPERBOLIC 3 /* Hyperbolic sine transformation */
  175758. #define PNG_EQUATION_LAST 4 /* Not a valid value */
  175759. /* These are for the sCAL chunk. These values should NOT be changed. */
  175760. #define PNG_SCALE_UNKNOWN 0 /* unknown unit (image scale) */
  175761. #define PNG_SCALE_METER 1 /* meters per pixel */
  175762. #define PNG_SCALE_RADIAN 2 /* radians per pixel */
  175763. #define PNG_SCALE_LAST 3 /* Not a valid value */
  175764. /* These are for the pHYs chunk. These values should NOT be changed. */
  175765. #define PNG_RESOLUTION_UNKNOWN 0 /* pixels/unknown unit (aspect ratio) */
  175766. #define PNG_RESOLUTION_METER 1 /* pixels/meter */
  175767. #define PNG_RESOLUTION_LAST 2 /* Not a valid value */
  175768. /* These are for the sRGB chunk. These values should NOT be changed. */
  175769. #define PNG_sRGB_INTENT_PERCEPTUAL 0
  175770. #define PNG_sRGB_INTENT_RELATIVE 1
  175771. #define PNG_sRGB_INTENT_SATURATION 2
  175772. #define PNG_sRGB_INTENT_ABSOLUTE 3
  175773. #define PNG_sRGB_INTENT_LAST 4 /* Not a valid value */
  175774. /* This is for text chunks */
  175775. #define PNG_KEYWORD_MAX_LENGTH 79
  175776. /* Maximum number of entries in PLTE/sPLT/tRNS arrays */
  175777. #define PNG_MAX_PALETTE_LENGTH 256
  175778. /* These determine if an ancillary chunk's data has been successfully read
  175779. * from the PNG header, or if the application has filled in the corresponding
  175780. * data in the info_struct to be written into the output file. The values
  175781. * of the PNG_INFO_<chunk> defines should NOT be changed.
  175782. */
  175783. #define PNG_INFO_gAMA 0x0001
  175784. #define PNG_INFO_sBIT 0x0002
  175785. #define PNG_INFO_cHRM 0x0004
  175786. #define PNG_INFO_PLTE 0x0008
  175787. #define PNG_INFO_tRNS 0x0010
  175788. #define PNG_INFO_bKGD 0x0020
  175789. #define PNG_INFO_hIST 0x0040
  175790. #define PNG_INFO_pHYs 0x0080
  175791. #define PNG_INFO_oFFs 0x0100
  175792. #define PNG_INFO_tIME 0x0200
  175793. #define PNG_INFO_pCAL 0x0400
  175794. #define PNG_INFO_sRGB 0x0800 /* GR-P, 0.96a */
  175795. #define PNG_INFO_iCCP 0x1000 /* ESR, 1.0.6 */
  175796. #define PNG_INFO_sPLT 0x2000 /* ESR, 1.0.6 */
  175797. #define PNG_INFO_sCAL 0x4000 /* ESR, 1.0.6 */
  175798. #define PNG_INFO_IDAT 0x8000L /* ESR, 1.0.6 */
  175799. /* This is used for the transformation routines, as some of them
  175800. * change these values for the row. It also should enable using
  175801. * the routines for other purposes.
  175802. */
  175803. typedef struct png_row_info_struct
  175804. {
  175805. png_uint_32 width; /* width of row */
  175806. png_uint_32 rowbytes; /* number of bytes in row */
  175807. png_byte color_type; /* color type of row */
  175808. png_byte bit_depth; /* bit depth of row */
  175809. png_byte channels; /* number of channels (1, 2, 3, or 4) */
  175810. png_byte pixel_depth; /* bits per pixel (depth * channels) */
  175811. } png_row_info;
  175812. typedef png_row_info FAR * png_row_infop;
  175813. typedef png_row_info FAR * FAR * png_row_infopp;
  175814. /* These are the function types for the I/O functions and for the functions
  175815. * that allow the user to override the default I/O functions with his or her
  175816. * own. The png_error_ptr type should match that of user-supplied warning
  175817. * and error functions, while the png_rw_ptr type should match that of the
  175818. * user read/write data functions.
  175819. */
  175820. typedef struct png_struct_def png_struct;
  175821. typedef png_struct FAR * png_structp;
  175822. typedef void (PNGAPI *png_error_ptr) PNGARG((png_structp, png_const_charp));
  175823. typedef void (PNGAPI *png_rw_ptr) PNGARG((png_structp, png_bytep, png_size_t));
  175824. typedef void (PNGAPI *png_flush_ptr) PNGARG((png_structp));
  175825. typedef void (PNGAPI *png_read_status_ptr) PNGARG((png_structp, png_uint_32,
  175826. int));
  175827. typedef void (PNGAPI *png_write_status_ptr) PNGARG((png_structp, png_uint_32,
  175828. int));
  175829. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  175830. typedef void (PNGAPI *png_progressive_info_ptr) PNGARG((png_structp, png_infop));
  175831. typedef void (PNGAPI *png_progressive_end_ptr) PNGARG((png_structp, png_infop));
  175832. typedef void (PNGAPI *png_progressive_row_ptr) PNGARG((png_structp, png_bytep,
  175833. png_uint_32, int));
  175834. #endif
  175835. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  175836. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  175837. defined(PNG_LEGACY_SUPPORTED)
  175838. typedef void (PNGAPI *png_user_transform_ptr) PNGARG((png_structp,
  175839. png_row_infop, png_bytep));
  175840. #endif
  175841. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  175842. typedef int (PNGAPI *png_user_chunk_ptr) PNGARG((png_structp, png_unknown_chunkp));
  175843. #endif
  175844. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  175845. typedef void (PNGAPI *png_unknown_chunk_ptr) PNGARG((png_structp));
  175846. #endif
  175847. /* Transform masks for the high-level interface */
  175848. #define PNG_TRANSFORM_IDENTITY 0x0000 /* read and write */
  175849. #define PNG_TRANSFORM_STRIP_16 0x0001 /* read only */
  175850. #define PNG_TRANSFORM_STRIP_ALPHA 0x0002 /* read only */
  175851. #define PNG_TRANSFORM_PACKING 0x0004 /* read and write */
  175852. #define PNG_TRANSFORM_PACKSWAP 0x0008 /* read and write */
  175853. #define PNG_TRANSFORM_EXPAND 0x0010 /* read only */
  175854. #define PNG_TRANSFORM_INVERT_MONO 0x0020 /* read and write */
  175855. #define PNG_TRANSFORM_SHIFT 0x0040 /* read and write */
  175856. #define PNG_TRANSFORM_BGR 0x0080 /* read and write */
  175857. #define PNG_TRANSFORM_SWAP_ALPHA 0x0100 /* read and write */
  175858. #define PNG_TRANSFORM_SWAP_ENDIAN 0x0200 /* read and write */
  175859. #define PNG_TRANSFORM_INVERT_ALPHA 0x0400 /* read and write */
  175860. #define PNG_TRANSFORM_STRIP_FILLER 0x0800 /* WRITE only */
  175861. /* Flags for MNG supported features */
  175862. #define PNG_FLAG_MNG_EMPTY_PLTE 0x01
  175863. #define PNG_FLAG_MNG_FILTER_64 0x04
  175864. #define PNG_ALL_MNG_FEATURES 0x05
  175865. typedef png_voidp (*png_malloc_ptr) PNGARG((png_structp, png_size_t));
  175866. typedef void (*png_free_ptr) PNGARG((png_structp, png_voidp));
  175867. /* The structure that holds the information to read and write PNG files.
  175868. * The only people who need to care about what is inside of this are the
  175869. * people who will be modifying the library for their own special needs.
  175870. * It should NOT be accessed directly by an application, except to store
  175871. * the jmp_buf.
  175872. */
  175873. struct png_struct_def
  175874. {
  175875. #ifdef PNG_SETJMP_SUPPORTED
  175876. jmp_buf jmpbuf; /* used in png_error */
  175877. #endif
  175878. png_error_ptr error_fn; /* function for printing errors and aborting */
  175879. png_error_ptr warning_fn; /* function for printing warnings */
  175880. png_voidp error_ptr; /* user supplied struct for error functions */
  175881. png_rw_ptr write_data_fn; /* function for writing output data */
  175882. png_rw_ptr read_data_fn; /* function for reading input data */
  175883. png_voidp io_ptr; /* ptr to application struct for I/O functions */
  175884. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  175885. png_user_transform_ptr read_user_transform_fn; /* user read transform */
  175886. #endif
  175887. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  175888. png_user_transform_ptr write_user_transform_fn; /* user write transform */
  175889. #endif
  175890. /* These were added in libpng-1.0.2 */
  175891. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  175892. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  175893. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  175894. png_voidp user_transform_ptr; /* user supplied struct for user transform */
  175895. png_byte user_transform_depth; /* bit depth of user transformed pixels */
  175896. png_byte user_transform_channels; /* channels in user transformed pixels */
  175897. #endif
  175898. #endif
  175899. png_uint_32 mode; /* tells us where we are in the PNG file */
  175900. png_uint_32 flags; /* flags indicating various things to libpng */
  175901. png_uint_32 transformations; /* which transformations to perform */
  175902. z_stream zstream; /* pointer to decompression structure (below) */
  175903. png_bytep zbuf; /* buffer for zlib */
  175904. png_size_t zbuf_size; /* size of zbuf */
  175905. int zlib_level; /* holds zlib compression level */
  175906. int zlib_method; /* holds zlib compression method */
  175907. int zlib_window_bits; /* holds zlib compression window bits */
  175908. int zlib_mem_level; /* holds zlib compression memory level */
  175909. int zlib_strategy; /* holds zlib compression strategy */
  175910. png_uint_32 width; /* width of image in pixels */
  175911. png_uint_32 height; /* height of image in pixels */
  175912. png_uint_32 num_rows; /* number of rows in current pass */
  175913. png_uint_32 usr_width; /* width of row at start of write */
  175914. png_uint_32 rowbytes; /* size of row in bytes */
  175915. png_uint_32 irowbytes; /* size of current interlaced row in bytes */
  175916. png_uint_32 iwidth; /* width of current interlaced row in pixels */
  175917. png_uint_32 row_number; /* current row in interlace pass */
  175918. png_bytep prev_row; /* buffer to save previous (unfiltered) row */
  175919. png_bytep row_buf; /* buffer to save current (unfiltered) row */
  175920. png_bytep sub_row; /* buffer to save "sub" row when filtering */
  175921. png_bytep up_row; /* buffer to save "up" row when filtering */
  175922. png_bytep avg_row; /* buffer to save "avg" row when filtering */
  175923. png_bytep paeth_row; /* buffer to save "Paeth" row when filtering */
  175924. png_row_info row_info; /* used for transformation routines */
  175925. png_uint_32 idat_size; /* current IDAT size for read */
  175926. png_uint_32 crc; /* current chunk CRC value */
  175927. png_colorp palette; /* palette from the input file */
  175928. png_uint_16 num_palette; /* number of color entries in palette */
  175929. png_uint_16 num_trans; /* number of transparency values */
  175930. png_byte chunk_name[5]; /* null-terminated name of current chunk */
  175931. png_byte compression; /* file compression type (always 0) */
  175932. png_byte filter; /* file filter type (always 0) */
  175933. png_byte interlaced; /* PNG_INTERLACE_NONE, PNG_INTERLACE_ADAM7 */
  175934. png_byte pass; /* current interlace pass (0 - 6) */
  175935. png_byte do_filter; /* row filter flags (see PNG_FILTER_ below ) */
  175936. png_byte color_type; /* color type of file */
  175937. png_byte bit_depth; /* bit depth of file */
  175938. png_byte usr_bit_depth; /* bit depth of users row */
  175939. png_byte pixel_depth; /* number of bits per pixel */
  175940. png_byte channels; /* number of channels in file */
  175941. png_byte usr_channels; /* channels at start of write */
  175942. png_byte sig_bytes; /* magic bytes read/written from start of file */
  175943. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  175944. #ifdef PNG_LEGACY_SUPPORTED
  175945. png_byte filler; /* filler byte for pixel expansion */
  175946. #else
  175947. png_uint_16 filler; /* filler bytes for pixel expansion */
  175948. #endif
  175949. #endif
  175950. #if defined(PNG_bKGD_SUPPORTED)
  175951. png_byte background_gamma_type;
  175952. # ifdef PNG_FLOATING_POINT_SUPPORTED
  175953. float background_gamma;
  175954. # endif
  175955. png_color_16 background; /* background color in screen gamma space */
  175956. #if defined(PNG_READ_GAMMA_SUPPORTED)
  175957. png_color_16 background_1; /* background normalized to gamma 1.0 */
  175958. #endif
  175959. #endif /* PNG_bKGD_SUPPORTED */
  175960. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  175961. png_flush_ptr output_flush_fn;/* Function for flushing output */
  175962. png_uint_32 flush_dist; /* how many rows apart to flush, 0 - no flush */
  175963. png_uint_32 flush_rows; /* number of rows written since last flush */
  175964. #endif
  175965. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  175966. int gamma_shift; /* number of "insignificant" bits 16-bit gamma */
  175967. #ifdef PNG_FLOATING_POINT_SUPPORTED
  175968. float gamma; /* file gamma value */
  175969. float screen_gamma; /* screen gamma value (display_exponent) */
  175970. #endif
  175971. #endif
  175972. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  175973. png_bytep gamma_table; /* gamma table for 8-bit depth files */
  175974. png_bytep gamma_from_1; /* converts from 1.0 to screen */
  175975. png_bytep gamma_to_1; /* converts from file to 1.0 */
  175976. png_uint_16pp gamma_16_table; /* gamma table for 16-bit depth files */
  175977. png_uint_16pp gamma_16_from_1; /* converts from 1.0 to screen */
  175978. png_uint_16pp gamma_16_to_1; /* converts from file to 1.0 */
  175979. #endif
  175980. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_sBIT_SUPPORTED)
  175981. png_color_8 sig_bit; /* significant bits in each available channel */
  175982. #endif
  175983. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  175984. png_color_8 shift; /* shift for significant bit tranformation */
  175985. #endif
  175986. #if defined(PNG_tRNS_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED) \
  175987. || defined(PNG_READ_EXPAND_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  175988. png_bytep trans; /* transparency values for paletted files */
  175989. png_color_16 trans_values; /* transparency values for non-paletted files */
  175990. #endif
  175991. png_read_status_ptr read_row_fn; /* called after each row is decoded */
  175992. png_write_status_ptr write_row_fn; /* called after each row is encoded */
  175993. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  175994. png_progressive_info_ptr info_fn; /* called after header data fully read */
  175995. png_progressive_row_ptr row_fn; /* called after each prog. row is decoded */
  175996. png_progressive_end_ptr end_fn; /* called after image is complete */
  175997. png_bytep save_buffer_ptr; /* current location in save_buffer */
  175998. png_bytep save_buffer; /* buffer for previously read data */
  175999. png_bytep current_buffer_ptr; /* current location in current_buffer */
  176000. png_bytep current_buffer; /* buffer for recently used data */
  176001. png_uint_32 push_length; /* size of current input chunk */
  176002. png_uint_32 skip_length; /* bytes to skip in input data */
  176003. png_size_t save_buffer_size; /* amount of data now in save_buffer */
  176004. png_size_t save_buffer_max; /* total size of save_buffer */
  176005. png_size_t buffer_size; /* total amount of available input data */
  176006. png_size_t current_buffer_size; /* amount of data now in current_buffer */
  176007. int process_mode; /* what push library is currently doing */
  176008. int cur_palette; /* current push library palette index */
  176009. # if defined(PNG_TEXT_SUPPORTED)
  176010. png_size_t current_text_size; /* current size of text input data */
  176011. png_size_t current_text_left; /* how much text left to read in input */
  176012. png_charp current_text; /* current text chunk buffer */
  176013. png_charp current_text_ptr; /* current location in current_text */
  176014. # endif /* PNG_TEXT_SUPPORTED */
  176015. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  176016. #if defined(__TURBOC__) && !defined(_Windows) && !defined(__FLAT__)
  176017. /* for the Borland special 64K segment handler */
  176018. png_bytepp offset_table_ptr;
  176019. png_bytep offset_table;
  176020. png_uint_16 offset_table_number;
  176021. png_uint_16 offset_table_count;
  176022. png_uint_16 offset_table_count_free;
  176023. #endif
  176024. #if defined(PNG_READ_DITHER_SUPPORTED)
  176025. png_bytep palette_lookup; /* lookup table for dithering */
  176026. png_bytep dither_index; /* index translation for palette files */
  176027. #endif
  176028. #if defined(PNG_READ_DITHER_SUPPORTED) || defined(PNG_hIST_SUPPORTED)
  176029. png_uint_16p hist; /* histogram */
  176030. #endif
  176031. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  176032. png_byte heuristic_method; /* heuristic for row filter selection */
  176033. png_byte num_prev_filters; /* number of weights for previous rows */
  176034. png_bytep prev_filters; /* filter type(s) of previous row(s) */
  176035. png_uint_16p filter_weights; /* weight(s) for previous line(s) */
  176036. png_uint_16p inv_filter_weights; /* 1/weight(s) for previous line(s) */
  176037. png_uint_16p filter_costs; /* relative filter calculation cost */
  176038. png_uint_16p inv_filter_costs; /* 1/relative filter calculation cost */
  176039. #endif
  176040. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  176041. png_charp time_buffer; /* String to hold RFC 1123 time text */
  176042. #endif
  176043. /* New members added in libpng-1.0.6 */
  176044. #ifdef PNG_FREE_ME_SUPPORTED
  176045. png_uint_32 free_me; /* flags items libpng is responsible for freeing */
  176046. #endif
  176047. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  176048. png_voidp user_chunk_ptr;
  176049. png_user_chunk_ptr read_user_chunk_fn; /* user read chunk handler */
  176050. #endif
  176051. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  176052. int num_chunk_list;
  176053. png_bytep chunk_list;
  176054. #endif
  176055. /* New members added in libpng-1.0.3 */
  176056. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  176057. png_byte rgb_to_gray_status;
  176058. /* These were changed from png_byte in libpng-1.0.6 */
  176059. png_uint_16 rgb_to_gray_red_coeff;
  176060. png_uint_16 rgb_to_gray_green_coeff;
  176061. png_uint_16 rgb_to_gray_blue_coeff;
  176062. #endif
  176063. /* New member added in libpng-1.0.4 (renamed in 1.0.9) */
  176064. #if defined(PNG_MNG_FEATURES_SUPPORTED) || \
  176065. defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  176066. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  176067. /* changed from png_byte to png_uint_32 at version 1.2.0 */
  176068. #ifdef PNG_1_0_X
  176069. png_byte mng_features_permitted;
  176070. #else
  176071. png_uint_32 mng_features_permitted;
  176072. #endif /* PNG_1_0_X */
  176073. #endif
  176074. /* New member added in libpng-1.0.7 */
  176075. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  176076. png_fixed_point int_gamma;
  176077. #endif
  176078. /* New member added in libpng-1.0.9, ifdef'ed out in 1.0.12, enabled in 1.2.0 */
  176079. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  176080. png_byte filter_type;
  176081. #endif
  176082. #if defined(PNG_1_0_X)
  176083. /* New member added in libpng-1.0.10, ifdef'ed out in 1.2.0 */
  176084. png_uint_32 row_buf_size;
  176085. #endif
  176086. /* New members added in libpng-1.2.0 */
  176087. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  176088. # if !defined(PNG_1_0_X)
  176089. # if defined(PNG_MMX_CODE_SUPPORTED)
  176090. png_byte mmx_bitdepth_threshold;
  176091. png_uint_32 mmx_rowbytes_threshold;
  176092. # endif
  176093. png_uint_32 asm_flags;
  176094. # endif
  176095. #endif
  176096. /* New members added in libpng-1.0.2 but first enabled by default in 1.2.0 */
  176097. #ifdef PNG_USER_MEM_SUPPORTED
  176098. png_voidp mem_ptr; /* user supplied struct for mem functions */
  176099. png_malloc_ptr malloc_fn; /* function for allocating memory */
  176100. png_free_ptr free_fn; /* function for freeing memory */
  176101. #endif
  176102. /* New member added in libpng-1.0.13 and 1.2.0 */
  176103. png_bytep big_row_buf; /* buffer to save current (unfiltered) row */
  176104. #if defined(PNG_READ_DITHER_SUPPORTED)
  176105. /* The following three members were added at version 1.0.14 and 1.2.4 */
  176106. png_bytep dither_sort; /* working sort array */
  176107. png_bytep index_to_palette; /* where the original index currently is */
  176108. /* in the palette */
  176109. png_bytep palette_to_index; /* which original index points to this */
  176110. /* palette color */
  176111. #endif
  176112. /* New members added in libpng-1.0.16 and 1.2.6 */
  176113. png_byte compression_type;
  176114. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  176115. png_uint_32 user_width_max;
  176116. png_uint_32 user_height_max;
  176117. #endif
  176118. /* New member added in libpng-1.0.25 and 1.2.17 */
  176119. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  176120. /* storage for unknown chunk that the library doesn't recognize. */
  176121. png_unknown_chunk unknown_chunk;
  176122. #endif
  176123. };
  176124. /* This triggers a compiler error in png.c, if png.c and png.h
  176125. * do not agree upon the version number.
  176126. */
  176127. typedef png_structp version_1_2_21;
  176128. typedef png_struct FAR * FAR * png_structpp;
  176129. /* Here are the function definitions most commonly used. This is not
  176130. * the place to find out how to use libpng. See libpng.txt for the
  176131. * full explanation, see example.c for the summary. This just provides
  176132. * a simple one line description of the use of each function.
  176133. */
  176134. /* Returns the version number of the library */
  176135. extern PNG_EXPORT(png_uint_32,png_access_version_number) PNGARG((void));
  176136. /* Tell lib we have already handled the first <num_bytes> magic bytes.
  176137. * Handling more than 8 bytes from the beginning of the file is an error.
  176138. */
  176139. extern PNG_EXPORT(void,png_set_sig_bytes) PNGARG((png_structp png_ptr,
  176140. int num_bytes));
  176141. /* Check sig[start] through sig[start + num_to_check - 1] to see if it's a
  176142. * PNG file. Returns zero if the supplied bytes match the 8-byte PNG
  176143. * signature, and non-zero otherwise. Having num_to_check == 0 or
  176144. * start > 7 will always fail (ie return non-zero).
  176145. */
  176146. extern PNG_EXPORT(int,png_sig_cmp) PNGARG((png_bytep sig, png_size_t start,
  176147. png_size_t num_to_check));
  176148. /* Simple signature checking function. This is the same as calling
  176149. * png_check_sig(sig, n) := !png_sig_cmp(sig, 0, n).
  176150. */
  176151. extern PNG_EXPORT(int,png_check_sig) PNGARG((png_bytep sig, int num));
  176152. /* Allocate and initialize png_ptr struct for reading, and any other memory. */
  176153. extern PNG_EXPORT(png_structp,png_create_read_struct)
  176154. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  176155. png_error_ptr error_fn, png_error_ptr warn_fn));
  176156. /* Allocate and initialize png_ptr struct for writing, and any other memory */
  176157. extern PNG_EXPORT(png_structp,png_create_write_struct)
  176158. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  176159. png_error_ptr error_fn, png_error_ptr warn_fn));
  176160. #ifdef PNG_WRITE_SUPPORTED
  176161. extern PNG_EXPORT(png_uint_32,png_get_compression_buffer_size)
  176162. PNGARG((png_structp png_ptr));
  176163. #endif
  176164. #ifdef PNG_WRITE_SUPPORTED
  176165. extern PNG_EXPORT(void,png_set_compression_buffer_size)
  176166. PNGARG((png_structp png_ptr, png_uint_32 size));
  176167. #endif
  176168. /* Reset the compression stream */
  176169. extern PNG_EXPORT(int,png_reset_zstream) PNGARG((png_structp png_ptr));
  176170. /* New functions added in libpng-1.0.2 (not enabled by default until 1.2.0) */
  176171. #ifdef PNG_USER_MEM_SUPPORTED
  176172. extern PNG_EXPORT(png_structp,png_create_read_struct_2)
  176173. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  176174. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  176175. png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  176176. extern PNG_EXPORT(png_structp,png_create_write_struct_2)
  176177. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  176178. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  176179. png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  176180. #endif
  176181. /* Write a PNG chunk - size, type, (optional) data, CRC. */
  176182. extern PNG_EXPORT(void,png_write_chunk) PNGARG((png_structp png_ptr,
  176183. png_bytep chunk_name, png_bytep data, png_size_t length));
  176184. /* Write the start of a PNG chunk - length and chunk name. */
  176185. extern PNG_EXPORT(void,png_write_chunk_start) PNGARG((png_structp png_ptr,
  176186. png_bytep chunk_name, png_uint_32 length));
  176187. /* Write the data of a PNG chunk started with png_write_chunk_start(). */
  176188. extern PNG_EXPORT(void,png_write_chunk_data) PNGARG((png_structp png_ptr,
  176189. png_bytep data, png_size_t length));
  176190. /* Finish a chunk started with png_write_chunk_start() (includes CRC). */
  176191. extern PNG_EXPORT(void,png_write_chunk_end) PNGARG((png_structp png_ptr));
  176192. /* Allocate and initialize the info structure */
  176193. extern PNG_EXPORT(png_infop,png_create_info_struct)
  176194. PNGARG((png_structp png_ptr));
  176195. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  176196. /* Initialize the info structure (old interface - DEPRECATED) */
  176197. extern PNG_EXPORT(void,png_info_init) PNGARG((png_infop info_ptr));
  176198. #undef png_info_init
  176199. #define png_info_init(info_ptr) png_info_init_3(&info_ptr,\
  176200. png_sizeof(png_info));
  176201. #endif
  176202. extern PNG_EXPORT(void,png_info_init_3) PNGARG((png_infopp info_ptr,
  176203. png_size_t png_info_struct_size));
  176204. /* Writes all the PNG information before the image. */
  176205. extern PNG_EXPORT(void,png_write_info_before_PLTE) PNGARG((png_structp png_ptr,
  176206. png_infop info_ptr));
  176207. extern PNG_EXPORT(void,png_write_info) PNGARG((png_structp png_ptr,
  176208. png_infop info_ptr));
  176209. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  176210. /* read the information before the actual image data. */
  176211. extern PNG_EXPORT(void,png_read_info) PNGARG((png_structp png_ptr,
  176212. png_infop info_ptr));
  176213. #endif
  176214. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  176215. extern PNG_EXPORT(png_charp,png_convert_to_rfc1123)
  176216. PNGARG((png_structp png_ptr, png_timep ptime));
  176217. #endif
  176218. #if !defined(_WIN32_WCE)
  176219. /* "time.h" functions are not supported on WindowsCE */
  176220. #if defined(PNG_WRITE_tIME_SUPPORTED)
  176221. /* convert from a struct tm to png_time */
  176222. extern PNG_EXPORT(void,png_convert_from_struct_tm) PNGARG((png_timep ptime,
  176223. struct tm FAR * ttime));
  176224. /* convert from time_t to png_time. Uses gmtime() */
  176225. extern PNG_EXPORT(void,png_convert_from_time_t) PNGARG((png_timep ptime,
  176226. time_t ttime));
  176227. #endif /* PNG_WRITE_tIME_SUPPORTED */
  176228. #endif /* _WIN32_WCE */
  176229. #if defined(PNG_READ_EXPAND_SUPPORTED)
  176230. /* Expand data to 24-bit RGB, or 8-bit grayscale, with alpha if available. */
  176231. extern PNG_EXPORT(void,png_set_expand) PNGARG((png_structp png_ptr));
  176232. #if !defined(PNG_1_0_X)
  176233. extern PNG_EXPORT(void,png_set_expand_gray_1_2_4_to_8) PNGARG((png_structp
  176234. png_ptr));
  176235. #endif
  176236. extern PNG_EXPORT(void,png_set_palette_to_rgb) PNGARG((png_structp png_ptr));
  176237. extern PNG_EXPORT(void,png_set_tRNS_to_alpha) PNGARG((png_structp png_ptr));
  176238. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  176239. /* Deprecated */
  176240. extern PNG_EXPORT(void,png_set_gray_1_2_4_to_8) PNGARG((png_structp png_ptr));
  176241. #endif
  176242. #endif
  176243. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  176244. /* Use blue, green, red order for pixels. */
  176245. extern PNG_EXPORT(void,png_set_bgr) PNGARG((png_structp png_ptr));
  176246. #endif
  176247. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  176248. /* Expand the grayscale to 24-bit RGB if necessary. */
  176249. extern PNG_EXPORT(void,png_set_gray_to_rgb) PNGARG((png_structp png_ptr));
  176250. #endif
  176251. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  176252. /* Reduce RGB to grayscale. */
  176253. #ifdef PNG_FLOATING_POINT_SUPPORTED
  176254. extern PNG_EXPORT(void,png_set_rgb_to_gray) PNGARG((png_structp png_ptr,
  176255. int error_action, double red, double green ));
  176256. #endif
  176257. extern PNG_EXPORT(void,png_set_rgb_to_gray_fixed) PNGARG((png_structp png_ptr,
  176258. int error_action, png_fixed_point red, png_fixed_point green ));
  176259. extern PNG_EXPORT(png_byte,png_get_rgb_to_gray_status) PNGARG((png_structp
  176260. png_ptr));
  176261. #endif
  176262. extern PNG_EXPORT(void,png_build_grayscale_palette) PNGARG((int bit_depth,
  176263. png_colorp palette));
  176264. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  176265. extern PNG_EXPORT(void,png_set_strip_alpha) PNGARG((png_structp png_ptr));
  176266. #endif
  176267. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED) || \
  176268. defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  176269. extern PNG_EXPORT(void,png_set_swap_alpha) PNGARG((png_structp png_ptr));
  176270. #endif
  176271. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED) || \
  176272. defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  176273. extern PNG_EXPORT(void,png_set_invert_alpha) PNGARG((png_structp png_ptr));
  176274. #endif
  176275. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  176276. /* Add a filler byte to 8-bit Gray or 24-bit RGB images. */
  176277. extern PNG_EXPORT(void,png_set_filler) PNGARG((png_structp png_ptr,
  176278. png_uint_32 filler, int flags));
  176279. /* The values of the PNG_FILLER_ defines should NOT be changed */
  176280. #define PNG_FILLER_BEFORE 0
  176281. #define PNG_FILLER_AFTER 1
  176282. /* Add an alpha byte to 8-bit Gray or 24-bit RGB images. */
  176283. #if !defined(PNG_1_0_X)
  176284. extern PNG_EXPORT(void,png_set_add_alpha) PNGARG((png_structp png_ptr,
  176285. png_uint_32 filler, int flags));
  176286. #endif
  176287. #endif /* PNG_READ_FILLER_SUPPORTED || PNG_WRITE_FILLER_SUPPORTED */
  176288. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  176289. /* Swap bytes in 16-bit depth files. */
  176290. extern PNG_EXPORT(void,png_set_swap) PNGARG((png_structp png_ptr));
  176291. #endif
  176292. #if defined(PNG_READ_PACK_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED)
  176293. /* Use 1 byte per pixel in 1, 2, or 4-bit depth files. */
  176294. extern PNG_EXPORT(void,png_set_packing) PNGARG((png_structp png_ptr));
  176295. #endif
  176296. #if defined(PNG_READ_PACKSWAP_SUPPORTED) || defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  176297. /* Swap packing order of pixels in bytes. */
  176298. extern PNG_EXPORT(void,png_set_packswap) PNGARG((png_structp png_ptr));
  176299. #endif
  176300. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  176301. /* Converts files to legal bit depths. */
  176302. extern PNG_EXPORT(void,png_set_shift) PNGARG((png_structp png_ptr,
  176303. png_color_8p true_bits));
  176304. #endif
  176305. #if defined(PNG_READ_INTERLACING_SUPPORTED) || \
  176306. defined(PNG_WRITE_INTERLACING_SUPPORTED)
  176307. /* Have the code handle the interlacing. Returns the number of passes. */
  176308. extern PNG_EXPORT(int,png_set_interlace_handling) PNGARG((png_structp png_ptr));
  176309. #endif
  176310. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  176311. /* Invert monochrome files */
  176312. extern PNG_EXPORT(void,png_set_invert_mono) PNGARG((png_structp png_ptr));
  176313. #endif
  176314. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  176315. /* Handle alpha and tRNS by replacing with a background color. */
  176316. #ifdef PNG_FLOATING_POINT_SUPPORTED
  176317. extern PNG_EXPORT(void,png_set_background) PNGARG((png_structp png_ptr,
  176318. png_color_16p background_color, int background_gamma_code,
  176319. int need_expand, double background_gamma));
  176320. #endif
  176321. #define PNG_BACKGROUND_GAMMA_UNKNOWN 0
  176322. #define PNG_BACKGROUND_GAMMA_SCREEN 1
  176323. #define PNG_BACKGROUND_GAMMA_FILE 2
  176324. #define PNG_BACKGROUND_GAMMA_UNIQUE 3
  176325. #endif
  176326. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  176327. /* strip the second byte of information from a 16-bit depth file. */
  176328. extern PNG_EXPORT(void,png_set_strip_16) PNGARG((png_structp png_ptr));
  176329. #endif
  176330. #if defined(PNG_READ_DITHER_SUPPORTED)
  176331. /* Turn on dithering, and reduce the palette to the number of colors available. */
  176332. extern PNG_EXPORT(void,png_set_dither) PNGARG((png_structp png_ptr,
  176333. png_colorp palette, int num_palette, int maximum_colors,
  176334. png_uint_16p histogram, int full_dither));
  176335. #endif
  176336. #if defined(PNG_READ_GAMMA_SUPPORTED)
  176337. /* Handle gamma correction. Screen_gamma=(display_exponent) */
  176338. #ifdef PNG_FLOATING_POINT_SUPPORTED
  176339. extern PNG_EXPORT(void,png_set_gamma) PNGARG((png_structp png_ptr,
  176340. double screen_gamma, double default_file_gamma));
  176341. #endif
  176342. #endif
  176343. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  176344. #if defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  176345. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  176346. /* Permit or disallow empty PLTE (0: not permitted, 1: permitted) */
  176347. /* Deprecated and will be removed. Use png_permit_mng_features() instead. */
  176348. extern PNG_EXPORT(void,png_permit_empty_plte) PNGARG((png_structp png_ptr,
  176349. int empty_plte_permitted));
  176350. #endif
  176351. #endif
  176352. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  176353. /* Set how many lines between output flushes - 0 for no flushing */
  176354. extern PNG_EXPORT(void,png_set_flush) PNGARG((png_structp png_ptr, int nrows));
  176355. /* Flush the current PNG output buffer */
  176356. extern PNG_EXPORT(void,png_write_flush) PNGARG((png_structp png_ptr));
  176357. #endif
  176358. /* optional update palette with requested transformations */
  176359. extern PNG_EXPORT(void,png_start_read_image) PNGARG((png_structp png_ptr));
  176360. /* optional call to update the users info structure */
  176361. extern PNG_EXPORT(void,png_read_update_info) PNGARG((png_structp png_ptr,
  176362. png_infop info_ptr));
  176363. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  176364. /* read one or more rows of image data. */
  176365. extern PNG_EXPORT(void,png_read_rows) PNGARG((png_structp png_ptr,
  176366. png_bytepp row, png_bytepp display_row, png_uint_32 num_rows));
  176367. #endif
  176368. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  176369. /* read a row of data. */
  176370. extern PNG_EXPORT(void,png_read_row) PNGARG((png_structp png_ptr,
  176371. png_bytep row,
  176372. png_bytep display_row));
  176373. #endif
  176374. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  176375. /* read the whole image into memory at once. */
  176376. extern PNG_EXPORT(void,png_read_image) PNGARG((png_structp png_ptr,
  176377. png_bytepp image));
  176378. #endif
  176379. /* write a row of image data */
  176380. extern PNG_EXPORT(void,png_write_row) PNGARG((png_structp png_ptr,
  176381. png_bytep row));
  176382. /* write a few rows of image data */
  176383. extern PNG_EXPORT(void,png_write_rows) PNGARG((png_structp png_ptr,
  176384. png_bytepp row, png_uint_32 num_rows));
  176385. /* write the image data */
  176386. extern PNG_EXPORT(void,png_write_image) PNGARG((png_structp png_ptr,
  176387. png_bytepp image));
  176388. /* writes the end of the PNG file. */
  176389. extern PNG_EXPORT(void,png_write_end) PNGARG((png_structp png_ptr,
  176390. png_infop info_ptr));
  176391. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  176392. /* read the end of the PNG file. */
  176393. extern PNG_EXPORT(void,png_read_end) PNGARG((png_structp png_ptr,
  176394. png_infop info_ptr));
  176395. #endif
  176396. /* free any memory associated with the png_info_struct */
  176397. extern PNG_EXPORT(void,png_destroy_info_struct) PNGARG((png_structp png_ptr,
  176398. png_infopp info_ptr_ptr));
  176399. /* free any memory associated with the png_struct and the png_info_structs */
  176400. extern PNG_EXPORT(void,png_destroy_read_struct) PNGARG((png_structpp
  176401. png_ptr_ptr, png_infopp info_ptr_ptr, png_infopp end_info_ptr_ptr));
  176402. /* free all memory used by the read (old method - NOT DLL EXPORTED) */
  176403. extern void png_read_destroy PNGARG((png_structp png_ptr, png_infop info_ptr,
  176404. png_infop end_info_ptr));
  176405. /* free any memory associated with the png_struct and the png_info_structs */
  176406. extern PNG_EXPORT(void,png_destroy_write_struct)
  176407. PNGARG((png_structpp png_ptr_ptr, png_infopp info_ptr_ptr));
  176408. /* free any memory used in png_ptr struct (old method - NOT DLL EXPORTED) */
  176409. extern void png_write_destroy PNGARG((png_structp png_ptr));
  176410. /* set the libpng method of handling chunk CRC errors */
  176411. extern PNG_EXPORT(void,png_set_crc_action) PNGARG((png_structp png_ptr,
  176412. int crit_action, int ancil_action));
  176413. /* Values for png_set_crc_action() to say how to handle CRC errors in
  176414. * ancillary and critical chunks, and whether to use the data contained
  176415. * therein. Note that it is impossible to "discard" data in a critical
  176416. * chunk. For versions prior to 0.90, the action was always error/quit,
  176417. * whereas in version 0.90 and later, the action for CRC errors in ancillary
  176418. * chunks is warn/discard. These values should NOT be changed.
  176419. *
  176420. * value action:critical action:ancillary
  176421. */
  176422. #define PNG_CRC_DEFAULT 0 /* error/quit warn/discard data */
  176423. #define PNG_CRC_ERROR_QUIT 1 /* error/quit error/quit */
  176424. #define PNG_CRC_WARN_DISCARD 2 /* (INVALID) warn/discard data */
  176425. #define PNG_CRC_WARN_USE 3 /* warn/use data warn/use data */
  176426. #define PNG_CRC_QUIET_USE 4 /* quiet/use data quiet/use data */
  176427. #define PNG_CRC_NO_CHANGE 5 /* use current value use current value */
  176428. /* These functions give the user control over the scan-line filtering in
  176429. * libpng and the compression methods used by zlib. These functions are
  176430. * mainly useful for testing, as the defaults should work with most users.
  176431. * Those users who are tight on memory or want faster performance at the
  176432. * expense of compression can modify them. See the compression library
  176433. * header file (zlib.h) for an explination of the compression functions.
  176434. */
  176435. /* set the filtering method(s) used by libpng. Currently, the only valid
  176436. * value for "method" is 0.
  176437. */
  176438. extern PNG_EXPORT(void,png_set_filter) PNGARG((png_structp png_ptr, int method,
  176439. int filters));
  176440. /* Flags for png_set_filter() to say which filters to use. The flags
  176441. * are chosen so that they don't conflict with real filter types
  176442. * below, in case they are supplied instead of the #defined constants.
  176443. * These values should NOT be changed.
  176444. */
  176445. #define PNG_NO_FILTERS 0x00
  176446. #define PNG_FILTER_NONE 0x08
  176447. #define PNG_FILTER_SUB 0x10
  176448. #define PNG_FILTER_UP 0x20
  176449. #define PNG_FILTER_AVG 0x40
  176450. #define PNG_FILTER_PAETH 0x80
  176451. #define PNG_ALL_FILTERS (PNG_FILTER_NONE | PNG_FILTER_SUB | PNG_FILTER_UP | \
  176452. PNG_FILTER_AVG | PNG_FILTER_PAETH)
  176453. /* Filter values (not flags) - used in pngwrite.c, pngwutil.c for now.
  176454. * These defines should NOT be changed.
  176455. */
  176456. #define PNG_FILTER_VALUE_NONE 0
  176457. #define PNG_FILTER_VALUE_SUB 1
  176458. #define PNG_FILTER_VALUE_UP 2
  176459. #define PNG_FILTER_VALUE_AVG 3
  176460. #define PNG_FILTER_VALUE_PAETH 4
  176461. #define PNG_FILTER_VALUE_LAST 5
  176462. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED) /* EXPERIMENTAL */
  176463. /* The "heuristic_method" is given by one of the PNG_FILTER_HEURISTIC_
  176464. * defines, either the default (minimum-sum-of-absolute-differences), or
  176465. * the experimental method (weighted-minimum-sum-of-absolute-differences).
  176466. *
  176467. * Weights are factors >= 1.0, indicating how important it is to keep the
  176468. * filter type consistent between rows. Larger numbers mean the current
  176469. * filter is that many times as likely to be the same as the "num_weights"
  176470. * previous filters. This is cumulative for each previous row with a weight.
  176471. * There needs to be "num_weights" values in "filter_weights", or it can be
  176472. * NULL if the weights aren't being specified. Weights have no influence on
  176473. * the selection of the first row filter. Well chosen weights can (in theory)
  176474. * improve the compression for a given image.
  176475. *
  176476. * Costs are factors >= 1.0 indicating the relative decoding costs of a
  176477. * filter type. Higher costs indicate more decoding expense, and are
  176478. * therefore less likely to be selected over a filter with lower computational
  176479. * costs. There needs to be a value in "filter_costs" for each valid filter
  176480. * type (given by PNG_FILTER_VALUE_LAST), or it can be NULL if you aren't
  176481. * setting the costs. Costs try to improve the speed of decompression without
  176482. * unduly increasing the compressed image size.
  176483. *
  176484. * A negative weight or cost indicates the default value is to be used, and
  176485. * values in the range [0.0, 1.0) indicate the value is to remain unchanged.
  176486. * The default values for both weights and costs are currently 1.0, but may
  176487. * change if good general weighting/cost heuristics can be found. If both
  176488. * the weights and costs are set to 1.0, this degenerates the WEIGHTED method
  176489. * to the UNWEIGHTED method, but with added encoding time/computation.
  176490. */
  176491. #ifdef PNG_FLOATING_POINT_SUPPORTED
  176492. extern PNG_EXPORT(void,png_set_filter_heuristics) PNGARG((png_structp png_ptr,
  176493. int heuristic_method, int num_weights, png_doublep filter_weights,
  176494. png_doublep filter_costs));
  176495. #endif
  176496. #endif /* PNG_WRITE_WEIGHTED_FILTER_SUPPORTED */
  176497. /* Heuristic used for row filter selection. These defines should NOT be
  176498. * changed.
  176499. */
  176500. #define PNG_FILTER_HEURISTIC_DEFAULT 0 /* Currently "UNWEIGHTED" */
  176501. #define PNG_FILTER_HEURISTIC_UNWEIGHTED 1 /* Used by libpng < 0.95 */
  176502. #define PNG_FILTER_HEURISTIC_WEIGHTED 2 /* Experimental feature */
  176503. #define PNG_FILTER_HEURISTIC_LAST 3 /* Not a valid value */
  176504. /* Set the library compression level. Currently, valid values range from
  176505. * 0 - 9, corresponding directly to the zlib compression levels 0 - 9
  176506. * (0 - no compression, 9 - "maximal" compression). Note that tests have
  176507. * shown that zlib compression levels 3-6 usually perform as well as level 9
  176508. * for PNG images, and do considerably fewer caclulations. In the future,
  176509. * these values may not correspond directly to the zlib compression levels.
  176510. */
  176511. extern PNG_EXPORT(void,png_set_compression_level) PNGARG((png_structp png_ptr,
  176512. int level));
  176513. extern PNG_EXPORT(void,png_set_compression_mem_level)
  176514. PNGARG((png_structp png_ptr, int mem_level));
  176515. extern PNG_EXPORT(void,png_set_compression_strategy)
  176516. PNGARG((png_structp png_ptr, int strategy));
  176517. extern PNG_EXPORT(void,png_set_compression_window_bits)
  176518. PNGARG((png_structp png_ptr, int window_bits));
  176519. extern PNG_EXPORT(void,png_set_compression_method) PNGARG((png_structp png_ptr,
  176520. int method));
  176521. /* These next functions are called for input/output, memory, and error
  176522. * handling. They are in the file pngrio.c, pngwio.c, and pngerror.c,
  176523. * and call standard C I/O routines such as fread(), fwrite(), and
  176524. * fprintf(). These functions can be made to use other I/O routines
  176525. * at run time for those applications that need to handle I/O in a
  176526. * different manner by calling png_set_???_fn(). See libpng.txt for
  176527. * more information.
  176528. */
  176529. #if !defined(PNG_NO_STDIO)
  176530. /* Initialize the input/output for the PNG file to the default functions. */
  176531. extern PNG_EXPORT(void,png_init_io) PNGARG((png_structp png_ptr, png_FILE_p fp));
  176532. #endif
  176533. /* Replace the (error and abort), and warning functions with user
  176534. * supplied functions. If no messages are to be printed you must still
  176535. * write and use replacement functions. The replacement error_fn should
  176536. * still do a longjmp to the last setjmp location if you are using this
  176537. * method of error handling. If error_fn or warning_fn is NULL, the
  176538. * default function will be used.
  176539. */
  176540. extern PNG_EXPORT(void,png_set_error_fn) PNGARG((png_structp png_ptr,
  176541. png_voidp error_ptr, png_error_ptr error_fn, png_error_ptr warning_fn));
  176542. /* Return the user pointer associated with the error functions */
  176543. extern PNG_EXPORT(png_voidp,png_get_error_ptr) PNGARG((png_structp png_ptr));
  176544. /* Replace the default data output functions with a user supplied one(s).
  176545. * If buffered output is not used, then output_flush_fn can be set to NULL.
  176546. * If PNG_WRITE_FLUSH_SUPPORTED is not defined at libpng compile time
  176547. * output_flush_fn will be ignored (and thus can be NULL).
  176548. */
  176549. extern PNG_EXPORT(void,png_set_write_fn) PNGARG((png_structp png_ptr,
  176550. png_voidp io_ptr, png_rw_ptr write_data_fn, png_flush_ptr output_flush_fn));
  176551. /* Replace the default data input function with a user supplied one. */
  176552. extern PNG_EXPORT(void,png_set_read_fn) PNGARG((png_structp png_ptr,
  176553. png_voidp io_ptr, png_rw_ptr read_data_fn));
  176554. /* Return the user pointer associated with the I/O functions */
  176555. extern PNG_EXPORT(png_voidp,png_get_io_ptr) PNGARG((png_structp png_ptr));
  176556. extern PNG_EXPORT(void,png_set_read_status_fn) PNGARG((png_structp png_ptr,
  176557. png_read_status_ptr read_row_fn));
  176558. extern PNG_EXPORT(void,png_set_write_status_fn) PNGARG((png_structp png_ptr,
  176559. png_write_status_ptr write_row_fn));
  176560. #ifdef PNG_USER_MEM_SUPPORTED
  176561. /* Replace the default memory allocation functions with user supplied one(s). */
  176562. extern PNG_EXPORT(void,png_set_mem_fn) PNGARG((png_structp png_ptr,
  176563. png_voidp mem_ptr, png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  176564. /* Return the user pointer associated with the memory functions */
  176565. extern PNG_EXPORT(png_voidp,png_get_mem_ptr) PNGARG((png_structp png_ptr));
  176566. #endif
  176567. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  176568. defined(PNG_LEGACY_SUPPORTED)
  176569. extern PNG_EXPORT(void,png_set_read_user_transform_fn) PNGARG((png_structp
  176570. png_ptr, png_user_transform_ptr read_user_transform_fn));
  176571. #endif
  176572. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  176573. defined(PNG_LEGACY_SUPPORTED)
  176574. extern PNG_EXPORT(void,png_set_write_user_transform_fn) PNGARG((png_structp
  176575. png_ptr, png_user_transform_ptr write_user_transform_fn));
  176576. #endif
  176577. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  176578. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  176579. defined(PNG_LEGACY_SUPPORTED)
  176580. extern PNG_EXPORT(void,png_set_user_transform_info) PNGARG((png_structp
  176581. png_ptr, png_voidp user_transform_ptr, int user_transform_depth,
  176582. int user_transform_channels));
  176583. /* Return the user pointer associated with the user transform functions */
  176584. extern PNG_EXPORT(png_voidp,png_get_user_transform_ptr)
  176585. PNGARG((png_structp png_ptr));
  176586. #endif
  176587. #ifdef PNG_USER_CHUNKS_SUPPORTED
  176588. extern PNG_EXPORT(void,png_set_read_user_chunk_fn) PNGARG((png_structp png_ptr,
  176589. png_voidp user_chunk_ptr, png_user_chunk_ptr read_user_chunk_fn));
  176590. extern PNG_EXPORT(png_voidp,png_get_user_chunk_ptr) PNGARG((png_structp
  176591. png_ptr));
  176592. #endif
  176593. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  176594. /* Sets the function callbacks for the push reader, and a pointer to a
  176595. * user-defined structure available to the callback functions.
  176596. */
  176597. extern PNG_EXPORT(void,png_set_progressive_read_fn) PNGARG((png_structp png_ptr,
  176598. png_voidp progressive_ptr,
  176599. png_progressive_info_ptr info_fn, png_progressive_row_ptr row_fn,
  176600. png_progressive_end_ptr end_fn));
  176601. /* returns the user pointer associated with the push read functions */
  176602. extern PNG_EXPORT(png_voidp,png_get_progressive_ptr)
  176603. PNGARG((png_structp png_ptr));
  176604. /* function to be called when data becomes available */
  176605. extern PNG_EXPORT(void,png_process_data) PNGARG((png_structp png_ptr,
  176606. png_infop info_ptr, png_bytep buffer, png_size_t buffer_size));
  176607. /* function that combines rows. Not very much different than the
  176608. * png_combine_row() call. Is this even used?????
  176609. */
  176610. extern PNG_EXPORT(void,png_progressive_combine_row) PNGARG((png_structp png_ptr,
  176611. png_bytep old_row, png_bytep new_row));
  176612. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  176613. extern PNG_EXPORT(png_voidp,png_malloc) PNGARG((png_structp png_ptr,
  176614. png_uint_32 size));
  176615. #if defined(PNG_1_0_X)
  176616. # define png_malloc_warn png_malloc
  176617. #else
  176618. /* Added at libpng version 1.2.4 */
  176619. extern PNG_EXPORT(png_voidp,png_malloc_warn) PNGARG((png_structp png_ptr,
  176620. png_uint_32 size));
  176621. #endif
  176622. /* frees a pointer allocated by png_malloc() */
  176623. extern PNG_EXPORT(void,png_free) PNGARG((png_structp png_ptr, png_voidp ptr));
  176624. #if defined(PNG_1_0_X)
  176625. /* Function to allocate memory for zlib. */
  176626. extern PNG_EXPORT(voidpf,png_zalloc) PNGARG((voidpf png_ptr, uInt items,
  176627. uInt size));
  176628. /* Function to free memory for zlib */
  176629. extern PNG_EXPORT(void,png_zfree) PNGARG((voidpf png_ptr, voidpf ptr));
  176630. #endif
  176631. /* Free data that was allocated internally */
  176632. extern PNG_EXPORT(void,png_free_data) PNGARG((png_structp png_ptr,
  176633. png_infop info_ptr, png_uint_32 free_me, int num));
  176634. #ifdef PNG_FREE_ME_SUPPORTED
  176635. /* Reassign responsibility for freeing existing data, whether allocated
  176636. * by libpng or by the application */
  176637. extern PNG_EXPORT(void,png_data_freer) PNGARG((png_structp png_ptr,
  176638. png_infop info_ptr, int freer, png_uint_32 mask));
  176639. #endif
  176640. /* assignments for png_data_freer */
  176641. #define PNG_DESTROY_WILL_FREE_DATA 1
  176642. #define PNG_SET_WILL_FREE_DATA 1
  176643. #define PNG_USER_WILL_FREE_DATA 2
  176644. /* Flags for png_ptr->free_me and info_ptr->free_me */
  176645. #define PNG_FREE_HIST 0x0008
  176646. #define PNG_FREE_ICCP 0x0010
  176647. #define PNG_FREE_SPLT 0x0020
  176648. #define PNG_FREE_ROWS 0x0040
  176649. #define PNG_FREE_PCAL 0x0080
  176650. #define PNG_FREE_SCAL 0x0100
  176651. #define PNG_FREE_UNKN 0x0200
  176652. #define PNG_FREE_LIST 0x0400
  176653. #define PNG_FREE_PLTE 0x1000
  176654. #define PNG_FREE_TRNS 0x2000
  176655. #define PNG_FREE_TEXT 0x4000
  176656. #define PNG_FREE_ALL 0x7fff
  176657. #define PNG_FREE_MUL 0x4220 /* PNG_FREE_SPLT|PNG_FREE_TEXT|PNG_FREE_UNKN */
  176658. #ifdef PNG_USER_MEM_SUPPORTED
  176659. extern PNG_EXPORT(png_voidp,png_malloc_default) PNGARG((png_structp png_ptr,
  176660. png_uint_32 size));
  176661. extern PNG_EXPORT(void,png_free_default) PNGARG((png_structp png_ptr,
  176662. png_voidp ptr));
  176663. #endif
  176664. extern PNG_EXPORT(png_voidp,png_memcpy_check) PNGARG((png_structp png_ptr,
  176665. png_voidp s1, png_voidp s2, png_uint_32 size));
  176666. extern PNG_EXPORT(png_voidp,png_memset_check) PNGARG((png_structp png_ptr,
  176667. png_voidp s1, int value, png_uint_32 size));
  176668. #if defined(USE_FAR_KEYWORD) /* memory model conversion function */
  176669. extern void *png_far_to_near PNGARG((png_structp png_ptr,png_voidp ptr,
  176670. int check));
  176671. #endif /* USE_FAR_KEYWORD */
  176672. #ifndef PNG_NO_ERROR_TEXT
  176673. /* Fatal error in PNG image of libpng - can't continue */
  176674. extern PNG_EXPORT(void,png_error) PNGARG((png_structp png_ptr,
  176675. png_const_charp error_message));
  176676. /* The same, but the chunk name is prepended to the error string. */
  176677. extern PNG_EXPORT(void,png_chunk_error) PNGARG((png_structp png_ptr,
  176678. png_const_charp error_message));
  176679. #else
  176680. /* Fatal error in PNG image of libpng - can't continue */
  176681. extern PNG_EXPORT(void,png_err) PNGARG((png_structp png_ptr));
  176682. #endif
  176683. #ifndef PNG_NO_WARNINGS
  176684. /* Non-fatal error in libpng. Can continue, but may have a problem. */
  176685. extern PNG_EXPORT(void,png_warning) PNGARG((png_structp png_ptr,
  176686. png_const_charp warning_message));
  176687. #ifdef PNG_READ_SUPPORTED
  176688. /* Non-fatal error in libpng, chunk name is prepended to message. */
  176689. extern PNG_EXPORT(void,png_chunk_warning) PNGARG((png_structp png_ptr,
  176690. png_const_charp warning_message));
  176691. #endif /* PNG_READ_SUPPORTED */
  176692. #endif /* PNG_NO_WARNINGS */
  176693. /* The png_set_<chunk> functions are for storing values in the png_info_struct.
  176694. * Similarly, the png_get_<chunk> calls are used to read values from the
  176695. * png_info_struct, either storing the parameters in the passed variables, or
  176696. * setting pointers into the png_info_struct where the data is stored. The
  176697. * png_get_<chunk> functions return a non-zero value if the data was available
  176698. * in info_ptr, or return zero and do not change any of the parameters if the
  176699. * data was not available.
  176700. *
  176701. * These functions should be used instead of directly accessing png_info
  176702. * to avoid problems with future changes in the size and internal layout of
  176703. * png_info_struct.
  176704. */
  176705. /* Returns "flag" if chunk data is valid in info_ptr. */
  176706. extern PNG_EXPORT(png_uint_32,png_get_valid) PNGARG((png_structp png_ptr,
  176707. png_infop info_ptr, png_uint_32 flag));
  176708. /* Returns number of bytes needed to hold a transformed row. */
  176709. extern PNG_EXPORT(png_uint_32,png_get_rowbytes) PNGARG((png_structp png_ptr,
  176710. png_infop info_ptr));
  176711. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  176712. /* Returns row_pointers, which is an array of pointers to scanlines that was
  176713. returned from png_read_png(). */
  176714. extern PNG_EXPORT(png_bytepp,png_get_rows) PNGARG((png_structp png_ptr,
  176715. png_infop info_ptr));
  176716. /* Set row_pointers, which is an array of pointers to scanlines for use
  176717. by png_write_png(). */
  176718. extern PNG_EXPORT(void,png_set_rows) PNGARG((png_structp png_ptr,
  176719. png_infop info_ptr, png_bytepp row_pointers));
  176720. #endif
  176721. /* Returns number of color channels in image. */
  176722. extern PNG_EXPORT(png_byte,png_get_channels) PNGARG((png_structp png_ptr,
  176723. png_infop info_ptr));
  176724. #ifdef PNG_EASY_ACCESS_SUPPORTED
  176725. /* Returns image width in pixels. */
  176726. extern PNG_EXPORT(png_uint_32, png_get_image_width) PNGARG((png_structp
  176727. png_ptr, png_infop info_ptr));
  176728. /* Returns image height in pixels. */
  176729. extern PNG_EXPORT(png_uint_32, png_get_image_height) PNGARG((png_structp
  176730. png_ptr, png_infop info_ptr));
  176731. /* Returns image bit_depth. */
  176732. extern PNG_EXPORT(png_byte, png_get_bit_depth) PNGARG((png_structp
  176733. png_ptr, png_infop info_ptr));
  176734. /* Returns image color_type. */
  176735. extern PNG_EXPORT(png_byte, png_get_color_type) PNGARG((png_structp
  176736. png_ptr, png_infop info_ptr));
  176737. /* Returns image filter_type. */
  176738. extern PNG_EXPORT(png_byte, png_get_filter_type) PNGARG((png_structp
  176739. png_ptr, png_infop info_ptr));
  176740. /* Returns image interlace_type. */
  176741. extern PNG_EXPORT(png_byte, png_get_interlace_type) PNGARG((png_structp
  176742. png_ptr, png_infop info_ptr));
  176743. /* Returns image compression_type. */
  176744. extern PNG_EXPORT(png_byte, png_get_compression_type) PNGARG((png_structp
  176745. png_ptr, png_infop info_ptr));
  176746. /* Returns image resolution in pixels per meter, from pHYs chunk data. */
  176747. extern PNG_EXPORT(png_uint_32, png_get_pixels_per_meter) PNGARG((png_structp
  176748. png_ptr, png_infop info_ptr));
  176749. extern PNG_EXPORT(png_uint_32, png_get_x_pixels_per_meter) PNGARG((png_structp
  176750. png_ptr, png_infop info_ptr));
  176751. extern PNG_EXPORT(png_uint_32, png_get_y_pixels_per_meter) PNGARG((png_structp
  176752. png_ptr, png_infop info_ptr));
  176753. /* Returns pixel aspect ratio, computed from pHYs chunk data. */
  176754. #ifdef PNG_FLOATING_POINT_SUPPORTED
  176755. extern PNG_EXPORT(float, png_get_pixel_aspect_ratio) PNGARG((png_structp
  176756. png_ptr, png_infop info_ptr));
  176757. #endif
  176758. /* Returns image x, y offset in pixels or microns, from oFFs chunk data. */
  176759. extern PNG_EXPORT(png_int_32, png_get_x_offset_pixels) PNGARG((png_structp
  176760. png_ptr, png_infop info_ptr));
  176761. extern PNG_EXPORT(png_int_32, png_get_y_offset_pixels) PNGARG((png_structp
  176762. png_ptr, png_infop info_ptr));
  176763. extern PNG_EXPORT(png_int_32, png_get_x_offset_microns) PNGARG((png_structp
  176764. png_ptr, png_infop info_ptr));
  176765. extern PNG_EXPORT(png_int_32, png_get_y_offset_microns) PNGARG((png_structp
  176766. png_ptr, png_infop info_ptr));
  176767. #endif /* PNG_EASY_ACCESS_SUPPORTED */
  176768. /* Returns pointer to signature string read from PNG header */
  176769. extern PNG_EXPORT(png_bytep,png_get_signature) PNGARG((png_structp png_ptr,
  176770. png_infop info_ptr));
  176771. #if defined(PNG_bKGD_SUPPORTED)
  176772. extern PNG_EXPORT(png_uint_32,png_get_bKGD) PNGARG((png_structp png_ptr,
  176773. png_infop info_ptr, png_color_16p *background));
  176774. #endif
  176775. #if defined(PNG_bKGD_SUPPORTED)
  176776. extern PNG_EXPORT(void,png_set_bKGD) PNGARG((png_structp png_ptr,
  176777. png_infop info_ptr, png_color_16p background));
  176778. #endif
  176779. #if defined(PNG_cHRM_SUPPORTED)
  176780. #ifdef PNG_FLOATING_POINT_SUPPORTED
  176781. extern PNG_EXPORT(png_uint_32,png_get_cHRM) PNGARG((png_structp png_ptr,
  176782. png_infop info_ptr, double *white_x, double *white_y, double *red_x,
  176783. double *red_y, double *green_x, double *green_y, double *blue_x,
  176784. double *blue_y));
  176785. #endif
  176786. #ifdef PNG_FIXED_POINT_SUPPORTED
  176787. extern PNG_EXPORT(png_uint_32,png_get_cHRM_fixed) PNGARG((png_structp png_ptr,
  176788. png_infop info_ptr, png_fixed_point *int_white_x, png_fixed_point
  176789. *int_white_y, png_fixed_point *int_red_x, png_fixed_point *int_red_y,
  176790. png_fixed_point *int_green_x, png_fixed_point *int_green_y, png_fixed_point
  176791. *int_blue_x, png_fixed_point *int_blue_y));
  176792. #endif
  176793. #endif
  176794. #if defined(PNG_cHRM_SUPPORTED)
  176795. #ifdef PNG_FLOATING_POINT_SUPPORTED
  176796. extern PNG_EXPORT(void,png_set_cHRM) PNGARG((png_structp png_ptr,
  176797. png_infop info_ptr, double white_x, double white_y, double red_x,
  176798. double red_y, double green_x, double green_y, double blue_x, double blue_y));
  176799. #endif
  176800. #ifdef PNG_FIXED_POINT_SUPPORTED
  176801. extern PNG_EXPORT(void,png_set_cHRM_fixed) PNGARG((png_structp png_ptr,
  176802. png_infop info_ptr, png_fixed_point int_white_x, png_fixed_point int_white_y,
  176803. png_fixed_point int_red_x, png_fixed_point int_red_y, png_fixed_point
  176804. int_green_x, png_fixed_point int_green_y, png_fixed_point int_blue_x,
  176805. png_fixed_point int_blue_y));
  176806. #endif
  176807. #endif
  176808. #if defined(PNG_gAMA_SUPPORTED)
  176809. #ifdef PNG_FLOATING_POINT_SUPPORTED
  176810. extern PNG_EXPORT(png_uint_32,png_get_gAMA) PNGARG((png_structp png_ptr,
  176811. png_infop info_ptr, double *file_gamma));
  176812. #endif
  176813. extern PNG_EXPORT(png_uint_32,png_get_gAMA_fixed) PNGARG((png_structp png_ptr,
  176814. png_infop info_ptr, png_fixed_point *int_file_gamma));
  176815. #endif
  176816. #if defined(PNG_gAMA_SUPPORTED)
  176817. #ifdef PNG_FLOATING_POINT_SUPPORTED
  176818. extern PNG_EXPORT(void,png_set_gAMA) PNGARG((png_structp png_ptr,
  176819. png_infop info_ptr, double file_gamma));
  176820. #endif
  176821. extern PNG_EXPORT(void,png_set_gAMA_fixed) PNGARG((png_structp png_ptr,
  176822. png_infop info_ptr, png_fixed_point int_file_gamma));
  176823. #endif
  176824. #if defined(PNG_hIST_SUPPORTED)
  176825. extern PNG_EXPORT(png_uint_32,png_get_hIST) PNGARG((png_structp png_ptr,
  176826. png_infop info_ptr, png_uint_16p *hist));
  176827. #endif
  176828. #if defined(PNG_hIST_SUPPORTED)
  176829. extern PNG_EXPORT(void,png_set_hIST) PNGARG((png_structp png_ptr,
  176830. png_infop info_ptr, png_uint_16p hist));
  176831. #endif
  176832. extern PNG_EXPORT(png_uint_32,png_get_IHDR) PNGARG((png_structp png_ptr,
  176833. png_infop info_ptr, png_uint_32 *width, png_uint_32 *height,
  176834. int *bit_depth, int *color_type, int *interlace_method,
  176835. int *compression_method, int *filter_method));
  176836. extern PNG_EXPORT(void,png_set_IHDR) PNGARG((png_structp png_ptr,
  176837. png_infop info_ptr, png_uint_32 width, png_uint_32 height, int bit_depth,
  176838. int color_type, int interlace_method, int compression_method,
  176839. int filter_method));
  176840. #if defined(PNG_oFFs_SUPPORTED)
  176841. extern PNG_EXPORT(png_uint_32,png_get_oFFs) PNGARG((png_structp png_ptr,
  176842. png_infop info_ptr, png_int_32 *offset_x, png_int_32 *offset_y,
  176843. int *unit_type));
  176844. #endif
  176845. #if defined(PNG_oFFs_SUPPORTED)
  176846. extern PNG_EXPORT(void,png_set_oFFs) PNGARG((png_structp png_ptr,
  176847. png_infop info_ptr, png_int_32 offset_x, png_int_32 offset_y,
  176848. int unit_type));
  176849. #endif
  176850. #if defined(PNG_pCAL_SUPPORTED)
  176851. extern PNG_EXPORT(png_uint_32,png_get_pCAL) PNGARG((png_structp png_ptr,
  176852. png_infop info_ptr, png_charp *purpose, png_int_32 *X0, png_int_32 *X1,
  176853. int *type, int *nparams, png_charp *units, png_charpp *params));
  176854. #endif
  176855. #if defined(PNG_pCAL_SUPPORTED)
  176856. extern PNG_EXPORT(void,png_set_pCAL) PNGARG((png_structp png_ptr,
  176857. png_infop info_ptr, png_charp purpose, png_int_32 X0, png_int_32 X1,
  176858. int type, int nparams, png_charp units, png_charpp params));
  176859. #endif
  176860. #if defined(PNG_pHYs_SUPPORTED)
  176861. extern PNG_EXPORT(png_uint_32,png_get_pHYs) PNGARG((png_structp png_ptr,
  176862. png_infop info_ptr, png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type));
  176863. #endif
  176864. #if defined(PNG_pHYs_SUPPORTED)
  176865. extern PNG_EXPORT(void,png_set_pHYs) PNGARG((png_structp png_ptr,
  176866. png_infop info_ptr, png_uint_32 res_x, png_uint_32 res_y, int unit_type));
  176867. #endif
  176868. extern PNG_EXPORT(png_uint_32,png_get_PLTE) PNGARG((png_structp png_ptr,
  176869. png_infop info_ptr, png_colorp *palette, int *num_palette));
  176870. extern PNG_EXPORT(void,png_set_PLTE) PNGARG((png_structp png_ptr,
  176871. png_infop info_ptr, png_colorp palette, int num_palette));
  176872. #if defined(PNG_sBIT_SUPPORTED)
  176873. extern PNG_EXPORT(png_uint_32,png_get_sBIT) PNGARG((png_structp png_ptr,
  176874. png_infop info_ptr, png_color_8p *sig_bit));
  176875. #endif
  176876. #if defined(PNG_sBIT_SUPPORTED)
  176877. extern PNG_EXPORT(void,png_set_sBIT) PNGARG((png_structp png_ptr,
  176878. png_infop info_ptr, png_color_8p sig_bit));
  176879. #endif
  176880. #if defined(PNG_sRGB_SUPPORTED)
  176881. extern PNG_EXPORT(png_uint_32,png_get_sRGB) PNGARG((png_structp png_ptr,
  176882. png_infop info_ptr, int *intent));
  176883. #endif
  176884. #if defined(PNG_sRGB_SUPPORTED)
  176885. extern PNG_EXPORT(void,png_set_sRGB) PNGARG((png_structp png_ptr,
  176886. png_infop info_ptr, int intent));
  176887. extern PNG_EXPORT(void,png_set_sRGB_gAMA_and_cHRM) PNGARG((png_structp png_ptr,
  176888. png_infop info_ptr, int intent));
  176889. #endif
  176890. #if defined(PNG_iCCP_SUPPORTED)
  176891. extern PNG_EXPORT(png_uint_32,png_get_iCCP) PNGARG((png_structp png_ptr,
  176892. png_infop info_ptr, png_charpp name, int *compression_type,
  176893. png_charpp profile, png_uint_32 *proflen));
  176894. /* Note to maintainer: profile should be png_bytepp */
  176895. #endif
  176896. #if defined(PNG_iCCP_SUPPORTED)
  176897. extern PNG_EXPORT(void,png_set_iCCP) PNGARG((png_structp png_ptr,
  176898. png_infop info_ptr, png_charp name, int compression_type,
  176899. png_charp profile, png_uint_32 proflen));
  176900. /* Note to maintainer: profile should be png_bytep */
  176901. #endif
  176902. #if defined(PNG_sPLT_SUPPORTED)
  176903. extern PNG_EXPORT(png_uint_32,png_get_sPLT) PNGARG((png_structp png_ptr,
  176904. png_infop info_ptr, png_sPLT_tpp entries));
  176905. #endif
  176906. #if defined(PNG_sPLT_SUPPORTED)
  176907. extern PNG_EXPORT(void,png_set_sPLT) PNGARG((png_structp png_ptr,
  176908. png_infop info_ptr, png_sPLT_tp entries, int nentries));
  176909. #endif
  176910. #if defined(PNG_TEXT_SUPPORTED)
  176911. /* png_get_text also returns the number of text chunks in *num_text */
  176912. extern PNG_EXPORT(png_uint_32,png_get_text) PNGARG((png_structp png_ptr,
  176913. png_infop info_ptr, png_textp *text_ptr, int *num_text));
  176914. #endif
  176915. /*
  176916. * Note while png_set_text() will accept a structure whose text,
  176917. * language, and translated keywords are NULL pointers, the structure
  176918. * returned by png_get_text will always contain regular
  176919. * zero-terminated C strings. They might be empty strings but
  176920. * they will never be NULL pointers.
  176921. */
  176922. #if defined(PNG_TEXT_SUPPORTED)
  176923. extern PNG_EXPORT(void,png_set_text) PNGARG((png_structp png_ptr,
  176924. png_infop info_ptr, png_textp text_ptr, int num_text));
  176925. #endif
  176926. #if defined(PNG_tIME_SUPPORTED)
  176927. extern PNG_EXPORT(png_uint_32,png_get_tIME) PNGARG((png_structp png_ptr,
  176928. png_infop info_ptr, png_timep *mod_time));
  176929. #endif
  176930. #if defined(PNG_tIME_SUPPORTED)
  176931. extern PNG_EXPORT(void,png_set_tIME) PNGARG((png_structp png_ptr,
  176932. png_infop info_ptr, png_timep mod_time));
  176933. #endif
  176934. #if defined(PNG_tRNS_SUPPORTED)
  176935. extern PNG_EXPORT(png_uint_32,png_get_tRNS) PNGARG((png_structp png_ptr,
  176936. png_infop info_ptr, png_bytep *trans, int *num_trans,
  176937. png_color_16p *trans_values));
  176938. #endif
  176939. #if defined(PNG_tRNS_SUPPORTED)
  176940. extern PNG_EXPORT(void,png_set_tRNS) PNGARG((png_structp png_ptr,
  176941. png_infop info_ptr, png_bytep trans, int num_trans,
  176942. png_color_16p trans_values));
  176943. #endif
  176944. #if defined(PNG_tRNS_SUPPORTED)
  176945. #endif
  176946. #if defined(PNG_sCAL_SUPPORTED)
  176947. #ifdef PNG_FLOATING_POINT_SUPPORTED
  176948. extern PNG_EXPORT(png_uint_32,png_get_sCAL) PNGARG((png_structp png_ptr,
  176949. png_infop info_ptr, int *unit, double *width, double *height));
  176950. #else
  176951. #ifdef PNG_FIXED_POINT_SUPPORTED
  176952. extern PNG_EXPORT(png_uint_32,png_get_sCAL_s) PNGARG((png_structp png_ptr,
  176953. png_infop info_ptr, int *unit, png_charpp swidth, png_charpp sheight));
  176954. #endif
  176955. #endif
  176956. #endif /* PNG_sCAL_SUPPORTED */
  176957. #if defined(PNG_sCAL_SUPPORTED)
  176958. #ifdef PNG_FLOATING_POINT_SUPPORTED
  176959. extern PNG_EXPORT(void,png_set_sCAL) PNGARG((png_structp png_ptr,
  176960. png_infop info_ptr, int unit, double width, double height));
  176961. #else
  176962. #ifdef PNG_FIXED_POINT_SUPPORTED
  176963. extern PNG_EXPORT(void,png_set_sCAL_s) PNGARG((png_structp png_ptr,
  176964. png_infop info_ptr, int unit, png_charp swidth, png_charp sheight));
  176965. #endif
  176966. #endif
  176967. #endif /* PNG_sCAL_SUPPORTED || PNG_WRITE_sCAL_SUPPORTED */
  176968. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  176969. /* provide a list of chunks and how they are to be handled, if the built-in
  176970. handling or default unknown chunk handling is not desired. Any chunks not
  176971. listed will be handled in the default manner. The IHDR and IEND chunks
  176972. must not be listed.
  176973. keep = 0: follow default behaviour
  176974. = 1: do not keep
  176975. = 2: keep only if safe-to-copy
  176976. = 3: keep even if unsafe-to-copy
  176977. */
  176978. extern PNG_EXPORT(void, png_set_keep_unknown_chunks) PNGARG((png_structp
  176979. png_ptr, int keep, png_bytep chunk_list, int num_chunks));
  176980. extern PNG_EXPORT(void, png_set_unknown_chunks) PNGARG((png_structp png_ptr,
  176981. png_infop info_ptr, png_unknown_chunkp unknowns, int num_unknowns));
  176982. extern PNG_EXPORT(void, png_set_unknown_chunk_location)
  176983. PNGARG((png_structp png_ptr, png_infop info_ptr, int chunk, int location));
  176984. extern PNG_EXPORT(png_uint_32,png_get_unknown_chunks) PNGARG((png_structp
  176985. png_ptr, png_infop info_ptr, png_unknown_chunkpp entries));
  176986. #endif
  176987. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  176988. PNG_EXPORT(int,png_handle_as_unknown) PNGARG((png_structp png_ptr, png_bytep
  176989. chunk_name));
  176990. #endif
  176991. /* Png_free_data() will turn off the "valid" flag for anything it frees.
  176992. If you need to turn it off for a chunk that your application has freed,
  176993. you can use png_set_invalid(png_ptr, info_ptr, PNG_INFO_CHNK); */
  176994. extern PNG_EXPORT(void, png_set_invalid) PNGARG((png_structp png_ptr,
  176995. png_infop info_ptr, int mask));
  176996. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  176997. /* The "params" pointer is currently not used and is for future expansion. */
  176998. extern PNG_EXPORT(void, png_read_png) PNGARG((png_structp png_ptr,
  176999. png_infop info_ptr,
  177000. int transforms,
  177001. png_voidp params));
  177002. extern PNG_EXPORT(void, png_write_png) PNGARG((png_structp png_ptr,
  177003. png_infop info_ptr,
  177004. int transforms,
  177005. png_voidp params));
  177006. #endif
  177007. /* Define PNG_DEBUG at compile time for debugging information. Higher
  177008. * numbers for PNG_DEBUG mean more debugging information. This has
  177009. * only been added since version 0.95 so it is not implemented throughout
  177010. * libpng yet, but more support will be added as needed.
  177011. */
  177012. #ifdef PNG_DEBUG
  177013. #if (PNG_DEBUG > 0)
  177014. #if !defined(PNG_DEBUG_FILE) && defined(_MSC_VER)
  177015. #include <crtdbg.h>
  177016. #if (PNG_DEBUG > 1)
  177017. #define png_debug(l,m) _RPT0(_CRT_WARN,m)
  177018. #define png_debug1(l,m,p1) _RPT1(_CRT_WARN,m,p1)
  177019. #define png_debug2(l,m,p1,p2) _RPT2(_CRT_WARN,m,p1,p2)
  177020. #endif
  177021. #else /* PNG_DEBUG_FILE || !_MSC_VER */
  177022. #ifndef PNG_DEBUG_FILE
  177023. #define PNG_DEBUG_FILE stderr
  177024. #endif /* PNG_DEBUG_FILE */
  177025. #if (PNG_DEBUG > 1)
  177026. #define png_debug(l,m) \
  177027. { \
  177028. int num_tabs=l; \
  177029. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  177030. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":"")))); \
  177031. }
  177032. #define png_debug1(l,m,p1) \
  177033. { \
  177034. int num_tabs=l; \
  177035. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  177036. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":""))),p1); \
  177037. }
  177038. #define png_debug2(l,m,p1,p2) \
  177039. { \
  177040. int num_tabs=l; \
  177041. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  177042. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":""))),p1,p2); \
  177043. }
  177044. #endif /* (PNG_DEBUG > 1) */
  177045. #endif /* _MSC_VER */
  177046. #endif /* (PNG_DEBUG > 0) */
  177047. #endif /* PNG_DEBUG */
  177048. #ifndef png_debug
  177049. #define png_debug(l, m)
  177050. #endif
  177051. #ifndef png_debug1
  177052. #define png_debug1(l, m, p1)
  177053. #endif
  177054. #ifndef png_debug2
  177055. #define png_debug2(l, m, p1, p2)
  177056. #endif
  177057. extern PNG_EXPORT(png_charp,png_get_copyright) PNGARG((png_structp png_ptr));
  177058. extern PNG_EXPORT(png_charp,png_get_header_ver) PNGARG((png_structp png_ptr));
  177059. extern PNG_EXPORT(png_charp,png_get_header_version) PNGARG((png_structp png_ptr));
  177060. extern PNG_EXPORT(png_charp,png_get_libpng_ver) PNGARG((png_structp png_ptr));
  177061. #ifdef PNG_MNG_FEATURES_SUPPORTED
  177062. extern PNG_EXPORT(png_uint_32,png_permit_mng_features) PNGARG((png_structp
  177063. png_ptr, png_uint_32 mng_features_permitted));
  177064. #endif
  177065. /* For use in png_set_keep_unknown, added to version 1.2.6 */
  177066. #define PNG_HANDLE_CHUNK_AS_DEFAULT 0
  177067. #define PNG_HANDLE_CHUNK_NEVER 1
  177068. #define PNG_HANDLE_CHUNK_IF_SAFE 2
  177069. #define PNG_HANDLE_CHUNK_ALWAYS 3
  177070. /* Added to version 1.2.0 */
  177071. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  177072. #if defined(PNG_MMX_CODE_SUPPORTED)
  177073. #define PNG_ASM_FLAG_MMX_SUPPORT_COMPILED 0x01 /* not user-settable */
  177074. #define PNG_ASM_FLAG_MMX_SUPPORT_IN_CPU 0x02 /* not user-settable */
  177075. #define PNG_ASM_FLAG_MMX_READ_COMBINE_ROW 0x04
  177076. #define PNG_ASM_FLAG_MMX_READ_INTERLACE 0x08
  177077. #define PNG_ASM_FLAG_MMX_READ_FILTER_SUB 0x10
  177078. #define PNG_ASM_FLAG_MMX_READ_FILTER_UP 0x20
  177079. #define PNG_ASM_FLAG_MMX_READ_FILTER_AVG 0x40
  177080. #define PNG_ASM_FLAG_MMX_READ_FILTER_PAETH 0x80
  177081. #define PNG_ASM_FLAGS_INITIALIZED 0x80000000 /* not user-settable */
  177082. #define PNG_MMX_READ_FLAGS ( PNG_ASM_FLAG_MMX_READ_COMBINE_ROW \
  177083. | PNG_ASM_FLAG_MMX_READ_INTERLACE \
  177084. | PNG_ASM_FLAG_MMX_READ_FILTER_SUB \
  177085. | PNG_ASM_FLAG_MMX_READ_FILTER_UP \
  177086. | PNG_ASM_FLAG_MMX_READ_FILTER_AVG \
  177087. | PNG_ASM_FLAG_MMX_READ_FILTER_PAETH )
  177088. #define PNG_MMX_WRITE_FLAGS ( 0 )
  177089. #define PNG_MMX_FLAGS ( PNG_ASM_FLAG_MMX_SUPPORT_COMPILED \
  177090. | PNG_ASM_FLAG_MMX_SUPPORT_IN_CPU \
  177091. | PNG_MMX_READ_FLAGS \
  177092. | PNG_MMX_WRITE_FLAGS )
  177093. #define PNG_SELECT_READ 1
  177094. #define PNG_SELECT_WRITE 2
  177095. #endif /* PNG_MMX_CODE_SUPPORTED */
  177096. #if !defined(PNG_1_0_X)
  177097. /* pngget.c */
  177098. extern PNG_EXPORT(png_uint_32,png_get_mmx_flagmask)
  177099. PNGARG((int flag_select, int *compilerID));
  177100. /* pngget.c */
  177101. extern PNG_EXPORT(png_uint_32,png_get_asm_flagmask)
  177102. PNGARG((int flag_select));
  177103. /* pngget.c */
  177104. extern PNG_EXPORT(png_uint_32,png_get_asm_flags)
  177105. PNGARG((png_structp png_ptr));
  177106. /* pngget.c */
  177107. extern PNG_EXPORT(png_byte,png_get_mmx_bitdepth_threshold)
  177108. PNGARG((png_structp png_ptr));
  177109. /* pngget.c */
  177110. extern PNG_EXPORT(png_uint_32,png_get_mmx_rowbytes_threshold)
  177111. PNGARG((png_structp png_ptr));
  177112. /* pngset.c */
  177113. extern PNG_EXPORT(void,png_set_asm_flags)
  177114. PNGARG((png_structp png_ptr, png_uint_32 asm_flags));
  177115. /* pngset.c */
  177116. extern PNG_EXPORT(void,png_set_mmx_thresholds)
  177117. PNGARG((png_structp png_ptr, png_byte mmx_bitdepth_threshold,
  177118. png_uint_32 mmx_rowbytes_threshold));
  177119. #endif /* PNG_1_0_X */
  177120. #if !defined(PNG_1_0_X)
  177121. /* png.c, pnggccrd.c, or pngvcrd.c */
  177122. extern PNG_EXPORT(int,png_mmx_support) PNGARG((void));
  177123. #endif /* PNG_ASSEMBLER_CODE_SUPPORTED */
  177124. /* Strip the prepended error numbers ("#nnn ") from error and warning
  177125. * messages before passing them to the error or warning handler. */
  177126. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  177127. extern PNG_EXPORT(void,png_set_strip_error_numbers) PNGARG((png_structp
  177128. png_ptr, png_uint_32 strip_mode));
  177129. #endif
  177130. #endif /* PNG_1_0_X */
  177131. /* Added at libpng-1.2.6 */
  177132. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  177133. extern PNG_EXPORT(void,png_set_user_limits) PNGARG((png_structp
  177134. png_ptr, png_uint_32 user_width_max, png_uint_32 user_height_max));
  177135. extern PNG_EXPORT(png_uint_32,png_get_user_width_max) PNGARG((png_structp
  177136. png_ptr));
  177137. extern PNG_EXPORT(png_uint_32,png_get_user_height_max) PNGARG((png_structp
  177138. png_ptr));
  177139. #endif
  177140. /* Maintainer: Put new public prototypes here ^, in libpng.3, and project defs */
  177141. #ifdef PNG_READ_COMPOSITE_NODIV_SUPPORTED
  177142. /* With these routines we avoid an integer divide, which will be slower on
  177143. * most machines. However, it does take more operations than the corresponding
  177144. * divide method, so it may be slower on a few RISC systems. There are two
  177145. * shifts (by 8 or 16 bits) and an addition, versus a single integer divide.
  177146. *
  177147. * Note that the rounding factors are NOT supposed to be the same! 128 and
  177148. * 32768 are correct for the NODIV code; 127 and 32767 are correct for the
  177149. * standard method.
  177150. *
  177151. * [Optimized code by Greg Roelofs and Mark Adler...blame us for bugs. :-) ]
  177152. */
  177153. /* fg and bg should be in `gamma 1.0' space; alpha is the opacity */
  177154. # define png_composite(composite, fg, alpha, bg) \
  177155. { png_uint_16 temp = (png_uint_16)((png_uint_16)(fg) * (png_uint_16)(alpha) \
  177156. + (png_uint_16)(bg)*(png_uint_16)(255 - \
  177157. (png_uint_16)(alpha)) + (png_uint_16)128); \
  177158. (composite) = (png_byte)((temp + (temp >> 8)) >> 8); }
  177159. # define png_composite_16(composite, fg, alpha, bg) \
  177160. { png_uint_32 temp = (png_uint_32)((png_uint_32)(fg) * (png_uint_32)(alpha) \
  177161. + (png_uint_32)(bg)*(png_uint_32)(65535L - \
  177162. (png_uint_32)(alpha)) + (png_uint_32)32768L); \
  177163. (composite) = (png_uint_16)((temp + (temp >> 16)) >> 16); }
  177164. #else /* standard method using integer division */
  177165. # define png_composite(composite, fg, alpha, bg) \
  177166. (composite) = (png_byte)(((png_uint_16)(fg) * (png_uint_16)(alpha) + \
  177167. (png_uint_16)(bg) * (png_uint_16)(255 - (png_uint_16)(alpha)) + \
  177168. (png_uint_16)127) / 255)
  177169. # define png_composite_16(composite, fg, alpha, bg) \
  177170. (composite) = (png_uint_16)(((png_uint_32)(fg) * (png_uint_32)(alpha) + \
  177171. (png_uint_32)(bg)*(png_uint_32)(65535L - (png_uint_32)(alpha)) + \
  177172. (png_uint_32)32767) / (png_uint_32)65535L)
  177173. #endif /* PNG_READ_COMPOSITE_NODIV_SUPPORTED */
  177174. /* Inline macros to do direct reads of bytes from the input buffer. These
  177175. * require that you are using an architecture that uses PNG byte ordering
  177176. * (MSB first) and supports unaligned data storage. I think that PowerPC
  177177. * in big-endian mode and 680x0 are the only ones that will support this.
  177178. * The x86 line of processors definitely do not. The png_get_int_32()
  177179. * routine also assumes we are using two's complement format for negative
  177180. * values, which is almost certainly true.
  177181. */
  177182. #if defined(PNG_READ_BIG_ENDIAN_SUPPORTED)
  177183. # define png_get_uint_32(buf) ( *((png_uint_32p) (buf)))
  177184. # define png_get_uint_16(buf) ( *((png_uint_16p) (buf)))
  177185. # define png_get_int_32(buf) ( *((png_int_32p) (buf)))
  177186. #else
  177187. extern PNG_EXPORT(png_uint_32,png_get_uint_32) PNGARG((png_bytep buf));
  177188. extern PNG_EXPORT(png_uint_16,png_get_uint_16) PNGARG((png_bytep buf));
  177189. extern PNG_EXPORT(png_int_32,png_get_int_32) PNGARG((png_bytep buf));
  177190. #endif /* !PNG_READ_BIG_ENDIAN_SUPPORTED */
  177191. extern PNG_EXPORT(png_uint_32,png_get_uint_31)
  177192. PNGARG((png_structp png_ptr, png_bytep buf));
  177193. /* No png_get_int_16 -- may be added if there's a real need for it. */
  177194. /* Place a 32-bit number into a buffer in PNG byte order (big-endian).
  177195. */
  177196. extern PNG_EXPORT(void,png_save_uint_32)
  177197. PNGARG((png_bytep buf, png_uint_32 i));
  177198. extern PNG_EXPORT(void,png_save_int_32)
  177199. PNGARG((png_bytep buf, png_int_32 i));
  177200. /* Place a 16-bit number into a buffer in PNG byte order.
  177201. * The parameter is declared unsigned int, not png_uint_16,
  177202. * just to avoid potential problems on pre-ANSI C compilers.
  177203. */
  177204. extern PNG_EXPORT(void,png_save_uint_16)
  177205. PNGARG((png_bytep buf, unsigned int i));
  177206. /* No png_save_int_16 -- may be added if there's a real need for it. */
  177207. /* ************************************************************************* */
  177208. /* These next functions are used internally in the code. They generally
  177209. * shouldn't be used unless you are writing code to add or replace some
  177210. * functionality in libpng. More information about most functions can
  177211. * be found in the files where the functions are located.
  177212. */
  177213. /* Various modes of operation, that are visible to applications because
  177214. * they are used for unknown chunk location.
  177215. */
  177216. #define PNG_HAVE_IHDR 0x01
  177217. #define PNG_HAVE_PLTE 0x02
  177218. #define PNG_HAVE_IDAT 0x04
  177219. #define PNG_AFTER_IDAT 0x08 /* Have complete zlib datastream */
  177220. #define PNG_HAVE_IEND 0x10
  177221. #if defined(PNG_INTERNAL)
  177222. /* More modes of operation. Note that after an init, mode is set to
  177223. * zero automatically when the structure is created.
  177224. */
  177225. #define PNG_HAVE_gAMA 0x20
  177226. #define PNG_HAVE_cHRM 0x40
  177227. #define PNG_HAVE_sRGB 0x80
  177228. #define PNG_HAVE_CHUNK_HEADER 0x100
  177229. #define PNG_WROTE_tIME 0x200
  177230. #define PNG_WROTE_INFO_BEFORE_PLTE 0x400
  177231. #define PNG_BACKGROUND_IS_GRAY 0x800
  177232. #define PNG_HAVE_PNG_SIGNATURE 0x1000
  177233. #define PNG_HAVE_CHUNK_AFTER_IDAT 0x2000 /* Have another chunk after IDAT */
  177234. /* flags for the transformations the PNG library does on the image data */
  177235. #define PNG_BGR 0x0001
  177236. #define PNG_INTERLACE 0x0002
  177237. #define PNG_PACK 0x0004
  177238. #define PNG_SHIFT 0x0008
  177239. #define PNG_SWAP_BYTES 0x0010
  177240. #define PNG_INVERT_MONO 0x0020
  177241. #define PNG_DITHER 0x0040
  177242. #define PNG_BACKGROUND 0x0080
  177243. #define PNG_BACKGROUND_EXPAND 0x0100
  177244. /* 0x0200 unused */
  177245. #define PNG_16_TO_8 0x0400
  177246. #define PNG_RGBA 0x0800
  177247. #define PNG_EXPAND 0x1000
  177248. #define PNG_GAMMA 0x2000
  177249. #define PNG_GRAY_TO_RGB 0x4000
  177250. #define PNG_FILLER 0x8000L
  177251. #define PNG_PACKSWAP 0x10000L
  177252. #define PNG_SWAP_ALPHA 0x20000L
  177253. #define PNG_STRIP_ALPHA 0x40000L
  177254. #define PNG_INVERT_ALPHA 0x80000L
  177255. #define PNG_USER_TRANSFORM 0x100000L
  177256. #define PNG_RGB_TO_GRAY_ERR 0x200000L
  177257. #define PNG_RGB_TO_GRAY_WARN 0x400000L
  177258. #define PNG_RGB_TO_GRAY 0x600000L /* two bits, RGB_TO_GRAY_ERR|WARN */
  177259. /* 0x800000L Unused */
  177260. #define PNG_ADD_ALPHA 0x1000000L /* Added to libpng-1.2.7 */
  177261. #define PNG_EXPAND_tRNS 0x2000000L /* Added to libpng-1.2.9 */
  177262. /* 0x4000000L unused */
  177263. /* 0x8000000L unused */
  177264. /* 0x10000000L unused */
  177265. /* 0x20000000L unused */
  177266. /* 0x40000000L unused */
  177267. /* flags for png_create_struct */
  177268. #define PNG_STRUCT_PNG 0x0001
  177269. #define PNG_STRUCT_INFO 0x0002
  177270. /* Scaling factor for filter heuristic weighting calculations */
  177271. #define PNG_WEIGHT_SHIFT 8
  177272. #define PNG_WEIGHT_FACTOR (1<<(PNG_WEIGHT_SHIFT))
  177273. #define PNG_COST_SHIFT 3
  177274. #define PNG_COST_FACTOR (1<<(PNG_COST_SHIFT))
  177275. /* flags for the png_ptr->flags rather than declaring a byte for each one */
  177276. #define PNG_FLAG_ZLIB_CUSTOM_STRATEGY 0x0001
  177277. #define PNG_FLAG_ZLIB_CUSTOM_LEVEL 0x0002
  177278. #define PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL 0x0004
  177279. #define PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS 0x0008
  177280. #define PNG_FLAG_ZLIB_CUSTOM_METHOD 0x0010
  177281. #define PNG_FLAG_ZLIB_FINISHED 0x0020
  177282. #define PNG_FLAG_ROW_INIT 0x0040
  177283. #define PNG_FLAG_FILLER_AFTER 0x0080
  177284. #define PNG_FLAG_CRC_ANCILLARY_USE 0x0100
  177285. #define PNG_FLAG_CRC_ANCILLARY_NOWARN 0x0200
  177286. #define PNG_FLAG_CRC_CRITICAL_USE 0x0400
  177287. #define PNG_FLAG_CRC_CRITICAL_IGNORE 0x0800
  177288. #define PNG_FLAG_FREE_PLTE 0x1000
  177289. #define PNG_FLAG_FREE_TRNS 0x2000
  177290. #define PNG_FLAG_FREE_HIST 0x4000
  177291. #define PNG_FLAG_KEEP_UNKNOWN_CHUNKS 0x8000L
  177292. #define PNG_FLAG_KEEP_UNSAFE_CHUNKS 0x10000L
  177293. #define PNG_FLAG_LIBRARY_MISMATCH 0x20000L
  177294. #define PNG_FLAG_STRIP_ERROR_NUMBERS 0x40000L
  177295. #define PNG_FLAG_STRIP_ERROR_TEXT 0x80000L
  177296. #define PNG_FLAG_MALLOC_NULL_MEM_OK 0x100000L
  177297. #define PNG_FLAG_ADD_ALPHA 0x200000L /* Added to libpng-1.2.8 */
  177298. #define PNG_FLAG_STRIP_ALPHA 0x400000L /* Added to libpng-1.2.8 */
  177299. /* 0x800000L unused */
  177300. /* 0x1000000L unused */
  177301. /* 0x2000000L unused */
  177302. /* 0x4000000L unused */
  177303. /* 0x8000000L unused */
  177304. /* 0x10000000L unused */
  177305. /* 0x20000000L unused */
  177306. /* 0x40000000L unused */
  177307. #define PNG_FLAG_CRC_ANCILLARY_MASK (PNG_FLAG_CRC_ANCILLARY_USE | \
  177308. PNG_FLAG_CRC_ANCILLARY_NOWARN)
  177309. #define PNG_FLAG_CRC_CRITICAL_MASK (PNG_FLAG_CRC_CRITICAL_USE | \
  177310. PNG_FLAG_CRC_CRITICAL_IGNORE)
  177311. #define PNG_FLAG_CRC_MASK (PNG_FLAG_CRC_ANCILLARY_MASK | \
  177312. PNG_FLAG_CRC_CRITICAL_MASK)
  177313. /* save typing and make code easier to understand */
  177314. #define PNG_COLOR_DIST(c1, c2) (abs((int)((c1).red) - (int)((c2).red)) + \
  177315. abs((int)((c1).green) - (int)((c2).green)) + \
  177316. abs((int)((c1).blue) - (int)((c2).blue)))
  177317. /* Added to libpng-1.2.6 JB */
  177318. #define PNG_ROWBYTES(pixel_bits, width) \
  177319. ((pixel_bits) >= 8 ? \
  177320. ((width) * (((png_uint_32)(pixel_bits)) >> 3)) : \
  177321. (( ((width) * ((png_uint_32)(pixel_bits))) + 7) >> 3) )
  177322. /* PNG_OUT_OF_RANGE returns true if value is outside the range
  177323. ideal-delta..ideal+delta. Each argument is evaluated twice.
  177324. "ideal" and "delta" should be constants, normally simple
  177325. integers, "value" a variable. Added to libpng-1.2.6 JB */
  177326. #define PNG_OUT_OF_RANGE(value, ideal, delta) \
  177327. ( (value) < (ideal)-(delta) || (value) > (ideal)+(delta) )
  177328. /* variables declared in png.c - only it needs to define PNG_NO_EXTERN */
  177329. #if !defined(PNG_NO_EXTERN) || defined(PNG_ALWAYS_EXTERN)
  177330. /* place to hold the signature string for a PNG file. */
  177331. #ifdef PNG_USE_GLOBAL_ARRAYS
  177332. PNG_EXPORT_VAR (PNG_CONST png_byte FARDATA) png_sig[8];
  177333. #else
  177334. #endif
  177335. #endif /* PNG_NO_EXTERN */
  177336. /* Constant strings for known chunk types. If you need to add a chunk,
  177337. * define the name here, and add an invocation of the macro in png.c and
  177338. * wherever it's needed.
  177339. */
  177340. #define PNG_IHDR png_byte png_IHDR[5] = { 73, 72, 68, 82, '\0'}
  177341. #define PNG_IDAT png_byte png_IDAT[5] = { 73, 68, 65, 84, '\0'}
  177342. #define PNG_IEND png_byte png_IEND[5] = { 73, 69, 78, 68, '\0'}
  177343. #define PNG_PLTE png_byte png_PLTE[5] = { 80, 76, 84, 69, '\0'}
  177344. #define PNG_bKGD png_byte png_bKGD[5] = { 98, 75, 71, 68, '\0'}
  177345. #define PNG_cHRM png_byte png_cHRM[5] = { 99, 72, 82, 77, '\0'}
  177346. #define PNG_gAMA png_byte png_gAMA[5] = {103, 65, 77, 65, '\0'}
  177347. #define PNG_hIST png_byte png_hIST[5] = {104, 73, 83, 84, '\0'}
  177348. #define PNG_iCCP png_byte png_iCCP[5] = {105, 67, 67, 80, '\0'}
  177349. #define PNG_iTXt png_byte png_iTXt[5] = {105, 84, 88, 116, '\0'}
  177350. #define PNG_oFFs png_byte png_oFFs[5] = {111, 70, 70, 115, '\0'}
  177351. #define PNG_pCAL png_byte png_pCAL[5] = {112, 67, 65, 76, '\0'}
  177352. #define PNG_sCAL png_byte png_sCAL[5] = {115, 67, 65, 76, '\0'}
  177353. #define PNG_pHYs png_byte png_pHYs[5] = {112, 72, 89, 115, '\0'}
  177354. #define PNG_sBIT png_byte png_sBIT[5] = {115, 66, 73, 84, '\0'}
  177355. #define PNG_sPLT png_byte png_sPLT[5] = {115, 80, 76, 84, '\0'}
  177356. #define PNG_sRGB png_byte png_sRGB[5] = {115, 82, 71, 66, '\0'}
  177357. #define PNG_tEXt png_byte png_tEXt[5] = {116, 69, 88, 116, '\0'}
  177358. #define PNG_tIME png_byte png_tIME[5] = {116, 73, 77, 69, '\0'}
  177359. #define PNG_tRNS png_byte png_tRNS[5] = {116, 82, 78, 83, '\0'}
  177360. #define PNG_zTXt png_byte png_zTXt[5] = {122, 84, 88, 116, '\0'}
  177361. #ifdef PNG_USE_GLOBAL_ARRAYS
  177362. PNG_EXPORT_VAR (png_byte FARDATA) png_IHDR[5];
  177363. PNG_EXPORT_VAR (png_byte FARDATA) png_IDAT[5];
  177364. PNG_EXPORT_VAR (png_byte FARDATA) png_IEND[5];
  177365. PNG_EXPORT_VAR (png_byte FARDATA) png_PLTE[5];
  177366. PNG_EXPORT_VAR (png_byte FARDATA) png_bKGD[5];
  177367. PNG_EXPORT_VAR (png_byte FARDATA) png_cHRM[5];
  177368. PNG_EXPORT_VAR (png_byte FARDATA) png_gAMA[5];
  177369. PNG_EXPORT_VAR (png_byte FARDATA) png_hIST[5];
  177370. PNG_EXPORT_VAR (png_byte FARDATA) png_iCCP[5];
  177371. PNG_EXPORT_VAR (png_byte FARDATA) png_iTXt[5];
  177372. PNG_EXPORT_VAR (png_byte FARDATA) png_oFFs[5];
  177373. PNG_EXPORT_VAR (png_byte FARDATA) png_pCAL[5];
  177374. PNG_EXPORT_VAR (png_byte FARDATA) png_sCAL[5];
  177375. PNG_EXPORT_VAR (png_byte FARDATA) png_pHYs[5];
  177376. PNG_EXPORT_VAR (png_byte FARDATA) png_sBIT[5];
  177377. PNG_EXPORT_VAR (png_byte FARDATA) png_sPLT[5];
  177378. PNG_EXPORT_VAR (png_byte FARDATA) png_sRGB[5];
  177379. PNG_EXPORT_VAR (png_byte FARDATA) png_tEXt[5];
  177380. PNG_EXPORT_VAR (png_byte FARDATA) png_tIME[5];
  177381. PNG_EXPORT_VAR (png_byte FARDATA) png_tRNS[5];
  177382. PNG_EXPORT_VAR (png_byte FARDATA) png_zTXt[5];
  177383. #endif /* PNG_USE_GLOBAL_ARRAYS */
  177384. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  177385. /* Initialize png_ptr struct for reading, and allocate any other memory.
  177386. * (old interface - DEPRECATED - use png_create_read_struct instead).
  177387. */
  177388. extern PNG_EXPORT(void,png_read_init) PNGARG((png_structp png_ptr));
  177389. #undef png_read_init
  177390. #define png_read_init(png_ptr) png_read_init_3(&png_ptr, \
  177391. PNG_LIBPNG_VER_STRING, png_sizeof(png_struct));
  177392. #endif
  177393. extern PNG_EXPORT(void,png_read_init_3) PNGARG((png_structpp ptr_ptr,
  177394. png_const_charp user_png_ver, png_size_t png_struct_size));
  177395. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  177396. extern PNG_EXPORT(void,png_read_init_2) PNGARG((png_structp png_ptr,
  177397. png_const_charp user_png_ver, png_size_t png_struct_size, png_size_t
  177398. png_info_size));
  177399. #endif
  177400. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  177401. /* Initialize png_ptr struct for writing, and allocate any other memory.
  177402. * (old interface - DEPRECATED - use png_create_write_struct instead).
  177403. */
  177404. extern PNG_EXPORT(void,png_write_init) PNGARG((png_structp png_ptr));
  177405. #undef png_write_init
  177406. #define png_write_init(png_ptr) png_write_init_3(&png_ptr, \
  177407. PNG_LIBPNG_VER_STRING, png_sizeof(png_struct));
  177408. #endif
  177409. extern PNG_EXPORT(void,png_write_init_3) PNGARG((png_structpp ptr_ptr,
  177410. png_const_charp user_png_ver, png_size_t png_struct_size));
  177411. extern PNG_EXPORT(void,png_write_init_2) PNGARG((png_structp png_ptr,
  177412. png_const_charp user_png_ver, png_size_t png_struct_size, png_size_t
  177413. png_info_size));
  177414. /* Allocate memory for an internal libpng struct */
  177415. PNG_EXTERN png_voidp png_create_struct PNGARG((int type));
  177416. /* Free memory from internal libpng struct */
  177417. PNG_EXTERN void png_destroy_struct PNGARG((png_voidp struct_ptr));
  177418. PNG_EXTERN png_voidp png_create_struct_2 PNGARG((int type, png_malloc_ptr
  177419. malloc_fn, png_voidp mem_ptr));
  177420. PNG_EXTERN void png_destroy_struct_2 PNGARG((png_voidp struct_ptr,
  177421. png_free_ptr free_fn, png_voidp mem_ptr));
  177422. /* Free any memory that info_ptr points to and reset struct. */
  177423. PNG_EXTERN void png_info_destroy PNGARG((png_structp png_ptr,
  177424. png_infop info_ptr));
  177425. #ifndef PNG_1_0_X
  177426. /* Function to allocate memory for zlib. */
  177427. PNG_EXTERN voidpf png_zalloc PNGARG((voidpf png_ptr, uInt items, uInt size));
  177428. /* Function to free memory for zlib */
  177429. PNG_EXTERN void png_zfree PNGARG((voidpf png_ptr, voidpf ptr));
  177430. #ifdef PNG_SIZE_T
  177431. /* Function to convert a sizeof an item to png_sizeof item */
  177432. PNG_EXTERN png_size_t PNGAPI png_convert_size PNGARG((size_t size));
  177433. #endif
  177434. /* Next four functions are used internally as callbacks. PNGAPI is required
  177435. * but not PNG_EXPORT. PNGAPI added at libpng version 1.2.3. */
  177436. PNG_EXTERN void PNGAPI png_default_read_data PNGARG((png_structp png_ptr,
  177437. png_bytep data, png_size_t length));
  177438. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  177439. PNG_EXTERN void PNGAPI png_push_fill_buffer PNGARG((png_structp png_ptr,
  177440. png_bytep buffer, png_size_t length));
  177441. #endif
  177442. PNG_EXTERN void PNGAPI png_default_write_data PNGARG((png_structp png_ptr,
  177443. png_bytep data, png_size_t length));
  177444. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  177445. #if !defined(PNG_NO_STDIO)
  177446. PNG_EXTERN void PNGAPI png_default_flush PNGARG((png_structp png_ptr));
  177447. #endif
  177448. #endif
  177449. #else /* PNG_1_0_X */
  177450. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  177451. PNG_EXTERN void png_push_fill_buffer PNGARG((png_structp png_ptr,
  177452. png_bytep buffer, png_size_t length));
  177453. #endif
  177454. #endif /* PNG_1_0_X */
  177455. /* Reset the CRC variable */
  177456. PNG_EXTERN void png_reset_crc PNGARG((png_structp png_ptr));
  177457. /* Write the "data" buffer to whatever output you are using. */
  177458. PNG_EXTERN void png_write_data PNGARG((png_structp png_ptr, png_bytep data,
  177459. png_size_t length));
  177460. /* Read data from whatever input you are using into the "data" buffer */
  177461. PNG_EXTERN void png_read_data PNGARG((png_structp png_ptr, png_bytep data,
  177462. png_size_t length));
  177463. /* Read bytes into buf, and update png_ptr->crc */
  177464. PNG_EXTERN void png_crc_read PNGARG((png_structp png_ptr, png_bytep buf,
  177465. png_size_t length));
  177466. /* Decompress data in a chunk that uses compression */
  177467. #if defined(PNG_zTXt_SUPPORTED) || defined(PNG_iTXt_SUPPORTED) || \
  177468. defined(PNG_iCCP_SUPPORTED) || defined(PNG_sPLT_SUPPORTED)
  177469. PNG_EXTERN png_charp png_decompress_chunk PNGARG((png_structp png_ptr,
  177470. int comp_type, png_charp chunkdata, png_size_t chunklength,
  177471. png_size_t prefix_length, png_size_t *data_length));
  177472. #endif
  177473. /* Read "skip" bytes, read the file crc, and (optionally) verify png_ptr->crc */
  177474. PNG_EXTERN int png_crc_finish PNGARG((png_structp png_ptr, png_uint_32 skip));
  177475. /* Read the CRC from the file and compare it to the libpng calculated CRC */
  177476. PNG_EXTERN int png_crc_error PNGARG((png_structp png_ptr));
  177477. /* Calculate the CRC over a section of data. Note that we are only
  177478. * passing a maximum of 64K on systems that have this as a memory limit,
  177479. * since this is the maximum buffer size we can specify.
  177480. */
  177481. PNG_EXTERN void png_calculate_crc PNGARG((png_structp png_ptr, png_bytep ptr,
  177482. png_size_t length));
  177483. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  177484. PNG_EXTERN void png_flush PNGARG((png_structp png_ptr));
  177485. #endif
  177486. /* simple function to write the signature */
  177487. PNG_EXTERN void png_write_sig PNGARG((png_structp png_ptr));
  177488. /* write various chunks */
  177489. /* Write the IHDR chunk, and update the png_struct with the necessary
  177490. * information.
  177491. */
  177492. PNG_EXTERN void png_write_IHDR PNGARG((png_structp png_ptr, png_uint_32 width,
  177493. png_uint_32 height,
  177494. int bit_depth, int color_type, int compression_method, int filter_method,
  177495. int interlace_method));
  177496. PNG_EXTERN void png_write_PLTE PNGARG((png_structp png_ptr, png_colorp palette,
  177497. png_uint_32 num_pal));
  177498. PNG_EXTERN void png_write_IDAT PNGARG((png_structp png_ptr, png_bytep data,
  177499. png_size_t length));
  177500. PNG_EXTERN void png_write_IEND PNGARG((png_structp png_ptr));
  177501. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  177502. #ifdef PNG_FLOATING_POINT_SUPPORTED
  177503. PNG_EXTERN void png_write_gAMA PNGARG((png_structp png_ptr, double file_gamma));
  177504. #endif
  177505. #ifdef PNG_FIXED_POINT_SUPPORTED
  177506. PNG_EXTERN void png_write_gAMA_fixed PNGARG((png_structp png_ptr, png_fixed_point
  177507. file_gamma));
  177508. #endif
  177509. #endif
  177510. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  177511. PNG_EXTERN void png_write_sBIT PNGARG((png_structp png_ptr, png_color_8p sbit,
  177512. int color_type));
  177513. #endif
  177514. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  177515. #ifdef PNG_FLOATING_POINT_SUPPORTED
  177516. PNG_EXTERN void png_write_cHRM PNGARG((png_structp png_ptr,
  177517. double white_x, double white_y,
  177518. double red_x, double red_y, double green_x, double green_y,
  177519. double blue_x, double blue_y));
  177520. #endif
  177521. #ifdef PNG_FIXED_POINT_SUPPORTED
  177522. PNG_EXTERN void png_write_cHRM_fixed PNGARG((png_structp png_ptr,
  177523. png_fixed_point int_white_x, png_fixed_point int_white_y,
  177524. png_fixed_point int_red_x, png_fixed_point int_red_y, png_fixed_point
  177525. int_green_x, png_fixed_point int_green_y, png_fixed_point int_blue_x,
  177526. png_fixed_point int_blue_y));
  177527. #endif
  177528. #endif
  177529. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  177530. PNG_EXTERN void png_write_sRGB PNGARG((png_structp png_ptr,
  177531. int intent));
  177532. #endif
  177533. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  177534. PNG_EXTERN void png_write_iCCP PNGARG((png_structp png_ptr,
  177535. png_charp name, int compression_type,
  177536. png_charp profile, int proflen));
  177537. /* Note to maintainer: profile should be png_bytep */
  177538. #endif
  177539. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  177540. PNG_EXTERN void png_write_sPLT PNGARG((png_structp png_ptr,
  177541. png_sPLT_tp palette));
  177542. #endif
  177543. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  177544. PNG_EXTERN void png_write_tRNS PNGARG((png_structp png_ptr, png_bytep trans,
  177545. png_color_16p values, int number, int color_type));
  177546. #endif
  177547. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  177548. PNG_EXTERN void png_write_bKGD PNGARG((png_structp png_ptr,
  177549. png_color_16p values, int color_type));
  177550. #endif
  177551. #if defined(PNG_WRITE_hIST_SUPPORTED)
  177552. PNG_EXTERN void png_write_hIST PNGARG((png_structp png_ptr, png_uint_16p hist,
  177553. int num_hist));
  177554. #endif
  177555. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_pCAL_SUPPORTED) || \
  177556. defined(PNG_WRITE_iCCP_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  177557. PNG_EXTERN png_size_t png_check_keyword PNGARG((png_structp png_ptr,
  177558. png_charp key, png_charpp new_key));
  177559. #endif
  177560. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  177561. PNG_EXTERN void png_write_tEXt PNGARG((png_structp png_ptr, png_charp key,
  177562. png_charp text, png_size_t text_len));
  177563. #endif
  177564. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  177565. PNG_EXTERN void png_write_zTXt PNGARG((png_structp png_ptr, png_charp key,
  177566. png_charp text, png_size_t text_len, int compression));
  177567. #endif
  177568. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  177569. PNG_EXTERN void png_write_iTXt PNGARG((png_structp png_ptr,
  177570. int compression, png_charp key, png_charp lang, png_charp lang_key,
  177571. png_charp text));
  177572. #endif
  177573. #if defined(PNG_TEXT_SUPPORTED) /* Added at version 1.0.14 and 1.2.4 */
  177574. PNG_EXTERN int png_set_text_2 PNGARG((png_structp png_ptr,
  177575. png_infop info_ptr, png_textp text_ptr, int num_text));
  177576. #endif
  177577. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  177578. PNG_EXTERN void png_write_oFFs PNGARG((png_structp png_ptr,
  177579. png_int_32 x_offset, png_int_32 y_offset, int unit_type));
  177580. #endif
  177581. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  177582. PNG_EXTERN void png_write_pCAL PNGARG((png_structp png_ptr, png_charp purpose,
  177583. png_int_32 X0, png_int_32 X1, int type, int nparams,
  177584. png_charp units, png_charpp params));
  177585. #endif
  177586. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  177587. PNG_EXTERN void png_write_pHYs PNGARG((png_structp png_ptr,
  177588. png_uint_32 x_pixels_per_unit, png_uint_32 y_pixels_per_unit,
  177589. int unit_type));
  177590. #endif
  177591. #if defined(PNG_WRITE_tIME_SUPPORTED)
  177592. PNG_EXTERN void png_write_tIME PNGARG((png_structp png_ptr,
  177593. png_timep mod_time));
  177594. #endif
  177595. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  177596. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  177597. PNG_EXTERN void png_write_sCAL PNGARG((png_structp png_ptr,
  177598. int unit, double width, double height));
  177599. #else
  177600. #ifdef PNG_FIXED_POINT_SUPPORTED
  177601. PNG_EXTERN void png_write_sCAL_s PNGARG((png_structp png_ptr,
  177602. int unit, png_charp width, png_charp height));
  177603. #endif
  177604. #endif
  177605. #endif
  177606. /* Called when finished processing a row of data */
  177607. PNG_EXTERN void png_write_finish_row PNGARG((png_structp png_ptr));
  177608. /* Internal use only. Called before first row of data */
  177609. PNG_EXTERN void png_write_start_row PNGARG((png_structp png_ptr));
  177610. #if defined(PNG_READ_GAMMA_SUPPORTED)
  177611. PNG_EXTERN void png_build_gamma_table PNGARG((png_structp png_ptr));
  177612. #endif
  177613. /* combine a row of data, dealing with alpha, etc. if requested */
  177614. PNG_EXTERN void png_combine_row PNGARG((png_structp png_ptr, png_bytep row,
  177615. int mask));
  177616. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  177617. /* expand an interlaced row */
  177618. /* OLD pre-1.0.9 interface:
  177619. PNG_EXTERN void png_do_read_interlace PNGARG((png_row_infop row_info,
  177620. png_bytep row, int pass, png_uint_32 transformations));
  177621. */
  177622. PNG_EXTERN void png_do_read_interlace PNGARG((png_structp png_ptr));
  177623. #endif
  177624. /* GRR TO DO (2.0 or whenever): simplify other internal calling interfaces */
  177625. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  177626. /* grab pixels out of a row for an interlaced pass */
  177627. PNG_EXTERN void png_do_write_interlace PNGARG((png_row_infop row_info,
  177628. png_bytep row, int pass));
  177629. #endif
  177630. /* unfilter a row */
  177631. PNG_EXTERN void png_read_filter_row PNGARG((png_structp png_ptr,
  177632. png_row_infop row_info, png_bytep row, png_bytep prev_row, int filter));
  177633. /* Choose the best filter to use and filter the row data */
  177634. PNG_EXTERN void png_write_find_filter PNGARG((png_structp png_ptr,
  177635. png_row_infop row_info));
  177636. /* Write out the filtered row. */
  177637. PNG_EXTERN void png_write_filtered_row PNGARG((png_structp png_ptr,
  177638. png_bytep filtered_row));
  177639. /* finish a row while reading, dealing with interlacing passes, etc. */
  177640. PNG_EXTERN void png_read_finish_row PNGARG((png_structp png_ptr));
  177641. /* initialize the row buffers, etc. */
  177642. PNG_EXTERN void png_read_start_row PNGARG((png_structp png_ptr));
  177643. /* optional call to update the users info structure */
  177644. PNG_EXTERN void png_read_transform_info PNGARG((png_structp png_ptr,
  177645. png_infop info_ptr));
  177646. /* these are the functions that do the transformations */
  177647. #if defined(PNG_READ_FILLER_SUPPORTED)
  177648. PNG_EXTERN void png_do_read_filler PNGARG((png_row_infop row_info,
  177649. png_bytep row, png_uint_32 filler, png_uint_32 flags));
  177650. #endif
  177651. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  177652. PNG_EXTERN void png_do_read_swap_alpha PNGARG((png_row_infop row_info,
  177653. png_bytep row));
  177654. #endif
  177655. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  177656. PNG_EXTERN void png_do_write_swap_alpha PNGARG((png_row_infop row_info,
  177657. png_bytep row));
  177658. #endif
  177659. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  177660. PNG_EXTERN void png_do_read_invert_alpha PNGARG((png_row_infop row_info,
  177661. png_bytep row));
  177662. #endif
  177663. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  177664. PNG_EXTERN void png_do_write_invert_alpha PNGARG((png_row_infop row_info,
  177665. png_bytep row));
  177666. #endif
  177667. #if defined(PNG_WRITE_FILLER_SUPPORTED) || \
  177668. defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  177669. PNG_EXTERN void png_do_strip_filler PNGARG((png_row_infop row_info,
  177670. png_bytep row, png_uint_32 flags));
  177671. #endif
  177672. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  177673. PNG_EXTERN void png_do_swap PNGARG((png_row_infop row_info, png_bytep row));
  177674. #endif
  177675. #if defined(PNG_READ_PACKSWAP_SUPPORTED) || defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  177676. PNG_EXTERN void png_do_packswap PNGARG((png_row_infop row_info, png_bytep row));
  177677. #endif
  177678. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  177679. PNG_EXTERN int png_do_rgb_to_gray PNGARG((png_structp png_ptr, png_row_infop
  177680. row_info, png_bytep row));
  177681. #endif
  177682. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  177683. PNG_EXTERN void png_do_gray_to_rgb PNGARG((png_row_infop row_info,
  177684. png_bytep row));
  177685. #endif
  177686. #if defined(PNG_READ_PACK_SUPPORTED)
  177687. PNG_EXTERN void png_do_unpack PNGARG((png_row_infop row_info, png_bytep row));
  177688. #endif
  177689. #if defined(PNG_READ_SHIFT_SUPPORTED)
  177690. PNG_EXTERN void png_do_unshift PNGARG((png_row_infop row_info, png_bytep row,
  177691. png_color_8p sig_bits));
  177692. #endif
  177693. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  177694. PNG_EXTERN void png_do_invert PNGARG((png_row_infop row_info, png_bytep row));
  177695. #endif
  177696. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  177697. PNG_EXTERN void png_do_chop PNGARG((png_row_infop row_info, png_bytep row));
  177698. #endif
  177699. #if defined(PNG_READ_DITHER_SUPPORTED)
  177700. PNG_EXTERN void png_do_dither PNGARG((png_row_infop row_info,
  177701. png_bytep row, png_bytep palette_lookup, png_bytep dither_lookup));
  177702. # if defined(PNG_CORRECT_PALETTE_SUPPORTED)
  177703. PNG_EXTERN void png_correct_palette PNGARG((png_structp png_ptr,
  177704. png_colorp palette, int num_palette));
  177705. # endif
  177706. #endif
  177707. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  177708. PNG_EXTERN void png_do_bgr PNGARG((png_row_infop row_info, png_bytep row));
  177709. #endif
  177710. #if defined(PNG_WRITE_PACK_SUPPORTED)
  177711. PNG_EXTERN void png_do_pack PNGARG((png_row_infop row_info,
  177712. png_bytep row, png_uint_32 bit_depth));
  177713. #endif
  177714. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  177715. PNG_EXTERN void png_do_shift PNGARG((png_row_infop row_info, png_bytep row,
  177716. png_color_8p bit_depth));
  177717. #endif
  177718. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  177719. #if defined(PNG_READ_GAMMA_SUPPORTED)
  177720. PNG_EXTERN void png_do_background PNGARG((png_row_infop row_info, png_bytep row,
  177721. png_color_16p trans_values, png_color_16p background,
  177722. png_color_16p background_1,
  177723. png_bytep gamma_table, png_bytep gamma_from_1, png_bytep gamma_to_1,
  177724. png_uint_16pp gamma_16, png_uint_16pp gamma_16_from_1,
  177725. png_uint_16pp gamma_16_to_1, int gamma_shift));
  177726. #else
  177727. PNG_EXTERN void png_do_background PNGARG((png_row_infop row_info, png_bytep row,
  177728. png_color_16p trans_values, png_color_16p background));
  177729. #endif
  177730. #endif
  177731. #if defined(PNG_READ_GAMMA_SUPPORTED)
  177732. PNG_EXTERN void png_do_gamma PNGARG((png_row_infop row_info, png_bytep row,
  177733. png_bytep gamma_table, png_uint_16pp gamma_16_table,
  177734. int gamma_shift));
  177735. #endif
  177736. #if defined(PNG_READ_EXPAND_SUPPORTED)
  177737. PNG_EXTERN void png_do_expand_palette PNGARG((png_row_infop row_info,
  177738. png_bytep row, png_colorp palette, png_bytep trans, int num_trans));
  177739. PNG_EXTERN void png_do_expand PNGARG((png_row_infop row_info,
  177740. png_bytep row, png_color_16p trans_value));
  177741. #endif
  177742. /* The following decodes the appropriate chunks, and does error correction,
  177743. * then calls the appropriate callback for the chunk if it is valid.
  177744. */
  177745. /* decode the IHDR chunk */
  177746. PNG_EXTERN void png_handle_IHDR PNGARG((png_structp png_ptr, png_infop info_ptr,
  177747. png_uint_32 length));
  177748. PNG_EXTERN void png_handle_PLTE PNGARG((png_structp png_ptr, png_infop info_ptr,
  177749. png_uint_32 length));
  177750. PNG_EXTERN void png_handle_IEND PNGARG((png_structp png_ptr, png_infop info_ptr,
  177751. png_uint_32 length));
  177752. #if defined(PNG_READ_bKGD_SUPPORTED)
  177753. PNG_EXTERN void png_handle_bKGD PNGARG((png_structp png_ptr, png_infop info_ptr,
  177754. png_uint_32 length));
  177755. #endif
  177756. #if defined(PNG_READ_cHRM_SUPPORTED)
  177757. PNG_EXTERN void png_handle_cHRM PNGARG((png_structp png_ptr, png_infop info_ptr,
  177758. png_uint_32 length));
  177759. #endif
  177760. #if defined(PNG_READ_gAMA_SUPPORTED)
  177761. PNG_EXTERN void png_handle_gAMA PNGARG((png_structp png_ptr, png_infop info_ptr,
  177762. png_uint_32 length));
  177763. #endif
  177764. #if defined(PNG_READ_hIST_SUPPORTED)
  177765. PNG_EXTERN void png_handle_hIST PNGARG((png_structp png_ptr, png_infop info_ptr,
  177766. png_uint_32 length));
  177767. #endif
  177768. #if defined(PNG_READ_iCCP_SUPPORTED)
  177769. extern void png_handle_iCCP PNGARG((png_structp png_ptr, png_infop info_ptr,
  177770. png_uint_32 length));
  177771. #endif /* PNG_READ_iCCP_SUPPORTED */
  177772. #if defined(PNG_READ_iTXt_SUPPORTED)
  177773. PNG_EXTERN void png_handle_iTXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  177774. png_uint_32 length));
  177775. #endif
  177776. #if defined(PNG_READ_oFFs_SUPPORTED)
  177777. PNG_EXTERN void png_handle_oFFs PNGARG((png_structp png_ptr, png_infop info_ptr,
  177778. png_uint_32 length));
  177779. #endif
  177780. #if defined(PNG_READ_pCAL_SUPPORTED)
  177781. PNG_EXTERN void png_handle_pCAL PNGARG((png_structp png_ptr, png_infop info_ptr,
  177782. png_uint_32 length));
  177783. #endif
  177784. #if defined(PNG_READ_pHYs_SUPPORTED)
  177785. PNG_EXTERN void png_handle_pHYs PNGARG((png_structp png_ptr, png_infop info_ptr,
  177786. png_uint_32 length));
  177787. #endif
  177788. #if defined(PNG_READ_sBIT_SUPPORTED)
  177789. PNG_EXTERN void png_handle_sBIT PNGARG((png_structp png_ptr, png_infop info_ptr,
  177790. png_uint_32 length));
  177791. #endif
  177792. #if defined(PNG_READ_sCAL_SUPPORTED)
  177793. PNG_EXTERN void png_handle_sCAL PNGARG((png_structp png_ptr, png_infop info_ptr,
  177794. png_uint_32 length));
  177795. #endif
  177796. #if defined(PNG_READ_sPLT_SUPPORTED)
  177797. extern void png_handle_sPLT PNGARG((png_structp png_ptr, png_infop info_ptr,
  177798. png_uint_32 length));
  177799. #endif /* PNG_READ_sPLT_SUPPORTED */
  177800. #if defined(PNG_READ_sRGB_SUPPORTED)
  177801. PNG_EXTERN void png_handle_sRGB PNGARG((png_structp png_ptr, png_infop info_ptr,
  177802. png_uint_32 length));
  177803. #endif
  177804. #if defined(PNG_READ_tEXt_SUPPORTED)
  177805. PNG_EXTERN void png_handle_tEXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  177806. png_uint_32 length));
  177807. #endif
  177808. #if defined(PNG_READ_tIME_SUPPORTED)
  177809. PNG_EXTERN void png_handle_tIME PNGARG((png_structp png_ptr, png_infop info_ptr,
  177810. png_uint_32 length));
  177811. #endif
  177812. #if defined(PNG_READ_tRNS_SUPPORTED)
  177813. PNG_EXTERN void png_handle_tRNS PNGARG((png_structp png_ptr, png_infop info_ptr,
  177814. png_uint_32 length));
  177815. #endif
  177816. #if defined(PNG_READ_zTXt_SUPPORTED)
  177817. PNG_EXTERN void png_handle_zTXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  177818. png_uint_32 length));
  177819. #endif
  177820. PNG_EXTERN void png_handle_unknown PNGARG((png_structp png_ptr,
  177821. png_infop info_ptr, png_uint_32 length));
  177822. PNG_EXTERN void png_check_chunk_name PNGARG((png_structp png_ptr,
  177823. png_bytep chunk_name));
  177824. /* handle the transformations for reading and writing */
  177825. PNG_EXTERN void png_do_read_transformations PNGARG((png_structp png_ptr));
  177826. PNG_EXTERN void png_do_write_transformations PNGARG((png_structp png_ptr));
  177827. PNG_EXTERN void png_init_read_transformations PNGARG((png_structp png_ptr));
  177828. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  177829. PNG_EXTERN void png_push_read_chunk PNGARG((png_structp png_ptr,
  177830. png_infop info_ptr));
  177831. PNG_EXTERN void png_push_read_sig PNGARG((png_structp png_ptr,
  177832. png_infop info_ptr));
  177833. PNG_EXTERN void png_push_check_crc PNGARG((png_structp png_ptr));
  177834. PNG_EXTERN void png_push_crc_skip PNGARG((png_structp png_ptr,
  177835. png_uint_32 length));
  177836. PNG_EXTERN void png_push_crc_finish PNGARG((png_structp png_ptr));
  177837. PNG_EXTERN void png_push_save_buffer PNGARG((png_structp png_ptr));
  177838. PNG_EXTERN void png_push_restore_buffer PNGARG((png_structp png_ptr,
  177839. png_bytep buffer, png_size_t buffer_length));
  177840. PNG_EXTERN void png_push_read_IDAT PNGARG((png_structp png_ptr));
  177841. PNG_EXTERN void png_process_IDAT_data PNGARG((png_structp png_ptr,
  177842. png_bytep buffer, png_size_t buffer_length));
  177843. PNG_EXTERN void png_push_process_row PNGARG((png_structp png_ptr));
  177844. PNG_EXTERN void png_push_handle_unknown PNGARG((png_structp png_ptr,
  177845. png_infop info_ptr, png_uint_32 length));
  177846. PNG_EXTERN void png_push_have_info PNGARG((png_structp png_ptr,
  177847. png_infop info_ptr));
  177848. PNG_EXTERN void png_push_have_end PNGARG((png_structp png_ptr,
  177849. png_infop info_ptr));
  177850. PNG_EXTERN void png_push_have_row PNGARG((png_structp png_ptr, png_bytep row));
  177851. PNG_EXTERN void png_push_read_end PNGARG((png_structp png_ptr,
  177852. png_infop info_ptr));
  177853. PNG_EXTERN void png_process_some_data PNGARG((png_structp png_ptr,
  177854. png_infop info_ptr));
  177855. PNG_EXTERN void png_read_push_finish_row PNGARG((png_structp png_ptr));
  177856. #if defined(PNG_READ_tEXt_SUPPORTED)
  177857. PNG_EXTERN void png_push_handle_tEXt PNGARG((png_structp png_ptr,
  177858. png_infop info_ptr, png_uint_32 length));
  177859. PNG_EXTERN void png_push_read_tEXt PNGARG((png_structp png_ptr,
  177860. png_infop info_ptr));
  177861. #endif
  177862. #if defined(PNG_READ_zTXt_SUPPORTED)
  177863. PNG_EXTERN void png_push_handle_zTXt PNGARG((png_structp png_ptr,
  177864. png_infop info_ptr, png_uint_32 length));
  177865. PNG_EXTERN void png_push_read_zTXt PNGARG((png_structp png_ptr,
  177866. png_infop info_ptr));
  177867. #endif
  177868. #if defined(PNG_READ_iTXt_SUPPORTED)
  177869. PNG_EXTERN void png_push_handle_iTXt PNGARG((png_structp png_ptr,
  177870. png_infop info_ptr, png_uint_32 length));
  177871. PNG_EXTERN void png_push_read_iTXt PNGARG((png_structp png_ptr,
  177872. png_infop info_ptr));
  177873. #endif
  177874. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  177875. #ifdef PNG_MNG_FEATURES_SUPPORTED
  177876. PNG_EXTERN void png_do_read_intrapixel PNGARG((png_row_infop row_info,
  177877. png_bytep row));
  177878. PNG_EXTERN void png_do_write_intrapixel PNGARG((png_row_infop row_info,
  177879. png_bytep row));
  177880. #endif
  177881. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  177882. #if defined(PNG_MMX_CODE_SUPPORTED)
  177883. /* png.c */ /* PRIVATE */
  177884. PNG_EXTERN void png_init_mmx_flags PNGARG((png_structp png_ptr));
  177885. #endif
  177886. #endif
  177887. #if defined(PNG_INCH_CONVERSIONS) && defined(PNG_FLOATING_POINT_SUPPORTED)
  177888. PNG_EXTERN png_uint_32 png_get_pixels_per_inch PNGARG((png_structp png_ptr,
  177889. png_infop info_ptr));
  177890. PNG_EXTERN png_uint_32 png_get_x_pixels_per_inch PNGARG((png_structp png_ptr,
  177891. png_infop info_ptr));
  177892. PNG_EXTERN png_uint_32 png_get_y_pixels_per_inch PNGARG((png_structp png_ptr,
  177893. png_infop info_ptr));
  177894. PNG_EXTERN float png_get_x_offset_inches PNGARG((png_structp png_ptr,
  177895. png_infop info_ptr));
  177896. PNG_EXTERN float png_get_y_offset_inches PNGARG((png_structp png_ptr,
  177897. png_infop info_ptr));
  177898. #if defined(PNG_pHYs_SUPPORTED)
  177899. PNG_EXTERN png_uint_32 png_get_pHYs_dpi PNGARG((png_structp png_ptr,
  177900. png_infop info_ptr, png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type));
  177901. #endif /* PNG_pHYs_SUPPORTED */
  177902. #endif /* PNG_INCH_CONVERSIONS && PNG_FLOATING_POINT_SUPPORTED */
  177903. /* Maintainer: Put new private prototypes here ^ and in libpngpf.3 */
  177904. #endif /* PNG_INTERNAL */
  177905. #ifdef __cplusplus
  177906. }
  177907. #endif
  177908. #endif /* PNG_VERSION_INFO_ONLY */
  177909. /* do not put anything past this line */
  177910. #endif /* PNG_H */
  177911. /********* End of inlined file: png.h *********/
  177912. #define PNG_NO_EXTERN
  177913. /********* Start of inlined file: png.c *********/
  177914. /* png.c - location for general purpose libpng functions
  177915. *
  177916. * Last changed in libpng 1.2.21 [October 4, 2007]
  177917. * For conditions of distribution and use, see copyright notice in png.h
  177918. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  177919. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  177920. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  177921. */
  177922. #define PNG_INTERNAL
  177923. #define PNG_NO_EXTERN
  177924. /* Generate a compiler error if there is an old png.h in the search path. */
  177925. typedef version_1_2_21 Your_png_h_is_not_version_1_2_21;
  177926. /* Version information for C files. This had better match the version
  177927. * string defined in png.h. */
  177928. #ifdef PNG_USE_GLOBAL_ARRAYS
  177929. /* png_libpng_ver was changed to a function in version 1.0.5c */
  177930. PNG_CONST char png_libpng_ver[18] = PNG_LIBPNG_VER_STRING;
  177931. #ifdef PNG_READ_SUPPORTED
  177932. /* png_sig was changed to a function in version 1.0.5c */
  177933. /* Place to hold the signature string for a PNG file. */
  177934. PNG_CONST png_byte FARDATA png_sig[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  177935. #endif /* PNG_READ_SUPPORTED */
  177936. /* Invoke global declarations for constant strings for known chunk types */
  177937. PNG_IHDR;
  177938. PNG_IDAT;
  177939. PNG_IEND;
  177940. PNG_PLTE;
  177941. PNG_bKGD;
  177942. PNG_cHRM;
  177943. PNG_gAMA;
  177944. PNG_hIST;
  177945. PNG_iCCP;
  177946. PNG_iTXt;
  177947. PNG_oFFs;
  177948. PNG_pCAL;
  177949. PNG_sCAL;
  177950. PNG_pHYs;
  177951. PNG_sBIT;
  177952. PNG_sPLT;
  177953. PNG_sRGB;
  177954. PNG_tEXt;
  177955. PNG_tIME;
  177956. PNG_tRNS;
  177957. PNG_zTXt;
  177958. #ifdef PNG_READ_SUPPORTED
  177959. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  177960. /* start of interlace block */
  177961. PNG_CONST int FARDATA png_pass_start[] = {0, 4, 0, 2, 0, 1, 0};
  177962. /* offset to next interlace block */
  177963. PNG_CONST int FARDATA png_pass_inc[] = {8, 8, 4, 4, 2, 2, 1};
  177964. /* start of interlace block in the y direction */
  177965. PNG_CONST int FARDATA png_pass_ystart[] = {0, 0, 4, 0, 2, 0, 1};
  177966. /* offset to next interlace block in the y direction */
  177967. PNG_CONST int FARDATA png_pass_yinc[] = {8, 8, 8, 4, 4, 2, 2};
  177968. /* Height of interlace block. This is not currently used - if you need
  177969. * it, uncomment it here and in png.h
  177970. PNG_CONST int FARDATA png_pass_height[] = {8, 8, 4, 4, 2, 2, 1};
  177971. */
  177972. /* Mask to determine which pixels are valid in a pass */
  177973. PNG_CONST int FARDATA png_pass_mask[] = {0x80, 0x08, 0x88, 0x22, 0xaa, 0x55, 0xff};
  177974. /* Mask to determine which pixels to overwrite while displaying */
  177975. PNG_CONST int FARDATA png_pass_dsp_mask[]
  177976. = {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, 0xff};
  177977. #endif /* PNG_READ_SUPPORTED */
  177978. #endif /* PNG_USE_GLOBAL_ARRAYS */
  177979. /* Tells libpng that we have already handled the first "num_bytes" bytes
  177980. * of the PNG file signature. If the PNG data is embedded into another
  177981. * stream we can set num_bytes = 8 so that libpng will not attempt to read
  177982. * or write any of the magic bytes before it starts on the IHDR.
  177983. */
  177984. #ifdef PNG_READ_SUPPORTED
  177985. void PNGAPI
  177986. png_set_sig_bytes(png_structp png_ptr, int num_bytes)
  177987. {
  177988. if(png_ptr == NULL) return;
  177989. png_debug(1, "in png_set_sig_bytes\n");
  177990. if (num_bytes > 8)
  177991. png_error(png_ptr, "Too many bytes for PNG signature.");
  177992. png_ptr->sig_bytes = (png_byte)(num_bytes < 0 ? 0 : num_bytes);
  177993. }
  177994. /* Checks whether the supplied bytes match the PNG signature. We allow
  177995. * checking less than the full 8-byte signature so that those apps that
  177996. * already read the first few bytes of a file to determine the file type
  177997. * can simply check the remaining bytes for extra assurance. Returns
  177998. * an integer less than, equal to, or greater than zero if sig is found,
  177999. * respectively, to be less than, to match, or be greater than the correct
  178000. * PNG signature (this is the same behaviour as strcmp, memcmp, etc).
  178001. */
  178002. int PNGAPI
  178003. png_sig_cmp(png_bytep sig, png_size_t start, png_size_t num_to_check)
  178004. {
  178005. png_byte png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  178006. if (num_to_check > 8)
  178007. num_to_check = 8;
  178008. else if (num_to_check < 1)
  178009. return (-1);
  178010. if (start > 7)
  178011. return (-1);
  178012. if (start + num_to_check > 8)
  178013. num_to_check = 8 - start;
  178014. return ((int)(png_memcmp(&sig[start], &png_signature[start], num_to_check)));
  178015. }
  178016. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  178017. /* (Obsolete) function to check signature bytes. It does not allow one
  178018. * to check a partial signature. This function might be removed in the
  178019. * future - use png_sig_cmp(). Returns true (nonzero) if the file is PNG.
  178020. */
  178021. int PNGAPI
  178022. png_check_sig(png_bytep sig, int num)
  178023. {
  178024. return ((int)!png_sig_cmp(sig, (png_size_t)0, (png_size_t)num));
  178025. }
  178026. #endif
  178027. #endif /* PNG_READ_SUPPORTED */
  178028. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  178029. /* Function to allocate memory for zlib and clear it to 0. */
  178030. #ifdef PNG_1_0_X
  178031. voidpf PNGAPI
  178032. #else
  178033. voidpf /* private */
  178034. #endif
  178035. png_zalloc(voidpf png_ptr, uInt items, uInt size)
  178036. {
  178037. png_voidp ptr;
  178038. png_structp p=(png_structp)png_ptr;
  178039. png_uint_32 save_flags=p->flags;
  178040. png_uint_32 num_bytes;
  178041. if(png_ptr == NULL) return (NULL);
  178042. if (items > PNG_UINT_32_MAX/size)
  178043. {
  178044. png_warning (p, "Potential overflow in png_zalloc()");
  178045. return (NULL);
  178046. }
  178047. num_bytes = (png_uint_32)items * size;
  178048. p->flags|=PNG_FLAG_MALLOC_NULL_MEM_OK;
  178049. ptr = (png_voidp)png_malloc((png_structp)png_ptr, num_bytes);
  178050. p->flags=save_flags;
  178051. #if defined(PNG_1_0_X) && !defined(PNG_NO_ZALLOC_ZERO)
  178052. if (ptr == NULL)
  178053. return ((voidpf)ptr);
  178054. if (num_bytes > (png_uint_32)0x8000L)
  178055. {
  178056. png_memset(ptr, 0, (png_size_t)0x8000L);
  178057. png_memset((png_bytep)ptr + (png_size_t)0x8000L, 0,
  178058. (png_size_t)(num_bytes - (png_uint_32)0x8000L));
  178059. }
  178060. else
  178061. {
  178062. png_memset(ptr, 0, (png_size_t)num_bytes);
  178063. }
  178064. #endif
  178065. return ((voidpf)ptr);
  178066. }
  178067. /* function to free memory for zlib */
  178068. #ifdef PNG_1_0_X
  178069. void PNGAPI
  178070. #else
  178071. void /* private */
  178072. #endif
  178073. png_zfree(voidpf png_ptr, voidpf ptr)
  178074. {
  178075. png_free((png_structp)png_ptr, (png_voidp)ptr);
  178076. }
  178077. /* Reset the CRC variable to 32 bits of 1's. Care must be taken
  178078. * in case CRC is > 32 bits to leave the top bits 0.
  178079. */
  178080. void /* PRIVATE */
  178081. png_reset_crc(png_structp png_ptr)
  178082. {
  178083. png_ptr->crc = crc32(0, Z_NULL, 0);
  178084. }
  178085. /* Calculate the CRC over a section of data. We can only pass as
  178086. * much data to this routine as the largest single buffer size. We
  178087. * also check that this data will actually be used before going to the
  178088. * trouble of calculating it.
  178089. */
  178090. void /* PRIVATE */
  178091. png_calculate_crc(png_structp png_ptr, png_bytep ptr, png_size_t length)
  178092. {
  178093. int need_crc = 1;
  178094. if (png_ptr->chunk_name[0] & 0x20) /* ancillary */
  178095. {
  178096. if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_MASK) ==
  178097. (PNG_FLAG_CRC_ANCILLARY_USE | PNG_FLAG_CRC_ANCILLARY_NOWARN))
  178098. need_crc = 0;
  178099. }
  178100. else /* critical */
  178101. {
  178102. if (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_IGNORE)
  178103. need_crc = 0;
  178104. }
  178105. if (need_crc)
  178106. png_ptr->crc = crc32(png_ptr->crc, ptr, (uInt)length);
  178107. }
  178108. /* Allocate the memory for an info_struct for the application. We don't
  178109. * really need the png_ptr, but it could potentially be useful in the
  178110. * future. This should be used in favour of malloc(png_sizeof(png_info))
  178111. * and png_info_init() so that applications that want to use a shared
  178112. * libpng don't have to be recompiled if png_info changes size.
  178113. */
  178114. png_infop PNGAPI
  178115. png_create_info_struct(png_structp png_ptr)
  178116. {
  178117. png_infop info_ptr;
  178118. png_debug(1, "in png_create_info_struct\n");
  178119. if(png_ptr == NULL) return (NULL);
  178120. #ifdef PNG_USER_MEM_SUPPORTED
  178121. info_ptr = (png_infop)png_create_struct_2(PNG_STRUCT_INFO,
  178122. png_ptr->malloc_fn, png_ptr->mem_ptr);
  178123. #else
  178124. info_ptr = (png_infop)png_create_struct(PNG_STRUCT_INFO);
  178125. #endif
  178126. if (info_ptr != NULL)
  178127. png_info_init_3(&info_ptr, png_sizeof(png_info));
  178128. return (info_ptr);
  178129. }
  178130. /* This function frees the memory associated with a single info struct.
  178131. * Normally, one would use either png_destroy_read_struct() or
  178132. * png_destroy_write_struct() to free an info struct, but this may be
  178133. * useful for some applications.
  178134. */
  178135. void PNGAPI
  178136. png_destroy_info_struct(png_structp png_ptr, png_infopp info_ptr_ptr)
  178137. {
  178138. png_infop info_ptr = NULL;
  178139. if(png_ptr == NULL) return;
  178140. png_debug(1, "in png_destroy_info_struct\n");
  178141. if (info_ptr_ptr != NULL)
  178142. info_ptr = *info_ptr_ptr;
  178143. if (info_ptr != NULL)
  178144. {
  178145. png_info_destroy(png_ptr, info_ptr);
  178146. #ifdef PNG_USER_MEM_SUPPORTED
  178147. png_destroy_struct_2((png_voidp)info_ptr, png_ptr->free_fn,
  178148. png_ptr->mem_ptr);
  178149. #else
  178150. png_destroy_struct((png_voidp)info_ptr);
  178151. #endif
  178152. *info_ptr_ptr = NULL;
  178153. }
  178154. }
  178155. /* Initialize the info structure. This is now an internal function (0.89)
  178156. * and applications using it are urged to use png_create_info_struct()
  178157. * instead.
  178158. */
  178159. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  178160. #undef png_info_init
  178161. void PNGAPI
  178162. png_info_init(png_infop info_ptr)
  178163. {
  178164. /* We only come here via pre-1.0.12-compiled applications */
  178165. png_info_init_3(&info_ptr, 0);
  178166. }
  178167. #endif
  178168. void PNGAPI
  178169. png_info_init_3(png_infopp ptr_ptr, png_size_t png_info_struct_size)
  178170. {
  178171. png_infop info_ptr = *ptr_ptr;
  178172. if(info_ptr == NULL) return;
  178173. png_debug(1, "in png_info_init_3\n");
  178174. if(png_sizeof(png_info) > png_info_struct_size)
  178175. {
  178176. png_destroy_struct(info_ptr);
  178177. info_ptr = (png_infop)png_create_struct(PNG_STRUCT_INFO);
  178178. *ptr_ptr = info_ptr;
  178179. }
  178180. /* set everything to 0 */
  178181. png_memset(info_ptr, 0, png_sizeof (png_info));
  178182. }
  178183. #ifdef PNG_FREE_ME_SUPPORTED
  178184. void PNGAPI
  178185. png_data_freer(png_structp png_ptr, png_infop info_ptr,
  178186. int freer, png_uint_32 mask)
  178187. {
  178188. png_debug(1, "in png_data_freer\n");
  178189. if (png_ptr == NULL || info_ptr == NULL)
  178190. return;
  178191. if(freer == PNG_DESTROY_WILL_FREE_DATA)
  178192. info_ptr->free_me |= mask;
  178193. else if(freer == PNG_USER_WILL_FREE_DATA)
  178194. info_ptr->free_me &= ~mask;
  178195. else
  178196. png_warning(png_ptr,
  178197. "Unknown freer parameter in png_data_freer.");
  178198. }
  178199. #endif
  178200. void PNGAPI
  178201. png_free_data(png_structp png_ptr, png_infop info_ptr, png_uint_32 mask,
  178202. int num)
  178203. {
  178204. png_debug(1, "in png_free_data\n");
  178205. if (png_ptr == NULL || info_ptr == NULL)
  178206. return;
  178207. #if defined(PNG_TEXT_SUPPORTED)
  178208. /* free text item num or (if num == -1) all text items */
  178209. #ifdef PNG_FREE_ME_SUPPORTED
  178210. if ((mask & PNG_FREE_TEXT) & info_ptr->free_me)
  178211. #else
  178212. if (mask & PNG_FREE_TEXT)
  178213. #endif
  178214. {
  178215. if (num != -1)
  178216. {
  178217. if (info_ptr->text && info_ptr->text[num].key)
  178218. {
  178219. png_free(png_ptr, info_ptr->text[num].key);
  178220. info_ptr->text[num].key = NULL;
  178221. }
  178222. }
  178223. else
  178224. {
  178225. int i;
  178226. for (i = 0; i < info_ptr->num_text; i++)
  178227. png_free_data(png_ptr, info_ptr, PNG_FREE_TEXT, i);
  178228. png_free(png_ptr, info_ptr->text);
  178229. info_ptr->text = NULL;
  178230. info_ptr->num_text=0;
  178231. }
  178232. }
  178233. #endif
  178234. #if defined(PNG_tRNS_SUPPORTED)
  178235. /* free any tRNS entry */
  178236. #ifdef PNG_FREE_ME_SUPPORTED
  178237. if ((mask & PNG_FREE_TRNS) & info_ptr->free_me)
  178238. #else
  178239. if ((mask & PNG_FREE_TRNS) && (png_ptr->flags & PNG_FLAG_FREE_TRNS))
  178240. #endif
  178241. {
  178242. png_free(png_ptr, info_ptr->trans);
  178243. info_ptr->valid &= ~PNG_INFO_tRNS;
  178244. #ifndef PNG_FREE_ME_SUPPORTED
  178245. png_ptr->flags &= ~PNG_FLAG_FREE_TRNS;
  178246. #endif
  178247. info_ptr->trans = NULL;
  178248. }
  178249. #endif
  178250. #if defined(PNG_sCAL_SUPPORTED)
  178251. /* free any sCAL entry */
  178252. #ifdef PNG_FREE_ME_SUPPORTED
  178253. if ((mask & PNG_FREE_SCAL) & info_ptr->free_me)
  178254. #else
  178255. if (mask & PNG_FREE_SCAL)
  178256. #endif
  178257. {
  178258. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  178259. png_free(png_ptr, info_ptr->scal_s_width);
  178260. png_free(png_ptr, info_ptr->scal_s_height);
  178261. info_ptr->scal_s_width = NULL;
  178262. info_ptr->scal_s_height = NULL;
  178263. #endif
  178264. info_ptr->valid &= ~PNG_INFO_sCAL;
  178265. }
  178266. #endif
  178267. #if defined(PNG_pCAL_SUPPORTED)
  178268. /* free any pCAL entry */
  178269. #ifdef PNG_FREE_ME_SUPPORTED
  178270. if ((mask & PNG_FREE_PCAL) & info_ptr->free_me)
  178271. #else
  178272. if (mask & PNG_FREE_PCAL)
  178273. #endif
  178274. {
  178275. png_free(png_ptr, info_ptr->pcal_purpose);
  178276. png_free(png_ptr, info_ptr->pcal_units);
  178277. info_ptr->pcal_purpose = NULL;
  178278. info_ptr->pcal_units = NULL;
  178279. if (info_ptr->pcal_params != NULL)
  178280. {
  178281. int i;
  178282. for (i = 0; i < (int)info_ptr->pcal_nparams; i++)
  178283. {
  178284. png_free(png_ptr, info_ptr->pcal_params[i]);
  178285. info_ptr->pcal_params[i]=NULL;
  178286. }
  178287. png_free(png_ptr, info_ptr->pcal_params);
  178288. info_ptr->pcal_params = NULL;
  178289. }
  178290. info_ptr->valid &= ~PNG_INFO_pCAL;
  178291. }
  178292. #endif
  178293. #if defined(PNG_iCCP_SUPPORTED)
  178294. /* free any iCCP entry */
  178295. #ifdef PNG_FREE_ME_SUPPORTED
  178296. if ((mask & PNG_FREE_ICCP) & info_ptr->free_me)
  178297. #else
  178298. if (mask & PNG_FREE_ICCP)
  178299. #endif
  178300. {
  178301. png_free(png_ptr, info_ptr->iccp_name);
  178302. png_free(png_ptr, info_ptr->iccp_profile);
  178303. info_ptr->iccp_name = NULL;
  178304. info_ptr->iccp_profile = NULL;
  178305. info_ptr->valid &= ~PNG_INFO_iCCP;
  178306. }
  178307. #endif
  178308. #if defined(PNG_sPLT_SUPPORTED)
  178309. /* free a given sPLT entry, or (if num == -1) all sPLT entries */
  178310. #ifdef PNG_FREE_ME_SUPPORTED
  178311. if ((mask & PNG_FREE_SPLT) & info_ptr->free_me)
  178312. #else
  178313. if (mask & PNG_FREE_SPLT)
  178314. #endif
  178315. {
  178316. if (num != -1)
  178317. {
  178318. if(info_ptr->splt_palettes)
  178319. {
  178320. png_free(png_ptr, info_ptr->splt_palettes[num].name);
  178321. png_free(png_ptr, info_ptr->splt_palettes[num].entries);
  178322. info_ptr->splt_palettes[num].name = NULL;
  178323. info_ptr->splt_palettes[num].entries = NULL;
  178324. }
  178325. }
  178326. else
  178327. {
  178328. if(info_ptr->splt_palettes_num)
  178329. {
  178330. int i;
  178331. for (i = 0; i < (int)info_ptr->splt_palettes_num; i++)
  178332. png_free_data(png_ptr, info_ptr, PNG_FREE_SPLT, i);
  178333. png_free(png_ptr, info_ptr->splt_palettes);
  178334. info_ptr->splt_palettes = NULL;
  178335. info_ptr->splt_palettes_num = 0;
  178336. }
  178337. info_ptr->valid &= ~PNG_INFO_sPLT;
  178338. }
  178339. }
  178340. #endif
  178341. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  178342. if(png_ptr->unknown_chunk.data)
  178343. {
  178344. png_free(png_ptr, png_ptr->unknown_chunk.data);
  178345. png_ptr->unknown_chunk.data = NULL;
  178346. }
  178347. #ifdef PNG_FREE_ME_SUPPORTED
  178348. if ((mask & PNG_FREE_UNKN) & info_ptr->free_me)
  178349. #else
  178350. if (mask & PNG_FREE_UNKN)
  178351. #endif
  178352. {
  178353. if (num != -1)
  178354. {
  178355. if(info_ptr->unknown_chunks)
  178356. {
  178357. png_free(png_ptr, info_ptr->unknown_chunks[num].data);
  178358. info_ptr->unknown_chunks[num].data = NULL;
  178359. }
  178360. }
  178361. else
  178362. {
  178363. int i;
  178364. if(info_ptr->unknown_chunks_num)
  178365. {
  178366. for (i = 0; i < (int)info_ptr->unknown_chunks_num; i++)
  178367. png_free_data(png_ptr, info_ptr, PNG_FREE_UNKN, i);
  178368. png_free(png_ptr, info_ptr->unknown_chunks);
  178369. info_ptr->unknown_chunks = NULL;
  178370. info_ptr->unknown_chunks_num = 0;
  178371. }
  178372. }
  178373. }
  178374. #endif
  178375. #if defined(PNG_hIST_SUPPORTED)
  178376. /* free any hIST entry */
  178377. #ifdef PNG_FREE_ME_SUPPORTED
  178378. if ((mask & PNG_FREE_HIST) & info_ptr->free_me)
  178379. #else
  178380. if ((mask & PNG_FREE_HIST) && (png_ptr->flags & PNG_FLAG_FREE_HIST))
  178381. #endif
  178382. {
  178383. png_free(png_ptr, info_ptr->hist);
  178384. info_ptr->hist = NULL;
  178385. info_ptr->valid &= ~PNG_INFO_hIST;
  178386. #ifndef PNG_FREE_ME_SUPPORTED
  178387. png_ptr->flags &= ~PNG_FLAG_FREE_HIST;
  178388. #endif
  178389. }
  178390. #endif
  178391. /* free any PLTE entry that was internally allocated */
  178392. #ifdef PNG_FREE_ME_SUPPORTED
  178393. if ((mask & PNG_FREE_PLTE) & info_ptr->free_me)
  178394. #else
  178395. if ((mask & PNG_FREE_PLTE) && (png_ptr->flags & PNG_FLAG_FREE_PLTE))
  178396. #endif
  178397. {
  178398. png_zfree(png_ptr, info_ptr->palette);
  178399. info_ptr->palette = NULL;
  178400. info_ptr->valid &= ~PNG_INFO_PLTE;
  178401. #ifndef PNG_FREE_ME_SUPPORTED
  178402. png_ptr->flags &= ~PNG_FLAG_FREE_PLTE;
  178403. #endif
  178404. info_ptr->num_palette = 0;
  178405. }
  178406. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  178407. /* free any image bits attached to the info structure */
  178408. #ifdef PNG_FREE_ME_SUPPORTED
  178409. if ((mask & PNG_FREE_ROWS) & info_ptr->free_me)
  178410. #else
  178411. if (mask & PNG_FREE_ROWS)
  178412. #endif
  178413. {
  178414. if(info_ptr->row_pointers)
  178415. {
  178416. int row;
  178417. for (row = 0; row < (int)info_ptr->height; row++)
  178418. {
  178419. png_free(png_ptr, info_ptr->row_pointers[row]);
  178420. info_ptr->row_pointers[row]=NULL;
  178421. }
  178422. png_free(png_ptr, info_ptr->row_pointers);
  178423. info_ptr->row_pointers=NULL;
  178424. }
  178425. info_ptr->valid &= ~PNG_INFO_IDAT;
  178426. }
  178427. #endif
  178428. #ifdef PNG_FREE_ME_SUPPORTED
  178429. if(num == -1)
  178430. info_ptr->free_me &= ~mask;
  178431. else
  178432. info_ptr->free_me &= ~(mask & ~PNG_FREE_MUL);
  178433. #endif
  178434. }
  178435. /* This is an internal routine to free any memory that the info struct is
  178436. * pointing to before re-using it or freeing the struct itself. Recall
  178437. * that png_free() checks for NULL pointers for us.
  178438. */
  178439. void /* PRIVATE */
  178440. png_info_destroy(png_structp png_ptr, png_infop info_ptr)
  178441. {
  178442. png_debug(1, "in png_info_destroy\n");
  178443. png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
  178444. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  178445. if (png_ptr->num_chunk_list)
  178446. {
  178447. png_free(png_ptr, png_ptr->chunk_list);
  178448. png_ptr->chunk_list=NULL;
  178449. png_ptr->num_chunk_list=0;
  178450. }
  178451. #endif
  178452. png_info_init_3(&info_ptr, png_sizeof(png_info));
  178453. }
  178454. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  178455. /* This function returns a pointer to the io_ptr associated with the user
  178456. * functions. The application should free any memory associated with this
  178457. * pointer before png_write_destroy() or png_read_destroy() are called.
  178458. */
  178459. png_voidp PNGAPI
  178460. png_get_io_ptr(png_structp png_ptr)
  178461. {
  178462. if(png_ptr == NULL) return (NULL);
  178463. return (png_ptr->io_ptr);
  178464. }
  178465. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  178466. #if !defined(PNG_NO_STDIO)
  178467. /* Initialize the default input/output functions for the PNG file. If you
  178468. * use your own read or write routines, you can call either png_set_read_fn()
  178469. * or png_set_write_fn() instead of png_init_io(). If you have defined
  178470. * PNG_NO_STDIO, you must use a function of your own because "FILE *" isn't
  178471. * necessarily available.
  178472. */
  178473. void PNGAPI
  178474. png_init_io(png_structp png_ptr, png_FILE_p fp)
  178475. {
  178476. png_debug(1, "in png_init_io\n");
  178477. if(png_ptr == NULL) return;
  178478. png_ptr->io_ptr = (png_voidp)fp;
  178479. }
  178480. #endif
  178481. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  178482. /* Convert the supplied time into an RFC 1123 string suitable for use in
  178483. * a "Creation Time" or other text-based time string.
  178484. */
  178485. png_charp PNGAPI
  178486. png_convert_to_rfc1123(png_structp png_ptr, png_timep ptime)
  178487. {
  178488. static PNG_CONST char short_months[12][4] =
  178489. {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
  178490. "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
  178491. if(png_ptr == NULL) return (NULL);
  178492. if (png_ptr->time_buffer == NULL)
  178493. {
  178494. png_ptr->time_buffer = (png_charp)png_malloc(png_ptr, (png_uint_32)(29*
  178495. png_sizeof(char)));
  178496. }
  178497. #if defined(_WIN32_WCE)
  178498. {
  178499. wchar_t time_buf[29];
  178500. wsprintf(time_buf, TEXT("%d %S %d %02d:%02d:%02d +0000"),
  178501. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  178502. ptime->year, ptime->hour % 24, ptime->minute % 60,
  178503. ptime->second % 61);
  178504. WideCharToMultiByte(CP_ACP, 0, time_buf, -1, png_ptr->time_buffer, 29,
  178505. NULL, NULL);
  178506. }
  178507. #else
  178508. #ifdef USE_FAR_KEYWORD
  178509. {
  178510. char near_time_buf[29];
  178511. png_snprintf6(near_time_buf,29,"%d %s %d %02d:%02d:%02d +0000",
  178512. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  178513. ptime->year, ptime->hour % 24, ptime->minute % 60,
  178514. ptime->second % 61);
  178515. png_memcpy(png_ptr->time_buffer, near_time_buf,
  178516. 29*png_sizeof(char));
  178517. }
  178518. #else
  178519. png_snprintf6(png_ptr->time_buffer,29,"%d %s %d %02d:%02d:%02d +0000",
  178520. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  178521. ptime->year, ptime->hour % 24, ptime->minute % 60,
  178522. ptime->second % 61);
  178523. #endif
  178524. #endif /* _WIN32_WCE */
  178525. return ((png_charp)png_ptr->time_buffer);
  178526. }
  178527. #endif /* PNG_TIME_RFC1123_SUPPORTED */
  178528. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  178529. png_charp PNGAPI
  178530. png_get_copyright(png_structp png_ptr)
  178531. {
  178532. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  178533. return ((png_charp) "\n libpng version 1.2.21 - October 4, 2007\n\
  178534. Copyright (c) 1998-2007 Glenn Randers-Pehrson\n\
  178535. Copyright (c) 1996-1997 Andreas Dilger\n\
  178536. Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc.\n");
  178537. }
  178538. /* The following return the library version as a short string in the
  178539. * format 1.0.0 through 99.99.99zz. To get the version of *.h files
  178540. * used with your application, print out PNG_LIBPNG_VER_STRING, which
  178541. * is defined in png.h.
  178542. * Note: now there is no difference between png_get_libpng_ver() and
  178543. * png_get_header_ver(). Due to the version_nn_nn_nn typedef guard,
  178544. * it is guaranteed that png.c uses the correct version of png.h.
  178545. */
  178546. png_charp PNGAPI
  178547. png_get_libpng_ver(png_structp png_ptr)
  178548. {
  178549. /* Version of *.c files used when building libpng */
  178550. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  178551. return ((png_charp) PNG_LIBPNG_VER_STRING);
  178552. }
  178553. png_charp PNGAPI
  178554. png_get_header_ver(png_structp png_ptr)
  178555. {
  178556. /* Version of *.h files used when building libpng */
  178557. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  178558. return ((png_charp) PNG_LIBPNG_VER_STRING);
  178559. }
  178560. png_charp PNGAPI
  178561. png_get_header_version(png_structp png_ptr)
  178562. {
  178563. /* Returns longer string containing both version and date */
  178564. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  178565. return ((png_charp) PNG_HEADER_VERSION_STRING
  178566. #ifndef PNG_READ_SUPPORTED
  178567. " (NO READ SUPPORT)"
  178568. #endif
  178569. "\n");
  178570. }
  178571. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  178572. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  178573. int PNGAPI
  178574. png_handle_as_unknown(png_structp png_ptr, png_bytep chunk_name)
  178575. {
  178576. /* check chunk_name and return "keep" value if it's on the list, else 0 */
  178577. int i;
  178578. png_bytep p;
  178579. if(png_ptr == NULL || chunk_name == NULL || png_ptr->num_chunk_list<=0)
  178580. return 0;
  178581. p=png_ptr->chunk_list+png_ptr->num_chunk_list*5-5;
  178582. for (i = png_ptr->num_chunk_list; i; i--, p-=5)
  178583. if (!png_memcmp(chunk_name, p, 4))
  178584. return ((int)*(p+4));
  178585. return 0;
  178586. }
  178587. #endif
  178588. /* This function, added to libpng-1.0.6g, is untested. */
  178589. int PNGAPI
  178590. png_reset_zstream(png_structp png_ptr)
  178591. {
  178592. if (png_ptr == NULL) return Z_STREAM_ERROR;
  178593. return (inflateReset(&png_ptr->zstream));
  178594. }
  178595. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  178596. /* This function was added to libpng-1.0.7 */
  178597. png_uint_32 PNGAPI
  178598. png_access_version_number(void)
  178599. {
  178600. /* Version of *.c files used when building libpng */
  178601. return((png_uint_32) PNG_LIBPNG_VER);
  178602. }
  178603. #if defined(PNG_READ_SUPPORTED) && defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  178604. #if !defined(PNG_1_0_X)
  178605. /* this function was added to libpng 1.2.0 */
  178606. int PNGAPI
  178607. png_mmx_support(void)
  178608. {
  178609. /* obsolete, to be removed from libpng-1.4.0 */
  178610. return -1;
  178611. }
  178612. #endif /* PNG_1_0_X */
  178613. #endif /* PNG_READ_SUPPORTED && PNG_ASSEMBLER_CODE_SUPPORTED */
  178614. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  178615. #ifdef PNG_SIZE_T
  178616. /* Added at libpng version 1.2.6 */
  178617. PNG_EXTERN png_size_t PNGAPI png_convert_size PNGARG((size_t size));
  178618. png_size_t PNGAPI
  178619. png_convert_size(size_t size)
  178620. {
  178621. if (size > (png_size_t)-1)
  178622. PNG_ABORT(); /* We haven't got access to png_ptr, so no png_error() */
  178623. return ((png_size_t)size);
  178624. }
  178625. #endif /* PNG_SIZE_T */
  178626. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  178627. /********* End of inlined file: png.c *********/
  178628. /********* Start of inlined file: pngerror.c *********/
  178629. /* pngerror.c - stub functions for i/o and memory allocation
  178630. *
  178631. * Last changed in libpng 1.2.20 October 4, 2007
  178632. * For conditions of distribution and use, see copyright notice in png.h
  178633. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  178634. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  178635. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  178636. *
  178637. * This file provides a location for all error handling. Users who
  178638. * need special error handling are expected to write replacement functions
  178639. * and use png_set_error_fn() to use those functions. See the instructions
  178640. * at each function.
  178641. */
  178642. #define PNG_INTERNAL
  178643. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  178644. static void /* PRIVATE */
  178645. png_default_error PNGARG((png_structp png_ptr,
  178646. png_const_charp error_message));
  178647. #ifndef PNG_NO_WARNINGS
  178648. static void /* PRIVATE */
  178649. png_default_warning PNGARG((png_structp png_ptr,
  178650. png_const_charp warning_message));
  178651. #endif /* PNG_NO_WARNINGS */
  178652. /* This function is called whenever there is a fatal error. This function
  178653. * should not be changed. If there is a need to handle errors differently,
  178654. * you should supply a replacement error function and use png_set_error_fn()
  178655. * to replace the error function at run-time.
  178656. */
  178657. #ifndef PNG_NO_ERROR_TEXT
  178658. void PNGAPI
  178659. png_error(png_structp png_ptr, png_const_charp error_message)
  178660. {
  178661. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  178662. char msg[16];
  178663. if (png_ptr != NULL)
  178664. {
  178665. if (png_ptr->flags&
  178666. (PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))
  178667. {
  178668. if (*error_message == '#')
  178669. {
  178670. int offset;
  178671. for (offset=1; offset<15; offset++)
  178672. if (*(error_message+offset) == ' ')
  178673. break;
  178674. if (png_ptr->flags&PNG_FLAG_STRIP_ERROR_TEXT)
  178675. {
  178676. int i;
  178677. for (i=0; i<offset-1; i++)
  178678. msg[i]=error_message[i+1];
  178679. msg[i]='\0';
  178680. error_message=msg;
  178681. }
  178682. else
  178683. error_message+=offset;
  178684. }
  178685. else
  178686. {
  178687. if (png_ptr->flags&PNG_FLAG_STRIP_ERROR_TEXT)
  178688. {
  178689. msg[0]='0';
  178690. msg[1]='\0';
  178691. error_message=msg;
  178692. }
  178693. }
  178694. }
  178695. }
  178696. #endif
  178697. if (png_ptr != NULL && png_ptr->error_fn != NULL)
  178698. (*(png_ptr->error_fn))(png_ptr, error_message);
  178699. /* If the custom handler doesn't exist, or if it returns,
  178700. use the default handler, which will not return. */
  178701. png_default_error(png_ptr, error_message);
  178702. }
  178703. #else
  178704. void PNGAPI
  178705. png_err(png_structp png_ptr)
  178706. {
  178707. if (png_ptr != NULL && png_ptr->error_fn != NULL)
  178708. (*(png_ptr->error_fn))(png_ptr, '\0');
  178709. /* If the custom handler doesn't exist, or if it returns,
  178710. use the default handler, which will not return. */
  178711. png_default_error(png_ptr, '\0');
  178712. }
  178713. #endif /* PNG_NO_ERROR_TEXT */
  178714. #ifndef PNG_NO_WARNINGS
  178715. /* This function is called whenever there is a non-fatal error. This function
  178716. * should not be changed. If there is a need to handle warnings differently,
  178717. * you should supply a replacement warning function and use
  178718. * png_set_error_fn() to replace the warning function at run-time.
  178719. */
  178720. void PNGAPI
  178721. png_warning(png_structp png_ptr, png_const_charp warning_message)
  178722. {
  178723. int offset = 0;
  178724. if (png_ptr != NULL)
  178725. {
  178726. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  178727. if (png_ptr->flags&
  178728. (PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))
  178729. #endif
  178730. {
  178731. if (*warning_message == '#')
  178732. {
  178733. for (offset=1; offset<15; offset++)
  178734. if (*(warning_message+offset) == ' ')
  178735. break;
  178736. }
  178737. }
  178738. if (png_ptr != NULL && png_ptr->warning_fn != NULL)
  178739. (*(png_ptr->warning_fn))(png_ptr, warning_message+offset);
  178740. }
  178741. else
  178742. png_default_warning(png_ptr, warning_message+offset);
  178743. }
  178744. #endif /* PNG_NO_WARNINGS */
  178745. /* These utilities are used internally to build an error message that relates
  178746. * to the current chunk. The chunk name comes from png_ptr->chunk_name,
  178747. * this is used to prefix the message. The message is limited in length
  178748. * to 63 bytes, the name characters are output as hex digits wrapped in []
  178749. * if the character is invalid.
  178750. */
  178751. #define isnonalpha(c) ((c) < 65 || (c) > 122 || ((c) > 90 && (c) < 97))
  178752. /*static PNG_CONST char png_digit[16] = {
  178753. '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
  178754. 'A', 'B', 'C', 'D', 'E', 'F'
  178755. };*/
  178756. #if !defined(PNG_NO_WARNINGS) || !defined(PNG_NO_ERROR_TEXT)
  178757. static void /* PRIVATE */
  178758. png_format_buffer(png_structp png_ptr, png_charp buffer, png_const_charp
  178759. error_message)
  178760. {
  178761. int iout = 0, iin = 0;
  178762. while (iin < 4)
  178763. {
  178764. int c = png_ptr->chunk_name[iin++];
  178765. if (isnonalpha(c))
  178766. {
  178767. buffer[iout++] = '[';
  178768. buffer[iout++] = png_digit[(c & 0xf0) >> 4];
  178769. buffer[iout++] = png_digit[c & 0x0f];
  178770. buffer[iout++] = ']';
  178771. }
  178772. else
  178773. {
  178774. buffer[iout++] = (png_byte)c;
  178775. }
  178776. }
  178777. if (error_message == NULL)
  178778. buffer[iout] = 0;
  178779. else
  178780. {
  178781. buffer[iout++] = ':';
  178782. buffer[iout++] = ' ';
  178783. png_strncpy(buffer+iout, error_message, 63);
  178784. buffer[iout+63] = 0;
  178785. }
  178786. }
  178787. #ifdef PNG_READ_SUPPORTED
  178788. void PNGAPI
  178789. png_chunk_error(png_structp png_ptr, png_const_charp error_message)
  178790. {
  178791. char msg[18+64];
  178792. if (png_ptr == NULL)
  178793. png_error(png_ptr, error_message);
  178794. else
  178795. {
  178796. png_format_buffer(png_ptr, msg, error_message);
  178797. png_error(png_ptr, msg);
  178798. }
  178799. }
  178800. #endif /* PNG_READ_SUPPORTED */
  178801. #endif /* !defined(PNG_NO_WARNINGS) || !defined(PNG_NO_ERROR_TEXT) */
  178802. #ifndef PNG_NO_WARNINGS
  178803. void PNGAPI
  178804. png_chunk_warning(png_structp png_ptr, png_const_charp warning_message)
  178805. {
  178806. char msg[18+64];
  178807. if (png_ptr == NULL)
  178808. png_warning(png_ptr, warning_message);
  178809. else
  178810. {
  178811. png_format_buffer(png_ptr, msg, warning_message);
  178812. png_warning(png_ptr, msg);
  178813. }
  178814. }
  178815. #endif /* PNG_NO_WARNINGS */
  178816. /* This is the default error handling function. Note that replacements for
  178817. * this function MUST NOT RETURN, or the program will likely crash. This
  178818. * function is used by default, or if the program supplies NULL for the
  178819. * error function pointer in png_set_error_fn().
  178820. */
  178821. static void /* PRIVATE */
  178822. png_default_error(png_structp png_ptr, png_const_charp error_message)
  178823. {
  178824. #ifndef PNG_NO_CONSOLE_IO
  178825. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  178826. if (*error_message == '#')
  178827. {
  178828. int offset;
  178829. char error_number[16];
  178830. for (offset=0; offset<15; offset++)
  178831. {
  178832. error_number[offset] = *(error_message+offset+1);
  178833. if (*(error_message+offset) == ' ')
  178834. break;
  178835. }
  178836. if((offset > 1) && (offset < 15))
  178837. {
  178838. error_number[offset-1]='\0';
  178839. fprintf(stderr, "libpng error no. %s: %s\n", error_number,
  178840. error_message+offset);
  178841. }
  178842. else
  178843. fprintf(stderr, "libpng error: %s, offset=%d\n", error_message,offset);
  178844. }
  178845. else
  178846. #endif
  178847. fprintf(stderr, "libpng error: %s\n", error_message);
  178848. #endif
  178849. #ifdef PNG_SETJMP_SUPPORTED
  178850. if (png_ptr)
  178851. {
  178852. # ifdef USE_FAR_KEYWORD
  178853. {
  178854. jmp_buf jmpbuf;
  178855. png_memcpy(jmpbuf, png_ptr->jmpbuf, png_sizeof(jmp_buf));
  178856. longjmp(jmpbuf, 1);
  178857. }
  178858. # else
  178859. longjmp(png_ptr->jmpbuf, 1);
  178860. # endif
  178861. }
  178862. #else
  178863. PNG_ABORT();
  178864. #endif
  178865. #ifdef PNG_NO_CONSOLE_IO
  178866. error_message = error_message; /* make compiler happy */
  178867. #endif
  178868. }
  178869. #ifndef PNG_NO_WARNINGS
  178870. /* This function is called when there is a warning, but the library thinks
  178871. * it can continue anyway. Replacement functions don't have to do anything
  178872. * here if you don't want them to. In the default configuration, png_ptr is
  178873. * not used, but it is passed in case it may be useful.
  178874. */
  178875. static void /* PRIVATE */
  178876. png_default_warning(png_structp png_ptr, png_const_charp warning_message)
  178877. {
  178878. #ifndef PNG_NO_CONSOLE_IO
  178879. # ifdef PNG_ERROR_NUMBERS_SUPPORTED
  178880. if (*warning_message == '#')
  178881. {
  178882. int offset;
  178883. char warning_number[16];
  178884. for (offset=0; offset<15; offset++)
  178885. {
  178886. warning_number[offset]=*(warning_message+offset+1);
  178887. if (*(warning_message+offset) == ' ')
  178888. break;
  178889. }
  178890. if((offset > 1) && (offset < 15))
  178891. {
  178892. warning_number[offset-1]='\0';
  178893. fprintf(stderr, "libpng warning no. %s: %s\n", warning_number,
  178894. warning_message+offset);
  178895. }
  178896. else
  178897. fprintf(stderr, "libpng warning: %s\n", warning_message);
  178898. }
  178899. else
  178900. # endif
  178901. fprintf(stderr, "libpng warning: %s\n", warning_message);
  178902. #else
  178903. warning_message = warning_message; /* make compiler happy */
  178904. #endif
  178905. png_ptr = png_ptr; /* make compiler happy */
  178906. }
  178907. #endif /* PNG_NO_WARNINGS */
  178908. /* This function is called when the application wants to use another method
  178909. * of handling errors and warnings. Note that the error function MUST NOT
  178910. * return to the calling routine or serious problems will occur. The return
  178911. * method used in the default routine calls longjmp(png_ptr->jmpbuf, 1)
  178912. */
  178913. void PNGAPI
  178914. png_set_error_fn(png_structp png_ptr, png_voidp error_ptr,
  178915. png_error_ptr error_fn, png_error_ptr warning_fn)
  178916. {
  178917. if (png_ptr == NULL)
  178918. return;
  178919. png_ptr->error_ptr = error_ptr;
  178920. png_ptr->error_fn = error_fn;
  178921. png_ptr->warning_fn = warning_fn;
  178922. }
  178923. /* This function returns a pointer to the error_ptr associated with the user
  178924. * functions. The application should free any memory associated with this
  178925. * pointer before png_write_destroy and png_read_destroy are called.
  178926. */
  178927. png_voidp PNGAPI
  178928. png_get_error_ptr(png_structp png_ptr)
  178929. {
  178930. if (png_ptr == NULL)
  178931. return NULL;
  178932. return ((png_voidp)png_ptr->error_ptr);
  178933. }
  178934. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  178935. void PNGAPI
  178936. png_set_strip_error_numbers(png_structp png_ptr, png_uint_32 strip_mode)
  178937. {
  178938. if(png_ptr != NULL)
  178939. {
  178940. png_ptr->flags &=
  178941. ((~(PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))&strip_mode);
  178942. }
  178943. }
  178944. #endif
  178945. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  178946. /********* End of inlined file: pngerror.c *********/
  178947. /********* Start of inlined file: pngget.c *********/
  178948. /* pngget.c - retrieval of values from info struct
  178949. *
  178950. * Last changed in libpng 1.2.15 January 5, 2007
  178951. * For conditions of distribution and use, see copyright notice in png.h
  178952. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  178953. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  178954. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  178955. */
  178956. #define PNG_INTERNAL
  178957. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  178958. png_uint_32 PNGAPI
  178959. png_get_valid(png_structp png_ptr, png_infop info_ptr, png_uint_32 flag)
  178960. {
  178961. if (png_ptr != NULL && info_ptr != NULL)
  178962. return(info_ptr->valid & flag);
  178963. else
  178964. return(0);
  178965. }
  178966. png_uint_32 PNGAPI
  178967. png_get_rowbytes(png_structp png_ptr, png_infop info_ptr)
  178968. {
  178969. if (png_ptr != NULL && info_ptr != NULL)
  178970. return(info_ptr->rowbytes);
  178971. else
  178972. return(0);
  178973. }
  178974. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  178975. png_bytepp PNGAPI
  178976. png_get_rows(png_structp png_ptr, png_infop info_ptr)
  178977. {
  178978. if (png_ptr != NULL && info_ptr != NULL)
  178979. return(info_ptr->row_pointers);
  178980. else
  178981. return(0);
  178982. }
  178983. #endif
  178984. #ifdef PNG_EASY_ACCESS_SUPPORTED
  178985. /* easy access to info, added in libpng-0.99 */
  178986. png_uint_32 PNGAPI
  178987. png_get_image_width(png_structp png_ptr, png_infop info_ptr)
  178988. {
  178989. if (png_ptr != NULL && info_ptr != NULL)
  178990. {
  178991. return info_ptr->width;
  178992. }
  178993. return (0);
  178994. }
  178995. png_uint_32 PNGAPI
  178996. png_get_image_height(png_structp png_ptr, png_infop info_ptr)
  178997. {
  178998. if (png_ptr != NULL && info_ptr != NULL)
  178999. {
  179000. return info_ptr->height;
  179001. }
  179002. return (0);
  179003. }
  179004. png_byte PNGAPI
  179005. png_get_bit_depth(png_structp png_ptr, png_infop info_ptr)
  179006. {
  179007. if (png_ptr != NULL && info_ptr != NULL)
  179008. {
  179009. return info_ptr->bit_depth;
  179010. }
  179011. return (0);
  179012. }
  179013. png_byte PNGAPI
  179014. png_get_color_type(png_structp png_ptr, png_infop info_ptr)
  179015. {
  179016. if (png_ptr != NULL && info_ptr != NULL)
  179017. {
  179018. return info_ptr->color_type;
  179019. }
  179020. return (0);
  179021. }
  179022. png_byte PNGAPI
  179023. png_get_filter_type(png_structp png_ptr, png_infop info_ptr)
  179024. {
  179025. if (png_ptr != NULL && info_ptr != NULL)
  179026. {
  179027. return info_ptr->filter_type;
  179028. }
  179029. return (0);
  179030. }
  179031. png_byte PNGAPI
  179032. png_get_interlace_type(png_structp png_ptr, png_infop info_ptr)
  179033. {
  179034. if (png_ptr != NULL && info_ptr != NULL)
  179035. {
  179036. return info_ptr->interlace_type;
  179037. }
  179038. return (0);
  179039. }
  179040. png_byte PNGAPI
  179041. png_get_compression_type(png_structp png_ptr, png_infop info_ptr)
  179042. {
  179043. if (png_ptr != NULL && info_ptr != NULL)
  179044. {
  179045. return info_ptr->compression_type;
  179046. }
  179047. return (0);
  179048. }
  179049. png_uint_32 PNGAPI
  179050. png_get_x_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  179051. {
  179052. if (png_ptr != NULL && info_ptr != NULL)
  179053. #if defined(PNG_pHYs_SUPPORTED)
  179054. if (info_ptr->valid & PNG_INFO_pHYs)
  179055. {
  179056. png_debug1(1, "in %s retrieval function\n", "png_get_x_pixels_per_meter");
  179057. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER)
  179058. return (0);
  179059. else return (info_ptr->x_pixels_per_unit);
  179060. }
  179061. #else
  179062. return (0);
  179063. #endif
  179064. return (0);
  179065. }
  179066. png_uint_32 PNGAPI
  179067. png_get_y_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  179068. {
  179069. if (png_ptr != NULL && info_ptr != NULL)
  179070. #if defined(PNG_pHYs_SUPPORTED)
  179071. if (info_ptr->valid & PNG_INFO_pHYs)
  179072. {
  179073. png_debug1(1, "in %s retrieval function\n", "png_get_y_pixels_per_meter");
  179074. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER)
  179075. return (0);
  179076. else return (info_ptr->y_pixels_per_unit);
  179077. }
  179078. #else
  179079. return (0);
  179080. #endif
  179081. return (0);
  179082. }
  179083. png_uint_32 PNGAPI
  179084. png_get_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  179085. {
  179086. if (png_ptr != NULL && info_ptr != NULL)
  179087. #if defined(PNG_pHYs_SUPPORTED)
  179088. if (info_ptr->valid & PNG_INFO_pHYs)
  179089. {
  179090. png_debug1(1, "in %s retrieval function\n", "png_get_pixels_per_meter");
  179091. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER ||
  179092. info_ptr->x_pixels_per_unit != info_ptr->y_pixels_per_unit)
  179093. return (0);
  179094. else return (info_ptr->x_pixels_per_unit);
  179095. }
  179096. #else
  179097. return (0);
  179098. #endif
  179099. return (0);
  179100. }
  179101. #ifdef PNG_FLOATING_POINT_SUPPORTED
  179102. float PNGAPI
  179103. png_get_pixel_aspect_ratio(png_structp png_ptr, png_infop info_ptr)
  179104. {
  179105. if (png_ptr != NULL && info_ptr != NULL)
  179106. #if defined(PNG_pHYs_SUPPORTED)
  179107. if (info_ptr->valid & PNG_INFO_pHYs)
  179108. {
  179109. png_debug1(1, "in %s retrieval function\n", "png_get_aspect_ratio");
  179110. if (info_ptr->x_pixels_per_unit == 0)
  179111. return ((float)0.0);
  179112. else
  179113. return ((float)((float)info_ptr->y_pixels_per_unit
  179114. /(float)info_ptr->x_pixels_per_unit));
  179115. }
  179116. #else
  179117. return (0.0);
  179118. #endif
  179119. return ((float)0.0);
  179120. }
  179121. #endif
  179122. png_int_32 PNGAPI
  179123. png_get_x_offset_microns(png_structp png_ptr, png_infop info_ptr)
  179124. {
  179125. if (png_ptr != NULL && info_ptr != NULL)
  179126. #if defined(PNG_oFFs_SUPPORTED)
  179127. if (info_ptr->valid & PNG_INFO_oFFs)
  179128. {
  179129. png_debug1(1, "in %s retrieval function\n", "png_get_x_offset_microns");
  179130. if(info_ptr->offset_unit_type != PNG_OFFSET_MICROMETER)
  179131. return (0);
  179132. else return (info_ptr->x_offset);
  179133. }
  179134. #else
  179135. return (0);
  179136. #endif
  179137. return (0);
  179138. }
  179139. png_int_32 PNGAPI
  179140. png_get_y_offset_microns(png_structp png_ptr, png_infop info_ptr)
  179141. {
  179142. if (png_ptr != NULL && info_ptr != NULL)
  179143. #if defined(PNG_oFFs_SUPPORTED)
  179144. if (info_ptr->valid & PNG_INFO_oFFs)
  179145. {
  179146. png_debug1(1, "in %s retrieval function\n", "png_get_y_offset_microns");
  179147. if(info_ptr->offset_unit_type != PNG_OFFSET_MICROMETER)
  179148. return (0);
  179149. else return (info_ptr->y_offset);
  179150. }
  179151. #else
  179152. return (0);
  179153. #endif
  179154. return (0);
  179155. }
  179156. png_int_32 PNGAPI
  179157. png_get_x_offset_pixels(png_structp png_ptr, png_infop info_ptr)
  179158. {
  179159. if (png_ptr != NULL && info_ptr != NULL)
  179160. #if defined(PNG_oFFs_SUPPORTED)
  179161. if (info_ptr->valid & PNG_INFO_oFFs)
  179162. {
  179163. png_debug1(1, "in %s retrieval function\n", "png_get_x_offset_microns");
  179164. if(info_ptr->offset_unit_type != PNG_OFFSET_PIXEL)
  179165. return (0);
  179166. else return (info_ptr->x_offset);
  179167. }
  179168. #else
  179169. return (0);
  179170. #endif
  179171. return (0);
  179172. }
  179173. png_int_32 PNGAPI
  179174. png_get_y_offset_pixels(png_structp png_ptr, png_infop info_ptr)
  179175. {
  179176. if (png_ptr != NULL && info_ptr != NULL)
  179177. #if defined(PNG_oFFs_SUPPORTED)
  179178. if (info_ptr->valid & PNG_INFO_oFFs)
  179179. {
  179180. png_debug1(1, "in %s retrieval function\n", "png_get_y_offset_microns");
  179181. if(info_ptr->offset_unit_type != PNG_OFFSET_PIXEL)
  179182. return (0);
  179183. else return (info_ptr->y_offset);
  179184. }
  179185. #else
  179186. return (0);
  179187. #endif
  179188. return (0);
  179189. }
  179190. #if defined(PNG_INCH_CONVERSIONS) && defined(PNG_FLOATING_POINT_SUPPORTED)
  179191. png_uint_32 PNGAPI
  179192. png_get_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  179193. {
  179194. return ((png_uint_32)((float)png_get_pixels_per_meter(png_ptr, info_ptr)
  179195. *.0254 +.5));
  179196. }
  179197. png_uint_32 PNGAPI
  179198. png_get_x_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  179199. {
  179200. return ((png_uint_32)((float)png_get_x_pixels_per_meter(png_ptr, info_ptr)
  179201. *.0254 +.5));
  179202. }
  179203. png_uint_32 PNGAPI
  179204. png_get_y_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  179205. {
  179206. return ((png_uint_32)((float)png_get_y_pixels_per_meter(png_ptr, info_ptr)
  179207. *.0254 +.5));
  179208. }
  179209. float PNGAPI
  179210. png_get_x_offset_inches(png_structp png_ptr, png_infop info_ptr)
  179211. {
  179212. return ((float)png_get_x_offset_microns(png_ptr, info_ptr)
  179213. *.00003937);
  179214. }
  179215. float PNGAPI
  179216. png_get_y_offset_inches(png_structp png_ptr, png_infop info_ptr)
  179217. {
  179218. return ((float)png_get_y_offset_microns(png_ptr, info_ptr)
  179219. *.00003937);
  179220. }
  179221. #if defined(PNG_pHYs_SUPPORTED)
  179222. png_uint_32 PNGAPI
  179223. png_get_pHYs_dpi(png_structp png_ptr, png_infop info_ptr,
  179224. png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type)
  179225. {
  179226. png_uint_32 retval = 0;
  179227. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_pHYs))
  179228. {
  179229. png_debug1(1, "in %s retrieval function\n", "pHYs");
  179230. if (res_x != NULL)
  179231. {
  179232. *res_x = info_ptr->x_pixels_per_unit;
  179233. retval |= PNG_INFO_pHYs;
  179234. }
  179235. if (res_y != NULL)
  179236. {
  179237. *res_y = info_ptr->y_pixels_per_unit;
  179238. retval |= PNG_INFO_pHYs;
  179239. }
  179240. if (unit_type != NULL)
  179241. {
  179242. *unit_type = (int)info_ptr->phys_unit_type;
  179243. retval |= PNG_INFO_pHYs;
  179244. if(*unit_type == 1)
  179245. {
  179246. if (res_x != NULL) *res_x = (png_uint_32)(*res_x * .0254 + .50);
  179247. if (res_y != NULL) *res_y = (png_uint_32)(*res_y * .0254 + .50);
  179248. }
  179249. }
  179250. }
  179251. return (retval);
  179252. }
  179253. #endif /* PNG_pHYs_SUPPORTED */
  179254. #endif /* PNG_INCH_CONVERSIONS && PNG_FLOATING_POINT_SUPPORTED */
  179255. /* png_get_channels really belongs in here, too, but it's been around longer */
  179256. #endif /* PNG_EASY_ACCESS_SUPPORTED */
  179257. png_byte PNGAPI
  179258. png_get_channels(png_structp png_ptr, png_infop info_ptr)
  179259. {
  179260. if (png_ptr != NULL && info_ptr != NULL)
  179261. return(info_ptr->channels);
  179262. else
  179263. return (0);
  179264. }
  179265. png_bytep PNGAPI
  179266. png_get_signature(png_structp png_ptr, png_infop info_ptr)
  179267. {
  179268. if (png_ptr != NULL && info_ptr != NULL)
  179269. return(info_ptr->signature);
  179270. else
  179271. return (NULL);
  179272. }
  179273. #if defined(PNG_bKGD_SUPPORTED)
  179274. png_uint_32 PNGAPI
  179275. png_get_bKGD(png_structp png_ptr, png_infop info_ptr,
  179276. png_color_16p *background)
  179277. {
  179278. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_bKGD)
  179279. && background != NULL)
  179280. {
  179281. png_debug1(1, "in %s retrieval function\n", "bKGD");
  179282. *background = &(info_ptr->background);
  179283. return (PNG_INFO_bKGD);
  179284. }
  179285. return (0);
  179286. }
  179287. #endif
  179288. #if defined(PNG_cHRM_SUPPORTED)
  179289. #ifdef PNG_FLOATING_POINT_SUPPORTED
  179290. png_uint_32 PNGAPI
  179291. png_get_cHRM(png_structp png_ptr, png_infop info_ptr,
  179292. double *white_x, double *white_y, double *red_x, double *red_y,
  179293. double *green_x, double *green_y, double *blue_x, double *blue_y)
  179294. {
  179295. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  179296. {
  179297. png_debug1(1, "in %s retrieval function\n", "cHRM");
  179298. if (white_x != NULL)
  179299. *white_x = (double)info_ptr->x_white;
  179300. if (white_y != NULL)
  179301. *white_y = (double)info_ptr->y_white;
  179302. if (red_x != NULL)
  179303. *red_x = (double)info_ptr->x_red;
  179304. if (red_y != NULL)
  179305. *red_y = (double)info_ptr->y_red;
  179306. if (green_x != NULL)
  179307. *green_x = (double)info_ptr->x_green;
  179308. if (green_y != NULL)
  179309. *green_y = (double)info_ptr->y_green;
  179310. if (blue_x != NULL)
  179311. *blue_x = (double)info_ptr->x_blue;
  179312. if (blue_y != NULL)
  179313. *blue_y = (double)info_ptr->y_blue;
  179314. return (PNG_INFO_cHRM);
  179315. }
  179316. return (0);
  179317. }
  179318. #endif
  179319. #ifdef PNG_FIXED_POINT_SUPPORTED
  179320. png_uint_32 PNGAPI
  179321. png_get_cHRM_fixed(png_structp png_ptr, png_infop info_ptr,
  179322. png_fixed_point *white_x, png_fixed_point *white_y, png_fixed_point *red_x,
  179323. png_fixed_point *red_y, png_fixed_point *green_x, png_fixed_point *green_y,
  179324. png_fixed_point *blue_x, png_fixed_point *blue_y)
  179325. {
  179326. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  179327. {
  179328. png_debug1(1, "in %s retrieval function\n", "cHRM");
  179329. if (white_x != NULL)
  179330. *white_x = info_ptr->int_x_white;
  179331. if (white_y != NULL)
  179332. *white_y = info_ptr->int_y_white;
  179333. if (red_x != NULL)
  179334. *red_x = info_ptr->int_x_red;
  179335. if (red_y != NULL)
  179336. *red_y = info_ptr->int_y_red;
  179337. if (green_x != NULL)
  179338. *green_x = info_ptr->int_x_green;
  179339. if (green_y != NULL)
  179340. *green_y = info_ptr->int_y_green;
  179341. if (blue_x != NULL)
  179342. *blue_x = info_ptr->int_x_blue;
  179343. if (blue_y != NULL)
  179344. *blue_y = info_ptr->int_y_blue;
  179345. return (PNG_INFO_cHRM);
  179346. }
  179347. return (0);
  179348. }
  179349. #endif
  179350. #endif
  179351. #if defined(PNG_gAMA_SUPPORTED)
  179352. #ifdef PNG_FLOATING_POINT_SUPPORTED
  179353. png_uint_32 PNGAPI
  179354. png_get_gAMA(png_structp png_ptr, png_infop info_ptr, double *file_gamma)
  179355. {
  179356. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  179357. && file_gamma != NULL)
  179358. {
  179359. png_debug1(1, "in %s retrieval function\n", "gAMA");
  179360. *file_gamma = (double)info_ptr->gamma;
  179361. return (PNG_INFO_gAMA);
  179362. }
  179363. return (0);
  179364. }
  179365. #endif
  179366. #ifdef PNG_FIXED_POINT_SUPPORTED
  179367. png_uint_32 PNGAPI
  179368. png_get_gAMA_fixed(png_structp png_ptr, png_infop info_ptr,
  179369. png_fixed_point *int_file_gamma)
  179370. {
  179371. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  179372. && int_file_gamma != NULL)
  179373. {
  179374. png_debug1(1, "in %s retrieval function\n", "gAMA");
  179375. *int_file_gamma = info_ptr->int_gamma;
  179376. return (PNG_INFO_gAMA);
  179377. }
  179378. return (0);
  179379. }
  179380. #endif
  179381. #endif
  179382. #if defined(PNG_sRGB_SUPPORTED)
  179383. png_uint_32 PNGAPI
  179384. png_get_sRGB(png_structp png_ptr, png_infop info_ptr, int *file_srgb_intent)
  179385. {
  179386. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB)
  179387. && file_srgb_intent != NULL)
  179388. {
  179389. png_debug1(1, "in %s retrieval function\n", "sRGB");
  179390. *file_srgb_intent = (int)info_ptr->srgb_intent;
  179391. return (PNG_INFO_sRGB);
  179392. }
  179393. return (0);
  179394. }
  179395. #endif
  179396. #if defined(PNG_iCCP_SUPPORTED)
  179397. png_uint_32 PNGAPI
  179398. png_get_iCCP(png_structp png_ptr, png_infop info_ptr,
  179399. png_charpp name, int *compression_type,
  179400. png_charpp profile, png_uint_32 *proflen)
  179401. {
  179402. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_iCCP)
  179403. && name != NULL && profile != NULL && proflen != NULL)
  179404. {
  179405. png_debug1(1, "in %s retrieval function\n", "iCCP");
  179406. *name = info_ptr->iccp_name;
  179407. *profile = info_ptr->iccp_profile;
  179408. /* compression_type is a dummy so the API won't have to change
  179409. if we introduce multiple compression types later. */
  179410. *proflen = (int)info_ptr->iccp_proflen;
  179411. *compression_type = (int)info_ptr->iccp_compression;
  179412. return (PNG_INFO_iCCP);
  179413. }
  179414. return (0);
  179415. }
  179416. #endif
  179417. #if defined(PNG_sPLT_SUPPORTED)
  179418. png_uint_32 PNGAPI
  179419. png_get_sPLT(png_structp png_ptr, png_infop info_ptr,
  179420. png_sPLT_tpp spalettes)
  179421. {
  179422. if (png_ptr != NULL && info_ptr != NULL && spalettes != NULL)
  179423. {
  179424. *spalettes = info_ptr->splt_palettes;
  179425. return ((png_uint_32)info_ptr->splt_palettes_num);
  179426. }
  179427. return (0);
  179428. }
  179429. #endif
  179430. #if defined(PNG_hIST_SUPPORTED)
  179431. png_uint_32 PNGAPI
  179432. png_get_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_16p *hist)
  179433. {
  179434. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_hIST)
  179435. && hist != NULL)
  179436. {
  179437. png_debug1(1, "in %s retrieval function\n", "hIST");
  179438. *hist = info_ptr->hist;
  179439. return (PNG_INFO_hIST);
  179440. }
  179441. return (0);
  179442. }
  179443. #endif
  179444. png_uint_32 PNGAPI
  179445. png_get_IHDR(png_structp png_ptr, png_infop info_ptr,
  179446. png_uint_32 *width, png_uint_32 *height, int *bit_depth,
  179447. int *color_type, int *interlace_type, int *compression_type,
  179448. int *filter_type)
  179449. {
  179450. if (png_ptr != NULL && info_ptr != NULL && width != NULL && height != NULL &&
  179451. bit_depth != NULL && color_type != NULL)
  179452. {
  179453. png_debug1(1, "in %s retrieval function\n", "IHDR");
  179454. *width = info_ptr->width;
  179455. *height = info_ptr->height;
  179456. *bit_depth = info_ptr->bit_depth;
  179457. if (info_ptr->bit_depth < 1 || info_ptr->bit_depth > 16)
  179458. png_error(png_ptr, "Invalid bit depth");
  179459. *color_type = info_ptr->color_type;
  179460. if (info_ptr->color_type > 6)
  179461. png_error(png_ptr, "Invalid color type");
  179462. if (compression_type != NULL)
  179463. *compression_type = info_ptr->compression_type;
  179464. if (filter_type != NULL)
  179465. *filter_type = info_ptr->filter_type;
  179466. if (interlace_type != NULL)
  179467. *interlace_type = info_ptr->interlace_type;
  179468. /* check for potential overflow of rowbytes */
  179469. if (*width == 0 || *width > PNG_UINT_31_MAX)
  179470. png_error(png_ptr, "Invalid image width");
  179471. if (*height == 0 || *height > PNG_UINT_31_MAX)
  179472. png_error(png_ptr, "Invalid image height");
  179473. if (info_ptr->width > (PNG_UINT_32_MAX
  179474. >> 3) /* 8-byte RGBA pixels */
  179475. - 64 /* bigrowbuf hack */
  179476. - 1 /* filter byte */
  179477. - 7*8 /* rounding of width to multiple of 8 pixels */
  179478. - 8) /* extra max_pixel_depth pad */
  179479. {
  179480. png_warning(png_ptr,
  179481. "Width too large for libpng to process image data.");
  179482. }
  179483. return (1);
  179484. }
  179485. return (0);
  179486. }
  179487. #if defined(PNG_oFFs_SUPPORTED)
  179488. png_uint_32 PNGAPI
  179489. png_get_oFFs(png_structp png_ptr, png_infop info_ptr,
  179490. png_int_32 *offset_x, png_int_32 *offset_y, int *unit_type)
  179491. {
  179492. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_oFFs)
  179493. && offset_x != NULL && offset_y != NULL && unit_type != NULL)
  179494. {
  179495. png_debug1(1, "in %s retrieval function\n", "oFFs");
  179496. *offset_x = info_ptr->x_offset;
  179497. *offset_y = info_ptr->y_offset;
  179498. *unit_type = (int)info_ptr->offset_unit_type;
  179499. return (PNG_INFO_oFFs);
  179500. }
  179501. return (0);
  179502. }
  179503. #endif
  179504. #if defined(PNG_pCAL_SUPPORTED)
  179505. png_uint_32 PNGAPI
  179506. png_get_pCAL(png_structp png_ptr, png_infop info_ptr,
  179507. png_charp *purpose, png_int_32 *X0, png_int_32 *X1, int *type, int *nparams,
  179508. png_charp *units, png_charpp *params)
  179509. {
  179510. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_pCAL)
  179511. && purpose != NULL && X0 != NULL && X1 != NULL && type != NULL &&
  179512. nparams != NULL && units != NULL && params != NULL)
  179513. {
  179514. png_debug1(1, "in %s retrieval function\n", "pCAL");
  179515. *purpose = info_ptr->pcal_purpose;
  179516. *X0 = info_ptr->pcal_X0;
  179517. *X1 = info_ptr->pcal_X1;
  179518. *type = (int)info_ptr->pcal_type;
  179519. *nparams = (int)info_ptr->pcal_nparams;
  179520. *units = info_ptr->pcal_units;
  179521. *params = info_ptr->pcal_params;
  179522. return (PNG_INFO_pCAL);
  179523. }
  179524. return (0);
  179525. }
  179526. #endif
  179527. #if defined(PNG_sCAL_SUPPORTED)
  179528. #ifdef PNG_FLOATING_POINT_SUPPORTED
  179529. png_uint_32 PNGAPI
  179530. png_get_sCAL(png_structp png_ptr, png_infop info_ptr,
  179531. int *unit, double *width, double *height)
  179532. {
  179533. if (png_ptr != NULL && info_ptr != NULL &&
  179534. (info_ptr->valid & PNG_INFO_sCAL))
  179535. {
  179536. *unit = info_ptr->scal_unit;
  179537. *width = info_ptr->scal_pixel_width;
  179538. *height = info_ptr->scal_pixel_height;
  179539. return (PNG_INFO_sCAL);
  179540. }
  179541. return(0);
  179542. }
  179543. #else
  179544. #ifdef PNG_FIXED_POINT_SUPPORTED
  179545. png_uint_32 PNGAPI
  179546. png_get_sCAL_s(png_structp png_ptr, png_infop info_ptr,
  179547. int *unit, png_charpp width, png_charpp height)
  179548. {
  179549. if (png_ptr != NULL && info_ptr != NULL &&
  179550. (info_ptr->valid & PNG_INFO_sCAL))
  179551. {
  179552. *unit = info_ptr->scal_unit;
  179553. *width = info_ptr->scal_s_width;
  179554. *height = info_ptr->scal_s_height;
  179555. return (PNG_INFO_sCAL);
  179556. }
  179557. return(0);
  179558. }
  179559. #endif
  179560. #endif
  179561. #endif
  179562. #if defined(PNG_pHYs_SUPPORTED)
  179563. png_uint_32 PNGAPI
  179564. png_get_pHYs(png_structp png_ptr, png_infop info_ptr,
  179565. png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type)
  179566. {
  179567. png_uint_32 retval = 0;
  179568. if (png_ptr != NULL && info_ptr != NULL &&
  179569. (info_ptr->valid & PNG_INFO_pHYs))
  179570. {
  179571. png_debug1(1, "in %s retrieval function\n", "pHYs");
  179572. if (res_x != NULL)
  179573. {
  179574. *res_x = info_ptr->x_pixels_per_unit;
  179575. retval |= PNG_INFO_pHYs;
  179576. }
  179577. if (res_y != NULL)
  179578. {
  179579. *res_y = info_ptr->y_pixels_per_unit;
  179580. retval |= PNG_INFO_pHYs;
  179581. }
  179582. if (unit_type != NULL)
  179583. {
  179584. *unit_type = (int)info_ptr->phys_unit_type;
  179585. retval |= PNG_INFO_pHYs;
  179586. }
  179587. }
  179588. return (retval);
  179589. }
  179590. #endif
  179591. png_uint_32 PNGAPI
  179592. png_get_PLTE(png_structp png_ptr, png_infop info_ptr, png_colorp *palette,
  179593. int *num_palette)
  179594. {
  179595. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_PLTE)
  179596. && palette != NULL)
  179597. {
  179598. png_debug1(1, "in %s retrieval function\n", "PLTE");
  179599. *palette = info_ptr->palette;
  179600. *num_palette = info_ptr->num_palette;
  179601. png_debug1(3, "num_palette = %d\n", *num_palette);
  179602. return (PNG_INFO_PLTE);
  179603. }
  179604. return (0);
  179605. }
  179606. #if defined(PNG_sBIT_SUPPORTED)
  179607. png_uint_32 PNGAPI
  179608. png_get_sBIT(png_structp png_ptr, png_infop info_ptr, png_color_8p *sig_bit)
  179609. {
  179610. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_sBIT)
  179611. && sig_bit != NULL)
  179612. {
  179613. png_debug1(1, "in %s retrieval function\n", "sBIT");
  179614. *sig_bit = &(info_ptr->sig_bit);
  179615. return (PNG_INFO_sBIT);
  179616. }
  179617. return (0);
  179618. }
  179619. #endif
  179620. #if defined(PNG_TEXT_SUPPORTED)
  179621. png_uint_32 PNGAPI
  179622. png_get_text(png_structp png_ptr, png_infop info_ptr, png_textp *text_ptr,
  179623. int *num_text)
  179624. {
  179625. if (png_ptr != NULL && info_ptr != NULL && info_ptr->num_text > 0)
  179626. {
  179627. png_debug1(1, "in %s retrieval function\n",
  179628. (png_ptr->chunk_name[0] == '\0' ? "text"
  179629. : (png_const_charp)png_ptr->chunk_name));
  179630. if (text_ptr != NULL)
  179631. *text_ptr = info_ptr->text;
  179632. if (num_text != NULL)
  179633. *num_text = info_ptr->num_text;
  179634. return ((png_uint_32)info_ptr->num_text);
  179635. }
  179636. if (num_text != NULL)
  179637. *num_text = 0;
  179638. return(0);
  179639. }
  179640. #endif
  179641. #if defined(PNG_tIME_SUPPORTED)
  179642. png_uint_32 PNGAPI
  179643. png_get_tIME(png_structp png_ptr, png_infop info_ptr, png_timep *mod_time)
  179644. {
  179645. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_tIME)
  179646. && mod_time != NULL)
  179647. {
  179648. png_debug1(1, "in %s retrieval function\n", "tIME");
  179649. *mod_time = &(info_ptr->mod_time);
  179650. return (PNG_INFO_tIME);
  179651. }
  179652. return (0);
  179653. }
  179654. #endif
  179655. #if defined(PNG_tRNS_SUPPORTED)
  179656. png_uint_32 PNGAPI
  179657. png_get_tRNS(png_structp png_ptr, png_infop info_ptr,
  179658. png_bytep *trans, int *num_trans, png_color_16p *trans_values)
  179659. {
  179660. png_uint_32 retval = 0;
  179661. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  179662. {
  179663. png_debug1(1, "in %s retrieval function\n", "tRNS");
  179664. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  179665. {
  179666. if (trans != NULL)
  179667. {
  179668. *trans = info_ptr->trans;
  179669. retval |= PNG_INFO_tRNS;
  179670. }
  179671. if (trans_values != NULL)
  179672. *trans_values = &(info_ptr->trans_values);
  179673. }
  179674. else /* if (info_ptr->color_type != PNG_COLOR_TYPE_PALETTE) */
  179675. {
  179676. if (trans_values != NULL)
  179677. {
  179678. *trans_values = &(info_ptr->trans_values);
  179679. retval |= PNG_INFO_tRNS;
  179680. }
  179681. if(trans != NULL)
  179682. *trans = NULL;
  179683. }
  179684. if(num_trans != NULL)
  179685. {
  179686. *num_trans = info_ptr->num_trans;
  179687. retval |= PNG_INFO_tRNS;
  179688. }
  179689. }
  179690. return (retval);
  179691. }
  179692. #endif
  179693. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  179694. png_uint_32 PNGAPI
  179695. png_get_unknown_chunks(png_structp png_ptr, png_infop info_ptr,
  179696. png_unknown_chunkpp unknowns)
  179697. {
  179698. if (png_ptr != NULL && info_ptr != NULL && unknowns != NULL)
  179699. {
  179700. *unknowns = info_ptr->unknown_chunks;
  179701. return ((png_uint_32)info_ptr->unknown_chunks_num);
  179702. }
  179703. return (0);
  179704. }
  179705. #endif
  179706. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  179707. png_byte PNGAPI
  179708. png_get_rgb_to_gray_status (png_structp png_ptr)
  179709. {
  179710. return (png_byte)(png_ptr? png_ptr->rgb_to_gray_status : 0);
  179711. }
  179712. #endif
  179713. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  179714. png_voidp PNGAPI
  179715. png_get_user_chunk_ptr(png_structp png_ptr)
  179716. {
  179717. return (png_ptr? png_ptr->user_chunk_ptr : NULL);
  179718. }
  179719. #endif
  179720. #ifdef PNG_WRITE_SUPPORTED
  179721. png_uint_32 PNGAPI
  179722. png_get_compression_buffer_size(png_structp png_ptr)
  179723. {
  179724. return (png_uint_32)(png_ptr? png_ptr->zbuf_size : 0L);
  179725. }
  179726. #endif
  179727. #ifdef PNG_ASSEMBLER_CODE_SUPPORTED
  179728. #ifndef PNG_1_0_X
  179729. /* this function was added to libpng 1.2.0 and should exist by default */
  179730. png_uint_32 PNGAPI
  179731. png_get_asm_flags (png_structp png_ptr)
  179732. {
  179733. /* obsolete, to be removed from libpng-1.4.0 */
  179734. return (png_ptr? 0L: 0L);
  179735. }
  179736. /* this function was added to libpng 1.2.0 and should exist by default */
  179737. png_uint_32 PNGAPI
  179738. png_get_asm_flagmask (int flag_select)
  179739. {
  179740. /* obsolete, to be removed from libpng-1.4.0 */
  179741. flag_select=flag_select;
  179742. return 0L;
  179743. }
  179744. /* GRR: could add this: && defined(PNG_MMX_CODE_SUPPORTED) */
  179745. /* this function was added to libpng 1.2.0 */
  179746. png_uint_32 PNGAPI
  179747. png_get_mmx_flagmask (int flag_select, int *compilerID)
  179748. {
  179749. /* obsolete, to be removed from libpng-1.4.0 */
  179750. flag_select=flag_select;
  179751. *compilerID = -1; /* unknown (i.e., no asm/MMX code compiled) */
  179752. return 0L;
  179753. }
  179754. /* this function was added to libpng 1.2.0 */
  179755. png_byte PNGAPI
  179756. png_get_mmx_bitdepth_threshold (png_structp png_ptr)
  179757. {
  179758. /* obsolete, to be removed from libpng-1.4.0 */
  179759. return (png_ptr? 0: 0);
  179760. }
  179761. /* this function was added to libpng 1.2.0 */
  179762. png_uint_32 PNGAPI
  179763. png_get_mmx_rowbytes_threshold (png_structp png_ptr)
  179764. {
  179765. /* obsolete, to be removed from libpng-1.4.0 */
  179766. return (png_ptr? 0L: 0L);
  179767. }
  179768. #endif /* ?PNG_1_0_X */
  179769. #endif /* ?PNG_ASSEMBLER_CODE_SUPPORTED */
  179770. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  179771. /* these functions were added to libpng 1.2.6 */
  179772. png_uint_32 PNGAPI
  179773. png_get_user_width_max (png_structp png_ptr)
  179774. {
  179775. return (png_ptr? png_ptr->user_width_max : 0);
  179776. }
  179777. png_uint_32 PNGAPI
  179778. png_get_user_height_max (png_structp png_ptr)
  179779. {
  179780. return (png_ptr? png_ptr->user_height_max : 0);
  179781. }
  179782. #endif /* ?PNG_SET_USER_LIMITS_SUPPORTED */
  179783. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  179784. /********* End of inlined file: pngget.c *********/
  179785. /********* Start of inlined file: pngmem.c *********/
  179786. /* pngmem.c - stub functions for memory allocation
  179787. *
  179788. * Last changed in libpng 1.2.13 November 13, 2006
  179789. * For conditions of distribution and use, see copyright notice in png.h
  179790. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  179791. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  179792. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  179793. *
  179794. * This file provides a location for all memory allocation. Users who
  179795. * need special memory handling are expected to supply replacement
  179796. * functions for png_malloc() and png_free(), and to use
  179797. * png_create_read_struct_2() and png_create_write_struct_2() to
  179798. * identify the replacement functions.
  179799. */
  179800. #define PNG_INTERNAL
  179801. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  179802. /* Borland DOS special memory handler */
  179803. #if defined(__TURBOC__) && !defined(_Windows) && !defined(__FLAT__)
  179804. /* if you change this, be sure to change the one in png.h also */
  179805. /* Allocate memory for a png_struct. The malloc and memset can be replaced
  179806. by a single call to calloc() if this is thought to improve performance. */
  179807. png_voidp /* PRIVATE */
  179808. png_create_struct(int type)
  179809. {
  179810. #ifdef PNG_USER_MEM_SUPPORTED
  179811. return (png_create_struct_2(type, png_malloc_ptr_NULL, png_voidp_NULL));
  179812. }
  179813. /* Alternate version of png_create_struct, for use with user-defined malloc. */
  179814. png_voidp /* PRIVATE */
  179815. png_create_struct_2(int type, png_malloc_ptr malloc_fn, png_voidp mem_ptr)
  179816. {
  179817. #endif /* PNG_USER_MEM_SUPPORTED */
  179818. png_size_t size;
  179819. png_voidp struct_ptr;
  179820. if (type == PNG_STRUCT_INFO)
  179821. size = png_sizeof(png_info);
  179822. else if (type == PNG_STRUCT_PNG)
  179823. size = png_sizeof(png_struct);
  179824. else
  179825. return (png_get_copyright(NULL));
  179826. #ifdef PNG_USER_MEM_SUPPORTED
  179827. if(malloc_fn != NULL)
  179828. {
  179829. png_struct dummy_struct;
  179830. png_structp png_ptr = &dummy_struct;
  179831. png_ptr->mem_ptr=mem_ptr;
  179832. struct_ptr = (*(malloc_fn))(png_ptr, (png_uint_32)size);
  179833. }
  179834. else
  179835. #endif /* PNG_USER_MEM_SUPPORTED */
  179836. struct_ptr = (png_voidp)farmalloc(size);
  179837. if (struct_ptr != NULL)
  179838. png_memset(struct_ptr, 0, size);
  179839. return (struct_ptr);
  179840. }
  179841. /* Free memory allocated by a png_create_struct() call */
  179842. void /* PRIVATE */
  179843. png_destroy_struct(png_voidp struct_ptr)
  179844. {
  179845. #ifdef PNG_USER_MEM_SUPPORTED
  179846. png_destroy_struct_2(struct_ptr, png_free_ptr_NULL, png_voidp_NULL);
  179847. }
  179848. /* Free memory allocated by a png_create_struct() call */
  179849. void /* PRIVATE */
  179850. png_destroy_struct_2(png_voidp struct_ptr, png_free_ptr free_fn,
  179851. png_voidp mem_ptr)
  179852. {
  179853. #endif
  179854. if (struct_ptr != NULL)
  179855. {
  179856. #ifdef PNG_USER_MEM_SUPPORTED
  179857. if(free_fn != NULL)
  179858. {
  179859. png_struct dummy_struct;
  179860. png_structp png_ptr = &dummy_struct;
  179861. png_ptr->mem_ptr=mem_ptr;
  179862. (*(free_fn))(png_ptr, struct_ptr);
  179863. return;
  179864. }
  179865. #endif /* PNG_USER_MEM_SUPPORTED */
  179866. farfree (struct_ptr);
  179867. }
  179868. }
  179869. /* Allocate memory. For reasonable files, size should never exceed
  179870. * 64K. However, zlib may allocate more then 64K if you don't tell
  179871. * it not to. See zconf.h and png.h for more information. zlib does
  179872. * need to allocate exactly 64K, so whatever you call here must
  179873. * have the ability to do that.
  179874. *
  179875. * Borland seems to have a problem in DOS mode for exactly 64K.
  179876. * It gives you a segment with an offset of 8 (perhaps to store its
  179877. * memory stuff). zlib doesn't like this at all, so we have to
  179878. * detect and deal with it. This code should not be needed in
  179879. * Windows or OS/2 modes, and only in 16 bit mode. This code has
  179880. * been updated by Alexander Lehmann for version 0.89 to waste less
  179881. * memory.
  179882. *
  179883. * Note that we can't use png_size_t for the "size" declaration,
  179884. * since on some systems a png_size_t is a 16-bit quantity, and as a
  179885. * result, we would be truncating potentially larger memory requests
  179886. * (which should cause a fatal error) and introducing major problems.
  179887. */
  179888. png_voidp PNGAPI
  179889. png_malloc(png_structp png_ptr, png_uint_32 size)
  179890. {
  179891. png_voidp ret;
  179892. if (png_ptr == NULL || size == 0)
  179893. return (NULL);
  179894. #ifdef PNG_USER_MEM_SUPPORTED
  179895. if(png_ptr->malloc_fn != NULL)
  179896. ret = ((png_voidp)(*(png_ptr->malloc_fn))(png_ptr, (png_size_t)size));
  179897. else
  179898. ret = (png_malloc_default(png_ptr, size));
  179899. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  179900. png_error(png_ptr, "Out of memory!");
  179901. return (ret);
  179902. }
  179903. png_voidp PNGAPI
  179904. png_malloc_default(png_structp png_ptr, png_uint_32 size)
  179905. {
  179906. png_voidp ret;
  179907. #endif /* PNG_USER_MEM_SUPPORTED */
  179908. if (png_ptr == NULL || size == 0)
  179909. return (NULL);
  179910. #ifdef PNG_MAX_MALLOC_64K
  179911. if (size > (png_uint_32)65536L)
  179912. {
  179913. png_warning(png_ptr, "Cannot Allocate > 64K");
  179914. ret = NULL;
  179915. }
  179916. else
  179917. #endif
  179918. if (size != (size_t)size)
  179919. ret = NULL;
  179920. else if (size == (png_uint_32)65536L)
  179921. {
  179922. if (png_ptr->offset_table == NULL)
  179923. {
  179924. /* try to see if we need to do any of this fancy stuff */
  179925. ret = farmalloc(size);
  179926. if (ret == NULL || ((png_size_t)ret & 0xffff))
  179927. {
  179928. int num_blocks;
  179929. png_uint_32 total_size;
  179930. png_bytep table;
  179931. int i;
  179932. png_byte huge * hptr;
  179933. if (ret != NULL)
  179934. {
  179935. farfree(ret);
  179936. ret = NULL;
  179937. }
  179938. if(png_ptr->zlib_window_bits > 14)
  179939. num_blocks = (int)(1 << (png_ptr->zlib_window_bits - 14));
  179940. else
  179941. num_blocks = 1;
  179942. if (png_ptr->zlib_mem_level >= 7)
  179943. num_blocks += (int)(1 << (png_ptr->zlib_mem_level - 7));
  179944. else
  179945. num_blocks++;
  179946. total_size = ((png_uint_32)65536L) * (png_uint_32)num_blocks+16;
  179947. table = farmalloc(total_size);
  179948. if (table == NULL)
  179949. {
  179950. #ifndef PNG_USER_MEM_SUPPORTED
  179951. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  179952. png_error(png_ptr, "Out Of Memory."); /* Note "O" and "M" */
  179953. else
  179954. png_warning(png_ptr, "Out Of Memory.");
  179955. #endif
  179956. return (NULL);
  179957. }
  179958. if ((png_size_t)table & 0xfff0)
  179959. {
  179960. #ifndef PNG_USER_MEM_SUPPORTED
  179961. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  179962. png_error(png_ptr,
  179963. "Farmalloc didn't return normalized pointer");
  179964. else
  179965. png_warning(png_ptr,
  179966. "Farmalloc didn't return normalized pointer");
  179967. #endif
  179968. return (NULL);
  179969. }
  179970. png_ptr->offset_table = table;
  179971. png_ptr->offset_table_ptr = farmalloc(num_blocks *
  179972. png_sizeof (png_bytep));
  179973. if (png_ptr->offset_table_ptr == NULL)
  179974. {
  179975. #ifndef PNG_USER_MEM_SUPPORTED
  179976. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  179977. png_error(png_ptr, "Out Of memory."); /* Note "O" and "M" */
  179978. else
  179979. png_warning(png_ptr, "Out Of memory.");
  179980. #endif
  179981. return (NULL);
  179982. }
  179983. hptr = (png_byte huge *)table;
  179984. if ((png_size_t)hptr & 0xf)
  179985. {
  179986. hptr = (png_byte huge *)((long)(hptr) & 0xfffffff0L);
  179987. hptr = hptr + 16L; /* "hptr += 16L" fails on Turbo C++ 3.0 */
  179988. }
  179989. for (i = 0; i < num_blocks; i++)
  179990. {
  179991. png_ptr->offset_table_ptr[i] = (png_bytep)hptr;
  179992. hptr = hptr + (png_uint_32)65536L; /* "+=" fails on TC++3.0 */
  179993. }
  179994. png_ptr->offset_table_number = num_blocks;
  179995. png_ptr->offset_table_count = 0;
  179996. png_ptr->offset_table_count_free = 0;
  179997. }
  179998. }
  179999. if (png_ptr->offset_table_count >= png_ptr->offset_table_number)
  180000. {
  180001. #ifndef PNG_USER_MEM_SUPPORTED
  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.");
  180006. #endif
  180007. return (NULL);
  180008. }
  180009. ret = png_ptr->offset_table_ptr[png_ptr->offset_table_count++];
  180010. }
  180011. else
  180012. ret = farmalloc(size);
  180013. #ifndef PNG_USER_MEM_SUPPORTED
  180014. if (ret == NULL)
  180015. {
  180016. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  180017. png_error(png_ptr, "Out of memory."); /* Note "o" and "m" */
  180018. else
  180019. png_warning(png_ptr, "Out of memory."); /* Note "o" and "m" */
  180020. }
  180021. #endif
  180022. return (ret);
  180023. }
  180024. /* free a pointer allocated by png_malloc(). In the default
  180025. configuration, png_ptr is not used, but is passed in case it
  180026. is needed. If ptr is NULL, return without taking any action. */
  180027. void PNGAPI
  180028. png_free(png_structp png_ptr, png_voidp ptr)
  180029. {
  180030. if (png_ptr == NULL || ptr == NULL)
  180031. return;
  180032. #ifdef PNG_USER_MEM_SUPPORTED
  180033. if (png_ptr->free_fn != NULL)
  180034. {
  180035. (*(png_ptr->free_fn))(png_ptr, ptr);
  180036. return;
  180037. }
  180038. else png_free_default(png_ptr, ptr);
  180039. }
  180040. void PNGAPI
  180041. png_free_default(png_structp png_ptr, png_voidp ptr)
  180042. {
  180043. #endif /* PNG_USER_MEM_SUPPORTED */
  180044. if(png_ptr == NULL) return;
  180045. if (png_ptr->offset_table != NULL)
  180046. {
  180047. int i;
  180048. for (i = 0; i < png_ptr->offset_table_count; i++)
  180049. {
  180050. if (ptr == png_ptr->offset_table_ptr[i])
  180051. {
  180052. ptr = NULL;
  180053. png_ptr->offset_table_count_free++;
  180054. break;
  180055. }
  180056. }
  180057. if (png_ptr->offset_table_count_free == png_ptr->offset_table_count)
  180058. {
  180059. farfree(png_ptr->offset_table);
  180060. farfree(png_ptr->offset_table_ptr);
  180061. png_ptr->offset_table = NULL;
  180062. png_ptr->offset_table_ptr = NULL;
  180063. }
  180064. }
  180065. if (ptr != NULL)
  180066. {
  180067. farfree(ptr);
  180068. }
  180069. }
  180070. #else /* Not the Borland DOS special memory handler */
  180071. /* Allocate memory for a png_struct or a png_info. The malloc and
  180072. memset can be replaced by a single call to calloc() if this is thought
  180073. to improve performance noticably. */
  180074. png_voidp /* PRIVATE */
  180075. png_create_struct(int type)
  180076. {
  180077. #ifdef PNG_USER_MEM_SUPPORTED
  180078. return (png_create_struct_2(type, png_malloc_ptr_NULL, png_voidp_NULL));
  180079. }
  180080. /* Allocate memory for a png_struct or a png_info. The malloc and
  180081. memset can be replaced by a single call to calloc() if this is thought
  180082. to improve performance noticably. */
  180083. png_voidp /* PRIVATE */
  180084. png_create_struct_2(int type, png_malloc_ptr malloc_fn, png_voidp mem_ptr)
  180085. {
  180086. #endif /* PNG_USER_MEM_SUPPORTED */
  180087. png_size_t size;
  180088. png_voidp struct_ptr;
  180089. if (type == PNG_STRUCT_INFO)
  180090. size = png_sizeof(png_info);
  180091. else if (type == PNG_STRUCT_PNG)
  180092. size = png_sizeof(png_struct);
  180093. else
  180094. return (NULL);
  180095. #ifdef PNG_USER_MEM_SUPPORTED
  180096. if(malloc_fn != NULL)
  180097. {
  180098. png_struct dummy_struct;
  180099. png_structp png_ptr = &dummy_struct;
  180100. png_ptr->mem_ptr=mem_ptr;
  180101. struct_ptr = (*(malloc_fn))(png_ptr, size);
  180102. if (struct_ptr != NULL)
  180103. png_memset(struct_ptr, 0, size);
  180104. return (struct_ptr);
  180105. }
  180106. #endif /* PNG_USER_MEM_SUPPORTED */
  180107. #if defined(__TURBOC__) && !defined(__FLAT__)
  180108. struct_ptr = (png_voidp)farmalloc(size);
  180109. #else
  180110. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  180111. struct_ptr = (png_voidp)halloc(size,1);
  180112. # else
  180113. struct_ptr = (png_voidp)malloc(size);
  180114. # endif
  180115. #endif
  180116. if (struct_ptr != NULL)
  180117. png_memset(struct_ptr, 0, size);
  180118. return (struct_ptr);
  180119. }
  180120. /* Free memory allocated by a png_create_struct() call */
  180121. void /* PRIVATE */
  180122. png_destroy_struct(png_voidp struct_ptr)
  180123. {
  180124. #ifdef PNG_USER_MEM_SUPPORTED
  180125. png_destroy_struct_2(struct_ptr, png_free_ptr_NULL, png_voidp_NULL);
  180126. }
  180127. /* Free memory allocated by a png_create_struct() call */
  180128. void /* PRIVATE */
  180129. png_destroy_struct_2(png_voidp struct_ptr, png_free_ptr free_fn,
  180130. png_voidp mem_ptr)
  180131. {
  180132. #endif /* PNG_USER_MEM_SUPPORTED */
  180133. if (struct_ptr != NULL)
  180134. {
  180135. #ifdef PNG_USER_MEM_SUPPORTED
  180136. if(free_fn != NULL)
  180137. {
  180138. png_struct dummy_struct;
  180139. png_structp png_ptr = &dummy_struct;
  180140. png_ptr->mem_ptr=mem_ptr;
  180141. (*(free_fn))(png_ptr, struct_ptr);
  180142. return;
  180143. }
  180144. #endif /* PNG_USER_MEM_SUPPORTED */
  180145. #if defined(__TURBOC__) && !defined(__FLAT__)
  180146. farfree(struct_ptr);
  180147. #else
  180148. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  180149. hfree(struct_ptr);
  180150. # else
  180151. free(struct_ptr);
  180152. # endif
  180153. #endif
  180154. }
  180155. }
  180156. /* Allocate memory. For reasonable files, size should never exceed
  180157. 64K. However, zlib may allocate more then 64K if you don't tell
  180158. it not to. See zconf.h and png.h for more information. zlib does
  180159. need to allocate exactly 64K, so whatever you call here must
  180160. have the ability to do that. */
  180161. png_voidp PNGAPI
  180162. png_malloc(png_structp png_ptr, png_uint_32 size)
  180163. {
  180164. png_voidp ret;
  180165. #ifdef PNG_USER_MEM_SUPPORTED
  180166. if (png_ptr == NULL || size == 0)
  180167. return (NULL);
  180168. if(png_ptr->malloc_fn != NULL)
  180169. ret = ((png_voidp)(*(png_ptr->malloc_fn))(png_ptr, (png_size_t)size));
  180170. else
  180171. ret = (png_malloc_default(png_ptr, size));
  180172. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  180173. png_error(png_ptr, "Out of Memory!");
  180174. return (ret);
  180175. }
  180176. png_voidp PNGAPI
  180177. png_malloc_default(png_structp png_ptr, png_uint_32 size)
  180178. {
  180179. png_voidp ret;
  180180. #endif /* PNG_USER_MEM_SUPPORTED */
  180181. if (png_ptr == NULL || size == 0)
  180182. return (NULL);
  180183. #ifdef PNG_MAX_MALLOC_64K
  180184. if (size > (png_uint_32)65536L)
  180185. {
  180186. #ifndef PNG_USER_MEM_SUPPORTED
  180187. if(png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  180188. png_error(png_ptr, "Cannot Allocate > 64K");
  180189. else
  180190. #endif
  180191. return NULL;
  180192. }
  180193. #endif
  180194. /* Check for overflow */
  180195. #if defined(__TURBOC__) && !defined(__FLAT__)
  180196. if (size != (unsigned long)size)
  180197. ret = NULL;
  180198. else
  180199. ret = farmalloc(size);
  180200. #else
  180201. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  180202. if (size != (unsigned long)size)
  180203. ret = NULL;
  180204. else
  180205. ret = halloc(size, 1);
  180206. # else
  180207. if (size != (size_t)size)
  180208. ret = NULL;
  180209. else
  180210. ret = malloc((size_t)size);
  180211. # endif
  180212. #endif
  180213. #ifndef PNG_USER_MEM_SUPPORTED
  180214. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  180215. png_error(png_ptr, "Out of Memory");
  180216. #endif
  180217. return (ret);
  180218. }
  180219. /* Free a pointer allocated by png_malloc(). If ptr is NULL, return
  180220. without taking any action. */
  180221. void PNGAPI
  180222. png_free(png_structp png_ptr, png_voidp ptr)
  180223. {
  180224. if (png_ptr == NULL || ptr == NULL)
  180225. return;
  180226. #ifdef PNG_USER_MEM_SUPPORTED
  180227. if (png_ptr->free_fn != NULL)
  180228. {
  180229. (*(png_ptr->free_fn))(png_ptr, ptr);
  180230. return;
  180231. }
  180232. else png_free_default(png_ptr, ptr);
  180233. }
  180234. void PNGAPI
  180235. png_free_default(png_structp png_ptr, png_voidp ptr)
  180236. {
  180237. if (png_ptr == NULL || ptr == NULL)
  180238. return;
  180239. #endif /* PNG_USER_MEM_SUPPORTED */
  180240. #if defined(__TURBOC__) && !defined(__FLAT__)
  180241. farfree(ptr);
  180242. #else
  180243. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  180244. hfree(ptr);
  180245. # else
  180246. free(ptr);
  180247. # endif
  180248. #endif
  180249. }
  180250. #endif /* Not Borland DOS special memory handler */
  180251. #if defined(PNG_1_0_X)
  180252. # define png_malloc_warn png_malloc
  180253. #else
  180254. /* This function was added at libpng version 1.2.3. The png_malloc_warn()
  180255. * function will set up png_malloc() to issue a png_warning and return NULL
  180256. * instead of issuing a png_error, if it fails to allocate the requested
  180257. * memory.
  180258. */
  180259. png_voidp PNGAPI
  180260. png_malloc_warn(png_structp png_ptr, png_uint_32 size)
  180261. {
  180262. png_voidp ptr;
  180263. png_uint_32 save_flags;
  180264. if(png_ptr == NULL) return (NULL);
  180265. save_flags=png_ptr->flags;
  180266. png_ptr->flags|=PNG_FLAG_MALLOC_NULL_MEM_OK;
  180267. ptr = (png_voidp)png_malloc((png_structp)png_ptr, size);
  180268. png_ptr->flags=save_flags;
  180269. return(ptr);
  180270. }
  180271. #endif
  180272. png_voidp PNGAPI
  180273. png_memcpy_check (png_structp png_ptr, png_voidp s1, png_voidp s2,
  180274. png_uint_32 length)
  180275. {
  180276. png_size_t size;
  180277. size = (png_size_t)length;
  180278. if ((png_uint_32)size != length)
  180279. png_error(png_ptr,"Overflow in png_memcpy_check.");
  180280. return(png_memcpy (s1, s2, size));
  180281. }
  180282. png_voidp PNGAPI
  180283. png_memset_check (png_structp png_ptr, png_voidp s1, int value,
  180284. png_uint_32 length)
  180285. {
  180286. png_size_t size;
  180287. size = (png_size_t)length;
  180288. if ((png_uint_32)size != length)
  180289. png_error(png_ptr,"Overflow in png_memset_check.");
  180290. return (png_memset (s1, value, size));
  180291. }
  180292. #ifdef PNG_USER_MEM_SUPPORTED
  180293. /* This function is called when the application wants to use another method
  180294. * of allocating and freeing memory.
  180295. */
  180296. void PNGAPI
  180297. png_set_mem_fn(png_structp png_ptr, png_voidp mem_ptr, png_malloc_ptr
  180298. malloc_fn, png_free_ptr free_fn)
  180299. {
  180300. if(png_ptr != NULL) {
  180301. png_ptr->mem_ptr = mem_ptr;
  180302. png_ptr->malloc_fn = malloc_fn;
  180303. png_ptr->free_fn = free_fn;
  180304. }
  180305. }
  180306. /* This function returns a pointer to the mem_ptr associated with the user
  180307. * functions. The application should free any memory associated with this
  180308. * pointer before png_write_destroy and png_read_destroy are called.
  180309. */
  180310. png_voidp PNGAPI
  180311. png_get_mem_ptr(png_structp png_ptr)
  180312. {
  180313. if(png_ptr == NULL) return (NULL);
  180314. return ((png_voidp)png_ptr->mem_ptr);
  180315. }
  180316. #endif /* PNG_USER_MEM_SUPPORTED */
  180317. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  180318. /********* End of inlined file: pngmem.c *********/
  180319. /********* Start of inlined file: pngread.c *********/
  180320. /* pngread.c - read a PNG file
  180321. *
  180322. * Last changed in libpng 1.2.20 September 7, 2007
  180323. * For conditions of distribution and use, see copyright notice in png.h
  180324. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  180325. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  180326. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  180327. *
  180328. * This file contains routines that an application calls directly to
  180329. * read a PNG file or stream.
  180330. */
  180331. #define PNG_INTERNAL
  180332. #if defined(PNG_READ_SUPPORTED)
  180333. /* Create a PNG structure for reading, and allocate any memory needed. */
  180334. png_structp PNGAPI
  180335. png_create_read_struct(png_const_charp user_png_ver, png_voidp error_ptr,
  180336. png_error_ptr error_fn, png_error_ptr warn_fn)
  180337. {
  180338. #ifdef PNG_USER_MEM_SUPPORTED
  180339. return (png_create_read_struct_2(user_png_ver, error_ptr, error_fn,
  180340. warn_fn, png_voidp_NULL, png_malloc_ptr_NULL, png_free_ptr_NULL));
  180341. }
  180342. /* Alternate create PNG structure for reading, and allocate any memory needed. */
  180343. png_structp PNGAPI
  180344. png_create_read_struct_2(png_const_charp user_png_ver, png_voidp error_ptr,
  180345. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  180346. png_malloc_ptr malloc_fn, png_free_ptr free_fn)
  180347. {
  180348. #endif /* PNG_USER_MEM_SUPPORTED */
  180349. png_structp png_ptr;
  180350. #ifdef PNG_SETJMP_SUPPORTED
  180351. #ifdef USE_FAR_KEYWORD
  180352. jmp_buf jmpbuf;
  180353. #endif
  180354. #endif
  180355. int i;
  180356. png_debug(1, "in png_create_read_struct\n");
  180357. #ifdef PNG_USER_MEM_SUPPORTED
  180358. png_ptr = (png_structp)png_create_struct_2(PNG_STRUCT_PNG,
  180359. (png_malloc_ptr)malloc_fn, (png_voidp)mem_ptr);
  180360. #else
  180361. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  180362. #endif
  180363. if (png_ptr == NULL)
  180364. return (NULL);
  180365. /* added at libpng-1.2.6 */
  180366. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  180367. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  180368. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  180369. #endif
  180370. #ifdef PNG_SETJMP_SUPPORTED
  180371. #ifdef USE_FAR_KEYWORD
  180372. if (setjmp(jmpbuf))
  180373. #else
  180374. if (setjmp(png_ptr->jmpbuf))
  180375. #endif
  180376. {
  180377. png_free(png_ptr, png_ptr->zbuf);
  180378. png_ptr->zbuf=NULL;
  180379. #ifdef PNG_USER_MEM_SUPPORTED
  180380. png_destroy_struct_2((png_voidp)png_ptr,
  180381. (png_free_ptr)free_fn, (png_voidp)mem_ptr);
  180382. #else
  180383. png_destroy_struct((png_voidp)png_ptr);
  180384. #endif
  180385. return (NULL);
  180386. }
  180387. #ifdef USE_FAR_KEYWORD
  180388. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  180389. #endif
  180390. #endif
  180391. #ifdef PNG_USER_MEM_SUPPORTED
  180392. png_set_mem_fn(png_ptr, mem_ptr, malloc_fn, free_fn);
  180393. #endif
  180394. png_set_error_fn(png_ptr, error_ptr, error_fn, warn_fn);
  180395. i=0;
  180396. do
  180397. {
  180398. if(user_png_ver[i] != png_libpng_ver[i])
  180399. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  180400. } while (png_libpng_ver[i++]);
  180401. if (png_ptr->flags & PNG_FLAG_LIBRARY_MISMATCH)
  180402. {
  180403. /* Libpng 0.90 and later are binary incompatible with libpng 0.89, so
  180404. * we must recompile any applications that use any older library version.
  180405. * For versions after libpng 1.0, we will be compatible, so we need
  180406. * only check the first digit.
  180407. */
  180408. if (user_png_ver == NULL || user_png_ver[0] != png_libpng_ver[0] ||
  180409. (user_png_ver[0] == '1' && user_png_ver[2] != png_libpng_ver[2]) ||
  180410. (user_png_ver[0] == '0' && user_png_ver[2] < '9'))
  180411. {
  180412. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  180413. char msg[80];
  180414. if (user_png_ver)
  180415. {
  180416. png_snprintf(msg, 80,
  180417. "Application was compiled with png.h from libpng-%.20s",
  180418. user_png_ver);
  180419. png_warning(png_ptr, msg);
  180420. }
  180421. png_snprintf(msg, 80,
  180422. "Application is running with png.c from libpng-%.20s",
  180423. png_libpng_ver);
  180424. png_warning(png_ptr, msg);
  180425. #endif
  180426. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  180427. png_ptr->flags=0;
  180428. #endif
  180429. png_error(png_ptr,
  180430. "Incompatible libpng version in application and library");
  180431. }
  180432. }
  180433. /* initialize zbuf - compression buffer */
  180434. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  180435. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  180436. (png_uint_32)png_ptr->zbuf_size);
  180437. png_ptr->zstream.zalloc = png_zalloc;
  180438. png_ptr->zstream.zfree = png_zfree;
  180439. png_ptr->zstream.opaque = (voidpf)png_ptr;
  180440. switch (inflateInit(&png_ptr->zstream))
  180441. {
  180442. case Z_OK: /* Do nothing */ break;
  180443. case Z_MEM_ERROR:
  180444. case Z_STREAM_ERROR: png_error(png_ptr, "zlib memory error"); break;
  180445. case Z_VERSION_ERROR: png_error(png_ptr, "zlib version error"); break;
  180446. default: png_error(png_ptr, "Unknown zlib error");
  180447. }
  180448. png_ptr->zstream.next_out = png_ptr->zbuf;
  180449. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  180450. png_set_read_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL);
  180451. #ifdef PNG_SETJMP_SUPPORTED
  180452. /* Applications that neglect to set up their own setjmp() and then encounter
  180453. a png_error() will longjmp here. Since the jmpbuf is then meaningless we
  180454. abort instead of returning. */
  180455. #ifdef USE_FAR_KEYWORD
  180456. if (setjmp(jmpbuf))
  180457. PNG_ABORT();
  180458. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  180459. #else
  180460. if (setjmp(png_ptr->jmpbuf))
  180461. PNG_ABORT();
  180462. #endif
  180463. #endif
  180464. return (png_ptr);
  180465. }
  180466. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  180467. /* Initialize PNG structure for reading, and allocate any memory needed.
  180468. This interface is deprecated in favour of the png_create_read_struct(),
  180469. and it will disappear as of libpng-1.3.0. */
  180470. #undef png_read_init
  180471. void PNGAPI
  180472. png_read_init(png_structp png_ptr)
  180473. {
  180474. /* We only come here via pre-1.0.7-compiled applications */
  180475. png_read_init_2(png_ptr, "1.0.6 or earlier", 0, 0);
  180476. }
  180477. void PNGAPI
  180478. png_read_init_2(png_structp png_ptr, png_const_charp user_png_ver,
  180479. png_size_t png_struct_size, png_size_t png_info_size)
  180480. {
  180481. /* We only come here via pre-1.0.12-compiled applications */
  180482. if(png_ptr == NULL) return;
  180483. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  180484. if(png_sizeof(png_struct) > png_struct_size ||
  180485. png_sizeof(png_info) > png_info_size)
  180486. {
  180487. char msg[80];
  180488. png_ptr->warning_fn=NULL;
  180489. if (user_png_ver)
  180490. {
  180491. png_snprintf(msg, 80,
  180492. "Application was compiled with png.h from libpng-%.20s",
  180493. user_png_ver);
  180494. png_warning(png_ptr, msg);
  180495. }
  180496. png_snprintf(msg, 80,
  180497. "Application is running with png.c from libpng-%.20s",
  180498. png_libpng_ver);
  180499. png_warning(png_ptr, msg);
  180500. }
  180501. #endif
  180502. if(png_sizeof(png_struct) > png_struct_size)
  180503. {
  180504. png_ptr->error_fn=NULL;
  180505. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  180506. png_ptr->flags=0;
  180507. #endif
  180508. png_error(png_ptr,
  180509. "The png struct allocated by the application for reading is too small.");
  180510. }
  180511. if(png_sizeof(png_info) > png_info_size)
  180512. {
  180513. png_ptr->error_fn=NULL;
  180514. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  180515. png_ptr->flags=0;
  180516. #endif
  180517. png_error(png_ptr,
  180518. "The info struct allocated by application for reading is too small.");
  180519. }
  180520. png_read_init_3(&png_ptr, user_png_ver, png_struct_size);
  180521. }
  180522. #endif /* PNG_1_0_X || PNG_1_2_X */
  180523. void PNGAPI
  180524. png_read_init_3(png_structpp ptr_ptr, png_const_charp user_png_ver,
  180525. png_size_t png_struct_size)
  180526. {
  180527. #ifdef PNG_SETJMP_SUPPORTED
  180528. jmp_buf tmp_jmp; /* to save current jump buffer */
  180529. #endif
  180530. int i=0;
  180531. png_structp png_ptr=*ptr_ptr;
  180532. if(png_ptr == NULL) return;
  180533. do
  180534. {
  180535. if(user_png_ver[i] != png_libpng_ver[i])
  180536. {
  180537. #ifdef PNG_LEGACY_SUPPORTED
  180538. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  180539. #else
  180540. png_ptr->warning_fn=NULL;
  180541. png_warning(png_ptr,
  180542. "Application uses deprecated png_read_init() and should be recompiled.");
  180543. break;
  180544. #endif
  180545. }
  180546. } while (png_libpng_ver[i++]);
  180547. png_debug(1, "in png_read_init_3\n");
  180548. #ifdef PNG_SETJMP_SUPPORTED
  180549. /* save jump buffer and error functions */
  180550. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  180551. #endif
  180552. if(png_sizeof(png_struct) > png_struct_size)
  180553. {
  180554. png_destroy_struct(png_ptr);
  180555. *ptr_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  180556. png_ptr = *ptr_ptr;
  180557. }
  180558. /* reset all variables to 0 */
  180559. png_memset(png_ptr, 0, png_sizeof (png_struct));
  180560. #ifdef PNG_SETJMP_SUPPORTED
  180561. /* restore jump buffer */
  180562. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  180563. #endif
  180564. /* added at libpng-1.2.6 */
  180565. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  180566. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  180567. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  180568. #endif
  180569. /* initialize zbuf - compression buffer */
  180570. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  180571. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  180572. (png_uint_32)png_ptr->zbuf_size);
  180573. png_ptr->zstream.zalloc = png_zalloc;
  180574. png_ptr->zstream.zfree = png_zfree;
  180575. png_ptr->zstream.opaque = (voidpf)png_ptr;
  180576. switch (inflateInit(&png_ptr->zstream))
  180577. {
  180578. case Z_OK: /* Do nothing */ break;
  180579. case Z_MEM_ERROR:
  180580. case Z_STREAM_ERROR: png_error(png_ptr, "zlib memory"); break;
  180581. case Z_VERSION_ERROR: png_error(png_ptr, "zlib version"); break;
  180582. default: png_error(png_ptr, "Unknown zlib error");
  180583. }
  180584. png_ptr->zstream.next_out = png_ptr->zbuf;
  180585. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  180586. png_set_read_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL);
  180587. }
  180588. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  180589. /* Read the information before the actual image data. This has been
  180590. * changed in v0.90 to allow reading a file that already has the magic
  180591. * bytes read from the stream. You can tell libpng how many bytes have
  180592. * been read from the beginning of the stream (up to the maximum of 8)
  180593. * via png_set_sig_bytes(), and we will only check the remaining bytes
  180594. * here. The application can then have access to the signature bytes we
  180595. * read if it is determined that this isn't a valid PNG file.
  180596. */
  180597. void PNGAPI
  180598. png_read_info(png_structp png_ptr, png_infop info_ptr)
  180599. {
  180600. if(png_ptr == NULL) return;
  180601. png_debug(1, "in png_read_info\n");
  180602. /* If we haven't checked all of the PNG signature bytes, do so now. */
  180603. if (png_ptr->sig_bytes < 8)
  180604. {
  180605. png_size_t num_checked = png_ptr->sig_bytes,
  180606. num_to_check = 8 - num_checked;
  180607. png_read_data(png_ptr, &(info_ptr->signature[num_checked]), num_to_check);
  180608. png_ptr->sig_bytes = 8;
  180609. if (png_sig_cmp(info_ptr->signature, num_checked, num_to_check))
  180610. {
  180611. if (num_checked < 4 &&
  180612. png_sig_cmp(info_ptr->signature, num_checked, num_to_check - 4))
  180613. png_error(png_ptr, "Not a PNG file");
  180614. else
  180615. png_error(png_ptr, "PNG file corrupted by ASCII conversion");
  180616. }
  180617. if (num_checked < 3)
  180618. png_ptr->mode |= PNG_HAVE_PNG_SIGNATURE;
  180619. }
  180620. for(;;)
  180621. {
  180622. #ifdef PNG_USE_LOCAL_ARRAYS
  180623. PNG_CONST PNG_IHDR;
  180624. PNG_CONST PNG_IDAT;
  180625. PNG_CONST PNG_IEND;
  180626. PNG_CONST PNG_PLTE;
  180627. #if defined(PNG_READ_bKGD_SUPPORTED)
  180628. PNG_CONST PNG_bKGD;
  180629. #endif
  180630. #if defined(PNG_READ_cHRM_SUPPORTED)
  180631. PNG_CONST PNG_cHRM;
  180632. #endif
  180633. #if defined(PNG_READ_gAMA_SUPPORTED)
  180634. PNG_CONST PNG_gAMA;
  180635. #endif
  180636. #if defined(PNG_READ_hIST_SUPPORTED)
  180637. PNG_CONST PNG_hIST;
  180638. #endif
  180639. #if defined(PNG_READ_iCCP_SUPPORTED)
  180640. PNG_CONST PNG_iCCP;
  180641. #endif
  180642. #if defined(PNG_READ_iTXt_SUPPORTED)
  180643. PNG_CONST PNG_iTXt;
  180644. #endif
  180645. #if defined(PNG_READ_oFFs_SUPPORTED)
  180646. PNG_CONST PNG_oFFs;
  180647. #endif
  180648. #if defined(PNG_READ_pCAL_SUPPORTED)
  180649. PNG_CONST PNG_pCAL;
  180650. #endif
  180651. #if defined(PNG_READ_pHYs_SUPPORTED)
  180652. PNG_CONST PNG_pHYs;
  180653. #endif
  180654. #if defined(PNG_READ_sBIT_SUPPORTED)
  180655. PNG_CONST PNG_sBIT;
  180656. #endif
  180657. #if defined(PNG_READ_sCAL_SUPPORTED)
  180658. PNG_CONST PNG_sCAL;
  180659. #endif
  180660. #if defined(PNG_READ_sPLT_SUPPORTED)
  180661. PNG_CONST PNG_sPLT;
  180662. #endif
  180663. #if defined(PNG_READ_sRGB_SUPPORTED)
  180664. PNG_CONST PNG_sRGB;
  180665. #endif
  180666. #if defined(PNG_READ_tEXt_SUPPORTED)
  180667. PNG_CONST PNG_tEXt;
  180668. #endif
  180669. #if defined(PNG_READ_tIME_SUPPORTED)
  180670. PNG_CONST PNG_tIME;
  180671. #endif
  180672. #if defined(PNG_READ_tRNS_SUPPORTED)
  180673. PNG_CONST PNG_tRNS;
  180674. #endif
  180675. #if defined(PNG_READ_zTXt_SUPPORTED)
  180676. PNG_CONST PNG_zTXt;
  180677. #endif
  180678. #endif /* PNG_USE_LOCAL_ARRAYS */
  180679. png_byte chunk_length[4];
  180680. png_uint_32 length;
  180681. png_read_data(png_ptr, chunk_length, 4);
  180682. length = png_get_uint_31(png_ptr,chunk_length);
  180683. png_reset_crc(png_ptr);
  180684. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  180685. png_debug2(0, "Reading %s chunk, length=%lu.\n", png_ptr->chunk_name,
  180686. length);
  180687. /* This should be a binary subdivision search or a hash for
  180688. * matching the chunk name rather than a linear search.
  180689. */
  180690. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  180691. if(png_ptr->mode & PNG_AFTER_IDAT)
  180692. png_ptr->mode |= PNG_HAVE_CHUNK_AFTER_IDAT;
  180693. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  180694. png_handle_IHDR(png_ptr, info_ptr, length);
  180695. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  180696. png_handle_IEND(png_ptr, info_ptr, length);
  180697. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  180698. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  180699. {
  180700. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  180701. png_ptr->mode |= PNG_HAVE_IDAT;
  180702. png_handle_unknown(png_ptr, info_ptr, length);
  180703. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  180704. png_ptr->mode |= PNG_HAVE_PLTE;
  180705. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  180706. {
  180707. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  180708. png_error(png_ptr, "Missing IHDR before IDAT");
  180709. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  180710. !(png_ptr->mode & PNG_HAVE_PLTE))
  180711. png_error(png_ptr, "Missing PLTE before IDAT");
  180712. break;
  180713. }
  180714. }
  180715. #endif
  180716. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  180717. png_handle_PLTE(png_ptr, info_ptr, length);
  180718. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  180719. {
  180720. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  180721. png_error(png_ptr, "Missing IHDR before IDAT");
  180722. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  180723. !(png_ptr->mode & PNG_HAVE_PLTE))
  180724. png_error(png_ptr, "Missing PLTE before IDAT");
  180725. png_ptr->idat_size = length;
  180726. png_ptr->mode |= PNG_HAVE_IDAT;
  180727. break;
  180728. }
  180729. #if defined(PNG_READ_bKGD_SUPPORTED)
  180730. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  180731. png_handle_bKGD(png_ptr, info_ptr, length);
  180732. #endif
  180733. #if defined(PNG_READ_cHRM_SUPPORTED)
  180734. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  180735. png_handle_cHRM(png_ptr, info_ptr, length);
  180736. #endif
  180737. #if defined(PNG_READ_gAMA_SUPPORTED)
  180738. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  180739. png_handle_gAMA(png_ptr, info_ptr, length);
  180740. #endif
  180741. #if defined(PNG_READ_hIST_SUPPORTED)
  180742. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  180743. png_handle_hIST(png_ptr, info_ptr, length);
  180744. #endif
  180745. #if defined(PNG_READ_oFFs_SUPPORTED)
  180746. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  180747. png_handle_oFFs(png_ptr, info_ptr, length);
  180748. #endif
  180749. #if defined(PNG_READ_pCAL_SUPPORTED)
  180750. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  180751. png_handle_pCAL(png_ptr, info_ptr, length);
  180752. #endif
  180753. #if defined(PNG_READ_sCAL_SUPPORTED)
  180754. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  180755. png_handle_sCAL(png_ptr, info_ptr, length);
  180756. #endif
  180757. #if defined(PNG_READ_pHYs_SUPPORTED)
  180758. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  180759. png_handle_pHYs(png_ptr, info_ptr, length);
  180760. #endif
  180761. #if defined(PNG_READ_sBIT_SUPPORTED)
  180762. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  180763. png_handle_sBIT(png_ptr, info_ptr, length);
  180764. #endif
  180765. #if defined(PNG_READ_sRGB_SUPPORTED)
  180766. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  180767. png_handle_sRGB(png_ptr, info_ptr, length);
  180768. #endif
  180769. #if defined(PNG_READ_iCCP_SUPPORTED)
  180770. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  180771. png_handle_iCCP(png_ptr, info_ptr, length);
  180772. #endif
  180773. #if defined(PNG_READ_sPLT_SUPPORTED)
  180774. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  180775. png_handle_sPLT(png_ptr, info_ptr, length);
  180776. #endif
  180777. #if defined(PNG_READ_tEXt_SUPPORTED)
  180778. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  180779. png_handle_tEXt(png_ptr, info_ptr, length);
  180780. #endif
  180781. #if defined(PNG_READ_tIME_SUPPORTED)
  180782. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  180783. png_handle_tIME(png_ptr, info_ptr, length);
  180784. #endif
  180785. #if defined(PNG_READ_tRNS_SUPPORTED)
  180786. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  180787. png_handle_tRNS(png_ptr, info_ptr, length);
  180788. #endif
  180789. #if defined(PNG_READ_zTXt_SUPPORTED)
  180790. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  180791. png_handle_zTXt(png_ptr, info_ptr, length);
  180792. #endif
  180793. #if defined(PNG_READ_iTXt_SUPPORTED)
  180794. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  180795. png_handle_iTXt(png_ptr, info_ptr, length);
  180796. #endif
  180797. else
  180798. png_handle_unknown(png_ptr, info_ptr, length);
  180799. }
  180800. }
  180801. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  180802. /* optional call to update the users info_ptr structure */
  180803. void PNGAPI
  180804. png_read_update_info(png_structp png_ptr, png_infop info_ptr)
  180805. {
  180806. png_debug(1, "in png_read_update_info\n");
  180807. if(png_ptr == NULL) return;
  180808. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  180809. png_read_start_row(png_ptr);
  180810. else
  180811. png_warning(png_ptr,
  180812. "Ignoring extra png_read_update_info() call; row buffer not reallocated");
  180813. png_read_transform_info(png_ptr, info_ptr);
  180814. }
  180815. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  180816. /* Initialize palette, background, etc, after transformations
  180817. * are set, but before any reading takes place. This allows
  180818. * the user to obtain a gamma-corrected palette, for example.
  180819. * If the user doesn't call this, we will do it ourselves.
  180820. */
  180821. void PNGAPI
  180822. png_start_read_image(png_structp png_ptr)
  180823. {
  180824. png_debug(1, "in png_start_read_image\n");
  180825. if(png_ptr == NULL) return;
  180826. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  180827. png_read_start_row(png_ptr);
  180828. }
  180829. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  180830. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  180831. void PNGAPI
  180832. png_read_row(png_structp png_ptr, png_bytep row, png_bytep dsp_row)
  180833. {
  180834. #ifdef PNG_USE_LOCAL_ARRAYS
  180835. PNG_CONST PNG_IDAT;
  180836. PNG_CONST int png_pass_dsp_mask[7] = {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55,
  180837. 0xff};
  180838. PNG_CONST int png_pass_mask[7] = {0x80, 0x08, 0x88, 0x22, 0xaa, 0x55, 0xff};
  180839. #endif
  180840. int ret;
  180841. if(png_ptr == NULL) return;
  180842. png_debug2(1, "in png_read_row (row %lu, pass %d)\n",
  180843. png_ptr->row_number, png_ptr->pass);
  180844. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  180845. png_read_start_row(png_ptr);
  180846. if (png_ptr->row_number == 0 && png_ptr->pass == 0)
  180847. {
  180848. /* check for transforms that have been set but were defined out */
  180849. #if defined(PNG_WRITE_INVERT_SUPPORTED) && !defined(PNG_READ_INVERT_SUPPORTED)
  180850. if (png_ptr->transformations & PNG_INVERT_MONO)
  180851. png_warning(png_ptr, "PNG_READ_INVERT_SUPPORTED is not defined.");
  180852. #endif
  180853. #if defined(PNG_WRITE_FILLER_SUPPORTED) && !defined(PNG_READ_FILLER_SUPPORTED)
  180854. if (png_ptr->transformations & PNG_FILLER)
  180855. png_warning(png_ptr, "PNG_READ_FILLER_SUPPORTED is not defined.");
  180856. #endif
  180857. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED) && !defined(PNG_READ_PACKSWAP_SUPPORTED)
  180858. if (png_ptr->transformations & PNG_PACKSWAP)
  180859. png_warning(png_ptr, "PNG_READ_PACKSWAP_SUPPORTED is not defined.");
  180860. #endif
  180861. #if defined(PNG_WRITE_PACK_SUPPORTED) && !defined(PNG_READ_PACK_SUPPORTED)
  180862. if (png_ptr->transformations & PNG_PACK)
  180863. png_warning(png_ptr, "PNG_READ_PACK_SUPPORTED is not defined.");
  180864. #endif
  180865. #if defined(PNG_WRITE_SHIFT_SUPPORTED) && !defined(PNG_READ_SHIFT_SUPPORTED)
  180866. if (png_ptr->transformations & PNG_SHIFT)
  180867. png_warning(png_ptr, "PNG_READ_SHIFT_SUPPORTED is not defined.");
  180868. #endif
  180869. #if defined(PNG_WRITE_BGR_SUPPORTED) && !defined(PNG_READ_BGR_SUPPORTED)
  180870. if (png_ptr->transformations & PNG_BGR)
  180871. png_warning(png_ptr, "PNG_READ_BGR_SUPPORTED is not defined.");
  180872. #endif
  180873. #if defined(PNG_WRITE_SWAP_SUPPORTED) && !defined(PNG_READ_SWAP_SUPPORTED)
  180874. if (png_ptr->transformations & PNG_SWAP_BYTES)
  180875. png_warning(png_ptr, "PNG_READ_SWAP_SUPPORTED is not defined.");
  180876. #endif
  180877. }
  180878. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  180879. /* if interlaced and we do not need a new row, combine row and return */
  180880. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  180881. {
  180882. switch (png_ptr->pass)
  180883. {
  180884. case 0:
  180885. if (png_ptr->row_number & 0x07)
  180886. {
  180887. if (dsp_row != NULL)
  180888. png_combine_row(png_ptr, dsp_row,
  180889. png_pass_dsp_mask[png_ptr->pass]);
  180890. png_read_finish_row(png_ptr);
  180891. return;
  180892. }
  180893. break;
  180894. case 1:
  180895. if ((png_ptr->row_number & 0x07) || png_ptr->width < 5)
  180896. {
  180897. if (dsp_row != NULL)
  180898. png_combine_row(png_ptr, dsp_row,
  180899. png_pass_dsp_mask[png_ptr->pass]);
  180900. png_read_finish_row(png_ptr);
  180901. return;
  180902. }
  180903. break;
  180904. case 2:
  180905. if ((png_ptr->row_number & 0x07) != 4)
  180906. {
  180907. if (dsp_row != NULL && (png_ptr->row_number & 4))
  180908. png_combine_row(png_ptr, dsp_row,
  180909. png_pass_dsp_mask[png_ptr->pass]);
  180910. png_read_finish_row(png_ptr);
  180911. return;
  180912. }
  180913. break;
  180914. case 3:
  180915. if ((png_ptr->row_number & 3) || png_ptr->width < 3)
  180916. {
  180917. if (dsp_row != NULL)
  180918. png_combine_row(png_ptr, dsp_row,
  180919. png_pass_dsp_mask[png_ptr->pass]);
  180920. png_read_finish_row(png_ptr);
  180921. return;
  180922. }
  180923. break;
  180924. case 4:
  180925. if ((png_ptr->row_number & 3) != 2)
  180926. {
  180927. if (dsp_row != NULL && (png_ptr->row_number & 2))
  180928. png_combine_row(png_ptr, dsp_row,
  180929. png_pass_dsp_mask[png_ptr->pass]);
  180930. png_read_finish_row(png_ptr);
  180931. return;
  180932. }
  180933. break;
  180934. case 5:
  180935. if ((png_ptr->row_number & 1) || png_ptr->width < 2)
  180936. {
  180937. if (dsp_row != NULL)
  180938. png_combine_row(png_ptr, dsp_row,
  180939. png_pass_dsp_mask[png_ptr->pass]);
  180940. png_read_finish_row(png_ptr);
  180941. return;
  180942. }
  180943. break;
  180944. case 6:
  180945. if (!(png_ptr->row_number & 1))
  180946. {
  180947. png_read_finish_row(png_ptr);
  180948. return;
  180949. }
  180950. break;
  180951. }
  180952. }
  180953. #endif
  180954. if (!(png_ptr->mode & PNG_HAVE_IDAT))
  180955. png_error(png_ptr, "Invalid attempt to read row data");
  180956. png_ptr->zstream.next_out = png_ptr->row_buf;
  180957. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  180958. do
  180959. {
  180960. if (!(png_ptr->zstream.avail_in))
  180961. {
  180962. while (!png_ptr->idat_size)
  180963. {
  180964. png_byte chunk_length[4];
  180965. png_crc_finish(png_ptr, 0);
  180966. png_read_data(png_ptr, chunk_length, 4);
  180967. png_ptr->idat_size = png_get_uint_31(png_ptr,chunk_length);
  180968. png_reset_crc(png_ptr);
  180969. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  180970. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  180971. png_error(png_ptr, "Not enough image data");
  180972. }
  180973. png_ptr->zstream.avail_in = (uInt)png_ptr->zbuf_size;
  180974. png_ptr->zstream.next_in = png_ptr->zbuf;
  180975. if (png_ptr->zbuf_size > png_ptr->idat_size)
  180976. png_ptr->zstream.avail_in = (uInt)png_ptr->idat_size;
  180977. png_crc_read(png_ptr, png_ptr->zbuf,
  180978. (png_size_t)png_ptr->zstream.avail_in);
  180979. png_ptr->idat_size -= png_ptr->zstream.avail_in;
  180980. }
  180981. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  180982. if (ret == Z_STREAM_END)
  180983. {
  180984. if (png_ptr->zstream.avail_out || png_ptr->zstream.avail_in ||
  180985. png_ptr->idat_size)
  180986. png_error(png_ptr, "Extra compressed data");
  180987. png_ptr->mode |= PNG_AFTER_IDAT;
  180988. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  180989. break;
  180990. }
  180991. if (ret != Z_OK)
  180992. png_error(png_ptr, png_ptr->zstream.msg ? png_ptr->zstream.msg :
  180993. "Decompression error");
  180994. } while (png_ptr->zstream.avail_out);
  180995. png_ptr->row_info.color_type = png_ptr->color_type;
  180996. png_ptr->row_info.width = png_ptr->iwidth;
  180997. png_ptr->row_info.channels = png_ptr->channels;
  180998. png_ptr->row_info.bit_depth = png_ptr->bit_depth;
  180999. png_ptr->row_info.pixel_depth = png_ptr->pixel_depth;
  181000. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  181001. png_ptr->row_info.width);
  181002. if(png_ptr->row_buf[0])
  181003. png_read_filter_row(png_ptr, &(png_ptr->row_info),
  181004. png_ptr->row_buf + 1, png_ptr->prev_row + 1,
  181005. (int)(png_ptr->row_buf[0]));
  181006. png_memcpy_check(png_ptr, png_ptr->prev_row, png_ptr->row_buf,
  181007. png_ptr->rowbytes + 1);
  181008. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  181009. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  181010. (png_ptr->filter_type == PNG_INTRAPIXEL_DIFFERENCING))
  181011. {
  181012. /* Intrapixel differencing */
  181013. png_do_read_intrapixel(&(png_ptr->row_info), png_ptr->row_buf + 1);
  181014. }
  181015. #endif
  181016. if (png_ptr->transformations || (png_ptr->flags&PNG_FLAG_STRIP_ALPHA))
  181017. png_do_read_transformations(png_ptr);
  181018. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  181019. /* blow up interlaced rows to full size */
  181020. if (png_ptr->interlaced &&
  181021. (png_ptr->transformations & PNG_INTERLACE))
  181022. {
  181023. if (png_ptr->pass < 6)
  181024. /* old interface (pre-1.0.9):
  181025. png_do_read_interlace(&(png_ptr->row_info),
  181026. png_ptr->row_buf + 1, png_ptr->pass, png_ptr->transformations);
  181027. */
  181028. png_do_read_interlace(png_ptr);
  181029. if (dsp_row != NULL)
  181030. png_combine_row(png_ptr, dsp_row,
  181031. png_pass_dsp_mask[png_ptr->pass]);
  181032. if (row != NULL)
  181033. png_combine_row(png_ptr, row,
  181034. png_pass_mask[png_ptr->pass]);
  181035. }
  181036. else
  181037. #endif
  181038. {
  181039. if (row != NULL)
  181040. png_combine_row(png_ptr, row, 0xff);
  181041. if (dsp_row != NULL)
  181042. png_combine_row(png_ptr, dsp_row, 0xff);
  181043. }
  181044. png_read_finish_row(png_ptr);
  181045. if (png_ptr->read_row_fn != NULL)
  181046. (*(png_ptr->read_row_fn))(png_ptr, png_ptr->row_number, png_ptr->pass);
  181047. }
  181048. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  181049. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  181050. /* Read one or more rows of image data. If the image is interlaced,
  181051. * and png_set_interlace_handling() has been called, the rows need to
  181052. * contain the contents of the rows from the previous pass. If the
  181053. * image has alpha or transparency, and png_handle_alpha()[*] has been
  181054. * called, the rows contents must be initialized to the contents of the
  181055. * screen.
  181056. *
  181057. * "row" holds the actual image, and pixels are placed in it
  181058. * as they arrive. If the image is displayed after each pass, it will
  181059. * appear to "sparkle" in. "display_row" can be used to display a
  181060. * "chunky" progressive image, with finer detail added as it becomes
  181061. * available. If you do not want this "chunky" display, you may pass
  181062. * NULL for display_row. If you do not want the sparkle display, and
  181063. * you have not called png_handle_alpha(), you may pass NULL for rows.
  181064. * If you have called png_handle_alpha(), and the image has either an
  181065. * alpha channel or a transparency chunk, you must provide a buffer for
  181066. * rows. In this case, you do not have to provide a display_row buffer
  181067. * also, but you may. If the image is not interlaced, or if you have
  181068. * not called png_set_interlace_handling(), the display_row buffer will
  181069. * be ignored, so pass NULL to it.
  181070. *
  181071. * [*] png_handle_alpha() does not exist yet, as of this version of libpng
  181072. */
  181073. void PNGAPI
  181074. png_read_rows(png_structp png_ptr, png_bytepp row,
  181075. png_bytepp display_row, png_uint_32 num_rows)
  181076. {
  181077. png_uint_32 i;
  181078. png_bytepp rp;
  181079. png_bytepp dp;
  181080. png_debug(1, "in png_read_rows\n");
  181081. if(png_ptr == NULL) return;
  181082. rp = row;
  181083. dp = display_row;
  181084. if (rp != NULL && dp != NULL)
  181085. for (i = 0; i < num_rows; i++)
  181086. {
  181087. png_bytep rptr = *rp++;
  181088. png_bytep dptr = *dp++;
  181089. png_read_row(png_ptr, rptr, dptr);
  181090. }
  181091. else if(rp != NULL)
  181092. for (i = 0; i < num_rows; i++)
  181093. {
  181094. png_bytep rptr = *rp;
  181095. png_read_row(png_ptr, rptr, png_bytep_NULL);
  181096. rp++;
  181097. }
  181098. else if(dp != NULL)
  181099. for (i = 0; i < num_rows; i++)
  181100. {
  181101. png_bytep dptr = *dp;
  181102. png_read_row(png_ptr, png_bytep_NULL, dptr);
  181103. dp++;
  181104. }
  181105. }
  181106. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  181107. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  181108. /* Read the entire image. If the image has an alpha channel or a tRNS
  181109. * chunk, and you have called png_handle_alpha()[*], you will need to
  181110. * initialize the image to the current image that PNG will be overlaying.
  181111. * We set the num_rows again here, in case it was incorrectly set in
  181112. * png_read_start_row() by a call to png_read_update_info() or
  181113. * png_start_read_image() if png_set_interlace_handling() wasn't called
  181114. * prior to either of these functions like it should have been. You can
  181115. * only call this function once. If you desire to have an image for
  181116. * each pass of a interlaced image, use png_read_rows() instead.
  181117. *
  181118. * [*] png_handle_alpha() does not exist yet, as of this version of libpng
  181119. */
  181120. void PNGAPI
  181121. png_read_image(png_structp png_ptr, png_bytepp image)
  181122. {
  181123. png_uint_32 i,image_height;
  181124. int pass, j;
  181125. png_bytepp rp;
  181126. png_debug(1, "in png_read_image\n");
  181127. if(png_ptr == NULL) return;
  181128. #ifdef PNG_READ_INTERLACING_SUPPORTED
  181129. pass = png_set_interlace_handling(png_ptr);
  181130. #else
  181131. if (png_ptr->interlaced)
  181132. png_error(png_ptr,
  181133. "Cannot read interlaced image -- interlace handler disabled.");
  181134. pass = 1;
  181135. #endif
  181136. image_height=png_ptr->height;
  181137. png_ptr->num_rows = image_height; /* Make sure this is set correctly */
  181138. for (j = 0; j < pass; j++)
  181139. {
  181140. rp = image;
  181141. for (i = 0; i < image_height; i++)
  181142. {
  181143. png_read_row(png_ptr, *rp, png_bytep_NULL);
  181144. rp++;
  181145. }
  181146. }
  181147. }
  181148. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  181149. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  181150. /* Read the end of the PNG file. Will not read past the end of the
  181151. * file, will verify the end is accurate, and will read any comments
  181152. * or time information at the end of the file, if info is not NULL.
  181153. */
  181154. void PNGAPI
  181155. png_read_end(png_structp png_ptr, png_infop info_ptr)
  181156. {
  181157. png_byte chunk_length[4];
  181158. png_uint_32 length;
  181159. png_debug(1, "in png_read_end\n");
  181160. if(png_ptr == NULL) return;
  181161. png_crc_finish(png_ptr, 0); /* Finish off CRC from last IDAT chunk */
  181162. do
  181163. {
  181164. #ifdef PNG_USE_LOCAL_ARRAYS
  181165. PNG_CONST PNG_IHDR;
  181166. PNG_CONST PNG_IDAT;
  181167. PNG_CONST PNG_IEND;
  181168. PNG_CONST PNG_PLTE;
  181169. #if defined(PNG_READ_bKGD_SUPPORTED)
  181170. PNG_CONST PNG_bKGD;
  181171. #endif
  181172. #if defined(PNG_READ_cHRM_SUPPORTED)
  181173. PNG_CONST PNG_cHRM;
  181174. #endif
  181175. #if defined(PNG_READ_gAMA_SUPPORTED)
  181176. PNG_CONST PNG_gAMA;
  181177. #endif
  181178. #if defined(PNG_READ_hIST_SUPPORTED)
  181179. PNG_CONST PNG_hIST;
  181180. #endif
  181181. #if defined(PNG_READ_iCCP_SUPPORTED)
  181182. PNG_CONST PNG_iCCP;
  181183. #endif
  181184. #if defined(PNG_READ_iTXt_SUPPORTED)
  181185. PNG_CONST PNG_iTXt;
  181186. #endif
  181187. #if defined(PNG_READ_oFFs_SUPPORTED)
  181188. PNG_CONST PNG_oFFs;
  181189. #endif
  181190. #if defined(PNG_READ_pCAL_SUPPORTED)
  181191. PNG_CONST PNG_pCAL;
  181192. #endif
  181193. #if defined(PNG_READ_pHYs_SUPPORTED)
  181194. PNG_CONST PNG_pHYs;
  181195. #endif
  181196. #if defined(PNG_READ_sBIT_SUPPORTED)
  181197. PNG_CONST PNG_sBIT;
  181198. #endif
  181199. #if defined(PNG_READ_sCAL_SUPPORTED)
  181200. PNG_CONST PNG_sCAL;
  181201. #endif
  181202. #if defined(PNG_READ_sPLT_SUPPORTED)
  181203. PNG_CONST PNG_sPLT;
  181204. #endif
  181205. #if defined(PNG_READ_sRGB_SUPPORTED)
  181206. PNG_CONST PNG_sRGB;
  181207. #endif
  181208. #if defined(PNG_READ_tEXt_SUPPORTED)
  181209. PNG_CONST PNG_tEXt;
  181210. #endif
  181211. #if defined(PNG_READ_tIME_SUPPORTED)
  181212. PNG_CONST PNG_tIME;
  181213. #endif
  181214. #if defined(PNG_READ_tRNS_SUPPORTED)
  181215. PNG_CONST PNG_tRNS;
  181216. #endif
  181217. #if defined(PNG_READ_zTXt_SUPPORTED)
  181218. PNG_CONST PNG_zTXt;
  181219. #endif
  181220. #endif /* PNG_USE_LOCAL_ARRAYS */
  181221. png_read_data(png_ptr, chunk_length, 4);
  181222. length = png_get_uint_31(png_ptr,chunk_length);
  181223. png_reset_crc(png_ptr);
  181224. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  181225. png_debug1(0, "Reading %s chunk.\n", png_ptr->chunk_name);
  181226. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  181227. png_handle_IHDR(png_ptr, info_ptr, length);
  181228. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  181229. png_handle_IEND(png_ptr, info_ptr, length);
  181230. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  181231. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  181232. {
  181233. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  181234. {
  181235. if ((length > 0) || (png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  181236. png_error(png_ptr, "Too many IDAT's found");
  181237. }
  181238. png_handle_unknown(png_ptr, info_ptr, length);
  181239. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  181240. png_ptr->mode |= PNG_HAVE_PLTE;
  181241. }
  181242. #endif
  181243. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  181244. {
  181245. /* Zero length IDATs are legal after the last IDAT has been
  181246. * read, but not after other chunks have been read.
  181247. */
  181248. if ((length > 0) || (png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  181249. png_error(png_ptr, "Too many IDAT's found");
  181250. png_crc_finish(png_ptr, length);
  181251. }
  181252. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  181253. png_handle_PLTE(png_ptr, info_ptr, length);
  181254. #if defined(PNG_READ_bKGD_SUPPORTED)
  181255. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  181256. png_handle_bKGD(png_ptr, info_ptr, length);
  181257. #endif
  181258. #if defined(PNG_READ_cHRM_SUPPORTED)
  181259. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  181260. png_handle_cHRM(png_ptr, info_ptr, length);
  181261. #endif
  181262. #if defined(PNG_READ_gAMA_SUPPORTED)
  181263. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  181264. png_handle_gAMA(png_ptr, info_ptr, length);
  181265. #endif
  181266. #if defined(PNG_READ_hIST_SUPPORTED)
  181267. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  181268. png_handle_hIST(png_ptr, info_ptr, length);
  181269. #endif
  181270. #if defined(PNG_READ_oFFs_SUPPORTED)
  181271. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  181272. png_handle_oFFs(png_ptr, info_ptr, length);
  181273. #endif
  181274. #if defined(PNG_READ_pCAL_SUPPORTED)
  181275. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  181276. png_handle_pCAL(png_ptr, info_ptr, length);
  181277. #endif
  181278. #if defined(PNG_READ_sCAL_SUPPORTED)
  181279. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  181280. png_handle_sCAL(png_ptr, info_ptr, length);
  181281. #endif
  181282. #if defined(PNG_READ_pHYs_SUPPORTED)
  181283. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  181284. png_handle_pHYs(png_ptr, info_ptr, length);
  181285. #endif
  181286. #if defined(PNG_READ_sBIT_SUPPORTED)
  181287. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  181288. png_handle_sBIT(png_ptr, info_ptr, length);
  181289. #endif
  181290. #if defined(PNG_READ_sRGB_SUPPORTED)
  181291. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  181292. png_handle_sRGB(png_ptr, info_ptr, length);
  181293. #endif
  181294. #if defined(PNG_READ_iCCP_SUPPORTED)
  181295. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  181296. png_handle_iCCP(png_ptr, info_ptr, length);
  181297. #endif
  181298. #if defined(PNG_READ_sPLT_SUPPORTED)
  181299. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  181300. png_handle_sPLT(png_ptr, info_ptr, length);
  181301. #endif
  181302. #if defined(PNG_READ_tEXt_SUPPORTED)
  181303. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  181304. png_handle_tEXt(png_ptr, info_ptr, length);
  181305. #endif
  181306. #if defined(PNG_READ_tIME_SUPPORTED)
  181307. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  181308. png_handle_tIME(png_ptr, info_ptr, length);
  181309. #endif
  181310. #if defined(PNG_READ_tRNS_SUPPORTED)
  181311. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  181312. png_handle_tRNS(png_ptr, info_ptr, length);
  181313. #endif
  181314. #if defined(PNG_READ_zTXt_SUPPORTED)
  181315. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  181316. png_handle_zTXt(png_ptr, info_ptr, length);
  181317. #endif
  181318. #if defined(PNG_READ_iTXt_SUPPORTED)
  181319. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  181320. png_handle_iTXt(png_ptr, info_ptr, length);
  181321. #endif
  181322. else
  181323. png_handle_unknown(png_ptr, info_ptr, length);
  181324. } while (!(png_ptr->mode & PNG_HAVE_IEND));
  181325. }
  181326. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  181327. /* free all memory used by the read */
  181328. void PNGAPI
  181329. png_destroy_read_struct(png_structpp png_ptr_ptr, png_infopp info_ptr_ptr,
  181330. png_infopp end_info_ptr_ptr)
  181331. {
  181332. png_structp png_ptr = NULL;
  181333. png_infop info_ptr = NULL, end_info_ptr = NULL;
  181334. #ifdef PNG_USER_MEM_SUPPORTED
  181335. png_free_ptr free_fn;
  181336. png_voidp mem_ptr;
  181337. #endif
  181338. png_debug(1, "in png_destroy_read_struct\n");
  181339. if (png_ptr_ptr != NULL)
  181340. png_ptr = *png_ptr_ptr;
  181341. if (info_ptr_ptr != NULL)
  181342. info_ptr = *info_ptr_ptr;
  181343. if (end_info_ptr_ptr != NULL)
  181344. end_info_ptr = *end_info_ptr_ptr;
  181345. #ifdef PNG_USER_MEM_SUPPORTED
  181346. free_fn = png_ptr->free_fn;
  181347. mem_ptr = png_ptr->mem_ptr;
  181348. #endif
  181349. png_read_destroy(png_ptr, info_ptr, end_info_ptr);
  181350. if (info_ptr != NULL)
  181351. {
  181352. #if defined(PNG_TEXT_SUPPORTED)
  181353. png_free_data(png_ptr, info_ptr, PNG_FREE_TEXT, -1);
  181354. #endif
  181355. #ifdef PNG_USER_MEM_SUPPORTED
  181356. png_destroy_struct_2((png_voidp)info_ptr, (png_free_ptr)free_fn,
  181357. (png_voidp)mem_ptr);
  181358. #else
  181359. png_destroy_struct((png_voidp)info_ptr);
  181360. #endif
  181361. *info_ptr_ptr = NULL;
  181362. }
  181363. if (end_info_ptr != NULL)
  181364. {
  181365. #if defined(PNG_READ_TEXT_SUPPORTED)
  181366. png_free_data(png_ptr, end_info_ptr, PNG_FREE_TEXT, -1);
  181367. #endif
  181368. #ifdef PNG_USER_MEM_SUPPORTED
  181369. png_destroy_struct_2((png_voidp)end_info_ptr, (png_free_ptr)free_fn,
  181370. (png_voidp)mem_ptr);
  181371. #else
  181372. png_destroy_struct((png_voidp)end_info_ptr);
  181373. #endif
  181374. *end_info_ptr_ptr = NULL;
  181375. }
  181376. if (png_ptr != NULL)
  181377. {
  181378. #ifdef PNG_USER_MEM_SUPPORTED
  181379. png_destroy_struct_2((png_voidp)png_ptr, (png_free_ptr)free_fn,
  181380. (png_voidp)mem_ptr);
  181381. #else
  181382. png_destroy_struct((png_voidp)png_ptr);
  181383. #endif
  181384. *png_ptr_ptr = NULL;
  181385. }
  181386. }
  181387. /* free all memory used by the read (old method) */
  181388. void /* PRIVATE */
  181389. png_read_destroy(png_structp png_ptr, png_infop info_ptr, png_infop end_info_ptr)
  181390. {
  181391. #ifdef PNG_SETJMP_SUPPORTED
  181392. jmp_buf tmp_jmp;
  181393. #endif
  181394. png_error_ptr error_fn;
  181395. png_error_ptr warning_fn;
  181396. png_voidp error_ptr;
  181397. #ifdef PNG_USER_MEM_SUPPORTED
  181398. png_free_ptr free_fn;
  181399. #endif
  181400. png_debug(1, "in png_read_destroy\n");
  181401. if (info_ptr != NULL)
  181402. png_info_destroy(png_ptr, info_ptr);
  181403. if (end_info_ptr != NULL)
  181404. png_info_destroy(png_ptr, end_info_ptr);
  181405. png_free(png_ptr, png_ptr->zbuf);
  181406. png_free(png_ptr, png_ptr->big_row_buf);
  181407. png_free(png_ptr, png_ptr->prev_row);
  181408. #if defined(PNG_READ_DITHER_SUPPORTED)
  181409. png_free(png_ptr, png_ptr->palette_lookup);
  181410. png_free(png_ptr, png_ptr->dither_index);
  181411. #endif
  181412. #if defined(PNG_READ_GAMMA_SUPPORTED)
  181413. png_free(png_ptr, png_ptr->gamma_table);
  181414. #endif
  181415. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  181416. png_free(png_ptr, png_ptr->gamma_from_1);
  181417. png_free(png_ptr, png_ptr->gamma_to_1);
  181418. #endif
  181419. #ifdef PNG_FREE_ME_SUPPORTED
  181420. if (png_ptr->free_me & PNG_FREE_PLTE)
  181421. png_zfree(png_ptr, png_ptr->palette);
  181422. png_ptr->free_me &= ~PNG_FREE_PLTE;
  181423. #else
  181424. if (png_ptr->flags & PNG_FLAG_FREE_PLTE)
  181425. png_zfree(png_ptr, png_ptr->palette);
  181426. png_ptr->flags &= ~PNG_FLAG_FREE_PLTE;
  181427. #endif
  181428. #if defined(PNG_tRNS_SUPPORTED) || \
  181429. defined(PNG_READ_EXPAND_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  181430. #ifdef PNG_FREE_ME_SUPPORTED
  181431. if (png_ptr->free_me & PNG_FREE_TRNS)
  181432. png_free(png_ptr, png_ptr->trans);
  181433. png_ptr->free_me &= ~PNG_FREE_TRNS;
  181434. #else
  181435. if (png_ptr->flags & PNG_FLAG_FREE_TRNS)
  181436. png_free(png_ptr, png_ptr->trans);
  181437. png_ptr->flags &= ~PNG_FLAG_FREE_TRNS;
  181438. #endif
  181439. #endif
  181440. #if defined(PNG_READ_hIST_SUPPORTED)
  181441. #ifdef PNG_FREE_ME_SUPPORTED
  181442. if (png_ptr->free_me & PNG_FREE_HIST)
  181443. png_free(png_ptr, png_ptr->hist);
  181444. png_ptr->free_me &= ~PNG_FREE_HIST;
  181445. #else
  181446. if (png_ptr->flags & PNG_FLAG_FREE_HIST)
  181447. png_free(png_ptr, png_ptr->hist);
  181448. png_ptr->flags &= ~PNG_FLAG_FREE_HIST;
  181449. #endif
  181450. #endif
  181451. #if defined(PNG_READ_GAMMA_SUPPORTED)
  181452. if (png_ptr->gamma_16_table != NULL)
  181453. {
  181454. int i;
  181455. int istop = (1 << (8 - png_ptr->gamma_shift));
  181456. for (i = 0; i < istop; i++)
  181457. {
  181458. png_free(png_ptr, png_ptr->gamma_16_table[i]);
  181459. }
  181460. png_free(png_ptr, png_ptr->gamma_16_table);
  181461. }
  181462. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  181463. if (png_ptr->gamma_16_from_1 != NULL)
  181464. {
  181465. int i;
  181466. int istop = (1 << (8 - png_ptr->gamma_shift));
  181467. for (i = 0; i < istop; i++)
  181468. {
  181469. png_free(png_ptr, png_ptr->gamma_16_from_1[i]);
  181470. }
  181471. png_free(png_ptr, png_ptr->gamma_16_from_1);
  181472. }
  181473. if (png_ptr->gamma_16_to_1 != NULL)
  181474. {
  181475. int i;
  181476. int istop = (1 << (8 - png_ptr->gamma_shift));
  181477. for (i = 0; i < istop; i++)
  181478. {
  181479. png_free(png_ptr, png_ptr->gamma_16_to_1[i]);
  181480. }
  181481. png_free(png_ptr, png_ptr->gamma_16_to_1);
  181482. }
  181483. #endif
  181484. #endif
  181485. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  181486. png_free(png_ptr, png_ptr->time_buffer);
  181487. #endif
  181488. inflateEnd(&png_ptr->zstream);
  181489. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  181490. png_free(png_ptr, png_ptr->save_buffer);
  181491. #endif
  181492. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  181493. #ifdef PNG_TEXT_SUPPORTED
  181494. png_free(png_ptr, png_ptr->current_text);
  181495. #endif /* PNG_TEXT_SUPPORTED */
  181496. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  181497. /* Save the important info out of the png_struct, in case it is
  181498. * being used again.
  181499. */
  181500. #ifdef PNG_SETJMP_SUPPORTED
  181501. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  181502. #endif
  181503. error_fn = png_ptr->error_fn;
  181504. warning_fn = png_ptr->warning_fn;
  181505. error_ptr = png_ptr->error_ptr;
  181506. #ifdef PNG_USER_MEM_SUPPORTED
  181507. free_fn = png_ptr->free_fn;
  181508. #endif
  181509. png_memset(png_ptr, 0, png_sizeof (png_struct));
  181510. png_ptr->error_fn = error_fn;
  181511. png_ptr->warning_fn = warning_fn;
  181512. png_ptr->error_ptr = error_ptr;
  181513. #ifdef PNG_USER_MEM_SUPPORTED
  181514. png_ptr->free_fn = free_fn;
  181515. #endif
  181516. #ifdef PNG_SETJMP_SUPPORTED
  181517. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  181518. #endif
  181519. }
  181520. void PNGAPI
  181521. png_set_read_status_fn(png_structp png_ptr, png_read_status_ptr read_row_fn)
  181522. {
  181523. if(png_ptr == NULL) return;
  181524. png_ptr->read_row_fn = read_row_fn;
  181525. }
  181526. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  181527. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  181528. void PNGAPI
  181529. png_read_png(png_structp png_ptr, png_infop info_ptr,
  181530. int transforms,
  181531. voidp params)
  181532. {
  181533. int row;
  181534. if(png_ptr == NULL) return;
  181535. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  181536. /* invert the alpha channel from opacity to transparency
  181537. */
  181538. if (transforms & PNG_TRANSFORM_INVERT_ALPHA)
  181539. png_set_invert_alpha(png_ptr);
  181540. #endif
  181541. /* png_read_info() gives us all of the information from the
  181542. * PNG file before the first IDAT (image data chunk).
  181543. */
  181544. png_read_info(png_ptr, info_ptr);
  181545. if (info_ptr->height > PNG_UINT_32_MAX/png_sizeof(png_bytep))
  181546. png_error(png_ptr,"Image is too high to process with png_read_png()");
  181547. /* -------------- image transformations start here ------------------- */
  181548. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  181549. /* tell libpng to strip 16 bit/color files down to 8 bits per color
  181550. */
  181551. if (transforms & PNG_TRANSFORM_STRIP_16)
  181552. png_set_strip_16(png_ptr);
  181553. #endif
  181554. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  181555. /* Strip alpha bytes from the input data without combining with
  181556. * the background (not recommended).
  181557. */
  181558. if (transforms & PNG_TRANSFORM_STRIP_ALPHA)
  181559. png_set_strip_alpha(png_ptr);
  181560. #endif
  181561. #if defined(PNG_READ_PACK_SUPPORTED) && !defined(PNG_READ_EXPAND_SUPPORTED)
  181562. /* Extract multiple pixels with bit depths of 1, 2, or 4 from a single
  181563. * byte into separate bytes (useful for paletted and grayscale images).
  181564. */
  181565. if (transforms & PNG_TRANSFORM_PACKING)
  181566. png_set_packing(png_ptr);
  181567. #endif
  181568. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  181569. /* Change the order of packed pixels to least significant bit first
  181570. * (not useful if you are using png_set_packing).
  181571. */
  181572. if (transforms & PNG_TRANSFORM_PACKSWAP)
  181573. png_set_packswap(png_ptr);
  181574. #endif
  181575. #if defined(PNG_READ_EXPAND_SUPPORTED)
  181576. /* Expand paletted colors into true RGB triplets
  181577. * Expand grayscale images to full 8 bits from 1, 2, or 4 bits/pixel
  181578. * Expand paletted or RGB images with transparency to full alpha
  181579. * channels so the data will be available as RGBA quartets.
  181580. */
  181581. if (transforms & PNG_TRANSFORM_EXPAND)
  181582. if ((png_ptr->bit_depth < 8) ||
  181583. (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE) ||
  181584. (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)))
  181585. png_set_expand(png_ptr);
  181586. #endif
  181587. /* We don't handle background color or gamma transformation or dithering.
  181588. */
  181589. #if defined(PNG_READ_INVERT_SUPPORTED)
  181590. /* invert monochrome files to have 0 as white and 1 as black
  181591. */
  181592. if (transforms & PNG_TRANSFORM_INVERT_MONO)
  181593. png_set_invert_mono(png_ptr);
  181594. #endif
  181595. #if defined(PNG_READ_SHIFT_SUPPORTED)
  181596. /* If you want to shift the pixel values from the range [0,255] or
  181597. * [0,65535] to the original [0,7] or [0,31], or whatever range the
  181598. * colors were originally in:
  181599. */
  181600. if ((transforms & PNG_TRANSFORM_SHIFT)
  181601. && png_get_valid(png_ptr, info_ptr, PNG_INFO_sBIT))
  181602. {
  181603. png_color_8p sig_bit;
  181604. png_get_sBIT(png_ptr, info_ptr, &sig_bit);
  181605. png_set_shift(png_ptr, sig_bit);
  181606. }
  181607. #endif
  181608. #if defined(PNG_READ_BGR_SUPPORTED)
  181609. /* flip the RGB pixels to BGR (or RGBA to BGRA)
  181610. */
  181611. if (transforms & PNG_TRANSFORM_BGR)
  181612. png_set_bgr(png_ptr);
  181613. #endif
  181614. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  181615. /* swap the RGBA or GA data to ARGB or AG (or BGRA to ABGR)
  181616. */
  181617. if (transforms & PNG_TRANSFORM_SWAP_ALPHA)
  181618. png_set_swap_alpha(png_ptr);
  181619. #endif
  181620. #if defined(PNG_READ_SWAP_SUPPORTED)
  181621. /* swap bytes of 16 bit files to least significant byte first
  181622. */
  181623. if (transforms & PNG_TRANSFORM_SWAP_ENDIAN)
  181624. png_set_swap(png_ptr);
  181625. #endif
  181626. /* We don't handle adding filler bytes */
  181627. /* Optional call to gamma correct and add the background to the palette
  181628. * and update info structure. REQUIRED if you are expecting libpng to
  181629. * update the palette for you (i.e., you selected such a transform above).
  181630. */
  181631. png_read_update_info(png_ptr, info_ptr);
  181632. /* -------------- image transformations end here ------------------- */
  181633. #ifdef PNG_FREE_ME_SUPPORTED
  181634. png_free_data(png_ptr, info_ptr, PNG_FREE_ROWS, 0);
  181635. #endif
  181636. if(info_ptr->row_pointers == NULL)
  181637. {
  181638. info_ptr->row_pointers = (png_bytepp)png_malloc(png_ptr,
  181639. info_ptr->height * png_sizeof(png_bytep));
  181640. #ifdef PNG_FREE_ME_SUPPORTED
  181641. info_ptr->free_me |= PNG_FREE_ROWS;
  181642. #endif
  181643. for (row = 0; row < (int)info_ptr->height; row++)
  181644. {
  181645. info_ptr->row_pointers[row] = (png_bytep)png_malloc(png_ptr,
  181646. png_get_rowbytes(png_ptr, info_ptr));
  181647. }
  181648. }
  181649. png_read_image(png_ptr, info_ptr->row_pointers);
  181650. info_ptr->valid |= PNG_INFO_IDAT;
  181651. /* read rest of file, and get additional chunks in info_ptr - REQUIRED */
  181652. png_read_end(png_ptr, info_ptr);
  181653. transforms = transforms; /* quiet compiler warnings */
  181654. params = params;
  181655. }
  181656. #endif /* PNG_INFO_IMAGE_SUPPORTED */
  181657. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  181658. #endif /* PNG_READ_SUPPORTED */
  181659. /********* End of inlined file: pngread.c *********/
  181660. /********* Start of inlined file: pngpread.c *********/
  181661. /* pngpread.c - read a png file in push mode
  181662. *
  181663. * Last changed in libpng 1.2.21 October 4, 2007
  181664. * For conditions of distribution and use, see copyright notice in png.h
  181665. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  181666. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  181667. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  181668. */
  181669. #define PNG_INTERNAL
  181670. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  181671. /* push model modes */
  181672. #define PNG_READ_SIG_MODE 0
  181673. #define PNG_READ_CHUNK_MODE 1
  181674. #define PNG_READ_IDAT_MODE 2
  181675. #define PNG_SKIP_MODE 3
  181676. #define PNG_READ_tEXt_MODE 4
  181677. #define PNG_READ_zTXt_MODE 5
  181678. #define PNG_READ_DONE_MODE 6
  181679. #define PNG_READ_iTXt_MODE 7
  181680. #define PNG_ERROR_MODE 8
  181681. void PNGAPI
  181682. png_process_data(png_structp png_ptr, png_infop info_ptr,
  181683. png_bytep buffer, png_size_t buffer_size)
  181684. {
  181685. if(png_ptr == NULL) return;
  181686. png_push_restore_buffer(png_ptr, buffer, buffer_size);
  181687. while (png_ptr->buffer_size)
  181688. {
  181689. png_process_some_data(png_ptr, info_ptr);
  181690. }
  181691. }
  181692. /* What we do with the incoming data depends on what we were previously
  181693. * doing before we ran out of data...
  181694. */
  181695. void /* PRIVATE */
  181696. png_process_some_data(png_structp png_ptr, png_infop info_ptr)
  181697. {
  181698. if(png_ptr == NULL) return;
  181699. switch (png_ptr->process_mode)
  181700. {
  181701. case PNG_READ_SIG_MODE:
  181702. {
  181703. png_push_read_sig(png_ptr, info_ptr);
  181704. break;
  181705. }
  181706. case PNG_READ_CHUNK_MODE:
  181707. {
  181708. png_push_read_chunk(png_ptr, info_ptr);
  181709. break;
  181710. }
  181711. case PNG_READ_IDAT_MODE:
  181712. {
  181713. png_push_read_IDAT(png_ptr);
  181714. break;
  181715. }
  181716. #if defined(PNG_READ_tEXt_SUPPORTED)
  181717. case PNG_READ_tEXt_MODE:
  181718. {
  181719. png_push_read_tEXt(png_ptr, info_ptr);
  181720. break;
  181721. }
  181722. #endif
  181723. #if defined(PNG_READ_zTXt_SUPPORTED)
  181724. case PNG_READ_zTXt_MODE:
  181725. {
  181726. png_push_read_zTXt(png_ptr, info_ptr);
  181727. break;
  181728. }
  181729. #endif
  181730. #if defined(PNG_READ_iTXt_SUPPORTED)
  181731. case PNG_READ_iTXt_MODE:
  181732. {
  181733. png_push_read_iTXt(png_ptr, info_ptr);
  181734. break;
  181735. }
  181736. #endif
  181737. case PNG_SKIP_MODE:
  181738. {
  181739. png_push_crc_finish(png_ptr);
  181740. break;
  181741. }
  181742. default:
  181743. {
  181744. png_ptr->buffer_size = 0;
  181745. break;
  181746. }
  181747. }
  181748. }
  181749. /* Read any remaining signature bytes from the stream and compare them with
  181750. * the correct PNG signature. It is possible that this routine is called
  181751. * with bytes already read from the signature, either because they have been
  181752. * checked by the calling application, or because of multiple calls to this
  181753. * routine.
  181754. */
  181755. void /* PRIVATE */
  181756. png_push_read_sig(png_structp png_ptr, png_infop info_ptr)
  181757. {
  181758. png_size_t num_checked = png_ptr->sig_bytes,
  181759. num_to_check = 8 - num_checked;
  181760. if (png_ptr->buffer_size < num_to_check)
  181761. {
  181762. num_to_check = png_ptr->buffer_size;
  181763. }
  181764. png_push_fill_buffer(png_ptr, &(info_ptr->signature[num_checked]),
  181765. num_to_check);
  181766. png_ptr->sig_bytes = (png_byte)(png_ptr->sig_bytes+num_to_check);
  181767. if (png_sig_cmp(info_ptr->signature, num_checked, num_to_check))
  181768. {
  181769. if (num_checked < 4 &&
  181770. png_sig_cmp(info_ptr->signature, num_checked, num_to_check - 4))
  181771. png_error(png_ptr, "Not a PNG file");
  181772. else
  181773. png_error(png_ptr, "PNG file corrupted by ASCII conversion");
  181774. }
  181775. else
  181776. {
  181777. if (png_ptr->sig_bytes >= 8)
  181778. {
  181779. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  181780. }
  181781. }
  181782. }
  181783. void /* PRIVATE */
  181784. png_push_read_chunk(png_structp png_ptr, png_infop info_ptr)
  181785. {
  181786. #ifdef PNG_USE_LOCAL_ARRAYS
  181787. PNG_CONST PNG_IHDR;
  181788. PNG_CONST PNG_IDAT;
  181789. PNG_CONST PNG_IEND;
  181790. PNG_CONST PNG_PLTE;
  181791. #if defined(PNG_READ_bKGD_SUPPORTED)
  181792. PNG_CONST PNG_bKGD;
  181793. #endif
  181794. #if defined(PNG_READ_cHRM_SUPPORTED)
  181795. PNG_CONST PNG_cHRM;
  181796. #endif
  181797. #if defined(PNG_READ_gAMA_SUPPORTED)
  181798. PNG_CONST PNG_gAMA;
  181799. #endif
  181800. #if defined(PNG_READ_hIST_SUPPORTED)
  181801. PNG_CONST PNG_hIST;
  181802. #endif
  181803. #if defined(PNG_READ_iCCP_SUPPORTED)
  181804. PNG_CONST PNG_iCCP;
  181805. #endif
  181806. #if defined(PNG_READ_iTXt_SUPPORTED)
  181807. PNG_CONST PNG_iTXt;
  181808. #endif
  181809. #if defined(PNG_READ_oFFs_SUPPORTED)
  181810. PNG_CONST PNG_oFFs;
  181811. #endif
  181812. #if defined(PNG_READ_pCAL_SUPPORTED)
  181813. PNG_CONST PNG_pCAL;
  181814. #endif
  181815. #if defined(PNG_READ_pHYs_SUPPORTED)
  181816. PNG_CONST PNG_pHYs;
  181817. #endif
  181818. #if defined(PNG_READ_sBIT_SUPPORTED)
  181819. PNG_CONST PNG_sBIT;
  181820. #endif
  181821. #if defined(PNG_READ_sCAL_SUPPORTED)
  181822. PNG_CONST PNG_sCAL;
  181823. #endif
  181824. #if defined(PNG_READ_sRGB_SUPPORTED)
  181825. PNG_CONST PNG_sRGB;
  181826. #endif
  181827. #if defined(PNG_READ_sPLT_SUPPORTED)
  181828. PNG_CONST PNG_sPLT;
  181829. #endif
  181830. #if defined(PNG_READ_tEXt_SUPPORTED)
  181831. PNG_CONST PNG_tEXt;
  181832. #endif
  181833. #if defined(PNG_READ_tIME_SUPPORTED)
  181834. PNG_CONST PNG_tIME;
  181835. #endif
  181836. #if defined(PNG_READ_tRNS_SUPPORTED)
  181837. PNG_CONST PNG_tRNS;
  181838. #endif
  181839. #if defined(PNG_READ_zTXt_SUPPORTED)
  181840. PNG_CONST PNG_zTXt;
  181841. #endif
  181842. #endif /* PNG_USE_LOCAL_ARRAYS */
  181843. /* First we make sure we have enough data for the 4 byte chunk name
  181844. * and the 4 byte chunk length before proceeding with decoding the
  181845. * chunk data. To fully decode each of these chunks, we also make
  181846. * sure we have enough data in the buffer for the 4 byte CRC at the
  181847. * end of every chunk (except IDAT, which is handled separately).
  181848. */
  181849. if (!(png_ptr->mode & PNG_HAVE_CHUNK_HEADER))
  181850. {
  181851. png_byte chunk_length[4];
  181852. if (png_ptr->buffer_size < 8)
  181853. {
  181854. png_push_save_buffer(png_ptr);
  181855. return;
  181856. }
  181857. png_push_fill_buffer(png_ptr, chunk_length, 4);
  181858. png_ptr->push_length = png_get_uint_31(png_ptr,chunk_length);
  181859. png_reset_crc(png_ptr);
  181860. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  181861. png_ptr->mode |= PNG_HAVE_CHUNK_HEADER;
  181862. }
  181863. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  181864. if(png_ptr->mode & PNG_AFTER_IDAT)
  181865. png_ptr->mode |= PNG_HAVE_CHUNK_AFTER_IDAT;
  181866. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  181867. {
  181868. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  181869. {
  181870. png_push_save_buffer(png_ptr);
  181871. return;
  181872. }
  181873. png_handle_IHDR(png_ptr, info_ptr, png_ptr->push_length);
  181874. }
  181875. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  181876. {
  181877. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  181878. {
  181879. png_push_save_buffer(png_ptr);
  181880. return;
  181881. }
  181882. png_handle_IEND(png_ptr, info_ptr, png_ptr->push_length);
  181883. png_ptr->process_mode = PNG_READ_DONE_MODE;
  181884. png_push_have_end(png_ptr, info_ptr);
  181885. }
  181886. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  181887. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  181888. {
  181889. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  181890. {
  181891. png_push_save_buffer(png_ptr);
  181892. return;
  181893. }
  181894. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  181895. png_ptr->mode |= PNG_HAVE_IDAT;
  181896. png_handle_unknown(png_ptr, info_ptr, png_ptr->push_length);
  181897. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  181898. png_ptr->mode |= PNG_HAVE_PLTE;
  181899. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  181900. {
  181901. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  181902. png_error(png_ptr, "Missing IHDR before IDAT");
  181903. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  181904. !(png_ptr->mode & PNG_HAVE_PLTE))
  181905. png_error(png_ptr, "Missing PLTE before IDAT");
  181906. }
  181907. }
  181908. #endif
  181909. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  181910. {
  181911. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  181912. {
  181913. png_push_save_buffer(png_ptr);
  181914. return;
  181915. }
  181916. png_handle_PLTE(png_ptr, info_ptr, png_ptr->push_length);
  181917. }
  181918. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  181919. {
  181920. /* If we reach an IDAT chunk, this means we have read all of the
  181921. * header chunks, and we can start reading the image (or if this
  181922. * is called after the image has been read - we have an error).
  181923. */
  181924. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  181925. png_error(png_ptr, "Missing IHDR before IDAT");
  181926. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  181927. !(png_ptr->mode & PNG_HAVE_PLTE))
  181928. png_error(png_ptr, "Missing PLTE before IDAT");
  181929. if (png_ptr->mode & PNG_HAVE_IDAT)
  181930. {
  181931. if (!(png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  181932. if (png_ptr->push_length == 0)
  181933. return;
  181934. if (png_ptr->mode & PNG_AFTER_IDAT)
  181935. png_error(png_ptr, "Too many IDAT's found");
  181936. }
  181937. png_ptr->idat_size = png_ptr->push_length;
  181938. png_ptr->mode |= PNG_HAVE_IDAT;
  181939. png_ptr->process_mode = PNG_READ_IDAT_MODE;
  181940. png_push_have_info(png_ptr, info_ptr);
  181941. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  181942. png_ptr->zstream.next_out = png_ptr->row_buf;
  181943. return;
  181944. }
  181945. #if defined(PNG_READ_gAMA_SUPPORTED)
  181946. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  181947. {
  181948. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  181949. {
  181950. png_push_save_buffer(png_ptr);
  181951. return;
  181952. }
  181953. png_handle_gAMA(png_ptr, info_ptr, png_ptr->push_length);
  181954. }
  181955. #endif
  181956. #if defined(PNG_READ_sBIT_SUPPORTED)
  181957. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  181958. {
  181959. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  181960. {
  181961. png_push_save_buffer(png_ptr);
  181962. return;
  181963. }
  181964. png_handle_sBIT(png_ptr, info_ptr, png_ptr->push_length);
  181965. }
  181966. #endif
  181967. #if defined(PNG_READ_cHRM_SUPPORTED)
  181968. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  181969. {
  181970. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  181971. {
  181972. png_push_save_buffer(png_ptr);
  181973. return;
  181974. }
  181975. png_handle_cHRM(png_ptr, info_ptr, png_ptr->push_length);
  181976. }
  181977. #endif
  181978. #if defined(PNG_READ_sRGB_SUPPORTED)
  181979. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  181980. {
  181981. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  181982. {
  181983. png_push_save_buffer(png_ptr);
  181984. return;
  181985. }
  181986. png_handle_sRGB(png_ptr, info_ptr, png_ptr->push_length);
  181987. }
  181988. #endif
  181989. #if defined(PNG_READ_iCCP_SUPPORTED)
  181990. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  181991. {
  181992. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  181993. {
  181994. png_push_save_buffer(png_ptr);
  181995. return;
  181996. }
  181997. png_handle_iCCP(png_ptr, info_ptr, png_ptr->push_length);
  181998. }
  181999. #endif
  182000. #if defined(PNG_READ_sPLT_SUPPORTED)
  182001. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  182002. {
  182003. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  182004. {
  182005. png_push_save_buffer(png_ptr);
  182006. return;
  182007. }
  182008. png_handle_sPLT(png_ptr, info_ptr, png_ptr->push_length);
  182009. }
  182010. #endif
  182011. #if defined(PNG_READ_tRNS_SUPPORTED)
  182012. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  182013. {
  182014. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  182015. {
  182016. png_push_save_buffer(png_ptr);
  182017. return;
  182018. }
  182019. png_handle_tRNS(png_ptr, info_ptr, png_ptr->push_length);
  182020. }
  182021. #endif
  182022. #if defined(PNG_READ_bKGD_SUPPORTED)
  182023. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  182024. {
  182025. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  182026. {
  182027. png_push_save_buffer(png_ptr);
  182028. return;
  182029. }
  182030. png_handle_bKGD(png_ptr, info_ptr, png_ptr->push_length);
  182031. }
  182032. #endif
  182033. #if defined(PNG_READ_hIST_SUPPORTED)
  182034. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  182035. {
  182036. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  182037. {
  182038. png_push_save_buffer(png_ptr);
  182039. return;
  182040. }
  182041. png_handle_hIST(png_ptr, info_ptr, png_ptr->push_length);
  182042. }
  182043. #endif
  182044. #if defined(PNG_READ_pHYs_SUPPORTED)
  182045. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  182046. {
  182047. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  182048. {
  182049. png_push_save_buffer(png_ptr);
  182050. return;
  182051. }
  182052. png_handle_pHYs(png_ptr, info_ptr, png_ptr->push_length);
  182053. }
  182054. #endif
  182055. #if defined(PNG_READ_oFFs_SUPPORTED)
  182056. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  182057. {
  182058. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  182059. {
  182060. png_push_save_buffer(png_ptr);
  182061. return;
  182062. }
  182063. png_handle_oFFs(png_ptr, info_ptr, png_ptr->push_length);
  182064. }
  182065. #endif
  182066. #if defined(PNG_READ_pCAL_SUPPORTED)
  182067. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  182068. {
  182069. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  182070. {
  182071. png_push_save_buffer(png_ptr);
  182072. return;
  182073. }
  182074. png_handle_pCAL(png_ptr, info_ptr, png_ptr->push_length);
  182075. }
  182076. #endif
  182077. #if defined(PNG_READ_sCAL_SUPPORTED)
  182078. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  182079. {
  182080. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  182081. {
  182082. png_push_save_buffer(png_ptr);
  182083. return;
  182084. }
  182085. png_handle_sCAL(png_ptr, info_ptr, png_ptr->push_length);
  182086. }
  182087. #endif
  182088. #if defined(PNG_READ_tIME_SUPPORTED)
  182089. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  182090. {
  182091. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  182092. {
  182093. png_push_save_buffer(png_ptr);
  182094. return;
  182095. }
  182096. png_handle_tIME(png_ptr, info_ptr, png_ptr->push_length);
  182097. }
  182098. #endif
  182099. #if defined(PNG_READ_tEXt_SUPPORTED)
  182100. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  182101. {
  182102. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  182103. {
  182104. png_push_save_buffer(png_ptr);
  182105. return;
  182106. }
  182107. png_push_handle_tEXt(png_ptr, info_ptr, png_ptr->push_length);
  182108. }
  182109. #endif
  182110. #if defined(PNG_READ_zTXt_SUPPORTED)
  182111. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  182112. {
  182113. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  182114. {
  182115. png_push_save_buffer(png_ptr);
  182116. return;
  182117. }
  182118. png_push_handle_zTXt(png_ptr, info_ptr, png_ptr->push_length);
  182119. }
  182120. #endif
  182121. #if defined(PNG_READ_iTXt_SUPPORTED)
  182122. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  182123. {
  182124. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  182125. {
  182126. png_push_save_buffer(png_ptr);
  182127. return;
  182128. }
  182129. png_push_handle_iTXt(png_ptr, info_ptr, png_ptr->push_length);
  182130. }
  182131. #endif
  182132. else
  182133. {
  182134. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  182135. {
  182136. png_push_save_buffer(png_ptr);
  182137. return;
  182138. }
  182139. png_push_handle_unknown(png_ptr, info_ptr, png_ptr->push_length);
  182140. }
  182141. png_ptr->mode &= ~PNG_HAVE_CHUNK_HEADER;
  182142. }
  182143. void /* PRIVATE */
  182144. png_push_crc_skip(png_structp png_ptr, png_uint_32 skip)
  182145. {
  182146. png_ptr->process_mode = PNG_SKIP_MODE;
  182147. png_ptr->skip_length = skip;
  182148. }
  182149. void /* PRIVATE */
  182150. png_push_crc_finish(png_structp png_ptr)
  182151. {
  182152. if (png_ptr->skip_length && png_ptr->save_buffer_size)
  182153. {
  182154. png_size_t save_size;
  182155. if (png_ptr->skip_length < (png_uint_32)png_ptr->save_buffer_size)
  182156. save_size = (png_size_t)png_ptr->skip_length;
  182157. else
  182158. save_size = png_ptr->save_buffer_size;
  182159. png_calculate_crc(png_ptr, png_ptr->save_buffer_ptr, save_size);
  182160. png_ptr->skip_length -= save_size;
  182161. png_ptr->buffer_size -= save_size;
  182162. png_ptr->save_buffer_size -= save_size;
  182163. png_ptr->save_buffer_ptr += save_size;
  182164. }
  182165. if (png_ptr->skip_length && png_ptr->current_buffer_size)
  182166. {
  182167. png_size_t save_size;
  182168. if (png_ptr->skip_length < (png_uint_32)png_ptr->current_buffer_size)
  182169. save_size = (png_size_t)png_ptr->skip_length;
  182170. else
  182171. save_size = png_ptr->current_buffer_size;
  182172. png_calculate_crc(png_ptr, png_ptr->current_buffer_ptr, save_size);
  182173. png_ptr->skip_length -= save_size;
  182174. png_ptr->buffer_size -= save_size;
  182175. png_ptr->current_buffer_size -= save_size;
  182176. png_ptr->current_buffer_ptr += save_size;
  182177. }
  182178. if (!png_ptr->skip_length)
  182179. {
  182180. if (png_ptr->buffer_size < 4)
  182181. {
  182182. png_push_save_buffer(png_ptr);
  182183. return;
  182184. }
  182185. png_crc_finish(png_ptr, 0);
  182186. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  182187. }
  182188. }
  182189. void PNGAPI
  182190. png_push_fill_buffer(png_structp png_ptr, png_bytep buffer, png_size_t length)
  182191. {
  182192. png_bytep ptr;
  182193. if(png_ptr == NULL) return;
  182194. ptr = buffer;
  182195. if (png_ptr->save_buffer_size)
  182196. {
  182197. png_size_t save_size;
  182198. if (length < png_ptr->save_buffer_size)
  182199. save_size = length;
  182200. else
  182201. save_size = png_ptr->save_buffer_size;
  182202. png_memcpy(ptr, png_ptr->save_buffer_ptr, save_size);
  182203. length -= save_size;
  182204. ptr += save_size;
  182205. png_ptr->buffer_size -= save_size;
  182206. png_ptr->save_buffer_size -= save_size;
  182207. png_ptr->save_buffer_ptr += save_size;
  182208. }
  182209. if (length && png_ptr->current_buffer_size)
  182210. {
  182211. png_size_t save_size;
  182212. if (length < png_ptr->current_buffer_size)
  182213. save_size = length;
  182214. else
  182215. save_size = png_ptr->current_buffer_size;
  182216. png_memcpy(ptr, png_ptr->current_buffer_ptr, save_size);
  182217. png_ptr->buffer_size -= save_size;
  182218. png_ptr->current_buffer_size -= save_size;
  182219. png_ptr->current_buffer_ptr += save_size;
  182220. }
  182221. }
  182222. void /* PRIVATE */
  182223. png_push_save_buffer(png_structp png_ptr)
  182224. {
  182225. if (png_ptr->save_buffer_size)
  182226. {
  182227. if (png_ptr->save_buffer_ptr != png_ptr->save_buffer)
  182228. {
  182229. png_size_t i,istop;
  182230. png_bytep sp;
  182231. png_bytep dp;
  182232. istop = png_ptr->save_buffer_size;
  182233. for (i = 0, sp = png_ptr->save_buffer_ptr, dp = png_ptr->save_buffer;
  182234. i < istop; i++, sp++, dp++)
  182235. {
  182236. *dp = *sp;
  182237. }
  182238. }
  182239. }
  182240. if (png_ptr->save_buffer_size + png_ptr->current_buffer_size >
  182241. png_ptr->save_buffer_max)
  182242. {
  182243. png_size_t new_max;
  182244. png_bytep old_buffer;
  182245. if (png_ptr->save_buffer_size > PNG_SIZE_MAX -
  182246. (png_ptr->current_buffer_size + 256))
  182247. {
  182248. png_error(png_ptr, "Potential overflow of save_buffer");
  182249. }
  182250. new_max = png_ptr->save_buffer_size + png_ptr->current_buffer_size + 256;
  182251. old_buffer = png_ptr->save_buffer;
  182252. png_ptr->save_buffer = (png_bytep)png_malloc(png_ptr,
  182253. (png_uint_32)new_max);
  182254. png_memcpy(png_ptr->save_buffer, old_buffer, png_ptr->save_buffer_size);
  182255. png_free(png_ptr, old_buffer);
  182256. png_ptr->save_buffer_max = new_max;
  182257. }
  182258. if (png_ptr->current_buffer_size)
  182259. {
  182260. png_memcpy(png_ptr->save_buffer + png_ptr->save_buffer_size,
  182261. png_ptr->current_buffer_ptr, png_ptr->current_buffer_size);
  182262. png_ptr->save_buffer_size += png_ptr->current_buffer_size;
  182263. png_ptr->current_buffer_size = 0;
  182264. }
  182265. png_ptr->save_buffer_ptr = png_ptr->save_buffer;
  182266. png_ptr->buffer_size = 0;
  182267. }
  182268. void /* PRIVATE */
  182269. png_push_restore_buffer(png_structp png_ptr, png_bytep buffer,
  182270. png_size_t buffer_length)
  182271. {
  182272. png_ptr->current_buffer = buffer;
  182273. png_ptr->current_buffer_size = buffer_length;
  182274. png_ptr->buffer_size = buffer_length + png_ptr->save_buffer_size;
  182275. png_ptr->current_buffer_ptr = png_ptr->current_buffer;
  182276. }
  182277. void /* PRIVATE */
  182278. png_push_read_IDAT(png_structp png_ptr)
  182279. {
  182280. #ifdef PNG_USE_LOCAL_ARRAYS
  182281. PNG_CONST PNG_IDAT;
  182282. #endif
  182283. if (!(png_ptr->mode & PNG_HAVE_CHUNK_HEADER))
  182284. {
  182285. png_byte chunk_length[4];
  182286. if (png_ptr->buffer_size < 8)
  182287. {
  182288. png_push_save_buffer(png_ptr);
  182289. return;
  182290. }
  182291. png_push_fill_buffer(png_ptr, chunk_length, 4);
  182292. png_ptr->push_length = png_get_uint_31(png_ptr,chunk_length);
  182293. png_reset_crc(png_ptr);
  182294. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  182295. png_ptr->mode |= PNG_HAVE_CHUNK_HEADER;
  182296. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  182297. {
  182298. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  182299. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  182300. png_error(png_ptr, "Not enough compressed data");
  182301. return;
  182302. }
  182303. png_ptr->idat_size = png_ptr->push_length;
  182304. }
  182305. if (png_ptr->idat_size && png_ptr->save_buffer_size)
  182306. {
  182307. png_size_t save_size;
  182308. if (png_ptr->idat_size < (png_uint_32)png_ptr->save_buffer_size)
  182309. {
  182310. save_size = (png_size_t)png_ptr->idat_size;
  182311. /* check for overflow */
  182312. if((png_uint_32)save_size != png_ptr->idat_size)
  182313. png_error(png_ptr, "save_size overflowed in pngpread");
  182314. }
  182315. else
  182316. save_size = png_ptr->save_buffer_size;
  182317. png_calculate_crc(png_ptr, png_ptr->save_buffer_ptr, save_size);
  182318. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  182319. png_process_IDAT_data(png_ptr, png_ptr->save_buffer_ptr, save_size);
  182320. png_ptr->idat_size -= save_size;
  182321. png_ptr->buffer_size -= save_size;
  182322. png_ptr->save_buffer_size -= save_size;
  182323. png_ptr->save_buffer_ptr += save_size;
  182324. }
  182325. if (png_ptr->idat_size && png_ptr->current_buffer_size)
  182326. {
  182327. png_size_t save_size;
  182328. if (png_ptr->idat_size < (png_uint_32)png_ptr->current_buffer_size)
  182329. {
  182330. save_size = (png_size_t)png_ptr->idat_size;
  182331. /* check for overflow */
  182332. if((png_uint_32)save_size != png_ptr->idat_size)
  182333. png_error(png_ptr, "save_size overflowed in pngpread");
  182334. }
  182335. else
  182336. save_size = png_ptr->current_buffer_size;
  182337. png_calculate_crc(png_ptr, png_ptr->current_buffer_ptr, save_size);
  182338. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  182339. png_process_IDAT_data(png_ptr, png_ptr->current_buffer_ptr, save_size);
  182340. png_ptr->idat_size -= save_size;
  182341. png_ptr->buffer_size -= save_size;
  182342. png_ptr->current_buffer_size -= save_size;
  182343. png_ptr->current_buffer_ptr += save_size;
  182344. }
  182345. if (!png_ptr->idat_size)
  182346. {
  182347. if (png_ptr->buffer_size < 4)
  182348. {
  182349. png_push_save_buffer(png_ptr);
  182350. return;
  182351. }
  182352. png_crc_finish(png_ptr, 0);
  182353. png_ptr->mode &= ~PNG_HAVE_CHUNK_HEADER;
  182354. png_ptr->mode |= PNG_AFTER_IDAT;
  182355. }
  182356. }
  182357. void /* PRIVATE */
  182358. png_process_IDAT_data(png_structp png_ptr, png_bytep buffer,
  182359. png_size_t buffer_length)
  182360. {
  182361. int ret;
  182362. if ((png_ptr->flags & PNG_FLAG_ZLIB_FINISHED) && buffer_length)
  182363. png_error(png_ptr, "Extra compression data");
  182364. png_ptr->zstream.next_in = buffer;
  182365. png_ptr->zstream.avail_in = (uInt)buffer_length;
  182366. for(;;)
  182367. {
  182368. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  182369. if (ret != Z_OK)
  182370. {
  182371. if (ret == Z_STREAM_END)
  182372. {
  182373. if (png_ptr->zstream.avail_in)
  182374. png_error(png_ptr, "Extra compressed data");
  182375. if (!(png_ptr->zstream.avail_out))
  182376. {
  182377. png_push_process_row(png_ptr);
  182378. }
  182379. png_ptr->mode |= PNG_AFTER_IDAT;
  182380. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  182381. break;
  182382. }
  182383. else if (ret == Z_BUF_ERROR)
  182384. break;
  182385. else
  182386. png_error(png_ptr, "Decompression Error");
  182387. }
  182388. if (!(png_ptr->zstream.avail_out))
  182389. {
  182390. if ((
  182391. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  182392. png_ptr->interlaced && png_ptr->pass > 6) ||
  182393. (!png_ptr->interlaced &&
  182394. #endif
  182395. png_ptr->row_number == png_ptr->num_rows))
  182396. {
  182397. if (png_ptr->zstream.avail_in)
  182398. {
  182399. png_warning(png_ptr, "Too much data in IDAT chunks");
  182400. }
  182401. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  182402. break;
  182403. }
  182404. png_push_process_row(png_ptr);
  182405. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  182406. png_ptr->zstream.next_out = png_ptr->row_buf;
  182407. }
  182408. else
  182409. break;
  182410. }
  182411. }
  182412. void /* PRIVATE */
  182413. png_push_process_row(png_structp png_ptr)
  182414. {
  182415. png_ptr->row_info.color_type = png_ptr->color_type;
  182416. png_ptr->row_info.width = png_ptr->iwidth;
  182417. png_ptr->row_info.channels = png_ptr->channels;
  182418. png_ptr->row_info.bit_depth = png_ptr->bit_depth;
  182419. png_ptr->row_info.pixel_depth = png_ptr->pixel_depth;
  182420. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  182421. png_ptr->row_info.width);
  182422. png_read_filter_row(png_ptr, &(png_ptr->row_info),
  182423. png_ptr->row_buf + 1, png_ptr->prev_row + 1,
  182424. (int)(png_ptr->row_buf[0]));
  182425. png_memcpy_check(png_ptr, png_ptr->prev_row, png_ptr->row_buf,
  182426. png_ptr->rowbytes + 1);
  182427. if (png_ptr->transformations || (png_ptr->flags&PNG_FLAG_STRIP_ALPHA))
  182428. png_do_read_transformations(png_ptr);
  182429. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  182430. /* blow up interlaced rows to full size */
  182431. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  182432. {
  182433. if (png_ptr->pass < 6)
  182434. /* old interface (pre-1.0.9):
  182435. png_do_read_interlace(&(png_ptr->row_info),
  182436. png_ptr->row_buf + 1, png_ptr->pass, png_ptr->transformations);
  182437. */
  182438. png_do_read_interlace(png_ptr);
  182439. switch (png_ptr->pass)
  182440. {
  182441. case 0:
  182442. {
  182443. int i;
  182444. for (i = 0; i < 8 && png_ptr->pass == 0; i++)
  182445. {
  182446. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  182447. png_read_push_finish_row(png_ptr); /* updates png_ptr->pass */
  182448. }
  182449. if (png_ptr->pass == 2) /* pass 1 might be empty */
  182450. {
  182451. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  182452. {
  182453. png_push_have_row(png_ptr, png_bytep_NULL);
  182454. png_read_push_finish_row(png_ptr);
  182455. }
  182456. }
  182457. if (png_ptr->pass == 4 && png_ptr->height <= 4)
  182458. {
  182459. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  182460. {
  182461. png_push_have_row(png_ptr, png_bytep_NULL);
  182462. png_read_push_finish_row(png_ptr);
  182463. }
  182464. }
  182465. if (png_ptr->pass == 6 && png_ptr->height <= 4)
  182466. {
  182467. png_push_have_row(png_ptr, png_bytep_NULL);
  182468. png_read_push_finish_row(png_ptr);
  182469. }
  182470. break;
  182471. }
  182472. case 1:
  182473. {
  182474. int i;
  182475. for (i = 0; i < 8 && png_ptr->pass == 1; i++)
  182476. {
  182477. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  182478. png_read_push_finish_row(png_ptr);
  182479. }
  182480. if (png_ptr->pass == 2) /* skip top 4 generated rows */
  182481. {
  182482. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  182483. {
  182484. png_push_have_row(png_ptr, png_bytep_NULL);
  182485. png_read_push_finish_row(png_ptr);
  182486. }
  182487. }
  182488. break;
  182489. }
  182490. case 2:
  182491. {
  182492. int i;
  182493. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  182494. {
  182495. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  182496. png_read_push_finish_row(png_ptr);
  182497. }
  182498. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  182499. {
  182500. png_push_have_row(png_ptr, png_bytep_NULL);
  182501. png_read_push_finish_row(png_ptr);
  182502. }
  182503. if (png_ptr->pass == 4) /* pass 3 might be empty */
  182504. {
  182505. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  182506. {
  182507. png_push_have_row(png_ptr, png_bytep_NULL);
  182508. png_read_push_finish_row(png_ptr);
  182509. }
  182510. }
  182511. break;
  182512. }
  182513. case 3:
  182514. {
  182515. int i;
  182516. for (i = 0; i < 4 && png_ptr->pass == 3; i++)
  182517. {
  182518. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  182519. png_read_push_finish_row(png_ptr);
  182520. }
  182521. if (png_ptr->pass == 4) /* skip top two generated rows */
  182522. {
  182523. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  182524. {
  182525. png_push_have_row(png_ptr, png_bytep_NULL);
  182526. png_read_push_finish_row(png_ptr);
  182527. }
  182528. }
  182529. break;
  182530. }
  182531. case 4:
  182532. {
  182533. int i;
  182534. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  182535. {
  182536. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  182537. png_read_push_finish_row(png_ptr);
  182538. }
  182539. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  182540. {
  182541. png_push_have_row(png_ptr, png_bytep_NULL);
  182542. png_read_push_finish_row(png_ptr);
  182543. }
  182544. if (png_ptr->pass == 6) /* pass 5 might be empty */
  182545. {
  182546. png_push_have_row(png_ptr, png_bytep_NULL);
  182547. png_read_push_finish_row(png_ptr);
  182548. }
  182549. break;
  182550. }
  182551. case 5:
  182552. {
  182553. int i;
  182554. for (i = 0; i < 2 && png_ptr->pass == 5; i++)
  182555. {
  182556. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  182557. png_read_push_finish_row(png_ptr);
  182558. }
  182559. if (png_ptr->pass == 6) /* skip top generated row */
  182560. {
  182561. png_push_have_row(png_ptr, png_bytep_NULL);
  182562. png_read_push_finish_row(png_ptr);
  182563. }
  182564. break;
  182565. }
  182566. case 6:
  182567. {
  182568. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  182569. png_read_push_finish_row(png_ptr);
  182570. if (png_ptr->pass != 6)
  182571. break;
  182572. png_push_have_row(png_ptr, png_bytep_NULL);
  182573. png_read_push_finish_row(png_ptr);
  182574. }
  182575. }
  182576. }
  182577. else
  182578. #endif
  182579. {
  182580. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  182581. png_read_push_finish_row(png_ptr);
  182582. }
  182583. }
  182584. void /* PRIVATE */
  182585. png_read_push_finish_row(png_structp png_ptr)
  182586. {
  182587. #ifdef PNG_USE_LOCAL_ARRAYS
  182588. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  182589. /* start of interlace block */
  182590. PNG_CONST int FARDATA png_pass_start[] = {0, 4, 0, 2, 0, 1, 0};
  182591. /* offset to next interlace block */
  182592. PNG_CONST int FARDATA png_pass_inc[] = {8, 8, 4, 4, 2, 2, 1};
  182593. /* start of interlace block in the y direction */
  182594. PNG_CONST int FARDATA png_pass_ystart[] = {0, 0, 4, 0, 2, 0, 1};
  182595. /* offset to next interlace block in the y direction */
  182596. PNG_CONST int FARDATA png_pass_yinc[] = {8, 8, 8, 4, 4, 2, 2};
  182597. /* Height of interlace block. This is not currently used - if you need
  182598. * it, uncomment it here and in png.h
  182599. PNG_CONST int FARDATA png_pass_height[] = {8, 8, 4, 4, 2, 2, 1};
  182600. */
  182601. #endif
  182602. png_ptr->row_number++;
  182603. if (png_ptr->row_number < png_ptr->num_rows)
  182604. return;
  182605. if (png_ptr->interlaced)
  182606. {
  182607. png_ptr->row_number = 0;
  182608. png_memset_check(png_ptr, png_ptr->prev_row, 0,
  182609. png_ptr->rowbytes + 1);
  182610. do
  182611. {
  182612. png_ptr->pass++;
  182613. if ((png_ptr->pass == 1 && png_ptr->width < 5) ||
  182614. (png_ptr->pass == 3 && png_ptr->width < 3) ||
  182615. (png_ptr->pass == 5 && png_ptr->width < 2))
  182616. png_ptr->pass++;
  182617. if (png_ptr->pass > 7)
  182618. png_ptr->pass--;
  182619. if (png_ptr->pass >= 7)
  182620. break;
  182621. png_ptr->iwidth = (png_ptr->width +
  182622. png_pass_inc[png_ptr->pass] - 1 -
  182623. png_pass_start[png_ptr->pass]) /
  182624. png_pass_inc[png_ptr->pass];
  182625. png_ptr->irowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,
  182626. png_ptr->iwidth) + 1;
  182627. if (png_ptr->transformations & PNG_INTERLACE)
  182628. break;
  182629. png_ptr->num_rows = (png_ptr->height +
  182630. png_pass_yinc[png_ptr->pass] - 1 -
  182631. png_pass_ystart[png_ptr->pass]) /
  182632. png_pass_yinc[png_ptr->pass];
  182633. } while (png_ptr->iwidth == 0 || png_ptr->num_rows == 0);
  182634. }
  182635. }
  182636. #if defined(PNG_READ_tEXt_SUPPORTED)
  182637. void /* PRIVATE */
  182638. png_push_handle_tEXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  182639. length)
  182640. {
  182641. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  182642. {
  182643. png_error(png_ptr, "Out of place tEXt");
  182644. info_ptr = info_ptr; /* to quiet some compiler warnings */
  182645. }
  182646. #ifdef PNG_MAX_MALLOC_64K
  182647. png_ptr->skip_length = 0; /* This may not be necessary */
  182648. if (length > (png_uint_32)65535L) /* Can't hold entire string in memory */
  182649. {
  182650. png_warning(png_ptr, "tEXt chunk too large to fit in memory");
  182651. png_ptr->skip_length = length - (png_uint_32)65535L;
  182652. length = (png_uint_32)65535L;
  182653. }
  182654. #endif
  182655. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  182656. (png_uint_32)(length+1));
  182657. png_ptr->current_text[length] = '\0';
  182658. png_ptr->current_text_ptr = png_ptr->current_text;
  182659. png_ptr->current_text_size = (png_size_t)length;
  182660. png_ptr->current_text_left = (png_size_t)length;
  182661. png_ptr->process_mode = PNG_READ_tEXt_MODE;
  182662. }
  182663. void /* PRIVATE */
  182664. png_push_read_tEXt(png_structp png_ptr, png_infop info_ptr)
  182665. {
  182666. if (png_ptr->buffer_size && png_ptr->current_text_left)
  182667. {
  182668. png_size_t text_size;
  182669. if (png_ptr->buffer_size < png_ptr->current_text_left)
  182670. text_size = png_ptr->buffer_size;
  182671. else
  182672. text_size = png_ptr->current_text_left;
  182673. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  182674. png_ptr->current_text_left -= text_size;
  182675. png_ptr->current_text_ptr += text_size;
  182676. }
  182677. if (!(png_ptr->current_text_left))
  182678. {
  182679. png_textp text_ptr;
  182680. png_charp text;
  182681. png_charp key;
  182682. int ret;
  182683. if (png_ptr->buffer_size < 4)
  182684. {
  182685. png_push_save_buffer(png_ptr);
  182686. return;
  182687. }
  182688. png_push_crc_finish(png_ptr);
  182689. #if defined(PNG_MAX_MALLOC_64K)
  182690. if (png_ptr->skip_length)
  182691. return;
  182692. #endif
  182693. key = png_ptr->current_text;
  182694. for (text = key; *text; text++)
  182695. /* empty loop */ ;
  182696. if (text < key + png_ptr->current_text_size)
  182697. text++;
  182698. text_ptr = (png_textp)png_malloc(png_ptr,
  182699. (png_uint_32)png_sizeof(png_text));
  182700. text_ptr->compression = PNG_TEXT_COMPRESSION_NONE;
  182701. text_ptr->key = key;
  182702. #ifdef PNG_iTXt_SUPPORTED
  182703. text_ptr->lang = NULL;
  182704. text_ptr->lang_key = NULL;
  182705. #endif
  182706. text_ptr->text = text;
  182707. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  182708. png_free(png_ptr, key);
  182709. png_free(png_ptr, text_ptr);
  182710. png_ptr->current_text = NULL;
  182711. if (ret)
  182712. png_warning(png_ptr, "Insufficient memory to store text chunk.");
  182713. }
  182714. }
  182715. #endif
  182716. #if defined(PNG_READ_zTXt_SUPPORTED)
  182717. void /* PRIVATE */
  182718. png_push_handle_zTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  182719. length)
  182720. {
  182721. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  182722. {
  182723. png_error(png_ptr, "Out of place zTXt");
  182724. info_ptr = info_ptr; /* to quiet some compiler warnings */
  182725. }
  182726. #ifdef PNG_MAX_MALLOC_64K
  182727. /* We can't handle zTXt chunks > 64K, since we don't have enough space
  182728. * to be able to store the uncompressed data. Actually, the threshold
  182729. * is probably around 32K, but it isn't as definite as 64K is.
  182730. */
  182731. if (length > (png_uint_32)65535L)
  182732. {
  182733. png_warning(png_ptr, "zTXt chunk too large to fit in memory");
  182734. png_push_crc_skip(png_ptr, length);
  182735. return;
  182736. }
  182737. #endif
  182738. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  182739. (png_uint_32)(length+1));
  182740. png_ptr->current_text[length] = '\0';
  182741. png_ptr->current_text_ptr = png_ptr->current_text;
  182742. png_ptr->current_text_size = (png_size_t)length;
  182743. png_ptr->current_text_left = (png_size_t)length;
  182744. png_ptr->process_mode = PNG_READ_zTXt_MODE;
  182745. }
  182746. void /* PRIVATE */
  182747. png_push_read_zTXt(png_structp png_ptr, png_infop info_ptr)
  182748. {
  182749. if (png_ptr->buffer_size && png_ptr->current_text_left)
  182750. {
  182751. png_size_t text_size;
  182752. if (png_ptr->buffer_size < (png_uint_32)png_ptr->current_text_left)
  182753. text_size = png_ptr->buffer_size;
  182754. else
  182755. text_size = png_ptr->current_text_left;
  182756. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  182757. png_ptr->current_text_left -= text_size;
  182758. png_ptr->current_text_ptr += text_size;
  182759. }
  182760. if (!(png_ptr->current_text_left))
  182761. {
  182762. png_textp text_ptr;
  182763. png_charp text;
  182764. png_charp key;
  182765. int ret;
  182766. png_size_t text_size, key_size;
  182767. if (png_ptr->buffer_size < 4)
  182768. {
  182769. png_push_save_buffer(png_ptr);
  182770. return;
  182771. }
  182772. png_push_crc_finish(png_ptr);
  182773. key = png_ptr->current_text;
  182774. for (text = key; *text; text++)
  182775. /* empty loop */ ;
  182776. /* zTXt can't have zero text */
  182777. if (text >= key + png_ptr->current_text_size)
  182778. {
  182779. png_ptr->current_text = NULL;
  182780. png_free(png_ptr, key);
  182781. return;
  182782. }
  182783. text++;
  182784. if (*text != PNG_TEXT_COMPRESSION_zTXt) /* check compression byte */
  182785. {
  182786. png_ptr->current_text = NULL;
  182787. png_free(png_ptr, key);
  182788. return;
  182789. }
  182790. text++;
  182791. png_ptr->zstream.next_in = (png_bytep )text;
  182792. png_ptr->zstream.avail_in = (uInt)(png_ptr->current_text_size -
  182793. (text - key));
  182794. png_ptr->zstream.next_out = png_ptr->zbuf;
  182795. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  182796. key_size = text - key;
  182797. text_size = 0;
  182798. text = NULL;
  182799. ret = Z_STREAM_END;
  182800. while (png_ptr->zstream.avail_in)
  182801. {
  182802. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  182803. if (ret != Z_OK && ret != Z_STREAM_END)
  182804. {
  182805. inflateReset(&png_ptr->zstream);
  182806. png_ptr->zstream.avail_in = 0;
  182807. png_ptr->current_text = NULL;
  182808. png_free(png_ptr, key);
  182809. png_free(png_ptr, text);
  182810. return;
  182811. }
  182812. if (!(png_ptr->zstream.avail_out) || ret == Z_STREAM_END)
  182813. {
  182814. if (text == NULL)
  182815. {
  182816. text = (png_charp)png_malloc(png_ptr,
  182817. (png_uint_32)(png_ptr->zbuf_size - png_ptr->zstream.avail_out
  182818. + key_size + 1));
  182819. png_memcpy(text + key_size, png_ptr->zbuf,
  182820. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  182821. png_memcpy(text, key, key_size);
  182822. text_size = key_size + png_ptr->zbuf_size -
  182823. png_ptr->zstream.avail_out;
  182824. *(text + text_size) = '\0';
  182825. }
  182826. else
  182827. {
  182828. png_charp tmp;
  182829. tmp = text;
  182830. text = (png_charp)png_malloc(png_ptr, text_size +
  182831. (png_uint_32)(png_ptr->zbuf_size - png_ptr->zstream.avail_out
  182832. + 1));
  182833. png_memcpy(text, tmp, text_size);
  182834. png_free(png_ptr, tmp);
  182835. png_memcpy(text + text_size, png_ptr->zbuf,
  182836. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  182837. text_size += png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  182838. *(text + text_size) = '\0';
  182839. }
  182840. if (ret != Z_STREAM_END)
  182841. {
  182842. png_ptr->zstream.next_out = png_ptr->zbuf;
  182843. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  182844. }
  182845. }
  182846. else
  182847. {
  182848. break;
  182849. }
  182850. if (ret == Z_STREAM_END)
  182851. break;
  182852. }
  182853. inflateReset(&png_ptr->zstream);
  182854. png_ptr->zstream.avail_in = 0;
  182855. if (ret != Z_STREAM_END)
  182856. {
  182857. png_ptr->current_text = NULL;
  182858. png_free(png_ptr, key);
  182859. png_free(png_ptr, text);
  182860. return;
  182861. }
  182862. png_ptr->current_text = NULL;
  182863. png_free(png_ptr, key);
  182864. key = text;
  182865. text += key_size;
  182866. text_ptr = (png_textp)png_malloc(png_ptr,
  182867. (png_uint_32)png_sizeof(png_text));
  182868. text_ptr->compression = PNG_TEXT_COMPRESSION_zTXt;
  182869. text_ptr->key = key;
  182870. #ifdef PNG_iTXt_SUPPORTED
  182871. text_ptr->lang = NULL;
  182872. text_ptr->lang_key = NULL;
  182873. #endif
  182874. text_ptr->text = text;
  182875. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  182876. png_free(png_ptr, key);
  182877. png_free(png_ptr, text_ptr);
  182878. if (ret)
  182879. png_warning(png_ptr, "Insufficient memory to store text chunk.");
  182880. }
  182881. }
  182882. #endif
  182883. #if defined(PNG_READ_iTXt_SUPPORTED)
  182884. void /* PRIVATE */
  182885. png_push_handle_iTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  182886. length)
  182887. {
  182888. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  182889. {
  182890. png_error(png_ptr, "Out of place iTXt");
  182891. info_ptr = info_ptr; /* to quiet some compiler warnings */
  182892. }
  182893. #ifdef PNG_MAX_MALLOC_64K
  182894. png_ptr->skip_length = 0; /* This may not be necessary */
  182895. if (length > (png_uint_32)65535L) /* Can't hold entire string in memory */
  182896. {
  182897. png_warning(png_ptr, "iTXt chunk too large to fit in memory");
  182898. png_ptr->skip_length = length - (png_uint_32)65535L;
  182899. length = (png_uint_32)65535L;
  182900. }
  182901. #endif
  182902. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  182903. (png_uint_32)(length+1));
  182904. png_ptr->current_text[length] = '\0';
  182905. png_ptr->current_text_ptr = png_ptr->current_text;
  182906. png_ptr->current_text_size = (png_size_t)length;
  182907. png_ptr->current_text_left = (png_size_t)length;
  182908. png_ptr->process_mode = PNG_READ_iTXt_MODE;
  182909. }
  182910. void /* PRIVATE */
  182911. png_push_read_iTXt(png_structp png_ptr, png_infop info_ptr)
  182912. {
  182913. if (png_ptr->buffer_size && png_ptr->current_text_left)
  182914. {
  182915. png_size_t text_size;
  182916. if (png_ptr->buffer_size < png_ptr->current_text_left)
  182917. text_size = png_ptr->buffer_size;
  182918. else
  182919. text_size = png_ptr->current_text_left;
  182920. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  182921. png_ptr->current_text_left -= text_size;
  182922. png_ptr->current_text_ptr += text_size;
  182923. }
  182924. if (!(png_ptr->current_text_left))
  182925. {
  182926. png_textp text_ptr;
  182927. png_charp key;
  182928. int comp_flag;
  182929. png_charp lang;
  182930. png_charp lang_key;
  182931. png_charp text;
  182932. int ret;
  182933. if (png_ptr->buffer_size < 4)
  182934. {
  182935. png_push_save_buffer(png_ptr);
  182936. return;
  182937. }
  182938. png_push_crc_finish(png_ptr);
  182939. #if defined(PNG_MAX_MALLOC_64K)
  182940. if (png_ptr->skip_length)
  182941. return;
  182942. #endif
  182943. key = png_ptr->current_text;
  182944. for (lang = key; *lang; lang++)
  182945. /* empty loop */ ;
  182946. if (lang < key + png_ptr->current_text_size - 3)
  182947. lang++;
  182948. comp_flag = *lang++;
  182949. lang++; /* skip comp_type, always zero */
  182950. for (lang_key = lang; *lang_key; lang_key++)
  182951. /* empty loop */ ;
  182952. lang_key++; /* skip NUL separator */
  182953. text=lang_key;
  182954. if (lang_key < key + png_ptr->current_text_size - 1)
  182955. {
  182956. for (; *text; text++)
  182957. /* empty loop */ ;
  182958. }
  182959. if (text < key + png_ptr->current_text_size)
  182960. text++;
  182961. text_ptr = (png_textp)png_malloc(png_ptr,
  182962. (png_uint_32)png_sizeof(png_text));
  182963. text_ptr->compression = comp_flag + 2;
  182964. text_ptr->key = key;
  182965. text_ptr->lang = lang;
  182966. text_ptr->lang_key = lang_key;
  182967. text_ptr->text = text;
  182968. text_ptr->text_length = 0;
  182969. text_ptr->itxt_length = png_strlen(text);
  182970. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  182971. png_ptr->current_text = NULL;
  182972. png_free(png_ptr, text_ptr);
  182973. if (ret)
  182974. png_warning(png_ptr, "Insufficient memory to store iTXt chunk.");
  182975. }
  182976. }
  182977. #endif
  182978. /* This function is called when we haven't found a handler for this
  182979. * chunk. If there isn't a problem with the chunk itself (ie a bad chunk
  182980. * name or a critical chunk), the chunk is (currently) silently ignored.
  182981. */
  182982. void /* PRIVATE */
  182983. png_push_handle_unknown(png_structp png_ptr, png_infop info_ptr, png_uint_32
  182984. length)
  182985. {
  182986. png_uint_32 skip=0;
  182987. png_check_chunk_name(png_ptr, png_ptr->chunk_name);
  182988. if (!(png_ptr->chunk_name[0] & 0x20))
  182989. {
  182990. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  182991. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  182992. PNG_HANDLE_CHUNK_ALWAYS
  182993. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  182994. && png_ptr->read_user_chunk_fn == NULL
  182995. #endif
  182996. )
  182997. #endif
  182998. png_chunk_error(png_ptr, "unknown critical chunk");
  182999. info_ptr = info_ptr; /* to quiet some compiler warnings */
  183000. }
  183001. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  183002. if (png_ptr->flags & PNG_FLAG_KEEP_UNKNOWN_CHUNKS)
  183003. {
  183004. #ifdef PNG_MAX_MALLOC_64K
  183005. if (length > (png_uint_32)65535L)
  183006. {
  183007. png_warning(png_ptr, "unknown chunk too large to fit in memory");
  183008. skip = length - (png_uint_32)65535L;
  183009. length = (png_uint_32)65535L;
  183010. }
  183011. #endif
  183012. png_strncpy((png_charp)png_ptr->unknown_chunk.name,
  183013. (png_charp)png_ptr->chunk_name, 5);
  183014. png_ptr->unknown_chunk.data = (png_bytep)png_malloc(png_ptr, length);
  183015. png_ptr->unknown_chunk.size = (png_size_t)length;
  183016. png_crc_read(png_ptr, (png_bytep)png_ptr->unknown_chunk.data, length);
  183017. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  183018. if(png_ptr->read_user_chunk_fn != NULL)
  183019. {
  183020. /* callback to user unknown chunk handler */
  183021. int ret;
  183022. ret = (*(png_ptr->read_user_chunk_fn))
  183023. (png_ptr, &png_ptr->unknown_chunk);
  183024. if (ret < 0)
  183025. png_chunk_error(png_ptr, "error in user chunk");
  183026. if (ret == 0)
  183027. {
  183028. if (!(png_ptr->chunk_name[0] & 0x20))
  183029. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  183030. PNG_HANDLE_CHUNK_ALWAYS)
  183031. png_chunk_error(png_ptr, "unknown critical chunk");
  183032. png_set_unknown_chunks(png_ptr, info_ptr,
  183033. &png_ptr->unknown_chunk, 1);
  183034. }
  183035. }
  183036. #else
  183037. png_set_unknown_chunks(png_ptr, info_ptr, &png_ptr->unknown_chunk, 1);
  183038. #endif
  183039. png_free(png_ptr, png_ptr->unknown_chunk.data);
  183040. png_ptr->unknown_chunk.data = NULL;
  183041. }
  183042. else
  183043. #endif
  183044. skip=length;
  183045. png_push_crc_skip(png_ptr, skip);
  183046. }
  183047. void /* PRIVATE */
  183048. png_push_have_info(png_structp png_ptr, png_infop info_ptr)
  183049. {
  183050. if (png_ptr->info_fn != NULL)
  183051. (*(png_ptr->info_fn))(png_ptr, info_ptr);
  183052. }
  183053. void /* PRIVATE */
  183054. png_push_have_end(png_structp png_ptr, png_infop info_ptr)
  183055. {
  183056. if (png_ptr->end_fn != NULL)
  183057. (*(png_ptr->end_fn))(png_ptr, info_ptr);
  183058. }
  183059. void /* PRIVATE */
  183060. png_push_have_row(png_structp png_ptr, png_bytep row)
  183061. {
  183062. if (png_ptr->row_fn != NULL)
  183063. (*(png_ptr->row_fn))(png_ptr, row, png_ptr->row_number,
  183064. (int)png_ptr->pass);
  183065. }
  183066. void PNGAPI
  183067. png_progressive_combine_row (png_structp png_ptr,
  183068. png_bytep old_row, png_bytep new_row)
  183069. {
  183070. #ifdef PNG_USE_LOCAL_ARRAYS
  183071. PNG_CONST int FARDATA png_pass_dsp_mask[7] =
  183072. {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, 0xff};
  183073. #endif
  183074. if(png_ptr == NULL) return;
  183075. if (new_row != NULL) /* new_row must == png_ptr->row_buf here. */
  183076. png_combine_row(png_ptr, old_row, png_pass_dsp_mask[png_ptr->pass]);
  183077. }
  183078. void PNGAPI
  183079. png_set_progressive_read_fn(png_structp png_ptr, png_voidp progressive_ptr,
  183080. png_progressive_info_ptr info_fn, png_progressive_row_ptr row_fn,
  183081. png_progressive_end_ptr end_fn)
  183082. {
  183083. if(png_ptr == NULL) return;
  183084. png_ptr->info_fn = info_fn;
  183085. png_ptr->row_fn = row_fn;
  183086. png_ptr->end_fn = end_fn;
  183087. png_set_read_fn(png_ptr, progressive_ptr, png_push_fill_buffer);
  183088. }
  183089. png_voidp PNGAPI
  183090. png_get_progressive_ptr(png_structp png_ptr)
  183091. {
  183092. if(png_ptr == NULL) return (NULL);
  183093. return png_ptr->io_ptr;
  183094. }
  183095. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  183096. /********* End of inlined file: pngpread.c *********/
  183097. /********* Start of inlined file: pngrio.c *********/
  183098. /* pngrio.c - functions for data input
  183099. *
  183100. * Last changed in libpng 1.2.13 November 13, 2006
  183101. * For conditions of distribution and use, see copyright notice in png.h
  183102. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  183103. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  183104. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  183105. *
  183106. * This file provides a location for all input. Users who need
  183107. * special handling are expected to write a function that has the same
  183108. * arguments as this and performs a similar function, but that possibly
  183109. * has a different input method. Note that you shouldn't change this
  183110. * function, but rather write a replacement function and then make
  183111. * libpng use it at run time with png_set_read_fn(...).
  183112. */
  183113. #define PNG_INTERNAL
  183114. #if defined(PNG_READ_SUPPORTED)
  183115. /* Read the data from whatever input you are using. The default routine
  183116. reads from a file pointer. Note that this routine sometimes gets called
  183117. with very small lengths, so you should implement some kind of simple
  183118. buffering if you are using unbuffered reads. This should never be asked
  183119. to read more then 64K on a 16 bit machine. */
  183120. void /* PRIVATE */
  183121. png_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  183122. {
  183123. png_debug1(4,"reading %d bytes\n", (int)length);
  183124. if (png_ptr->read_data_fn != NULL)
  183125. (*(png_ptr->read_data_fn))(png_ptr, data, length);
  183126. else
  183127. png_error(png_ptr, "Call to NULL read function");
  183128. }
  183129. #if !defined(PNG_NO_STDIO)
  183130. /* This is the function that does the actual reading of data. If you are
  183131. not reading from a standard C stream, you should create a replacement
  183132. read_data function and use it at run time with png_set_read_fn(), rather
  183133. than changing the library. */
  183134. #ifndef USE_FAR_KEYWORD
  183135. void PNGAPI
  183136. png_default_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  183137. {
  183138. png_size_t check;
  183139. if(png_ptr == NULL) return;
  183140. /* fread() returns 0 on error, so it is OK to store this in a png_size_t
  183141. * instead of an int, which is what fread() actually returns.
  183142. */
  183143. #if defined(_WIN32_WCE)
  183144. if ( !ReadFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  183145. check = 0;
  183146. #else
  183147. check = (png_size_t)fread(data, (png_size_t)1, length,
  183148. (png_FILE_p)png_ptr->io_ptr);
  183149. #endif
  183150. if (check != length)
  183151. png_error(png_ptr, "Read Error");
  183152. }
  183153. #else
  183154. /* this is the model-independent version. Since the standard I/O library
  183155. can't handle far buffers in the medium and small models, we have to copy
  183156. the data.
  183157. */
  183158. #define NEAR_BUF_SIZE 1024
  183159. #define MIN(a,b) (a <= b ? a : b)
  183160. static void PNGAPI
  183161. png_default_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  183162. {
  183163. int check;
  183164. png_byte *n_data;
  183165. png_FILE_p io_ptr;
  183166. if(png_ptr == NULL) return;
  183167. /* Check if data really is near. If so, use usual code. */
  183168. n_data = (png_byte *)CVT_PTR_NOCHECK(data);
  183169. io_ptr = (png_FILE_p)CVT_PTR(png_ptr->io_ptr);
  183170. if ((png_bytep)n_data == data)
  183171. {
  183172. #if defined(_WIN32_WCE)
  183173. if ( !ReadFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  183174. check = 0;
  183175. #else
  183176. check = fread(n_data, 1, length, io_ptr);
  183177. #endif
  183178. }
  183179. else
  183180. {
  183181. png_byte buf[NEAR_BUF_SIZE];
  183182. png_size_t read, remaining, err;
  183183. check = 0;
  183184. remaining = length;
  183185. do
  183186. {
  183187. read = MIN(NEAR_BUF_SIZE, remaining);
  183188. #if defined(_WIN32_WCE)
  183189. if ( !ReadFile((HANDLE)(io_ptr), buf, read, &err, NULL) )
  183190. err = 0;
  183191. #else
  183192. err = fread(buf, (png_size_t)1, read, io_ptr);
  183193. #endif
  183194. png_memcpy(data, buf, read); /* copy far buffer to near buffer */
  183195. if(err != read)
  183196. break;
  183197. else
  183198. check += err;
  183199. data += read;
  183200. remaining -= read;
  183201. }
  183202. while (remaining != 0);
  183203. }
  183204. if ((png_uint_32)check != (png_uint_32)length)
  183205. png_error(png_ptr, "read Error");
  183206. }
  183207. #endif
  183208. #endif
  183209. /* This function allows the application to supply a new input function
  183210. for libpng if standard C streams aren't being used.
  183211. This function takes as its arguments:
  183212. png_ptr - pointer to a png input data structure
  183213. io_ptr - pointer to user supplied structure containing info about
  183214. the input functions. May be NULL.
  183215. read_data_fn - pointer to a new input function that takes as its
  183216. arguments a pointer to a png_struct, a pointer to
  183217. a location where input data can be stored, and a 32-bit
  183218. unsigned int that is the number of bytes to be read.
  183219. To exit and output any fatal error messages the new write
  183220. function should call png_error(png_ptr, "Error msg"). */
  183221. void PNGAPI
  183222. png_set_read_fn(png_structp png_ptr, png_voidp io_ptr,
  183223. png_rw_ptr read_data_fn)
  183224. {
  183225. if(png_ptr == NULL) return;
  183226. png_ptr->io_ptr = io_ptr;
  183227. #if !defined(PNG_NO_STDIO)
  183228. if (read_data_fn != NULL)
  183229. png_ptr->read_data_fn = read_data_fn;
  183230. else
  183231. png_ptr->read_data_fn = png_default_read_data;
  183232. #else
  183233. png_ptr->read_data_fn = read_data_fn;
  183234. #endif
  183235. /* It is an error to write to a read device */
  183236. if (png_ptr->write_data_fn != NULL)
  183237. {
  183238. png_ptr->write_data_fn = NULL;
  183239. png_warning(png_ptr,
  183240. "It's an error to set both read_data_fn and write_data_fn in the ");
  183241. png_warning(png_ptr,
  183242. "same structure. Resetting write_data_fn to NULL.");
  183243. }
  183244. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  183245. png_ptr->output_flush_fn = NULL;
  183246. #endif
  183247. }
  183248. #endif /* PNG_READ_SUPPORTED */
  183249. /********* End of inlined file: pngrio.c *********/
  183250. /********* Start of inlined file: pngrtran.c *********/
  183251. /* pngrtran.c - transforms the data in a row for PNG readers
  183252. *
  183253. * Last changed in libpng 1.2.21 [October 4, 2007]
  183254. * For conditions of distribution and use, see copyright notice in png.h
  183255. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  183256. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  183257. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  183258. *
  183259. * This file contains functions optionally called by an application
  183260. * in order to tell libpng how to handle data when reading a PNG.
  183261. * Transformations that are used in both reading and writing are
  183262. * in pngtrans.c.
  183263. */
  183264. #define PNG_INTERNAL
  183265. #if defined(PNG_READ_SUPPORTED)
  183266. /* Set the action on getting a CRC error for an ancillary or critical chunk. */
  183267. void PNGAPI
  183268. png_set_crc_action(png_structp png_ptr, int crit_action, int ancil_action)
  183269. {
  183270. png_debug(1, "in png_set_crc_action\n");
  183271. /* Tell libpng how we react to CRC errors in critical chunks */
  183272. if(png_ptr == NULL) return;
  183273. switch (crit_action)
  183274. {
  183275. case PNG_CRC_NO_CHANGE: /* leave setting as is */
  183276. break;
  183277. case PNG_CRC_WARN_USE: /* warn/use data */
  183278. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  183279. png_ptr->flags |= PNG_FLAG_CRC_CRITICAL_USE;
  183280. break;
  183281. case PNG_CRC_QUIET_USE: /* quiet/use data */
  183282. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  183283. png_ptr->flags |= PNG_FLAG_CRC_CRITICAL_USE |
  183284. PNG_FLAG_CRC_CRITICAL_IGNORE;
  183285. break;
  183286. case PNG_CRC_WARN_DISCARD: /* not a valid action for critical data */
  183287. png_warning(png_ptr, "Can't discard critical data on CRC error.");
  183288. case PNG_CRC_ERROR_QUIT: /* error/quit */
  183289. case PNG_CRC_DEFAULT:
  183290. default:
  183291. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  183292. break;
  183293. }
  183294. switch (ancil_action)
  183295. {
  183296. case PNG_CRC_NO_CHANGE: /* leave setting as is */
  183297. break;
  183298. case PNG_CRC_WARN_USE: /* warn/use data */
  183299. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  183300. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_USE;
  183301. break;
  183302. case PNG_CRC_QUIET_USE: /* quiet/use data */
  183303. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  183304. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_USE |
  183305. PNG_FLAG_CRC_ANCILLARY_NOWARN;
  183306. break;
  183307. case PNG_CRC_ERROR_QUIT: /* error/quit */
  183308. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  183309. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_NOWARN;
  183310. break;
  183311. case PNG_CRC_WARN_DISCARD: /* warn/discard data */
  183312. case PNG_CRC_DEFAULT:
  183313. default:
  183314. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  183315. break;
  183316. }
  183317. }
  183318. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && \
  183319. defined(PNG_FLOATING_POINT_SUPPORTED)
  183320. /* handle alpha and tRNS via a background color */
  183321. void PNGAPI
  183322. png_set_background(png_structp png_ptr,
  183323. png_color_16p background_color, int background_gamma_code,
  183324. int need_expand, double background_gamma)
  183325. {
  183326. png_debug(1, "in png_set_background\n");
  183327. if(png_ptr == NULL) return;
  183328. if (background_gamma_code == PNG_BACKGROUND_GAMMA_UNKNOWN)
  183329. {
  183330. png_warning(png_ptr, "Application must supply a known background gamma");
  183331. return;
  183332. }
  183333. png_ptr->transformations |= PNG_BACKGROUND;
  183334. png_memcpy(&(png_ptr->background), background_color,
  183335. png_sizeof(png_color_16));
  183336. png_ptr->background_gamma = (float)background_gamma;
  183337. png_ptr->background_gamma_type = (png_byte)(background_gamma_code);
  183338. png_ptr->transformations |= (need_expand ? PNG_BACKGROUND_EXPAND : 0);
  183339. }
  183340. #endif
  183341. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  183342. /* strip 16 bit depth files to 8 bit depth */
  183343. void PNGAPI
  183344. png_set_strip_16(png_structp png_ptr)
  183345. {
  183346. png_debug(1, "in png_set_strip_16\n");
  183347. if(png_ptr == NULL) return;
  183348. png_ptr->transformations |= PNG_16_TO_8;
  183349. }
  183350. #endif
  183351. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  183352. void PNGAPI
  183353. png_set_strip_alpha(png_structp png_ptr)
  183354. {
  183355. png_debug(1, "in png_set_strip_alpha\n");
  183356. if(png_ptr == NULL) return;
  183357. png_ptr->flags |= PNG_FLAG_STRIP_ALPHA;
  183358. }
  183359. #endif
  183360. #if defined(PNG_READ_DITHER_SUPPORTED)
  183361. /* Dither file to 8 bit. Supply a palette, the current number
  183362. * of elements in the palette, the maximum number of elements
  183363. * allowed, and a histogram if possible. If the current number
  183364. * of colors is greater then the maximum number, the palette will be
  183365. * modified to fit in the maximum number. "full_dither" indicates
  183366. * whether we need a dithering cube set up for RGB images, or if we
  183367. * simply are reducing the number of colors in a paletted image.
  183368. */
  183369. typedef struct png_dsort_struct
  183370. {
  183371. struct png_dsort_struct FAR * next;
  183372. png_byte left;
  183373. png_byte right;
  183374. } png_dsort;
  183375. typedef png_dsort FAR * png_dsortp;
  183376. typedef png_dsort FAR * FAR * png_dsortpp;
  183377. void PNGAPI
  183378. png_set_dither(png_structp png_ptr, png_colorp palette,
  183379. int num_palette, int maximum_colors, png_uint_16p histogram,
  183380. int full_dither)
  183381. {
  183382. png_debug(1, "in png_set_dither\n");
  183383. if(png_ptr == NULL) return;
  183384. png_ptr->transformations |= PNG_DITHER;
  183385. if (!full_dither)
  183386. {
  183387. int i;
  183388. png_ptr->dither_index = (png_bytep)png_malloc(png_ptr,
  183389. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  183390. for (i = 0; i < num_palette; i++)
  183391. png_ptr->dither_index[i] = (png_byte)i;
  183392. }
  183393. if (num_palette > maximum_colors)
  183394. {
  183395. if (histogram != NULL)
  183396. {
  183397. /* This is easy enough, just throw out the least used colors.
  183398. Perhaps not the best solution, but good enough. */
  183399. int i;
  183400. /* initialize an array to sort colors */
  183401. png_ptr->dither_sort = (png_bytep)png_malloc(png_ptr,
  183402. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  183403. /* initialize the dither_sort array */
  183404. for (i = 0; i < num_palette; i++)
  183405. png_ptr->dither_sort[i] = (png_byte)i;
  183406. /* Find the least used palette entries by starting a
  183407. bubble sort, and running it until we have sorted
  183408. out enough colors. Note that we don't care about
  183409. sorting all the colors, just finding which are
  183410. least used. */
  183411. for (i = num_palette - 1; i >= maximum_colors; i--)
  183412. {
  183413. int done; /* to stop early if the list is pre-sorted */
  183414. int j;
  183415. done = 1;
  183416. for (j = 0; j < i; j++)
  183417. {
  183418. if (histogram[png_ptr->dither_sort[j]]
  183419. < histogram[png_ptr->dither_sort[j + 1]])
  183420. {
  183421. png_byte t;
  183422. t = png_ptr->dither_sort[j];
  183423. png_ptr->dither_sort[j] = png_ptr->dither_sort[j + 1];
  183424. png_ptr->dither_sort[j + 1] = t;
  183425. done = 0;
  183426. }
  183427. }
  183428. if (done)
  183429. break;
  183430. }
  183431. /* swap the palette around, and set up a table, if necessary */
  183432. if (full_dither)
  183433. {
  183434. int j = num_palette;
  183435. /* put all the useful colors within the max, but don't
  183436. move the others */
  183437. for (i = 0; i < maximum_colors; i++)
  183438. {
  183439. if ((int)png_ptr->dither_sort[i] >= maximum_colors)
  183440. {
  183441. do
  183442. j--;
  183443. while ((int)png_ptr->dither_sort[j] >= maximum_colors);
  183444. palette[i] = palette[j];
  183445. }
  183446. }
  183447. }
  183448. else
  183449. {
  183450. int j = num_palette;
  183451. /* move all the used colors inside the max limit, and
  183452. develop a translation table */
  183453. for (i = 0; i < maximum_colors; i++)
  183454. {
  183455. /* only move the colors we need to */
  183456. if ((int)png_ptr->dither_sort[i] >= maximum_colors)
  183457. {
  183458. png_color tmp_color;
  183459. do
  183460. j--;
  183461. while ((int)png_ptr->dither_sort[j] >= maximum_colors);
  183462. tmp_color = palette[j];
  183463. palette[j] = palette[i];
  183464. palette[i] = tmp_color;
  183465. /* indicate where the color went */
  183466. png_ptr->dither_index[j] = (png_byte)i;
  183467. png_ptr->dither_index[i] = (png_byte)j;
  183468. }
  183469. }
  183470. /* find closest color for those colors we are not using */
  183471. for (i = 0; i < num_palette; i++)
  183472. {
  183473. if ((int)png_ptr->dither_index[i] >= maximum_colors)
  183474. {
  183475. int min_d, k, min_k, d_index;
  183476. /* find the closest color to one we threw out */
  183477. d_index = png_ptr->dither_index[i];
  183478. min_d = PNG_COLOR_DIST(palette[d_index], palette[0]);
  183479. for (k = 1, min_k = 0; k < maximum_colors; k++)
  183480. {
  183481. int d;
  183482. d = PNG_COLOR_DIST(palette[d_index], palette[k]);
  183483. if (d < min_d)
  183484. {
  183485. min_d = d;
  183486. min_k = k;
  183487. }
  183488. }
  183489. /* point to closest color */
  183490. png_ptr->dither_index[i] = (png_byte)min_k;
  183491. }
  183492. }
  183493. }
  183494. png_free(png_ptr, png_ptr->dither_sort);
  183495. png_ptr->dither_sort=NULL;
  183496. }
  183497. else
  183498. {
  183499. /* This is much harder to do simply (and quickly). Perhaps
  183500. we need to go through a median cut routine, but those
  183501. don't always behave themselves with only a few colors
  183502. as input. So we will just find the closest two colors,
  183503. and throw out one of them (chosen somewhat randomly).
  183504. [We don't understand this at all, so if someone wants to
  183505. work on improving it, be our guest - AED, GRP]
  183506. */
  183507. int i;
  183508. int max_d;
  183509. int num_new_palette;
  183510. png_dsortp t;
  183511. png_dsortpp hash;
  183512. t=NULL;
  183513. /* initialize palette index arrays */
  183514. png_ptr->index_to_palette = (png_bytep)png_malloc(png_ptr,
  183515. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  183516. png_ptr->palette_to_index = (png_bytep)png_malloc(png_ptr,
  183517. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  183518. /* initialize the sort array */
  183519. for (i = 0; i < num_palette; i++)
  183520. {
  183521. png_ptr->index_to_palette[i] = (png_byte)i;
  183522. png_ptr->palette_to_index[i] = (png_byte)i;
  183523. }
  183524. hash = (png_dsortpp)png_malloc(png_ptr, (png_uint_32)(769 *
  183525. png_sizeof (png_dsortp)));
  183526. for (i = 0; i < 769; i++)
  183527. hash[i] = NULL;
  183528. /* png_memset(hash, 0, 769 * png_sizeof (png_dsortp)); */
  183529. num_new_palette = num_palette;
  183530. /* initial wild guess at how far apart the farthest pixel
  183531. pair we will be eliminating will be. Larger
  183532. numbers mean more areas will be allocated, Smaller
  183533. numbers run the risk of not saving enough data, and
  183534. having to do this all over again.
  183535. I have not done extensive checking on this number.
  183536. */
  183537. max_d = 96;
  183538. while (num_new_palette > maximum_colors)
  183539. {
  183540. for (i = 0; i < num_new_palette - 1; i++)
  183541. {
  183542. int j;
  183543. for (j = i + 1; j < num_new_palette; j++)
  183544. {
  183545. int d;
  183546. d = PNG_COLOR_DIST(palette[i], palette[j]);
  183547. if (d <= max_d)
  183548. {
  183549. t = (png_dsortp)png_malloc_warn(png_ptr,
  183550. (png_uint_32)(png_sizeof(png_dsort)));
  183551. if (t == NULL)
  183552. break;
  183553. t->next = hash[d];
  183554. t->left = (png_byte)i;
  183555. t->right = (png_byte)j;
  183556. hash[d] = t;
  183557. }
  183558. }
  183559. if (t == NULL)
  183560. break;
  183561. }
  183562. if (t != NULL)
  183563. for (i = 0; i <= max_d; i++)
  183564. {
  183565. if (hash[i] != NULL)
  183566. {
  183567. png_dsortp p;
  183568. for (p = hash[i]; p; p = p->next)
  183569. {
  183570. if ((int)png_ptr->index_to_palette[p->left]
  183571. < num_new_palette &&
  183572. (int)png_ptr->index_to_palette[p->right]
  183573. < num_new_palette)
  183574. {
  183575. int j, next_j;
  183576. if (num_new_palette & 0x01)
  183577. {
  183578. j = p->left;
  183579. next_j = p->right;
  183580. }
  183581. else
  183582. {
  183583. j = p->right;
  183584. next_j = p->left;
  183585. }
  183586. num_new_palette--;
  183587. palette[png_ptr->index_to_palette[j]]
  183588. = palette[num_new_palette];
  183589. if (!full_dither)
  183590. {
  183591. int k;
  183592. for (k = 0; k < num_palette; k++)
  183593. {
  183594. if (png_ptr->dither_index[k] ==
  183595. png_ptr->index_to_palette[j])
  183596. png_ptr->dither_index[k] =
  183597. png_ptr->index_to_palette[next_j];
  183598. if ((int)png_ptr->dither_index[k] ==
  183599. num_new_palette)
  183600. png_ptr->dither_index[k] =
  183601. png_ptr->index_to_palette[j];
  183602. }
  183603. }
  183604. png_ptr->index_to_palette[png_ptr->palette_to_index
  183605. [num_new_palette]] = png_ptr->index_to_palette[j];
  183606. png_ptr->palette_to_index[png_ptr->index_to_palette[j]]
  183607. = png_ptr->palette_to_index[num_new_palette];
  183608. png_ptr->index_to_palette[j] = (png_byte)num_new_palette;
  183609. png_ptr->palette_to_index[num_new_palette] = (png_byte)j;
  183610. }
  183611. if (num_new_palette <= maximum_colors)
  183612. break;
  183613. }
  183614. if (num_new_palette <= maximum_colors)
  183615. break;
  183616. }
  183617. }
  183618. for (i = 0; i < 769; i++)
  183619. {
  183620. if (hash[i] != NULL)
  183621. {
  183622. png_dsortp p = hash[i];
  183623. while (p)
  183624. {
  183625. t = p->next;
  183626. png_free(png_ptr, p);
  183627. p = t;
  183628. }
  183629. }
  183630. hash[i] = 0;
  183631. }
  183632. max_d += 96;
  183633. }
  183634. png_free(png_ptr, hash);
  183635. png_free(png_ptr, png_ptr->palette_to_index);
  183636. png_free(png_ptr, png_ptr->index_to_palette);
  183637. png_ptr->palette_to_index=NULL;
  183638. png_ptr->index_to_palette=NULL;
  183639. }
  183640. num_palette = maximum_colors;
  183641. }
  183642. if (png_ptr->palette == NULL)
  183643. {
  183644. png_ptr->palette = palette;
  183645. }
  183646. png_ptr->num_palette = (png_uint_16)num_palette;
  183647. if (full_dither)
  183648. {
  183649. int i;
  183650. png_bytep distance;
  183651. int total_bits = PNG_DITHER_RED_BITS + PNG_DITHER_GREEN_BITS +
  183652. PNG_DITHER_BLUE_BITS;
  183653. int num_red = (1 << PNG_DITHER_RED_BITS);
  183654. int num_green = (1 << PNG_DITHER_GREEN_BITS);
  183655. int num_blue = (1 << PNG_DITHER_BLUE_BITS);
  183656. png_size_t num_entries = ((png_size_t)1 << total_bits);
  183657. png_ptr->palette_lookup = (png_bytep )png_malloc(png_ptr,
  183658. (png_uint_32)(num_entries * png_sizeof (png_byte)));
  183659. png_memset(png_ptr->palette_lookup, 0, num_entries *
  183660. png_sizeof (png_byte));
  183661. distance = (png_bytep)png_malloc(png_ptr, (png_uint_32)(num_entries *
  183662. png_sizeof(png_byte)));
  183663. png_memset(distance, 0xff, num_entries * png_sizeof(png_byte));
  183664. for (i = 0; i < num_palette; i++)
  183665. {
  183666. int ir, ig, ib;
  183667. int r = (palette[i].red >> (8 - PNG_DITHER_RED_BITS));
  183668. int g = (palette[i].green >> (8 - PNG_DITHER_GREEN_BITS));
  183669. int b = (palette[i].blue >> (8 - PNG_DITHER_BLUE_BITS));
  183670. for (ir = 0; ir < num_red; ir++)
  183671. {
  183672. /* int dr = abs(ir - r); */
  183673. int dr = ((ir > r) ? ir - r : r - ir);
  183674. int index_r = (ir << (PNG_DITHER_BLUE_BITS + PNG_DITHER_GREEN_BITS));
  183675. for (ig = 0; ig < num_green; ig++)
  183676. {
  183677. /* int dg = abs(ig - g); */
  183678. int dg = ((ig > g) ? ig - g : g - ig);
  183679. int dt = dr + dg;
  183680. int dm = ((dr > dg) ? dr : dg);
  183681. int index_g = index_r | (ig << PNG_DITHER_BLUE_BITS);
  183682. for (ib = 0; ib < num_blue; ib++)
  183683. {
  183684. int d_index = index_g | ib;
  183685. /* int db = abs(ib - b); */
  183686. int db = ((ib > b) ? ib - b : b - ib);
  183687. int dmax = ((dm > db) ? dm : db);
  183688. int d = dmax + dt + db;
  183689. if (d < (int)distance[d_index])
  183690. {
  183691. distance[d_index] = (png_byte)d;
  183692. png_ptr->palette_lookup[d_index] = (png_byte)i;
  183693. }
  183694. }
  183695. }
  183696. }
  183697. }
  183698. png_free(png_ptr, distance);
  183699. }
  183700. }
  183701. #endif
  183702. #if defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  183703. /* Transform the image from the file_gamma to the screen_gamma. We
  183704. * only do transformations on images where the file_gamma and screen_gamma
  183705. * are not close reciprocals, otherwise it slows things down slightly, and
  183706. * also needlessly introduces small errors.
  183707. *
  183708. * We will turn off gamma transformation later if no semitransparent entries
  183709. * are present in the tRNS array for palette images. We can't do it here
  183710. * because we don't necessarily have the tRNS chunk yet.
  183711. */
  183712. void PNGAPI
  183713. png_set_gamma(png_structp png_ptr, double scrn_gamma, double file_gamma)
  183714. {
  183715. png_debug(1, "in png_set_gamma\n");
  183716. if(png_ptr == NULL) return;
  183717. if ((fabs(scrn_gamma * file_gamma - 1.0) > PNG_GAMMA_THRESHOLD) ||
  183718. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA) ||
  183719. (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE))
  183720. png_ptr->transformations |= PNG_GAMMA;
  183721. png_ptr->gamma = (float)file_gamma;
  183722. png_ptr->screen_gamma = (float)scrn_gamma;
  183723. }
  183724. #endif
  183725. #if defined(PNG_READ_EXPAND_SUPPORTED)
  183726. /* Expand paletted images to RGB, expand grayscale images of
  183727. * less than 8-bit depth to 8-bit depth, and expand tRNS chunks
  183728. * to alpha channels.
  183729. */
  183730. void PNGAPI
  183731. png_set_expand(png_structp png_ptr)
  183732. {
  183733. png_debug(1, "in png_set_expand\n");
  183734. if(png_ptr == NULL) return;
  183735. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  183736. #ifdef PNG_WARN_UNINITIALIZED_ROW
  183737. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  183738. #endif
  183739. }
  183740. /* GRR 19990627: the following three functions currently are identical
  183741. * to png_set_expand(). However, it is entirely reasonable that someone
  183742. * might wish to expand an indexed image to RGB but *not* expand a single,
  183743. * fully transparent palette entry to a full alpha channel--perhaps instead
  183744. * convert tRNS to the grayscale/RGB format (16-bit RGB value), or replace
  183745. * the transparent color with a particular RGB value, or drop tRNS entirely.
  183746. * IOW, a future version of the library may make the transformations flag
  183747. * a bit more fine-grained, with separate bits for each of these three
  183748. * functions.
  183749. *
  183750. * More to the point, these functions make it obvious what libpng will be
  183751. * doing, whereas "expand" can (and does) mean any number of things.
  183752. *
  183753. * GRP 20060307: In libpng-1.4.0, png_set_gray_1_2_4_to_8() was modified
  183754. * to expand only the sample depth but not to expand the tRNS to alpha.
  183755. */
  183756. /* Expand paletted images to RGB. */
  183757. void PNGAPI
  183758. png_set_palette_to_rgb(png_structp png_ptr)
  183759. {
  183760. png_debug(1, "in png_set_palette_to_rgb\n");
  183761. if(png_ptr == NULL) return;
  183762. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  183763. #ifdef PNG_WARN_UNINITIALIZED_ROW
  183764. png_ptr->flags &= !(PNG_FLAG_ROW_INIT);
  183765. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  183766. #endif
  183767. }
  183768. #if !defined(PNG_1_0_X)
  183769. /* Expand grayscale images of less than 8-bit depth to 8 bits. */
  183770. void PNGAPI
  183771. png_set_expand_gray_1_2_4_to_8(png_structp png_ptr)
  183772. {
  183773. png_debug(1, "in png_set_expand_gray_1_2_4_to_8\n");
  183774. if(png_ptr == NULL) return;
  183775. png_ptr->transformations |= PNG_EXPAND;
  183776. #ifdef PNG_WARN_UNINITIALIZED_ROW
  183777. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  183778. #endif
  183779. }
  183780. #endif
  183781. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  183782. /* Expand grayscale images of less than 8-bit depth to 8 bits. */
  183783. /* Deprecated as of libpng-1.2.9 */
  183784. void PNGAPI
  183785. png_set_gray_1_2_4_to_8(png_structp png_ptr)
  183786. {
  183787. png_debug(1, "in png_set_gray_1_2_4_to_8\n");
  183788. if(png_ptr == NULL) return;
  183789. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  183790. }
  183791. #endif
  183792. /* Expand tRNS chunks to alpha channels. */
  183793. void PNGAPI
  183794. png_set_tRNS_to_alpha(png_structp png_ptr)
  183795. {
  183796. png_debug(1, "in png_set_tRNS_to_alpha\n");
  183797. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  183798. #ifdef PNG_WARN_UNINITIALIZED_ROW
  183799. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  183800. #endif
  183801. }
  183802. #endif /* defined(PNG_READ_EXPAND_SUPPORTED) */
  183803. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  183804. void PNGAPI
  183805. png_set_gray_to_rgb(png_structp png_ptr)
  183806. {
  183807. png_debug(1, "in png_set_gray_to_rgb\n");
  183808. png_ptr->transformations |= PNG_GRAY_TO_RGB;
  183809. #ifdef PNG_WARN_UNINITIALIZED_ROW
  183810. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  183811. #endif
  183812. }
  183813. #endif
  183814. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  183815. #if defined(PNG_FLOATING_POINT_SUPPORTED)
  183816. /* Convert a RGB image to a grayscale of the same width. This allows us,
  183817. * for example, to convert a 24 bpp RGB image into an 8 bpp grayscale image.
  183818. */
  183819. void PNGAPI
  183820. png_set_rgb_to_gray(png_structp png_ptr, int error_action, double red,
  183821. double green)
  183822. {
  183823. int red_fixed = (int)((float)red*100000.0 + 0.5);
  183824. int green_fixed = (int)((float)green*100000.0 + 0.5);
  183825. if(png_ptr == NULL) return;
  183826. png_set_rgb_to_gray_fixed(png_ptr, error_action, red_fixed, green_fixed);
  183827. }
  183828. #endif
  183829. void PNGAPI
  183830. png_set_rgb_to_gray_fixed(png_structp png_ptr, int error_action,
  183831. png_fixed_point red, png_fixed_point green)
  183832. {
  183833. png_debug(1, "in png_set_rgb_to_gray\n");
  183834. if(png_ptr == NULL) return;
  183835. switch(error_action)
  183836. {
  183837. case 1: png_ptr->transformations |= PNG_RGB_TO_GRAY;
  183838. break;
  183839. case 2: png_ptr->transformations |= PNG_RGB_TO_GRAY_WARN;
  183840. break;
  183841. case 3: png_ptr->transformations |= PNG_RGB_TO_GRAY_ERR;
  183842. }
  183843. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  183844. #if defined(PNG_READ_EXPAND_SUPPORTED)
  183845. png_ptr->transformations |= PNG_EXPAND;
  183846. #else
  183847. {
  183848. png_warning(png_ptr, "Cannot do RGB_TO_GRAY without EXPAND_SUPPORTED.");
  183849. png_ptr->transformations &= ~PNG_RGB_TO_GRAY;
  183850. }
  183851. #endif
  183852. {
  183853. png_uint_16 red_int, green_int;
  183854. if(red < 0 || green < 0)
  183855. {
  183856. red_int = 6968; /* .212671 * 32768 + .5 */
  183857. green_int = 23434; /* .715160 * 32768 + .5 */
  183858. }
  183859. else if(red + green < 100000L)
  183860. {
  183861. red_int = (png_uint_16)(((png_uint_32)red*32768L)/100000L);
  183862. green_int = (png_uint_16)(((png_uint_32)green*32768L)/100000L);
  183863. }
  183864. else
  183865. {
  183866. png_warning(png_ptr, "ignoring out of range rgb_to_gray coefficients");
  183867. red_int = 6968;
  183868. green_int = 23434;
  183869. }
  183870. png_ptr->rgb_to_gray_red_coeff = red_int;
  183871. png_ptr->rgb_to_gray_green_coeff = green_int;
  183872. png_ptr->rgb_to_gray_blue_coeff = (png_uint_16)(32768-red_int-green_int);
  183873. }
  183874. }
  183875. #endif
  183876. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  183877. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  183878. defined(PNG_LEGACY_SUPPORTED)
  183879. void PNGAPI
  183880. png_set_read_user_transform_fn(png_structp png_ptr, png_user_transform_ptr
  183881. read_user_transform_fn)
  183882. {
  183883. png_debug(1, "in png_set_read_user_transform_fn\n");
  183884. if(png_ptr == NULL) return;
  183885. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  183886. png_ptr->transformations |= PNG_USER_TRANSFORM;
  183887. png_ptr->read_user_transform_fn = read_user_transform_fn;
  183888. #endif
  183889. #ifdef PNG_LEGACY_SUPPORTED
  183890. if(read_user_transform_fn)
  183891. png_warning(png_ptr,
  183892. "This version of libpng does not support user transforms");
  183893. #endif
  183894. }
  183895. #endif
  183896. /* Initialize everything needed for the read. This includes modifying
  183897. * the palette.
  183898. */
  183899. void /* PRIVATE */
  183900. png_init_read_transformations(png_structp png_ptr)
  183901. {
  183902. png_debug(1, "in png_init_read_transformations\n");
  183903. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  183904. if(png_ptr != NULL)
  183905. #endif
  183906. {
  183907. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || defined(PNG_READ_SHIFT_SUPPORTED) \
  183908. || defined(PNG_READ_GAMMA_SUPPORTED)
  183909. int color_type = png_ptr->color_type;
  183910. #endif
  183911. #if defined(PNG_READ_EXPAND_SUPPORTED) && defined(PNG_READ_BACKGROUND_SUPPORTED)
  183912. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  183913. /* Detect gray background and attempt to enable optimization
  183914. * for gray --> RGB case */
  183915. /* Note: if PNG_BACKGROUND_EXPAND is set and color_type is either RGB or
  183916. * RGB_ALPHA (in which case need_expand is superfluous anyway), the
  183917. * background color might actually be gray yet not be flagged as such.
  183918. * This is not a problem for the current code, which uses
  183919. * PNG_BACKGROUND_IS_GRAY only to decide when to do the
  183920. * png_do_gray_to_rgb() transformation.
  183921. */
  183922. if ((png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  183923. !(color_type & PNG_COLOR_MASK_COLOR))
  183924. {
  183925. png_ptr->mode |= PNG_BACKGROUND_IS_GRAY;
  183926. } else if ((png_ptr->transformations & PNG_BACKGROUND) &&
  183927. !(png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  183928. (png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  183929. png_ptr->background.red == png_ptr->background.green &&
  183930. png_ptr->background.red == png_ptr->background.blue)
  183931. {
  183932. png_ptr->mode |= PNG_BACKGROUND_IS_GRAY;
  183933. png_ptr->background.gray = png_ptr->background.red;
  183934. }
  183935. #endif
  183936. if ((png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  183937. (png_ptr->transformations & PNG_EXPAND))
  183938. {
  183939. if (!(color_type & PNG_COLOR_MASK_COLOR)) /* i.e., GRAY or GRAY_ALPHA */
  183940. {
  183941. /* expand background and tRNS chunks */
  183942. switch (png_ptr->bit_depth)
  183943. {
  183944. case 1:
  183945. png_ptr->background.gray *= (png_uint_16)0xff;
  183946. png_ptr->background.red = png_ptr->background.green
  183947. = png_ptr->background.blue = png_ptr->background.gray;
  183948. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  183949. {
  183950. png_ptr->trans_values.gray *= (png_uint_16)0xff;
  183951. png_ptr->trans_values.red = png_ptr->trans_values.green
  183952. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  183953. }
  183954. break;
  183955. case 2:
  183956. png_ptr->background.gray *= (png_uint_16)0x55;
  183957. png_ptr->background.red = png_ptr->background.green
  183958. = png_ptr->background.blue = png_ptr->background.gray;
  183959. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  183960. {
  183961. png_ptr->trans_values.gray *= (png_uint_16)0x55;
  183962. png_ptr->trans_values.red = png_ptr->trans_values.green
  183963. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  183964. }
  183965. break;
  183966. case 4:
  183967. png_ptr->background.gray *= (png_uint_16)0x11;
  183968. png_ptr->background.red = png_ptr->background.green
  183969. = png_ptr->background.blue = png_ptr->background.gray;
  183970. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  183971. {
  183972. png_ptr->trans_values.gray *= (png_uint_16)0x11;
  183973. png_ptr->trans_values.red = png_ptr->trans_values.green
  183974. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  183975. }
  183976. break;
  183977. case 8:
  183978. case 16:
  183979. png_ptr->background.red = png_ptr->background.green
  183980. = png_ptr->background.blue = png_ptr->background.gray;
  183981. break;
  183982. }
  183983. }
  183984. else if (color_type == PNG_COLOR_TYPE_PALETTE)
  183985. {
  183986. png_ptr->background.red =
  183987. png_ptr->palette[png_ptr->background.index].red;
  183988. png_ptr->background.green =
  183989. png_ptr->palette[png_ptr->background.index].green;
  183990. png_ptr->background.blue =
  183991. png_ptr->palette[png_ptr->background.index].blue;
  183992. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  183993. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  183994. {
  183995. #if defined(PNG_READ_EXPAND_SUPPORTED)
  183996. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  183997. #endif
  183998. {
  183999. /* invert the alpha channel (in tRNS) unless the pixels are
  184000. going to be expanded, in which case leave it for later */
  184001. int i,istop;
  184002. istop=(int)png_ptr->num_trans;
  184003. for (i=0; i<istop; i++)
  184004. png_ptr->trans[i] = (png_byte)(255 - png_ptr->trans[i]);
  184005. }
  184006. }
  184007. #endif
  184008. }
  184009. }
  184010. #endif
  184011. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && defined(PNG_READ_GAMMA_SUPPORTED)
  184012. png_ptr->background_1 = png_ptr->background;
  184013. #endif
  184014. #if defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  184015. if ((color_type == PNG_COLOR_TYPE_PALETTE && png_ptr->num_trans != 0)
  184016. && (fabs(png_ptr->screen_gamma * png_ptr->gamma - 1.0)
  184017. < PNG_GAMMA_THRESHOLD))
  184018. {
  184019. int i,k;
  184020. k=0;
  184021. for (i=0; i<png_ptr->num_trans; i++)
  184022. {
  184023. if (png_ptr->trans[i] != 0 && png_ptr->trans[i] != 0xff)
  184024. k=1; /* partial transparency is present */
  184025. }
  184026. if (k == 0)
  184027. png_ptr->transformations &= (~PNG_GAMMA);
  184028. }
  184029. if ((png_ptr->transformations & (PNG_GAMMA | PNG_RGB_TO_GRAY)) &&
  184030. png_ptr->gamma != 0.0)
  184031. {
  184032. png_build_gamma_table(png_ptr);
  184033. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  184034. if (png_ptr->transformations & PNG_BACKGROUND)
  184035. {
  184036. if (color_type == PNG_COLOR_TYPE_PALETTE)
  184037. {
  184038. /* could skip if no transparency and
  184039. */
  184040. png_color back, back_1;
  184041. png_colorp palette = png_ptr->palette;
  184042. int num_palette = png_ptr->num_palette;
  184043. int i;
  184044. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_FILE)
  184045. {
  184046. back.red = png_ptr->gamma_table[png_ptr->background.red];
  184047. back.green = png_ptr->gamma_table[png_ptr->background.green];
  184048. back.blue = png_ptr->gamma_table[png_ptr->background.blue];
  184049. back_1.red = png_ptr->gamma_to_1[png_ptr->background.red];
  184050. back_1.green = png_ptr->gamma_to_1[png_ptr->background.green];
  184051. back_1.blue = png_ptr->gamma_to_1[png_ptr->background.blue];
  184052. }
  184053. else
  184054. {
  184055. double g, gs;
  184056. switch (png_ptr->background_gamma_type)
  184057. {
  184058. case PNG_BACKGROUND_GAMMA_SCREEN:
  184059. g = (png_ptr->screen_gamma);
  184060. gs = 1.0;
  184061. break;
  184062. case PNG_BACKGROUND_GAMMA_FILE:
  184063. g = 1.0 / (png_ptr->gamma);
  184064. gs = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  184065. break;
  184066. case PNG_BACKGROUND_GAMMA_UNIQUE:
  184067. g = 1.0 / (png_ptr->background_gamma);
  184068. gs = 1.0 / (png_ptr->background_gamma *
  184069. png_ptr->screen_gamma);
  184070. break;
  184071. default:
  184072. g = 1.0; /* back_1 */
  184073. gs = 1.0; /* back */
  184074. }
  184075. if ( fabs(gs - 1.0) < PNG_GAMMA_THRESHOLD)
  184076. {
  184077. back.red = (png_byte)png_ptr->background.red;
  184078. back.green = (png_byte)png_ptr->background.green;
  184079. back.blue = (png_byte)png_ptr->background.blue;
  184080. }
  184081. else
  184082. {
  184083. back.red = (png_byte)(pow(
  184084. (double)png_ptr->background.red/255, gs) * 255.0 + .5);
  184085. back.green = (png_byte)(pow(
  184086. (double)png_ptr->background.green/255, gs) * 255.0 + .5);
  184087. back.blue = (png_byte)(pow(
  184088. (double)png_ptr->background.blue/255, gs) * 255.0 + .5);
  184089. }
  184090. back_1.red = (png_byte)(pow(
  184091. (double)png_ptr->background.red/255, g) * 255.0 + .5);
  184092. back_1.green = (png_byte)(pow(
  184093. (double)png_ptr->background.green/255, g) * 255.0 + .5);
  184094. back_1.blue = (png_byte)(pow(
  184095. (double)png_ptr->background.blue/255, g) * 255.0 + .5);
  184096. }
  184097. for (i = 0; i < num_palette; i++)
  184098. {
  184099. if (i < (int)png_ptr->num_trans && png_ptr->trans[i] != 0xff)
  184100. {
  184101. if (png_ptr->trans[i] == 0)
  184102. {
  184103. palette[i] = back;
  184104. }
  184105. else /* if (png_ptr->trans[i] != 0xff) */
  184106. {
  184107. png_byte v, w;
  184108. v = png_ptr->gamma_to_1[palette[i].red];
  184109. png_composite(w, v, png_ptr->trans[i], back_1.red);
  184110. palette[i].red = png_ptr->gamma_from_1[w];
  184111. v = png_ptr->gamma_to_1[palette[i].green];
  184112. png_composite(w, v, png_ptr->trans[i], back_1.green);
  184113. palette[i].green = png_ptr->gamma_from_1[w];
  184114. v = png_ptr->gamma_to_1[palette[i].blue];
  184115. png_composite(w, v, png_ptr->trans[i], back_1.blue);
  184116. palette[i].blue = png_ptr->gamma_from_1[w];
  184117. }
  184118. }
  184119. else
  184120. {
  184121. palette[i].red = png_ptr->gamma_table[palette[i].red];
  184122. palette[i].green = png_ptr->gamma_table[palette[i].green];
  184123. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  184124. }
  184125. }
  184126. }
  184127. /* if (png_ptr->background_gamma_type!=PNG_BACKGROUND_GAMMA_UNKNOWN) */
  184128. else
  184129. /* color_type != PNG_COLOR_TYPE_PALETTE */
  184130. {
  184131. double m = (double)(((png_uint_32)1 << png_ptr->bit_depth) - 1);
  184132. double g = 1.0;
  184133. double gs = 1.0;
  184134. switch (png_ptr->background_gamma_type)
  184135. {
  184136. case PNG_BACKGROUND_GAMMA_SCREEN:
  184137. g = (png_ptr->screen_gamma);
  184138. gs = 1.0;
  184139. break;
  184140. case PNG_BACKGROUND_GAMMA_FILE:
  184141. g = 1.0 / (png_ptr->gamma);
  184142. gs = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  184143. break;
  184144. case PNG_BACKGROUND_GAMMA_UNIQUE:
  184145. g = 1.0 / (png_ptr->background_gamma);
  184146. gs = 1.0 / (png_ptr->background_gamma *
  184147. png_ptr->screen_gamma);
  184148. break;
  184149. }
  184150. png_ptr->background_1.gray = (png_uint_16)(pow(
  184151. (double)png_ptr->background.gray / m, g) * m + .5);
  184152. png_ptr->background.gray = (png_uint_16)(pow(
  184153. (double)png_ptr->background.gray / m, gs) * m + .5);
  184154. if ((png_ptr->background.red != png_ptr->background.green) ||
  184155. (png_ptr->background.red != png_ptr->background.blue) ||
  184156. (png_ptr->background.red != png_ptr->background.gray))
  184157. {
  184158. /* RGB or RGBA with color background */
  184159. png_ptr->background_1.red = (png_uint_16)(pow(
  184160. (double)png_ptr->background.red / m, g) * m + .5);
  184161. png_ptr->background_1.green = (png_uint_16)(pow(
  184162. (double)png_ptr->background.green / m, g) * m + .5);
  184163. png_ptr->background_1.blue = (png_uint_16)(pow(
  184164. (double)png_ptr->background.blue / m, g) * m + .5);
  184165. png_ptr->background.red = (png_uint_16)(pow(
  184166. (double)png_ptr->background.red / m, gs) * m + .5);
  184167. png_ptr->background.green = (png_uint_16)(pow(
  184168. (double)png_ptr->background.green / m, gs) * m + .5);
  184169. png_ptr->background.blue = (png_uint_16)(pow(
  184170. (double)png_ptr->background.blue / m, gs) * m + .5);
  184171. }
  184172. else
  184173. {
  184174. /* GRAY, GRAY ALPHA, RGB, or RGBA with gray background */
  184175. png_ptr->background_1.red = png_ptr->background_1.green
  184176. = png_ptr->background_1.blue = png_ptr->background_1.gray;
  184177. png_ptr->background.red = png_ptr->background.green
  184178. = png_ptr->background.blue = png_ptr->background.gray;
  184179. }
  184180. }
  184181. }
  184182. else
  184183. /* transformation does not include PNG_BACKGROUND */
  184184. #endif /* PNG_READ_BACKGROUND_SUPPORTED */
  184185. if (color_type == PNG_COLOR_TYPE_PALETTE)
  184186. {
  184187. png_colorp palette = png_ptr->palette;
  184188. int num_palette = png_ptr->num_palette;
  184189. int i;
  184190. for (i = 0; i < num_palette; i++)
  184191. {
  184192. palette[i].red = png_ptr->gamma_table[palette[i].red];
  184193. palette[i].green = png_ptr->gamma_table[palette[i].green];
  184194. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  184195. }
  184196. }
  184197. }
  184198. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  184199. else
  184200. #endif
  184201. #endif /* PNG_READ_GAMMA_SUPPORTED && PNG_FLOATING_POINT_SUPPORTED */
  184202. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  184203. /* No GAMMA transformation */
  184204. if ((png_ptr->transformations & PNG_BACKGROUND) &&
  184205. (color_type == PNG_COLOR_TYPE_PALETTE))
  184206. {
  184207. int i;
  184208. int istop = (int)png_ptr->num_trans;
  184209. png_color back;
  184210. png_colorp palette = png_ptr->palette;
  184211. back.red = (png_byte)png_ptr->background.red;
  184212. back.green = (png_byte)png_ptr->background.green;
  184213. back.blue = (png_byte)png_ptr->background.blue;
  184214. for (i = 0; i < istop; i++)
  184215. {
  184216. if (png_ptr->trans[i] == 0)
  184217. {
  184218. palette[i] = back;
  184219. }
  184220. else if (png_ptr->trans[i] != 0xff)
  184221. {
  184222. /* The png_composite() macro is defined in png.h */
  184223. png_composite(palette[i].red, palette[i].red,
  184224. png_ptr->trans[i], back.red);
  184225. png_composite(palette[i].green, palette[i].green,
  184226. png_ptr->trans[i], back.green);
  184227. png_composite(palette[i].blue, palette[i].blue,
  184228. png_ptr->trans[i], back.blue);
  184229. }
  184230. }
  184231. }
  184232. #endif /* PNG_READ_BACKGROUND_SUPPORTED */
  184233. #if defined(PNG_READ_SHIFT_SUPPORTED)
  184234. if ((png_ptr->transformations & PNG_SHIFT) &&
  184235. (color_type == PNG_COLOR_TYPE_PALETTE))
  184236. {
  184237. png_uint_16 i;
  184238. png_uint_16 istop = png_ptr->num_palette;
  184239. int sr = 8 - png_ptr->sig_bit.red;
  184240. int sg = 8 - png_ptr->sig_bit.green;
  184241. int sb = 8 - png_ptr->sig_bit.blue;
  184242. if (sr < 0 || sr > 8)
  184243. sr = 0;
  184244. if (sg < 0 || sg > 8)
  184245. sg = 0;
  184246. if (sb < 0 || sb > 8)
  184247. sb = 0;
  184248. for (i = 0; i < istop; i++)
  184249. {
  184250. png_ptr->palette[i].red >>= sr;
  184251. png_ptr->palette[i].green >>= sg;
  184252. png_ptr->palette[i].blue >>= sb;
  184253. }
  184254. }
  184255. #endif /* PNG_READ_SHIFT_SUPPORTED */
  184256. }
  184257. #if !defined(PNG_READ_GAMMA_SUPPORTED) && !defined(PNG_READ_SHIFT_SUPPORTED) \
  184258. && !defined(PNG_READ_BACKGROUND_SUPPORTED)
  184259. if(png_ptr)
  184260. return;
  184261. #endif
  184262. }
  184263. /* Modify the info structure to reflect the transformations. The
  184264. * info should be updated so a PNG file could be written with it,
  184265. * assuming the transformations result in valid PNG data.
  184266. */
  184267. void /* PRIVATE */
  184268. png_read_transform_info(png_structp png_ptr, png_infop info_ptr)
  184269. {
  184270. png_debug(1, "in png_read_transform_info\n");
  184271. #if defined(PNG_READ_EXPAND_SUPPORTED)
  184272. if (png_ptr->transformations & PNG_EXPAND)
  184273. {
  184274. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  184275. {
  184276. if (png_ptr->num_trans && (png_ptr->transformations & PNG_EXPAND_tRNS))
  184277. info_ptr->color_type = PNG_COLOR_TYPE_RGB_ALPHA;
  184278. else
  184279. info_ptr->color_type = PNG_COLOR_TYPE_RGB;
  184280. info_ptr->bit_depth = 8;
  184281. info_ptr->num_trans = 0;
  184282. }
  184283. else
  184284. {
  184285. if (png_ptr->num_trans)
  184286. {
  184287. if (png_ptr->transformations & PNG_EXPAND_tRNS)
  184288. info_ptr->color_type |= PNG_COLOR_MASK_ALPHA;
  184289. else
  184290. info_ptr->color_type |= PNG_COLOR_MASK_COLOR;
  184291. }
  184292. if (info_ptr->bit_depth < 8)
  184293. info_ptr->bit_depth = 8;
  184294. info_ptr->num_trans = 0;
  184295. }
  184296. }
  184297. #endif
  184298. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  184299. if (png_ptr->transformations & PNG_BACKGROUND)
  184300. {
  184301. info_ptr->color_type &= ~PNG_COLOR_MASK_ALPHA;
  184302. info_ptr->num_trans = 0;
  184303. info_ptr->background = png_ptr->background;
  184304. }
  184305. #endif
  184306. #if defined(PNG_READ_GAMMA_SUPPORTED)
  184307. if (png_ptr->transformations & PNG_GAMMA)
  184308. {
  184309. #ifdef PNG_FLOATING_POINT_SUPPORTED
  184310. info_ptr->gamma = png_ptr->gamma;
  184311. #endif
  184312. #ifdef PNG_FIXED_POINT_SUPPORTED
  184313. info_ptr->int_gamma = png_ptr->int_gamma;
  184314. #endif
  184315. }
  184316. #endif
  184317. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  184318. if ((png_ptr->transformations & PNG_16_TO_8) && (info_ptr->bit_depth == 16))
  184319. info_ptr->bit_depth = 8;
  184320. #endif
  184321. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  184322. if (png_ptr->transformations & PNG_GRAY_TO_RGB)
  184323. info_ptr->color_type |= PNG_COLOR_MASK_COLOR;
  184324. #endif
  184325. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  184326. if (png_ptr->transformations & PNG_RGB_TO_GRAY)
  184327. info_ptr->color_type &= ~PNG_COLOR_MASK_COLOR;
  184328. #endif
  184329. #if defined(PNG_READ_DITHER_SUPPORTED)
  184330. if (png_ptr->transformations & PNG_DITHER)
  184331. {
  184332. if (((info_ptr->color_type == PNG_COLOR_TYPE_RGB) ||
  184333. (info_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)) &&
  184334. png_ptr->palette_lookup && info_ptr->bit_depth == 8)
  184335. {
  184336. info_ptr->color_type = PNG_COLOR_TYPE_PALETTE;
  184337. }
  184338. }
  184339. #endif
  184340. #if defined(PNG_READ_PACK_SUPPORTED)
  184341. if ((png_ptr->transformations & PNG_PACK) && (info_ptr->bit_depth < 8))
  184342. info_ptr->bit_depth = 8;
  184343. #endif
  184344. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  184345. info_ptr->channels = 1;
  184346. else if (info_ptr->color_type & PNG_COLOR_MASK_COLOR)
  184347. info_ptr->channels = 3;
  184348. else
  184349. info_ptr->channels = 1;
  184350. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  184351. if (png_ptr->flags & PNG_FLAG_STRIP_ALPHA)
  184352. info_ptr->color_type &= ~PNG_COLOR_MASK_ALPHA;
  184353. #endif
  184354. if (info_ptr->color_type & PNG_COLOR_MASK_ALPHA)
  184355. info_ptr->channels++;
  184356. #if defined(PNG_READ_FILLER_SUPPORTED)
  184357. /* STRIP_ALPHA and FILLER allowed: MASK_ALPHA bit stripped above */
  184358. if ((png_ptr->transformations & PNG_FILLER) &&
  184359. ((info_ptr->color_type == PNG_COLOR_TYPE_RGB) ||
  184360. (info_ptr->color_type == PNG_COLOR_TYPE_GRAY)))
  184361. {
  184362. info_ptr->channels++;
  184363. /* if adding a true alpha channel not just filler */
  184364. #if !defined(PNG_1_0_X)
  184365. if (png_ptr->transformations & PNG_ADD_ALPHA)
  184366. info_ptr->color_type |= PNG_COLOR_MASK_ALPHA;
  184367. #endif
  184368. }
  184369. #endif
  184370. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED) && \
  184371. defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  184372. if(png_ptr->transformations & PNG_USER_TRANSFORM)
  184373. {
  184374. if(info_ptr->bit_depth < png_ptr->user_transform_depth)
  184375. info_ptr->bit_depth = png_ptr->user_transform_depth;
  184376. if(info_ptr->channels < png_ptr->user_transform_channels)
  184377. info_ptr->channels = png_ptr->user_transform_channels;
  184378. }
  184379. #endif
  184380. info_ptr->pixel_depth = (png_byte)(info_ptr->channels *
  184381. info_ptr->bit_depth);
  184382. info_ptr->rowbytes = PNG_ROWBYTES(info_ptr->pixel_depth,info_ptr->width);
  184383. #if !defined(PNG_READ_EXPAND_SUPPORTED)
  184384. if(png_ptr)
  184385. return;
  184386. #endif
  184387. }
  184388. /* Transform the row. The order of transformations is significant,
  184389. * and is very touchy. If you add a transformation, take care to
  184390. * decide how it fits in with the other transformations here.
  184391. */
  184392. void /* PRIVATE */
  184393. png_do_read_transformations(png_structp png_ptr)
  184394. {
  184395. png_debug(1, "in png_do_read_transformations\n");
  184396. if (png_ptr->row_buf == NULL)
  184397. {
  184398. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  184399. char msg[50];
  184400. png_snprintf2(msg, 50,
  184401. "NULL row buffer for row %ld, pass %d", png_ptr->row_number,
  184402. png_ptr->pass);
  184403. png_error(png_ptr, msg);
  184404. #else
  184405. png_error(png_ptr, "NULL row buffer");
  184406. #endif
  184407. }
  184408. #ifdef PNG_WARN_UNINITIALIZED_ROW
  184409. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  184410. /* Application has failed to call either png_read_start_image()
  184411. * or png_read_update_info() after setting transforms that expand
  184412. * pixels. This check added to libpng-1.2.19 */
  184413. #if (PNG_WARN_UNINITIALIZED_ROW==1)
  184414. png_error(png_ptr, "Uninitialized row");
  184415. #else
  184416. png_warning(png_ptr, "Uninitialized row");
  184417. #endif
  184418. #endif
  184419. #if defined(PNG_READ_EXPAND_SUPPORTED)
  184420. if (png_ptr->transformations & PNG_EXPAND)
  184421. {
  184422. if (png_ptr->row_info.color_type == PNG_COLOR_TYPE_PALETTE)
  184423. {
  184424. png_do_expand_palette(&(png_ptr->row_info), png_ptr->row_buf + 1,
  184425. png_ptr->palette, png_ptr->trans, png_ptr->num_trans);
  184426. }
  184427. else
  184428. {
  184429. if (png_ptr->num_trans &&
  184430. (png_ptr->transformations & PNG_EXPAND_tRNS))
  184431. png_do_expand(&(png_ptr->row_info), png_ptr->row_buf + 1,
  184432. &(png_ptr->trans_values));
  184433. else
  184434. png_do_expand(&(png_ptr->row_info), png_ptr->row_buf + 1,
  184435. NULL);
  184436. }
  184437. }
  184438. #endif
  184439. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  184440. if (png_ptr->flags & PNG_FLAG_STRIP_ALPHA)
  184441. png_do_strip_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  184442. PNG_FLAG_FILLER_AFTER | (png_ptr->flags & PNG_FLAG_STRIP_ALPHA));
  184443. #endif
  184444. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  184445. if (png_ptr->transformations & PNG_RGB_TO_GRAY)
  184446. {
  184447. int rgb_error =
  184448. png_do_rgb_to_gray(png_ptr, &(png_ptr->row_info), png_ptr->row_buf + 1);
  184449. if(rgb_error)
  184450. {
  184451. png_ptr->rgb_to_gray_status=1;
  184452. if((png_ptr->transformations & PNG_RGB_TO_GRAY) ==
  184453. PNG_RGB_TO_GRAY_WARN)
  184454. png_warning(png_ptr, "png_do_rgb_to_gray found nongray pixel");
  184455. if((png_ptr->transformations & PNG_RGB_TO_GRAY) ==
  184456. PNG_RGB_TO_GRAY_ERR)
  184457. png_error(png_ptr, "png_do_rgb_to_gray found nongray pixel");
  184458. }
  184459. }
  184460. #endif
  184461. /*
  184462. From Andreas Dilger e-mail to png-implement, 26 March 1998:
  184463. In most cases, the "simple transparency" should be done prior to doing
  184464. gray-to-RGB, or you will have to test 3x as many bytes to check if a
  184465. pixel is transparent. You would also need to make sure that the
  184466. transparency information is upgraded to RGB.
  184467. To summarize, the current flow is:
  184468. - Gray + simple transparency -> compare 1 or 2 gray bytes and composite
  184469. with background "in place" if transparent,
  184470. convert to RGB if necessary
  184471. - Gray + alpha -> composite with gray background and remove alpha bytes,
  184472. convert to RGB if necessary
  184473. To support RGB backgrounds for gray images we need:
  184474. - Gray + simple transparency -> convert to RGB + simple transparency, compare
  184475. 3 or 6 bytes and composite with background
  184476. "in place" if transparent (3x compare/pixel
  184477. compared to doing composite with gray bkgrnd)
  184478. - Gray + alpha -> convert to RGB + alpha, composite with background and
  184479. remove alpha bytes (3x float operations/pixel
  184480. compared with composite on gray background)
  184481. Greg's change will do this. The reason it wasn't done before is for
  184482. performance, as this increases the per-pixel operations. If we would check
  184483. in advance if the background was gray or RGB, and position the gray-to-RGB
  184484. transform appropriately, then it would save a lot of work/time.
  184485. */
  184486. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  184487. /* if gray -> RGB, do so now only if background is non-gray; else do later
  184488. * for performance reasons */
  184489. if ((png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  184490. !(png_ptr->mode & PNG_BACKGROUND_IS_GRAY))
  184491. png_do_gray_to_rgb(&(png_ptr->row_info), png_ptr->row_buf + 1);
  184492. #endif
  184493. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  184494. if ((png_ptr->transformations & PNG_BACKGROUND) &&
  184495. ((png_ptr->num_trans != 0 ) ||
  184496. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA)))
  184497. png_do_background(&(png_ptr->row_info), png_ptr->row_buf + 1,
  184498. &(png_ptr->trans_values), &(png_ptr->background)
  184499. #if defined(PNG_READ_GAMMA_SUPPORTED)
  184500. , &(png_ptr->background_1),
  184501. png_ptr->gamma_table, png_ptr->gamma_from_1,
  184502. png_ptr->gamma_to_1, png_ptr->gamma_16_table,
  184503. png_ptr->gamma_16_from_1, png_ptr->gamma_16_to_1,
  184504. png_ptr->gamma_shift
  184505. #endif
  184506. );
  184507. #endif
  184508. #if defined(PNG_READ_GAMMA_SUPPORTED)
  184509. if ((png_ptr->transformations & PNG_GAMMA) &&
  184510. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  184511. !((png_ptr->transformations & PNG_BACKGROUND) &&
  184512. ((png_ptr->num_trans != 0) ||
  184513. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA))) &&
  184514. #endif
  184515. (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE))
  184516. png_do_gamma(&(png_ptr->row_info), png_ptr->row_buf + 1,
  184517. png_ptr->gamma_table, png_ptr->gamma_16_table,
  184518. png_ptr->gamma_shift);
  184519. #endif
  184520. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  184521. if (png_ptr->transformations & PNG_16_TO_8)
  184522. png_do_chop(&(png_ptr->row_info), png_ptr->row_buf + 1);
  184523. #endif
  184524. #if defined(PNG_READ_DITHER_SUPPORTED)
  184525. if (png_ptr->transformations & PNG_DITHER)
  184526. {
  184527. png_do_dither((png_row_infop)&(png_ptr->row_info), png_ptr->row_buf + 1,
  184528. png_ptr->palette_lookup, png_ptr->dither_index);
  184529. if(png_ptr->row_info.rowbytes == (png_uint_32)0)
  184530. png_error(png_ptr, "png_do_dither returned rowbytes=0");
  184531. }
  184532. #endif
  184533. #if defined(PNG_READ_INVERT_SUPPORTED)
  184534. if (png_ptr->transformations & PNG_INVERT_MONO)
  184535. png_do_invert(&(png_ptr->row_info), png_ptr->row_buf + 1);
  184536. #endif
  184537. #if defined(PNG_READ_SHIFT_SUPPORTED)
  184538. if (png_ptr->transformations & PNG_SHIFT)
  184539. png_do_unshift(&(png_ptr->row_info), png_ptr->row_buf + 1,
  184540. &(png_ptr->shift));
  184541. #endif
  184542. #if defined(PNG_READ_PACK_SUPPORTED)
  184543. if (png_ptr->transformations & PNG_PACK)
  184544. png_do_unpack(&(png_ptr->row_info), png_ptr->row_buf + 1);
  184545. #endif
  184546. #if defined(PNG_READ_BGR_SUPPORTED)
  184547. if (png_ptr->transformations & PNG_BGR)
  184548. png_do_bgr(&(png_ptr->row_info), png_ptr->row_buf + 1);
  184549. #endif
  184550. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  184551. if (png_ptr->transformations & PNG_PACKSWAP)
  184552. png_do_packswap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  184553. #endif
  184554. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  184555. /* if gray -> RGB, do so now only if we did not do so above */
  184556. if ((png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  184557. (png_ptr->mode & PNG_BACKGROUND_IS_GRAY))
  184558. png_do_gray_to_rgb(&(png_ptr->row_info), png_ptr->row_buf + 1);
  184559. #endif
  184560. #if defined(PNG_READ_FILLER_SUPPORTED)
  184561. if (png_ptr->transformations & PNG_FILLER)
  184562. png_do_read_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  184563. (png_uint_32)png_ptr->filler, png_ptr->flags);
  184564. #endif
  184565. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  184566. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  184567. png_do_read_invert_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  184568. #endif
  184569. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  184570. if (png_ptr->transformations & PNG_SWAP_ALPHA)
  184571. png_do_read_swap_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  184572. #endif
  184573. #if defined(PNG_READ_SWAP_SUPPORTED)
  184574. if (png_ptr->transformations & PNG_SWAP_BYTES)
  184575. png_do_swap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  184576. #endif
  184577. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  184578. if (png_ptr->transformations & PNG_USER_TRANSFORM)
  184579. {
  184580. if(png_ptr->read_user_transform_fn != NULL)
  184581. (*(png_ptr->read_user_transform_fn)) /* user read transform function */
  184582. (png_ptr, /* png_ptr */
  184583. &(png_ptr->row_info), /* row_info: */
  184584. /* png_uint_32 width; width of row */
  184585. /* png_uint_32 rowbytes; number of bytes in row */
  184586. /* png_byte color_type; color type of pixels */
  184587. /* png_byte bit_depth; bit depth of samples */
  184588. /* png_byte channels; number of channels (1-4) */
  184589. /* png_byte pixel_depth; bits per pixel (depth*channels) */
  184590. png_ptr->row_buf + 1); /* start of pixel data for row */
  184591. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  184592. if(png_ptr->user_transform_depth)
  184593. png_ptr->row_info.bit_depth = png_ptr->user_transform_depth;
  184594. if(png_ptr->user_transform_channels)
  184595. png_ptr->row_info.channels = png_ptr->user_transform_channels;
  184596. #endif
  184597. png_ptr->row_info.pixel_depth = (png_byte)(png_ptr->row_info.bit_depth *
  184598. png_ptr->row_info.channels);
  184599. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  184600. png_ptr->row_info.width);
  184601. }
  184602. #endif
  184603. }
  184604. #if defined(PNG_READ_PACK_SUPPORTED)
  184605. /* Unpack pixels of 1, 2, or 4 bits per pixel into 1 byte per pixel,
  184606. * without changing the actual values. Thus, if you had a row with
  184607. * a bit depth of 1, you would end up with bytes that only contained
  184608. * the numbers 0 or 1. If you would rather they contain 0 and 255, use
  184609. * png_do_shift() after this.
  184610. */
  184611. void /* PRIVATE */
  184612. png_do_unpack(png_row_infop row_info, png_bytep row)
  184613. {
  184614. png_debug(1, "in png_do_unpack\n");
  184615. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  184616. if (row != NULL && row_info != NULL && row_info->bit_depth < 8)
  184617. #else
  184618. if (row_info->bit_depth < 8)
  184619. #endif
  184620. {
  184621. png_uint_32 i;
  184622. png_uint_32 row_width=row_info->width;
  184623. switch (row_info->bit_depth)
  184624. {
  184625. case 1:
  184626. {
  184627. png_bytep sp = row + (png_size_t)((row_width - 1) >> 3);
  184628. png_bytep dp = row + (png_size_t)row_width - 1;
  184629. png_uint_32 shift = 7 - (int)((row_width + 7) & 0x07);
  184630. for (i = 0; i < row_width; i++)
  184631. {
  184632. *dp = (png_byte)((*sp >> shift) & 0x01);
  184633. if (shift == 7)
  184634. {
  184635. shift = 0;
  184636. sp--;
  184637. }
  184638. else
  184639. shift++;
  184640. dp--;
  184641. }
  184642. break;
  184643. }
  184644. case 2:
  184645. {
  184646. png_bytep sp = row + (png_size_t)((row_width - 1) >> 2);
  184647. png_bytep dp = row + (png_size_t)row_width - 1;
  184648. png_uint_32 shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  184649. for (i = 0; i < row_width; i++)
  184650. {
  184651. *dp = (png_byte)((*sp >> shift) & 0x03);
  184652. if (shift == 6)
  184653. {
  184654. shift = 0;
  184655. sp--;
  184656. }
  184657. else
  184658. shift += 2;
  184659. dp--;
  184660. }
  184661. break;
  184662. }
  184663. case 4:
  184664. {
  184665. png_bytep sp = row + (png_size_t)((row_width - 1) >> 1);
  184666. png_bytep dp = row + (png_size_t)row_width - 1;
  184667. png_uint_32 shift = (int)((1 - ((row_width + 1) & 0x01)) << 2);
  184668. for (i = 0; i < row_width; i++)
  184669. {
  184670. *dp = (png_byte)((*sp >> shift) & 0x0f);
  184671. if (shift == 4)
  184672. {
  184673. shift = 0;
  184674. sp--;
  184675. }
  184676. else
  184677. shift = 4;
  184678. dp--;
  184679. }
  184680. break;
  184681. }
  184682. }
  184683. row_info->bit_depth = 8;
  184684. row_info->pixel_depth = (png_byte)(8 * row_info->channels);
  184685. row_info->rowbytes = row_width * row_info->channels;
  184686. }
  184687. }
  184688. #endif
  184689. #if defined(PNG_READ_SHIFT_SUPPORTED)
  184690. /* Reverse the effects of png_do_shift. This routine merely shifts the
  184691. * pixels back to their significant bits values. Thus, if you have
  184692. * a row of bit depth 8, but only 5 are significant, this will shift
  184693. * the values back to 0 through 31.
  184694. */
  184695. void /* PRIVATE */
  184696. png_do_unshift(png_row_infop row_info, png_bytep row, png_color_8p sig_bits)
  184697. {
  184698. png_debug(1, "in png_do_unshift\n");
  184699. if (
  184700. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  184701. row != NULL && row_info != NULL && sig_bits != NULL &&
  184702. #endif
  184703. row_info->color_type != PNG_COLOR_TYPE_PALETTE)
  184704. {
  184705. int shift[4];
  184706. int channels = 0;
  184707. int c;
  184708. png_uint_16 value = 0;
  184709. png_uint_32 row_width = row_info->width;
  184710. if (row_info->color_type & PNG_COLOR_MASK_COLOR)
  184711. {
  184712. shift[channels++] = row_info->bit_depth - sig_bits->red;
  184713. shift[channels++] = row_info->bit_depth - sig_bits->green;
  184714. shift[channels++] = row_info->bit_depth - sig_bits->blue;
  184715. }
  184716. else
  184717. {
  184718. shift[channels++] = row_info->bit_depth - sig_bits->gray;
  184719. }
  184720. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  184721. {
  184722. shift[channels++] = row_info->bit_depth - sig_bits->alpha;
  184723. }
  184724. for (c = 0; c < channels; c++)
  184725. {
  184726. if (shift[c] <= 0)
  184727. shift[c] = 0;
  184728. else
  184729. value = 1;
  184730. }
  184731. if (!value)
  184732. return;
  184733. switch (row_info->bit_depth)
  184734. {
  184735. case 2:
  184736. {
  184737. png_bytep bp;
  184738. png_uint_32 i;
  184739. png_uint_32 istop = row_info->rowbytes;
  184740. for (bp = row, i = 0; i < istop; i++)
  184741. {
  184742. *bp >>= 1;
  184743. *bp++ &= 0x55;
  184744. }
  184745. break;
  184746. }
  184747. case 4:
  184748. {
  184749. png_bytep bp = row;
  184750. png_uint_32 i;
  184751. png_uint_32 istop = row_info->rowbytes;
  184752. png_byte mask = (png_byte)((((int)0xf0 >> shift[0]) & (int)0xf0) |
  184753. (png_byte)((int)0xf >> shift[0]));
  184754. for (i = 0; i < istop; i++)
  184755. {
  184756. *bp >>= shift[0];
  184757. *bp++ &= mask;
  184758. }
  184759. break;
  184760. }
  184761. case 8:
  184762. {
  184763. png_bytep bp = row;
  184764. png_uint_32 i;
  184765. png_uint_32 istop = row_width * channels;
  184766. for (i = 0; i < istop; i++)
  184767. {
  184768. *bp++ >>= shift[i%channels];
  184769. }
  184770. break;
  184771. }
  184772. case 16:
  184773. {
  184774. png_bytep bp = row;
  184775. png_uint_32 i;
  184776. png_uint_32 istop = channels * row_width;
  184777. for (i = 0; i < istop; i++)
  184778. {
  184779. value = (png_uint_16)((*bp << 8) + *(bp + 1));
  184780. value >>= shift[i%channels];
  184781. *bp++ = (png_byte)(value >> 8);
  184782. *bp++ = (png_byte)(value & 0xff);
  184783. }
  184784. break;
  184785. }
  184786. }
  184787. }
  184788. }
  184789. #endif
  184790. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  184791. /* chop rows of bit depth 16 down to 8 */
  184792. void /* PRIVATE */
  184793. png_do_chop(png_row_infop row_info, png_bytep row)
  184794. {
  184795. png_debug(1, "in png_do_chop\n");
  184796. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  184797. if (row != NULL && row_info != NULL && row_info->bit_depth == 16)
  184798. #else
  184799. if (row_info->bit_depth == 16)
  184800. #endif
  184801. {
  184802. png_bytep sp = row;
  184803. png_bytep dp = row;
  184804. png_uint_32 i;
  184805. png_uint_32 istop = row_info->width * row_info->channels;
  184806. for (i = 0; i<istop; i++, sp += 2, dp++)
  184807. {
  184808. #if defined(PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED)
  184809. /* This does a more accurate scaling of the 16-bit color
  184810. * value, rather than a simple low-byte truncation.
  184811. *
  184812. * What the ideal calculation should be:
  184813. * *dp = (((((png_uint_32)(*sp) << 8) |
  184814. * (png_uint_32)(*(sp + 1))) * 255 + 127) / (png_uint_32)65535L;
  184815. *
  184816. * GRR: no, I think this is what it really should be:
  184817. * *dp = (((((png_uint_32)(*sp) << 8) |
  184818. * (png_uint_32)(*(sp + 1))) + 128L) / (png_uint_32)257L;
  184819. *
  184820. * GRR: here's the exact calculation with shifts:
  184821. * temp = (((png_uint_32)(*sp) << 8) | (png_uint_32)(*(sp + 1))) + 128L;
  184822. * *dp = (temp - (temp >> 8)) >> 8;
  184823. *
  184824. * Approximate calculation with shift/add instead of multiply/divide:
  184825. * *dp = ((((png_uint_32)(*sp) << 8) |
  184826. * (png_uint_32)((int)(*(sp + 1)) - *sp)) + 128) >> 8;
  184827. *
  184828. * What we actually do to avoid extra shifting and conversion:
  184829. */
  184830. *dp = *sp + ((((int)(*(sp + 1)) - *sp) > 128) ? 1 : 0);
  184831. #else
  184832. /* Simply discard the low order byte */
  184833. *dp = *sp;
  184834. #endif
  184835. }
  184836. row_info->bit_depth = 8;
  184837. row_info->pixel_depth = (png_byte)(8 * row_info->channels);
  184838. row_info->rowbytes = row_info->width * row_info->channels;
  184839. }
  184840. }
  184841. #endif
  184842. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  184843. void /* PRIVATE */
  184844. png_do_read_swap_alpha(png_row_infop row_info, png_bytep row)
  184845. {
  184846. png_debug(1, "in png_do_read_swap_alpha\n");
  184847. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  184848. if (row != NULL && row_info != NULL)
  184849. #endif
  184850. {
  184851. png_uint_32 row_width = row_info->width;
  184852. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  184853. {
  184854. /* This converts from RGBA to ARGB */
  184855. if (row_info->bit_depth == 8)
  184856. {
  184857. png_bytep sp = row + row_info->rowbytes;
  184858. png_bytep dp = sp;
  184859. png_byte save;
  184860. png_uint_32 i;
  184861. for (i = 0; i < row_width; i++)
  184862. {
  184863. save = *(--sp);
  184864. *(--dp) = *(--sp);
  184865. *(--dp) = *(--sp);
  184866. *(--dp) = *(--sp);
  184867. *(--dp) = save;
  184868. }
  184869. }
  184870. /* This converts from RRGGBBAA to AARRGGBB */
  184871. else
  184872. {
  184873. png_bytep sp = row + row_info->rowbytes;
  184874. png_bytep dp = sp;
  184875. png_byte save[2];
  184876. png_uint_32 i;
  184877. for (i = 0; i < row_width; i++)
  184878. {
  184879. save[0] = *(--sp);
  184880. save[1] = *(--sp);
  184881. *(--dp) = *(--sp);
  184882. *(--dp) = *(--sp);
  184883. *(--dp) = *(--sp);
  184884. *(--dp) = *(--sp);
  184885. *(--dp) = *(--sp);
  184886. *(--dp) = *(--sp);
  184887. *(--dp) = save[0];
  184888. *(--dp) = save[1];
  184889. }
  184890. }
  184891. }
  184892. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  184893. {
  184894. /* This converts from GA to AG */
  184895. if (row_info->bit_depth == 8)
  184896. {
  184897. png_bytep sp = row + row_info->rowbytes;
  184898. png_bytep dp = sp;
  184899. png_byte save;
  184900. png_uint_32 i;
  184901. for (i = 0; i < row_width; i++)
  184902. {
  184903. save = *(--sp);
  184904. *(--dp) = *(--sp);
  184905. *(--dp) = save;
  184906. }
  184907. }
  184908. /* This converts from GGAA to AAGG */
  184909. else
  184910. {
  184911. png_bytep sp = row + row_info->rowbytes;
  184912. png_bytep dp = sp;
  184913. png_byte save[2];
  184914. png_uint_32 i;
  184915. for (i = 0; i < row_width; i++)
  184916. {
  184917. save[0] = *(--sp);
  184918. save[1] = *(--sp);
  184919. *(--dp) = *(--sp);
  184920. *(--dp) = *(--sp);
  184921. *(--dp) = save[0];
  184922. *(--dp) = save[1];
  184923. }
  184924. }
  184925. }
  184926. }
  184927. }
  184928. #endif
  184929. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  184930. void /* PRIVATE */
  184931. png_do_read_invert_alpha(png_row_infop row_info, png_bytep row)
  184932. {
  184933. png_debug(1, "in png_do_read_invert_alpha\n");
  184934. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  184935. if (row != NULL && row_info != NULL)
  184936. #endif
  184937. {
  184938. png_uint_32 row_width = row_info->width;
  184939. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  184940. {
  184941. /* This inverts the alpha channel in RGBA */
  184942. if (row_info->bit_depth == 8)
  184943. {
  184944. png_bytep sp = row + row_info->rowbytes;
  184945. png_bytep dp = sp;
  184946. png_uint_32 i;
  184947. for (i = 0; i < row_width; i++)
  184948. {
  184949. *(--dp) = (png_byte)(255 - *(--sp));
  184950. /* This does nothing:
  184951. *(--dp) = *(--sp);
  184952. *(--dp) = *(--sp);
  184953. *(--dp) = *(--sp);
  184954. We can replace it with:
  184955. */
  184956. sp-=3;
  184957. dp=sp;
  184958. }
  184959. }
  184960. /* This inverts the alpha channel in RRGGBBAA */
  184961. else
  184962. {
  184963. png_bytep sp = row + row_info->rowbytes;
  184964. png_bytep dp = sp;
  184965. png_uint_32 i;
  184966. for (i = 0; i < row_width; i++)
  184967. {
  184968. *(--dp) = (png_byte)(255 - *(--sp));
  184969. *(--dp) = (png_byte)(255 - *(--sp));
  184970. /* This does nothing:
  184971. *(--dp) = *(--sp);
  184972. *(--dp) = *(--sp);
  184973. *(--dp) = *(--sp);
  184974. *(--dp) = *(--sp);
  184975. *(--dp) = *(--sp);
  184976. *(--dp) = *(--sp);
  184977. We can replace it with:
  184978. */
  184979. sp-=6;
  184980. dp=sp;
  184981. }
  184982. }
  184983. }
  184984. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  184985. {
  184986. /* This inverts the alpha channel in GA */
  184987. if (row_info->bit_depth == 8)
  184988. {
  184989. png_bytep sp = row + row_info->rowbytes;
  184990. png_bytep dp = sp;
  184991. png_uint_32 i;
  184992. for (i = 0; i < row_width; i++)
  184993. {
  184994. *(--dp) = (png_byte)(255 - *(--sp));
  184995. *(--dp) = *(--sp);
  184996. }
  184997. }
  184998. /* This inverts the alpha channel in GGAA */
  184999. else
  185000. {
  185001. png_bytep sp = row + row_info->rowbytes;
  185002. png_bytep dp = sp;
  185003. png_uint_32 i;
  185004. for (i = 0; i < row_width; i++)
  185005. {
  185006. *(--dp) = (png_byte)(255 - *(--sp));
  185007. *(--dp) = (png_byte)(255 - *(--sp));
  185008. /*
  185009. *(--dp) = *(--sp);
  185010. *(--dp) = *(--sp);
  185011. */
  185012. sp-=2;
  185013. dp=sp;
  185014. }
  185015. }
  185016. }
  185017. }
  185018. }
  185019. #endif
  185020. #if defined(PNG_READ_FILLER_SUPPORTED)
  185021. /* Add filler channel if we have RGB color */
  185022. void /* PRIVATE */
  185023. png_do_read_filler(png_row_infop row_info, png_bytep row,
  185024. png_uint_32 filler, png_uint_32 flags)
  185025. {
  185026. png_uint_32 i;
  185027. png_uint_32 row_width = row_info->width;
  185028. png_byte hi_filler = (png_byte)((filler>>8) & 0xff);
  185029. png_byte lo_filler = (png_byte)(filler & 0xff);
  185030. png_debug(1, "in png_do_read_filler\n");
  185031. if (
  185032. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  185033. row != NULL && row_info != NULL &&
  185034. #endif
  185035. row_info->color_type == PNG_COLOR_TYPE_GRAY)
  185036. {
  185037. if(row_info->bit_depth == 8)
  185038. {
  185039. /* This changes the data from G to GX */
  185040. if (flags & PNG_FLAG_FILLER_AFTER)
  185041. {
  185042. png_bytep sp = row + (png_size_t)row_width;
  185043. png_bytep dp = sp + (png_size_t)row_width;
  185044. for (i = 1; i < row_width; i++)
  185045. {
  185046. *(--dp) = lo_filler;
  185047. *(--dp) = *(--sp);
  185048. }
  185049. *(--dp) = lo_filler;
  185050. row_info->channels = 2;
  185051. row_info->pixel_depth = 16;
  185052. row_info->rowbytes = row_width * 2;
  185053. }
  185054. /* This changes the data from G to XG */
  185055. else
  185056. {
  185057. png_bytep sp = row + (png_size_t)row_width;
  185058. png_bytep dp = sp + (png_size_t)row_width;
  185059. for (i = 0; i < row_width; i++)
  185060. {
  185061. *(--dp) = *(--sp);
  185062. *(--dp) = lo_filler;
  185063. }
  185064. row_info->channels = 2;
  185065. row_info->pixel_depth = 16;
  185066. row_info->rowbytes = row_width * 2;
  185067. }
  185068. }
  185069. else if(row_info->bit_depth == 16)
  185070. {
  185071. /* This changes the data from GG to GGXX */
  185072. if (flags & PNG_FLAG_FILLER_AFTER)
  185073. {
  185074. png_bytep sp = row + (png_size_t)row_width * 2;
  185075. png_bytep dp = sp + (png_size_t)row_width * 2;
  185076. for (i = 1; i < row_width; i++)
  185077. {
  185078. *(--dp) = hi_filler;
  185079. *(--dp) = lo_filler;
  185080. *(--dp) = *(--sp);
  185081. *(--dp) = *(--sp);
  185082. }
  185083. *(--dp) = hi_filler;
  185084. *(--dp) = lo_filler;
  185085. row_info->channels = 2;
  185086. row_info->pixel_depth = 32;
  185087. row_info->rowbytes = row_width * 4;
  185088. }
  185089. /* This changes the data from GG to XXGG */
  185090. else
  185091. {
  185092. png_bytep sp = row + (png_size_t)row_width * 2;
  185093. png_bytep dp = sp + (png_size_t)row_width * 2;
  185094. for (i = 0; i < row_width; i++)
  185095. {
  185096. *(--dp) = *(--sp);
  185097. *(--dp) = *(--sp);
  185098. *(--dp) = hi_filler;
  185099. *(--dp) = lo_filler;
  185100. }
  185101. row_info->channels = 2;
  185102. row_info->pixel_depth = 32;
  185103. row_info->rowbytes = row_width * 4;
  185104. }
  185105. }
  185106. } /* COLOR_TYPE == GRAY */
  185107. else if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  185108. {
  185109. if(row_info->bit_depth == 8)
  185110. {
  185111. /* This changes the data from RGB to RGBX */
  185112. if (flags & PNG_FLAG_FILLER_AFTER)
  185113. {
  185114. png_bytep sp = row + (png_size_t)row_width * 3;
  185115. png_bytep dp = sp + (png_size_t)row_width;
  185116. for (i = 1; i < row_width; i++)
  185117. {
  185118. *(--dp) = lo_filler;
  185119. *(--dp) = *(--sp);
  185120. *(--dp) = *(--sp);
  185121. *(--dp) = *(--sp);
  185122. }
  185123. *(--dp) = lo_filler;
  185124. row_info->channels = 4;
  185125. row_info->pixel_depth = 32;
  185126. row_info->rowbytes = row_width * 4;
  185127. }
  185128. /* This changes the data from RGB to XRGB */
  185129. else
  185130. {
  185131. png_bytep sp = row + (png_size_t)row_width * 3;
  185132. png_bytep dp = sp + (png_size_t)row_width;
  185133. for (i = 0; i < row_width; i++)
  185134. {
  185135. *(--dp) = *(--sp);
  185136. *(--dp) = *(--sp);
  185137. *(--dp) = *(--sp);
  185138. *(--dp) = lo_filler;
  185139. }
  185140. row_info->channels = 4;
  185141. row_info->pixel_depth = 32;
  185142. row_info->rowbytes = row_width * 4;
  185143. }
  185144. }
  185145. else if(row_info->bit_depth == 16)
  185146. {
  185147. /* This changes the data from RRGGBB to RRGGBBXX */
  185148. if (flags & PNG_FLAG_FILLER_AFTER)
  185149. {
  185150. png_bytep sp = row + (png_size_t)row_width * 6;
  185151. png_bytep dp = sp + (png_size_t)row_width * 2;
  185152. for (i = 1; i < row_width; i++)
  185153. {
  185154. *(--dp) = hi_filler;
  185155. *(--dp) = lo_filler;
  185156. *(--dp) = *(--sp);
  185157. *(--dp) = *(--sp);
  185158. *(--dp) = *(--sp);
  185159. *(--dp) = *(--sp);
  185160. *(--dp) = *(--sp);
  185161. *(--dp) = *(--sp);
  185162. }
  185163. *(--dp) = hi_filler;
  185164. *(--dp) = lo_filler;
  185165. row_info->channels = 4;
  185166. row_info->pixel_depth = 64;
  185167. row_info->rowbytes = row_width * 8;
  185168. }
  185169. /* This changes the data from RRGGBB to XXRRGGBB */
  185170. else
  185171. {
  185172. png_bytep sp = row + (png_size_t)row_width * 6;
  185173. png_bytep dp = sp + (png_size_t)row_width * 2;
  185174. for (i = 0; i < row_width; i++)
  185175. {
  185176. *(--dp) = *(--sp);
  185177. *(--dp) = *(--sp);
  185178. *(--dp) = *(--sp);
  185179. *(--dp) = *(--sp);
  185180. *(--dp) = *(--sp);
  185181. *(--dp) = *(--sp);
  185182. *(--dp) = hi_filler;
  185183. *(--dp) = lo_filler;
  185184. }
  185185. row_info->channels = 4;
  185186. row_info->pixel_depth = 64;
  185187. row_info->rowbytes = row_width * 8;
  185188. }
  185189. }
  185190. } /* COLOR_TYPE == RGB */
  185191. }
  185192. #endif
  185193. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  185194. /* expand grayscale files to RGB, with or without alpha */
  185195. void /* PRIVATE */
  185196. png_do_gray_to_rgb(png_row_infop row_info, png_bytep row)
  185197. {
  185198. png_uint_32 i;
  185199. png_uint_32 row_width = row_info->width;
  185200. png_debug(1, "in png_do_gray_to_rgb\n");
  185201. if (row_info->bit_depth >= 8 &&
  185202. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  185203. row != NULL && row_info != NULL &&
  185204. #endif
  185205. !(row_info->color_type & PNG_COLOR_MASK_COLOR))
  185206. {
  185207. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  185208. {
  185209. if (row_info->bit_depth == 8)
  185210. {
  185211. png_bytep sp = row + (png_size_t)row_width - 1;
  185212. png_bytep dp = sp + (png_size_t)row_width * 2;
  185213. for (i = 0; i < row_width; i++)
  185214. {
  185215. *(dp--) = *sp;
  185216. *(dp--) = *sp;
  185217. *(dp--) = *(sp--);
  185218. }
  185219. }
  185220. else
  185221. {
  185222. png_bytep sp = row + (png_size_t)row_width * 2 - 1;
  185223. png_bytep dp = sp + (png_size_t)row_width * 4;
  185224. for (i = 0; i < row_width; i++)
  185225. {
  185226. *(dp--) = *sp;
  185227. *(dp--) = *(sp - 1);
  185228. *(dp--) = *sp;
  185229. *(dp--) = *(sp - 1);
  185230. *(dp--) = *(sp--);
  185231. *(dp--) = *(sp--);
  185232. }
  185233. }
  185234. }
  185235. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  185236. {
  185237. if (row_info->bit_depth == 8)
  185238. {
  185239. png_bytep sp = row + (png_size_t)row_width * 2 - 1;
  185240. png_bytep dp = sp + (png_size_t)row_width * 2;
  185241. for (i = 0; i < row_width; i++)
  185242. {
  185243. *(dp--) = *(sp--);
  185244. *(dp--) = *sp;
  185245. *(dp--) = *sp;
  185246. *(dp--) = *(sp--);
  185247. }
  185248. }
  185249. else
  185250. {
  185251. png_bytep sp = row + (png_size_t)row_width * 4 - 1;
  185252. png_bytep dp = sp + (png_size_t)row_width * 4;
  185253. for (i = 0; i < row_width; i++)
  185254. {
  185255. *(dp--) = *(sp--);
  185256. *(dp--) = *(sp--);
  185257. *(dp--) = *sp;
  185258. *(dp--) = *(sp - 1);
  185259. *(dp--) = *sp;
  185260. *(dp--) = *(sp - 1);
  185261. *(dp--) = *(sp--);
  185262. *(dp--) = *(sp--);
  185263. }
  185264. }
  185265. }
  185266. row_info->channels += (png_byte)2;
  185267. row_info->color_type |= PNG_COLOR_MASK_COLOR;
  185268. row_info->pixel_depth = (png_byte)(row_info->channels *
  185269. row_info->bit_depth);
  185270. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  185271. }
  185272. }
  185273. #endif
  185274. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  185275. /* reduce RGB files to grayscale, with or without alpha
  185276. * using the equation given in Poynton's ColorFAQ at
  185277. * <http://www.inforamp.net/~poynton/>
  185278. * Copyright (c) 1998-01-04 Charles Poynton poynton at inforamp.net
  185279. *
  185280. * Y = 0.212671 * R + 0.715160 * G + 0.072169 * B
  185281. *
  185282. * We approximate this with
  185283. *
  185284. * Y = 0.21268 * R + 0.7151 * G + 0.07217 * B
  185285. *
  185286. * which can be expressed with integers as
  185287. *
  185288. * Y = (6969 * R + 23434 * G + 2365 * B)/32768
  185289. *
  185290. * The calculation is to be done in a linear colorspace.
  185291. *
  185292. * Other integer coefficents can be used via png_set_rgb_to_gray().
  185293. */
  185294. int /* PRIVATE */
  185295. png_do_rgb_to_gray(png_structp png_ptr, png_row_infop row_info, png_bytep row)
  185296. {
  185297. png_uint_32 i;
  185298. png_uint_32 row_width = row_info->width;
  185299. int rgb_error = 0;
  185300. png_debug(1, "in png_do_rgb_to_gray\n");
  185301. if (
  185302. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  185303. row != NULL && row_info != NULL &&
  185304. #endif
  185305. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  185306. {
  185307. png_uint_32 rc = png_ptr->rgb_to_gray_red_coeff;
  185308. png_uint_32 gc = png_ptr->rgb_to_gray_green_coeff;
  185309. png_uint_32 bc = png_ptr->rgb_to_gray_blue_coeff;
  185310. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  185311. {
  185312. if (row_info->bit_depth == 8)
  185313. {
  185314. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  185315. if (png_ptr->gamma_from_1 != NULL && png_ptr->gamma_to_1 != NULL)
  185316. {
  185317. png_bytep sp = row;
  185318. png_bytep dp = row;
  185319. for (i = 0; i < row_width; i++)
  185320. {
  185321. png_byte red = png_ptr->gamma_to_1[*(sp++)];
  185322. png_byte green = png_ptr->gamma_to_1[*(sp++)];
  185323. png_byte blue = png_ptr->gamma_to_1[*(sp++)];
  185324. if(red != green || red != blue)
  185325. {
  185326. rgb_error |= 1;
  185327. *(dp++) = png_ptr->gamma_from_1[
  185328. (rc*red+gc*green+bc*blue)>>15];
  185329. }
  185330. else
  185331. *(dp++) = *(sp-1);
  185332. }
  185333. }
  185334. else
  185335. #endif
  185336. {
  185337. png_bytep sp = row;
  185338. png_bytep dp = row;
  185339. for (i = 0; i < row_width; i++)
  185340. {
  185341. png_byte red = *(sp++);
  185342. png_byte green = *(sp++);
  185343. png_byte blue = *(sp++);
  185344. if(red != green || red != blue)
  185345. {
  185346. rgb_error |= 1;
  185347. *(dp++) = (png_byte)((rc*red+gc*green+bc*blue)>>15);
  185348. }
  185349. else
  185350. *(dp++) = *(sp-1);
  185351. }
  185352. }
  185353. }
  185354. else /* RGB bit_depth == 16 */
  185355. {
  185356. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  185357. if (png_ptr->gamma_16_to_1 != NULL &&
  185358. png_ptr->gamma_16_from_1 != NULL)
  185359. {
  185360. png_bytep sp = row;
  185361. png_bytep dp = row;
  185362. for (i = 0; i < row_width; i++)
  185363. {
  185364. png_uint_16 red, green, blue, w;
  185365. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  185366. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  185367. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  185368. if(red == green && red == blue)
  185369. w = red;
  185370. else
  185371. {
  185372. png_uint_16 red_1 = png_ptr->gamma_16_to_1[(red&0xff) >>
  185373. png_ptr->gamma_shift][red>>8];
  185374. png_uint_16 green_1 = png_ptr->gamma_16_to_1[(green&0xff) >>
  185375. png_ptr->gamma_shift][green>>8];
  185376. png_uint_16 blue_1 = png_ptr->gamma_16_to_1[(blue&0xff) >>
  185377. png_ptr->gamma_shift][blue>>8];
  185378. png_uint_16 gray16 = (png_uint_16)((rc*red_1 + gc*green_1
  185379. + bc*blue_1)>>15);
  185380. w = png_ptr->gamma_16_from_1[(gray16&0xff) >>
  185381. png_ptr->gamma_shift][gray16 >> 8];
  185382. rgb_error |= 1;
  185383. }
  185384. *(dp++) = (png_byte)((w>>8) & 0xff);
  185385. *(dp++) = (png_byte)(w & 0xff);
  185386. }
  185387. }
  185388. else
  185389. #endif
  185390. {
  185391. png_bytep sp = row;
  185392. png_bytep dp = row;
  185393. for (i = 0; i < row_width; i++)
  185394. {
  185395. png_uint_16 red, green, blue, gray16;
  185396. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  185397. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  185398. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  185399. if(red != green || red != blue)
  185400. rgb_error |= 1;
  185401. gray16 = (png_uint_16)((rc*red + gc*green + bc*blue)>>15);
  185402. *(dp++) = (png_byte)((gray16>>8) & 0xff);
  185403. *(dp++) = (png_byte)(gray16 & 0xff);
  185404. }
  185405. }
  185406. }
  185407. }
  185408. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  185409. {
  185410. if (row_info->bit_depth == 8)
  185411. {
  185412. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  185413. if (png_ptr->gamma_from_1 != NULL && png_ptr->gamma_to_1 != NULL)
  185414. {
  185415. png_bytep sp = row;
  185416. png_bytep dp = row;
  185417. for (i = 0; i < row_width; i++)
  185418. {
  185419. png_byte red = png_ptr->gamma_to_1[*(sp++)];
  185420. png_byte green = png_ptr->gamma_to_1[*(sp++)];
  185421. png_byte blue = png_ptr->gamma_to_1[*(sp++)];
  185422. if(red != green || red != blue)
  185423. rgb_error |= 1;
  185424. *(dp++) = png_ptr->gamma_from_1
  185425. [(rc*red + gc*green + bc*blue)>>15];
  185426. *(dp++) = *(sp++); /* alpha */
  185427. }
  185428. }
  185429. else
  185430. #endif
  185431. {
  185432. png_bytep sp = row;
  185433. png_bytep dp = row;
  185434. for (i = 0; i < row_width; i++)
  185435. {
  185436. png_byte red = *(sp++);
  185437. png_byte green = *(sp++);
  185438. png_byte blue = *(sp++);
  185439. if(red != green || red != blue)
  185440. rgb_error |= 1;
  185441. *(dp++) = (png_byte)((rc*red + gc*green + bc*blue)>>15);
  185442. *(dp++) = *(sp++); /* alpha */
  185443. }
  185444. }
  185445. }
  185446. else /* RGBA bit_depth == 16 */
  185447. {
  185448. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  185449. if (png_ptr->gamma_16_to_1 != NULL &&
  185450. png_ptr->gamma_16_from_1 != NULL)
  185451. {
  185452. png_bytep sp = row;
  185453. png_bytep dp = row;
  185454. for (i = 0; i < row_width; i++)
  185455. {
  185456. png_uint_16 red, green, blue, w;
  185457. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  185458. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  185459. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  185460. if(red == green && red == blue)
  185461. w = red;
  185462. else
  185463. {
  185464. png_uint_16 red_1 = png_ptr->gamma_16_to_1[(red&0xff) >>
  185465. png_ptr->gamma_shift][red>>8];
  185466. png_uint_16 green_1 = png_ptr->gamma_16_to_1[(green&0xff) >>
  185467. png_ptr->gamma_shift][green>>8];
  185468. png_uint_16 blue_1 = png_ptr->gamma_16_to_1[(blue&0xff) >>
  185469. png_ptr->gamma_shift][blue>>8];
  185470. png_uint_16 gray16 = (png_uint_16)((rc * red_1
  185471. + gc * green_1 + bc * blue_1)>>15);
  185472. w = png_ptr->gamma_16_from_1[(gray16&0xff) >>
  185473. png_ptr->gamma_shift][gray16 >> 8];
  185474. rgb_error |= 1;
  185475. }
  185476. *(dp++) = (png_byte)((w>>8) & 0xff);
  185477. *(dp++) = (png_byte)(w & 0xff);
  185478. *(dp++) = *(sp++); /* alpha */
  185479. *(dp++) = *(sp++);
  185480. }
  185481. }
  185482. else
  185483. #endif
  185484. {
  185485. png_bytep sp = row;
  185486. png_bytep dp = row;
  185487. for (i = 0; i < row_width; i++)
  185488. {
  185489. png_uint_16 red, green, blue, gray16;
  185490. red = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  185491. green = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  185492. blue = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  185493. if(red != green || red != blue)
  185494. rgb_error |= 1;
  185495. gray16 = (png_uint_16)((rc*red + gc*green + bc*blue)>>15);
  185496. *(dp++) = (png_byte)((gray16>>8) & 0xff);
  185497. *(dp++) = (png_byte)(gray16 & 0xff);
  185498. *(dp++) = *(sp++); /* alpha */
  185499. *(dp++) = *(sp++);
  185500. }
  185501. }
  185502. }
  185503. }
  185504. row_info->channels -= (png_byte)2;
  185505. row_info->color_type &= ~PNG_COLOR_MASK_COLOR;
  185506. row_info->pixel_depth = (png_byte)(row_info->channels *
  185507. row_info->bit_depth);
  185508. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  185509. }
  185510. return rgb_error;
  185511. }
  185512. #endif
  185513. /* Build a grayscale palette. Palette is assumed to be 1 << bit_depth
  185514. * large of png_color. This lets grayscale images be treated as
  185515. * paletted. Most useful for gamma correction and simplification
  185516. * of code.
  185517. */
  185518. void PNGAPI
  185519. png_build_grayscale_palette(int bit_depth, png_colorp palette)
  185520. {
  185521. int num_palette;
  185522. int color_inc;
  185523. int i;
  185524. int v;
  185525. png_debug(1, "in png_do_build_grayscale_palette\n");
  185526. if (palette == NULL)
  185527. return;
  185528. switch (bit_depth)
  185529. {
  185530. case 1:
  185531. num_palette = 2;
  185532. color_inc = 0xff;
  185533. break;
  185534. case 2:
  185535. num_palette = 4;
  185536. color_inc = 0x55;
  185537. break;
  185538. case 4:
  185539. num_palette = 16;
  185540. color_inc = 0x11;
  185541. break;
  185542. case 8:
  185543. num_palette = 256;
  185544. color_inc = 1;
  185545. break;
  185546. default:
  185547. num_palette = 0;
  185548. color_inc = 0;
  185549. break;
  185550. }
  185551. for (i = 0, v = 0; i < num_palette; i++, v += color_inc)
  185552. {
  185553. palette[i].red = (png_byte)v;
  185554. palette[i].green = (png_byte)v;
  185555. palette[i].blue = (png_byte)v;
  185556. }
  185557. }
  185558. /* This function is currently unused. Do we really need it? */
  185559. #if defined(PNG_READ_DITHER_SUPPORTED) && defined(PNG_CORRECT_PALETTE_SUPPORTED)
  185560. void /* PRIVATE */
  185561. png_correct_palette(png_structp png_ptr, png_colorp palette,
  185562. int num_palette)
  185563. {
  185564. png_debug(1, "in png_correct_palette\n");
  185565. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && \
  185566. defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  185567. if (png_ptr->transformations & (PNG_GAMMA | PNG_BACKGROUND))
  185568. {
  185569. png_color back, back_1;
  185570. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_FILE)
  185571. {
  185572. back.red = png_ptr->gamma_table[png_ptr->background.red];
  185573. back.green = png_ptr->gamma_table[png_ptr->background.green];
  185574. back.blue = png_ptr->gamma_table[png_ptr->background.blue];
  185575. back_1.red = png_ptr->gamma_to_1[png_ptr->background.red];
  185576. back_1.green = png_ptr->gamma_to_1[png_ptr->background.green];
  185577. back_1.blue = png_ptr->gamma_to_1[png_ptr->background.blue];
  185578. }
  185579. else
  185580. {
  185581. double g;
  185582. g = 1.0 / (png_ptr->background_gamma * png_ptr->screen_gamma);
  185583. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_SCREEN ||
  185584. fabs(g - 1.0) < PNG_GAMMA_THRESHOLD)
  185585. {
  185586. back.red = png_ptr->background.red;
  185587. back.green = png_ptr->background.green;
  185588. back.blue = png_ptr->background.blue;
  185589. }
  185590. else
  185591. {
  185592. back.red =
  185593. (png_byte)(pow((double)png_ptr->background.red/255, g) *
  185594. 255.0 + 0.5);
  185595. back.green =
  185596. (png_byte)(pow((double)png_ptr->background.green/255, g) *
  185597. 255.0 + 0.5);
  185598. back.blue =
  185599. (png_byte)(pow((double)png_ptr->background.blue/255, g) *
  185600. 255.0 + 0.5);
  185601. }
  185602. g = 1.0 / png_ptr->background_gamma;
  185603. back_1.red =
  185604. (png_byte)(pow((double)png_ptr->background.red/255, g) *
  185605. 255.0 + 0.5);
  185606. back_1.green =
  185607. (png_byte)(pow((double)png_ptr->background.green/255, g) *
  185608. 255.0 + 0.5);
  185609. back_1.blue =
  185610. (png_byte)(pow((double)png_ptr->background.blue/255, g) *
  185611. 255.0 + 0.5);
  185612. }
  185613. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  185614. {
  185615. png_uint_32 i;
  185616. for (i = 0; i < (png_uint_32)num_palette; i++)
  185617. {
  185618. if (i < png_ptr->num_trans && png_ptr->trans[i] == 0)
  185619. {
  185620. palette[i] = back;
  185621. }
  185622. else if (i < png_ptr->num_trans && png_ptr->trans[i] != 0xff)
  185623. {
  185624. png_byte v, w;
  185625. v = png_ptr->gamma_to_1[png_ptr->palette[i].red];
  185626. png_composite(w, v, png_ptr->trans[i], back_1.red);
  185627. palette[i].red = png_ptr->gamma_from_1[w];
  185628. v = png_ptr->gamma_to_1[png_ptr->palette[i].green];
  185629. png_composite(w, v, png_ptr->trans[i], back_1.green);
  185630. palette[i].green = png_ptr->gamma_from_1[w];
  185631. v = png_ptr->gamma_to_1[png_ptr->palette[i].blue];
  185632. png_composite(w, v, png_ptr->trans[i], back_1.blue);
  185633. palette[i].blue = png_ptr->gamma_from_1[w];
  185634. }
  185635. else
  185636. {
  185637. palette[i].red = png_ptr->gamma_table[palette[i].red];
  185638. palette[i].green = png_ptr->gamma_table[palette[i].green];
  185639. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  185640. }
  185641. }
  185642. }
  185643. else
  185644. {
  185645. int i;
  185646. for (i = 0; i < num_palette; i++)
  185647. {
  185648. if (palette[i].red == (png_byte)png_ptr->trans_values.gray)
  185649. {
  185650. palette[i] = back;
  185651. }
  185652. else
  185653. {
  185654. palette[i].red = png_ptr->gamma_table[palette[i].red];
  185655. palette[i].green = png_ptr->gamma_table[palette[i].green];
  185656. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  185657. }
  185658. }
  185659. }
  185660. }
  185661. else
  185662. #endif
  185663. #if defined(PNG_READ_GAMMA_SUPPORTED)
  185664. if (png_ptr->transformations & PNG_GAMMA)
  185665. {
  185666. int i;
  185667. for (i = 0; i < num_palette; i++)
  185668. {
  185669. palette[i].red = png_ptr->gamma_table[palette[i].red];
  185670. palette[i].green = png_ptr->gamma_table[palette[i].green];
  185671. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  185672. }
  185673. }
  185674. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  185675. else
  185676. #endif
  185677. #endif
  185678. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  185679. if (png_ptr->transformations & PNG_BACKGROUND)
  185680. {
  185681. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  185682. {
  185683. png_color back;
  185684. back.red = (png_byte)png_ptr->background.red;
  185685. back.green = (png_byte)png_ptr->background.green;
  185686. back.blue = (png_byte)png_ptr->background.blue;
  185687. for (i = 0; i < (int)png_ptr->num_trans; i++)
  185688. {
  185689. if (png_ptr->trans[i] == 0)
  185690. {
  185691. palette[i].red = back.red;
  185692. palette[i].green = back.green;
  185693. palette[i].blue = back.blue;
  185694. }
  185695. else if (png_ptr->trans[i] != 0xff)
  185696. {
  185697. png_composite(palette[i].red, png_ptr->palette[i].red,
  185698. png_ptr->trans[i], back.red);
  185699. png_composite(palette[i].green, png_ptr->palette[i].green,
  185700. png_ptr->trans[i], back.green);
  185701. png_composite(palette[i].blue, png_ptr->palette[i].blue,
  185702. png_ptr->trans[i], back.blue);
  185703. }
  185704. }
  185705. }
  185706. else /* assume grayscale palette (what else could it be?) */
  185707. {
  185708. int i;
  185709. for (i = 0; i < num_palette; i++)
  185710. {
  185711. if (i == (png_byte)png_ptr->trans_values.gray)
  185712. {
  185713. palette[i].red = (png_byte)png_ptr->background.red;
  185714. palette[i].green = (png_byte)png_ptr->background.green;
  185715. palette[i].blue = (png_byte)png_ptr->background.blue;
  185716. }
  185717. }
  185718. }
  185719. }
  185720. #endif
  185721. }
  185722. #endif
  185723. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  185724. /* Replace any alpha or transparency with the supplied background color.
  185725. * "background" is already in the screen gamma, while "background_1" is
  185726. * at a gamma of 1.0. Paletted files have already been taken care of.
  185727. */
  185728. void /* PRIVATE */
  185729. png_do_background(png_row_infop row_info, png_bytep row,
  185730. png_color_16p trans_values, png_color_16p background
  185731. #if defined(PNG_READ_GAMMA_SUPPORTED)
  185732. , png_color_16p background_1,
  185733. png_bytep gamma_table, png_bytep gamma_from_1, png_bytep gamma_to_1,
  185734. png_uint_16pp gamma_16, png_uint_16pp gamma_16_from_1,
  185735. png_uint_16pp gamma_16_to_1, int gamma_shift
  185736. #endif
  185737. )
  185738. {
  185739. png_bytep sp, dp;
  185740. png_uint_32 i;
  185741. png_uint_32 row_width=row_info->width;
  185742. int shift;
  185743. png_debug(1, "in png_do_background\n");
  185744. if (background != NULL &&
  185745. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  185746. row != NULL && row_info != NULL &&
  185747. #endif
  185748. (!(row_info->color_type & PNG_COLOR_MASK_ALPHA) ||
  185749. (row_info->color_type != PNG_COLOR_TYPE_PALETTE && trans_values)))
  185750. {
  185751. switch (row_info->color_type)
  185752. {
  185753. case PNG_COLOR_TYPE_GRAY:
  185754. {
  185755. switch (row_info->bit_depth)
  185756. {
  185757. case 1:
  185758. {
  185759. sp = row;
  185760. shift = 7;
  185761. for (i = 0; i < row_width; i++)
  185762. {
  185763. if ((png_uint_16)((*sp >> shift) & 0x01)
  185764. == trans_values->gray)
  185765. {
  185766. *sp &= (png_byte)((0x7f7f >> (7 - shift)) & 0xff);
  185767. *sp |= (png_byte)(background->gray << shift);
  185768. }
  185769. if (!shift)
  185770. {
  185771. shift = 7;
  185772. sp++;
  185773. }
  185774. else
  185775. shift--;
  185776. }
  185777. break;
  185778. }
  185779. case 2:
  185780. {
  185781. #if defined(PNG_READ_GAMMA_SUPPORTED)
  185782. if (gamma_table != NULL)
  185783. {
  185784. sp = row;
  185785. shift = 6;
  185786. for (i = 0; i < row_width; i++)
  185787. {
  185788. if ((png_uint_16)((*sp >> shift) & 0x03)
  185789. == trans_values->gray)
  185790. {
  185791. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  185792. *sp |= (png_byte)(background->gray << shift);
  185793. }
  185794. else
  185795. {
  185796. png_byte p = (png_byte)((*sp >> shift) & 0x03);
  185797. png_byte g = (png_byte)((gamma_table [p | (p << 2) |
  185798. (p << 4) | (p << 6)] >> 6) & 0x03);
  185799. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  185800. *sp |= (png_byte)(g << shift);
  185801. }
  185802. if (!shift)
  185803. {
  185804. shift = 6;
  185805. sp++;
  185806. }
  185807. else
  185808. shift -= 2;
  185809. }
  185810. }
  185811. else
  185812. #endif
  185813. {
  185814. sp = row;
  185815. shift = 6;
  185816. for (i = 0; i < row_width; i++)
  185817. {
  185818. if ((png_uint_16)((*sp >> shift) & 0x03)
  185819. == trans_values->gray)
  185820. {
  185821. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  185822. *sp |= (png_byte)(background->gray << shift);
  185823. }
  185824. if (!shift)
  185825. {
  185826. shift = 6;
  185827. sp++;
  185828. }
  185829. else
  185830. shift -= 2;
  185831. }
  185832. }
  185833. break;
  185834. }
  185835. case 4:
  185836. {
  185837. #if defined(PNG_READ_GAMMA_SUPPORTED)
  185838. if (gamma_table != NULL)
  185839. {
  185840. sp = row;
  185841. shift = 4;
  185842. for (i = 0; i < row_width; i++)
  185843. {
  185844. if ((png_uint_16)((*sp >> shift) & 0x0f)
  185845. == trans_values->gray)
  185846. {
  185847. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  185848. *sp |= (png_byte)(background->gray << shift);
  185849. }
  185850. else
  185851. {
  185852. png_byte p = (png_byte)((*sp >> shift) & 0x0f);
  185853. png_byte g = (png_byte)((gamma_table[p |
  185854. (p << 4)] >> 4) & 0x0f);
  185855. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  185856. *sp |= (png_byte)(g << shift);
  185857. }
  185858. if (!shift)
  185859. {
  185860. shift = 4;
  185861. sp++;
  185862. }
  185863. else
  185864. shift -= 4;
  185865. }
  185866. }
  185867. else
  185868. #endif
  185869. {
  185870. sp = row;
  185871. shift = 4;
  185872. for (i = 0; i < row_width; i++)
  185873. {
  185874. if ((png_uint_16)((*sp >> shift) & 0x0f)
  185875. == trans_values->gray)
  185876. {
  185877. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  185878. *sp |= (png_byte)(background->gray << shift);
  185879. }
  185880. if (!shift)
  185881. {
  185882. shift = 4;
  185883. sp++;
  185884. }
  185885. else
  185886. shift -= 4;
  185887. }
  185888. }
  185889. break;
  185890. }
  185891. case 8:
  185892. {
  185893. #if defined(PNG_READ_GAMMA_SUPPORTED)
  185894. if (gamma_table != NULL)
  185895. {
  185896. sp = row;
  185897. for (i = 0; i < row_width; i++, sp++)
  185898. {
  185899. if (*sp == trans_values->gray)
  185900. {
  185901. *sp = (png_byte)background->gray;
  185902. }
  185903. else
  185904. {
  185905. *sp = gamma_table[*sp];
  185906. }
  185907. }
  185908. }
  185909. else
  185910. #endif
  185911. {
  185912. sp = row;
  185913. for (i = 0; i < row_width; i++, sp++)
  185914. {
  185915. if (*sp == trans_values->gray)
  185916. {
  185917. *sp = (png_byte)background->gray;
  185918. }
  185919. }
  185920. }
  185921. break;
  185922. }
  185923. case 16:
  185924. {
  185925. #if defined(PNG_READ_GAMMA_SUPPORTED)
  185926. if (gamma_16 != NULL)
  185927. {
  185928. sp = row;
  185929. for (i = 0; i < row_width; i++, sp += 2)
  185930. {
  185931. png_uint_16 v;
  185932. v = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  185933. if (v == trans_values->gray)
  185934. {
  185935. /* background is already in screen gamma */
  185936. *sp = (png_byte)((background->gray >> 8) & 0xff);
  185937. *(sp + 1) = (png_byte)(background->gray & 0xff);
  185938. }
  185939. else
  185940. {
  185941. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  185942. *sp = (png_byte)((v >> 8) & 0xff);
  185943. *(sp + 1) = (png_byte)(v & 0xff);
  185944. }
  185945. }
  185946. }
  185947. else
  185948. #endif
  185949. {
  185950. sp = row;
  185951. for (i = 0; i < row_width; i++, sp += 2)
  185952. {
  185953. png_uint_16 v;
  185954. v = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  185955. if (v == trans_values->gray)
  185956. {
  185957. *sp = (png_byte)((background->gray >> 8) & 0xff);
  185958. *(sp + 1) = (png_byte)(background->gray & 0xff);
  185959. }
  185960. }
  185961. }
  185962. break;
  185963. }
  185964. }
  185965. break;
  185966. }
  185967. case PNG_COLOR_TYPE_RGB:
  185968. {
  185969. if (row_info->bit_depth == 8)
  185970. {
  185971. #if defined(PNG_READ_GAMMA_SUPPORTED)
  185972. if (gamma_table != NULL)
  185973. {
  185974. sp = row;
  185975. for (i = 0; i < row_width; i++, sp += 3)
  185976. {
  185977. if (*sp == trans_values->red &&
  185978. *(sp + 1) == trans_values->green &&
  185979. *(sp + 2) == trans_values->blue)
  185980. {
  185981. *sp = (png_byte)background->red;
  185982. *(sp + 1) = (png_byte)background->green;
  185983. *(sp + 2) = (png_byte)background->blue;
  185984. }
  185985. else
  185986. {
  185987. *sp = gamma_table[*sp];
  185988. *(sp + 1) = gamma_table[*(sp + 1)];
  185989. *(sp + 2) = gamma_table[*(sp + 2)];
  185990. }
  185991. }
  185992. }
  185993. else
  185994. #endif
  185995. {
  185996. sp = row;
  185997. for (i = 0; i < row_width; i++, sp += 3)
  185998. {
  185999. if (*sp == trans_values->red &&
  186000. *(sp + 1) == trans_values->green &&
  186001. *(sp + 2) == trans_values->blue)
  186002. {
  186003. *sp = (png_byte)background->red;
  186004. *(sp + 1) = (png_byte)background->green;
  186005. *(sp + 2) = (png_byte)background->blue;
  186006. }
  186007. }
  186008. }
  186009. }
  186010. else /* if (row_info->bit_depth == 16) */
  186011. {
  186012. #if defined(PNG_READ_GAMMA_SUPPORTED)
  186013. if (gamma_16 != NULL)
  186014. {
  186015. sp = row;
  186016. for (i = 0; i < row_width; i++, sp += 6)
  186017. {
  186018. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  186019. png_uint_16 g = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  186020. png_uint_16 b = (png_uint_16)(((*(sp+4)) << 8) + *(sp+5));
  186021. if (r == trans_values->red && g == trans_values->green &&
  186022. b == trans_values->blue)
  186023. {
  186024. /* background is already in screen gamma */
  186025. *sp = (png_byte)((background->red >> 8) & 0xff);
  186026. *(sp + 1) = (png_byte)(background->red & 0xff);
  186027. *(sp + 2) = (png_byte)((background->green >> 8) & 0xff);
  186028. *(sp + 3) = (png_byte)(background->green & 0xff);
  186029. *(sp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  186030. *(sp + 5) = (png_byte)(background->blue & 0xff);
  186031. }
  186032. else
  186033. {
  186034. png_uint_16 v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  186035. *sp = (png_byte)((v >> 8) & 0xff);
  186036. *(sp + 1) = (png_byte)(v & 0xff);
  186037. v = gamma_16[*(sp + 3) >> gamma_shift][*(sp + 2)];
  186038. *(sp + 2) = (png_byte)((v >> 8) & 0xff);
  186039. *(sp + 3) = (png_byte)(v & 0xff);
  186040. v = gamma_16[*(sp + 5) >> gamma_shift][*(sp + 4)];
  186041. *(sp + 4) = (png_byte)((v >> 8) & 0xff);
  186042. *(sp + 5) = (png_byte)(v & 0xff);
  186043. }
  186044. }
  186045. }
  186046. else
  186047. #endif
  186048. {
  186049. sp = row;
  186050. for (i = 0; i < row_width; i++, sp += 6)
  186051. {
  186052. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp+1));
  186053. png_uint_16 g = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  186054. png_uint_16 b = (png_uint_16)(((*(sp+4)) << 8) + *(sp+5));
  186055. if (r == trans_values->red && g == trans_values->green &&
  186056. b == trans_values->blue)
  186057. {
  186058. *sp = (png_byte)((background->red >> 8) & 0xff);
  186059. *(sp + 1) = (png_byte)(background->red & 0xff);
  186060. *(sp + 2) = (png_byte)((background->green >> 8) & 0xff);
  186061. *(sp + 3) = (png_byte)(background->green & 0xff);
  186062. *(sp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  186063. *(sp + 5) = (png_byte)(background->blue & 0xff);
  186064. }
  186065. }
  186066. }
  186067. }
  186068. break;
  186069. }
  186070. case PNG_COLOR_TYPE_GRAY_ALPHA:
  186071. {
  186072. if (row_info->bit_depth == 8)
  186073. {
  186074. #if defined(PNG_READ_GAMMA_SUPPORTED)
  186075. if (gamma_to_1 != NULL && gamma_from_1 != NULL &&
  186076. gamma_table != NULL)
  186077. {
  186078. sp = row;
  186079. dp = row;
  186080. for (i = 0; i < row_width; i++, sp += 2, dp++)
  186081. {
  186082. png_uint_16 a = *(sp + 1);
  186083. if (a == 0xff)
  186084. {
  186085. *dp = gamma_table[*sp];
  186086. }
  186087. else if (a == 0)
  186088. {
  186089. /* background is already in screen gamma */
  186090. *dp = (png_byte)background->gray;
  186091. }
  186092. else
  186093. {
  186094. png_byte v, w;
  186095. v = gamma_to_1[*sp];
  186096. png_composite(w, v, a, background_1->gray);
  186097. *dp = gamma_from_1[w];
  186098. }
  186099. }
  186100. }
  186101. else
  186102. #endif
  186103. {
  186104. sp = row;
  186105. dp = row;
  186106. for (i = 0; i < row_width; i++, sp += 2, dp++)
  186107. {
  186108. png_byte a = *(sp + 1);
  186109. if (a == 0xff)
  186110. {
  186111. *dp = *sp;
  186112. }
  186113. #if defined(PNG_READ_GAMMA_SUPPORTED)
  186114. else if (a == 0)
  186115. {
  186116. *dp = (png_byte)background->gray;
  186117. }
  186118. else
  186119. {
  186120. png_composite(*dp, *sp, a, background_1->gray);
  186121. }
  186122. #else
  186123. *dp = (png_byte)background->gray;
  186124. #endif
  186125. }
  186126. }
  186127. }
  186128. else /* if (png_ptr->bit_depth == 16) */
  186129. {
  186130. #if defined(PNG_READ_GAMMA_SUPPORTED)
  186131. if (gamma_16 != NULL && gamma_16_from_1 != NULL &&
  186132. gamma_16_to_1 != NULL)
  186133. {
  186134. sp = row;
  186135. dp = row;
  186136. for (i = 0; i < row_width; i++, sp += 4, dp += 2)
  186137. {
  186138. png_uint_16 a = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  186139. if (a == (png_uint_16)0xffff)
  186140. {
  186141. png_uint_16 v;
  186142. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  186143. *dp = (png_byte)((v >> 8) & 0xff);
  186144. *(dp + 1) = (png_byte)(v & 0xff);
  186145. }
  186146. #if defined(PNG_READ_GAMMA_SUPPORTED)
  186147. else if (a == 0)
  186148. #else
  186149. else
  186150. #endif
  186151. {
  186152. /* background is already in screen gamma */
  186153. *dp = (png_byte)((background->gray >> 8) & 0xff);
  186154. *(dp + 1) = (png_byte)(background->gray & 0xff);
  186155. }
  186156. #if defined(PNG_READ_GAMMA_SUPPORTED)
  186157. else
  186158. {
  186159. png_uint_16 g, v, w;
  186160. g = gamma_16_to_1[*(sp + 1) >> gamma_shift][*sp];
  186161. png_composite_16(v, g, a, background_1->gray);
  186162. w = gamma_16_from_1[(v&0xff) >> gamma_shift][v >> 8];
  186163. *dp = (png_byte)((w >> 8) & 0xff);
  186164. *(dp + 1) = (png_byte)(w & 0xff);
  186165. }
  186166. #endif
  186167. }
  186168. }
  186169. else
  186170. #endif
  186171. {
  186172. sp = row;
  186173. dp = row;
  186174. for (i = 0; i < row_width; i++, sp += 4, dp += 2)
  186175. {
  186176. png_uint_16 a = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  186177. if (a == (png_uint_16)0xffff)
  186178. {
  186179. png_memcpy(dp, sp, 2);
  186180. }
  186181. #if defined(PNG_READ_GAMMA_SUPPORTED)
  186182. else if (a == 0)
  186183. #else
  186184. else
  186185. #endif
  186186. {
  186187. *dp = (png_byte)((background->gray >> 8) & 0xff);
  186188. *(dp + 1) = (png_byte)(background->gray & 0xff);
  186189. }
  186190. #if defined(PNG_READ_GAMMA_SUPPORTED)
  186191. else
  186192. {
  186193. png_uint_16 g, v;
  186194. g = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  186195. png_composite_16(v, g, a, background_1->gray);
  186196. *dp = (png_byte)((v >> 8) & 0xff);
  186197. *(dp + 1) = (png_byte)(v & 0xff);
  186198. }
  186199. #endif
  186200. }
  186201. }
  186202. }
  186203. break;
  186204. }
  186205. case PNG_COLOR_TYPE_RGB_ALPHA:
  186206. {
  186207. if (row_info->bit_depth == 8)
  186208. {
  186209. #if defined(PNG_READ_GAMMA_SUPPORTED)
  186210. if (gamma_to_1 != NULL && gamma_from_1 != NULL &&
  186211. gamma_table != NULL)
  186212. {
  186213. sp = row;
  186214. dp = row;
  186215. for (i = 0; i < row_width; i++, sp += 4, dp += 3)
  186216. {
  186217. png_byte a = *(sp + 3);
  186218. if (a == 0xff)
  186219. {
  186220. *dp = gamma_table[*sp];
  186221. *(dp + 1) = gamma_table[*(sp + 1)];
  186222. *(dp + 2) = gamma_table[*(sp + 2)];
  186223. }
  186224. else if (a == 0)
  186225. {
  186226. /* background is already in screen gamma */
  186227. *dp = (png_byte)background->red;
  186228. *(dp + 1) = (png_byte)background->green;
  186229. *(dp + 2) = (png_byte)background->blue;
  186230. }
  186231. else
  186232. {
  186233. png_byte v, w;
  186234. v = gamma_to_1[*sp];
  186235. png_composite(w, v, a, background_1->red);
  186236. *dp = gamma_from_1[w];
  186237. v = gamma_to_1[*(sp + 1)];
  186238. png_composite(w, v, a, background_1->green);
  186239. *(dp + 1) = gamma_from_1[w];
  186240. v = gamma_to_1[*(sp + 2)];
  186241. png_composite(w, v, a, background_1->blue);
  186242. *(dp + 2) = gamma_from_1[w];
  186243. }
  186244. }
  186245. }
  186246. else
  186247. #endif
  186248. {
  186249. sp = row;
  186250. dp = row;
  186251. for (i = 0; i < row_width; i++, sp += 4, dp += 3)
  186252. {
  186253. png_byte a = *(sp + 3);
  186254. if (a == 0xff)
  186255. {
  186256. *dp = *sp;
  186257. *(dp + 1) = *(sp + 1);
  186258. *(dp + 2) = *(sp + 2);
  186259. }
  186260. else if (a == 0)
  186261. {
  186262. *dp = (png_byte)background->red;
  186263. *(dp + 1) = (png_byte)background->green;
  186264. *(dp + 2) = (png_byte)background->blue;
  186265. }
  186266. else
  186267. {
  186268. png_composite(*dp, *sp, a, background->red);
  186269. png_composite(*(dp + 1), *(sp + 1), a,
  186270. background->green);
  186271. png_composite(*(dp + 2), *(sp + 2), a,
  186272. background->blue);
  186273. }
  186274. }
  186275. }
  186276. }
  186277. else /* if (row_info->bit_depth == 16) */
  186278. {
  186279. #if defined(PNG_READ_GAMMA_SUPPORTED)
  186280. if (gamma_16 != NULL && gamma_16_from_1 != NULL &&
  186281. gamma_16_to_1 != NULL)
  186282. {
  186283. sp = row;
  186284. dp = row;
  186285. for (i = 0; i < row_width; i++, sp += 8, dp += 6)
  186286. {
  186287. png_uint_16 a = (png_uint_16)(((png_uint_16)(*(sp + 6))
  186288. << 8) + (png_uint_16)(*(sp + 7)));
  186289. if (a == (png_uint_16)0xffff)
  186290. {
  186291. png_uint_16 v;
  186292. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  186293. *dp = (png_byte)((v >> 8) & 0xff);
  186294. *(dp + 1) = (png_byte)(v & 0xff);
  186295. v = gamma_16[*(sp + 3) >> gamma_shift][*(sp + 2)];
  186296. *(dp + 2) = (png_byte)((v >> 8) & 0xff);
  186297. *(dp + 3) = (png_byte)(v & 0xff);
  186298. v = gamma_16[*(sp + 5) >> gamma_shift][*(sp + 4)];
  186299. *(dp + 4) = (png_byte)((v >> 8) & 0xff);
  186300. *(dp + 5) = (png_byte)(v & 0xff);
  186301. }
  186302. else if (a == 0)
  186303. {
  186304. /* background is already in screen gamma */
  186305. *dp = (png_byte)((background->red >> 8) & 0xff);
  186306. *(dp + 1) = (png_byte)(background->red & 0xff);
  186307. *(dp + 2) = (png_byte)((background->green >> 8) & 0xff);
  186308. *(dp + 3) = (png_byte)(background->green & 0xff);
  186309. *(dp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  186310. *(dp + 5) = (png_byte)(background->blue & 0xff);
  186311. }
  186312. else
  186313. {
  186314. png_uint_16 v, w, x;
  186315. v = gamma_16_to_1[*(sp + 1) >> gamma_shift][*sp];
  186316. png_composite_16(w, v, a, background_1->red);
  186317. x = gamma_16_from_1[((w&0xff) >> gamma_shift)][w >> 8];
  186318. *dp = (png_byte)((x >> 8) & 0xff);
  186319. *(dp + 1) = (png_byte)(x & 0xff);
  186320. v = gamma_16_to_1[*(sp + 3) >> gamma_shift][*(sp + 2)];
  186321. png_composite_16(w, v, a, background_1->green);
  186322. x = gamma_16_from_1[((w&0xff) >> gamma_shift)][w >> 8];
  186323. *(dp + 2) = (png_byte)((x >> 8) & 0xff);
  186324. *(dp + 3) = (png_byte)(x & 0xff);
  186325. v = gamma_16_to_1[*(sp + 5) >> gamma_shift][*(sp + 4)];
  186326. png_composite_16(w, v, a, background_1->blue);
  186327. x = gamma_16_from_1[(w & 0xff) >> gamma_shift][w >> 8];
  186328. *(dp + 4) = (png_byte)((x >> 8) & 0xff);
  186329. *(dp + 5) = (png_byte)(x & 0xff);
  186330. }
  186331. }
  186332. }
  186333. else
  186334. #endif
  186335. {
  186336. sp = row;
  186337. dp = row;
  186338. for (i = 0; i < row_width; i++, sp += 8, dp += 6)
  186339. {
  186340. png_uint_16 a = (png_uint_16)(((png_uint_16)(*(sp + 6))
  186341. << 8) + (png_uint_16)(*(sp + 7)));
  186342. if (a == (png_uint_16)0xffff)
  186343. {
  186344. png_memcpy(dp, sp, 6);
  186345. }
  186346. else if (a == 0)
  186347. {
  186348. *dp = (png_byte)((background->red >> 8) & 0xff);
  186349. *(dp + 1) = (png_byte)(background->red & 0xff);
  186350. *(dp + 2) = (png_byte)((background->green >> 8) & 0xff);
  186351. *(dp + 3) = (png_byte)(background->green & 0xff);
  186352. *(dp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  186353. *(dp + 5) = (png_byte)(background->blue & 0xff);
  186354. }
  186355. else
  186356. {
  186357. png_uint_16 v;
  186358. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  186359. png_uint_16 g = (png_uint_16)(((*(sp + 2)) << 8)
  186360. + *(sp + 3));
  186361. png_uint_16 b = (png_uint_16)(((*(sp + 4)) << 8)
  186362. + *(sp + 5));
  186363. png_composite_16(v, r, a, background->red);
  186364. *dp = (png_byte)((v >> 8) & 0xff);
  186365. *(dp + 1) = (png_byte)(v & 0xff);
  186366. png_composite_16(v, g, a, background->green);
  186367. *(dp + 2) = (png_byte)((v >> 8) & 0xff);
  186368. *(dp + 3) = (png_byte)(v & 0xff);
  186369. png_composite_16(v, b, a, background->blue);
  186370. *(dp + 4) = (png_byte)((v >> 8) & 0xff);
  186371. *(dp + 5) = (png_byte)(v & 0xff);
  186372. }
  186373. }
  186374. }
  186375. }
  186376. break;
  186377. }
  186378. }
  186379. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  186380. {
  186381. row_info->color_type &= ~PNG_COLOR_MASK_ALPHA;
  186382. row_info->channels--;
  186383. row_info->pixel_depth = (png_byte)(row_info->channels *
  186384. row_info->bit_depth);
  186385. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  186386. }
  186387. }
  186388. }
  186389. #endif
  186390. #if defined(PNG_READ_GAMMA_SUPPORTED)
  186391. /* Gamma correct the image, avoiding the alpha channel. Make sure
  186392. * you do this after you deal with the transparency issue on grayscale
  186393. * or RGB images. If your bit depth is 8, use gamma_table, if it
  186394. * is 16, use gamma_16_table and gamma_shift. Build these with
  186395. * build_gamma_table().
  186396. */
  186397. void /* PRIVATE */
  186398. png_do_gamma(png_row_infop row_info, png_bytep row,
  186399. png_bytep gamma_table, png_uint_16pp gamma_16_table,
  186400. int gamma_shift)
  186401. {
  186402. png_bytep sp;
  186403. png_uint_32 i;
  186404. png_uint_32 row_width=row_info->width;
  186405. png_debug(1, "in png_do_gamma\n");
  186406. if (
  186407. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  186408. row != NULL && row_info != NULL &&
  186409. #endif
  186410. ((row_info->bit_depth <= 8 && gamma_table != NULL) ||
  186411. (row_info->bit_depth == 16 && gamma_16_table != NULL)))
  186412. {
  186413. switch (row_info->color_type)
  186414. {
  186415. case PNG_COLOR_TYPE_RGB:
  186416. {
  186417. if (row_info->bit_depth == 8)
  186418. {
  186419. sp = row;
  186420. for (i = 0; i < row_width; i++)
  186421. {
  186422. *sp = gamma_table[*sp];
  186423. sp++;
  186424. *sp = gamma_table[*sp];
  186425. sp++;
  186426. *sp = gamma_table[*sp];
  186427. sp++;
  186428. }
  186429. }
  186430. else /* if (row_info->bit_depth == 16) */
  186431. {
  186432. sp = row;
  186433. for (i = 0; i < row_width; i++)
  186434. {
  186435. png_uint_16 v;
  186436. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  186437. *sp = (png_byte)((v >> 8) & 0xff);
  186438. *(sp + 1) = (png_byte)(v & 0xff);
  186439. sp += 2;
  186440. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  186441. *sp = (png_byte)((v >> 8) & 0xff);
  186442. *(sp + 1) = (png_byte)(v & 0xff);
  186443. sp += 2;
  186444. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  186445. *sp = (png_byte)((v >> 8) & 0xff);
  186446. *(sp + 1) = (png_byte)(v & 0xff);
  186447. sp += 2;
  186448. }
  186449. }
  186450. break;
  186451. }
  186452. case PNG_COLOR_TYPE_RGB_ALPHA:
  186453. {
  186454. if (row_info->bit_depth == 8)
  186455. {
  186456. sp = row;
  186457. for (i = 0; i < row_width; i++)
  186458. {
  186459. *sp = gamma_table[*sp];
  186460. sp++;
  186461. *sp = gamma_table[*sp];
  186462. sp++;
  186463. *sp = gamma_table[*sp];
  186464. sp++;
  186465. sp++;
  186466. }
  186467. }
  186468. else /* if (row_info->bit_depth == 16) */
  186469. {
  186470. sp = row;
  186471. for (i = 0; i < row_width; i++)
  186472. {
  186473. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  186474. *sp = (png_byte)((v >> 8) & 0xff);
  186475. *(sp + 1) = (png_byte)(v & 0xff);
  186476. sp += 2;
  186477. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  186478. *sp = (png_byte)((v >> 8) & 0xff);
  186479. *(sp + 1) = (png_byte)(v & 0xff);
  186480. sp += 2;
  186481. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  186482. *sp = (png_byte)((v >> 8) & 0xff);
  186483. *(sp + 1) = (png_byte)(v & 0xff);
  186484. sp += 4;
  186485. }
  186486. }
  186487. break;
  186488. }
  186489. case PNG_COLOR_TYPE_GRAY_ALPHA:
  186490. {
  186491. if (row_info->bit_depth == 8)
  186492. {
  186493. sp = row;
  186494. for (i = 0; i < row_width; i++)
  186495. {
  186496. *sp = gamma_table[*sp];
  186497. sp += 2;
  186498. }
  186499. }
  186500. else /* if (row_info->bit_depth == 16) */
  186501. {
  186502. sp = row;
  186503. for (i = 0; i < row_width; i++)
  186504. {
  186505. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  186506. *sp = (png_byte)((v >> 8) & 0xff);
  186507. *(sp + 1) = (png_byte)(v & 0xff);
  186508. sp += 4;
  186509. }
  186510. }
  186511. break;
  186512. }
  186513. case PNG_COLOR_TYPE_GRAY:
  186514. {
  186515. if (row_info->bit_depth == 2)
  186516. {
  186517. sp = row;
  186518. for (i = 0; i < row_width; i += 4)
  186519. {
  186520. int a = *sp & 0xc0;
  186521. int b = *sp & 0x30;
  186522. int c = *sp & 0x0c;
  186523. int d = *sp & 0x03;
  186524. *sp = (png_byte)(
  186525. ((((int)gamma_table[a|(a>>2)|(a>>4)|(a>>6)]) ) & 0xc0)|
  186526. ((((int)gamma_table[(b<<2)|b|(b>>2)|(b>>4)])>>2) & 0x30)|
  186527. ((((int)gamma_table[(c<<4)|(c<<2)|c|(c>>2)])>>4) & 0x0c)|
  186528. ((((int)gamma_table[(d<<6)|(d<<4)|(d<<2)|d])>>6) ));
  186529. sp++;
  186530. }
  186531. }
  186532. if (row_info->bit_depth == 4)
  186533. {
  186534. sp = row;
  186535. for (i = 0; i < row_width; i += 2)
  186536. {
  186537. int msb = *sp & 0xf0;
  186538. int lsb = *sp & 0x0f;
  186539. *sp = (png_byte)((((int)gamma_table[msb | (msb >> 4)]) & 0xf0)
  186540. | (((int)gamma_table[(lsb << 4) | lsb]) >> 4));
  186541. sp++;
  186542. }
  186543. }
  186544. else if (row_info->bit_depth == 8)
  186545. {
  186546. sp = row;
  186547. for (i = 0; i < row_width; i++)
  186548. {
  186549. *sp = gamma_table[*sp];
  186550. sp++;
  186551. }
  186552. }
  186553. else if (row_info->bit_depth == 16)
  186554. {
  186555. sp = row;
  186556. for (i = 0; i < row_width; i++)
  186557. {
  186558. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  186559. *sp = (png_byte)((v >> 8) & 0xff);
  186560. *(sp + 1) = (png_byte)(v & 0xff);
  186561. sp += 2;
  186562. }
  186563. }
  186564. break;
  186565. }
  186566. }
  186567. }
  186568. }
  186569. #endif
  186570. #if defined(PNG_READ_EXPAND_SUPPORTED)
  186571. /* Expands a palette row to an RGB or RGBA row depending
  186572. * upon whether you supply trans and num_trans.
  186573. */
  186574. void /* PRIVATE */
  186575. png_do_expand_palette(png_row_infop row_info, png_bytep row,
  186576. png_colorp palette, png_bytep trans, int num_trans)
  186577. {
  186578. int shift, value;
  186579. png_bytep sp, dp;
  186580. png_uint_32 i;
  186581. png_uint_32 row_width=row_info->width;
  186582. png_debug(1, "in png_do_expand_palette\n");
  186583. if (
  186584. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  186585. row != NULL && row_info != NULL &&
  186586. #endif
  186587. row_info->color_type == PNG_COLOR_TYPE_PALETTE)
  186588. {
  186589. if (row_info->bit_depth < 8)
  186590. {
  186591. switch (row_info->bit_depth)
  186592. {
  186593. case 1:
  186594. {
  186595. sp = row + (png_size_t)((row_width - 1) >> 3);
  186596. dp = row + (png_size_t)row_width - 1;
  186597. shift = 7 - (int)((row_width + 7) & 0x07);
  186598. for (i = 0; i < row_width; i++)
  186599. {
  186600. if ((*sp >> shift) & 0x01)
  186601. *dp = 1;
  186602. else
  186603. *dp = 0;
  186604. if (shift == 7)
  186605. {
  186606. shift = 0;
  186607. sp--;
  186608. }
  186609. else
  186610. shift++;
  186611. dp--;
  186612. }
  186613. break;
  186614. }
  186615. case 2:
  186616. {
  186617. sp = row + (png_size_t)((row_width - 1) >> 2);
  186618. dp = row + (png_size_t)row_width - 1;
  186619. shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  186620. for (i = 0; i < row_width; i++)
  186621. {
  186622. value = (*sp >> shift) & 0x03;
  186623. *dp = (png_byte)value;
  186624. if (shift == 6)
  186625. {
  186626. shift = 0;
  186627. sp--;
  186628. }
  186629. else
  186630. shift += 2;
  186631. dp--;
  186632. }
  186633. break;
  186634. }
  186635. case 4:
  186636. {
  186637. sp = row + (png_size_t)((row_width - 1) >> 1);
  186638. dp = row + (png_size_t)row_width - 1;
  186639. shift = (int)((row_width & 0x01) << 2);
  186640. for (i = 0; i < row_width; i++)
  186641. {
  186642. value = (*sp >> shift) & 0x0f;
  186643. *dp = (png_byte)value;
  186644. if (shift == 4)
  186645. {
  186646. shift = 0;
  186647. sp--;
  186648. }
  186649. else
  186650. shift += 4;
  186651. dp--;
  186652. }
  186653. break;
  186654. }
  186655. }
  186656. row_info->bit_depth = 8;
  186657. row_info->pixel_depth = 8;
  186658. row_info->rowbytes = row_width;
  186659. }
  186660. switch (row_info->bit_depth)
  186661. {
  186662. case 8:
  186663. {
  186664. if (trans != NULL)
  186665. {
  186666. sp = row + (png_size_t)row_width - 1;
  186667. dp = row + (png_size_t)(row_width << 2) - 1;
  186668. for (i = 0; i < row_width; i++)
  186669. {
  186670. if ((int)(*sp) >= num_trans)
  186671. *dp-- = 0xff;
  186672. else
  186673. *dp-- = trans[*sp];
  186674. *dp-- = palette[*sp].blue;
  186675. *dp-- = palette[*sp].green;
  186676. *dp-- = palette[*sp].red;
  186677. sp--;
  186678. }
  186679. row_info->bit_depth = 8;
  186680. row_info->pixel_depth = 32;
  186681. row_info->rowbytes = row_width * 4;
  186682. row_info->color_type = 6;
  186683. row_info->channels = 4;
  186684. }
  186685. else
  186686. {
  186687. sp = row + (png_size_t)row_width - 1;
  186688. dp = row + (png_size_t)(row_width * 3) - 1;
  186689. for (i = 0; i < row_width; i++)
  186690. {
  186691. *dp-- = palette[*sp].blue;
  186692. *dp-- = palette[*sp].green;
  186693. *dp-- = palette[*sp].red;
  186694. sp--;
  186695. }
  186696. row_info->bit_depth = 8;
  186697. row_info->pixel_depth = 24;
  186698. row_info->rowbytes = row_width * 3;
  186699. row_info->color_type = 2;
  186700. row_info->channels = 3;
  186701. }
  186702. break;
  186703. }
  186704. }
  186705. }
  186706. }
  186707. /* If the bit depth < 8, it is expanded to 8. Also, if the already
  186708. * expanded transparency value is supplied, an alpha channel is built.
  186709. */
  186710. void /* PRIVATE */
  186711. png_do_expand(png_row_infop row_info, png_bytep row,
  186712. png_color_16p trans_value)
  186713. {
  186714. int shift, value;
  186715. png_bytep sp, dp;
  186716. png_uint_32 i;
  186717. png_uint_32 row_width=row_info->width;
  186718. png_debug(1, "in png_do_expand\n");
  186719. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  186720. if (row != NULL && row_info != NULL)
  186721. #endif
  186722. {
  186723. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  186724. {
  186725. png_uint_16 gray = (png_uint_16)(trans_value ? trans_value->gray : 0);
  186726. if (row_info->bit_depth < 8)
  186727. {
  186728. switch (row_info->bit_depth)
  186729. {
  186730. case 1:
  186731. {
  186732. gray = (png_uint_16)((gray&0x01)*0xff);
  186733. sp = row + (png_size_t)((row_width - 1) >> 3);
  186734. dp = row + (png_size_t)row_width - 1;
  186735. shift = 7 - (int)((row_width + 7) & 0x07);
  186736. for (i = 0; i < row_width; i++)
  186737. {
  186738. if ((*sp >> shift) & 0x01)
  186739. *dp = 0xff;
  186740. else
  186741. *dp = 0;
  186742. if (shift == 7)
  186743. {
  186744. shift = 0;
  186745. sp--;
  186746. }
  186747. else
  186748. shift++;
  186749. dp--;
  186750. }
  186751. break;
  186752. }
  186753. case 2:
  186754. {
  186755. gray = (png_uint_16)((gray&0x03)*0x55);
  186756. sp = row + (png_size_t)((row_width - 1) >> 2);
  186757. dp = row + (png_size_t)row_width - 1;
  186758. shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  186759. for (i = 0; i < row_width; i++)
  186760. {
  186761. value = (*sp >> shift) & 0x03;
  186762. *dp = (png_byte)(value | (value << 2) | (value << 4) |
  186763. (value << 6));
  186764. if (shift == 6)
  186765. {
  186766. shift = 0;
  186767. sp--;
  186768. }
  186769. else
  186770. shift += 2;
  186771. dp--;
  186772. }
  186773. break;
  186774. }
  186775. case 4:
  186776. {
  186777. gray = (png_uint_16)((gray&0x0f)*0x11);
  186778. sp = row + (png_size_t)((row_width - 1) >> 1);
  186779. dp = row + (png_size_t)row_width - 1;
  186780. shift = (int)((1 - ((row_width + 1) & 0x01)) << 2);
  186781. for (i = 0; i < row_width; i++)
  186782. {
  186783. value = (*sp >> shift) & 0x0f;
  186784. *dp = (png_byte)(value | (value << 4));
  186785. if (shift == 4)
  186786. {
  186787. shift = 0;
  186788. sp--;
  186789. }
  186790. else
  186791. shift = 4;
  186792. dp--;
  186793. }
  186794. break;
  186795. }
  186796. }
  186797. row_info->bit_depth = 8;
  186798. row_info->pixel_depth = 8;
  186799. row_info->rowbytes = row_width;
  186800. }
  186801. if (trans_value != NULL)
  186802. {
  186803. if (row_info->bit_depth == 8)
  186804. {
  186805. gray = gray & 0xff;
  186806. sp = row + (png_size_t)row_width - 1;
  186807. dp = row + (png_size_t)(row_width << 1) - 1;
  186808. for (i = 0; i < row_width; i++)
  186809. {
  186810. if (*sp == gray)
  186811. *dp-- = 0;
  186812. else
  186813. *dp-- = 0xff;
  186814. *dp-- = *sp--;
  186815. }
  186816. }
  186817. else if (row_info->bit_depth == 16)
  186818. {
  186819. png_byte gray_high = (gray >> 8) & 0xff;
  186820. png_byte gray_low = gray & 0xff;
  186821. sp = row + row_info->rowbytes - 1;
  186822. dp = row + (row_info->rowbytes << 1) - 1;
  186823. for (i = 0; i < row_width; i++)
  186824. {
  186825. if (*(sp-1) == gray_high && *(sp) == gray_low)
  186826. {
  186827. *dp-- = 0;
  186828. *dp-- = 0;
  186829. }
  186830. else
  186831. {
  186832. *dp-- = 0xff;
  186833. *dp-- = 0xff;
  186834. }
  186835. *dp-- = *sp--;
  186836. *dp-- = *sp--;
  186837. }
  186838. }
  186839. row_info->color_type = PNG_COLOR_TYPE_GRAY_ALPHA;
  186840. row_info->channels = 2;
  186841. row_info->pixel_depth = (png_byte)(row_info->bit_depth << 1);
  186842. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  186843. row_width);
  186844. }
  186845. }
  186846. else if (row_info->color_type == PNG_COLOR_TYPE_RGB && trans_value)
  186847. {
  186848. if (row_info->bit_depth == 8)
  186849. {
  186850. png_byte red = trans_value->red & 0xff;
  186851. png_byte green = trans_value->green & 0xff;
  186852. png_byte blue = trans_value->blue & 0xff;
  186853. sp = row + (png_size_t)row_info->rowbytes - 1;
  186854. dp = row + (png_size_t)(row_width << 2) - 1;
  186855. for (i = 0; i < row_width; i++)
  186856. {
  186857. if (*(sp - 2) == red && *(sp - 1) == green && *(sp) == blue)
  186858. *dp-- = 0;
  186859. else
  186860. *dp-- = 0xff;
  186861. *dp-- = *sp--;
  186862. *dp-- = *sp--;
  186863. *dp-- = *sp--;
  186864. }
  186865. }
  186866. else if (row_info->bit_depth == 16)
  186867. {
  186868. png_byte red_high = (trans_value->red >> 8) & 0xff;
  186869. png_byte green_high = (trans_value->green >> 8) & 0xff;
  186870. png_byte blue_high = (trans_value->blue >> 8) & 0xff;
  186871. png_byte red_low = trans_value->red & 0xff;
  186872. png_byte green_low = trans_value->green & 0xff;
  186873. png_byte blue_low = trans_value->blue & 0xff;
  186874. sp = row + row_info->rowbytes - 1;
  186875. dp = row + (png_size_t)(row_width << 3) - 1;
  186876. for (i = 0; i < row_width; i++)
  186877. {
  186878. if (*(sp - 5) == red_high &&
  186879. *(sp - 4) == red_low &&
  186880. *(sp - 3) == green_high &&
  186881. *(sp - 2) == green_low &&
  186882. *(sp - 1) == blue_high &&
  186883. *(sp ) == blue_low)
  186884. {
  186885. *dp-- = 0;
  186886. *dp-- = 0;
  186887. }
  186888. else
  186889. {
  186890. *dp-- = 0xff;
  186891. *dp-- = 0xff;
  186892. }
  186893. *dp-- = *sp--;
  186894. *dp-- = *sp--;
  186895. *dp-- = *sp--;
  186896. *dp-- = *sp--;
  186897. *dp-- = *sp--;
  186898. *dp-- = *sp--;
  186899. }
  186900. }
  186901. row_info->color_type = PNG_COLOR_TYPE_RGB_ALPHA;
  186902. row_info->channels = 4;
  186903. row_info->pixel_depth = (png_byte)(row_info->bit_depth << 2);
  186904. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  186905. }
  186906. }
  186907. }
  186908. #endif
  186909. #if defined(PNG_READ_DITHER_SUPPORTED)
  186910. void /* PRIVATE */
  186911. png_do_dither(png_row_infop row_info, png_bytep row,
  186912. png_bytep palette_lookup, png_bytep dither_lookup)
  186913. {
  186914. png_bytep sp, dp;
  186915. png_uint_32 i;
  186916. png_uint_32 row_width=row_info->width;
  186917. png_debug(1, "in png_do_dither\n");
  186918. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  186919. if (row != NULL && row_info != NULL)
  186920. #endif
  186921. {
  186922. if (row_info->color_type == PNG_COLOR_TYPE_RGB &&
  186923. palette_lookup && row_info->bit_depth == 8)
  186924. {
  186925. int r, g, b, p;
  186926. sp = row;
  186927. dp = row;
  186928. for (i = 0; i < row_width; i++)
  186929. {
  186930. r = *sp++;
  186931. g = *sp++;
  186932. b = *sp++;
  186933. /* this looks real messy, but the compiler will reduce
  186934. it down to a reasonable formula. For example, with
  186935. 5 bits per color, we get:
  186936. p = (((r >> 3) & 0x1f) << 10) |
  186937. (((g >> 3) & 0x1f) << 5) |
  186938. ((b >> 3) & 0x1f);
  186939. */
  186940. p = (((r >> (8 - PNG_DITHER_RED_BITS)) &
  186941. ((1 << PNG_DITHER_RED_BITS) - 1)) <<
  186942. (PNG_DITHER_GREEN_BITS + PNG_DITHER_BLUE_BITS)) |
  186943. (((g >> (8 - PNG_DITHER_GREEN_BITS)) &
  186944. ((1 << PNG_DITHER_GREEN_BITS) - 1)) <<
  186945. (PNG_DITHER_BLUE_BITS)) |
  186946. ((b >> (8 - PNG_DITHER_BLUE_BITS)) &
  186947. ((1 << PNG_DITHER_BLUE_BITS) - 1));
  186948. *dp++ = palette_lookup[p];
  186949. }
  186950. row_info->color_type = PNG_COLOR_TYPE_PALETTE;
  186951. row_info->channels = 1;
  186952. row_info->pixel_depth = row_info->bit_depth;
  186953. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  186954. }
  186955. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA &&
  186956. palette_lookup != NULL && row_info->bit_depth == 8)
  186957. {
  186958. int r, g, b, p;
  186959. sp = row;
  186960. dp = row;
  186961. for (i = 0; i < row_width; i++)
  186962. {
  186963. r = *sp++;
  186964. g = *sp++;
  186965. b = *sp++;
  186966. sp++;
  186967. p = (((r >> (8 - PNG_DITHER_RED_BITS)) &
  186968. ((1 << PNG_DITHER_RED_BITS) - 1)) <<
  186969. (PNG_DITHER_GREEN_BITS + PNG_DITHER_BLUE_BITS)) |
  186970. (((g >> (8 - PNG_DITHER_GREEN_BITS)) &
  186971. ((1 << PNG_DITHER_GREEN_BITS) - 1)) <<
  186972. (PNG_DITHER_BLUE_BITS)) |
  186973. ((b >> (8 - PNG_DITHER_BLUE_BITS)) &
  186974. ((1 << PNG_DITHER_BLUE_BITS) - 1));
  186975. *dp++ = palette_lookup[p];
  186976. }
  186977. row_info->color_type = PNG_COLOR_TYPE_PALETTE;
  186978. row_info->channels = 1;
  186979. row_info->pixel_depth = row_info->bit_depth;
  186980. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  186981. }
  186982. else if (row_info->color_type == PNG_COLOR_TYPE_PALETTE &&
  186983. dither_lookup && row_info->bit_depth == 8)
  186984. {
  186985. sp = row;
  186986. for (i = 0; i < row_width; i++, sp++)
  186987. {
  186988. *sp = dither_lookup[*sp];
  186989. }
  186990. }
  186991. }
  186992. }
  186993. #endif
  186994. #ifdef PNG_FLOATING_POINT_SUPPORTED
  186995. #if defined(PNG_READ_GAMMA_SUPPORTED)
  186996. static PNG_CONST int png_gamma_shift[] =
  186997. {0x10, 0x21, 0x42, 0x84, 0x110, 0x248, 0x550, 0xff0, 0x00};
  186998. /* We build the 8- or 16-bit gamma tables here. Note that for 16-bit
  186999. * tables, we don't make a full table if we are reducing to 8-bit in
  187000. * the future. Note also how the gamma_16 tables are segmented so that
  187001. * we don't need to allocate > 64K chunks for a full 16-bit table.
  187002. */
  187003. void /* PRIVATE */
  187004. png_build_gamma_table(png_structp png_ptr)
  187005. {
  187006. png_debug(1, "in png_build_gamma_table\n");
  187007. if (png_ptr->bit_depth <= 8)
  187008. {
  187009. int i;
  187010. double g;
  187011. if (png_ptr->screen_gamma > .000001)
  187012. g = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  187013. else
  187014. g = 1.0;
  187015. png_ptr->gamma_table = (png_bytep)png_malloc(png_ptr,
  187016. (png_uint_32)256);
  187017. for (i = 0; i < 256; i++)
  187018. {
  187019. png_ptr->gamma_table[i] = (png_byte)(pow((double)i / 255.0,
  187020. g) * 255.0 + .5);
  187021. }
  187022. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || \
  187023. defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  187024. if (png_ptr->transformations & ((PNG_BACKGROUND) | PNG_RGB_TO_GRAY))
  187025. {
  187026. g = 1.0 / (png_ptr->gamma);
  187027. png_ptr->gamma_to_1 = (png_bytep)png_malloc(png_ptr,
  187028. (png_uint_32)256);
  187029. for (i = 0; i < 256; i++)
  187030. {
  187031. png_ptr->gamma_to_1[i] = (png_byte)(pow((double)i / 255.0,
  187032. g) * 255.0 + .5);
  187033. }
  187034. png_ptr->gamma_from_1 = (png_bytep)png_malloc(png_ptr,
  187035. (png_uint_32)256);
  187036. if(png_ptr->screen_gamma > 0.000001)
  187037. g = 1.0 / png_ptr->screen_gamma;
  187038. else
  187039. g = png_ptr->gamma; /* probably doing rgb_to_gray */
  187040. for (i = 0; i < 256; i++)
  187041. {
  187042. png_ptr->gamma_from_1[i] = (png_byte)(pow((double)i / 255.0,
  187043. g) * 255.0 + .5);
  187044. }
  187045. }
  187046. #endif /* PNG_READ_BACKGROUND_SUPPORTED || PNG_RGB_TO_GRAY_SUPPORTED */
  187047. }
  187048. else
  187049. {
  187050. double g;
  187051. int i, j, shift, num;
  187052. int sig_bit;
  187053. png_uint_32 ig;
  187054. if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  187055. {
  187056. sig_bit = (int)png_ptr->sig_bit.red;
  187057. if ((int)png_ptr->sig_bit.green > sig_bit)
  187058. sig_bit = png_ptr->sig_bit.green;
  187059. if ((int)png_ptr->sig_bit.blue > sig_bit)
  187060. sig_bit = png_ptr->sig_bit.blue;
  187061. }
  187062. else
  187063. {
  187064. sig_bit = (int)png_ptr->sig_bit.gray;
  187065. }
  187066. if (sig_bit > 0)
  187067. shift = 16 - sig_bit;
  187068. else
  187069. shift = 0;
  187070. if (png_ptr->transformations & PNG_16_TO_8)
  187071. {
  187072. if (shift < (16 - PNG_MAX_GAMMA_8))
  187073. shift = (16 - PNG_MAX_GAMMA_8);
  187074. }
  187075. if (shift > 8)
  187076. shift = 8;
  187077. if (shift < 0)
  187078. shift = 0;
  187079. png_ptr->gamma_shift = (png_byte)shift;
  187080. num = (1 << (8 - shift));
  187081. if (png_ptr->screen_gamma > .000001)
  187082. g = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  187083. else
  187084. g = 1.0;
  187085. png_ptr->gamma_16_table = (png_uint_16pp)png_malloc(png_ptr,
  187086. (png_uint_32)(num * png_sizeof (png_uint_16p)));
  187087. if (png_ptr->transformations & (PNG_16_TO_8 | PNG_BACKGROUND))
  187088. {
  187089. double fin, fout;
  187090. png_uint_32 last, max;
  187091. for (i = 0; i < num; i++)
  187092. {
  187093. png_ptr->gamma_16_table[i] = (png_uint_16p)png_malloc(png_ptr,
  187094. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  187095. }
  187096. g = 1.0 / g;
  187097. last = 0;
  187098. for (i = 0; i < 256; i++)
  187099. {
  187100. fout = ((double)i + 0.5) / 256.0;
  187101. fin = pow(fout, g);
  187102. max = (png_uint_32)(fin * (double)((png_uint_32)num << 8));
  187103. while (last <= max)
  187104. {
  187105. png_ptr->gamma_16_table[(int)(last & (0xff >> shift))]
  187106. [(int)(last >> (8 - shift))] = (png_uint_16)(
  187107. (png_uint_16)i | ((png_uint_16)i << 8));
  187108. last++;
  187109. }
  187110. }
  187111. while (last < ((png_uint_32)num << 8))
  187112. {
  187113. png_ptr->gamma_16_table[(int)(last & (0xff >> shift))]
  187114. [(int)(last >> (8 - shift))] = (png_uint_16)65535L;
  187115. last++;
  187116. }
  187117. }
  187118. else
  187119. {
  187120. for (i = 0; i < num; i++)
  187121. {
  187122. png_ptr->gamma_16_table[i] = (png_uint_16p)png_malloc(png_ptr,
  187123. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  187124. ig = (((png_uint_32)i * (png_uint_32)png_gamma_shift[shift]) >> 4);
  187125. for (j = 0; j < 256; j++)
  187126. {
  187127. png_ptr->gamma_16_table[i][j] =
  187128. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  187129. 65535.0, g) * 65535.0 + .5);
  187130. }
  187131. }
  187132. }
  187133. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || \
  187134. defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  187135. if (png_ptr->transformations & (PNG_BACKGROUND | PNG_RGB_TO_GRAY))
  187136. {
  187137. g = 1.0 / (png_ptr->gamma);
  187138. png_ptr->gamma_16_to_1 = (png_uint_16pp)png_malloc(png_ptr,
  187139. (png_uint_32)(num * png_sizeof (png_uint_16p )));
  187140. for (i = 0; i < num; i++)
  187141. {
  187142. png_ptr->gamma_16_to_1[i] = (png_uint_16p)png_malloc(png_ptr,
  187143. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  187144. ig = (((png_uint_32)i *
  187145. (png_uint_32)png_gamma_shift[shift]) >> 4);
  187146. for (j = 0; j < 256; j++)
  187147. {
  187148. png_ptr->gamma_16_to_1[i][j] =
  187149. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  187150. 65535.0, g) * 65535.0 + .5);
  187151. }
  187152. }
  187153. if(png_ptr->screen_gamma > 0.000001)
  187154. g = 1.0 / png_ptr->screen_gamma;
  187155. else
  187156. g = png_ptr->gamma; /* probably doing rgb_to_gray */
  187157. png_ptr->gamma_16_from_1 = (png_uint_16pp)png_malloc(png_ptr,
  187158. (png_uint_32)(num * png_sizeof (png_uint_16p)));
  187159. for (i = 0; i < num; i++)
  187160. {
  187161. png_ptr->gamma_16_from_1[i] = (png_uint_16p)png_malloc(png_ptr,
  187162. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  187163. ig = (((png_uint_32)i *
  187164. (png_uint_32)png_gamma_shift[shift]) >> 4);
  187165. for (j = 0; j < 256; j++)
  187166. {
  187167. png_ptr->gamma_16_from_1[i][j] =
  187168. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  187169. 65535.0, g) * 65535.0 + .5);
  187170. }
  187171. }
  187172. }
  187173. #endif /* PNG_READ_BACKGROUND_SUPPORTED || PNG_RGB_TO_GRAY_SUPPORTED */
  187174. }
  187175. }
  187176. #endif
  187177. /* To do: install integer version of png_build_gamma_table here */
  187178. #endif
  187179. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  187180. /* undoes intrapixel differencing */
  187181. void /* PRIVATE */
  187182. png_do_read_intrapixel(png_row_infop row_info, png_bytep row)
  187183. {
  187184. png_debug(1, "in png_do_read_intrapixel\n");
  187185. if (
  187186. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  187187. row != NULL && row_info != NULL &&
  187188. #endif
  187189. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  187190. {
  187191. int bytes_per_pixel;
  187192. png_uint_32 row_width = row_info->width;
  187193. if (row_info->bit_depth == 8)
  187194. {
  187195. png_bytep rp;
  187196. png_uint_32 i;
  187197. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  187198. bytes_per_pixel = 3;
  187199. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  187200. bytes_per_pixel = 4;
  187201. else
  187202. return;
  187203. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  187204. {
  187205. *(rp) = (png_byte)((256 + *rp + *(rp+1))&0xff);
  187206. *(rp+2) = (png_byte)((256 + *(rp+2) + *(rp+1))&0xff);
  187207. }
  187208. }
  187209. else if (row_info->bit_depth == 16)
  187210. {
  187211. png_bytep rp;
  187212. png_uint_32 i;
  187213. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  187214. bytes_per_pixel = 6;
  187215. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  187216. bytes_per_pixel = 8;
  187217. else
  187218. return;
  187219. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  187220. {
  187221. png_uint_32 s0 = (*(rp ) << 8) | *(rp+1);
  187222. png_uint_32 s1 = (*(rp+2) << 8) | *(rp+3);
  187223. png_uint_32 s2 = (*(rp+4) << 8) | *(rp+5);
  187224. png_uint_32 red = (png_uint_32)((s0+s1+65536L) & 0xffffL);
  187225. png_uint_32 blue = (png_uint_32)((s2+s1+65536L) & 0xffffL);
  187226. *(rp ) = (png_byte)((red >> 8) & 0xff);
  187227. *(rp+1) = (png_byte)(red & 0xff);
  187228. *(rp+4) = (png_byte)((blue >> 8) & 0xff);
  187229. *(rp+5) = (png_byte)(blue & 0xff);
  187230. }
  187231. }
  187232. }
  187233. }
  187234. #endif /* PNG_MNG_FEATURES_SUPPORTED */
  187235. #endif /* PNG_READ_SUPPORTED */
  187236. /********* End of inlined file: pngrtran.c *********/
  187237. /********* Start of inlined file: pngrutil.c *********/
  187238. /* pngrutil.c - utilities to read a PNG file
  187239. *
  187240. * Last changed in libpng 1.2.21 [October 4, 2007]
  187241. * For conditions of distribution and use, see copyright notice in png.h
  187242. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  187243. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  187244. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  187245. *
  187246. * This file contains routines that are only called from within
  187247. * libpng itself during the course of reading an image.
  187248. */
  187249. #define PNG_INTERNAL
  187250. #if defined(PNG_READ_SUPPORTED)
  187251. #if defined(_WIN32_WCE) && (_WIN32_WCE<0x500)
  187252. # define WIN32_WCE_OLD
  187253. #endif
  187254. #ifdef PNG_FLOATING_POINT_SUPPORTED
  187255. # if defined(WIN32_WCE_OLD)
  187256. /* strtod() function is not supported on WindowsCE */
  187257. __inline double png_strtod(png_structp png_ptr, PNG_CONST char *nptr, char **endptr)
  187258. {
  187259. double result = 0;
  187260. int len;
  187261. wchar_t *str, *end;
  187262. len = MultiByteToWideChar(CP_ACP, 0, nptr, -1, NULL, 0);
  187263. str = (wchar_t *)png_malloc(png_ptr, len * sizeof(wchar_t));
  187264. if ( NULL != str )
  187265. {
  187266. MultiByteToWideChar(CP_ACP, 0, nptr, -1, str, len);
  187267. result = wcstod(str, &end);
  187268. len = WideCharToMultiByte(CP_ACP, 0, end, -1, NULL, 0, NULL, NULL);
  187269. *endptr = (char *)nptr + (png_strlen(nptr) - len + 1);
  187270. png_free(png_ptr, str);
  187271. }
  187272. return result;
  187273. }
  187274. # else
  187275. # define png_strtod(p,a,b) strtod(a,b)
  187276. # endif
  187277. #endif
  187278. png_uint_32 PNGAPI
  187279. png_get_uint_31(png_structp png_ptr, png_bytep buf)
  187280. {
  187281. png_uint_32 i = png_get_uint_32(buf);
  187282. if (i > PNG_UINT_31_MAX)
  187283. png_error(png_ptr, "PNG unsigned integer out of range.");
  187284. return (i);
  187285. }
  187286. #ifndef PNG_READ_BIG_ENDIAN_SUPPORTED
  187287. /* Grab an unsigned 32-bit integer from a buffer in big-endian format. */
  187288. png_uint_32 PNGAPI
  187289. png_get_uint_32(png_bytep buf)
  187290. {
  187291. png_uint_32 i = ((png_uint_32)(*buf) << 24) +
  187292. ((png_uint_32)(*(buf + 1)) << 16) +
  187293. ((png_uint_32)(*(buf + 2)) << 8) +
  187294. (png_uint_32)(*(buf + 3));
  187295. return (i);
  187296. }
  187297. /* Grab a signed 32-bit integer from a buffer in big-endian format. The
  187298. * data is stored in the PNG file in two's complement format, and it is
  187299. * assumed that the machine format for signed integers is the same. */
  187300. png_int_32 PNGAPI
  187301. png_get_int_32(png_bytep buf)
  187302. {
  187303. png_int_32 i = ((png_int_32)(*buf) << 24) +
  187304. ((png_int_32)(*(buf + 1)) << 16) +
  187305. ((png_int_32)(*(buf + 2)) << 8) +
  187306. (png_int_32)(*(buf + 3));
  187307. return (i);
  187308. }
  187309. /* Grab an unsigned 16-bit integer from a buffer in big-endian format. */
  187310. png_uint_16 PNGAPI
  187311. png_get_uint_16(png_bytep buf)
  187312. {
  187313. png_uint_16 i = (png_uint_16)(((png_uint_16)(*buf) << 8) +
  187314. (png_uint_16)(*(buf + 1)));
  187315. return (i);
  187316. }
  187317. #endif /* PNG_READ_BIG_ENDIAN_SUPPORTED */
  187318. /* Read data, and (optionally) run it through the CRC. */
  187319. void /* PRIVATE */
  187320. png_crc_read(png_structp png_ptr, png_bytep buf, png_size_t length)
  187321. {
  187322. if(png_ptr == NULL) return;
  187323. png_read_data(png_ptr, buf, length);
  187324. png_calculate_crc(png_ptr, buf, length);
  187325. }
  187326. /* Optionally skip data and then check the CRC. Depending on whether we
  187327. are reading a ancillary or critical chunk, and how the program has set
  187328. things up, we may calculate the CRC on the data and print a message.
  187329. Returns '1' if there was a CRC error, '0' otherwise. */
  187330. int /* PRIVATE */
  187331. png_crc_finish(png_structp png_ptr, png_uint_32 skip)
  187332. {
  187333. png_size_t i;
  187334. png_size_t istop = png_ptr->zbuf_size;
  187335. for (i = (png_size_t)skip; i > istop; i -= istop)
  187336. {
  187337. png_crc_read(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  187338. }
  187339. if (i)
  187340. {
  187341. png_crc_read(png_ptr, png_ptr->zbuf, i);
  187342. }
  187343. if (png_crc_error(png_ptr))
  187344. {
  187345. if (((png_ptr->chunk_name[0] & 0x20) && /* Ancillary */
  187346. !(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN)) ||
  187347. (!(png_ptr->chunk_name[0] & 0x20) && /* Critical */
  187348. (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_USE)))
  187349. {
  187350. png_chunk_warning(png_ptr, "CRC error");
  187351. }
  187352. else
  187353. {
  187354. png_chunk_error(png_ptr, "CRC error");
  187355. }
  187356. return (1);
  187357. }
  187358. return (0);
  187359. }
  187360. /* Compare the CRC stored in the PNG file with that calculated by libpng from
  187361. the data it has read thus far. */
  187362. int /* PRIVATE */
  187363. png_crc_error(png_structp png_ptr)
  187364. {
  187365. png_byte crc_bytes[4];
  187366. png_uint_32 crc;
  187367. int need_crc = 1;
  187368. if (png_ptr->chunk_name[0] & 0x20) /* ancillary */
  187369. {
  187370. if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_MASK) ==
  187371. (PNG_FLAG_CRC_ANCILLARY_USE | PNG_FLAG_CRC_ANCILLARY_NOWARN))
  187372. need_crc = 0;
  187373. }
  187374. else /* critical */
  187375. {
  187376. if (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_IGNORE)
  187377. need_crc = 0;
  187378. }
  187379. png_read_data(png_ptr, crc_bytes, 4);
  187380. if (need_crc)
  187381. {
  187382. crc = png_get_uint_32(crc_bytes);
  187383. return ((int)(crc != png_ptr->crc));
  187384. }
  187385. else
  187386. return (0);
  187387. }
  187388. #if defined(PNG_READ_zTXt_SUPPORTED) || defined(PNG_READ_iTXt_SUPPORTED) || \
  187389. defined(PNG_READ_iCCP_SUPPORTED)
  187390. /*
  187391. * Decompress trailing data in a chunk. The assumption is that chunkdata
  187392. * points at an allocated area holding the contents of a chunk with a
  187393. * trailing compressed part. What we get back is an allocated area
  187394. * holding the original prefix part and an uncompressed version of the
  187395. * trailing part (the malloc area passed in is freed).
  187396. */
  187397. png_charp /* PRIVATE */
  187398. png_decompress_chunk(png_structp png_ptr, int comp_type,
  187399. png_charp chunkdata, png_size_t chunklength,
  187400. png_size_t prefix_size, png_size_t *newlength)
  187401. {
  187402. static PNG_CONST char msg[] = "Error decoding compressed text";
  187403. png_charp text;
  187404. png_size_t text_size;
  187405. if (comp_type == PNG_COMPRESSION_TYPE_BASE)
  187406. {
  187407. int ret = Z_OK;
  187408. png_ptr->zstream.next_in = (png_bytep)(chunkdata + prefix_size);
  187409. png_ptr->zstream.avail_in = (uInt)(chunklength - prefix_size);
  187410. png_ptr->zstream.next_out = png_ptr->zbuf;
  187411. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  187412. text_size = 0;
  187413. text = NULL;
  187414. while (png_ptr->zstream.avail_in)
  187415. {
  187416. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  187417. if (ret != Z_OK && ret != Z_STREAM_END)
  187418. {
  187419. if (png_ptr->zstream.msg != NULL)
  187420. png_warning(png_ptr, png_ptr->zstream.msg);
  187421. else
  187422. png_warning(png_ptr, msg);
  187423. inflateReset(&png_ptr->zstream);
  187424. png_ptr->zstream.avail_in = 0;
  187425. if (text == NULL)
  187426. {
  187427. text_size = prefix_size + png_sizeof(msg) + 1;
  187428. text = (png_charp)png_malloc_warn(png_ptr, text_size);
  187429. if (text == NULL)
  187430. {
  187431. png_free(png_ptr,chunkdata);
  187432. png_error(png_ptr,"Not enough memory to decompress chunk");
  187433. }
  187434. png_memcpy(text, chunkdata, prefix_size);
  187435. }
  187436. text[text_size - 1] = 0x00;
  187437. /* Copy what we can of the error message into the text chunk */
  187438. text_size = (png_size_t)(chunklength - (text - chunkdata) - 1);
  187439. text_size = png_sizeof(msg) > text_size ? text_size :
  187440. png_sizeof(msg);
  187441. png_memcpy(text + prefix_size, msg, text_size + 1);
  187442. break;
  187443. }
  187444. if (!png_ptr->zstream.avail_out || ret == Z_STREAM_END)
  187445. {
  187446. if (text == NULL)
  187447. {
  187448. text_size = prefix_size +
  187449. png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  187450. text = (png_charp)png_malloc_warn(png_ptr, text_size + 1);
  187451. if (text == NULL)
  187452. {
  187453. png_free(png_ptr,chunkdata);
  187454. png_error(png_ptr,"Not enough memory to decompress chunk.");
  187455. }
  187456. png_memcpy(text + prefix_size, png_ptr->zbuf,
  187457. text_size - prefix_size);
  187458. png_memcpy(text, chunkdata, prefix_size);
  187459. *(text + text_size) = 0x00;
  187460. }
  187461. else
  187462. {
  187463. png_charp tmp;
  187464. tmp = text;
  187465. text = (png_charp)png_malloc_warn(png_ptr,
  187466. (png_uint_32)(text_size +
  187467. png_ptr->zbuf_size - png_ptr->zstream.avail_out + 1));
  187468. if (text == NULL)
  187469. {
  187470. png_free(png_ptr, tmp);
  187471. png_free(png_ptr, chunkdata);
  187472. png_error(png_ptr,"Not enough memory to decompress chunk..");
  187473. }
  187474. png_memcpy(text, tmp, text_size);
  187475. png_free(png_ptr, tmp);
  187476. png_memcpy(text + text_size, png_ptr->zbuf,
  187477. (png_ptr->zbuf_size - png_ptr->zstream.avail_out));
  187478. text_size += png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  187479. *(text + text_size) = 0x00;
  187480. }
  187481. if (ret == Z_STREAM_END)
  187482. break;
  187483. else
  187484. {
  187485. png_ptr->zstream.next_out = png_ptr->zbuf;
  187486. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  187487. }
  187488. }
  187489. }
  187490. if (ret != Z_STREAM_END)
  187491. {
  187492. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  187493. char umsg[52];
  187494. if (ret == Z_BUF_ERROR)
  187495. png_snprintf(umsg, 52,
  187496. "Buffer error in compressed datastream in %s chunk",
  187497. png_ptr->chunk_name);
  187498. else if (ret == Z_DATA_ERROR)
  187499. png_snprintf(umsg, 52,
  187500. "Data error in compressed datastream in %s chunk",
  187501. png_ptr->chunk_name);
  187502. else
  187503. png_snprintf(umsg, 52,
  187504. "Incomplete compressed datastream in %s chunk",
  187505. png_ptr->chunk_name);
  187506. png_warning(png_ptr, umsg);
  187507. #else
  187508. png_warning(png_ptr,
  187509. "Incomplete compressed datastream in chunk other than IDAT");
  187510. #endif
  187511. text_size=prefix_size;
  187512. if (text == NULL)
  187513. {
  187514. text = (png_charp)png_malloc_warn(png_ptr, text_size+1);
  187515. if (text == NULL)
  187516. {
  187517. png_free(png_ptr, chunkdata);
  187518. png_error(png_ptr,"Not enough memory for text.");
  187519. }
  187520. png_memcpy(text, chunkdata, prefix_size);
  187521. }
  187522. *(text + text_size) = 0x00;
  187523. }
  187524. inflateReset(&png_ptr->zstream);
  187525. png_ptr->zstream.avail_in = 0;
  187526. png_free(png_ptr, chunkdata);
  187527. chunkdata = text;
  187528. *newlength=text_size;
  187529. }
  187530. else /* if (comp_type != PNG_COMPRESSION_TYPE_BASE) */
  187531. {
  187532. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  187533. char umsg[50];
  187534. png_snprintf(umsg, 50,
  187535. "Unknown zTXt compression type %d", comp_type);
  187536. png_warning(png_ptr, umsg);
  187537. #else
  187538. png_warning(png_ptr, "Unknown zTXt compression type");
  187539. #endif
  187540. *(chunkdata + prefix_size) = 0x00;
  187541. *newlength=prefix_size;
  187542. }
  187543. return chunkdata;
  187544. }
  187545. #endif
  187546. /* read and check the IDHR chunk */
  187547. void /* PRIVATE */
  187548. png_handle_IHDR(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  187549. {
  187550. png_byte buf[13];
  187551. png_uint_32 width, height;
  187552. int bit_depth, color_type, compression_type, filter_type;
  187553. int interlace_type;
  187554. png_debug(1, "in png_handle_IHDR\n");
  187555. if (png_ptr->mode & PNG_HAVE_IHDR)
  187556. png_error(png_ptr, "Out of place IHDR");
  187557. /* check the length */
  187558. if (length != 13)
  187559. png_error(png_ptr, "Invalid IHDR chunk");
  187560. png_ptr->mode |= PNG_HAVE_IHDR;
  187561. png_crc_read(png_ptr, buf, 13);
  187562. png_crc_finish(png_ptr, 0);
  187563. width = png_get_uint_31(png_ptr, buf);
  187564. height = png_get_uint_31(png_ptr, buf + 4);
  187565. bit_depth = buf[8];
  187566. color_type = buf[9];
  187567. compression_type = buf[10];
  187568. filter_type = buf[11];
  187569. interlace_type = buf[12];
  187570. /* set internal variables */
  187571. png_ptr->width = width;
  187572. png_ptr->height = height;
  187573. png_ptr->bit_depth = (png_byte)bit_depth;
  187574. png_ptr->interlaced = (png_byte)interlace_type;
  187575. png_ptr->color_type = (png_byte)color_type;
  187576. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  187577. png_ptr->filter_type = (png_byte)filter_type;
  187578. #endif
  187579. png_ptr->compression_type = (png_byte)compression_type;
  187580. /* find number of channels */
  187581. switch (png_ptr->color_type)
  187582. {
  187583. case PNG_COLOR_TYPE_GRAY:
  187584. case PNG_COLOR_TYPE_PALETTE:
  187585. png_ptr->channels = 1;
  187586. break;
  187587. case PNG_COLOR_TYPE_RGB:
  187588. png_ptr->channels = 3;
  187589. break;
  187590. case PNG_COLOR_TYPE_GRAY_ALPHA:
  187591. png_ptr->channels = 2;
  187592. break;
  187593. case PNG_COLOR_TYPE_RGB_ALPHA:
  187594. png_ptr->channels = 4;
  187595. break;
  187596. }
  187597. /* set up other useful info */
  187598. png_ptr->pixel_depth = (png_byte)(png_ptr->bit_depth *
  187599. png_ptr->channels);
  187600. png_ptr->rowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,png_ptr->width);
  187601. png_debug1(3,"bit_depth = %d\n", png_ptr->bit_depth);
  187602. png_debug1(3,"channels = %d\n", png_ptr->channels);
  187603. png_debug1(3,"rowbytes = %lu\n", png_ptr->rowbytes);
  187604. png_set_IHDR(png_ptr, info_ptr, width, height, bit_depth,
  187605. color_type, interlace_type, compression_type, filter_type);
  187606. }
  187607. /* read and check the palette */
  187608. void /* PRIVATE */
  187609. png_handle_PLTE(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  187610. {
  187611. png_color palette[PNG_MAX_PALETTE_LENGTH];
  187612. int num, i;
  187613. #ifndef PNG_NO_POINTER_INDEXING
  187614. png_colorp pal_ptr;
  187615. #endif
  187616. png_debug(1, "in png_handle_PLTE\n");
  187617. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  187618. png_error(png_ptr, "Missing IHDR before PLTE");
  187619. else if (png_ptr->mode & PNG_HAVE_IDAT)
  187620. {
  187621. png_warning(png_ptr, "Invalid PLTE after IDAT");
  187622. png_crc_finish(png_ptr, length);
  187623. return;
  187624. }
  187625. else if (png_ptr->mode & PNG_HAVE_PLTE)
  187626. png_error(png_ptr, "Duplicate PLTE chunk");
  187627. png_ptr->mode |= PNG_HAVE_PLTE;
  187628. if (!(png_ptr->color_type&PNG_COLOR_MASK_COLOR))
  187629. {
  187630. png_warning(png_ptr,
  187631. "Ignoring PLTE chunk in grayscale PNG");
  187632. png_crc_finish(png_ptr, length);
  187633. return;
  187634. }
  187635. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  187636. if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE)
  187637. {
  187638. png_crc_finish(png_ptr, length);
  187639. return;
  187640. }
  187641. #endif
  187642. if (length > 3*PNG_MAX_PALETTE_LENGTH || length % 3)
  187643. {
  187644. if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE)
  187645. {
  187646. png_warning(png_ptr, "Invalid palette chunk");
  187647. png_crc_finish(png_ptr, length);
  187648. return;
  187649. }
  187650. else
  187651. {
  187652. png_error(png_ptr, "Invalid palette chunk");
  187653. }
  187654. }
  187655. num = (int)length / 3;
  187656. #ifndef PNG_NO_POINTER_INDEXING
  187657. for (i = 0, pal_ptr = palette; i < num; i++, pal_ptr++)
  187658. {
  187659. png_byte buf[3];
  187660. png_crc_read(png_ptr, buf, 3);
  187661. pal_ptr->red = buf[0];
  187662. pal_ptr->green = buf[1];
  187663. pal_ptr->blue = buf[2];
  187664. }
  187665. #else
  187666. for (i = 0; i < num; i++)
  187667. {
  187668. png_byte buf[3];
  187669. png_crc_read(png_ptr, buf, 3);
  187670. /* don't depend upon png_color being any order */
  187671. palette[i].red = buf[0];
  187672. palette[i].green = buf[1];
  187673. palette[i].blue = buf[2];
  187674. }
  187675. #endif
  187676. /* If we actually NEED the PLTE chunk (ie for a paletted image), we do
  187677. whatever the normal CRC configuration tells us. However, if we
  187678. have an RGB image, the PLTE can be considered ancillary, so
  187679. we will act as though it is. */
  187680. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  187681. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  187682. #endif
  187683. {
  187684. png_crc_finish(png_ptr, 0);
  187685. }
  187686. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  187687. else if (png_crc_error(png_ptr)) /* Only if we have a CRC error */
  187688. {
  187689. /* If we don't want to use the data from an ancillary chunk,
  187690. we have two options: an error abort, or a warning and we
  187691. ignore the data in this chunk (which should be OK, since
  187692. it's considered ancillary for a RGB or RGBA image). */
  187693. if (!(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_USE))
  187694. {
  187695. if (png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN)
  187696. {
  187697. png_chunk_error(png_ptr, "CRC error");
  187698. }
  187699. else
  187700. {
  187701. png_chunk_warning(png_ptr, "CRC error");
  187702. return;
  187703. }
  187704. }
  187705. /* Otherwise, we (optionally) emit a warning and use the chunk. */
  187706. else if (!(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN))
  187707. {
  187708. png_chunk_warning(png_ptr, "CRC error");
  187709. }
  187710. }
  187711. #endif
  187712. png_set_PLTE(png_ptr, info_ptr, palette, num);
  187713. #if defined(PNG_READ_tRNS_SUPPORTED)
  187714. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  187715. {
  187716. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  187717. {
  187718. if (png_ptr->num_trans > (png_uint_16)num)
  187719. {
  187720. png_warning(png_ptr, "Truncating incorrect tRNS chunk length");
  187721. png_ptr->num_trans = (png_uint_16)num;
  187722. }
  187723. if (info_ptr->num_trans > (png_uint_16)num)
  187724. {
  187725. png_warning(png_ptr, "Truncating incorrect info tRNS chunk length");
  187726. info_ptr->num_trans = (png_uint_16)num;
  187727. }
  187728. }
  187729. }
  187730. #endif
  187731. }
  187732. void /* PRIVATE */
  187733. png_handle_IEND(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  187734. {
  187735. png_debug(1, "in png_handle_IEND\n");
  187736. if (!(png_ptr->mode & PNG_HAVE_IHDR) || !(png_ptr->mode & PNG_HAVE_IDAT))
  187737. {
  187738. png_error(png_ptr, "No image in file");
  187739. }
  187740. png_ptr->mode |= (PNG_AFTER_IDAT | PNG_HAVE_IEND);
  187741. if (length != 0)
  187742. {
  187743. png_warning(png_ptr, "Incorrect IEND chunk length");
  187744. }
  187745. png_crc_finish(png_ptr, length);
  187746. info_ptr =info_ptr; /* quiet compiler warnings about unused info_ptr */
  187747. }
  187748. #if defined(PNG_READ_gAMA_SUPPORTED)
  187749. void /* PRIVATE */
  187750. png_handle_gAMA(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  187751. {
  187752. png_fixed_point igamma;
  187753. #ifdef PNG_FLOATING_POINT_SUPPORTED
  187754. float file_gamma;
  187755. #endif
  187756. png_byte buf[4];
  187757. png_debug(1, "in png_handle_gAMA\n");
  187758. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  187759. png_error(png_ptr, "Missing IHDR before gAMA");
  187760. else if (png_ptr->mode & PNG_HAVE_IDAT)
  187761. {
  187762. png_warning(png_ptr, "Invalid gAMA after IDAT");
  187763. png_crc_finish(png_ptr, length);
  187764. return;
  187765. }
  187766. else if (png_ptr->mode & PNG_HAVE_PLTE)
  187767. /* Should be an error, but we can cope with it */
  187768. png_warning(png_ptr, "Out of place gAMA chunk");
  187769. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  187770. #if defined(PNG_READ_sRGB_SUPPORTED)
  187771. && !(info_ptr->valid & PNG_INFO_sRGB)
  187772. #endif
  187773. )
  187774. {
  187775. png_warning(png_ptr, "Duplicate gAMA chunk");
  187776. png_crc_finish(png_ptr, length);
  187777. return;
  187778. }
  187779. if (length != 4)
  187780. {
  187781. png_warning(png_ptr, "Incorrect gAMA chunk length");
  187782. png_crc_finish(png_ptr, length);
  187783. return;
  187784. }
  187785. png_crc_read(png_ptr, buf, 4);
  187786. if (png_crc_finish(png_ptr, 0))
  187787. return;
  187788. igamma = (png_fixed_point)png_get_uint_32(buf);
  187789. /* check for zero gamma */
  187790. if (igamma == 0)
  187791. {
  187792. png_warning(png_ptr,
  187793. "Ignoring gAMA chunk with gamma=0");
  187794. return;
  187795. }
  187796. #if defined(PNG_READ_sRGB_SUPPORTED)
  187797. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB))
  187798. if (PNG_OUT_OF_RANGE(igamma, 45500L, 500))
  187799. {
  187800. png_warning(png_ptr,
  187801. "Ignoring incorrect gAMA value when sRGB is also present");
  187802. #ifndef PNG_NO_CONSOLE_IO
  187803. fprintf(stderr, "gamma = (%d/100000)\n", (int)igamma);
  187804. #endif
  187805. return;
  187806. }
  187807. #endif /* PNG_READ_sRGB_SUPPORTED */
  187808. #ifdef PNG_FLOATING_POINT_SUPPORTED
  187809. file_gamma = (float)igamma / (float)100000.0;
  187810. # ifdef PNG_READ_GAMMA_SUPPORTED
  187811. png_ptr->gamma = file_gamma;
  187812. # endif
  187813. png_set_gAMA(png_ptr, info_ptr, file_gamma);
  187814. #endif
  187815. #ifdef PNG_FIXED_POINT_SUPPORTED
  187816. png_set_gAMA_fixed(png_ptr, info_ptr, igamma);
  187817. #endif
  187818. }
  187819. #endif
  187820. #if defined(PNG_READ_sBIT_SUPPORTED)
  187821. void /* PRIVATE */
  187822. png_handle_sBIT(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  187823. {
  187824. png_size_t truelen;
  187825. png_byte buf[4];
  187826. png_debug(1, "in png_handle_sBIT\n");
  187827. buf[0] = buf[1] = buf[2] = buf[3] = 0;
  187828. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  187829. png_error(png_ptr, "Missing IHDR before sBIT");
  187830. else if (png_ptr->mode & PNG_HAVE_IDAT)
  187831. {
  187832. png_warning(png_ptr, "Invalid sBIT after IDAT");
  187833. png_crc_finish(png_ptr, length);
  187834. return;
  187835. }
  187836. else if (png_ptr->mode & PNG_HAVE_PLTE)
  187837. {
  187838. /* Should be an error, but we can cope with it */
  187839. png_warning(png_ptr, "Out of place sBIT chunk");
  187840. }
  187841. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sBIT))
  187842. {
  187843. png_warning(png_ptr, "Duplicate sBIT chunk");
  187844. png_crc_finish(png_ptr, length);
  187845. return;
  187846. }
  187847. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  187848. truelen = 3;
  187849. else
  187850. truelen = (png_size_t)png_ptr->channels;
  187851. if (length != truelen || length > 4)
  187852. {
  187853. png_warning(png_ptr, "Incorrect sBIT chunk length");
  187854. png_crc_finish(png_ptr, length);
  187855. return;
  187856. }
  187857. png_crc_read(png_ptr, buf, truelen);
  187858. if (png_crc_finish(png_ptr, 0))
  187859. return;
  187860. if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  187861. {
  187862. png_ptr->sig_bit.red = buf[0];
  187863. png_ptr->sig_bit.green = buf[1];
  187864. png_ptr->sig_bit.blue = buf[2];
  187865. png_ptr->sig_bit.alpha = buf[3];
  187866. }
  187867. else
  187868. {
  187869. png_ptr->sig_bit.gray = buf[0];
  187870. png_ptr->sig_bit.red = buf[0];
  187871. png_ptr->sig_bit.green = buf[0];
  187872. png_ptr->sig_bit.blue = buf[0];
  187873. png_ptr->sig_bit.alpha = buf[1];
  187874. }
  187875. png_set_sBIT(png_ptr, info_ptr, &(png_ptr->sig_bit));
  187876. }
  187877. #endif
  187878. #if defined(PNG_READ_cHRM_SUPPORTED)
  187879. void /* PRIVATE */
  187880. png_handle_cHRM(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  187881. {
  187882. png_byte buf[4];
  187883. #ifdef PNG_FLOATING_POINT_SUPPORTED
  187884. float white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y;
  187885. #endif
  187886. png_fixed_point int_x_white, int_y_white, int_x_red, int_y_red, int_x_green,
  187887. int_y_green, int_x_blue, int_y_blue;
  187888. png_uint_32 uint_x, uint_y;
  187889. png_debug(1, "in png_handle_cHRM\n");
  187890. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  187891. png_error(png_ptr, "Missing IHDR before cHRM");
  187892. else if (png_ptr->mode & PNG_HAVE_IDAT)
  187893. {
  187894. png_warning(png_ptr, "Invalid cHRM after IDAT");
  187895. png_crc_finish(png_ptr, length);
  187896. return;
  187897. }
  187898. else if (png_ptr->mode & PNG_HAVE_PLTE)
  187899. /* Should be an error, but we can cope with it */
  187900. png_warning(png_ptr, "Missing PLTE before cHRM");
  187901. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM)
  187902. #if defined(PNG_READ_sRGB_SUPPORTED)
  187903. && !(info_ptr->valid & PNG_INFO_sRGB)
  187904. #endif
  187905. )
  187906. {
  187907. png_warning(png_ptr, "Duplicate cHRM chunk");
  187908. png_crc_finish(png_ptr, length);
  187909. return;
  187910. }
  187911. if (length != 32)
  187912. {
  187913. png_warning(png_ptr, "Incorrect cHRM chunk length");
  187914. png_crc_finish(png_ptr, length);
  187915. return;
  187916. }
  187917. png_crc_read(png_ptr, buf, 4);
  187918. uint_x = png_get_uint_32(buf);
  187919. png_crc_read(png_ptr, buf, 4);
  187920. uint_y = png_get_uint_32(buf);
  187921. if (uint_x > 80000L || uint_y > 80000L ||
  187922. uint_x + uint_y > 100000L)
  187923. {
  187924. png_warning(png_ptr, "Invalid cHRM white point");
  187925. png_crc_finish(png_ptr, 24);
  187926. return;
  187927. }
  187928. int_x_white = (png_fixed_point)uint_x;
  187929. int_y_white = (png_fixed_point)uint_y;
  187930. png_crc_read(png_ptr, buf, 4);
  187931. uint_x = png_get_uint_32(buf);
  187932. png_crc_read(png_ptr, buf, 4);
  187933. uint_y = png_get_uint_32(buf);
  187934. if (uint_x + uint_y > 100000L)
  187935. {
  187936. png_warning(png_ptr, "Invalid cHRM red point");
  187937. png_crc_finish(png_ptr, 16);
  187938. return;
  187939. }
  187940. int_x_red = (png_fixed_point)uint_x;
  187941. int_y_red = (png_fixed_point)uint_y;
  187942. png_crc_read(png_ptr, buf, 4);
  187943. uint_x = png_get_uint_32(buf);
  187944. png_crc_read(png_ptr, buf, 4);
  187945. uint_y = png_get_uint_32(buf);
  187946. if (uint_x + uint_y > 100000L)
  187947. {
  187948. png_warning(png_ptr, "Invalid cHRM green point");
  187949. png_crc_finish(png_ptr, 8);
  187950. return;
  187951. }
  187952. int_x_green = (png_fixed_point)uint_x;
  187953. int_y_green = (png_fixed_point)uint_y;
  187954. png_crc_read(png_ptr, buf, 4);
  187955. uint_x = png_get_uint_32(buf);
  187956. png_crc_read(png_ptr, buf, 4);
  187957. uint_y = png_get_uint_32(buf);
  187958. if (uint_x + uint_y > 100000L)
  187959. {
  187960. png_warning(png_ptr, "Invalid cHRM blue point");
  187961. png_crc_finish(png_ptr, 0);
  187962. return;
  187963. }
  187964. int_x_blue = (png_fixed_point)uint_x;
  187965. int_y_blue = (png_fixed_point)uint_y;
  187966. #ifdef PNG_FLOATING_POINT_SUPPORTED
  187967. white_x = (float)int_x_white / (float)100000.0;
  187968. white_y = (float)int_y_white / (float)100000.0;
  187969. red_x = (float)int_x_red / (float)100000.0;
  187970. red_y = (float)int_y_red / (float)100000.0;
  187971. green_x = (float)int_x_green / (float)100000.0;
  187972. green_y = (float)int_y_green / (float)100000.0;
  187973. blue_x = (float)int_x_blue / (float)100000.0;
  187974. blue_y = (float)int_y_blue / (float)100000.0;
  187975. #endif
  187976. #if defined(PNG_READ_sRGB_SUPPORTED)
  187977. if ((info_ptr != NULL) && (info_ptr->valid & PNG_INFO_sRGB))
  187978. {
  187979. if (PNG_OUT_OF_RANGE(int_x_white, 31270, 1000) ||
  187980. PNG_OUT_OF_RANGE(int_y_white, 32900, 1000) ||
  187981. PNG_OUT_OF_RANGE(int_x_red, 64000L, 1000) ||
  187982. PNG_OUT_OF_RANGE(int_y_red, 33000, 1000) ||
  187983. PNG_OUT_OF_RANGE(int_x_green, 30000, 1000) ||
  187984. PNG_OUT_OF_RANGE(int_y_green, 60000L, 1000) ||
  187985. PNG_OUT_OF_RANGE(int_x_blue, 15000, 1000) ||
  187986. PNG_OUT_OF_RANGE(int_y_blue, 6000, 1000))
  187987. {
  187988. png_warning(png_ptr,
  187989. "Ignoring incorrect cHRM value when sRGB is also present");
  187990. #ifndef PNG_NO_CONSOLE_IO
  187991. #ifdef PNG_FLOATING_POINT_SUPPORTED
  187992. fprintf(stderr,"wx=%f, wy=%f, rx=%f, ry=%f\n",
  187993. white_x, white_y, red_x, red_y);
  187994. fprintf(stderr,"gx=%f, gy=%f, bx=%f, by=%f\n",
  187995. green_x, green_y, blue_x, blue_y);
  187996. #else
  187997. fprintf(stderr,"wx=%ld, wy=%ld, rx=%ld, ry=%ld\n",
  187998. int_x_white, int_y_white, int_x_red, int_y_red);
  187999. fprintf(stderr,"gx=%ld, gy=%ld, bx=%ld, by=%ld\n",
  188000. int_x_green, int_y_green, int_x_blue, int_y_blue);
  188001. #endif
  188002. #endif /* PNG_NO_CONSOLE_IO */
  188003. }
  188004. png_crc_finish(png_ptr, 0);
  188005. return;
  188006. }
  188007. #endif /* PNG_READ_sRGB_SUPPORTED */
  188008. #ifdef PNG_FLOATING_POINT_SUPPORTED
  188009. png_set_cHRM(png_ptr, info_ptr,
  188010. white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y);
  188011. #endif
  188012. #ifdef PNG_FIXED_POINT_SUPPORTED
  188013. png_set_cHRM_fixed(png_ptr, info_ptr,
  188014. int_x_white, int_y_white, int_x_red, int_y_red, int_x_green,
  188015. int_y_green, int_x_blue, int_y_blue);
  188016. #endif
  188017. if (png_crc_finish(png_ptr, 0))
  188018. return;
  188019. }
  188020. #endif
  188021. #if defined(PNG_READ_sRGB_SUPPORTED)
  188022. void /* PRIVATE */
  188023. png_handle_sRGB(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  188024. {
  188025. int intent;
  188026. png_byte buf[1];
  188027. png_debug(1, "in png_handle_sRGB\n");
  188028. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  188029. png_error(png_ptr, "Missing IHDR before sRGB");
  188030. else if (png_ptr->mode & PNG_HAVE_IDAT)
  188031. {
  188032. png_warning(png_ptr, "Invalid sRGB after IDAT");
  188033. png_crc_finish(png_ptr, length);
  188034. return;
  188035. }
  188036. else if (png_ptr->mode & PNG_HAVE_PLTE)
  188037. /* Should be an error, but we can cope with it */
  188038. png_warning(png_ptr, "Out of place sRGB chunk");
  188039. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB))
  188040. {
  188041. png_warning(png_ptr, "Duplicate sRGB chunk");
  188042. png_crc_finish(png_ptr, length);
  188043. return;
  188044. }
  188045. if (length != 1)
  188046. {
  188047. png_warning(png_ptr, "Incorrect sRGB chunk length");
  188048. png_crc_finish(png_ptr, length);
  188049. return;
  188050. }
  188051. png_crc_read(png_ptr, buf, 1);
  188052. if (png_crc_finish(png_ptr, 0))
  188053. return;
  188054. intent = buf[0];
  188055. /* check for bad intent */
  188056. if (intent >= PNG_sRGB_INTENT_LAST)
  188057. {
  188058. png_warning(png_ptr, "Unknown sRGB intent");
  188059. return;
  188060. }
  188061. #if defined(PNG_READ_gAMA_SUPPORTED) && defined(PNG_READ_GAMMA_SUPPORTED)
  188062. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA))
  188063. {
  188064. png_fixed_point igamma;
  188065. #ifdef PNG_FIXED_POINT_SUPPORTED
  188066. igamma=info_ptr->int_gamma;
  188067. #else
  188068. # ifdef PNG_FLOATING_POINT_SUPPORTED
  188069. igamma=(png_fixed_point)(info_ptr->gamma * 100000.);
  188070. # endif
  188071. #endif
  188072. if (PNG_OUT_OF_RANGE(igamma, 45500L, 500))
  188073. {
  188074. png_warning(png_ptr,
  188075. "Ignoring incorrect gAMA value when sRGB is also present");
  188076. #ifndef PNG_NO_CONSOLE_IO
  188077. # ifdef PNG_FIXED_POINT_SUPPORTED
  188078. fprintf(stderr,"incorrect gamma=(%d/100000)\n",(int)png_ptr->int_gamma);
  188079. # else
  188080. # ifdef PNG_FLOATING_POINT_SUPPORTED
  188081. fprintf(stderr,"incorrect gamma=%f\n",png_ptr->gamma);
  188082. # endif
  188083. # endif
  188084. #endif
  188085. }
  188086. }
  188087. #endif /* PNG_READ_gAMA_SUPPORTED */
  188088. #ifdef PNG_READ_cHRM_SUPPORTED
  188089. #ifdef PNG_FIXED_POINT_SUPPORTED
  188090. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  188091. if (PNG_OUT_OF_RANGE(info_ptr->int_x_white, 31270, 1000) ||
  188092. PNG_OUT_OF_RANGE(info_ptr->int_y_white, 32900, 1000) ||
  188093. PNG_OUT_OF_RANGE(info_ptr->int_x_red, 64000L, 1000) ||
  188094. PNG_OUT_OF_RANGE(info_ptr->int_y_red, 33000, 1000) ||
  188095. PNG_OUT_OF_RANGE(info_ptr->int_x_green, 30000, 1000) ||
  188096. PNG_OUT_OF_RANGE(info_ptr->int_y_green, 60000L, 1000) ||
  188097. PNG_OUT_OF_RANGE(info_ptr->int_x_blue, 15000, 1000) ||
  188098. PNG_OUT_OF_RANGE(info_ptr->int_y_blue, 6000, 1000))
  188099. {
  188100. png_warning(png_ptr,
  188101. "Ignoring incorrect cHRM value when sRGB is also present");
  188102. }
  188103. #endif /* PNG_FIXED_POINT_SUPPORTED */
  188104. #endif /* PNG_READ_cHRM_SUPPORTED */
  188105. png_set_sRGB_gAMA_and_cHRM(png_ptr, info_ptr, intent);
  188106. }
  188107. #endif /* PNG_READ_sRGB_SUPPORTED */
  188108. #if defined(PNG_READ_iCCP_SUPPORTED)
  188109. void /* PRIVATE */
  188110. png_handle_iCCP(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  188111. /* Note: this does not properly handle chunks that are > 64K under DOS */
  188112. {
  188113. png_charp chunkdata;
  188114. png_byte compression_type;
  188115. png_bytep pC;
  188116. png_charp profile;
  188117. png_uint_32 skip = 0;
  188118. png_uint_32 profile_size, profile_length;
  188119. png_size_t slength, prefix_length, data_length;
  188120. png_debug(1, "in png_handle_iCCP\n");
  188121. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  188122. png_error(png_ptr, "Missing IHDR before iCCP");
  188123. else if (png_ptr->mode & PNG_HAVE_IDAT)
  188124. {
  188125. png_warning(png_ptr, "Invalid iCCP after IDAT");
  188126. png_crc_finish(png_ptr, length);
  188127. return;
  188128. }
  188129. else if (png_ptr->mode & PNG_HAVE_PLTE)
  188130. /* Should be an error, but we can cope with it */
  188131. png_warning(png_ptr, "Out of place iCCP chunk");
  188132. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_iCCP))
  188133. {
  188134. png_warning(png_ptr, "Duplicate iCCP chunk");
  188135. png_crc_finish(png_ptr, length);
  188136. return;
  188137. }
  188138. #ifdef PNG_MAX_MALLOC_64K
  188139. if (length > (png_uint_32)65535L)
  188140. {
  188141. png_warning(png_ptr, "iCCP chunk too large to fit in memory");
  188142. skip = length - (png_uint_32)65535L;
  188143. length = (png_uint_32)65535L;
  188144. }
  188145. #endif
  188146. chunkdata = (png_charp)png_malloc(png_ptr, length + 1);
  188147. slength = (png_size_t)length;
  188148. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  188149. if (png_crc_finish(png_ptr, skip))
  188150. {
  188151. png_free(png_ptr, chunkdata);
  188152. return;
  188153. }
  188154. chunkdata[slength] = 0x00;
  188155. for (profile = chunkdata; *profile; profile++)
  188156. /* empty loop to find end of name */ ;
  188157. ++profile;
  188158. /* there should be at least one zero (the compression type byte)
  188159. following the separator, and we should be on it */
  188160. if ( profile >= chunkdata + slength - 1)
  188161. {
  188162. png_free(png_ptr, chunkdata);
  188163. png_warning(png_ptr, "Malformed iCCP chunk");
  188164. return;
  188165. }
  188166. /* compression_type should always be zero */
  188167. compression_type = *profile++;
  188168. if (compression_type)
  188169. {
  188170. png_warning(png_ptr, "Ignoring nonzero compression type in iCCP chunk");
  188171. compression_type=0x00; /* Reset it to zero (libpng-1.0.6 through 1.0.8
  188172. wrote nonzero) */
  188173. }
  188174. prefix_length = profile - chunkdata;
  188175. chunkdata = png_decompress_chunk(png_ptr, compression_type, chunkdata,
  188176. slength, prefix_length, &data_length);
  188177. profile_length = data_length - prefix_length;
  188178. if ( prefix_length > data_length || profile_length < 4)
  188179. {
  188180. png_free(png_ptr, chunkdata);
  188181. png_warning(png_ptr, "Profile size field missing from iCCP chunk");
  188182. return;
  188183. }
  188184. /* Check the profile_size recorded in the first 32 bits of the ICC profile */
  188185. pC = (png_bytep)(chunkdata+prefix_length);
  188186. profile_size = ((*(pC ))<<24) |
  188187. ((*(pC+1))<<16) |
  188188. ((*(pC+2))<< 8) |
  188189. ((*(pC+3)) );
  188190. if(profile_size < profile_length)
  188191. profile_length = profile_size;
  188192. if(profile_size > profile_length)
  188193. {
  188194. png_free(png_ptr, chunkdata);
  188195. png_warning(png_ptr, "Ignoring truncated iCCP profile.");
  188196. return;
  188197. }
  188198. png_set_iCCP(png_ptr, info_ptr, chunkdata, compression_type,
  188199. chunkdata + prefix_length, profile_length);
  188200. png_free(png_ptr, chunkdata);
  188201. }
  188202. #endif /* PNG_READ_iCCP_SUPPORTED */
  188203. #if defined(PNG_READ_sPLT_SUPPORTED)
  188204. void /* PRIVATE */
  188205. png_handle_sPLT(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  188206. /* Note: this does not properly handle chunks that are > 64K under DOS */
  188207. {
  188208. png_bytep chunkdata;
  188209. png_bytep entry_start;
  188210. png_sPLT_t new_palette;
  188211. #ifdef PNG_NO_POINTER_INDEXING
  188212. png_sPLT_entryp pp;
  188213. #endif
  188214. int data_length, entry_size, i;
  188215. png_uint_32 skip = 0;
  188216. png_size_t slength;
  188217. png_debug(1, "in png_handle_sPLT\n");
  188218. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  188219. png_error(png_ptr, "Missing IHDR before sPLT");
  188220. else if (png_ptr->mode & PNG_HAVE_IDAT)
  188221. {
  188222. png_warning(png_ptr, "Invalid sPLT after IDAT");
  188223. png_crc_finish(png_ptr, length);
  188224. return;
  188225. }
  188226. #ifdef PNG_MAX_MALLOC_64K
  188227. if (length > (png_uint_32)65535L)
  188228. {
  188229. png_warning(png_ptr, "sPLT chunk too large to fit in memory");
  188230. skip = length - (png_uint_32)65535L;
  188231. length = (png_uint_32)65535L;
  188232. }
  188233. #endif
  188234. chunkdata = (png_bytep)png_malloc(png_ptr, length + 1);
  188235. slength = (png_size_t)length;
  188236. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  188237. if (png_crc_finish(png_ptr, skip))
  188238. {
  188239. png_free(png_ptr, chunkdata);
  188240. return;
  188241. }
  188242. chunkdata[slength] = 0x00;
  188243. for (entry_start = chunkdata; *entry_start; entry_start++)
  188244. /* empty loop to find end of name */ ;
  188245. ++entry_start;
  188246. /* a sample depth should follow the separator, and we should be on it */
  188247. if (entry_start > chunkdata + slength - 2)
  188248. {
  188249. png_free(png_ptr, chunkdata);
  188250. png_warning(png_ptr, "malformed sPLT chunk");
  188251. return;
  188252. }
  188253. new_palette.depth = *entry_start++;
  188254. entry_size = (new_palette.depth == 8 ? 6 : 10);
  188255. data_length = (slength - (entry_start - chunkdata));
  188256. /* integrity-check the data length */
  188257. if (data_length % entry_size)
  188258. {
  188259. png_free(png_ptr, chunkdata);
  188260. png_warning(png_ptr, "sPLT chunk has bad length");
  188261. return;
  188262. }
  188263. new_palette.nentries = (png_int_32) ( data_length / entry_size);
  188264. if ((png_uint_32) new_palette.nentries > (png_uint_32) (PNG_SIZE_MAX /
  188265. png_sizeof(png_sPLT_entry)))
  188266. {
  188267. png_warning(png_ptr, "sPLT chunk too long");
  188268. return;
  188269. }
  188270. new_palette.entries = (png_sPLT_entryp)png_malloc_warn(
  188271. png_ptr, new_palette.nentries * png_sizeof(png_sPLT_entry));
  188272. if (new_palette.entries == NULL)
  188273. {
  188274. png_warning(png_ptr, "sPLT chunk requires too much memory");
  188275. return;
  188276. }
  188277. #ifndef PNG_NO_POINTER_INDEXING
  188278. for (i = 0; i < new_palette.nentries; i++)
  188279. {
  188280. png_sPLT_entryp pp = new_palette.entries + i;
  188281. if (new_palette.depth == 8)
  188282. {
  188283. pp->red = *entry_start++;
  188284. pp->green = *entry_start++;
  188285. pp->blue = *entry_start++;
  188286. pp->alpha = *entry_start++;
  188287. }
  188288. else
  188289. {
  188290. pp->red = png_get_uint_16(entry_start); entry_start += 2;
  188291. pp->green = png_get_uint_16(entry_start); entry_start += 2;
  188292. pp->blue = png_get_uint_16(entry_start); entry_start += 2;
  188293. pp->alpha = png_get_uint_16(entry_start); entry_start += 2;
  188294. }
  188295. pp->frequency = png_get_uint_16(entry_start); entry_start += 2;
  188296. }
  188297. #else
  188298. pp = new_palette.entries;
  188299. for (i = 0; i < new_palette.nentries; i++)
  188300. {
  188301. if (new_palette.depth == 8)
  188302. {
  188303. pp[i].red = *entry_start++;
  188304. pp[i].green = *entry_start++;
  188305. pp[i].blue = *entry_start++;
  188306. pp[i].alpha = *entry_start++;
  188307. }
  188308. else
  188309. {
  188310. pp[i].red = png_get_uint_16(entry_start); entry_start += 2;
  188311. pp[i].green = png_get_uint_16(entry_start); entry_start += 2;
  188312. pp[i].blue = png_get_uint_16(entry_start); entry_start += 2;
  188313. pp[i].alpha = png_get_uint_16(entry_start); entry_start += 2;
  188314. }
  188315. pp->frequency = png_get_uint_16(entry_start); entry_start += 2;
  188316. }
  188317. #endif
  188318. /* discard all chunk data except the name and stash that */
  188319. new_palette.name = (png_charp)chunkdata;
  188320. png_set_sPLT(png_ptr, info_ptr, &new_palette, 1);
  188321. png_free(png_ptr, chunkdata);
  188322. png_free(png_ptr, new_palette.entries);
  188323. }
  188324. #endif /* PNG_READ_sPLT_SUPPORTED */
  188325. #if defined(PNG_READ_tRNS_SUPPORTED)
  188326. void /* PRIVATE */
  188327. png_handle_tRNS(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  188328. {
  188329. png_byte readbuf[PNG_MAX_PALETTE_LENGTH];
  188330. int bit_mask;
  188331. png_debug(1, "in png_handle_tRNS\n");
  188332. /* For non-indexed color, mask off any bits in the tRNS value that
  188333. * exceed the bit depth. Some creators were writing extra bits there.
  188334. * This is not needed for indexed color. */
  188335. bit_mask = (1 << png_ptr->bit_depth) - 1;
  188336. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  188337. png_error(png_ptr, "Missing IHDR before tRNS");
  188338. else if (png_ptr->mode & PNG_HAVE_IDAT)
  188339. {
  188340. png_warning(png_ptr, "Invalid tRNS after IDAT");
  188341. png_crc_finish(png_ptr, length);
  188342. return;
  188343. }
  188344. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  188345. {
  188346. png_warning(png_ptr, "Duplicate tRNS chunk");
  188347. png_crc_finish(png_ptr, length);
  188348. return;
  188349. }
  188350. if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  188351. {
  188352. png_byte buf[2];
  188353. if (length != 2)
  188354. {
  188355. png_warning(png_ptr, "Incorrect tRNS chunk length");
  188356. png_crc_finish(png_ptr, length);
  188357. return;
  188358. }
  188359. png_crc_read(png_ptr, buf, 2);
  188360. png_ptr->num_trans = 1;
  188361. png_ptr->trans_values.gray = png_get_uint_16(buf) & bit_mask;
  188362. }
  188363. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  188364. {
  188365. png_byte buf[6];
  188366. if (length != 6)
  188367. {
  188368. png_warning(png_ptr, "Incorrect tRNS chunk length");
  188369. png_crc_finish(png_ptr, length);
  188370. return;
  188371. }
  188372. png_crc_read(png_ptr, buf, (png_size_t)length);
  188373. png_ptr->num_trans = 1;
  188374. png_ptr->trans_values.red = png_get_uint_16(buf) & bit_mask;
  188375. png_ptr->trans_values.green = png_get_uint_16(buf + 2) & bit_mask;
  188376. png_ptr->trans_values.blue = png_get_uint_16(buf + 4) & bit_mask;
  188377. }
  188378. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  188379. {
  188380. if (!(png_ptr->mode & PNG_HAVE_PLTE))
  188381. {
  188382. /* Should be an error, but we can cope with it. */
  188383. png_warning(png_ptr, "Missing PLTE before tRNS");
  188384. }
  188385. if (length > (png_uint_32)png_ptr->num_palette ||
  188386. length > PNG_MAX_PALETTE_LENGTH)
  188387. {
  188388. png_warning(png_ptr, "Incorrect tRNS chunk length");
  188389. png_crc_finish(png_ptr, length);
  188390. return;
  188391. }
  188392. if (length == 0)
  188393. {
  188394. png_warning(png_ptr, "Zero length tRNS chunk");
  188395. png_crc_finish(png_ptr, length);
  188396. return;
  188397. }
  188398. png_crc_read(png_ptr, readbuf, (png_size_t)length);
  188399. png_ptr->num_trans = (png_uint_16)length;
  188400. }
  188401. else
  188402. {
  188403. png_warning(png_ptr, "tRNS chunk not allowed with alpha channel");
  188404. png_crc_finish(png_ptr, length);
  188405. return;
  188406. }
  188407. if (png_crc_finish(png_ptr, 0))
  188408. {
  188409. png_ptr->num_trans = 0;
  188410. return;
  188411. }
  188412. png_set_tRNS(png_ptr, info_ptr, readbuf, png_ptr->num_trans,
  188413. &(png_ptr->trans_values));
  188414. }
  188415. #endif
  188416. #if defined(PNG_READ_bKGD_SUPPORTED)
  188417. void /* PRIVATE */
  188418. png_handle_bKGD(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  188419. {
  188420. png_size_t truelen;
  188421. png_byte buf[6];
  188422. png_debug(1, "in png_handle_bKGD\n");
  188423. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  188424. png_error(png_ptr, "Missing IHDR before bKGD");
  188425. else if (png_ptr->mode & PNG_HAVE_IDAT)
  188426. {
  188427. png_warning(png_ptr, "Invalid bKGD after IDAT");
  188428. png_crc_finish(png_ptr, length);
  188429. return;
  188430. }
  188431. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  188432. !(png_ptr->mode & PNG_HAVE_PLTE))
  188433. {
  188434. png_warning(png_ptr, "Missing PLTE before bKGD");
  188435. png_crc_finish(png_ptr, length);
  188436. return;
  188437. }
  188438. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_bKGD))
  188439. {
  188440. png_warning(png_ptr, "Duplicate bKGD chunk");
  188441. png_crc_finish(png_ptr, length);
  188442. return;
  188443. }
  188444. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  188445. truelen = 1;
  188446. else if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  188447. truelen = 6;
  188448. else
  188449. truelen = 2;
  188450. if (length != truelen)
  188451. {
  188452. png_warning(png_ptr, "Incorrect bKGD chunk length");
  188453. png_crc_finish(png_ptr, length);
  188454. return;
  188455. }
  188456. png_crc_read(png_ptr, buf, truelen);
  188457. if (png_crc_finish(png_ptr, 0))
  188458. return;
  188459. /* We convert the index value into RGB components so that we can allow
  188460. * arbitrary RGB values for background when we have transparency, and
  188461. * so it is easy to determine the RGB values of the background color
  188462. * from the info_ptr struct. */
  188463. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  188464. {
  188465. png_ptr->background.index = buf[0];
  188466. if(info_ptr->num_palette)
  188467. {
  188468. if(buf[0] > info_ptr->num_palette)
  188469. {
  188470. png_warning(png_ptr, "Incorrect bKGD chunk index value");
  188471. return;
  188472. }
  188473. png_ptr->background.red =
  188474. (png_uint_16)png_ptr->palette[buf[0]].red;
  188475. png_ptr->background.green =
  188476. (png_uint_16)png_ptr->palette[buf[0]].green;
  188477. png_ptr->background.blue =
  188478. (png_uint_16)png_ptr->palette[buf[0]].blue;
  188479. }
  188480. }
  188481. else if (!(png_ptr->color_type & PNG_COLOR_MASK_COLOR)) /* GRAY */
  188482. {
  188483. png_ptr->background.red =
  188484. png_ptr->background.green =
  188485. png_ptr->background.blue =
  188486. png_ptr->background.gray = png_get_uint_16(buf);
  188487. }
  188488. else
  188489. {
  188490. png_ptr->background.red = png_get_uint_16(buf);
  188491. png_ptr->background.green = png_get_uint_16(buf + 2);
  188492. png_ptr->background.blue = png_get_uint_16(buf + 4);
  188493. }
  188494. png_set_bKGD(png_ptr, info_ptr, &(png_ptr->background));
  188495. }
  188496. #endif
  188497. #if defined(PNG_READ_hIST_SUPPORTED)
  188498. void /* PRIVATE */
  188499. png_handle_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  188500. {
  188501. unsigned int num, i;
  188502. png_uint_16 readbuf[PNG_MAX_PALETTE_LENGTH];
  188503. png_debug(1, "in png_handle_hIST\n");
  188504. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  188505. png_error(png_ptr, "Missing IHDR before hIST");
  188506. else if (png_ptr->mode & PNG_HAVE_IDAT)
  188507. {
  188508. png_warning(png_ptr, "Invalid hIST after IDAT");
  188509. png_crc_finish(png_ptr, length);
  188510. return;
  188511. }
  188512. else if (!(png_ptr->mode & PNG_HAVE_PLTE))
  188513. {
  188514. png_warning(png_ptr, "Missing PLTE before hIST");
  188515. png_crc_finish(png_ptr, length);
  188516. return;
  188517. }
  188518. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_hIST))
  188519. {
  188520. png_warning(png_ptr, "Duplicate hIST chunk");
  188521. png_crc_finish(png_ptr, length);
  188522. return;
  188523. }
  188524. num = length / 2 ;
  188525. if (num != (unsigned int) png_ptr->num_palette || num >
  188526. (unsigned int) PNG_MAX_PALETTE_LENGTH)
  188527. {
  188528. png_warning(png_ptr, "Incorrect hIST chunk length");
  188529. png_crc_finish(png_ptr, length);
  188530. return;
  188531. }
  188532. for (i = 0; i < num; i++)
  188533. {
  188534. png_byte buf[2];
  188535. png_crc_read(png_ptr, buf, 2);
  188536. readbuf[i] = png_get_uint_16(buf);
  188537. }
  188538. if (png_crc_finish(png_ptr, 0))
  188539. return;
  188540. png_set_hIST(png_ptr, info_ptr, readbuf);
  188541. }
  188542. #endif
  188543. #if defined(PNG_READ_pHYs_SUPPORTED)
  188544. void /* PRIVATE */
  188545. png_handle_pHYs(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  188546. {
  188547. png_byte buf[9];
  188548. png_uint_32 res_x, res_y;
  188549. int unit_type;
  188550. png_debug(1, "in png_handle_pHYs\n");
  188551. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  188552. png_error(png_ptr, "Missing IHDR before pHYs");
  188553. else if (png_ptr->mode & PNG_HAVE_IDAT)
  188554. {
  188555. png_warning(png_ptr, "Invalid pHYs after IDAT");
  188556. png_crc_finish(png_ptr, length);
  188557. return;
  188558. }
  188559. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_pHYs))
  188560. {
  188561. png_warning(png_ptr, "Duplicate pHYs chunk");
  188562. png_crc_finish(png_ptr, length);
  188563. return;
  188564. }
  188565. if (length != 9)
  188566. {
  188567. png_warning(png_ptr, "Incorrect pHYs chunk length");
  188568. png_crc_finish(png_ptr, length);
  188569. return;
  188570. }
  188571. png_crc_read(png_ptr, buf, 9);
  188572. if (png_crc_finish(png_ptr, 0))
  188573. return;
  188574. res_x = png_get_uint_32(buf);
  188575. res_y = png_get_uint_32(buf + 4);
  188576. unit_type = buf[8];
  188577. png_set_pHYs(png_ptr, info_ptr, res_x, res_y, unit_type);
  188578. }
  188579. #endif
  188580. #if defined(PNG_READ_oFFs_SUPPORTED)
  188581. void /* PRIVATE */
  188582. png_handle_oFFs(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  188583. {
  188584. png_byte buf[9];
  188585. png_int_32 offset_x, offset_y;
  188586. int unit_type;
  188587. png_debug(1, "in png_handle_oFFs\n");
  188588. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  188589. png_error(png_ptr, "Missing IHDR before oFFs");
  188590. else if (png_ptr->mode & PNG_HAVE_IDAT)
  188591. {
  188592. png_warning(png_ptr, "Invalid oFFs after IDAT");
  188593. png_crc_finish(png_ptr, length);
  188594. return;
  188595. }
  188596. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_oFFs))
  188597. {
  188598. png_warning(png_ptr, "Duplicate oFFs chunk");
  188599. png_crc_finish(png_ptr, length);
  188600. return;
  188601. }
  188602. if (length != 9)
  188603. {
  188604. png_warning(png_ptr, "Incorrect oFFs chunk length");
  188605. png_crc_finish(png_ptr, length);
  188606. return;
  188607. }
  188608. png_crc_read(png_ptr, buf, 9);
  188609. if (png_crc_finish(png_ptr, 0))
  188610. return;
  188611. offset_x = png_get_int_32(buf);
  188612. offset_y = png_get_int_32(buf + 4);
  188613. unit_type = buf[8];
  188614. png_set_oFFs(png_ptr, info_ptr, offset_x, offset_y, unit_type);
  188615. }
  188616. #endif
  188617. #if defined(PNG_READ_pCAL_SUPPORTED)
  188618. /* read the pCAL chunk (described in the PNG Extensions document) */
  188619. void /* PRIVATE */
  188620. png_handle_pCAL(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  188621. {
  188622. png_charp purpose;
  188623. png_int_32 X0, X1;
  188624. png_byte type, nparams;
  188625. png_charp buf, units, endptr;
  188626. png_charpp params;
  188627. png_size_t slength;
  188628. int i;
  188629. png_debug(1, "in png_handle_pCAL\n");
  188630. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  188631. png_error(png_ptr, "Missing IHDR before pCAL");
  188632. else if (png_ptr->mode & PNG_HAVE_IDAT)
  188633. {
  188634. png_warning(png_ptr, "Invalid pCAL after IDAT");
  188635. png_crc_finish(png_ptr, length);
  188636. return;
  188637. }
  188638. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_pCAL))
  188639. {
  188640. png_warning(png_ptr, "Duplicate pCAL chunk");
  188641. png_crc_finish(png_ptr, length);
  188642. return;
  188643. }
  188644. png_debug1(2, "Allocating and reading pCAL chunk data (%lu bytes)\n",
  188645. length + 1);
  188646. purpose = (png_charp)png_malloc_warn(png_ptr, length + 1);
  188647. if (purpose == NULL)
  188648. {
  188649. png_warning(png_ptr, "No memory for pCAL purpose.");
  188650. return;
  188651. }
  188652. slength = (png_size_t)length;
  188653. png_crc_read(png_ptr, (png_bytep)purpose, slength);
  188654. if (png_crc_finish(png_ptr, 0))
  188655. {
  188656. png_free(png_ptr, purpose);
  188657. return;
  188658. }
  188659. purpose[slength] = 0x00; /* null terminate the last string */
  188660. png_debug(3, "Finding end of pCAL purpose string\n");
  188661. for (buf = purpose; *buf; buf++)
  188662. /* empty loop */ ;
  188663. endptr = purpose + slength;
  188664. /* We need to have at least 12 bytes after the purpose string
  188665. in order to get the parameter information. */
  188666. if (endptr <= buf + 12)
  188667. {
  188668. png_warning(png_ptr, "Invalid pCAL data");
  188669. png_free(png_ptr, purpose);
  188670. return;
  188671. }
  188672. png_debug(3, "Reading pCAL X0, X1, type, nparams, and units\n");
  188673. X0 = png_get_int_32((png_bytep)buf+1);
  188674. X1 = png_get_int_32((png_bytep)buf+5);
  188675. type = buf[9];
  188676. nparams = buf[10];
  188677. units = buf + 11;
  188678. png_debug(3, "Checking pCAL equation type and number of parameters\n");
  188679. /* Check that we have the right number of parameters for known
  188680. equation types. */
  188681. if ((type == PNG_EQUATION_LINEAR && nparams != 2) ||
  188682. (type == PNG_EQUATION_BASE_E && nparams != 3) ||
  188683. (type == PNG_EQUATION_ARBITRARY && nparams != 3) ||
  188684. (type == PNG_EQUATION_HYPERBOLIC && nparams != 4))
  188685. {
  188686. png_warning(png_ptr, "Invalid pCAL parameters for equation type");
  188687. png_free(png_ptr, purpose);
  188688. return;
  188689. }
  188690. else if (type >= PNG_EQUATION_LAST)
  188691. {
  188692. png_warning(png_ptr, "Unrecognized equation type for pCAL chunk");
  188693. }
  188694. for (buf = units; *buf; buf++)
  188695. /* Empty loop to move past the units string. */ ;
  188696. png_debug(3, "Allocating pCAL parameters array\n");
  188697. params = (png_charpp)png_malloc_warn(png_ptr, (png_uint_32)(nparams
  188698. *png_sizeof(png_charp))) ;
  188699. if (params == NULL)
  188700. {
  188701. png_free(png_ptr, purpose);
  188702. png_warning(png_ptr, "No memory for pCAL params.");
  188703. return;
  188704. }
  188705. /* Get pointers to the start of each parameter string. */
  188706. for (i = 0; i < (int)nparams; i++)
  188707. {
  188708. buf++; /* Skip the null string terminator from previous parameter. */
  188709. png_debug1(3, "Reading pCAL parameter %d\n", i);
  188710. for (params[i] = buf; buf <= endptr && *buf != 0x00; buf++)
  188711. /* Empty loop to move past each parameter string */ ;
  188712. /* Make sure we haven't run out of data yet */
  188713. if (buf > endptr)
  188714. {
  188715. png_warning(png_ptr, "Invalid pCAL data");
  188716. png_free(png_ptr, purpose);
  188717. png_free(png_ptr, params);
  188718. return;
  188719. }
  188720. }
  188721. png_set_pCAL(png_ptr, info_ptr, purpose, X0, X1, type, nparams,
  188722. units, params);
  188723. png_free(png_ptr, purpose);
  188724. png_free(png_ptr, params);
  188725. }
  188726. #endif
  188727. #if defined(PNG_READ_sCAL_SUPPORTED)
  188728. /* read the sCAL chunk */
  188729. void /* PRIVATE */
  188730. png_handle_sCAL(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  188731. {
  188732. png_charp buffer, ep;
  188733. #ifdef PNG_FLOATING_POINT_SUPPORTED
  188734. double width, height;
  188735. png_charp vp;
  188736. #else
  188737. #ifdef PNG_FIXED_POINT_SUPPORTED
  188738. png_charp swidth, sheight;
  188739. #endif
  188740. #endif
  188741. png_size_t slength;
  188742. png_debug(1, "in png_handle_sCAL\n");
  188743. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  188744. png_error(png_ptr, "Missing IHDR before sCAL");
  188745. else if (png_ptr->mode & PNG_HAVE_IDAT)
  188746. {
  188747. png_warning(png_ptr, "Invalid sCAL after IDAT");
  188748. png_crc_finish(png_ptr, length);
  188749. return;
  188750. }
  188751. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sCAL))
  188752. {
  188753. png_warning(png_ptr, "Duplicate sCAL chunk");
  188754. png_crc_finish(png_ptr, length);
  188755. return;
  188756. }
  188757. png_debug1(2, "Allocating and reading sCAL chunk data (%lu bytes)\n",
  188758. length + 1);
  188759. buffer = (png_charp)png_malloc_warn(png_ptr, length + 1);
  188760. if (buffer == NULL)
  188761. {
  188762. png_warning(png_ptr, "Out of memory while processing sCAL chunk");
  188763. return;
  188764. }
  188765. slength = (png_size_t)length;
  188766. png_crc_read(png_ptr, (png_bytep)buffer, slength);
  188767. if (png_crc_finish(png_ptr, 0))
  188768. {
  188769. png_free(png_ptr, buffer);
  188770. return;
  188771. }
  188772. buffer[slength] = 0x00; /* null terminate the last string */
  188773. ep = buffer + 1; /* skip unit byte */
  188774. #ifdef PNG_FLOATING_POINT_SUPPORTED
  188775. width = png_strtod(png_ptr, ep, &vp);
  188776. if (*vp)
  188777. {
  188778. png_warning(png_ptr, "malformed width string in sCAL chunk");
  188779. return;
  188780. }
  188781. #else
  188782. #ifdef PNG_FIXED_POINT_SUPPORTED
  188783. swidth = (png_charp)png_malloc_warn(png_ptr, png_strlen(ep) + 1);
  188784. if (swidth == NULL)
  188785. {
  188786. png_warning(png_ptr, "Out of memory while processing sCAL chunk width");
  188787. return;
  188788. }
  188789. png_memcpy(swidth, ep, (png_size_t)png_strlen(ep));
  188790. #endif
  188791. #endif
  188792. for (ep = buffer; *ep; ep++)
  188793. /* empty loop */ ;
  188794. ep++;
  188795. if (buffer + slength < ep)
  188796. {
  188797. png_warning(png_ptr, "Truncated sCAL chunk");
  188798. #if defined(PNG_FIXED_POINT_SUPPORTED) && \
  188799. !defined(PNG_FLOATING_POINT_SUPPORTED)
  188800. png_free(png_ptr, swidth);
  188801. #endif
  188802. png_free(png_ptr, buffer);
  188803. return;
  188804. }
  188805. #ifdef PNG_FLOATING_POINT_SUPPORTED
  188806. height = png_strtod(png_ptr, ep, &vp);
  188807. if (*vp)
  188808. {
  188809. png_warning(png_ptr, "malformed height string in sCAL chunk");
  188810. return;
  188811. }
  188812. #else
  188813. #ifdef PNG_FIXED_POINT_SUPPORTED
  188814. sheight = (png_charp)png_malloc_warn(png_ptr, png_strlen(ep) + 1);
  188815. if (swidth == NULL)
  188816. {
  188817. png_warning(png_ptr, "Out of memory while processing sCAL chunk height");
  188818. return;
  188819. }
  188820. png_memcpy(sheight, ep, (png_size_t)png_strlen(ep));
  188821. #endif
  188822. #endif
  188823. if (buffer + slength < ep
  188824. #ifdef PNG_FLOATING_POINT_SUPPORTED
  188825. || width <= 0. || height <= 0.
  188826. #endif
  188827. )
  188828. {
  188829. png_warning(png_ptr, "Invalid sCAL data");
  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. return;
  188836. }
  188837. #ifdef PNG_FLOATING_POINT_SUPPORTED
  188838. png_set_sCAL(png_ptr, info_ptr, buffer[0], width, height);
  188839. #else
  188840. #ifdef PNG_FIXED_POINT_SUPPORTED
  188841. png_set_sCAL_s(png_ptr, info_ptr, buffer[0], swidth, sheight);
  188842. #endif
  188843. #endif
  188844. png_free(png_ptr, buffer);
  188845. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  188846. png_free(png_ptr, swidth);
  188847. png_free(png_ptr, sheight);
  188848. #endif
  188849. }
  188850. #endif
  188851. #if defined(PNG_READ_tIME_SUPPORTED)
  188852. void /* PRIVATE */
  188853. png_handle_tIME(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  188854. {
  188855. png_byte buf[7];
  188856. png_time mod_time;
  188857. png_debug(1, "in png_handle_tIME\n");
  188858. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  188859. png_error(png_ptr, "Out of place tIME chunk");
  188860. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tIME))
  188861. {
  188862. png_warning(png_ptr, "Duplicate tIME chunk");
  188863. png_crc_finish(png_ptr, length);
  188864. return;
  188865. }
  188866. if (png_ptr->mode & PNG_HAVE_IDAT)
  188867. png_ptr->mode |= PNG_AFTER_IDAT;
  188868. if (length != 7)
  188869. {
  188870. png_warning(png_ptr, "Incorrect tIME chunk length");
  188871. png_crc_finish(png_ptr, length);
  188872. return;
  188873. }
  188874. png_crc_read(png_ptr, buf, 7);
  188875. if (png_crc_finish(png_ptr, 0))
  188876. return;
  188877. mod_time.second = buf[6];
  188878. mod_time.minute = buf[5];
  188879. mod_time.hour = buf[4];
  188880. mod_time.day = buf[3];
  188881. mod_time.month = buf[2];
  188882. mod_time.year = png_get_uint_16(buf);
  188883. png_set_tIME(png_ptr, info_ptr, &mod_time);
  188884. }
  188885. #endif
  188886. #if defined(PNG_READ_tEXt_SUPPORTED)
  188887. /* Note: this does not properly handle chunks that are > 64K under DOS */
  188888. void /* PRIVATE */
  188889. png_handle_tEXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  188890. {
  188891. png_textp text_ptr;
  188892. png_charp key;
  188893. png_charp text;
  188894. png_uint_32 skip = 0;
  188895. png_size_t slength;
  188896. int ret;
  188897. png_debug(1, "in png_handle_tEXt\n");
  188898. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  188899. png_error(png_ptr, "Missing IHDR before tEXt");
  188900. if (png_ptr->mode & PNG_HAVE_IDAT)
  188901. png_ptr->mode |= PNG_AFTER_IDAT;
  188902. #ifdef PNG_MAX_MALLOC_64K
  188903. if (length > (png_uint_32)65535L)
  188904. {
  188905. png_warning(png_ptr, "tEXt chunk too large to fit in memory");
  188906. skip = length - (png_uint_32)65535L;
  188907. length = (png_uint_32)65535L;
  188908. }
  188909. #endif
  188910. key = (png_charp)png_malloc_warn(png_ptr, length + 1);
  188911. if (key == NULL)
  188912. {
  188913. png_warning(png_ptr, "No memory to process text chunk.");
  188914. return;
  188915. }
  188916. slength = (png_size_t)length;
  188917. png_crc_read(png_ptr, (png_bytep)key, slength);
  188918. if (png_crc_finish(png_ptr, skip))
  188919. {
  188920. png_free(png_ptr, key);
  188921. return;
  188922. }
  188923. key[slength] = 0x00;
  188924. for (text = key; *text; text++)
  188925. /* empty loop to find end of key */ ;
  188926. if (text != key + slength)
  188927. text++;
  188928. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  188929. (png_uint_32)png_sizeof(png_text));
  188930. if (text_ptr == NULL)
  188931. {
  188932. png_warning(png_ptr, "Not enough memory to process text chunk.");
  188933. png_free(png_ptr, key);
  188934. return;
  188935. }
  188936. text_ptr->compression = PNG_TEXT_COMPRESSION_NONE;
  188937. text_ptr->key = key;
  188938. #ifdef PNG_iTXt_SUPPORTED
  188939. text_ptr->lang = NULL;
  188940. text_ptr->lang_key = NULL;
  188941. text_ptr->itxt_length = 0;
  188942. #endif
  188943. text_ptr->text = text;
  188944. text_ptr->text_length = png_strlen(text);
  188945. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  188946. png_free(png_ptr, key);
  188947. png_free(png_ptr, text_ptr);
  188948. if (ret)
  188949. png_warning(png_ptr, "Insufficient memory to process text chunk.");
  188950. }
  188951. #endif
  188952. #if defined(PNG_READ_zTXt_SUPPORTED)
  188953. /* note: this does not correctly handle chunks that are > 64K under DOS */
  188954. void /* PRIVATE */
  188955. png_handle_zTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  188956. {
  188957. png_textp text_ptr;
  188958. png_charp chunkdata;
  188959. png_charp text;
  188960. int comp_type;
  188961. int ret;
  188962. png_size_t slength, prefix_len, data_len;
  188963. png_debug(1, "in png_handle_zTXt\n");
  188964. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  188965. png_error(png_ptr, "Missing IHDR before zTXt");
  188966. if (png_ptr->mode & PNG_HAVE_IDAT)
  188967. png_ptr->mode |= PNG_AFTER_IDAT;
  188968. #ifdef PNG_MAX_MALLOC_64K
  188969. /* We will no doubt have problems with chunks even half this size, but
  188970. there is no hard and fast rule to tell us where to stop. */
  188971. if (length > (png_uint_32)65535L)
  188972. {
  188973. png_warning(png_ptr,"zTXt chunk too large to fit in memory");
  188974. png_crc_finish(png_ptr, length);
  188975. return;
  188976. }
  188977. #endif
  188978. chunkdata = (png_charp)png_malloc_warn(png_ptr, length + 1);
  188979. if (chunkdata == NULL)
  188980. {
  188981. png_warning(png_ptr,"Out of memory processing zTXt chunk.");
  188982. return;
  188983. }
  188984. slength = (png_size_t)length;
  188985. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  188986. if (png_crc_finish(png_ptr, 0))
  188987. {
  188988. png_free(png_ptr, chunkdata);
  188989. return;
  188990. }
  188991. chunkdata[slength] = 0x00;
  188992. for (text = chunkdata; *text; text++)
  188993. /* empty loop */ ;
  188994. /* zTXt must have some text after the chunkdataword */
  188995. if (text >= chunkdata + slength - 2)
  188996. {
  188997. png_warning(png_ptr, "Truncated zTXt chunk");
  188998. png_free(png_ptr, chunkdata);
  188999. return;
  189000. }
  189001. else
  189002. {
  189003. comp_type = *(++text);
  189004. if (comp_type != PNG_TEXT_COMPRESSION_zTXt)
  189005. {
  189006. png_warning(png_ptr, "Unknown compression type in zTXt chunk");
  189007. comp_type = PNG_TEXT_COMPRESSION_zTXt;
  189008. }
  189009. text++; /* skip the compression_method byte */
  189010. }
  189011. prefix_len = text - chunkdata;
  189012. chunkdata = (png_charp)png_decompress_chunk(png_ptr, comp_type, chunkdata,
  189013. (png_size_t)length, prefix_len, &data_len);
  189014. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  189015. (png_uint_32)png_sizeof(png_text));
  189016. if (text_ptr == NULL)
  189017. {
  189018. png_warning(png_ptr,"Not enough memory to process zTXt chunk.");
  189019. png_free(png_ptr, chunkdata);
  189020. return;
  189021. }
  189022. text_ptr->compression = comp_type;
  189023. text_ptr->key = chunkdata;
  189024. #ifdef PNG_iTXt_SUPPORTED
  189025. text_ptr->lang = NULL;
  189026. text_ptr->lang_key = NULL;
  189027. text_ptr->itxt_length = 0;
  189028. #endif
  189029. text_ptr->text = chunkdata + prefix_len;
  189030. text_ptr->text_length = data_len;
  189031. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  189032. png_free(png_ptr, text_ptr);
  189033. png_free(png_ptr, chunkdata);
  189034. if (ret)
  189035. png_error(png_ptr, "Insufficient memory to store zTXt chunk.");
  189036. }
  189037. #endif
  189038. #if defined(PNG_READ_iTXt_SUPPORTED)
  189039. /* note: this does not correctly handle chunks that are > 64K under DOS */
  189040. void /* PRIVATE */
  189041. png_handle_iTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  189042. {
  189043. png_textp text_ptr;
  189044. png_charp chunkdata;
  189045. png_charp key, lang, text, lang_key;
  189046. int comp_flag;
  189047. int comp_type = 0;
  189048. int ret;
  189049. png_size_t slength, prefix_len, data_len;
  189050. png_debug(1, "in png_handle_iTXt\n");
  189051. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  189052. png_error(png_ptr, "Missing IHDR before iTXt");
  189053. if (png_ptr->mode & PNG_HAVE_IDAT)
  189054. png_ptr->mode |= PNG_AFTER_IDAT;
  189055. #ifdef PNG_MAX_MALLOC_64K
  189056. /* We will no doubt have problems with chunks even half this size, but
  189057. there is no hard and fast rule to tell us where to stop. */
  189058. if (length > (png_uint_32)65535L)
  189059. {
  189060. png_warning(png_ptr,"iTXt chunk too large to fit in memory");
  189061. png_crc_finish(png_ptr, length);
  189062. return;
  189063. }
  189064. #endif
  189065. chunkdata = (png_charp)png_malloc_warn(png_ptr, length + 1);
  189066. if (chunkdata == NULL)
  189067. {
  189068. png_warning(png_ptr, "No memory to process iTXt chunk.");
  189069. return;
  189070. }
  189071. slength = (png_size_t)length;
  189072. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  189073. if (png_crc_finish(png_ptr, 0))
  189074. {
  189075. png_free(png_ptr, chunkdata);
  189076. return;
  189077. }
  189078. chunkdata[slength] = 0x00;
  189079. for (lang = chunkdata; *lang; lang++)
  189080. /* empty loop */ ;
  189081. lang++; /* skip NUL separator */
  189082. /* iTXt must have a language tag (possibly empty), two compression bytes,
  189083. translated keyword (possibly empty), and possibly some text after the
  189084. keyword */
  189085. if (lang >= chunkdata + slength - 3)
  189086. {
  189087. png_warning(png_ptr, "Truncated iTXt chunk");
  189088. png_free(png_ptr, chunkdata);
  189089. return;
  189090. }
  189091. else
  189092. {
  189093. comp_flag = *lang++;
  189094. comp_type = *lang++;
  189095. }
  189096. for (lang_key = lang; *lang_key; lang_key++)
  189097. /* empty loop */ ;
  189098. lang_key++; /* skip NUL separator */
  189099. if (lang_key >= chunkdata + slength)
  189100. {
  189101. png_warning(png_ptr, "Truncated iTXt chunk");
  189102. png_free(png_ptr, chunkdata);
  189103. return;
  189104. }
  189105. for (text = lang_key; *text; text++)
  189106. /* empty loop */ ;
  189107. text++; /* skip NUL separator */
  189108. if (text >= chunkdata + slength)
  189109. {
  189110. png_warning(png_ptr, "Malformed iTXt chunk");
  189111. png_free(png_ptr, chunkdata);
  189112. return;
  189113. }
  189114. prefix_len = text - chunkdata;
  189115. key=chunkdata;
  189116. if (comp_flag)
  189117. chunkdata = png_decompress_chunk(png_ptr, comp_type, chunkdata,
  189118. (size_t)length, prefix_len, &data_len);
  189119. else
  189120. data_len=png_strlen(chunkdata + prefix_len);
  189121. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  189122. (png_uint_32)png_sizeof(png_text));
  189123. if (text_ptr == NULL)
  189124. {
  189125. png_warning(png_ptr,"Not enough memory to process iTXt chunk.");
  189126. png_free(png_ptr, chunkdata);
  189127. return;
  189128. }
  189129. text_ptr->compression = (int)comp_flag + 1;
  189130. text_ptr->lang_key = chunkdata+(lang_key-key);
  189131. text_ptr->lang = chunkdata+(lang-key);
  189132. text_ptr->itxt_length = data_len;
  189133. text_ptr->text_length = 0;
  189134. text_ptr->key = chunkdata;
  189135. text_ptr->text = chunkdata + prefix_len;
  189136. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  189137. png_free(png_ptr, text_ptr);
  189138. png_free(png_ptr, chunkdata);
  189139. if (ret)
  189140. png_error(png_ptr, "Insufficient memory to store iTXt chunk.");
  189141. }
  189142. #endif
  189143. /* This function is called when we haven't found a handler for a
  189144. chunk. If there isn't a problem with the chunk itself (ie bad
  189145. chunk name, CRC, or a critical chunk), the chunk is silently ignored
  189146. -- unless the PNG_FLAG_UNKNOWN_CHUNKS_SUPPORTED flag is on in which
  189147. case it will be saved away to be written out later. */
  189148. void /* PRIVATE */
  189149. png_handle_unknown(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  189150. {
  189151. png_uint_32 skip = 0;
  189152. png_debug(1, "in png_handle_unknown\n");
  189153. if (png_ptr->mode & PNG_HAVE_IDAT)
  189154. {
  189155. #ifdef PNG_USE_LOCAL_ARRAYS
  189156. PNG_CONST PNG_IDAT;
  189157. #endif
  189158. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4)) /* not an IDAT */
  189159. png_ptr->mode |= PNG_AFTER_IDAT;
  189160. }
  189161. png_check_chunk_name(png_ptr, png_ptr->chunk_name);
  189162. if (!(png_ptr->chunk_name[0] & 0x20))
  189163. {
  189164. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  189165. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  189166. PNG_HANDLE_CHUNK_ALWAYS
  189167. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  189168. && png_ptr->read_user_chunk_fn == NULL
  189169. #endif
  189170. )
  189171. #endif
  189172. png_chunk_error(png_ptr, "unknown critical chunk");
  189173. }
  189174. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  189175. if ((png_ptr->flags & PNG_FLAG_KEEP_UNKNOWN_CHUNKS) ||
  189176. (png_ptr->read_user_chunk_fn != NULL))
  189177. {
  189178. #ifdef PNG_MAX_MALLOC_64K
  189179. if (length > (png_uint_32)65535L)
  189180. {
  189181. png_warning(png_ptr, "unknown chunk too large to fit in memory");
  189182. skip = length - (png_uint_32)65535L;
  189183. length = (png_uint_32)65535L;
  189184. }
  189185. #endif
  189186. png_strncpy((png_charp)png_ptr->unknown_chunk.name,
  189187. (png_charp)png_ptr->chunk_name, 5);
  189188. png_ptr->unknown_chunk.data = (png_bytep)png_malloc(png_ptr, length);
  189189. png_ptr->unknown_chunk.size = (png_size_t)length;
  189190. png_crc_read(png_ptr, (png_bytep)png_ptr->unknown_chunk.data, length);
  189191. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  189192. if(png_ptr->read_user_chunk_fn != NULL)
  189193. {
  189194. /* callback to user unknown chunk handler */
  189195. int ret;
  189196. ret = (*(png_ptr->read_user_chunk_fn))
  189197. (png_ptr, &png_ptr->unknown_chunk);
  189198. if (ret < 0)
  189199. png_chunk_error(png_ptr, "error in user chunk");
  189200. if (ret == 0)
  189201. {
  189202. if (!(png_ptr->chunk_name[0] & 0x20))
  189203. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  189204. PNG_HANDLE_CHUNK_ALWAYS)
  189205. png_chunk_error(png_ptr, "unknown critical chunk");
  189206. png_set_unknown_chunks(png_ptr, info_ptr,
  189207. &png_ptr->unknown_chunk, 1);
  189208. }
  189209. }
  189210. #else
  189211. png_set_unknown_chunks(png_ptr, info_ptr, &png_ptr->unknown_chunk, 1);
  189212. #endif
  189213. png_free(png_ptr, png_ptr->unknown_chunk.data);
  189214. png_ptr->unknown_chunk.data = NULL;
  189215. }
  189216. else
  189217. #endif
  189218. skip = length;
  189219. png_crc_finish(png_ptr, skip);
  189220. #if !defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  189221. info_ptr = info_ptr; /* quiet compiler warnings about unused info_ptr */
  189222. #endif
  189223. }
  189224. /* This function is called to verify that a chunk name is valid.
  189225. This function can't have the "critical chunk check" incorporated
  189226. into it, since in the future we will need to be able to call user
  189227. functions to handle unknown critical chunks after we check that
  189228. the chunk name itself is valid. */
  189229. #define isnonalpha(c) ((c) < 65 || (c) > 122 || ((c) > 90 && (c) < 97))
  189230. void /* PRIVATE */
  189231. png_check_chunk_name(png_structp png_ptr, png_bytep chunk_name)
  189232. {
  189233. png_debug(1, "in png_check_chunk_name\n");
  189234. if (isnonalpha(chunk_name[0]) || isnonalpha(chunk_name[1]) ||
  189235. isnonalpha(chunk_name[2]) || isnonalpha(chunk_name[3]))
  189236. {
  189237. png_chunk_error(png_ptr, "invalid chunk type");
  189238. }
  189239. }
  189240. /* Combines the row recently read in with the existing pixels in the
  189241. row. This routine takes care of alpha and transparency if requested.
  189242. This routine also handles the two methods of progressive display
  189243. of interlaced images, depending on the mask value.
  189244. The mask value describes which pixels are to be combined with
  189245. the row. The pattern always repeats every 8 pixels, so just 8
  189246. bits are needed. A one indicates the pixel is to be combined,
  189247. a zero indicates the pixel is to be skipped. This is in addition
  189248. to any alpha or transparency value associated with the pixel. If
  189249. you want all pixels to be combined, pass 0xff (255) in mask. */
  189250. void /* PRIVATE */
  189251. png_combine_row(png_structp png_ptr, png_bytep row, int mask)
  189252. {
  189253. png_debug(1,"in png_combine_row\n");
  189254. if (mask == 0xff)
  189255. {
  189256. png_memcpy(row, png_ptr->row_buf + 1,
  189257. PNG_ROWBYTES(png_ptr->row_info.pixel_depth, png_ptr->width));
  189258. }
  189259. else
  189260. {
  189261. switch (png_ptr->row_info.pixel_depth)
  189262. {
  189263. case 1:
  189264. {
  189265. png_bytep sp = png_ptr->row_buf + 1;
  189266. png_bytep dp = row;
  189267. int s_inc, s_start, s_end;
  189268. int m = 0x80;
  189269. int shift;
  189270. png_uint_32 i;
  189271. png_uint_32 row_width = png_ptr->width;
  189272. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  189273. if (png_ptr->transformations & PNG_PACKSWAP)
  189274. {
  189275. s_start = 0;
  189276. s_end = 7;
  189277. s_inc = 1;
  189278. }
  189279. else
  189280. #endif
  189281. {
  189282. s_start = 7;
  189283. s_end = 0;
  189284. s_inc = -1;
  189285. }
  189286. shift = s_start;
  189287. for (i = 0; i < row_width; i++)
  189288. {
  189289. if (m & mask)
  189290. {
  189291. int value;
  189292. value = (*sp >> shift) & 0x01;
  189293. *dp &= (png_byte)((0x7f7f >> (7 - shift)) & 0xff);
  189294. *dp |= (png_byte)(value << shift);
  189295. }
  189296. if (shift == s_end)
  189297. {
  189298. shift = s_start;
  189299. sp++;
  189300. dp++;
  189301. }
  189302. else
  189303. shift += s_inc;
  189304. if (m == 1)
  189305. m = 0x80;
  189306. else
  189307. m >>= 1;
  189308. }
  189309. break;
  189310. }
  189311. case 2:
  189312. {
  189313. png_bytep sp = png_ptr->row_buf + 1;
  189314. png_bytep dp = row;
  189315. int s_start, s_end, s_inc;
  189316. int m = 0x80;
  189317. int shift;
  189318. png_uint_32 i;
  189319. png_uint_32 row_width = png_ptr->width;
  189320. int value;
  189321. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  189322. if (png_ptr->transformations & PNG_PACKSWAP)
  189323. {
  189324. s_start = 0;
  189325. s_end = 6;
  189326. s_inc = 2;
  189327. }
  189328. else
  189329. #endif
  189330. {
  189331. s_start = 6;
  189332. s_end = 0;
  189333. s_inc = -2;
  189334. }
  189335. shift = s_start;
  189336. for (i = 0; i < row_width; i++)
  189337. {
  189338. if (m & mask)
  189339. {
  189340. value = (*sp >> shift) & 0x03;
  189341. *dp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  189342. *dp |= (png_byte)(value << shift);
  189343. }
  189344. if (shift == s_end)
  189345. {
  189346. shift = s_start;
  189347. sp++;
  189348. dp++;
  189349. }
  189350. else
  189351. shift += s_inc;
  189352. if (m == 1)
  189353. m = 0x80;
  189354. else
  189355. m >>= 1;
  189356. }
  189357. break;
  189358. }
  189359. case 4:
  189360. {
  189361. png_bytep sp = png_ptr->row_buf + 1;
  189362. png_bytep dp = row;
  189363. int s_start, s_end, s_inc;
  189364. int m = 0x80;
  189365. int shift;
  189366. png_uint_32 i;
  189367. png_uint_32 row_width = png_ptr->width;
  189368. int value;
  189369. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  189370. if (png_ptr->transformations & PNG_PACKSWAP)
  189371. {
  189372. s_start = 0;
  189373. s_end = 4;
  189374. s_inc = 4;
  189375. }
  189376. else
  189377. #endif
  189378. {
  189379. s_start = 4;
  189380. s_end = 0;
  189381. s_inc = -4;
  189382. }
  189383. shift = s_start;
  189384. for (i = 0; i < row_width; i++)
  189385. {
  189386. if (m & mask)
  189387. {
  189388. value = (*sp >> shift) & 0xf;
  189389. *dp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  189390. *dp |= (png_byte)(value << shift);
  189391. }
  189392. if (shift == s_end)
  189393. {
  189394. shift = s_start;
  189395. sp++;
  189396. dp++;
  189397. }
  189398. else
  189399. shift += s_inc;
  189400. if (m == 1)
  189401. m = 0x80;
  189402. else
  189403. m >>= 1;
  189404. }
  189405. break;
  189406. }
  189407. default:
  189408. {
  189409. png_bytep sp = png_ptr->row_buf + 1;
  189410. png_bytep dp = row;
  189411. png_size_t pixel_bytes = (png_ptr->row_info.pixel_depth >> 3);
  189412. png_uint_32 i;
  189413. png_uint_32 row_width = png_ptr->width;
  189414. png_byte m = 0x80;
  189415. for (i = 0; i < row_width; i++)
  189416. {
  189417. if (m & mask)
  189418. {
  189419. png_memcpy(dp, sp, pixel_bytes);
  189420. }
  189421. sp += pixel_bytes;
  189422. dp += pixel_bytes;
  189423. if (m == 1)
  189424. m = 0x80;
  189425. else
  189426. m >>= 1;
  189427. }
  189428. break;
  189429. }
  189430. }
  189431. }
  189432. }
  189433. #ifdef PNG_READ_INTERLACING_SUPPORTED
  189434. /* OLD pre-1.0.9 interface:
  189435. void png_do_read_interlace(png_row_infop row_info, png_bytep row, int pass,
  189436. png_uint_32 transformations)
  189437. */
  189438. void /* PRIVATE */
  189439. png_do_read_interlace(png_structp png_ptr)
  189440. {
  189441. png_row_infop row_info = &(png_ptr->row_info);
  189442. png_bytep row = png_ptr->row_buf + 1;
  189443. int pass = png_ptr->pass;
  189444. png_uint_32 transformations = png_ptr->transformations;
  189445. #ifdef PNG_USE_LOCAL_ARRAYS
  189446. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  189447. /* offset to next interlace block */
  189448. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  189449. #endif
  189450. png_debug(1,"in png_do_read_interlace\n");
  189451. if (row != NULL && row_info != NULL)
  189452. {
  189453. png_uint_32 final_width;
  189454. final_width = row_info->width * png_pass_inc[pass];
  189455. switch (row_info->pixel_depth)
  189456. {
  189457. case 1:
  189458. {
  189459. png_bytep sp = row + (png_size_t)((row_info->width - 1) >> 3);
  189460. png_bytep dp = row + (png_size_t)((final_width - 1) >> 3);
  189461. int sshift, dshift;
  189462. int s_start, s_end, s_inc;
  189463. int jstop = png_pass_inc[pass];
  189464. png_byte v;
  189465. png_uint_32 i;
  189466. int j;
  189467. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  189468. if (transformations & PNG_PACKSWAP)
  189469. {
  189470. sshift = (int)((row_info->width + 7) & 0x07);
  189471. dshift = (int)((final_width + 7) & 0x07);
  189472. s_start = 7;
  189473. s_end = 0;
  189474. s_inc = -1;
  189475. }
  189476. else
  189477. #endif
  189478. {
  189479. sshift = 7 - (int)((row_info->width + 7) & 0x07);
  189480. dshift = 7 - (int)((final_width + 7) & 0x07);
  189481. s_start = 0;
  189482. s_end = 7;
  189483. s_inc = 1;
  189484. }
  189485. for (i = 0; i < row_info->width; i++)
  189486. {
  189487. v = (png_byte)((*sp >> sshift) & 0x01);
  189488. for (j = 0; j < jstop; j++)
  189489. {
  189490. *dp &= (png_byte)((0x7f7f >> (7 - dshift)) & 0xff);
  189491. *dp |= (png_byte)(v << dshift);
  189492. if (dshift == s_end)
  189493. {
  189494. dshift = s_start;
  189495. dp--;
  189496. }
  189497. else
  189498. dshift += s_inc;
  189499. }
  189500. if (sshift == s_end)
  189501. {
  189502. sshift = s_start;
  189503. sp--;
  189504. }
  189505. else
  189506. sshift += s_inc;
  189507. }
  189508. break;
  189509. }
  189510. case 2:
  189511. {
  189512. png_bytep sp = row + (png_uint_32)((row_info->width - 1) >> 2);
  189513. png_bytep dp = row + (png_uint_32)((final_width - 1) >> 2);
  189514. int sshift, dshift;
  189515. int s_start, s_end, s_inc;
  189516. int jstop = png_pass_inc[pass];
  189517. png_uint_32 i;
  189518. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  189519. if (transformations & PNG_PACKSWAP)
  189520. {
  189521. sshift = (int)(((row_info->width + 3) & 0x03) << 1);
  189522. dshift = (int)(((final_width + 3) & 0x03) << 1);
  189523. s_start = 6;
  189524. s_end = 0;
  189525. s_inc = -2;
  189526. }
  189527. else
  189528. #endif
  189529. {
  189530. sshift = (int)((3 - ((row_info->width + 3) & 0x03)) << 1);
  189531. dshift = (int)((3 - ((final_width + 3) & 0x03)) << 1);
  189532. s_start = 0;
  189533. s_end = 6;
  189534. s_inc = 2;
  189535. }
  189536. for (i = 0; i < row_info->width; i++)
  189537. {
  189538. png_byte v;
  189539. int j;
  189540. v = (png_byte)((*sp >> sshift) & 0x03);
  189541. for (j = 0; j < jstop; j++)
  189542. {
  189543. *dp &= (png_byte)((0x3f3f >> (6 - dshift)) & 0xff);
  189544. *dp |= (png_byte)(v << dshift);
  189545. if (dshift == s_end)
  189546. {
  189547. dshift = s_start;
  189548. dp--;
  189549. }
  189550. else
  189551. dshift += s_inc;
  189552. }
  189553. if (sshift == s_end)
  189554. {
  189555. sshift = s_start;
  189556. sp--;
  189557. }
  189558. else
  189559. sshift += s_inc;
  189560. }
  189561. break;
  189562. }
  189563. case 4:
  189564. {
  189565. png_bytep sp = row + (png_size_t)((row_info->width - 1) >> 1);
  189566. png_bytep dp = row + (png_size_t)((final_width - 1) >> 1);
  189567. int sshift, dshift;
  189568. int s_start, s_end, s_inc;
  189569. png_uint_32 i;
  189570. int jstop = png_pass_inc[pass];
  189571. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  189572. if (transformations & PNG_PACKSWAP)
  189573. {
  189574. sshift = (int)(((row_info->width + 1) & 0x01) << 2);
  189575. dshift = (int)(((final_width + 1) & 0x01) << 2);
  189576. s_start = 4;
  189577. s_end = 0;
  189578. s_inc = -4;
  189579. }
  189580. else
  189581. #endif
  189582. {
  189583. sshift = (int)((1 - ((row_info->width + 1) & 0x01)) << 2);
  189584. dshift = (int)((1 - ((final_width + 1) & 0x01)) << 2);
  189585. s_start = 0;
  189586. s_end = 4;
  189587. s_inc = 4;
  189588. }
  189589. for (i = 0; i < row_info->width; i++)
  189590. {
  189591. png_byte v = (png_byte)((*sp >> sshift) & 0xf);
  189592. int j;
  189593. for (j = 0; j < jstop; j++)
  189594. {
  189595. *dp &= (png_byte)((0xf0f >> (4 - dshift)) & 0xff);
  189596. *dp |= (png_byte)(v << dshift);
  189597. if (dshift == s_end)
  189598. {
  189599. dshift = s_start;
  189600. dp--;
  189601. }
  189602. else
  189603. dshift += s_inc;
  189604. }
  189605. if (sshift == s_end)
  189606. {
  189607. sshift = s_start;
  189608. sp--;
  189609. }
  189610. else
  189611. sshift += s_inc;
  189612. }
  189613. break;
  189614. }
  189615. default:
  189616. {
  189617. png_size_t pixel_bytes = (row_info->pixel_depth >> 3);
  189618. png_bytep sp = row + (png_size_t)(row_info->width - 1) * pixel_bytes;
  189619. png_bytep dp = row + (png_size_t)(final_width - 1) * pixel_bytes;
  189620. int jstop = png_pass_inc[pass];
  189621. png_uint_32 i;
  189622. for (i = 0; i < row_info->width; i++)
  189623. {
  189624. png_byte v[8];
  189625. int j;
  189626. png_memcpy(v, sp, pixel_bytes);
  189627. for (j = 0; j < jstop; j++)
  189628. {
  189629. png_memcpy(dp, v, pixel_bytes);
  189630. dp -= pixel_bytes;
  189631. }
  189632. sp -= pixel_bytes;
  189633. }
  189634. break;
  189635. }
  189636. }
  189637. row_info->width = final_width;
  189638. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,final_width);
  189639. }
  189640. #if !defined(PNG_READ_PACKSWAP_SUPPORTED)
  189641. transformations = transformations; /* silence compiler warning */
  189642. #endif
  189643. }
  189644. #endif /* PNG_READ_INTERLACING_SUPPORTED */
  189645. void /* PRIVATE */
  189646. png_read_filter_row(png_structp png_ptr, png_row_infop row_info, png_bytep row,
  189647. png_bytep prev_row, int filter)
  189648. {
  189649. png_debug(1, "in png_read_filter_row\n");
  189650. png_debug2(2,"row = %lu, filter = %d\n", png_ptr->row_number, filter);
  189651. switch (filter)
  189652. {
  189653. case PNG_FILTER_VALUE_NONE:
  189654. break;
  189655. case PNG_FILTER_VALUE_SUB:
  189656. {
  189657. png_uint_32 i;
  189658. png_uint_32 istop = row_info->rowbytes;
  189659. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  189660. png_bytep rp = row + bpp;
  189661. png_bytep lp = row;
  189662. for (i = bpp; i < istop; i++)
  189663. {
  189664. *rp = (png_byte)(((int)(*rp) + (int)(*lp++)) & 0xff);
  189665. rp++;
  189666. }
  189667. break;
  189668. }
  189669. case PNG_FILTER_VALUE_UP:
  189670. {
  189671. png_uint_32 i;
  189672. png_uint_32 istop = row_info->rowbytes;
  189673. png_bytep rp = row;
  189674. png_bytep pp = prev_row;
  189675. for (i = 0; i < istop; i++)
  189676. {
  189677. *rp = (png_byte)(((int)(*rp) + (int)(*pp++)) & 0xff);
  189678. rp++;
  189679. }
  189680. break;
  189681. }
  189682. case PNG_FILTER_VALUE_AVG:
  189683. {
  189684. png_uint_32 i;
  189685. png_bytep rp = row;
  189686. png_bytep pp = prev_row;
  189687. png_bytep lp = row;
  189688. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  189689. png_uint_32 istop = row_info->rowbytes - bpp;
  189690. for (i = 0; i < bpp; i++)
  189691. {
  189692. *rp = (png_byte)(((int)(*rp) +
  189693. ((int)(*pp++) / 2 )) & 0xff);
  189694. rp++;
  189695. }
  189696. for (i = 0; i < istop; i++)
  189697. {
  189698. *rp = (png_byte)(((int)(*rp) +
  189699. (int)(*pp++ + *lp++) / 2 ) & 0xff);
  189700. rp++;
  189701. }
  189702. break;
  189703. }
  189704. case PNG_FILTER_VALUE_PAETH:
  189705. {
  189706. png_uint_32 i;
  189707. png_bytep rp = row;
  189708. png_bytep pp = prev_row;
  189709. png_bytep lp = row;
  189710. png_bytep cp = prev_row;
  189711. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  189712. png_uint_32 istop=row_info->rowbytes - bpp;
  189713. for (i = 0; i < bpp; i++)
  189714. {
  189715. *rp = (png_byte)(((int)(*rp) + (int)(*pp++)) & 0xff);
  189716. rp++;
  189717. }
  189718. for (i = 0; i < istop; i++) /* use leftover rp,pp */
  189719. {
  189720. int a, b, c, pa, pb, pc, p;
  189721. a = *lp++;
  189722. b = *pp++;
  189723. c = *cp++;
  189724. p = b - c;
  189725. pc = a - c;
  189726. #ifdef PNG_USE_ABS
  189727. pa = abs(p);
  189728. pb = abs(pc);
  189729. pc = abs(p + pc);
  189730. #else
  189731. pa = p < 0 ? -p : p;
  189732. pb = pc < 0 ? -pc : pc;
  189733. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  189734. #endif
  189735. /*
  189736. if (pa <= pb && pa <= pc)
  189737. p = a;
  189738. else if (pb <= pc)
  189739. p = b;
  189740. else
  189741. p = c;
  189742. */
  189743. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  189744. *rp = (png_byte)(((int)(*rp) + p) & 0xff);
  189745. rp++;
  189746. }
  189747. break;
  189748. }
  189749. default:
  189750. png_warning(png_ptr, "Ignoring bad adaptive filter type");
  189751. *row=0;
  189752. break;
  189753. }
  189754. }
  189755. void /* PRIVATE */
  189756. png_read_finish_row(png_structp png_ptr)
  189757. {
  189758. #ifdef PNG_USE_LOCAL_ARRAYS
  189759. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  189760. /* start of interlace block */
  189761. PNG_CONST int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  189762. /* offset to next interlace block */
  189763. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  189764. /* start of interlace block in the y direction */
  189765. PNG_CONST int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  189766. /* offset to next interlace block in the y direction */
  189767. PNG_CONST int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  189768. #endif
  189769. png_debug(1, "in png_read_finish_row\n");
  189770. png_ptr->row_number++;
  189771. if (png_ptr->row_number < png_ptr->num_rows)
  189772. return;
  189773. if (png_ptr->interlaced)
  189774. {
  189775. png_ptr->row_number = 0;
  189776. png_memset_check(png_ptr, png_ptr->prev_row, 0,
  189777. png_ptr->rowbytes + 1);
  189778. do
  189779. {
  189780. png_ptr->pass++;
  189781. if (png_ptr->pass >= 7)
  189782. break;
  189783. png_ptr->iwidth = (png_ptr->width +
  189784. png_pass_inc[png_ptr->pass] - 1 -
  189785. png_pass_start[png_ptr->pass]) /
  189786. png_pass_inc[png_ptr->pass];
  189787. png_ptr->irowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,
  189788. png_ptr->iwidth) + 1;
  189789. if (!(png_ptr->transformations & PNG_INTERLACE))
  189790. {
  189791. png_ptr->num_rows = (png_ptr->height +
  189792. png_pass_yinc[png_ptr->pass] - 1 -
  189793. png_pass_ystart[png_ptr->pass]) /
  189794. png_pass_yinc[png_ptr->pass];
  189795. if (!(png_ptr->num_rows))
  189796. continue;
  189797. }
  189798. else /* if (png_ptr->transformations & PNG_INTERLACE) */
  189799. break;
  189800. } while (png_ptr->iwidth == 0);
  189801. if (png_ptr->pass < 7)
  189802. return;
  189803. }
  189804. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  189805. {
  189806. #ifdef PNG_USE_LOCAL_ARRAYS
  189807. PNG_CONST PNG_IDAT;
  189808. #endif
  189809. char extra;
  189810. int ret;
  189811. png_ptr->zstream.next_out = (Byte *)&extra;
  189812. png_ptr->zstream.avail_out = (uInt)1;
  189813. for(;;)
  189814. {
  189815. if (!(png_ptr->zstream.avail_in))
  189816. {
  189817. while (!png_ptr->idat_size)
  189818. {
  189819. png_byte chunk_length[4];
  189820. png_crc_finish(png_ptr, 0);
  189821. png_read_data(png_ptr, chunk_length, 4);
  189822. png_ptr->idat_size = png_get_uint_31(png_ptr, chunk_length);
  189823. png_reset_crc(png_ptr);
  189824. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  189825. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  189826. png_error(png_ptr, "Not enough image data");
  189827. }
  189828. png_ptr->zstream.avail_in = (uInt)png_ptr->zbuf_size;
  189829. png_ptr->zstream.next_in = png_ptr->zbuf;
  189830. if (png_ptr->zbuf_size > png_ptr->idat_size)
  189831. png_ptr->zstream.avail_in = (uInt)png_ptr->idat_size;
  189832. png_crc_read(png_ptr, png_ptr->zbuf, png_ptr->zstream.avail_in);
  189833. png_ptr->idat_size -= png_ptr->zstream.avail_in;
  189834. }
  189835. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  189836. if (ret == Z_STREAM_END)
  189837. {
  189838. if (!(png_ptr->zstream.avail_out) || png_ptr->zstream.avail_in ||
  189839. png_ptr->idat_size)
  189840. png_warning(png_ptr, "Extra compressed data");
  189841. png_ptr->mode |= PNG_AFTER_IDAT;
  189842. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  189843. break;
  189844. }
  189845. if (ret != Z_OK)
  189846. png_error(png_ptr, png_ptr->zstream.msg ? png_ptr->zstream.msg :
  189847. "Decompression Error");
  189848. if (!(png_ptr->zstream.avail_out))
  189849. {
  189850. png_warning(png_ptr, "Extra compressed data.");
  189851. png_ptr->mode |= PNG_AFTER_IDAT;
  189852. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  189853. break;
  189854. }
  189855. }
  189856. png_ptr->zstream.avail_out = 0;
  189857. }
  189858. if (png_ptr->idat_size || png_ptr->zstream.avail_in)
  189859. png_warning(png_ptr, "Extra compression data");
  189860. inflateReset(&png_ptr->zstream);
  189861. png_ptr->mode |= PNG_AFTER_IDAT;
  189862. }
  189863. void /* PRIVATE */
  189864. png_read_start_row(png_structp png_ptr)
  189865. {
  189866. #ifdef PNG_USE_LOCAL_ARRAYS
  189867. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  189868. /* start of interlace block */
  189869. PNG_CONST int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  189870. /* offset to next interlace block */
  189871. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  189872. /* start of interlace block in the y direction */
  189873. PNG_CONST int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  189874. /* offset to next interlace block in the y direction */
  189875. PNG_CONST int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  189876. #endif
  189877. int max_pixel_depth;
  189878. png_uint_32 row_bytes;
  189879. png_debug(1, "in png_read_start_row\n");
  189880. png_ptr->zstream.avail_in = 0;
  189881. png_init_read_transformations(png_ptr);
  189882. if (png_ptr->interlaced)
  189883. {
  189884. if (!(png_ptr->transformations & PNG_INTERLACE))
  189885. png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 -
  189886. png_pass_ystart[0]) / png_pass_yinc[0];
  189887. else
  189888. png_ptr->num_rows = png_ptr->height;
  189889. png_ptr->iwidth = (png_ptr->width +
  189890. png_pass_inc[png_ptr->pass] - 1 -
  189891. png_pass_start[png_ptr->pass]) /
  189892. png_pass_inc[png_ptr->pass];
  189893. row_bytes = PNG_ROWBYTES(png_ptr->pixel_depth,png_ptr->iwidth) + 1;
  189894. png_ptr->irowbytes = (png_size_t)row_bytes;
  189895. if((png_uint_32)png_ptr->irowbytes != row_bytes)
  189896. png_error(png_ptr, "Rowbytes overflow in png_read_start_row");
  189897. }
  189898. else
  189899. {
  189900. png_ptr->num_rows = png_ptr->height;
  189901. png_ptr->iwidth = png_ptr->width;
  189902. png_ptr->irowbytes = png_ptr->rowbytes + 1;
  189903. }
  189904. max_pixel_depth = png_ptr->pixel_depth;
  189905. #if defined(PNG_READ_PACK_SUPPORTED)
  189906. if ((png_ptr->transformations & PNG_PACK) && png_ptr->bit_depth < 8)
  189907. max_pixel_depth = 8;
  189908. #endif
  189909. #if defined(PNG_READ_EXPAND_SUPPORTED)
  189910. if (png_ptr->transformations & PNG_EXPAND)
  189911. {
  189912. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  189913. {
  189914. if (png_ptr->num_trans)
  189915. max_pixel_depth = 32;
  189916. else
  189917. max_pixel_depth = 24;
  189918. }
  189919. else if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  189920. {
  189921. if (max_pixel_depth < 8)
  189922. max_pixel_depth = 8;
  189923. if (png_ptr->num_trans)
  189924. max_pixel_depth *= 2;
  189925. }
  189926. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  189927. {
  189928. if (png_ptr->num_trans)
  189929. {
  189930. max_pixel_depth *= 4;
  189931. max_pixel_depth /= 3;
  189932. }
  189933. }
  189934. }
  189935. #endif
  189936. #if defined(PNG_READ_FILLER_SUPPORTED)
  189937. if (png_ptr->transformations & (PNG_FILLER))
  189938. {
  189939. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  189940. max_pixel_depth = 32;
  189941. else if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  189942. {
  189943. if (max_pixel_depth <= 8)
  189944. max_pixel_depth = 16;
  189945. else
  189946. max_pixel_depth = 32;
  189947. }
  189948. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  189949. {
  189950. if (max_pixel_depth <= 32)
  189951. max_pixel_depth = 32;
  189952. else
  189953. max_pixel_depth = 64;
  189954. }
  189955. }
  189956. #endif
  189957. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  189958. if (png_ptr->transformations & PNG_GRAY_TO_RGB)
  189959. {
  189960. if (
  189961. #if defined(PNG_READ_EXPAND_SUPPORTED)
  189962. (png_ptr->num_trans && (png_ptr->transformations & PNG_EXPAND)) ||
  189963. #endif
  189964. #if defined(PNG_READ_FILLER_SUPPORTED)
  189965. (png_ptr->transformations & (PNG_FILLER)) ||
  189966. #endif
  189967. png_ptr->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  189968. {
  189969. if (max_pixel_depth <= 16)
  189970. max_pixel_depth = 32;
  189971. else
  189972. max_pixel_depth = 64;
  189973. }
  189974. else
  189975. {
  189976. if (max_pixel_depth <= 8)
  189977. {
  189978. if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  189979. max_pixel_depth = 32;
  189980. else
  189981. max_pixel_depth = 24;
  189982. }
  189983. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  189984. max_pixel_depth = 64;
  189985. else
  189986. max_pixel_depth = 48;
  189987. }
  189988. }
  189989. #endif
  189990. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) && \
  189991. defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  189992. if(png_ptr->transformations & PNG_USER_TRANSFORM)
  189993. {
  189994. int user_pixel_depth=png_ptr->user_transform_depth*
  189995. png_ptr->user_transform_channels;
  189996. if(user_pixel_depth > max_pixel_depth)
  189997. max_pixel_depth=user_pixel_depth;
  189998. }
  189999. #endif
  190000. /* align the width on the next larger 8 pixels. Mainly used
  190001. for interlacing */
  190002. row_bytes = ((png_ptr->width + 7) & ~((png_uint_32)7));
  190003. /* calculate the maximum bytes needed, adding a byte and a pixel
  190004. for safety's sake */
  190005. row_bytes = PNG_ROWBYTES(max_pixel_depth,row_bytes) +
  190006. 1 + ((max_pixel_depth + 7) >> 3);
  190007. #ifdef PNG_MAX_MALLOC_64K
  190008. if (row_bytes > (png_uint_32)65536L)
  190009. png_error(png_ptr, "This image requires a row greater than 64KB");
  190010. #endif
  190011. png_ptr->big_row_buf = (png_bytep)png_malloc(png_ptr, row_bytes+64);
  190012. png_ptr->row_buf = png_ptr->big_row_buf+32;
  190013. #ifdef PNG_MAX_MALLOC_64K
  190014. if ((png_uint_32)png_ptr->rowbytes + 1 > (png_uint_32)65536L)
  190015. png_error(png_ptr, "This image requires a row greater than 64KB");
  190016. #endif
  190017. if ((png_uint_32)png_ptr->rowbytes > (png_uint_32)(PNG_SIZE_MAX - 1))
  190018. png_error(png_ptr, "Row has too many bytes to allocate in memory.");
  190019. png_ptr->prev_row = (png_bytep)png_malloc(png_ptr, (png_uint_32)(
  190020. png_ptr->rowbytes + 1));
  190021. png_memset_check(png_ptr, png_ptr->prev_row, 0, png_ptr->rowbytes + 1);
  190022. png_debug1(3, "width = %lu,\n", png_ptr->width);
  190023. png_debug1(3, "height = %lu,\n", png_ptr->height);
  190024. png_debug1(3, "iwidth = %lu,\n", png_ptr->iwidth);
  190025. png_debug1(3, "num_rows = %lu\n", png_ptr->num_rows);
  190026. png_debug1(3, "rowbytes = %lu,\n", png_ptr->rowbytes);
  190027. png_debug1(3, "irowbytes = %lu,\n", png_ptr->irowbytes);
  190028. png_ptr->flags |= PNG_FLAG_ROW_INIT;
  190029. }
  190030. #endif /* PNG_READ_SUPPORTED */
  190031. /********* End of inlined file: pngrutil.c *********/
  190032. /********* Start of inlined file: pngset.c *********/
  190033. /* pngset.c - storage of image information into info struct
  190034. *
  190035. * Last changed in libpng 1.2.21 [October 4, 2007]
  190036. * For conditions of distribution and use, see copyright notice in png.h
  190037. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  190038. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  190039. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  190040. *
  190041. * The functions here are used during reads to store data from the file
  190042. * into the info struct, and during writes to store application data
  190043. * into the info struct for writing into the file. This abstracts the
  190044. * info struct and allows us to change the structure in the future.
  190045. */
  190046. #define PNG_INTERNAL
  190047. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  190048. #if defined(PNG_bKGD_SUPPORTED)
  190049. void PNGAPI
  190050. png_set_bKGD(png_structp png_ptr, png_infop info_ptr, png_color_16p background)
  190051. {
  190052. png_debug1(1, "in %s storage function\n", "bKGD");
  190053. if (png_ptr == NULL || info_ptr == NULL)
  190054. return;
  190055. png_memcpy(&(info_ptr->background), background, png_sizeof(png_color_16));
  190056. info_ptr->valid |= PNG_INFO_bKGD;
  190057. }
  190058. #endif
  190059. #if defined(PNG_cHRM_SUPPORTED)
  190060. #ifdef PNG_FLOATING_POINT_SUPPORTED
  190061. void PNGAPI
  190062. png_set_cHRM(png_structp png_ptr, png_infop info_ptr,
  190063. double white_x, double white_y, double red_x, double red_y,
  190064. double green_x, double green_y, double blue_x, double blue_y)
  190065. {
  190066. png_debug1(1, "in %s storage function\n", "cHRM");
  190067. if (png_ptr == NULL || info_ptr == NULL)
  190068. return;
  190069. if (white_x < 0.0 || white_y < 0.0 ||
  190070. red_x < 0.0 || red_y < 0.0 ||
  190071. green_x < 0.0 || green_y < 0.0 ||
  190072. blue_x < 0.0 || blue_y < 0.0)
  190073. {
  190074. png_warning(png_ptr,
  190075. "Ignoring attempt to set negative chromaticity value");
  190076. return;
  190077. }
  190078. if (white_x > 21474.83 || white_y > 21474.83 ||
  190079. red_x > 21474.83 || red_y > 21474.83 ||
  190080. green_x > 21474.83 || green_y > 21474.83 ||
  190081. blue_x > 21474.83 || blue_y > 21474.83)
  190082. {
  190083. png_warning(png_ptr,
  190084. "Ignoring attempt to set chromaticity value exceeding 21474.83");
  190085. return;
  190086. }
  190087. info_ptr->x_white = (float)white_x;
  190088. info_ptr->y_white = (float)white_y;
  190089. info_ptr->x_red = (float)red_x;
  190090. info_ptr->y_red = (float)red_y;
  190091. info_ptr->x_green = (float)green_x;
  190092. info_ptr->y_green = (float)green_y;
  190093. info_ptr->x_blue = (float)blue_x;
  190094. info_ptr->y_blue = (float)blue_y;
  190095. #ifdef PNG_FIXED_POINT_SUPPORTED
  190096. info_ptr->int_x_white = (png_fixed_point)(white_x*100000.+0.5);
  190097. info_ptr->int_y_white = (png_fixed_point)(white_y*100000.+0.5);
  190098. info_ptr->int_x_red = (png_fixed_point)( red_x*100000.+0.5);
  190099. info_ptr->int_y_red = (png_fixed_point)( red_y*100000.+0.5);
  190100. info_ptr->int_x_green = (png_fixed_point)(green_x*100000.+0.5);
  190101. info_ptr->int_y_green = (png_fixed_point)(green_y*100000.+0.5);
  190102. info_ptr->int_x_blue = (png_fixed_point)( blue_x*100000.+0.5);
  190103. info_ptr->int_y_blue = (png_fixed_point)( blue_y*100000.+0.5);
  190104. #endif
  190105. info_ptr->valid |= PNG_INFO_cHRM;
  190106. }
  190107. #endif
  190108. #ifdef PNG_FIXED_POINT_SUPPORTED
  190109. void PNGAPI
  190110. png_set_cHRM_fixed(png_structp png_ptr, png_infop info_ptr,
  190111. png_fixed_point white_x, png_fixed_point white_y, png_fixed_point red_x,
  190112. png_fixed_point red_y, png_fixed_point green_x, png_fixed_point green_y,
  190113. png_fixed_point blue_x, png_fixed_point blue_y)
  190114. {
  190115. png_debug1(1, "in %s storage function\n", "cHRM");
  190116. if (png_ptr == NULL || info_ptr == NULL)
  190117. return;
  190118. if (white_x < 0 || white_y < 0 ||
  190119. red_x < 0 || red_y < 0 ||
  190120. green_x < 0 || green_y < 0 ||
  190121. blue_x < 0 || blue_y < 0)
  190122. {
  190123. png_warning(png_ptr,
  190124. "Ignoring attempt to set negative chromaticity value");
  190125. return;
  190126. }
  190127. #ifdef PNG_FLOATING_POINT_SUPPORTED
  190128. if (white_x > (double) PNG_UINT_31_MAX ||
  190129. white_y > (double) PNG_UINT_31_MAX ||
  190130. red_x > (double) PNG_UINT_31_MAX ||
  190131. red_y > (double) PNG_UINT_31_MAX ||
  190132. green_x > (double) PNG_UINT_31_MAX ||
  190133. green_y > (double) PNG_UINT_31_MAX ||
  190134. blue_x > (double) PNG_UINT_31_MAX ||
  190135. blue_y > (double) PNG_UINT_31_MAX)
  190136. #else
  190137. if (white_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  190138. white_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  190139. red_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  190140. red_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  190141. green_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  190142. green_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  190143. blue_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  190144. blue_y > (png_fixed_point) PNG_UINT_31_MAX/100000L)
  190145. #endif
  190146. {
  190147. png_warning(png_ptr,
  190148. "Ignoring attempt to set chromaticity value exceeding 21474.83");
  190149. return;
  190150. }
  190151. info_ptr->int_x_white = white_x;
  190152. info_ptr->int_y_white = white_y;
  190153. info_ptr->int_x_red = red_x;
  190154. info_ptr->int_y_red = red_y;
  190155. info_ptr->int_x_green = green_x;
  190156. info_ptr->int_y_green = green_y;
  190157. info_ptr->int_x_blue = blue_x;
  190158. info_ptr->int_y_blue = blue_y;
  190159. #ifdef PNG_FLOATING_POINT_SUPPORTED
  190160. info_ptr->x_white = (float)(white_x/100000.);
  190161. info_ptr->y_white = (float)(white_y/100000.);
  190162. info_ptr->x_red = (float)( red_x/100000.);
  190163. info_ptr->y_red = (float)( red_y/100000.);
  190164. info_ptr->x_green = (float)(green_x/100000.);
  190165. info_ptr->y_green = (float)(green_y/100000.);
  190166. info_ptr->x_blue = (float)( blue_x/100000.);
  190167. info_ptr->y_blue = (float)( blue_y/100000.);
  190168. #endif
  190169. info_ptr->valid |= PNG_INFO_cHRM;
  190170. }
  190171. #endif
  190172. #endif
  190173. #if defined(PNG_gAMA_SUPPORTED)
  190174. #ifdef PNG_FLOATING_POINT_SUPPORTED
  190175. void PNGAPI
  190176. png_set_gAMA(png_structp png_ptr, png_infop info_ptr, double file_gamma)
  190177. {
  190178. double gamma;
  190179. png_debug1(1, "in %s storage function\n", "gAMA");
  190180. if (png_ptr == NULL || info_ptr == NULL)
  190181. return;
  190182. /* Check for overflow */
  190183. if (file_gamma > 21474.83)
  190184. {
  190185. png_warning(png_ptr, "Limiting gamma to 21474.83");
  190186. gamma=21474.83;
  190187. }
  190188. else
  190189. gamma=file_gamma;
  190190. info_ptr->gamma = (float)gamma;
  190191. #ifdef PNG_FIXED_POINT_SUPPORTED
  190192. info_ptr->int_gamma = (int)(gamma*100000.+.5);
  190193. #endif
  190194. info_ptr->valid |= PNG_INFO_gAMA;
  190195. if(gamma == 0.0)
  190196. png_warning(png_ptr, "Setting gamma=0");
  190197. }
  190198. #endif
  190199. void PNGAPI
  190200. png_set_gAMA_fixed(png_structp png_ptr, png_infop info_ptr, png_fixed_point
  190201. int_gamma)
  190202. {
  190203. png_fixed_point gamma;
  190204. png_debug1(1, "in %s storage function\n", "gAMA");
  190205. if (png_ptr == NULL || info_ptr == NULL)
  190206. return;
  190207. if (int_gamma > (png_fixed_point) PNG_UINT_31_MAX)
  190208. {
  190209. png_warning(png_ptr, "Limiting gamma to 21474.83");
  190210. gamma=PNG_UINT_31_MAX;
  190211. }
  190212. else
  190213. {
  190214. if (int_gamma < 0)
  190215. {
  190216. png_warning(png_ptr, "Setting negative gamma to zero");
  190217. gamma=0;
  190218. }
  190219. else
  190220. gamma=int_gamma;
  190221. }
  190222. #ifdef PNG_FLOATING_POINT_SUPPORTED
  190223. info_ptr->gamma = (float)(gamma/100000.);
  190224. #endif
  190225. #ifdef PNG_FIXED_POINT_SUPPORTED
  190226. info_ptr->int_gamma = gamma;
  190227. #endif
  190228. info_ptr->valid |= PNG_INFO_gAMA;
  190229. if(gamma == 0)
  190230. png_warning(png_ptr, "Setting gamma=0");
  190231. }
  190232. #endif
  190233. #if defined(PNG_hIST_SUPPORTED)
  190234. void PNGAPI
  190235. png_set_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_16p hist)
  190236. {
  190237. int i;
  190238. png_debug1(1, "in %s storage function\n", "hIST");
  190239. if (png_ptr == NULL || info_ptr == NULL)
  190240. return;
  190241. if (info_ptr->num_palette == 0 || info_ptr->num_palette
  190242. > PNG_MAX_PALETTE_LENGTH)
  190243. {
  190244. png_warning(png_ptr,
  190245. "Invalid palette size, hIST allocation skipped.");
  190246. return;
  190247. }
  190248. #ifdef PNG_FREE_ME_SUPPORTED
  190249. png_free_data(png_ptr, info_ptr, PNG_FREE_HIST, 0);
  190250. #endif
  190251. /* Changed from info->num_palette to PNG_MAX_PALETTE_LENGTH in version
  190252. 1.2.1 */
  190253. png_ptr->hist = (png_uint_16p)png_malloc_warn(png_ptr,
  190254. (png_uint_32)(PNG_MAX_PALETTE_LENGTH * png_sizeof (png_uint_16)));
  190255. if (png_ptr->hist == NULL)
  190256. {
  190257. png_warning(png_ptr, "Insufficient memory for hIST chunk data.");
  190258. return;
  190259. }
  190260. for (i = 0; i < info_ptr->num_palette; i++)
  190261. png_ptr->hist[i] = hist[i];
  190262. info_ptr->hist = png_ptr->hist;
  190263. info_ptr->valid |= PNG_INFO_hIST;
  190264. #ifdef PNG_FREE_ME_SUPPORTED
  190265. info_ptr->free_me |= PNG_FREE_HIST;
  190266. #else
  190267. png_ptr->flags |= PNG_FLAG_FREE_HIST;
  190268. #endif
  190269. }
  190270. #endif
  190271. void PNGAPI
  190272. png_set_IHDR(png_structp png_ptr, png_infop info_ptr,
  190273. png_uint_32 width, png_uint_32 height, int bit_depth,
  190274. int color_type, int interlace_type, int compression_type,
  190275. int filter_type)
  190276. {
  190277. png_debug1(1, "in %s storage function\n", "IHDR");
  190278. if (png_ptr == NULL || info_ptr == NULL)
  190279. return;
  190280. /* check for width and height valid values */
  190281. if (width == 0 || height == 0)
  190282. png_error(png_ptr, "Image width or height is zero in IHDR");
  190283. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  190284. if (width > png_ptr->user_width_max || height > png_ptr->user_height_max)
  190285. png_error(png_ptr, "image size exceeds user limits in IHDR");
  190286. #else
  190287. if (width > PNG_USER_WIDTH_MAX || height > PNG_USER_HEIGHT_MAX)
  190288. png_error(png_ptr, "image size exceeds user limits in IHDR");
  190289. #endif
  190290. if (width > PNG_UINT_31_MAX || height > PNG_UINT_31_MAX)
  190291. png_error(png_ptr, "Invalid image size in IHDR");
  190292. if ( width > (PNG_UINT_32_MAX
  190293. >> 3) /* 8-byte RGBA pixels */
  190294. - 64 /* bigrowbuf hack */
  190295. - 1 /* filter byte */
  190296. - 7*8 /* rounding of width to multiple of 8 pixels */
  190297. - 8) /* extra max_pixel_depth pad */
  190298. png_warning(png_ptr, "Width is too large for libpng to process pixels");
  190299. /* check other values */
  190300. if (bit_depth != 1 && bit_depth != 2 && bit_depth != 4 &&
  190301. bit_depth != 8 && bit_depth != 16)
  190302. png_error(png_ptr, "Invalid bit depth in IHDR");
  190303. if (color_type < 0 || color_type == 1 ||
  190304. color_type == 5 || color_type > 6)
  190305. png_error(png_ptr, "Invalid color type in IHDR");
  190306. if (((color_type == PNG_COLOR_TYPE_PALETTE) && bit_depth > 8) ||
  190307. ((color_type == PNG_COLOR_TYPE_RGB ||
  190308. color_type == PNG_COLOR_TYPE_GRAY_ALPHA ||
  190309. color_type == PNG_COLOR_TYPE_RGB_ALPHA) && bit_depth < 8))
  190310. png_error(png_ptr, "Invalid color type/bit depth combination in IHDR");
  190311. if (interlace_type >= PNG_INTERLACE_LAST)
  190312. png_error(png_ptr, "Unknown interlace method in IHDR");
  190313. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  190314. png_error(png_ptr, "Unknown compression method in IHDR");
  190315. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  190316. /* Accept filter_method 64 (intrapixel differencing) only if
  190317. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  190318. * 2. Libpng did not read a PNG signature (this filter_method is only
  190319. * used in PNG datastreams that are embedded in MNG datastreams) and
  190320. * 3. The application called png_permit_mng_features with a mask that
  190321. * included PNG_FLAG_MNG_FILTER_64 and
  190322. * 4. The filter_method is 64 and
  190323. * 5. The color_type is RGB or RGBA
  190324. */
  190325. if((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)&&png_ptr->mng_features_permitted)
  190326. png_warning(png_ptr,"MNG features are not allowed in a PNG datastream");
  190327. if(filter_type != PNG_FILTER_TYPE_BASE)
  190328. {
  190329. if(!((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  190330. (filter_type == PNG_INTRAPIXEL_DIFFERENCING) &&
  190331. ((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE) == 0) &&
  190332. (color_type == PNG_COLOR_TYPE_RGB ||
  190333. color_type == PNG_COLOR_TYPE_RGB_ALPHA)))
  190334. png_error(png_ptr, "Unknown filter method in IHDR");
  190335. if(png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)
  190336. png_warning(png_ptr, "Invalid filter method in IHDR");
  190337. }
  190338. #else
  190339. if(filter_type != PNG_FILTER_TYPE_BASE)
  190340. png_error(png_ptr, "Unknown filter method in IHDR");
  190341. #endif
  190342. info_ptr->width = width;
  190343. info_ptr->height = height;
  190344. info_ptr->bit_depth = (png_byte)bit_depth;
  190345. info_ptr->color_type =(png_byte) color_type;
  190346. info_ptr->compression_type = (png_byte)compression_type;
  190347. info_ptr->filter_type = (png_byte)filter_type;
  190348. info_ptr->interlace_type = (png_byte)interlace_type;
  190349. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  190350. info_ptr->channels = 1;
  190351. else if (info_ptr->color_type & PNG_COLOR_MASK_COLOR)
  190352. info_ptr->channels = 3;
  190353. else
  190354. info_ptr->channels = 1;
  190355. if (info_ptr->color_type & PNG_COLOR_MASK_ALPHA)
  190356. info_ptr->channels++;
  190357. info_ptr->pixel_depth = (png_byte)(info_ptr->channels * info_ptr->bit_depth);
  190358. /* check for potential overflow */
  190359. if (width > (PNG_UINT_32_MAX
  190360. >> 3) /* 8-byte RGBA pixels */
  190361. - 64 /* bigrowbuf hack */
  190362. - 1 /* filter byte */
  190363. - 7*8 /* rounding of width to multiple of 8 pixels */
  190364. - 8) /* extra max_pixel_depth pad */
  190365. info_ptr->rowbytes = (png_size_t)0;
  190366. else
  190367. info_ptr->rowbytes = PNG_ROWBYTES(info_ptr->pixel_depth,width);
  190368. }
  190369. #if defined(PNG_oFFs_SUPPORTED)
  190370. void PNGAPI
  190371. png_set_oFFs(png_structp png_ptr, png_infop info_ptr,
  190372. png_int_32 offset_x, png_int_32 offset_y, int unit_type)
  190373. {
  190374. png_debug1(1, "in %s storage function\n", "oFFs");
  190375. if (png_ptr == NULL || info_ptr == NULL)
  190376. return;
  190377. info_ptr->x_offset = offset_x;
  190378. info_ptr->y_offset = offset_y;
  190379. info_ptr->offset_unit_type = (png_byte)unit_type;
  190380. info_ptr->valid |= PNG_INFO_oFFs;
  190381. }
  190382. #endif
  190383. #if defined(PNG_pCAL_SUPPORTED)
  190384. void PNGAPI
  190385. png_set_pCAL(png_structp png_ptr, png_infop info_ptr,
  190386. png_charp purpose, png_int_32 X0, png_int_32 X1, int type, int nparams,
  190387. png_charp units, png_charpp params)
  190388. {
  190389. png_uint_32 length;
  190390. int i;
  190391. png_debug1(1, "in %s storage function\n", "pCAL");
  190392. if (png_ptr == NULL || info_ptr == NULL)
  190393. return;
  190394. length = png_strlen(purpose) + 1;
  190395. png_debug1(3, "allocating purpose for info (%lu bytes)\n", length);
  190396. info_ptr->pcal_purpose = (png_charp)png_malloc_warn(png_ptr, length);
  190397. if (info_ptr->pcal_purpose == NULL)
  190398. {
  190399. png_warning(png_ptr, "Insufficient memory for pCAL purpose.");
  190400. return;
  190401. }
  190402. png_memcpy(info_ptr->pcal_purpose, purpose, (png_size_t)length);
  190403. png_debug(3, "storing X0, X1, type, and nparams in info\n");
  190404. info_ptr->pcal_X0 = X0;
  190405. info_ptr->pcal_X1 = X1;
  190406. info_ptr->pcal_type = (png_byte)type;
  190407. info_ptr->pcal_nparams = (png_byte)nparams;
  190408. length = png_strlen(units) + 1;
  190409. png_debug1(3, "allocating units for info (%lu bytes)\n", length);
  190410. info_ptr->pcal_units = (png_charp)png_malloc_warn(png_ptr, length);
  190411. if (info_ptr->pcal_units == NULL)
  190412. {
  190413. png_warning(png_ptr, "Insufficient memory for pCAL units.");
  190414. return;
  190415. }
  190416. png_memcpy(info_ptr->pcal_units, units, (png_size_t)length);
  190417. info_ptr->pcal_params = (png_charpp)png_malloc_warn(png_ptr,
  190418. (png_uint_32)((nparams + 1) * png_sizeof(png_charp)));
  190419. if (info_ptr->pcal_params == NULL)
  190420. {
  190421. png_warning(png_ptr, "Insufficient memory for pCAL params.");
  190422. return;
  190423. }
  190424. info_ptr->pcal_params[nparams] = NULL;
  190425. for (i = 0; i < nparams; i++)
  190426. {
  190427. length = png_strlen(params[i]) + 1;
  190428. png_debug2(3, "allocating parameter %d for info (%lu bytes)\n", i, length);
  190429. info_ptr->pcal_params[i] = (png_charp)png_malloc_warn(png_ptr, length);
  190430. if (info_ptr->pcal_params[i] == NULL)
  190431. {
  190432. png_warning(png_ptr, "Insufficient memory for pCAL parameter.");
  190433. return;
  190434. }
  190435. png_memcpy(info_ptr->pcal_params[i], params[i], (png_size_t)length);
  190436. }
  190437. info_ptr->valid |= PNG_INFO_pCAL;
  190438. #ifdef PNG_FREE_ME_SUPPORTED
  190439. info_ptr->free_me |= PNG_FREE_PCAL;
  190440. #endif
  190441. }
  190442. #endif
  190443. #if defined(PNG_READ_sCAL_SUPPORTED) || defined(PNG_WRITE_sCAL_SUPPORTED)
  190444. #ifdef PNG_FLOATING_POINT_SUPPORTED
  190445. void PNGAPI
  190446. png_set_sCAL(png_structp png_ptr, png_infop info_ptr,
  190447. int unit, double width, double height)
  190448. {
  190449. png_debug1(1, "in %s storage function\n", "sCAL");
  190450. if (png_ptr == NULL || info_ptr == NULL)
  190451. return;
  190452. info_ptr->scal_unit = (png_byte)unit;
  190453. info_ptr->scal_pixel_width = width;
  190454. info_ptr->scal_pixel_height = height;
  190455. info_ptr->valid |= PNG_INFO_sCAL;
  190456. }
  190457. #else
  190458. #ifdef PNG_FIXED_POINT_SUPPORTED
  190459. void PNGAPI
  190460. png_set_sCAL_s(png_structp png_ptr, png_infop info_ptr,
  190461. int unit, png_charp swidth, png_charp sheight)
  190462. {
  190463. png_uint_32 length;
  190464. png_debug1(1, "in %s storage function\n", "sCAL");
  190465. if (png_ptr == NULL || info_ptr == NULL)
  190466. return;
  190467. info_ptr->scal_unit = (png_byte)unit;
  190468. length = png_strlen(swidth) + 1;
  190469. png_debug1(3, "allocating unit for info (%d bytes)\n", length);
  190470. info_ptr->scal_s_width = (png_charp)png_malloc_warn(png_ptr, length);
  190471. if (info_ptr->scal_s_width == NULL)
  190472. {
  190473. png_warning(png_ptr,
  190474. "Memory allocation failed while processing sCAL.");
  190475. }
  190476. png_memcpy(info_ptr->scal_s_width, swidth, (png_size_t)length);
  190477. length = png_strlen(sheight) + 1;
  190478. png_debug1(3, "allocating unit for info (%d bytes)\n", length);
  190479. info_ptr->scal_s_height = (png_charp)png_malloc_warn(png_ptr, length);
  190480. if (info_ptr->scal_s_height == NULL)
  190481. {
  190482. png_free (png_ptr, info_ptr->scal_s_width);
  190483. png_warning(png_ptr,
  190484. "Memory allocation failed while processing sCAL.");
  190485. }
  190486. png_memcpy(info_ptr->scal_s_height, sheight, (png_size_t)length);
  190487. info_ptr->valid |= PNG_INFO_sCAL;
  190488. #ifdef PNG_FREE_ME_SUPPORTED
  190489. info_ptr->free_me |= PNG_FREE_SCAL;
  190490. #endif
  190491. }
  190492. #endif
  190493. #endif
  190494. #endif
  190495. #if defined(PNG_pHYs_SUPPORTED)
  190496. void PNGAPI
  190497. png_set_pHYs(png_structp png_ptr, png_infop info_ptr,
  190498. png_uint_32 res_x, png_uint_32 res_y, int unit_type)
  190499. {
  190500. png_debug1(1, "in %s storage function\n", "pHYs");
  190501. if (png_ptr == NULL || info_ptr == NULL)
  190502. return;
  190503. info_ptr->x_pixels_per_unit = res_x;
  190504. info_ptr->y_pixels_per_unit = res_y;
  190505. info_ptr->phys_unit_type = (png_byte)unit_type;
  190506. info_ptr->valid |= PNG_INFO_pHYs;
  190507. }
  190508. #endif
  190509. void PNGAPI
  190510. png_set_PLTE(png_structp png_ptr, png_infop info_ptr,
  190511. png_colorp palette, int num_palette)
  190512. {
  190513. png_debug1(1, "in %s storage function\n", "PLTE");
  190514. if (png_ptr == NULL || info_ptr == NULL)
  190515. return;
  190516. if (num_palette < 0 || num_palette > PNG_MAX_PALETTE_LENGTH)
  190517. {
  190518. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  190519. png_error(png_ptr, "Invalid palette length");
  190520. else
  190521. {
  190522. png_warning(png_ptr, "Invalid palette length");
  190523. return;
  190524. }
  190525. }
  190526. /*
  190527. * It may not actually be necessary to set png_ptr->palette here;
  190528. * we do it for backward compatibility with the way the png_handle_tRNS
  190529. * function used to do the allocation.
  190530. */
  190531. #ifdef PNG_FREE_ME_SUPPORTED
  190532. png_free_data(png_ptr, info_ptr, PNG_FREE_PLTE, 0);
  190533. #endif
  190534. /* Changed in libpng-1.2.1 to allocate PNG_MAX_PALETTE_LENGTH instead
  190535. of num_palette entries,
  190536. in case of an invalid PNG file that has too-large sample values. */
  190537. png_ptr->palette = (png_colorp)png_malloc(png_ptr,
  190538. PNG_MAX_PALETTE_LENGTH * png_sizeof(png_color));
  190539. png_memset(png_ptr->palette, 0, PNG_MAX_PALETTE_LENGTH *
  190540. png_sizeof(png_color));
  190541. png_memcpy(png_ptr->palette, palette, num_palette * png_sizeof (png_color));
  190542. info_ptr->palette = png_ptr->palette;
  190543. info_ptr->num_palette = png_ptr->num_palette = (png_uint_16)num_palette;
  190544. #ifdef PNG_FREE_ME_SUPPORTED
  190545. info_ptr->free_me |= PNG_FREE_PLTE;
  190546. #else
  190547. png_ptr->flags |= PNG_FLAG_FREE_PLTE;
  190548. #endif
  190549. info_ptr->valid |= PNG_INFO_PLTE;
  190550. }
  190551. #if defined(PNG_sBIT_SUPPORTED)
  190552. void PNGAPI
  190553. png_set_sBIT(png_structp png_ptr, png_infop info_ptr,
  190554. png_color_8p sig_bit)
  190555. {
  190556. png_debug1(1, "in %s storage function\n", "sBIT");
  190557. if (png_ptr == NULL || info_ptr == NULL)
  190558. return;
  190559. png_memcpy(&(info_ptr->sig_bit), sig_bit, png_sizeof (png_color_8));
  190560. info_ptr->valid |= PNG_INFO_sBIT;
  190561. }
  190562. #endif
  190563. #if defined(PNG_sRGB_SUPPORTED)
  190564. void PNGAPI
  190565. png_set_sRGB(png_structp png_ptr, png_infop info_ptr, int intent)
  190566. {
  190567. png_debug1(1, "in %s storage function\n", "sRGB");
  190568. if (png_ptr == NULL || info_ptr == NULL)
  190569. return;
  190570. info_ptr->srgb_intent = (png_byte)intent;
  190571. info_ptr->valid |= PNG_INFO_sRGB;
  190572. }
  190573. void PNGAPI
  190574. png_set_sRGB_gAMA_and_cHRM(png_structp png_ptr, png_infop info_ptr,
  190575. int intent)
  190576. {
  190577. #if defined(PNG_gAMA_SUPPORTED)
  190578. #ifdef PNG_FLOATING_POINT_SUPPORTED
  190579. float file_gamma;
  190580. #endif
  190581. #ifdef PNG_FIXED_POINT_SUPPORTED
  190582. png_fixed_point int_file_gamma;
  190583. #endif
  190584. #endif
  190585. #if defined(PNG_cHRM_SUPPORTED)
  190586. #ifdef PNG_FLOATING_POINT_SUPPORTED
  190587. float white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y;
  190588. #endif
  190589. #ifdef PNG_FIXED_POINT_SUPPORTED
  190590. png_fixed_point int_white_x, int_white_y, int_red_x, int_red_y, int_green_x,
  190591. int_green_y, int_blue_x, int_blue_y;
  190592. #endif
  190593. #endif
  190594. png_debug1(1, "in %s storage function\n", "sRGB_gAMA_and_cHRM");
  190595. if (png_ptr == NULL || info_ptr == NULL)
  190596. return;
  190597. png_set_sRGB(png_ptr, info_ptr, intent);
  190598. #if defined(PNG_gAMA_SUPPORTED)
  190599. #ifdef PNG_FLOATING_POINT_SUPPORTED
  190600. file_gamma = (float).45455;
  190601. png_set_gAMA(png_ptr, info_ptr, file_gamma);
  190602. #endif
  190603. #ifdef PNG_FIXED_POINT_SUPPORTED
  190604. int_file_gamma = 45455L;
  190605. png_set_gAMA_fixed(png_ptr, info_ptr, int_file_gamma);
  190606. #endif
  190607. #endif
  190608. #if defined(PNG_cHRM_SUPPORTED)
  190609. #ifdef PNG_FIXED_POINT_SUPPORTED
  190610. int_white_x = 31270L;
  190611. int_white_y = 32900L;
  190612. int_red_x = 64000L;
  190613. int_red_y = 33000L;
  190614. int_green_x = 30000L;
  190615. int_green_y = 60000L;
  190616. int_blue_x = 15000L;
  190617. int_blue_y = 6000L;
  190618. png_set_cHRM_fixed(png_ptr, info_ptr,
  190619. int_white_x, int_white_y, int_red_x, int_red_y, int_green_x, int_green_y,
  190620. int_blue_x, int_blue_y);
  190621. #endif
  190622. #ifdef PNG_FLOATING_POINT_SUPPORTED
  190623. white_x = (float).3127;
  190624. white_y = (float).3290;
  190625. red_x = (float).64;
  190626. red_y = (float).33;
  190627. green_x = (float).30;
  190628. green_y = (float).60;
  190629. blue_x = (float).15;
  190630. blue_y = (float).06;
  190631. png_set_cHRM(png_ptr, info_ptr,
  190632. white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y);
  190633. #endif
  190634. #endif
  190635. }
  190636. #endif
  190637. #if defined(PNG_iCCP_SUPPORTED)
  190638. void PNGAPI
  190639. png_set_iCCP(png_structp png_ptr, png_infop info_ptr,
  190640. png_charp name, int compression_type,
  190641. png_charp profile, png_uint_32 proflen)
  190642. {
  190643. png_charp new_iccp_name;
  190644. png_charp new_iccp_profile;
  190645. png_debug1(1, "in %s storage function\n", "iCCP");
  190646. if (png_ptr == NULL || info_ptr == NULL || name == NULL || profile == NULL)
  190647. return;
  190648. new_iccp_name = (png_charp)png_malloc_warn(png_ptr, png_strlen(name)+1);
  190649. if (new_iccp_name == NULL)
  190650. {
  190651. png_warning(png_ptr, "Insufficient memory to process iCCP chunk.");
  190652. return;
  190653. }
  190654. png_strncpy(new_iccp_name, name, png_strlen(name)+1);
  190655. new_iccp_profile = (png_charp)png_malloc_warn(png_ptr, proflen);
  190656. if (new_iccp_profile == NULL)
  190657. {
  190658. png_free (png_ptr, new_iccp_name);
  190659. png_warning(png_ptr, "Insufficient memory to process iCCP profile.");
  190660. return;
  190661. }
  190662. png_memcpy(new_iccp_profile, profile, (png_size_t)proflen);
  190663. png_free_data(png_ptr, info_ptr, PNG_FREE_ICCP, 0);
  190664. info_ptr->iccp_proflen = proflen;
  190665. info_ptr->iccp_name = new_iccp_name;
  190666. info_ptr->iccp_profile = new_iccp_profile;
  190667. /* Compression is always zero but is here so the API and info structure
  190668. * does not have to change if we introduce multiple compression types */
  190669. info_ptr->iccp_compression = (png_byte)compression_type;
  190670. #ifdef PNG_FREE_ME_SUPPORTED
  190671. info_ptr->free_me |= PNG_FREE_ICCP;
  190672. #endif
  190673. info_ptr->valid |= PNG_INFO_iCCP;
  190674. }
  190675. #endif
  190676. #if defined(PNG_TEXT_SUPPORTED)
  190677. void PNGAPI
  190678. png_set_text(png_structp png_ptr, png_infop info_ptr, png_textp text_ptr,
  190679. int num_text)
  190680. {
  190681. int ret;
  190682. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, num_text);
  190683. if (ret)
  190684. png_error(png_ptr, "Insufficient memory to store text");
  190685. }
  190686. int /* PRIVATE */
  190687. png_set_text_2(png_structp png_ptr, png_infop info_ptr, png_textp text_ptr,
  190688. int num_text)
  190689. {
  190690. int i;
  190691. png_debug1(1, "in %s storage function\n", (png_ptr->chunk_name[0] == '\0' ?
  190692. "text" : (png_const_charp)png_ptr->chunk_name));
  190693. if (png_ptr == NULL || info_ptr == NULL || num_text == 0)
  190694. return(0);
  190695. /* Make sure we have enough space in the "text" array in info_struct
  190696. * to hold all of the incoming text_ptr objects.
  190697. */
  190698. if (info_ptr->num_text + num_text > info_ptr->max_text)
  190699. {
  190700. if (info_ptr->text != NULL)
  190701. {
  190702. png_textp old_text;
  190703. int old_max;
  190704. old_max = info_ptr->max_text;
  190705. info_ptr->max_text = info_ptr->num_text + num_text + 8;
  190706. old_text = info_ptr->text;
  190707. info_ptr->text = (png_textp)png_malloc_warn(png_ptr,
  190708. (png_uint_32)(info_ptr->max_text * png_sizeof (png_text)));
  190709. if (info_ptr->text == NULL)
  190710. {
  190711. png_free(png_ptr, old_text);
  190712. return(1);
  190713. }
  190714. png_memcpy(info_ptr->text, old_text, (png_size_t)(old_max *
  190715. png_sizeof(png_text)));
  190716. png_free(png_ptr, old_text);
  190717. }
  190718. else
  190719. {
  190720. info_ptr->max_text = num_text + 8;
  190721. info_ptr->num_text = 0;
  190722. info_ptr->text = (png_textp)png_malloc_warn(png_ptr,
  190723. (png_uint_32)(info_ptr->max_text * png_sizeof (png_text)));
  190724. if (info_ptr->text == NULL)
  190725. return(1);
  190726. #ifdef PNG_FREE_ME_SUPPORTED
  190727. info_ptr->free_me |= PNG_FREE_TEXT;
  190728. #endif
  190729. }
  190730. png_debug1(3, "allocated %d entries for info_ptr->text\n",
  190731. info_ptr->max_text);
  190732. }
  190733. for (i = 0; i < num_text; i++)
  190734. {
  190735. png_size_t text_length,key_len;
  190736. png_size_t lang_len,lang_key_len;
  190737. png_textp textp = &(info_ptr->text[info_ptr->num_text]);
  190738. if (text_ptr[i].key == NULL)
  190739. continue;
  190740. key_len = png_strlen(text_ptr[i].key);
  190741. if(text_ptr[i].compression <= 0)
  190742. {
  190743. lang_len = 0;
  190744. lang_key_len = 0;
  190745. }
  190746. else
  190747. #ifdef PNG_iTXt_SUPPORTED
  190748. {
  190749. /* set iTXt data */
  190750. if (text_ptr[i].lang != NULL)
  190751. lang_len = png_strlen(text_ptr[i].lang);
  190752. else
  190753. lang_len = 0;
  190754. if (text_ptr[i].lang_key != NULL)
  190755. lang_key_len = png_strlen(text_ptr[i].lang_key);
  190756. else
  190757. lang_key_len = 0;
  190758. }
  190759. #else
  190760. {
  190761. png_warning(png_ptr, "iTXt chunk not supported.");
  190762. continue;
  190763. }
  190764. #endif
  190765. if (text_ptr[i].text == NULL || text_ptr[i].text[0] == '\0')
  190766. {
  190767. text_length = 0;
  190768. #ifdef PNG_iTXt_SUPPORTED
  190769. if(text_ptr[i].compression > 0)
  190770. textp->compression = PNG_ITXT_COMPRESSION_NONE;
  190771. else
  190772. #endif
  190773. textp->compression = PNG_TEXT_COMPRESSION_NONE;
  190774. }
  190775. else
  190776. {
  190777. text_length = png_strlen(text_ptr[i].text);
  190778. textp->compression = text_ptr[i].compression;
  190779. }
  190780. textp->key = (png_charp)png_malloc_warn(png_ptr,
  190781. (png_uint_32)(key_len + text_length + lang_len + lang_key_len + 4));
  190782. if (textp->key == NULL)
  190783. return(1);
  190784. png_debug2(2, "Allocated %lu bytes at %x in png_set_text\n",
  190785. (png_uint_32)(key_len + lang_len + lang_key_len + text_length + 4),
  190786. (int)textp->key);
  190787. png_memcpy(textp->key, text_ptr[i].key,
  190788. (png_size_t)(key_len));
  190789. *(textp->key+key_len) = '\0';
  190790. #ifdef PNG_iTXt_SUPPORTED
  190791. if (text_ptr[i].compression > 0)
  190792. {
  190793. textp->lang=textp->key + key_len + 1;
  190794. png_memcpy(textp->lang, text_ptr[i].lang, lang_len);
  190795. *(textp->lang+lang_len) = '\0';
  190796. textp->lang_key=textp->lang + lang_len + 1;
  190797. png_memcpy(textp->lang_key, text_ptr[i].lang_key, lang_key_len);
  190798. *(textp->lang_key+lang_key_len) = '\0';
  190799. textp->text=textp->lang_key + lang_key_len + 1;
  190800. }
  190801. else
  190802. #endif
  190803. {
  190804. #ifdef PNG_iTXt_SUPPORTED
  190805. textp->lang=NULL;
  190806. textp->lang_key=NULL;
  190807. #endif
  190808. textp->text=textp->key + key_len + 1;
  190809. }
  190810. if(text_length)
  190811. png_memcpy(textp->text, text_ptr[i].text,
  190812. (png_size_t)(text_length));
  190813. *(textp->text+text_length) = '\0';
  190814. #ifdef PNG_iTXt_SUPPORTED
  190815. if(textp->compression > 0)
  190816. {
  190817. textp->text_length = 0;
  190818. textp->itxt_length = text_length;
  190819. }
  190820. else
  190821. #endif
  190822. {
  190823. textp->text_length = text_length;
  190824. #ifdef PNG_iTXt_SUPPORTED
  190825. textp->itxt_length = 0;
  190826. #endif
  190827. }
  190828. info_ptr->num_text++;
  190829. png_debug1(3, "transferred text chunk %d\n", info_ptr->num_text);
  190830. }
  190831. return(0);
  190832. }
  190833. #endif
  190834. #if defined(PNG_tIME_SUPPORTED)
  190835. void PNGAPI
  190836. png_set_tIME(png_structp png_ptr, png_infop info_ptr, png_timep mod_time)
  190837. {
  190838. png_debug1(1, "in %s storage function\n", "tIME");
  190839. if (png_ptr == NULL || info_ptr == NULL ||
  190840. (png_ptr->mode & PNG_WROTE_tIME))
  190841. return;
  190842. png_memcpy(&(info_ptr->mod_time), mod_time, png_sizeof (png_time));
  190843. info_ptr->valid |= PNG_INFO_tIME;
  190844. }
  190845. #endif
  190846. #if defined(PNG_tRNS_SUPPORTED)
  190847. void PNGAPI
  190848. png_set_tRNS(png_structp png_ptr, png_infop info_ptr,
  190849. png_bytep trans, int num_trans, png_color_16p trans_values)
  190850. {
  190851. png_debug1(1, "in %s storage function\n", "tRNS");
  190852. if (png_ptr == NULL || info_ptr == NULL)
  190853. return;
  190854. if (trans != NULL)
  190855. {
  190856. /*
  190857. * It may not actually be necessary to set png_ptr->trans here;
  190858. * we do it for backward compatibility with the way the png_handle_tRNS
  190859. * function used to do the allocation.
  190860. */
  190861. #ifdef PNG_FREE_ME_SUPPORTED
  190862. png_free_data(png_ptr, info_ptr, PNG_FREE_TRNS, 0);
  190863. #endif
  190864. /* Changed from num_trans to PNG_MAX_PALETTE_LENGTH in version 1.2.1 */
  190865. png_ptr->trans = info_ptr->trans = (png_bytep)png_malloc(png_ptr,
  190866. (png_uint_32)PNG_MAX_PALETTE_LENGTH);
  190867. if (num_trans <= PNG_MAX_PALETTE_LENGTH)
  190868. png_memcpy(info_ptr->trans, trans, (png_size_t)num_trans);
  190869. #ifdef PNG_FREE_ME_SUPPORTED
  190870. info_ptr->free_me |= PNG_FREE_TRNS;
  190871. #else
  190872. png_ptr->flags |= PNG_FLAG_FREE_TRNS;
  190873. #endif
  190874. }
  190875. if (trans_values != NULL)
  190876. {
  190877. png_memcpy(&(info_ptr->trans_values), trans_values,
  190878. png_sizeof(png_color_16));
  190879. if (num_trans == 0)
  190880. num_trans = 1;
  190881. }
  190882. info_ptr->num_trans = (png_uint_16)num_trans;
  190883. info_ptr->valid |= PNG_INFO_tRNS;
  190884. }
  190885. #endif
  190886. #if defined(PNG_sPLT_SUPPORTED)
  190887. void PNGAPI
  190888. png_set_sPLT(png_structp png_ptr,
  190889. png_infop info_ptr, png_sPLT_tp entries, int nentries)
  190890. {
  190891. png_sPLT_tp np;
  190892. int i;
  190893. if (png_ptr == NULL || info_ptr == NULL)
  190894. return;
  190895. np = (png_sPLT_tp)png_malloc_warn(png_ptr,
  190896. (info_ptr->splt_palettes_num + nentries) * png_sizeof(png_sPLT_t));
  190897. if (np == NULL)
  190898. {
  190899. png_warning(png_ptr, "No memory for sPLT palettes.");
  190900. return;
  190901. }
  190902. png_memcpy(np, info_ptr->splt_palettes,
  190903. info_ptr->splt_palettes_num * png_sizeof(png_sPLT_t));
  190904. png_free(png_ptr, info_ptr->splt_palettes);
  190905. info_ptr->splt_palettes=NULL;
  190906. for (i = 0; i < nentries; i++)
  190907. {
  190908. png_sPLT_tp to = np + info_ptr->splt_palettes_num + i;
  190909. png_sPLT_tp from = entries + i;
  190910. to->name = (png_charp)png_malloc_warn(png_ptr,
  190911. png_strlen(from->name) + 1);
  190912. if (to->name == NULL)
  190913. {
  190914. png_warning(png_ptr,
  190915. "Out of memory while processing sPLT chunk");
  190916. }
  190917. /* TODO: use png_malloc_warn */
  190918. png_strncpy(to->name, from->name, png_strlen(from->name)+1);
  190919. to->entries = (png_sPLT_entryp)png_malloc_warn(png_ptr,
  190920. from->nentries * png_sizeof(png_sPLT_entry));
  190921. /* TODO: use png_malloc_warn */
  190922. png_memcpy(to->entries, from->entries,
  190923. from->nentries * png_sizeof(png_sPLT_entry));
  190924. if (to->entries == NULL)
  190925. {
  190926. png_warning(png_ptr,
  190927. "Out of memory while processing sPLT chunk");
  190928. png_free(png_ptr,to->name);
  190929. to->name = NULL;
  190930. }
  190931. to->nentries = from->nentries;
  190932. to->depth = from->depth;
  190933. }
  190934. info_ptr->splt_palettes = np;
  190935. info_ptr->splt_palettes_num += nentries;
  190936. info_ptr->valid |= PNG_INFO_sPLT;
  190937. #ifdef PNG_FREE_ME_SUPPORTED
  190938. info_ptr->free_me |= PNG_FREE_SPLT;
  190939. #endif
  190940. }
  190941. #endif /* PNG_sPLT_SUPPORTED */
  190942. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  190943. void PNGAPI
  190944. png_set_unknown_chunks(png_structp png_ptr,
  190945. png_infop info_ptr, png_unknown_chunkp unknowns, int num_unknowns)
  190946. {
  190947. png_unknown_chunkp np;
  190948. int i;
  190949. if (png_ptr == NULL || info_ptr == NULL || num_unknowns == 0)
  190950. return;
  190951. np = (png_unknown_chunkp)png_malloc_warn(png_ptr,
  190952. (info_ptr->unknown_chunks_num + num_unknowns) *
  190953. png_sizeof(png_unknown_chunk));
  190954. if (np == NULL)
  190955. {
  190956. png_warning(png_ptr,
  190957. "Out of memory while processing unknown chunk.");
  190958. return;
  190959. }
  190960. png_memcpy(np, info_ptr->unknown_chunks,
  190961. info_ptr->unknown_chunks_num * png_sizeof(png_unknown_chunk));
  190962. png_free(png_ptr, info_ptr->unknown_chunks);
  190963. info_ptr->unknown_chunks=NULL;
  190964. for (i = 0; i < num_unknowns; i++)
  190965. {
  190966. png_unknown_chunkp to = np + info_ptr->unknown_chunks_num + i;
  190967. png_unknown_chunkp from = unknowns + i;
  190968. png_strncpy((png_charp)to->name, (png_charp)from->name, 5);
  190969. to->data = (png_bytep)png_malloc_warn(png_ptr, from->size);
  190970. if (to->data == NULL)
  190971. {
  190972. png_warning(png_ptr,
  190973. "Out of memory while processing unknown chunk.");
  190974. }
  190975. else
  190976. {
  190977. png_memcpy(to->data, from->data, from->size);
  190978. to->size = from->size;
  190979. /* note our location in the read or write sequence */
  190980. to->location = (png_byte)(png_ptr->mode & 0xff);
  190981. }
  190982. }
  190983. info_ptr->unknown_chunks = np;
  190984. info_ptr->unknown_chunks_num += num_unknowns;
  190985. #ifdef PNG_FREE_ME_SUPPORTED
  190986. info_ptr->free_me |= PNG_FREE_UNKN;
  190987. #endif
  190988. }
  190989. void PNGAPI
  190990. png_set_unknown_chunk_location(png_structp png_ptr, png_infop info_ptr,
  190991. int chunk, int location)
  190992. {
  190993. if(png_ptr != NULL && info_ptr != NULL && chunk >= 0 && chunk <
  190994. (int)info_ptr->unknown_chunks_num)
  190995. info_ptr->unknown_chunks[chunk].location = (png_byte)location;
  190996. }
  190997. #endif
  190998. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  190999. #if defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  191000. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  191001. void PNGAPI
  191002. png_permit_empty_plte (png_structp png_ptr, int empty_plte_permitted)
  191003. {
  191004. /* This function is deprecated in favor of png_permit_mng_features()
  191005. and will be removed from libpng-1.3.0 */
  191006. png_debug(1, "in png_permit_empty_plte, DEPRECATED.\n");
  191007. if (png_ptr == NULL)
  191008. return;
  191009. png_ptr->mng_features_permitted = (png_byte)
  191010. ((png_ptr->mng_features_permitted & (~(PNG_FLAG_MNG_EMPTY_PLTE))) |
  191011. ((empty_plte_permitted & PNG_FLAG_MNG_EMPTY_PLTE)));
  191012. }
  191013. #endif
  191014. #endif
  191015. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  191016. png_uint_32 PNGAPI
  191017. png_permit_mng_features (png_structp png_ptr, png_uint_32 mng_features)
  191018. {
  191019. png_debug(1, "in png_permit_mng_features\n");
  191020. if (png_ptr == NULL)
  191021. return (png_uint_32)0;
  191022. png_ptr->mng_features_permitted =
  191023. (png_byte)(mng_features & PNG_ALL_MNG_FEATURES);
  191024. return (png_uint_32)png_ptr->mng_features_permitted;
  191025. }
  191026. #endif
  191027. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  191028. void PNGAPI
  191029. png_set_keep_unknown_chunks(png_structp png_ptr, int keep, png_bytep
  191030. chunk_list, int num_chunks)
  191031. {
  191032. png_bytep new_list, p;
  191033. int i, old_num_chunks;
  191034. if (png_ptr == NULL)
  191035. return;
  191036. if (num_chunks == 0)
  191037. {
  191038. if(keep == PNG_HANDLE_CHUNK_ALWAYS || keep == PNG_HANDLE_CHUNK_IF_SAFE)
  191039. png_ptr->flags |= PNG_FLAG_KEEP_UNKNOWN_CHUNKS;
  191040. else
  191041. png_ptr->flags &= ~PNG_FLAG_KEEP_UNKNOWN_CHUNKS;
  191042. if(keep == PNG_HANDLE_CHUNK_ALWAYS)
  191043. png_ptr->flags |= PNG_FLAG_KEEP_UNSAFE_CHUNKS;
  191044. else
  191045. png_ptr->flags &= ~PNG_FLAG_KEEP_UNSAFE_CHUNKS;
  191046. return;
  191047. }
  191048. if (chunk_list == NULL)
  191049. return;
  191050. old_num_chunks=png_ptr->num_chunk_list;
  191051. new_list=(png_bytep)png_malloc(png_ptr,
  191052. (png_uint_32)(5*(num_chunks+old_num_chunks)));
  191053. if(png_ptr->chunk_list != NULL)
  191054. {
  191055. png_memcpy(new_list, png_ptr->chunk_list,
  191056. (png_size_t)(5*old_num_chunks));
  191057. png_free(png_ptr, png_ptr->chunk_list);
  191058. png_ptr->chunk_list=NULL;
  191059. }
  191060. png_memcpy(new_list+5*old_num_chunks, chunk_list,
  191061. (png_size_t)(5*num_chunks));
  191062. for (p=new_list+5*old_num_chunks+4, i=0; i<num_chunks; i++, p+=5)
  191063. *p=(png_byte)keep;
  191064. png_ptr->num_chunk_list=old_num_chunks+num_chunks;
  191065. png_ptr->chunk_list=new_list;
  191066. #ifdef PNG_FREE_ME_SUPPORTED
  191067. png_ptr->free_me |= PNG_FREE_LIST;
  191068. #endif
  191069. }
  191070. #endif
  191071. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  191072. void PNGAPI
  191073. png_set_read_user_chunk_fn(png_structp png_ptr, png_voidp user_chunk_ptr,
  191074. png_user_chunk_ptr read_user_chunk_fn)
  191075. {
  191076. png_debug(1, "in png_set_read_user_chunk_fn\n");
  191077. if (png_ptr == NULL)
  191078. return;
  191079. png_ptr->read_user_chunk_fn = read_user_chunk_fn;
  191080. png_ptr->user_chunk_ptr = user_chunk_ptr;
  191081. }
  191082. #endif
  191083. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  191084. void PNGAPI
  191085. png_set_rows(png_structp png_ptr, png_infop info_ptr, png_bytepp row_pointers)
  191086. {
  191087. png_debug1(1, "in %s storage function\n", "rows");
  191088. if (png_ptr == NULL || info_ptr == NULL)
  191089. return;
  191090. if(info_ptr->row_pointers && (info_ptr->row_pointers != row_pointers))
  191091. png_free_data(png_ptr, info_ptr, PNG_FREE_ROWS, 0);
  191092. info_ptr->row_pointers = row_pointers;
  191093. if(row_pointers)
  191094. info_ptr->valid |= PNG_INFO_IDAT;
  191095. }
  191096. #endif
  191097. #ifdef PNG_WRITE_SUPPORTED
  191098. void PNGAPI
  191099. png_set_compression_buffer_size(png_structp png_ptr, png_uint_32 size)
  191100. {
  191101. if (png_ptr == NULL)
  191102. return;
  191103. if(png_ptr->zbuf)
  191104. png_free(png_ptr, png_ptr->zbuf);
  191105. png_ptr->zbuf_size = (png_size_t)size;
  191106. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr, size);
  191107. png_ptr->zstream.next_out = png_ptr->zbuf;
  191108. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  191109. }
  191110. #endif
  191111. void PNGAPI
  191112. png_set_invalid(png_structp png_ptr, png_infop info_ptr, int mask)
  191113. {
  191114. if (png_ptr && info_ptr)
  191115. info_ptr->valid &= ~(mask);
  191116. }
  191117. #ifndef PNG_1_0_X
  191118. #ifdef PNG_ASSEMBLER_CODE_SUPPORTED
  191119. /* function was added to libpng 1.2.0 and should always exist by default */
  191120. void PNGAPI
  191121. png_set_asm_flags (png_structp png_ptr, png_uint_32 asm_flags)
  191122. {
  191123. /* Obsolete as of libpng-1.2.20 and will be removed from libpng-1.4.0 */
  191124. if (png_ptr != NULL)
  191125. png_ptr->asm_flags = 0;
  191126. }
  191127. /* this function was added to libpng 1.2.0 */
  191128. void PNGAPI
  191129. png_set_mmx_thresholds (png_structp png_ptr,
  191130. png_byte mmx_bitdepth_threshold,
  191131. png_uint_32 mmx_rowbytes_threshold)
  191132. {
  191133. /* Obsolete as of libpng-1.2.20 and will be removed from libpng-1.4.0 */
  191134. if (png_ptr == NULL)
  191135. return;
  191136. }
  191137. #endif /* ?PNG_ASSEMBLER_CODE_SUPPORTED */
  191138. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  191139. /* this function was added to libpng 1.2.6 */
  191140. void PNGAPI
  191141. png_set_user_limits (png_structp png_ptr, png_uint_32 user_width_max,
  191142. png_uint_32 user_height_max)
  191143. {
  191144. /* Images with dimensions larger than these limits will be
  191145. * rejected by png_set_IHDR(). To accept any PNG datastream
  191146. * regardless of dimensions, set both limits to 0x7ffffffL.
  191147. */
  191148. if(png_ptr == NULL) return;
  191149. png_ptr->user_width_max = user_width_max;
  191150. png_ptr->user_height_max = user_height_max;
  191151. }
  191152. #endif /* ?PNG_SET_USER_LIMITS_SUPPORTED */
  191153. #endif /* ?PNG_1_0_X */
  191154. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  191155. /********* End of inlined file: pngset.c *********/
  191156. /********* Start of inlined file: pngtrans.c *********/
  191157. /* pngtrans.c - transforms the data in a row (used by both readers and writers)
  191158. *
  191159. * Last changed in libpng 1.2.17 May 15, 2007
  191160. * For conditions of distribution and use, see copyright notice in png.h
  191161. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  191162. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  191163. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  191164. */
  191165. #define PNG_INTERNAL
  191166. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  191167. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  191168. /* turn on BGR-to-RGB mapping */
  191169. void PNGAPI
  191170. png_set_bgr(png_structp png_ptr)
  191171. {
  191172. png_debug(1, "in png_set_bgr\n");
  191173. if(png_ptr == NULL) return;
  191174. png_ptr->transformations |= PNG_BGR;
  191175. }
  191176. #endif
  191177. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  191178. /* turn on 16 bit byte swapping */
  191179. void PNGAPI
  191180. png_set_swap(png_structp png_ptr)
  191181. {
  191182. png_debug(1, "in png_set_swap\n");
  191183. if(png_ptr == NULL) return;
  191184. if (png_ptr->bit_depth == 16)
  191185. png_ptr->transformations |= PNG_SWAP_BYTES;
  191186. }
  191187. #endif
  191188. #if defined(PNG_READ_PACK_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED)
  191189. /* turn on pixel packing */
  191190. void PNGAPI
  191191. png_set_packing(png_structp png_ptr)
  191192. {
  191193. png_debug(1, "in png_set_packing\n");
  191194. if(png_ptr == NULL) return;
  191195. if (png_ptr->bit_depth < 8)
  191196. {
  191197. png_ptr->transformations |= PNG_PACK;
  191198. png_ptr->usr_bit_depth = 8;
  191199. }
  191200. }
  191201. #endif
  191202. #if defined(PNG_READ_PACKSWAP_SUPPORTED)||defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  191203. /* turn on packed pixel swapping */
  191204. void PNGAPI
  191205. png_set_packswap(png_structp png_ptr)
  191206. {
  191207. png_debug(1, "in png_set_packswap\n");
  191208. if(png_ptr == NULL) return;
  191209. if (png_ptr->bit_depth < 8)
  191210. png_ptr->transformations |= PNG_PACKSWAP;
  191211. }
  191212. #endif
  191213. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  191214. void PNGAPI
  191215. png_set_shift(png_structp png_ptr, png_color_8p true_bits)
  191216. {
  191217. png_debug(1, "in png_set_shift\n");
  191218. if(png_ptr == NULL) return;
  191219. png_ptr->transformations |= PNG_SHIFT;
  191220. png_ptr->shift = *true_bits;
  191221. }
  191222. #endif
  191223. #if defined(PNG_READ_INTERLACING_SUPPORTED) || \
  191224. defined(PNG_WRITE_INTERLACING_SUPPORTED)
  191225. int PNGAPI
  191226. png_set_interlace_handling(png_structp png_ptr)
  191227. {
  191228. png_debug(1, "in png_set_interlace handling\n");
  191229. if (png_ptr && png_ptr->interlaced)
  191230. {
  191231. png_ptr->transformations |= PNG_INTERLACE;
  191232. return (7);
  191233. }
  191234. return (1);
  191235. }
  191236. #endif
  191237. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  191238. /* Add a filler byte on read, or remove a filler or alpha byte on write.
  191239. * The filler type has changed in v0.95 to allow future 2-byte fillers
  191240. * for 48-bit input data, as well as to avoid problems with some compilers
  191241. * that don't like bytes as parameters.
  191242. */
  191243. void PNGAPI
  191244. png_set_filler(png_structp png_ptr, png_uint_32 filler, int filler_loc)
  191245. {
  191246. png_debug(1, "in png_set_filler\n");
  191247. if(png_ptr == NULL) return;
  191248. png_ptr->transformations |= PNG_FILLER;
  191249. png_ptr->filler = (png_byte)filler;
  191250. if (filler_loc == PNG_FILLER_AFTER)
  191251. png_ptr->flags |= PNG_FLAG_FILLER_AFTER;
  191252. else
  191253. png_ptr->flags &= ~PNG_FLAG_FILLER_AFTER;
  191254. /* This should probably go in the "do_read_filler" routine.
  191255. * I attempted to do that in libpng-1.0.1a but that caused problems
  191256. * so I restored it in libpng-1.0.2a
  191257. */
  191258. if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  191259. {
  191260. png_ptr->usr_channels = 4;
  191261. }
  191262. /* Also I added this in libpng-1.0.2a (what happens when we expand
  191263. * a less-than-8-bit grayscale to GA? */
  191264. if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY && png_ptr->bit_depth >= 8)
  191265. {
  191266. png_ptr->usr_channels = 2;
  191267. }
  191268. }
  191269. #if !defined(PNG_1_0_X)
  191270. /* Added to libpng-1.2.7 */
  191271. void PNGAPI
  191272. png_set_add_alpha(png_structp png_ptr, png_uint_32 filler, int filler_loc)
  191273. {
  191274. png_debug(1, "in png_set_add_alpha\n");
  191275. if(png_ptr == NULL) return;
  191276. png_set_filler(png_ptr, filler, filler_loc);
  191277. png_ptr->transformations |= PNG_ADD_ALPHA;
  191278. }
  191279. #endif
  191280. #endif
  191281. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED) || \
  191282. defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  191283. void PNGAPI
  191284. png_set_swap_alpha(png_structp png_ptr)
  191285. {
  191286. png_debug(1, "in png_set_swap_alpha\n");
  191287. if(png_ptr == NULL) return;
  191288. png_ptr->transformations |= PNG_SWAP_ALPHA;
  191289. }
  191290. #endif
  191291. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED) || \
  191292. defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  191293. void PNGAPI
  191294. png_set_invert_alpha(png_structp png_ptr)
  191295. {
  191296. png_debug(1, "in png_set_invert_alpha\n");
  191297. if(png_ptr == NULL) return;
  191298. png_ptr->transformations |= PNG_INVERT_ALPHA;
  191299. }
  191300. #endif
  191301. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  191302. void PNGAPI
  191303. png_set_invert_mono(png_structp png_ptr)
  191304. {
  191305. png_debug(1, "in png_set_invert_mono\n");
  191306. if(png_ptr == NULL) return;
  191307. png_ptr->transformations |= PNG_INVERT_MONO;
  191308. }
  191309. /* invert monochrome grayscale data */
  191310. void /* PRIVATE */
  191311. png_do_invert(png_row_infop row_info, png_bytep row)
  191312. {
  191313. png_debug(1, "in png_do_invert\n");
  191314. /* This test removed from libpng version 1.0.13 and 1.2.0:
  191315. * if (row_info->bit_depth == 1 &&
  191316. */
  191317. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191318. if (row == NULL || row_info == NULL)
  191319. return;
  191320. #endif
  191321. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  191322. {
  191323. png_bytep rp = row;
  191324. png_uint_32 i;
  191325. png_uint_32 istop = row_info->rowbytes;
  191326. for (i = 0; i < istop; i++)
  191327. {
  191328. *rp = (png_byte)(~(*rp));
  191329. rp++;
  191330. }
  191331. }
  191332. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  191333. row_info->bit_depth == 8)
  191334. {
  191335. png_bytep rp = row;
  191336. png_uint_32 i;
  191337. png_uint_32 istop = row_info->rowbytes;
  191338. for (i = 0; i < istop; i+=2)
  191339. {
  191340. *rp = (png_byte)(~(*rp));
  191341. rp+=2;
  191342. }
  191343. }
  191344. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  191345. row_info->bit_depth == 16)
  191346. {
  191347. png_bytep rp = row;
  191348. png_uint_32 i;
  191349. png_uint_32 istop = row_info->rowbytes;
  191350. for (i = 0; i < istop; i+=4)
  191351. {
  191352. *rp = (png_byte)(~(*rp));
  191353. *(rp+1) = (png_byte)(~(*(rp+1)));
  191354. rp+=4;
  191355. }
  191356. }
  191357. }
  191358. #endif
  191359. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  191360. /* swaps byte order on 16 bit depth images */
  191361. void /* PRIVATE */
  191362. png_do_swap(png_row_infop row_info, png_bytep row)
  191363. {
  191364. png_debug(1, "in png_do_swap\n");
  191365. if (
  191366. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191367. row != NULL && row_info != NULL &&
  191368. #endif
  191369. row_info->bit_depth == 16)
  191370. {
  191371. png_bytep rp = row;
  191372. png_uint_32 i;
  191373. png_uint_32 istop= row_info->width * row_info->channels;
  191374. for (i = 0; i < istop; i++, rp += 2)
  191375. {
  191376. png_byte t = *rp;
  191377. *rp = *(rp + 1);
  191378. *(rp + 1) = t;
  191379. }
  191380. }
  191381. }
  191382. #endif
  191383. #if defined(PNG_READ_PACKSWAP_SUPPORTED)||defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  191384. static PNG_CONST png_byte onebppswaptable[256] = {
  191385. 0x00, 0x80, 0x40, 0xC0, 0x20, 0xA0, 0x60, 0xE0,
  191386. 0x10, 0x90, 0x50, 0xD0, 0x30, 0xB0, 0x70, 0xF0,
  191387. 0x08, 0x88, 0x48, 0xC8, 0x28, 0xA8, 0x68, 0xE8,
  191388. 0x18, 0x98, 0x58, 0xD8, 0x38, 0xB8, 0x78, 0xF8,
  191389. 0x04, 0x84, 0x44, 0xC4, 0x24, 0xA4, 0x64, 0xE4,
  191390. 0x14, 0x94, 0x54, 0xD4, 0x34, 0xB4, 0x74, 0xF4,
  191391. 0x0C, 0x8C, 0x4C, 0xCC, 0x2C, 0xAC, 0x6C, 0xEC,
  191392. 0x1C, 0x9C, 0x5C, 0xDC, 0x3C, 0xBC, 0x7C, 0xFC,
  191393. 0x02, 0x82, 0x42, 0xC2, 0x22, 0xA2, 0x62, 0xE2,
  191394. 0x12, 0x92, 0x52, 0xD2, 0x32, 0xB2, 0x72, 0xF2,
  191395. 0x0A, 0x8A, 0x4A, 0xCA, 0x2A, 0xAA, 0x6A, 0xEA,
  191396. 0x1A, 0x9A, 0x5A, 0xDA, 0x3A, 0xBA, 0x7A, 0xFA,
  191397. 0x06, 0x86, 0x46, 0xC6, 0x26, 0xA6, 0x66, 0xE6,
  191398. 0x16, 0x96, 0x56, 0xD6, 0x36, 0xB6, 0x76, 0xF6,
  191399. 0x0E, 0x8E, 0x4E, 0xCE, 0x2E, 0xAE, 0x6E, 0xEE,
  191400. 0x1E, 0x9E, 0x5E, 0xDE, 0x3E, 0xBE, 0x7E, 0xFE,
  191401. 0x01, 0x81, 0x41, 0xC1, 0x21, 0xA1, 0x61, 0xE1,
  191402. 0x11, 0x91, 0x51, 0xD1, 0x31, 0xB1, 0x71, 0xF1,
  191403. 0x09, 0x89, 0x49, 0xC9, 0x29, 0xA9, 0x69, 0xE9,
  191404. 0x19, 0x99, 0x59, 0xD9, 0x39, 0xB9, 0x79, 0xF9,
  191405. 0x05, 0x85, 0x45, 0xC5, 0x25, 0xA5, 0x65, 0xE5,
  191406. 0x15, 0x95, 0x55, 0xD5, 0x35, 0xB5, 0x75, 0xF5,
  191407. 0x0D, 0x8D, 0x4D, 0xCD, 0x2D, 0xAD, 0x6D, 0xED,
  191408. 0x1D, 0x9D, 0x5D, 0xDD, 0x3D, 0xBD, 0x7D, 0xFD,
  191409. 0x03, 0x83, 0x43, 0xC3, 0x23, 0xA3, 0x63, 0xE3,
  191410. 0x13, 0x93, 0x53, 0xD3, 0x33, 0xB3, 0x73, 0xF3,
  191411. 0x0B, 0x8B, 0x4B, 0xCB, 0x2B, 0xAB, 0x6B, 0xEB,
  191412. 0x1B, 0x9B, 0x5B, 0xDB, 0x3B, 0xBB, 0x7B, 0xFB,
  191413. 0x07, 0x87, 0x47, 0xC7, 0x27, 0xA7, 0x67, 0xE7,
  191414. 0x17, 0x97, 0x57, 0xD7, 0x37, 0xB7, 0x77, 0xF7,
  191415. 0x0F, 0x8F, 0x4F, 0xCF, 0x2F, 0xAF, 0x6F, 0xEF,
  191416. 0x1F, 0x9F, 0x5F, 0xDF, 0x3F, 0xBF, 0x7F, 0xFF
  191417. };
  191418. static PNG_CONST png_byte twobppswaptable[256] = {
  191419. 0x00, 0x40, 0x80, 0xC0, 0x10, 0x50, 0x90, 0xD0,
  191420. 0x20, 0x60, 0xA0, 0xE0, 0x30, 0x70, 0xB0, 0xF0,
  191421. 0x04, 0x44, 0x84, 0xC4, 0x14, 0x54, 0x94, 0xD4,
  191422. 0x24, 0x64, 0xA4, 0xE4, 0x34, 0x74, 0xB4, 0xF4,
  191423. 0x08, 0x48, 0x88, 0xC8, 0x18, 0x58, 0x98, 0xD8,
  191424. 0x28, 0x68, 0xA8, 0xE8, 0x38, 0x78, 0xB8, 0xF8,
  191425. 0x0C, 0x4C, 0x8C, 0xCC, 0x1C, 0x5C, 0x9C, 0xDC,
  191426. 0x2C, 0x6C, 0xAC, 0xEC, 0x3C, 0x7C, 0xBC, 0xFC,
  191427. 0x01, 0x41, 0x81, 0xC1, 0x11, 0x51, 0x91, 0xD1,
  191428. 0x21, 0x61, 0xA1, 0xE1, 0x31, 0x71, 0xB1, 0xF1,
  191429. 0x05, 0x45, 0x85, 0xC5, 0x15, 0x55, 0x95, 0xD5,
  191430. 0x25, 0x65, 0xA5, 0xE5, 0x35, 0x75, 0xB5, 0xF5,
  191431. 0x09, 0x49, 0x89, 0xC9, 0x19, 0x59, 0x99, 0xD9,
  191432. 0x29, 0x69, 0xA9, 0xE9, 0x39, 0x79, 0xB9, 0xF9,
  191433. 0x0D, 0x4D, 0x8D, 0xCD, 0x1D, 0x5D, 0x9D, 0xDD,
  191434. 0x2D, 0x6D, 0xAD, 0xED, 0x3D, 0x7D, 0xBD, 0xFD,
  191435. 0x02, 0x42, 0x82, 0xC2, 0x12, 0x52, 0x92, 0xD2,
  191436. 0x22, 0x62, 0xA2, 0xE2, 0x32, 0x72, 0xB2, 0xF2,
  191437. 0x06, 0x46, 0x86, 0xC6, 0x16, 0x56, 0x96, 0xD6,
  191438. 0x26, 0x66, 0xA6, 0xE6, 0x36, 0x76, 0xB6, 0xF6,
  191439. 0x0A, 0x4A, 0x8A, 0xCA, 0x1A, 0x5A, 0x9A, 0xDA,
  191440. 0x2A, 0x6A, 0xAA, 0xEA, 0x3A, 0x7A, 0xBA, 0xFA,
  191441. 0x0E, 0x4E, 0x8E, 0xCE, 0x1E, 0x5E, 0x9E, 0xDE,
  191442. 0x2E, 0x6E, 0xAE, 0xEE, 0x3E, 0x7E, 0xBE, 0xFE,
  191443. 0x03, 0x43, 0x83, 0xC3, 0x13, 0x53, 0x93, 0xD3,
  191444. 0x23, 0x63, 0xA3, 0xE3, 0x33, 0x73, 0xB3, 0xF3,
  191445. 0x07, 0x47, 0x87, 0xC7, 0x17, 0x57, 0x97, 0xD7,
  191446. 0x27, 0x67, 0xA7, 0xE7, 0x37, 0x77, 0xB7, 0xF7,
  191447. 0x0B, 0x4B, 0x8B, 0xCB, 0x1B, 0x5B, 0x9B, 0xDB,
  191448. 0x2B, 0x6B, 0xAB, 0xEB, 0x3B, 0x7B, 0xBB, 0xFB,
  191449. 0x0F, 0x4F, 0x8F, 0xCF, 0x1F, 0x5F, 0x9F, 0xDF,
  191450. 0x2F, 0x6F, 0xAF, 0xEF, 0x3F, 0x7F, 0xBF, 0xFF
  191451. };
  191452. static PNG_CONST png_byte fourbppswaptable[256] = {
  191453. 0x00, 0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70,
  191454. 0x80, 0x90, 0xA0, 0xB0, 0xC0, 0xD0, 0xE0, 0xF0,
  191455. 0x01, 0x11, 0x21, 0x31, 0x41, 0x51, 0x61, 0x71,
  191456. 0x81, 0x91, 0xA1, 0xB1, 0xC1, 0xD1, 0xE1, 0xF1,
  191457. 0x02, 0x12, 0x22, 0x32, 0x42, 0x52, 0x62, 0x72,
  191458. 0x82, 0x92, 0xA2, 0xB2, 0xC2, 0xD2, 0xE2, 0xF2,
  191459. 0x03, 0x13, 0x23, 0x33, 0x43, 0x53, 0x63, 0x73,
  191460. 0x83, 0x93, 0xA3, 0xB3, 0xC3, 0xD3, 0xE3, 0xF3,
  191461. 0x04, 0x14, 0x24, 0x34, 0x44, 0x54, 0x64, 0x74,
  191462. 0x84, 0x94, 0xA4, 0xB4, 0xC4, 0xD4, 0xE4, 0xF4,
  191463. 0x05, 0x15, 0x25, 0x35, 0x45, 0x55, 0x65, 0x75,
  191464. 0x85, 0x95, 0xA5, 0xB5, 0xC5, 0xD5, 0xE5, 0xF5,
  191465. 0x06, 0x16, 0x26, 0x36, 0x46, 0x56, 0x66, 0x76,
  191466. 0x86, 0x96, 0xA6, 0xB6, 0xC6, 0xD6, 0xE6, 0xF6,
  191467. 0x07, 0x17, 0x27, 0x37, 0x47, 0x57, 0x67, 0x77,
  191468. 0x87, 0x97, 0xA7, 0xB7, 0xC7, 0xD7, 0xE7, 0xF7,
  191469. 0x08, 0x18, 0x28, 0x38, 0x48, 0x58, 0x68, 0x78,
  191470. 0x88, 0x98, 0xA8, 0xB8, 0xC8, 0xD8, 0xE8, 0xF8,
  191471. 0x09, 0x19, 0x29, 0x39, 0x49, 0x59, 0x69, 0x79,
  191472. 0x89, 0x99, 0xA9, 0xB9, 0xC9, 0xD9, 0xE9, 0xF9,
  191473. 0x0A, 0x1A, 0x2A, 0x3A, 0x4A, 0x5A, 0x6A, 0x7A,
  191474. 0x8A, 0x9A, 0xAA, 0xBA, 0xCA, 0xDA, 0xEA, 0xFA,
  191475. 0x0B, 0x1B, 0x2B, 0x3B, 0x4B, 0x5B, 0x6B, 0x7B,
  191476. 0x8B, 0x9B, 0xAB, 0xBB, 0xCB, 0xDB, 0xEB, 0xFB,
  191477. 0x0C, 0x1C, 0x2C, 0x3C, 0x4C, 0x5C, 0x6C, 0x7C,
  191478. 0x8C, 0x9C, 0xAC, 0xBC, 0xCC, 0xDC, 0xEC, 0xFC,
  191479. 0x0D, 0x1D, 0x2D, 0x3D, 0x4D, 0x5D, 0x6D, 0x7D,
  191480. 0x8D, 0x9D, 0xAD, 0xBD, 0xCD, 0xDD, 0xED, 0xFD,
  191481. 0x0E, 0x1E, 0x2E, 0x3E, 0x4E, 0x5E, 0x6E, 0x7E,
  191482. 0x8E, 0x9E, 0xAE, 0xBE, 0xCE, 0xDE, 0xEE, 0xFE,
  191483. 0x0F, 0x1F, 0x2F, 0x3F, 0x4F, 0x5F, 0x6F, 0x7F,
  191484. 0x8F, 0x9F, 0xAF, 0xBF, 0xCF, 0xDF, 0xEF, 0xFF
  191485. };
  191486. /* swaps pixel packing order within bytes */
  191487. void /* PRIVATE */
  191488. png_do_packswap(png_row_infop row_info, png_bytep row)
  191489. {
  191490. png_debug(1, "in png_do_packswap\n");
  191491. if (
  191492. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191493. row != NULL && row_info != NULL &&
  191494. #endif
  191495. row_info->bit_depth < 8)
  191496. {
  191497. png_bytep rp, end, table;
  191498. end = row + row_info->rowbytes;
  191499. if (row_info->bit_depth == 1)
  191500. table = (png_bytep)onebppswaptable;
  191501. else if (row_info->bit_depth == 2)
  191502. table = (png_bytep)twobppswaptable;
  191503. else if (row_info->bit_depth == 4)
  191504. table = (png_bytep)fourbppswaptable;
  191505. else
  191506. return;
  191507. for (rp = row; rp < end; rp++)
  191508. *rp = table[*rp];
  191509. }
  191510. }
  191511. #endif /* PNG_READ_PACKSWAP_SUPPORTED or PNG_WRITE_PACKSWAP_SUPPORTED */
  191512. #if defined(PNG_WRITE_FILLER_SUPPORTED) || \
  191513. defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  191514. /* remove filler or alpha byte(s) */
  191515. void /* PRIVATE */
  191516. png_do_strip_filler(png_row_infop row_info, png_bytep row, png_uint_32 flags)
  191517. {
  191518. png_debug(1, "in png_do_strip_filler\n");
  191519. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191520. if (row != NULL && row_info != NULL)
  191521. #endif
  191522. {
  191523. png_bytep sp=row;
  191524. png_bytep dp=row;
  191525. png_uint_32 row_width=row_info->width;
  191526. png_uint_32 i;
  191527. if ((row_info->color_type == PNG_COLOR_TYPE_RGB ||
  191528. (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA &&
  191529. (flags & PNG_FLAG_STRIP_ALPHA))) &&
  191530. row_info->channels == 4)
  191531. {
  191532. if (row_info->bit_depth == 8)
  191533. {
  191534. /* This converts from RGBX or RGBA to RGB */
  191535. if (flags & PNG_FLAG_FILLER_AFTER)
  191536. {
  191537. dp+=3; sp+=4;
  191538. for (i = 1; i < row_width; i++)
  191539. {
  191540. *dp++ = *sp++;
  191541. *dp++ = *sp++;
  191542. *dp++ = *sp++;
  191543. sp++;
  191544. }
  191545. }
  191546. /* This converts from XRGB or ARGB to RGB */
  191547. else
  191548. {
  191549. for (i = 0; i < row_width; i++)
  191550. {
  191551. sp++;
  191552. *dp++ = *sp++;
  191553. *dp++ = *sp++;
  191554. *dp++ = *sp++;
  191555. }
  191556. }
  191557. row_info->pixel_depth = 24;
  191558. row_info->rowbytes = row_width * 3;
  191559. }
  191560. else /* if (row_info->bit_depth == 16) */
  191561. {
  191562. if (flags & PNG_FLAG_FILLER_AFTER)
  191563. {
  191564. /* This converts from RRGGBBXX or RRGGBBAA to RRGGBB */
  191565. sp += 8; dp += 6;
  191566. for (i = 1; i < row_width; i++)
  191567. {
  191568. /* This could be (although png_memcpy is probably slower):
  191569. png_memcpy(dp, sp, 6);
  191570. sp += 8;
  191571. dp += 6;
  191572. */
  191573. *dp++ = *sp++;
  191574. *dp++ = *sp++;
  191575. *dp++ = *sp++;
  191576. *dp++ = *sp++;
  191577. *dp++ = *sp++;
  191578. *dp++ = *sp++;
  191579. sp += 2;
  191580. }
  191581. }
  191582. else
  191583. {
  191584. /* This converts from XXRRGGBB or AARRGGBB to RRGGBB */
  191585. for (i = 0; i < row_width; i++)
  191586. {
  191587. /* This could be (although png_memcpy is probably slower):
  191588. png_memcpy(dp, sp, 6);
  191589. sp += 8;
  191590. dp += 6;
  191591. */
  191592. sp+=2;
  191593. *dp++ = *sp++;
  191594. *dp++ = *sp++;
  191595. *dp++ = *sp++;
  191596. *dp++ = *sp++;
  191597. *dp++ = *sp++;
  191598. *dp++ = *sp++;
  191599. }
  191600. }
  191601. row_info->pixel_depth = 48;
  191602. row_info->rowbytes = row_width * 6;
  191603. }
  191604. row_info->channels = 3;
  191605. }
  191606. else if ((row_info->color_type == PNG_COLOR_TYPE_GRAY ||
  191607. (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  191608. (flags & PNG_FLAG_STRIP_ALPHA))) &&
  191609. row_info->channels == 2)
  191610. {
  191611. if (row_info->bit_depth == 8)
  191612. {
  191613. /* This converts from GX or GA to G */
  191614. if (flags & PNG_FLAG_FILLER_AFTER)
  191615. {
  191616. for (i = 0; i < row_width; i++)
  191617. {
  191618. *dp++ = *sp++;
  191619. sp++;
  191620. }
  191621. }
  191622. /* This converts from XG or AG to G */
  191623. else
  191624. {
  191625. for (i = 0; i < row_width; i++)
  191626. {
  191627. sp++;
  191628. *dp++ = *sp++;
  191629. }
  191630. }
  191631. row_info->pixel_depth = 8;
  191632. row_info->rowbytes = row_width;
  191633. }
  191634. else /* if (row_info->bit_depth == 16) */
  191635. {
  191636. if (flags & PNG_FLAG_FILLER_AFTER)
  191637. {
  191638. /* This converts from GGXX or GGAA to GG */
  191639. sp += 4; dp += 2;
  191640. for (i = 1; i < row_width; i++)
  191641. {
  191642. *dp++ = *sp++;
  191643. *dp++ = *sp++;
  191644. sp += 2;
  191645. }
  191646. }
  191647. else
  191648. {
  191649. /* This converts from XXGG or AAGG to GG */
  191650. for (i = 0; i < row_width; i++)
  191651. {
  191652. sp += 2;
  191653. *dp++ = *sp++;
  191654. *dp++ = *sp++;
  191655. }
  191656. }
  191657. row_info->pixel_depth = 16;
  191658. row_info->rowbytes = row_width * 2;
  191659. }
  191660. row_info->channels = 1;
  191661. }
  191662. if (flags & PNG_FLAG_STRIP_ALPHA)
  191663. row_info->color_type &= ~PNG_COLOR_MASK_ALPHA;
  191664. }
  191665. }
  191666. #endif
  191667. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  191668. /* swaps red and blue bytes within a pixel */
  191669. void /* PRIVATE */
  191670. png_do_bgr(png_row_infop row_info, png_bytep row)
  191671. {
  191672. png_debug(1, "in png_do_bgr\n");
  191673. if (
  191674. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191675. row != NULL && row_info != NULL &&
  191676. #endif
  191677. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  191678. {
  191679. png_uint_32 row_width = row_info->width;
  191680. if (row_info->bit_depth == 8)
  191681. {
  191682. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  191683. {
  191684. png_bytep rp;
  191685. png_uint_32 i;
  191686. for (i = 0, rp = row; i < row_width; i++, rp += 3)
  191687. {
  191688. png_byte save = *rp;
  191689. *rp = *(rp + 2);
  191690. *(rp + 2) = save;
  191691. }
  191692. }
  191693. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  191694. {
  191695. png_bytep rp;
  191696. png_uint_32 i;
  191697. for (i = 0, rp = row; i < row_width; i++, rp += 4)
  191698. {
  191699. png_byte save = *rp;
  191700. *rp = *(rp + 2);
  191701. *(rp + 2) = save;
  191702. }
  191703. }
  191704. }
  191705. else if (row_info->bit_depth == 16)
  191706. {
  191707. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  191708. {
  191709. png_bytep rp;
  191710. png_uint_32 i;
  191711. for (i = 0, rp = row; i < row_width; i++, rp += 6)
  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. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  191722. {
  191723. png_bytep rp;
  191724. png_uint_32 i;
  191725. for (i = 0, rp = row; i < row_width; i++, rp += 8)
  191726. {
  191727. png_byte save = *rp;
  191728. *rp = *(rp + 4);
  191729. *(rp + 4) = save;
  191730. save = *(rp + 1);
  191731. *(rp + 1) = *(rp + 5);
  191732. *(rp + 5) = save;
  191733. }
  191734. }
  191735. }
  191736. }
  191737. }
  191738. #endif /* PNG_READ_BGR_SUPPORTED or PNG_WRITE_BGR_SUPPORTED */
  191739. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  191740. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  191741. defined(PNG_LEGACY_SUPPORTED)
  191742. void PNGAPI
  191743. png_set_user_transform_info(png_structp png_ptr, png_voidp
  191744. user_transform_ptr, int user_transform_depth, int user_transform_channels)
  191745. {
  191746. png_debug(1, "in png_set_user_transform_info\n");
  191747. if(png_ptr == NULL) return;
  191748. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  191749. png_ptr->user_transform_ptr = user_transform_ptr;
  191750. png_ptr->user_transform_depth = (png_byte)user_transform_depth;
  191751. png_ptr->user_transform_channels = (png_byte)user_transform_channels;
  191752. #else
  191753. if(user_transform_ptr || user_transform_depth || user_transform_channels)
  191754. png_warning(png_ptr,
  191755. "This version of libpng does not support user transform info");
  191756. #endif
  191757. }
  191758. #endif
  191759. /* This function returns a pointer to the user_transform_ptr associated with
  191760. * the user transform functions. The application should free any memory
  191761. * associated with this pointer before png_write_destroy and png_read_destroy
  191762. * are called.
  191763. */
  191764. png_voidp PNGAPI
  191765. png_get_user_transform_ptr(png_structp png_ptr)
  191766. {
  191767. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  191768. if (png_ptr == NULL) return (NULL);
  191769. return ((png_voidp)png_ptr->user_transform_ptr);
  191770. #else
  191771. return (NULL);
  191772. #endif
  191773. }
  191774. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  191775. /********* End of inlined file: pngtrans.c *********/
  191776. /********* Start of inlined file: pngwio.c *********/
  191777. /* pngwio.c - functions for data output
  191778. *
  191779. * Last changed in libpng 1.2.13 November 13, 2006
  191780. * For conditions of distribution and use, see copyright notice in png.h
  191781. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  191782. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  191783. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  191784. *
  191785. * This file provides a location for all output. Users who need
  191786. * special handling are expected to write functions that have the same
  191787. * arguments as these and perform similar functions, but that possibly
  191788. * use different output methods. Note that you shouldn't change these
  191789. * functions, but rather write replacement functions and then change
  191790. * them at run time with png_set_write_fn(...).
  191791. */
  191792. #define PNG_INTERNAL
  191793. #ifdef PNG_WRITE_SUPPORTED
  191794. /* Write the data to whatever output you are using. The default routine
  191795. writes to a file pointer. Note that this routine sometimes gets called
  191796. with very small lengths, so you should implement some kind of simple
  191797. buffering if you are using unbuffered writes. This should never be asked
  191798. to write more than 64K on a 16 bit machine. */
  191799. void /* PRIVATE */
  191800. png_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  191801. {
  191802. if (png_ptr->write_data_fn != NULL )
  191803. (*(png_ptr->write_data_fn))(png_ptr, data, length);
  191804. else
  191805. png_error(png_ptr, "Call to NULL write function");
  191806. }
  191807. #if !defined(PNG_NO_STDIO)
  191808. /* This is the function that does the actual writing of data. If you are
  191809. not writing to a standard C stream, you should create a replacement
  191810. write_data function and use it at run time with png_set_write_fn(), rather
  191811. than changing the library. */
  191812. #ifndef USE_FAR_KEYWORD
  191813. void PNGAPI
  191814. png_default_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  191815. {
  191816. png_uint_32 check;
  191817. if(png_ptr == NULL) return;
  191818. #if defined(_WIN32_WCE)
  191819. if ( !WriteFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  191820. check = 0;
  191821. #else
  191822. check = fwrite(data, 1, length, (png_FILE_p)(png_ptr->io_ptr));
  191823. #endif
  191824. if (check != length)
  191825. png_error(png_ptr, "Write Error");
  191826. }
  191827. #else
  191828. /* this is the model-independent version. Since the standard I/O library
  191829. can't handle far buffers in the medium and small models, we have to copy
  191830. the data.
  191831. */
  191832. #define NEAR_BUF_SIZE 1024
  191833. #define MIN(a,b) (a <= b ? a : b)
  191834. void PNGAPI
  191835. png_default_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  191836. {
  191837. png_uint_32 check;
  191838. png_byte *near_data; /* Needs to be "png_byte *" instead of "png_bytep" */
  191839. png_FILE_p io_ptr;
  191840. if(png_ptr == NULL) return;
  191841. /* Check if data really is near. If so, use usual code. */
  191842. near_data = (png_byte *)CVT_PTR_NOCHECK(data);
  191843. io_ptr = (png_FILE_p)CVT_PTR(png_ptr->io_ptr);
  191844. if ((png_bytep)near_data == data)
  191845. {
  191846. #if defined(_WIN32_WCE)
  191847. if ( !WriteFile(io_ptr, near_data, length, &check, NULL) )
  191848. check = 0;
  191849. #else
  191850. check = fwrite(near_data, 1, length, io_ptr);
  191851. #endif
  191852. }
  191853. else
  191854. {
  191855. png_byte buf[NEAR_BUF_SIZE];
  191856. png_size_t written, remaining, err;
  191857. check = 0;
  191858. remaining = length;
  191859. do
  191860. {
  191861. written = MIN(NEAR_BUF_SIZE, remaining);
  191862. png_memcpy(buf, data, written); /* copy far buffer to near buffer */
  191863. #if defined(_WIN32_WCE)
  191864. if ( !WriteFile(io_ptr, buf, written, &err, NULL) )
  191865. err = 0;
  191866. #else
  191867. err = fwrite(buf, 1, written, io_ptr);
  191868. #endif
  191869. if (err != written)
  191870. break;
  191871. else
  191872. check += err;
  191873. data += written;
  191874. remaining -= written;
  191875. }
  191876. while (remaining != 0);
  191877. }
  191878. if (check != length)
  191879. png_error(png_ptr, "Write Error");
  191880. }
  191881. #endif
  191882. #endif
  191883. /* This function is called to output any data pending writing (normally
  191884. to disk). After png_flush is called, there should be no data pending
  191885. writing in any buffers. */
  191886. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  191887. void /* PRIVATE */
  191888. png_flush(png_structp png_ptr)
  191889. {
  191890. if (png_ptr->output_flush_fn != NULL)
  191891. (*(png_ptr->output_flush_fn))(png_ptr);
  191892. }
  191893. #if !defined(PNG_NO_STDIO)
  191894. void PNGAPI
  191895. png_default_flush(png_structp png_ptr)
  191896. {
  191897. #if !defined(_WIN32_WCE)
  191898. png_FILE_p io_ptr;
  191899. #endif
  191900. if(png_ptr == NULL) return;
  191901. #if !defined(_WIN32_WCE)
  191902. io_ptr = (png_FILE_p)CVT_PTR((png_ptr->io_ptr));
  191903. if (io_ptr != NULL)
  191904. fflush(io_ptr);
  191905. #endif
  191906. }
  191907. #endif
  191908. #endif
  191909. /* This function allows the application to supply new output functions for
  191910. libpng if standard C streams aren't being used.
  191911. This function takes as its arguments:
  191912. png_ptr - pointer to a png output data structure
  191913. io_ptr - pointer to user supplied structure containing info about
  191914. the output functions. May be NULL.
  191915. write_data_fn - pointer to a new output function that takes as its
  191916. arguments a pointer to a png_struct, a pointer to
  191917. data to be written, and a 32-bit unsigned int that is
  191918. the number of bytes to be written. The new write
  191919. function should call png_error(png_ptr, "Error msg")
  191920. to exit and output any fatal error messages.
  191921. flush_data_fn - pointer to a new flush function that takes as its
  191922. arguments a pointer to a png_struct. After a call to
  191923. the flush function, there should be no data in any buffers
  191924. or pending transmission. If the output method doesn't do
  191925. any buffering of ouput, a function prototype must still be
  191926. supplied although it doesn't have to do anything. If
  191927. PNG_WRITE_FLUSH_SUPPORTED is not defined at libpng compile
  191928. time, output_flush_fn will be ignored, although it must be
  191929. supplied for compatibility. */
  191930. void PNGAPI
  191931. png_set_write_fn(png_structp png_ptr, png_voidp io_ptr,
  191932. png_rw_ptr write_data_fn, png_flush_ptr output_flush_fn)
  191933. {
  191934. if(png_ptr == NULL) return;
  191935. png_ptr->io_ptr = io_ptr;
  191936. #if !defined(PNG_NO_STDIO)
  191937. if (write_data_fn != NULL)
  191938. png_ptr->write_data_fn = write_data_fn;
  191939. else
  191940. png_ptr->write_data_fn = png_default_write_data;
  191941. #else
  191942. png_ptr->write_data_fn = write_data_fn;
  191943. #endif
  191944. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  191945. #if !defined(PNG_NO_STDIO)
  191946. if (output_flush_fn != NULL)
  191947. png_ptr->output_flush_fn = output_flush_fn;
  191948. else
  191949. png_ptr->output_flush_fn = png_default_flush;
  191950. #else
  191951. png_ptr->output_flush_fn = output_flush_fn;
  191952. #endif
  191953. #endif /* PNG_WRITE_FLUSH_SUPPORTED */
  191954. /* It is an error to read while writing a png file */
  191955. if (png_ptr->read_data_fn != NULL)
  191956. {
  191957. png_ptr->read_data_fn = NULL;
  191958. png_warning(png_ptr,
  191959. "Attempted to set both read_data_fn and write_data_fn in");
  191960. png_warning(png_ptr,
  191961. "the same structure. Resetting read_data_fn to NULL.");
  191962. }
  191963. }
  191964. #if defined(USE_FAR_KEYWORD)
  191965. #if defined(_MSC_VER)
  191966. void *png_far_to_near(png_structp png_ptr,png_voidp ptr, int check)
  191967. {
  191968. void *near_ptr;
  191969. void FAR *far_ptr;
  191970. FP_OFF(near_ptr) = FP_OFF(ptr);
  191971. far_ptr = (void FAR *)near_ptr;
  191972. if(check != 0)
  191973. if(FP_SEG(ptr) != FP_SEG(far_ptr))
  191974. png_error(png_ptr,"segment lost in conversion");
  191975. return(near_ptr);
  191976. }
  191977. # else
  191978. void *png_far_to_near(png_structp png_ptr,png_voidp ptr, int check)
  191979. {
  191980. void *near_ptr;
  191981. void FAR *far_ptr;
  191982. near_ptr = (void FAR *)ptr;
  191983. far_ptr = (void FAR *)near_ptr;
  191984. if(check != 0)
  191985. if(far_ptr != ptr)
  191986. png_error(png_ptr,"segment lost in conversion");
  191987. return(near_ptr);
  191988. }
  191989. # endif
  191990. # endif
  191991. #endif /* PNG_WRITE_SUPPORTED */
  191992. /********* End of inlined file: pngwio.c *********/
  191993. /********* Start of inlined file: pngwrite.c *********/
  191994. /* pngwrite.c - general routines to write a PNG file
  191995. *
  191996. * Last changed in libpng 1.2.15 January 5, 2007
  191997. * For conditions of distribution and use, see copyright notice in png.h
  191998. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  191999. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  192000. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  192001. */
  192002. /* get internal access to png.h */
  192003. #define PNG_INTERNAL
  192004. #ifdef PNG_WRITE_SUPPORTED
  192005. /* Writes all the PNG information. This is the suggested way to use the
  192006. * library. If you have a new chunk to add, make a function to write it,
  192007. * and put it in the correct location here. If you want the chunk written
  192008. * after the image data, put it in png_write_end(). I strongly encourage
  192009. * you to supply a PNG_INFO_ flag, and check info_ptr->valid before writing
  192010. * the chunk, as that will keep the code from breaking if you want to just
  192011. * write a plain PNG file. If you have long comments, I suggest writing
  192012. * them in png_write_end(), and compressing them.
  192013. */
  192014. void PNGAPI
  192015. png_write_info_before_PLTE(png_structp png_ptr, png_infop info_ptr)
  192016. {
  192017. png_debug(1, "in png_write_info_before_PLTE\n");
  192018. if (png_ptr == NULL || info_ptr == NULL)
  192019. return;
  192020. if (!(png_ptr->mode & PNG_WROTE_INFO_BEFORE_PLTE))
  192021. {
  192022. png_write_sig(png_ptr); /* write PNG signature */
  192023. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  192024. if((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)&&(png_ptr->mng_features_permitted))
  192025. {
  192026. png_warning(png_ptr,"MNG features are not allowed in a PNG datastream");
  192027. png_ptr->mng_features_permitted=0;
  192028. }
  192029. #endif
  192030. /* write IHDR information. */
  192031. png_write_IHDR(png_ptr, info_ptr->width, info_ptr->height,
  192032. info_ptr->bit_depth, info_ptr->color_type, info_ptr->compression_type,
  192033. info_ptr->filter_type,
  192034. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  192035. info_ptr->interlace_type);
  192036. #else
  192037. 0);
  192038. #endif
  192039. /* the rest of these check to see if the valid field has the appropriate
  192040. flag set, and if it does, writes the chunk. */
  192041. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  192042. if (info_ptr->valid & PNG_INFO_gAMA)
  192043. {
  192044. # ifdef PNG_FLOATING_POINT_SUPPORTED
  192045. png_write_gAMA(png_ptr, info_ptr->gamma);
  192046. #else
  192047. #ifdef PNG_FIXED_POINT_SUPPORTED
  192048. png_write_gAMA_fixed(png_ptr, info_ptr->int_gamma);
  192049. # endif
  192050. #endif
  192051. }
  192052. #endif
  192053. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  192054. if (info_ptr->valid & PNG_INFO_sRGB)
  192055. png_write_sRGB(png_ptr, (int)info_ptr->srgb_intent);
  192056. #endif
  192057. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  192058. if (info_ptr->valid & PNG_INFO_iCCP)
  192059. png_write_iCCP(png_ptr, info_ptr->iccp_name, PNG_COMPRESSION_TYPE_BASE,
  192060. info_ptr->iccp_profile, (int)info_ptr->iccp_proflen);
  192061. #endif
  192062. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  192063. if (info_ptr->valid & PNG_INFO_sBIT)
  192064. png_write_sBIT(png_ptr, &(info_ptr->sig_bit), info_ptr->color_type);
  192065. #endif
  192066. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  192067. if (info_ptr->valid & PNG_INFO_cHRM)
  192068. {
  192069. #ifdef PNG_FLOATING_POINT_SUPPORTED
  192070. png_write_cHRM(png_ptr,
  192071. info_ptr->x_white, info_ptr->y_white,
  192072. info_ptr->x_red, info_ptr->y_red,
  192073. info_ptr->x_green, info_ptr->y_green,
  192074. info_ptr->x_blue, info_ptr->y_blue);
  192075. #else
  192076. # ifdef PNG_FIXED_POINT_SUPPORTED
  192077. png_write_cHRM_fixed(png_ptr,
  192078. info_ptr->int_x_white, info_ptr->int_y_white,
  192079. info_ptr->int_x_red, info_ptr->int_y_red,
  192080. info_ptr->int_x_green, info_ptr->int_y_green,
  192081. info_ptr->int_x_blue, info_ptr->int_y_blue);
  192082. # endif
  192083. #endif
  192084. }
  192085. #endif
  192086. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  192087. if (info_ptr->unknown_chunks_num)
  192088. {
  192089. png_unknown_chunk *up;
  192090. png_debug(5, "writing extra chunks\n");
  192091. for (up = info_ptr->unknown_chunks;
  192092. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  192093. up++)
  192094. {
  192095. int keep=png_handle_as_unknown(png_ptr, up->name);
  192096. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  192097. up->location && !(up->location & PNG_HAVE_PLTE) &&
  192098. !(up->location & PNG_HAVE_IDAT) &&
  192099. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  192100. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  192101. {
  192102. png_write_chunk(png_ptr, up->name, up->data, up->size);
  192103. }
  192104. }
  192105. }
  192106. #endif
  192107. png_ptr->mode |= PNG_WROTE_INFO_BEFORE_PLTE;
  192108. }
  192109. }
  192110. void PNGAPI
  192111. png_write_info(png_structp png_ptr, png_infop info_ptr)
  192112. {
  192113. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  192114. int i;
  192115. #endif
  192116. png_debug(1, "in png_write_info\n");
  192117. if (png_ptr == NULL || info_ptr == NULL)
  192118. return;
  192119. png_write_info_before_PLTE(png_ptr, info_ptr);
  192120. if (info_ptr->valid & PNG_INFO_PLTE)
  192121. png_write_PLTE(png_ptr, info_ptr->palette,
  192122. (png_uint_32)info_ptr->num_palette);
  192123. else if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  192124. png_error(png_ptr, "Valid palette required for paletted images");
  192125. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  192126. if (info_ptr->valid & PNG_INFO_tRNS)
  192127. {
  192128. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  192129. /* invert the alpha channel (in tRNS) */
  192130. if ((png_ptr->transformations & PNG_INVERT_ALPHA) &&
  192131. info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  192132. {
  192133. int j;
  192134. for (j=0; j<(int)info_ptr->num_trans; j++)
  192135. info_ptr->trans[j] = (png_byte)(255 - info_ptr->trans[j]);
  192136. }
  192137. #endif
  192138. png_write_tRNS(png_ptr, info_ptr->trans, &(info_ptr->trans_values),
  192139. info_ptr->num_trans, info_ptr->color_type);
  192140. }
  192141. #endif
  192142. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  192143. if (info_ptr->valid & PNG_INFO_bKGD)
  192144. png_write_bKGD(png_ptr, &(info_ptr->background), info_ptr->color_type);
  192145. #endif
  192146. #if defined(PNG_WRITE_hIST_SUPPORTED)
  192147. if (info_ptr->valid & PNG_INFO_hIST)
  192148. png_write_hIST(png_ptr, info_ptr->hist, info_ptr->num_palette);
  192149. #endif
  192150. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  192151. if (info_ptr->valid & PNG_INFO_oFFs)
  192152. png_write_oFFs(png_ptr, info_ptr->x_offset, info_ptr->y_offset,
  192153. info_ptr->offset_unit_type);
  192154. #endif
  192155. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  192156. if (info_ptr->valid & PNG_INFO_pCAL)
  192157. png_write_pCAL(png_ptr, info_ptr->pcal_purpose, info_ptr->pcal_X0,
  192158. info_ptr->pcal_X1, info_ptr->pcal_type, info_ptr->pcal_nparams,
  192159. info_ptr->pcal_units, info_ptr->pcal_params);
  192160. #endif
  192161. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  192162. if (info_ptr->valid & PNG_INFO_sCAL)
  192163. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  192164. png_write_sCAL(png_ptr, (int)info_ptr->scal_unit,
  192165. info_ptr->scal_pixel_width, info_ptr->scal_pixel_height);
  192166. #else
  192167. #ifdef PNG_FIXED_POINT_SUPPORTED
  192168. png_write_sCAL_s(png_ptr, (int)info_ptr->scal_unit,
  192169. info_ptr->scal_s_width, info_ptr->scal_s_height);
  192170. #else
  192171. png_warning(png_ptr,
  192172. "png_write_sCAL not supported; sCAL chunk not written.");
  192173. #endif
  192174. #endif
  192175. #endif
  192176. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  192177. if (info_ptr->valid & PNG_INFO_pHYs)
  192178. png_write_pHYs(png_ptr, info_ptr->x_pixels_per_unit,
  192179. info_ptr->y_pixels_per_unit, info_ptr->phys_unit_type);
  192180. #endif
  192181. #if defined(PNG_WRITE_tIME_SUPPORTED)
  192182. if (info_ptr->valid & PNG_INFO_tIME)
  192183. {
  192184. png_write_tIME(png_ptr, &(info_ptr->mod_time));
  192185. png_ptr->mode |= PNG_WROTE_tIME;
  192186. }
  192187. #endif
  192188. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  192189. if (info_ptr->valid & PNG_INFO_sPLT)
  192190. for (i = 0; i < (int)info_ptr->splt_palettes_num; i++)
  192191. png_write_sPLT(png_ptr, info_ptr->splt_palettes + i);
  192192. #endif
  192193. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  192194. /* Check to see if we need to write text chunks */
  192195. for (i = 0; i < info_ptr->num_text; i++)
  192196. {
  192197. png_debug2(2, "Writing header text chunk %d, type %d\n", i,
  192198. info_ptr->text[i].compression);
  192199. /* an internationalized chunk? */
  192200. if (info_ptr->text[i].compression > 0)
  192201. {
  192202. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  192203. /* write international chunk */
  192204. png_write_iTXt(png_ptr,
  192205. info_ptr->text[i].compression,
  192206. info_ptr->text[i].key,
  192207. info_ptr->text[i].lang,
  192208. info_ptr->text[i].lang_key,
  192209. info_ptr->text[i].text);
  192210. #else
  192211. png_warning(png_ptr, "Unable to write international text");
  192212. #endif
  192213. /* Mark this chunk as written */
  192214. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  192215. }
  192216. /* If we want a compressed text chunk */
  192217. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_zTXt)
  192218. {
  192219. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  192220. /* write compressed chunk */
  192221. png_write_zTXt(png_ptr, info_ptr->text[i].key,
  192222. info_ptr->text[i].text, 0,
  192223. info_ptr->text[i].compression);
  192224. #else
  192225. png_warning(png_ptr, "Unable to write compressed text");
  192226. #endif
  192227. /* Mark this chunk as written */
  192228. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR;
  192229. }
  192230. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE)
  192231. {
  192232. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  192233. /* write uncompressed chunk */
  192234. png_write_tEXt(png_ptr, info_ptr->text[i].key,
  192235. info_ptr->text[i].text,
  192236. 0);
  192237. #else
  192238. png_warning(png_ptr, "Unable to write uncompressed text");
  192239. #endif
  192240. /* Mark this chunk as written */
  192241. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  192242. }
  192243. }
  192244. #endif
  192245. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  192246. if (info_ptr->unknown_chunks_num)
  192247. {
  192248. png_unknown_chunk *up;
  192249. png_debug(5, "writing extra chunks\n");
  192250. for (up = info_ptr->unknown_chunks;
  192251. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  192252. up++)
  192253. {
  192254. int keep=png_handle_as_unknown(png_ptr, up->name);
  192255. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  192256. up->location && (up->location & PNG_HAVE_PLTE) &&
  192257. !(up->location & PNG_HAVE_IDAT) &&
  192258. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  192259. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  192260. {
  192261. png_write_chunk(png_ptr, up->name, up->data, up->size);
  192262. }
  192263. }
  192264. }
  192265. #endif
  192266. }
  192267. /* Writes the end of the PNG file. If you don't want to write comments or
  192268. * time information, you can pass NULL for info. If you already wrote these
  192269. * in png_write_info(), do not write them again here. If you have long
  192270. * comments, I suggest writing them here, and compressing them.
  192271. */
  192272. void PNGAPI
  192273. png_write_end(png_structp png_ptr, png_infop info_ptr)
  192274. {
  192275. png_debug(1, "in png_write_end\n");
  192276. if (png_ptr == NULL)
  192277. return;
  192278. if (!(png_ptr->mode & PNG_HAVE_IDAT))
  192279. png_error(png_ptr, "No IDATs written into file");
  192280. /* see if user wants us to write information chunks */
  192281. if (info_ptr != NULL)
  192282. {
  192283. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  192284. int i; /* local index variable */
  192285. #endif
  192286. #if defined(PNG_WRITE_tIME_SUPPORTED)
  192287. /* check to see if user has supplied a time chunk */
  192288. if ((info_ptr->valid & PNG_INFO_tIME) &&
  192289. !(png_ptr->mode & PNG_WROTE_tIME))
  192290. png_write_tIME(png_ptr, &(info_ptr->mod_time));
  192291. #endif
  192292. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  192293. /* loop through comment chunks */
  192294. for (i = 0; i < info_ptr->num_text; i++)
  192295. {
  192296. png_debug2(2, "Writing trailer text chunk %d, type %d\n", i,
  192297. info_ptr->text[i].compression);
  192298. /* an internationalized chunk? */
  192299. if (info_ptr->text[i].compression > 0)
  192300. {
  192301. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  192302. /* write international chunk */
  192303. png_write_iTXt(png_ptr,
  192304. info_ptr->text[i].compression,
  192305. info_ptr->text[i].key,
  192306. info_ptr->text[i].lang,
  192307. info_ptr->text[i].lang_key,
  192308. info_ptr->text[i].text);
  192309. #else
  192310. png_warning(png_ptr, "Unable to write international text");
  192311. #endif
  192312. /* Mark this chunk as written */
  192313. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  192314. }
  192315. else if (info_ptr->text[i].compression >= PNG_TEXT_COMPRESSION_zTXt)
  192316. {
  192317. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  192318. /* write compressed chunk */
  192319. png_write_zTXt(png_ptr, info_ptr->text[i].key,
  192320. info_ptr->text[i].text, 0,
  192321. info_ptr->text[i].compression);
  192322. #else
  192323. png_warning(png_ptr, "Unable to write compressed text");
  192324. #endif
  192325. /* Mark this chunk as written */
  192326. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR;
  192327. }
  192328. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE)
  192329. {
  192330. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  192331. /* write uncompressed chunk */
  192332. png_write_tEXt(png_ptr, info_ptr->text[i].key,
  192333. info_ptr->text[i].text, 0);
  192334. #else
  192335. png_warning(png_ptr, "Unable to write uncompressed text");
  192336. #endif
  192337. /* Mark this chunk as written */
  192338. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  192339. }
  192340. }
  192341. #endif
  192342. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  192343. if (info_ptr->unknown_chunks_num)
  192344. {
  192345. png_unknown_chunk *up;
  192346. png_debug(5, "writing extra chunks\n");
  192347. for (up = info_ptr->unknown_chunks;
  192348. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  192349. up++)
  192350. {
  192351. int keep=png_handle_as_unknown(png_ptr, up->name);
  192352. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  192353. up->location && (up->location & PNG_AFTER_IDAT) &&
  192354. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  192355. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  192356. {
  192357. png_write_chunk(png_ptr, up->name, up->data, up->size);
  192358. }
  192359. }
  192360. }
  192361. #endif
  192362. }
  192363. png_ptr->mode |= PNG_AFTER_IDAT;
  192364. /* write end of PNG file */
  192365. png_write_IEND(png_ptr);
  192366. }
  192367. #if defined(PNG_WRITE_tIME_SUPPORTED)
  192368. #if !defined(_WIN32_WCE)
  192369. /* "time.h" functions are not supported on WindowsCE */
  192370. void PNGAPI
  192371. png_convert_from_struct_tm(png_timep ptime, struct tm FAR * ttime)
  192372. {
  192373. png_debug(1, "in png_convert_from_struct_tm\n");
  192374. ptime->year = (png_uint_16)(1900 + ttime->tm_year);
  192375. ptime->month = (png_byte)(ttime->tm_mon + 1);
  192376. ptime->day = (png_byte)ttime->tm_mday;
  192377. ptime->hour = (png_byte)ttime->tm_hour;
  192378. ptime->minute = (png_byte)ttime->tm_min;
  192379. ptime->second = (png_byte)ttime->tm_sec;
  192380. }
  192381. void PNGAPI
  192382. png_convert_from_time_t(png_timep ptime, time_t ttime)
  192383. {
  192384. struct tm *tbuf;
  192385. png_debug(1, "in png_convert_from_time_t\n");
  192386. tbuf = gmtime(&ttime);
  192387. png_convert_from_struct_tm(ptime, tbuf);
  192388. }
  192389. #endif
  192390. #endif
  192391. /* Initialize png_ptr structure, and allocate any memory needed */
  192392. png_structp PNGAPI
  192393. png_create_write_struct(png_const_charp user_png_ver, png_voidp error_ptr,
  192394. png_error_ptr error_fn, png_error_ptr warn_fn)
  192395. {
  192396. #ifdef PNG_USER_MEM_SUPPORTED
  192397. return (png_create_write_struct_2(user_png_ver, error_ptr, error_fn,
  192398. warn_fn, png_voidp_NULL, png_malloc_ptr_NULL, png_free_ptr_NULL));
  192399. }
  192400. /* Alternate initialize png_ptr structure, and allocate any memory needed */
  192401. png_structp PNGAPI
  192402. png_create_write_struct_2(png_const_charp user_png_ver, png_voidp error_ptr,
  192403. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  192404. png_malloc_ptr malloc_fn, png_free_ptr free_fn)
  192405. {
  192406. #endif /* PNG_USER_MEM_SUPPORTED */
  192407. png_structp png_ptr;
  192408. #ifdef PNG_SETJMP_SUPPORTED
  192409. #ifdef USE_FAR_KEYWORD
  192410. jmp_buf jmpbuf;
  192411. #endif
  192412. #endif
  192413. int i;
  192414. png_debug(1, "in png_create_write_struct\n");
  192415. #ifdef PNG_USER_MEM_SUPPORTED
  192416. png_ptr = (png_structp)png_create_struct_2(PNG_STRUCT_PNG,
  192417. (png_malloc_ptr)malloc_fn, (png_voidp)mem_ptr);
  192418. #else
  192419. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  192420. #endif /* PNG_USER_MEM_SUPPORTED */
  192421. if (png_ptr == NULL)
  192422. return (NULL);
  192423. /* added at libpng-1.2.6 */
  192424. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  192425. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  192426. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  192427. #endif
  192428. #ifdef PNG_SETJMP_SUPPORTED
  192429. #ifdef USE_FAR_KEYWORD
  192430. if (setjmp(jmpbuf))
  192431. #else
  192432. if (setjmp(png_ptr->jmpbuf))
  192433. #endif
  192434. {
  192435. png_free(png_ptr, png_ptr->zbuf);
  192436. png_ptr->zbuf=NULL;
  192437. png_destroy_struct(png_ptr);
  192438. return (NULL);
  192439. }
  192440. #ifdef USE_FAR_KEYWORD
  192441. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  192442. #endif
  192443. #endif
  192444. #ifdef PNG_USER_MEM_SUPPORTED
  192445. png_set_mem_fn(png_ptr, mem_ptr, malloc_fn, free_fn);
  192446. #endif /* PNG_USER_MEM_SUPPORTED */
  192447. png_set_error_fn(png_ptr, error_ptr, error_fn, warn_fn);
  192448. i=0;
  192449. do
  192450. {
  192451. if(user_png_ver[i] != png_libpng_ver[i])
  192452. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  192453. } while (png_libpng_ver[i++]);
  192454. if (png_ptr->flags & PNG_FLAG_LIBRARY_MISMATCH)
  192455. {
  192456. /* Libpng 0.90 and later are binary incompatible with libpng 0.89, so
  192457. * we must recompile any applications that use any older library version.
  192458. * For versions after libpng 1.0, we will be compatible, so we need
  192459. * only check the first digit.
  192460. */
  192461. if (user_png_ver == NULL || user_png_ver[0] != png_libpng_ver[0] ||
  192462. (user_png_ver[0] == '1' && user_png_ver[2] != png_libpng_ver[2]) ||
  192463. (user_png_ver[0] == '0' && user_png_ver[2] < '9'))
  192464. {
  192465. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  192466. char msg[80];
  192467. if (user_png_ver)
  192468. {
  192469. png_snprintf(msg, 80,
  192470. "Application was compiled with png.h from libpng-%.20s",
  192471. user_png_ver);
  192472. png_warning(png_ptr, msg);
  192473. }
  192474. png_snprintf(msg, 80,
  192475. "Application is running with png.c from libpng-%.20s",
  192476. png_libpng_ver);
  192477. png_warning(png_ptr, msg);
  192478. #endif
  192479. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  192480. png_ptr->flags=0;
  192481. #endif
  192482. png_error(png_ptr,
  192483. "Incompatible libpng version in application and library");
  192484. }
  192485. }
  192486. /* initialize zbuf - compression buffer */
  192487. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  192488. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  192489. (png_uint_32)png_ptr->zbuf_size);
  192490. png_set_write_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL,
  192491. png_flush_ptr_NULL);
  192492. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  192493. png_set_filter_heuristics(png_ptr, PNG_FILTER_HEURISTIC_DEFAULT,
  192494. 1, png_doublep_NULL, png_doublep_NULL);
  192495. #endif
  192496. #ifdef PNG_SETJMP_SUPPORTED
  192497. /* Applications that neglect to set up their own setjmp() and then encounter
  192498. a png_error() will longjmp here. Since the jmpbuf is then meaningless we
  192499. abort instead of returning. */
  192500. #ifdef USE_FAR_KEYWORD
  192501. if (setjmp(jmpbuf))
  192502. PNG_ABORT();
  192503. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  192504. #else
  192505. if (setjmp(png_ptr->jmpbuf))
  192506. PNG_ABORT();
  192507. #endif
  192508. #endif
  192509. return (png_ptr);
  192510. }
  192511. /* Initialize png_ptr structure, and allocate any memory needed */
  192512. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  192513. /* Deprecated. */
  192514. #undef png_write_init
  192515. void PNGAPI
  192516. png_write_init(png_structp png_ptr)
  192517. {
  192518. /* We only come here via pre-1.0.7-compiled applications */
  192519. png_write_init_2(png_ptr, "1.0.6 or earlier", 0, 0);
  192520. }
  192521. void PNGAPI
  192522. png_write_init_2(png_structp png_ptr, png_const_charp user_png_ver,
  192523. png_size_t png_struct_size, png_size_t png_info_size)
  192524. {
  192525. /* We only come here via pre-1.0.12-compiled applications */
  192526. if(png_ptr == NULL) return;
  192527. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  192528. if(png_sizeof(png_struct) > png_struct_size ||
  192529. png_sizeof(png_info) > png_info_size)
  192530. {
  192531. char msg[80];
  192532. png_ptr->warning_fn=NULL;
  192533. if (user_png_ver)
  192534. {
  192535. png_snprintf(msg, 80,
  192536. "Application was compiled with png.h from libpng-%.20s",
  192537. user_png_ver);
  192538. png_warning(png_ptr, msg);
  192539. }
  192540. png_snprintf(msg, 80,
  192541. "Application is running with png.c from libpng-%.20s",
  192542. png_libpng_ver);
  192543. png_warning(png_ptr, msg);
  192544. }
  192545. #endif
  192546. if(png_sizeof(png_struct) > png_struct_size)
  192547. {
  192548. png_ptr->error_fn=NULL;
  192549. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  192550. png_ptr->flags=0;
  192551. #endif
  192552. png_error(png_ptr,
  192553. "The png struct allocated by the application for writing is too small.");
  192554. }
  192555. if(png_sizeof(png_info) > png_info_size)
  192556. {
  192557. png_ptr->error_fn=NULL;
  192558. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  192559. png_ptr->flags=0;
  192560. #endif
  192561. png_error(png_ptr,
  192562. "The info struct allocated by the application for writing is too small.");
  192563. }
  192564. png_write_init_3(&png_ptr, user_png_ver, png_struct_size);
  192565. }
  192566. #endif /* PNG_1_0_X || PNG_1_2_X */
  192567. void PNGAPI
  192568. png_write_init_3(png_structpp ptr_ptr, png_const_charp user_png_ver,
  192569. png_size_t png_struct_size)
  192570. {
  192571. png_structp png_ptr=*ptr_ptr;
  192572. #ifdef PNG_SETJMP_SUPPORTED
  192573. jmp_buf tmp_jmp; /* to save current jump buffer */
  192574. #endif
  192575. int i = 0;
  192576. if (png_ptr == NULL)
  192577. return;
  192578. do
  192579. {
  192580. if (user_png_ver[i] != png_libpng_ver[i])
  192581. {
  192582. #ifdef PNG_LEGACY_SUPPORTED
  192583. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  192584. #else
  192585. png_ptr->warning_fn=NULL;
  192586. png_warning(png_ptr,
  192587. "Application uses deprecated png_write_init() and should be recompiled.");
  192588. break;
  192589. #endif
  192590. }
  192591. } while (png_libpng_ver[i++]);
  192592. png_debug(1, "in png_write_init_3\n");
  192593. #ifdef PNG_SETJMP_SUPPORTED
  192594. /* save jump buffer and error functions */
  192595. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  192596. #endif
  192597. if (png_sizeof(png_struct) > png_struct_size)
  192598. {
  192599. png_destroy_struct(png_ptr);
  192600. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  192601. *ptr_ptr = png_ptr;
  192602. }
  192603. /* reset all variables to 0 */
  192604. png_memset(png_ptr, 0, png_sizeof (png_struct));
  192605. /* added at libpng-1.2.6 */
  192606. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  192607. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  192608. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  192609. #endif
  192610. #ifdef PNG_SETJMP_SUPPORTED
  192611. /* restore jump buffer */
  192612. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  192613. #endif
  192614. png_set_write_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL,
  192615. png_flush_ptr_NULL);
  192616. /* initialize zbuf - compression buffer */
  192617. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  192618. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  192619. (png_uint_32)png_ptr->zbuf_size);
  192620. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  192621. png_set_filter_heuristics(png_ptr, PNG_FILTER_HEURISTIC_DEFAULT,
  192622. 1, png_doublep_NULL, png_doublep_NULL);
  192623. #endif
  192624. }
  192625. /* Write a few rows of image data. If the image is interlaced,
  192626. * either you will have to write the 7 sub images, or, if you
  192627. * have called png_set_interlace_handling(), you will have to
  192628. * "write" the image seven times.
  192629. */
  192630. void PNGAPI
  192631. png_write_rows(png_structp png_ptr, png_bytepp row,
  192632. png_uint_32 num_rows)
  192633. {
  192634. png_uint_32 i; /* row counter */
  192635. png_bytepp rp; /* row pointer */
  192636. png_debug(1, "in png_write_rows\n");
  192637. if (png_ptr == NULL)
  192638. return;
  192639. /* loop through the rows */
  192640. for (i = 0, rp = row; i < num_rows; i++, rp++)
  192641. {
  192642. png_write_row(png_ptr, *rp);
  192643. }
  192644. }
  192645. /* Write the image. You only need to call this function once, even
  192646. * if you are writing an interlaced image.
  192647. */
  192648. void PNGAPI
  192649. png_write_image(png_structp png_ptr, png_bytepp image)
  192650. {
  192651. png_uint_32 i; /* row index */
  192652. int pass, num_pass; /* pass variables */
  192653. png_bytepp rp; /* points to current row */
  192654. if (png_ptr == NULL)
  192655. return;
  192656. png_debug(1, "in png_write_image\n");
  192657. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  192658. /* intialize interlace handling. If image is not interlaced,
  192659. this will set pass to 1 */
  192660. num_pass = png_set_interlace_handling(png_ptr);
  192661. #else
  192662. num_pass = 1;
  192663. #endif
  192664. /* loop through passes */
  192665. for (pass = 0; pass < num_pass; pass++)
  192666. {
  192667. /* loop through image */
  192668. for (i = 0, rp = image; i < png_ptr->height; i++, rp++)
  192669. {
  192670. png_write_row(png_ptr, *rp);
  192671. }
  192672. }
  192673. }
  192674. /* called by user to write a row of image data */
  192675. void PNGAPI
  192676. png_write_row(png_structp png_ptr, png_bytep row)
  192677. {
  192678. if (png_ptr == NULL)
  192679. return;
  192680. png_debug2(1, "in png_write_row (row %ld, pass %d)\n",
  192681. png_ptr->row_number, png_ptr->pass);
  192682. /* initialize transformations and other stuff if first time */
  192683. if (png_ptr->row_number == 0 && png_ptr->pass == 0)
  192684. {
  192685. /* make sure we wrote the header info */
  192686. if (!(png_ptr->mode & PNG_WROTE_INFO_BEFORE_PLTE))
  192687. png_error(png_ptr,
  192688. "png_write_info was never called before png_write_row.");
  192689. /* check for transforms that have been set but were defined out */
  192690. #if !defined(PNG_WRITE_INVERT_SUPPORTED) && defined(PNG_READ_INVERT_SUPPORTED)
  192691. if (png_ptr->transformations & PNG_INVERT_MONO)
  192692. png_warning(png_ptr, "PNG_WRITE_INVERT_SUPPORTED is not defined.");
  192693. #endif
  192694. #if !defined(PNG_WRITE_FILLER_SUPPORTED) && defined(PNG_READ_FILLER_SUPPORTED)
  192695. if (png_ptr->transformations & PNG_FILLER)
  192696. png_warning(png_ptr, "PNG_WRITE_FILLER_SUPPORTED is not defined.");
  192697. #endif
  192698. #if !defined(PNG_WRITE_PACKSWAP_SUPPORTED) && defined(PNG_READ_PACKSWAP_SUPPORTED)
  192699. if (png_ptr->transformations & PNG_PACKSWAP)
  192700. png_warning(png_ptr, "PNG_WRITE_PACKSWAP_SUPPORTED is not defined.");
  192701. #endif
  192702. #if !defined(PNG_WRITE_PACK_SUPPORTED) && defined(PNG_READ_PACK_SUPPORTED)
  192703. if (png_ptr->transformations & PNG_PACK)
  192704. png_warning(png_ptr, "PNG_WRITE_PACK_SUPPORTED is not defined.");
  192705. #endif
  192706. #if !defined(PNG_WRITE_SHIFT_SUPPORTED) && defined(PNG_READ_SHIFT_SUPPORTED)
  192707. if (png_ptr->transformations & PNG_SHIFT)
  192708. png_warning(png_ptr, "PNG_WRITE_SHIFT_SUPPORTED is not defined.");
  192709. #endif
  192710. #if !defined(PNG_WRITE_BGR_SUPPORTED) && defined(PNG_READ_BGR_SUPPORTED)
  192711. if (png_ptr->transformations & PNG_BGR)
  192712. png_warning(png_ptr, "PNG_WRITE_BGR_SUPPORTED is not defined.");
  192713. #endif
  192714. #if !defined(PNG_WRITE_SWAP_SUPPORTED) && defined(PNG_READ_SWAP_SUPPORTED)
  192715. if (png_ptr->transformations & PNG_SWAP_BYTES)
  192716. png_warning(png_ptr, "PNG_WRITE_SWAP_SUPPORTED is not defined.");
  192717. #endif
  192718. png_write_start_row(png_ptr);
  192719. }
  192720. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  192721. /* if interlaced and not interested in row, return */
  192722. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  192723. {
  192724. switch (png_ptr->pass)
  192725. {
  192726. case 0:
  192727. if (png_ptr->row_number & 0x07)
  192728. {
  192729. png_write_finish_row(png_ptr);
  192730. return;
  192731. }
  192732. break;
  192733. case 1:
  192734. if ((png_ptr->row_number & 0x07) || png_ptr->width < 5)
  192735. {
  192736. png_write_finish_row(png_ptr);
  192737. return;
  192738. }
  192739. break;
  192740. case 2:
  192741. if ((png_ptr->row_number & 0x07) != 4)
  192742. {
  192743. png_write_finish_row(png_ptr);
  192744. return;
  192745. }
  192746. break;
  192747. case 3:
  192748. if ((png_ptr->row_number & 0x03) || png_ptr->width < 3)
  192749. {
  192750. png_write_finish_row(png_ptr);
  192751. return;
  192752. }
  192753. break;
  192754. case 4:
  192755. if ((png_ptr->row_number & 0x03) != 2)
  192756. {
  192757. png_write_finish_row(png_ptr);
  192758. return;
  192759. }
  192760. break;
  192761. case 5:
  192762. if ((png_ptr->row_number & 0x01) || png_ptr->width < 2)
  192763. {
  192764. png_write_finish_row(png_ptr);
  192765. return;
  192766. }
  192767. break;
  192768. case 6:
  192769. if (!(png_ptr->row_number & 0x01))
  192770. {
  192771. png_write_finish_row(png_ptr);
  192772. return;
  192773. }
  192774. break;
  192775. }
  192776. }
  192777. #endif
  192778. /* set up row info for transformations */
  192779. png_ptr->row_info.color_type = png_ptr->color_type;
  192780. png_ptr->row_info.width = png_ptr->usr_width;
  192781. png_ptr->row_info.channels = png_ptr->usr_channels;
  192782. png_ptr->row_info.bit_depth = png_ptr->usr_bit_depth;
  192783. png_ptr->row_info.pixel_depth = (png_byte)(png_ptr->row_info.bit_depth *
  192784. png_ptr->row_info.channels);
  192785. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  192786. png_ptr->row_info.width);
  192787. png_debug1(3, "row_info->color_type = %d\n", png_ptr->row_info.color_type);
  192788. png_debug1(3, "row_info->width = %lu\n", png_ptr->row_info.width);
  192789. png_debug1(3, "row_info->channels = %d\n", png_ptr->row_info.channels);
  192790. png_debug1(3, "row_info->bit_depth = %d\n", png_ptr->row_info.bit_depth);
  192791. png_debug1(3, "row_info->pixel_depth = %d\n", png_ptr->row_info.pixel_depth);
  192792. png_debug1(3, "row_info->rowbytes = %lu\n", png_ptr->row_info.rowbytes);
  192793. /* Copy user's row into buffer, leaving room for filter byte. */
  192794. png_memcpy_check(png_ptr, png_ptr->row_buf + 1, row,
  192795. png_ptr->row_info.rowbytes);
  192796. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  192797. /* handle interlacing */
  192798. if (png_ptr->interlaced && png_ptr->pass < 6 &&
  192799. (png_ptr->transformations & PNG_INTERLACE))
  192800. {
  192801. png_do_write_interlace(&(png_ptr->row_info),
  192802. png_ptr->row_buf + 1, png_ptr->pass);
  192803. /* this should always get caught above, but still ... */
  192804. if (!(png_ptr->row_info.width))
  192805. {
  192806. png_write_finish_row(png_ptr);
  192807. return;
  192808. }
  192809. }
  192810. #endif
  192811. /* handle other transformations */
  192812. if (png_ptr->transformations)
  192813. png_do_write_transformations(png_ptr);
  192814. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  192815. /* Write filter_method 64 (intrapixel differencing) only if
  192816. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  192817. * 2. Libpng did not write a PNG signature (this filter_method is only
  192818. * used in PNG datastreams that are embedded in MNG datastreams) and
  192819. * 3. The application called png_permit_mng_features with a mask that
  192820. * included PNG_FLAG_MNG_FILTER_64 and
  192821. * 4. The filter_method is 64 and
  192822. * 5. The color_type is RGB or RGBA
  192823. */
  192824. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  192825. (png_ptr->filter_type == PNG_INTRAPIXEL_DIFFERENCING))
  192826. {
  192827. /* Intrapixel differencing */
  192828. png_do_write_intrapixel(&(png_ptr->row_info), png_ptr->row_buf + 1);
  192829. }
  192830. #endif
  192831. /* Find a filter if necessary, filter the row and write it out. */
  192832. png_write_find_filter(png_ptr, &(png_ptr->row_info));
  192833. if (png_ptr->write_row_fn != NULL)
  192834. (*(png_ptr->write_row_fn))(png_ptr, png_ptr->row_number, png_ptr->pass);
  192835. }
  192836. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  192837. /* Set the automatic flush interval or 0 to turn flushing off */
  192838. void PNGAPI
  192839. png_set_flush(png_structp png_ptr, int nrows)
  192840. {
  192841. png_debug(1, "in png_set_flush\n");
  192842. if (png_ptr == NULL)
  192843. return;
  192844. png_ptr->flush_dist = (nrows < 0 ? 0 : nrows);
  192845. }
  192846. /* flush the current output buffers now */
  192847. void PNGAPI
  192848. png_write_flush(png_structp png_ptr)
  192849. {
  192850. int wrote_IDAT;
  192851. png_debug(1, "in png_write_flush\n");
  192852. if (png_ptr == NULL)
  192853. return;
  192854. /* We have already written out all of the data */
  192855. if (png_ptr->row_number >= png_ptr->num_rows)
  192856. return;
  192857. do
  192858. {
  192859. int ret;
  192860. /* compress the data */
  192861. ret = deflate(&png_ptr->zstream, Z_SYNC_FLUSH);
  192862. wrote_IDAT = 0;
  192863. /* check for compression errors */
  192864. if (ret != Z_OK)
  192865. {
  192866. if (png_ptr->zstream.msg != NULL)
  192867. png_error(png_ptr, png_ptr->zstream.msg);
  192868. else
  192869. png_error(png_ptr, "zlib error");
  192870. }
  192871. if (!(png_ptr->zstream.avail_out))
  192872. {
  192873. /* write the IDAT and reset the zlib output buffer */
  192874. png_write_IDAT(png_ptr, png_ptr->zbuf,
  192875. png_ptr->zbuf_size);
  192876. png_ptr->zstream.next_out = png_ptr->zbuf;
  192877. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  192878. wrote_IDAT = 1;
  192879. }
  192880. } while(wrote_IDAT == 1);
  192881. /* If there is any data left to be output, write it into a new IDAT */
  192882. if (png_ptr->zbuf_size != png_ptr->zstream.avail_out)
  192883. {
  192884. /* write the IDAT and reset the zlib output buffer */
  192885. png_write_IDAT(png_ptr, png_ptr->zbuf,
  192886. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  192887. png_ptr->zstream.next_out = png_ptr->zbuf;
  192888. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  192889. }
  192890. png_ptr->flush_rows = 0;
  192891. png_flush(png_ptr);
  192892. }
  192893. #endif /* PNG_WRITE_FLUSH_SUPPORTED */
  192894. /* free all memory used by the write */
  192895. void PNGAPI
  192896. png_destroy_write_struct(png_structpp png_ptr_ptr, png_infopp info_ptr_ptr)
  192897. {
  192898. png_structp png_ptr = NULL;
  192899. png_infop info_ptr = NULL;
  192900. #ifdef PNG_USER_MEM_SUPPORTED
  192901. png_free_ptr free_fn = NULL;
  192902. png_voidp mem_ptr = NULL;
  192903. #endif
  192904. png_debug(1, "in png_destroy_write_struct\n");
  192905. if (png_ptr_ptr != NULL)
  192906. {
  192907. png_ptr = *png_ptr_ptr;
  192908. #ifdef PNG_USER_MEM_SUPPORTED
  192909. free_fn = png_ptr->free_fn;
  192910. mem_ptr = png_ptr->mem_ptr;
  192911. #endif
  192912. }
  192913. if (info_ptr_ptr != NULL)
  192914. info_ptr = *info_ptr_ptr;
  192915. if (info_ptr != NULL)
  192916. {
  192917. png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
  192918. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  192919. if (png_ptr->num_chunk_list)
  192920. {
  192921. png_free(png_ptr, png_ptr->chunk_list);
  192922. png_ptr->chunk_list=NULL;
  192923. png_ptr->num_chunk_list=0;
  192924. }
  192925. #endif
  192926. #ifdef PNG_USER_MEM_SUPPORTED
  192927. png_destroy_struct_2((png_voidp)info_ptr, (png_free_ptr)free_fn,
  192928. (png_voidp)mem_ptr);
  192929. #else
  192930. png_destroy_struct((png_voidp)info_ptr);
  192931. #endif
  192932. *info_ptr_ptr = NULL;
  192933. }
  192934. if (png_ptr != NULL)
  192935. {
  192936. png_write_destroy(png_ptr);
  192937. #ifdef PNG_USER_MEM_SUPPORTED
  192938. png_destroy_struct_2((png_voidp)png_ptr, (png_free_ptr)free_fn,
  192939. (png_voidp)mem_ptr);
  192940. #else
  192941. png_destroy_struct((png_voidp)png_ptr);
  192942. #endif
  192943. *png_ptr_ptr = NULL;
  192944. }
  192945. }
  192946. /* Free any memory used in png_ptr struct (old method) */
  192947. void /* PRIVATE */
  192948. png_write_destroy(png_structp png_ptr)
  192949. {
  192950. #ifdef PNG_SETJMP_SUPPORTED
  192951. jmp_buf tmp_jmp; /* save jump buffer */
  192952. #endif
  192953. png_error_ptr error_fn;
  192954. png_error_ptr warning_fn;
  192955. png_voidp error_ptr;
  192956. #ifdef PNG_USER_MEM_SUPPORTED
  192957. png_free_ptr free_fn;
  192958. #endif
  192959. png_debug(1, "in png_write_destroy\n");
  192960. /* free any memory zlib uses */
  192961. deflateEnd(&png_ptr->zstream);
  192962. /* free our memory. png_free checks NULL for us. */
  192963. png_free(png_ptr, png_ptr->zbuf);
  192964. png_free(png_ptr, png_ptr->row_buf);
  192965. png_free(png_ptr, png_ptr->prev_row);
  192966. png_free(png_ptr, png_ptr->sub_row);
  192967. png_free(png_ptr, png_ptr->up_row);
  192968. png_free(png_ptr, png_ptr->avg_row);
  192969. png_free(png_ptr, png_ptr->paeth_row);
  192970. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  192971. png_free(png_ptr, png_ptr->time_buffer);
  192972. #endif
  192973. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  192974. png_free(png_ptr, png_ptr->prev_filters);
  192975. png_free(png_ptr, png_ptr->filter_weights);
  192976. png_free(png_ptr, png_ptr->inv_filter_weights);
  192977. png_free(png_ptr, png_ptr->filter_costs);
  192978. png_free(png_ptr, png_ptr->inv_filter_costs);
  192979. #endif
  192980. #ifdef PNG_SETJMP_SUPPORTED
  192981. /* reset structure */
  192982. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  192983. #endif
  192984. error_fn = png_ptr->error_fn;
  192985. warning_fn = png_ptr->warning_fn;
  192986. error_ptr = png_ptr->error_ptr;
  192987. #ifdef PNG_USER_MEM_SUPPORTED
  192988. free_fn = png_ptr->free_fn;
  192989. #endif
  192990. png_memset(png_ptr, 0, png_sizeof (png_struct));
  192991. png_ptr->error_fn = error_fn;
  192992. png_ptr->warning_fn = warning_fn;
  192993. png_ptr->error_ptr = error_ptr;
  192994. #ifdef PNG_USER_MEM_SUPPORTED
  192995. png_ptr->free_fn = free_fn;
  192996. #endif
  192997. #ifdef PNG_SETJMP_SUPPORTED
  192998. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  192999. #endif
  193000. }
  193001. /* Allow the application to select one or more row filters to use. */
  193002. void PNGAPI
  193003. png_set_filter(png_structp png_ptr, int method, int filters)
  193004. {
  193005. png_debug(1, "in png_set_filter\n");
  193006. if (png_ptr == NULL)
  193007. return;
  193008. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  193009. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  193010. (method == PNG_INTRAPIXEL_DIFFERENCING))
  193011. method = PNG_FILTER_TYPE_BASE;
  193012. #endif
  193013. if (method == PNG_FILTER_TYPE_BASE)
  193014. {
  193015. switch (filters & (PNG_ALL_FILTERS | 0x07))
  193016. {
  193017. #ifndef PNG_NO_WRITE_FILTER
  193018. case 5:
  193019. case 6:
  193020. case 7: png_warning(png_ptr, "Unknown row filter for method 0");
  193021. #endif /* PNG_NO_WRITE_FILTER */
  193022. case PNG_FILTER_VALUE_NONE:
  193023. png_ptr->do_filter=PNG_FILTER_NONE; break;
  193024. #ifndef PNG_NO_WRITE_FILTER
  193025. case PNG_FILTER_VALUE_SUB:
  193026. png_ptr->do_filter=PNG_FILTER_SUB; break;
  193027. case PNG_FILTER_VALUE_UP:
  193028. png_ptr->do_filter=PNG_FILTER_UP; break;
  193029. case PNG_FILTER_VALUE_AVG:
  193030. png_ptr->do_filter=PNG_FILTER_AVG; break;
  193031. case PNG_FILTER_VALUE_PAETH:
  193032. png_ptr->do_filter=PNG_FILTER_PAETH; break;
  193033. default: png_ptr->do_filter = (png_byte)filters; break;
  193034. #else
  193035. default: png_warning(png_ptr, "Unknown row filter for method 0");
  193036. #endif /* PNG_NO_WRITE_FILTER */
  193037. }
  193038. /* If we have allocated the row_buf, this means we have already started
  193039. * with the image and we should have allocated all of the filter buffers
  193040. * that have been selected. If prev_row isn't already allocated, then
  193041. * it is too late to start using the filters that need it, since we
  193042. * will be missing the data in the previous row. If an application
  193043. * wants to start and stop using particular filters during compression,
  193044. * it should start out with all of the filters, and then add and
  193045. * remove them after the start of compression.
  193046. */
  193047. if (png_ptr->row_buf != NULL)
  193048. {
  193049. #ifndef PNG_NO_WRITE_FILTER
  193050. if ((png_ptr->do_filter & PNG_FILTER_SUB) && png_ptr->sub_row == NULL)
  193051. {
  193052. png_ptr->sub_row = (png_bytep)png_malloc(png_ptr,
  193053. (png_ptr->rowbytes + 1));
  193054. png_ptr->sub_row[0] = PNG_FILTER_VALUE_SUB;
  193055. }
  193056. if ((png_ptr->do_filter & PNG_FILTER_UP) && png_ptr->up_row == NULL)
  193057. {
  193058. if (png_ptr->prev_row == NULL)
  193059. {
  193060. png_warning(png_ptr, "Can't add Up filter after starting");
  193061. png_ptr->do_filter &= ~PNG_FILTER_UP;
  193062. }
  193063. else
  193064. {
  193065. png_ptr->up_row = (png_bytep)png_malloc(png_ptr,
  193066. (png_ptr->rowbytes + 1));
  193067. png_ptr->up_row[0] = PNG_FILTER_VALUE_UP;
  193068. }
  193069. }
  193070. if ((png_ptr->do_filter & PNG_FILTER_AVG) && png_ptr->avg_row == NULL)
  193071. {
  193072. if (png_ptr->prev_row == NULL)
  193073. {
  193074. png_warning(png_ptr, "Can't add Average filter after starting");
  193075. png_ptr->do_filter &= ~PNG_FILTER_AVG;
  193076. }
  193077. else
  193078. {
  193079. png_ptr->avg_row = (png_bytep)png_malloc(png_ptr,
  193080. (png_ptr->rowbytes + 1));
  193081. png_ptr->avg_row[0] = PNG_FILTER_VALUE_AVG;
  193082. }
  193083. }
  193084. if ((png_ptr->do_filter & PNG_FILTER_PAETH) &&
  193085. png_ptr->paeth_row == NULL)
  193086. {
  193087. if (png_ptr->prev_row == NULL)
  193088. {
  193089. png_warning(png_ptr, "Can't add Paeth filter after starting");
  193090. png_ptr->do_filter &= (png_byte)(~PNG_FILTER_PAETH);
  193091. }
  193092. else
  193093. {
  193094. png_ptr->paeth_row = (png_bytep)png_malloc(png_ptr,
  193095. (png_ptr->rowbytes + 1));
  193096. png_ptr->paeth_row[0] = PNG_FILTER_VALUE_PAETH;
  193097. }
  193098. }
  193099. if (png_ptr->do_filter == PNG_NO_FILTERS)
  193100. #endif /* PNG_NO_WRITE_FILTER */
  193101. png_ptr->do_filter = PNG_FILTER_NONE;
  193102. }
  193103. }
  193104. else
  193105. png_error(png_ptr, "Unknown custom filter method");
  193106. }
  193107. /* This allows us to influence the way in which libpng chooses the "best"
  193108. * filter for the current scanline. While the "minimum-sum-of-absolute-
  193109. * differences metric is relatively fast and effective, there is some
  193110. * question as to whether it can be improved upon by trying to keep the
  193111. * filtered data going to zlib more consistent, hopefully resulting in
  193112. * better compression.
  193113. */
  193114. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED) /* GRR 970116 */
  193115. void PNGAPI
  193116. png_set_filter_heuristics(png_structp png_ptr, int heuristic_method,
  193117. int num_weights, png_doublep filter_weights,
  193118. png_doublep filter_costs)
  193119. {
  193120. int i;
  193121. png_debug(1, "in png_set_filter_heuristics\n");
  193122. if (png_ptr == NULL)
  193123. return;
  193124. if (heuristic_method >= PNG_FILTER_HEURISTIC_LAST)
  193125. {
  193126. png_warning(png_ptr, "Unknown filter heuristic method");
  193127. return;
  193128. }
  193129. if (heuristic_method == PNG_FILTER_HEURISTIC_DEFAULT)
  193130. {
  193131. heuristic_method = PNG_FILTER_HEURISTIC_UNWEIGHTED;
  193132. }
  193133. if (num_weights < 0 || filter_weights == NULL ||
  193134. heuristic_method == PNG_FILTER_HEURISTIC_UNWEIGHTED)
  193135. {
  193136. num_weights = 0;
  193137. }
  193138. png_ptr->num_prev_filters = (png_byte)num_weights;
  193139. png_ptr->heuristic_method = (png_byte)heuristic_method;
  193140. if (num_weights > 0)
  193141. {
  193142. if (png_ptr->prev_filters == NULL)
  193143. {
  193144. png_ptr->prev_filters = (png_bytep)png_malloc(png_ptr,
  193145. (png_uint_32)(png_sizeof(png_byte) * num_weights));
  193146. /* To make sure that the weighting starts out fairly */
  193147. for (i = 0; i < num_weights; i++)
  193148. {
  193149. png_ptr->prev_filters[i] = 255;
  193150. }
  193151. }
  193152. if (png_ptr->filter_weights == NULL)
  193153. {
  193154. png_ptr->filter_weights = (png_uint_16p)png_malloc(png_ptr,
  193155. (png_uint_32)(png_sizeof(png_uint_16) * num_weights));
  193156. png_ptr->inv_filter_weights = (png_uint_16p)png_malloc(png_ptr,
  193157. (png_uint_32)(png_sizeof(png_uint_16) * num_weights));
  193158. for (i = 0; i < num_weights; i++)
  193159. {
  193160. png_ptr->inv_filter_weights[i] =
  193161. png_ptr->filter_weights[i] = PNG_WEIGHT_FACTOR;
  193162. }
  193163. }
  193164. for (i = 0; i < num_weights; i++)
  193165. {
  193166. if (filter_weights[i] < 0.0)
  193167. {
  193168. png_ptr->inv_filter_weights[i] =
  193169. png_ptr->filter_weights[i] = PNG_WEIGHT_FACTOR;
  193170. }
  193171. else
  193172. {
  193173. png_ptr->inv_filter_weights[i] =
  193174. (png_uint_16)((double)PNG_WEIGHT_FACTOR*filter_weights[i]+0.5);
  193175. png_ptr->filter_weights[i] =
  193176. (png_uint_16)((double)PNG_WEIGHT_FACTOR/filter_weights[i]+0.5);
  193177. }
  193178. }
  193179. }
  193180. /* If, in the future, there are other filter methods, this would
  193181. * need to be based on png_ptr->filter.
  193182. */
  193183. if (png_ptr->filter_costs == NULL)
  193184. {
  193185. png_ptr->filter_costs = (png_uint_16p)png_malloc(png_ptr,
  193186. (png_uint_32)(png_sizeof(png_uint_16) * PNG_FILTER_VALUE_LAST));
  193187. png_ptr->inv_filter_costs = (png_uint_16p)png_malloc(png_ptr,
  193188. (png_uint_32)(png_sizeof(png_uint_16) * PNG_FILTER_VALUE_LAST));
  193189. for (i = 0; i < PNG_FILTER_VALUE_LAST; i++)
  193190. {
  193191. png_ptr->inv_filter_costs[i] =
  193192. png_ptr->filter_costs[i] = PNG_COST_FACTOR;
  193193. }
  193194. }
  193195. /* Here is where we set the relative costs of the different filters. We
  193196. * should take the desired compression level into account when setting
  193197. * the costs, so that Paeth, for instance, has a high relative cost at low
  193198. * compression levels, while it has a lower relative cost at higher
  193199. * compression settings. The filter types are in order of increasing
  193200. * relative cost, so it would be possible to do this with an algorithm.
  193201. */
  193202. for (i = 0; i < PNG_FILTER_VALUE_LAST; i++)
  193203. {
  193204. if (filter_costs == NULL || filter_costs[i] < 0.0)
  193205. {
  193206. png_ptr->inv_filter_costs[i] =
  193207. png_ptr->filter_costs[i] = PNG_COST_FACTOR;
  193208. }
  193209. else if (filter_costs[i] >= 1.0)
  193210. {
  193211. png_ptr->inv_filter_costs[i] =
  193212. (png_uint_16)((double)PNG_COST_FACTOR / filter_costs[i] + 0.5);
  193213. png_ptr->filter_costs[i] =
  193214. (png_uint_16)((double)PNG_COST_FACTOR * filter_costs[i] + 0.5);
  193215. }
  193216. }
  193217. }
  193218. #endif /* PNG_WRITE_WEIGHTED_FILTER_SUPPORTED */
  193219. void PNGAPI
  193220. png_set_compression_level(png_structp png_ptr, int level)
  193221. {
  193222. png_debug(1, "in png_set_compression_level\n");
  193223. if (png_ptr == NULL)
  193224. return;
  193225. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_LEVEL;
  193226. png_ptr->zlib_level = level;
  193227. }
  193228. void PNGAPI
  193229. png_set_compression_mem_level(png_structp png_ptr, int mem_level)
  193230. {
  193231. png_debug(1, "in png_set_compression_mem_level\n");
  193232. if (png_ptr == NULL)
  193233. return;
  193234. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL;
  193235. png_ptr->zlib_mem_level = mem_level;
  193236. }
  193237. void PNGAPI
  193238. png_set_compression_strategy(png_structp png_ptr, int strategy)
  193239. {
  193240. png_debug(1, "in png_set_compression_strategy\n");
  193241. if (png_ptr == NULL)
  193242. return;
  193243. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_STRATEGY;
  193244. png_ptr->zlib_strategy = strategy;
  193245. }
  193246. void PNGAPI
  193247. png_set_compression_window_bits(png_structp png_ptr, int window_bits)
  193248. {
  193249. if (png_ptr == NULL)
  193250. return;
  193251. if (window_bits > 15)
  193252. png_warning(png_ptr, "Only compression windows <= 32k supported by PNG");
  193253. else if (window_bits < 8)
  193254. png_warning(png_ptr, "Only compression windows >= 256 supported by PNG");
  193255. #ifndef WBITS_8_OK
  193256. /* avoid libpng bug with 256-byte windows */
  193257. if (window_bits == 8)
  193258. {
  193259. png_warning(png_ptr, "Compression window is being reset to 512");
  193260. window_bits=9;
  193261. }
  193262. #endif
  193263. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS;
  193264. png_ptr->zlib_window_bits = window_bits;
  193265. }
  193266. void PNGAPI
  193267. png_set_compression_method(png_structp png_ptr, int method)
  193268. {
  193269. png_debug(1, "in png_set_compression_method\n");
  193270. if (png_ptr == NULL)
  193271. return;
  193272. if (method != 8)
  193273. png_warning(png_ptr, "Only compression method 8 is supported by PNG");
  193274. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_METHOD;
  193275. png_ptr->zlib_method = method;
  193276. }
  193277. void PNGAPI
  193278. png_set_write_status_fn(png_structp png_ptr, png_write_status_ptr write_row_fn)
  193279. {
  193280. if (png_ptr == NULL)
  193281. return;
  193282. png_ptr->write_row_fn = write_row_fn;
  193283. }
  193284. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  193285. void PNGAPI
  193286. png_set_write_user_transform_fn(png_structp png_ptr, png_user_transform_ptr
  193287. write_user_transform_fn)
  193288. {
  193289. png_debug(1, "in png_set_write_user_transform_fn\n");
  193290. if (png_ptr == NULL)
  193291. return;
  193292. png_ptr->transformations |= PNG_USER_TRANSFORM;
  193293. png_ptr->write_user_transform_fn = write_user_transform_fn;
  193294. }
  193295. #endif
  193296. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  193297. void PNGAPI
  193298. png_write_png(png_structp png_ptr, png_infop info_ptr,
  193299. int transforms, voidp params)
  193300. {
  193301. if (png_ptr == NULL || info_ptr == NULL)
  193302. return;
  193303. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  193304. /* invert the alpha channel from opacity to transparency */
  193305. if (transforms & PNG_TRANSFORM_INVERT_ALPHA)
  193306. png_set_invert_alpha(png_ptr);
  193307. #endif
  193308. /* Write the file header information. */
  193309. png_write_info(png_ptr, info_ptr);
  193310. /* ------ these transformations don't touch the info structure ------- */
  193311. #if defined(PNG_WRITE_INVERT_SUPPORTED)
  193312. /* invert monochrome pixels */
  193313. if (transforms & PNG_TRANSFORM_INVERT_MONO)
  193314. png_set_invert_mono(png_ptr);
  193315. #endif
  193316. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  193317. /* Shift the pixels up to a legal bit depth and fill in
  193318. * as appropriate to correctly scale the image.
  193319. */
  193320. if ((transforms & PNG_TRANSFORM_SHIFT)
  193321. && (info_ptr->valid & PNG_INFO_sBIT))
  193322. png_set_shift(png_ptr, &info_ptr->sig_bit);
  193323. #endif
  193324. #if defined(PNG_WRITE_PACK_SUPPORTED)
  193325. /* pack pixels into bytes */
  193326. if (transforms & PNG_TRANSFORM_PACKING)
  193327. png_set_packing(png_ptr);
  193328. #endif
  193329. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  193330. /* swap location of alpha bytes from ARGB to RGBA */
  193331. if (transforms & PNG_TRANSFORM_SWAP_ALPHA)
  193332. png_set_swap_alpha(png_ptr);
  193333. #endif
  193334. #if defined(PNG_WRITE_FILLER_SUPPORTED)
  193335. /* Get rid of filler (OR ALPHA) bytes, pack XRGB/RGBX/ARGB/RGBA into
  193336. * RGB (4 channels -> 3 channels). The second parameter is not used.
  193337. */
  193338. if (transforms & PNG_TRANSFORM_STRIP_FILLER)
  193339. png_set_filler(png_ptr, 0, PNG_FILLER_BEFORE);
  193340. #endif
  193341. #if defined(PNG_WRITE_BGR_SUPPORTED)
  193342. /* flip BGR pixels to RGB */
  193343. if (transforms & PNG_TRANSFORM_BGR)
  193344. png_set_bgr(png_ptr);
  193345. #endif
  193346. #if defined(PNG_WRITE_SWAP_SUPPORTED)
  193347. /* swap bytes of 16-bit files to most significant byte first */
  193348. if (transforms & PNG_TRANSFORM_SWAP_ENDIAN)
  193349. png_set_swap(png_ptr);
  193350. #endif
  193351. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  193352. /* swap bits of 1, 2, 4 bit packed pixel formats */
  193353. if (transforms & PNG_TRANSFORM_PACKSWAP)
  193354. png_set_packswap(png_ptr);
  193355. #endif
  193356. /* ----------------------- end of transformations ------------------- */
  193357. /* write the bits */
  193358. if (info_ptr->valid & PNG_INFO_IDAT)
  193359. png_write_image(png_ptr, info_ptr->row_pointers);
  193360. /* It is REQUIRED to call this to finish writing the rest of the file */
  193361. png_write_end(png_ptr, info_ptr);
  193362. transforms = transforms; /* quiet compiler warnings */
  193363. params = params;
  193364. }
  193365. #endif
  193366. #endif /* PNG_WRITE_SUPPORTED */
  193367. /********* End of inlined file: pngwrite.c *********/
  193368. /********* Start of inlined file: pngwtran.c *********/
  193369. /* pngwtran.c - transforms the data in a row for PNG writers
  193370. *
  193371. * Last changed in libpng 1.2.9 April 14, 2006
  193372. * For conditions of distribution and use, see copyright notice in png.h
  193373. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  193374. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  193375. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  193376. */
  193377. #define PNG_INTERNAL
  193378. #ifdef PNG_WRITE_SUPPORTED
  193379. /* Transform the data according to the user's wishes. The order of
  193380. * transformations is significant.
  193381. */
  193382. void /* PRIVATE */
  193383. png_do_write_transformations(png_structp png_ptr)
  193384. {
  193385. png_debug(1, "in png_do_write_transformations\n");
  193386. if (png_ptr == NULL)
  193387. return;
  193388. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  193389. if (png_ptr->transformations & PNG_USER_TRANSFORM)
  193390. if(png_ptr->write_user_transform_fn != NULL)
  193391. (*(png_ptr->write_user_transform_fn)) /* user write transform function */
  193392. (png_ptr, /* png_ptr */
  193393. &(png_ptr->row_info), /* row_info: */
  193394. /* png_uint_32 width; width of row */
  193395. /* png_uint_32 rowbytes; number of bytes in row */
  193396. /* png_byte color_type; color type of pixels */
  193397. /* png_byte bit_depth; bit depth of samples */
  193398. /* png_byte channels; number of channels (1-4) */
  193399. /* png_byte pixel_depth; bits per pixel (depth*channels) */
  193400. png_ptr->row_buf + 1); /* start of pixel data for row */
  193401. #endif
  193402. #if defined(PNG_WRITE_FILLER_SUPPORTED)
  193403. if (png_ptr->transformations & PNG_FILLER)
  193404. png_do_strip_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  193405. png_ptr->flags);
  193406. #endif
  193407. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  193408. if (png_ptr->transformations & PNG_PACKSWAP)
  193409. png_do_packswap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  193410. #endif
  193411. #if defined(PNG_WRITE_PACK_SUPPORTED)
  193412. if (png_ptr->transformations & PNG_PACK)
  193413. png_do_pack(&(png_ptr->row_info), png_ptr->row_buf + 1,
  193414. (png_uint_32)png_ptr->bit_depth);
  193415. #endif
  193416. #if defined(PNG_WRITE_SWAP_SUPPORTED)
  193417. if (png_ptr->transformations & PNG_SWAP_BYTES)
  193418. png_do_swap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  193419. #endif
  193420. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  193421. if (png_ptr->transformations & PNG_SHIFT)
  193422. png_do_shift(&(png_ptr->row_info), png_ptr->row_buf + 1,
  193423. &(png_ptr->shift));
  193424. #endif
  193425. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  193426. if (png_ptr->transformations & PNG_SWAP_ALPHA)
  193427. png_do_write_swap_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  193428. #endif
  193429. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  193430. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  193431. png_do_write_invert_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  193432. #endif
  193433. #if defined(PNG_WRITE_BGR_SUPPORTED)
  193434. if (png_ptr->transformations & PNG_BGR)
  193435. png_do_bgr(&(png_ptr->row_info), png_ptr->row_buf + 1);
  193436. #endif
  193437. #if defined(PNG_WRITE_INVERT_SUPPORTED)
  193438. if (png_ptr->transformations & PNG_INVERT_MONO)
  193439. png_do_invert(&(png_ptr->row_info), png_ptr->row_buf + 1);
  193440. #endif
  193441. }
  193442. #if defined(PNG_WRITE_PACK_SUPPORTED)
  193443. /* Pack pixels into bytes. Pass the true bit depth in bit_depth. The
  193444. * row_info bit depth should be 8 (one pixel per byte). The channels
  193445. * should be 1 (this only happens on grayscale and paletted images).
  193446. */
  193447. void /* PRIVATE */
  193448. png_do_pack(png_row_infop row_info, png_bytep row, png_uint_32 bit_depth)
  193449. {
  193450. png_debug(1, "in png_do_pack\n");
  193451. if (row_info->bit_depth == 8 &&
  193452. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193453. row != NULL && row_info != NULL &&
  193454. #endif
  193455. row_info->channels == 1)
  193456. {
  193457. switch ((int)bit_depth)
  193458. {
  193459. case 1:
  193460. {
  193461. png_bytep sp, dp;
  193462. int mask, v;
  193463. png_uint_32 i;
  193464. png_uint_32 row_width = row_info->width;
  193465. sp = row;
  193466. dp = row;
  193467. mask = 0x80;
  193468. v = 0;
  193469. for (i = 0; i < row_width; i++)
  193470. {
  193471. if (*sp != 0)
  193472. v |= mask;
  193473. sp++;
  193474. if (mask > 1)
  193475. mask >>= 1;
  193476. else
  193477. {
  193478. mask = 0x80;
  193479. *dp = (png_byte)v;
  193480. dp++;
  193481. v = 0;
  193482. }
  193483. }
  193484. if (mask != 0x80)
  193485. *dp = (png_byte)v;
  193486. break;
  193487. }
  193488. case 2:
  193489. {
  193490. png_bytep sp, dp;
  193491. int shift, v;
  193492. png_uint_32 i;
  193493. png_uint_32 row_width = row_info->width;
  193494. sp = row;
  193495. dp = row;
  193496. shift = 6;
  193497. v = 0;
  193498. for (i = 0; i < row_width; i++)
  193499. {
  193500. png_byte value;
  193501. value = (png_byte)(*sp & 0x03);
  193502. v |= (value << shift);
  193503. if (shift == 0)
  193504. {
  193505. shift = 6;
  193506. *dp = (png_byte)v;
  193507. dp++;
  193508. v = 0;
  193509. }
  193510. else
  193511. shift -= 2;
  193512. sp++;
  193513. }
  193514. if (shift != 6)
  193515. *dp = (png_byte)v;
  193516. break;
  193517. }
  193518. case 4:
  193519. {
  193520. png_bytep sp, dp;
  193521. int shift, v;
  193522. png_uint_32 i;
  193523. png_uint_32 row_width = row_info->width;
  193524. sp = row;
  193525. dp = row;
  193526. shift = 4;
  193527. v = 0;
  193528. for (i = 0; i < row_width; i++)
  193529. {
  193530. png_byte value;
  193531. value = (png_byte)(*sp & 0x0f);
  193532. v |= (value << shift);
  193533. if (shift == 0)
  193534. {
  193535. shift = 4;
  193536. *dp = (png_byte)v;
  193537. dp++;
  193538. v = 0;
  193539. }
  193540. else
  193541. shift -= 4;
  193542. sp++;
  193543. }
  193544. if (shift != 4)
  193545. *dp = (png_byte)v;
  193546. break;
  193547. }
  193548. }
  193549. row_info->bit_depth = (png_byte)bit_depth;
  193550. row_info->pixel_depth = (png_byte)(bit_depth * row_info->channels);
  193551. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  193552. row_info->width);
  193553. }
  193554. }
  193555. #endif
  193556. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  193557. /* Shift pixel values to take advantage of whole range. Pass the
  193558. * true number of bits in bit_depth. The row should be packed
  193559. * according to row_info->bit_depth. Thus, if you had a row of
  193560. * bit depth 4, but the pixels only had values from 0 to 7, you
  193561. * would pass 3 as bit_depth, and this routine would translate the
  193562. * data to 0 to 15.
  193563. */
  193564. void /* PRIVATE */
  193565. png_do_shift(png_row_infop row_info, png_bytep row, png_color_8p bit_depth)
  193566. {
  193567. png_debug(1, "in png_do_shift\n");
  193568. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193569. if (row != NULL && row_info != NULL &&
  193570. #else
  193571. if (
  193572. #endif
  193573. row_info->color_type != PNG_COLOR_TYPE_PALETTE)
  193574. {
  193575. int shift_start[4], shift_dec[4];
  193576. int channels = 0;
  193577. if (row_info->color_type & PNG_COLOR_MASK_COLOR)
  193578. {
  193579. shift_start[channels] = row_info->bit_depth - bit_depth->red;
  193580. shift_dec[channels] = bit_depth->red;
  193581. channels++;
  193582. shift_start[channels] = row_info->bit_depth - bit_depth->green;
  193583. shift_dec[channels] = bit_depth->green;
  193584. channels++;
  193585. shift_start[channels] = row_info->bit_depth - bit_depth->blue;
  193586. shift_dec[channels] = bit_depth->blue;
  193587. channels++;
  193588. }
  193589. else
  193590. {
  193591. shift_start[channels] = row_info->bit_depth - bit_depth->gray;
  193592. shift_dec[channels] = bit_depth->gray;
  193593. channels++;
  193594. }
  193595. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  193596. {
  193597. shift_start[channels] = row_info->bit_depth - bit_depth->alpha;
  193598. shift_dec[channels] = bit_depth->alpha;
  193599. channels++;
  193600. }
  193601. /* with low row depths, could only be grayscale, so one channel */
  193602. if (row_info->bit_depth < 8)
  193603. {
  193604. png_bytep bp = row;
  193605. png_uint_32 i;
  193606. png_byte mask;
  193607. png_uint_32 row_bytes = row_info->rowbytes;
  193608. if (bit_depth->gray == 1 && row_info->bit_depth == 2)
  193609. mask = 0x55;
  193610. else if (row_info->bit_depth == 4 && bit_depth->gray == 3)
  193611. mask = 0x11;
  193612. else
  193613. mask = 0xff;
  193614. for (i = 0; i < row_bytes; i++, bp++)
  193615. {
  193616. png_uint_16 v;
  193617. int j;
  193618. v = *bp;
  193619. *bp = 0;
  193620. for (j = shift_start[0]; j > -shift_dec[0]; j -= shift_dec[0])
  193621. {
  193622. if (j > 0)
  193623. *bp |= (png_byte)((v << j) & 0xff);
  193624. else
  193625. *bp |= (png_byte)((v >> (-j)) & mask);
  193626. }
  193627. }
  193628. }
  193629. else if (row_info->bit_depth == 8)
  193630. {
  193631. png_bytep bp = row;
  193632. png_uint_32 i;
  193633. png_uint_32 istop = channels * row_info->width;
  193634. for (i = 0; i < istop; i++, bp++)
  193635. {
  193636. png_uint_16 v;
  193637. int j;
  193638. int c = (int)(i%channels);
  193639. v = *bp;
  193640. *bp = 0;
  193641. for (j = shift_start[c]; j > -shift_dec[c]; j -= shift_dec[c])
  193642. {
  193643. if (j > 0)
  193644. *bp |= (png_byte)((v << j) & 0xff);
  193645. else
  193646. *bp |= (png_byte)((v >> (-j)) & 0xff);
  193647. }
  193648. }
  193649. }
  193650. else
  193651. {
  193652. png_bytep bp;
  193653. png_uint_32 i;
  193654. png_uint_32 istop = channels * row_info->width;
  193655. for (bp = row, i = 0; i < istop; i++)
  193656. {
  193657. int c = (int)(i%channels);
  193658. png_uint_16 value, v;
  193659. int j;
  193660. v = (png_uint_16)(((png_uint_16)(*bp) << 8) + *(bp + 1));
  193661. value = 0;
  193662. for (j = shift_start[c]; j > -shift_dec[c]; j -= shift_dec[c])
  193663. {
  193664. if (j > 0)
  193665. value |= (png_uint_16)((v << j) & (png_uint_16)0xffff);
  193666. else
  193667. value |= (png_uint_16)((v >> (-j)) & (png_uint_16)0xffff);
  193668. }
  193669. *bp++ = (png_byte)(value >> 8);
  193670. *bp++ = (png_byte)(value & 0xff);
  193671. }
  193672. }
  193673. }
  193674. }
  193675. #endif
  193676. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  193677. void /* PRIVATE */
  193678. png_do_write_swap_alpha(png_row_infop row_info, png_bytep row)
  193679. {
  193680. png_debug(1, "in png_do_write_swap_alpha\n");
  193681. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193682. if (row != NULL && row_info != NULL)
  193683. #endif
  193684. {
  193685. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  193686. {
  193687. /* This converts from ARGB to RGBA */
  193688. if (row_info->bit_depth == 8)
  193689. {
  193690. png_bytep sp, dp;
  193691. png_uint_32 i;
  193692. png_uint_32 row_width = row_info->width;
  193693. for (i = 0, sp = dp = row; i < row_width; i++)
  193694. {
  193695. png_byte save = *(sp++);
  193696. *(dp++) = *(sp++);
  193697. *(dp++) = *(sp++);
  193698. *(dp++) = *(sp++);
  193699. *(dp++) = save;
  193700. }
  193701. }
  193702. /* This converts from AARRGGBB to RRGGBBAA */
  193703. else
  193704. {
  193705. png_bytep sp, dp;
  193706. png_uint_32 i;
  193707. png_uint_32 row_width = row_info->width;
  193708. for (i = 0, sp = dp = row; i < row_width; i++)
  193709. {
  193710. png_byte save[2];
  193711. save[0] = *(sp++);
  193712. save[1] = *(sp++);
  193713. *(dp++) = *(sp++);
  193714. *(dp++) = *(sp++);
  193715. *(dp++) = *(sp++);
  193716. *(dp++) = *(sp++);
  193717. *(dp++) = *(sp++);
  193718. *(dp++) = *(sp++);
  193719. *(dp++) = save[0];
  193720. *(dp++) = save[1];
  193721. }
  193722. }
  193723. }
  193724. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  193725. {
  193726. /* This converts from AG to GA */
  193727. if (row_info->bit_depth == 8)
  193728. {
  193729. png_bytep sp, dp;
  193730. png_uint_32 i;
  193731. png_uint_32 row_width = row_info->width;
  193732. for (i = 0, sp = dp = row; i < row_width; i++)
  193733. {
  193734. png_byte save = *(sp++);
  193735. *(dp++) = *(sp++);
  193736. *(dp++) = save;
  193737. }
  193738. }
  193739. /* This converts from AAGG to GGAA */
  193740. else
  193741. {
  193742. png_bytep sp, dp;
  193743. png_uint_32 i;
  193744. png_uint_32 row_width = row_info->width;
  193745. for (i = 0, sp = dp = row; i < row_width; i++)
  193746. {
  193747. png_byte save[2];
  193748. save[0] = *(sp++);
  193749. save[1] = *(sp++);
  193750. *(dp++) = *(sp++);
  193751. *(dp++) = *(sp++);
  193752. *(dp++) = save[0];
  193753. *(dp++) = save[1];
  193754. }
  193755. }
  193756. }
  193757. }
  193758. }
  193759. #endif
  193760. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  193761. void /* PRIVATE */
  193762. png_do_write_invert_alpha(png_row_infop row_info, png_bytep row)
  193763. {
  193764. png_debug(1, "in png_do_write_invert_alpha\n");
  193765. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193766. if (row != NULL && row_info != NULL)
  193767. #endif
  193768. {
  193769. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  193770. {
  193771. /* This inverts the alpha channel in RGBA */
  193772. if (row_info->bit_depth == 8)
  193773. {
  193774. png_bytep sp, dp;
  193775. png_uint_32 i;
  193776. png_uint_32 row_width = row_info->width;
  193777. for (i = 0, sp = dp = row; i < row_width; i++)
  193778. {
  193779. /* does nothing
  193780. *(dp++) = *(sp++);
  193781. *(dp++) = *(sp++);
  193782. *(dp++) = *(sp++);
  193783. */
  193784. sp+=3; dp = sp;
  193785. *(dp++) = (png_byte)(255 - *(sp++));
  193786. }
  193787. }
  193788. /* This inverts the alpha channel in RRGGBBAA */
  193789. else
  193790. {
  193791. png_bytep sp, dp;
  193792. png_uint_32 i;
  193793. png_uint_32 row_width = row_info->width;
  193794. for (i = 0, sp = dp = row; i < row_width; i++)
  193795. {
  193796. /* does nothing
  193797. *(dp++) = *(sp++);
  193798. *(dp++) = *(sp++);
  193799. *(dp++) = *(sp++);
  193800. *(dp++) = *(sp++);
  193801. *(dp++) = *(sp++);
  193802. *(dp++) = *(sp++);
  193803. */
  193804. sp+=6; dp = sp;
  193805. *(dp++) = (png_byte)(255 - *(sp++));
  193806. *(dp++) = (png_byte)(255 - *(sp++));
  193807. }
  193808. }
  193809. }
  193810. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  193811. {
  193812. /* This inverts the alpha channel in GA */
  193813. if (row_info->bit_depth == 8)
  193814. {
  193815. png_bytep sp, dp;
  193816. png_uint_32 i;
  193817. png_uint_32 row_width = row_info->width;
  193818. for (i = 0, sp = dp = row; i < row_width; i++)
  193819. {
  193820. *(dp++) = *(sp++);
  193821. *(dp++) = (png_byte)(255 - *(sp++));
  193822. }
  193823. }
  193824. /* This inverts the alpha channel in GGAA */
  193825. else
  193826. {
  193827. png_bytep sp, dp;
  193828. png_uint_32 i;
  193829. png_uint_32 row_width = row_info->width;
  193830. for (i = 0, sp = dp = row; i < row_width; i++)
  193831. {
  193832. /* does nothing
  193833. *(dp++) = *(sp++);
  193834. *(dp++) = *(sp++);
  193835. */
  193836. sp+=2; dp = sp;
  193837. *(dp++) = (png_byte)(255 - *(sp++));
  193838. *(dp++) = (png_byte)(255 - *(sp++));
  193839. }
  193840. }
  193841. }
  193842. }
  193843. }
  193844. #endif
  193845. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  193846. /* undoes intrapixel differencing */
  193847. void /* PRIVATE */
  193848. png_do_write_intrapixel(png_row_infop row_info, png_bytep row)
  193849. {
  193850. png_debug(1, "in png_do_write_intrapixel\n");
  193851. if (
  193852. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193853. row != NULL && row_info != NULL &&
  193854. #endif
  193855. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  193856. {
  193857. int bytes_per_pixel;
  193858. png_uint_32 row_width = row_info->width;
  193859. if (row_info->bit_depth == 8)
  193860. {
  193861. png_bytep rp;
  193862. png_uint_32 i;
  193863. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  193864. bytes_per_pixel = 3;
  193865. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  193866. bytes_per_pixel = 4;
  193867. else
  193868. return;
  193869. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  193870. {
  193871. *(rp) = (png_byte)((*rp - *(rp+1))&0xff);
  193872. *(rp+2) = (png_byte)((*(rp+2) - *(rp+1))&0xff);
  193873. }
  193874. }
  193875. else if (row_info->bit_depth == 16)
  193876. {
  193877. png_bytep rp;
  193878. png_uint_32 i;
  193879. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  193880. bytes_per_pixel = 6;
  193881. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  193882. bytes_per_pixel = 8;
  193883. else
  193884. return;
  193885. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  193886. {
  193887. png_uint_32 s0 = (*(rp ) << 8) | *(rp+1);
  193888. png_uint_32 s1 = (*(rp+2) << 8) | *(rp+3);
  193889. png_uint_32 s2 = (*(rp+4) << 8) | *(rp+5);
  193890. png_uint_32 red = (png_uint_32)((s0-s1) & 0xffffL);
  193891. png_uint_32 blue = (png_uint_32)((s2-s1) & 0xffffL);
  193892. *(rp ) = (png_byte)((red >> 8) & 0xff);
  193893. *(rp+1) = (png_byte)(red & 0xff);
  193894. *(rp+4) = (png_byte)((blue >> 8) & 0xff);
  193895. *(rp+5) = (png_byte)(blue & 0xff);
  193896. }
  193897. }
  193898. }
  193899. }
  193900. #endif /* PNG_MNG_FEATURES_SUPPORTED */
  193901. #endif /* PNG_WRITE_SUPPORTED */
  193902. /********* End of inlined file: pngwtran.c *********/
  193903. /********* Start of inlined file: pngwutil.c *********/
  193904. /* pngwutil.c - utilities to write a PNG file
  193905. *
  193906. * Last changed in libpng 1.2.20 Septhember 3, 2007
  193907. * For conditions of distribution and use, see copyright notice in png.h
  193908. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  193909. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  193910. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  193911. */
  193912. #define PNG_INTERNAL
  193913. #ifdef PNG_WRITE_SUPPORTED
  193914. /* Place a 32-bit number into a buffer in PNG byte order. We work
  193915. * with unsigned numbers for convenience, although one supported
  193916. * ancillary chunk uses signed (two's complement) numbers.
  193917. */
  193918. void PNGAPI
  193919. png_save_uint_32(png_bytep buf, png_uint_32 i)
  193920. {
  193921. buf[0] = (png_byte)((i >> 24) & 0xff);
  193922. buf[1] = (png_byte)((i >> 16) & 0xff);
  193923. buf[2] = (png_byte)((i >> 8) & 0xff);
  193924. buf[3] = (png_byte)(i & 0xff);
  193925. }
  193926. /* The png_save_int_32 function assumes integers are stored in two's
  193927. * complement format. If this isn't the case, then this routine needs to
  193928. * be modified to write data in two's complement format.
  193929. */
  193930. void PNGAPI
  193931. png_save_int_32(png_bytep buf, png_int_32 i)
  193932. {
  193933. buf[0] = (png_byte)((i >> 24) & 0xff);
  193934. buf[1] = (png_byte)((i >> 16) & 0xff);
  193935. buf[2] = (png_byte)((i >> 8) & 0xff);
  193936. buf[3] = (png_byte)(i & 0xff);
  193937. }
  193938. /* Place a 16-bit number into a buffer in PNG byte order.
  193939. * The parameter is declared unsigned int, not png_uint_16,
  193940. * just to avoid potential problems on pre-ANSI C compilers.
  193941. */
  193942. void PNGAPI
  193943. png_save_uint_16(png_bytep buf, unsigned int i)
  193944. {
  193945. buf[0] = (png_byte)((i >> 8) & 0xff);
  193946. buf[1] = (png_byte)(i & 0xff);
  193947. }
  193948. /* Write a PNG chunk all at once. The type is an array of ASCII characters
  193949. * representing the chunk name. The array must be at least 4 bytes in
  193950. * length, and does not need to be null terminated. To be safe, pass the
  193951. * pre-defined chunk names here, and if you need a new one, define it
  193952. * where the others are defined. The length is the length of the data.
  193953. * All the data must be present. If that is not possible, use the
  193954. * png_write_chunk_start(), png_write_chunk_data(), and png_write_chunk_end()
  193955. * functions instead.
  193956. */
  193957. void PNGAPI
  193958. png_write_chunk(png_structp png_ptr, png_bytep chunk_name,
  193959. png_bytep data, png_size_t length)
  193960. {
  193961. if(png_ptr == NULL) return;
  193962. png_write_chunk_start(png_ptr, chunk_name, (png_uint_32)length);
  193963. png_write_chunk_data(png_ptr, data, length);
  193964. png_write_chunk_end(png_ptr);
  193965. }
  193966. /* Write the start of a PNG chunk. The type is the chunk type.
  193967. * The total_length is the sum of the lengths of all the data you will be
  193968. * passing in png_write_chunk_data().
  193969. */
  193970. void PNGAPI
  193971. png_write_chunk_start(png_structp png_ptr, png_bytep chunk_name,
  193972. png_uint_32 length)
  193973. {
  193974. png_byte buf[4];
  193975. png_debug2(0, "Writing %s chunk (%lu bytes)\n", chunk_name, length);
  193976. if(png_ptr == NULL) return;
  193977. /* write the length */
  193978. png_save_uint_32(buf, length);
  193979. png_write_data(png_ptr, buf, (png_size_t)4);
  193980. /* write the chunk name */
  193981. png_write_data(png_ptr, chunk_name, (png_size_t)4);
  193982. /* reset the crc and run it over the chunk name */
  193983. png_reset_crc(png_ptr);
  193984. png_calculate_crc(png_ptr, chunk_name, (png_size_t)4);
  193985. }
  193986. /* Write the data of a PNG chunk started with png_write_chunk_start().
  193987. * Note that multiple calls to this function are allowed, and that the
  193988. * sum of the lengths from these calls *must* add up to the total_length
  193989. * given to png_write_chunk_start().
  193990. */
  193991. void PNGAPI
  193992. png_write_chunk_data(png_structp png_ptr, png_bytep data, png_size_t length)
  193993. {
  193994. /* write the data, and run the CRC over it */
  193995. if(png_ptr == NULL) return;
  193996. if (data != NULL && length > 0)
  193997. {
  193998. png_calculate_crc(png_ptr, data, length);
  193999. png_write_data(png_ptr, data, length);
  194000. }
  194001. }
  194002. /* Finish a chunk started with png_write_chunk_start(). */
  194003. void PNGAPI
  194004. png_write_chunk_end(png_structp png_ptr)
  194005. {
  194006. png_byte buf[4];
  194007. if(png_ptr == NULL) return;
  194008. /* write the crc */
  194009. png_save_uint_32(buf, png_ptr->crc);
  194010. png_write_data(png_ptr, buf, (png_size_t)4);
  194011. }
  194012. /* Simple function to write the signature. If we have already written
  194013. * the magic bytes of the signature, or more likely, the PNG stream is
  194014. * being embedded into another stream and doesn't need its own signature,
  194015. * we should call png_set_sig_bytes() to tell libpng how many of the
  194016. * bytes have already been written.
  194017. */
  194018. void /* PRIVATE */
  194019. png_write_sig(png_structp png_ptr)
  194020. {
  194021. png_byte png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  194022. /* write the rest of the 8 byte signature */
  194023. png_write_data(png_ptr, &png_signature[png_ptr->sig_bytes],
  194024. (png_size_t)8 - png_ptr->sig_bytes);
  194025. if(png_ptr->sig_bytes < 3)
  194026. png_ptr->mode |= PNG_HAVE_PNG_SIGNATURE;
  194027. }
  194028. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_iCCP_SUPPORTED)
  194029. /*
  194030. * This pair of functions encapsulates the operation of (a) compressing a
  194031. * text string, and (b) issuing it later as a series of chunk data writes.
  194032. * The compression_state structure is shared context for these functions
  194033. * set up by the caller in order to make the whole mess thread-safe.
  194034. */
  194035. typedef struct
  194036. {
  194037. char *input; /* the uncompressed input data */
  194038. int input_len; /* its length */
  194039. int num_output_ptr; /* number of output pointers used */
  194040. int max_output_ptr; /* size of output_ptr */
  194041. png_charpp output_ptr; /* array of pointers to output */
  194042. } compression_state;
  194043. /* compress given text into storage in the png_ptr structure */
  194044. static int /* PRIVATE */
  194045. png_text_compress(png_structp png_ptr,
  194046. png_charp text, png_size_t text_len, int compression,
  194047. compression_state *comp)
  194048. {
  194049. int ret;
  194050. comp->num_output_ptr = 0;
  194051. comp->max_output_ptr = 0;
  194052. comp->output_ptr = NULL;
  194053. comp->input = NULL;
  194054. comp->input_len = 0;
  194055. /* we may just want to pass the text right through */
  194056. if (compression == PNG_TEXT_COMPRESSION_NONE)
  194057. {
  194058. comp->input = text;
  194059. comp->input_len = text_len;
  194060. return((int)text_len);
  194061. }
  194062. if (compression >= PNG_TEXT_COMPRESSION_LAST)
  194063. {
  194064. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  194065. char msg[50];
  194066. png_snprintf(msg, 50, "Unknown compression type %d", compression);
  194067. png_warning(png_ptr, msg);
  194068. #else
  194069. png_warning(png_ptr, "Unknown compression type");
  194070. #endif
  194071. }
  194072. /* We can't write the chunk until we find out how much data we have,
  194073. * which means we need to run the compressor first and save the
  194074. * output. This shouldn't be a problem, as the vast majority of
  194075. * comments should be reasonable, but we will set up an array of
  194076. * malloc'd pointers to be sure.
  194077. *
  194078. * If we knew the application was well behaved, we could simplify this
  194079. * greatly by assuming we can always malloc an output buffer large
  194080. * enough to hold the compressed text ((1001 * text_len / 1000) + 12)
  194081. * and malloc this directly. The only time this would be a bad idea is
  194082. * if we can't malloc more than 64K and we have 64K of random input
  194083. * data, or if the input string is incredibly large (although this
  194084. * wouldn't cause a failure, just a slowdown due to swapping).
  194085. */
  194086. /* set up the compression buffers */
  194087. png_ptr->zstream.avail_in = (uInt)text_len;
  194088. png_ptr->zstream.next_in = (Bytef *)text;
  194089. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  194090. png_ptr->zstream.next_out = (Bytef *)png_ptr->zbuf;
  194091. /* this is the same compression loop as in png_write_row() */
  194092. do
  194093. {
  194094. /* compress the data */
  194095. ret = deflate(&png_ptr->zstream, Z_NO_FLUSH);
  194096. if (ret != Z_OK)
  194097. {
  194098. /* error */
  194099. if (png_ptr->zstream.msg != NULL)
  194100. png_error(png_ptr, png_ptr->zstream.msg);
  194101. else
  194102. png_error(png_ptr, "zlib error");
  194103. }
  194104. /* check to see if we need more room */
  194105. if (!(png_ptr->zstream.avail_out))
  194106. {
  194107. /* make sure the output array has room */
  194108. if (comp->num_output_ptr >= comp->max_output_ptr)
  194109. {
  194110. int old_max;
  194111. old_max = comp->max_output_ptr;
  194112. comp->max_output_ptr = comp->num_output_ptr + 4;
  194113. if (comp->output_ptr != NULL)
  194114. {
  194115. png_charpp old_ptr;
  194116. old_ptr = comp->output_ptr;
  194117. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  194118. (png_uint_32)(comp->max_output_ptr *
  194119. png_sizeof (png_charpp)));
  194120. png_memcpy(comp->output_ptr, old_ptr, old_max
  194121. * png_sizeof (png_charp));
  194122. png_free(png_ptr, old_ptr);
  194123. }
  194124. else
  194125. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  194126. (png_uint_32)(comp->max_output_ptr *
  194127. png_sizeof (png_charp)));
  194128. }
  194129. /* save the data */
  194130. comp->output_ptr[comp->num_output_ptr] = (png_charp)png_malloc(png_ptr,
  194131. (png_uint_32)png_ptr->zbuf_size);
  194132. png_memcpy(comp->output_ptr[comp->num_output_ptr], png_ptr->zbuf,
  194133. png_ptr->zbuf_size);
  194134. comp->num_output_ptr++;
  194135. /* and reset the buffer */
  194136. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  194137. png_ptr->zstream.next_out = png_ptr->zbuf;
  194138. }
  194139. /* continue until we don't have any more to compress */
  194140. } while (png_ptr->zstream.avail_in);
  194141. /* finish the compression */
  194142. do
  194143. {
  194144. /* tell zlib we are finished */
  194145. ret = deflate(&png_ptr->zstream, Z_FINISH);
  194146. if (ret == Z_OK)
  194147. {
  194148. /* check to see if we need more room */
  194149. if (!(png_ptr->zstream.avail_out))
  194150. {
  194151. /* check to make sure our output array has room */
  194152. if (comp->num_output_ptr >= comp->max_output_ptr)
  194153. {
  194154. int old_max;
  194155. old_max = comp->max_output_ptr;
  194156. comp->max_output_ptr = comp->num_output_ptr + 4;
  194157. if (comp->output_ptr != NULL)
  194158. {
  194159. png_charpp old_ptr;
  194160. old_ptr = comp->output_ptr;
  194161. /* This could be optimized to realloc() */
  194162. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  194163. (png_uint_32)(comp->max_output_ptr *
  194164. png_sizeof (png_charpp)));
  194165. png_memcpy(comp->output_ptr, old_ptr,
  194166. old_max * png_sizeof (png_charp));
  194167. png_free(png_ptr, old_ptr);
  194168. }
  194169. else
  194170. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  194171. (png_uint_32)(comp->max_output_ptr *
  194172. png_sizeof (png_charp)));
  194173. }
  194174. /* save off the data */
  194175. comp->output_ptr[comp->num_output_ptr] =
  194176. (png_charp)png_malloc(png_ptr, (png_uint_32)png_ptr->zbuf_size);
  194177. png_memcpy(comp->output_ptr[comp->num_output_ptr], png_ptr->zbuf,
  194178. png_ptr->zbuf_size);
  194179. comp->num_output_ptr++;
  194180. /* and reset the buffer pointers */
  194181. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  194182. png_ptr->zstream.next_out = png_ptr->zbuf;
  194183. }
  194184. }
  194185. else if (ret != Z_STREAM_END)
  194186. {
  194187. /* we got an error */
  194188. if (png_ptr->zstream.msg != NULL)
  194189. png_error(png_ptr, png_ptr->zstream.msg);
  194190. else
  194191. png_error(png_ptr, "zlib error");
  194192. }
  194193. } while (ret != Z_STREAM_END);
  194194. /* text length is number of buffers plus last buffer */
  194195. text_len = png_ptr->zbuf_size * comp->num_output_ptr;
  194196. if (png_ptr->zstream.avail_out < png_ptr->zbuf_size)
  194197. text_len += png_ptr->zbuf_size - (png_size_t)png_ptr->zstream.avail_out;
  194198. return((int)text_len);
  194199. }
  194200. /* ship the compressed text out via chunk writes */
  194201. static void /* PRIVATE */
  194202. png_write_compressed_data_out(png_structp png_ptr, compression_state *comp)
  194203. {
  194204. int i;
  194205. /* handle the no-compression case */
  194206. if (comp->input)
  194207. {
  194208. png_write_chunk_data(png_ptr, (png_bytep)comp->input,
  194209. (png_size_t)comp->input_len);
  194210. return;
  194211. }
  194212. /* write saved output buffers, if any */
  194213. for (i = 0; i < comp->num_output_ptr; i++)
  194214. {
  194215. png_write_chunk_data(png_ptr,(png_bytep)comp->output_ptr[i],
  194216. png_ptr->zbuf_size);
  194217. png_free(png_ptr, comp->output_ptr[i]);
  194218. comp->output_ptr[i]=NULL;
  194219. }
  194220. if (comp->max_output_ptr != 0)
  194221. png_free(png_ptr, comp->output_ptr);
  194222. comp->output_ptr=NULL;
  194223. /* write anything left in zbuf */
  194224. if (png_ptr->zstream.avail_out < (png_uint_32)png_ptr->zbuf_size)
  194225. png_write_chunk_data(png_ptr, png_ptr->zbuf,
  194226. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  194227. /* reset zlib for another zTXt/iTXt or image data */
  194228. deflateReset(&png_ptr->zstream);
  194229. png_ptr->zstream.data_type = Z_BINARY;
  194230. }
  194231. #endif
  194232. /* Write the IHDR chunk, and update the png_struct with the necessary
  194233. * information. Note that the rest of this code depends upon this
  194234. * information being correct.
  194235. */
  194236. void /* PRIVATE */
  194237. png_write_IHDR(png_structp png_ptr, png_uint_32 width, png_uint_32 height,
  194238. int bit_depth, int color_type, int compression_type, int filter_type,
  194239. int interlace_type)
  194240. {
  194241. #ifdef PNG_USE_LOCAL_ARRAYS
  194242. PNG_IHDR;
  194243. #endif
  194244. png_byte buf[13]; /* buffer to store the IHDR info */
  194245. png_debug(1, "in png_write_IHDR\n");
  194246. /* Check that we have valid input data from the application info */
  194247. switch (color_type)
  194248. {
  194249. case PNG_COLOR_TYPE_GRAY:
  194250. switch (bit_depth)
  194251. {
  194252. case 1:
  194253. case 2:
  194254. case 4:
  194255. case 8:
  194256. case 16: png_ptr->channels = 1; break;
  194257. default: png_error(png_ptr,"Invalid bit depth for grayscale image");
  194258. }
  194259. break;
  194260. case PNG_COLOR_TYPE_RGB:
  194261. if (bit_depth != 8 && bit_depth != 16)
  194262. png_error(png_ptr, "Invalid bit depth for RGB image");
  194263. png_ptr->channels = 3;
  194264. break;
  194265. case PNG_COLOR_TYPE_PALETTE:
  194266. switch (bit_depth)
  194267. {
  194268. case 1:
  194269. case 2:
  194270. case 4:
  194271. case 8: png_ptr->channels = 1; break;
  194272. default: png_error(png_ptr, "Invalid bit depth for paletted image");
  194273. }
  194274. break;
  194275. case PNG_COLOR_TYPE_GRAY_ALPHA:
  194276. if (bit_depth != 8 && bit_depth != 16)
  194277. png_error(png_ptr, "Invalid bit depth for grayscale+alpha image");
  194278. png_ptr->channels = 2;
  194279. break;
  194280. case PNG_COLOR_TYPE_RGB_ALPHA:
  194281. if (bit_depth != 8 && bit_depth != 16)
  194282. png_error(png_ptr, "Invalid bit depth for RGBA image");
  194283. png_ptr->channels = 4;
  194284. break;
  194285. default:
  194286. png_error(png_ptr, "Invalid image color type specified");
  194287. }
  194288. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  194289. {
  194290. png_warning(png_ptr, "Invalid compression type specified");
  194291. compression_type = PNG_COMPRESSION_TYPE_BASE;
  194292. }
  194293. /* Write filter_method 64 (intrapixel differencing) only if
  194294. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  194295. * 2. Libpng did not write a PNG signature (this filter_method is only
  194296. * used in PNG datastreams that are embedded in MNG datastreams) and
  194297. * 3. The application called png_permit_mng_features with a mask that
  194298. * included PNG_FLAG_MNG_FILTER_64 and
  194299. * 4. The filter_method is 64 and
  194300. * 5. The color_type is RGB or RGBA
  194301. */
  194302. if (
  194303. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  194304. !((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  194305. ((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE) == 0) &&
  194306. (color_type == PNG_COLOR_TYPE_RGB ||
  194307. color_type == PNG_COLOR_TYPE_RGB_ALPHA) &&
  194308. (filter_type == PNG_INTRAPIXEL_DIFFERENCING)) &&
  194309. #endif
  194310. filter_type != PNG_FILTER_TYPE_BASE)
  194311. {
  194312. png_warning(png_ptr, "Invalid filter type specified");
  194313. filter_type = PNG_FILTER_TYPE_BASE;
  194314. }
  194315. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  194316. if (interlace_type != PNG_INTERLACE_NONE &&
  194317. interlace_type != PNG_INTERLACE_ADAM7)
  194318. {
  194319. png_warning(png_ptr, "Invalid interlace type specified");
  194320. interlace_type = PNG_INTERLACE_ADAM7;
  194321. }
  194322. #else
  194323. interlace_type=PNG_INTERLACE_NONE;
  194324. #endif
  194325. /* save off the relevent information */
  194326. png_ptr->bit_depth = (png_byte)bit_depth;
  194327. png_ptr->color_type = (png_byte)color_type;
  194328. png_ptr->interlaced = (png_byte)interlace_type;
  194329. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  194330. png_ptr->filter_type = (png_byte)filter_type;
  194331. #endif
  194332. png_ptr->compression_type = (png_byte)compression_type;
  194333. png_ptr->width = width;
  194334. png_ptr->height = height;
  194335. png_ptr->pixel_depth = (png_byte)(bit_depth * png_ptr->channels);
  194336. png_ptr->rowbytes = PNG_ROWBYTES(png_ptr->pixel_depth, width);
  194337. /* set the usr info, so any transformations can modify it */
  194338. png_ptr->usr_width = png_ptr->width;
  194339. png_ptr->usr_bit_depth = png_ptr->bit_depth;
  194340. png_ptr->usr_channels = png_ptr->channels;
  194341. /* pack the header information into the buffer */
  194342. png_save_uint_32(buf, width);
  194343. png_save_uint_32(buf + 4, height);
  194344. buf[8] = (png_byte)bit_depth;
  194345. buf[9] = (png_byte)color_type;
  194346. buf[10] = (png_byte)compression_type;
  194347. buf[11] = (png_byte)filter_type;
  194348. buf[12] = (png_byte)interlace_type;
  194349. /* write the chunk */
  194350. png_write_chunk(png_ptr, png_IHDR, buf, (png_size_t)13);
  194351. /* initialize zlib with PNG info */
  194352. png_ptr->zstream.zalloc = png_zalloc;
  194353. png_ptr->zstream.zfree = png_zfree;
  194354. png_ptr->zstream.opaque = (voidpf)png_ptr;
  194355. if (!(png_ptr->do_filter))
  194356. {
  194357. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE ||
  194358. png_ptr->bit_depth < 8)
  194359. png_ptr->do_filter = PNG_FILTER_NONE;
  194360. else
  194361. png_ptr->do_filter = PNG_ALL_FILTERS;
  194362. }
  194363. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_STRATEGY))
  194364. {
  194365. if (png_ptr->do_filter != PNG_FILTER_NONE)
  194366. png_ptr->zlib_strategy = Z_FILTERED;
  194367. else
  194368. png_ptr->zlib_strategy = Z_DEFAULT_STRATEGY;
  194369. }
  194370. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_LEVEL))
  194371. png_ptr->zlib_level = Z_DEFAULT_COMPRESSION;
  194372. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL))
  194373. png_ptr->zlib_mem_level = 8;
  194374. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS))
  194375. png_ptr->zlib_window_bits = 15;
  194376. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_METHOD))
  194377. png_ptr->zlib_method = 8;
  194378. if (deflateInit2(&png_ptr->zstream, png_ptr->zlib_level,
  194379. png_ptr->zlib_method, png_ptr->zlib_window_bits,
  194380. png_ptr->zlib_mem_level, png_ptr->zlib_strategy) != Z_OK)
  194381. png_error(png_ptr, "zlib failed to initialize compressor");
  194382. png_ptr->zstream.next_out = png_ptr->zbuf;
  194383. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  194384. /* libpng is not interested in zstream.data_type */
  194385. /* set it to a predefined value, to avoid its evaluation inside zlib */
  194386. png_ptr->zstream.data_type = Z_BINARY;
  194387. png_ptr->mode = PNG_HAVE_IHDR;
  194388. }
  194389. /* write the palette. We are careful not to trust png_color to be in the
  194390. * correct order for PNG, so people can redefine it to any convenient
  194391. * structure.
  194392. */
  194393. void /* PRIVATE */
  194394. png_write_PLTE(png_structp png_ptr, png_colorp palette, png_uint_32 num_pal)
  194395. {
  194396. #ifdef PNG_USE_LOCAL_ARRAYS
  194397. PNG_PLTE;
  194398. #endif
  194399. png_uint_32 i;
  194400. png_colorp pal_ptr;
  194401. png_byte buf[3];
  194402. png_debug(1, "in png_write_PLTE\n");
  194403. if ((
  194404. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  194405. !(png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE) &&
  194406. #endif
  194407. num_pal == 0) || num_pal > 256)
  194408. {
  194409. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  194410. {
  194411. png_error(png_ptr, "Invalid number of colors in palette");
  194412. }
  194413. else
  194414. {
  194415. png_warning(png_ptr, "Invalid number of colors in palette");
  194416. return;
  194417. }
  194418. }
  194419. if (!(png_ptr->color_type&PNG_COLOR_MASK_COLOR))
  194420. {
  194421. png_warning(png_ptr,
  194422. "Ignoring request to write a PLTE chunk in grayscale PNG");
  194423. return;
  194424. }
  194425. png_ptr->num_palette = (png_uint_16)num_pal;
  194426. png_debug1(3, "num_palette = %d\n", png_ptr->num_palette);
  194427. png_write_chunk_start(png_ptr, png_PLTE, num_pal * 3);
  194428. #ifndef PNG_NO_POINTER_INDEXING
  194429. for (i = 0, pal_ptr = palette; i < num_pal; i++, pal_ptr++)
  194430. {
  194431. buf[0] = pal_ptr->red;
  194432. buf[1] = pal_ptr->green;
  194433. buf[2] = pal_ptr->blue;
  194434. png_write_chunk_data(png_ptr, buf, (png_size_t)3);
  194435. }
  194436. #else
  194437. /* This is a little slower but some buggy compilers need to do this instead */
  194438. pal_ptr=palette;
  194439. for (i = 0; i < num_pal; i++)
  194440. {
  194441. buf[0] = pal_ptr[i].red;
  194442. buf[1] = pal_ptr[i].green;
  194443. buf[2] = pal_ptr[i].blue;
  194444. png_write_chunk_data(png_ptr, buf, (png_size_t)3);
  194445. }
  194446. #endif
  194447. png_write_chunk_end(png_ptr);
  194448. png_ptr->mode |= PNG_HAVE_PLTE;
  194449. }
  194450. /* write an IDAT chunk */
  194451. void /* PRIVATE */
  194452. png_write_IDAT(png_structp png_ptr, png_bytep data, png_size_t length)
  194453. {
  194454. #ifdef PNG_USE_LOCAL_ARRAYS
  194455. PNG_IDAT;
  194456. #endif
  194457. png_debug(1, "in png_write_IDAT\n");
  194458. /* Optimize the CMF field in the zlib stream. */
  194459. /* This hack of the zlib stream is compliant to the stream specification. */
  194460. if (!(png_ptr->mode & PNG_HAVE_IDAT) &&
  194461. png_ptr->compression_type == PNG_COMPRESSION_TYPE_BASE)
  194462. {
  194463. unsigned int z_cmf = data[0]; /* zlib compression method and flags */
  194464. if ((z_cmf & 0x0f) == 8 && (z_cmf & 0xf0) <= 0x70)
  194465. {
  194466. /* Avoid memory underflows and multiplication overflows. */
  194467. /* The conditions below are practically always satisfied;
  194468. however, they still must be checked. */
  194469. if (length >= 2 &&
  194470. png_ptr->height < 16384 && png_ptr->width < 16384)
  194471. {
  194472. png_uint_32 uncompressed_idat_size = png_ptr->height *
  194473. ((png_ptr->width *
  194474. png_ptr->channels * png_ptr->bit_depth + 15) >> 3);
  194475. unsigned int z_cinfo = z_cmf >> 4;
  194476. unsigned int half_z_window_size = 1 << (z_cinfo + 7);
  194477. while (uncompressed_idat_size <= half_z_window_size &&
  194478. half_z_window_size >= 256)
  194479. {
  194480. z_cinfo--;
  194481. half_z_window_size >>= 1;
  194482. }
  194483. z_cmf = (z_cmf & 0x0f) | (z_cinfo << 4);
  194484. if (data[0] != (png_byte)z_cmf)
  194485. {
  194486. data[0] = (png_byte)z_cmf;
  194487. data[1] &= 0xe0;
  194488. data[1] += (png_byte)(0x1f - ((z_cmf << 8) + data[1]) % 0x1f);
  194489. }
  194490. }
  194491. }
  194492. else
  194493. png_error(png_ptr,
  194494. "Invalid zlib compression method or flags in IDAT");
  194495. }
  194496. png_write_chunk(png_ptr, png_IDAT, data, length);
  194497. png_ptr->mode |= PNG_HAVE_IDAT;
  194498. }
  194499. /* write an IEND chunk */
  194500. void /* PRIVATE */
  194501. png_write_IEND(png_structp png_ptr)
  194502. {
  194503. #ifdef PNG_USE_LOCAL_ARRAYS
  194504. PNG_IEND;
  194505. #endif
  194506. png_debug(1, "in png_write_IEND\n");
  194507. png_write_chunk(png_ptr, png_IEND, png_bytep_NULL,
  194508. (png_size_t)0);
  194509. png_ptr->mode |= PNG_HAVE_IEND;
  194510. }
  194511. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  194512. /* write a gAMA chunk */
  194513. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194514. void /* PRIVATE */
  194515. png_write_gAMA(png_structp png_ptr, double file_gamma)
  194516. {
  194517. #ifdef PNG_USE_LOCAL_ARRAYS
  194518. PNG_gAMA;
  194519. #endif
  194520. png_uint_32 igamma;
  194521. png_byte buf[4];
  194522. png_debug(1, "in png_write_gAMA\n");
  194523. /* file_gamma is saved in 1/100,000ths */
  194524. igamma = (png_uint_32)(file_gamma * 100000.0 + 0.5);
  194525. png_save_uint_32(buf, igamma);
  194526. png_write_chunk(png_ptr, png_gAMA, buf, (png_size_t)4);
  194527. }
  194528. #endif
  194529. #ifdef PNG_FIXED_POINT_SUPPORTED
  194530. void /* PRIVATE */
  194531. png_write_gAMA_fixed(png_structp png_ptr, png_fixed_point file_gamma)
  194532. {
  194533. #ifdef PNG_USE_LOCAL_ARRAYS
  194534. PNG_gAMA;
  194535. #endif
  194536. png_byte buf[4];
  194537. png_debug(1, "in png_write_gAMA\n");
  194538. /* file_gamma is saved in 1/100,000ths */
  194539. png_save_uint_32(buf, (png_uint_32)file_gamma);
  194540. png_write_chunk(png_ptr, png_gAMA, buf, (png_size_t)4);
  194541. }
  194542. #endif
  194543. #endif
  194544. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  194545. /* write a sRGB chunk */
  194546. void /* PRIVATE */
  194547. png_write_sRGB(png_structp png_ptr, int srgb_intent)
  194548. {
  194549. #ifdef PNG_USE_LOCAL_ARRAYS
  194550. PNG_sRGB;
  194551. #endif
  194552. png_byte buf[1];
  194553. png_debug(1, "in png_write_sRGB\n");
  194554. if(srgb_intent >= PNG_sRGB_INTENT_LAST)
  194555. png_warning(png_ptr,
  194556. "Invalid sRGB rendering intent specified");
  194557. buf[0]=(png_byte)srgb_intent;
  194558. png_write_chunk(png_ptr, png_sRGB, buf, (png_size_t)1);
  194559. }
  194560. #endif
  194561. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  194562. /* write an iCCP chunk */
  194563. void /* PRIVATE */
  194564. png_write_iCCP(png_structp png_ptr, png_charp name, int compression_type,
  194565. png_charp profile, int profile_len)
  194566. {
  194567. #ifdef PNG_USE_LOCAL_ARRAYS
  194568. PNG_iCCP;
  194569. #endif
  194570. png_size_t name_len;
  194571. png_charp new_name;
  194572. compression_state comp;
  194573. int embedded_profile_len = 0;
  194574. png_debug(1, "in png_write_iCCP\n");
  194575. comp.num_output_ptr = 0;
  194576. comp.max_output_ptr = 0;
  194577. comp.output_ptr = NULL;
  194578. comp.input = NULL;
  194579. comp.input_len = 0;
  194580. if (name == NULL || (name_len = png_check_keyword(png_ptr, name,
  194581. &new_name)) == 0)
  194582. {
  194583. png_warning(png_ptr, "Empty keyword in iCCP chunk");
  194584. return;
  194585. }
  194586. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  194587. png_warning(png_ptr, "Unknown compression type in iCCP chunk");
  194588. if (profile == NULL)
  194589. profile_len = 0;
  194590. if (profile_len > 3)
  194591. embedded_profile_len =
  194592. ((*( (png_bytep)profile ))<<24) |
  194593. ((*( (png_bytep)profile+1))<<16) |
  194594. ((*( (png_bytep)profile+2))<< 8) |
  194595. ((*( (png_bytep)profile+3)) );
  194596. if (profile_len < embedded_profile_len)
  194597. {
  194598. png_warning(png_ptr,
  194599. "Embedded profile length too large in iCCP chunk");
  194600. return;
  194601. }
  194602. if (profile_len > embedded_profile_len)
  194603. {
  194604. png_warning(png_ptr,
  194605. "Truncating profile to actual length in iCCP chunk");
  194606. profile_len = embedded_profile_len;
  194607. }
  194608. if (profile_len)
  194609. profile_len = png_text_compress(png_ptr, profile, (png_size_t)profile_len,
  194610. PNG_COMPRESSION_TYPE_BASE, &comp);
  194611. /* make sure we include the NULL after the name and the compression type */
  194612. png_write_chunk_start(png_ptr, png_iCCP,
  194613. (png_uint_32)name_len+profile_len+2);
  194614. new_name[name_len+1]=0x00;
  194615. png_write_chunk_data(png_ptr, (png_bytep)new_name, name_len + 2);
  194616. if (profile_len)
  194617. png_write_compressed_data_out(png_ptr, &comp);
  194618. png_write_chunk_end(png_ptr);
  194619. png_free(png_ptr, new_name);
  194620. }
  194621. #endif
  194622. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  194623. /* write a sPLT chunk */
  194624. void /* PRIVATE */
  194625. png_write_sPLT(png_structp png_ptr, png_sPLT_tp spalette)
  194626. {
  194627. #ifdef PNG_USE_LOCAL_ARRAYS
  194628. PNG_sPLT;
  194629. #endif
  194630. png_size_t name_len;
  194631. png_charp new_name;
  194632. png_byte entrybuf[10];
  194633. int entry_size = (spalette->depth == 8 ? 6 : 10);
  194634. int palette_size = entry_size * spalette->nentries;
  194635. png_sPLT_entryp ep;
  194636. #ifdef PNG_NO_POINTER_INDEXING
  194637. int i;
  194638. #endif
  194639. png_debug(1, "in png_write_sPLT\n");
  194640. if (spalette->name == NULL || (name_len = png_check_keyword(png_ptr,
  194641. spalette->name, &new_name))==0)
  194642. {
  194643. png_warning(png_ptr, "Empty keyword in sPLT chunk");
  194644. return;
  194645. }
  194646. /* make sure we include the NULL after the name */
  194647. png_write_chunk_start(png_ptr, png_sPLT,
  194648. (png_uint_32)(name_len + 2 + palette_size));
  194649. png_write_chunk_data(png_ptr, (png_bytep)new_name, name_len + 1);
  194650. png_write_chunk_data(png_ptr, (png_bytep)&spalette->depth, 1);
  194651. /* loop through each palette entry, writing appropriately */
  194652. #ifndef PNG_NO_POINTER_INDEXING
  194653. for (ep = spalette->entries; ep<spalette->entries+spalette->nentries; ep++)
  194654. {
  194655. if (spalette->depth == 8)
  194656. {
  194657. entrybuf[0] = (png_byte)ep->red;
  194658. entrybuf[1] = (png_byte)ep->green;
  194659. entrybuf[2] = (png_byte)ep->blue;
  194660. entrybuf[3] = (png_byte)ep->alpha;
  194661. png_save_uint_16(entrybuf + 4, ep->frequency);
  194662. }
  194663. else
  194664. {
  194665. png_save_uint_16(entrybuf + 0, ep->red);
  194666. png_save_uint_16(entrybuf + 2, ep->green);
  194667. png_save_uint_16(entrybuf + 4, ep->blue);
  194668. png_save_uint_16(entrybuf + 6, ep->alpha);
  194669. png_save_uint_16(entrybuf + 8, ep->frequency);
  194670. }
  194671. png_write_chunk_data(png_ptr, entrybuf, (png_size_t)entry_size);
  194672. }
  194673. #else
  194674. ep=spalette->entries;
  194675. for (i=0; i>spalette->nentries; i++)
  194676. {
  194677. if (spalette->depth == 8)
  194678. {
  194679. entrybuf[0] = (png_byte)ep[i].red;
  194680. entrybuf[1] = (png_byte)ep[i].green;
  194681. entrybuf[2] = (png_byte)ep[i].blue;
  194682. entrybuf[3] = (png_byte)ep[i].alpha;
  194683. png_save_uint_16(entrybuf + 4, ep[i].frequency);
  194684. }
  194685. else
  194686. {
  194687. png_save_uint_16(entrybuf + 0, ep[i].red);
  194688. png_save_uint_16(entrybuf + 2, ep[i].green);
  194689. png_save_uint_16(entrybuf + 4, ep[i].blue);
  194690. png_save_uint_16(entrybuf + 6, ep[i].alpha);
  194691. png_save_uint_16(entrybuf + 8, ep[i].frequency);
  194692. }
  194693. png_write_chunk_data(png_ptr, entrybuf, entry_size);
  194694. }
  194695. #endif
  194696. png_write_chunk_end(png_ptr);
  194697. png_free(png_ptr, new_name);
  194698. }
  194699. #endif
  194700. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  194701. /* write the sBIT chunk */
  194702. void /* PRIVATE */
  194703. png_write_sBIT(png_structp png_ptr, png_color_8p sbit, int color_type)
  194704. {
  194705. #ifdef PNG_USE_LOCAL_ARRAYS
  194706. PNG_sBIT;
  194707. #endif
  194708. png_byte buf[4];
  194709. png_size_t size;
  194710. png_debug(1, "in png_write_sBIT\n");
  194711. /* make sure we don't depend upon the order of PNG_COLOR_8 */
  194712. if (color_type & PNG_COLOR_MASK_COLOR)
  194713. {
  194714. png_byte maxbits;
  194715. maxbits = (png_byte)(color_type==PNG_COLOR_TYPE_PALETTE ? 8 :
  194716. png_ptr->usr_bit_depth);
  194717. if (sbit->red == 0 || sbit->red > maxbits ||
  194718. sbit->green == 0 || sbit->green > maxbits ||
  194719. sbit->blue == 0 || sbit->blue > maxbits)
  194720. {
  194721. png_warning(png_ptr, "Invalid sBIT depth specified");
  194722. return;
  194723. }
  194724. buf[0] = sbit->red;
  194725. buf[1] = sbit->green;
  194726. buf[2] = sbit->blue;
  194727. size = 3;
  194728. }
  194729. else
  194730. {
  194731. if (sbit->gray == 0 || sbit->gray > png_ptr->usr_bit_depth)
  194732. {
  194733. png_warning(png_ptr, "Invalid sBIT depth specified");
  194734. return;
  194735. }
  194736. buf[0] = sbit->gray;
  194737. size = 1;
  194738. }
  194739. if (color_type & PNG_COLOR_MASK_ALPHA)
  194740. {
  194741. if (sbit->alpha == 0 || sbit->alpha > png_ptr->usr_bit_depth)
  194742. {
  194743. png_warning(png_ptr, "Invalid sBIT depth specified");
  194744. return;
  194745. }
  194746. buf[size++] = sbit->alpha;
  194747. }
  194748. png_write_chunk(png_ptr, png_sBIT, buf, size);
  194749. }
  194750. #endif
  194751. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  194752. /* write the cHRM chunk */
  194753. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194754. void /* PRIVATE */
  194755. png_write_cHRM(png_structp png_ptr, double white_x, double white_y,
  194756. double red_x, double red_y, double green_x, double green_y,
  194757. double blue_x, double blue_y)
  194758. {
  194759. #ifdef PNG_USE_LOCAL_ARRAYS
  194760. PNG_cHRM;
  194761. #endif
  194762. png_byte buf[32];
  194763. png_uint_32 itemp;
  194764. png_debug(1, "in png_write_cHRM\n");
  194765. /* each value is saved in 1/100,000ths */
  194766. if (white_x < 0 || white_x > 0.8 || white_y < 0 || white_y > 0.8 ||
  194767. white_x + white_y > 1.0)
  194768. {
  194769. png_warning(png_ptr, "Invalid cHRM white point specified");
  194770. #if !defined(PNG_NO_CONSOLE_IO)
  194771. fprintf(stderr,"white_x=%f, white_y=%f\n",white_x, white_y);
  194772. #endif
  194773. return;
  194774. }
  194775. itemp = (png_uint_32)(white_x * 100000.0 + 0.5);
  194776. png_save_uint_32(buf, itemp);
  194777. itemp = (png_uint_32)(white_y * 100000.0 + 0.5);
  194778. png_save_uint_32(buf + 4, itemp);
  194779. if (red_x < 0 || red_y < 0 || red_x + red_y > 1.0)
  194780. {
  194781. png_warning(png_ptr, "Invalid cHRM red point specified");
  194782. return;
  194783. }
  194784. itemp = (png_uint_32)(red_x * 100000.0 + 0.5);
  194785. png_save_uint_32(buf + 8, itemp);
  194786. itemp = (png_uint_32)(red_y * 100000.0 + 0.5);
  194787. png_save_uint_32(buf + 12, itemp);
  194788. if (green_x < 0 || green_y < 0 || green_x + green_y > 1.0)
  194789. {
  194790. png_warning(png_ptr, "Invalid cHRM green point specified");
  194791. return;
  194792. }
  194793. itemp = (png_uint_32)(green_x * 100000.0 + 0.5);
  194794. png_save_uint_32(buf + 16, itemp);
  194795. itemp = (png_uint_32)(green_y * 100000.0 + 0.5);
  194796. png_save_uint_32(buf + 20, itemp);
  194797. if (blue_x < 0 || blue_y < 0 || blue_x + blue_y > 1.0)
  194798. {
  194799. png_warning(png_ptr, "Invalid cHRM blue point specified");
  194800. return;
  194801. }
  194802. itemp = (png_uint_32)(blue_x * 100000.0 + 0.5);
  194803. png_save_uint_32(buf + 24, itemp);
  194804. itemp = (png_uint_32)(blue_y * 100000.0 + 0.5);
  194805. png_save_uint_32(buf + 28, itemp);
  194806. png_write_chunk(png_ptr, png_cHRM, buf, (png_size_t)32);
  194807. }
  194808. #endif
  194809. #ifdef PNG_FIXED_POINT_SUPPORTED
  194810. void /* PRIVATE */
  194811. png_write_cHRM_fixed(png_structp png_ptr, png_fixed_point white_x,
  194812. png_fixed_point white_y, png_fixed_point red_x, png_fixed_point red_y,
  194813. png_fixed_point green_x, png_fixed_point green_y, png_fixed_point blue_x,
  194814. png_fixed_point blue_y)
  194815. {
  194816. #ifdef PNG_USE_LOCAL_ARRAYS
  194817. PNG_cHRM;
  194818. #endif
  194819. png_byte buf[32];
  194820. png_debug(1, "in png_write_cHRM\n");
  194821. /* each value is saved in 1/100,000ths */
  194822. if (white_x > 80000L || white_y > 80000L || white_x + white_y > 100000L)
  194823. {
  194824. png_warning(png_ptr, "Invalid fixed cHRM white point specified");
  194825. #if !defined(PNG_NO_CONSOLE_IO)
  194826. fprintf(stderr,"white_x=%ld, white_y=%ld\n",white_x, white_y);
  194827. #endif
  194828. return;
  194829. }
  194830. png_save_uint_32(buf, (png_uint_32)white_x);
  194831. png_save_uint_32(buf + 4, (png_uint_32)white_y);
  194832. if (red_x + red_y > 100000L)
  194833. {
  194834. png_warning(png_ptr, "Invalid cHRM fixed red point specified");
  194835. return;
  194836. }
  194837. png_save_uint_32(buf + 8, (png_uint_32)red_x);
  194838. png_save_uint_32(buf + 12, (png_uint_32)red_y);
  194839. if (green_x + green_y > 100000L)
  194840. {
  194841. png_warning(png_ptr, "Invalid fixed cHRM green point specified");
  194842. return;
  194843. }
  194844. png_save_uint_32(buf + 16, (png_uint_32)green_x);
  194845. png_save_uint_32(buf + 20, (png_uint_32)green_y);
  194846. if (blue_x + blue_y > 100000L)
  194847. {
  194848. png_warning(png_ptr, "Invalid fixed cHRM blue point specified");
  194849. return;
  194850. }
  194851. png_save_uint_32(buf + 24, (png_uint_32)blue_x);
  194852. png_save_uint_32(buf + 28, (png_uint_32)blue_y);
  194853. png_write_chunk(png_ptr, png_cHRM, buf, (png_size_t)32);
  194854. }
  194855. #endif
  194856. #endif
  194857. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  194858. /* write the tRNS chunk */
  194859. void /* PRIVATE */
  194860. png_write_tRNS(png_structp png_ptr, png_bytep trans, png_color_16p tran,
  194861. int num_trans, int color_type)
  194862. {
  194863. #ifdef PNG_USE_LOCAL_ARRAYS
  194864. PNG_tRNS;
  194865. #endif
  194866. png_byte buf[6];
  194867. png_debug(1, "in png_write_tRNS\n");
  194868. if (color_type == PNG_COLOR_TYPE_PALETTE)
  194869. {
  194870. if (num_trans <= 0 || num_trans > (int)png_ptr->num_palette)
  194871. {
  194872. png_warning(png_ptr,"Invalid number of transparent colors specified");
  194873. return;
  194874. }
  194875. /* write the chunk out as it is */
  194876. png_write_chunk(png_ptr, png_tRNS, trans, (png_size_t)num_trans);
  194877. }
  194878. else if (color_type == PNG_COLOR_TYPE_GRAY)
  194879. {
  194880. /* one 16 bit value */
  194881. if(tran->gray >= (1 << png_ptr->bit_depth))
  194882. {
  194883. png_warning(png_ptr,
  194884. "Ignoring attempt to write tRNS chunk out-of-range for bit_depth");
  194885. return;
  194886. }
  194887. png_save_uint_16(buf, tran->gray);
  194888. png_write_chunk(png_ptr, png_tRNS, buf, (png_size_t)2);
  194889. }
  194890. else if (color_type == PNG_COLOR_TYPE_RGB)
  194891. {
  194892. /* three 16 bit values */
  194893. png_save_uint_16(buf, tran->red);
  194894. png_save_uint_16(buf + 2, tran->green);
  194895. png_save_uint_16(buf + 4, tran->blue);
  194896. if(png_ptr->bit_depth == 8 && (buf[0] | buf[2] | buf[4]))
  194897. {
  194898. png_warning(png_ptr,
  194899. "Ignoring attempt to write 16-bit tRNS chunk when bit_depth is 8");
  194900. return;
  194901. }
  194902. png_write_chunk(png_ptr, png_tRNS, buf, (png_size_t)6);
  194903. }
  194904. else
  194905. {
  194906. png_warning(png_ptr, "Can't write tRNS with an alpha channel");
  194907. }
  194908. }
  194909. #endif
  194910. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  194911. /* write the background chunk */
  194912. void /* PRIVATE */
  194913. png_write_bKGD(png_structp png_ptr, png_color_16p back, int color_type)
  194914. {
  194915. #ifdef PNG_USE_LOCAL_ARRAYS
  194916. PNG_bKGD;
  194917. #endif
  194918. png_byte buf[6];
  194919. png_debug(1, "in png_write_bKGD\n");
  194920. if (color_type == PNG_COLOR_TYPE_PALETTE)
  194921. {
  194922. if (
  194923. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  194924. (png_ptr->num_palette ||
  194925. (!(png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE))) &&
  194926. #endif
  194927. back->index > png_ptr->num_palette)
  194928. {
  194929. png_warning(png_ptr, "Invalid background palette index");
  194930. return;
  194931. }
  194932. buf[0] = back->index;
  194933. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)1);
  194934. }
  194935. else if (color_type & PNG_COLOR_MASK_COLOR)
  194936. {
  194937. png_save_uint_16(buf, back->red);
  194938. png_save_uint_16(buf + 2, back->green);
  194939. png_save_uint_16(buf + 4, back->blue);
  194940. if(png_ptr->bit_depth == 8 && (buf[0] | buf[2] | buf[4]))
  194941. {
  194942. png_warning(png_ptr,
  194943. "Ignoring attempt to write 16-bit bKGD chunk when bit_depth is 8");
  194944. return;
  194945. }
  194946. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)6);
  194947. }
  194948. else
  194949. {
  194950. if(back->gray >= (1 << png_ptr->bit_depth))
  194951. {
  194952. png_warning(png_ptr,
  194953. "Ignoring attempt to write bKGD chunk out-of-range for bit_depth");
  194954. return;
  194955. }
  194956. png_save_uint_16(buf, back->gray);
  194957. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)2);
  194958. }
  194959. }
  194960. #endif
  194961. #if defined(PNG_WRITE_hIST_SUPPORTED)
  194962. /* write the histogram */
  194963. void /* PRIVATE */
  194964. png_write_hIST(png_structp png_ptr, png_uint_16p hist, int num_hist)
  194965. {
  194966. #ifdef PNG_USE_LOCAL_ARRAYS
  194967. PNG_hIST;
  194968. #endif
  194969. int i;
  194970. png_byte buf[3];
  194971. png_debug(1, "in png_write_hIST\n");
  194972. if (num_hist > (int)png_ptr->num_palette)
  194973. {
  194974. png_debug2(3, "num_hist = %d, num_palette = %d\n", num_hist,
  194975. png_ptr->num_palette);
  194976. png_warning(png_ptr, "Invalid number of histogram entries specified");
  194977. return;
  194978. }
  194979. png_write_chunk_start(png_ptr, png_hIST, (png_uint_32)(num_hist * 2));
  194980. for (i = 0; i < num_hist; i++)
  194981. {
  194982. png_save_uint_16(buf, hist[i]);
  194983. png_write_chunk_data(png_ptr, buf, (png_size_t)2);
  194984. }
  194985. png_write_chunk_end(png_ptr);
  194986. }
  194987. #endif
  194988. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_pCAL_SUPPORTED) || \
  194989. defined(PNG_WRITE_iCCP_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  194990. /* Check that the tEXt or zTXt keyword is valid per PNG 1.0 specification,
  194991. * and if invalid, correct the keyword rather than discarding the entire
  194992. * chunk. The PNG 1.0 specification requires keywords 1-79 characters in
  194993. * length, forbids leading or trailing whitespace, multiple internal spaces,
  194994. * and the non-break space (0x80) from ISO 8859-1. Returns keyword length.
  194995. *
  194996. * The new_key is allocated to hold the corrected keyword and must be freed
  194997. * by the calling routine. This avoids problems with trying to write to
  194998. * static keywords without having to have duplicate copies of the strings.
  194999. */
  195000. png_size_t /* PRIVATE */
  195001. png_check_keyword(png_structp png_ptr, png_charp key, png_charpp new_key)
  195002. {
  195003. png_size_t key_len;
  195004. png_charp kp, dp;
  195005. int kflag;
  195006. int kwarn=0;
  195007. png_debug(1, "in png_check_keyword\n");
  195008. *new_key = NULL;
  195009. if (key == NULL || (key_len = png_strlen(key)) == 0)
  195010. {
  195011. png_warning(png_ptr, "zero length keyword");
  195012. return ((png_size_t)0);
  195013. }
  195014. png_debug1(2, "Keyword to be checked is '%s'\n", key);
  195015. *new_key = (png_charp)png_malloc_warn(png_ptr, (png_uint_32)(key_len + 2));
  195016. if (*new_key == NULL)
  195017. {
  195018. png_warning(png_ptr, "Out of memory while procesing keyword");
  195019. return ((png_size_t)0);
  195020. }
  195021. /* Replace non-printing characters with a blank and print a warning */
  195022. for (kp = key, dp = *new_key; *kp != '\0'; kp++, dp++)
  195023. {
  195024. if ((png_byte)*kp < 0x20 ||
  195025. ((png_byte)*kp > 0x7E && (png_byte)*kp < 0xA1))
  195026. {
  195027. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  195028. char msg[40];
  195029. png_snprintf(msg, 40,
  195030. "invalid keyword character 0x%02X", (png_byte)*kp);
  195031. png_warning(png_ptr, msg);
  195032. #else
  195033. png_warning(png_ptr, "invalid character in keyword");
  195034. #endif
  195035. *dp = ' ';
  195036. }
  195037. else
  195038. {
  195039. *dp = *kp;
  195040. }
  195041. }
  195042. *dp = '\0';
  195043. /* Remove any trailing white space. */
  195044. kp = *new_key + key_len - 1;
  195045. if (*kp == ' ')
  195046. {
  195047. png_warning(png_ptr, "trailing spaces removed from keyword");
  195048. while (*kp == ' ')
  195049. {
  195050. *(kp--) = '\0';
  195051. key_len--;
  195052. }
  195053. }
  195054. /* Remove any leading white space. */
  195055. kp = *new_key;
  195056. if (*kp == ' ')
  195057. {
  195058. png_warning(png_ptr, "leading spaces removed from keyword");
  195059. while (*kp == ' ')
  195060. {
  195061. kp++;
  195062. key_len--;
  195063. }
  195064. }
  195065. png_debug1(2, "Checking for multiple internal spaces in '%s'\n", kp);
  195066. /* Remove multiple internal spaces. */
  195067. for (kflag = 0, dp = *new_key; *kp != '\0'; kp++)
  195068. {
  195069. if (*kp == ' ' && kflag == 0)
  195070. {
  195071. *(dp++) = *kp;
  195072. kflag = 1;
  195073. }
  195074. else if (*kp == ' ')
  195075. {
  195076. key_len--;
  195077. kwarn=1;
  195078. }
  195079. else
  195080. {
  195081. *(dp++) = *kp;
  195082. kflag = 0;
  195083. }
  195084. }
  195085. *dp = '\0';
  195086. if(kwarn)
  195087. png_warning(png_ptr, "extra interior spaces removed from keyword");
  195088. if (key_len == 0)
  195089. {
  195090. png_free(png_ptr, *new_key);
  195091. *new_key=NULL;
  195092. png_warning(png_ptr, "Zero length keyword");
  195093. }
  195094. if (key_len > 79)
  195095. {
  195096. png_warning(png_ptr, "keyword length must be 1 - 79 characters");
  195097. new_key[79] = '\0';
  195098. key_len = 79;
  195099. }
  195100. return (key_len);
  195101. }
  195102. #endif
  195103. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  195104. /* write a tEXt chunk */
  195105. void /* PRIVATE */
  195106. png_write_tEXt(png_structp png_ptr, png_charp key, png_charp text,
  195107. png_size_t text_len)
  195108. {
  195109. #ifdef PNG_USE_LOCAL_ARRAYS
  195110. PNG_tEXt;
  195111. #endif
  195112. png_size_t key_len;
  195113. png_charp new_key;
  195114. png_debug(1, "in png_write_tEXt\n");
  195115. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  195116. {
  195117. png_warning(png_ptr, "Empty keyword in tEXt chunk");
  195118. return;
  195119. }
  195120. if (text == NULL || *text == '\0')
  195121. text_len = 0;
  195122. else
  195123. text_len = png_strlen(text);
  195124. /* make sure we include the 0 after the key */
  195125. png_write_chunk_start(png_ptr, png_tEXt, (png_uint_32)key_len+text_len+1);
  195126. /*
  195127. * We leave it to the application to meet PNG-1.0 requirements on the
  195128. * contents of the text. PNG-1.0 through PNG-1.2 discourage the use of
  195129. * any non-Latin-1 characters except for NEWLINE. ISO PNG will forbid them.
  195130. * The NUL character is forbidden by PNG-1.0 through PNG-1.2 and ISO PNG.
  195131. */
  195132. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  195133. if (text_len)
  195134. png_write_chunk_data(png_ptr, (png_bytep)text, text_len);
  195135. png_write_chunk_end(png_ptr);
  195136. png_free(png_ptr, new_key);
  195137. }
  195138. #endif
  195139. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  195140. /* write a compressed text chunk */
  195141. void /* PRIVATE */
  195142. png_write_zTXt(png_structp png_ptr, png_charp key, png_charp text,
  195143. png_size_t text_len, int compression)
  195144. {
  195145. #ifdef PNG_USE_LOCAL_ARRAYS
  195146. PNG_zTXt;
  195147. #endif
  195148. png_size_t key_len;
  195149. char buf[1];
  195150. png_charp new_key;
  195151. compression_state comp;
  195152. png_debug(1, "in png_write_zTXt\n");
  195153. comp.num_output_ptr = 0;
  195154. comp.max_output_ptr = 0;
  195155. comp.output_ptr = NULL;
  195156. comp.input = NULL;
  195157. comp.input_len = 0;
  195158. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  195159. {
  195160. png_warning(png_ptr, "Empty keyword in zTXt chunk");
  195161. return;
  195162. }
  195163. if (text == NULL || *text == '\0' || compression==PNG_TEXT_COMPRESSION_NONE)
  195164. {
  195165. png_write_tEXt(png_ptr, new_key, text, (png_size_t)0);
  195166. png_free(png_ptr, new_key);
  195167. return;
  195168. }
  195169. text_len = png_strlen(text);
  195170. /* compute the compressed data; do it now for the length */
  195171. text_len = png_text_compress(png_ptr, text, text_len, compression,
  195172. &comp);
  195173. /* write start of chunk */
  195174. png_write_chunk_start(png_ptr, png_zTXt, (png_uint_32)
  195175. (key_len+text_len+2));
  195176. /* write key */
  195177. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  195178. png_free(png_ptr, new_key);
  195179. buf[0] = (png_byte)compression;
  195180. /* write compression */
  195181. png_write_chunk_data(png_ptr, (png_bytep)buf, (png_size_t)1);
  195182. /* write the compressed data */
  195183. png_write_compressed_data_out(png_ptr, &comp);
  195184. /* close the chunk */
  195185. png_write_chunk_end(png_ptr);
  195186. }
  195187. #endif
  195188. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  195189. /* write an iTXt chunk */
  195190. void /* PRIVATE */
  195191. png_write_iTXt(png_structp png_ptr, int compression, png_charp key,
  195192. png_charp lang, png_charp lang_key, png_charp text)
  195193. {
  195194. #ifdef PNG_USE_LOCAL_ARRAYS
  195195. PNG_iTXt;
  195196. #endif
  195197. png_size_t lang_len, key_len, lang_key_len, text_len;
  195198. png_charp new_lang, new_key;
  195199. png_byte cbuf[2];
  195200. compression_state comp;
  195201. png_debug(1, "in png_write_iTXt\n");
  195202. comp.num_output_ptr = 0;
  195203. comp.max_output_ptr = 0;
  195204. comp.output_ptr = NULL;
  195205. comp.input = NULL;
  195206. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  195207. {
  195208. png_warning(png_ptr, "Empty keyword in iTXt chunk");
  195209. return;
  195210. }
  195211. if (lang == NULL || (lang_len = png_check_keyword(png_ptr, lang, &new_lang))==0)
  195212. {
  195213. png_warning(png_ptr, "Empty language field in iTXt chunk");
  195214. new_lang = NULL;
  195215. lang_len = 0;
  195216. }
  195217. if (lang_key == NULL)
  195218. lang_key_len = 0;
  195219. else
  195220. lang_key_len = png_strlen(lang_key);
  195221. if (text == NULL)
  195222. text_len = 0;
  195223. else
  195224. text_len = png_strlen(text);
  195225. /* compute the compressed data; do it now for the length */
  195226. text_len = png_text_compress(png_ptr, text, text_len, compression-2,
  195227. &comp);
  195228. /* make sure we include the compression flag, the compression byte,
  195229. * and the NULs after the key, lang, and lang_key parts */
  195230. png_write_chunk_start(png_ptr, png_iTXt,
  195231. (png_uint_32)(
  195232. 5 /* comp byte, comp flag, terminators for key, lang and lang_key */
  195233. + key_len
  195234. + lang_len
  195235. + lang_key_len
  195236. + text_len));
  195237. /*
  195238. * We leave it to the application to meet PNG-1.0 requirements on the
  195239. * contents of the text. PNG-1.0 through PNG-1.2 discourage the use of
  195240. * any non-Latin-1 characters except for NEWLINE. ISO PNG will forbid them.
  195241. * The NUL character is forbidden by PNG-1.0 through PNG-1.2 and ISO PNG.
  195242. */
  195243. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  195244. /* set the compression flag */
  195245. if (compression == PNG_ITXT_COMPRESSION_NONE || \
  195246. compression == PNG_TEXT_COMPRESSION_NONE)
  195247. cbuf[0] = 0;
  195248. else /* compression == PNG_ITXT_COMPRESSION_zTXt */
  195249. cbuf[0] = 1;
  195250. /* set the compression method */
  195251. cbuf[1] = 0;
  195252. png_write_chunk_data(png_ptr, cbuf, 2);
  195253. cbuf[0] = 0;
  195254. png_write_chunk_data(png_ptr, (new_lang ? (png_bytep)new_lang : cbuf), lang_len + 1);
  195255. png_write_chunk_data(png_ptr, (lang_key ? (png_bytep)lang_key : cbuf), lang_key_len + 1);
  195256. png_write_compressed_data_out(png_ptr, &comp);
  195257. png_write_chunk_end(png_ptr);
  195258. png_free(png_ptr, new_key);
  195259. if (new_lang)
  195260. png_free(png_ptr, new_lang);
  195261. }
  195262. #endif
  195263. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  195264. /* write the oFFs chunk */
  195265. void /* PRIVATE */
  195266. png_write_oFFs(png_structp png_ptr, png_int_32 x_offset, png_int_32 y_offset,
  195267. int unit_type)
  195268. {
  195269. #ifdef PNG_USE_LOCAL_ARRAYS
  195270. PNG_oFFs;
  195271. #endif
  195272. png_byte buf[9];
  195273. png_debug(1, "in png_write_oFFs\n");
  195274. if (unit_type >= PNG_OFFSET_LAST)
  195275. png_warning(png_ptr, "Unrecognized unit type for oFFs chunk");
  195276. png_save_int_32(buf, x_offset);
  195277. png_save_int_32(buf + 4, y_offset);
  195278. buf[8] = (png_byte)unit_type;
  195279. png_write_chunk(png_ptr, png_oFFs, buf, (png_size_t)9);
  195280. }
  195281. #endif
  195282. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  195283. /* write the pCAL chunk (described in the PNG extensions document) */
  195284. void /* PRIVATE */
  195285. png_write_pCAL(png_structp png_ptr, png_charp purpose, png_int_32 X0,
  195286. png_int_32 X1, int type, int nparams, png_charp units, png_charpp params)
  195287. {
  195288. #ifdef PNG_USE_LOCAL_ARRAYS
  195289. PNG_pCAL;
  195290. #endif
  195291. png_size_t purpose_len, units_len, total_len;
  195292. png_uint_32p params_len;
  195293. png_byte buf[10];
  195294. png_charp new_purpose;
  195295. int i;
  195296. png_debug1(1, "in png_write_pCAL (%d parameters)\n", nparams);
  195297. if (type >= PNG_EQUATION_LAST)
  195298. png_warning(png_ptr, "Unrecognized equation type for pCAL chunk");
  195299. purpose_len = png_check_keyword(png_ptr, purpose, &new_purpose) + 1;
  195300. png_debug1(3, "pCAL purpose length = %d\n", (int)purpose_len);
  195301. units_len = png_strlen(units) + (nparams == 0 ? 0 : 1);
  195302. png_debug1(3, "pCAL units length = %d\n", (int)units_len);
  195303. total_len = purpose_len + units_len + 10;
  195304. params_len = (png_uint_32p)png_malloc(png_ptr, (png_uint_32)(nparams
  195305. *png_sizeof(png_uint_32)));
  195306. /* Find the length of each parameter, making sure we don't count the
  195307. null terminator for the last parameter. */
  195308. for (i = 0; i < nparams; i++)
  195309. {
  195310. params_len[i] = png_strlen(params[i]) + (i == nparams - 1 ? 0 : 1);
  195311. png_debug2(3, "pCAL parameter %d length = %lu\n", i, params_len[i]);
  195312. total_len += (png_size_t)params_len[i];
  195313. }
  195314. png_debug1(3, "pCAL total length = %d\n", (int)total_len);
  195315. png_write_chunk_start(png_ptr, png_pCAL, (png_uint_32)total_len);
  195316. png_write_chunk_data(png_ptr, (png_bytep)new_purpose, purpose_len);
  195317. png_save_int_32(buf, X0);
  195318. png_save_int_32(buf + 4, X1);
  195319. buf[8] = (png_byte)type;
  195320. buf[9] = (png_byte)nparams;
  195321. png_write_chunk_data(png_ptr, buf, (png_size_t)10);
  195322. png_write_chunk_data(png_ptr, (png_bytep)units, (png_size_t)units_len);
  195323. png_free(png_ptr, new_purpose);
  195324. for (i = 0; i < nparams; i++)
  195325. {
  195326. png_write_chunk_data(png_ptr, (png_bytep)params[i],
  195327. (png_size_t)params_len[i]);
  195328. }
  195329. png_free(png_ptr, params_len);
  195330. png_write_chunk_end(png_ptr);
  195331. }
  195332. #endif
  195333. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  195334. /* write the sCAL chunk */
  195335. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  195336. void /* PRIVATE */
  195337. png_write_sCAL(png_structp png_ptr, int unit, double width, double height)
  195338. {
  195339. #ifdef PNG_USE_LOCAL_ARRAYS
  195340. PNG_sCAL;
  195341. #endif
  195342. char buf[64];
  195343. png_size_t total_len;
  195344. png_debug(1, "in png_write_sCAL\n");
  195345. buf[0] = (char)unit;
  195346. #if defined(_WIN32_WCE)
  195347. /* sprintf() function is not supported on WindowsCE */
  195348. {
  195349. wchar_t wc_buf[32];
  195350. size_t wc_len;
  195351. swprintf(wc_buf, TEXT("%12.12e"), width);
  195352. wc_len = wcslen(wc_buf);
  195353. WideCharToMultiByte(CP_ACP, 0, wc_buf, -1, buf + 1, wc_len, NULL, NULL);
  195354. total_len = wc_len + 2;
  195355. swprintf(wc_buf, TEXT("%12.12e"), height);
  195356. wc_len = wcslen(wc_buf);
  195357. WideCharToMultiByte(CP_ACP, 0, wc_buf, -1, buf + total_len, wc_len,
  195358. NULL, NULL);
  195359. total_len += wc_len;
  195360. }
  195361. #else
  195362. png_snprintf(buf + 1, 63, "%12.12e", width);
  195363. total_len = 1 + png_strlen(buf + 1) + 1;
  195364. png_snprintf(buf + total_len, 64-total_len, "%12.12e", height);
  195365. total_len += png_strlen(buf + total_len);
  195366. #endif
  195367. png_debug1(3, "sCAL total length = %u\n", (unsigned int)total_len);
  195368. png_write_chunk(png_ptr, png_sCAL, (png_bytep)buf, total_len);
  195369. }
  195370. #else
  195371. #ifdef PNG_FIXED_POINT_SUPPORTED
  195372. void /* PRIVATE */
  195373. png_write_sCAL_s(png_structp png_ptr, int unit, png_charp width,
  195374. png_charp height)
  195375. {
  195376. #ifdef PNG_USE_LOCAL_ARRAYS
  195377. PNG_sCAL;
  195378. #endif
  195379. png_byte buf[64];
  195380. png_size_t wlen, hlen, total_len;
  195381. png_debug(1, "in png_write_sCAL_s\n");
  195382. wlen = png_strlen(width);
  195383. hlen = png_strlen(height);
  195384. total_len = wlen + hlen + 2;
  195385. if (total_len > 64)
  195386. {
  195387. png_warning(png_ptr, "Can't write sCAL (buffer too small)");
  195388. return;
  195389. }
  195390. buf[0] = (png_byte)unit;
  195391. png_memcpy(buf + 1, width, wlen + 1); /* append the '\0' here */
  195392. png_memcpy(buf + wlen + 2, height, hlen); /* do NOT append the '\0' here */
  195393. png_debug1(3, "sCAL total length = %u\n", (unsigned int)total_len);
  195394. png_write_chunk(png_ptr, png_sCAL, buf, total_len);
  195395. }
  195396. #endif
  195397. #endif
  195398. #endif
  195399. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  195400. /* write the pHYs chunk */
  195401. void /* PRIVATE */
  195402. png_write_pHYs(png_structp png_ptr, png_uint_32 x_pixels_per_unit,
  195403. png_uint_32 y_pixels_per_unit,
  195404. int unit_type)
  195405. {
  195406. #ifdef PNG_USE_LOCAL_ARRAYS
  195407. PNG_pHYs;
  195408. #endif
  195409. png_byte buf[9];
  195410. png_debug(1, "in png_write_pHYs\n");
  195411. if (unit_type >= PNG_RESOLUTION_LAST)
  195412. png_warning(png_ptr, "Unrecognized unit type for pHYs chunk");
  195413. png_save_uint_32(buf, x_pixels_per_unit);
  195414. png_save_uint_32(buf + 4, y_pixels_per_unit);
  195415. buf[8] = (png_byte)unit_type;
  195416. png_write_chunk(png_ptr, png_pHYs, buf, (png_size_t)9);
  195417. }
  195418. #endif
  195419. #if defined(PNG_WRITE_tIME_SUPPORTED)
  195420. /* Write the tIME chunk. Use either png_convert_from_struct_tm()
  195421. * or png_convert_from_time_t(), or fill in the structure yourself.
  195422. */
  195423. void /* PRIVATE */
  195424. png_write_tIME(png_structp png_ptr, png_timep mod_time)
  195425. {
  195426. #ifdef PNG_USE_LOCAL_ARRAYS
  195427. PNG_tIME;
  195428. #endif
  195429. png_byte buf[7];
  195430. png_debug(1, "in png_write_tIME\n");
  195431. if (mod_time->month > 12 || mod_time->month < 1 ||
  195432. mod_time->day > 31 || mod_time->day < 1 ||
  195433. mod_time->hour > 23 || mod_time->second > 60)
  195434. {
  195435. png_warning(png_ptr, "Invalid time specified for tIME chunk");
  195436. return;
  195437. }
  195438. png_save_uint_16(buf, mod_time->year);
  195439. buf[2] = mod_time->month;
  195440. buf[3] = mod_time->day;
  195441. buf[4] = mod_time->hour;
  195442. buf[5] = mod_time->minute;
  195443. buf[6] = mod_time->second;
  195444. png_write_chunk(png_ptr, png_tIME, buf, (png_size_t)7);
  195445. }
  195446. #endif
  195447. /* initializes the row writing capability of libpng */
  195448. void /* PRIVATE */
  195449. png_write_start_row(png_structp png_ptr)
  195450. {
  195451. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  195452. #ifdef PNG_USE_LOCAL_ARRAYS
  195453. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  195454. /* start of interlace block */
  195455. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  195456. /* offset to next interlace block */
  195457. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  195458. /* start of interlace block in the y direction */
  195459. int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  195460. /* offset to next interlace block in the y direction */
  195461. int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  195462. #endif
  195463. #endif
  195464. png_size_t buf_size;
  195465. png_debug(1, "in png_write_start_row\n");
  195466. buf_size = (png_size_t)(PNG_ROWBYTES(
  195467. png_ptr->usr_channels*png_ptr->usr_bit_depth,png_ptr->width)+1);
  195468. /* set up row buffer */
  195469. png_ptr->row_buf = (png_bytep)png_malloc(png_ptr, (png_uint_32)buf_size);
  195470. png_ptr->row_buf[0] = PNG_FILTER_VALUE_NONE;
  195471. #ifndef PNG_NO_WRITE_FILTERING
  195472. /* set up filtering buffer, if using this filter */
  195473. if (png_ptr->do_filter & PNG_FILTER_SUB)
  195474. {
  195475. png_ptr->sub_row = (png_bytep)png_malloc(png_ptr,
  195476. (png_ptr->rowbytes + 1));
  195477. png_ptr->sub_row[0] = PNG_FILTER_VALUE_SUB;
  195478. }
  195479. /* We only need to keep the previous row if we are using one of these. */
  195480. if (png_ptr->do_filter & (PNG_FILTER_AVG | PNG_FILTER_UP | PNG_FILTER_PAETH))
  195481. {
  195482. /* set up previous row buffer */
  195483. png_ptr->prev_row = (png_bytep)png_malloc(png_ptr, (png_uint_32)buf_size);
  195484. png_memset(png_ptr->prev_row, 0, buf_size);
  195485. if (png_ptr->do_filter & PNG_FILTER_UP)
  195486. {
  195487. png_ptr->up_row = (png_bytep)png_malloc(png_ptr,
  195488. (png_ptr->rowbytes + 1));
  195489. png_ptr->up_row[0] = PNG_FILTER_VALUE_UP;
  195490. }
  195491. if (png_ptr->do_filter & PNG_FILTER_AVG)
  195492. {
  195493. png_ptr->avg_row = (png_bytep)png_malloc(png_ptr,
  195494. (png_ptr->rowbytes + 1));
  195495. png_ptr->avg_row[0] = PNG_FILTER_VALUE_AVG;
  195496. }
  195497. if (png_ptr->do_filter & PNG_FILTER_PAETH)
  195498. {
  195499. png_ptr->paeth_row = (png_bytep)png_malloc(png_ptr,
  195500. (png_ptr->rowbytes + 1));
  195501. png_ptr->paeth_row[0] = PNG_FILTER_VALUE_PAETH;
  195502. }
  195503. #endif /* PNG_NO_WRITE_FILTERING */
  195504. }
  195505. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  195506. /* if interlaced, we need to set up width and height of pass */
  195507. if (png_ptr->interlaced)
  195508. {
  195509. if (!(png_ptr->transformations & PNG_INTERLACE))
  195510. {
  195511. png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 -
  195512. png_pass_ystart[0]) / png_pass_yinc[0];
  195513. png_ptr->usr_width = (png_ptr->width + png_pass_inc[0] - 1 -
  195514. png_pass_start[0]) / png_pass_inc[0];
  195515. }
  195516. else
  195517. {
  195518. png_ptr->num_rows = png_ptr->height;
  195519. png_ptr->usr_width = png_ptr->width;
  195520. }
  195521. }
  195522. else
  195523. #endif
  195524. {
  195525. png_ptr->num_rows = png_ptr->height;
  195526. png_ptr->usr_width = png_ptr->width;
  195527. }
  195528. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  195529. png_ptr->zstream.next_out = png_ptr->zbuf;
  195530. }
  195531. /* Internal use only. Called when finished processing a row of data. */
  195532. void /* PRIVATE */
  195533. png_write_finish_row(png_structp png_ptr)
  195534. {
  195535. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  195536. #ifdef PNG_USE_LOCAL_ARRAYS
  195537. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  195538. /* start of interlace block */
  195539. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  195540. /* offset to next interlace block */
  195541. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  195542. /* start of interlace block in the y direction */
  195543. int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  195544. /* offset to next interlace block in the y direction */
  195545. int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  195546. #endif
  195547. #endif
  195548. int ret;
  195549. png_debug(1, "in png_write_finish_row\n");
  195550. /* next row */
  195551. png_ptr->row_number++;
  195552. /* see if we are done */
  195553. if (png_ptr->row_number < png_ptr->num_rows)
  195554. return;
  195555. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  195556. /* if interlaced, go to next pass */
  195557. if (png_ptr->interlaced)
  195558. {
  195559. png_ptr->row_number = 0;
  195560. if (png_ptr->transformations & PNG_INTERLACE)
  195561. {
  195562. png_ptr->pass++;
  195563. }
  195564. else
  195565. {
  195566. /* loop until we find a non-zero width or height pass */
  195567. do
  195568. {
  195569. png_ptr->pass++;
  195570. if (png_ptr->pass >= 7)
  195571. break;
  195572. png_ptr->usr_width = (png_ptr->width +
  195573. png_pass_inc[png_ptr->pass] - 1 -
  195574. png_pass_start[png_ptr->pass]) /
  195575. png_pass_inc[png_ptr->pass];
  195576. png_ptr->num_rows = (png_ptr->height +
  195577. png_pass_yinc[png_ptr->pass] - 1 -
  195578. png_pass_ystart[png_ptr->pass]) /
  195579. png_pass_yinc[png_ptr->pass];
  195580. if (png_ptr->transformations & PNG_INTERLACE)
  195581. break;
  195582. } while (png_ptr->usr_width == 0 || png_ptr->num_rows == 0);
  195583. }
  195584. /* reset the row above the image for the next pass */
  195585. if (png_ptr->pass < 7)
  195586. {
  195587. if (png_ptr->prev_row != NULL)
  195588. png_memset(png_ptr->prev_row, 0,
  195589. (png_size_t)(PNG_ROWBYTES(png_ptr->usr_channels*
  195590. png_ptr->usr_bit_depth,png_ptr->width))+1);
  195591. return;
  195592. }
  195593. }
  195594. #endif
  195595. /* if we get here, we've just written the last row, so we need
  195596. to flush the compressor */
  195597. do
  195598. {
  195599. /* tell the compressor we are done */
  195600. ret = deflate(&png_ptr->zstream, Z_FINISH);
  195601. /* check for an error */
  195602. if (ret == Z_OK)
  195603. {
  195604. /* check to see if we need more room */
  195605. if (!(png_ptr->zstream.avail_out))
  195606. {
  195607. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  195608. png_ptr->zstream.next_out = png_ptr->zbuf;
  195609. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  195610. }
  195611. }
  195612. else if (ret != Z_STREAM_END)
  195613. {
  195614. if (png_ptr->zstream.msg != NULL)
  195615. png_error(png_ptr, png_ptr->zstream.msg);
  195616. else
  195617. png_error(png_ptr, "zlib error");
  195618. }
  195619. } while (ret != Z_STREAM_END);
  195620. /* write any extra space */
  195621. if (png_ptr->zstream.avail_out < png_ptr->zbuf_size)
  195622. {
  195623. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size -
  195624. png_ptr->zstream.avail_out);
  195625. }
  195626. deflateReset(&png_ptr->zstream);
  195627. png_ptr->zstream.data_type = Z_BINARY;
  195628. }
  195629. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  195630. /* Pick out the correct pixels for the interlace pass.
  195631. * The basic idea here is to go through the row with a source
  195632. * pointer and a destination pointer (sp and dp), and copy the
  195633. * correct pixels for the pass. As the row gets compacted,
  195634. * sp will always be >= dp, so we should never overwrite anything.
  195635. * See the default: case for the easiest code to understand.
  195636. */
  195637. void /* PRIVATE */
  195638. png_do_write_interlace(png_row_infop row_info, png_bytep row, int pass)
  195639. {
  195640. #ifdef PNG_USE_LOCAL_ARRAYS
  195641. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  195642. /* start of interlace block */
  195643. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  195644. /* offset to next interlace block */
  195645. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  195646. #endif
  195647. png_debug(1, "in png_do_write_interlace\n");
  195648. /* we don't have to do anything on the last pass (6) */
  195649. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  195650. if (row != NULL && row_info != NULL && pass < 6)
  195651. #else
  195652. if (pass < 6)
  195653. #endif
  195654. {
  195655. /* each pixel depth is handled separately */
  195656. switch (row_info->pixel_depth)
  195657. {
  195658. case 1:
  195659. {
  195660. png_bytep sp;
  195661. png_bytep dp;
  195662. int shift;
  195663. int d;
  195664. int value;
  195665. png_uint_32 i;
  195666. png_uint_32 row_width = row_info->width;
  195667. dp = row;
  195668. d = 0;
  195669. shift = 7;
  195670. for (i = png_pass_start[pass]; i < row_width;
  195671. i += png_pass_inc[pass])
  195672. {
  195673. sp = row + (png_size_t)(i >> 3);
  195674. value = (int)(*sp >> (7 - (int)(i & 0x07))) & 0x01;
  195675. d |= (value << shift);
  195676. if (shift == 0)
  195677. {
  195678. shift = 7;
  195679. *dp++ = (png_byte)d;
  195680. d = 0;
  195681. }
  195682. else
  195683. shift--;
  195684. }
  195685. if (shift != 7)
  195686. *dp = (png_byte)d;
  195687. break;
  195688. }
  195689. case 2:
  195690. {
  195691. png_bytep sp;
  195692. png_bytep dp;
  195693. int shift;
  195694. int d;
  195695. int value;
  195696. png_uint_32 i;
  195697. png_uint_32 row_width = row_info->width;
  195698. dp = row;
  195699. shift = 6;
  195700. d = 0;
  195701. for (i = png_pass_start[pass]; i < row_width;
  195702. i += png_pass_inc[pass])
  195703. {
  195704. sp = row + (png_size_t)(i >> 2);
  195705. value = (*sp >> ((3 - (int)(i & 0x03)) << 1)) & 0x03;
  195706. d |= (value << shift);
  195707. if (shift == 0)
  195708. {
  195709. shift = 6;
  195710. *dp++ = (png_byte)d;
  195711. d = 0;
  195712. }
  195713. else
  195714. shift -= 2;
  195715. }
  195716. if (shift != 6)
  195717. *dp = (png_byte)d;
  195718. break;
  195719. }
  195720. case 4:
  195721. {
  195722. png_bytep sp;
  195723. png_bytep dp;
  195724. int shift;
  195725. int d;
  195726. int value;
  195727. png_uint_32 i;
  195728. png_uint_32 row_width = row_info->width;
  195729. dp = row;
  195730. shift = 4;
  195731. d = 0;
  195732. for (i = png_pass_start[pass]; i < row_width;
  195733. i += png_pass_inc[pass])
  195734. {
  195735. sp = row + (png_size_t)(i >> 1);
  195736. value = (*sp >> ((1 - (int)(i & 0x01)) << 2)) & 0x0f;
  195737. d |= (value << shift);
  195738. if (shift == 0)
  195739. {
  195740. shift = 4;
  195741. *dp++ = (png_byte)d;
  195742. d = 0;
  195743. }
  195744. else
  195745. shift -= 4;
  195746. }
  195747. if (shift != 4)
  195748. *dp = (png_byte)d;
  195749. break;
  195750. }
  195751. default:
  195752. {
  195753. png_bytep sp;
  195754. png_bytep dp;
  195755. png_uint_32 i;
  195756. png_uint_32 row_width = row_info->width;
  195757. png_size_t pixel_bytes;
  195758. /* start at the beginning */
  195759. dp = row;
  195760. /* find out how many bytes each pixel takes up */
  195761. pixel_bytes = (row_info->pixel_depth >> 3);
  195762. /* loop through the row, only looking at the pixels that
  195763. matter */
  195764. for (i = png_pass_start[pass]; i < row_width;
  195765. i += png_pass_inc[pass])
  195766. {
  195767. /* find out where the original pixel is */
  195768. sp = row + (png_size_t)i * pixel_bytes;
  195769. /* move the pixel */
  195770. if (dp != sp)
  195771. png_memcpy(dp, sp, pixel_bytes);
  195772. /* next pixel */
  195773. dp += pixel_bytes;
  195774. }
  195775. break;
  195776. }
  195777. }
  195778. /* set new row width */
  195779. row_info->width = (row_info->width +
  195780. png_pass_inc[pass] - 1 -
  195781. png_pass_start[pass]) /
  195782. png_pass_inc[pass];
  195783. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  195784. row_info->width);
  195785. }
  195786. }
  195787. #endif
  195788. /* This filters the row, chooses which filter to use, if it has not already
  195789. * been specified by the application, and then writes the row out with the
  195790. * chosen filter.
  195791. */
  195792. #define PNG_MAXSUM (((png_uint_32)(-1)) >> 1)
  195793. #define PNG_HISHIFT 10
  195794. #define PNG_LOMASK ((png_uint_32)0xffffL)
  195795. #define PNG_HIMASK ((png_uint_32)(~PNG_LOMASK >> PNG_HISHIFT))
  195796. void /* PRIVATE */
  195797. png_write_find_filter(png_structp png_ptr, png_row_infop row_info)
  195798. {
  195799. png_bytep best_row;
  195800. #ifndef PNG_NO_WRITE_FILTER
  195801. png_bytep prev_row, row_buf;
  195802. png_uint_32 mins, bpp;
  195803. png_byte filter_to_do = png_ptr->do_filter;
  195804. png_uint_32 row_bytes = row_info->rowbytes;
  195805. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  195806. int num_p_filters = (int)png_ptr->num_prev_filters;
  195807. #endif
  195808. png_debug(1, "in png_write_find_filter\n");
  195809. /* find out how many bytes offset each pixel is */
  195810. bpp = (row_info->pixel_depth + 7) >> 3;
  195811. prev_row = png_ptr->prev_row;
  195812. #endif
  195813. best_row = png_ptr->row_buf;
  195814. #ifndef PNG_NO_WRITE_FILTER
  195815. row_buf = best_row;
  195816. mins = PNG_MAXSUM;
  195817. /* The prediction method we use is to find which method provides the
  195818. * smallest value when summing the absolute values of the distances
  195819. * from zero, using anything >= 128 as negative numbers. This is known
  195820. * as the "minimum sum of absolute differences" heuristic. Other
  195821. * heuristics are the "weighted minimum sum of absolute differences"
  195822. * (experimental and can in theory improve compression), and the "zlib
  195823. * predictive" method (not implemented yet), which does test compressions
  195824. * of lines using different filter methods, and then chooses the
  195825. * (series of) filter(s) that give minimum compressed data size (VERY
  195826. * computationally expensive).
  195827. *
  195828. * GRR 980525: consider also
  195829. * (1) minimum sum of absolute differences from running average (i.e.,
  195830. * keep running sum of non-absolute differences & count of bytes)
  195831. * [track dispersion, too? restart average if dispersion too large?]
  195832. * (1b) minimum sum of absolute differences from sliding average, probably
  195833. * with window size <= deflate window (usually 32K)
  195834. * (2) minimum sum of squared differences from zero or running average
  195835. * (i.e., ~ root-mean-square approach)
  195836. */
  195837. /* We don't need to test the 'no filter' case if this is the only filter
  195838. * that has been chosen, as it doesn't actually do anything to the data.
  195839. */
  195840. if ((filter_to_do & PNG_FILTER_NONE) &&
  195841. filter_to_do != PNG_FILTER_NONE)
  195842. {
  195843. png_bytep rp;
  195844. png_uint_32 sum = 0;
  195845. png_uint_32 i;
  195846. int v;
  195847. for (i = 0, rp = row_buf + 1; i < row_bytes; i++, rp++)
  195848. {
  195849. v = *rp;
  195850. sum += (v < 128) ? v : 256 - v;
  195851. }
  195852. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  195853. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  195854. {
  195855. png_uint_32 sumhi, sumlo;
  195856. int j;
  195857. sumlo = sum & PNG_LOMASK;
  195858. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK; /* Gives us some footroom */
  195859. /* Reduce the sum if we match any of the previous rows */
  195860. for (j = 0; j < num_p_filters; j++)
  195861. {
  195862. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_NONE)
  195863. {
  195864. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  195865. PNG_WEIGHT_SHIFT;
  195866. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  195867. PNG_WEIGHT_SHIFT;
  195868. }
  195869. }
  195870. /* Factor in the cost of this filter (this is here for completeness,
  195871. * but it makes no sense to have a "cost" for the NONE filter, as
  195872. * it has the minimum possible computational cost - none).
  195873. */
  195874. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_NONE]) >>
  195875. PNG_COST_SHIFT;
  195876. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_NONE]) >>
  195877. PNG_COST_SHIFT;
  195878. if (sumhi > PNG_HIMASK)
  195879. sum = PNG_MAXSUM;
  195880. else
  195881. sum = (sumhi << PNG_HISHIFT) + sumlo;
  195882. }
  195883. #endif
  195884. mins = sum;
  195885. }
  195886. /* sub filter */
  195887. if (filter_to_do == PNG_FILTER_SUB)
  195888. /* it's the only filter so no testing is needed */
  195889. {
  195890. png_bytep rp, lp, dp;
  195891. png_uint_32 i;
  195892. for (i = 0, rp = row_buf + 1, dp = png_ptr->sub_row + 1; i < bpp;
  195893. i++, rp++, dp++)
  195894. {
  195895. *dp = *rp;
  195896. }
  195897. for (lp = row_buf + 1; i < row_bytes;
  195898. i++, rp++, lp++, dp++)
  195899. {
  195900. *dp = (png_byte)(((int)*rp - (int)*lp) & 0xff);
  195901. }
  195902. best_row = png_ptr->sub_row;
  195903. }
  195904. else if (filter_to_do & PNG_FILTER_SUB)
  195905. {
  195906. png_bytep rp, dp, lp;
  195907. png_uint_32 sum = 0, lmins = mins;
  195908. png_uint_32 i;
  195909. int v;
  195910. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  195911. /* We temporarily increase the "minimum sum" by the factor we
  195912. * would reduce the sum of this filter, so that we can do the
  195913. * early exit comparison without scaling the sum each time.
  195914. */
  195915. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  195916. {
  195917. int j;
  195918. png_uint_32 lmhi, lmlo;
  195919. lmlo = lmins & PNG_LOMASK;
  195920. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  195921. for (j = 0; j < num_p_filters; j++)
  195922. {
  195923. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_SUB)
  195924. {
  195925. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  195926. PNG_WEIGHT_SHIFT;
  195927. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  195928. PNG_WEIGHT_SHIFT;
  195929. }
  195930. }
  195931. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  195932. PNG_COST_SHIFT;
  195933. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  195934. PNG_COST_SHIFT;
  195935. if (lmhi > PNG_HIMASK)
  195936. lmins = PNG_MAXSUM;
  195937. else
  195938. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  195939. }
  195940. #endif
  195941. for (i = 0, rp = row_buf + 1, dp = png_ptr->sub_row + 1; i < bpp;
  195942. i++, rp++, dp++)
  195943. {
  195944. v = *dp = *rp;
  195945. sum += (v < 128) ? v : 256 - v;
  195946. }
  195947. for (lp = row_buf + 1; i < row_bytes;
  195948. i++, rp++, lp++, dp++)
  195949. {
  195950. v = *dp = (png_byte)(((int)*rp - (int)*lp) & 0xff);
  195951. sum += (v < 128) ? v : 256 - v;
  195952. if (sum > lmins) /* We are already worse, don't continue. */
  195953. break;
  195954. }
  195955. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  195956. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  195957. {
  195958. int j;
  195959. png_uint_32 sumhi, sumlo;
  195960. sumlo = sum & PNG_LOMASK;
  195961. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  195962. for (j = 0; j < num_p_filters; j++)
  195963. {
  195964. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_SUB)
  195965. {
  195966. sumlo = (sumlo * png_ptr->inv_filter_weights[j]) >>
  195967. PNG_WEIGHT_SHIFT;
  195968. sumhi = (sumhi * png_ptr->inv_filter_weights[j]) >>
  195969. PNG_WEIGHT_SHIFT;
  195970. }
  195971. }
  195972. sumlo = (sumlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  195973. PNG_COST_SHIFT;
  195974. sumhi = (sumhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  195975. PNG_COST_SHIFT;
  195976. if (sumhi > PNG_HIMASK)
  195977. sum = PNG_MAXSUM;
  195978. else
  195979. sum = (sumhi << PNG_HISHIFT) + sumlo;
  195980. }
  195981. #endif
  195982. if (sum < mins)
  195983. {
  195984. mins = sum;
  195985. best_row = png_ptr->sub_row;
  195986. }
  195987. }
  195988. /* up filter */
  195989. if (filter_to_do == PNG_FILTER_UP)
  195990. {
  195991. png_bytep rp, dp, pp;
  195992. png_uint_32 i;
  195993. for (i = 0, rp = row_buf + 1, dp = png_ptr->up_row + 1,
  195994. pp = prev_row + 1; i < row_bytes;
  195995. i++, rp++, pp++, dp++)
  195996. {
  195997. *dp = (png_byte)(((int)*rp - (int)*pp) & 0xff);
  195998. }
  195999. best_row = png_ptr->up_row;
  196000. }
  196001. else if (filter_to_do & PNG_FILTER_UP)
  196002. {
  196003. png_bytep rp, dp, pp;
  196004. png_uint_32 sum = 0, lmins = mins;
  196005. png_uint_32 i;
  196006. int v;
  196007. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  196008. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  196009. {
  196010. int j;
  196011. png_uint_32 lmhi, lmlo;
  196012. lmlo = lmins & PNG_LOMASK;
  196013. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  196014. for (j = 0; j < num_p_filters; j++)
  196015. {
  196016. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_UP)
  196017. {
  196018. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  196019. PNG_WEIGHT_SHIFT;
  196020. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  196021. PNG_WEIGHT_SHIFT;
  196022. }
  196023. }
  196024. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_UP]) >>
  196025. PNG_COST_SHIFT;
  196026. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_UP]) >>
  196027. PNG_COST_SHIFT;
  196028. if (lmhi > PNG_HIMASK)
  196029. lmins = PNG_MAXSUM;
  196030. else
  196031. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  196032. }
  196033. #endif
  196034. for (i = 0, rp = row_buf + 1, dp = png_ptr->up_row + 1,
  196035. pp = prev_row + 1; i < row_bytes; i++)
  196036. {
  196037. v = *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  196038. sum += (v < 128) ? v : 256 - v;
  196039. if (sum > lmins) /* We are already worse, don't continue. */
  196040. break;
  196041. }
  196042. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  196043. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  196044. {
  196045. int j;
  196046. png_uint_32 sumhi, sumlo;
  196047. sumlo = sum & PNG_LOMASK;
  196048. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  196049. for (j = 0; j < num_p_filters; j++)
  196050. {
  196051. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_UP)
  196052. {
  196053. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  196054. PNG_WEIGHT_SHIFT;
  196055. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  196056. PNG_WEIGHT_SHIFT;
  196057. }
  196058. }
  196059. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_UP]) >>
  196060. PNG_COST_SHIFT;
  196061. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_UP]) >>
  196062. PNG_COST_SHIFT;
  196063. if (sumhi > PNG_HIMASK)
  196064. sum = PNG_MAXSUM;
  196065. else
  196066. sum = (sumhi << PNG_HISHIFT) + sumlo;
  196067. }
  196068. #endif
  196069. if (sum < mins)
  196070. {
  196071. mins = sum;
  196072. best_row = png_ptr->up_row;
  196073. }
  196074. }
  196075. /* avg filter */
  196076. if (filter_to_do == PNG_FILTER_AVG)
  196077. {
  196078. png_bytep rp, dp, pp, lp;
  196079. png_uint_32 i;
  196080. for (i = 0, rp = row_buf + 1, dp = png_ptr->avg_row + 1,
  196081. pp = prev_row + 1; i < bpp; i++)
  196082. {
  196083. *dp++ = (png_byte)(((int)*rp++ - ((int)*pp++ / 2)) & 0xff);
  196084. }
  196085. for (lp = row_buf + 1; i < row_bytes; i++)
  196086. {
  196087. *dp++ = (png_byte)(((int)*rp++ - (((int)*pp++ + (int)*lp++) / 2))
  196088. & 0xff);
  196089. }
  196090. best_row = png_ptr->avg_row;
  196091. }
  196092. else if (filter_to_do & PNG_FILTER_AVG)
  196093. {
  196094. png_bytep rp, dp, pp, lp;
  196095. png_uint_32 sum = 0, lmins = mins;
  196096. png_uint_32 i;
  196097. int v;
  196098. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  196099. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  196100. {
  196101. int j;
  196102. png_uint_32 lmhi, lmlo;
  196103. lmlo = lmins & PNG_LOMASK;
  196104. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  196105. for (j = 0; j < num_p_filters; j++)
  196106. {
  196107. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_AVG)
  196108. {
  196109. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  196110. PNG_WEIGHT_SHIFT;
  196111. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  196112. PNG_WEIGHT_SHIFT;
  196113. }
  196114. }
  196115. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_AVG]) >>
  196116. PNG_COST_SHIFT;
  196117. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_AVG]) >>
  196118. PNG_COST_SHIFT;
  196119. if (lmhi > PNG_HIMASK)
  196120. lmins = PNG_MAXSUM;
  196121. else
  196122. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  196123. }
  196124. #endif
  196125. for (i = 0, rp = row_buf + 1, dp = png_ptr->avg_row + 1,
  196126. pp = prev_row + 1; i < bpp; i++)
  196127. {
  196128. v = *dp++ = (png_byte)(((int)*rp++ - ((int)*pp++ / 2)) & 0xff);
  196129. sum += (v < 128) ? v : 256 - v;
  196130. }
  196131. for (lp = row_buf + 1; i < row_bytes; i++)
  196132. {
  196133. v = *dp++ =
  196134. (png_byte)(((int)*rp++ - (((int)*pp++ + (int)*lp++) / 2)) & 0xff);
  196135. sum += (v < 128) ? v : 256 - v;
  196136. if (sum > lmins) /* We are already worse, don't continue. */
  196137. break;
  196138. }
  196139. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  196140. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  196141. {
  196142. int j;
  196143. png_uint_32 sumhi, sumlo;
  196144. sumlo = sum & PNG_LOMASK;
  196145. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  196146. for (j = 0; j < num_p_filters; j++)
  196147. {
  196148. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_NONE)
  196149. {
  196150. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  196151. PNG_WEIGHT_SHIFT;
  196152. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  196153. PNG_WEIGHT_SHIFT;
  196154. }
  196155. }
  196156. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_AVG]) >>
  196157. PNG_COST_SHIFT;
  196158. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_AVG]) >>
  196159. PNG_COST_SHIFT;
  196160. if (sumhi > PNG_HIMASK)
  196161. sum = PNG_MAXSUM;
  196162. else
  196163. sum = (sumhi << PNG_HISHIFT) + sumlo;
  196164. }
  196165. #endif
  196166. if (sum < mins)
  196167. {
  196168. mins = sum;
  196169. best_row = png_ptr->avg_row;
  196170. }
  196171. }
  196172. /* Paeth filter */
  196173. if (filter_to_do == PNG_FILTER_PAETH)
  196174. {
  196175. png_bytep rp, dp, pp, cp, lp;
  196176. png_uint_32 i;
  196177. for (i = 0, rp = row_buf + 1, dp = png_ptr->paeth_row + 1,
  196178. pp = prev_row + 1; i < bpp; i++)
  196179. {
  196180. *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  196181. }
  196182. for (lp = row_buf + 1, cp = prev_row + 1; i < row_bytes; i++)
  196183. {
  196184. int a, b, c, pa, pb, pc, p;
  196185. b = *pp++;
  196186. c = *cp++;
  196187. a = *lp++;
  196188. p = b - c;
  196189. pc = a - c;
  196190. #ifdef PNG_USE_ABS
  196191. pa = abs(p);
  196192. pb = abs(pc);
  196193. pc = abs(p + pc);
  196194. #else
  196195. pa = p < 0 ? -p : p;
  196196. pb = pc < 0 ? -pc : pc;
  196197. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  196198. #endif
  196199. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  196200. *dp++ = (png_byte)(((int)*rp++ - p) & 0xff);
  196201. }
  196202. best_row = png_ptr->paeth_row;
  196203. }
  196204. else if (filter_to_do & PNG_FILTER_PAETH)
  196205. {
  196206. png_bytep rp, dp, pp, cp, lp;
  196207. png_uint_32 sum = 0, lmins = mins;
  196208. png_uint_32 i;
  196209. int v;
  196210. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  196211. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  196212. {
  196213. int j;
  196214. png_uint_32 lmhi, lmlo;
  196215. lmlo = lmins & PNG_LOMASK;
  196216. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  196217. for (j = 0; j < num_p_filters; j++)
  196218. {
  196219. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_PAETH)
  196220. {
  196221. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  196222. PNG_WEIGHT_SHIFT;
  196223. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  196224. PNG_WEIGHT_SHIFT;
  196225. }
  196226. }
  196227. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  196228. PNG_COST_SHIFT;
  196229. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  196230. PNG_COST_SHIFT;
  196231. if (lmhi > PNG_HIMASK)
  196232. lmins = PNG_MAXSUM;
  196233. else
  196234. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  196235. }
  196236. #endif
  196237. for (i = 0, rp = row_buf + 1, dp = png_ptr->paeth_row + 1,
  196238. pp = prev_row + 1; i < bpp; i++)
  196239. {
  196240. v = *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  196241. sum += (v < 128) ? v : 256 - v;
  196242. }
  196243. for (lp = row_buf + 1, cp = prev_row + 1; i < row_bytes; i++)
  196244. {
  196245. int a, b, c, pa, pb, pc, p;
  196246. b = *pp++;
  196247. c = *cp++;
  196248. a = *lp++;
  196249. #ifndef PNG_SLOW_PAETH
  196250. p = b - c;
  196251. pc = a - c;
  196252. #ifdef PNG_USE_ABS
  196253. pa = abs(p);
  196254. pb = abs(pc);
  196255. pc = abs(p + pc);
  196256. #else
  196257. pa = p < 0 ? -p : p;
  196258. pb = pc < 0 ? -pc : pc;
  196259. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  196260. #endif
  196261. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  196262. #else /* PNG_SLOW_PAETH */
  196263. p = a + b - c;
  196264. pa = abs(p - a);
  196265. pb = abs(p - b);
  196266. pc = abs(p - c);
  196267. if (pa <= pb && pa <= pc)
  196268. p = a;
  196269. else if (pb <= pc)
  196270. p = b;
  196271. else
  196272. p = c;
  196273. #endif /* PNG_SLOW_PAETH */
  196274. v = *dp++ = (png_byte)(((int)*rp++ - p) & 0xff);
  196275. sum += (v < 128) ? v : 256 - v;
  196276. if (sum > lmins) /* We are already worse, don't continue. */
  196277. break;
  196278. }
  196279. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  196280. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  196281. {
  196282. int j;
  196283. png_uint_32 sumhi, sumlo;
  196284. sumlo = sum & PNG_LOMASK;
  196285. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  196286. for (j = 0; j < num_p_filters; j++)
  196287. {
  196288. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_PAETH)
  196289. {
  196290. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  196291. PNG_WEIGHT_SHIFT;
  196292. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  196293. PNG_WEIGHT_SHIFT;
  196294. }
  196295. }
  196296. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  196297. PNG_COST_SHIFT;
  196298. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  196299. PNG_COST_SHIFT;
  196300. if (sumhi > PNG_HIMASK)
  196301. sum = PNG_MAXSUM;
  196302. else
  196303. sum = (sumhi << PNG_HISHIFT) + sumlo;
  196304. }
  196305. #endif
  196306. if (sum < mins)
  196307. {
  196308. best_row = png_ptr->paeth_row;
  196309. }
  196310. }
  196311. #endif /* PNG_NO_WRITE_FILTER */
  196312. /* Do the actual writing of the filtered row data from the chosen filter. */
  196313. png_write_filtered_row(png_ptr, best_row);
  196314. #ifndef PNG_NO_WRITE_FILTER
  196315. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  196316. /* Save the type of filter we picked this time for future calculations */
  196317. if (png_ptr->num_prev_filters > 0)
  196318. {
  196319. int j;
  196320. for (j = 1; j < num_p_filters; j++)
  196321. {
  196322. png_ptr->prev_filters[j] = png_ptr->prev_filters[j - 1];
  196323. }
  196324. png_ptr->prev_filters[j] = best_row[0];
  196325. }
  196326. #endif
  196327. #endif /* PNG_NO_WRITE_FILTER */
  196328. }
  196329. /* Do the actual writing of a previously filtered row. */
  196330. void /* PRIVATE */
  196331. png_write_filtered_row(png_structp png_ptr, png_bytep filtered_row)
  196332. {
  196333. png_debug(1, "in png_write_filtered_row\n");
  196334. png_debug1(2, "filter = %d\n", filtered_row[0]);
  196335. /* set up the zlib input buffer */
  196336. png_ptr->zstream.next_in = filtered_row;
  196337. png_ptr->zstream.avail_in = (uInt)png_ptr->row_info.rowbytes + 1;
  196338. /* repeat until we have compressed all the data */
  196339. do
  196340. {
  196341. int ret; /* return of zlib */
  196342. /* compress the data */
  196343. ret = deflate(&png_ptr->zstream, Z_NO_FLUSH);
  196344. /* check for compression errors */
  196345. if (ret != Z_OK)
  196346. {
  196347. if (png_ptr->zstream.msg != NULL)
  196348. png_error(png_ptr, png_ptr->zstream.msg);
  196349. else
  196350. png_error(png_ptr, "zlib error");
  196351. }
  196352. /* see if it is time to write another IDAT */
  196353. if (!(png_ptr->zstream.avail_out))
  196354. {
  196355. /* write the IDAT and reset the zlib output buffer */
  196356. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  196357. png_ptr->zstream.next_out = png_ptr->zbuf;
  196358. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  196359. }
  196360. /* repeat until all data has been compressed */
  196361. } while (png_ptr->zstream.avail_in);
  196362. /* swap the current and previous rows */
  196363. if (png_ptr->prev_row != NULL)
  196364. {
  196365. png_bytep tptr;
  196366. tptr = png_ptr->prev_row;
  196367. png_ptr->prev_row = png_ptr->row_buf;
  196368. png_ptr->row_buf = tptr;
  196369. }
  196370. /* finish row - updates counters and flushes zlib if last row */
  196371. png_write_finish_row(png_ptr);
  196372. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  196373. png_ptr->flush_rows++;
  196374. if (png_ptr->flush_dist > 0 &&
  196375. png_ptr->flush_rows >= png_ptr->flush_dist)
  196376. {
  196377. png_write_flush(png_ptr);
  196378. }
  196379. #endif
  196380. }
  196381. #endif /* PNG_WRITE_SUPPORTED */
  196382. /********* End of inlined file: pngwutil.c *********/
  196383. }
  196384. }
  196385. #ifdef _MSC_VER
  196386. #pragma warning (pop)
  196387. #endif
  196388. BEGIN_JUCE_NAMESPACE
  196389. using namespace pnglibNamespace;
  196390. using ::malloc;
  196391. using ::free;
  196392. static void pngReadCallback (png_structp pngReadStruct, png_bytep data, png_size_t length) throw()
  196393. {
  196394. InputStream* const in = (InputStream*) png_get_io_ptr (pngReadStruct);
  196395. in->read (data, (int) length);
  196396. }
  196397. struct PNGErrorStruct {};
  196398. static void pngErrorCallback (png_structp, png_const_charp)
  196399. {
  196400. throw PNGErrorStruct();
  196401. }
  196402. Image* juce_loadPNGImageFromStream (InputStream& in) throw()
  196403. {
  196404. Image* image = 0;
  196405. png_structp pngReadStruct;
  196406. png_infop pngInfoStruct;
  196407. pngReadStruct = png_create_read_struct (PNG_LIBPNG_VER_STRING, 0, 0, 0);
  196408. if (pngReadStruct != 0)
  196409. {
  196410. pngInfoStruct = png_create_info_struct (pngReadStruct);
  196411. if (pngInfoStruct == 0)
  196412. {
  196413. png_destroy_read_struct (&pngReadStruct, 0, 0);
  196414. return 0;
  196415. }
  196416. png_set_error_fn (pngReadStruct, 0, pngErrorCallback, pngErrorCallback);
  196417. // read the header..
  196418. png_set_read_fn (pngReadStruct, &in, pngReadCallback);
  196419. png_uint_32 width, height;
  196420. int bitDepth, colorType, interlaceType;
  196421. try
  196422. {
  196423. png_read_info (pngReadStruct, pngInfoStruct);
  196424. png_get_IHDR (pngReadStruct, pngInfoStruct,
  196425. &width, &height,
  196426. &bitDepth, &colorType,
  196427. &interlaceType, 0, 0);
  196428. }
  196429. catch (...)
  196430. {
  196431. png_destroy_read_struct (&pngReadStruct, 0, 0);
  196432. return 0;
  196433. }
  196434. if (bitDepth == 16)
  196435. png_set_strip_16 (pngReadStruct);
  196436. if (colorType == PNG_COLOR_TYPE_PALETTE)
  196437. png_set_expand (pngReadStruct);
  196438. if (bitDepth < 8)
  196439. png_set_expand (pngReadStruct);
  196440. if (png_get_valid (pngReadStruct, pngInfoStruct, PNG_INFO_tRNS))
  196441. png_set_expand (pngReadStruct);
  196442. if (colorType == PNG_COLOR_TYPE_GRAY || colorType == PNG_COLOR_TYPE_GRAY_ALPHA)
  196443. png_set_gray_to_rgb (pngReadStruct);
  196444. png_set_add_alpha (pngReadStruct, 0xff, PNG_FILLER_AFTER);
  196445. const bool hasAlphaChan = (colorType & PNG_COLOR_MASK_ALPHA) != 0
  196446. || pngInfoStruct->num_trans > 0;
  196447. // Load the image into a temp buffer in the pnglib format..
  196448. uint8* const tempBuffer = (uint8*) juce_malloc (height * (width << 2));
  196449. png_bytepp rows = (png_bytepp) juce_malloc (sizeof (png_bytep) * height);
  196450. int y;
  196451. for (y = (int) height; --y >= 0;)
  196452. rows[y] = (png_bytep) (tempBuffer + (width << 2) * y);
  196453. bool crashed = false;
  196454. try
  196455. {
  196456. png_read_image (pngReadStruct, rows);
  196457. png_read_end (pngReadStruct, pngInfoStruct);
  196458. }
  196459. catch (...)
  196460. {
  196461. crashed = true;
  196462. }
  196463. juce_free (rows);
  196464. png_destroy_read_struct (&pngReadStruct, &pngInfoStruct, 0);
  196465. if (crashed)
  196466. return 0;
  196467. // now convert the data to a juce image format..
  196468. image = new Image (hasAlphaChan ? Image::ARGB : Image::RGB,
  196469. width, height, hasAlphaChan);
  196470. int stride, pixelStride;
  196471. uint8* const pixels = image->lockPixelDataReadWrite (0, 0, width, height, stride, pixelStride);
  196472. uint8* srcRow = tempBuffer;
  196473. uint8* destRow = pixels;
  196474. for (y = 0; y < (int) height; ++y)
  196475. {
  196476. const uint8* src = srcRow;
  196477. srcRow += (width << 2);
  196478. uint8* dest = destRow;
  196479. destRow += stride;
  196480. if (hasAlphaChan)
  196481. {
  196482. for (int i = width; --i >= 0;)
  196483. {
  196484. ((PixelARGB*) dest)->setARGB (src[3], src[0], src[1], src[2]);
  196485. ((PixelARGB*) dest)->premultiply();
  196486. dest += pixelStride;
  196487. src += 4;
  196488. }
  196489. }
  196490. else
  196491. {
  196492. for (int i = width; --i >= 0;)
  196493. {
  196494. ((PixelRGB*) dest)->setARGB (0, src[0], src[1], src[2]);
  196495. dest += pixelStride;
  196496. src += 4;
  196497. }
  196498. }
  196499. }
  196500. image->releasePixelDataReadWrite (pixels);
  196501. juce_free (tempBuffer);
  196502. }
  196503. return image;
  196504. }
  196505. static void pngWriteDataCallback (png_structp png_ptr, png_bytep data, png_size_t length) throw()
  196506. {
  196507. OutputStream* const out = (OutputStream*) png_ptr->io_ptr;
  196508. const bool ok = out->write (data, length);
  196509. (void) ok;
  196510. jassert (ok);
  196511. }
  196512. bool juce_writePNGImageToStream (const Image& image, OutputStream& out) throw()
  196513. {
  196514. const int width = image.getWidth();
  196515. const int height = image.getHeight();
  196516. png_structp pngWriteStruct = png_create_write_struct (PNG_LIBPNG_VER_STRING, 0, 0, 0);
  196517. if (pngWriteStruct == 0)
  196518. return false;
  196519. png_infop pngInfoStruct = png_create_info_struct (pngWriteStruct);
  196520. if (pngInfoStruct == 0)
  196521. {
  196522. png_destroy_write_struct (&pngWriteStruct, (png_infopp) 0);
  196523. return false;
  196524. }
  196525. png_set_write_fn (pngWriteStruct, &out, pngWriteDataCallback, 0);
  196526. png_set_IHDR (pngWriteStruct, pngInfoStruct, width, height, 8,
  196527. image.hasAlphaChannel() ? PNG_COLOR_TYPE_RGB_ALPHA
  196528. : PNG_COLOR_TYPE_RGB,
  196529. PNG_INTERLACE_NONE,
  196530. PNG_COMPRESSION_TYPE_BASE,
  196531. PNG_FILTER_TYPE_BASE);
  196532. png_bytep rowData = (png_bytep) juce_malloc (width * 4 * sizeof (png_byte));
  196533. png_color_8 sig_bit;
  196534. sig_bit.red = 8;
  196535. sig_bit.green = 8;
  196536. sig_bit.blue = 8;
  196537. sig_bit.alpha = 8;
  196538. png_set_sBIT (pngWriteStruct, pngInfoStruct, &sig_bit);
  196539. png_write_info (pngWriteStruct, pngInfoStruct);
  196540. png_set_shift (pngWriteStruct, &sig_bit);
  196541. png_set_packing (pngWriteStruct);
  196542. for (int y = 0; y < height; ++y)
  196543. {
  196544. uint8* dst = (uint8*) rowData;
  196545. int stride, pixelStride;
  196546. const uint8* pixels = image.lockPixelDataReadOnly (0, y, width, 1, stride, pixelStride);
  196547. const uint8* src = pixels;
  196548. if (image.hasAlphaChannel())
  196549. {
  196550. for (int i = width; --i >= 0;)
  196551. {
  196552. PixelARGB p (*(const PixelARGB*) src);
  196553. p.unpremultiply();
  196554. *dst++ = p.getRed();
  196555. *dst++ = p.getGreen();
  196556. *dst++ = p.getBlue();
  196557. *dst++ = p.getAlpha();
  196558. src += pixelStride;
  196559. }
  196560. }
  196561. else
  196562. {
  196563. for (int i = width; --i >= 0;)
  196564. {
  196565. *dst++ = ((const PixelRGB*) src)->getRed();
  196566. *dst++ = ((const PixelRGB*) src)->getGreen();
  196567. *dst++ = ((const PixelRGB*) src)->getBlue();
  196568. src += pixelStride;
  196569. }
  196570. }
  196571. png_write_rows (pngWriteStruct, &rowData, 1);
  196572. image.releasePixelDataReadOnly (pixels);
  196573. }
  196574. juce_free (rowData);
  196575. png_write_end (pngWriteStruct, pngInfoStruct);
  196576. png_destroy_write_struct (&pngWriteStruct, &pngInfoStruct);
  196577. out.flush();
  196578. return true;
  196579. }
  196580. END_JUCE_NAMESPACE
  196581. /********* End of inlined file: juce_PNGLoader.cpp *********/
  196582. #endif
  196583. //==============================================================================
  196584. #if JUCE_WIN32
  196585. /********* Start of inlined file: juce_win32_Files.cpp *********/
  196586. #ifdef _MSC_VER
  196587. #pragma warning (disable: 4514)
  196588. #pragma warning (push)
  196589. #endif
  196590. #include <ctime>
  196591. #ifndef _WIN32_IE
  196592. #define _WIN32_IE 0x0400
  196593. #endif
  196594. #include <shlobj.h>
  196595. #ifndef CSIDL_MYMUSIC
  196596. #define CSIDL_MYMUSIC 0x000d
  196597. #endif
  196598. #ifndef CSIDL_MYVIDEO
  196599. #define CSIDL_MYVIDEO 0x000e
  196600. #endif
  196601. BEGIN_JUCE_NAMESPACE
  196602. #ifdef _MSC_VER
  196603. #pragma warning (pop)
  196604. #endif
  196605. const tchar File::separator = T('\\');
  196606. const tchar* File::separatorString = T("\\");
  196607. bool juce_fileExists (const String& fileName,
  196608. const bool dontCountDirectories) throw()
  196609. {
  196610. if (fileName.isEmpty())
  196611. return false;
  196612. const DWORD attr = GetFileAttributes (fileName);
  196613. return dontCountDirectories ? ((attr & FILE_ATTRIBUTE_DIRECTORY) == 0)
  196614. : (attr != 0xffffffff);
  196615. }
  196616. bool juce_isDirectory (const String& fileName) throw()
  196617. {
  196618. const DWORD attr = GetFileAttributes (fileName);
  196619. return (attr != 0xffffffff)
  196620. && ((attr & FILE_ATTRIBUTE_DIRECTORY) != 0);
  196621. }
  196622. bool juce_canWriteToFile (const String& fileName) throw()
  196623. {
  196624. const DWORD attr = GetFileAttributes (fileName);
  196625. return ((attr & FILE_ATTRIBUTE_READONLY) == 0);
  196626. }
  196627. bool juce_setFileReadOnly (const String& fileName,
  196628. bool isReadOnly)
  196629. {
  196630. DWORD attr = GetFileAttributes (fileName);
  196631. if (attr == 0xffffffff)
  196632. return false;
  196633. if (isReadOnly != juce_canWriteToFile (fileName))
  196634. return true;
  196635. if (isReadOnly)
  196636. attr |= FILE_ATTRIBUTE_READONLY;
  196637. else
  196638. attr &= ~FILE_ATTRIBUTE_READONLY;
  196639. return SetFileAttributes (fileName, attr) != FALSE;
  196640. }
  196641. bool File::isHidden() const throw()
  196642. {
  196643. return (GetFileAttributes (getFullPathName()) & FILE_ATTRIBUTE_HIDDEN) != 0;
  196644. }
  196645. bool juce_deleteFile (const String& fileName) throw()
  196646. {
  196647. if (juce_isDirectory (fileName))
  196648. return RemoveDirectory (fileName) != 0;
  196649. return DeleteFile (fileName) != 0;
  196650. }
  196651. bool juce_moveFile (const String& source, const String& dest) throw()
  196652. {
  196653. return MoveFile (source, dest) != 0;
  196654. }
  196655. bool juce_copyFile (const String& source, const String& dest) throw()
  196656. {
  196657. return CopyFile (source, dest, false) != 0;
  196658. }
  196659. void juce_createDirectory (const String& fileName) throw()
  196660. {
  196661. if (! juce_fileExists (fileName, true))
  196662. {
  196663. CreateDirectory (fileName, 0);
  196664. }
  196665. }
  196666. // return 0 if not possible
  196667. void* juce_fileOpen (const String& fileName, bool forWriting) throw()
  196668. {
  196669. HANDLE h;
  196670. if (forWriting)
  196671. {
  196672. h = CreateFile (fileName, GENERIC_WRITE, FILE_SHARE_READ, 0,
  196673. OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
  196674. if (h != INVALID_HANDLE_VALUE)
  196675. SetFilePointer (h, 0, 0, FILE_END);
  196676. else
  196677. h = 0;
  196678. }
  196679. else
  196680. {
  196681. h = CreateFile (fileName, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, 0,
  196682. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN, 0);
  196683. if (h == INVALID_HANDLE_VALUE)
  196684. h = 0;
  196685. }
  196686. return (void*) h;
  196687. }
  196688. void juce_fileClose (void* handle) throw()
  196689. {
  196690. CloseHandle (handle);
  196691. }
  196692. int juce_fileRead (void* handle, void* buffer, int size) throw()
  196693. {
  196694. DWORD num = 0;
  196695. ReadFile ((HANDLE) handle, buffer, size, &num, 0);
  196696. return num;
  196697. }
  196698. int juce_fileWrite (void* handle, const void* buffer, int size) throw()
  196699. {
  196700. DWORD num;
  196701. WriteFile ((HANDLE) handle,
  196702. buffer, size,
  196703. &num, 0);
  196704. return num;
  196705. }
  196706. int64 juce_fileSetPosition (void* handle, int64 pos) throw()
  196707. {
  196708. LARGE_INTEGER li;
  196709. li.QuadPart = pos;
  196710. li.LowPart = SetFilePointer ((HANDLE) handle,
  196711. li.LowPart,
  196712. &li.HighPart,
  196713. FILE_BEGIN); // (returns -1 if it fails)
  196714. return li.QuadPart;
  196715. }
  196716. int64 juce_fileGetPosition (void* handle) throw()
  196717. {
  196718. LARGE_INTEGER li;
  196719. li.QuadPart = 0;
  196720. li.LowPart = SetFilePointer ((HANDLE) handle,
  196721. 0, &li.HighPart,
  196722. FILE_CURRENT); // (returns -1 if it fails)
  196723. return jmax ((int64) 0, li.QuadPart);
  196724. }
  196725. void juce_fileFlush (void* handle) throw()
  196726. {
  196727. FlushFileBuffers ((HANDLE) handle);
  196728. }
  196729. int64 juce_getFileSize (const String& fileName) throw()
  196730. {
  196731. WIN32_FILE_ATTRIBUTE_DATA attributes;
  196732. if (GetFileAttributesEx (fileName, GetFileExInfoStandard, &attributes))
  196733. {
  196734. return (((int64) attributes.nFileSizeHigh) << 32)
  196735. | attributes.nFileSizeLow;
  196736. }
  196737. return 0;
  196738. }
  196739. static int64 fileTimeToTime (const FILETIME* const ft) throw()
  196740. {
  196741. // tell me if this fails!
  196742. static_jassert (sizeof (ULARGE_INTEGER) == sizeof (FILETIME));
  196743. #if JUCE_GCC
  196744. return (((const ULARGE_INTEGER*) ft)->QuadPart - 116444736000000000LL) / 10000;
  196745. #else
  196746. return (((const ULARGE_INTEGER*) ft)->QuadPart - 116444736000000000) / 10000;
  196747. #endif
  196748. }
  196749. static void timeToFileTime (const int64 time, FILETIME* const ft) throw()
  196750. {
  196751. #if JUCE_GCC
  196752. ((ULARGE_INTEGER*) ft)->QuadPart = time * 10000 + 116444736000000000LL;
  196753. #else
  196754. ((ULARGE_INTEGER*) ft)->QuadPart = time * 10000 + 116444736000000000;
  196755. #endif
  196756. }
  196757. void juce_getFileTimes (const String& fileName,
  196758. int64& modificationTime,
  196759. int64& accessTime,
  196760. int64& creationTime) throw()
  196761. {
  196762. WIN32_FILE_ATTRIBUTE_DATA attributes;
  196763. if (GetFileAttributesEx (fileName, GetFileExInfoStandard, &attributes))
  196764. {
  196765. modificationTime = fileTimeToTime (&attributes.ftLastWriteTime);
  196766. creationTime = fileTimeToTime (&attributes.ftCreationTime);
  196767. accessTime = fileTimeToTime (&attributes.ftLastAccessTime);
  196768. }
  196769. else
  196770. {
  196771. creationTime = accessTime = modificationTime = 0;
  196772. }
  196773. }
  196774. bool juce_setFileTimes (const String& fileName,
  196775. int64 modificationTime,
  196776. int64 accessTime,
  196777. int64 creationTime) throw()
  196778. {
  196779. FILETIME m, a, c;
  196780. if (modificationTime > 0)
  196781. timeToFileTime (modificationTime, &m);
  196782. if (accessTime > 0)
  196783. timeToFileTime (accessTime, &a);
  196784. if (creationTime > 0)
  196785. timeToFileTime (creationTime, &c);
  196786. void* const h = juce_fileOpen (fileName, true);
  196787. bool ok = false;
  196788. if (h != 0)
  196789. {
  196790. ok = SetFileTime ((HANDLE) h,
  196791. (creationTime > 0) ? &c : 0,
  196792. (accessTime > 0) ? &a : 0,
  196793. (modificationTime > 0) ? &m : 0) != 0;
  196794. juce_fileClose (h);
  196795. }
  196796. return ok;
  196797. }
  196798. // return '\0' separated list of strings
  196799. const StringArray juce_getFileSystemRoots() throw()
  196800. {
  196801. TCHAR buffer [2048];
  196802. buffer[0] = 0;
  196803. buffer[1] = 0;
  196804. GetLogicalDriveStrings (2048, buffer);
  196805. TCHAR* n = buffer;
  196806. StringArray roots;
  196807. while (*n != 0)
  196808. {
  196809. roots.add (String (n));
  196810. while (*n++ != 0)
  196811. {
  196812. }
  196813. }
  196814. roots.sort (true);
  196815. return roots;
  196816. }
  196817. const String juce_getVolumeLabel (const String& filenameOnVolume,
  196818. int& volumeSerialNumber) throw()
  196819. {
  196820. TCHAR n [4];
  196821. n[0] = *(const TCHAR*) filenameOnVolume;
  196822. n[1] = L':';
  196823. n[2] = L'\\';
  196824. n[3] = 0;
  196825. TCHAR dest [64];
  196826. DWORD serialNum;
  196827. if (! GetVolumeInformation (n, dest, 64, (DWORD*) &serialNum, 0, 0, 0, 0))
  196828. {
  196829. dest[0] = 0;
  196830. serialNum = 0;
  196831. }
  196832. volumeSerialNumber = serialNum;
  196833. return String (dest);
  196834. }
  196835. int64 File::getBytesFreeOnVolume() const throw()
  196836. {
  196837. String fn (getFullPathName());
  196838. if (fn[1] == T(':'))
  196839. fn = fn.substring (0, 2) + T("\\");
  196840. ULARGE_INTEGER spc;
  196841. ULARGE_INTEGER tot;
  196842. ULARGE_INTEGER totFree;
  196843. if (GetDiskFreeSpaceEx (fn, &spc, &tot, &totFree))
  196844. return (int64)(spc.QuadPart);
  196845. return 0;
  196846. }
  196847. static unsigned int getWindowsDriveType (const String& fileName) throw()
  196848. {
  196849. TCHAR n[4];
  196850. n[0] = *(const TCHAR*) fileName;
  196851. n[1] = L':';
  196852. n[2] = L'\\';
  196853. n[3] = 0;
  196854. return GetDriveType (n);
  196855. }
  196856. bool File::isOnCDRomDrive() const throw()
  196857. {
  196858. return getWindowsDriveType (getFullPathName()) == DRIVE_CDROM;
  196859. }
  196860. bool File::isOnHardDisk() const throw()
  196861. {
  196862. if (fullPath.isEmpty())
  196863. return false;
  196864. const unsigned int n = getWindowsDriveType (getFullPathName());
  196865. if (fullPath.toLowerCase()[0] <= 'b'
  196866. && fullPath[1] == T(':'))
  196867. {
  196868. return n != DRIVE_REMOVABLE;
  196869. }
  196870. else
  196871. {
  196872. return n != DRIVE_CDROM && n != DRIVE_REMOTE;
  196873. }
  196874. }
  196875. bool File::isOnRemovableDrive() const throw()
  196876. {
  196877. if (fullPath.isEmpty())
  196878. return false;
  196879. const unsigned int n = getWindowsDriveType (getFullPathName());
  196880. return n == DRIVE_CDROM
  196881. || n == DRIVE_REMOTE
  196882. || n == DRIVE_REMOVABLE
  196883. || n == DRIVE_RAMDISK;
  196884. }
  196885. #define MAX_PATH_CHARS (MAX_PATH + 256)
  196886. static const File juce_getSpecialFolderPath (int type) throw()
  196887. {
  196888. WCHAR path [MAX_PATH_CHARS];
  196889. if (SHGetSpecialFolderPath (0, path, type, 0))
  196890. return File (String (path));
  196891. return File::nonexistent;
  196892. }
  196893. const File JUCE_CALLTYPE File::getSpecialLocation (const SpecialLocationType type)
  196894. {
  196895. int csidlType = 0;
  196896. switch (type)
  196897. {
  196898. case userHomeDirectory:
  196899. case userDocumentsDirectory:
  196900. csidlType = CSIDL_PERSONAL;
  196901. break;
  196902. case userDesktopDirectory:
  196903. csidlType = CSIDL_DESKTOP;
  196904. break;
  196905. case userApplicationDataDirectory:
  196906. csidlType = CSIDL_APPDATA;
  196907. break;
  196908. case commonApplicationDataDirectory:
  196909. csidlType = CSIDL_COMMON_APPDATA;
  196910. break;
  196911. case globalApplicationsDirectory:
  196912. csidlType = CSIDL_PROGRAM_FILES;
  196913. break;
  196914. case userMusicDirectory:
  196915. csidlType = CSIDL_MYMUSIC;
  196916. break;
  196917. case userMoviesDirectory:
  196918. csidlType = CSIDL_MYVIDEO;
  196919. break;
  196920. case tempDirectory:
  196921. {
  196922. WCHAR dest [2048];
  196923. dest[0] = 0;
  196924. GetTempPath (2048, dest);
  196925. return File (String (dest));
  196926. }
  196927. case currentExecutableFile:
  196928. case currentApplicationFile:
  196929. {
  196930. HINSTANCE moduleHandle = (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle();
  196931. WCHAR dest [MAX_PATH_CHARS];
  196932. dest[0] = 0;
  196933. GetModuleFileName (moduleHandle, dest, MAX_PATH_CHARS);
  196934. return File (String (dest));
  196935. }
  196936. break;
  196937. default:
  196938. jassertfalse // unknown type?
  196939. return File::nonexistent;
  196940. }
  196941. return juce_getSpecialFolderPath (csidlType);
  196942. }
  196943. void juce_setCurrentExecutableFileName (const String&) throw()
  196944. {
  196945. // n/a on windows
  196946. }
  196947. const File File::getCurrentWorkingDirectory() throw()
  196948. {
  196949. WCHAR dest [MAX_PATH_CHARS];
  196950. dest[0] = 0;
  196951. GetCurrentDirectory (MAX_PATH_CHARS, dest);
  196952. return File (String (dest));
  196953. }
  196954. bool File::setAsCurrentWorkingDirectory() const throw()
  196955. {
  196956. return SetCurrentDirectory (getFullPathName()) != FALSE;
  196957. }
  196958. template <class FindDataType>
  196959. static void getFindFileInfo (FindDataType& findData,
  196960. String& filename, bool* const isDir, bool* const isHidden,
  196961. int64* const fileSize, Time* const modTime, Time* const creationTime,
  196962. bool* const isReadOnly) throw()
  196963. {
  196964. filename = findData.cFileName;
  196965. if (isDir != 0)
  196966. *isDir = ((findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0);
  196967. if (isHidden != 0)
  196968. *isHidden = ((findData.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN) != 0);
  196969. if (fileSize != 0)
  196970. *fileSize = findData.nFileSizeLow + (((int64) findData.nFileSizeHigh) << 32);
  196971. if (modTime != 0)
  196972. *modTime = fileTimeToTime (&findData.ftLastWriteTime);
  196973. if (creationTime != 0)
  196974. *creationTime = fileTimeToTime (&findData.ftCreationTime);
  196975. if (isReadOnly != 0)
  196976. *isReadOnly = ((findData.dwFileAttributes & FILE_ATTRIBUTE_READONLY) != 0);
  196977. }
  196978. void* juce_findFileStart (const String& directory, const String& wildCard, String& firstResult,
  196979. bool* isDir, bool* isHidden, int64* fileSize,
  196980. Time* modTime, Time* creationTime, bool* isReadOnly) throw()
  196981. {
  196982. String wc (directory);
  196983. if (! wc.endsWithChar (File::separator))
  196984. wc += File::separator;
  196985. wc += wildCard;
  196986. WIN32_FIND_DATA findData;
  196987. HANDLE h = FindFirstFile (wc, &findData);
  196988. if (h != INVALID_HANDLE_VALUE)
  196989. {
  196990. getFindFileInfo (findData, firstResult, isDir, isHidden, fileSize,
  196991. modTime, creationTime, isReadOnly);
  196992. return h;
  196993. }
  196994. firstResult = String::empty;
  196995. return 0;
  196996. }
  196997. bool juce_findFileNext (void* handle, String& resultFile,
  196998. bool* isDir, bool* isHidden, int64* fileSize,
  196999. Time* modTime, Time* creationTime, bool* isReadOnly) throw()
  197000. {
  197001. WIN32_FIND_DATA findData;
  197002. if (handle != 0 && FindNextFile ((HANDLE) handle, &findData) != 0)
  197003. {
  197004. getFindFileInfo (findData, resultFile, isDir, isHidden, fileSize,
  197005. modTime, creationTime, isReadOnly);
  197006. return true;
  197007. }
  197008. resultFile = String::empty;
  197009. return false;
  197010. }
  197011. void juce_findFileClose (void* handle) throw()
  197012. {
  197013. FindClose (handle);
  197014. }
  197015. bool juce_launchFile (const String& fileName,
  197016. const String& parameters) throw()
  197017. {
  197018. HINSTANCE hInstance = 0;
  197019. JUCE_TRY
  197020. {
  197021. hInstance = ShellExecute (0, 0, fileName, parameters, 0, SW_SHOWDEFAULT);
  197022. }
  197023. JUCE_CATCH_ALL
  197024. return hInstance > (HINSTANCE) 32;
  197025. }
  197026. struct NamedPipeInternal
  197027. {
  197028. HANDLE pipeH;
  197029. HANDLE cancelEvent;
  197030. bool connected, createdPipe;
  197031. NamedPipeInternal()
  197032. : pipeH (0),
  197033. cancelEvent (0),
  197034. connected (false),
  197035. createdPipe (false)
  197036. {
  197037. cancelEvent = CreateEvent (0, FALSE, FALSE, 0);
  197038. }
  197039. ~NamedPipeInternal()
  197040. {
  197041. disconnect();
  197042. if (pipeH != 0)
  197043. CloseHandle (pipeH);
  197044. CloseHandle (cancelEvent);
  197045. }
  197046. bool connect (const int timeOutMs)
  197047. {
  197048. if (! createdPipe)
  197049. return true;
  197050. if (! connected)
  197051. {
  197052. OVERLAPPED over;
  197053. zerostruct (over);
  197054. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  197055. if (ConnectNamedPipe (pipeH, &over))
  197056. {
  197057. connected = false; // yes, you read that right. In overlapped mode it should always return 0.
  197058. }
  197059. else
  197060. {
  197061. const int err = GetLastError();
  197062. if (err == ERROR_IO_PENDING || err == ERROR_PIPE_LISTENING)
  197063. {
  197064. HANDLE handles[] = { over.hEvent, cancelEvent };
  197065. if (WaitForMultipleObjects (2, handles, FALSE,
  197066. timeOutMs >= 0 ? timeOutMs : INFINITE) == WAIT_OBJECT_0)
  197067. connected = true;
  197068. }
  197069. else if (err == ERROR_PIPE_CONNECTED)
  197070. {
  197071. connected = true;
  197072. }
  197073. }
  197074. CloseHandle (over.hEvent);
  197075. }
  197076. return connected;
  197077. }
  197078. void disconnect()
  197079. {
  197080. if (connected)
  197081. {
  197082. DisconnectNamedPipe (pipeH);
  197083. connected = false;
  197084. }
  197085. }
  197086. };
  197087. void NamedPipe::close()
  197088. {
  197089. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  197090. delete intern;
  197091. internal = 0;
  197092. }
  197093. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  197094. {
  197095. close();
  197096. NamedPipeInternal* const intern = new NamedPipeInternal();
  197097. String file ("\\\\.\\pipe\\");
  197098. file += pipeName;
  197099. intern->createdPipe = createPipe;
  197100. if (createPipe)
  197101. {
  197102. intern->pipeH = CreateNamedPipe (file, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED, 0,
  197103. 1, 64, 64, 0, NULL);
  197104. }
  197105. else
  197106. {
  197107. intern->pipeH = CreateFile (file, GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING,
  197108. FILE_FLAG_OVERLAPPED, 0);
  197109. }
  197110. if (intern->pipeH != INVALID_HANDLE_VALUE)
  197111. {
  197112. internal = intern;
  197113. return true;
  197114. }
  197115. delete intern;
  197116. return false;
  197117. }
  197118. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int timeOutMilliseconds)
  197119. {
  197120. int bytesRead = -1;
  197121. bool waitAgain = true;
  197122. while (waitAgain && internal != 0)
  197123. {
  197124. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  197125. waitAgain = false;
  197126. if (! intern->connect (timeOutMilliseconds))
  197127. break;
  197128. if (maxBytesToRead <= 0)
  197129. return 0;
  197130. OVERLAPPED over;
  197131. zerostruct (over);
  197132. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  197133. unsigned long numRead;
  197134. if (ReadFile (intern->pipeH, destBuffer, maxBytesToRead, &numRead, &over))
  197135. {
  197136. bytesRead = (int) numRead;
  197137. }
  197138. else if (GetLastError() == ERROR_IO_PENDING)
  197139. {
  197140. HANDLE handles[] = { over.hEvent, intern->cancelEvent };
  197141. if (WaitForMultipleObjects (2, handles, FALSE,
  197142. timeOutMilliseconds >= 0 ? timeOutMilliseconds
  197143. : INFINITE) == WAIT_OBJECT_0)
  197144. {
  197145. if (GetOverlappedResult (intern->pipeH, &over, &numRead, FALSE))
  197146. {
  197147. bytesRead = (int) numRead;
  197148. }
  197149. else if (GetLastError() == ERROR_BROKEN_PIPE && intern->createdPipe)
  197150. {
  197151. intern->disconnect();
  197152. waitAgain = true;
  197153. }
  197154. }
  197155. }
  197156. else
  197157. {
  197158. waitAgain = internal != 0;
  197159. Sleep (5);
  197160. }
  197161. CloseHandle (over.hEvent);
  197162. }
  197163. return bytesRead;
  197164. }
  197165. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  197166. {
  197167. int bytesWritten = -1;
  197168. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  197169. if (intern != 0 && intern->connect (timeOutMilliseconds))
  197170. {
  197171. if (numBytesToWrite <= 0)
  197172. return 0;
  197173. OVERLAPPED over;
  197174. zerostruct (over);
  197175. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  197176. unsigned long numWritten;
  197177. if (WriteFile (intern->pipeH, sourceBuffer, numBytesToWrite, &numWritten, &over))
  197178. {
  197179. bytesWritten = (int) numWritten;
  197180. }
  197181. else if (GetLastError() == ERROR_IO_PENDING)
  197182. {
  197183. HANDLE handles[] = { over.hEvent, intern->cancelEvent };
  197184. if (WaitForMultipleObjects (2, handles, FALSE, timeOutMilliseconds >= 0 ? timeOutMilliseconds
  197185. : INFINITE) == WAIT_OBJECT_0)
  197186. {
  197187. if (GetOverlappedResult (intern->pipeH, &over, &numWritten, FALSE))
  197188. {
  197189. bytesWritten = (int) numWritten;
  197190. }
  197191. else if (GetLastError() == ERROR_BROKEN_PIPE && intern->createdPipe)
  197192. {
  197193. intern->disconnect();
  197194. }
  197195. }
  197196. }
  197197. CloseHandle (over.hEvent);
  197198. }
  197199. return bytesWritten;
  197200. }
  197201. void NamedPipe::cancelPendingReads()
  197202. {
  197203. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  197204. if (intern != 0)
  197205. SetEvent (intern->cancelEvent);
  197206. }
  197207. END_JUCE_NAMESPACE
  197208. /********* End of inlined file: juce_win32_Files.cpp *********/
  197209. /********* Start of inlined file: juce_win32_Network.cpp *********/
  197210. #ifdef _MSC_VER
  197211. #pragma warning (disable: 4514)
  197212. #pragma warning (push)
  197213. #endif
  197214. #include <wininet.h>
  197215. #include <nb30.h>
  197216. #include <iphlpapi.h>
  197217. #include <mapi.h>
  197218. BEGIN_JUCE_NAMESPACE
  197219. /********* Start of inlined file: juce_win32_DynamicLibraryLoader.h *********/
  197220. #ifndef __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  197221. #define __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  197222. #ifndef DOXYGEN
  197223. // use with DynamicLibraryLoader to simplify importing functions
  197224. //
  197225. // functionName: function to import
  197226. // localFunctionName: name you want to use to actually call it (must be different)
  197227. // returnType: the return type
  197228. // object: the DynamicLibraryLoader to use
  197229. // params: list of params (bracketed)
  197230. //
  197231. #define DynamicLibraryImport(functionName, localFunctionName, returnType, object, params) \
  197232. typedef returnType (WINAPI *type##localFunctionName) params; \
  197233. type##localFunctionName localFunctionName \
  197234. = (type##localFunctionName)object.findProcAddress (#functionName);
  197235. // loads and unloads a DLL automatically
  197236. class JUCE_API DynamicLibraryLoader
  197237. {
  197238. public:
  197239. DynamicLibraryLoader (const String& name);
  197240. ~DynamicLibraryLoader();
  197241. void* findProcAddress (const String& functionName);
  197242. private:
  197243. void* libHandle;
  197244. };
  197245. #endif
  197246. #endif // __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  197247. /********* End of inlined file: juce_win32_DynamicLibraryLoader.h *********/
  197248. #ifndef INTERNET_FLAG_NEED_FILE
  197249. #define INTERNET_FLAG_NEED_FILE 0x00000010
  197250. #endif
  197251. #ifdef _MSC_VER
  197252. #pragma warning (pop)
  197253. #endif
  197254. bool juce_isOnLine()
  197255. {
  197256. DWORD connectionType;
  197257. return InternetGetConnectedState (&connectionType, 0) != 0
  197258. || (connectionType & (INTERNET_CONNECTION_LAN | INTERNET_CONNECTION_PROXY)) != 0;
  197259. }
  197260. struct ConnectionAndRequestStruct
  197261. {
  197262. HINTERNET connection, request;
  197263. };
  197264. static HINTERNET sessionHandle = 0;
  197265. void* juce_openInternetFile (const String& url,
  197266. const String& headers,
  197267. const MemoryBlock& postData,
  197268. const bool isPost,
  197269. URL::OpenStreamProgressCallback* callback,
  197270. void* callbackContext)
  197271. {
  197272. if (sessionHandle == 0)
  197273. sessionHandle = InternetOpen (_T("juce"),
  197274. INTERNET_OPEN_TYPE_PRECONFIG,
  197275. 0, 0, 0);
  197276. if (sessionHandle != 0)
  197277. {
  197278. // break up the url..
  197279. TCHAR file[1024], server[1024];
  197280. URL_COMPONENTS uc;
  197281. zerostruct (uc);
  197282. uc.dwStructSize = sizeof (uc);
  197283. uc.dwUrlPathLength = sizeof (file);
  197284. uc.dwHostNameLength = sizeof (server);
  197285. uc.lpszUrlPath = file;
  197286. uc.lpszHostName = server;
  197287. if (InternetCrackUrl (url, 0, 0, &uc))
  197288. {
  197289. const bool isFtp = url.startsWithIgnoreCase (T("ftp:"));
  197290. HINTERNET connection = InternetConnect (sessionHandle,
  197291. uc.lpszHostName,
  197292. uc.nPort,
  197293. _T(""), _T(""),
  197294. isFtp ? INTERNET_SERVICE_FTP
  197295. : INTERNET_SERVICE_HTTP,
  197296. 0, 0);
  197297. if (connection != 0)
  197298. {
  197299. if (isFtp)
  197300. {
  197301. HINTERNET request = FtpOpenFile (connection,
  197302. uc.lpszUrlPath,
  197303. GENERIC_READ,
  197304. FTP_TRANSFER_TYPE_BINARY | INTERNET_FLAG_NEED_FILE,
  197305. 0);
  197306. ConnectionAndRequestStruct* const result = new ConnectionAndRequestStruct();
  197307. result->connection = connection;
  197308. result->request = request;
  197309. return result;
  197310. }
  197311. else
  197312. {
  197313. const TCHAR* mimeTypes[] = { _T("*/*"), 0 };
  197314. HINTERNET request = HttpOpenRequest (connection,
  197315. isPost ? _T("POST")
  197316. : _T("GET"),
  197317. uc.lpszUrlPath,
  197318. 0, 0, mimeTypes,
  197319. INTERNET_FLAG_RELOAD | INTERNET_FLAG_NO_CACHE_WRITE,
  197320. 0);
  197321. if (request != 0)
  197322. {
  197323. INTERNET_BUFFERS buffers;
  197324. zerostruct (buffers);
  197325. buffers.dwStructSize = sizeof (INTERNET_BUFFERS);
  197326. buffers.lpcszHeader = (LPCTSTR) headers;
  197327. buffers.dwHeadersLength = headers.length();
  197328. buffers.dwBufferTotal = (DWORD) postData.getSize();
  197329. ConnectionAndRequestStruct* result = 0;
  197330. if (HttpSendRequestEx (request, &buffers, 0, HSR_INITIATE, 0))
  197331. {
  197332. int bytesSent = 0;
  197333. for (;;)
  197334. {
  197335. const int bytesToDo = jmin (1024, postData.getSize() - bytesSent);
  197336. DWORD bytesDone = 0;
  197337. if (bytesToDo > 0
  197338. && ! InternetWriteFile (request,
  197339. ((const char*) postData.getData()) + bytesSent,
  197340. bytesToDo, &bytesDone))
  197341. {
  197342. break;
  197343. }
  197344. if (bytesToDo == 0 || (int) bytesDone < bytesToDo)
  197345. {
  197346. result = new ConnectionAndRequestStruct();
  197347. result->connection = connection;
  197348. result->request = request;
  197349. HttpEndRequest (request, 0, 0, 0);
  197350. return result;
  197351. }
  197352. bytesSent += bytesDone;
  197353. if (callback != 0 && ! callback (callbackContext, bytesSent, postData.getSize()))
  197354. break;
  197355. }
  197356. }
  197357. InternetCloseHandle (request);
  197358. }
  197359. InternetCloseHandle (connection);
  197360. }
  197361. }
  197362. }
  197363. }
  197364. return 0;
  197365. }
  197366. int juce_readFromInternetFile (void* handle, void* buffer, int bytesToRead)
  197367. {
  197368. DWORD bytesRead = 0;
  197369. const ConnectionAndRequestStruct* const crs = (const ConnectionAndRequestStruct*) handle;
  197370. if (crs != 0)
  197371. InternetReadFile (crs->request,
  197372. buffer, bytesToRead,
  197373. &bytesRead);
  197374. return bytesRead;
  197375. }
  197376. int juce_seekInInternetFile (void* handle, int newPosition)
  197377. {
  197378. if (handle != 0)
  197379. {
  197380. const ConnectionAndRequestStruct* const crs = (const ConnectionAndRequestStruct*) handle;
  197381. return InternetSetFilePointer (crs->request,
  197382. newPosition, 0,
  197383. FILE_BEGIN, 0);
  197384. }
  197385. else
  197386. {
  197387. return -1;
  197388. }
  197389. }
  197390. void juce_closeInternetFile (void* handle)
  197391. {
  197392. if (handle != 0)
  197393. {
  197394. ConnectionAndRequestStruct* const crs = (ConnectionAndRequestStruct*) handle;
  197395. InternetCloseHandle (crs->request);
  197396. InternetCloseHandle (crs->connection);
  197397. delete crs;
  197398. }
  197399. }
  197400. static int getMACAddressViaGetAdaptersInfo (int64* addresses, int maxNum, const bool littleEndian) throw()
  197401. {
  197402. int numFound = 0;
  197403. DynamicLibraryLoader dll ("iphlpapi.dll");
  197404. DynamicLibraryImport (GetAdaptersInfo, getAdaptersInfo, DWORD, dll, (PIP_ADAPTER_INFO, PULONG))
  197405. if (getAdaptersInfo != 0)
  197406. {
  197407. ULONG len = sizeof (IP_ADAPTER_INFO);
  197408. MemoryBlock mb;
  197409. PIP_ADAPTER_INFO adapterInfo = (PIP_ADAPTER_INFO) mb.getData();
  197410. if (getAdaptersInfo (adapterInfo, &len) == ERROR_BUFFER_OVERFLOW)
  197411. {
  197412. mb.setSize (len);
  197413. adapterInfo = (PIP_ADAPTER_INFO) mb.getData();
  197414. }
  197415. if (getAdaptersInfo (adapterInfo, &len) == NO_ERROR)
  197416. {
  197417. PIP_ADAPTER_INFO adapter = adapterInfo;
  197418. while (adapter != 0)
  197419. {
  197420. int64 mac = 0;
  197421. for (unsigned int i = 0; i < adapter->AddressLength; ++i)
  197422. mac = (mac << 8) | adapter->Address[i];
  197423. if (littleEndian)
  197424. mac = (int64) swapByteOrder ((uint64) mac);
  197425. if (numFound < maxNum && mac != 0)
  197426. addresses [numFound++] = mac;
  197427. adapter = adapter->Next;
  197428. }
  197429. }
  197430. }
  197431. return numFound;
  197432. }
  197433. static int getMACAddressesViaNetBios (int64* addresses, int maxNum, const bool littleEndian) throw()
  197434. {
  197435. int numFound = 0;
  197436. DynamicLibraryLoader dll ("netapi32.dll");
  197437. DynamicLibraryImport (Netbios, NetbiosCall, UCHAR, dll, (PNCB))
  197438. if (NetbiosCall != 0)
  197439. {
  197440. NCB ncb;
  197441. zerostruct (ncb);
  197442. typedef struct _ASTAT_
  197443. {
  197444. ADAPTER_STATUS adapt;
  197445. NAME_BUFFER NameBuff [30];
  197446. } ASTAT;
  197447. ASTAT astat;
  197448. zerostruct (astat);
  197449. LANA_ENUM enums;
  197450. zerostruct (enums);
  197451. ncb.ncb_command = NCBENUM;
  197452. ncb.ncb_buffer = (unsigned char*) &enums;
  197453. ncb.ncb_length = sizeof (LANA_ENUM);
  197454. NetbiosCall (&ncb);
  197455. for (int i = 0; i < enums.length; ++i)
  197456. {
  197457. zerostruct (ncb);
  197458. ncb.ncb_command = NCBRESET;
  197459. ncb.ncb_lana_num = enums.lana[i];
  197460. if (NetbiosCall (&ncb) == 0)
  197461. {
  197462. zerostruct (ncb);
  197463. memcpy (ncb.ncb_callname, "* ", NCBNAMSZ);
  197464. ncb.ncb_command = NCBASTAT;
  197465. ncb.ncb_lana_num = enums.lana[i];
  197466. ncb.ncb_buffer = (unsigned char*) &astat;
  197467. ncb.ncb_length = sizeof (ASTAT);
  197468. if (NetbiosCall (&ncb) == 0)
  197469. {
  197470. if (astat.adapt.adapter_type == 0xfe)
  197471. {
  197472. int64 mac = 0;
  197473. for (unsigned int i = 0; i < 6; ++i)
  197474. mac = (mac << 8) | astat.adapt.adapter_address[i];
  197475. if (littleEndian)
  197476. mac = (int64) swapByteOrder ((uint64) mac);
  197477. if (numFound < maxNum && mac != 0)
  197478. addresses [numFound++] = mac;
  197479. }
  197480. }
  197481. }
  197482. }
  197483. }
  197484. return numFound;
  197485. }
  197486. int SystemStats::getMACAddresses (int64* addresses, int maxNum, const bool littleEndian) throw()
  197487. {
  197488. int numFound = getMACAddressViaGetAdaptersInfo (addresses, maxNum, littleEndian);
  197489. if (numFound == 0)
  197490. numFound = getMACAddressesViaNetBios (addresses, maxNum, littleEndian);
  197491. return numFound;
  197492. }
  197493. typedef ULONG (WINAPI *MAPISendMailType) (LHANDLE, ULONG, lpMapiMessage, ::FLAGS, ULONG);
  197494. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  197495. const String& emailSubject,
  197496. const String& bodyText,
  197497. const StringArray& filesToAttach)
  197498. {
  197499. HMODULE h = LoadLibraryA ("MAPI32.dll");
  197500. MAPISendMailType mapiSendMail = (MAPISendMailType) GetProcAddress (h, "MAPISendMail");
  197501. bool ok = false;
  197502. if (mapiSendMail != 0)
  197503. {
  197504. MapiMessage message;
  197505. zerostruct (message);
  197506. message.lpszSubject = (LPSTR) (LPCSTR) emailSubject;
  197507. message.lpszNoteText = (LPSTR) (LPCSTR) bodyText;
  197508. MapiRecipDesc recip;
  197509. zerostruct (recip);
  197510. recip.ulRecipClass = MAPI_TO;
  197511. recip.lpszName = (LPSTR) (LPCSTR) targetEmailAddress;
  197512. message.nRecipCount = 1;
  197513. message.lpRecips = &recip;
  197514. MemoryBlock mb (sizeof (MapiFileDesc) * filesToAttach.size());
  197515. mb.fillWith (0);
  197516. MapiFileDesc* files = (MapiFileDesc*) mb.getData();
  197517. message.nFileCount = filesToAttach.size();
  197518. message.lpFiles = files;
  197519. for (int i = 0; i < filesToAttach.size(); ++i)
  197520. {
  197521. files[i].nPosition = (ULONG) -1;
  197522. files[i].lpszPathName = (LPSTR) (LPCSTR) filesToAttach [i];
  197523. }
  197524. ok = (mapiSendMail (0, 0, &message, MAPI_DIALOG | MAPI_LOGON_UI, 0) == SUCCESS_SUCCESS);
  197525. }
  197526. FreeLibrary (h);
  197527. return ok;
  197528. }
  197529. END_JUCE_NAMESPACE
  197530. /********* End of inlined file: juce_win32_Network.cpp *********/
  197531. /********* Start of inlined file: juce_win32_Misc.cpp *********/
  197532. BEGIN_JUCE_NAMESPACE
  197533. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  197534. bool AlertWindow::showNativeDialogBox (const String& title,
  197535. const String& bodyText,
  197536. bool isOkCancel)
  197537. {
  197538. return MessageBox (0, bodyText, title,
  197539. (isOkCancel) ? MB_OKCANCEL
  197540. : MB_OK) == IDOK;
  197541. }
  197542. #endif
  197543. void PlatformUtilities::beep()
  197544. {
  197545. MessageBeep (MB_OK);
  197546. }
  197547. #if JUCE_MSVC
  197548. #pragma warning (disable : 4127) // "Conditional expression is constant" warning
  197549. #endif
  197550. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  197551. void SystemClipboard::copyTextToClipboard (const String& text) throw()
  197552. {
  197553. if (OpenClipboard (0) != 0)
  197554. {
  197555. if (EmptyClipboard() != 0)
  197556. {
  197557. const int len = text.length();
  197558. if (len > 0)
  197559. {
  197560. HGLOBAL bufH = GlobalAlloc (GMEM_MOVEABLE | GMEM_DDESHARE,
  197561. (len + 1) * sizeof (wchar_t));
  197562. if (bufH != 0)
  197563. {
  197564. wchar_t* const data = (wchar_t*) GlobalLock (bufH);
  197565. text.copyToBuffer (data, len);
  197566. GlobalUnlock (bufH);
  197567. SetClipboardData (CF_UNICODETEXT, bufH);
  197568. }
  197569. }
  197570. }
  197571. CloseClipboard();
  197572. }
  197573. }
  197574. const String SystemClipboard::getTextFromClipboard() throw()
  197575. {
  197576. String result;
  197577. if (OpenClipboard (0) != 0)
  197578. {
  197579. HANDLE bufH = GetClipboardData (CF_UNICODETEXT);
  197580. if (bufH != 0)
  197581. {
  197582. const wchar_t* const data = (const wchar_t*) GlobalLock (bufH);
  197583. if (data != 0)
  197584. {
  197585. result = String (data, (int) (GlobalSize (bufH) / sizeof (tchar)));
  197586. GlobalUnlock (bufH);
  197587. }
  197588. }
  197589. CloseClipboard();
  197590. }
  197591. return result;
  197592. }
  197593. #endif
  197594. END_JUCE_NAMESPACE
  197595. /********* End of inlined file: juce_win32_Misc.cpp *********/
  197596. /********* Start of inlined file: juce_win32_PlatformUtils.cpp *********/
  197597. #ifdef _MSC_VER
  197598. #pragma warning (disable: 4514)
  197599. #pragma warning (push)
  197600. #endif
  197601. #include <float.h>
  197602. BEGIN_JUCE_NAMESPACE
  197603. #ifdef _MSC_VER
  197604. #pragma warning (pop)
  197605. #endif
  197606. static HKEY findKeyForPath (String name,
  197607. const bool createForWriting,
  197608. String& valueName) throw()
  197609. {
  197610. HKEY rootKey = 0;
  197611. if (name.startsWithIgnoreCase (T("HKEY_CURRENT_USER\\")))
  197612. rootKey = HKEY_CURRENT_USER;
  197613. else if (name.startsWithIgnoreCase (T("HKEY_LOCAL_MACHINE\\")))
  197614. rootKey = HKEY_LOCAL_MACHINE;
  197615. else if (name.startsWithIgnoreCase (T("HKEY_CLASSES_ROOT\\")))
  197616. rootKey = HKEY_CLASSES_ROOT;
  197617. if (rootKey != 0)
  197618. {
  197619. name = name.substring (name.indexOfChar (T('\\')) + 1);
  197620. const int lastSlash = name.lastIndexOfChar (T('\\'));
  197621. valueName = name.substring (lastSlash + 1);
  197622. name = name.substring (0, lastSlash);
  197623. HKEY key;
  197624. DWORD result;
  197625. if (createForWriting)
  197626. {
  197627. if (RegCreateKeyEx (rootKey, name, 0, L"", REG_OPTION_NON_VOLATILE,
  197628. (KEY_WRITE | KEY_QUERY_VALUE), 0, &key, &result) == ERROR_SUCCESS)
  197629. return key;
  197630. }
  197631. else
  197632. {
  197633. if (RegOpenKeyEx (rootKey, name, 0, KEY_READ, &key) == ERROR_SUCCESS)
  197634. return key;
  197635. }
  197636. }
  197637. return 0;
  197638. }
  197639. const String PlatformUtilities::getRegistryValue (const String& regValuePath,
  197640. const String& defaultValue)
  197641. {
  197642. String valueName, s;
  197643. HKEY k = findKeyForPath (regValuePath, false, valueName);
  197644. if (k != 0)
  197645. {
  197646. WCHAR buffer [2048];
  197647. unsigned long bufferSize = sizeof (buffer);
  197648. DWORD type = REG_SZ;
  197649. if (RegQueryValueEx (k, valueName, 0, &type, (LPBYTE) buffer, &bufferSize) == ERROR_SUCCESS)
  197650. s = buffer;
  197651. else
  197652. s = defaultValue;
  197653. RegCloseKey (k);
  197654. }
  197655. return s;
  197656. }
  197657. void PlatformUtilities::setRegistryValue (const String& regValuePath,
  197658. const String& value)
  197659. {
  197660. String valueName;
  197661. HKEY k = findKeyForPath (regValuePath, true, valueName);
  197662. if (k != 0)
  197663. {
  197664. RegSetValueEx (k, valueName, 0, REG_SZ,
  197665. (const BYTE*) (const WCHAR*) value,
  197666. sizeof (WCHAR) * (value.length() + 1));
  197667. RegCloseKey (k);
  197668. }
  197669. }
  197670. bool PlatformUtilities::registryValueExists (const String& regValuePath)
  197671. {
  197672. bool exists = false;
  197673. String valueName;
  197674. HKEY k = findKeyForPath (regValuePath, false, valueName);
  197675. if (k != 0)
  197676. {
  197677. unsigned char buffer [2048];
  197678. unsigned long bufferSize = sizeof (buffer);
  197679. DWORD type = 0;
  197680. if (RegQueryValueEx (k, valueName, 0, &type, buffer, &bufferSize) == ERROR_SUCCESS)
  197681. exists = true;
  197682. RegCloseKey (k);
  197683. }
  197684. return exists;
  197685. }
  197686. void PlatformUtilities::deleteRegistryValue (const String& regValuePath)
  197687. {
  197688. String valueName;
  197689. HKEY k = findKeyForPath (regValuePath, true, valueName);
  197690. if (k != 0)
  197691. {
  197692. RegDeleteValue (k, valueName);
  197693. RegCloseKey (k);
  197694. }
  197695. }
  197696. void PlatformUtilities::deleteRegistryKey (const String& regKeyPath)
  197697. {
  197698. String valueName;
  197699. HKEY k = findKeyForPath (regKeyPath, true, valueName);
  197700. if (k != 0)
  197701. {
  197702. RegDeleteKey (k, valueName);
  197703. RegCloseKey (k);
  197704. }
  197705. }
  197706. bool juce_IsRunningInWine() throw()
  197707. {
  197708. HKEY key;
  197709. if (RegOpenKeyEx (HKEY_CURRENT_USER, _T("Software\\Wine"), 0, KEY_READ, &key) == ERROR_SUCCESS)
  197710. {
  197711. RegCloseKey (key);
  197712. return true;
  197713. }
  197714. return false;
  197715. }
  197716. static void* currentModuleHandle = 0;
  197717. void* PlatformUtilities::getCurrentModuleInstanceHandle() throw()
  197718. {
  197719. if (currentModuleHandle == 0)
  197720. currentModuleHandle = GetModuleHandle (0);
  197721. return currentModuleHandle;
  197722. }
  197723. void PlatformUtilities::setCurrentModuleInstanceHandle (void* const newHandle) throw()
  197724. {
  197725. currentModuleHandle = newHandle;
  197726. }
  197727. void PlatformUtilities::fpuReset()
  197728. {
  197729. #if JUCE_MSVC
  197730. _clearfp();
  197731. #endif
  197732. }
  197733. END_JUCE_NAMESPACE
  197734. /********* End of inlined file: juce_win32_PlatformUtils.cpp *********/
  197735. /********* Start of inlined file: juce_win32_SystemStats.cpp *********/
  197736. // Auto-link the other win32 libs that are needed by library calls..
  197737. #if defined (JUCE_DLL_BUILD) && JUCE_MSVC
  197738. /********* Start of inlined file: juce_win32_AutoLinkLibraries.h *********/
  197739. // Auto-links to various win32 libs that are needed by library calls..
  197740. #pragma comment(lib, "kernel32.lib")
  197741. #pragma comment(lib, "user32.lib")
  197742. #pragma comment(lib, "shell32.lib")
  197743. #pragma comment(lib, "gdi32.lib")
  197744. #pragma comment(lib, "vfw32.lib")
  197745. #pragma comment(lib, "comdlg32.lib")
  197746. #pragma comment(lib, "winmm.lib")
  197747. #pragma comment(lib, "wininet.lib")
  197748. #pragma comment(lib, "ole32.lib")
  197749. #pragma comment(lib, "advapi32.lib")
  197750. #pragma comment(lib, "ws2_32.lib")
  197751. #pragma comment(lib, "comsupp.lib")
  197752. #if JUCE_OPENGL
  197753. #pragma comment(lib, "OpenGL32.Lib")
  197754. #pragma comment(lib, "GlU32.Lib")
  197755. #endif
  197756. #if JUCE_QUICKTIME
  197757. #pragma comment (lib, "QTMLClient.lib")
  197758. #endif
  197759. /********* End of inlined file: juce_win32_AutoLinkLibraries.h *********/
  197760. #endif
  197761. BEGIN_JUCE_NAMESPACE
  197762. extern void juce_updateMultiMonitorInfo() throw();
  197763. extern void juce_initialiseThreadEvents() throw();
  197764. void Logger::outputDebugString (const String& text) throw()
  197765. {
  197766. OutputDebugString (text + T("\n"));
  197767. }
  197768. void Logger::outputDebugPrintf (const tchar* format, ...) throw()
  197769. {
  197770. String text;
  197771. va_list args;
  197772. va_start (args, format);
  197773. text.vprintf(format, args);
  197774. outputDebugString (text);
  197775. }
  197776. static int64 hiResTicksPerSecond;
  197777. static double hiResTicksScaleFactor;
  197778. #if JUCE_USE_INTRINSICS
  197779. // CPU info functions using intrinsics...
  197780. #pragma intrinsic (__cpuid)
  197781. #pragma intrinsic (__rdtsc)
  197782. /*static unsigned int getCPUIDWord (int* familyModel = 0, int* extFeatures = 0) throw()
  197783. {
  197784. int info [4];
  197785. __cpuid (info, 1);
  197786. if (familyModel != 0)
  197787. *familyModel = info [0];
  197788. if (extFeatures != 0)
  197789. *extFeatures = info[1];
  197790. return info[3];
  197791. }*/
  197792. const String SystemStats::getCpuVendor() throw()
  197793. {
  197794. int info [4];
  197795. __cpuid (info, 0);
  197796. char v [12];
  197797. memcpy (v, info + 1, 4);
  197798. memcpy (v + 4, info + 3, 4);
  197799. memcpy (v + 8, info + 2, 4);
  197800. return String (v, 12);
  197801. }
  197802. #else
  197803. // CPU info functions using old fashioned inline asm...
  197804. /*static juce_noinline unsigned int getCPUIDWord (int* familyModel = 0, int* extFeatures = 0)
  197805. {
  197806. unsigned int cpu = 0;
  197807. unsigned int ext = 0;
  197808. unsigned int family = 0;
  197809. #if JUCE_GCC
  197810. unsigned int dummy = 0;
  197811. #endif
  197812. #ifndef __MINGW32__
  197813. __try
  197814. #endif
  197815. {
  197816. #if JUCE_GCC
  197817. __asm__ ("cpuid" : "=a" (family), "=b" (ext), "=c" (dummy),"=d" (cpu) : "a" (1));
  197818. #else
  197819. __asm
  197820. {
  197821. mov eax, 1
  197822. cpuid
  197823. mov cpu, edx
  197824. mov family, eax
  197825. mov ext, ebx
  197826. }
  197827. #endif
  197828. }
  197829. #ifndef __MINGW32__
  197830. __except (EXCEPTION_EXECUTE_HANDLER)
  197831. {
  197832. return 0;
  197833. }
  197834. #endif
  197835. if (familyModel != 0)
  197836. *familyModel = family;
  197837. if (extFeatures != 0)
  197838. *extFeatures = ext;
  197839. return cpu;
  197840. }*/
  197841. static void juce_getCpuVendor (char* const v)
  197842. {
  197843. int vendor[4];
  197844. zeromem (vendor, 16);
  197845. #ifdef JUCE_64BIT
  197846. #else
  197847. #ifndef __MINGW32__
  197848. __try
  197849. #endif
  197850. {
  197851. #if JUCE_GCC
  197852. unsigned int dummy = 0;
  197853. __asm__ ("cpuid" : "=a" (dummy), "=b" (vendor[0]), "=c" (vendor[2]),"=d" (vendor[1]) : "a" (0));
  197854. #else
  197855. __asm
  197856. {
  197857. mov eax, 0
  197858. cpuid
  197859. mov [vendor], ebx
  197860. mov [vendor + 4], edx
  197861. mov [vendor + 8], ecx
  197862. }
  197863. #endif
  197864. }
  197865. #ifndef __MINGW32__
  197866. __except (EXCEPTION_EXECUTE_HANDLER)
  197867. {
  197868. *v = 0;
  197869. }
  197870. #endif
  197871. #endif
  197872. memcpy (v, vendor, 16);
  197873. }
  197874. const String SystemStats::getCpuVendor() throw()
  197875. {
  197876. char v [16];
  197877. juce_getCpuVendor (v);
  197878. return String (v, 16);
  197879. }
  197880. #endif
  197881. struct CPUFlags
  197882. {
  197883. bool hasMMX : 1;
  197884. bool hasSSE : 1;
  197885. bool hasSSE2 : 1;
  197886. bool has3DNow : 1;
  197887. };
  197888. static CPUFlags cpuFlags;
  197889. bool SystemStats::hasMMX() throw()
  197890. {
  197891. return cpuFlags.hasMMX;
  197892. }
  197893. bool SystemStats::hasSSE() throw()
  197894. {
  197895. return cpuFlags.hasSSE;
  197896. }
  197897. bool SystemStats::hasSSE2() throw()
  197898. {
  197899. return cpuFlags.hasSSE2;
  197900. }
  197901. bool SystemStats::has3DNow() throw()
  197902. {
  197903. return cpuFlags.has3DNow;
  197904. }
  197905. void SystemStats::initialiseStats() throw()
  197906. {
  197907. juce_initialiseThreadEvents();
  197908. cpuFlags.hasMMX = IsProcessorFeaturePresent (PF_MMX_INSTRUCTIONS_AVAILABLE) != 0;
  197909. cpuFlags.hasSSE = IsProcessorFeaturePresent (PF_XMMI_INSTRUCTIONS_AVAILABLE) != 0;
  197910. cpuFlags.hasSSE2 = IsProcessorFeaturePresent (PF_XMMI64_INSTRUCTIONS_AVAILABLE) != 0;
  197911. #ifdef PF_AMD3D_INSTRUCTIONS_AVAILABLE
  197912. cpuFlags.has3DNow = IsProcessorFeaturePresent (PF_AMD3D_INSTRUCTIONS_AVAILABLE) != 0;
  197913. #else
  197914. cpuFlags.has3DNow = IsProcessorFeaturePresent (PF_3DNOW_INSTRUCTIONS_AVAILABLE) != 0;
  197915. #endif
  197916. LARGE_INTEGER f;
  197917. QueryPerformanceFrequency (&f);
  197918. hiResTicksPerSecond = f.QuadPart;
  197919. hiResTicksScaleFactor = 1000.0 / hiResTicksPerSecond;
  197920. String s (SystemStats::getJUCEVersion());
  197921. #ifdef JUCE_DEBUG
  197922. const MMRESULT res = timeBeginPeriod (1);
  197923. jassert (res == TIMERR_NOERROR);
  197924. #else
  197925. timeBeginPeriod (1);
  197926. #endif
  197927. #if defined (JUCE_DEBUG) && JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  197928. _CrtSetDbgFlag (_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
  197929. #endif
  197930. }
  197931. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType() throw()
  197932. {
  197933. OSVERSIONINFO info;
  197934. info.dwOSVersionInfoSize = sizeof (info);
  197935. GetVersionEx (&info);
  197936. if (info.dwPlatformId == VER_PLATFORM_WIN32_NT)
  197937. {
  197938. switch (info.dwMajorVersion)
  197939. {
  197940. case 5:
  197941. return (info.dwMinorVersion == 0) ? Win2000 : WinXP;
  197942. case 6:
  197943. return WinVista;
  197944. default:
  197945. jassertfalse // !! not a supported OS!
  197946. break;
  197947. }
  197948. }
  197949. else if (info.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS)
  197950. {
  197951. jassert (info.dwMinorVersion != 0); // !! still running on Windows 95??
  197952. return Win98;
  197953. }
  197954. return UnknownOS;
  197955. }
  197956. const String SystemStats::getOperatingSystemName() throw()
  197957. {
  197958. const char* name = "Unknown OS";
  197959. switch (getOperatingSystemType())
  197960. {
  197961. case WinVista:
  197962. name = "Windows Vista";
  197963. break;
  197964. case WinXP:
  197965. name = "Windows XP";
  197966. break;
  197967. case Win2000:
  197968. name = "Windows 2000";
  197969. break;
  197970. case Win98:
  197971. name = "Windows 98";
  197972. break;
  197973. default:
  197974. jassertfalse // !! new type of OS?
  197975. break;
  197976. }
  197977. return name;
  197978. }
  197979. bool SystemStats::isOperatingSystem64Bit() throw()
  197980. {
  197981. #ifdef _WIN64
  197982. return true;
  197983. #else
  197984. typedef BOOL (WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
  197985. LPFN_ISWOW64PROCESS fnIsWow64Process = (LPFN_ISWOW64PROCESS) GetProcAddress (GetModuleHandle (L"kernel32"), "IsWow64Process");
  197986. BOOL isWow64 = FALSE;
  197987. return (fnIsWow64Process != 0)
  197988. && fnIsWow64Process (GetCurrentProcess(), &isWow64)
  197989. && (isWow64 != FALSE);
  197990. #endif
  197991. }
  197992. int SystemStats::getMemorySizeInMegabytes() throw()
  197993. {
  197994. MEMORYSTATUS mem;
  197995. GlobalMemoryStatus (&mem);
  197996. return (int) (mem.dwTotalPhys / (1024 * 1024)) + 1;
  197997. }
  197998. int SystemStats::getNumCpus() throw()
  197999. {
  198000. SYSTEM_INFO systemInfo;
  198001. GetSystemInfo (&systemInfo);
  198002. return systemInfo.dwNumberOfProcessors;
  198003. }
  198004. uint32 juce_millisecondsSinceStartup() throw()
  198005. {
  198006. return (uint32) GetTickCount();
  198007. }
  198008. int64 Time::getHighResolutionTicks() throw()
  198009. {
  198010. LARGE_INTEGER ticks;
  198011. QueryPerformanceCounter (&ticks);
  198012. const int64 mainCounterAsHiResTicks = (GetTickCount() * hiResTicksPerSecond) / 1000;
  198013. const int64 newOffset = mainCounterAsHiResTicks - ticks.QuadPart;
  198014. // fix for a very obscure PCI hardware bug that can make the counter
  198015. // sometimes jump forwards by a few seconds..
  198016. static int64 hiResTicksOffset = 0;
  198017. const int64 offsetDrift = abs64 (newOffset - hiResTicksOffset);
  198018. if (offsetDrift > (hiResTicksPerSecond >> 1))
  198019. hiResTicksOffset = newOffset;
  198020. return ticks.QuadPart + hiResTicksOffset;
  198021. }
  198022. double Time::getMillisecondCounterHiRes() throw()
  198023. {
  198024. return getHighResolutionTicks() * hiResTicksScaleFactor;
  198025. }
  198026. int64 Time::getHighResolutionTicksPerSecond() throw()
  198027. {
  198028. return hiResTicksPerSecond;
  198029. }
  198030. int64 SystemStats::getClockCycleCounter() throw()
  198031. {
  198032. #if JUCE_USE_INTRINSICS
  198033. // MS intrinsics version...
  198034. return __rdtsc();
  198035. #elif JUCE_GCC
  198036. // GNU inline asm version...
  198037. unsigned int hi = 0, lo = 0;
  198038. __asm__ __volatile__ (
  198039. "xor %%eax, %%eax \n\
  198040. xor %%edx, %%edx \n\
  198041. rdtsc \n\
  198042. movl %%eax, %[lo] \n\
  198043. movl %%edx, %[hi]"
  198044. :
  198045. : [hi] "m" (hi),
  198046. [lo] "m" (lo)
  198047. : "cc", "eax", "ebx", "ecx", "edx", "memory");
  198048. return (int64) ((((uint64) hi) << 32) | lo);
  198049. #else
  198050. // MSVC inline asm version...
  198051. unsigned int hi = 0, lo = 0;
  198052. __asm
  198053. {
  198054. xor eax, eax
  198055. xor edx, edx
  198056. rdtsc
  198057. mov lo, eax
  198058. mov hi, edx
  198059. }
  198060. return (int64) ((((uint64) hi) << 32) | lo);
  198061. #endif
  198062. }
  198063. int SystemStats::getCpuSpeedInMegaherz() throw()
  198064. {
  198065. const int64 cycles = SystemStats::getClockCycleCounter();
  198066. const uint32 millis = Time::getMillisecondCounter();
  198067. int lastResult = 0;
  198068. for (;;)
  198069. {
  198070. int n = 1000000;
  198071. while (--n > 0) {}
  198072. const uint32 millisElapsed = Time::getMillisecondCounter() - millis;
  198073. const int64 cyclesNow = SystemStats::getClockCycleCounter();
  198074. if (millisElapsed > 80)
  198075. {
  198076. const int newResult = (int) (((cyclesNow - cycles) / millisElapsed) / 1000);
  198077. if (millisElapsed > 500 || (lastResult == newResult && newResult > 100))
  198078. return newResult;
  198079. lastResult = newResult;
  198080. }
  198081. }
  198082. }
  198083. bool Time::setSystemTimeToThisTime() const throw()
  198084. {
  198085. SYSTEMTIME st;
  198086. st.wDayOfWeek = 0;
  198087. st.wYear = (WORD) getYear();
  198088. st.wMonth = (WORD) (getMonth() + 1);
  198089. st.wDay = (WORD) getDayOfMonth();
  198090. st.wHour = (WORD) getHours();
  198091. st.wMinute = (WORD) getMinutes();
  198092. st.wSecond = (WORD) getSeconds();
  198093. st.wMilliseconds = (WORD) (millisSinceEpoch % 1000);
  198094. // do this twice because of daylight saving conversion problems - the
  198095. // first one sets it up, the second one kicks it in.
  198096. return SetLocalTime (&st) != 0
  198097. && SetLocalTime (&st) != 0;
  198098. }
  198099. int SystemStats::getPageSize() throw()
  198100. {
  198101. SYSTEM_INFO systemInfo;
  198102. GetSystemInfo (&systemInfo);
  198103. return systemInfo.dwPageSize;
  198104. }
  198105. END_JUCE_NAMESPACE
  198106. /********* End of inlined file: juce_win32_SystemStats.cpp *********/
  198107. /********* Start of inlined file: juce_win32_Threads.cpp *********/
  198108. #ifdef _MSC_VER
  198109. #pragma warning (disable: 4514)
  198110. #pragma warning (push)
  198111. #include <crtdbg.h>
  198112. #endif
  198113. #include <process.h>
  198114. BEGIN_JUCE_NAMESPACE
  198115. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  198116. extern HWND juce_messageWindowHandle;
  198117. #endif
  198118. #ifdef _MSC_VER
  198119. #pragma warning (pop)
  198120. #endif
  198121. CriticalSection::CriticalSection() throw()
  198122. {
  198123. // (just to check the MS haven't changed this structure and broken things...)
  198124. #if _MSC_VER >= 1400
  198125. static_jassert (sizeof (CRITICAL_SECTION) <= sizeof (internal));
  198126. #else
  198127. static_jassert (sizeof (CRITICAL_SECTION) <= 24);
  198128. #endif
  198129. InitializeCriticalSection ((CRITICAL_SECTION*) internal);
  198130. }
  198131. CriticalSection::~CriticalSection() throw()
  198132. {
  198133. DeleteCriticalSection ((CRITICAL_SECTION*) internal);
  198134. }
  198135. void CriticalSection::enter() const throw()
  198136. {
  198137. EnterCriticalSection ((CRITICAL_SECTION*) internal);
  198138. }
  198139. bool CriticalSection::tryEnter() const throw()
  198140. {
  198141. return TryEnterCriticalSection ((CRITICAL_SECTION*) internal) != FALSE;
  198142. }
  198143. void CriticalSection::exit() const throw()
  198144. {
  198145. LeaveCriticalSection ((CRITICAL_SECTION*) internal);
  198146. }
  198147. WaitableEvent::WaitableEvent() throw()
  198148. : internal (CreateEvent (0, FALSE, FALSE, 0))
  198149. {
  198150. }
  198151. WaitableEvent::~WaitableEvent() throw()
  198152. {
  198153. CloseHandle (internal);
  198154. }
  198155. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  198156. {
  198157. return WaitForSingleObject (internal, timeOutMillisecs) == WAIT_OBJECT_0;
  198158. }
  198159. void WaitableEvent::signal() const throw()
  198160. {
  198161. SetEvent (internal);
  198162. }
  198163. void WaitableEvent::reset() const throw()
  198164. {
  198165. ResetEvent (internal);
  198166. }
  198167. void JUCE_API juce_threadEntryPoint (void*);
  198168. static unsigned int __stdcall threadEntryProc (void* userData) throw()
  198169. {
  198170. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  198171. AttachThreadInput (GetWindowThreadProcessId (juce_messageWindowHandle, 0),
  198172. GetCurrentThreadId(), TRUE);
  198173. #endif
  198174. juce_threadEntryPoint (userData);
  198175. _endthreadex(0);
  198176. return 0;
  198177. }
  198178. void juce_CloseThreadHandle (void* handle) throw()
  198179. {
  198180. CloseHandle ((HANDLE) handle);
  198181. }
  198182. void* juce_createThread (void* userData) throw()
  198183. {
  198184. unsigned int threadId;
  198185. return (void*) _beginthreadex (0, 0,
  198186. &threadEntryProc,
  198187. userData,
  198188. 0, &threadId);
  198189. }
  198190. void juce_killThread (void* handle) throw()
  198191. {
  198192. if (handle != 0)
  198193. {
  198194. #ifdef JUCE_DEBUG
  198195. OutputDebugString (_T("** Warning - Forced thread termination **\n"));
  198196. #endif
  198197. TerminateThread (handle, 0);
  198198. }
  198199. }
  198200. void juce_setCurrentThreadName (const String& name) throw()
  198201. {
  198202. #if defined (JUCE_DEBUG) && JUCE_MSVC
  198203. struct
  198204. {
  198205. DWORD dwType;
  198206. LPCSTR szName;
  198207. DWORD dwThreadID;
  198208. DWORD dwFlags;
  198209. } info;
  198210. info.dwType = 0x1000;
  198211. info.szName = name;
  198212. info.dwThreadID = GetCurrentThreadId();
  198213. info.dwFlags = 0;
  198214. #define MS_VC_EXCEPTION 0x406d1388
  198215. __try
  198216. {
  198217. RaiseException (MS_VC_EXCEPTION, 0, sizeof (info) / sizeof (ULONG_PTR), (ULONG_PTR*) &info);
  198218. }
  198219. __except (EXCEPTION_CONTINUE_EXECUTION)
  198220. {}
  198221. #else
  198222. (void) name;
  198223. #endif
  198224. }
  198225. int Thread::getCurrentThreadId() throw()
  198226. {
  198227. return (int) GetCurrentThreadId();
  198228. }
  198229. // priority 1 to 10 where 5=normal, 1=low
  198230. void juce_setThreadPriority (void* threadHandle, int priority) throw()
  198231. {
  198232. int pri = THREAD_PRIORITY_TIME_CRITICAL;
  198233. if (priority < 1)
  198234. pri = THREAD_PRIORITY_IDLE;
  198235. else if (priority < 2)
  198236. pri = THREAD_PRIORITY_LOWEST;
  198237. else if (priority < 5)
  198238. pri = THREAD_PRIORITY_BELOW_NORMAL;
  198239. else if (priority < 7)
  198240. pri = THREAD_PRIORITY_NORMAL;
  198241. else if (priority < 9)
  198242. pri = THREAD_PRIORITY_ABOVE_NORMAL;
  198243. else if (priority < 10)
  198244. pri = THREAD_PRIORITY_HIGHEST;
  198245. if (threadHandle == 0)
  198246. threadHandle = GetCurrentThread();
  198247. SetThreadPriority (threadHandle, pri);
  198248. }
  198249. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask) throw()
  198250. {
  198251. SetThreadAffinityMask (GetCurrentThread(), affinityMask);
  198252. }
  198253. static HANDLE sleepEvent = 0;
  198254. void juce_initialiseThreadEvents() throw()
  198255. {
  198256. if (sleepEvent == 0)
  198257. #ifdef JUCE_DEBUG
  198258. sleepEvent = CreateEvent (0, 0, 0, _T("Juce Sleep Event"));
  198259. #else
  198260. sleepEvent = CreateEvent (0, 0, 0, 0);
  198261. #endif
  198262. }
  198263. void Thread::yield() throw()
  198264. {
  198265. Sleep (0);
  198266. }
  198267. void JUCE_CALLTYPE Thread::sleep (const int millisecs) throw()
  198268. {
  198269. if (millisecs >= 10)
  198270. {
  198271. Sleep (millisecs);
  198272. }
  198273. else
  198274. {
  198275. jassert (sleepEvent != 0);
  198276. // unlike Sleep() this is guaranteed to return to the current thread after
  198277. // the time expires, so we'll use this for short waits, which are more likely
  198278. // to need to be accurate
  198279. WaitForSingleObject (sleepEvent, millisecs);
  198280. }
  198281. }
  198282. static int lastProcessPriority = -1;
  198283. // called by WindowDriver because Windows does wierd things to process priority
  198284. // when you swap apps, and this forces an update when the app is brought to the front.
  198285. void juce_repeatLastProcessPriority() throw()
  198286. {
  198287. if (lastProcessPriority >= 0) // (avoid changing this if it's not been explicitly set by the app..)
  198288. {
  198289. DWORD p;
  198290. switch (lastProcessPriority)
  198291. {
  198292. case Process::LowPriority:
  198293. p = IDLE_PRIORITY_CLASS;
  198294. break;
  198295. case Process::NormalPriority:
  198296. p = NORMAL_PRIORITY_CLASS;
  198297. break;
  198298. case Process::HighPriority:
  198299. p = HIGH_PRIORITY_CLASS;
  198300. break;
  198301. case Process::RealtimePriority:
  198302. p = REALTIME_PRIORITY_CLASS;
  198303. break;
  198304. default:
  198305. jassertfalse // bad priority value
  198306. return;
  198307. }
  198308. SetPriorityClass (GetCurrentProcess(), p);
  198309. }
  198310. }
  198311. void Process::setPriority (ProcessPriority prior)
  198312. {
  198313. if (lastProcessPriority != (int) prior)
  198314. {
  198315. lastProcessPriority = (int) prior;
  198316. juce_repeatLastProcessPriority();
  198317. }
  198318. }
  198319. bool JUCE_API JUCE_CALLTYPE juce_isRunningUnderDebugger() throw()
  198320. {
  198321. return IsDebuggerPresent() != FALSE;
  198322. }
  198323. bool JUCE_CALLTYPE Process::isRunningUnderDebugger() throw()
  198324. {
  198325. return juce_isRunningUnderDebugger();
  198326. }
  198327. void Process::raisePrivilege()
  198328. {
  198329. jassertfalse // xxx not implemented
  198330. }
  198331. void Process::lowerPrivilege()
  198332. {
  198333. jassertfalse // xxx not implemented
  198334. }
  198335. void Process::terminate()
  198336. {
  198337. #if defined (JUCE_DEBUG) && JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  198338. _CrtDumpMemoryLeaks();
  198339. #endif
  198340. // bullet in the head in case there's a problem shutting down..
  198341. ExitProcess (0);
  198342. }
  198343. void* Process::loadDynamicLibrary (const String& name)
  198344. {
  198345. void* result = 0;
  198346. JUCE_TRY
  198347. {
  198348. result = (void*) LoadLibrary (name);
  198349. }
  198350. JUCE_CATCH_ALL
  198351. return result;
  198352. }
  198353. void Process::freeDynamicLibrary (void* h)
  198354. {
  198355. JUCE_TRY
  198356. {
  198357. if (h != 0)
  198358. FreeLibrary ((HMODULE) h);
  198359. }
  198360. JUCE_CATCH_ALL
  198361. }
  198362. void* Process::getProcedureEntryPoint (void* h, const String& name)
  198363. {
  198364. return (h != 0) ? (void*) GetProcAddress ((HMODULE) h, name)
  198365. : 0;
  198366. }
  198367. InterProcessLock::InterProcessLock (const String& name_) throw()
  198368. : internal (0),
  198369. name (name_),
  198370. reentrancyLevel (0)
  198371. {
  198372. }
  198373. InterProcessLock::~InterProcessLock() throw()
  198374. {
  198375. exit();
  198376. }
  198377. bool InterProcessLock::enter (const int timeOutMillisecs) throw()
  198378. {
  198379. if (reentrancyLevel++ == 0)
  198380. {
  198381. internal = CreateMutex (0, TRUE, name);
  198382. if (internal != 0 && GetLastError() == ERROR_ALREADY_EXISTS)
  198383. {
  198384. if (timeOutMillisecs == 0
  198385. || WaitForSingleObject (internal, (timeOutMillisecs < 0) ? INFINITE : timeOutMillisecs)
  198386. == WAIT_TIMEOUT)
  198387. {
  198388. ReleaseMutex (internal);
  198389. CloseHandle (internal);
  198390. internal = 0;
  198391. }
  198392. }
  198393. }
  198394. return (internal != 0);
  198395. }
  198396. void InterProcessLock::exit() throw()
  198397. {
  198398. if (--reentrancyLevel == 0 && internal != 0)
  198399. {
  198400. ReleaseMutex (internal);
  198401. CloseHandle (internal);
  198402. internal = 0;
  198403. }
  198404. }
  198405. END_JUCE_NAMESPACE
  198406. /********* End of inlined file: juce_win32_Threads.cpp *********/
  198407. /********* Start of inlined file: juce_win32_DynamicLibraryLoader.cpp *********/
  198408. BEGIN_JUCE_NAMESPACE
  198409. DynamicLibraryLoader::DynamicLibraryLoader (const String& name)
  198410. {
  198411. libHandle = LoadLibrary (name);
  198412. }
  198413. DynamicLibraryLoader::~DynamicLibraryLoader()
  198414. {
  198415. FreeLibrary ((HMODULE) libHandle);
  198416. }
  198417. void* DynamicLibraryLoader::findProcAddress (const String& functionName)
  198418. {
  198419. return (void*) GetProcAddress ((HMODULE) libHandle, functionName);
  198420. }
  198421. END_JUCE_NAMESPACE
  198422. /********* End of inlined file: juce_win32_DynamicLibraryLoader.cpp *********/
  198423. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  198424. /********* Start of inlined file: juce_win32_ASIO.cpp *********/
  198425. #undef WINDOWS
  198426. #if JUCE_ASIO
  198427. /*
  198428. This is very frustrating - we only need to use a handful of definitions from
  198429. a couple of the header files in Steinberg's ASIO SDK, and it'd be easy to copy
  198430. about 30 lines of code into this cpp file to create a fully stand-alone ASIO
  198431. implementation...
  198432. ..unfortunately that would break Steinberg's license agreement for use of
  198433. their SDK, so I'm not allowed to do this.
  198434. This means that anyone who wants to use JUCE's ASIO abilities will have to:
  198435. 1) Agree to Steinberg's licensing terms and download the ASIO SDK
  198436. (see www.steinberg.net/Steinberg/Developers.asp).
  198437. 2) Rebuild the whole of JUCE, setting the global definition JUCE_ASIO (you
  198438. can un-comment the "#define JUCE_ASIO" line in juce_Config.h
  198439. if you prefer). Make sure that your header search path will find the
  198440. iasiodrv.h file that comes with the SDK. (Only about 2-3 of the SDK header
  198441. files are actually needed - so to simplify things, you could just copy
  198442. these into your JUCE directory).
  198443. */
  198444. #include "iasiodrv.h" // if you're compiling and this line causes an error because
  198445. // you don't have the ASIO SDK installed, you can disable ASIO
  198446. // support by commenting-out the "#define JUCE_ASIO" line in
  198447. // juce_Config.h
  198448. BEGIN_JUCE_NAMESPACE
  198449. // #define ASIO_DEBUGGING
  198450. #ifdef ASIO_DEBUGGING
  198451. #define log(a) { Logger::writeToLog (a); DBG (a) }
  198452. #else
  198453. #define log(a) {}
  198454. #endif
  198455. #ifdef ASIO_DEBUGGING
  198456. static void logError (const String& context, long error)
  198457. {
  198458. String err ("unknown error");
  198459. if (error == ASE_NotPresent)
  198460. err = "Not Present";
  198461. else if (error == ASE_HWMalfunction)
  198462. err = "Hardware Malfunction";
  198463. else if (error == ASE_InvalidParameter)
  198464. err = "Invalid Parameter";
  198465. else if (error == ASE_InvalidMode)
  198466. err = "Invalid Mode";
  198467. else if (error == ASE_SPNotAdvancing)
  198468. err = "Sample position not advancing";
  198469. else if (error == ASE_NoClock)
  198470. err = "No Clock";
  198471. else if (error == ASE_NoMemory)
  198472. err = "Out of memory";
  198473. log (T("!!error: ") + context + T(" - ") + err);
  198474. }
  198475. #else
  198476. #define logError(a, b) {}
  198477. #endif
  198478. class ASIOAudioIODevice;
  198479. static ASIOAudioIODevice* volatile currentASIODev[3] = { 0, 0, 0 };
  198480. static const int maxASIOChannels = 160;
  198481. class JUCE_API ASIOAudioIODevice : public AudioIODevice,
  198482. private Thread,
  198483. private Timer
  198484. {
  198485. public:
  198486. Component ourWindow;
  198487. ASIOAudioIODevice (const String& name_, const CLSID classId_, const int slotNumber)
  198488. : AudioIODevice (name_, T("ASIO")),
  198489. Thread ("Juce ASIO"),
  198490. asioObject (0),
  198491. classId (classId_),
  198492. currentBitDepth (16),
  198493. currentSampleRate (0),
  198494. tempBuffer (0),
  198495. isOpen_ (false),
  198496. isStarted (false),
  198497. postOutput (true),
  198498. insideControlPanelModalLoop (false),
  198499. shouldUsePreferredSize (false)
  198500. {
  198501. name = name_;
  198502. ourWindow.addToDesktop (0);
  198503. windowHandle = ourWindow.getWindowHandle();
  198504. jassert (currentASIODev [slotNumber] == 0);
  198505. currentASIODev [slotNumber] = this;
  198506. openDevice();
  198507. }
  198508. ~ASIOAudioIODevice()
  198509. {
  198510. for (int i = 0; i < numElementsInArray (currentASIODev); ++i)
  198511. if (currentASIODev[i] == this)
  198512. currentASIODev[i] = 0;
  198513. close();
  198514. log ("ASIO - exiting");
  198515. removeCurrentDriver();
  198516. juce_free (tempBuffer);
  198517. }
  198518. void updateSampleRates()
  198519. {
  198520. // find a list of sample rates..
  198521. const double possibleSampleRates[] = { 44100.0, 48000.0, 88200.0, 96000.0, 176400.0, 192000.0 };
  198522. sampleRates.clear();
  198523. if (asioObject != 0)
  198524. {
  198525. for (int index = 0; index < numElementsInArray (possibleSampleRates); ++index)
  198526. {
  198527. const long err = asioObject->canSampleRate (possibleSampleRates[index]);
  198528. if (err == 0)
  198529. {
  198530. sampleRates.add ((int) possibleSampleRates[index]);
  198531. log (T("rate: ") + String ((int) possibleSampleRates[index]));
  198532. }
  198533. else if (err != ASE_NoClock)
  198534. {
  198535. logError (T("CanSampleRate"), err);
  198536. }
  198537. }
  198538. if (sampleRates.size() == 0)
  198539. {
  198540. double cr = 0;
  198541. const long err = asioObject->getSampleRate (&cr);
  198542. log (T("No sample rates supported - current rate: ") + String ((int) cr));
  198543. if (err == 0)
  198544. sampleRates.add ((int) cr);
  198545. }
  198546. }
  198547. }
  198548. const StringArray getOutputChannelNames()
  198549. {
  198550. return outputChannelNames;
  198551. }
  198552. const StringArray getInputChannelNames()
  198553. {
  198554. return inputChannelNames;
  198555. }
  198556. int getNumSampleRates()
  198557. {
  198558. return sampleRates.size();
  198559. }
  198560. double getSampleRate (int index)
  198561. {
  198562. return sampleRates [index];
  198563. }
  198564. int getNumBufferSizesAvailable()
  198565. {
  198566. return bufferSizes.size();
  198567. }
  198568. int getBufferSizeSamples (int index)
  198569. {
  198570. return bufferSizes [index];
  198571. }
  198572. int getDefaultBufferSize()
  198573. {
  198574. return preferredSize;
  198575. }
  198576. const String open (const BitArray& inputChannels,
  198577. const BitArray& outputChannels,
  198578. double sr,
  198579. int bufferSizeSamples)
  198580. {
  198581. close();
  198582. currentCallback = 0;
  198583. if (bufferSizeSamples <= 0)
  198584. shouldUsePreferredSize = true;
  198585. if (asioObject == 0 || ! isASIOOpen)
  198586. {
  198587. log ("Warning: device not open");
  198588. const String err (openDevice());
  198589. if (asioObject == 0 || ! isASIOOpen)
  198590. return err;
  198591. }
  198592. isStarted = false;
  198593. bufferIndex = -1;
  198594. long err = 0;
  198595. long newPreferredSize = 0;
  198596. // if the preferred size has just changed, assume it's a control panel thing and use it as the new value.
  198597. minSize = 0;
  198598. maxSize = 0;
  198599. newPreferredSize = 0;
  198600. granularity = 0;
  198601. if (asioObject->getBufferSize (&minSize, &maxSize, &newPreferredSize, &granularity) == 0)
  198602. {
  198603. if (preferredSize != 0 && newPreferredSize != 0 && newPreferredSize != preferredSize)
  198604. shouldUsePreferredSize = true;
  198605. preferredSize = newPreferredSize;
  198606. }
  198607. // unfortunate workaround for certain manufacturers whose drivers crash horribly if you make
  198608. // dynamic changes to the buffer size...
  198609. shouldUsePreferredSize = shouldUsePreferredSize
  198610. || getName().containsIgnoreCase (T("Digidesign"));
  198611. if (shouldUsePreferredSize)
  198612. {
  198613. log ("Using preferred size for buffer..");
  198614. if ((err = asioObject->getBufferSize (&minSize, &maxSize, &preferredSize, &granularity)) == 0)
  198615. {
  198616. bufferSizeSamples = preferredSize;
  198617. }
  198618. else
  198619. {
  198620. bufferSizeSamples = 1024;
  198621. logError ("GetBufferSize1", err);
  198622. }
  198623. shouldUsePreferredSize = false;
  198624. }
  198625. int sampleRate = roundDoubleToInt (sr);
  198626. currentSampleRate = sampleRate;
  198627. currentBlockSizeSamples = bufferSizeSamples;
  198628. currentChansOut.clear();
  198629. currentChansIn.clear();
  198630. zeromem (inBuffers, sizeof (inBuffers));
  198631. zeromem (outBuffers, sizeof (outBuffers));
  198632. updateSampleRates();
  198633. if (sampleRate == 0 || (sampleRates.size() > 0 && ! sampleRates.contains (sampleRate)))
  198634. sampleRate = sampleRates[0];
  198635. jassert (sampleRate != 0);
  198636. if (sampleRate == 0)
  198637. sampleRate = 44100;
  198638. long numSources = 32;
  198639. ASIOClockSource clocks[32];
  198640. zeromem (clocks, sizeof (clocks));
  198641. asioObject->getClockSources (clocks, &numSources);
  198642. bool isSourceSet = false;
  198643. // careful not to remove this loop because it does more than just logging!
  198644. int i;
  198645. for (i = 0; i < numSources; ++i)
  198646. {
  198647. String s ("clock: ");
  198648. s += clocks[i].name;
  198649. if (clocks[i].isCurrentSource)
  198650. {
  198651. isSourceSet = true;
  198652. s << " (cur)";
  198653. }
  198654. log (s);
  198655. }
  198656. if (numSources > 1 && ! isSourceSet)
  198657. {
  198658. log ("setting clock source");
  198659. asioObject->setClockSource (clocks[0].index);
  198660. Thread::sleep (20);
  198661. }
  198662. else
  198663. {
  198664. if (numSources == 0)
  198665. {
  198666. log ("ASIO - no clock sources!");
  198667. }
  198668. }
  198669. double cr = 0;
  198670. err = asioObject->getSampleRate (&cr);
  198671. if (err == 0)
  198672. {
  198673. currentSampleRate = cr;
  198674. }
  198675. else
  198676. {
  198677. logError ("GetSampleRate", err);
  198678. currentSampleRate = 0;
  198679. }
  198680. error = String::empty;
  198681. needToReset = false;
  198682. isReSync = false;
  198683. err = 0;
  198684. bool buffersCreated = false;
  198685. if (currentSampleRate != sampleRate)
  198686. {
  198687. log (T("ASIO samplerate: ") + String (currentSampleRate) + T(" to ") + String (sampleRate));
  198688. err = asioObject->setSampleRate (sampleRate);
  198689. if (err == ASE_NoClock && numSources > 0)
  198690. {
  198691. log ("trying to set a clock source..");
  198692. Thread::sleep (10);
  198693. err = asioObject->setClockSource (clocks[0].index);
  198694. if (err != 0)
  198695. {
  198696. logError ("SetClock", err);
  198697. }
  198698. Thread::sleep (10);
  198699. err = asioObject->setSampleRate (sampleRate);
  198700. }
  198701. }
  198702. if (err == 0)
  198703. {
  198704. currentSampleRate = sampleRate;
  198705. if (needToReset)
  198706. {
  198707. if (isReSync)
  198708. {
  198709. log ("Resync request");
  198710. }
  198711. log ("! Resetting ASIO after sample rate change");
  198712. removeCurrentDriver();
  198713. loadDriver();
  198714. const String error (initDriver());
  198715. if (error.isNotEmpty())
  198716. {
  198717. log (T("ASIOInit: ") + error);
  198718. }
  198719. needToReset = false;
  198720. isReSync = false;
  198721. }
  198722. numActiveInputChans = 0;
  198723. numActiveOutputChans = 0;
  198724. ASIOBufferInfo* info = bufferInfos;
  198725. int i;
  198726. for (i = 0; i < totalNumInputChans; ++i)
  198727. {
  198728. if (inputChannels[i])
  198729. {
  198730. currentChansIn.setBit (i);
  198731. info->isInput = 1;
  198732. info->channelNum = i;
  198733. info->buffers[0] = info->buffers[1] = 0;
  198734. ++info;
  198735. ++numActiveInputChans;
  198736. }
  198737. }
  198738. for (i = 0; i < totalNumOutputChans; ++i)
  198739. {
  198740. if (outputChannels[i])
  198741. {
  198742. currentChansOut.setBit (i);
  198743. info->isInput = 0;
  198744. info->channelNum = i;
  198745. info->buffers[0] = info->buffers[1] = 0;
  198746. ++info;
  198747. ++numActiveOutputChans;
  198748. }
  198749. }
  198750. const int totalBuffers = numActiveInputChans + numActiveOutputChans;
  198751. callbacks.sampleRateDidChange = &sampleRateChangedCallback;
  198752. if (currentASIODev[0] == this)
  198753. {
  198754. callbacks.bufferSwitch = &bufferSwitchCallback0;
  198755. callbacks.asioMessage = &asioMessagesCallback0;
  198756. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback0;
  198757. }
  198758. else if (currentASIODev[1] == this)
  198759. {
  198760. callbacks.bufferSwitch = &bufferSwitchCallback1;
  198761. callbacks.asioMessage = &asioMessagesCallback1;
  198762. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback1;
  198763. }
  198764. else if (currentASIODev[2] == this)
  198765. {
  198766. callbacks.bufferSwitch = &bufferSwitchCallback2;
  198767. callbacks.asioMessage = &asioMessagesCallback2;
  198768. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback2;
  198769. }
  198770. else
  198771. {
  198772. jassertfalse
  198773. }
  198774. log ("disposing buffers");
  198775. err = asioObject->disposeBuffers();
  198776. log (T("creating buffers: ") + String (totalBuffers) + T(", ") + String (currentBlockSizeSamples));
  198777. err = asioObject->createBuffers (bufferInfos,
  198778. totalBuffers,
  198779. currentBlockSizeSamples,
  198780. &callbacks);
  198781. if (err != 0)
  198782. {
  198783. currentBlockSizeSamples = preferredSize;
  198784. logError ("create buffers 2", err);
  198785. asioObject->disposeBuffers();
  198786. err = asioObject->createBuffers (bufferInfos,
  198787. totalBuffers,
  198788. currentBlockSizeSamples,
  198789. &callbacks);
  198790. }
  198791. if (err == 0)
  198792. {
  198793. buffersCreated = true;
  198794. jassert (! isThreadRunning());
  198795. juce_free (tempBuffer);
  198796. tempBuffer = (float*) juce_calloc (totalBuffers * currentBlockSizeSamples * sizeof (float) + 128);
  198797. int n = 0;
  198798. Array <int> types;
  198799. currentBitDepth = 16;
  198800. for (i = 0; i < jmin (totalNumInputChans, maxASIOChannels); ++i)
  198801. {
  198802. if (inputChannels[i])
  198803. {
  198804. inBuffers[n] = tempBuffer + (currentBlockSizeSamples * n);
  198805. ASIOChannelInfo channelInfo;
  198806. zerostruct (channelInfo);
  198807. channelInfo.channel = i;
  198808. channelInfo.isInput = 1;
  198809. asioObject->getChannelInfo (&channelInfo);
  198810. types.addIfNotAlreadyThere (channelInfo.type);
  198811. typeToFormatParameters (channelInfo.type,
  198812. inputChannelBitDepths[n],
  198813. inputChannelBytesPerSample[n],
  198814. inputChannelIsFloat[n],
  198815. inputChannelLittleEndian[n]);
  198816. currentBitDepth = jmax (currentBitDepth, inputChannelBitDepths[n]);
  198817. ++n;
  198818. }
  198819. }
  198820. jassert (numActiveInputChans == n);
  198821. n = 0;
  198822. for (i = 0; i < jmin (totalNumOutputChans, maxASIOChannels); ++i)
  198823. {
  198824. if (outputChannels[i])
  198825. {
  198826. outBuffers[n] = tempBuffer + (currentBlockSizeSamples * (numActiveInputChans + n));
  198827. ASIOChannelInfo channelInfo;
  198828. zerostruct (channelInfo);
  198829. channelInfo.channel = i;
  198830. channelInfo.isInput = 0;
  198831. asioObject->getChannelInfo (&channelInfo);
  198832. types.addIfNotAlreadyThere (channelInfo.type);
  198833. typeToFormatParameters (channelInfo.type,
  198834. outputChannelBitDepths[n],
  198835. outputChannelBytesPerSample[n],
  198836. outputChannelIsFloat[n],
  198837. outputChannelLittleEndian[n]);
  198838. currentBitDepth = jmax (currentBitDepth, outputChannelBitDepths[n]);
  198839. ++n;
  198840. }
  198841. }
  198842. jassert (numActiveOutputChans == n);
  198843. for (i = types.size(); --i >= 0;)
  198844. {
  198845. log (T("channel format: ") + String (types[i]));
  198846. }
  198847. jassert (n <= totalBuffers);
  198848. for (i = 0; i < numActiveOutputChans; ++i)
  198849. {
  198850. const int size = currentBlockSizeSamples * (outputChannelBitDepths[i] >> 3);
  198851. if (bufferInfos [numActiveInputChans + i].buffers[0] == 0
  198852. || bufferInfos [numActiveInputChans + i].buffers[1] == 0)
  198853. {
  198854. log ("!! Null buffers");
  198855. }
  198856. else
  198857. {
  198858. zeromem (bufferInfos[numActiveInputChans + i].buffers[0], size);
  198859. zeromem (bufferInfos[numActiveInputChans + i].buffers[1], size);
  198860. }
  198861. }
  198862. inputLatency = outputLatency = 0;
  198863. if (asioObject->getLatencies (&inputLatency, &outputLatency) != 0)
  198864. {
  198865. log ("ASIO - no latencies");
  198866. }
  198867. else
  198868. {
  198869. log (T("ASIO latencies: ")
  198870. + String ((int) outputLatency)
  198871. + T(", ")
  198872. + String ((int) inputLatency));
  198873. }
  198874. isOpen_ = true;
  198875. isThreadReady = false;
  198876. log ("starting ASIO");
  198877. calledback = false;
  198878. err = asioObject->start();
  198879. if (err != 0)
  198880. {
  198881. isOpen_ = false;
  198882. log ("ASIO - stop on failure");
  198883. Thread::sleep (10);
  198884. asioObject->stop();
  198885. error = "Can't start device";
  198886. Thread::sleep (10);
  198887. }
  198888. else
  198889. {
  198890. int count = 300;
  198891. while (--count > 0 && ! calledback)
  198892. Thread::sleep (10);
  198893. isStarted = true;
  198894. if (! calledback)
  198895. {
  198896. error = "Device didn't start correctly";
  198897. log ("ASIO didn't callback - stopping..");
  198898. asioObject->stop();
  198899. }
  198900. }
  198901. }
  198902. else
  198903. {
  198904. error = "Can't create i/o buffers";
  198905. }
  198906. }
  198907. else
  198908. {
  198909. error = "Can't set sample rate: ";
  198910. error << sampleRate;
  198911. }
  198912. if (error.isNotEmpty())
  198913. {
  198914. logError (error, err);
  198915. if (asioObject != 0 && buffersCreated)
  198916. asioObject->disposeBuffers();
  198917. Thread::sleep (20);
  198918. isStarted = false;
  198919. isOpen_ = false;
  198920. close();
  198921. }
  198922. needToReset = false;
  198923. isReSync = false;
  198924. return error;
  198925. }
  198926. void close()
  198927. {
  198928. error = String::empty;
  198929. stopTimer();
  198930. stop();
  198931. if (isASIOOpen && isOpen_)
  198932. {
  198933. const ScopedLock sl (callbackLock);
  198934. isOpen_ = false;
  198935. isStarted = false;
  198936. needToReset = false;
  198937. isReSync = false;
  198938. log ("ASIO - stopping");
  198939. if (asioObject != 0)
  198940. {
  198941. Thread::sleep (20);
  198942. asioObject->stop();
  198943. Thread::sleep (10);
  198944. asioObject->disposeBuffers();
  198945. }
  198946. Thread::sleep (10);
  198947. }
  198948. }
  198949. bool isOpen()
  198950. {
  198951. return isOpen_ || insideControlPanelModalLoop;
  198952. }
  198953. int getCurrentBufferSizeSamples()
  198954. {
  198955. return currentBlockSizeSamples;
  198956. }
  198957. double getCurrentSampleRate()
  198958. {
  198959. return currentSampleRate;
  198960. }
  198961. const BitArray getActiveOutputChannels() const
  198962. {
  198963. return currentChansOut;
  198964. }
  198965. const BitArray getActiveInputChannels() const
  198966. {
  198967. return currentChansIn;
  198968. }
  198969. int getCurrentBitDepth()
  198970. {
  198971. return currentBitDepth;
  198972. }
  198973. int getOutputLatencyInSamples()
  198974. {
  198975. return outputLatency + currentBlockSizeSamples / 4;
  198976. }
  198977. int getInputLatencyInSamples()
  198978. {
  198979. return inputLatency + currentBlockSizeSamples / 4;
  198980. }
  198981. void start (AudioIODeviceCallback* callback)
  198982. {
  198983. if (callback != 0)
  198984. {
  198985. callback->audioDeviceAboutToStart (this);
  198986. const ScopedLock sl (callbackLock);
  198987. currentCallback = callback;
  198988. }
  198989. }
  198990. void stop()
  198991. {
  198992. AudioIODeviceCallback* const lastCallback = currentCallback;
  198993. {
  198994. const ScopedLock sl (callbackLock);
  198995. currentCallback = 0;
  198996. }
  198997. if (lastCallback != 0)
  198998. lastCallback->audioDeviceStopped();
  198999. }
  199000. bool isPlaying()
  199001. {
  199002. return isASIOOpen && (currentCallback != 0);
  199003. }
  199004. const String getLastError()
  199005. {
  199006. return error;
  199007. }
  199008. bool hasControlPanel() const
  199009. {
  199010. return true;
  199011. }
  199012. bool showControlPanel()
  199013. {
  199014. log ("ASIO - showing control panel");
  199015. Component modalWindow (String::empty);
  199016. modalWindow.setOpaque (true);
  199017. modalWindow.addToDesktop (0);
  199018. modalWindow.enterModalState();
  199019. bool done = false;
  199020. JUCE_TRY
  199021. {
  199022. close();
  199023. insideControlPanelModalLoop = true;
  199024. const uint32 started = Time::getMillisecondCounter();
  199025. if (asioObject != 0)
  199026. {
  199027. asioObject->controlPanel();
  199028. const int spent = (int) Time::getMillisecondCounter() - (int) started;
  199029. log (T("spent: ") + String (spent));
  199030. if (spent > 300)
  199031. {
  199032. shouldUsePreferredSize = true;
  199033. done = true;
  199034. }
  199035. }
  199036. }
  199037. JUCE_CATCH_ALL
  199038. insideControlPanelModalLoop = false;
  199039. return done;
  199040. }
  199041. void run()
  199042. {
  199043. isThreadReady = true;
  199044. for (;;)
  199045. {
  199046. event1.wait();
  199047. if (threadShouldExit())
  199048. break;
  199049. processBuffer();
  199050. }
  199051. if (bufferIndex < 0)
  199052. {
  199053. log ("! ASIO callback never called");
  199054. }
  199055. }
  199056. void resetRequest() throw()
  199057. {
  199058. needToReset = true;
  199059. }
  199060. void resyncRequest() throw()
  199061. {
  199062. needToReset = true;
  199063. isReSync = true;
  199064. }
  199065. void timerCallback()
  199066. {
  199067. if (! insideControlPanelModalLoop)
  199068. {
  199069. stopTimer();
  199070. // used to cause a reset
  199071. log ("! ASIO restart request!");
  199072. if (isOpen_)
  199073. {
  199074. AudioIODeviceCallback* const oldCallback = currentCallback;
  199075. close();
  199076. open (currentChansIn, currentChansOut,
  199077. currentSampleRate, currentBlockSizeSamples);
  199078. if (oldCallback != 0)
  199079. start (oldCallback);
  199080. }
  199081. }
  199082. else
  199083. {
  199084. startTimer (100);
  199085. }
  199086. }
  199087. juce_UseDebuggingNewOperator
  199088. private:
  199089. IASIO* volatile asioObject;
  199090. ASIOCallbacks callbacks;
  199091. void* windowHandle;
  199092. CLSID classId;
  199093. String error;
  199094. long totalNumInputChans, totalNumOutputChans;
  199095. StringArray inputChannelNames, outputChannelNames;
  199096. Array<int> sampleRates, bufferSizes;
  199097. long inputLatency, outputLatency;
  199098. long minSize, maxSize, preferredSize, granularity;
  199099. int volatile currentBlockSizeSamples;
  199100. int volatile currentBitDepth;
  199101. double volatile currentSampleRate;
  199102. BitArray currentChansOut, currentChansIn;
  199103. AudioIODeviceCallback* volatile currentCallback;
  199104. CriticalSection callbackLock;
  199105. ASIOBufferInfo bufferInfos [maxASIOChannels];
  199106. float* inBuffers [maxASIOChannels];
  199107. float* outBuffers [maxASIOChannels];
  199108. int inputChannelBitDepths [maxASIOChannels];
  199109. int outputChannelBitDepths [maxASIOChannels];
  199110. int inputChannelBytesPerSample [maxASIOChannels];
  199111. int outputChannelBytesPerSample [maxASIOChannels];
  199112. bool inputChannelIsFloat [maxASIOChannels];
  199113. bool outputChannelIsFloat [maxASIOChannels];
  199114. bool inputChannelLittleEndian [maxASIOChannels];
  199115. bool outputChannelLittleEndian [maxASIOChannels];
  199116. WaitableEvent event1;
  199117. float* tempBuffer;
  199118. int volatile bufferIndex, numActiveInputChans, numActiveOutputChans;
  199119. bool isOpen_, isStarted;
  199120. bool volatile isASIOOpen;
  199121. bool volatile calledback;
  199122. bool volatile littleEndian, postOutput, needToReset, isReSync, isThreadReady;
  199123. bool volatile insideControlPanelModalLoop;
  199124. bool volatile shouldUsePreferredSize;
  199125. void removeCurrentDriver()
  199126. {
  199127. if (asioObject != 0)
  199128. {
  199129. asioObject->Release();
  199130. asioObject = 0;
  199131. }
  199132. }
  199133. bool loadDriver()
  199134. {
  199135. removeCurrentDriver();
  199136. JUCE_TRY
  199137. {
  199138. if (CoCreateInstance (classId, 0, CLSCTX_INPROC_SERVER,
  199139. classId, (void**) &asioObject) == S_OK)
  199140. {
  199141. return true;
  199142. }
  199143. }
  199144. JUCE_CATCH_ALL
  199145. asioObject = 0;
  199146. return false;
  199147. }
  199148. const String initDriver()
  199149. {
  199150. if (asioObject != 0)
  199151. {
  199152. char buffer [256];
  199153. zeromem (buffer, sizeof (buffer));
  199154. if (! asioObject->init (windowHandle))
  199155. {
  199156. asioObject->getErrorMessage (buffer);
  199157. return String (buffer, sizeof (buffer) - 1);
  199158. }
  199159. // just in case any daft drivers expect this to be called..
  199160. asioObject->getDriverName (buffer);
  199161. return String::empty;
  199162. }
  199163. return "No Driver";
  199164. }
  199165. const String openDevice()
  199166. {
  199167. // use this in case the driver starts opening dialog boxes..
  199168. Component modalWindow (String::empty);
  199169. modalWindow.setOpaque (true);
  199170. modalWindow.addToDesktop (0);
  199171. modalWindow.enterModalState();
  199172. // open the device and get its info..
  199173. log (T("opening ASIO device: ") + getName());
  199174. needToReset = false;
  199175. isReSync = false;
  199176. outputChannelNames.clear();
  199177. inputChannelNames.clear();
  199178. bufferSizes.clear();
  199179. sampleRates.clear();
  199180. isASIOOpen = false;
  199181. isOpen_ = false;
  199182. totalNumInputChans = 0;
  199183. totalNumOutputChans = 0;
  199184. numActiveInputChans = 0;
  199185. numActiveOutputChans = 0;
  199186. currentCallback = 0;
  199187. error = String::empty;
  199188. if (getName().isEmpty())
  199189. return error;
  199190. long err = 0;
  199191. if (loadDriver())
  199192. {
  199193. if ((error = initDriver()).isEmpty())
  199194. {
  199195. numActiveInputChans = 0;
  199196. numActiveOutputChans = 0;
  199197. totalNumInputChans = 0;
  199198. totalNumOutputChans = 0;
  199199. if (asioObject != 0
  199200. && (err = asioObject->getChannels (&totalNumInputChans, &totalNumOutputChans)) == 0)
  199201. {
  199202. log (String ((int) totalNumInputChans) + T(" in, ") + String ((int) totalNumOutputChans) + T(" out"));
  199203. if ((err = asioObject->getBufferSize (&minSize, &maxSize, &preferredSize, &granularity)) == 0)
  199204. {
  199205. // find a list of buffer sizes..
  199206. log (String ((int) minSize) + T(" ") + String ((int) maxSize) + T(" ") + String ((int)preferredSize) + T(" ") + String ((int)granularity));
  199207. if (granularity >= 0)
  199208. {
  199209. granularity = jmax (1, (int) granularity);
  199210. for (int i = jmax (minSize, (int) granularity); i < jmin (6400, maxSize); i += granularity)
  199211. bufferSizes.addIfNotAlreadyThere (granularity * (i / granularity));
  199212. }
  199213. else if (granularity < 0)
  199214. {
  199215. for (int i = 0; i < 18; ++i)
  199216. {
  199217. const int s = (1 << i);
  199218. if (s >= minSize && s <= maxSize)
  199219. bufferSizes.add (s);
  199220. }
  199221. }
  199222. if (! bufferSizes.contains (preferredSize))
  199223. bufferSizes.insert (0, preferredSize);
  199224. double currentRate = 0;
  199225. asioObject->getSampleRate (&currentRate);
  199226. if (currentRate <= 0.0 || currentRate > 192001.0)
  199227. {
  199228. log ("setting sample rate");
  199229. err = asioObject->setSampleRate (44100.0);
  199230. if (err != 0)
  199231. {
  199232. logError ("setting sample rate", err);
  199233. }
  199234. asioObject->getSampleRate (&currentRate);
  199235. }
  199236. currentSampleRate = currentRate;
  199237. postOutput = (asioObject->outputReady() == 0);
  199238. if (postOutput)
  199239. {
  199240. log ("ASIO outputReady = ok");
  199241. }
  199242. updateSampleRates();
  199243. // ..because cubase does it at this point
  199244. inputLatency = outputLatency = 0;
  199245. if (asioObject->getLatencies (&inputLatency, &outputLatency) != 0)
  199246. {
  199247. log ("ASIO - no latencies");
  199248. }
  199249. log (String ("latencies: ")
  199250. + String ((int) inputLatency)
  199251. + T(", ") + String ((int) outputLatency));
  199252. // create some dummy buffers now.. because cubase does..
  199253. numActiveInputChans = 0;
  199254. numActiveOutputChans = 0;
  199255. ASIOBufferInfo* info = bufferInfos;
  199256. int i, numChans = 0;
  199257. for (i = 0; i < jmin (2, totalNumInputChans); ++i)
  199258. {
  199259. info->isInput = 1;
  199260. info->channelNum = i;
  199261. info->buffers[0] = info->buffers[1] = 0;
  199262. ++info;
  199263. ++numChans;
  199264. }
  199265. const int outputBufferIndex = numChans;
  199266. for (i = 0; i < jmin (2, totalNumOutputChans); ++i)
  199267. {
  199268. info->isInput = 0;
  199269. info->channelNum = i;
  199270. info->buffers[0] = info->buffers[1] = 0;
  199271. ++info;
  199272. ++numChans;
  199273. }
  199274. callbacks.sampleRateDidChange = &sampleRateChangedCallback;
  199275. if (currentASIODev[0] == this)
  199276. {
  199277. callbacks.bufferSwitch = &bufferSwitchCallback0;
  199278. callbacks.asioMessage = &asioMessagesCallback0;
  199279. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback0;
  199280. }
  199281. else if (currentASIODev[1] == this)
  199282. {
  199283. callbacks.bufferSwitch = &bufferSwitchCallback1;
  199284. callbacks.asioMessage = &asioMessagesCallback1;
  199285. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback1;
  199286. }
  199287. else if (currentASIODev[2] == this)
  199288. {
  199289. callbacks.bufferSwitch = &bufferSwitchCallback2;
  199290. callbacks.asioMessage = &asioMessagesCallback2;
  199291. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback2;
  199292. }
  199293. else
  199294. {
  199295. jassertfalse
  199296. }
  199297. log (T("creating buffers (dummy): ") + String (numChans)
  199298. + T(", ") + String ((int) preferredSize));
  199299. if (preferredSize > 0)
  199300. {
  199301. err = asioObject->createBuffers (bufferInfos, numChans, preferredSize, &callbacks);
  199302. if (err != 0)
  199303. {
  199304. logError ("dummy buffers", err);
  199305. }
  199306. }
  199307. long newInps = 0, newOuts = 0;
  199308. asioObject->getChannels (&newInps, &newOuts);
  199309. if (totalNumInputChans != newInps || totalNumOutputChans != newOuts)
  199310. {
  199311. totalNumInputChans = newInps;
  199312. totalNumOutputChans = newOuts;
  199313. log (String ((int) totalNumInputChans) + T(" in; ")
  199314. + String ((int) totalNumOutputChans) + T(" out"));
  199315. }
  199316. updateSampleRates();
  199317. ASIOChannelInfo channelInfo;
  199318. channelInfo.type = 0;
  199319. for (i = 0; i < totalNumInputChans; ++i)
  199320. {
  199321. zerostruct (channelInfo);
  199322. channelInfo.channel = i;
  199323. channelInfo.isInput = 1;
  199324. asioObject->getChannelInfo (&channelInfo);
  199325. inputChannelNames.add (String (channelInfo.name));
  199326. }
  199327. for (i = 0; i < totalNumOutputChans; ++i)
  199328. {
  199329. zerostruct (channelInfo);
  199330. channelInfo.channel = i;
  199331. channelInfo.isInput = 0;
  199332. asioObject->getChannelInfo (&channelInfo);
  199333. outputChannelNames.add (String (channelInfo.name));
  199334. typeToFormatParameters (channelInfo.type,
  199335. outputChannelBitDepths[i],
  199336. outputChannelBytesPerSample[i],
  199337. outputChannelIsFloat[i],
  199338. outputChannelLittleEndian[i]);
  199339. if (i < 2)
  199340. {
  199341. // clear the channels that are used with the dummy stuff
  199342. const int bytesPerBuffer = preferredSize * (outputChannelBitDepths[i] >> 3);
  199343. zeromem (bufferInfos [outputBufferIndex + i].buffers[0], bytesPerBuffer);
  199344. zeromem (bufferInfos [outputBufferIndex + i].buffers[1], bytesPerBuffer);
  199345. }
  199346. }
  199347. outputChannelNames.trim();
  199348. inputChannelNames.trim();
  199349. outputChannelNames.appendNumbersToDuplicates (false, true);
  199350. inputChannelNames.appendNumbersToDuplicates (false, true);
  199351. // start and stop because cubase does it..
  199352. asioObject->getLatencies (&inputLatency, &outputLatency);
  199353. if ((err = asioObject->start()) != 0)
  199354. {
  199355. // ignore an error here, as it might start later after setting other stuff up
  199356. logError ("ASIO start", err);
  199357. }
  199358. Thread::sleep (100);
  199359. asioObject->stop();
  199360. }
  199361. else
  199362. {
  199363. error = "Can't detect buffer sizes";
  199364. }
  199365. }
  199366. else
  199367. {
  199368. error = "Can't detect asio channels";
  199369. }
  199370. }
  199371. }
  199372. else
  199373. {
  199374. error = "No such device";
  199375. }
  199376. if (error.isNotEmpty())
  199377. {
  199378. logError (error, err);
  199379. if (asioObject != 0)
  199380. asioObject->disposeBuffers();
  199381. removeCurrentDriver();
  199382. isASIOOpen = false;
  199383. }
  199384. else
  199385. {
  199386. isASIOOpen = true;
  199387. log ("ASIO device open");
  199388. }
  199389. isOpen_ = false;
  199390. needToReset = false;
  199391. isReSync = false;
  199392. return error;
  199393. }
  199394. void callback (const long index) throw()
  199395. {
  199396. if (isStarted)
  199397. {
  199398. bufferIndex = index;
  199399. processBuffer();
  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 i;
  199432. for (i = 0; i < numActiveInputChans; ++i)
  199433. {
  199434. float* const dst = inBuffers[i];
  199435. jassert (dst != 0);
  199436. const char* const src = (const char*) (infos[i].buffers[bi]);
  199437. if (inputChannelIsFloat[i])
  199438. {
  199439. memcpy (dst, src, samps * sizeof (float));
  199440. }
  199441. else
  199442. {
  199443. jassert (dst == tempBuffer + (samps * i));
  199444. switch (inputChannelBitDepths[i])
  199445. {
  199446. case 16:
  199447. convertInt16ToFloat (src, dst, inputChannelBytesPerSample[i],
  199448. samps, inputChannelLittleEndian[i]);
  199449. break;
  199450. case 24:
  199451. convertInt24ToFloat (src, dst, inputChannelBytesPerSample[i],
  199452. samps, inputChannelLittleEndian[i]);
  199453. break;
  199454. case 32:
  199455. convertInt32ToFloat (src, dst, inputChannelBytesPerSample[i],
  199456. samps, inputChannelLittleEndian[i]);
  199457. break;
  199458. case 64:
  199459. jassertfalse
  199460. break;
  199461. }
  199462. }
  199463. }
  199464. currentCallback->audioDeviceIOCallback ((const float**) inBuffers,
  199465. numActiveInputChans,
  199466. outBuffers,
  199467. numActiveOutputChans,
  199468. samps);
  199469. for (i = 0; i < numActiveOutputChans; ++i)
  199470. {
  199471. float* const src = outBuffers[i];
  199472. jassert (src != 0);
  199473. char* const dst = (char*) (infos [numActiveInputChans + i].buffers[bi]);
  199474. if (outputChannelIsFloat[i])
  199475. {
  199476. memcpy (dst, src, samps * sizeof (float));
  199477. }
  199478. else
  199479. {
  199480. jassert (src == tempBuffer + (samps * (numActiveInputChans + i)));
  199481. switch (outputChannelBitDepths[i])
  199482. {
  199483. case 16:
  199484. convertFloatToInt16 (src, dst, outputChannelBytesPerSample[i],
  199485. samps, outputChannelLittleEndian[i]);
  199486. break;
  199487. case 24:
  199488. convertFloatToInt24 (src, dst, outputChannelBytesPerSample[i],
  199489. samps, outputChannelLittleEndian[i]);
  199490. break;
  199491. case 32:
  199492. convertFloatToInt32 (src, dst, outputChannelBytesPerSample[i],
  199493. samps, outputChannelLittleEndian[i]);
  199494. break;
  199495. case 64:
  199496. jassertfalse
  199497. break;
  199498. }
  199499. }
  199500. }
  199501. }
  199502. else
  199503. {
  199504. for (int i = 0; i < numActiveOutputChans; ++i)
  199505. {
  199506. const int bytesPerBuffer = samps * (outputChannelBitDepths[i] >> 3);
  199507. zeromem (infos[numActiveInputChans + i].buffers[bi], bytesPerBuffer);
  199508. }
  199509. }
  199510. }
  199511. if (postOutput)
  199512. asioObject->outputReady();
  199513. }
  199514. static ASIOTime* bufferSwitchTimeInfoCallback0 (ASIOTime*, long index, long) throw()
  199515. {
  199516. if (currentASIODev[0] != 0)
  199517. currentASIODev[0]->callback (index);
  199518. return 0;
  199519. }
  199520. static ASIOTime* bufferSwitchTimeInfoCallback1 (ASIOTime*, long index, long) throw()
  199521. {
  199522. if (currentASIODev[1] != 0)
  199523. currentASIODev[1]->callback (index);
  199524. return 0;
  199525. }
  199526. static ASIOTime* bufferSwitchTimeInfoCallback2 (ASIOTime*, long index, long) throw()
  199527. {
  199528. if (currentASIODev[2] != 0)
  199529. currentASIODev[2]->callback (index);
  199530. return 0;
  199531. }
  199532. static void bufferSwitchCallback0 (long index, long) throw()
  199533. {
  199534. if (currentASIODev[0] != 0)
  199535. currentASIODev[0]->callback (index);
  199536. }
  199537. static void bufferSwitchCallback1 (long index, long) throw()
  199538. {
  199539. if (currentASIODev[1] != 0)
  199540. currentASIODev[1]->callback (index);
  199541. }
  199542. static void bufferSwitchCallback2 (long index, long) throw()
  199543. {
  199544. if (currentASIODev[2] != 0)
  199545. currentASIODev[2]->callback (index);
  199546. }
  199547. static long asioMessagesCallback0 (long selector, long value, void*, double*) throw()
  199548. {
  199549. return asioMessagesCallback (selector, value, 0);
  199550. }
  199551. static long asioMessagesCallback1 (long selector, long value, void*, double*) throw()
  199552. {
  199553. return asioMessagesCallback (selector, value, 1);
  199554. }
  199555. static long asioMessagesCallback2 (long selector, long value, void*, double*) throw()
  199556. {
  199557. return asioMessagesCallback (selector, value, 2);
  199558. }
  199559. static long asioMessagesCallback (long selector, long value, const int deviceIndex) throw()
  199560. {
  199561. switch (selector)
  199562. {
  199563. case kAsioSelectorSupported:
  199564. if (value == kAsioResetRequest
  199565. || value == kAsioEngineVersion
  199566. || value == kAsioResyncRequest
  199567. || value == kAsioLatenciesChanged
  199568. || value == kAsioSupportsInputMonitor)
  199569. return 1;
  199570. break;
  199571. case kAsioBufferSizeChange:
  199572. break;
  199573. case kAsioResetRequest:
  199574. if (currentASIODev[deviceIndex] != 0)
  199575. currentASIODev[deviceIndex]->resetRequest();
  199576. return 1;
  199577. case kAsioResyncRequest:
  199578. if (currentASIODev[deviceIndex] != 0)
  199579. currentASIODev[deviceIndex]->resyncRequest();
  199580. return 1;
  199581. case kAsioLatenciesChanged:
  199582. return 1;
  199583. case kAsioEngineVersion:
  199584. return 2;
  199585. case kAsioSupportsTimeInfo:
  199586. case kAsioSupportsTimeCode:
  199587. return 0;
  199588. }
  199589. return 0;
  199590. }
  199591. static void sampleRateChangedCallback (ASIOSampleRate) throw()
  199592. {
  199593. }
  199594. static void convertInt16ToFloat (const char* src,
  199595. float* dest,
  199596. const int srcStrideBytes,
  199597. int numSamples,
  199598. const bool littleEndian) throw()
  199599. {
  199600. const double g = 1.0 / 32768.0;
  199601. if (littleEndian)
  199602. {
  199603. while (--numSamples >= 0)
  199604. {
  199605. *dest++ = (float) (g * (short) littleEndianShort (src));
  199606. src += srcStrideBytes;
  199607. }
  199608. }
  199609. else
  199610. {
  199611. while (--numSamples >= 0)
  199612. {
  199613. *dest++ = (float) (g * (short) bigEndianShort (src));
  199614. src += srcStrideBytes;
  199615. }
  199616. }
  199617. }
  199618. static void convertFloatToInt16 (const float* src,
  199619. char* dest,
  199620. const int dstStrideBytes,
  199621. int numSamples,
  199622. const bool littleEndian) throw()
  199623. {
  199624. const double maxVal = (double) 0x7fff;
  199625. if (littleEndian)
  199626. {
  199627. while (--numSamples >= 0)
  199628. {
  199629. *(uint16*) dest = swapIfBigEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  199630. dest += dstStrideBytes;
  199631. }
  199632. }
  199633. else
  199634. {
  199635. while (--numSamples >= 0)
  199636. {
  199637. *(uint16*) dest = swapIfLittleEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  199638. dest += dstStrideBytes;
  199639. }
  199640. }
  199641. }
  199642. static void convertInt24ToFloat (const char* src,
  199643. float* dest,
  199644. const int srcStrideBytes,
  199645. int numSamples,
  199646. const bool littleEndian) throw()
  199647. {
  199648. const double g = 1.0 / 0x7fffff;
  199649. if (littleEndian)
  199650. {
  199651. while (--numSamples >= 0)
  199652. {
  199653. *dest++ = (float) (g * littleEndian24Bit (src));
  199654. src += srcStrideBytes;
  199655. }
  199656. }
  199657. else
  199658. {
  199659. while (--numSamples >= 0)
  199660. {
  199661. *dest++ = (float) (g * bigEndian24Bit (src));
  199662. src += srcStrideBytes;
  199663. }
  199664. }
  199665. }
  199666. static void convertFloatToInt24 (const float* src,
  199667. char* dest,
  199668. const int dstStrideBytes,
  199669. int numSamples,
  199670. const bool littleEndian) throw()
  199671. {
  199672. const double maxVal = (double) 0x7fffff;
  199673. if (littleEndian)
  199674. {
  199675. while (--numSamples >= 0)
  199676. {
  199677. littleEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)), dest);
  199678. dest += dstStrideBytes;
  199679. }
  199680. }
  199681. else
  199682. {
  199683. while (--numSamples >= 0)
  199684. {
  199685. bigEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)), dest);
  199686. dest += dstStrideBytes;
  199687. }
  199688. }
  199689. }
  199690. static void convertInt32ToFloat (const char* src,
  199691. float* dest,
  199692. const int srcStrideBytes,
  199693. int numSamples,
  199694. const bool littleEndian) throw()
  199695. {
  199696. const double g = 1.0 / 0x7fffffff;
  199697. if (littleEndian)
  199698. {
  199699. while (--numSamples >= 0)
  199700. {
  199701. *dest++ = (float) (g * (int) littleEndianInt (src));
  199702. src += srcStrideBytes;
  199703. }
  199704. }
  199705. else
  199706. {
  199707. while (--numSamples >= 0)
  199708. {
  199709. *dest++ = (float) (g * (int) bigEndianInt (src));
  199710. src += srcStrideBytes;
  199711. }
  199712. }
  199713. }
  199714. static void convertFloatToInt32 (const float* src,
  199715. char* dest,
  199716. const int dstStrideBytes,
  199717. int numSamples,
  199718. const bool littleEndian) throw()
  199719. {
  199720. const double maxVal = (double) 0x7fffffff;
  199721. if (littleEndian)
  199722. {
  199723. while (--numSamples >= 0)
  199724. {
  199725. *(uint32*) dest = swapIfBigEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  199726. dest += dstStrideBytes;
  199727. }
  199728. }
  199729. else
  199730. {
  199731. while (--numSamples >= 0)
  199732. {
  199733. *(uint32*) dest = swapIfLittleEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  199734. dest += dstStrideBytes;
  199735. }
  199736. }
  199737. }
  199738. static void typeToFormatParameters (const long type,
  199739. int& bitDepth,
  199740. int& byteStride,
  199741. bool& formatIsFloat,
  199742. bool& littleEndian) throw()
  199743. {
  199744. bitDepth = 0;
  199745. littleEndian = false;
  199746. formatIsFloat = false;
  199747. switch (type)
  199748. {
  199749. case ASIOSTInt16MSB:
  199750. case ASIOSTInt16LSB:
  199751. case ASIOSTInt32MSB16:
  199752. case ASIOSTInt32LSB16:
  199753. bitDepth = 16; break;
  199754. case ASIOSTFloat32MSB:
  199755. case ASIOSTFloat32LSB:
  199756. formatIsFloat = true;
  199757. bitDepth = 32; break;
  199758. case ASIOSTInt32MSB:
  199759. case ASIOSTInt32LSB:
  199760. bitDepth = 32; break;
  199761. case ASIOSTInt24MSB:
  199762. case ASIOSTInt24LSB:
  199763. case ASIOSTInt32MSB24:
  199764. case ASIOSTInt32LSB24:
  199765. case ASIOSTInt32MSB18:
  199766. case ASIOSTInt32MSB20:
  199767. case ASIOSTInt32LSB18:
  199768. case ASIOSTInt32LSB20:
  199769. bitDepth = 24; break;
  199770. case ASIOSTFloat64MSB:
  199771. case ASIOSTFloat64LSB:
  199772. default:
  199773. bitDepth = 64;
  199774. break;
  199775. }
  199776. switch (type)
  199777. {
  199778. case ASIOSTInt16MSB:
  199779. case ASIOSTInt32MSB16:
  199780. case ASIOSTFloat32MSB:
  199781. case ASIOSTFloat64MSB:
  199782. case ASIOSTInt32MSB:
  199783. case ASIOSTInt32MSB18:
  199784. case ASIOSTInt32MSB20:
  199785. case ASIOSTInt32MSB24:
  199786. case ASIOSTInt24MSB:
  199787. littleEndian = false; break;
  199788. case ASIOSTInt16LSB:
  199789. case ASIOSTInt32LSB16:
  199790. case ASIOSTFloat32LSB:
  199791. case ASIOSTFloat64LSB:
  199792. case ASIOSTInt32LSB:
  199793. case ASIOSTInt32LSB18:
  199794. case ASIOSTInt32LSB20:
  199795. case ASIOSTInt32LSB24:
  199796. case ASIOSTInt24LSB:
  199797. littleEndian = true; break;
  199798. default:
  199799. break;
  199800. }
  199801. switch (type)
  199802. {
  199803. case ASIOSTInt16LSB:
  199804. case ASIOSTInt16MSB:
  199805. byteStride = 2; break;
  199806. case ASIOSTInt24LSB:
  199807. case ASIOSTInt24MSB:
  199808. byteStride = 3; break;
  199809. case ASIOSTInt32MSB16:
  199810. case ASIOSTInt32LSB16:
  199811. case ASIOSTInt32MSB:
  199812. case ASIOSTInt32MSB18:
  199813. case ASIOSTInt32MSB20:
  199814. case ASIOSTInt32MSB24:
  199815. case ASIOSTInt32LSB:
  199816. case ASIOSTInt32LSB18:
  199817. case ASIOSTInt32LSB20:
  199818. case ASIOSTInt32LSB24:
  199819. case ASIOSTFloat32LSB:
  199820. case ASIOSTFloat32MSB:
  199821. byteStride = 4; break;
  199822. case ASIOSTFloat64MSB:
  199823. case ASIOSTFloat64LSB:
  199824. byteStride = 8; break;
  199825. default:
  199826. break;
  199827. }
  199828. }
  199829. };
  199830. class ASIOAudioIODeviceType : public AudioIODeviceType
  199831. {
  199832. public:
  199833. ASIOAudioIODeviceType()
  199834. : AudioIODeviceType (T("ASIO")),
  199835. classIds (2),
  199836. hasScanned (false)
  199837. {
  199838. CoInitialize (0);
  199839. }
  199840. ~ASIOAudioIODeviceType()
  199841. {
  199842. }
  199843. void scanForDevices()
  199844. {
  199845. hasScanned = true;
  199846. deviceNames.clear();
  199847. classIds.clear();
  199848. HKEY hk = 0;
  199849. int index = 0;
  199850. if (RegOpenKeyA (HKEY_LOCAL_MACHINE, "software\\asio", &hk) == ERROR_SUCCESS)
  199851. {
  199852. for (;;)
  199853. {
  199854. char name [256];
  199855. if (RegEnumKeyA (hk, index++, name, 256) == ERROR_SUCCESS)
  199856. {
  199857. addDriverInfo (name, hk);
  199858. }
  199859. else
  199860. {
  199861. break;
  199862. }
  199863. }
  199864. RegCloseKey (hk);
  199865. }
  199866. }
  199867. const StringArray getDeviceNames (const bool /*preferInputNames*/) const
  199868. {
  199869. jassert (hasScanned); // need to call scanForDevices() before doing this
  199870. return deviceNames;
  199871. }
  199872. const String getDefaultDeviceName (const bool /*preferInputNames*/,
  199873. const int /*numInputChannelsNeeded*/,
  199874. const int /*numOutputChannelsNeeded*/) const
  199875. {
  199876. jassert (hasScanned); // need to call scanForDevices() before doing this
  199877. return deviceNames [0];
  199878. }
  199879. AudioIODevice* createDevice (const String& deviceName)
  199880. {
  199881. jassert (hasScanned); // need to call scanForDevices() before doing this
  199882. const int index = deviceNames.indexOf (deviceName);
  199883. if (index >= 0)
  199884. {
  199885. int freeSlot = -1;
  199886. for (int i = 0; i < numElementsInArray (currentASIODev); ++i)
  199887. {
  199888. if (currentASIODev[i] == 0)
  199889. {
  199890. freeSlot = i;
  199891. break;
  199892. }
  199893. }
  199894. jassert (freeSlot >= 0); // unfortunately you can only have a finite number
  199895. // of ASIO devices open at the same time..
  199896. if (freeSlot >= 0)
  199897. return new ASIOAudioIODevice (deviceName, *(classIds [index]), freeSlot);
  199898. }
  199899. return 0;
  199900. }
  199901. juce_UseDebuggingNewOperator
  199902. private:
  199903. StringArray deviceNames;
  199904. OwnedArray <CLSID> classIds;
  199905. bool hasScanned;
  199906. static bool checkClassIsOk (const String& classId)
  199907. {
  199908. HKEY hk = 0;
  199909. bool ok = false;
  199910. if (RegOpenKeyA (HKEY_CLASSES_ROOT, "clsid", &hk) == ERROR_SUCCESS)
  199911. {
  199912. int index = 0;
  199913. for (;;)
  199914. {
  199915. char buf [512];
  199916. if (RegEnumKeyA (hk, index++, buf, 512) == ERROR_SUCCESS)
  199917. {
  199918. if (classId.equalsIgnoreCase (buf))
  199919. {
  199920. HKEY subKey, pathKey;
  199921. if (RegOpenKeyExA (hk, buf, 0, KEY_READ, &subKey) == ERROR_SUCCESS)
  199922. {
  199923. if (RegOpenKeyExA (subKey, "InprocServer32", 0, KEY_READ, &pathKey) == ERROR_SUCCESS)
  199924. {
  199925. char pathName [600];
  199926. DWORD dtype = REG_SZ;
  199927. DWORD dsize = sizeof (pathName);
  199928. if (RegQueryValueExA (pathKey, 0, 0, &dtype,
  199929. (LPBYTE) pathName, &dsize) == ERROR_SUCCESS)
  199930. {
  199931. OFSTRUCT of;
  199932. zerostruct (of);
  199933. of.cBytes = sizeof (of);
  199934. ok = (OpenFile (String (pathName), &of, OF_EXIST) != 0);
  199935. }
  199936. RegCloseKey (pathKey);
  199937. }
  199938. RegCloseKey (subKey);
  199939. }
  199940. break;
  199941. }
  199942. }
  199943. else
  199944. {
  199945. break;
  199946. }
  199947. }
  199948. RegCloseKey (hk);
  199949. }
  199950. return ok;
  199951. }
  199952. void addDriverInfo (const String& keyName, HKEY hk)
  199953. {
  199954. HKEY subKey;
  199955. if (RegOpenKeyExA (hk, keyName, 0, KEY_READ, &subKey) == ERROR_SUCCESS)
  199956. {
  199957. char buf [256];
  199958. DWORD dtype = REG_SZ;
  199959. DWORD dsize = sizeof (buf);
  199960. zeromem (buf, dsize);
  199961. if (RegQueryValueExA (subKey, "clsid", 0, &dtype, (LPBYTE) buf, &dsize) == ERROR_SUCCESS)
  199962. {
  199963. if (dsize > 0 && checkClassIsOk (buf))
  199964. {
  199965. wchar_t classIdStr [130];
  199966. MultiByteToWideChar (CP_ACP, 0, buf, -1, classIdStr, 128);
  199967. String deviceName;
  199968. CLSID classId;
  199969. if (CLSIDFromString ((LPOLESTR) classIdStr, &classId) == S_OK)
  199970. {
  199971. dtype = REG_SZ;
  199972. dsize = sizeof (buf);
  199973. if (RegQueryValueExA (subKey, "description", 0, &dtype, (LPBYTE) buf, &dsize) == ERROR_SUCCESS)
  199974. deviceName = buf;
  199975. else
  199976. deviceName = keyName;
  199977. log (T("found ") + deviceName);
  199978. deviceNames.add (deviceName);
  199979. classIds.add (new CLSID (classId));
  199980. }
  199981. }
  199982. RegCloseKey (subKey);
  199983. }
  199984. }
  199985. }
  199986. ASIOAudioIODeviceType (const ASIOAudioIODeviceType&);
  199987. const ASIOAudioIODeviceType& operator= (const ASIOAudioIODeviceType&);
  199988. };
  199989. AudioIODeviceType* juce_createASIOAudioIODeviceType()
  199990. {
  199991. return new ASIOAudioIODeviceType();
  199992. }
  199993. END_JUCE_NAMESPACE
  199994. #undef log
  199995. #endif
  199996. /********* End of inlined file: juce_win32_ASIO.cpp *********/
  199997. /********* Start of inlined file: juce_win32_AudioCDReader.cpp *********/
  199998. #ifdef _MSC_VER
  199999. #pragma warning (disable: 4514)
  200000. #pragma warning (push)
  200001. #endif
  200002. #include <stddef.h>
  200003. #if JUCE_USE_CDBURNER
  200004. // you'll need the Platform SDK for these headers - if you don't have it and don't
  200005. // need to use CD-burning, then you might just want to disable the JUCE_USE_CDBURNER
  200006. // flag in juce_Config.h to avoid these includes.
  200007. #include <imapi.h>
  200008. #include <imapierror.h>
  200009. #endif
  200010. BEGIN_JUCE_NAMESPACE
  200011. #ifdef _MSC_VER
  200012. #pragma warning (pop)
  200013. #endif
  200014. //***************************************************************************
  200015. // %%% TARGET STATUS VALUES %%%
  200016. //***************************************************************************
  200017. #define STATUS_GOOD 0x00 // Status Good
  200018. #define STATUS_CHKCOND 0x02 // Check Condition
  200019. #define STATUS_CONDMET 0x04 // Condition Met
  200020. #define STATUS_BUSY 0x08 // Busy
  200021. #define STATUS_INTERM 0x10 // Intermediate
  200022. #define STATUS_INTCDMET 0x14 // Intermediate-condition met
  200023. #define STATUS_RESCONF 0x18 // Reservation conflict
  200024. #define STATUS_COMTERM 0x22 // Command Terminated
  200025. #define STATUS_QFULL 0x28 // Queue full
  200026. //***************************************************************************
  200027. // %%% SCSI MISCELLANEOUS EQUATES %%%
  200028. //***************************************************************************
  200029. #define MAXLUN 7 // Maximum Logical Unit Id
  200030. #define MAXTARG 7 // Maximum Target Id
  200031. #define MAX_SCSI_LUNS 64 // Maximum Number of SCSI LUNs
  200032. #define MAX_NUM_HA 8 // Maximum Number of SCSI HA's
  200033. //***************************************************************************
  200034. // %%% Commands for all Device Types %%%
  200035. //***************************************************************************
  200036. #define SCSI_CHANGE_DEF 0x40 // Change Definition (Optional)
  200037. #define SCSI_COMPARE 0x39 // Compare (O)
  200038. #define SCSI_COPY 0x18 // Copy (O)
  200039. #define SCSI_COP_VERIFY 0x3A // Copy and Verify (O)
  200040. #define SCSI_INQUIRY 0x12 // Inquiry (MANDATORY)
  200041. #define SCSI_LOG_SELECT 0x4C // Log Select (O)
  200042. #define SCSI_LOG_SENSE 0x4D // Log Sense (O)
  200043. #define SCSI_MODE_SEL6 0x15 // Mode Select 6-byte (Device Specific)
  200044. #define SCSI_MODE_SEL10 0x55 // Mode Select 10-byte (Device Specific)
  200045. #define SCSI_MODE_SEN6 0x1A // Mode Sense 6-byte (Device Specific)
  200046. #define SCSI_MODE_SEN10 0x5A // Mode Sense 10-byte (Device Specific)
  200047. #define SCSI_READ_BUFF 0x3C // Read Buffer (O)
  200048. #define SCSI_REQ_SENSE 0x03 // Request Sense (MANDATORY)
  200049. #define SCSI_SEND_DIAG 0x1D // Send Diagnostic (O)
  200050. #define SCSI_TST_U_RDY 0x00 // Test Unit Ready (MANDATORY)
  200051. #define SCSI_WRITE_BUFF 0x3B // Write Buffer (O)
  200052. //***************************************************************************
  200053. // %%% Commands Unique to Direct Access Devices %%%
  200054. //***************************************************************************
  200055. #define SCSI_COMPARE 0x39 // Compare (O)
  200056. #define SCSI_FORMAT 0x04 // Format Unit (MANDATORY)
  200057. #define SCSI_LCK_UN_CAC 0x36 // Lock Unlock Cache (O)
  200058. #define SCSI_PREFETCH 0x34 // Prefetch (O)
  200059. #define SCSI_MED_REMOVL 0x1E // Prevent/Allow medium Removal (O)
  200060. #define SCSI_READ6 0x08 // Read 6-byte (MANDATORY)
  200061. #define SCSI_READ10 0x28 // Read 10-byte (MANDATORY)
  200062. #define SCSI_RD_CAPAC 0x25 // Read Capacity (MANDATORY)
  200063. #define SCSI_RD_DEFECT 0x37 // Read Defect Data (O)
  200064. #define SCSI_READ_LONG 0x3E // Read Long (O)
  200065. #define SCSI_REASS_BLK 0x07 // Reassign Blocks (O)
  200066. #define SCSI_RCV_DIAG 0x1C // Receive Diagnostic Results (O)
  200067. #define SCSI_RELEASE 0x17 // Release Unit (MANDATORY)
  200068. #define SCSI_REZERO 0x01 // Rezero Unit (O)
  200069. #define SCSI_SRCH_DAT_E 0x31 // Search Data Equal (O)
  200070. #define SCSI_SRCH_DAT_H 0x30 // Search Data High (O)
  200071. #define SCSI_SRCH_DAT_L 0x32 // Search Data Low (O)
  200072. #define SCSI_SEEK6 0x0B // Seek 6-Byte (O)
  200073. #define SCSI_SEEK10 0x2B // Seek 10-Byte (O)
  200074. #define SCSI_SEND_DIAG 0x1D // Send Diagnostics (MANDATORY)
  200075. #define SCSI_SET_LIMIT 0x33 // Set Limits (O)
  200076. #define SCSI_START_STP 0x1B // Start/Stop Unit (O)
  200077. #define SCSI_SYNC_CACHE 0x35 // Synchronize Cache (O)
  200078. #define SCSI_VERIFY 0x2F // Verify (O)
  200079. #define SCSI_WRITE6 0x0A // Write 6-Byte (MANDATORY)
  200080. #define SCSI_WRITE10 0x2A // Write 10-Byte (MANDATORY)
  200081. #define SCSI_WRT_VERIFY 0x2E // Write and Verify (O)
  200082. #define SCSI_WRITE_LONG 0x3F // Write Long (O)
  200083. #define SCSI_WRITE_SAME 0x41 // Write Same (O)
  200084. //***************************************************************************
  200085. // %%% Commands Unique to Sequential Access Devices %%%
  200086. //***************************************************************************
  200087. #define SCSI_ERASE 0x19 // Erase (MANDATORY)
  200088. #define SCSI_LOAD_UN 0x1b // Load/Unload (O)
  200089. #define SCSI_LOCATE 0x2B // Locate (O)
  200090. #define SCSI_RD_BLK_LIM 0x05 // Read Block Limits (MANDATORY)
  200091. #define SCSI_READ_POS 0x34 // Read Position (O)
  200092. #define SCSI_READ_REV 0x0F // Read Reverse (O)
  200093. #define SCSI_REC_BF_DAT 0x14 // Recover Buffer Data (O)
  200094. #define SCSI_RESERVE 0x16 // Reserve Unit (MANDATORY)
  200095. #define SCSI_REWIND 0x01 // Rewind (MANDATORY)
  200096. #define SCSI_SPACE 0x11 // Space (MANDATORY)
  200097. #define SCSI_VERIFY_T 0x13 // Verify (Tape) (O)
  200098. #define SCSI_WRT_FILE 0x10 // Write Filemarks (MANDATORY)
  200099. //***************************************************************************
  200100. // %%% Commands Unique to Printer Devices %%%
  200101. //***************************************************************************
  200102. #define SCSI_PRINT 0x0A // Print (MANDATORY)
  200103. #define SCSI_SLEW_PNT 0x0B // Slew and Print (O)
  200104. #define SCSI_STOP_PNT 0x1B // Stop Print (O)
  200105. #define SCSI_SYNC_BUFF 0x10 // Synchronize Buffer (O)
  200106. //***************************************************************************
  200107. // %%% Commands Unique to Processor Devices %%%
  200108. //***************************************************************************
  200109. #define SCSI_RECEIVE 0x08 // Receive (O)
  200110. #define SCSI_SEND 0x0A // Send (O)
  200111. //***************************************************************************
  200112. // %%% Commands Unique to Write-Once Devices %%%
  200113. //***************************************************************************
  200114. #define SCSI_MEDIUM_SCN 0x38 // Medium Scan (O)
  200115. #define SCSI_SRCHDATE10 0x31 // Search Data Equal 10-Byte (O)
  200116. #define SCSI_SRCHDATE12 0xB1 // Search Data Equal 12-Byte (O)
  200117. #define SCSI_SRCHDATH10 0x30 // Search Data High 10-Byte (O)
  200118. #define SCSI_SRCHDATH12 0xB0 // Search Data High 12-Byte (O)
  200119. #define SCSI_SRCHDATL10 0x32 // Search Data Low 10-Byte (O)
  200120. #define SCSI_SRCHDATL12 0xB2 // Search Data Low 12-Byte (O)
  200121. #define SCSI_SET_LIM_10 0x33 // Set Limits 10-Byte (O)
  200122. #define SCSI_SET_LIM_12 0xB3 // Set Limits 10-Byte (O)
  200123. #define SCSI_VERIFY10 0x2F // Verify 10-Byte (O)
  200124. #define SCSI_VERIFY12 0xAF // Verify 12-Byte (O)
  200125. #define SCSI_WRITE12 0xAA // Write 12-Byte (O)
  200126. #define SCSI_WRT_VER10 0x2E // Write and Verify 10-Byte (O)
  200127. #define SCSI_WRT_VER12 0xAE // Write and Verify 12-Byte (O)
  200128. //***************************************************************************
  200129. // %%% Commands Unique to CD-ROM Devices %%%
  200130. //***************************************************************************
  200131. #define SCSI_PLAYAUD_10 0x45 // Play Audio 10-Byte (O)
  200132. #define SCSI_PLAYAUD_12 0xA5 // Play Audio 12-Byte 12-Byte (O)
  200133. #define SCSI_PLAYAUDMSF 0x47 // Play Audio MSF (O)
  200134. #define SCSI_PLAYA_TKIN 0x48 // Play Audio Track/Index (O)
  200135. #define SCSI_PLYTKREL10 0x49 // Play Track Relative 10-Byte (O)
  200136. #define SCSI_PLYTKREL12 0xA9 // Play Track Relative 12-Byte (O)
  200137. #define SCSI_READCDCAP 0x25 // Read CD-ROM Capacity (MANDATORY)
  200138. #define SCSI_READHEADER 0x44 // Read Header (O)
  200139. #define SCSI_SUBCHANNEL 0x42 // Read Subchannel (O)
  200140. #define SCSI_READ_TOC 0x43 // Read TOC (O)
  200141. //***************************************************************************
  200142. // %%% Commands Unique to Scanner Devices %%%
  200143. //***************************************************************************
  200144. #define SCSI_GETDBSTAT 0x34 // Get Data Buffer Status (O)
  200145. #define SCSI_GETWINDOW 0x25 // Get Window (O)
  200146. #define SCSI_OBJECTPOS 0x31 // Object Postion (O)
  200147. #define SCSI_SCAN 0x1B // Scan (O)
  200148. #define SCSI_SETWINDOW 0x24 // Set Window (MANDATORY)
  200149. //***************************************************************************
  200150. // %%% Commands Unique to Optical Memory Devices %%%
  200151. //***************************************************************************
  200152. #define SCSI_UpdateBlk 0x3D // Update Block (O)
  200153. //***************************************************************************
  200154. // %%% Commands Unique to Medium Changer Devices %%%
  200155. //***************************************************************************
  200156. #define SCSI_EXCHMEDIUM 0xA6 // Exchange Medium (O)
  200157. #define SCSI_INITELSTAT 0x07 // Initialize Element Status (O)
  200158. #define SCSI_POSTOELEM 0x2B // Position to Element (O)
  200159. #define SCSI_REQ_VE_ADD 0xB5 // Request Volume Element Address (O)
  200160. #define SCSI_SENDVOLTAG 0xB6 // Send Volume Tag (O)
  200161. //***************************************************************************
  200162. // %%% Commands Unique to Communication Devices %%%
  200163. //***************************************************************************
  200164. #define SCSI_GET_MSG_6 0x08 // Get Message 6-Byte (MANDATORY)
  200165. #define SCSI_GET_MSG_10 0x28 // Get Message 10-Byte (O)
  200166. #define SCSI_GET_MSG_12 0xA8 // Get Message 12-Byte (O)
  200167. #define SCSI_SND_MSG_6 0x0A // Send Message 6-Byte (MANDATORY)
  200168. #define SCSI_SND_MSG_10 0x2A // Send Message 10-Byte (O)
  200169. #define SCSI_SND_MSG_12 0xAA // Send Message 12-Byte (O)
  200170. //***************************************************************************
  200171. // %%% Request Sense Data Format %%%
  200172. //***************************************************************************
  200173. typedef struct {
  200174. BYTE ErrorCode; // Error Code (70H or 71H)
  200175. BYTE SegmentNum; // Number of current segment descriptor
  200176. BYTE SenseKey; // Sense Key(See bit definitions too)
  200177. BYTE InfoByte0; // Information MSB
  200178. BYTE InfoByte1; // Information MID
  200179. BYTE InfoByte2; // Information MID
  200180. BYTE InfoByte3; // Information LSB
  200181. BYTE AddSenLen; // Additional Sense Length
  200182. BYTE ComSpecInf0; // Command Specific Information MSB
  200183. BYTE ComSpecInf1; // Command Specific Information MID
  200184. BYTE ComSpecInf2; // Command Specific Information MID
  200185. BYTE ComSpecInf3; // Command Specific Information LSB
  200186. BYTE AddSenseCode; // Additional Sense Code
  200187. BYTE AddSenQual; // Additional Sense Code Qualifier
  200188. BYTE FieldRepUCode; // Field Replaceable Unit Code
  200189. BYTE SenKeySpec15; // Sense Key Specific 15th byte
  200190. BYTE SenKeySpec16; // Sense Key Specific 16th byte
  200191. BYTE SenKeySpec17; // Sense Key Specific 17th byte
  200192. BYTE AddSenseBytes; // Additional Sense Bytes
  200193. } SENSE_DATA_FMT;
  200194. //***************************************************************************
  200195. // %%% REQUEST SENSE ERROR CODE %%%
  200196. //***************************************************************************
  200197. #define SERROR_CURRENT 0x70 // Current Errors
  200198. #define SERROR_DEFERED 0x71 // Deferred Errors
  200199. //***************************************************************************
  200200. // %%% REQUEST SENSE BIT DEFINITIONS %%%
  200201. //***************************************************************************
  200202. #define SENSE_VALID 0x80 // Byte 0 Bit 7
  200203. #define SENSE_FILEMRK 0x80 // Byte 2 Bit 7
  200204. #define SENSE_EOM 0x40 // Byte 2 Bit 6
  200205. #define SENSE_ILI 0x20 // Byte 2 Bit 5
  200206. //***************************************************************************
  200207. // %%% REQUEST SENSE SENSE KEY DEFINITIONS %%%
  200208. //***************************************************************************
  200209. #define KEY_NOSENSE 0x00 // No Sense
  200210. #define KEY_RECERROR 0x01 // Recovered Error
  200211. #define KEY_NOTREADY 0x02 // Not Ready
  200212. #define KEY_MEDIUMERR 0x03 // Medium Error
  200213. #define KEY_HARDERROR 0x04 // Hardware Error
  200214. #define KEY_ILLGLREQ 0x05 // Illegal Request
  200215. #define KEY_UNITATT 0x06 // Unit Attention
  200216. #define KEY_DATAPROT 0x07 // Data Protect
  200217. #define KEY_BLANKCHK 0x08 // Blank Check
  200218. #define KEY_VENDSPEC 0x09 // Vendor Specific
  200219. #define KEY_COPYABORT 0x0A // Copy Abort
  200220. #define KEY_EQUAL 0x0C // Equal (Search)
  200221. #define KEY_VOLOVRFLW 0x0D // Volume Overflow
  200222. #define KEY_MISCOMP 0x0E // Miscompare (Search)
  200223. #define KEY_RESERVED 0x0F // Reserved
  200224. //***************************************************************************
  200225. // %%% PERIPHERAL DEVICE TYPE DEFINITIONS %%%
  200226. //***************************************************************************
  200227. #define DTYPE_DASD 0x00 // Disk Device
  200228. #define DTYPE_SEQD 0x01 // Tape Device
  200229. #define DTYPE_PRNT 0x02 // Printer
  200230. #define DTYPE_PROC 0x03 // Processor
  200231. #define DTYPE_WORM 0x04 // Write-once read-multiple
  200232. #define DTYPE_CROM 0x05 // CD-ROM device
  200233. #define DTYPE_SCAN 0x06 // Scanner device
  200234. #define DTYPE_OPTI 0x07 // Optical memory device
  200235. #define DTYPE_JUKE 0x08 // Medium Changer device
  200236. #define DTYPE_COMM 0x09 // Communications device
  200237. #define DTYPE_RESL 0x0A // Reserved (low)
  200238. #define DTYPE_RESH 0x1E // Reserved (high)
  200239. #define DTYPE_UNKNOWN 0x1F // Unknown or no device type
  200240. //***************************************************************************
  200241. // %%% ANSI APPROVED VERSION DEFINITIONS %%%
  200242. //***************************************************************************
  200243. #define ANSI_MAYBE 0x0 // Device may or may not be ANSI approved stand
  200244. #define ANSI_SCSI1 0x1 // Device complies to ANSI X3.131-1986 (SCSI-1)
  200245. #define ANSI_SCSI2 0x2 // Device complies to SCSI-2
  200246. #define ANSI_RESLO 0x3 // Reserved (low)
  200247. #define ANSI_RESHI 0x7 // Reserved (high)
  200248. typedef struct
  200249. {
  200250. USHORT Length;
  200251. UCHAR ScsiStatus;
  200252. UCHAR PathId;
  200253. UCHAR TargetId;
  200254. UCHAR Lun;
  200255. UCHAR CdbLength;
  200256. UCHAR SenseInfoLength;
  200257. UCHAR DataIn;
  200258. ULONG DataTransferLength;
  200259. ULONG TimeOutValue;
  200260. ULONG DataBufferOffset;
  200261. ULONG SenseInfoOffset;
  200262. UCHAR Cdb[16];
  200263. } SCSI_PASS_THROUGH, *PSCSI_PASS_THROUGH;
  200264. typedef struct
  200265. {
  200266. USHORT Length;
  200267. UCHAR ScsiStatus;
  200268. UCHAR PathId;
  200269. UCHAR TargetId;
  200270. UCHAR Lun;
  200271. UCHAR CdbLength;
  200272. UCHAR SenseInfoLength;
  200273. UCHAR DataIn;
  200274. ULONG DataTransferLength;
  200275. ULONG TimeOutValue;
  200276. PVOID DataBuffer;
  200277. ULONG SenseInfoOffset;
  200278. UCHAR Cdb[16];
  200279. } SCSI_PASS_THROUGH_DIRECT, *PSCSI_PASS_THROUGH_DIRECT;
  200280. typedef struct
  200281. {
  200282. SCSI_PASS_THROUGH_DIRECT spt;
  200283. ULONG Filler;
  200284. UCHAR ucSenseBuf[32];
  200285. } SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, *PSCSI_PASS_THROUGH_DIRECT_WITH_BUFFER;
  200286. typedef struct
  200287. {
  200288. ULONG Length;
  200289. UCHAR PortNumber;
  200290. UCHAR PathId;
  200291. UCHAR TargetId;
  200292. UCHAR Lun;
  200293. } SCSI_ADDRESS, *PSCSI_ADDRESS;
  200294. #define METHOD_BUFFERED 0
  200295. #define METHOD_IN_DIRECT 1
  200296. #define METHOD_OUT_DIRECT 2
  200297. #define METHOD_NEITHER 3
  200298. #define FILE_ANY_ACCESS 0
  200299. #ifndef FILE_READ_ACCESS
  200300. #define FILE_READ_ACCESS (0x0001)
  200301. #endif
  200302. #ifndef FILE_WRITE_ACCESS
  200303. #define FILE_WRITE_ACCESS (0x0002)
  200304. #endif
  200305. #define IOCTL_SCSI_BASE 0x00000004
  200306. #define SCSI_IOCTL_DATA_OUT 0
  200307. #define SCSI_IOCTL_DATA_IN 1
  200308. #define SCSI_IOCTL_DATA_UNSPECIFIED 2
  200309. #define CTL_CODE2( DevType, Function, Method, Access ) ( \
  200310. ((DevType) << 16) | ((Access) << 14) | ((Function) << 2) | (Method) \
  200311. )
  200312. #define IOCTL_SCSI_PASS_THROUGH CTL_CODE2( IOCTL_SCSI_BASE, 0x0401, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS )
  200313. #define IOCTL_SCSI_GET_CAPABILITIES CTL_CODE2( IOCTL_SCSI_BASE, 0x0404, METHOD_BUFFERED, FILE_ANY_ACCESS)
  200314. #define IOCTL_SCSI_PASS_THROUGH_DIRECT CTL_CODE2( IOCTL_SCSI_BASE, 0x0405, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS )
  200315. #define IOCTL_SCSI_GET_ADDRESS CTL_CODE2( IOCTL_SCSI_BASE, 0x0406, METHOD_BUFFERED, FILE_ANY_ACCESS )
  200316. #define SENSE_LEN 14
  200317. #define SRB_DIR_SCSI 0x00
  200318. #define SRB_POSTING 0x01
  200319. #define SRB_ENABLE_RESIDUAL_COUNT 0x04
  200320. #define SRB_DIR_IN 0x08
  200321. #define SRB_DIR_OUT 0x10
  200322. #define SRB_EVENT_NOTIFY 0x40
  200323. #define RESIDUAL_COUNT_SUPPORTED 0x02
  200324. #define MAX_SRB_TIMEOUT 1080001u
  200325. #define DEFAULT_SRB_TIMEOUT 1080001u
  200326. #define SC_HA_INQUIRY 0x00
  200327. #define SC_GET_DEV_TYPE 0x01
  200328. #define SC_EXEC_SCSI_CMD 0x02
  200329. #define SC_ABORT_SRB 0x03
  200330. #define SC_RESET_DEV 0x04
  200331. #define SC_SET_HA_PARMS 0x05
  200332. #define SC_GET_DISK_INFO 0x06
  200333. #define SC_RESCAN_SCSI_BUS 0x07
  200334. #define SC_GETSET_TIMEOUTS 0x08
  200335. #define SS_PENDING 0x00
  200336. #define SS_COMP 0x01
  200337. #define SS_ABORTED 0x02
  200338. #define SS_ABORT_FAIL 0x03
  200339. #define SS_ERR 0x04
  200340. #define SS_INVALID_CMD 0x80
  200341. #define SS_INVALID_HA 0x81
  200342. #define SS_NO_DEVICE 0x82
  200343. #define SS_INVALID_SRB 0xE0
  200344. #define SS_OLD_MANAGER 0xE1
  200345. #define SS_BUFFER_ALIGN 0xE1
  200346. #define SS_ILLEGAL_MODE 0xE2
  200347. #define SS_NO_ASPI 0xE3
  200348. #define SS_FAILED_INIT 0xE4
  200349. #define SS_ASPI_IS_BUSY 0xE5
  200350. #define SS_BUFFER_TO_BIG 0xE6
  200351. #define SS_BUFFER_TOO_BIG 0xE6
  200352. #define SS_MISMATCHED_COMPONENTS 0xE7
  200353. #define SS_NO_ADAPTERS 0xE8
  200354. #define SS_INSUFFICIENT_RESOURCES 0xE9
  200355. #define SS_ASPI_IS_SHUTDOWN 0xEA
  200356. #define SS_BAD_INSTALL 0xEB
  200357. #define HASTAT_OK 0x00
  200358. #define HASTAT_SEL_TO 0x11
  200359. #define HASTAT_DO_DU 0x12
  200360. #define HASTAT_BUS_FREE 0x13
  200361. #define HASTAT_PHASE_ERR 0x14
  200362. #define HASTAT_TIMEOUT 0x09
  200363. #define HASTAT_COMMAND_TIMEOUT 0x0B
  200364. #define HASTAT_MESSAGE_REJECT 0x0D
  200365. #define HASTAT_BUS_RESET 0x0E
  200366. #define HASTAT_PARITY_ERROR 0x0F
  200367. #define HASTAT_REQUEST_SENSE_FAILED 0x10
  200368. #define PACKED
  200369. #pragma pack(1)
  200370. typedef struct
  200371. {
  200372. BYTE SRB_Cmd;
  200373. BYTE SRB_Status;
  200374. BYTE SRB_HaID;
  200375. BYTE SRB_Flags;
  200376. DWORD SRB_Hdr_Rsvd;
  200377. BYTE HA_Count;
  200378. BYTE HA_SCSI_ID;
  200379. BYTE HA_ManagerId[16];
  200380. BYTE HA_Identifier[16];
  200381. BYTE HA_Unique[16];
  200382. WORD HA_Rsvd1;
  200383. BYTE pad[20];
  200384. } PACKED SRB_HAInquiry, *PSRB_HAInquiry, FAR *LPSRB_HAInquiry;
  200385. typedef struct
  200386. {
  200387. BYTE SRB_Cmd;
  200388. BYTE SRB_Status;
  200389. BYTE SRB_HaID;
  200390. BYTE SRB_Flags;
  200391. DWORD SRB_Hdr_Rsvd;
  200392. BYTE SRB_Target;
  200393. BYTE SRB_Lun;
  200394. BYTE SRB_DeviceType;
  200395. BYTE SRB_Rsvd1;
  200396. BYTE pad[68];
  200397. } PACKED SRB_GDEVBlock, *PSRB_GDEVBlock, FAR *LPSRB_GDEVBlock;
  200398. typedef struct
  200399. {
  200400. BYTE SRB_Cmd;
  200401. BYTE SRB_Status;
  200402. BYTE SRB_HaID;
  200403. BYTE SRB_Flags;
  200404. DWORD SRB_Hdr_Rsvd;
  200405. BYTE SRB_Target;
  200406. BYTE SRB_Lun;
  200407. WORD SRB_Rsvd1;
  200408. DWORD SRB_BufLen;
  200409. BYTE FAR *SRB_BufPointer;
  200410. BYTE SRB_SenseLen;
  200411. BYTE SRB_CDBLen;
  200412. BYTE SRB_HaStat;
  200413. BYTE SRB_TargStat;
  200414. VOID FAR *SRB_PostProc;
  200415. BYTE SRB_Rsvd2[20];
  200416. BYTE CDBByte[16];
  200417. BYTE SenseArea[SENSE_LEN+2];
  200418. } PACKED SRB_ExecSCSICmd, *PSRB_ExecSCSICmd, FAR *LPSRB_ExecSCSICmd;
  200419. typedef struct
  200420. {
  200421. BYTE SRB_Cmd;
  200422. BYTE SRB_Status;
  200423. BYTE SRB_HaId;
  200424. BYTE SRB_Flags;
  200425. DWORD SRB_Hdr_Rsvd;
  200426. } PACKED SRB, *PSRB, FAR *LPSRB;
  200427. #pragma pack()
  200428. struct CDDeviceInfo
  200429. {
  200430. char vendor[9];
  200431. char productId[17];
  200432. char rev[5];
  200433. char vendorSpec[21];
  200434. BYTE ha;
  200435. BYTE tgt;
  200436. BYTE lun;
  200437. char scsiDriveLetter; // will be 0 if not using scsi
  200438. };
  200439. class CDReadBuffer
  200440. {
  200441. public:
  200442. int startFrame;
  200443. int numFrames;
  200444. int dataStartOffset;
  200445. int dataLength;
  200446. BYTE* buffer;
  200447. int bufferSize;
  200448. int index;
  200449. bool wantsIndex;
  200450. CDReadBuffer (const int numberOfFrames)
  200451. : startFrame (0),
  200452. numFrames (0),
  200453. dataStartOffset (0),
  200454. dataLength (0),
  200455. index (0),
  200456. wantsIndex (false)
  200457. {
  200458. bufferSize = 2352 * numberOfFrames;
  200459. buffer = (BYTE*) malloc (bufferSize);
  200460. }
  200461. ~CDReadBuffer()
  200462. {
  200463. free (buffer);
  200464. }
  200465. bool isZero() const
  200466. {
  200467. BYTE* p = buffer + dataStartOffset;
  200468. for (int i = dataLength; --i >= 0;)
  200469. if (*p++ != 0)
  200470. return false;
  200471. return true;
  200472. }
  200473. };
  200474. class CDDeviceHandle;
  200475. class CDController
  200476. {
  200477. public:
  200478. CDController();
  200479. virtual ~CDController();
  200480. virtual bool read (CDReadBuffer* t) = 0;
  200481. virtual void shutDown();
  200482. bool readAudio (CDReadBuffer* t, CDReadBuffer* overlapBuffer = 0);
  200483. int getLastIndex();
  200484. public:
  200485. bool initialised;
  200486. CDDeviceHandle* deviceInfo;
  200487. int framesToCheck, framesOverlap;
  200488. void prepare (SRB_ExecSCSICmd& s);
  200489. void perform (SRB_ExecSCSICmd& s);
  200490. void setPaused (bool paused);
  200491. };
  200492. #pragma pack(1)
  200493. struct TOCTRACK
  200494. {
  200495. BYTE rsvd;
  200496. BYTE ADR;
  200497. BYTE trackNumber;
  200498. BYTE rsvd2;
  200499. BYTE addr[4];
  200500. };
  200501. struct TOC
  200502. {
  200503. WORD tocLen;
  200504. BYTE firstTrack;
  200505. BYTE lastTrack;
  200506. TOCTRACK tracks[100];
  200507. };
  200508. #pragma pack()
  200509. enum
  200510. {
  200511. READTYPE_ANY = 0,
  200512. READTYPE_ATAPI1 = 1,
  200513. READTYPE_ATAPI2 = 2,
  200514. READTYPE_READ6 = 3,
  200515. READTYPE_READ10 = 4,
  200516. READTYPE_READ_D8 = 5,
  200517. READTYPE_READ_D4 = 6,
  200518. READTYPE_READ_D4_1 = 7,
  200519. READTYPE_READ10_2 = 8
  200520. };
  200521. class CDDeviceHandle
  200522. {
  200523. public:
  200524. CDDeviceHandle (const CDDeviceInfo* const device)
  200525. : scsiHandle (0),
  200526. readType (READTYPE_ANY),
  200527. controller (0)
  200528. {
  200529. memcpy (&info, device, sizeof (info));
  200530. }
  200531. ~CDDeviceHandle()
  200532. {
  200533. if (controller != 0)
  200534. {
  200535. controller->shutDown();
  200536. delete controller;
  200537. }
  200538. if (scsiHandle != 0)
  200539. CloseHandle (scsiHandle);
  200540. }
  200541. bool readTOC (TOC* lpToc, bool useMSF);
  200542. bool readAudio (CDReadBuffer* buffer, CDReadBuffer* overlapBuffer = 0);
  200543. void openDrawer (bool shouldBeOpen);
  200544. CDDeviceInfo info;
  200545. HANDLE scsiHandle;
  200546. BYTE readType;
  200547. private:
  200548. CDController* controller;
  200549. bool testController (const int readType,
  200550. CDController* const newController,
  200551. CDReadBuffer* const bufferToUse);
  200552. };
  200553. DWORD (*fGetASPI32SupportInfo)(void);
  200554. DWORD (*fSendASPI32Command)(LPSRB);
  200555. static HINSTANCE winAspiLib = 0;
  200556. static bool usingScsi = false;
  200557. static bool initialised = false;
  200558. static bool InitialiseCDRipper()
  200559. {
  200560. if (! initialised)
  200561. {
  200562. initialised = true;
  200563. OSVERSIONINFO info;
  200564. info.dwOSVersionInfoSize = sizeof (info);
  200565. GetVersionEx (&info);
  200566. usingScsi = (info.dwPlatformId == VER_PLATFORM_WIN32_NT) && (info.dwMajorVersion > 4);
  200567. if (! usingScsi)
  200568. {
  200569. fGetASPI32SupportInfo = 0;
  200570. fSendASPI32Command = 0;
  200571. winAspiLib = LoadLibrary (_T("WNASPI32.DLL"));
  200572. if (winAspiLib != 0)
  200573. {
  200574. fGetASPI32SupportInfo = (DWORD(*)(void)) GetProcAddress (winAspiLib, "GetASPI32SupportInfo");
  200575. fSendASPI32Command = (DWORD(*)(LPSRB)) GetProcAddress (winAspiLib, "SendASPI32Command");
  200576. if (fGetASPI32SupportInfo == 0 || fSendASPI32Command == 0)
  200577. return false;
  200578. }
  200579. else
  200580. {
  200581. usingScsi = true;
  200582. }
  200583. }
  200584. }
  200585. return true;
  200586. }
  200587. static void DeinitialiseCDRipper()
  200588. {
  200589. if (winAspiLib != 0)
  200590. {
  200591. fGetASPI32SupportInfo = 0;
  200592. fSendASPI32Command = 0;
  200593. FreeLibrary (winAspiLib);
  200594. winAspiLib = 0;
  200595. }
  200596. initialised = false;
  200597. }
  200598. static HANDLE CreateSCSIDeviceHandle (char driveLetter)
  200599. {
  200600. TCHAR devicePath[8];
  200601. devicePath[0] = '\\';
  200602. devicePath[1] = '\\';
  200603. devicePath[2] = '.';
  200604. devicePath[3] = '\\';
  200605. devicePath[4] = driveLetter;
  200606. devicePath[5] = ':';
  200607. devicePath[6] = 0;
  200608. OSVERSIONINFO info;
  200609. info.dwOSVersionInfoSize = sizeof (info);
  200610. GetVersionEx (&info);
  200611. DWORD flags = GENERIC_READ;
  200612. if ((info.dwPlatformId == VER_PLATFORM_WIN32_NT) && (info.dwMajorVersion > 4))
  200613. flags = GENERIC_READ | GENERIC_WRITE;
  200614. HANDLE h = CreateFile (devicePath, flags, FILE_SHARE_WRITE | FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
  200615. if (h == INVALID_HANDLE_VALUE)
  200616. {
  200617. flags ^= GENERIC_WRITE;
  200618. h = CreateFile (devicePath, flags, FILE_SHARE_WRITE | FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
  200619. }
  200620. return h;
  200621. }
  200622. static DWORD performScsiPassThroughCommand (const LPSRB_ExecSCSICmd srb,
  200623. const char driveLetter,
  200624. HANDLE& deviceHandle,
  200625. const bool retryOnFailure = true)
  200626. {
  200627. SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER s;
  200628. zerostruct (s);
  200629. s.spt.Length = sizeof (SCSI_PASS_THROUGH);
  200630. s.spt.CdbLength = srb->SRB_CDBLen;
  200631. s.spt.DataIn = (BYTE) ((srb->SRB_Flags & SRB_DIR_IN)
  200632. ? SCSI_IOCTL_DATA_IN
  200633. : ((srb->SRB_Flags & SRB_DIR_OUT)
  200634. ? SCSI_IOCTL_DATA_OUT
  200635. : SCSI_IOCTL_DATA_UNSPECIFIED));
  200636. s.spt.DataTransferLength = srb->SRB_BufLen;
  200637. s.spt.TimeOutValue = 5;
  200638. s.spt.DataBuffer = srb->SRB_BufPointer;
  200639. s.spt.SenseInfoOffset = offsetof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, ucSenseBuf);
  200640. memcpy (s.spt.Cdb, srb->CDBByte, srb->SRB_CDBLen);
  200641. srb->SRB_Status = SS_ERR;
  200642. srb->SRB_TargStat = 0x0004;
  200643. DWORD bytesReturned = 0;
  200644. if (DeviceIoControl (deviceHandle, IOCTL_SCSI_PASS_THROUGH_DIRECT,
  200645. &s, sizeof (s),
  200646. &s, sizeof (s),
  200647. &bytesReturned, 0) != 0)
  200648. {
  200649. srb->SRB_Status = SS_COMP;
  200650. }
  200651. else if (retryOnFailure)
  200652. {
  200653. const DWORD error = GetLastError();
  200654. if ((error == ERROR_MEDIA_CHANGED) || (error == ERROR_INVALID_HANDLE))
  200655. {
  200656. if (error != ERROR_INVALID_HANDLE)
  200657. CloseHandle (deviceHandle);
  200658. deviceHandle = CreateSCSIDeviceHandle (driveLetter);
  200659. return performScsiPassThroughCommand (srb, driveLetter, deviceHandle, false);
  200660. }
  200661. }
  200662. return srb->SRB_Status;
  200663. }
  200664. // Controller types..
  200665. class ControllerType1 : public CDController
  200666. {
  200667. public:
  200668. ControllerType1() {}
  200669. ~ControllerType1() {}
  200670. bool read (CDReadBuffer* rb)
  200671. {
  200672. if (rb->numFrames * 2352 > rb->bufferSize)
  200673. return false;
  200674. SRB_ExecSCSICmd s;
  200675. prepare (s);
  200676. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  200677. s.SRB_BufLen = rb->bufferSize;
  200678. s.SRB_BufPointer = rb->buffer;
  200679. s.SRB_CDBLen = 12;
  200680. s.CDBByte[0] = 0xBE;
  200681. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  200682. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  200683. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  200684. s.CDBByte[8] = (BYTE)(rb->numFrames & 0xFF);
  200685. s.CDBByte[9] = (BYTE)((deviceInfo->readType == READTYPE_ATAPI1) ? 0x10 : 0xF0);
  200686. perform (s);
  200687. if (s.SRB_Status != SS_COMP)
  200688. return false;
  200689. rb->dataLength = rb->numFrames * 2352;
  200690. rb->dataStartOffset = 0;
  200691. return true;
  200692. }
  200693. };
  200694. class ControllerType2 : public CDController
  200695. {
  200696. public:
  200697. ControllerType2() {}
  200698. ~ControllerType2() {}
  200699. void shutDown()
  200700. {
  200701. if (initialised)
  200702. {
  200703. BYTE bufPointer[] = { 0, 0, 0, 8, 83, 0, 0, 0, 0, 0, 8, 0 };
  200704. SRB_ExecSCSICmd s;
  200705. prepare (s);
  200706. s.SRB_Flags = SRB_EVENT_NOTIFY | SRB_ENABLE_RESIDUAL_COUNT;
  200707. s.SRB_BufLen = 0x0C;
  200708. s.SRB_BufPointer = bufPointer;
  200709. s.SRB_CDBLen = 6;
  200710. s.CDBByte[0] = 0x15;
  200711. s.CDBByte[4] = 0x0C;
  200712. perform (s);
  200713. }
  200714. }
  200715. bool init()
  200716. {
  200717. SRB_ExecSCSICmd s;
  200718. s.SRB_Status = SS_ERR;
  200719. if (deviceInfo->readType == READTYPE_READ10_2)
  200720. {
  200721. BYTE bufPointer1[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48, 35, 6, 0, 0, 0, 0, 0, 128 };
  200722. BYTE bufPointer2[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48, 1, 6, 32, 7, 0, 0, 0, 0 };
  200723. for (int i = 0; i < 2; ++i)
  200724. {
  200725. prepare (s);
  200726. s.SRB_Flags = SRB_EVENT_NOTIFY;
  200727. s.SRB_BufLen = 0x14;
  200728. s.SRB_BufPointer = (i == 0) ? bufPointer1 : bufPointer2;
  200729. s.SRB_CDBLen = 6;
  200730. s.CDBByte[0] = 0x15;
  200731. s.CDBByte[1] = 0x10;
  200732. s.CDBByte[4] = 0x14;
  200733. perform (s);
  200734. if (s.SRB_Status != SS_COMP)
  200735. return false;
  200736. }
  200737. }
  200738. else
  200739. {
  200740. BYTE bufPointer[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48 };
  200741. prepare (s);
  200742. s.SRB_Flags = SRB_EVENT_NOTIFY;
  200743. s.SRB_BufLen = 0x0C;
  200744. s.SRB_BufPointer = bufPointer;
  200745. s.SRB_CDBLen = 6;
  200746. s.CDBByte[0] = 0x15;
  200747. s.CDBByte[4] = 0x0C;
  200748. perform (s);
  200749. }
  200750. return s.SRB_Status == SS_COMP;
  200751. }
  200752. bool read (CDReadBuffer* rb)
  200753. {
  200754. if (rb->numFrames * 2352 > rb->bufferSize)
  200755. return false;
  200756. if (!initialised)
  200757. {
  200758. initialised = init();
  200759. if (!initialised)
  200760. return false;
  200761. }
  200762. SRB_ExecSCSICmd s;
  200763. prepare (s);
  200764. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  200765. s.SRB_BufLen = rb->bufferSize;
  200766. s.SRB_BufPointer = rb->buffer;
  200767. s.SRB_CDBLen = 10;
  200768. s.CDBByte[0] = 0x28;
  200769. s.CDBByte[1] = (BYTE)(deviceInfo->info.lun << 5);
  200770. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  200771. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  200772. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  200773. s.CDBByte[8] = (BYTE)(rb->numFrames & 0xFF);
  200774. perform (s);
  200775. if (s.SRB_Status != SS_COMP)
  200776. return false;
  200777. rb->dataLength = rb->numFrames * 2352;
  200778. rb->dataStartOffset = 0;
  200779. return true;
  200780. }
  200781. };
  200782. class ControllerType3 : public CDController
  200783. {
  200784. public:
  200785. ControllerType3() {}
  200786. ~ControllerType3() {}
  200787. bool read (CDReadBuffer* rb)
  200788. {
  200789. if (rb->numFrames * 2352 > rb->bufferSize)
  200790. return false;
  200791. if (!initialised)
  200792. {
  200793. setPaused (false);
  200794. initialised = true;
  200795. }
  200796. SRB_ExecSCSICmd s;
  200797. prepare (s);
  200798. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  200799. s.SRB_BufLen = rb->numFrames * 2352;
  200800. s.SRB_BufPointer = rb->buffer;
  200801. s.SRB_CDBLen = 12;
  200802. s.CDBByte[0] = 0xD8;
  200803. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  200804. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  200805. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  200806. s.CDBByte[9] = (BYTE)(rb->numFrames & 0xFF);
  200807. perform (s);
  200808. if (s.SRB_Status != SS_COMP)
  200809. return false;
  200810. rb->dataLength = rb->numFrames * 2352;
  200811. rb->dataStartOffset = 0;
  200812. return true;
  200813. }
  200814. };
  200815. class ControllerType4 : public CDController
  200816. {
  200817. public:
  200818. ControllerType4() {}
  200819. ~ControllerType4() {}
  200820. bool selectD4Mode()
  200821. {
  200822. BYTE bufPointer[12] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 48 };
  200823. SRB_ExecSCSICmd s;
  200824. prepare (s);
  200825. s.SRB_Flags = SRB_EVENT_NOTIFY;
  200826. s.SRB_CDBLen = 6;
  200827. s.SRB_BufLen = 12;
  200828. s.SRB_BufPointer = bufPointer;
  200829. s.CDBByte[0] = 0x15;
  200830. s.CDBByte[1] = 0x10;
  200831. s.CDBByte[4] = 0x08;
  200832. perform (s);
  200833. return s.SRB_Status == SS_COMP;
  200834. }
  200835. bool read (CDReadBuffer* rb)
  200836. {
  200837. if (rb->numFrames * 2352 > rb->bufferSize)
  200838. return false;
  200839. if (!initialised)
  200840. {
  200841. setPaused (true);
  200842. if (deviceInfo->readType == READTYPE_READ_D4_1)
  200843. selectD4Mode();
  200844. initialised = true;
  200845. }
  200846. SRB_ExecSCSICmd s;
  200847. prepare (s);
  200848. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  200849. s.SRB_BufLen = rb->bufferSize;
  200850. s.SRB_BufPointer = rb->buffer;
  200851. s.SRB_CDBLen = 10;
  200852. s.CDBByte[0] = 0xD4;
  200853. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  200854. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  200855. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  200856. s.CDBByte[8] = (BYTE)(rb->numFrames & 0xFF);
  200857. perform (s);
  200858. if (s.SRB_Status != SS_COMP)
  200859. return false;
  200860. rb->dataLength = rb->numFrames * 2352;
  200861. rb->dataStartOffset = 0;
  200862. return true;
  200863. }
  200864. };
  200865. CDController::CDController() : initialised (false)
  200866. {
  200867. }
  200868. CDController::~CDController()
  200869. {
  200870. }
  200871. void CDController::prepare (SRB_ExecSCSICmd& s)
  200872. {
  200873. zerostruct (s);
  200874. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  200875. s.SRB_HaID = deviceInfo->info.ha;
  200876. s.SRB_Target = deviceInfo->info.tgt;
  200877. s.SRB_Lun = deviceInfo->info.lun;
  200878. s.SRB_SenseLen = SENSE_LEN;
  200879. }
  200880. void CDController::perform (SRB_ExecSCSICmd& s)
  200881. {
  200882. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  200883. s.SRB_PostProc = (void*)event;
  200884. ResetEvent (event);
  200885. DWORD status = (usingScsi) ? performScsiPassThroughCommand ((LPSRB_ExecSCSICmd)&s,
  200886. deviceInfo->info.scsiDriveLetter,
  200887. deviceInfo->scsiHandle)
  200888. : fSendASPI32Command ((LPSRB)&s);
  200889. if (status == SS_PENDING)
  200890. WaitForSingleObject (event, 4000);
  200891. CloseHandle (event);
  200892. }
  200893. void CDController::setPaused (bool paused)
  200894. {
  200895. SRB_ExecSCSICmd s;
  200896. prepare (s);
  200897. s.SRB_Flags = SRB_EVENT_NOTIFY;
  200898. s.SRB_CDBLen = 10;
  200899. s.CDBByte[0] = 0x4B;
  200900. s.CDBByte[8] = (BYTE) (paused ? 0 : 1);
  200901. perform (s);
  200902. }
  200903. void CDController::shutDown()
  200904. {
  200905. }
  200906. bool CDController::readAudio (CDReadBuffer* rb, CDReadBuffer* overlapBuffer)
  200907. {
  200908. if (overlapBuffer != 0)
  200909. {
  200910. const bool canDoJitter = (overlapBuffer->bufferSize >= 2352 * framesToCheck);
  200911. const bool doJitter = canDoJitter && ! overlapBuffer->isZero();
  200912. if (doJitter
  200913. && overlapBuffer->startFrame > 0
  200914. && overlapBuffer->numFrames > 0
  200915. && overlapBuffer->dataLength > 0)
  200916. {
  200917. const int numFrames = rb->numFrames;
  200918. if (overlapBuffer->startFrame == (rb->startFrame - framesToCheck))
  200919. {
  200920. rb->startFrame -= framesOverlap;
  200921. if (framesToCheck < framesOverlap
  200922. && numFrames + framesOverlap <= rb->bufferSize / 2352)
  200923. rb->numFrames += framesOverlap;
  200924. }
  200925. else
  200926. {
  200927. overlapBuffer->dataLength = 0;
  200928. overlapBuffer->startFrame = 0;
  200929. overlapBuffer->numFrames = 0;
  200930. }
  200931. }
  200932. if (! read (rb))
  200933. return false;
  200934. if (doJitter)
  200935. {
  200936. const int checkLen = framesToCheck * 2352;
  200937. const int maxToCheck = rb->dataLength - checkLen;
  200938. if (overlapBuffer->dataLength == 0 || overlapBuffer->isZero())
  200939. return true;
  200940. BYTE* const p = overlapBuffer->buffer + overlapBuffer->dataStartOffset;
  200941. bool found = false;
  200942. for (int i = 0; i < maxToCheck; ++i)
  200943. {
  200944. if (!memcmp (p, rb->buffer + i, checkLen))
  200945. {
  200946. i += checkLen;
  200947. rb->dataStartOffset = i;
  200948. rb->dataLength -= i;
  200949. rb->startFrame = overlapBuffer->startFrame + framesToCheck;
  200950. found = true;
  200951. break;
  200952. }
  200953. }
  200954. rb->numFrames = rb->dataLength / 2352;
  200955. rb->dataLength = 2352 * rb->numFrames;
  200956. if (!found)
  200957. return false;
  200958. }
  200959. if (canDoJitter)
  200960. {
  200961. memcpy (overlapBuffer->buffer,
  200962. rb->buffer + rb->dataStartOffset + 2352 * (rb->numFrames - framesToCheck),
  200963. 2352 * framesToCheck);
  200964. overlapBuffer->startFrame = rb->startFrame + rb->numFrames - framesToCheck;
  200965. overlapBuffer->numFrames = framesToCheck;
  200966. overlapBuffer->dataLength = 2352 * framesToCheck;
  200967. overlapBuffer->dataStartOffset = 0;
  200968. }
  200969. else
  200970. {
  200971. overlapBuffer->startFrame = 0;
  200972. overlapBuffer->numFrames = 0;
  200973. overlapBuffer->dataLength = 0;
  200974. }
  200975. return true;
  200976. }
  200977. else
  200978. {
  200979. return read (rb);
  200980. }
  200981. }
  200982. int CDController::getLastIndex()
  200983. {
  200984. char qdata[100];
  200985. SRB_ExecSCSICmd s;
  200986. prepare (s);
  200987. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  200988. s.SRB_BufLen = sizeof (qdata);
  200989. s.SRB_BufPointer = (BYTE*)qdata;
  200990. s.SRB_CDBLen = 12;
  200991. s.CDBByte[0] = 0x42;
  200992. s.CDBByte[1] = (BYTE)(deviceInfo->info.lun << 5);
  200993. s.CDBByte[2] = 64;
  200994. s.CDBByte[3] = 1; // get current position
  200995. s.CDBByte[7] = 0;
  200996. s.CDBByte[8] = (BYTE)sizeof (qdata);
  200997. perform (s);
  200998. if (s.SRB_Status == SS_COMP)
  200999. return qdata[7];
  201000. return 0;
  201001. }
  201002. bool CDDeviceHandle::readTOC (TOC* lpToc, bool useMSF)
  201003. {
  201004. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  201005. SRB_ExecSCSICmd s;
  201006. zerostruct (s);
  201007. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  201008. s.SRB_HaID = info.ha;
  201009. s.SRB_Target = info.tgt;
  201010. s.SRB_Lun = info.lun;
  201011. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  201012. s.SRB_BufLen = 0x324;
  201013. s.SRB_BufPointer = (BYTE*)lpToc;
  201014. s.SRB_SenseLen = 0x0E;
  201015. s.SRB_CDBLen = 0x0A;
  201016. s.SRB_PostProc = (void*)event;
  201017. s.CDBByte[0] = 0x43;
  201018. s.CDBByte[1] = (BYTE)(useMSF ? 0x02 : 0x00);
  201019. s.CDBByte[7] = 0x03;
  201020. s.CDBByte[8] = 0x24;
  201021. ResetEvent (event);
  201022. DWORD status = (usingScsi) ? performScsiPassThroughCommand ((LPSRB_ExecSCSICmd)&s, info.scsiDriveLetter, scsiHandle)
  201023. : fSendASPI32Command ((LPSRB)&s);
  201024. if (status == SS_PENDING)
  201025. WaitForSingleObject (event, 4000);
  201026. CloseHandle (event);
  201027. return (s.SRB_Status == SS_COMP);
  201028. }
  201029. bool CDDeviceHandle::readAudio (CDReadBuffer* const buffer,
  201030. CDReadBuffer* const overlapBuffer)
  201031. {
  201032. if (controller == 0)
  201033. {
  201034. testController (READTYPE_ATAPI2, new ControllerType1(), buffer)
  201035. || testController (READTYPE_ATAPI1, new ControllerType1(), buffer)
  201036. || testController (READTYPE_READ10_2, new ControllerType2(), buffer)
  201037. || testController (READTYPE_READ10, new ControllerType2(), buffer)
  201038. || testController (READTYPE_READ_D8, new ControllerType3(), buffer)
  201039. || testController (READTYPE_READ_D4, new ControllerType4(), buffer)
  201040. || testController (READTYPE_READ_D4_1, new ControllerType4(), buffer);
  201041. }
  201042. buffer->index = 0;
  201043. if ((controller != 0)
  201044. && controller->readAudio (buffer, overlapBuffer))
  201045. {
  201046. if (buffer->wantsIndex)
  201047. buffer->index = controller->getLastIndex();
  201048. return true;
  201049. }
  201050. return false;
  201051. }
  201052. void CDDeviceHandle::openDrawer (bool shouldBeOpen)
  201053. {
  201054. if (shouldBeOpen)
  201055. {
  201056. if (controller != 0)
  201057. {
  201058. controller->shutDown();
  201059. delete controller;
  201060. controller = 0;
  201061. }
  201062. if (scsiHandle != 0)
  201063. {
  201064. CloseHandle (scsiHandle);
  201065. scsiHandle = 0;
  201066. }
  201067. }
  201068. SRB_ExecSCSICmd s;
  201069. zerostruct (s);
  201070. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  201071. s.SRB_HaID = info.ha;
  201072. s.SRB_Target = info.tgt;
  201073. s.SRB_Lun = info.lun;
  201074. s.SRB_SenseLen = SENSE_LEN;
  201075. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  201076. s.SRB_BufLen = 0;
  201077. s.SRB_BufPointer = 0;
  201078. s.SRB_CDBLen = 12;
  201079. s.CDBByte[0] = 0x1b;
  201080. s.CDBByte[1] = (BYTE)(info.lun << 5);
  201081. s.CDBByte[4] = (BYTE)((shouldBeOpen) ? 2 : 3);
  201082. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  201083. s.SRB_PostProc = (void*)event;
  201084. ResetEvent (event);
  201085. DWORD status = (usingScsi) ? performScsiPassThroughCommand ((LPSRB_ExecSCSICmd)&s, info.scsiDriveLetter, scsiHandle)
  201086. : fSendASPI32Command ((LPSRB)&s);
  201087. if (status == SS_PENDING)
  201088. WaitForSingleObject (event, 4000);
  201089. CloseHandle (event);
  201090. }
  201091. bool CDDeviceHandle::testController (const int type,
  201092. CDController* const newController,
  201093. CDReadBuffer* const rb)
  201094. {
  201095. controller = newController;
  201096. readType = (BYTE)type;
  201097. controller->deviceInfo = this;
  201098. controller->framesToCheck = 1;
  201099. controller->framesOverlap = 3;
  201100. bool passed = false;
  201101. memset (rb->buffer, 0xcd, rb->bufferSize);
  201102. if (controller->read (rb))
  201103. {
  201104. passed = true;
  201105. int* p = (int*) (rb->buffer + rb->dataStartOffset);
  201106. int wrong = 0;
  201107. for (int i = rb->dataLength / 4; --i >= 0;)
  201108. {
  201109. if (*p++ == (int) 0xcdcdcdcd)
  201110. {
  201111. if (++wrong == 4)
  201112. {
  201113. passed = false;
  201114. break;
  201115. }
  201116. }
  201117. else
  201118. {
  201119. wrong = 0;
  201120. }
  201121. }
  201122. }
  201123. if (! passed)
  201124. {
  201125. controller->shutDown();
  201126. delete controller;
  201127. controller = 0;
  201128. }
  201129. return passed;
  201130. }
  201131. static void GetAspiDeviceInfo (CDDeviceInfo* dev, BYTE ha, BYTE tgt, BYTE lun)
  201132. {
  201133. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  201134. const int bufSize = 128;
  201135. BYTE buffer[bufSize];
  201136. zeromem (buffer, bufSize);
  201137. SRB_ExecSCSICmd s;
  201138. zerostruct (s);
  201139. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  201140. s.SRB_HaID = ha;
  201141. s.SRB_Target = tgt;
  201142. s.SRB_Lun = lun;
  201143. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  201144. s.SRB_BufLen = bufSize;
  201145. s.SRB_BufPointer = buffer;
  201146. s.SRB_SenseLen = SENSE_LEN;
  201147. s.SRB_CDBLen = 6;
  201148. s.SRB_PostProc = (void*)event;
  201149. s.CDBByte[0] = SCSI_INQUIRY;
  201150. s.CDBByte[4] = 100;
  201151. ResetEvent (event);
  201152. if (fSendASPI32Command ((LPSRB)&s) == SS_PENDING)
  201153. WaitForSingleObject (event, 4000);
  201154. CloseHandle (event);
  201155. if (s.SRB_Status == SS_COMP)
  201156. {
  201157. memcpy (dev->vendor, &buffer[8], 8);
  201158. memcpy (dev->productId, &buffer[16], 16);
  201159. memcpy (dev->rev, &buffer[32], 4);
  201160. memcpy (dev->vendorSpec, &buffer[36], 20);
  201161. }
  201162. }
  201163. static int FindCDDevices (CDDeviceInfo* const list,
  201164. int maxItems)
  201165. {
  201166. int count = 0;
  201167. if (usingScsi)
  201168. {
  201169. for (char driveLetter = 'b'; driveLetter <= 'z'; ++driveLetter)
  201170. {
  201171. TCHAR drivePath[8];
  201172. drivePath[0] = driveLetter;
  201173. drivePath[1] = ':';
  201174. drivePath[2] = '\\';
  201175. drivePath[3] = 0;
  201176. if (GetDriveType (drivePath) == DRIVE_CDROM)
  201177. {
  201178. HANDLE h = CreateSCSIDeviceHandle (driveLetter);
  201179. if (h != INVALID_HANDLE_VALUE)
  201180. {
  201181. BYTE buffer[100], passThroughStruct[1024];
  201182. zeromem (buffer, sizeof (buffer));
  201183. zeromem (passThroughStruct, sizeof (passThroughStruct));
  201184. PSCSI_PASS_THROUGH_DIRECT_WITH_BUFFER p = (PSCSI_PASS_THROUGH_DIRECT_WITH_BUFFER)passThroughStruct;
  201185. p->spt.Length = sizeof (SCSI_PASS_THROUGH);
  201186. p->spt.CdbLength = 6;
  201187. p->spt.SenseInfoLength = 24;
  201188. p->spt.DataIn = SCSI_IOCTL_DATA_IN;
  201189. p->spt.DataTransferLength = 100;
  201190. p->spt.TimeOutValue = 2;
  201191. p->spt.DataBuffer = buffer;
  201192. p->spt.SenseInfoOffset = offsetof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, ucSenseBuf);
  201193. p->spt.Cdb[0] = 0x12;
  201194. p->spt.Cdb[4] = 100;
  201195. DWORD bytesReturned = 0;
  201196. if (DeviceIoControl (h, IOCTL_SCSI_PASS_THROUGH_DIRECT,
  201197. p, sizeof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER),
  201198. p, sizeof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER),
  201199. &bytesReturned, 0) != 0)
  201200. {
  201201. zeromem (&list[count], sizeof (CDDeviceInfo));
  201202. list[count].scsiDriveLetter = driveLetter;
  201203. memcpy (list[count].vendor, &buffer[8], 8);
  201204. memcpy (list[count].productId, &buffer[16], 16);
  201205. memcpy (list[count].rev, &buffer[32], 4);
  201206. memcpy (list[count].vendorSpec, &buffer[36], 20);
  201207. zeromem (passThroughStruct, sizeof (passThroughStruct));
  201208. PSCSI_ADDRESS scsiAddr = (PSCSI_ADDRESS)passThroughStruct;
  201209. scsiAddr->Length = sizeof (SCSI_ADDRESS);
  201210. if (DeviceIoControl (h, IOCTL_SCSI_GET_ADDRESS,
  201211. 0, 0, scsiAddr, sizeof (SCSI_ADDRESS),
  201212. &bytesReturned, 0) != 0)
  201213. {
  201214. list[count].ha = scsiAddr->PortNumber;
  201215. list[count].tgt = scsiAddr->TargetId;
  201216. list[count].lun = scsiAddr->Lun;
  201217. ++count;
  201218. }
  201219. }
  201220. CloseHandle (h);
  201221. }
  201222. }
  201223. }
  201224. }
  201225. else
  201226. {
  201227. const DWORD d = fGetASPI32SupportInfo();
  201228. BYTE status = HIBYTE (LOWORD (d));
  201229. if (status != SS_COMP || status == SS_NO_ADAPTERS)
  201230. return 0;
  201231. const int numAdapters = LOBYTE (LOWORD (d));
  201232. for (BYTE ha = 0; ha < numAdapters; ++ha)
  201233. {
  201234. SRB_HAInquiry s;
  201235. zerostruct (s);
  201236. s.SRB_Cmd = SC_HA_INQUIRY;
  201237. s.SRB_HaID = ha;
  201238. fSendASPI32Command ((LPSRB)&s);
  201239. if (s.SRB_Status == SS_COMP)
  201240. {
  201241. maxItems = (int)s.HA_Unique[3];
  201242. if (maxItems == 0)
  201243. maxItems = 8;
  201244. for (BYTE tgt = 0; tgt < maxItems; ++tgt)
  201245. {
  201246. for (BYTE lun = 0; lun < 8; ++lun)
  201247. {
  201248. SRB_GDEVBlock sb;
  201249. zerostruct (sb);
  201250. sb.SRB_Cmd = SC_GET_DEV_TYPE;
  201251. sb.SRB_HaID = ha;
  201252. sb.SRB_Target = tgt;
  201253. sb.SRB_Lun = lun;
  201254. fSendASPI32Command ((LPSRB) &sb);
  201255. if (sb.SRB_Status == SS_COMP
  201256. && sb.SRB_DeviceType == DTYPE_CROM)
  201257. {
  201258. zeromem (&list[count], sizeof (CDDeviceInfo));
  201259. list[count].ha = ha;
  201260. list[count].tgt = tgt;
  201261. list[count].lun = lun;
  201262. GetAspiDeviceInfo (&(list[count]), ha, tgt, lun);
  201263. ++count;
  201264. }
  201265. }
  201266. }
  201267. }
  201268. }
  201269. }
  201270. return count;
  201271. }
  201272. static int ripperUsers = 0;
  201273. static bool initialisedOk = false;
  201274. class DeinitialiseTimer : private Timer,
  201275. private DeletedAtShutdown
  201276. {
  201277. DeinitialiseTimer (const DeinitialiseTimer&);
  201278. const DeinitialiseTimer& operator= (const DeinitialiseTimer&);
  201279. public:
  201280. DeinitialiseTimer()
  201281. {
  201282. startTimer (4000);
  201283. }
  201284. ~DeinitialiseTimer()
  201285. {
  201286. if (--ripperUsers == 0)
  201287. DeinitialiseCDRipper();
  201288. }
  201289. void timerCallback()
  201290. {
  201291. delete this;
  201292. }
  201293. juce_UseDebuggingNewOperator
  201294. };
  201295. static void incUserCount()
  201296. {
  201297. if (ripperUsers++ == 0)
  201298. initialisedOk = InitialiseCDRipper();
  201299. }
  201300. static void decUserCount()
  201301. {
  201302. new DeinitialiseTimer();
  201303. }
  201304. struct CDDeviceWrapper
  201305. {
  201306. CDDeviceHandle* cdH;
  201307. CDReadBuffer* overlapBuffer;
  201308. bool jitter;
  201309. };
  201310. static int getAddressOf (const TOCTRACK* const t)
  201311. {
  201312. return (((DWORD)t->addr[0]) << 24) + (((DWORD)t->addr[1]) << 16) +
  201313. (((DWORD)t->addr[2]) << 8) + ((DWORD)t->addr[3]);
  201314. }
  201315. static int getMSFAddressOf (const TOCTRACK* const t)
  201316. {
  201317. return 60 * t->addr[1] + t->addr[2];
  201318. }
  201319. static const int samplesPerFrame = 44100 / 75;
  201320. static const int bytesPerFrame = samplesPerFrame * 4;
  201321. const StringArray AudioCDReader::getAvailableCDNames()
  201322. {
  201323. StringArray results;
  201324. incUserCount();
  201325. if (initialisedOk)
  201326. {
  201327. CDDeviceInfo list[8];
  201328. const int num = FindCDDevices (list, 8);
  201329. decUserCount();
  201330. for (int i = 0; i < num; ++i)
  201331. {
  201332. String s;
  201333. if (list[i].scsiDriveLetter > 0)
  201334. s << String::charToString (list[i].scsiDriveLetter).toUpperCase() << T(": ");
  201335. s << String (list[i].vendor).trim()
  201336. << T(" ") << String (list[i].productId).trim()
  201337. << T(" ") << String (list[i].rev).trim();
  201338. results.add (s);
  201339. }
  201340. }
  201341. return results;
  201342. }
  201343. static CDDeviceHandle* openHandle (const CDDeviceInfo* const device)
  201344. {
  201345. SRB_GDEVBlock s;
  201346. zerostruct (s);
  201347. s.SRB_Cmd = SC_GET_DEV_TYPE;
  201348. s.SRB_HaID = device->ha;
  201349. s.SRB_Target = device->tgt;
  201350. s.SRB_Lun = device->lun;
  201351. if (usingScsi)
  201352. {
  201353. HANDLE h = CreateSCSIDeviceHandle (device->scsiDriveLetter);
  201354. if (h != INVALID_HANDLE_VALUE)
  201355. {
  201356. CDDeviceHandle* cdh = new CDDeviceHandle (device);
  201357. cdh->scsiHandle = h;
  201358. return cdh;
  201359. }
  201360. }
  201361. else
  201362. {
  201363. if (fSendASPI32Command ((LPSRB)&s) == SS_COMP
  201364. && s.SRB_DeviceType == DTYPE_CROM)
  201365. {
  201366. return new CDDeviceHandle (device);
  201367. }
  201368. }
  201369. return 0;
  201370. }
  201371. AudioCDReader* AudioCDReader::createReaderForCD (const int deviceIndex)
  201372. {
  201373. incUserCount();
  201374. if (initialisedOk)
  201375. {
  201376. CDDeviceInfo list[8];
  201377. const int num = FindCDDevices (list, 8);
  201378. if (((unsigned int) deviceIndex) < (unsigned int) num)
  201379. {
  201380. CDDeviceHandle* const handle = openHandle (&(list[deviceIndex]));
  201381. if (handle != 0)
  201382. {
  201383. CDDeviceWrapper* const d = new CDDeviceWrapper();
  201384. d->cdH = handle;
  201385. d->overlapBuffer = new CDReadBuffer(3);
  201386. return new AudioCDReader (d);
  201387. }
  201388. }
  201389. }
  201390. decUserCount();
  201391. return 0;
  201392. }
  201393. AudioCDReader::AudioCDReader (void* handle_)
  201394. : AudioFormatReader (0, T("CD Audio")),
  201395. handle (handle_),
  201396. indexingEnabled (false),
  201397. lastIndex (0),
  201398. firstFrameInBuffer (0),
  201399. samplesInBuffer (0)
  201400. {
  201401. jassert (handle_ != 0);
  201402. refreshTrackLengths();
  201403. sampleRate = 44100.0;
  201404. bitsPerSample = 16;
  201405. lengthInSamples = getPositionOfTrackStart (numTracks);
  201406. numChannels = 2;
  201407. usesFloatingPointData = false;
  201408. buffer.setSize (4 * bytesPerFrame, true);
  201409. }
  201410. AudioCDReader::~AudioCDReader()
  201411. {
  201412. CDDeviceWrapper* const device = (CDDeviceWrapper*)handle;
  201413. delete device->cdH;
  201414. delete device->overlapBuffer;
  201415. delete device;
  201416. decUserCount();
  201417. }
  201418. bool AudioCDReader::read (int** destSamples,
  201419. int64 startSampleInFile,
  201420. int numSamples)
  201421. {
  201422. CDDeviceWrapper* const device = (CDDeviceWrapper*)handle;
  201423. bool ok = true;
  201424. int offset = 0;
  201425. if (startSampleInFile < 0)
  201426. {
  201427. int* l = destSamples[0];
  201428. int* r = destSamples[1];
  201429. numSamples += (int) startSampleInFile;
  201430. offset -= (int) startSampleInFile;
  201431. while (++startSampleInFile <= 0)
  201432. {
  201433. *l++ = 0;
  201434. if (r != 0)
  201435. *r++ = 0;
  201436. }
  201437. }
  201438. while (numSamples > 0)
  201439. {
  201440. const int bufferStartSample = firstFrameInBuffer * samplesPerFrame;
  201441. const int bufferEndSample = bufferStartSample + samplesInBuffer;
  201442. if (startSampleInFile >= bufferStartSample
  201443. && startSampleInFile < bufferEndSample)
  201444. {
  201445. const int toDo = (int) jmin ((int64) numSamples, bufferEndSample - startSampleInFile);
  201446. int* const l = destSamples[0] + offset;
  201447. int* const r = destSamples[1] + offset;
  201448. const short* src = (const short*) buffer.getData();
  201449. src += 2 * (startSampleInFile - bufferStartSample);
  201450. for (int i = 0; i < toDo; ++i)
  201451. {
  201452. l[i] = src [i << 1] << 16;
  201453. if (r != 0)
  201454. r[i] = src [(i << 1) + 1] << 16;
  201455. }
  201456. offset += toDo;
  201457. startSampleInFile += toDo;
  201458. numSamples -= toDo;
  201459. }
  201460. else
  201461. {
  201462. const int framesInBuffer = buffer.getSize() / bytesPerFrame;
  201463. const int frameNeeded = (int) (startSampleInFile / samplesPerFrame);
  201464. if (firstFrameInBuffer + framesInBuffer != frameNeeded)
  201465. {
  201466. device->overlapBuffer->dataLength = 0;
  201467. device->overlapBuffer->startFrame = 0;
  201468. device->overlapBuffer->numFrames = 0;
  201469. device->jitter = false;
  201470. }
  201471. firstFrameInBuffer = frameNeeded;
  201472. lastIndex = 0;
  201473. CDReadBuffer readBuffer (framesInBuffer + 4);
  201474. readBuffer.wantsIndex = indexingEnabled;
  201475. int i;
  201476. for (i = 5; --i >= 0;)
  201477. {
  201478. readBuffer.startFrame = frameNeeded;
  201479. readBuffer.numFrames = framesInBuffer;
  201480. if (device->cdH->readAudio (&readBuffer, (device->jitter) ? device->overlapBuffer : 0))
  201481. break;
  201482. else
  201483. device->overlapBuffer->dataLength = 0;
  201484. }
  201485. if (i >= 0)
  201486. {
  201487. memcpy ((char*) buffer.getData(),
  201488. readBuffer.buffer + readBuffer.dataStartOffset,
  201489. readBuffer.dataLength);
  201490. samplesInBuffer = readBuffer.dataLength >> 2;
  201491. lastIndex = readBuffer.index;
  201492. }
  201493. else
  201494. {
  201495. int* l = destSamples[0] + offset;
  201496. int* r = destSamples[1] + offset;
  201497. while (--numSamples >= 0)
  201498. {
  201499. *l++ = 0;
  201500. if (r != 0)
  201501. *r++ = 0;
  201502. }
  201503. // sometimes the read fails for just the very last couple of blocks, so
  201504. // we'll ignore and errors in the last half-second of the disk..
  201505. ok = startSampleInFile > (trackStarts [numTracks] - 20000);
  201506. break;
  201507. }
  201508. }
  201509. }
  201510. return ok;
  201511. }
  201512. bool AudioCDReader::isCDStillPresent() const
  201513. {
  201514. TOC toc;
  201515. zerostruct (toc);
  201516. return ((CDDeviceWrapper*)handle)->cdH->readTOC (&toc, false);
  201517. }
  201518. int AudioCDReader::getNumTracks() const
  201519. {
  201520. return numTracks;
  201521. }
  201522. int AudioCDReader::getPositionOfTrackStart (int trackNum) const
  201523. {
  201524. return (trackNum >= 0 && trackNum <= numTracks) ? trackStarts [trackNum] * samplesPerFrame
  201525. : 0;
  201526. }
  201527. void AudioCDReader::refreshTrackLengths()
  201528. {
  201529. zeromem (trackStarts, sizeof (trackStarts));
  201530. zeromem (audioTracks, sizeof (audioTracks));
  201531. TOC toc;
  201532. zerostruct (toc);
  201533. if (((CDDeviceWrapper*)handle)->cdH->readTOC (&toc, false))
  201534. {
  201535. numTracks = 1 + toc.lastTrack - toc.firstTrack;
  201536. for (int i = 0; i <= numTracks; ++i)
  201537. {
  201538. trackStarts[i] = getAddressOf (&toc.tracks[i]);
  201539. audioTracks[i] = ((toc.tracks[i].ADR & 4) == 0);
  201540. }
  201541. }
  201542. else
  201543. {
  201544. numTracks = 0;
  201545. }
  201546. }
  201547. bool AudioCDReader::isTrackAudio (int trackNum) const
  201548. {
  201549. return (trackNum >= 0 && trackNum <= numTracks) ? audioTracks [trackNum]
  201550. : false;
  201551. }
  201552. void AudioCDReader::enableIndexScanning (bool b)
  201553. {
  201554. indexingEnabled = b;
  201555. }
  201556. int AudioCDReader::getLastIndex() const
  201557. {
  201558. return lastIndex;
  201559. }
  201560. const int framesPerIndexRead = 4;
  201561. int AudioCDReader::getIndexAt (int samplePos)
  201562. {
  201563. CDDeviceWrapper* const device = (CDDeviceWrapper*) handle;
  201564. const int frameNeeded = samplePos / samplesPerFrame;
  201565. device->overlapBuffer->dataLength = 0;
  201566. device->overlapBuffer->startFrame = 0;
  201567. device->overlapBuffer->numFrames = 0;
  201568. device->jitter = false;
  201569. firstFrameInBuffer = 0;
  201570. lastIndex = 0;
  201571. CDReadBuffer readBuffer (4 + framesPerIndexRead);
  201572. readBuffer.wantsIndex = true;
  201573. int i;
  201574. for (i = 5; --i >= 0;)
  201575. {
  201576. readBuffer.startFrame = frameNeeded;
  201577. readBuffer.numFrames = framesPerIndexRead;
  201578. if (device->cdH->readAudio (&readBuffer, (false) ? device->overlapBuffer : 0))
  201579. break;
  201580. }
  201581. if (i >= 0)
  201582. return readBuffer.index;
  201583. return -1;
  201584. }
  201585. const Array <int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  201586. {
  201587. Array <int> indexes;
  201588. const int trackStart = getPositionOfTrackStart (trackNumber);
  201589. const int trackEnd = getPositionOfTrackStart (trackNumber + 1);
  201590. bool needToScan = true;
  201591. if (trackEnd - trackStart > 20 * 44100)
  201592. {
  201593. // check the end of the track for indexes before scanning the whole thing
  201594. needToScan = false;
  201595. int pos = jmax (trackStart, trackEnd - 44100 * 5);
  201596. bool seenAnIndex = false;
  201597. while (pos <= trackEnd - samplesPerFrame)
  201598. {
  201599. const int index = getIndexAt (pos);
  201600. if (index == 0)
  201601. {
  201602. // lead-out, so skip back a bit if we've not found any indexes yet..
  201603. if (seenAnIndex)
  201604. break;
  201605. pos -= 44100 * 5;
  201606. if (pos < trackStart)
  201607. break;
  201608. }
  201609. else
  201610. {
  201611. if (index > 0)
  201612. seenAnIndex = true;
  201613. if (index > 1)
  201614. {
  201615. needToScan = true;
  201616. break;
  201617. }
  201618. pos += samplesPerFrame * framesPerIndexRead;
  201619. }
  201620. }
  201621. }
  201622. if (needToScan)
  201623. {
  201624. CDDeviceWrapper* const device = (CDDeviceWrapper*) handle;
  201625. int pos = trackStart;
  201626. int last = -1;
  201627. while (pos < trackEnd - samplesPerFrame * 10)
  201628. {
  201629. const int frameNeeded = pos / samplesPerFrame;
  201630. device->overlapBuffer->dataLength = 0;
  201631. device->overlapBuffer->startFrame = 0;
  201632. device->overlapBuffer->numFrames = 0;
  201633. device->jitter = false;
  201634. firstFrameInBuffer = 0;
  201635. CDReadBuffer readBuffer (4);
  201636. readBuffer.wantsIndex = true;
  201637. int i;
  201638. for (i = 5; --i >= 0;)
  201639. {
  201640. readBuffer.startFrame = frameNeeded;
  201641. readBuffer.numFrames = framesPerIndexRead;
  201642. if (device->cdH->readAudio (&readBuffer, (false) ? device->overlapBuffer : 0))
  201643. break;
  201644. }
  201645. if (i < 0)
  201646. break;
  201647. if (readBuffer.index > last && readBuffer.index > 1)
  201648. {
  201649. last = readBuffer.index;
  201650. indexes.add (pos);
  201651. }
  201652. pos += samplesPerFrame * framesPerIndexRead;
  201653. }
  201654. indexes.removeValue (trackStart);
  201655. }
  201656. return indexes;
  201657. }
  201658. int AudioCDReader::getCDDBId()
  201659. {
  201660. refreshTrackLengths();
  201661. if (numTracks > 0)
  201662. {
  201663. TOC toc;
  201664. zerostruct (toc);
  201665. if (((CDDeviceWrapper*) handle)->cdH->readTOC (&toc, true))
  201666. {
  201667. int n = 0;
  201668. for (int i = numTracks; --i >= 0;)
  201669. {
  201670. int j = getMSFAddressOf (&toc.tracks[i]);
  201671. while (j > 0)
  201672. {
  201673. n += (j % 10);
  201674. j /= 10;
  201675. }
  201676. }
  201677. if (n != 0)
  201678. {
  201679. const int t = getMSFAddressOf (&toc.tracks[numTracks])
  201680. - getMSFAddressOf (&toc.tracks[0]);
  201681. return ((n % 0xff) << 24) | (t << 8) | numTracks;
  201682. }
  201683. }
  201684. }
  201685. return 0;
  201686. }
  201687. void AudioCDReader::ejectDisk()
  201688. {
  201689. ((CDDeviceWrapper*) handle)->cdH->openDrawer (true);
  201690. }
  201691. #if JUCE_USE_CDBURNER
  201692. static IDiscRecorder* enumCDBurners (StringArray* list, int indexToOpen, IDiscMaster** master)
  201693. {
  201694. CoInitialize (0);
  201695. IDiscMaster* dm;
  201696. IDiscRecorder* result = 0;
  201697. if (SUCCEEDED (CoCreateInstance (CLSID_MSDiscMasterObj, 0,
  201698. CLSCTX_INPROC_SERVER | CLSCTX_LOCAL_SERVER,
  201699. IID_IDiscMaster,
  201700. (void**) &dm)))
  201701. {
  201702. if (SUCCEEDED (dm->Open()))
  201703. {
  201704. IEnumDiscRecorders* drEnum = 0;
  201705. if (SUCCEEDED (dm->EnumDiscRecorders (&drEnum)))
  201706. {
  201707. IDiscRecorder* dr = 0;
  201708. DWORD dummy;
  201709. int index = 0;
  201710. while (drEnum->Next (1, &dr, &dummy) == S_OK)
  201711. {
  201712. if (indexToOpen == index)
  201713. {
  201714. result = dr;
  201715. break;
  201716. }
  201717. else if (list != 0)
  201718. {
  201719. BSTR path;
  201720. if (SUCCEEDED (dr->GetPath (&path)))
  201721. list->add ((const WCHAR*) path);
  201722. }
  201723. ++index;
  201724. dr->Release();
  201725. }
  201726. drEnum->Release();
  201727. }
  201728. /*if (redbookFormat != 0)
  201729. {
  201730. IEnumDiscMasterFormats* mfEnum;
  201731. if (SUCCEEDED (dm->EnumDiscMasterFormats (&mfEnum)))
  201732. {
  201733. IID formatIID;
  201734. DWORD dummy;
  201735. while (mfEnum->Next (1, &formatIID, &dummy) == S_OK)
  201736. {
  201737. }
  201738. mfEnum->Release();
  201739. }
  201740. redbookFormat
  201741. }*/
  201742. if (master == 0)
  201743. dm->Close();
  201744. }
  201745. if (master != 0)
  201746. *master = dm;
  201747. else
  201748. dm->Release();
  201749. }
  201750. return result;
  201751. }
  201752. const StringArray AudioCDBurner::findAvailableDevices()
  201753. {
  201754. StringArray devs;
  201755. enumCDBurners (&devs, -1, 0);
  201756. return devs;
  201757. }
  201758. AudioCDBurner* AudioCDBurner::openDevice (const int deviceIndex)
  201759. {
  201760. AudioCDBurner* b = new AudioCDBurner (deviceIndex);
  201761. if (b->internal == 0)
  201762. deleteAndZero (b);
  201763. return b;
  201764. }
  201765. class CDBurnerInfo : public IDiscMasterProgressEvents
  201766. {
  201767. public:
  201768. CDBurnerInfo()
  201769. : refCount (1),
  201770. progress (0),
  201771. shouldCancel (false),
  201772. listener (0)
  201773. {
  201774. }
  201775. ~CDBurnerInfo()
  201776. {
  201777. }
  201778. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  201779. {
  201780. if (result == 0)
  201781. return E_POINTER;
  201782. if (id == IID_IUnknown || id == IID_IDiscMasterProgressEvents)
  201783. {
  201784. AddRef();
  201785. *result = this;
  201786. return S_OK;
  201787. }
  201788. *result = 0;
  201789. return E_NOINTERFACE;
  201790. }
  201791. ULONG __stdcall AddRef() { return ++refCount; }
  201792. ULONG __stdcall Release() { jassert (refCount > 0); const int r = --refCount; if (r == 0) delete this; return r; }
  201793. HRESULT __stdcall QueryCancel (boolean* pbCancel)
  201794. {
  201795. if (listener != 0 && ! shouldCancel)
  201796. shouldCancel = listener->audioCDBurnProgress (progress);
  201797. *pbCancel = shouldCancel;
  201798. return S_OK;
  201799. }
  201800. HRESULT __stdcall NotifyBlockProgress (long nCompleted, long nTotal)
  201801. {
  201802. progress = nCompleted / (float) nTotal;
  201803. shouldCancel = listener != 0 && listener->audioCDBurnProgress (progress);
  201804. return E_NOTIMPL;
  201805. }
  201806. HRESULT __stdcall NotifyPnPActivity (void) { return E_NOTIMPL; }
  201807. HRESULT __stdcall NotifyAddProgress (long /*nCompletedSteps*/, long /*nTotalSteps*/) { return E_NOTIMPL; }
  201808. HRESULT __stdcall NotifyTrackProgress (long /*nCurrentTrack*/, long /*nTotalTracks*/) { return E_NOTIMPL; }
  201809. HRESULT __stdcall NotifyPreparingBurn (long /*nEstimatedSeconds*/) { return E_NOTIMPL; }
  201810. HRESULT __stdcall NotifyClosingDisc (long /*nEstimatedSeconds*/) { return E_NOTIMPL; }
  201811. HRESULT __stdcall NotifyBurnComplete (HRESULT /*status*/) { return E_NOTIMPL; }
  201812. HRESULT __stdcall NotifyEraseComplete (HRESULT /*status*/) { return E_NOTIMPL; }
  201813. IDiscMaster* discMaster;
  201814. IDiscRecorder* discRecorder;
  201815. IRedbookDiscMaster* redbook;
  201816. AudioCDBurner::BurnProgressListener* listener;
  201817. float progress;
  201818. bool shouldCancel;
  201819. private:
  201820. int refCount;
  201821. };
  201822. AudioCDBurner::AudioCDBurner (const int deviceIndex)
  201823. : internal (0)
  201824. {
  201825. IDiscMaster* discMaster;
  201826. IDiscRecorder* dr = enumCDBurners (0, deviceIndex, &discMaster);
  201827. if (dr != 0)
  201828. {
  201829. IRedbookDiscMaster* redbook;
  201830. HRESULT hr = discMaster->SetActiveDiscMasterFormat (IID_IRedbookDiscMaster, (void**) &redbook);
  201831. hr = discMaster->SetActiveDiscRecorder (dr);
  201832. CDBurnerInfo* const info = new CDBurnerInfo();
  201833. internal = info;
  201834. info->discMaster = discMaster;
  201835. info->discRecorder = dr;
  201836. info->redbook = redbook;
  201837. }
  201838. }
  201839. AudioCDBurner::~AudioCDBurner()
  201840. {
  201841. CDBurnerInfo* const info = (CDBurnerInfo*) internal;
  201842. if (info != 0)
  201843. {
  201844. info->discRecorder->Close();
  201845. info->redbook->Release();
  201846. info->discRecorder->Release();
  201847. info->discMaster->Release();
  201848. info->Release();
  201849. }
  201850. }
  201851. bool AudioCDBurner::isDiskPresent() const
  201852. {
  201853. CDBurnerInfo* const info = (CDBurnerInfo*) internal;
  201854. HRESULT hr = info->discRecorder->OpenExclusive();
  201855. long type, flags;
  201856. hr = info->discRecorder->QueryMediaType (&type, &flags);
  201857. info->discRecorder->Close();
  201858. return hr == S_OK && type != 0 && (flags & MEDIA_WRITABLE) != 0;
  201859. }
  201860. int AudioCDBurner::getNumAvailableAudioBlocks() const
  201861. {
  201862. CDBurnerInfo* const info = (CDBurnerInfo*) internal;
  201863. long blocksFree = 0;
  201864. info->redbook->GetAvailableAudioTrackBlocks (&blocksFree);
  201865. return blocksFree;
  201866. }
  201867. const String AudioCDBurner::burn (AudioCDBurner::BurnProgressListener* listener,
  201868. const bool ejectDiscAfterwards,
  201869. const bool performFakeBurnForTesting)
  201870. {
  201871. CDBurnerInfo* const info = (CDBurnerInfo*) internal;
  201872. info->listener = listener;
  201873. info->progress = 0;
  201874. info->shouldCancel = false;
  201875. UINT_PTR cookie;
  201876. HRESULT hr = info->discMaster->ProgressAdvise (info, &cookie);
  201877. hr = info->discMaster->RecordDisc (performFakeBurnForTesting,
  201878. ejectDiscAfterwards);
  201879. String error;
  201880. if (hr != S_OK)
  201881. {
  201882. const char* e = "Couldn't open or write to the CD device";
  201883. if (hr == IMAPI_E_USERABORT)
  201884. e = "User cancelled the write operation";
  201885. else if (hr == IMAPI_E_MEDIUM_NOTPRESENT || hr == IMAPI_E_TRACKOPEN)
  201886. e = "No Disk present";
  201887. error = e;
  201888. }
  201889. info->discMaster->ProgressUnadvise (cookie);
  201890. info->listener = 0;
  201891. return error;
  201892. }
  201893. bool AudioCDBurner::addAudioTrack (AudioSource* source, int numSamples)
  201894. {
  201895. if (source == 0)
  201896. return false;
  201897. CDBurnerInfo* const info = (CDBurnerInfo*) internal;
  201898. long bytesPerBlock;
  201899. HRESULT hr = info->redbook->GetAudioBlockSize (&bytesPerBlock);
  201900. const int samplesPerBlock = bytesPerBlock / 4;
  201901. bool ok = true;
  201902. hr = info->redbook->CreateAudioTrack ((long) numSamples / (bytesPerBlock * 4));
  201903. byte* const buffer = (byte*) juce_malloc (bytesPerBlock);
  201904. AudioSampleBuffer sourceBuffer (2, samplesPerBlock);
  201905. int samplesDone = 0;
  201906. source->prepareToPlay (samplesPerBlock, 44100.0);
  201907. while (ok)
  201908. {
  201909. {
  201910. AudioSourceChannelInfo info;
  201911. info.buffer = &sourceBuffer;
  201912. info.numSamples = samplesPerBlock;
  201913. info.startSample = 0;
  201914. sourceBuffer.clear();
  201915. source->getNextAudioBlock (info);
  201916. }
  201917. zeromem (buffer, bytesPerBlock);
  201918. AudioDataConverters::convertFloatToInt16LE (sourceBuffer.getSampleData (0, 0),
  201919. buffer, samplesPerBlock, 4);
  201920. AudioDataConverters::convertFloatToInt16LE (sourceBuffer.getSampleData (1, 0),
  201921. buffer + 2, samplesPerBlock, 4);
  201922. hr = info->redbook->AddAudioTrackBlocks (buffer, bytesPerBlock);
  201923. if (hr != S_OK)
  201924. ok = false;
  201925. samplesDone += samplesPerBlock;
  201926. if (samplesDone >= numSamples)
  201927. break;
  201928. }
  201929. juce_free (buffer);
  201930. hr = info->redbook->CloseAudioTrack();
  201931. delete source;
  201932. return ok && hr == S_OK;
  201933. }
  201934. #endif
  201935. END_JUCE_NAMESPACE
  201936. /********* End of inlined file: juce_win32_AudioCDReader.cpp *********/
  201937. /********* Start of inlined file: juce_win32_DirectSound.cpp *********/
  201938. extern "C"
  201939. {
  201940. // Declare just the minimum number of interfaces for the DSound objects that we need..
  201941. typedef struct typeDSBUFFERDESC
  201942. {
  201943. DWORD dwSize;
  201944. DWORD dwFlags;
  201945. DWORD dwBufferBytes;
  201946. DWORD dwReserved;
  201947. LPWAVEFORMATEX lpwfxFormat;
  201948. GUID guid3DAlgorithm;
  201949. } DSBUFFERDESC;
  201950. struct IDirectSoundBuffer;
  201951. #undef INTERFACE
  201952. #define INTERFACE IDirectSound
  201953. DECLARE_INTERFACE_(IDirectSound, IUnknown)
  201954. {
  201955. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  201956. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  201957. STDMETHOD_(ULONG,Release) (THIS) PURE;
  201958. STDMETHOD(CreateSoundBuffer) (THIS_ DSBUFFERDESC*, IDirectSoundBuffer**, LPUNKNOWN) PURE;
  201959. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  201960. STDMETHOD(DuplicateSoundBuffer) (THIS_ IDirectSoundBuffer*, IDirectSoundBuffer**) PURE;
  201961. STDMETHOD(SetCooperativeLevel) (THIS_ HWND, DWORD) PURE;
  201962. STDMETHOD(Compact) (THIS) PURE;
  201963. STDMETHOD(GetSpeakerConfig) (THIS_ LPDWORD) PURE;
  201964. STDMETHOD(SetSpeakerConfig) (THIS_ DWORD) PURE;
  201965. STDMETHOD(Initialize) (THIS_ const GUID*) PURE;
  201966. };
  201967. #undef INTERFACE
  201968. #define INTERFACE IDirectSoundBuffer
  201969. DECLARE_INTERFACE_(IDirectSoundBuffer, IUnknown)
  201970. {
  201971. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  201972. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  201973. STDMETHOD_(ULONG,Release) (THIS) PURE;
  201974. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  201975. STDMETHOD(GetCurrentPosition) (THIS_ LPDWORD, LPDWORD) PURE;
  201976. STDMETHOD(GetFormat) (THIS_ LPWAVEFORMATEX, DWORD, LPDWORD) PURE;
  201977. STDMETHOD(GetVolume) (THIS_ LPLONG) PURE;
  201978. STDMETHOD(GetPan) (THIS_ LPLONG) PURE;
  201979. STDMETHOD(GetFrequency) (THIS_ LPDWORD) PURE;
  201980. STDMETHOD(GetStatus) (THIS_ LPDWORD) PURE;
  201981. STDMETHOD(Initialize) (THIS_ IDirectSound*, DSBUFFERDESC*) PURE;
  201982. STDMETHOD(Lock) (THIS_ DWORD, DWORD, LPVOID*, LPDWORD, LPVOID*, LPDWORD, DWORD) PURE;
  201983. STDMETHOD(Play) (THIS_ DWORD, DWORD, DWORD) PURE;
  201984. STDMETHOD(SetCurrentPosition) (THIS_ DWORD) PURE;
  201985. STDMETHOD(SetFormat) (THIS_ const WAVEFORMATEX*) PURE;
  201986. STDMETHOD(SetVolume) (THIS_ LONG) PURE;
  201987. STDMETHOD(SetPan) (THIS_ LONG) PURE;
  201988. STDMETHOD(SetFrequency) (THIS_ DWORD) PURE;
  201989. STDMETHOD(Stop) (THIS) PURE;
  201990. STDMETHOD(Unlock) (THIS_ LPVOID, DWORD, LPVOID, DWORD) PURE;
  201991. STDMETHOD(Restore) (THIS) PURE;
  201992. };
  201993. typedef struct typeDSCBUFFERDESC
  201994. {
  201995. DWORD dwSize;
  201996. DWORD dwFlags;
  201997. DWORD dwBufferBytes;
  201998. DWORD dwReserved;
  201999. LPWAVEFORMATEX lpwfxFormat;
  202000. } DSCBUFFERDESC;
  202001. struct IDirectSoundCaptureBuffer;
  202002. #undef INTERFACE
  202003. #define INTERFACE IDirectSoundCapture
  202004. DECLARE_INTERFACE_(IDirectSoundCapture, IUnknown)
  202005. {
  202006. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  202007. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  202008. STDMETHOD_(ULONG,Release) (THIS) PURE;
  202009. STDMETHOD(CreateCaptureBuffer) (THIS_ DSCBUFFERDESC*, IDirectSoundCaptureBuffer**, LPUNKNOWN) PURE;
  202010. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  202011. STDMETHOD(Initialize) (THIS_ const GUID*) PURE;
  202012. };
  202013. #undef INTERFACE
  202014. #define INTERFACE IDirectSoundCaptureBuffer
  202015. DECLARE_INTERFACE_(IDirectSoundCaptureBuffer, IUnknown)
  202016. {
  202017. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  202018. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  202019. STDMETHOD_(ULONG,Release) (THIS) PURE;
  202020. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  202021. STDMETHOD(GetCurrentPosition) (THIS_ LPDWORD, LPDWORD) PURE;
  202022. STDMETHOD(GetFormat) (THIS_ LPWAVEFORMATEX, DWORD, LPDWORD) PURE;
  202023. STDMETHOD(GetStatus) (THIS_ LPDWORD) PURE;
  202024. STDMETHOD(Initialize) (THIS_ IDirectSoundCapture*, DSCBUFFERDESC*) PURE;
  202025. STDMETHOD(Lock) (THIS_ DWORD, DWORD, LPVOID*, LPDWORD, LPVOID*, LPDWORD, DWORD) PURE;
  202026. STDMETHOD(Start) (THIS_ DWORD) PURE;
  202027. STDMETHOD(Stop) (THIS) PURE;
  202028. STDMETHOD(Unlock) (THIS_ LPVOID, DWORD, LPVOID, DWORD) PURE;
  202029. };
  202030. };
  202031. BEGIN_JUCE_NAMESPACE
  202032. static const String getDSErrorMessage (HRESULT hr)
  202033. {
  202034. const char* result = 0;
  202035. switch (hr)
  202036. {
  202037. case MAKE_HRESULT(1, 0x878, 10):
  202038. result = "Device already allocated";
  202039. break;
  202040. case MAKE_HRESULT(1, 0x878, 30):
  202041. result = "Control unavailable";
  202042. break;
  202043. case E_INVALIDARG:
  202044. result = "Invalid parameter";
  202045. break;
  202046. case MAKE_HRESULT(1, 0x878, 50):
  202047. result = "Invalid call";
  202048. break;
  202049. case E_FAIL:
  202050. result = "Generic error";
  202051. break;
  202052. case MAKE_HRESULT(1, 0x878, 70):
  202053. result = "Priority level error";
  202054. break;
  202055. case E_OUTOFMEMORY:
  202056. result = "Out of memory";
  202057. break;
  202058. case MAKE_HRESULT(1, 0x878, 100):
  202059. result = "Bad format";
  202060. break;
  202061. case E_NOTIMPL:
  202062. result = "Unsupported function";
  202063. break;
  202064. case MAKE_HRESULT(1, 0x878, 120):
  202065. result = "No driver";
  202066. break;
  202067. case MAKE_HRESULT(1, 0x878, 130):
  202068. result = "Already initialised";
  202069. break;
  202070. case CLASS_E_NOAGGREGATION:
  202071. result = "No aggregation";
  202072. break;
  202073. case MAKE_HRESULT(1, 0x878, 150):
  202074. result = "Buffer lost";
  202075. break;
  202076. case MAKE_HRESULT(1, 0x878, 160):
  202077. result = "Another app has priority";
  202078. break;
  202079. case MAKE_HRESULT(1, 0x878, 170):
  202080. result = "Uninitialised";
  202081. break;
  202082. case E_NOINTERFACE:
  202083. result = "No interface";
  202084. break;
  202085. case S_OK:
  202086. result = "No error";
  202087. break;
  202088. default:
  202089. return "Unknown error: " + String ((int) hr);
  202090. }
  202091. return result;
  202092. }
  202093. #define DS_DEBUGGING 1
  202094. #ifdef DS_DEBUGGING
  202095. #define CATCH JUCE_CATCH_EXCEPTION
  202096. #undef log
  202097. #define log(a) Logger::writeToLog(a);
  202098. #undef logError
  202099. #define logError(a) logDSError(a, __LINE__);
  202100. static void logDSError (HRESULT hr, int lineNum)
  202101. {
  202102. if (hr != S_OK)
  202103. {
  202104. String error ("DS error at line ");
  202105. error << lineNum << T(" - ") << getDSErrorMessage (hr);
  202106. log (error);
  202107. }
  202108. }
  202109. #else
  202110. #define CATCH JUCE_CATCH_ALL
  202111. #define log(a)
  202112. #define logError(a)
  202113. #endif
  202114. #define DSOUND_FUNCTION(functionName, params) \
  202115. typedef HRESULT (WINAPI *type##functionName) params; \
  202116. static type##functionName ds##functionName = 0;
  202117. #define DSOUND_FUNCTION_LOAD(functionName) \
  202118. ds##functionName = (type##functionName) GetProcAddress (h, #functionName); \
  202119. jassert (ds##functionName != 0);
  202120. typedef BOOL (CALLBACK *LPDSENUMCALLBACKW) (LPGUID, LPCWSTR, LPCWSTR, LPVOID);
  202121. typedef BOOL (CALLBACK *LPDSENUMCALLBACKA) (LPGUID, LPCSTR, LPCSTR, LPVOID);
  202122. DSOUND_FUNCTION (DirectSoundCreate, (const GUID*, IDirectSound**, LPUNKNOWN))
  202123. DSOUND_FUNCTION (DirectSoundCaptureCreate, (const GUID*, IDirectSoundCapture**, LPUNKNOWN))
  202124. DSOUND_FUNCTION (DirectSoundEnumerateW, (LPDSENUMCALLBACKW, LPVOID))
  202125. DSOUND_FUNCTION (DirectSoundCaptureEnumerateW, (LPDSENUMCALLBACKW, LPVOID))
  202126. static void initialiseDSoundFunctions()
  202127. {
  202128. if (dsDirectSoundCreate == 0)
  202129. {
  202130. HMODULE h = LoadLibraryA ("dsound.dll");
  202131. DSOUND_FUNCTION_LOAD (DirectSoundCreate)
  202132. DSOUND_FUNCTION_LOAD (DirectSoundCaptureCreate)
  202133. DSOUND_FUNCTION_LOAD (DirectSoundEnumerateW)
  202134. DSOUND_FUNCTION_LOAD (DirectSoundCaptureEnumerateW)
  202135. }
  202136. }
  202137. class DSoundInternalOutChannel
  202138. {
  202139. String name;
  202140. LPGUID guid;
  202141. int sampleRate, bufferSizeSamples;
  202142. float* leftBuffer;
  202143. float* rightBuffer;
  202144. IDirectSound* pDirectSound;
  202145. IDirectSoundBuffer* pOutputBuffer;
  202146. DWORD writeOffset;
  202147. int totalBytesPerBuffer;
  202148. int bytesPerBuffer;
  202149. unsigned int lastPlayCursor;
  202150. public:
  202151. int bitDepth;
  202152. bool doneFlag;
  202153. DSoundInternalOutChannel (const String& name_,
  202154. LPGUID guid_,
  202155. int rate,
  202156. int bufferSize,
  202157. float* left,
  202158. float* right)
  202159. : name (name_),
  202160. guid (guid_),
  202161. sampleRate (rate),
  202162. bufferSizeSamples (bufferSize),
  202163. leftBuffer (left),
  202164. rightBuffer (right),
  202165. pDirectSound (0),
  202166. pOutputBuffer (0),
  202167. bitDepth (16)
  202168. {
  202169. }
  202170. ~DSoundInternalOutChannel()
  202171. {
  202172. close();
  202173. }
  202174. void close()
  202175. {
  202176. HRESULT hr;
  202177. if (pOutputBuffer != 0)
  202178. {
  202179. JUCE_TRY
  202180. {
  202181. log (T("closing dsound out: ") + name);
  202182. hr = pOutputBuffer->Stop();
  202183. logError (hr);
  202184. }
  202185. CATCH
  202186. JUCE_TRY
  202187. {
  202188. hr = pOutputBuffer->Release();
  202189. logError (hr);
  202190. }
  202191. CATCH
  202192. pOutputBuffer = 0;
  202193. }
  202194. if (pDirectSound != 0)
  202195. {
  202196. JUCE_TRY
  202197. {
  202198. hr = pDirectSound->Release();
  202199. logError (hr);
  202200. }
  202201. CATCH
  202202. pDirectSound = 0;
  202203. }
  202204. }
  202205. const String open()
  202206. {
  202207. log (T("opening dsound out device: ") + name
  202208. + T(" rate=") + String (sampleRate)
  202209. + T(" bits=") + String (bitDepth)
  202210. + T(" buf=") + String (bufferSizeSamples));
  202211. pDirectSound = 0;
  202212. pOutputBuffer = 0;
  202213. writeOffset = 0;
  202214. String error;
  202215. HRESULT hr = E_NOINTERFACE;
  202216. if (dsDirectSoundCreate != 0)
  202217. hr = dsDirectSoundCreate (guid, &pDirectSound, 0);
  202218. if (hr == S_OK)
  202219. {
  202220. bytesPerBuffer = (bufferSizeSamples * (bitDepth >> 2)) & ~15;
  202221. totalBytesPerBuffer = (3 * bytesPerBuffer) & ~15;
  202222. const int numChannels = 2;
  202223. hr = pDirectSound->SetCooperativeLevel (GetDesktopWindow(), 3 /* DSSCL_EXCLUSIVE */);
  202224. logError (hr);
  202225. if (hr == S_OK)
  202226. {
  202227. IDirectSoundBuffer* pPrimaryBuffer;
  202228. DSBUFFERDESC primaryDesc;
  202229. zerostruct (primaryDesc);
  202230. primaryDesc.dwSize = sizeof (DSBUFFERDESC);
  202231. primaryDesc.dwFlags = 1 /* DSBCAPS_PRIMARYBUFFER */;
  202232. primaryDesc.dwBufferBytes = 0;
  202233. primaryDesc.lpwfxFormat = 0;
  202234. log ("opening dsound out step 2");
  202235. hr = pDirectSound->CreateSoundBuffer (&primaryDesc, &pPrimaryBuffer, 0);
  202236. logError (hr);
  202237. if (hr == S_OK)
  202238. {
  202239. WAVEFORMATEX wfFormat;
  202240. wfFormat.wFormatTag = WAVE_FORMAT_PCM;
  202241. wfFormat.nChannels = (unsigned short) numChannels;
  202242. wfFormat.nSamplesPerSec = sampleRate;
  202243. wfFormat.wBitsPerSample = (unsigned short) bitDepth;
  202244. wfFormat.nBlockAlign = (unsigned short) (wfFormat.nChannels * wfFormat.wBitsPerSample / 8);
  202245. wfFormat.nAvgBytesPerSec = wfFormat.nSamplesPerSec * wfFormat.nBlockAlign;
  202246. wfFormat.cbSize = 0;
  202247. hr = pPrimaryBuffer->SetFormat (&wfFormat);
  202248. logError (hr);
  202249. if (hr == S_OK)
  202250. {
  202251. DSBUFFERDESC secondaryDesc;
  202252. zerostruct (secondaryDesc);
  202253. secondaryDesc.dwSize = sizeof (DSBUFFERDESC);
  202254. secondaryDesc.dwFlags = 0x8000 /* DSBCAPS_GLOBALFOCUS */
  202255. | 0x10000 /* DSBCAPS_GETCURRENTPOSITION2 */;
  202256. secondaryDesc.dwBufferBytes = totalBytesPerBuffer;
  202257. secondaryDesc.lpwfxFormat = &wfFormat;
  202258. hr = pDirectSound->CreateSoundBuffer (&secondaryDesc, &pOutputBuffer, 0);
  202259. logError (hr);
  202260. if (hr == S_OK)
  202261. {
  202262. log ("opening dsound out step 3");
  202263. DWORD dwDataLen;
  202264. unsigned char* pDSBuffData;
  202265. hr = pOutputBuffer->Lock (0, totalBytesPerBuffer,
  202266. (LPVOID*) &pDSBuffData, &dwDataLen, 0, 0, 0);
  202267. logError (hr);
  202268. if (hr == S_OK)
  202269. {
  202270. zeromem (pDSBuffData, dwDataLen);
  202271. hr = pOutputBuffer->Unlock (pDSBuffData, dwDataLen, 0, 0);
  202272. if (hr == S_OK)
  202273. {
  202274. hr = pOutputBuffer->SetCurrentPosition (0);
  202275. if (hr == S_OK)
  202276. {
  202277. hr = pOutputBuffer->Play (0, 0, 1 /* DSBPLAY_LOOPING */);
  202278. if (hr == S_OK)
  202279. return String::empty;
  202280. }
  202281. }
  202282. }
  202283. }
  202284. }
  202285. }
  202286. }
  202287. }
  202288. error = getDSErrorMessage (hr);
  202289. close();
  202290. return error;
  202291. }
  202292. void synchronisePosition()
  202293. {
  202294. if (pOutputBuffer != 0)
  202295. {
  202296. DWORD playCursor;
  202297. pOutputBuffer->GetCurrentPosition (&playCursor, &writeOffset);
  202298. }
  202299. }
  202300. bool service()
  202301. {
  202302. if (pOutputBuffer == 0)
  202303. return true;
  202304. DWORD playCursor, writeCursor;
  202305. HRESULT hr = pOutputBuffer->GetCurrentPosition (&playCursor, &writeCursor);
  202306. if (hr != S_OK)
  202307. {
  202308. logError (hr);
  202309. jassertfalse
  202310. return true;
  202311. }
  202312. int playWriteGap = writeCursor - playCursor;
  202313. if (playWriteGap < 0)
  202314. playWriteGap += totalBytesPerBuffer;
  202315. int bytesEmpty = playCursor - writeOffset;
  202316. if (bytesEmpty < 0)
  202317. bytesEmpty += totalBytesPerBuffer;
  202318. if (bytesEmpty > (totalBytesPerBuffer - playWriteGap))
  202319. {
  202320. writeOffset = writeCursor;
  202321. bytesEmpty = totalBytesPerBuffer - playWriteGap;
  202322. }
  202323. if (bytesEmpty >= bytesPerBuffer)
  202324. {
  202325. LPBYTE lpbuf1 = 0;
  202326. LPBYTE lpbuf2 = 0;
  202327. DWORD dwSize1 = 0;
  202328. DWORD dwSize2 = 0;
  202329. HRESULT hr = pOutputBuffer->Lock (writeOffset,
  202330. bytesPerBuffer,
  202331. (void**) &lpbuf1, &dwSize1,
  202332. (void**) &lpbuf2, &dwSize2, 0);
  202333. if (hr == S_OK)
  202334. {
  202335. if (bitDepth == 16)
  202336. {
  202337. const float gainL = 32767.0f;
  202338. const float gainR = 32767.0f;
  202339. int* dest = (int*)lpbuf1;
  202340. const float* left = leftBuffer;
  202341. const float* right = rightBuffer;
  202342. int samples1 = dwSize1 >> 2;
  202343. int samples2 = dwSize2 >> 2;
  202344. if (left == 0)
  202345. {
  202346. while (--samples1 >= 0)
  202347. {
  202348. int r = roundFloatToInt (gainR * *right++);
  202349. if (r < -32768)
  202350. r = -32768;
  202351. else if (r > 32767)
  202352. r = 32767;
  202353. *dest++ = (r << 16);
  202354. }
  202355. dest = (int*)lpbuf2;
  202356. while (--samples2 >= 0)
  202357. {
  202358. int r = roundFloatToInt (gainR * *right++);
  202359. if (r < -32768)
  202360. r = -32768;
  202361. else if (r > 32767)
  202362. r = 32767;
  202363. *dest++ = (r << 16);
  202364. }
  202365. }
  202366. else if (right == 0)
  202367. {
  202368. while (--samples1 >= 0)
  202369. {
  202370. int l = roundFloatToInt (gainL * *left++);
  202371. if (l < -32768)
  202372. l = -32768;
  202373. else if (l > 32767)
  202374. l = 32767;
  202375. l &= 0xffff;
  202376. *dest++ = l;
  202377. }
  202378. dest = (int*)lpbuf2;
  202379. while (--samples2 >= 0)
  202380. {
  202381. int l = roundFloatToInt (gainL * *left++);
  202382. if (l < -32768)
  202383. l = -32768;
  202384. else if (l > 32767)
  202385. l = 32767;
  202386. l &= 0xffff;
  202387. *dest++ = l;
  202388. }
  202389. }
  202390. else
  202391. {
  202392. while (--samples1 >= 0)
  202393. {
  202394. int l = roundFloatToInt (gainL * *left++);
  202395. if (l < -32768)
  202396. l = -32768;
  202397. else if (l > 32767)
  202398. l = 32767;
  202399. l &= 0xffff;
  202400. int r = roundFloatToInt (gainR * *right++);
  202401. if (r < -32768)
  202402. r = -32768;
  202403. else if (r > 32767)
  202404. r = 32767;
  202405. *dest++ = (r << 16) | l;
  202406. }
  202407. dest = (int*)lpbuf2;
  202408. while (--samples2 >= 0)
  202409. {
  202410. int l = roundFloatToInt (gainL * *left++);
  202411. if (l < -32768)
  202412. l = -32768;
  202413. else if (l > 32767)
  202414. l = 32767;
  202415. l &= 0xffff;
  202416. int r = roundFloatToInt (gainR * *right++);
  202417. if (r < -32768)
  202418. r = -32768;
  202419. else if (r > 32767)
  202420. r = 32767;
  202421. *dest++ = (r << 16) | l;
  202422. }
  202423. }
  202424. }
  202425. else
  202426. {
  202427. jassertfalse
  202428. }
  202429. writeOffset = (writeOffset + dwSize1 + dwSize2) % totalBytesPerBuffer;
  202430. pOutputBuffer->Unlock (lpbuf1, dwSize1, lpbuf2, dwSize2);
  202431. }
  202432. else
  202433. {
  202434. jassertfalse
  202435. logError (hr);
  202436. }
  202437. bytesEmpty -= bytesPerBuffer;
  202438. return true;
  202439. }
  202440. else
  202441. {
  202442. return false;
  202443. }
  202444. }
  202445. };
  202446. struct DSoundInternalInChannel
  202447. {
  202448. String name;
  202449. LPGUID guid;
  202450. int sampleRate, bufferSizeSamples;
  202451. float* leftBuffer;
  202452. float* rightBuffer;
  202453. IDirectSound* pDirectSound;
  202454. IDirectSoundCapture* pDirectSoundCapture;
  202455. IDirectSoundCaptureBuffer* pInputBuffer;
  202456. public:
  202457. unsigned int readOffset;
  202458. int bytesPerBuffer, totalBytesPerBuffer;
  202459. int bitDepth;
  202460. bool doneFlag;
  202461. DSoundInternalInChannel (const String& name_,
  202462. LPGUID guid_,
  202463. int rate,
  202464. int bufferSize,
  202465. float* left,
  202466. float* right)
  202467. : name (name_),
  202468. guid (guid_),
  202469. sampleRate (rate),
  202470. bufferSizeSamples (bufferSize),
  202471. leftBuffer (left),
  202472. rightBuffer (right),
  202473. pDirectSound (0),
  202474. pDirectSoundCapture (0),
  202475. pInputBuffer (0),
  202476. bitDepth (16)
  202477. {
  202478. }
  202479. ~DSoundInternalInChannel()
  202480. {
  202481. close();
  202482. }
  202483. void close()
  202484. {
  202485. HRESULT hr;
  202486. if (pInputBuffer != 0)
  202487. {
  202488. JUCE_TRY
  202489. {
  202490. log (T("closing dsound in: ") + name);
  202491. hr = pInputBuffer->Stop();
  202492. logError (hr);
  202493. }
  202494. CATCH
  202495. JUCE_TRY
  202496. {
  202497. hr = pInputBuffer->Release();
  202498. logError (hr);
  202499. }
  202500. CATCH
  202501. pInputBuffer = 0;
  202502. }
  202503. if (pDirectSoundCapture != 0)
  202504. {
  202505. JUCE_TRY
  202506. {
  202507. hr = pDirectSoundCapture->Release();
  202508. logError (hr);
  202509. }
  202510. CATCH
  202511. pDirectSoundCapture = 0;
  202512. }
  202513. if (pDirectSound != 0)
  202514. {
  202515. JUCE_TRY
  202516. {
  202517. hr = pDirectSound->Release();
  202518. logError (hr);
  202519. }
  202520. CATCH
  202521. pDirectSound = 0;
  202522. }
  202523. }
  202524. const String open()
  202525. {
  202526. log (T("opening dsound in device: ") + name
  202527. + T(" rate=") + String (sampleRate) + T(" bits=") + String (bitDepth) + T(" buf=") + String (bufferSizeSamples));
  202528. pDirectSound = 0;
  202529. pDirectSoundCapture = 0;
  202530. pInputBuffer = 0;
  202531. readOffset = 0;
  202532. totalBytesPerBuffer = 0;
  202533. String error;
  202534. HRESULT hr = E_NOINTERFACE;
  202535. if (dsDirectSoundCaptureCreate != 0)
  202536. hr = dsDirectSoundCaptureCreate (guid, &pDirectSoundCapture, 0);
  202537. logError (hr);
  202538. if (hr == S_OK)
  202539. {
  202540. const int numChannels = 2;
  202541. bytesPerBuffer = (bufferSizeSamples * (bitDepth >> 2)) & ~15;
  202542. totalBytesPerBuffer = (3 * bytesPerBuffer) & ~15;
  202543. WAVEFORMATEX wfFormat;
  202544. wfFormat.wFormatTag = WAVE_FORMAT_PCM;
  202545. wfFormat.nChannels = (unsigned short)numChannels;
  202546. wfFormat.nSamplesPerSec = sampleRate;
  202547. wfFormat.wBitsPerSample = (unsigned short)bitDepth;
  202548. wfFormat.nBlockAlign = (unsigned short)(wfFormat.nChannels * (wfFormat.wBitsPerSample / 8));
  202549. wfFormat.nAvgBytesPerSec = wfFormat.nSamplesPerSec * wfFormat.nBlockAlign;
  202550. wfFormat.cbSize = 0;
  202551. DSCBUFFERDESC captureDesc;
  202552. zerostruct (captureDesc);
  202553. captureDesc.dwSize = sizeof (DSCBUFFERDESC);
  202554. captureDesc.dwFlags = 0;
  202555. captureDesc.dwBufferBytes = totalBytesPerBuffer;
  202556. captureDesc.lpwfxFormat = &wfFormat;
  202557. log (T("opening dsound in step 2"));
  202558. hr = pDirectSoundCapture->CreateCaptureBuffer (&captureDesc, &pInputBuffer, 0);
  202559. logError (hr);
  202560. if (hr == S_OK)
  202561. {
  202562. hr = pInputBuffer->Start (1 /* DSCBSTART_LOOPING */);
  202563. logError (hr);
  202564. if (hr == S_OK)
  202565. return String::empty;
  202566. }
  202567. }
  202568. error = getDSErrorMessage (hr);
  202569. close();
  202570. return error;
  202571. }
  202572. void synchronisePosition()
  202573. {
  202574. if (pInputBuffer != 0)
  202575. {
  202576. DWORD capturePos;
  202577. pInputBuffer->GetCurrentPosition (&capturePos, (DWORD*)&readOffset);
  202578. }
  202579. }
  202580. bool service()
  202581. {
  202582. if (pInputBuffer == 0)
  202583. return true;
  202584. DWORD capturePos, readPos;
  202585. HRESULT hr = pInputBuffer->GetCurrentPosition (&capturePos, &readPos);
  202586. logError (hr);
  202587. if (hr != S_OK)
  202588. return true;
  202589. int bytesFilled = readPos - readOffset;
  202590. if (bytesFilled < 0)
  202591. bytesFilled += totalBytesPerBuffer;
  202592. if (bytesFilled >= bytesPerBuffer)
  202593. {
  202594. LPBYTE lpbuf1 = 0;
  202595. LPBYTE lpbuf2 = 0;
  202596. DWORD dwsize1 = 0;
  202597. DWORD dwsize2 = 0;
  202598. HRESULT hr = pInputBuffer->Lock (readOffset,
  202599. bytesPerBuffer,
  202600. (void**) &lpbuf1, &dwsize1,
  202601. (void**) &lpbuf2, &dwsize2, 0);
  202602. if (hr == S_OK)
  202603. {
  202604. if (bitDepth == 16)
  202605. {
  202606. const float g = 1.0f / 32768.0f;
  202607. float* destL = leftBuffer;
  202608. float* destR = rightBuffer;
  202609. int samples1 = dwsize1 >> 2;
  202610. int samples2 = dwsize2 >> 2;
  202611. const short* src = (const short*)lpbuf1;
  202612. if (destL == 0)
  202613. {
  202614. while (--samples1 >= 0)
  202615. {
  202616. ++src;
  202617. *destR++ = *src++ * g;
  202618. }
  202619. src = (const short*)lpbuf2;
  202620. while (--samples2 >= 0)
  202621. {
  202622. ++src;
  202623. *destR++ = *src++ * g;
  202624. }
  202625. }
  202626. else if (destR == 0)
  202627. {
  202628. while (--samples1 >= 0)
  202629. {
  202630. *destL++ = *src++ * g;
  202631. ++src;
  202632. }
  202633. src = (const short*)lpbuf2;
  202634. while (--samples2 >= 0)
  202635. {
  202636. *destL++ = *src++ * g;
  202637. ++src;
  202638. }
  202639. }
  202640. else
  202641. {
  202642. while (--samples1 >= 0)
  202643. {
  202644. *destL++ = *src++ * g;
  202645. *destR++ = *src++ * g;
  202646. }
  202647. src = (const short*)lpbuf2;
  202648. while (--samples2 >= 0)
  202649. {
  202650. *destL++ = *src++ * g;
  202651. *destR++ = *src++ * g;
  202652. }
  202653. }
  202654. }
  202655. else
  202656. {
  202657. jassertfalse
  202658. }
  202659. readOffset = (readOffset + dwsize1 + dwsize2) % totalBytesPerBuffer;
  202660. pInputBuffer->Unlock (lpbuf1, dwsize1, lpbuf2, dwsize2);
  202661. }
  202662. else
  202663. {
  202664. logError (hr);
  202665. jassertfalse
  202666. }
  202667. bytesFilled -= bytesPerBuffer;
  202668. return true;
  202669. }
  202670. else
  202671. {
  202672. return false;
  202673. }
  202674. }
  202675. };
  202676. static int findBestMatchForName (const String& name, const StringArray& names)
  202677. {
  202678. int i = names.indexOf (name);
  202679. if (i >= 0)
  202680. return i;
  202681. StringArray tokens1;
  202682. tokens1.addTokens (name, T(" :-"), 0);
  202683. int bestResult = -1;
  202684. int bestNumMatches = 1;
  202685. for (i = 0; i < names.size(); ++i)
  202686. {
  202687. StringArray tokens2;
  202688. tokens2.addTokens (names[i], T(" :-"), 0);
  202689. int matches = 0;
  202690. for (int j = tokens1.size(); --j >= 0;)
  202691. if (tokens2.contains (tokens1 [j]))
  202692. ++matches;
  202693. if (matches > bestNumMatches)
  202694. bestResult = i;
  202695. }
  202696. return bestResult;
  202697. }
  202698. class DSoundAudioIODevice : public AudioIODevice,
  202699. public Thread
  202700. {
  202701. public:
  202702. DSoundAudioIODevice (const String& deviceName,
  202703. const int index,
  202704. const int inputIndex_)
  202705. : AudioIODevice (deviceName, "DirectSound"),
  202706. Thread ("Juce DSound"),
  202707. isOpen_ (false),
  202708. isStarted (false),
  202709. deviceIndex (index),
  202710. inputIndex (inputIndex_),
  202711. inChans (4),
  202712. outChans (4),
  202713. numInputBuffers (0),
  202714. numOutputBuffers (0),
  202715. totalSamplesOut (0),
  202716. sampleRate (0.0),
  202717. inputBuffers (0),
  202718. outputBuffers (0),
  202719. callback (0)
  202720. {
  202721. }
  202722. ~DSoundAudioIODevice()
  202723. {
  202724. close();
  202725. }
  202726. const StringArray getOutputChannelNames()
  202727. {
  202728. return outChannels;
  202729. }
  202730. const StringArray getInputChannelNames()
  202731. {
  202732. return inChannels;
  202733. }
  202734. int getNumSampleRates()
  202735. {
  202736. return 4;
  202737. }
  202738. double getSampleRate (int index)
  202739. {
  202740. const double samps[] = { 44100.0, 48000.0, 88200.0, 96000.0 };
  202741. return samps [jlimit (0, 3, index)];
  202742. }
  202743. int getNumBufferSizesAvailable()
  202744. {
  202745. return 50;
  202746. }
  202747. int getBufferSizeSamples (int index)
  202748. {
  202749. int n = 64;
  202750. for (int i = 0; i < index; ++i)
  202751. n += (n < 512) ? 32
  202752. : ((n < 1024) ? 64
  202753. : ((n < 2048) ? 128 : 256));
  202754. return n;
  202755. }
  202756. int getDefaultBufferSize()
  202757. {
  202758. return 2560;
  202759. }
  202760. const String open (const BitArray& inputChannels,
  202761. const BitArray& outputChannels,
  202762. double sampleRate,
  202763. int bufferSizeSamples)
  202764. {
  202765. BitArray ins, outs;
  202766. if (deviceIndex >= 0)
  202767. {
  202768. if (outputChannels[0])
  202769. outs.setBit (2 * deviceIndex);
  202770. if (outputChannels[1])
  202771. outs.setBit (2 * deviceIndex + 1);
  202772. if (inputIndex >= 0)
  202773. {
  202774. if (inputChannels[0])
  202775. ins.setBit (2 * inputIndex);
  202776. if (inputChannels[1])
  202777. ins.setBit (2 * inputIndex + 1);
  202778. }
  202779. }
  202780. else
  202781. {
  202782. ins = inputChannels;
  202783. outs = outputChannels;
  202784. }
  202785. lastError = openDevice (ins, outs, sampleRate, bufferSizeSamples);
  202786. isOpen_ = lastError.isEmpty();
  202787. return lastError;
  202788. }
  202789. void close()
  202790. {
  202791. stop();
  202792. if (isOpen_)
  202793. {
  202794. closeDevice();
  202795. isOpen_ = false;
  202796. }
  202797. }
  202798. bool isOpen()
  202799. {
  202800. return isOpen_ && isThreadRunning();
  202801. }
  202802. int getCurrentBufferSizeSamples()
  202803. {
  202804. return bufferSizeSamples;
  202805. }
  202806. double getCurrentSampleRate()
  202807. {
  202808. return sampleRate;
  202809. }
  202810. int getCurrentBitDepth()
  202811. {
  202812. int i, bits = 256;
  202813. for (i = inChans.size(); --i >= 0;)
  202814. bits = jmin (bits, inChans[i]->bitDepth);
  202815. for (i = outChans.size(); --i >= 0;)
  202816. bits = jmin (bits, outChans[i]->bitDepth);
  202817. if (bits > 32)
  202818. bits = 16;
  202819. return bits;
  202820. }
  202821. const BitArray getActiveOutputChannels() const
  202822. {
  202823. return enabledOutputs;
  202824. }
  202825. const BitArray getActiveInputChannels() const
  202826. {
  202827. return enabledInputs;
  202828. }
  202829. int getOutputLatencyInSamples()
  202830. {
  202831. return (int) (getCurrentBufferSizeSamples() * 1.5);
  202832. }
  202833. int getInputLatencyInSamples()
  202834. {
  202835. return getOutputLatencyInSamples();
  202836. }
  202837. void start (AudioIODeviceCallback* call)
  202838. {
  202839. if (isOpen_ && call != 0 && ! isStarted)
  202840. {
  202841. if (! isThreadRunning())
  202842. {
  202843. // something gone wrong and the thread's stopped..
  202844. isOpen_ = false;
  202845. return;
  202846. }
  202847. call->audioDeviceAboutToStart (this);
  202848. const ScopedLock sl (startStopLock);
  202849. callback = call;
  202850. isStarted = true;
  202851. }
  202852. }
  202853. void stop()
  202854. {
  202855. if (isStarted)
  202856. {
  202857. AudioIODeviceCallback* const callbackLocal = callback;
  202858. {
  202859. const ScopedLock sl (startStopLock);
  202860. isStarted = false;
  202861. }
  202862. if (callbackLocal != 0)
  202863. callbackLocal->audioDeviceStopped();
  202864. }
  202865. }
  202866. bool isPlaying()
  202867. {
  202868. return isStarted && isOpen_ && isThreadRunning();
  202869. }
  202870. const String getLastError()
  202871. {
  202872. return lastError;
  202873. }
  202874. juce_UseDebuggingNewOperator
  202875. StringArray inChannels, outChannels;
  202876. private:
  202877. bool isOpen_;
  202878. bool isStarted;
  202879. String lastError;
  202880. int deviceIndex, inputIndex;
  202881. OwnedArray <DSoundInternalInChannel> inChans;
  202882. OwnedArray <DSoundInternalOutChannel> outChans;
  202883. WaitableEvent startEvent;
  202884. int numInputBuffers, numOutputBuffers, bufferSizeSamples;
  202885. int volatile totalSamplesOut;
  202886. int64 volatile lastBlockTime;
  202887. double sampleRate;
  202888. BitArray enabledInputs, enabledOutputs;
  202889. float** inputBuffers;
  202890. float** outputBuffers;
  202891. AudioIODeviceCallback* callback;
  202892. CriticalSection startStopLock;
  202893. DSoundAudioIODevice (const DSoundAudioIODevice&);
  202894. const DSoundAudioIODevice& operator= (const DSoundAudioIODevice&);
  202895. const String openDevice (const BitArray& inputChannels,
  202896. const BitArray& outputChannels,
  202897. double sampleRate_,
  202898. int bufferSizeSamples_);
  202899. void closeDevice()
  202900. {
  202901. isStarted = false;
  202902. stopThread (5000);
  202903. inChans.clear();
  202904. outChans.clear();
  202905. int i;
  202906. for (i = 0; i < numInputBuffers; ++i)
  202907. juce_free (inputBuffers[i]);
  202908. delete[] inputBuffers;
  202909. inputBuffers = 0;
  202910. numInputBuffers = 0;
  202911. for (i = 0; i < numOutputBuffers; ++i)
  202912. juce_free (outputBuffers[i]);
  202913. delete[] outputBuffers;
  202914. outputBuffers = 0;
  202915. numOutputBuffers = 0;
  202916. }
  202917. void resync()
  202918. {
  202919. int i;
  202920. for (i = outChans.size(); --i >= 0;)
  202921. outChans.getUnchecked(i)->close();
  202922. for (i = inChans.size(); --i >= 0;)
  202923. inChans.getUnchecked(i)->close();
  202924. if (threadShouldExit())
  202925. return;
  202926. // boost our priority while opening the devices to try to get better sync between them
  202927. const int oldThreadPri = GetThreadPriority (GetCurrentThread());
  202928. const int oldProcPri = GetPriorityClass (GetCurrentProcess());
  202929. SetThreadPriority (GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
  202930. SetPriorityClass (GetCurrentProcess(), REALTIME_PRIORITY_CLASS);
  202931. for (i = outChans.size(); --i >= 0;)
  202932. outChans.getUnchecked(i)->open();
  202933. for (i = inChans.size(); --i >= 0;)
  202934. inChans.getUnchecked(i)->open();
  202935. if (! threadShouldExit())
  202936. {
  202937. sleep (5);
  202938. for (i = 0; i < outChans.size(); ++i)
  202939. outChans.getUnchecked(i)->synchronisePosition();
  202940. for (i = 0; i < inChans.size(); ++i)
  202941. inChans.getUnchecked(i)->synchronisePosition();
  202942. }
  202943. SetThreadPriority (GetCurrentThread(), oldThreadPri);
  202944. SetPriorityClass (GetCurrentProcess(), oldProcPri);
  202945. }
  202946. public:
  202947. void run()
  202948. {
  202949. while (! threadShouldExit())
  202950. {
  202951. if (wait (100))
  202952. break;
  202953. }
  202954. const int latencyMs = (int) (bufferSizeSamples * 1000.0 / sampleRate);
  202955. const int maxTimeMS = jmax (5, 3 * latencyMs);
  202956. while (! threadShouldExit())
  202957. {
  202958. int numToDo = 0;
  202959. uint32 startTime = Time::getMillisecondCounter();
  202960. int i;
  202961. for (i = inChans.size(); --i >= 0;)
  202962. {
  202963. inChans.getUnchecked(i)->doneFlag = false;
  202964. ++numToDo;
  202965. }
  202966. for (i = outChans.size(); --i >= 0;)
  202967. {
  202968. outChans.getUnchecked(i)->doneFlag = false;
  202969. ++numToDo;
  202970. }
  202971. if (numToDo > 0)
  202972. {
  202973. const int maxCount = 3;
  202974. int count = maxCount;
  202975. for (;;)
  202976. {
  202977. for (i = inChans.size(); --i >= 0;)
  202978. {
  202979. DSoundInternalInChannel* const in = inChans.getUnchecked(i);
  202980. if ((! in->doneFlag) && in->service())
  202981. {
  202982. in->doneFlag = true;
  202983. --numToDo;
  202984. }
  202985. }
  202986. for (i = outChans.size(); --i >= 0;)
  202987. {
  202988. DSoundInternalOutChannel* const out = outChans.getUnchecked(i);
  202989. if ((! out->doneFlag) && out->service())
  202990. {
  202991. out->doneFlag = true;
  202992. --numToDo;
  202993. }
  202994. }
  202995. if (numToDo <= 0)
  202996. break;
  202997. if (Time::getMillisecondCounter() > startTime + maxTimeMS)
  202998. {
  202999. resync();
  203000. break;
  203001. }
  203002. if (--count <= 0)
  203003. {
  203004. Sleep (1);
  203005. count = maxCount;
  203006. }
  203007. if (threadShouldExit())
  203008. return;
  203009. }
  203010. }
  203011. else
  203012. {
  203013. sleep (1);
  203014. }
  203015. const ScopedLock sl (startStopLock);
  203016. if (isStarted)
  203017. {
  203018. JUCE_TRY
  203019. {
  203020. callback->audioDeviceIOCallback ((const float**) inputBuffers,
  203021. numInputBuffers,
  203022. outputBuffers,
  203023. numOutputBuffers,
  203024. bufferSizeSamples);
  203025. }
  203026. JUCE_CATCH_EXCEPTION
  203027. totalSamplesOut += bufferSizeSamples;
  203028. }
  203029. else
  203030. {
  203031. for (i = 0; i < numOutputBuffers; ++i)
  203032. if (outputBuffers[i] != 0)
  203033. zeromem (outputBuffers[i], bufferSizeSamples * sizeof (float));
  203034. totalSamplesOut = 0;
  203035. sleep (1);
  203036. }
  203037. }
  203038. }
  203039. };
  203040. class DSoundAudioIODeviceType : public AudioIODeviceType
  203041. {
  203042. public:
  203043. DSoundAudioIODeviceType()
  203044. : AudioIODeviceType (T("DirectSound")),
  203045. hasScanned (false)
  203046. {
  203047. initialiseDSoundFunctions();
  203048. }
  203049. ~DSoundAudioIODeviceType()
  203050. {
  203051. }
  203052. void scanForDevices()
  203053. {
  203054. hasScanned = true;
  203055. outputDeviceNames.clear();
  203056. outputGuids.clear();
  203057. inputDeviceNames.clear();
  203058. inputGuids.clear();
  203059. if (dsDirectSoundEnumerateW != 0)
  203060. {
  203061. dsDirectSoundEnumerateW (outputEnumProcW, this);
  203062. dsDirectSoundCaptureEnumerateW (inputEnumProcW, this);
  203063. }
  203064. }
  203065. const StringArray getDeviceNames (const bool preferInputNames) const
  203066. {
  203067. jassert (hasScanned); // need to call scanForDevices() before doing this
  203068. return preferInputNames ? inputDeviceNames
  203069. : outputDeviceNames;
  203070. }
  203071. const String getDefaultDeviceName (const bool preferInputNames,
  203072. const int /*numInputChannelsNeeded*/,
  203073. const int /*numOutputChannelsNeeded*/) const
  203074. {
  203075. jassert (hasScanned); // need to call scanForDevices() before doing this
  203076. return getDeviceNames (preferInputNames) [0];
  203077. }
  203078. AudioIODevice* createDevice (const String& deviceName)
  203079. {
  203080. jassert (hasScanned); // need to call scanForDevices() before doing this
  203081. if (deviceName.isEmpty() || deviceName.equalsIgnoreCase (T("DirectSound")))
  203082. {
  203083. DSoundAudioIODevice* device = new DSoundAudioIODevice (deviceName, -1, -1);
  203084. int i;
  203085. for (i = 0; i < outputDeviceNames.size(); ++i)
  203086. {
  203087. device->outChannels.add (outputDeviceNames[i] + TRANS(" (left)"));
  203088. device->outChannels.add (outputDeviceNames[i] + TRANS(" (right)"));
  203089. }
  203090. for (i = 0; i < inputDeviceNames.size(); ++i)
  203091. {
  203092. device->inChannels.add (inputDeviceNames[i] + TRANS(" (left)"));
  203093. device->inChannels.add (inputDeviceNames[i] + TRANS(" (right)"));
  203094. }
  203095. return device;
  203096. }
  203097. else if (outputDeviceNames.contains (deviceName)
  203098. || inputDeviceNames.contains (deviceName))
  203099. {
  203100. int outputIndex = outputDeviceNames.indexOf (deviceName);
  203101. int inputIndex = findBestMatchForName (deviceName, inputDeviceNames);
  203102. if (outputIndex < 0)
  203103. {
  203104. // using an input device name instead..
  203105. inputIndex = inputDeviceNames.indexOf (deviceName);
  203106. outputIndex = jmax (0, findBestMatchForName (deviceName, outputDeviceNames));
  203107. }
  203108. DSoundAudioIODevice* device = new DSoundAudioIODevice (deviceName, outputIndex, inputIndex);
  203109. device->outChannels.add (TRANS("Left"));
  203110. device->outChannels.add (TRANS("Right"));
  203111. if (inputIndex >= 0)
  203112. {
  203113. device->inChannels.add (TRANS("Left"));
  203114. device->inChannels.add (TRANS("Right"));
  203115. }
  203116. return device;
  203117. }
  203118. return 0;
  203119. }
  203120. juce_UseDebuggingNewOperator
  203121. StringArray outputDeviceNames;
  203122. OwnedArray <GUID> outputGuids;
  203123. StringArray inputDeviceNames;
  203124. OwnedArray <GUID> inputGuids;
  203125. private:
  203126. bool hasScanned;
  203127. BOOL outputEnumProc (LPGUID lpGUID, String desc)
  203128. {
  203129. desc = desc.trim();
  203130. if (desc.isNotEmpty())
  203131. {
  203132. const String origDesc (desc);
  203133. int n = 2;
  203134. while (outputDeviceNames.contains (desc))
  203135. desc = origDesc + T(" (") + String (n++) + T(")");
  203136. outputDeviceNames.add (desc);
  203137. if (lpGUID != 0)
  203138. outputGuids.add (new GUID (*lpGUID));
  203139. else
  203140. outputGuids.add (0);
  203141. }
  203142. return TRUE;
  203143. }
  203144. static BOOL CALLBACK outputEnumProcW (LPGUID lpGUID, LPCWSTR description, LPCWSTR, LPVOID object)
  203145. {
  203146. return ((DSoundAudioIODeviceType*) object)
  203147. ->outputEnumProc (lpGUID, String (description));
  203148. }
  203149. static BOOL CALLBACK outputEnumProcA (LPGUID lpGUID, LPCTSTR description, LPCTSTR, LPVOID object)
  203150. {
  203151. return ((DSoundAudioIODeviceType*) object)
  203152. ->outputEnumProc (lpGUID, String (description));
  203153. }
  203154. BOOL CALLBACK inputEnumProc (LPGUID lpGUID, String desc)
  203155. {
  203156. desc = desc.trim();
  203157. if (desc.isNotEmpty())
  203158. {
  203159. const String origDesc (desc);
  203160. int n = 2;
  203161. while (inputDeviceNames.contains (desc))
  203162. desc = origDesc + T(" (") + String (n++) + T(")");
  203163. inputDeviceNames.add (desc);
  203164. if (lpGUID != 0)
  203165. inputGuids.add (new GUID (*lpGUID));
  203166. else
  203167. inputGuids.add (0);
  203168. }
  203169. return TRUE;
  203170. }
  203171. static BOOL CALLBACK inputEnumProcW (LPGUID lpGUID, LPCWSTR description, LPCWSTR, LPVOID object)
  203172. {
  203173. return ((DSoundAudioIODeviceType*) object)
  203174. ->inputEnumProc (lpGUID, String (description));
  203175. }
  203176. static BOOL CALLBACK inputEnumProcA (LPGUID lpGUID, LPCTSTR description, LPCTSTR, LPVOID object)
  203177. {
  203178. return ((DSoundAudioIODeviceType*) object)
  203179. ->inputEnumProc (lpGUID, String (description));
  203180. }
  203181. DSoundAudioIODeviceType (const DSoundAudioIODeviceType&);
  203182. const DSoundAudioIODeviceType& operator= (const DSoundAudioIODeviceType&);
  203183. };
  203184. AudioIODeviceType* juce_createDefaultAudioIODeviceType()
  203185. {
  203186. return new DSoundAudioIODeviceType();
  203187. }
  203188. const String DSoundAudioIODevice::openDevice (const BitArray& inputChannels,
  203189. const BitArray& outputChannels,
  203190. double sampleRate_,
  203191. int bufferSizeSamples_)
  203192. {
  203193. closeDevice();
  203194. totalSamplesOut = 0;
  203195. enabledInputs.clear();
  203196. enabledOutputs.clear();
  203197. sampleRate = sampleRate_;
  203198. if (bufferSizeSamples_ <= 0)
  203199. bufferSizeSamples_ = 960; // use as a default size if none is set.
  203200. bufferSizeSamples = bufferSizeSamples_ & ~7;
  203201. DSoundAudioIODeviceType dlh;
  203202. dlh.scanForDevices();
  203203. enabledInputs = inputChannels;
  203204. numInputBuffers = inputChannels.countNumberOfSetBits();
  203205. inputBuffers = new float* [numInputBuffers + 2];
  203206. zeromem (inputBuffers, sizeof (inputBuffers));
  203207. int i, numIns = 0;
  203208. for (i = 0; i < inputChannels.getHighestBit(); i += 2)
  203209. {
  203210. float* left = 0;
  203211. float* right = 0;
  203212. if (inputChannels[i])
  203213. left = inputBuffers[numIns++] = (float*) juce_calloc ((bufferSizeSamples + 16) * sizeof (float));
  203214. if (inputChannels[i + 1])
  203215. right = inputBuffers[numIns++] = (float*) juce_calloc ((bufferSizeSamples + 16) * sizeof (float));
  203216. if (left != 0 || right != 0)
  203217. inChans.add (new DSoundInternalInChannel (dlh.inputDeviceNames [i / 2],
  203218. dlh.inputGuids [i / 2],
  203219. (int) sampleRate, bufferSizeSamples,
  203220. left, right));
  203221. }
  203222. enabledOutputs = outputChannels;
  203223. numOutputBuffers = outputChannels.countNumberOfSetBits();
  203224. outputBuffers = new float* [numOutputBuffers + 2];
  203225. zeromem (outputBuffers, sizeof (outputBuffers));
  203226. int numOuts = 0;
  203227. for (i = 0; i < outputChannels.getHighestBit(); i += 2)
  203228. {
  203229. float* left = 0;
  203230. float* right = 0;
  203231. if (inputChannels[i])
  203232. left = outputBuffers[numOuts++] = (float*) juce_calloc ((bufferSizeSamples + 16) * sizeof (float));
  203233. if (inputChannels[i + 1])
  203234. right = outputBuffers[numOuts++] = (float*) juce_calloc ((bufferSizeSamples + 16) * sizeof (float));
  203235. if (left != 0 || right != 0)
  203236. outChans.add (new DSoundInternalOutChannel (dlh.outputDeviceNames[i / 2],
  203237. dlh.outputGuids [i / 2],
  203238. (int) sampleRate, bufferSizeSamples,
  203239. left, right));
  203240. }
  203241. String error;
  203242. // boost our priority while opening the devices to try to get better sync between them
  203243. const int oldThreadPri = GetThreadPriority (GetCurrentThread());
  203244. const int oldProcPri = GetPriorityClass (GetCurrentProcess());
  203245. SetThreadPriority (GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
  203246. SetPriorityClass (GetCurrentProcess(), REALTIME_PRIORITY_CLASS);
  203247. for (i = 0; i < outChans.size(); ++i)
  203248. {
  203249. error = outChans[i]->open();
  203250. if (error.isNotEmpty())
  203251. {
  203252. error = T("Error opening ") + dlh.outputDeviceNames[i]
  203253. + T(": \"") + error + T("\"");
  203254. break;
  203255. }
  203256. }
  203257. if (error.isEmpty())
  203258. {
  203259. for (i = 0; i < inChans.size(); ++i)
  203260. {
  203261. error = inChans[i]->open();
  203262. if (error.isNotEmpty())
  203263. {
  203264. error = T("Error opening ") + dlh.inputDeviceNames[i]
  203265. + T(": \"") + error + T("\"");
  203266. break;
  203267. }
  203268. }
  203269. }
  203270. if (error.isEmpty())
  203271. {
  203272. totalSamplesOut = 0;
  203273. for (i = 0; i < outChans.size(); ++i)
  203274. outChans.getUnchecked(i)->synchronisePosition();
  203275. for (i = 0; i < inChans.size(); ++i)
  203276. inChans.getUnchecked(i)->synchronisePosition();
  203277. startThread (9);
  203278. sleep (10);
  203279. notify();
  203280. }
  203281. else
  203282. {
  203283. log (error);
  203284. }
  203285. SetThreadPriority (GetCurrentThread(), oldThreadPri);
  203286. SetPriorityClass (GetCurrentProcess(), oldProcPri);
  203287. return error;
  203288. }
  203289. #undef log
  203290. END_JUCE_NAMESPACE
  203291. /********* End of inlined file: juce_win32_DirectSound.cpp *********/
  203292. /********* Start of inlined file: juce_win32_FileChooser.cpp *********/
  203293. #ifdef _MSC_VER
  203294. #pragma warning (disable: 4514)
  203295. #pragma warning (push)
  203296. #endif
  203297. #include <shlobj.h>
  203298. BEGIN_JUCE_NAMESPACE
  203299. #ifdef _MSC_VER
  203300. #pragma warning (pop)
  203301. #endif
  203302. static const void* defaultDirPath = 0;
  203303. static String returnedString; // need this to get non-existent pathnames from the directory chooser
  203304. static Component* currentExtraFileWin = 0;
  203305. static bool areThereAnyAlwaysOnTopWindows()
  203306. {
  203307. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  203308. {
  203309. Component* c = Desktop::getInstance().getComponent (i);
  203310. if (c != 0 && c->isAlwaysOnTop() && c->isShowing())
  203311. return true;
  203312. }
  203313. return false;
  203314. }
  203315. static int CALLBACK browseCallbackProc (HWND hWnd, UINT msg, LPARAM lParam, LPARAM /*lpData*/)
  203316. {
  203317. if (msg == BFFM_INITIALIZED)
  203318. {
  203319. SendMessage (hWnd, BFFM_SETSELECTIONW, TRUE, (LPARAM) defaultDirPath);
  203320. }
  203321. else if (msg == BFFM_VALIDATEFAILEDW)
  203322. {
  203323. returnedString = (LPCWSTR) lParam;
  203324. }
  203325. else if (msg == BFFM_VALIDATEFAILEDA)
  203326. {
  203327. returnedString = (const char*) lParam;
  203328. }
  203329. return 0;
  203330. }
  203331. void juce_setWindowStyleBit (HWND h, int styleType, int feature, bool bitIsSet);
  203332. static UINT_PTR CALLBACK openCallback (HWND hdlg, UINT uiMsg, WPARAM /*wParam*/, LPARAM lParam)
  203333. {
  203334. if (currentExtraFileWin != 0)
  203335. {
  203336. if (uiMsg == WM_INITDIALOG)
  203337. {
  203338. HWND dialogH = GetParent (hdlg);
  203339. jassert (dialogH != 0);
  203340. if (dialogH == 0)
  203341. dialogH = hdlg;
  203342. RECT r, cr;
  203343. GetWindowRect (dialogH, &r);
  203344. GetClientRect (dialogH, &cr);
  203345. SetWindowPos (dialogH, 0,
  203346. r.left, r.top,
  203347. currentExtraFileWin->getWidth() + jmax (150, r.right - r.left),
  203348. jmax (150, r.bottom - r.top),
  203349. SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER);
  203350. currentExtraFileWin->setBounds (cr.right, cr.top, currentExtraFileWin->getWidth(), cr.bottom - cr.top);
  203351. currentExtraFileWin->getChildComponent(0)->setBounds (0, 0, currentExtraFileWin->getWidth(), currentExtraFileWin->getHeight());
  203352. SetParent ((HWND) currentExtraFileWin->getWindowHandle(), (HWND) dialogH);
  203353. juce_setWindowStyleBit ((HWND)currentExtraFileWin->getWindowHandle(), GWL_STYLE, WS_CHILD, (dialogH != 0));
  203354. juce_setWindowStyleBit ((HWND)currentExtraFileWin->getWindowHandle(), GWL_STYLE, WS_POPUP, (dialogH == 0));
  203355. }
  203356. else if (uiMsg == WM_NOTIFY)
  203357. {
  203358. LPOFNOTIFY ofn = (LPOFNOTIFY) lParam;
  203359. if (ofn->hdr.code == CDN_SELCHANGE)
  203360. {
  203361. FilePreviewComponent* comp = (FilePreviewComponent*) currentExtraFileWin->getChildComponent(0);
  203362. if (comp != 0)
  203363. {
  203364. TCHAR path [MAX_PATH * 2];
  203365. path[0] = 0;
  203366. CommDlg_OpenSave_GetFilePath (GetParent (hdlg), (LPARAM) &path, MAX_PATH);
  203367. const String fn ((const WCHAR*) path);
  203368. comp->selectedFileChanged (File (fn));
  203369. }
  203370. }
  203371. }
  203372. }
  203373. return 0;
  203374. }
  203375. class FPComponentHolder : public Component
  203376. {
  203377. public:
  203378. FPComponentHolder()
  203379. {
  203380. setVisible (true);
  203381. setOpaque (true);
  203382. }
  203383. ~FPComponentHolder()
  203384. {
  203385. }
  203386. void paint (Graphics& g)
  203387. {
  203388. g.fillAll (Colours::lightgrey);
  203389. }
  203390. private:
  203391. FPComponentHolder (const FPComponentHolder&);
  203392. const FPComponentHolder& operator= (const FPComponentHolder&);
  203393. };
  203394. void FileChooser::showPlatformDialog (OwnedArray<File>& results,
  203395. const String& title,
  203396. const File& currentFileOrDirectory,
  203397. const String& filter,
  203398. bool selectsDirectory,
  203399. bool isSaveDialogue,
  203400. bool warnAboutOverwritingExistingFiles,
  203401. bool selectMultipleFiles,
  203402. FilePreviewComponent* extraInfoComponent)
  203403. {
  203404. const int numCharsAvailable = 32768;
  203405. MemoryBlock filenameSpace ((numCharsAvailable + 1) * sizeof (WCHAR), true);
  203406. WCHAR* const fname = (WCHAR*) filenameSpace.getData();
  203407. int fnameIdx = 0;
  203408. JUCE_TRY
  203409. {
  203410. // use a modal window as the parent for this dialog box
  203411. // to block input from other app windows
  203412. const Rectangle mainMon (Desktop::getInstance().getMainMonitorArea());
  203413. Component w (String::empty);
  203414. w.setBounds (mainMon.getX() + mainMon.getWidth() / 4,
  203415. mainMon.getY() + mainMon.getHeight() / 4,
  203416. 0, 0);
  203417. w.setOpaque (true);
  203418. w.setAlwaysOnTop (areThereAnyAlwaysOnTopWindows());
  203419. w.addToDesktop (0);
  203420. if (extraInfoComponent == 0)
  203421. w.enterModalState();
  203422. String initialDir;
  203423. if (currentFileOrDirectory.isDirectory())
  203424. {
  203425. initialDir = currentFileOrDirectory.getFullPathName();
  203426. }
  203427. else
  203428. {
  203429. currentFileOrDirectory.getFileName().copyToBuffer (fname, numCharsAvailable);
  203430. initialDir = currentFileOrDirectory.getParentDirectory().getFullPathName();
  203431. }
  203432. if (currentExtraFileWin->isValidComponent())
  203433. {
  203434. jassertfalse
  203435. return;
  203436. }
  203437. if (selectsDirectory)
  203438. {
  203439. LPITEMIDLIST list = 0;
  203440. filenameSpace.fillWith (0);
  203441. {
  203442. BROWSEINFO bi;
  203443. zerostruct (bi);
  203444. bi.hwndOwner = (HWND) w.getWindowHandle();
  203445. bi.pszDisplayName = fname;
  203446. bi.lpszTitle = title;
  203447. bi.lpfn = browseCallbackProc;
  203448. #ifdef BIF_USENEWUI
  203449. bi.ulFlags = BIF_USENEWUI | BIF_VALIDATE;
  203450. #else
  203451. bi.ulFlags = 0x50;
  203452. #endif
  203453. defaultDirPath = (const WCHAR*) initialDir;
  203454. list = SHBrowseForFolder (&bi);
  203455. if (! SHGetPathFromIDListW (list, fname))
  203456. {
  203457. fname[0] = 0;
  203458. returnedString = String::empty;
  203459. }
  203460. }
  203461. LPMALLOC al;
  203462. if (list != 0 && SUCCEEDED (SHGetMalloc (&al)))
  203463. al->Free (list);
  203464. defaultDirPath = 0;
  203465. if (returnedString.isNotEmpty())
  203466. {
  203467. const String stringFName (fname);
  203468. results.add (new File (File (stringFName).getSiblingFile (returnedString)));
  203469. returnedString = String::empty;
  203470. return;
  203471. }
  203472. }
  203473. else
  203474. {
  203475. DWORD flags = OFN_EXPLORER | OFN_PATHMUSTEXIST | OFN_NOCHANGEDIR | OFN_HIDEREADONLY;
  203476. if (warnAboutOverwritingExistingFiles)
  203477. flags |= OFN_OVERWRITEPROMPT;
  203478. if (selectMultipleFiles)
  203479. flags |= OFN_ALLOWMULTISELECT;
  203480. if (extraInfoComponent != 0)
  203481. {
  203482. flags |= OFN_ENABLEHOOK;
  203483. currentExtraFileWin = new FPComponentHolder();
  203484. currentExtraFileWin->addAndMakeVisible (extraInfoComponent);
  203485. currentExtraFileWin->setSize (jlimit (20, 800, extraInfoComponent->getWidth()),
  203486. extraInfoComponent->getHeight());
  203487. currentExtraFileWin->addToDesktop (0);
  203488. currentExtraFileWin->enterModalState();
  203489. }
  203490. {
  203491. WCHAR filters [1024];
  203492. zeromem (filters, sizeof (filters));
  203493. filter.copyToBuffer (filters, 1024);
  203494. filter.copyToBuffer (filters + filter.length() + 1,
  203495. 1022 - filter.length());
  203496. OPENFILENAMEW of;
  203497. zerostruct (of);
  203498. #ifdef OPENFILENAME_SIZE_VERSION_400W
  203499. of.lStructSize = OPENFILENAME_SIZE_VERSION_400W;
  203500. #else
  203501. of.lStructSize = sizeof (of);
  203502. #endif
  203503. of.hwndOwner = (HWND) w.getWindowHandle();
  203504. of.lpstrFilter = filters;
  203505. of.nFilterIndex = 1;
  203506. of.lpstrFile = fname;
  203507. of.nMaxFile = numCharsAvailable;
  203508. of.lpstrInitialDir = initialDir;
  203509. of.lpstrTitle = title;
  203510. of.Flags = flags;
  203511. if (extraInfoComponent != 0)
  203512. of.lpfnHook = &openCallback;
  203513. if (isSaveDialogue)
  203514. {
  203515. if (! GetSaveFileName (&of))
  203516. fname[0] = 0;
  203517. else
  203518. fnameIdx = of.nFileOffset;
  203519. }
  203520. else
  203521. {
  203522. if (! GetOpenFileName (&of))
  203523. fname[0] = 0;
  203524. else
  203525. fnameIdx = of.nFileOffset;
  203526. }
  203527. }
  203528. }
  203529. }
  203530. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  203531. catch (...)
  203532. {
  203533. fname[0] = 0;
  203534. }
  203535. #endif
  203536. deleteAndZero (currentExtraFileWin);
  203537. const WCHAR* const files = fname;
  203538. if (selectMultipleFiles && fnameIdx > 0 && files [fnameIdx - 1] == 0)
  203539. {
  203540. const WCHAR* filename = files + fnameIdx;
  203541. while (*filename != 0)
  203542. {
  203543. const String filepath (String (files) + T("\\") + String (filename));
  203544. results.add (new File (filepath));
  203545. filename += CharacterFunctions::length (filename) + 1;
  203546. }
  203547. }
  203548. else if (files[0] != 0)
  203549. {
  203550. results.add (new File (files));
  203551. }
  203552. }
  203553. END_JUCE_NAMESPACE
  203554. /********* End of inlined file: juce_win32_FileChooser.cpp *********/
  203555. /********* Start of inlined file: juce_win32_Fonts.cpp *********/
  203556. BEGIN_JUCE_NAMESPACE
  203557. static int CALLBACK wfontEnum2 (ENUMLOGFONTEXW* lpelfe,
  203558. NEWTEXTMETRICEXW*,
  203559. int type,
  203560. LPARAM lParam)
  203561. {
  203562. if (lpelfe != 0 && type == TRUETYPE_FONTTYPE)
  203563. {
  203564. const String fontName (lpelfe->elfLogFont.lfFaceName);
  203565. ((StringArray*) lParam)->addIfNotAlreadyThere (fontName.removeCharacters (T("@")));
  203566. }
  203567. return 1;
  203568. }
  203569. static int CALLBACK wfontEnum1 (ENUMLOGFONTEXW* lpelfe,
  203570. NEWTEXTMETRICEXW*,
  203571. int type,
  203572. LPARAM lParam)
  203573. {
  203574. if (lpelfe != 0
  203575. && ((type & (DEVICE_FONTTYPE | RASTER_FONTTYPE)) == 0))
  203576. {
  203577. LOGFONTW lf;
  203578. zerostruct (lf);
  203579. lf.lfWeight = FW_DONTCARE;
  203580. lf.lfOutPrecision = OUT_TT_ONLY_PRECIS;
  203581. lf.lfQuality = DEFAULT_QUALITY;
  203582. lf.lfCharSet = DEFAULT_CHARSET;
  203583. lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  203584. lf.lfPitchAndFamily = FF_DONTCARE;
  203585. const String fontName (lpelfe->elfLogFont.lfFaceName);
  203586. fontName.copyToBuffer (lf.lfFaceName, LF_FACESIZE - 1);
  203587. HDC dc = CreateCompatibleDC (0);
  203588. EnumFontFamiliesEx (dc, &lf,
  203589. (FONTENUMPROCW) &wfontEnum2,
  203590. lParam, 0);
  203591. DeleteDC (dc);
  203592. }
  203593. return 1;
  203594. }
  203595. const StringArray Font::findAllTypefaceNames() throw()
  203596. {
  203597. StringArray results;
  203598. HDC dc = CreateCompatibleDC (0);
  203599. {
  203600. LOGFONTW lf;
  203601. zerostruct (lf);
  203602. lf.lfWeight = FW_DONTCARE;
  203603. lf.lfOutPrecision = OUT_TT_ONLY_PRECIS;
  203604. lf.lfQuality = DEFAULT_QUALITY;
  203605. lf.lfCharSet = DEFAULT_CHARSET;
  203606. lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  203607. lf.lfPitchAndFamily = FF_DONTCARE;
  203608. lf.lfFaceName[0] = 0;
  203609. EnumFontFamiliesEx (dc, &lf,
  203610. (FONTENUMPROCW) &wfontEnum1,
  203611. (LPARAM) &results, 0);
  203612. }
  203613. DeleteDC (dc);
  203614. results.sort (true);
  203615. return results;
  203616. }
  203617. extern bool juce_IsRunningInWine() throw();
  203618. void Font::getDefaultFontNames (String& defaultSans,
  203619. String& defaultSerif,
  203620. String& defaultFixed) throw()
  203621. {
  203622. if (juce_IsRunningInWine())
  203623. {
  203624. // If we're running in Wine, then use fonts that might be available on Linux..
  203625. defaultSans = "Bitstream Vera Sans";
  203626. defaultSerif = "Bitstream Vera Serif";
  203627. defaultFixed = "Bitstream Vera Sans Mono";
  203628. }
  203629. else
  203630. {
  203631. defaultSans = "Verdana";
  203632. defaultSerif = "Times";
  203633. defaultFixed = "Lucida Console";
  203634. }
  203635. }
  203636. class FontDCHolder : private DeletedAtShutdown
  203637. {
  203638. HDC dc;
  203639. String fontName;
  203640. KERNINGPAIR* kps;
  203641. int numKPs;
  203642. bool bold, italic;
  203643. int size;
  203644. FontDCHolder (const FontDCHolder&);
  203645. const FontDCHolder& operator= (const FontDCHolder&);
  203646. public:
  203647. HFONT fontH;
  203648. FontDCHolder() throw()
  203649. : dc (0),
  203650. kps (0),
  203651. numKPs (0),
  203652. bold (false),
  203653. italic (false),
  203654. size (0)
  203655. {
  203656. }
  203657. ~FontDCHolder() throw()
  203658. {
  203659. if (dc != 0)
  203660. {
  203661. DeleteDC (dc);
  203662. DeleteObject (fontH);
  203663. juce_free (kps);
  203664. }
  203665. clearSingletonInstance();
  203666. }
  203667. juce_DeclareSingleton_SingleThreaded_Minimal (FontDCHolder);
  203668. HDC loadFont (const String& fontName_,
  203669. const bool bold_,
  203670. const bool italic_,
  203671. const int size_) throw()
  203672. {
  203673. if (fontName != fontName_ || bold != bold_ || italic != italic_ || size != size_)
  203674. {
  203675. fontName = fontName_;
  203676. bold = bold_;
  203677. italic = italic_;
  203678. size = size_;
  203679. if (dc != 0)
  203680. {
  203681. DeleteDC (dc);
  203682. DeleteObject (fontH);
  203683. juce_free (kps);
  203684. kps = 0;
  203685. }
  203686. fontH = 0;
  203687. dc = CreateCompatibleDC (0);
  203688. SetMapperFlags (dc, 0);
  203689. SetMapMode (dc, MM_TEXT);
  203690. LOGFONTW lfw;
  203691. zerostruct (lfw);
  203692. lfw.lfCharSet = DEFAULT_CHARSET;
  203693. lfw.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  203694. lfw.lfOutPrecision = OUT_OUTLINE_PRECIS;
  203695. lfw.lfPitchAndFamily = DEFAULT_PITCH | FF_DONTCARE;
  203696. lfw.lfQuality = PROOF_QUALITY;
  203697. lfw.lfItalic = (BYTE) (italic ? TRUE : FALSE);
  203698. lfw.lfWeight = bold ? FW_BOLD : FW_NORMAL;
  203699. fontName.copyToBuffer (lfw.lfFaceName, LF_FACESIZE - 1);
  203700. lfw.lfHeight = size > 0 ? size : -256;
  203701. HFONT standardSizedFont = CreateFontIndirect (&lfw);
  203702. if (standardSizedFont != 0)
  203703. {
  203704. if (SelectObject (dc, standardSizedFont) != 0)
  203705. {
  203706. fontH = standardSizedFont;
  203707. if (size == 0)
  203708. {
  203709. OUTLINETEXTMETRIC otm;
  203710. if (GetOutlineTextMetrics (dc, sizeof (otm), &otm) != 0)
  203711. {
  203712. lfw.lfHeight = -(int) otm.otmEMSquare;
  203713. fontH = CreateFontIndirect (&lfw);
  203714. SelectObject (dc, fontH);
  203715. DeleteObject (standardSizedFont);
  203716. }
  203717. }
  203718. }
  203719. else
  203720. {
  203721. jassertfalse
  203722. }
  203723. }
  203724. else
  203725. {
  203726. jassertfalse
  203727. }
  203728. }
  203729. return dc;
  203730. }
  203731. KERNINGPAIR* getKerningPairs (int& numKPs_) throw()
  203732. {
  203733. if (kps == 0)
  203734. {
  203735. numKPs = GetKerningPairs (dc, 0, 0);
  203736. kps = (KERNINGPAIR*) juce_calloc (sizeof (KERNINGPAIR) * numKPs);
  203737. GetKerningPairs (dc, numKPs, kps);
  203738. }
  203739. numKPs_ = numKPs;
  203740. return kps;
  203741. }
  203742. };
  203743. juce_ImplementSingleton_SingleThreaded (FontDCHolder);
  203744. static bool addGlyphToTypeface (HDC dc,
  203745. juce_wchar character,
  203746. Typeface& dest,
  203747. bool addKerning)
  203748. {
  203749. Path destShape;
  203750. GLYPHMETRICS gm;
  203751. float height;
  203752. BOOL ok = false;
  203753. {
  203754. const WCHAR charToTest[] = { (WCHAR) character, 0 };
  203755. WORD index = 0;
  203756. if (GetGlyphIndices (dc, charToTest, 1, &index, GGI_MARK_NONEXISTING_GLYPHS) != GDI_ERROR
  203757. && index == 0xffff)
  203758. {
  203759. return false;
  203760. }
  203761. }
  203762. TEXTMETRIC tm;
  203763. ok = GetTextMetrics (dc, &tm);
  203764. height = (float) tm.tmHeight;
  203765. if (! ok)
  203766. {
  203767. dest.addGlyph (character, destShape, 0);
  203768. return true;
  203769. }
  203770. const float scaleX = 1.0f / height;
  203771. const float scaleY = -1.0f / height;
  203772. static const MAT2 identityMatrix = { { 0, 1 }, { 0, 0 }, { 0, 0 }, { 0, 1 } };
  203773. const int bufSize = GetGlyphOutline (dc, character, GGO_NATIVE,
  203774. &gm, 0, 0, &identityMatrix);
  203775. if (bufSize > 0)
  203776. {
  203777. char* const data = (char*) juce_malloc (bufSize);
  203778. GetGlyphOutline (dc, character, GGO_NATIVE, &gm,
  203779. bufSize, data, &identityMatrix);
  203780. const TTPOLYGONHEADER* pheader = (TTPOLYGONHEADER*) data;
  203781. while ((char*) pheader < data + bufSize)
  203782. {
  203783. #define remapX(v) (scaleX * (v).x.value)
  203784. #define remapY(v) (scaleY * (v).y.value)
  203785. float x = remapX (pheader->pfxStart);
  203786. float y = remapY (pheader->pfxStart);
  203787. destShape.startNewSubPath (x, y);
  203788. const TTPOLYCURVE* curve = (const TTPOLYCURVE*) ((const char*) pheader + sizeof (TTPOLYGONHEADER));
  203789. const char* const curveEnd = ((const char*) pheader) + pheader->cb;
  203790. while ((const char*) curve < curveEnd)
  203791. {
  203792. if (curve->wType == TT_PRIM_LINE)
  203793. {
  203794. for (int i = 0; i < curve->cpfx; ++i)
  203795. {
  203796. x = remapX (curve->apfx [i]);
  203797. y = remapY (curve->apfx [i]);
  203798. destShape.lineTo (x, y);
  203799. }
  203800. }
  203801. else if (curve->wType == TT_PRIM_QSPLINE)
  203802. {
  203803. for (int i = 0; i < curve->cpfx - 1; ++i)
  203804. {
  203805. const float x2 = remapX (curve->apfx [i]);
  203806. const float y2 = remapY (curve->apfx [i]);
  203807. float x3, y3;
  203808. if (i < curve->cpfx - 2)
  203809. {
  203810. x3 = 0.5f * (x2 + remapX (curve->apfx [i + 1]));
  203811. y3 = 0.5f * (y2 + remapY (curve->apfx [i + 1]));
  203812. }
  203813. else
  203814. {
  203815. x3 = remapX (curve->apfx [i + 1]);
  203816. y3 = remapY (curve->apfx [i + 1]);
  203817. }
  203818. destShape.quadraticTo (x2, y2, x3, y3);
  203819. x = x3;
  203820. y = y3;
  203821. }
  203822. }
  203823. curve = (const TTPOLYCURVE*) &(curve->apfx [curve->cpfx]);
  203824. }
  203825. pheader = (const TTPOLYGONHEADER*) curve;
  203826. destShape.closeSubPath();
  203827. }
  203828. juce_free (data);
  203829. }
  203830. dest.addGlyph (character, destShape, gm.gmCellIncX / height);
  203831. if (addKerning)
  203832. {
  203833. int numKPs;
  203834. const KERNINGPAIR* const kps = FontDCHolder::getInstance()->getKerningPairs (numKPs);
  203835. for (int i = 0; i < numKPs; ++i)
  203836. {
  203837. if (kps[i].wFirst == character)
  203838. {
  203839. dest.addKerningPair (kps[i].wFirst,
  203840. kps[i].wSecond,
  203841. kps[i].iKernAmount / height);
  203842. }
  203843. }
  203844. }
  203845. return true;
  203846. }
  203847. bool Typeface::findAndAddSystemGlyph (juce_wchar character) throw()
  203848. {
  203849. HDC dc = FontDCHolder::getInstance()->loadFont (getName(), isBold(), isItalic(), 0);
  203850. return addGlyphToTypeface (dc, character, *this, true);
  203851. }
  203852. /*Image* Typeface::renderGlyphToImage (juce_wchar character, float& topLeftX, float& topLeftY)
  203853. {
  203854. HDC dc = FontDCHolder::getInstance()->loadFont (getName(), isBold(), isItalic(), hintingSize);
  203855. int bufSize;
  203856. GLYPHMETRICS gm;
  203857. const UINT format = GGO_GRAY2_BITMAP;
  203858. const int shift = 6;
  203859. if (wGetGlyphOutlineW != 0)
  203860. bufSize = wGetGlyphOutlineW (dc, character, format, &gm, 0, 0, &identityMatrix);
  203861. else
  203862. bufSize = GetGlyphOutline (dc, character, format, &gm, 0, 0, &identityMatrix);
  203863. Image* im = new Image (Image::SingleChannel, jmax (1, gm.gmBlackBoxX), jmax (1, gm.gmBlackBoxY), true);
  203864. if (bufSize > 0)
  203865. {
  203866. topLeftX = (float) gm.gmptGlyphOrigin.x;
  203867. topLeftY = (float) -gm.gmptGlyphOrigin.y;
  203868. uint8* const data = (uint8*) juce_calloc (bufSize);
  203869. if (wGetGlyphOutlineW != 0)
  203870. wGetGlyphOutlineW (dc, character, format, &gm, bufSize, data, &identityMatrix);
  203871. else
  203872. GetGlyphOutline (dc, character, format, &gm, bufSize, data, &identityMatrix);
  203873. const int stride = ((gm.gmBlackBoxX + 3) & ~3);
  203874. for (int y = gm.gmBlackBoxY; --y >= 0;)
  203875. {
  203876. for (int x = gm.gmBlackBoxX; --x >= 0;)
  203877. {
  203878. const int level = data [x + y * stride] << shift;
  203879. if (level > 0)
  203880. im->setPixelAt (x, y, Colour ((uint8) 0xff, (uint8) 0xff, (uint8) 0xff, (uint8) jmin (0xff, level)));
  203881. }
  203882. }
  203883. juce_free (data);
  203884. }
  203885. return im;
  203886. }*/
  203887. void Typeface::initialiseTypefaceCharacteristics (const String& fontName,
  203888. bool bold,
  203889. bool italic,
  203890. bool addAllGlyphsToFont) throw()
  203891. {
  203892. clear();
  203893. HDC dc = FontDCHolder::getInstance()->loadFont (fontName, bold, italic, 0);
  203894. float height;
  203895. int firstChar, lastChar;
  203896. {
  203897. TEXTMETRIC tm;
  203898. GetTextMetrics (dc, &tm);
  203899. height = (float) tm.tmHeight;
  203900. firstChar = tm.tmFirstChar;
  203901. lastChar = tm.tmLastChar;
  203902. setAscent (tm.tmAscent / height);
  203903. setDefaultCharacter (tm.tmDefaultChar);
  203904. }
  203905. setName (fontName);
  203906. setBold (bold);
  203907. setItalic (italic);
  203908. if (addAllGlyphsToFont)
  203909. {
  203910. for (int character = firstChar; character <= lastChar; ++character)
  203911. addGlyphToTypeface (dc, (juce_wchar) character, *this, false);
  203912. int numKPs;
  203913. const KERNINGPAIR* const kps = FontDCHolder::getInstance()->getKerningPairs (numKPs);
  203914. for (int i = 0; i < numKPs; ++i)
  203915. {
  203916. addKerningPair (kps[i].wFirst,
  203917. kps[i].wSecond,
  203918. kps[i].iKernAmount / height);
  203919. }
  203920. }
  203921. }
  203922. END_JUCE_NAMESPACE
  203923. /********* End of inlined file: juce_win32_Fonts.cpp *********/
  203924. /********* Start of inlined file: juce_win32_Messaging.cpp *********/
  203925. BEGIN_JUCE_NAMESPACE
  203926. static const unsigned int specialId = WM_APP + 0x4400;
  203927. static const unsigned int broadcastId = WM_APP + 0x4403;
  203928. static const unsigned int specialCallbackId = WM_APP + 0x4402;
  203929. static const TCHAR* const messageWindowName = _T("JUCEWindow");
  203930. HWND juce_messageWindowHandle = 0;
  203931. extern long improbableWindowNumber; // defined in windowing.cpp
  203932. static LRESULT CALLBACK juce_MessageWndProc (HWND h,
  203933. const UINT message,
  203934. const WPARAM wParam,
  203935. const LPARAM lParam) throw()
  203936. {
  203937. JUCE_TRY
  203938. {
  203939. if (h == juce_messageWindowHandle)
  203940. {
  203941. if (message == specialCallbackId)
  203942. {
  203943. MessageCallbackFunction* const func = (MessageCallbackFunction*) wParam;
  203944. return (LRESULT) (*func) ((void*) lParam);
  203945. }
  203946. else if (message == specialId)
  203947. {
  203948. // these are trapped early in the dispatch call, but must also be checked
  203949. // here in case there are windows modal dialog boxes doing their own
  203950. // dispatch loop and not calling our version
  203951. MessageManager::getInstance()->deliverMessage ((void*) lParam);
  203952. return 0;
  203953. }
  203954. else if (message == broadcastId)
  203955. {
  203956. String* const messageString = (String*) lParam;
  203957. MessageManager::getInstance()->deliverBroadcastMessage (*messageString);
  203958. delete messageString;
  203959. return 0;
  203960. }
  203961. else if (message == WM_COPYDATA && ((const COPYDATASTRUCT*) lParam)->dwData == broadcastId)
  203962. {
  203963. const String messageString ((const juce_wchar*) ((const COPYDATASTRUCT*) lParam)->lpData,
  203964. ((const COPYDATASTRUCT*) lParam)->cbData / sizeof (juce_wchar));
  203965. PostMessage (juce_messageWindowHandle, broadcastId, 0, (LPARAM) new String (messageString));
  203966. return 0;
  203967. }
  203968. }
  203969. }
  203970. JUCE_CATCH_EXCEPTION
  203971. return DefWindowProc (h, message, wParam, lParam);
  203972. }
  203973. bool juce_dispatchNextMessageOnSystemQueue (const bool returnIfNoPendingMessages)
  203974. {
  203975. MSG m;
  203976. if (returnIfNoPendingMessages && ! PeekMessage (&m, (HWND) 0, 0, 0, 0))
  203977. return false;
  203978. if (GetMessage (&m, (HWND) 0, 0, 0) > 0)
  203979. {
  203980. if (m.message == specialId
  203981. && m.hwnd == juce_messageWindowHandle)
  203982. {
  203983. MessageManager::getInstance()->deliverMessage ((void*) m.lParam);
  203984. }
  203985. else
  203986. {
  203987. if (GetWindowLong (m.hwnd, GWLP_USERDATA) != improbableWindowNumber
  203988. && (m.message == WM_LBUTTONDOWN || m.message == WM_RBUTTONDOWN))
  203989. {
  203990. // if it's someone else's window being clicked on, and the focus is
  203991. // currently on a juce window, pass the kb focus over..
  203992. HWND currentFocus = GetFocus();
  203993. if (currentFocus == 0 || GetWindowLong (currentFocus, GWLP_USERDATA) == improbableWindowNumber)
  203994. SetFocus (m.hwnd);
  203995. }
  203996. TranslateMessage (&m);
  203997. DispatchMessage (&m);
  203998. }
  203999. }
  204000. return true;
  204001. }
  204002. bool juce_postMessageToSystemQueue (void* message)
  204003. {
  204004. return PostMessage (juce_messageWindowHandle, specialId, 0, (LPARAM) message) != 0;
  204005. }
  204006. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback,
  204007. void* userData)
  204008. {
  204009. if (MessageManager::getInstance()->isThisTheMessageThread())
  204010. {
  204011. return (*callback) (userData);
  204012. }
  204013. else
  204014. {
  204015. // If a thread has a MessageManagerLock and then tries to call this method, it'll
  204016. // deadlock because the message manager is blocked from running, and can't
  204017. // call your function..
  204018. jassert (! MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  204019. return (void*) SendMessage (juce_messageWindowHandle,
  204020. specialCallbackId,
  204021. (WPARAM) callback,
  204022. (LPARAM) userData);
  204023. }
  204024. }
  204025. static BOOL CALLBACK BroadcastEnumWindowProc (HWND hwnd, LPARAM lParam)
  204026. {
  204027. if (hwnd != juce_messageWindowHandle)
  204028. (reinterpret_cast <VoidArray*> (lParam))->add ((void*) hwnd);
  204029. return TRUE;
  204030. }
  204031. void MessageManager::broadcastMessage (const String& value) throw()
  204032. {
  204033. VoidArray windows;
  204034. EnumWindows (&BroadcastEnumWindowProc, (LPARAM) &windows);
  204035. const String localCopy (value);
  204036. COPYDATASTRUCT data;
  204037. data.dwData = broadcastId;
  204038. data.cbData = (localCopy.length() + 1) * sizeof (juce_wchar);
  204039. data.lpData = (void*) (const juce_wchar*) localCopy;
  204040. for (int i = windows.size(); --i >= 0;)
  204041. {
  204042. HWND hwnd = (HWND) windows.getUnchecked(i);
  204043. TCHAR windowName [64]; // no need to read longer strings than this
  204044. GetWindowText (hwnd, windowName, 64);
  204045. windowName [63] = 0;
  204046. if (String (windowName) == String (messageWindowName))
  204047. {
  204048. DWORD_PTR result;
  204049. SendMessageTimeout (hwnd, WM_COPYDATA,
  204050. (WPARAM) juce_messageWindowHandle,
  204051. (LPARAM) &data,
  204052. SMTO_BLOCK | SMTO_ABORTIFHUNG,
  204053. 8000,
  204054. &result);
  204055. }
  204056. }
  204057. }
  204058. static const String getMessageWindowClassName()
  204059. {
  204060. // this name has to be different for each app/dll instance because otherwise
  204061. // poor old Win32 can get a bit confused (even despite it not being a process-global
  204062. // window class).
  204063. static int number = 0;
  204064. if (number == 0)
  204065. number = 0x7fffffff & (int) Time::getHighResolutionTicks();
  204066. return T("JUCEcs_") + String (number);
  204067. }
  204068. void MessageManager::doPlatformSpecificInitialisation()
  204069. {
  204070. OleInitialize (0);
  204071. const String className (getMessageWindowClassName());
  204072. HMODULE hmod = (HMODULE) PlatformUtilities::getCurrentModuleInstanceHandle();
  204073. WNDCLASSEX wc;
  204074. zerostruct (wc);
  204075. wc.cbSize = sizeof (wc);
  204076. wc.lpfnWndProc = (WNDPROC) juce_MessageWndProc;
  204077. wc.cbWndExtra = 4;
  204078. wc.hInstance = hmod;
  204079. wc.lpszClassName = className;
  204080. RegisterClassEx (&wc);
  204081. juce_messageWindowHandle = CreateWindow (wc.lpszClassName,
  204082. messageWindowName,
  204083. 0, 0, 0, 0, 0, 0, 0,
  204084. hmod, 0);
  204085. }
  204086. void MessageManager::doPlatformSpecificShutdown()
  204087. {
  204088. DestroyWindow (juce_messageWindowHandle);
  204089. UnregisterClass (getMessageWindowClassName(), 0);
  204090. OleUninitialize();
  204091. }
  204092. END_JUCE_NAMESPACE
  204093. /********* End of inlined file: juce_win32_Messaging.cpp *********/
  204094. /********* Start of inlined file: juce_win32_Midi.cpp *********/
  204095. BEGIN_JUCE_NAMESPACE
  204096. #if JUCE_MSVC
  204097. #pragma warning (disable: 4312)
  204098. #endif
  204099. using ::free;
  204100. static const int midiBufferSize = 1024 * 10;
  204101. static const int numInHeaders = 32;
  204102. static const int inBufferSize = 256;
  204103. static Array <void*, CriticalSection> activeMidiThreads;
  204104. class MidiInThread : public Thread
  204105. {
  204106. public:
  204107. MidiInThread (MidiInput* const input_,
  204108. MidiInputCallback* const callback_)
  204109. : Thread ("Juce Midi"),
  204110. hIn (0),
  204111. input (input_),
  204112. callback (callback_),
  204113. isStarted (false),
  204114. startTime (0),
  204115. pendingLength(0)
  204116. {
  204117. for (int i = numInHeaders; --i >= 0;)
  204118. {
  204119. zeromem (&hdr[i], sizeof (MIDIHDR));
  204120. hdr[i].lpData = inData[i];
  204121. hdr[i].dwBufferLength = inBufferSize;
  204122. }
  204123. };
  204124. ~MidiInThread()
  204125. {
  204126. stop();
  204127. if (hIn != 0)
  204128. {
  204129. int count = 5;
  204130. while (--count >= 0)
  204131. {
  204132. if (midiInClose (hIn) == MMSYSERR_NOERROR)
  204133. break;
  204134. Sleep (20);
  204135. }
  204136. }
  204137. }
  204138. void handle (const uint32 message, const uint32 timeStamp) throw()
  204139. {
  204140. const int byte = message & 0xff;
  204141. if (byte < 0x80)
  204142. return;
  204143. const int numBytes = MidiMessage::getMessageLengthFromFirstByte ((uint8) byte);
  204144. const double time = timeStampToTime (timeStamp);
  204145. lock.enter();
  204146. if (pendingLength < midiBufferSize - 12)
  204147. {
  204148. char* const p = pending + pendingLength;
  204149. *(double*) p = time;
  204150. *(uint32*) (p + 8) = numBytes;
  204151. *(uint32*) (p + 12) = message;
  204152. pendingLength += 12 + numBytes;
  204153. }
  204154. else
  204155. {
  204156. jassertfalse // midi buffer overflow! You might need to increase the size..
  204157. }
  204158. lock.exit();
  204159. notify();
  204160. }
  204161. void handleSysEx (MIDIHDR* const hdr, const uint32 timeStamp) throw()
  204162. {
  204163. const int num = hdr->dwBytesRecorded;
  204164. if (num > 0)
  204165. {
  204166. const double time = timeStampToTime (timeStamp);
  204167. lock.enter();
  204168. if (pendingLength < midiBufferSize - (8 + num))
  204169. {
  204170. char* const p = pending + pendingLength;
  204171. *(double*) p = time;
  204172. *(uint32*) (p + 8) = num;
  204173. memcpy (p + 12, hdr->lpData, num);
  204174. pendingLength += 12 + num;
  204175. }
  204176. else
  204177. {
  204178. jassertfalse // midi buffer overflow! You might need to increase the size..
  204179. }
  204180. lock.exit();
  204181. notify();
  204182. }
  204183. }
  204184. void writeBlock (const int i) throw()
  204185. {
  204186. hdr[i].dwBytesRecorded = 0;
  204187. MMRESULT res = midiInPrepareHeader (hIn, &hdr[i], sizeof (MIDIHDR));
  204188. jassert (res == MMSYSERR_NOERROR);
  204189. res = midiInAddBuffer (hIn, &hdr[i], sizeof (MIDIHDR));
  204190. jassert (res == MMSYSERR_NOERROR);
  204191. }
  204192. void run()
  204193. {
  204194. MemoryBlock pendingCopy (64);
  204195. while (! threadShouldExit())
  204196. {
  204197. for (int i = 0; i < numInHeaders; ++i)
  204198. {
  204199. if ((hdr[i].dwFlags & WHDR_DONE) != 0)
  204200. {
  204201. MMRESULT res = midiInUnprepareHeader (hIn, &hdr[i], sizeof (MIDIHDR));
  204202. (void) res;
  204203. jassert (res == MMSYSERR_NOERROR);
  204204. writeBlock (i);
  204205. }
  204206. }
  204207. lock.enter();
  204208. int len = pendingLength;
  204209. if (len > 0)
  204210. {
  204211. pendingCopy.ensureSize (len);
  204212. pendingCopy.copyFrom (pending, 0, len);
  204213. pendingLength = 0;
  204214. }
  204215. lock.exit();
  204216. //xxx needs to figure out if blocks are broken up or not
  204217. if (len == 0)
  204218. {
  204219. wait (500);
  204220. }
  204221. else
  204222. {
  204223. const char* p = (const char*) pendingCopy.getData();
  204224. while (len > 0)
  204225. {
  204226. const double time = *(const double*) p;
  204227. const int messageLen = *(const int*) (p + 8);
  204228. const MidiMessage message ((const uint8*) (p + 12), messageLen, time);
  204229. callback->handleIncomingMidiMessage (input, message);
  204230. p += 12 + messageLen;
  204231. len -= 12 + messageLen;
  204232. }
  204233. }
  204234. }
  204235. }
  204236. void start() throw()
  204237. {
  204238. jassert (hIn != 0);
  204239. if (hIn != 0 && ! isStarted)
  204240. {
  204241. stop();
  204242. activeMidiThreads.addIfNotAlreadyThere (this);
  204243. int i;
  204244. for (i = 0; i < numInHeaders; ++i)
  204245. writeBlock (i);
  204246. startTime = Time::getMillisecondCounter();
  204247. MMRESULT res = midiInStart (hIn);
  204248. jassert (res == MMSYSERR_NOERROR);
  204249. if (res == MMSYSERR_NOERROR)
  204250. {
  204251. isStarted = true;
  204252. pendingLength = 0;
  204253. startThread (6);
  204254. }
  204255. }
  204256. }
  204257. void stop() throw()
  204258. {
  204259. if (isStarted)
  204260. {
  204261. stopThread (5000);
  204262. midiInReset (hIn);
  204263. midiInStop (hIn);
  204264. activeMidiThreads.removeValue (this);
  204265. lock.enter();
  204266. lock.exit();
  204267. for (int i = numInHeaders; --i >= 0;)
  204268. {
  204269. if ((hdr[i].dwFlags & WHDR_DONE) != 0)
  204270. {
  204271. int c = 10;
  204272. while (--c >= 0 && midiInUnprepareHeader (hIn, &hdr[i], sizeof (MIDIHDR)) == MIDIERR_STILLPLAYING)
  204273. Sleep (20);
  204274. jassert (c >= 0);
  204275. }
  204276. }
  204277. isStarted = false;
  204278. pendingLength = 0;
  204279. }
  204280. }
  204281. juce_UseDebuggingNewOperator
  204282. HMIDIIN hIn;
  204283. private:
  204284. MidiInput* input;
  204285. MidiInputCallback* callback;
  204286. bool isStarted;
  204287. uint32 startTime;
  204288. CriticalSection lock;
  204289. MIDIHDR hdr [numInHeaders];
  204290. char inData [numInHeaders] [inBufferSize];
  204291. int pendingLength;
  204292. char pending [midiBufferSize];
  204293. double timeStampToTime (uint32 timeStamp) throw()
  204294. {
  204295. timeStamp += startTime;
  204296. const uint32 now = Time::getMillisecondCounter();
  204297. if (timeStamp > now)
  204298. {
  204299. if (timeStamp > now + 2)
  204300. --startTime;
  204301. timeStamp = now;
  204302. }
  204303. return 0.001 * timeStamp;
  204304. }
  204305. MidiInThread (const MidiInThread&);
  204306. const MidiInThread& operator= (const MidiInThread&);
  204307. };
  204308. static void CALLBACK midiInCallback (HMIDIIN,
  204309. UINT uMsg,
  204310. DWORD_PTR dwInstance,
  204311. DWORD_PTR midiMessage,
  204312. DWORD_PTR timeStamp)
  204313. {
  204314. MidiInThread* const thread = (MidiInThread*) dwInstance;
  204315. if (thread != 0 && activeMidiThreads.contains (thread))
  204316. {
  204317. if (uMsg == MIM_DATA)
  204318. thread->handle ((uint32) midiMessage, (uint32) timeStamp);
  204319. else if (uMsg == MIM_LONGDATA)
  204320. thread->handleSysEx ((MIDIHDR*) midiMessage, (uint32) timeStamp);
  204321. }
  204322. }
  204323. const StringArray MidiInput::getDevices()
  204324. {
  204325. StringArray s;
  204326. const int num = midiInGetNumDevs();
  204327. for (int i = 0; i < num; ++i)
  204328. {
  204329. MIDIINCAPS mc;
  204330. zerostruct (mc);
  204331. if (midiInGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  204332. s.add (String (mc.szPname, sizeof (mc.szPname)));
  204333. }
  204334. return s;
  204335. }
  204336. int MidiInput::getDefaultDeviceIndex()
  204337. {
  204338. return 0;
  204339. }
  204340. MidiInput* MidiInput::openDevice (const int index, MidiInputCallback* const callback)
  204341. {
  204342. if (callback == 0)
  204343. return 0;
  204344. UINT deviceId = MIDI_MAPPER;
  204345. int n = 0;
  204346. String name;
  204347. const int num = midiInGetNumDevs();
  204348. for (int i = 0; i < num; ++i)
  204349. {
  204350. MIDIINCAPS mc;
  204351. zerostruct (mc);
  204352. if (midiInGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  204353. {
  204354. if (index == n)
  204355. {
  204356. deviceId = i;
  204357. name = String (mc.szPname, sizeof (mc.szPname));
  204358. break;
  204359. }
  204360. ++n;
  204361. }
  204362. }
  204363. MidiInput* const in = new MidiInput (name);
  204364. MidiInThread* const thread = new MidiInThread (in, callback);
  204365. HMIDIIN h;
  204366. HRESULT err = midiInOpen (&h, deviceId,
  204367. (DWORD_PTR) &midiInCallback,
  204368. (DWORD_PTR) thread,
  204369. CALLBACK_FUNCTION);
  204370. if (err == MMSYSERR_NOERROR)
  204371. {
  204372. thread->hIn = h;
  204373. in->internal = (void*) thread;
  204374. return in;
  204375. }
  204376. else
  204377. {
  204378. delete in;
  204379. delete thread;
  204380. return 0;
  204381. }
  204382. }
  204383. MidiInput::MidiInput (const String& name_)
  204384. : name (name_),
  204385. internal (0)
  204386. {
  204387. }
  204388. MidiInput::~MidiInput()
  204389. {
  204390. if (internal != 0)
  204391. {
  204392. MidiInThread* const thread = (MidiInThread*) internal;
  204393. delete thread;
  204394. }
  204395. }
  204396. void MidiInput::start()
  204397. {
  204398. ((MidiInThread*) internal)->start();
  204399. }
  204400. void MidiInput::stop()
  204401. {
  204402. ((MidiInThread*) internal)->stop();
  204403. }
  204404. struct MidiOutHandle
  204405. {
  204406. int refCount;
  204407. UINT deviceId;
  204408. HMIDIOUT handle;
  204409. juce_UseDebuggingNewOperator
  204410. };
  204411. static VoidArray handles (4);
  204412. const StringArray MidiOutput::getDevices()
  204413. {
  204414. StringArray s;
  204415. const int num = midiOutGetNumDevs();
  204416. for (int i = 0; i < num; ++i)
  204417. {
  204418. MIDIOUTCAPS mc;
  204419. zerostruct (mc);
  204420. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  204421. s.add (String (mc.szPname, sizeof (mc.szPname)));
  204422. }
  204423. return s;
  204424. }
  204425. int MidiOutput::getDefaultDeviceIndex()
  204426. {
  204427. const int num = midiOutGetNumDevs();
  204428. int n = 0;
  204429. for (int i = 0; i < num; ++i)
  204430. {
  204431. MIDIOUTCAPS mc;
  204432. zerostruct (mc);
  204433. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  204434. {
  204435. if ((mc.wTechnology & MOD_MAPPER) != 0)
  204436. return n;
  204437. ++n;
  204438. }
  204439. }
  204440. return 0;
  204441. }
  204442. MidiOutput* MidiOutput::openDevice (int index)
  204443. {
  204444. UINT deviceId = MIDI_MAPPER;
  204445. const int num = midiOutGetNumDevs();
  204446. int i, n = 0;
  204447. for (i = 0; i < num; ++i)
  204448. {
  204449. MIDIOUTCAPS mc;
  204450. zerostruct (mc);
  204451. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  204452. {
  204453. // use the microsoft sw synth as a default - best not to allow deviceId
  204454. // to be MIDI_MAPPER, or else device sharing breaks
  204455. if (String (mc.szPname, sizeof (mc.szPname)).containsIgnoreCase (T("microsoft")))
  204456. deviceId = i;
  204457. if (index == n)
  204458. {
  204459. deviceId = i;
  204460. break;
  204461. }
  204462. ++n;
  204463. }
  204464. }
  204465. for (i = handles.size(); --i >= 0;)
  204466. {
  204467. MidiOutHandle* const han = (MidiOutHandle*) handles.getUnchecked(i);
  204468. if (han != 0 && han->deviceId == deviceId)
  204469. {
  204470. han->refCount++;
  204471. MidiOutput* const out = new MidiOutput();
  204472. out->internal = (void*) han;
  204473. return out;
  204474. }
  204475. }
  204476. for (i = 4; --i >= 0;)
  204477. {
  204478. HMIDIOUT h = 0;
  204479. MMRESULT res = midiOutOpen (&h, deviceId, 0, 0, CALLBACK_NULL);
  204480. if (res == MMSYSERR_NOERROR)
  204481. {
  204482. MidiOutHandle* const han = new MidiOutHandle();
  204483. han->deviceId = deviceId;
  204484. han->refCount = 1;
  204485. han->handle = h;
  204486. handles.add (han);
  204487. MidiOutput* const out = new MidiOutput();
  204488. out->internal = (void*) han;
  204489. return out;
  204490. }
  204491. else if (res == MMSYSERR_ALLOCATED)
  204492. {
  204493. Sleep (100);
  204494. }
  204495. else
  204496. {
  204497. break;
  204498. }
  204499. }
  204500. return 0;
  204501. }
  204502. MidiOutput::~MidiOutput()
  204503. {
  204504. MidiOutHandle* const h = (MidiOutHandle*) internal;
  204505. if (handles.contains ((void*) h) && --(h->refCount) == 0)
  204506. {
  204507. midiOutClose (h->handle);
  204508. handles.removeValue ((void*) h);
  204509. delete h;
  204510. }
  204511. }
  204512. void MidiOutput::reset()
  204513. {
  204514. const MidiOutHandle* const h = (MidiOutHandle*) internal;
  204515. midiOutReset (h->handle);
  204516. }
  204517. bool MidiOutput::getVolume (float& leftVol,
  204518. float& rightVol)
  204519. {
  204520. const MidiOutHandle* const handle = (const MidiOutHandle*) internal;
  204521. DWORD n;
  204522. if (midiOutGetVolume (handle->handle, &n) == MMSYSERR_NOERROR)
  204523. {
  204524. const unsigned short* const nn = (const unsigned short*) &n;
  204525. rightVol = nn[0] / (float) 0xffff;
  204526. leftVol = nn[1] / (float) 0xffff;
  204527. return true;
  204528. }
  204529. else
  204530. {
  204531. rightVol = leftVol = 1.0f;
  204532. return false;
  204533. }
  204534. }
  204535. void MidiOutput::setVolume (float leftVol,
  204536. float rightVol)
  204537. {
  204538. const MidiOutHandle* const handle = (MidiOutHandle*) internal;
  204539. DWORD n;
  204540. unsigned short* const nn = (unsigned short*) &n;
  204541. nn[0] = (unsigned short) jlimit (0, 0xffff, (int)(rightVol * 0xffff));
  204542. nn[1] = (unsigned short) jlimit (0, 0xffff, (int)(leftVol * 0xffff));
  204543. midiOutSetVolume (handle->handle, n);
  204544. }
  204545. void MidiOutput::sendMessageNow (const MidiMessage& message)
  204546. {
  204547. const MidiOutHandle* const handle = (const MidiOutHandle*) internal;
  204548. if (message.getRawDataSize() > 3
  204549. || message.isSysEx())
  204550. {
  204551. MIDIHDR h;
  204552. zerostruct (h);
  204553. h.lpData = (char*) message.getRawData();
  204554. h.dwBufferLength = message.getRawDataSize();
  204555. h.dwBytesRecorded = message.getRawDataSize();
  204556. if (midiOutPrepareHeader (handle->handle, &h, sizeof (MIDIHDR)) == MMSYSERR_NOERROR)
  204557. {
  204558. MMRESULT res = midiOutLongMsg (handle->handle, &h, sizeof (MIDIHDR));
  204559. if (res == MMSYSERR_NOERROR)
  204560. {
  204561. while ((h.dwFlags & MHDR_DONE) == 0)
  204562. Sleep (1);
  204563. int count = 500; // 1 sec timeout
  204564. while (--count >= 0)
  204565. {
  204566. res = midiOutUnprepareHeader (handle->handle, &h, sizeof (MIDIHDR));
  204567. if (res == MIDIERR_STILLPLAYING)
  204568. Sleep (2);
  204569. else
  204570. break;
  204571. }
  204572. }
  204573. }
  204574. }
  204575. else
  204576. {
  204577. midiOutShortMsg (handle->handle,
  204578. *(unsigned int*) message.getRawData());
  204579. }
  204580. }
  204581. END_JUCE_NAMESPACE
  204582. /********* End of inlined file: juce_win32_Midi.cpp *********/
  204583. /********* Start of inlined file: juce_win32_WebBrowserComponent.cpp *********/
  204584. #ifdef _MSC_VER
  204585. #pragma warning (disable: 4514)
  204586. #pragma warning (push)
  204587. #endif
  204588. #include <comutil.h>
  204589. #include <Exdisp.h>
  204590. #include <exdispid.h>
  204591. #ifdef _MSC_VER
  204592. #pragma warning (pop)
  204593. #pragma warning (disable: 4312 4244)
  204594. #endif
  204595. BEGIN_JUCE_NAMESPACE
  204596. class WebBrowserComponentInternal : public ActiveXControlComponent
  204597. {
  204598. public:
  204599. WebBrowserComponentInternal()
  204600. : browser (0),
  204601. connectionPoint (0),
  204602. adviseCookie (0)
  204603. {
  204604. }
  204605. ~WebBrowserComponentInternal()
  204606. {
  204607. if (connectionPoint != 0)
  204608. connectionPoint->Unadvise (adviseCookie);
  204609. if (browser != 0)
  204610. browser->Release();
  204611. }
  204612. void createBrowser()
  204613. {
  204614. createControl (&CLSID_WebBrowser);
  204615. browser = (IWebBrowser2*) queryInterface (&IID_IWebBrowser2);
  204616. IConnectionPointContainer* connectionPointContainer = (IConnectionPointContainer*) queryInterface (&IID_IConnectionPointContainer);
  204617. if (connectionPointContainer != 0)
  204618. {
  204619. connectionPointContainer->FindConnectionPoint (DIID_DWebBrowserEvents2,
  204620. &connectionPoint);
  204621. if (connectionPoint != 0)
  204622. {
  204623. WebBrowserComponent* const owner = dynamic_cast <WebBrowserComponent*> (getParentComponent());
  204624. jassert (owner != 0);
  204625. EventHandler* handler = new EventHandler (owner);
  204626. connectionPoint->Advise (handler, &adviseCookie);
  204627. }
  204628. }
  204629. }
  204630. void goToURL (const String& url,
  204631. const StringArray* headers,
  204632. const MemoryBlock* postData)
  204633. {
  204634. if (browser != 0)
  204635. {
  204636. LPSAFEARRAY sa = 0;
  204637. _variant_t flags, frame, postDataVar, headersVar;
  204638. if (headers != 0)
  204639. headersVar = (const tchar*) headers->joinIntoString ("\r\n");
  204640. if (postData != 0 && postData->getSize() > 0)
  204641. {
  204642. LPSAFEARRAY sa = SafeArrayCreateVector (VT_UI1, 0, postData->getSize());
  204643. if (sa != 0)
  204644. {
  204645. void* data = 0;
  204646. SafeArrayAccessData (sa, &data);
  204647. jassert (data != 0);
  204648. if (data != 0)
  204649. {
  204650. postData->copyTo (data, 0, postData->getSize());
  204651. SafeArrayUnaccessData (sa);
  204652. VARIANT postDataVar2;
  204653. VariantInit (&postDataVar2);
  204654. V_VT (&postDataVar2) = VT_ARRAY | VT_UI1;
  204655. V_ARRAY (&postDataVar2) = sa;
  204656. postDataVar = postDataVar2;
  204657. }
  204658. }
  204659. }
  204660. browser->Navigate ((BSTR) (const OLECHAR*) url,
  204661. &flags, &frame,
  204662. &postDataVar, &headersVar);
  204663. if (sa != 0)
  204664. SafeArrayDestroy (sa);
  204665. }
  204666. }
  204667. IWebBrowser2* browser;
  204668. juce_UseDebuggingNewOperator
  204669. private:
  204670. IConnectionPoint* connectionPoint;
  204671. DWORD adviseCookie;
  204672. class EventHandler : public IDispatch
  204673. {
  204674. public:
  204675. EventHandler (WebBrowserComponent* owner_)
  204676. : owner (owner_),
  204677. refCount (0)
  204678. {
  204679. }
  204680. ~EventHandler()
  204681. {
  204682. }
  204683. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  204684. {
  204685. if (id == IID_IUnknown || id == IID_IDispatch || id == DIID_DWebBrowserEvents2)
  204686. {
  204687. AddRef();
  204688. *result = this;
  204689. return S_OK;
  204690. }
  204691. *result = 0;
  204692. return E_NOINTERFACE;
  204693. }
  204694. ULONG __stdcall AddRef() { return ++refCount; }
  204695. ULONG __stdcall Release() { jassert (refCount > 0); const int r = --refCount; if (r == 0) delete this; return r; }
  204696. HRESULT __stdcall GetTypeInfoCount (UINT __RPC_FAR*) { return E_NOTIMPL; }
  204697. HRESULT __stdcall GetTypeInfo (UINT, LCID, ITypeInfo __RPC_FAR *__RPC_FAR*) { return E_NOTIMPL; }
  204698. HRESULT __stdcall GetIDsOfNames (REFIID, LPOLESTR __RPC_FAR*, UINT, LCID, DISPID __RPC_FAR*) { return E_NOTIMPL; }
  204699. HRESULT __stdcall Invoke (DISPID dispIdMember, REFIID /*riid*/, LCID /*lcid*/,
  204700. WORD /*wFlags*/, DISPPARAMS __RPC_FAR* pDispParams,
  204701. VARIANT __RPC_FAR* /*pVarResult*/, EXCEPINFO __RPC_FAR* /*pExcepInfo*/,
  204702. UINT __RPC_FAR* /*puArgErr*/)
  204703. {
  204704. switch (dispIdMember)
  204705. {
  204706. case DISPID_BEFORENAVIGATE2:
  204707. {
  204708. VARIANT* const vurl = pDispParams->rgvarg[5].pvarVal;
  204709. String url;
  204710. if ((vurl->vt & VT_BYREF) != 0)
  204711. url = *vurl->pbstrVal;
  204712. else
  204713. url = vurl->bstrVal;
  204714. *pDispParams->rgvarg->pboolVal
  204715. = owner->pageAboutToLoad (url) ? VARIANT_FALSE
  204716. : VARIANT_TRUE;
  204717. return S_OK;
  204718. }
  204719. default:
  204720. break;
  204721. }
  204722. return E_NOTIMPL;
  204723. }
  204724. juce_UseDebuggingNewOperator
  204725. private:
  204726. WebBrowserComponent* const owner;
  204727. int refCount;
  204728. EventHandler (const EventHandler&);
  204729. const EventHandler& operator= (const EventHandler&);
  204730. };
  204731. };
  204732. WebBrowserComponent::WebBrowserComponent()
  204733. : browser (0),
  204734. blankPageShown (false)
  204735. {
  204736. setOpaque (true);
  204737. addAndMakeVisible (browser = new WebBrowserComponentInternal());
  204738. }
  204739. WebBrowserComponent::~WebBrowserComponent()
  204740. {
  204741. delete browser;
  204742. }
  204743. void WebBrowserComponent::goToURL (const String& url,
  204744. const StringArray* headers,
  204745. const MemoryBlock* postData)
  204746. {
  204747. lastURL = url;
  204748. lastHeaders.clear();
  204749. if (headers != 0)
  204750. lastHeaders = *headers;
  204751. lastPostData.setSize (0);
  204752. if (postData != 0)
  204753. lastPostData = *postData;
  204754. blankPageShown = false;
  204755. browser->goToURL (url, headers, postData);
  204756. }
  204757. void WebBrowserComponent::stop()
  204758. {
  204759. if (browser->browser != 0)
  204760. browser->browser->Stop();
  204761. }
  204762. void WebBrowserComponent::goBack()
  204763. {
  204764. lastURL = String::empty;
  204765. blankPageShown = false;
  204766. if (browser->browser != 0)
  204767. browser->browser->GoBack();
  204768. }
  204769. void WebBrowserComponent::goForward()
  204770. {
  204771. lastURL = String::empty;
  204772. if (browser->browser != 0)
  204773. browser->browser->GoForward();
  204774. }
  204775. void WebBrowserComponent::paint (Graphics& g)
  204776. {
  204777. if (browser->browser == 0)
  204778. g.fillAll (Colours::white);
  204779. }
  204780. void WebBrowserComponent::checkWindowAssociation()
  204781. {
  204782. if (isShowing())
  204783. {
  204784. if (blankPageShown)
  204785. goBack();
  204786. if (browser->browser == 0 && getPeer() != 0)
  204787. {
  204788. browser->createBrowser();
  204789. reloadLastURL();
  204790. }
  204791. }
  204792. else
  204793. {
  204794. if (browser != 0 && ! blankPageShown)
  204795. {
  204796. // when the component becomes invisible, some stuff like flash
  204797. // carries on playing audio, so we need to force it onto a blank
  204798. // page to avoid this..
  204799. blankPageShown = true;
  204800. browser->goToURL ("about:blank", 0, 0);
  204801. }
  204802. }
  204803. }
  204804. void WebBrowserComponent::reloadLastURL()
  204805. {
  204806. if (lastURL.isNotEmpty())
  204807. {
  204808. goToURL (lastURL, &lastHeaders, &lastPostData);
  204809. lastURL = String::empty;
  204810. }
  204811. }
  204812. void WebBrowserComponent::parentHierarchyChanged()
  204813. {
  204814. checkWindowAssociation();
  204815. }
  204816. void WebBrowserComponent::moved()
  204817. {
  204818. }
  204819. void WebBrowserComponent::resized()
  204820. {
  204821. browser->setSize (getWidth(), getHeight());
  204822. }
  204823. void WebBrowserComponent::visibilityChanged()
  204824. {
  204825. checkWindowAssociation();
  204826. }
  204827. bool WebBrowserComponent::pageAboutToLoad (const String&)
  204828. {
  204829. return true;
  204830. }
  204831. END_JUCE_NAMESPACE
  204832. /********* End of inlined file: juce_win32_WebBrowserComponent.cpp *********/
  204833. /********* Start of inlined file: juce_win32_Windowing.cpp *********/
  204834. #ifdef _MSC_VER
  204835. #pragma warning (disable: 4514)
  204836. #pragma warning (push)
  204837. #endif
  204838. #include <float.h>
  204839. #include <windowsx.h>
  204840. #include <shlobj.h>
  204841. #if JUCE_OPENGL
  204842. #include <gl/gl.h>
  204843. #endif
  204844. #ifdef _MSC_VER
  204845. #pragma warning (pop)
  204846. #pragma warning (disable: 4312 4244)
  204847. #endif
  204848. #undef GetSystemMetrics // multimon overrides this for some reason and causes a mess..
  204849. // these are in the windows SDK, but need to be repeated here for GCC..
  204850. #ifndef GET_APPCOMMAND_LPARAM
  204851. #define FAPPCOMMAND_MASK 0xF000
  204852. #define GET_APPCOMMAND_LPARAM(lParam) ((short) (HIWORD (lParam) & ~FAPPCOMMAND_MASK))
  204853. #define APPCOMMAND_MEDIA_NEXTTRACK 11
  204854. #define APPCOMMAND_MEDIA_PREVIOUSTRACK 12
  204855. #define APPCOMMAND_MEDIA_STOP 13
  204856. #define APPCOMMAND_MEDIA_PLAY_PAUSE 14
  204857. #define WM_APPCOMMAND 0x0319
  204858. #endif
  204859. BEGIN_JUCE_NAMESPACE
  204860. extern void juce_repeatLastProcessPriority() throw(); // in juce_win32_Threads.cpp
  204861. extern void juce_CheckCurrentlyFocusedTopLevelWindow() throw(); // in juce_TopLevelWindow.cpp
  204862. extern bool juce_IsRunningInWine() throw();
  204863. #ifndef ULW_ALPHA
  204864. #define ULW_ALPHA 0x00000002
  204865. #endif
  204866. #ifndef AC_SRC_ALPHA
  204867. #define AC_SRC_ALPHA 0x01
  204868. #endif
  204869. #define DEBUG_REPAINT_TIMES 0
  204870. static HPALETTE palette = 0;
  204871. static bool createPaletteIfNeeded = true;
  204872. static bool shouldDeactivateTitleBar = true;
  204873. static bool screenSaverAllowed = true;
  204874. static HICON createHICONFromImage (const Image& image, const BOOL isIcon, int hotspotX, int hotspotY) throw();
  204875. #define WM_TRAYNOTIFY WM_USER + 100
  204876. using ::abs;
  204877. typedef BOOL (WINAPI* UpdateLayeredWinFunc) (HWND, HDC, POINT*, SIZE*, HDC, POINT*, COLORREF, BLENDFUNCTION*, DWORD);
  204878. static UpdateLayeredWinFunc updateLayeredWindow = 0;
  204879. bool Desktop::canUseSemiTransparentWindows() throw()
  204880. {
  204881. if (updateLayeredWindow == 0)
  204882. {
  204883. if (! juce_IsRunningInWine())
  204884. {
  204885. HMODULE user32Mod = GetModuleHandle (_T("user32.dll"));
  204886. updateLayeredWindow = (UpdateLayeredWinFunc) GetProcAddress (user32Mod, "UpdateLayeredWindow");
  204887. }
  204888. }
  204889. return updateLayeredWindow != 0;
  204890. }
  204891. #undef DefWindowProc
  204892. #define DefWindowProc DefWindowProcW
  204893. const int extendedKeyModifier = 0x10000;
  204894. const int KeyPress::spaceKey = VK_SPACE;
  204895. const int KeyPress::returnKey = VK_RETURN;
  204896. const int KeyPress::escapeKey = VK_ESCAPE;
  204897. const int KeyPress::backspaceKey = VK_BACK;
  204898. const int KeyPress::deleteKey = VK_DELETE | extendedKeyModifier;
  204899. const int KeyPress::insertKey = VK_INSERT | extendedKeyModifier;
  204900. const int KeyPress::tabKey = VK_TAB;
  204901. const int KeyPress::leftKey = VK_LEFT | extendedKeyModifier;
  204902. const int KeyPress::rightKey = VK_RIGHT | extendedKeyModifier;
  204903. const int KeyPress::upKey = VK_UP | extendedKeyModifier;
  204904. const int KeyPress::downKey = VK_DOWN | extendedKeyModifier;
  204905. const int KeyPress::homeKey = VK_HOME | extendedKeyModifier;
  204906. const int KeyPress::endKey = VK_END | extendedKeyModifier;
  204907. const int KeyPress::pageUpKey = VK_PRIOR | extendedKeyModifier;
  204908. const int KeyPress::pageDownKey = VK_NEXT | extendedKeyModifier;
  204909. const int KeyPress::F1Key = VK_F1 | extendedKeyModifier;
  204910. const int KeyPress::F2Key = VK_F2 | extendedKeyModifier;
  204911. const int KeyPress::F3Key = VK_F3 | extendedKeyModifier;
  204912. const int KeyPress::F4Key = VK_F4 | extendedKeyModifier;
  204913. const int KeyPress::F5Key = VK_F5 | extendedKeyModifier;
  204914. const int KeyPress::F6Key = VK_F6 | extendedKeyModifier;
  204915. const int KeyPress::F7Key = VK_F7 | extendedKeyModifier;
  204916. const int KeyPress::F8Key = VK_F8 | extendedKeyModifier;
  204917. const int KeyPress::F9Key = VK_F9 | extendedKeyModifier;
  204918. const int KeyPress::F10Key = VK_F10 | extendedKeyModifier;
  204919. const int KeyPress::F11Key = VK_F11 | extendedKeyModifier;
  204920. const int KeyPress::F12Key = VK_F12 | extendedKeyModifier;
  204921. const int KeyPress::F13Key = VK_F13 | extendedKeyModifier;
  204922. const int KeyPress::F14Key = VK_F14 | extendedKeyModifier;
  204923. const int KeyPress::F15Key = VK_F15 | extendedKeyModifier;
  204924. const int KeyPress::F16Key = VK_F16 | extendedKeyModifier;
  204925. const int KeyPress::numberPad0 = VK_NUMPAD0 | extendedKeyModifier;
  204926. const int KeyPress::numberPad1 = VK_NUMPAD1 | extendedKeyModifier;
  204927. const int KeyPress::numberPad2 = VK_NUMPAD2 | extendedKeyModifier;
  204928. const int KeyPress::numberPad3 = VK_NUMPAD3 | extendedKeyModifier;
  204929. const int KeyPress::numberPad4 = VK_NUMPAD4 | extendedKeyModifier;
  204930. const int KeyPress::numberPad5 = VK_NUMPAD5 | extendedKeyModifier;
  204931. const int KeyPress::numberPad6 = VK_NUMPAD6 | extendedKeyModifier;
  204932. const int KeyPress::numberPad7 = VK_NUMPAD7 | extendedKeyModifier;
  204933. const int KeyPress::numberPad8 = VK_NUMPAD8 | extendedKeyModifier;
  204934. const int KeyPress::numberPad9 = VK_NUMPAD9 | extendedKeyModifier;
  204935. const int KeyPress::numberPadAdd = VK_ADD | extendedKeyModifier;
  204936. const int KeyPress::numberPadSubtract = VK_SUBTRACT | extendedKeyModifier;
  204937. const int KeyPress::numberPadMultiply = VK_MULTIPLY | extendedKeyModifier;
  204938. const int KeyPress::numberPadDivide = VK_DIVIDE | extendedKeyModifier;
  204939. const int KeyPress::numberPadSeparator = VK_SEPARATOR | extendedKeyModifier;
  204940. const int KeyPress::numberPadDecimalPoint = VK_DECIMAL | extendedKeyModifier;
  204941. const int KeyPress::numberPadEquals = 0x92 /*VK_OEM_NEC_EQUAL*/ | extendedKeyModifier;
  204942. const int KeyPress::numberPadDelete = VK_DELETE | extendedKeyModifier;
  204943. const int KeyPress::playKey = 0x30000;
  204944. const int KeyPress::stopKey = 0x30001;
  204945. const int KeyPress::fastForwardKey = 0x30002;
  204946. const int KeyPress::rewindKey = 0x30003;
  204947. class WindowsBitmapImage : public Image
  204948. {
  204949. public:
  204950. HBITMAP hBitmap;
  204951. BITMAPV4HEADER bitmapInfo;
  204952. HDC hdc;
  204953. unsigned char* bitmapData;
  204954. WindowsBitmapImage (const PixelFormat format_,
  204955. const int w, const int h, const bool clearImage)
  204956. : Image (format_, w, h)
  204957. {
  204958. jassert (format_ == RGB || format_ == ARGB);
  204959. pixelStride = (format_ == RGB) ? 3 : 4;
  204960. zerostruct (bitmapInfo);
  204961. bitmapInfo.bV4Size = sizeof (BITMAPV4HEADER);
  204962. bitmapInfo.bV4Width = w;
  204963. bitmapInfo.bV4Height = h;
  204964. bitmapInfo.bV4Planes = 1;
  204965. bitmapInfo.bV4BitCount = (unsigned short) (pixelStride * 8);
  204966. if (format_ == ARGB)
  204967. {
  204968. bitmapInfo.bV4AlphaMask = 0xff000000;
  204969. bitmapInfo.bV4RedMask = 0xff0000;
  204970. bitmapInfo.bV4GreenMask = 0xff00;
  204971. bitmapInfo.bV4BlueMask = 0xff;
  204972. bitmapInfo.bV4V4Compression = BI_BITFIELDS;
  204973. }
  204974. else
  204975. {
  204976. bitmapInfo.bV4V4Compression = BI_RGB;
  204977. }
  204978. lineStride = -((w * pixelStride + 3) & ~3);
  204979. HDC dc = GetDC (0);
  204980. hdc = CreateCompatibleDC (dc);
  204981. ReleaseDC (0, dc);
  204982. SetMapMode (hdc, MM_TEXT);
  204983. hBitmap = CreateDIBSection (hdc,
  204984. (BITMAPINFO*) &(bitmapInfo),
  204985. DIB_RGB_COLORS,
  204986. (void**) &bitmapData,
  204987. 0, 0);
  204988. SelectObject (hdc, hBitmap);
  204989. if (format_ == ARGB && clearImage)
  204990. zeromem (bitmapData, abs (h * lineStride));
  204991. imageData = bitmapData - (lineStride * (h - 1));
  204992. }
  204993. ~WindowsBitmapImage()
  204994. {
  204995. DeleteDC (hdc);
  204996. DeleteObject (hBitmap);
  204997. imageData = 0; // to stop the base class freeing this
  204998. }
  204999. void blitToWindow (HWND hwnd, HDC dc, const bool transparent,
  205000. const int x, const int y,
  205001. const RectangleList& maskedRegion) throw()
  205002. {
  205003. static HDRAWDIB hdd = 0;
  205004. static bool needToCreateDrawDib = true;
  205005. if (needToCreateDrawDib)
  205006. {
  205007. needToCreateDrawDib = false;
  205008. HDC dc = GetDC (0);
  205009. const int n = GetDeviceCaps (dc, BITSPIXEL);
  205010. ReleaseDC (0, dc);
  205011. // only open if we're not palettised
  205012. if (n > 8)
  205013. hdd = DrawDibOpen();
  205014. }
  205015. if (createPaletteIfNeeded)
  205016. {
  205017. HDC dc = GetDC (0);
  205018. const int n = GetDeviceCaps (dc, BITSPIXEL);
  205019. ReleaseDC (0, dc);
  205020. if (n <= 8)
  205021. palette = CreateHalftonePalette (dc);
  205022. createPaletteIfNeeded = false;
  205023. }
  205024. if (palette != 0)
  205025. {
  205026. SelectPalette (dc, palette, FALSE);
  205027. RealizePalette (dc);
  205028. SetStretchBltMode (dc, HALFTONE);
  205029. }
  205030. SetMapMode (dc, MM_TEXT);
  205031. if (transparent)
  205032. {
  205033. POINT p, pos;
  205034. SIZE size;
  205035. RECT windowBounds;
  205036. GetWindowRect (hwnd, &windowBounds);
  205037. p.x = -x;
  205038. p.y = -y;
  205039. pos.x = windowBounds.left;
  205040. pos.y = windowBounds.top;
  205041. size.cx = windowBounds.right - windowBounds.left;
  205042. size.cy = windowBounds.bottom - windowBounds.top;
  205043. BLENDFUNCTION bf;
  205044. bf.AlphaFormat = AC_SRC_ALPHA;
  205045. bf.BlendFlags = 0;
  205046. bf.BlendOp = AC_SRC_OVER;
  205047. bf.SourceConstantAlpha = 0xff;
  205048. if (! maskedRegion.isEmpty())
  205049. {
  205050. for (RectangleList::Iterator i (maskedRegion); i.next();)
  205051. {
  205052. const Rectangle& r = *i.getRectangle();
  205053. ExcludeClipRect (hdc, r.getX(), r.getY(), r.getRight(), r.getBottom());
  205054. }
  205055. }
  205056. updateLayeredWindow (hwnd, 0, &pos, &size, hdc, &p, 0, &bf, ULW_ALPHA);
  205057. }
  205058. else
  205059. {
  205060. int savedDC = 0;
  205061. if (! maskedRegion.isEmpty())
  205062. {
  205063. savedDC = SaveDC (dc);
  205064. for (RectangleList::Iterator i (maskedRegion); i.next();)
  205065. {
  205066. const Rectangle& r = *i.getRectangle();
  205067. ExcludeClipRect (dc, r.getX(), r.getY(), r.getRight(), r.getBottom());
  205068. }
  205069. }
  205070. const int w = getWidth();
  205071. const int h = getHeight();
  205072. if (hdd == 0)
  205073. {
  205074. StretchDIBits (dc,
  205075. x, y, w, h,
  205076. 0, 0, w, h,
  205077. bitmapData, (const BITMAPINFO*) &bitmapInfo,
  205078. DIB_RGB_COLORS, SRCCOPY);
  205079. }
  205080. else
  205081. {
  205082. DrawDibDraw (hdd, dc, x, y, -1, -1,
  205083. (BITMAPINFOHEADER*) &bitmapInfo, bitmapData,
  205084. 0, 0, w, h, 0);
  205085. }
  205086. if (! maskedRegion.isEmpty())
  205087. RestoreDC (dc, savedDC);
  205088. }
  205089. }
  205090. juce_UseDebuggingNewOperator
  205091. private:
  205092. WindowsBitmapImage (const WindowsBitmapImage&);
  205093. const WindowsBitmapImage& operator= (const WindowsBitmapImage&);
  205094. };
  205095. long improbableWindowNumber = 0xf965aa01; // also referenced by messaging.cpp
  205096. static int currentModifiers = 0;
  205097. static int modifiersAtLastCallback = 0;
  205098. static void updateKeyModifiers() throw()
  205099. {
  205100. currentModifiers &= ~(ModifierKeys::shiftModifier
  205101. | ModifierKeys::ctrlModifier
  205102. | ModifierKeys::altModifier);
  205103. if ((GetKeyState (VK_SHIFT) & 0x8000) != 0)
  205104. currentModifiers |= ModifierKeys::shiftModifier;
  205105. if ((GetKeyState (VK_CONTROL) & 0x8000) != 0)
  205106. currentModifiers |= ModifierKeys::ctrlModifier;
  205107. if ((GetKeyState (VK_MENU) & 0x8000) != 0)
  205108. currentModifiers |= ModifierKeys::altModifier;
  205109. if ((GetKeyState (VK_RMENU) & 0x8000) != 0)
  205110. currentModifiers &= ~(ModifierKeys::ctrlModifier | ModifierKeys::altModifier);
  205111. }
  205112. void ModifierKeys::updateCurrentModifiers() throw()
  205113. {
  205114. currentModifierFlags = currentModifiers;
  205115. }
  205116. bool KeyPress::isKeyCurrentlyDown (const int keyCode) throw()
  205117. {
  205118. SHORT k = (SHORT) keyCode;
  205119. if ((keyCode & extendedKeyModifier) == 0
  205120. && (k >= (SHORT) T('a') && k <= (SHORT) T('z')))
  205121. k += (SHORT) T('A') - (SHORT) T('a');
  205122. const SHORT translatedValues[] = { (SHORT) ',', VK_OEM_COMMA,
  205123. (SHORT) '+', VK_OEM_PLUS,
  205124. (SHORT) '-', VK_OEM_MINUS,
  205125. (SHORT) '.', VK_OEM_PERIOD,
  205126. (SHORT) ';', VK_OEM_1,
  205127. (SHORT) ':', VK_OEM_1,
  205128. (SHORT) '/', VK_OEM_2,
  205129. (SHORT) '?', VK_OEM_2,
  205130. (SHORT) '[', VK_OEM_4,
  205131. (SHORT) ']', VK_OEM_6 };
  205132. for (int i = 0; i < numElementsInArray (translatedValues); i += 2)
  205133. if (k == translatedValues [i])
  205134. k = translatedValues [i + 1];
  205135. return (GetKeyState (k) & 0x8000) != 0;
  205136. }
  205137. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  205138. {
  205139. updateKeyModifiers();
  205140. currentModifiers &= ~ModifierKeys::allMouseButtonModifiers;
  205141. if ((GetKeyState (VK_LBUTTON) & 0x8000) != 0)
  205142. currentModifiers |= ModifierKeys::leftButtonModifier;
  205143. if ((GetKeyState (VK_RBUTTON) & 0x8000) != 0)
  205144. currentModifiers |= ModifierKeys::rightButtonModifier;
  205145. if ((GetKeyState (VK_MBUTTON) & 0x8000) != 0)
  205146. currentModifiers |= ModifierKeys::middleButtonModifier;
  205147. return ModifierKeys (currentModifiers);
  205148. }
  205149. static int64 getMouseEventTime() throw()
  205150. {
  205151. static int64 eventTimeOffset = 0;
  205152. static DWORD lastMessageTime = 0;
  205153. const DWORD thisMessageTime = GetMessageTime();
  205154. if (thisMessageTime < lastMessageTime || lastMessageTime == 0)
  205155. {
  205156. lastMessageTime = thisMessageTime;
  205157. eventTimeOffset = Time::currentTimeMillis() - thisMessageTime;
  205158. }
  205159. return eventTimeOffset + thisMessageTime;
  205160. }
  205161. class Win32ComponentPeer : public ComponentPeer
  205162. {
  205163. public:
  205164. Win32ComponentPeer (Component* const component,
  205165. const int windowStyleFlags)
  205166. : ComponentPeer (component, windowStyleFlags),
  205167. dontRepaint (false),
  205168. fullScreen (false),
  205169. isDragging (false),
  205170. isMouseOver (false),
  205171. currentWindowIcon (0),
  205172. taskBarIcon (0),
  205173. dropTarget (0)
  205174. {
  205175. MessageManager::getInstance()
  205176. ->callFunctionOnMessageThread (&createWindowCallback, (void*) this);
  205177. setTitle (component->getName());
  205178. if ((windowStyleFlags & windowHasDropShadow) != 0
  205179. && Desktop::canUseSemiTransparentWindows())
  205180. {
  205181. shadower = component->getLookAndFeel().createDropShadowerForComponent (component);
  205182. if (shadower != 0)
  205183. shadower->setOwner (component);
  205184. }
  205185. else
  205186. {
  205187. shadower = 0;
  205188. }
  205189. }
  205190. ~Win32ComponentPeer()
  205191. {
  205192. setTaskBarIcon (0);
  205193. deleteAndZero (shadower);
  205194. // do this before the next bit to avoid messages arriving for this window
  205195. // before it's destroyed
  205196. SetWindowLongPtr (hwnd, GWLP_USERDATA, 0);
  205197. MessageManager::getInstance()
  205198. ->callFunctionOnMessageThread (&destroyWindowCallback, (void*) hwnd);
  205199. if (currentWindowIcon != 0)
  205200. DestroyIcon (currentWindowIcon);
  205201. if (dropTarget != 0)
  205202. {
  205203. dropTarget->Release();
  205204. dropTarget = 0;
  205205. }
  205206. }
  205207. void* getNativeHandle() const
  205208. {
  205209. return (void*) hwnd;
  205210. }
  205211. void setVisible (bool shouldBeVisible)
  205212. {
  205213. ShowWindow (hwnd, shouldBeVisible ? SW_SHOWNA : SW_HIDE);
  205214. if (shouldBeVisible)
  205215. InvalidateRect (hwnd, 0, 0);
  205216. else
  205217. lastPaintTime = 0;
  205218. }
  205219. void setTitle (const String& title)
  205220. {
  205221. SetWindowText (hwnd, title);
  205222. }
  205223. void setPosition (int x, int y)
  205224. {
  205225. offsetWithinParent (x, y);
  205226. SetWindowPos (hwnd, 0,
  205227. x - windowBorder.getLeft(),
  205228. y - windowBorder.getTop(),
  205229. 0, 0,
  205230. SWP_NOACTIVATE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  205231. }
  205232. void repaintNowIfTransparent()
  205233. {
  205234. if (isTransparent() && lastPaintTime > 0 && Time::getMillisecondCounter() > lastPaintTime + 30)
  205235. handlePaintMessage();
  205236. }
  205237. void updateBorderSize()
  205238. {
  205239. WINDOWINFO info;
  205240. info.cbSize = sizeof (info);
  205241. if (GetWindowInfo (hwnd, &info))
  205242. {
  205243. windowBorder = BorderSize (info.rcClient.top - info.rcWindow.top,
  205244. info.rcClient.left - info.rcWindow.left,
  205245. info.rcWindow.bottom - info.rcClient.bottom,
  205246. info.rcWindow.right - info.rcClient.right);
  205247. }
  205248. }
  205249. void setSize (int w, int h)
  205250. {
  205251. SetWindowPos (hwnd, 0, 0, 0,
  205252. w + windowBorder.getLeftAndRight(),
  205253. h + windowBorder.getTopAndBottom(),
  205254. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  205255. updateBorderSize();
  205256. repaintNowIfTransparent();
  205257. }
  205258. void setBounds (int x, int y, int w, int h, const bool isNowFullScreen)
  205259. {
  205260. fullScreen = isNowFullScreen;
  205261. offsetWithinParent (x, y);
  205262. SetWindowPos (hwnd, 0,
  205263. x - windowBorder.getLeft(),
  205264. y - windowBorder.getTop(),
  205265. w + windowBorder.getLeftAndRight(),
  205266. h + windowBorder.getTopAndBottom(),
  205267. SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  205268. updateBorderSize();
  205269. repaintNowIfTransparent();
  205270. }
  205271. void getBounds (int& x, int& y, int& w, int& h) const
  205272. {
  205273. RECT r;
  205274. GetWindowRect (hwnd, &r);
  205275. x = r.left;
  205276. y = r.top;
  205277. w = r.right - x;
  205278. h = r.bottom - y;
  205279. HWND parentH = GetParent (hwnd);
  205280. if (parentH != 0)
  205281. {
  205282. GetWindowRect (parentH, &r);
  205283. x -= r.left;
  205284. y -= r.top;
  205285. }
  205286. x += windowBorder.getLeft();
  205287. y += windowBorder.getTop();
  205288. w -= windowBorder.getLeftAndRight();
  205289. h -= windowBorder.getTopAndBottom();
  205290. }
  205291. int getScreenX() const
  205292. {
  205293. RECT r;
  205294. GetWindowRect (hwnd, &r);
  205295. return r.left + windowBorder.getLeft();
  205296. }
  205297. int getScreenY() const
  205298. {
  205299. RECT r;
  205300. GetWindowRect (hwnd, &r);
  205301. return r.top + windowBorder.getTop();
  205302. }
  205303. void relativePositionToGlobal (int& x, int& y)
  205304. {
  205305. RECT r;
  205306. GetWindowRect (hwnd, &r);
  205307. x += r.left + windowBorder.getLeft();
  205308. y += r.top + windowBorder.getTop();
  205309. }
  205310. void globalPositionToRelative (int& x, int& y)
  205311. {
  205312. RECT r;
  205313. GetWindowRect (hwnd, &r);
  205314. x -= r.left + windowBorder.getLeft();
  205315. y -= r.top + windowBorder.getTop();
  205316. }
  205317. void setMinimised (bool shouldBeMinimised)
  205318. {
  205319. if (shouldBeMinimised != isMinimised())
  205320. ShowWindow (hwnd, shouldBeMinimised ? SW_MINIMIZE : SW_SHOWNORMAL);
  205321. }
  205322. bool isMinimised() const
  205323. {
  205324. WINDOWPLACEMENT wp;
  205325. wp.length = sizeof (WINDOWPLACEMENT);
  205326. GetWindowPlacement (hwnd, &wp);
  205327. return wp.showCmd == SW_SHOWMINIMIZED;
  205328. }
  205329. void setFullScreen (bool shouldBeFullScreen)
  205330. {
  205331. setMinimised (false);
  205332. if (fullScreen != shouldBeFullScreen)
  205333. {
  205334. fullScreen = shouldBeFullScreen;
  205335. const ComponentDeletionWatcher deletionChecker (component);
  205336. if (! fullScreen)
  205337. {
  205338. const Rectangle boundsCopy (lastNonFullscreenBounds);
  205339. if (hasTitleBar())
  205340. ShowWindow (hwnd, SW_SHOWNORMAL);
  205341. if (! boundsCopy.isEmpty())
  205342. {
  205343. setBounds (boundsCopy.getX(),
  205344. boundsCopy.getY(),
  205345. boundsCopy.getWidth(),
  205346. boundsCopy.getHeight(),
  205347. false);
  205348. }
  205349. }
  205350. else
  205351. {
  205352. if (hasTitleBar())
  205353. ShowWindow (hwnd, SW_SHOWMAXIMIZED);
  205354. else
  205355. SendMessageW (hwnd, WM_SETTINGCHANGE, 0, 0);
  205356. }
  205357. if (! deletionChecker.hasBeenDeleted())
  205358. handleMovedOrResized();
  205359. }
  205360. }
  205361. bool isFullScreen() const
  205362. {
  205363. if (! hasTitleBar())
  205364. return fullScreen;
  205365. WINDOWPLACEMENT wp;
  205366. wp.length = sizeof (wp);
  205367. GetWindowPlacement (hwnd, &wp);
  205368. return wp.showCmd == SW_SHOWMAXIMIZED;
  205369. }
  205370. bool contains (int x, int y, bool trueIfInAChildWindow) const
  205371. {
  205372. RECT r;
  205373. GetWindowRect (hwnd, &r);
  205374. POINT p;
  205375. p.x = x + r.left + windowBorder.getLeft();
  205376. p.y = y + r.top + windowBorder.getTop();
  205377. HWND w = WindowFromPoint (p);
  205378. return w == hwnd || (trueIfInAChildWindow && (IsChild (hwnd, w) != 0));
  205379. }
  205380. const BorderSize getFrameSize() const
  205381. {
  205382. return windowBorder;
  205383. }
  205384. bool setAlwaysOnTop (bool alwaysOnTop)
  205385. {
  205386. const bool oldDeactivate = shouldDeactivateTitleBar;
  205387. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  205388. SetWindowPos (hwnd, alwaysOnTop ? HWND_TOPMOST : HWND_NOTOPMOST,
  205389. 0, 0, 0, 0,
  205390. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  205391. shouldDeactivateTitleBar = oldDeactivate;
  205392. if (shadower != 0)
  205393. shadower->componentBroughtToFront (*component);
  205394. return true;
  205395. }
  205396. void toFront (bool makeActive)
  205397. {
  205398. setMinimised (false);
  205399. const bool oldDeactivate = shouldDeactivateTitleBar;
  205400. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  205401. MessageManager::getInstance()
  205402. ->callFunctionOnMessageThread (makeActive ? &toFrontCallback1
  205403. : &toFrontCallback2,
  205404. (void*) hwnd);
  205405. shouldDeactivateTitleBar = oldDeactivate;
  205406. if (! makeActive)
  205407. {
  205408. // in this case a broughttofront call won't have occured, so do it now..
  205409. handleBroughtToFront();
  205410. }
  205411. }
  205412. void toBehind (ComponentPeer* other)
  205413. {
  205414. Win32ComponentPeer* const otherPeer = dynamic_cast <Win32ComponentPeer*> (other);
  205415. jassert (otherPeer != 0); // wrong type of window?
  205416. if (otherPeer != 0)
  205417. {
  205418. setMinimised (false);
  205419. SetWindowPos (hwnd, otherPeer->hwnd, 0, 0, 0, 0,
  205420. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  205421. }
  205422. }
  205423. bool isFocused() const
  205424. {
  205425. return MessageManager::getInstance()
  205426. ->callFunctionOnMessageThread (&getFocusCallback, 0) == (void*) hwnd;
  205427. }
  205428. void grabFocus()
  205429. {
  205430. const bool oldDeactivate = shouldDeactivateTitleBar;
  205431. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  205432. MessageManager::getInstance()
  205433. ->callFunctionOnMessageThread (&setFocusCallback, (void*) hwnd);
  205434. shouldDeactivateTitleBar = oldDeactivate;
  205435. }
  205436. void repaint (int x, int y, int w, int h)
  205437. {
  205438. const RECT r = { x, y, x + w, y + h };
  205439. InvalidateRect (hwnd, &r, FALSE);
  205440. }
  205441. void performAnyPendingRepaintsNow()
  205442. {
  205443. MSG m;
  205444. if (component->isVisible() && PeekMessage (&m, hwnd, WM_PAINT, WM_PAINT, PM_REMOVE))
  205445. DispatchMessage (&m);
  205446. }
  205447. static Win32ComponentPeer* getOwnerOfWindow (HWND h) throw()
  205448. {
  205449. if (h != 0 && GetWindowLongPtr (h, GWLP_USERDATA) == improbableWindowNumber)
  205450. return (Win32ComponentPeer*) GetWindowLongPtr (h, 8);
  205451. return 0;
  205452. }
  205453. void setTaskBarIcon (const Image* const image)
  205454. {
  205455. if (image != 0)
  205456. {
  205457. HICON hicon = createHICONFromImage (*image, TRUE, 0, 0);
  205458. if (taskBarIcon == 0)
  205459. {
  205460. taskBarIcon = new NOTIFYICONDATA();
  205461. taskBarIcon->cbSize = sizeof (NOTIFYICONDATA);
  205462. taskBarIcon->hWnd = (HWND) hwnd;
  205463. taskBarIcon->uID = (int) (pointer_sized_int) hwnd;
  205464. taskBarIcon->uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP;
  205465. taskBarIcon->uCallbackMessage = WM_TRAYNOTIFY;
  205466. taskBarIcon->hIcon = hicon;
  205467. taskBarIcon->szTip[0] = 0;
  205468. Shell_NotifyIcon (NIM_ADD, taskBarIcon);
  205469. }
  205470. else
  205471. {
  205472. HICON oldIcon = taskBarIcon->hIcon;
  205473. taskBarIcon->hIcon = hicon;
  205474. taskBarIcon->uFlags = NIF_ICON;
  205475. Shell_NotifyIcon (NIM_MODIFY, taskBarIcon);
  205476. DestroyIcon (oldIcon);
  205477. }
  205478. DestroyIcon (hicon);
  205479. }
  205480. else if (taskBarIcon != 0)
  205481. {
  205482. taskBarIcon->uFlags = 0;
  205483. Shell_NotifyIcon (NIM_DELETE, taskBarIcon);
  205484. DestroyIcon (taskBarIcon->hIcon);
  205485. deleteAndZero (taskBarIcon);
  205486. }
  205487. }
  205488. void setTaskBarIconToolTip (const String& toolTip) const
  205489. {
  205490. if (taskBarIcon != 0)
  205491. {
  205492. taskBarIcon->uFlags = NIF_TIP;
  205493. toolTip.copyToBuffer (taskBarIcon->szTip, sizeof (taskBarIcon->szTip) - 1);
  205494. Shell_NotifyIcon (NIM_MODIFY, taskBarIcon);
  205495. }
  205496. }
  205497. juce_UseDebuggingNewOperator
  205498. bool dontRepaint;
  205499. private:
  205500. HWND hwnd;
  205501. DropShadower* shadower;
  205502. bool fullScreen, isDragging, isMouseOver;
  205503. BorderSize windowBorder;
  205504. HICON currentWindowIcon;
  205505. NOTIFYICONDATA* taskBarIcon;
  205506. IDropTarget* dropTarget;
  205507. class TemporaryImage : public Timer
  205508. {
  205509. public:
  205510. TemporaryImage()
  205511. : image (0)
  205512. {
  205513. }
  205514. ~TemporaryImage()
  205515. {
  205516. delete image;
  205517. }
  205518. WindowsBitmapImage* getImage (const bool transparent, const int w, const int h) throw()
  205519. {
  205520. const Image::PixelFormat format = transparent ? Image::ARGB : Image::RGB;
  205521. if (image == 0 || image->getWidth() < w || image->getHeight() < h || image->getFormat() != format)
  205522. {
  205523. delete image;
  205524. image = new WindowsBitmapImage (format, (w + 31) & ~31, (h + 31) & ~31, false);
  205525. }
  205526. startTimer (3000);
  205527. return image;
  205528. }
  205529. void timerCallback()
  205530. {
  205531. stopTimer();
  205532. deleteAndZero (image);
  205533. }
  205534. private:
  205535. WindowsBitmapImage* image;
  205536. TemporaryImage (const TemporaryImage&);
  205537. const TemporaryImage& operator= (const TemporaryImage&);
  205538. };
  205539. TemporaryImage offscreenImageGenerator;
  205540. class WindowClassHolder : public DeletedAtShutdown
  205541. {
  205542. public:
  205543. WindowClassHolder()
  205544. : windowClassName ("JUCE_")
  205545. {
  205546. // this name has to be different for each app/dll instance because otherwise
  205547. // poor old Win32 can get a bit confused (even despite it not being a process-global
  205548. // window class).
  205549. windowClassName << (int) (Time::currentTimeMillis() & 0x7fffffff);
  205550. HINSTANCE moduleHandle = (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle();
  205551. TCHAR moduleFile [1024];
  205552. moduleFile[0] = 0;
  205553. GetModuleFileName (moduleHandle, moduleFile, 1024);
  205554. WORD iconNum = 0;
  205555. WNDCLASSEX wcex;
  205556. wcex.cbSize = sizeof (wcex);
  205557. wcex.style = CS_OWNDC;
  205558. wcex.lpfnWndProc = (WNDPROC) windowProc;
  205559. wcex.lpszClassName = windowClassName;
  205560. wcex.cbClsExtra = 0;
  205561. wcex.cbWndExtra = 32;
  205562. wcex.hInstance = moduleHandle;
  205563. wcex.hIcon = ExtractAssociatedIcon (moduleHandle, moduleFile, &iconNum);
  205564. iconNum = 1;
  205565. wcex.hIconSm = ExtractAssociatedIcon (moduleHandle, moduleFile, &iconNum);
  205566. wcex.hCursor = 0;
  205567. wcex.hbrBackground = 0;
  205568. wcex.lpszMenuName = 0;
  205569. RegisterClassEx (&wcex);
  205570. }
  205571. ~WindowClassHolder()
  205572. {
  205573. if (ComponentPeer::getNumPeers() == 0)
  205574. UnregisterClass (windowClassName, (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle());
  205575. clearSingletonInstance();
  205576. }
  205577. String windowClassName;
  205578. juce_DeclareSingleton_SingleThreaded_Minimal (WindowClassHolder);
  205579. };
  205580. static void* createWindowCallback (void* userData)
  205581. {
  205582. ((Win32ComponentPeer*) userData)->createWindow();
  205583. return 0;
  205584. }
  205585. void createWindow()
  205586. {
  205587. DWORD exstyle = WS_EX_ACCEPTFILES;
  205588. DWORD type = WS_CLIPSIBLINGS | WS_CLIPCHILDREN;
  205589. if (hasTitleBar())
  205590. {
  205591. type |= WS_OVERLAPPED;
  205592. exstyle |= WS_EX_APPWINDOW;
  205593. if ((styleFlags & windowHasCloseButton) != 0)
  205594. {
  205595. type |= WS_SYSMENU;
  205596. }
  205597. else
  205598. {
  205599. // annoyingly, windows won't let you have a min/max button without a close button
  205600. jassert ((styleFlags & (windowHasMinimiseButton | windowHasMaximiseButton)) == 0);
  205601. }
  205602. if ((styleFlags & windowIsResizable) != 0)
  205603. type |= WS_THICKFRAME;
  205604. }
  205605. else
  205606. {
  205607. type |= WS_POPUP | WS_SYSMENU;
  205608. if ((styleFlags & windowAppearsOnTaskbar) == 0)
  205609. exstyle |= WS_EX_TOOLWINDOW;
  205610. else
  205611. exstyle |= WS_EX_APPWINDOW;
  205612. }
  205613. if ((styleFlags & windowHasMinimiseButton) != 0)
  205614. type |= WS_MINIMIZEBOX;
  205615. if ((styleFlags & windowHasMaximiseButton) != 0)
  205616. type |= WS_MAXIMIZEBOX;
  205617. if ((styleFlags & windowIgnoresMouseClicks) != 0)
  205618. exstyle |= WS_EX_TRANSPARENT;
  205619. if ((styleFlags & windowIsSemiTransparent) != 0
  205620. && Desktop::canUseSemiTransparentWindows())
  205621. exstyle |= WS_EX_LAYERED;
  205622. hwnd = CreateWindowEx (exstyle, WindowClassHolder::getInstance()->windowClassName, L"", type, 0, 0, 0, 0, 0, 0, 0, 0);
  205623. if (hwnd != 0)
  205624. {
  205625. SetWindowLongPtr (hwnd, 0, 0);
  205626. SetWindowLongPtr (hwnd, 8, (LONG_PTR) this);
  205627. SetWindowLongPtr (hwnd, GWLP_USERDATA, improbableWindowNumber);
  205628. if (dropTarget == 0)
  205629. dropTarget = new JuceDropTarget (this);
  205630. RegisterDragDrop (hwnd, dropTarget);
  205631. updateBorderSize();
  205632. // Calling this function here is (for some reason) necessary to make Windows
  205633. // correctly enable the menu items that we specify in the wm_initmenu message.
  205634. GetSystemMenu (hwnd, false);
  205635. }
  205636. else
  205637. {
  205638. jassertfalse
  205639. }
  205640. }
  205641. static void* destroyWindowCallback (void* handle)
  205642. {
  205643. RevokeDragDrop ((HWND) handle);
  205644. DestroyWindow ((HWND) handle);
  205645. return 0;
  205646. }
  205647. static void* toFrontCallback1 (void* h)
  205648. {
  205649. SetForegroundWindow ((HWND) h);
  205650. return 0;
  205651. }
  205652. static void* toFrontCallback2 (void* h)
  205653. {
  205654. SetWindowPos ((HWND) h, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  205655. return 0;
  205656. }
  205657. static void* setFocusCallback (void* h)
  205658. {
  205659. SetFocus ((HWND) h);
  205660. return 0;
  205661. }
  205662. static void* getFocusCallback (void*)
  205663. {
  205664. return (void*) GetFocus();
  205665. }
  205666. void offsetWithinParent (int& x, int& y) const
  205667. {
  205668. if (isTransparent())
  205669. {
  205670. HWND parentHwnd = GetParent (hwnd);
  205671. if (parentHwnd != 0)
  205672. {
  205673. RECT parentRect;
  205674. GetWindowRect (parentHwnd, &parentRect);
  205675. x += parentRect.left;
  205676. y += parentRect.top;
  205677. }
  205678. }
  205679. }
  205680. bool isTransparent() const
  205681. {
  205682. return (GetWindowLong (hwnd, GWL_EXSTYLE) & WS_EX_LAYERED) != 0;
  205683. }
  205684. inline bool hasTitleBar() const throw() { return (styleFlags & windowHasTitleBar) != 0; }
  205685. void setIcon (const Image& newIcon)
  205686. {
  205687. HICON hicon = createHICONFromImage (newIcon, TRUE, 0, 0);
  205688. if (hicon != 0)
  205689. {
  205690. SendMessage (hwnd, WM_SETICON, ICON_BIG, (LPARAM) hicon);
  205691. SendMessage (hwnd, WM_SETICON, ICON_SMALL, (LPARAM) hicon);
  205692. if (currentWindowIcon != 0)
  205693. DestroyIcon (currentWindowIcon);
  205694. currentWindowIcon = hicon;
  205695. }
  205696. }
  205697. void handlePaintMessage()
  205698. {
  205699. #if DEBUG_REPAINT_TIMES
  205700. const double paintStart = Time::getMillisecondCounterHiRes();
  205701. #endif
  205702. HRGN rgn = CreateRectRgn (0, 0, 0, 0);
  205703. const int regionType = GetUpdateRgn (hwnd, rgn, false);
  205704. PAINTSTRUCT paintStruct;
  205705. HDC dc = BeginPaint (hwnd, &paintStruct); // Note this can immediately generate a WM_NCPAINT
  205706. // message and become re-entrant, but that's OK
  205707. // if something in a paint handler calls, e.g. a message box, this can become reentrant and
  205708. // corrupt the image it's using to paint into, so do a check here.
  205709. static bool reentrant = false;
  205710. if (reentrant)
  205711. {
  205712. DeleteObject (rgn);
  205713. EndPaint (hwnd, &paintStruct);
  205714. return;
  205715. }
  205716. reentrant = true;
  205717. // this is the rectangle to update..
  205718. int x = paintStruct.rcPaint.left;
  205719. int y = paintStruct.rcPaint.top;
  205720. int w = paintStruct.rcPaint.right - x;
  205721. int h = paintStruct.rcPaint.bottom - y;
  205722. const bool transparent = isTransparent();
  205723. if (transparent)
  205724. {
  205725. // it's not possible to have a transparent window with a title bar at the moment!
  205726. jassert (! hasTitleBar());
  205727. RECT r;
  205728. GetWindowRect (hwnd, &r);
  205729. x = y = 0;
  205730. w = r.right - r.left;
  205731. h = r.bottom - r.top;
  205732. }
  205733. if (w > 0 && h > 0)
  205734. {
  205735. clearMaskedRegion();
  205736. WindowsBitmapImage* const offscreenImage = offscreenImageGenerator.getImage (transparent, w, h);
  205737. LowLevelGraphicsSoftwareRenderer context (*offscreenImage);
  205738. RectangleList* const contextClip = context.getRawClipRegion();
  205739. contextClip->clear();
  205740. context.setOrigin (-x, -y);
  205741. bool needToPaintAll = true;
  205742. if (regionType == COMPLEXREGION && ! transparent)
  205743. {
  205744. HRGN clipRgn = CreateRectRgnIndirect (&paintStruct.rcPaint);
  205745. CombineRgn (rgn, rgn, clipRgn, RGN_AND);
  205746. DeleteObject (clipRgn);
  205747. char rgnData [8192];
  205748. const DWORD res = GetRegionData (rgn, sizeof (rgnData), (RGNDATA*) rgnData);
  205749. if (res > 0 && res <= sizeof (rgnData))
  205750. {
  205751. const RGNDATAHEADER* const hdr = &(((const RGNDATA*) rgnData)->rdh);
  205752. if (hdr->iType == RDH_RECTANGLES
  205753. && hdr->rcBound.right - hdr->rcBound.left >= w
  205754. && hdr->rcBound.bottom - hdr->rcBound.top >= h)
  205755. {
  205756. needToPaintAll = false;
  205757. const RECT* rects = (const RECT*) (rgnData + sizeof (RGNDATAHEADER));
  205758. int num = ((RGNDATA*) rgnData)->rdh.nCount;
  205759. while (--num >= 0)
  205760. {
  205761. // (need to move this one pixel to the left because of a win32 bug)
  205762. const int cx = jmax (x, rects->left - 1);
  205763. const int cy = rects->top;
  205764. const int cw = rects->right - cx;
  205765. const int ch = rects->bottom - rects->top;
  205766. if (cx + cw - x <= w && cy + ch - y <= h)
  205767. {
  205768. contextClip->addWithoutMerging (Rectangle (cx - x, cy - y, cw, ch));
  205769. }
  205770. else
  205771. {
  205772. needToPaintAll = true;
  205773. break;
  205774. }
  205775. ++rects;
  205776. }
  205777. }
  205778. }
  205779. }
  205780. if (needToPaintAll)
  205781. {
  205782. contextClip->clear();
  205783. contextClip->addWithoutMerging (Rectangle (0, 0, w, h));
  205784. }
  205785. if (transparent)
  205786. {
  205787. RectangleList::Iterator i (*contextClip);
  205788. while (i.next())
  205789. {
  205790. const Rectangle& r = *i.getRectangle();
  205791. offscreenImage->clear (r.getX(), r.getY(), r.getWidth(), r.getHeight());
  205792. }
  205793. }
  205794. // if the component's not opaque, this won't draw properly unless the platform can support this
  205795. jassert (Desktop::canUseSemiTransparentWindows() || component->isOpaque());
  205796. updateCurrentModifiers();
  205797. handlePaint (context);
  205798. if (! dontRepaint)
  205799. offscreenImage->blitToWindow (hwnd, dc, transparent, x, y, maskedRegion);
  205800. }
  205801. DeleteObject (rgn);
  205802. EndPaint (hwnd, &paintStruct);
  205803. reentrant = false;
  205804. #ifndef JUCE_GCC //xxx should add this fn for gcc..
  205805. _fpreset(); // because some graphics cards can unmask FP exceptions
  205806. #endif
  205807. lastPaintTime = Time::getMillisecondCounter();
  205808. #if DEBUG_REPAINT_TIMES
  205809. const double elapsed = Time::getMillisecondCounterHiRes() - paintStart;
  205810. Logger::outputDebugString (T("repaint time: ") + String (elapsed, 2));
  205811. #endif
  205812. }
  205813. void doMouseMove (const int x, const int y)
  205814. {
  205815. static uint32 lastMouseTime = 0;
  205816. // this can be set to throttle the mouse-messages to less than a
  205817. // certain number per second, as things can get unresponsive
  205818. // if each drag or move callback has to do a lot of work.
  205819. const int maxMouseMovesPerSecond = 60;
  205820. const int64 mouseEventTime = getMouseEventTime();
  205821. if (! isMouseOver)
  205822. {
  205823. isMouseOver = true;
  205824. TRACKMOUSEEVENT tme;
  205825. tme.cbSize = sizeof (tme);
  205826. tme.dwFlags = TME_LEAVE;
  205827. tme.hwndTrack = hwnd;
  205828. tme.dwHoverTime = 0;
  205829. if (! TrackMouseEvent (&tme))
  205830. {
  205831. jassertfalse;
  205832. }
  205833. updateKeyModifiers();
  205834. handleMouseEnter (x, y, mouseEventTime);
  205835. }
  205836. else if (! isDragging)
  205837. {
  205838. if (((unsigned int) x) < (unsigned int) component->getWidth()
  205839. && ((unsigned int) y) < (unsigned int) component->getHeight())
  205840. {
  205841. RECT r;
  205842. GetWindowRect (hwnd, &r);
  205843. POINT p;
  205844. p.x = x + r.left + windowBorder.getLeft();
  205845. p.y = y + r.top + windowBorder.getTop();
  205846. if (WindowFromPoint (p) == hwnd)
  205847. {
  205848. const uint32 now = Time::getMillisecondCounter();
  205849. if (now > lastMouseTime + 1000 / maxMouseMovesPerSecond)
  205850. {
  205851. lastMouseTime = now;
  205852. handleMouseMove (x, y, mouseEventTime);
  205853. }
  205854. }
  205855. }
  205856. }
  205857. else
  205858. {
  205859. const uint32 now = Time::getMillisecondCounter();
  205860. if (now > lastMouseTime + 1000 / maxMouseMovesPerSecond)
  205861. {
  205862. lastMouseTime = now;
  205863. handleMouseDrag (x, y, mouseEventTime);
  205864. }
  205865. }
  205866. }
  205867. void doMouseDown (const int x, const int y, const WPARAM wParam)
  205868. {
  205869. if (GetCapture() != hwnd)
  205870. SetCapture (hwnd);
  205871. doMouseMove (x, y);
  205872. currentModifiers &= ~ModifierKeys::allMouseButtonModifiers;
  205873. if ((wParam & MK_LBUTTON) != 0)
  205874. currentModifiers |= ModifierKeys::leftButtonModifier;
  205875. if ((wParam & MK_RBUTTON) != 0)
  205876. currentModifiers |= ModifierKeys::rightButtonModifier;
  205877. if ((wParam & MK_MBUTTON) != 0)
  205878. currentModifiers |= ModifierKeys::middleButtonModifier;
  205879. updateKeyModifiers();
  205880. isDragging = true;
  205881. handleMouseDown (x, y, getMouseEventTime());
  205882. }
  205883. void doMouseUp (const int x, const int y, const WPARAM wParam)
  205884. {
  205885. int numButtons = 0;
  205886. if ((wParam & MK_LBUTTON) != 0)
  205887. ++numButtons;
  205888. if ((wParam & MK_RBUTTON) != 0)
  205889. ++numButtons;
  205890. if ((wParam & MK_MBUTTON) != 0)
  205891. ++numButtons;
  205892. const int oldModifiers = currentModifiers;
  205893. // update the currentmodifiers only after the callback, so the callback
  205894. // knows which button was released.
  205895. currentModifiers &= ~ModifierKeys::allMouseButtonModifiers;
  205896. if ((wParam & MK_LBUTTON) != 0)
  205897. currentModifiers |= ModifierKeys::leftButtonModifier;
  205898. if ((wParam & MK_RBUTTON) != 0)
  205899. currentModifiers |= ModifierKeys::rightButtonModifier;
  205900. if ((wParam & MK_MBUTTON) != 0)
  205901. currentModifiers |= ModifierKeys::middleButtonModifier;
  205902. updateKeyModifiers();
  205903. isDragging = false;
  205904. // release the mouse capture if the user's not still got a button down
  205905. if (numButtons == 0 && hwnd == GetCapture())
  205906. ReleaseCapture();
  205907. handleMouseUp (oldModifiers, x, y, getMouseEventTime());
  205908. }
  205909. void doCaptureChanged()
  205910. {
  205911. if (isDragging)
  205912. {
  205913. RECT wr;
  205914. GetWindowRect (hwnd, &wr);
  205915. const DWORD mp = GetMessagePos();
  205916. doMouseUp (GET_X_LPARAM (mp) - wr.left - windowBorder.getLeft(),
  205917. GET_Y_LPARAM (mp) - wr.top - windowBorder.getTop(),
  205918. getMouseEventTime());
  205919. }
  205920. }
  205921. void doMouseExit()
  205922. {
  205923. if (isMouseOver)
  205924. {
  205925. isMouseOver = false;
  205926. RECT wr;
  205927. GetWindowRect (hwnd, &wr);
  205928. const DWORD mp = GetMessagePos();
  205929. handleMouseExit (GET_X_LPARAM (mp) - wr.left - windowBorder.getLeft(),
  205930. GET_Y_LPARAM (mp) - wr.top - windowBorder.getTop(),
  205931. getMouseEventTime());
  205932. }
  205933. }
  205934. void doMouseWheel (const WPARAM wParam, const bool isVertical)
  205935. {
  205936. updateKeyModifiers();
  205937. const int amount = jlimit (-1000, 1000, (int) (0.75f * (short) HIWORD (wParam)));
  205938. handleMouseWheel (isVertical ? 0 : amount,
  205939. isVertical ? amount : 0,
  205940. getMouseEventTime());
  205941. }
  205942. void sendModifierKeyChangeIfNeeded()
  205943. {
  205944. if (modifiersAtLastCallback != currentModifiers)
  205945. {
  205946. modifiersAtLastCallback = currentModifiers;
  205947. handleModifierKeysChange();
  205948. }
  205949. }
  205950. bool doKeyUp (const WPARAM key)
  205951. {
  205952. updateKeyModifiers();
  205953. switch (key)
  205954. {
  205955. case VK_SHIFT:
  205956. case VK_CONTROL:
  205957. case VK_MENU:
  205958. case VK_CAPITAL:
  205959. case VK_LWIN:
  205960. case VK_RWIN:
  205961. case VK_APPS:
  205962. case VK_NUMLOCK:
  205963. case VK_SCROLL:
  205964. case VK_LSHIFT:
  205965. case VK_RSHIFT:
  205966. case VK_LCONTROL:
  205967. case VK_LMENU:
  205968. case VK_RCONTROL:
  205969. case VK_RMENU:
  205970. sendModifierKeyChangeIfNeeded();
  205971. }
  205972. return handleKeyUpOrDown();
  205973. }
  205974. bool doKeyDown (const WPARAM key)
  205975. {
  205976. updateKeyModifiers();
  205977. bool used = false;
  205978. switch (key)
  205979. {
  205980. case VK_SHIFT:
  205981. case VK_LSHIFT:
  205982. case VK_RSHIFT:
  205983. case VK_CONTROL:
  205984. case VK_LCONTROL:
  205985. case VK_RCONTROL:
  205986. case VK_MENU:
  205987. case VK_LMENU:
  205988. case VK_RMENU:
  205989. case VK_LWIN:
  205990. case VK_RWIN:
  205991. case VK_CAPITAL:
  205992. case VK_NUMLOCK:
  205993. case VK_SCROLL:
  205994. case VK_APPS:
  205995. sendModifierKeyChangeIfNeeded();
  205996. break;
  205997. case VK_LEFT:
  205998. case VK_RIGHT:
  205999. case VK_UP:
  206000. case VK_DOWN:
  206001. case VK_PRIOR:
  206002. case VK_NEXT:
  206003. case VK_HOME:
  206004. case VK_END:
  206005. case VK_DELETE:
  206006. case VK_INSERT:
  206007. case VK_F1:
  206008. case VK_F2:
  206009. case VK_F3:
  206010. case VK_F4:
  206011. case VK_F5:
  206012. case VK_F6:
  206013. case VK_F7:
  206014. case VK_F8:
  206015. case VK_F9:
  206016. case VK_F10:
  206017. case VK_F11:
  206018. case VK_F12:
  206019. case VK_F13:
  206020. case VK_F14:
  206021. case VK_F15:
  206022. case VK_F16:
  206023. used = handleKeyUpOrDown();
  206024. used = handleKeyPress (extendedKeyModifier | (int) key, 0) || used;
  206025. break;
  206026. case VK_ADD:
  206027. case VK_SUBTRACT:
  206028. case VK_MULTIPLY:
  206029. case VK_DIVIDE:
  206030. case VK_SEPARATOR:
  206031. case VK_DECIMAL:
  206032. used = handleKeyUpOrDown();
  206033. break;
  206034. default:
  206035. used = handleKeyUpOrDown();
  206036. {
  206037. MSG msg;
  206038. if (! PeekMessage (&msg, hwnd, WM_CHAR, WM_DEADCHAR, PM_NOREMOVE))
  206039. {
  206040. // if there isn't a WM_CHAR or WM_DEADCHAR message pending, we need to
  206041. // manually generate the key-press event that matches this key-down.
  206042. const UINT keyChar = MapVirtualKey (key, 2);
  206043. used = handleKeyPress ((int) LOWORD (keyChar), 0) || used;
  206044. }
  206045. }
  206046. break;
  206047. }
  206048. return used;
  206049. }
  206050. bool doKeyChar (int key, const LPARAM flags)
  206051. {
  206052. updateKeyModifiers();
  206053. juce_wchar textChar = (juce_wchar) key;
  206054. const int virtualScanCode = (flags >> 16) & 0xff;
  206055. if (key >= '0' && key <= '9')
  206056. {
  206057. switch (virtualScanCode) // check for a numeric keypad scan-code
  206058. {
  206059. case 0x52:
  206060. case 0x4f:
  206061. case 0x50:
  206062. case 0x51:
  206063. case 0x4b:
  206064. case 0x4c:
  206065. case 0x4d:
  206066. case 0x47:
  206067. case 0x48:
  206068. case 0x49:
  206069. key = (key - '0') + KeyPress::numberPad0;
  206070. break;
  206071. default:
  206072. break;
  206073. }
  206074. }
  206075. else
  206076. {
  206077. // convert the scan code to an unmodified character code..
  206078. const UINT virtualKey = MapVirtualKey (virtualScanCode, 1);
  206079. UINT keyChar = MapVirtualKey (virtualKey, 2);
  206080. keyChar = LOWORD (keyChar);
  206081. if (keyChar != 0)
  206082. key = (int) keyChar;
  206083. // avoid sending junk text characters for some control-key combinations
  206084. if (textChar < ' ' && (currentModifiers & (ModifierKeys::ctrlModifier | ModifierKeys::altModifier)) != 0)
  206085. textChar = 0;
  206086. }
  206087. return handleKeyPress (key, textChar);
  206088. }
  206089. bool doAppCommand (const LPARAM lParam)
  206090. {
  206091. int key = 0;
  206092. switch (GET_APPCOMMAND_LPARAM (lParam))
  206093. {
  206094. case APPCOMMAND_MEDIA_PLAY_PAUSE:
  206095. key = KeyPress::playKey;
  206096. break;
  206097. case APPCOMMAND_MEDIA_STOP:
  206098. key = KeyPress::stopKey;
  206099. break;
  206100. case APPCOMMAND_MEDIA_NEXTTRACK:
  206101. key = KeyPress::fastForwardKey;
  206102. break;
  206103. case APPCOMMAND_MEDIA_PREVIOUSTRACK:
  206104. key = KeyPress::rewindKey;
  206105. break;
  206106. }
  206107. if (key != 0)
  206108. {
  206109. updateKeyModifiers();
  206110. if (hwnd == GetActiveWindow())
  206111. {
  206112. handleKeyPress (key, 0);
  206113. return true;
  206114. }
  206115. }
  206116. return false;
  206117. }
  206118. class JuceDropTarget : public IDropTarget
  206119. {
  206120. public:
  206121. JuceDropTarget (Win32ComponentPeer* const owner_)
  206122. : owner (owner_),
  206123. refCount (1)
  206124. {
  206125. }
  206126. virtual ~JuceDropTarget()
  206127. {
  206128. jassert (refCount == 0);
  206129. }
  206130. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  206131. {
  206132. if (id == IID_IUnknown || id == IID_IDropTarget)
  206133. {
  206134. AddRef();
  206135. *result = this;
  206136. return S_OK;
  206137. }
  206138. *result = 0;
  206139. return E_NOINTERFACE;
  206140. }
  206141. ULONG __stdcall AddRef() { return ++refCount; }
  206142. ULONG __stdcall Release() { jassert (refCount > 0); const int r = --refCount; if (r == 0) delete this; return r; }
  206143. HRESULT __stdcall DragEnter (IDataObject* pDataObject, DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  206144. {
  206145. updateFileList (pDataObject);
  206146. int x = mousePos.x, y = mousePos.y;
  206147. owner->globalPositionToRelative (x, y);
  206148. owner->handleFileDragMove (files, x, y);
  206149. *pdwEffect = DROPEFFECT_COPY;
  206150. return S_OK;
  206151. }
  206152. HRESULT __stdcall DragLeave()
  206153. {
  206154. owner->handleFileDragExit (files);
  206155. return S_OK;
  206156. }
  206157. HRESULT __stdcall DragOver (DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  206158. {
  206159. int x = mousePos.x, y = mousePos.y;
  206160. owner->globalPositionToRelative (x, y);
  206161. owner->handleFileDragMove (files, x, y);
  206162. *pdwEffect = DROPEFFECT_COPY;
  206163. return S_OK;
  206164. }
  206165. HRESULT __stdcall Drop (IDataObject* pDataObject, DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  206166. {
  206167. updateFileList (pDataObject);
  206168. int x = mousePos.x, y = mousePos.y;
  206169. owner->globalPositionToRelative (x, y);
  206170. owner->handleFileDragDrop (files, x, y);
  206171. *pdwEffect = DROPEFFECT_COPY;
  206172. return S_OK;
  206173. }
  206174. private:
  206175. Win32ComponentPeer* const owner;
  206176. int refCount;
  206177. StringArray files;
  206178. void updateFileList (IDataObject* const pDataObject)
  206179. {
  206180. files.clear();
  206181. FORMATETC format = { CF_HDROP, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  206182. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  206183. if (pDataObject->GetData (&format, &medium) == S_OK)
  206184. {
  206185. const SIZE_T totalLen = GlobalSize (medium.hGlobal);
  206186. const LPDROPFILES pDropFiles = (const LPDROPFILES) GlobalLock (medium.hGlobal);
  206187. unsigned int i = 0;
  206188. if (pDropFiles->fWide)
  206189. {
  206190. const WCHAR* const fname = (WCHAR*) (((const char*) pDropFiles) + sizeof (DROPFILES));
  206191. for (;;)
  206192. {
  206193. unsigned int len = 0;
  206194. while (i + len < totalLen && fname [i + len] != 0)
  206195. ++len;
  206196. if (len == 0)
  206197. break;
  206198. files.add (String (fname + i, len));
  206199. i += len + 1;
  206200. }
  206201. }
  206202. else
  206203. {
  206204. const char* const fname = ((const char*) pDropFiles) + sizeof (DROPFILES);
  206205. for (;;)
  206206. {
  206207. unsigned int len = 0;
  206208. while (i + len < totalLen && fname [i + len] != 0)
  206209. ++len;
  206210. if (len == 0)
  206211. break;
  206212. files.add (String (fname + i, len));
  206213. i += len + 1;
  206214. }
  206215. }
  206216. GlobalUnlock (medium.hGlobal);
  206217. }
  206218. }
  206219. JuceDropTarget (const JuceDropTarget&);
  206220. const JuceDropTarget& operator= (const JuceDropTarget&);
  206221. };
  206222. void doSettingChange()
  206223. {
  206224. Desktop::getInstance().refreshMonitorSizes();
  206225. if (fullScreen && ! isMinimised())
  206226. {
  206227. const Rectangle r (component->getParentMonitorArea());
  206228. SetWindowPos (hwnd, 0,
  206229. r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  206230. SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER | SWP_NOSENDCHANGING);
  206231. }
  206232. }
  206233. public:
  206234. static LRESULT CALLBACK windowProc (HWND h, UINT message, WPARAM wParam, LPARAM lParam)
  206235. {
  206236. Win32ComponentPeer* const peer = getOwnerOfWindow (h);
  206237. if (peer != 0)
  206238. return peer->peerWindowProc (h, message, wParam, lParam);
  206239. return DefWindowProc (h, message, wParam, lParam);
  206240. }
  206241. private:
  206242. LRESULT peerWindowProc (HWND h, UINT message, WPARAM wParam, LPARAM lParam)
  206243. {
  206244. {
  206245. const MessageManagerLock messLock;
  206246. if (isValidPeer (this))
  206247. {
  206248. switch (message)
  206249. {
  206250. case WM_NCHITTEST:
  206251. if (hasTitleBar())
  206252. break;
  206253. return HTCLIENT;
  206254. case WM_PAINT:
  206255. handlePaintMessage();
  206256. return 0;
  206257. case WM_NCPAINT:
  206258. if (wParam != 1)
  206259. handlePaintMessage();
  206260. if (hasTitleBar())
  206261. break;
  206262. return 0;
  206263. case WM_ERASEBKGND:
  206264. case WM_NCCALCSIZE:
  206265. if (hasTitleBar())
  206266. break;
  206267. return 1;
  206268. case WM_MOUSEMOVE:
  206269. doMouseMove (GET_X_LPARAM (lParam), GET_Y_LPARAM (lParam));
  206270. return 0;
  206271. case WM_MOUSELEAVE:
  206272. doMouseExit();
  206273. return 0;
  206274. case WM_LBUTTONDOWN:
  206275. case WM_MBUTTONDOWN:
  206276. case WM_RBUTTONDOWN:
  206277. doMouseDown (GET_X_LPARAM (lParam), GET_Y_LPARAM (lParam), wParam);
  206278. return 0;
  206279. case WM_LBUTTONUP:
  206280. case WM_MBUTTONUP:
  206281. case WM_RBUTTONUP:
  206282. doMouseUp (GET_X_LPARAM (lParam), GET_Y_LPARAM (lParam), wParam);
  206283. return 0;
  206284. case WM_CAPTURECHANGED:
  206285. doCaptureChanged();
  206286. return 0;
  206287. case WM_NCMOUSEMOVE:
  206288. if (hasTitleBar())
  206289. break;
  206290. return 0;
  206291. case 0x020A: /* WM_MOUSEWHEEL */
  206292. doMouseWheel (wParam, true);
  206293. return 0;
  206294. case 0x020E: /* WM_MOUSEHWHEEL */
  206295. doMouseWheel (wParam, false);
  206296. return 0;
  206297. case WM_WINDOWPOSCHANGING:
  206298. if ((styleFlags & (windowHasTitleBar | windowIsResizable)) == (windowHasTitleBar | windowIsResizable))
  206299. {
  206300. WINDOWPOS* const wp = (WINDOWPOS*) lParam;
  206301. if ((wp->flags & (SWP_NOMOVE | SWP_NOSIZE)) != (SWP_NOMOVE | SWP_NOSIZE))
  206302. {
  206303. if (constrainer != 0)
  206304. {
  206305. const Rectangle current (component->getX() - windowBorder.getLeft(),
  206306. component->getY() - windowBorder.getTop(),
  206307. component->getWidth() + windowBorder.getLeftAndRight(),
  206308. component->getHeight() + windowBorder.getTopAndBottom());
  206309. constrainer->checkBounds (wp->x, wp->y, wp->cx, wp->cy,
  206310. current,
  206311. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  206312. wp->y != current.getY() && wp->y + wp->cy == current.getBottom(),
  206313. wp->x != current.getX() && wp->x + wp->cx == current.getRight(),
  206314. wp->y == current.getY() && wp->y + wp->cy != current.getBottom(),
  206315. wp->x == current.getX() && wp->x + wp->cx != current.getRight());
  206316. }
  206317. }
  206318. }
  206319. return 0;
  206320. case WM_WINDOWPOSCHANGED:
  206321. handleMovedOrResized();
  206322. if (dontRepaint)
  206323. break; // needed for non-accelerated openGL windows to draw themselves correctly..
  206324. else
  206325. return 0;
  206326. case WM_KEYDOWN:
  206327. case WM_SYSKEYDOWN:
  206328. if (doKeyDown (wParam))
  206329. return 0;
  206330. break;
  206331. case WM_KEYUP:
  206332. case WM_SYSKEYUP:
  206333. if (doKeyUp (wParam))
  206334. return 0;
  206335. break;
  206336. case WM_CHAR:
  206337. if (doKeyChar ((int) wParam, lParam))
  206338. return 0;
  206339. break;
  206340. case WM_APPCOMMAND:
  206341. if (doAppCommand (lParam))
  206342. return TRUE;
  206343. break;
  206344. case WM_SETFOCUS:
  206345. updateKeyModifiers();
  206346. handleFocusGain();
  206347. break;
  206348. case WM_KILLFOCUS:
  206349. handleFocusLoss();
  206350. break;
  206351. case WM_ACTIVATEAPP:
  206352. // Windows does weird things to process priority when you swap apps,
  206353. // so this forces an update when the app is brought to the front
  206354. if (wParam != FALSE)
  206355. juce_repeatLastProcessPriority();
  206356. juce_CheckCurrentlyFocusedTopLevelWindow();
  206357. modifiersAtLastCallback = -1;
  206358. return 0;
  206359. case WM_ACTIVATE:
  206360. if (LOWORD (wParam) == WA_ACTIVE || LOWORD (wParam) == WA_CLICKACTIVE)
  206361. {
  206362. modifiersAtLastCallback = -1;
  206363. updateKeyModifiers();
  206364. if (isMinimised())
  206365. {
  206366. component->repaint();
  206367. handleMovedOrResized();
  206368. if (! isValidMessageListener())
  206369. return 0;
  206370. }
  206371. if (LOWORD (wParam) == WA_CLICKACTIVE
  206372. && component->isCurrentlyBlockedByAnotherModalComponent())
  206373. {
  206374. int mx, my;
  206375. component->getMouseXYRelative (mx, my);
  206376. Component* const underMouse = component->getComponentAt (mx, my);
  206377. if (underMouse != 0 && underMouse->isCurrentlyBlockedByAnotherModalComponent())
  206378. Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  206379. return 0;
  206380. }
  206381. handleBroughtToFront();
  206382. return 0;
  206383. }
  206384. break;
  206385. case WM_NCACTIVATE:
  206386. // while a temporary window is being shown, prevent Windows from deactivating the
  206387. // title bars of our main windows.
  206388. if (wParam == 0 && ! shouldDeactivateTitleBar)
  206389. wParam = TRUE; // change this and let it get passed to the DefWindowProc.
  206390. break;
  206391. case WM_MOUSEACTIVATE:
  206392. if (! component->getMouseClickGrabsKeyboardFocus())
  206393. return MA_NOACTIVATE;
  206394. break;
  206395. case WM_SHOWWINDOW:
  206396. if (wParam != 0)
  206397. handleBroughtToFront();
  206398. break;
  206399. case WM_CLOSE:
  206400. handleUserClosingWindow();
  206401. return 0;
  206402. case WM_QUIT:
  206403. JUCEApplication::quit();
  206404. return 0;
  206405. case WM_TRAYNOTIFY:
  206406. if (component->isCurrentlyBlockedByAnotherModalComponent())
  206407. {
  206408. if (lParam == WM_LBUTTONDOWN || lParam == WM_RBUTTONDOWN
  206409. || lParam == WM_LBUTTONDBLCLK || lParam == WM_LBUTTONDBLCLK)
  206410. {
  206411. Component* const current = Component::getCurrentlyModalComponent();
  206412. if (current != 0)
  206413. current->inputAttemptWhenModal();
  206414. }
  206415. }
  206416. else
  206417. {
  206418. const int oldModifiers = currentModifiers;
  206419. MouseEvent e (0, 0, ModifierKeys::getCurrentModifiersRealtime(), component,
  206420. getMouseEventTime(), 0, 0, getMouseEventTime(), 1, false);
  206421. if (lParam == WM_LBUTTONDOWN || lParam == WM_LBUTTONDBLCLK)
  206422. e.mods = ModifierKeys (e.mods.getRawFlags() | ModifierKeys::leftButtonModifier);
  206423. else if (lParam == WM_RBUTTONDOWN || lParam == WM_RBUTTONDBLCLK)
  206424. e.mods = ModifierKeys (e.mods.getRawFlags() | ModifierKeys::rightButtonModifier);
  206425. if (lParam == WM_LBUTTONDOWN || lParam == WM_RBUTTONDOWN)
  206426. {
  206427. SetFocus (hwnd);
  206428. SetForegroundWindow (hwnd);
  206429. component->mouseDown (e);
  206430. }
  206431. else if (lParam == WM_LBUTTONUP || lParam == WM_RBUTTONUP)
  206432. {
  206433. e.mods = ModifierKeys (oldModifiers);
  206434. component->mouseUp (e);
  206435. }
  206436. else if (lParam == WM_LBUTTONDBLCLK || lParam == WM_LBUTTONDBLCLK)
  206437. {
  206438. e.mods = ModifierKeys (oldModifiers);
  206439. component->mouseDoubleClick (e);
  206440. }
  206441. else if (lParam == WM_MOUSEMOVE)
  206442. {
  206443. component->mouseMove (e);
  206444. }
  206445. }
  206446. break;
  206447. case WM_SYNCPAINT:
  206448. return 0;
  206449. case WM_PALETTECHANGED:
  206450. InvalidateRect (h, 0, 0);
  206451. break;
  206452. case WM_DISPLAYCHANGE:
  206453. InvalidateRect (h, 0, 0);
  206454. createPaletteIfNeeded = true;
  206455. // intentional fall-through...
  206456. case WM_SETTINGCHANGE: // note the fall-through in the previous case!
  206457. doSettingChange();
  206458. break;
  206459. case WM_INITMENU:
  206460. if (! hasTitleBar())
  206461. {
  206462. if (isFullScreen())
  206463. {
  206464. EnableMenuItem ((HMENU) wParam, SC_RESTORE, MF_BYCOMMAND | MF_ENABLED);
  206465. EnableMenuItem ((HMENU) wParam, SC_MOVE, MF_BYCOMMAND | MF_GRAYED);
  206466. }
  206467. else if (! isMinimised())
  206468. {
  206469. EnableMenuItem ((HMENU) wParam, SC_MAXIMIZE, MF_BYCOMMAND | MF_GRAYED);
  206470. }
  206471. }
  206472. break;
  206473. case WM_SYSCOMMAND:
  206474. switch (wParam & 0xfff0)
  206475. {
  206476. case SC_CLOSE:
  206477. if (hasTitleBar())
  206478. {
  206479. PostMessage (h, WM_CLOSE, 0, 0);
  206480. return 0;
  206481. }
  206482. break;
  206483. case SC_KEYMENU:
  206484. if (hasTitleBar() && h == GetCapture())
  206485. ReleaseCapture();
  206486. break;
  206487. case SC_MAXIMIZE:
  206488. setFullScreen (true);
  206489. return 0;
  206490. case SC_MINIMIZE:
  206491. if (! hasTitleBar())
  206492. {
  206493. setMinimised (true);
  206494. return 0;
  206495. }
  206496. break;
  206497. case SC_RESTORE:
  206498. if (hasTitleBar())
  206499. {
  206500. if (isFullScreen())
  206501. {
  206502. setFullScreen (false);
  206503. return 0;
  206504. }
  206505. }
  206506. else
  206507. {
  206508. if (isMinimised())
  206509. setMinimised (false);
  206510. else if (isFullScreen())
  206511. setFullScreen (false);
  206512. return 0;
  206513. }
  206514. break;
  206515. case SC_MONITORPOWER:
  206516. case SC_SCREENSAVE:
  206517. if (! screenSaverAllowed)
  206518. return 0;
  206519. break;
  206520. }
  206521. break;
  206522. case WM_NCLBUTTONDOWN:
  206523. case WM_NCRBUTTONDOWN:
  206524. case WM_NCMBUTTONDOWN:
  206525. if (component->isCurrentlyBlockedByAnotherModalComponent())
  206526. {
  206527. Component* const current = Component::getCurrentlyModalComponent();
  206528. if (current != 0)
  206529. current->inputAttemptWhenModal();
  206530. }
  206531. break;
  206532. //case WM_IME_STARTCOMPOSITION;
  206533. // return 0;
  206534. case WM_GETDLGCODE:
  206535. return DLGC_WANTALLKEYS;
  206536. default:
  206537. break;
  206538. }
  206539. }
  206540. }
  206541. // (the message manager lock exits before calling this, to avoid deadlocks if
  206542. // this calls into non-juce windows)
  206543. return DefWindowProc (h, message, wParam, lParam);
  206544. }
  206545. Win32ComponentPeer (const Win32ComponentPeer&);
  206546. const Win32ComponentPeer& operator= (const Win32ComponentPeer&);
  206547. };
  206548. ComponentPeer* Component::createNewPeer (int styleFlags, void* /*nativeWindowToAttachTo*/)
  206549. {
  206550. return new Win32ComponentPeer (this, styleFlags);
  206551. }
  206552. juce_ImplementSingleton_SingleThreaded (Win32ComponentPeer::WindowClassHolder);
  206553. void SystemTrayIconComponent::setIconImage (const Image& newImage)
  206554. {
  206555. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (getPeer());
  206556. if (wp != 0)
  206557. wp->setTaskBarIcon (&newImage);
  206558. }
  206559. void SystemTrayIconComponent::setIconTooltip (const String& tooltip)
  206560. {
  206561. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (getPeer());
  206562. if (wp != 0)
  206563. wp->setTaskBarIconToolTip (tooltip);
  206564. }
  206565. void juce_setWindowStyleBit (HWND h, const int styleType, const int feature, const bool bitIsSet) throw()
  206566. {
  206567. DWORD val = GetWindowLong (h, styleType);
  206568. if (bitIsSet)
  206569. val |= feature;
  206570. else
  206571. val &= ~feature;
  206572. SetWindowLongPtr (h, styleType, val);
  206573. SetWindowPos (h, 0, 0, 0, 0, 0,
  206574. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER
  206575. | SWP_NOOWNERZORDER | SWP_FRAMECHANGED | SWP_NOSENDCHANGING);
  206576. }
  206577. bool Process::isForegroundProcess() throw()
  206578. {
  206579. HWND fg = GetForegroundWindow();
  206580. if (fg == 0)
  206581. return true;
  206582. DWORD processId = 0;
  206583. GetWindowThreadProcessId (fg, &processId);
  206584. return processId == GetCurrentProcessId();
  206585. }
  206586. void Desktop::getMousePosition (int& x, int& y) throw()
  206587. {
  206588. POINT mousePos;
  206589. GetCursorPos (&mousePos);
  206590. x = mousePos.x;
  206591. y = mousePos.y;
  206592. }
  206593. void Desktop::setMousePosition (int x, int y) throw()
  206594. {
  206595. SetCursorPos (x, y);
  206596. }
  206597. void Desktop::setScreenSaverEnabled (const bool isEnabled) throw()
  206598. {
  206599. screenSaverAllowed = isEnabled;
  206600. }
  206601. bool Desktop::isScreenSaverEnabled() throw()
  206602. {
  206603. return screenSaverAllowed;
  206604. }
  206605. static BOOL CALLBACK enumMonitorsProc (HMONITOR, HDC, LPRECT r, LPARAM userInfo)
  206606. {
  206607. Array <Rectangle>* const monitorCoords = (Array <Rectangle>*) userInfo;
  206608. monitorCoords->add (Rectangle (r->left, r->top, r->right - r->left, r->bottom - r->top));
  206609. return TRUE;
  206610. }
  206611. void juce_updateMultiMonitorInfo (Array <Rectangle>& monitorCoords, const bool clipToWorkArea) throw()
  206612. {
  206613. EnumDisplayMonitors (0, 0, &enumMonitorsProc, (LPARAM) &monitorCoords);
  206614. // make sure the first in the list is the main monitor
  206615. for (int i = 1; i < monitorCoords.size(); ++i)
  206616. if (monitorCoords[i].getX() == 0 && monitorCoords[i].getY() == 0)
  206617. monitorCoords.swap (i, 0);
  206618. if (monitorCoords.size() == 0)
  206619. {
  206620. RECT r;
  206621. GetWindowRect (GetDesktopWindow(), &r);
  206622. monitorCoords.add (Rectangle (r.left, r.top, r.right - r.left, r.bottom - r.top));
  206623. }
  206624. if (clipToWorkArea)
  206625. {
  206626. // clip the main monitor to the active non-taskbar area
  206627. RECT r;
  206628. SystemParametersInfo (SPI_GETWORKAREA, 0, &r, 0);
  206629. Rectangle& screen = monitorCoords.getReference (0);
  206630. screen.setPosition (jmax (screen.getX(), r.left),
  206631. jmax (screen.getY(), r.top));
  206632. screen.setSize (jmin (screen.getRight(), r.right) - screen.getX(),
  206633. jmin (screen.getBottom(), r.bottom) - screen.getY());
  206634. }
  206635. }
  206636. static Image* createImageFromHBITMAP (HBITMAP bitmap) throw()
  206637. {
  206638. Image* im = 0;
  206639. if (bitmap != 0)
  206640. {
  206641. BITMAP bm;
  206642. if (GetObject (bitmap, sizeof (BITMAP), &bm)
  206643. && bm.bmWidth > 0 && bm.bmHeight > 0)
  206644. {
  206645. HDC tempDC = GetDC (0);
  206646. HDC dc = CreateCompatibleDC (tempDC);
  206647. ReleaseDC (0, tempDC);
  206648. SelectObject (dc, bitmap);
  206649. im = new Image (Image::ARGB, bm.bmWidth, bm.bmHeight, true);
  206650. for (int y = bm.bmHeight; --y >= 0;)
  206651. {
  206652. for (int x = bm.bmWidth; --x >= 0;)
  206653. {
  206654. COLORREF col = GetPixel (dc, x, y);
  206655. im->setPixelAt (x, y, Colour ((uint8) GetRValue (col),
  206656. (uint8) GetGValue (col),
  206657. (uint8) GetBValue (col)));
  206658. }
  206659. }
  206660. DeleteDC (dc);
  206661. }
  206662. }
  206663. return im;
  206664. }
  206665. static Image* createImageFromHICON (HICON icon) throw()
  206666. {
  206667. ICONINFO info;
  206668. if (GetIconInfo (icon, &info))
  206669. {
  206670. Image* const mask = createImageFromHBITMAP (info.hbmMask);
  206671. if (mask == 0)
  206672. return 0;
  206673. Image* const image = createImageFromHBITMAP (info.hbmColor);
  206674. if (image == 0)
  206675. return mask;
  206676. for (int y = image->getHeight(); --y >= 0;)
  206677. {
  206678. for (int x = image->getWidth(); --x >= 0;)
  206679. {
  206680. const float brightness = mask->getPixelAt (x, y).getBrightness();
  206681. if (brightness > 0.0f)
  206682. image->multiplyAlphaAt (x, y, 1.0f - brightness);
  206683. }
  206684. }
  206685. delete mask;
  206686. return image;
  206687. }
  206688. return 0;
  206689. }
  206690. static HICON createHICONFromImage (const Image& image, const BOOL isIcon, int hotspotX, int hotspotY) throw()
  206691. {
  206692. HBITMAP mask = CreateBitmap (image.getWidth(), image.getHeight(), 1, 1, 0);
  206693. ICONINFO info;
  206694. info.fIcon = isIcon;
  206695. info.xHotspot = hotspotX;
  206696. info.yHotspot = hotspotY;
  206697. info.hbmMask = mask;
  206698. HICON hi = 0;
  206699. if (SystemStats::getOperatingSystemType() >= SystemStats::WinXP)
  206700. {
  206701. WindowsBitmapImage bitmap (Image::ARGB, image.getWidth(), image.getHeight(), true);
  206702. Graphics g (bitmap);
  206703. g.drawImageAt (&image, 0, 0);
  206704. info.hbmColor = bitmap.hBitmap;
  206705. hi = CreateIconIndirect (&info);
  206706. }
  206707. else
  206708. {
  206709. HBITMAP colour = CreateCompatibleBitmap (GetDC (0), image.getWidth(), image.getHeight());
  206710. HDC colDC = CreateCompatibleDC (GetDC (0));
  206711. HDC alphaDC = CreateCompatibleDC (GetDC (0));
  206712. SelectObject (colDC, colour);
  206713. SelectObject (alphaDC, mask);
  206714. for (int y = image.getHeight(); --y >= 0;)
  206715. {
  206716. for (int x = image.getWidth(); --x >= 0;)
  206717. {
  206718. const Colour c (image.getPixelAt (x, y));
  206719. SetPixel (colDC, x, y, COLORREF (c.getRed() | (c.getGreen() << 8) | (c.getBlue() << 16)));
  206720. SetPixel (alphaDC, x, y, COLORREF (0xffffff - (c.getAlpha() | (c.getAlpha() << 8) | (c.getAlpha() << 16))));
  206721. }
  206722. }
  206723. DeleteDC (colDC);
  206724. DeleteDC (alphaDC);
  206725. info.hbmColor = colour;
  206726. hi = CreateIconIndirect (&info);
  206727. DeleteObject (colour);
  206728. }
  206729. DeleteObject (mask);
  206730. return hi;
  206731. }
  206732. Image* juce_createIconForFile (const File& file)
  206733. {
  206734. Image* image = 0;
  206735. TCHAR filename [1024];
  206736. file.getFullPathName().copyToBuffer (filename, 1023);
  206737. WORD iconNum = 0;
  206738. HICON icon = ExtractAssociatedIcon ((HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle(),
  206739. filename, &iconNum);
  206740. if (icon != 0)
  206741. {
  206742. image = createImageFromHICON (icon);
  206743. DestroyIcon (icon);
  206744. }
  206745. return image;
  206746. }
  206747. void* juce_createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) throw()
  206748. {
  206749. const int maxW = GetSystemMetrics (SM_CXCURSOR);
  206750. const int maxH = GetSystemMetrics (SM_CYCURSOR);
  206751. const Image* im = &image;
  206752. Image* newIm = 0;
  206753. if (image.getWidth() > maxW || image.getHeight() > maxH)
  206754. {
  206755. im = newIm = image.createCopy (maxW, maxH);
  206756. hotspotX = (hotspotX * maxW) / image.getWidth();
  206757. hotspotY = (hotspotY * maxH) / image.getHeight();
  206758. }
  206759. void* cursorH = 0;
  206760. const SystemStats::OperatingSystemType os = SystemStats::getOperatingSystemType();
  206761. if (os == SystemStats::WinXP)
  206762. {
  206763. cursorH = (void*) createHICONFromImage (*im, FALSE, hotspotX, hotspotY);
  206764. }
  206765. else
  206766. {
  206767. const int stride = (maxW + 7) >> 3;
  206768. uint8* const andPlane = (uint8*) juce_calloc (stride * maxH);
  206769. uint8* const xorPlane = (uint8*) juce_calloc (stride * maxH);
  206770. int index = 0;
  206771. for (int y = 0; y < maxH; ++y)
  206772. {
  206773. for (int x = 0; x < maxW; ++x)
  206774. {
  206775. const unsigned char bit = (unsigned char) (1 << (7 - (x & 7)));
  206776. const Colour pixelColour (im->getPixelAt (x, y));
  206777. if (pixelColour.getAlpha() < 127)
  206778. andPlane [index + (x >> 3)] |= bit;
  206779. else if (pixelColour.getBrightness() >= 0.5f)
  206780. xorPlane [index + (x >> 3)] |= bit;
  206781. }
  206782. index += stride;
  206783. }
  206784. cursorH = CreateCursor (0, hotspotX, hotspotY, maxW, maxH, andPlane, xorPlane);
  206785. juce_free (andPlane);
  206786. juce_free (xorPlane);
  206787. }
  206788. delete newIm;
  206789. return cursorH;
  206790. }
  206791. void juce_deleteMouseCursor (void* const cursorHandle, const bool isStandard) throw()
  206792. {
  206793. if (cursorHandle != 0 && ! isStandard)
  206794. DestroyCursor ((HCURSOR) cursorHandle);
  206795. }
  206796. void* juce_createStandardMouseCursor (MouseCursor::StandardCursorType type) throw()
  206797. {
  206798. LPCTSTR cursorName = IDC_ARROW;
  206799. switch (type)
  206800. {
  206801. case MouseCursor::NormalCursor:
  206802. cursorName = IDC_ARROW;
  206803. break;
  206804. case MouseCursor::NoCursor:
  206805. return 0;
  206806. case MouseCursor::DraggingHandCursor:
  206807. {
  206808. static void* dragHandCursor = 0;
  206809. if (dragHandCursor == 0)
  206810. {
  206811. static const unsigned char dragHandData[] =
  206812. { 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,
  206813. 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,
  206814. 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 };
  206815. Image* const image = ImageFileFormat::loadFrom ((const char*) dragHandData, sizeof (dragHandData));
  206816. dragHandCursor = juce_createMouseCursorFromImage (*image, 8, 7);
  206817. delete image;
  206818. }
  206819. return dragHandCursor;
  206820. }
  206821. case MouseCursor::WaitCursor:
  206822. cursorName = IDC_WAIT;
  206823. break;
  206824. case MouseCursor::IBeamCursor:
  206825. cursorName = IDC_IBEAM;
  206826. break;
  206827. case MouseCursor::PointingHandCursor:
  206828. cursorName = MAKEINTRESOURCE(32649);
  206829. break;
  206830. case MouseCursor::LeftRightResizeCursor:
  206831. case MouseCursor::LeftEdgeResizeCursor:
  206832. case MouseCursor::RightEdgeResizeCursor:
  206833. cursorName = IDC_SIZEWE;
  206834. break;
  206835. case MouseCursor::UpDownResizeCursor:
  206836. case MouseCursor::TopEdgeResizeCursor:
  206837. case MouseCursor::BottomEdgeResizeCursor:
  206838. cursorName = IDC_SIZENS;
  206839. break;
  206840. case MouseCursor::TopLeftCornerResizeCursor:
  206841. case MouseCursor::BottomRightCornerResizeCursor:
  206842. cursorName = IDC_SIZENWSE;
  206843. break;
  206844. case MouseCursor::TopRightCornerResizeCursor:
  206845. case MouseCursor::BottomLeftCornerResizeCursor:
  206846. cursorName = IDC_SIZENESW;
  206847. break;
  206848. case MouseCursor::UpDownLeftRightResizeCursor:
  206849. cursorName = IDC_SIZEALL;
  206850. break;
  206851. case MouseCursor::CrosshairCursor:
  206852. cursorName = IDC_CROSS;
  206853. break;
  206854. case MouseCursor::CopyingCursor:
  206855. // can't seem to find one of these in the win32 list..
  206856. break;
  206857. }
  206858. HCURSOR cursorH = LoadCursor (0, cursorName);
  206859. if (cursorH == 0)
  206860. cursorH = LoadCursor (0, IDC_ARROW);
  206861. return (void*) cursorH;
  206862. }
  206863. void MouseCursor::showInWindow (ComponentPeer*) const throw()
  206864. {
  206865. SetCursor ((HCURSOR) getHandle());
  206866. }
  206867. void MouseCursor::showInAllWindows() const throw()
  206868. {
  206869. showInWindow (0);
  206870. }
  206871. class JuceDropSource : public IDropSource
  206872. {
  206873. int refCount;
  206874. public:
  206875. JuceDropSource()
  206876. : refCount (1)
  206877. {
  206878. }
  206879. virtual ~JuceDropSource()
  206880. {
  206881. jassert (refCount == 0);
  206882. }
  206883. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  206884. {
  206885. if (id == IID_IUnknown || id == IID_IDropSource)
  206886. {
  206887. AddRef();
  206888. *result = this;
  206889. return S_OK;
  206890. }
  206891. *result = 0;
  206892. return E_NOINTERFACE;
  206893. }
  206894. ULONG __stdcall AddRef() { return ++refCount; }
  206895. ULONG __stdcall Release() { jassert (refCount > 0); const int r = --refCount; if (r == 0) delete this; return r; }
  206896. HRESULT __stdcall QueryContinueDrag (BOOL escapePressed, DWORD keys)
  206897. {
  206898. if (escapePressed)
  206899. return DRAGDROP_S_CANCEL;
  206900. if ((keys & (MK_LBUTTON | MK_RBUTTON)) == 0)
  206901. return DRAGDROP_S_DROP;
  206902. return S_OK;
  206903. }
  206904. HRESULT __stdcall GiveFeedback (DWORD)
  206905. {
  206906. return DRAGDROP_S_USEDEFAULTCURSORS;
  206907. }
  206908. };
  206909. class JuceEnumFormatEtc : public IEnumFORMATETC
  206910. {
  206911. public:
  206912. JuceEnumFormatEtc (const FORMATETC* const format_)
  206913. : refCount (1),
  206914. format (format_),
  206915. index (0)
  206916. {
  206917. }
  206918. virtual ~JuceEnumFormatEtc()
  206919. {
  206920. jassert (refCount == 0);
  206921. }
  206922. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  206923. {
  206924. if (id == IID_IUnknown || id == IID_IEnumFORMATETC)
  206925. {
  206926. AddRef();
  206927. *result = this;
  206928. return S_OK;
  206929. }
  206930. *result = 0;
  206931. return E_NOINTERFACE;
  206932. }
  206933. ULONG __stdcall AddRef() { return ++refCount; }
  206934. ULONG __stdcall Release() { jassert (refCount > 0); const int r = --refCount; if (r == 0) delete this; return r; }
  206935. HRESULT __stdcall Clone (IEnumFORMATETC** result)
  206936. {
  206937. if (result == 0)
  206938. return E_POINTER;
  206939. JuceEnumFormatEtc* const newOne = new JuceEnumFormatEtc (format);
  206940. newOne->index = index;
  206941. *result = newOne;
  206942. return S_OK;
  206943. }
  206944. HRESULT __stdcall Next (ULONG celt, LPFORMATETC lpFormatEtc, ULONG* pceltFetched)
  206945. {
  206946. if (pceltFetched != 0)
  206947. *pceltFetched = 0;
  206948. else if (celt != 1)
  206949. return S_FALSE;
  206950. if (index == 0 && celt > 0 && lpFormatEtc != 0)
  206951. {
  206952. copyFormatEtc (lpFormatEtc [0], *format);
  206953. ++index;
  206954. if (pceltFetched != 0)
  206955. *pceltFetched = 1;
  206956. return S_OK;
  206957. }
  206958. return S_FALSE;
  206959. }
  206960. HRESULT __stdcall Skip (ULONG celt)
  206961. {
  206962. if (index + (int) celt >= 1)
  206963. return S_FALSE;
  206964. index += celt;
  206965. return S_OK;
  206966. }
  206967. HRESULT __stdcall Reset()
  206968. {
  206969. index = 0;
  206970. return S_OK;
  206971. }
  206972. private:
  206973. int refCount;
  206974. const FORMATETC* const format;
  206975. int index;
  206976. static void copyFormatEtc (FORMATETC& dest, const FORMATETC& source)
  206977. {
  206978. dest = source;
  206979. if (source.ptd != 0)
  206980. {
  206981. dest.ptd = (DVTARGETDEVICE*) CoTaskMemAlloc (sizeof (DVTARGETDEVICE));
  206982. *(dest.ptd) = *(source.ptd);
  206983. }
  206984. }
  206985. JuceEnumFormatEtc (const JuceEnumFormatEtc&);
  206986. const JuceEnumFormatEtc& operator= (const JuceEnumFormatEtc&);
  206987. };
  206988. class JuceDataObject : public IDataObject
  206989. {
  206990. JuceDropSource* const dropSource;
  206991. const FORMATETC* const format;
  206992. const STGMEDIUM* const medium;
  206993. int refCount;
  206994. JuceDataObject (const JuceDataObject&);
  206995. const JuceDataObject& operator= (const JuceDataObject&);
  206996. public:
  206997. JuceDataObject (JuceDropSource* const dropSource_,
  206998. const FORMATETC* const format_,
  206999. const STGMEDIUM* const medium_)
  207000. : dropSource (dropSource_),
  207001. format (format_),
  207002. medium (medium_),
  207003. refCount (1)
  207004. {
  207005. }
  207006. virtual ~JuceDataObject()
  207007. {
  207008. jassert (refCount == 0);
  207009. }
  207010. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  207011. {
  207012. if (id == IID_IUnknown || id == IID_IDataObject)
  207013. {
  207014. AddRef();
  207015. *result = this;
  207016. return S_OK;
  207017. }
  207018. *result = 0;
  207019. return E_NOINTERFACE;
  207020. }
  207021. ULONG __stdcall AddRef() { return ++refCount; }
  207022. ULONG __stdcall Release() { jassert (refCount > 0); const int r = --refCount; if (r == 0) delete this; return r; }
  207023. HRESULT __stdcall GetData (FORMATETC __RPC_FAR* pFormatEtc, STGMEDIUM __RPC_FAR* pMedium)
  207024. {
  207025. if (pFormatEtc->tymed == format->tymed
  207026. && pFormatEtc->cfFormat == format->cfFormat
  207027. && pFormatEtc->dwAspect == format->dwAspect)
  207028. {
  207029. pMedium->tymed = format->tymed;
  207030. pMedium->pUnkForRelease = 0;
  207031. if (format->tymed == TYMED_HGLOBAL)
  207032. {
  207033. const SIZE_T len = GlobalSize (medium->hGlobal);
  207034. void* const src = GlobalLock (medium->hGlobal);
  207035. void* const dst = GlobalAlloc (GMEM_FIXED, len);
  207036. memcpy (dst, src, len);
  207037. GlobalUnlock (medium->hGlobal);
  207038. pMedium->hGlobal = dst;
  207039. return S_OK;
  207040. }
  207041. }
  207042. return DV_E_FORMATETC;
  207043. }
  207044. HRESULT __stdcall QueryGetData (FORMATETC __RPC_FAR* f)
  207045. {
  207046. if (f == 0)
  207047. return E_INVALIDARG;
  207048. if (f->tymed == format->tymed
  207049. && f->cfFormat == format->cfFormat
  207050. && f->dwAspect == format->dwAspect)
  207051. return S_OK;
  207052. return DV_E_FORMATETC;
  207053. }
  207054. HRESULT __stdcall GetCanonicalFormatEtc (FORMATETC __RPC_FAR*, FORMATETC __RPC_FAR* pFormatEtcOut)
  207055. {
  207056. pFormatEtcOut->ptd = 0;
  207057. return E_NOTIMPL;
  207058. }
  207059. HRESULT __stdcall EnumFormatEtc (DWORD direction, IEnumFORMATETC __RPC_FAR *__RPC_FAR *result)
  207060. {
  207061. if (result == 0)
  207062. return E_POINTER;
  207063. if (direction == DATADIR_GET)
  207064. {
  207065. *result = new JuceEnumFormatEtc (format);
  207066. return S_OK;
  207067. }
  207068. *result = 0;
  207069. return E_NOTIMPL;
  207070. }
  207071. HRESULT __stdcall GetDataHere (FORMATETC __RPC_FAR*, STGMEDIUM __RPC_FAR*) { return DATA_E_FORMATETC; }
  207072. HRESULT __stdcall SetData (FORMATETC __RPC_FAR*, STGMEDIUM __RPC_FAR*, BOOL) { return E_NOTIMPL; }
  207073. HRESULT __stdcall DAdvise (FORMATETC __RPC_FAR*, DWORD, IAdviseSink __RPC_FAR*, DWORD __RPC_FAR*) { return OLE_E_ADVISENOTSUPPORTED; }
  207074. HRESULT __stdcall DUnadvise (DWORD) { return E_NOTIMPL; }
  207075. HRESULT __stdcall EnumDAdvise (IEnumSTATDATA __RPC_FAR *__RPC_FAR *) { return OLE_E_ADVISENOTSUPPORTED; }
  207076. };
  207077. static HDROP createHDrop (const StringArray& fileNames) throw()
  207078. {
  207079. int totalChars = 0;
  207080. for (int i = fileNames.size(); --i >= 0;)
  207081. totalChars += fileNames[i].length() + 1;
  207082. HDROP hDrop = (HDROP) GlobalAlloc (GMEM_MOVEABLE | GMEM_ZEROINIT,
  207083. sizeof (DROPFILES)
  207084. + sizeof (WCHAR) * (totalChars + 2));
  207085. if (hDrop != 0)
  207086. {
  207087. LPDROPFILES pDropFiles = (LPDROPFILES) GlobalLock (hDrop);
  207088. pDropFiles->pFiles = sizeof (DROPFILES);
  207089. pDropFiles->fWide = true;
  207090. WCHAR* fname = (WCHAR*) (((char*) pDropFiles) + sizeof (DROPFILES));
  207091. for (int i = 0; i < fileNames.size(); ++i)
  207092. {
  207093. fileNames[i].copyToBuffer (fname, 2048);
  207094. fname += fileNames[i].length() + 1;
  207095. }
  207096. *fname = 0;
  207097. GlobalUnlock (hDrop);
  207098. }
  207099. return hDrop;
  207100. }
  207101. static bool performDragDrop (FORMATETC* const format, STGMEDIUM* const medium, const DWORD whatToDo) throw()
  207102. {
  207103. JuceDropSource* const source = new JuceDropSource();
  207104. JuceDataObject* const data = new JuceDataObject (source, format, medium);
  207105. DWORD effect;
  207106. const HRESULT res = DoDragDrop (data, source, whatToDo, &effect);
  207107. data->Release();
  207108. source->Release();
  207109. return res == DRAGDROP_S_DROP;
  207110. }
  207111. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMove)
  207112. {
  207113. FORMATETC format = { CF_HDROP, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  207114. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  207115. medium.hGlobal = createHDrop (files);
  207116. return performDragDrop (&format, &medium, canMove ? (DROPEFFECT_COPY | DROPEFFECT_MOVE)
  207117. : DROPEFFECT_COPY);
  207118. }
  207119. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  207120. {
  207121. FORMATETC format = { CF_TEXT, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  207122. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  207123. const int numChars = text.length();
  207124. medium.hGlobal = GlobalAlloc (GMEM_MOVEABLE | GMEM_ZEROINIT, (numChars + 2) * sizeof (WCHAR));
  207125. char* d = (char*) GlobalLock (medium.hGlobal);
  207126. text.copyToBuffer ((WCHAR*) d, numChars + 1);
  207127. format.cfFormat = CF_UNICODETEXT;
  207128. GlobalUnlock (medium.hGlobal);
  207129. return performDragDrop (&format, &medium, DROPEFFECT_COPY | DROPEFFECT_MOVE);
  207130. }
  207131. #if JUCE_OPENGL
  207132. #define WGL_EXT_FUNCTION_INIT(extType, extFunc) \
  207133. ((extFunc = (extType) wglGetProcAddress (#extFunc)) != 0)
  207134. typedef const char* (WINAPI* PFNWGLGETEXTENSIONSSTRINGARBPROC) (HDC hdc);
  207135. typedef BOOL (WINAPI * PFNWGLGETPIXELFORMATATTRIBIVARBPROC) (HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, const int *piAttributes, int *piValues);
  207136. typedef BOOL (WINAPI * PFNWGLCHOOSEPIXELFORMATARBPROC) (HDC hdc, const int* piAttribIList, const FLOAT *pfAttribFList, UINT nMaxFormats, int *piFormats, UINT *nNumFormats);
  207137. typedef BOOL (WINAPI * PFNWGLSWAPINTERVALEXTPROC) (int interval);
  207138. typedef int (WINAPI * PFNWGLGETSWAPINTERVALEXTPROC) (void);
  207139. #define WGL_NUMBER_PIXEL_FORMATS_ARB 0x2000
  207140. #define WGL_DRAW_TO_WINDOW_ARB 0x2001
  207141. #define WGL_ACCELERATION_ARB 0x2003
  207142. #define WGL_SWAP_METHOD_ARB 0x2007
  207143. #define WGL_SUPPORT_OPENGL_ARB 0x2010
  207144. #define WGL_PIXEL_TYPE_ARB 0x2013
  207145. #define WGL_DOUBLE_BUFFER_ARB 0x2011
  207146. #define WGL_COLOR_BITS_ARB 0x2014
  207147. #define WGL_RED_BITS_ARB 0x2015
  207148. #define WGL_GREEN_BITS_ARB 0x2017
  207149. #define WGL_BLUE_BITS_ARB 0x2019
  207150. #define WGL_ALPHA_BITS_ARB 0x201B
  207151. #define WGL_DEPTH_BITS_ARB 0x2022
  207152. #define WGL_STENCIL_BITS_ARB 0x2023
  207153. #define WGL_FULL_ACCELERATION_ARB 0x2027
  207154. #define WGL_ACCUM_RED_BITS_ARB 0x201E
  207155. #define WGL_ACCUM_GREEN_BITS_ARB 0x201F
  207156. #define WGL_ACCUM_BLUE_BITS_ARB 0x2020
  207157. #define WGL_ACCUM_ALPHA_BITS_ARB 0x2021
  207158. #define WGL_STEREO_ARB 0x2012
  207159. #define WGL_SAMPLE_BUFFERS_ARB 0x2041
  207160. #define WGL_SAMPLES_ARB 0x2042
  207161. #define WGL_TYPE_RGBA_ARB 0x202B
  207162. static void getWglExtensions (HDC dc, StringArray& result) throw()
  207163. {
  207164. PFNWGLGETEXTENSIONSSTRINGARBPROC wglGetExtensionsStringARB = 0;
  207165. if (WGL_EXT_FUNCTION_INIT (PFNWGLGETEXTENSIONSSTRINGARBPROC, wglGetExtensionsStringARB))
  207166. result.addTokens (String (wglGetExtensionsStringARB (dc)), false);
  207167. else
  207168. jassertfalse // If this fails, it may be because you didn't activate the openGL context
  207169. }
  207170. class WindowedGLContext : public OpenGLContext
  207171. {
  207172. public:
  207173. WindowedGLContext (Component* const component_,
  207174. HGLRC contextToShareWith,
  207175. const OpenGLPixelFormat& pixelFormat)
  207176. : renderContext (0),
  207177. nativeWindow (0),
  207178. dc (0),
  207179. component (component_)
  207180. {
  207181. jassert (component != 0);
  207182. createNativeWindow();
  207183. // Use a default pixel format that should be supported everywhere
  207184. PIXELFORMATDESCRIPTOR pfd;
  207185. zerostruct (pfd);
  207186. pfd.nSize = sizeof (pfd);
  207187. pfd.nVersion = 1;
  207188. pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
  207189. pfd.iPixelType = PFD_TYPE_RGBA;
  207190. pfd.cColorBits = 24;
  207191. pfd.cDepthBits = 16;
  207192. const int format = ChoosePixelFormat (dc, &pfd);
  207193. if (format != 0)
  207194. SetPixelFormat (dc, format, &pfd);
  207195. renderContext = wglCreateContext (dc);
  207196. makeActive();
  207197. setPixelFormat (pixelFormat);
  207198. if (contextToShareWith != 0 && renderContext != 0)
  207199. wglShareLists (contextToShareWith, renderContext);
  207200. }
  207201. ~WindowedGLContext()
  207202. {
  207203. makeInactive();
  207204. wglDeleteContext (renderContext);
  207205. ReleaseDC ((HWND) nativeWindow->getNativeHandle(), dc);
  207206. delete nativeWindow;
  207207. }
  207208. bool makeActive() const throw()
  207209. {
  207210. jassert (renderContext != 0);
  207211. return wglMakeCurrent (dc, renderContext) != 0;
  207212. }
  207213. bool makeInactive() const throw()
  207214. {
  207215. return (! isActive()) || (wglMakeCurrent (0, 0) != 0);
  207216. }
  207217. bool isActive() const throw()
  207218. {
  207219. return wglGetCurrentContext() == renderContext;
  207220. }
  207221. const OpenGLPixelFormat getPixelFormat() const
  207222. {
  207223. OpenGLPixelFormat pf;
  207224. makeActive();
  207225. StringArray availableExtensions;
  207226. getWglExtensions (dc, availableExtensions);
  207227. fillInPixelFormatDetails (GetPixelFormat (dc), pf, availableExtensions);
  207228. return pf;
  207229. }
  207230. void* getRawContext() const throw()
  207231. {
  207232. return renderContext;
  207233. }
  207234. bool setPixelFormat (const OpenGLPixelFormat& pixelFormat)
  207235. {
  207236. makeActive();
  207237. PIXELFORMATDESCRIPTOR pfd;
  207238. zerostruct (pfd);
  207239. pfd.nSize = sizeof (pfd);
  207240. pfd.nVersion = 1;
  207241. pfd.dwFlags = PFD_SUPPORT_OPENGL | PFD_DRAW_TO_WINDOW | PFD_DOUBLEBUFFER;
  207242. pfd.iPixelType = PFD_TYPE_RGBA;
  207243. pfd.iLayerType = PFD_MAIN_PLANE;
  207244. pfd.cColorBits = pixelFormat.redBits + pixelFormat.greenBits + pixelFormat.blueBits;
  207245. pfd.cRedBits = pixelFormat.redBits;
  207246. pfd.cGreenBits = pixelFormat.greenBits;
  207247. pfd.cBlueBits = pixelFormat.blueBits;
  207248. pfd.cAlphaBits = pixelFormat.alphaBits;
  207249. pfd.cDepthBits = pixelFormat.depthBufferBits;
  207250. pfd.cStencilBits = pixelFormat.stencilBufferBits;
  207251. pfd.cAccumBits = pixelFormat.accumulationBufferRedBits + pixelFormat.accumulationBufferGreenBits
  207252. + pixelFormat.accumulationBufferBlueBits + pixelFormat.accumulationBufferAlphaBits;
  207253. pfd.cAccumRedBits = pixelFormat.accumulationBufferRedBits;
  207254. pfd.cAccumGreenBits = pixelFormat.accumulationBufferGreenBits;
  207255. pfd.cAccumBlueBits = pixelFormat.accumulationBufferBlueBits;
  207256. pfd.cAccumAlphaBits = pixelFormat.accumulationBufferAlphaBits;
  207257. int format = 0;
  207258. PFNWGLCHOOSEPIXELFORMATARBPROC wglChoosePixelFormatARB = 0;
  207259. StringArray availableExtensions;
  207260. getWglExtensions (dc, availableExtensions);
  207261. if (availableExtensions.contains ("WGL_ARB_pixel_format")
  207262. && WGL_EXT_FUNCTION_INIT (PFNWGLCHOOSEPIXELFORMATARBPROC, wglChoosePixelFormatARB))
  207263. {
  207264. int attributes[64];
  207265. int n = 0;
  207266. attributes[n++] = WGL_DRAW_TO_WINDOW_ARB;
  207267. attributes[n++] = GL_TRUE;
  207268. attributes[n++] = WGL_SUPPORT_OPENGL_ARB;
  207269. attributes[n++] = GL_TRUE;
  207270. attributes[n++] = WGL_ACCELERATION_ARB;
  207271. attributes[n++] = WGL_FULL_ACCELERATION_ARB;
  207272. attributes[n++] = WGL_DOUBLE_BUFFER_ARB;
  207273. attributes[n++] = GL_TRUE;
  207274. attributes[n++] = WGL_PIXEL_TYPE_ARB;
  207275. attributes[n++] = WGL_TYPE_RGBA_ARB;
  207276. attributes[n++] = WGL_COLOR_BITS_ARB;
  207277. attributes[n++] = pfd.cColorBits;
  207278. attributes[n++] = WGL_RED_BITS_ARB;
  207279. attributes[n++] = pixelFormat.redBits;
  207280. attributes[n++] = WGL_GREEN_BITS_ARB;
  207281. attributes[n++] = pixelFormat.greenBits;
  207282. attributes[n++] = WGL_BLUE_BITS_ARB;
  207283. attributes[n++] = pixelFormat.blueBits;
  207284. attributes[n++] = WGL_ALPHA_BITS_ARB;
  207285. attributes[n++] = pixelFormat.alphaBits;
  207286. attributes[n++] = WGL_DEPTH_BITS_ARB;
  207287. attributes[n++] = pixelFormat.depthBufferBits;
  207288. if (pixelFormat.stencilBufferBits > 0)
  207289. {
  207290. attributes[n++] = WGL_STENCIL_BITS_ARB;
  207291. attributes[n++] = pixelFormat.stencilBufferBits;
  207292. }
  207293. attributes[n++] = WGL_ACCUM_RED_BITS_ARB;
  207294. attributes[n++] = pixelFormat.accumulationBufferRedBits;
  207295. attributes[n++] = WGL_ACCUM_GREEN_BITS_ARB;
  207296. attributes[n++] = pixelFormat.accumulationBufferGreenBits;
  207297. attributes[n++] = WGL_ACCUM_BLUE_BITS_ARB;
  207298. attributes[n++] = pixelFormat.accumulationBufferBlueBits;
  207299. attributes[n++] = WGL_ACCUM_ALPHA_BITS_ARB;
  207300. attributes[n++] = pixelFormat.accumulationBufferAlphaBits;
  207301. if (availableExtensions.contains ("WGL_ARB_multisample")
  207302. && pixelFormat.fullSceneAntiAliasingNumSamples > 0)
  207303. {
  207304. attributes[n++] = WGL_SAMPLE_BUFFERS_ARB;
  207305. attributes[n++] = 1;
  207306. attributes[n++] = WGL_SAMPLES_ARB;
  207307. attributes[n++] = pixelFormat.fullSceneAntiAliasingNumSamples;
  207308. }
  207309. attributes[n++] = 0;
  207310. UINT formatsCount;
  207311. const BOOL ok = wglChoosePixelFormatARB (dc, attributes, 0, 1, &format, &formatsCount);
  207312. (void) ok;
  207313. jassert (ok);
  207314. }
  207315. else
  207316. {
  207317. format = ChoosePixelFormat (dc, &pfd);
  207318. }
  207319. if (format != 0)
  207320. {
  207321. makeInactive();
  207322. // win32 can't change the pixel format of a window, so need to delete the
  207323. // old one and create a new one..
  207324. jassert (nativeWindow != 0);
  207325. ReleaseDC ((HWND) nativeWindow->getNativeHandle(), dc);
  207326. delete nativeWindow;
  207327. createNativeWindow();
  207328. if (SetPixelFormat (dc, format, &pfd))
  207329. {
  207330. wglDeleteContext (renderContext);
  207331. renderContext = wglCreateContext (dc);
  207332. jassert (renderContext != 0);
  207333. return renderContext != 0;
  207334. }
  207335. }
  207336. return false;
  207337. }
  207338. void updateWindowPosition (int x, int y, int w, int h, int)
  207339. {
  207340. SetWindowPos ((HWND) nativeWindow->getNativeHandle(), 0,
  207341. x, y, w, h,
  207342. SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  207343. }
  207344. void repaint()
  207345. {
  207346. int x, y, w, h;
  207347. nativeWindow->getBounds (x, y, w, h);
  207348. nativeWindow->repaint (0, 0, w, h);
  207349. }
  207350. void swapBuffers()
  207351. {
  207352. SwapBuffers (dc);
  207353. }
  207354. bool setSwapInterval (const int numFramesPerSwap)
  207355. {
  207356. makeActive();
  207357. StringArray availableExtensions;
  207358. getWglExtensions (dc, availableExtensions);
  207359. PFNWGLSWAPINTERVALEXTPROC wglSwapIntervalEXT = 0;
  207360. return availableExtensions.contains ("WGL_EXT_swap_control")
  207361. && WGL_EXT_FUNCTION_INIT (PFNWGLSWAPINTERVALEXTPROC, wglSwapIntervalEXT)
  207362. && wglSwapIntervalEXT (numFramesPerSwap) != FALSE;
  207363. }
  207364. int getSwapInterval() const
  207365. {
  207366. makeActive();
  207367. StringArray availableExtensions;
  207368. getWglExtensions (dc, availableExtensions);
  207369. PFNWGLGETSWAPINTERVALEXTPROC wglGetSwapIntervalEXT = 0;
  207370. if (availableExtensions.contains ("WGL_EXT_swap_control")
  207371. && WGL_EXT_FUNCTION_INIT (PFNWGLGETSWAPINTERVALEXTPROC, wglGetSwapIntervalEXT))
  207372. return wglGetSwapIntervalEXT();
  207373. return 0;
  207374. }
  207375. void findAlternativeOpenGLPixelFormats (OwnedArray <OpenGLPixelFormat>& results)
  207376. {
  207377. jassert (isActive());
  207378. StringArray availableExtensions;
  207379. getWglExtensions (dc, availableExtensions);
  207380. PFNWGLGETPIXELFORMATATTRIBIVARBPROC wglGetPixelFormatAttribivARB = 0;
  207381. int numTypes = 0;
  207382. if (availableExtensions.contains("WGL_ARB_pixel_format")
  207383. && WGL_EXT_FUNCTION_INIT (PFNWGLGETPIXELFORMATATTRIBIVARBPROC, wglGetPixelFormatAttribivARB))
  207384. {
  207385. int attributes = WGL_NUMBER_PIXEL_FORMATS_ARB;
  207386. if (! wglGetPixelFormatAttribivARB (dc, 1, 0, 1, &attributes, &numTypes))
  207387. jassertfalse
  207388. }
  207389. else
  207390. {
  207391. numTypes = DescribePixelFormat (dc, 0, 0, 0);
  207392. }
  207393. OpenGLPixelFormat pf;
  207394. for (int i = 0; i < numTypes; ++i)
  207395. {
  207396. if (fillInPixelFormatDetails (i + 1, pf, availableExtensions))
  207397. {
  207398. bool alreadyListed = false;
  207399. for (int j = results.size(); --j >= 0;)
  207400. if (pf == *results.getUnchecked(j))
  207401. alreadyListed = true;
  207402. if (! alreadyListed)
  207403. results.add (new OpenGLPixelFormat (pf));
  207404. }
  207405. }
  207406. }
  207407. juce_UseDebuggingNewOperator
  207408. HGLRC renderContext;
  207409. private:
  207410. Win32ComponentPeer* nativeWindow;
  207411. Component* const component;
  207412. HDC dc;
  207413. void createNativeWindow()
  207414. {
  207415. nativeWindow = new Win32ComponentPeer (component, 0);
  207416. nativeWindow->dontRepaint = true;
  207417. nativeWindow->setVisible (true);
  207418. HWND hwnd = (HWND) nativeWindow->getNativeHandle();
  207419. Win32ComponentPeer* const peer = dynamic_cast <Win32ComponentPeer*> (component->getTopLevelComponent()->getPeer());
  207420. if (peer != 0)
  207421. {
  207422. SetParent (hwnd, (HWND) peer->getNativeHandle());
  207423. juce_setWindowStyleBit (hwnd, GWL_STYLE, WS_CHILD, true);
  207424. juce_setWindowStyleBit (hwnd, GWL_STYLE, WS_POPUP, false);
  207425. }
  207426. dc = GetDC (hwnd);
  207427. }
  207428. bool fillInPixelFormatDetails (const int pixelFormatIndex,
  207429. OpenGLPixelFormat& result,
  207430. const StringArray& availableExtensions) const throw()
  207431. {
  207432. PFNWGLGETPIXELFORMATATTRIBIVARBPROC wglGetPixelFormatAttribivARB = 0;
  207433. if (availableExtensions.contains ("WGL_ARB_pixel_format")
  207434. && WGL_EXT_FUNCTION_INIT (PFNWGLGETPIXELFORMATATTRIBIVARBPROC, wglGetPixelFormatAttribivARB))
  207435. {
  207436. int attributes[32];
  207437. int numAttributes = 0;
  207438. attributes[numAttributes++] = WGL_DRAW_TO_WINDOW_ARB;
  207439. attributes[numAttributes++] = WGL_SUPPORT_OPENGL_ARB;
  207440. attributes[numAttributes++] = WGL_ACCELERATION_ARB;
  207441. attributes[numAttributes++] = WGL_DOUBLE_BUFFER_ARB;
  207442. attributes[numAttributes++] = WGL_PIXEL_TYPE_ARB;
  207443. attributes[numAttributes++] = WGL_RED_BITS_ARB;
  207444. attributes[numAttributes++] = WGL_GREEN_BITS_ARB;
  207445. attributes[numAttributes++] = WGL_BLUE_BITS_ARB;
  207446. attributes[numAttributes++] = WGL_ALPHA_BITS_ARB;
  207447. attributes[numAttributes++] = WGL_DEPTH_BITS_ARB;
  207448. attributes[numAttributes++] = WGL_STENCIL_BITS_ARB;
  207449. attributes[numAttributes++] = WGL_ACCUM_RED_BITS_ARB;
  207450. attributes[numAttributes++] = WGL_ACCUM_GREEN_BITS_ARB;
  207451. attributes[numAttributes++] = WGL_ACCUM_BLUE_BITS_ARB;
  207452. attributes[numAttributes++] = WGL_ACCUM_ALPHA_BITS_ARB;
  207453. if (availableExtensions.contains ("WGL_ARB_multisample"))
  207454. attributes[numAttributes++] = WGL_SAMPLES_ARB;
  207455. int values[32];
  207456. zeromem (values, sizeof (values));
  207457. if (wglGetPixelFormatAttribivARB (dc, pixelFormatIndex, 0, numAttributes, attributes, values))
  207458. {
  207459. int n = 0;
  207460. bool isValidFormat = (values[n++] == GL_TRUE); // WGL_DRAW_TO_WINDOW_ARB
  207461. isValidFormat = (values[n++] == GL_TRUE) && isValidFormat; // WGL_SUPPORT_OPENGL_ARB
  207462. isValidFormat = (values[n++] == WGL_FULL_ACCELERATION_ARB) && isValidFormat; // WGL_ACCELERATION_ARB
  207463. isValidFormat = (values[n++] == GL_TRUE) && isValidFormat; // WGL_DOUBLE_BUFFER_ARB:
  207464. isValidFormat = (values[n++] == WGL_TYPE_RGBA_ARB) && isValidFormat; // WGL_PIXEL_TYPE_ARB
  207465. result.redBits = values[n++]; // WGL_RED_BITS_ARB
  207466. result.greenBits = values[n++]; // WGL_GREEN_BITS_ARB
  207467. result.blueBits = values[n++]; // WGL_BLUE_BITS_ARB
  207468. result.alphaBits = values[n++]; // WGL_ALPHA_BITS_ARB
  207469. result.depthBufferBits = values[n++]; // WGL_DEPTH_BITS_ARB
  207470. result.stencilBufferBits = values[n++]; // WGL_STENCIL_BITS_ARB
  207471. result.accumulationBufferRedBits = values[n++]; // WGL_ACCUM_RED_BITS_ARB
  207472. result.accumulationBufferGreenBits = values[n++]; // WGL_ACCUM_GREEN_BITS_ARB
  207473. result.accumulationBufferBlueBits = values[n++]; // WGL_ACCUM_BLUE_BITS_ARB
  207474. result.accumulationBufferAlphaBits = values[n++]; // WGL_ACCUM_ALPHA_BITS_ARB
  207475. result.fullSceneAntiAliasingNumSamples = values[n++]; // WGL_SAMPLES_ARB
  207476. return isValidFormat;
  207477. }
  207478. else
  207479. {
  207480. jassertfalse
  207481. }
  207482. }
  207483. else
  207484. {
  207485. PIXELFORMATDESCRIPTOR pfd;
  207486. if (DescribePixelFormat (dc, pixelFormatIndex, sizeof (pfd), &pfd))
  207487. {
  207488. result.redBits = pfd.cRedBits;
  207489. result.greenBits = pfd.cGreenBits;
  207490. result.blueBits = pfd.cBlueBits;
  207491. result.alphaBits = pfd.cAlphaBits;
  207492. result.depthBufferBits = pfd.cDepthBits;
  207493. result.stencilBufferBits = pfd.cStencilBits;
  207494. result.accumulationBufferRedBits = pfd.cAccumRedBits;
  207495. result.accumulationBufferGreenBits = pfd.cAccumGreenBits;
  207496. result.accumulationBufferBlueBits = pfd.cAccumBlueBits;
  207497. result.accumulationBufferAlphaBits = pfd.cAccumAlphaBits;
  207498. result.fullSceneAntiAliasingNumSamples = 0;
  207499. return true;
  207500. }
  207501. else
  207502. {
  207503. jassertfalse
  207504. }
  207505. }
  207506. return false;
  207507. }
  207508. WindowedGLContext (const WindowedGLContext&);
  207509. const WindowedGLContext& operator= (const WindowedGLContext&);
  207510. };
  207511. OpenGLContext* OpenGLContext::createContextForWindow (Component* const component,
  207512. const OpenGLPixelFormat& pixelFormat,
  207513. const OpenGLContext* const contextToShareWith)
  207514. {
  207515. WindowedGLContext* c = new WindowedGLContext (component,
  207516. contextToShareWith != 0 ? (HGLRC) contextToShareWith->getRawContext() : 0,
  207517. pixelFormat);
  207518. if (c->renderContext == 0)
  207519. deleteAndZero (c);
  207520. return c;
  207521. }
  207522. void juce_glViewport (const int w, const int h)
  207523. {
  207524. glViewport (0, 0, w, h);
  207525. }
  207526. void OpenGLPixelFormat::getAvailablePixelFormats (Component* component,
  207527. OwnedArray <OpenGLPixelFormat>& results)
  207528. {
  207529. Component tempComp;
  207530. {
  207531. WindowedGLContext wc (component, 0, OpenGLPixelFormat (8, 8, 16, 0));
  207532. wc.makeActive();
  207533. wc.findAlternativeOpenGLPixelFormats (results);
  207534. }
  207535. }
  207536. #endif
  207537. class JuceIStorage : public IStorage
  207538. {
  207539. int refCount;
  207540. public:
  207541. JuceIStorage() : refCount (1) {}
  207542. virtual ~JuceIStorage()
  207543. {
  207544. jassert (refCount == 0);
  207545. }
  207546. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  207547. {
  207548. if (id == IID_IUnknown || id == IID_IStorage)
  207549. {
  207550. AddRef();
  207551. *result = this;
  207552. return S_OK;
  207553. }
  207554. *result = 0;
  207555. return E_NOINTERFACE;
  207556. }
  207557. ULONG __stdcall AddRef() { return ++refCount; }
  207558. ULONG __stdcall Release() { const int r = --refCount; if (r == 0) delete this; return r; }
  207559. HRESULT __stdcall CreateStream (const WCHAR*, DWORD, DWORD, DWORD, IStream**) { return E_NOTIMPL; }
  207560. HRESULT __stdcall OpenStream (const WCHAR*, void*, DWORD, DWORD, IStream**) { return E_NOTIMPL; }
  207561. HRESULT __stdcall CreateStorage (const WCHAR*, DWORD, DWORD, DWORD, IStorage**) { return E_NOTIMPL; }
  207562. HRESULT __stdcall OpenStorage (const WCHAR*, IStorage*, DWORD, SNB, DWORD, IStorage**) { return E_NOTIMPL; }
  207563. HRESULT __stdcall CopyTo (DWORD, IID const*, SNB, IStorage*) { return E_NOTIMPL; }
  207564. HRESULT __stdcall MoveElementTo (const OLECHAR*,IStorage*, const OLECHAR*, DWORD) { return E_NOTIMPL; }
  207565. HRESULT __stdcall Commit (DWORD) { return E_NOTIMPL; }
  207566. HRESULT __stdcall Revert() { return E_NOTIMPL; }
  207567. HRESULT __stdcall EnumElements (DWORD, void*, DWORD, IEnumSTATSTG**) { return E_NOTIMPL; }
  207568. HRESULT __stdcall DestroyElement (const OLECHAR*) { return E_NOTIMPL; }
  207569. HRESULT __stdcall RenameElement (const WCHAR*, const WCHAR*) { return E_NOTIMPL; }
  207570. HRESULT __stdcall SetElementTimes (const WCHAR*, FILETIME const*, FILETIME const*, FILETIME const*) { return E_NOTIMPL; }
  207571. HRESULT __stdcall SetClass (REFCLSID) { return S_OK; }
  207572. HRESULT __stdcall SetStateBits (DWORD, DWORD) { return E_NOTIMPL; }
  207573. HRESULT __stdcall Stat (STATSTG*, DWORD) { return E_NOTIMPL; }
  207574. juce_UseDebuggingNewOperator
  207575. };
  207576. class JuceOleInPlaceFrame : public IOleInPlaceFrame
  207577. {
  207578. int refCount;
  207579. HWND window;
  207580. public:
  207581. JuceOleInPlaceFrame (HWND window_)
  207582. : refCount (1),
  207583. window (window_)
  207584. {
  207585. }
  207586. virtual ~JuceOleInPlaceFrame()
  207587. {
  207588. jassert (refCount == 0);
  207589. }
  207590. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  207591. {
  207592. if (id == IID_IUnknown || id == IID_IOleInPlaceFrame)
  207593. {
  207594. AddRef();
  207595. *result = this;
  207596. return S_OK;
  207597. }
  207598. *result = 0;
  207599. return E_NOINTERFACE;
  207600. }
  207601. ULONG __stdcall AddRef() { return ++refCount; }
  207602. ULONG __stdcall Release() { const int r = --refCount; if (r == 0) delete this; return r; }
  207603. HRESULT __stdcall GetWindow (HWND* lphwnd) { *lphwnd = window; return S_OK; }
  207604. HRESULT __stdcall ContextSensitiveHelp (BOOL) { return E_NOTIMPL; }
  207605. HRESULT __stdcall GetBorder (LPRECT) { return E_NOTIMPL; }
  207606. HRESULT __stdcall RequestBorderSpace (LPCBORDERWIDTHS) { return E_NOTIMPL; }
  207607. HRESULT __stdcall SetBorderSpace (LPCBORDERWIDTHS) { return E_NOTIMPL; }
  207608. HRESULT __stdcall SetActiveObject (IOleInPlaceActiveObject*, LPCOLESTR) { return S_OK; }
  207609. HRESULT __stdcall InsertMenus (HMENU, LPOLEMENUGROUPWIDTHS) { return E_NOTIMPL; }
  207610. HRESULT __stdcall SetMenu (HMENU, HOLEMENU, HWND) { return S_OK; }
  207611. HRESULT __stdcall RemoveMenus (HMENU) { return E_NOTIMPL; }
  207612. HRESULT __stdcall SetStatusText (LPCOLESTR) { return S_OK; }
  207613. HRESULT __stdcall EnableModeless (BOOL) { return S_OK; }
  207614. HRESULT __stdcall TranslateAccelerator(LPMSG, WORD) { return E_NOTIMPL; }
  207615. juce_UseDebuggingNewOperator
  207616. };
  207617. class JuceIOleInPlaceSite : public IOleInPlaceSite
  207618. {
  207619. int refCount;
  207620. HWND window;
  207621. JuceOleInPlaceFrame* frame;
  207622. public:
  207623. JuceIOleInPlaceSite (HWND window_)
  207624. : refCount (1),
  207625. window (window_)
  207626. {
  207627. frame = new JuceOleInPlaceFrame (window);
  207628. }
  207629. virtual ~JuceIOleInPlaceSite()
  207630. {
  207631. jassert (refCount == 0);
  207632. frame->Release();
  207633. }
  207634. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  207635. {
  207636. if (id == IID_IUnknown || id == IID_IOleInPlaceSite)
  207637. {
  207638. AddRef();
  207639. *result = this;
  207640. return S_OK;
  207641. }
  207642. *result = 0;
  207643. return E_NOINTERFACE;
  207644. }
  207645. ULONG __stdcall AddRef() { return ++refCount; }
  207646. ULONG __stdcall Release() { const int r = --refCount; if (r == 0) delete this; return r; }
  207647. HRESULT __stdcall GetWindow (HWND* lphwnd) { *lphwnd = window; return S_OK; }
  207648. HRESULT __stdcall ContextSensitiveHelp (BOOL) { return E_NOTIMPL; }
  207649. HRESULT __stdcall CanInPlaceActivate() { return S_OK; }
  207650. HRESULT __stdcall OnInPlaceActivate() { return S_OK; }
  207651. HRESULT __stdcall OnUIActivate() { return S_OK; }
  207652. HRESULT __stdcall GetWindowContext (LPOLEINPLACEFRAME* lplpFrame, LPOLEINPLACEUIWINDOW* lplpDoc, LPRECT, LPRECT, LPOLEINPLACEFRAMEINFO lpFrameInfo)
  207653. {
  207654. frame->AddRef();
  207655. *lplpFrame = frame;
  207656. *lplpDoc = 0;
  207657. lpFrameInfo->fMDIApp = FALSE;
  207658. lpFrameInfo->hwndFrame = window;
  207659. lpFrameInfo->haccel = 0;
  207660. lpFrameInfo->cAccelEntries = 0;
  207661. return S_OK;
  207662. }
  207663. HRESULT __stdcall Scroll (SIZE) { return E_NOTIMPL; }
  207664. HRESULT __stdcall OnUIDeactivate (BOOL) { return S_OK; }
  207665. HRESULT __stdcall OnInPlaceDeactivate() { return S_OK; }
  207666. HRESULT __stdcall DiscardUndoState() { return E_NOTIMPL; }
  207667. HRESULT __stdcall DeactivateAndUndo() { return E_NOTIMPL; }
  207668. HRESULT __stdcall OnPosRectChange (LPCRECT) { return S_OK; }
  207669. juce_UseDebuggingNewOperator
  207670. };
  207671. class JuceIOleClientSite : public IOleClientSite
  207672. {
  207673. int refCount;
  207674. JuceIOleInPlaceSite* inplaceSite;
  207675. public:
  207676. JuceIOleClientSite (HWND window)
  207677. : refCount (1)
  207678. {
  207679. inplaceSite = new JuceIOleInPlaceSite (window);
  207680. }
  207681. virtual ~JuceIOleClientSite()
  207682. {
  207683. jassert (refCount == 0);
  207684. inplaceSite->Release();
  207685. }
  207686. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  207687. {
  207688. if (id == IID_IUnknown || id == IID_IOleClientSite)
  207689. {
  207690. AddRef();
  207691. *result = this;
  207692. return S_OK;
  207693. }
  207694. else if (id == IID_IOleInPlaceSite)
  207695. {
  207696. inplaceSite->AddRef();
  207697. *result = inplaceSite;
  207698. return S_OK;
  207699. }
  207700. *result = 0;
  207701. return E_NOINTERFACE;
  207702. }
  207703. ULONG __stdcall AddRef() { return ++refCount; }
  207704. ULONG __stdcall Release() { const int r = --refCount; if (r == 0) delete this; return r; }
  207705. HRESULT __stdcall SaveObject() { return E_NOTIMPL; }
  207706. HRESULT __stdcall GetMoniker (DWORD, DWORD, IMoniker**) { return E_NOTIMPL; }
  207707. HRESULT __stdcall GetContainer (LPOLECONTAINER* ppContainer) { *ppContainer = 0; return E_NOINTERFACE; }
  207708. HRESULT __stdcall ShowObject() { return S_OK; }
  207709. HRESULT __stdcall OnShowWindow (BOOL) { return E_NOTIMPL; }
  207710. HRESULT __stdcall RequestNewObjectLayout() { return E_NOTIMPL; }
  207711. juce_UseDebuggingNewOperator
  207712. };
  207713. class ActiveXControlData : public ComponentMovementWatcher
  207714. {
  207715. ActiveXControlComponent* const owner;
  207716. bool wasShowing;
  207717. public:
  207718. IStorage* storage;
  207719. IOleClientSite* clientSite;
  207720. IOleObject* control;
  207721. ActiveXControlData (HWND hwnd,
  207722. ActiveXControlComponent* const owner_)
  207723. : ComponentMovementWatcher (owner_),
  207724. owner (owner_),
  207725. wasShowing (owner_ != 0 && owner_->isShowing()),
  207726. storage (new JuceIStorage()),
  207727. clientSite (new JuceIOleClientSite (hwnd)),
  207728. control (0)
  207729. {
  207730. }
  207731. ~ActiveXControlData()
  207732. {
  207733. if (control != 0)
  207734. {
  207735. control->Close (OLECLOSE_NOSAVE);
  207736. control->Release();
  207737. }
  207738. clientSite->Release();
  207739. storage->Release();
  207740. }
  207741. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  207742. {
  207743. Component* const topComp = owner->getTopLevelComponent();
  207744. if (topComp->getPeer() != 0)
  207745. {
  207746. int x = 0, y = 0;
  207747. owner->relativePositionToOtherComponent (topComp, x, y);
  207748. owner->setControlBounds (Rectangle (x, y, owner->getWidth(), owner->getHeight()));
  207749. }
  207750. }
  207751. void componentPeerChanged()
  207752. {
  207753. const bool isShowingNow = owner->isShowing();
  207754. if (wasShowing != isShowingNow)
  207755. {
  207756. wasShowing = isShowingNow;
  207757. owner->setControlVisible (isShowingNow);
  207758. }
  207759. }
  207760. void componentVisibilityChanged (Component&)
  207761. {
  207762. componentPeerChanged();
  207763. }
  207764. };
  207765. static VoidArray activeXComps;
  207766. static HWND getHWND (const ActiveXControlComponent* const component)
  207767. {
  207768. HWND hwnd = 0;
  207769. const IID iid = IID_IOleWindow;
  207770. IOleWindow* const window = (IOleWindow*) component->queryInterface (&iid);
  207771. if (window != 0)
  207772. {
  207773. window->GetWindow (&hwnd);
  207774. window->Release();
  207775. }
  207776. return hwnd;
  207777. }
  207778. static void offerActiveXMouseEventToPeer (ComponentPeer* const peer, HWND hwnd, UINT message, LPARAM lParam)
  207779. {
  207780. RECT activeXRect, peerRect;
  207781. GetWindowRect (hwnd, &activeXRect);
  207782. GetWindowRect ((HWND) peer->getNativeHandle(), &peerRect);
  207783. const int mx = GET_X_LPARAM (lParam) + activeXRect.left - peerRect.left;
  207784. const int my = GET_Y_LPARAM (lParam) + activeXRect.top - peerRect.top;
  207785. const int64 mouseEventTime = getMouseEventTime();
  207786. const int oldModifiers = currentModifiers;
  207787. ModifierKeys::getCurrentModifiersRealtime(); // to update the mouse button flags
  207788. switch (message)
  207789. {
  207790. case WM_MOUSEMOVE:
  207791. if (ModifierKeys (currentModifiers).isAnyMouseButtonDown())
  207792. peer->handleMouseDrag (mx, my, mouseEventTime);
  207793. else
  207794. peer->handleMouseMove (mx, my, mouseEventTime);
  207795. break;
  207796. case WM_LBUTTONDOWN:
  207797. case WM_MBUTTONDOWN:
  207798. case WM_RBUTTONDOWN:
  207799. peer->handleMouseDown (mx, my, mouseEventTime);
  207800. break;
  207801. case WM_LBUTTONUP:
  207802. case WM_MBUTTONUP:
  207803. case WM_RBUTTONUP:
  207804. peer->handleMouseUp (oldModifiers, mx, my, mouseEventTime);
  207805. break;
  207806. default:
  207807. break;
  207808. }
  207809. }
  207810. // intercepts events going to an activeX control, so we can sneakily use the mouse events
  207811. static LRESULT CALLBACK activeXHookWndProc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
  207812. {
  207813. for (int i = activeXComps.size(); --i >= 0;)
  207814. {
  207815. const ActiveXControlComponent* const ax = (const ActiveXControlComponent*) activeXComps.getUnchecked(i);
  207816. HWND controlHWND = getHWND (ax);
  207817. if (controlHWND == hwnd)
  207818. {
  207819. switch (message)
  207820. {
  207821. case WM_MOUSEMOVE:
  207822. case WM_LBUTTONDOWN:
  207823. case WM_MBUTTONDOWN:
  207824. case WM_RBUTTONDOWN:
  207825. case WM_LBUTTONUP:
  207826. case WM_MBUTTONUP:
  207827. case WM_RBUTTONUP:
  207828. case WM_LBUTTONDBLCLK:
  207829. case WM_MBUTTONDBLCLK:
  207830. case WM_RBUTTONDBLCLK:
  207831. if (ax->isShowing())
  207832. {
  207833. ComponentPeer* const peer = ax->getPeer();
  207834. if (peer != 0)
  207835. {
  207836. offerActiveXMouseEventToPeer (peer, hwnd, message, lParam);
  207837. if (! ax->areMouseEventsAllowed())
  207838. return 0;
  207839. }
  207840. }
  207841. break;
  207842. default:
  207843. break;
  207844. }
  207845. return CallWindowProc ((WNDPROC) (ax->originalWndProc), hwnd, message, wParam, lParam);
  207846. }
  207847. }
  207848. return DefWindowProc (hwnd, message, wParam, lParam);
  207849. }
  207850. ActiveXControlComponent::ActiveXControlComponent()
  207851. : originalWndProc (0),
  207852. control (0),
  207853. mouseEventsAllowed (true)
  207854. {
  207855. activeXComps.add (this);
  207856. }
  207857. ActiveXControlComponent::~ActiveXControlComponent()
  207858. {
  207859. deleteControl();
  207860. activeXComps.removeValue (this);
  207861. }
  207862. void ActiveXControlComponent::paint (Graphics& g)
  207863. {
  207864. if (control == 0)
  207865. g.fillAll (Colours::lightgrey);
  207866. }
  207867. bool ActiveXControlComponent::createControl (const void* controlIID)
  207868. {
  207869. deleteControl();
  207870. ComponentPeer* const peer = getPeer();
  207871. // the component must have already been added to a real window when you call this!
  207872. jassert (dynamic_cast <Win32ComponentPeer*> (peer) != 0);
  207873. if (dynamic_cast <Win32ComponentPeer*> (peer) != 0)
  207874. {
  207875. int x = 0, y = 0;
  207876. relativePositionToOtherComponent (getTopLevelComponent(), x, y);
  207877. HWND hwnd = (HWND) peer->getNativeHandle();
  207878. ActiveXControlData* const info = new ActiveXControlData (hwnd, this);
  207879. HRESULT hr;
  207880. if ((hr = OleCreate (*(const IID*) controlIID, IID_IOleObject, 1 /*OLERENDER_DRAW*/, 0,
  207881. info->clientSite, info->storage,
  207882. (void**) &(info->control))) == S_OK)
  207883. {
  207884. info->control->SetHostNames (L"Juce", 0);
  207885. if (OleSetContainedObject (info->control, TRUE) == S_OK)
  207886. {
  207887. RECT rect;
  207888. rect.left = x;
  207889. rect.top = y;
  207890. rect.right = x + getWidth();
  207891. rect.bottom = y + getHeight();
  207892. if (info->control->DoVerb (OLEIVERB_SHOW, 0, info->clientSite, 0, hwnd, &rect) == S_OK)
  207893. {
  207894. control = info;
  207895. setControlBounds (Rectangle (x, y, getWidth(), getHeight()));
  207896. HWND controlHWND = getHWND (this);
  207897. if (controlHWND != 0)
  207898. {
  207899. originalWndProc = (void*) GetWindowLongPtr (controlHWND, GWLP_WNDPROC);
  207900. SetWindowLongPtr (controlHWND, GWLP_WNDPROC, (LONG_PTR) activeXHookWndProc);
  207901. }
  207902. return true;
  207903. }
  207904. }
  207905. }
  207906. delete info;
  207907. }
  207908. return false;
  207909. }
  207910. void ActiveXControlComponent::deleteControl()
  207911. {
  207912. ActiveXControlData* const info = (ActiveXControlData*) control;
  207913. if (info != 0)
  207914. {
  207915. delete info;
  207916. control = 0;
  207917. originalWndProc = 0;
  207918. }
  207919. }
  207920. void* ActiveXControlComponent::queryInterface (const void* iid) const
  207921. {
  207922. ActiveXControlData* const info = (ActiveXControlData*) control;
  207923. void* result = 0;
  207924. if (info != 0 && info->control != 0
  207925. && info->control->QueryInterface (*(const IID*) iid, &result) == S_OK)
  207926. return result;
  207927. return 0;
  207928. }
  207929. void ActiveXControlComponent::setControlBounds (const Rectangle& newBounds) const
  207930. {
  207931. HWND hwnd = getHWND (this);
  207932. if (hwnd != 0)
  207933. MoveWindow (hwnd, newBounds.getX(), newBounds.getY(), newBounds.getWidth(), newBounds.getHeight(), TRUE);
  207934. }
  207935. void ActiveXControlComponent::setControlVisible (const bool shouldBeVisible) const
  207936. {
  207937. HWND hwnd = getHWND (this);
  207938. if (hwnd != 0)
  207939. ShowWindow (hwnd, shouldBeVisible ? SW_SHOWNA : SW_HIDE);
  207940. }
  207941. void ActiveXControlComponent::setMouseEventsAllowed (const bool eventsCanReachControl)
  207942. {
  207943. mouseEventsAllowed = eventsCanReachControl;
  207944. }
  207945. END_JUCE_NAMESPACE
  207946. /********* End of inlined file: juce_win32_Windowing.cpp *********/
  207947. #endif
  207948. /********* Start of inlined file: juce_win32_AutoLinkLibraries.h *********/
  207949. // Auto-links to various win32 libs that are needed by library calls..
  207950. #pragma comment(lib, "kernel32.lib")
  207951. #pragma comment(lib, "user32.lib")
  207952. #pragma comment(lib, "shell32.lib")
  207953. #pragma comment(lib, "gdi32.lib")
  207954. #pragma comment(lib, "vfw32.lib")
  207955. #pragma comment(lib, "comdlg32.lib")
  207956. #pragma comment(lib, "winmm.lib")
  207957. #pragma comment(lib, "wininet.lib")
  207958. #pragma comment(lib, "ole32.lib")
  207959. #pragma comment(lib, "advapi32.lib")
  207960. #pragma comment(lib, "ws2_32.lib")
  207961. #pragma comment(lib, "comsupp.lib")
  207962. #if JUCE_OPENGL
  207963. #pragma comment(lib, "OpenGL32.Lib")
  207964. #pragma comment(lib, "GlU32.Lib")
  207965. #endif
  207966. #if JUCE_QUICKTIME
  207967. #pragma comment (lib, "QTMLClient.lib")
  207968. #endif
  207969. /********* End of inlined file: juce_win32_AutoLinkLibraries.h *********/
  207970. #endif
  207971. //==============================================================================
  207972. #if JUCE_LINUX
  207973. /********* Start of inlined file: juce_linux_Files.cpp *********/
  207974. /********* Start of inlined file: linuxincludes.h *********/
  207975. #ifndef __LINUXINCLUDES_JUCEHEADER__
  207976. #define __LINUXINCLUDES_JUCEHEADER__
  207977. // Linux Header Files:
  207978. #include <unistd.h>
  207979. #include <stdlib.h>
  207980. #include <sched.h>
  207981. #include <pthread.h>
  207982. #include <sys/time.h>
  207983. #include <errno.h>
  207984. /* Remove this macro if you're having problems compiling the cpu affinity
  207985. calls (the API for these has changed about quite a bit in various Linux
  207986. versions, and a lot of distros seem to ship with obsolete versions)
  207987. */
  207988. #ifndef SUPPORT_AFFINITIES
  207989. #define SUPPORT_AFFINITIES 1
  207990. #endif
  207991. #endif // __LINUXINCLUDES_JUCEHEADER__
  207992. /********* End of inlined file: linuxincludes.h *********/
  207993. #include <sys/stat.h>
  207994. #include <sys/dir.h>
  207995. #include <sys/ptrace.h>
  207996. #include <sys/vfs.h> // for statfs
  207997. #include <sys/wait.h>
  207998. #include <unistd.h>
  207999. #include <fnmatch.h>
  208000. #include <utime.h>
  208001. #include <pwd.h>
  208002. #include <fcntl.h>
  208003. #define U_ISOFS_SUPER_MAGIC (short) 0x9660 // linux/iso_fs.h
  208004. #define U_MSDOS_SUPER_MAGIC (short) 0x4d44 // linux/msdos_fs.h
  208005. #define U_NFS_SUPER_MAGIC (short) 0x6969 // linux/nfs_fs.h
  208006. #define U_SMB_SUPER_MAGIC (short) 0x517B // linux/smb_fs.h
  208007. BEGIN_JUCE_NAMESPACE
  208008. /*
  208009. Note that a lot of methods that you'd expect to find in this file actually
  208010. live in juce_posix_SharedCode.cpp!
  208011. */
  208012. /********* Start of inlined file: juce_posix_SharedCode.cpp *********/
  208013. /*
  208014. This file contains posix routines that are common to both the Linux and Mac builds.
  208015. It gets included directly in the cpp files for these platforms.
  208016. */
  208017. CriticalSection::CriticalSection() throw()
  208018. {
  208019. pthread_mutexattr_t atts;
  208020. pthread_mutexattr_init (&atts);
  208021. pthread_mutexattr_settype (&atts, PTHREAD_MUTEX_RECURSIVE);
  208022. pthread_mutex_init (&internal, &atts);
  208023. }
  208024. CriticalSection::~CriticalSection() throw()
  208025. {
  208026. pthread_mutex_destroy (&internal);
  208027. }
  208028. void CriticalSection::enter() const throw()
  208029. {
  208030. pthread_mutex_lock (&internal);
  208031. }
  208032. bool CriticalSection::tryEnter() const throw()
  208033. {
  208034. return pthread_mutex_trylock (&internal) == 0;
  208035. }
  208036. void CriticalSection::exit() const throw()
  208037. {
  208038. pthread_mutex_unlock (&internal);
  208039. }
  208040. struct EventStruct
  208041. {
  208042. pthread_cond_t condition;
  208043. pthread_mutex_t mutex;
  208044. bool triggered;
  208045. };
  208046. WaitableEvent::WaitableEvent() throw()
  208047. {
  208048. EventStruct* const es = new EventStruct();
  208049. es->triggered = false;
  208050. pthread_cond_init (&es->condition, 0);
  208051. pthread_mutex_init (&es->mutex, 0);
  208052. internal = es;
  208053. }
  208054. WaitableEvent::~WaitableEvent() throw()
  208055. {
  208056. EventStruct* const es = (EventStruct*) internal;
  208057. pthread_cond_destroy (&es->condition);
  208058. pthread_mutex_destroy (&es->mutex);
  208059. delete es;
  208060. }
  208061. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  208062. {
  208063. EventStruct* const es = (EventStruct*) internal;
  208064. bool ok = true;
  208065. pthread_mutex_lock (&es->mutex);
  208066. if (! es->triggered)
  208067. {
  208068. if (timeOutMillisecs < 0)
  208069. {
  208070. pthread_cond_wait (&es->condition, &es->mutex);
  208071. }
  208072. else
  208073. {
  208074. struct timespec time;
  208075. #if JUCE_MAC
  208076. time.tv_sec = timeOutMillisecs / 1000;
  208077. time.tv_nsec = (timeOutMillisecs % 1000) * 1000000;
  208078. pthread_cond_timedwait_relative_np (&es->condition, &es->mutex, &time);
  208079. #else
  208080. struct timeval t;
  208081. int timeout = 0;
  208082. gettimeofday (&t, 0);
  208083. time.tv_sec = t.tv_sec + (timeOutMillisecs / 1000);
  208084. time.tv_nsec = (t.tv_usec + ((timeOutMillisecs % 1000) * 1000)) * 1000;
  208085. while (time.tv_nsec >= 1000000000)
  208086. {
  208087. time.tv_nsec -= 1000000000;
  208088. time.tv_sec++;
  208089. }
  208090. while (! timeout)
  208091. {
  208092. timeout = pthread_cond_timedwait (&es->condition, &es->mutex, &time);
  208093. if (! timeout)
  208094. // Success
  208095. break;
  208096. if (timeout == EINTR)
  208097. // Go round again
  208098. timeout = 0;
  208099. }
  208100. #endif
  208101. }
  208102. ok = es->triggered;
  208103. }
  208104. es->triggered = false;
  208105. pthread_mutex_unlock (&es->mutex);
  208106. return ok;
  208107. }
  208108. void WaitableEvent::signal() const throw()
  208109. {
  208110. EventStruct* const es = (EventStruct*) internal;
  208111. pthread_mutex_lock (&es->mutex);
  208112. es->triggered = true;
  208113. pthread_cond_broadcast (&es->condition);
  208114. pthread_mutex_unlock (&es->mutex);
  208115. }
  208116. void WaitableEvent::reset() const throw()
  208117. {
  208118. EventStruct* const es = (EventStruct*) internal;
  208119. pthread_mutex_lock (&es->mutex);
  208120. es->triggered = false;
  208121. pthread_mutex_unlock (&es->mutex);
  208122. }
  208123. void JUCE_CALLTYPE Thread::sleep (int millisecs) throw()
  208124. {
  208125. struct timespec time;
  208126. time.tv_sec = millisecs / 1000;
  208127. time.tv_nsec = (millisecs % 1000) * 1000000;
  208128. nanosleep (&time, 0);
  208129. }
  208130. const tchar File::separator = T('/');
  208131. const tchar* File::separatorString = T("/");
  208132. bool juce_copyFile (const String& s, const String& d) throw();
  208133. static bool juce_stat (const String& fileName, struct stat& info) throw()
  208134. {
  208135. return fileName.isNotEmpty()
  208136. && (stat (fileName.toUTF8(), &info) == 0);
  208137. }
  208138. bool juce_isDirectory (const String& fileName) throw()
  208139. {
  208140. struct stat info;
  208141. return fileName.isEmpty()
  208142. || (juce_stat (fileName, info)
  208143. && ((info.st_mode & S_IFDIR) != 0));
  208144. }
  208145. bool juce_fileExists (const String& fileName, const bool dontCountDirectories) throw()
  208146. {
  208147. if (fileName.isEmpty())
  208148. return false;
  208149. const char* const fileNameUTF8 = fileName.toUTF8();
  208150. bool exists = access (fileNameUTF8, F_OK) == 0;
  208151. if (exists && dontCountDirectories)
  208152. {
  208153. struct stat info;
  208154. const int res = stat (fileNameUTF8, &info);
  208155. if (res == 0 && (info.st_mode & S_IFDIR) != 0)
  208156. exists = false;
  208157. }
  208158. return exists;
  208159. }
  208160. int64 juce_getFileSize (const String& fileName) throw()
  208161. {
  208162. struct stat info;
  208163. return juce_stat (fileName, info) ? info.st_size : 0;
  208164. }
  208165. bool juce_canWriteToFile (const String& fileName) throw()
  208166. {
  208167. return access (fileName.toUTF8(), W_OK) == 0;
  208168. }
  208169. bool juce_deleteFile (const String& fileName) throw()
  208170. {
  208171. const char* const fileNameUTF8 = fileName.toUTF8();
  208172. if (juce_isDirectory (fileName))
  208173. return rmdir (fileNameUTF8) == 0;
  208174. else
  208175. return remove (fileNameUTF8) == 0;
  208176. }
  208177. bool juce_moveFile (const String& source, const String& dest) throw()
  208178. {
  208179. if (rename (source.toUTF8(), dest.toUTF8()) == 0)
  208180. return true;
  208181. if (juce_canWriteToFile (source)
  208182. && juce_copyFile (source, dest))
  208183. {
  208184. if (juce_deleteFile (source))
  208185. return true;
  208186. juce_deleteFile (dest);
  208187. }
  208188. return false;
  208189. }
  208190. void juce_createDirectory (const String& fileName) throw()
  208191. {
  208192. mkdir (fileName.toUTF8(), 0777);
  208193. }
  208194. void* juce_fileOpen (const String& fileName, bool forWriting) throw()
  208195. {
  208196. const char* const fileNameUTF8 = fileName.toUTF8();
  208197. int flags = O_RDONLY;
  208198. if (forWriting)
  208199. {
  208200. if (juce_fileExists (fileName, false))
  208201. {
  208202. const int f = open (fileNameUTF8, O_RDWR, 00644);
  208203. if (f != -1)
  208204. lseek (f, 0, SEEK_END);
  208205. return (void*) f;
  208206. }
  208207. else
  208208. {
  208209. flags = O_RDWR + O_CREAT;
  208210. }
  208211. }
  208212. return (void*) open (fileNameUTF8, flags, 00644);
  208213. }
  208214. void juce_fileClose (void* handle) throw()
  208215. {
  208216. if (handle != 0)
  208217. close ((int) (pointer_sized_int) handle);
  208218. }
  208219. int juce_fileRead (void* handle, void* buffer, int size) throw()
  208220. {
  208221. if (handle != 0)
  208222. return read ((int) (pointer_sized_int) handle, buffer, size);
  208223. return 0;
  208224. }
  208225. int juce_fileWrite (void* handle, const void* buffer, int size) throw()
  208226. {
  208227. if (handle != 0)
  208228. return write ((int) (pointer_sized_int) handle, buffer, size);
  208229. return 0;
  208230. }
  208231. int64 juce_fileSetPosition (void* handle, int64 pos) throw()
  208232. {
  208233. if (handle != 0 && lseek ((int) (pointer_sized_int) handle, pos, SEEK_SET) == pos)
  208234. return pos;
  208235. return -1;
  208236. }
  208237. int64 juce_fileGetPosition (void* handle) throw()
  208238. {
  208239. if (handle != 0)
  208240. return lseek ((int) (pointer_sized_int) handle, 0, SEEK_CUR);
  208241. else
  208242. return -1;
  208243. }
  208244. void juce_fileFlush (void* handle) throw()
  208245. {
  208246. if (handle != 0)
  208247. fsync ((int) (pointer_sized_int) handle);
  208248. }
  208249. // if this file doesn't exist, find a parent of it that does..
  208250. static bool doStatFS (const File* file, struct statfs& result) throw()
  208251. {
  208252. File f (*file);
  208253. for (int i = 5; --i >= 0;)
  208254. {
  208255. if (f.exists())
  208256. break;
  208257. f = f.getParentDirectory();
  208258. }
  208259. return statfs (f.getFullPathName().toUTF8(), &result) == 0;
  208260. }
  208261. int64 File::getBytesFreeOnVolume() const throw()
  208262. {
  208263. int64 free_space = 0;
  208264. struct statfs buf;
  208265. if (doStatFS (this, buf))
  208266. // Note: this returns space available to non-super user
  208267. free_space = (int64) buf.f_bsize * (int64) buf.f_bavail;
  208268. return free_space;
  208269. }
  208270. const String juce_getVolumeLabel (const String& filenameOnVolume,
  208271. int& volumeSerialNumber) throw()
  208272. {
  208273. // There is no equivalent on Linux
  208274. volumeSerialNumber = 0;
  208275. return String::empty;
  208276. }
  208277. #if JUCE_64BIT
  208278. #define filedesc ((long long) internal)
  208279. #else
  208280. #define filedesc ((int) internal)
  208281. #endif
  208282. InterProcessLock::InterProcessLock (const String& name_) throw()
  208283. : internal (0),
  208284. name (name_),
  208285. reentrancyLevel (0)
  208286. {
  208287. #if JUCE_MAC
  208288. // (don't use getSpecialLocation() to avoid the temp folder being different for each app)
  208289. const File temp (File (T("~/Library/Caches/Juce")).getChildFile (name));
  208290. #else
  208291. const File temp (File::getSpecialLocation (File::tempDirectory).getChildFile (name));
  208292. #endif
  208293. temp.create();
  208294. internal = (void*) open (temp.getFullPathName().toUTF8(), O_RDWR);
  208295. }
  208296. InterProcessLock::~InterProcessLock() throw()
  208297. {
  208298. while (reentrancyLevel > 0)
  208299. this->exit();
  208300. close (filedesc);
  208301. }
  208302. bool InterProcessLock::enter (const int timeOutMillisecs) throw()
  208303. {
  208304. if (internal == 0)
  208305. return false;
  208306. if (reentrancyLevel != 0)
  208307. return true;
  208308. const int64 endTime = Time::currentTimeMillis() + timeOutMillisecs;
  208309. struct flock fl;
  208310. zerostruct (fl);
  208311. fl.l_whence = SEEK_SET;
  208312. fl.l_type = F_WRLCK;
  208313. for (;;)
  208314. {
  208315. const int result = fcntl (filedesc, F_SETLK, &fl);
  208316. if (result >= 0)
  208317. {
  208318. ++reentrancyLevel;
  208319. return true;
  208320. }
  208321. if (errno != EINTR)
  208322. {
  208323. if (timeOutMillisecs == 0
  208324. || (timeOutMillisecs > 0 && Time::currentTimeMillis() >= endTime))
  208325. break;
  208326. Thread::sleep (10);
  208327. }
  208328. }
  208329. return false;
  208330. }
  208331. void InterProcessLock::exit() throw()
  208332. {
  208333. if (reentrancyLevel > 0 && internal != 0)
  208334. {
  208335. --reentrancyLevel;
  208336. struct flock fl;
  208337. zerostruct (fl);
  208338. fl.l_whence = SEEK_SET;
  208339. fl.l_type = F_UNLCK;
  208340. for (;;)
  208341. {
  208342. const int result = fcntl (filedesc, F_SETLKW, &fl);
  208343. if (result >= 0 || errno != EINTR)
  208344. break;
  208345. }
  208346. }
  208347. }
  208348. /********* End of inlined file: juce_posix_SharedCode.cpp *********/
  208349. static File executableFile;
  208350. void juce_getFileTimes (const String& fileName,
  208351. int64& modificationTime,
  208352. int64& accessTime,
  208353. int64& creationTime) throw()
  208354. {
  208355. modificationTime = 0;
  208356. accessTime = 0;
  208357. creationTime = 0;
  208358. struct stat info;
  208359. const int res = stat (fileName.toUTF8(), &info);
  208360. if (res == 0)
  208361. {
  208362. modificationTime = (int64) info.st_mtime * 1000;
  208363. accessTime = (int64) info.st_atime * 1000;
  208364. creationTime = (int64) info.st_ctime * 1000;
  208365. }
  208366. }
  208367. bool juce_setFileTimes (const String& fileName,
  208368. int64 modificationTime,
  208369. int64 accessTime,
  208370. int64 creationTime) throw()
  208371. {
  208372. struct utimbuf times;
  208373. times.actime = (time_t) (accessTime / 1000);
  208374. times.modtime = (time_t) (modificationTime / 1000);
  208375. return utime (fileName.toUTF8(), &times) == 0;
  208376. }
  208377. bool juce_setFileReadOnly (const String& fileName, bool isReadOnly) throw()
  208378. {
  208379. struct stat info;
  208380. const int res = stat (fileName.toUTF8(), &info);
  208381. if (res != 0)
  208382. return false;
  208383. info.st_mode &= 0777; // Just permissions
  208384. if( isReadOnly )
  208385. info.st_mode &= ~(S_IWUSR | S_IWGRP | S_IWOTH);
  208386. else
  208387. // Give everybody write permission?
  208388. info.st_mode |= S_IWUSR | S_IWGRP | S_IWOTH;
  208389. return chmod (fileName.toUTF8(), info.st_mode) == 0;
  208390. }
  208391. bool juce_copyFile (const String& s, const String& d) throw()
  208392. {
  208393. const File source (s), dest (d);
  208394. FileInputStream* in = source.createInputStream();
  208395. bool ok = false;
  208396. if (in != 0)
  208397. {
  208398. if (dest.deleteFile())
  208399. {
  208400. FileOutputStream* const out = dest.createOutputStream();
  208401. if (out != 0)
  208402. {
  208403. const int bytesCopied = out->writeFromInputStream (*in, -1);
  208404. delete out;
  208405. ok = (bytesCopied == source.getSize());
  208406. if (! ok)
  208407. dest.deleteFile();
  208408. }
  208409. }
  208410. delete in;
  208411. }
  208412. return ok;
  208413. }
  208414. const StringArray juce_getFileSystemRoots() throw()
  208415. {
  208416. StringArray s;
  208417. s.add (T("/"));
  208418. return s;
  208419. }
  208420. bool File::isOnCDRomDrive() const throw()
  208421. {
  208422. struct statfs buf;
  208423. if (statfs (getFullPathName().toUTF8(), &buf) == 0)
  208424. return (buf.f_type == U_ISOFS_SUPER_MAGIC);
  208425. // Assume not if this fails for some reason
  208426. return false;
  208427. }
  208428. bool File::isOnHardDisk() const throw()
  208429. {
  208430. struct statfs buf;
  208431. if (statfs (getFullPathName().toUTF8(), &buf) == 0)
  208432. {
  208433. switch (buf.f_type)
  208434. {
  208435. case U_ISOFS_SUPER_MAGIC: // CD-ROM
  208436. case U_MSDOS_SUPER_MAGIC: // Probably floppy (but could be mounted FAT filesystem)
  208437. case U_NFS_SUPER_MAGIC: // Network NFS
  208438. case U_SMB_SUPER_MAGIC: // Network Samba
  208439. return false;
  208440. default:
  208441. // Assume anything else is a hard-disk (but note it could
  208442. // be a RAM disk. There isn't a good way of determining
  208443. // this for sure)
  208444. return true;
  208445. }
  208446. }
  208447. // Assume so if this fails for some reason
  208448. return true;
  208449. }
  208450. bool File::isHidden() const throw()
  208451. {
  208452. return getFileName().startsWithChar (T('.'));
  208453. }
  208454. const File File::getSpecialLocation (const SpecialLocationType type)
  208455. {
  208456. switch (type)
  208457. {
  208458. case userHomeDirectory:
  208459. {
  208460. const char* homeDir = getenv ("HOME");
  208461. if (homeDir == 0)
  208462. {
  208463. struct passwd* const pw = getpwuid (getuid());
  208464. if (pw != 0)
  208465. homeDir = pw->pw_dir;
  208466. }
  208467. return File (String::fromUTF8 ((const uint8*) homeDir));
  208468. }
  208469. case userDocumentsDirectory:
  208470. case userMusicDirectory:
  208471. case userMoviesDirectory:
  208472. case userApplicationDataDirectory:
  208473. return File ("~");
  208474. case userDesktopDirectory:
  208475. return File ("~/Desktop");
  208476. case commonApplicationDataDirectory:
  208477. return File ("/var");
  208478. case globalApplicationsDirectory:
  208479. return File ("/usr");
  208480. case tempDirectory:
  208481. {
  208482. File tmp ("/var/tmp");
  208483. if (! tmp.isDirectory())
  208484. {
  208485. tmp = T("/tmp");
  208486. if (! tmp.isDirectory())
  208487. tmp = File::getCurrentWorkingDirectory();
  208488. }
  208489. return tmp;
  208490. }
  208491. case currentExecutableFile:
  208492. case currentApplicationFile:
  208493. // if this fails, it's probably because juce_setCurrentExecutableFileName()
  208494. // was never called to set the filename - this should be done by the juce
  208495. // main() function, so maybe you've hacked it to use your own custom main()?
  208496. jassert (executableFile.exists());
  208497. return executableFile;
  208498. default:
  208499. jassertfalse // unknown type?
  208500. break;
  208501. }
  208502. return File::nonexistent;
  208503. }
  208504. void juce_setCurrentExecutableFileName (const String& filename) throw()
  208505. {
  208506. executableFile = File::getCurrentWorkingDirectory().getChildFile (filename);
  208507. }
  208508. const File File::getCurrentWorkingDirectory() throw()
  208509. {
  208510. char buf [2048];
  208511. getcwd (buf, sizeof(buf));
  208512. return File (String::fromUTF8 ((const uint8*) buf));
  208513. }
  208514. bool File::setAsCurrentWorkingDirectory() const throw()
  208515. {
  208516. return chdir (getFullPathName().toUTF8()) == 0;
  208517. }
  208518. struct FindFileStruct
  208519. {
  208520. String parentDir, wildCard;
  208521. DIR* dir;
  208522. bool getNextMatch (String& result, bool* const isDir, bool* const isHidden, int64* const fileSize,
  208523. Time* const modTime, Time* const creationTime, bool* const isReadOnly) throw()
  208524. {
  208525. const char* const wildcardUTF8 = wildCard.toUTF8();
  208526. for (;;)
  208527. {
  208528. struct dirent* const de = readdir (dir);
  208529. if (de == 0)
  208530. break;
  208531. if (fnmatch (wildcardUTF8, de->d_name, FNM_CASEFOLD) == 0)
  208532. {
  208533. result = String::fromUTF8 ((const uint8*) de->d_name);
  208534. const String path (parentDir + result);
  208535. if (isDir != 0 || fileSize != 0)
  208536. {
  208537. struct stat info;
  208538. const bool statOk = (stat (path.toUTF8(), &info) == 0);
  208539. if (isDir != 0)
  208540. *isDir = path.isEmpty() || (statOk && ((info.st_mode & S_IFDIR) != 0));
  208541. if (isHidden != 0)
  208542. *isHidden = (de->d_name[0] == '.');
  208543. if (fileSize != 0)
  208544. *fileSize = statOk ? info.st_size : 0;
  208545. }
  208546. if (modTime != 0 || creationTime != 0)
  208547. {
  208548. int64 m, a, c;
  208549. juce_getFileTimes (path, m, a, c);
  208550. if (modTime != 0)
  208551. *modTime = m;
  208552. if (creationTime != 0)
  208553. *creationTime = c;
  208554. }
  208555. if (isReadOnly != 0)
  208556. *isReadOnly = ! juce_canWriteToFile (path);
  208557. return true;
  208558. }
  208559. }
  208560. return false;
  208561. }
  208562. };
  208563. // returns 0 on failure
  208564. void* juce_findFileStart (const String& directory, const String& wildCard, String& firstResultFile,
  208565. bool* isDir, bool* isHidden, int64* fileSize, Time* modTime,
  208566. Time* creationTime, bool* isReadOnly) throw()
  208567. {
  208568. DIR* d = opendir (directory.toUTF8());
  208569. if (d != 0)
  208570. {
  208571. FindFileStruct* ff = new FindFileStruct();
  208572. ff->parentDir = directory;
  208573. if (!ff->parentDir.endsWithChar (File::separator))
  208574. ff->parentDir += File::separator;
  208575. ff->wildCard = wildCard;
  208576. if (wildCard == T("*.*"))
  208577. ff->wildCard = T("*");
  208578. ff->dir = d;
  208579. if (ff->getNextMatch (firstResultFile, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly))
  208580. {
  208581. return ff;
  208582. }
  208583. else
  208584. {
  208585. firstResultFile = String::empty;
  208586. isDir = false;
  208587. isHidden = false;
  208588. closedir (d);
  208589. delete ff;
  208590. }
  208591. }
  208592. return 0;
  208593. }
  208594. bool juce_findFileNext (void* handle, String& resultFile,
  208595. bool* isDir, bool* isHidden, int64* fileSize, Time* modTime, Time* creationTime, bool* isReadOnly) throw()
  208596. {
  208597. FindFileStruct* const ff = (FindFileStruct*) handle;
  208598. if (ff != 0)
  208599. return ff->getNextMatch (resultFile, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  208600. return false;
  208601. }
  208602. void juce_findFileClose (void* handle) throw()
  208603. {
  208604. FindFileStruct* const ff = (FindFileStruct*) handle;
  208605. if (ff != 0)
  208606. {
  208607. closedir (ff->dir);
  208608. delete ff;
  208609. }
  208610. }
  208611. bool juce_launchFile (const String& fileName,
  208612. const String& parameters) throw()
  208613. {
  208614. String cmdString (fileName);
  208615. cmdString << " " << parameters;
  208616. if (URL::isProbablyAWebsiteURL (cmdString) || URL::isProbablyAnEmailAddress (cmdString))
  208617. {
  208618. // create a command that tries to launch a bunch of likely browsers
  208619. const char* const browserNames[] = { "/etc/alternatives/x-www-browser", "firefox", "mozilla", "konqueror", "opera" };
  208620. StringArray cmdLines;
  208621. for (int i = 0; i < numElementsInArray (browserNames); ++i)
  208622. cmdLines.add (String (browserNames[i]) + T(" ") + cmdString.trim().quoted());
  208623. cmdString = cmdLines.joinIntoString (T(" || "));
  208624. }
  208625. char* const argv[4] = { "/bin/sh", "-c", (char*) cmdString.toUTF8(), 0 };
  208626. const int cpid = fork();
  208627. if (cpid == 0)
  208628. {
  208629. setsid();
  208630. // Child process
  208631. execve (argv[0], argv, environ);
  208632. exit (0);
  208633. }
  208634. return cpid >= 0;
  208635. }
  208636. END_JUCE_NAMESPACE
  208637. /********* End of inlined file: juce_linux_Files.cpp *********/
  208638. /********* Start of inlined file: juce_linux_NamedPipe.cpp *********/
  208639. /********* Start of inlined file: juce_mac_NamedPipe.cpp *********/
  208640. #include <sys/stat.h>
  208641. #include <sys/dir.h>
  208642. #include <fcntl.h>
  208643. // As well as being for the mac, this file is included by the linux build.
  208644. #if JUCE_MAC
  208645. #include <Carbon/Carbon.h>
  208646. #else
  208647. #include <sys/wait.h>
  208648. #include <errno.h>
  208649. #include <unistd.h>
  208650. #endif
  208651. BEGIN_JUCE_NAMESPACE
  208652. struct NamedPipeInternal
  208653. {
  208654. String pipeInName, pipeOutName;
  208655. int pipeIn, pipeOut;
  208656. bool volatile createdPipe, blocked, stopReadOperation;
  208657. static void signalHandler (int) {}
  208658. };
  208659. void NamedPipe::cancelPendingReads()
  208660. {
  208661. while (internal != 0 && ((NamedPipeInternal*) internal)->blocked)
  208662. {
  208663. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  208664. intern->stopReadOperation = true;
  208665. char buffer [1] = { 0 };
  208666. ::write (intern->pipeIn, buffer, 1);
  208667. int timeout = 2000;
  208668. while (intern->blocked && --timeout >= 0)
  208669. sleep (2);
  208670. intern->stopReadOperation = false;
  208671. }
  208672. }
  208673. void NamedPipe::close()
  208674. {
  208675. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  208676. if (intern != 0)
  208677. {
  208678. internal = 0;
  208679. if (intern->pipeIn != -1)
  208680. ::close (intern->pipeIn);
  208681. if (intern->pipeOut != -1)
  208682. ::close (intern->pipeOut);
  208683. if (intern->createdPipe)
  208684. {
  208685. unlink (intern->pipeInName);
  208686. unlink (intern->pipeOutName);
  208687. }
  208688. delete intern;
  208689. }
  208690. }
  208691. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  208692. {
  208693. close();
  208694. NamedPipeInternal* const intern = new NamedPipeInternal();
  208695. internal = intern;
  208696. intern->createdPipe = createPipe;
  208697. intern->blocked = false;
  208698. intern->stopReadOperation = false;
  208699. signal (SIGPIPE, NamedPipeInternal::signalHandler);
  208700. siginterrupt (SIGPIPE, 1);
  208701. const String pipePath (T("/tmp/") + File::createLegalFileName (pipeName));
  208702. intern->pipeInName = pipePath + T("_in");
  208703. intern->pipeOutName = pipePath + T("_out");
  208704. intern->pipeIn = -1;
  208705. intern->pipeOut = -1;
  208706. if (createPipe)
  208707. {
  208708. if ((mkfifo (intern->pipeInName, 0666) && errno != EEXIST)
  208709. || (mkfifo (intern->pipeOutName, 0666) && errno != EEXIST))
  208710. {
  208711. delete intern;
  208712. internal = 0;
  208713. return false;
  208714. }
  208715. }
  208716. return true;
  208717. }
  208718. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int /*timeOutMilliseconds*/)
  208719. {
  208720. int bytesRead = -1;
  208721. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  208722. if (intern != 0)
  208723. {
  208724. intern->blocked = true;
  208725. if (intern->pipeIn == -1)
  208726. {
  208727. if (intern->createdPipe)
  208728. intern->pipeIn = ::open (intern->pipeInName, O_RDWR);
  208729. else
  208730. intern->pipeIn = ::open (intern->pipeOutName, O_RDWR);
  208731. if (intern->pipeIn == -1)
  208732. {
  208733. intern->blocked = false;
  208734. return -1;
  208735. }
  208736. }
  208737. bytesRead = 0;
  208738. char* p = (char*) destBuffer;
  208739. while (bytesRead < maxBytesToRead)
  208740. {
  208741. const int bytesThisTime = maxBytesToRead - bytesRead;
  208742. const int numRead = ::read (intern->pipeIn, p, bytesThisTime);
  208743. if (numRead <= 0 || intern->stopReadOperation)
  208744. {
  208745. bytesRead = -1;
  208746. break;
  208747. }
  208748. bytesRead += numRead;
  208749. p += bytesRead;
  208750. }
  208751. intern->blocked = false;
  208752. }
  208753. return bytesRead;
  208754. }
  208755. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  208756. {
  208757. int bytesWritten = -1;
  208758. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  208759. if (intern != 0)
  208760. {
  208761. if (intern->pipeOut == -1)
  208762. {
  208763. if (intern->createdPipe)
  208764. intern->pipeOut = ::open (intern->pipeOutName, O_WRONLY);
  208765. else
  208766. intern->pipeOut = ::open (intern->pipeInName, O_WRONLY);
  208767. if (intern->pipeOut == -1)
  208768. {
  208769. return -1;
  208770. }
  208771. }
  208772. const char* p = (const char*) sourceBuffer;
  208773. bytesWritten = 0;
  208774. const uint32 timeOutTime = Time::getMillisecondCounter() + timeOutMilliseconds;
  208775. while (bytesWritten < numBytesToWrite
  208776. && (timeOutMilliseconds < 0 || Time::getMillisecondCounter() < timeOutTime))
  208777. {
  208778. const int bytesThisTime = numBytesToWrite - bytesWritten;
  208779. const int numWritten = ::write (intern->pipeOut, p, bytesThisTime);
  208780. if (numWritten <= 0)
  208781. {
  208782. bytesWritten = -1;
  208783. break;
  208784. }
  208785. bytesWritten += numWritten;
  208786. p += bytesWritten;
  208787. }
  208788. }
  208789. return bytesWritten;
  208790. }
  208791. END_JUCE_NAMESPACE
  208792. /********* End of inlined file: juce_mac_NamedPipe.cpp *********/
  208793. /********* End of inlined file: juce_linux_NamedPipe.cpp *********/
  208794. /********* Start of inlined file: juce_linux_Network.cpp *********/
  208795. #include <netdb.h>
  208796. #include <arpa/inet.h>
  208797. #include <netinet/in.h>
  208798. #include <sys/types.h>
  208799. #include <sys/ioctl.h>
  208800. #include <sys/socket.h>
  208801. #include <sys/wait.h>
  208802. #include <linux/if.h>
  208803. BEGIN_JUCE_NAMESPACE
  208804. // we'll borrow the mac's socket-based http streaming code..
  208805. /********* Start of inlined file: juce_mac_HTTPStream.h *********/
  208806. // (This file gets included by the mac + linux networking code)
  208807. /** A HTTP input stream that uses sockets.
  208808. */
  208809. class JUCE_HTTPSocketStream
  208810. {
  208811. public:
  208812. JUCE_HTTPSocketStream()
  208813. : readPosition (0),
  208814. socketHandle (-1),
  208815. levelsOfRedirection (0),
  208816. timeoutSeconds (15)
  208817. {
  208818. }
  208819. ~JUCE_HTTPSocketStream()
  208820. {
  208821. closeSocket();
  208822. }
  208823. bool open (const String& url,
  208824. const String& headers,
  208825. const MemoryBlock& postData,
  208826. const bool isPost,
  208827. URL::OpenStreamProgressCallback* callback,
  208828. void* callbackContext)
  208829. {
  208830. closeSocket();
  208831. String hostName, hostPath;
  208832. int hostPort;
  208833. if (! decomposeURL (url, hostName, hostPath, hostPort))
  208834. return false;
  208835. struct hostent* const host
  208836. = gethostbyname ((const char*) hostName.toUTF8());
  208837. if (host == 0)
  208838. return false;
  208839. struct sockaddr_in address;
  208840. zerostruct (address);
  208841. memcpy ((void*) &address.sin_addr, (const void*) host->h_addr, host->h_length);
  208842. address.sin_family = host->h_addrtype;
  208843. address.sin_port = htons (hostPort);
  208844. socketHandle = socket (host->h_addrtype, SOCK_STREAM, 0);
  208845. if (socketHandle == -1)
  208846. return false;
  208847. int receiveBufferSize = 16384;
  208848. setsockopt (socketHandle, SOL_SOCKET, SO_RCVBUF, (char*) &receiveBufferSize, sizeof (receiveBufferSize));
  208849. setsockopt (socketHandle, SOL_SOCKET, SO_KEEPALIVE, 0, 0);
  208850. #if JUCE_MAC
  208851. setsockopt (socketHandle, SOL_SOCKET, SO_NOSIGPIPE, 0, 0);
  208852. #endif
  208853. if (connect (socketHandle, (struct sockaddr*) &address, sizeof (address)) == -1)
  208854. {
  208855. closeSocket();
  208856. return false;
  208857. }
  208858. String proxyURL (getenv ("http_proxy"));
  208859. if (! proxyURL.startsWithIgnoreCase (T("http://")))
  208860. proxyURL = String::empty;
  208861. const MemoryBlock requestHeader (createRequestHeader (hostName, hostPath,
  208862. proxyURL, url,
  208863. hostPort,
  208864. headers, postData,
  208865. isPost));
  208866. int totalHeaderSent = 0;
  208867. while (totalHeaderSent < requestHeader.getSize())
  208868. {
  208869. const int numToSend = jmin (1024, requestHeader.getSize() - totalHeaderSent);
  208870. if (send (socketHandle,
  208871. ((const char*) requestHeader.getData()) + totalHeaderSent,
  208872. numToSend, 0)
  208873. != numToSend)
  208874. {
  208875. closeSocket();
  208876. return false;
  208877. }
  208878. totalHeaderSent += numToSend;
  208879. if (callback != 0 && ! callback (callbackContext, totalHeaderSent, requestHeader.getSize()))
  208880. {
  208881. closeSocket();
  208882. return false;
  208883. }
  208884. }
  208885. const String responseHeader (readResponse());
  208886. if (responseHeader.isNotEmpty())
  208887. {
  208888. //DBG (responseHeader);
  208889. StringArray lines;
  208890. lines.addLines (responseHeader);
  208891. // NB - using charToString() here instead of just T(" "), because that was
  208892. // causing a mysterious gcc internal compiler error...
  208893. const int statusCode = responseHeader.fromFirstOccurrenceOf (String::charToString (T(' ')), false, false)
  208894. .substring (0, 3)
  208895. .getIntValue();
  208896. //int contentLength = findHeaderItem (lines, T("Content-Length:")).getIntValue();
  208897. //bool isChunked = findHeaderItem (lines, T("Transfer-Encoding:")).equalsIgnoreCase ("chunked");
  208898. String location (findHeaderItem (lines, T("Location:")));
  208899. if (statusCode >= 300 && statusCode < 400
  208900. && location.isNotEmpty())
  208901. {
  208902. if (! location.startsWithIgnoreCase (T("http://")))
  208903. location = T("http://") + location;
  208904. if (levelsOfRedirection++ < 3)
  208905. return open (location, headers, postData, isPost, callback, callbackContext);
  208906. }
  208907. else
  208908. {
  208909. levelsOfRedirection = 0;
  208910. return true;
  208911. }
  208912. }
  208913. closeSocket();
  208914. return false;
  208915. }
  208916. int read (void* buffer, int bytesToRead)
  208917. {
  208918. fd_set readbits;
  208919. FD_ZERO (&readbits);
  208920. FD_SET (socketHandle, &readbits);
  208921. struct timeval tv;
  208922. tv.tv_sec = timeoutSeconds;
  208923. tv.tv_usec = 0;
  208924. if (select (socketHandle + 1, &readbits, 0, 0, &tv) <= 0)
  208925. return 0; // (timeout)
  208926. const int bytesRead = jmax (0, recv (socketHandle, buffer, bytesToRead, MSG_WAITALL));
  208927. readPosition += bytesRead;
  208928. return bytesRead;
  208929. }
  208930. int readPosition;
  208931. juce_UseDebuggingNewOperator
  208932. private:
  208933. int socketHandle, levelsOfRedirection;
  208934. const int timeoutSeconds;
  208935. void closeSocket()
  208936. {
  208937. if (socketHandle >= 0)
  208938. close (socketHandle);
  208939. socketHandle = -1;
  208940. }
  208941. const MemoryBlock createRequestHeader (const String& hostName,
  208942. const String& hostPath,
  208943. const String& proxyURL,
  208944. const String& originalURL,
  208945. const int hostPort,
  208946. const String& headers,
  208947. const MemoryBlock& postData,
  208948. const bool isPost)
  208949. {
  208950. String header (isPost ? "POST " : "GET ");
  208951. if (proxyURL.isEmpty())
  208952. {
  208953. header << hostPath << " HTTP/1.0\r\nHost: "
  208954. << hostName << ':' << hostPort;
  208955. }
  208956. else
  208957. {
  208958. String proxyName, proxyPath;
  208959. int proxyPort;
  208960. if (! decomposeURL (proxyURL, proxyName, proxyPath, proxyPort))
  208961. return MemoryBlock();
  208962. header << originalURL << " HTTP/1.0\r\nHost: "
  208963. << proxyName << ':' << proxyPort;
  208964. /* xxx needs finishing
  208965. const char* proxyAuth = getenv ("http_proxy_auth");
  208966. if (proxyAuth != 0)
  208967. header << T("\r\nProxy-Authorization: ") << Base64Encode (proxyAuth);
  208968. */
  208969. }
  208970. header << "\r\nUser-Agent: JUCE/"
  208971. << JUCE_MAJOR_VERSION << '.' << JUCE_MINOR_VERSION
  208972. << "\r\nConnection: Close\r\nContent-Length: "
  208973. << postData.getSize() << "\r\n"
  208974. << headers << "\r\n";
  208975. MemoryBlock mb;
  208976. mb.append (header.toUTF8(), (int) strlen (header.toUTF8()));
  208977. mb.append (postData.getData(), postData.getSize());
  208978. return mb;
  208979. }
  208980. const String readResponse()
  208981. {
  208982. int bytesRead = 0, numConsecutiveLFs = 0;
  208983. MemoryBlock buffer (1024, true);
  208984. while (numConsecutiveLFs < 2 && bytesRead < 32768)
  208985. {
  208986. fd_set readbits;
  208987. FD_ZERO (&readbits);
  208988. FD_SET (socketHandle, &readbits);
  208989. struct timeval tv;
  208990. tv.tv_sec = timeoutSeconds;
  208991. tv.tv_usec = 0;
  208992. if (select (socketHandle + 1, &readbits, 0, 0, &tv) <= 0)
  208993. return String::empty; // (timeout)
  208994. buffer.ensureSize (bytesRead + 8, true);
  208995. char* const dest = (char*) buffer.getData() + bytesRead;
  208996. if (recv (socketHandle, dest, 1, 0) == -1)
  208997. return String::empty;
  208998. const char lastByte = *dest;
  208999. ++bytesRead;
  209000. if (lastByte == '\n')
  209001. ++numConsecutiveLFs;
  209002. else if (lastByte != '\r')
  209003. numConsecutiveLFs = 0;
  209004. }
  209005. const String header (String::fromUTF8 ((const uint8*) buffer.getData()));
  209006. if (header.startsWithIgnoreCase (T("HTTP/")))
  209007. return header.trimEnd();
  209008. return String::empty;
  209009. }
  209010. static bool decomposeURL (const String& url,
  209011. String& host, String& path, int& port)
  209012. {
  209013. if (! url.startsWithIgnoreCase (T("http://")))
  209014. return false;
  209015. const int nextSlash = url.indexOfChar (7, '/');
  209016. int nextColon = url.indexOfChar (7, ':');
  209017. if (nextColon > nextSlash && nextSlash > 0)
  209018. nextColon = -1;
  209019. if (nextColon >= 0)
  209020. {
  209021. host = url.substring (7, nextColon);
  209022. if (nextSlash >= 0)
  209023. port = url.substring (nextColon + 1, nextSlash).getIntValue();
  209024. else
  209025. port = url.substring (nextColon + 1).getIntValue();
  209026. }
  209027. else
  209028. {
  209029. port = 80;
  209030. if (nextSlash >= 0)
  209031. host = url.substring (7, nextSlash);
  209032. else
  209033. host = url.substring (7);
  209034. }
  209035. if (nextSlash >= 0)
  209036. path = url.substring (nextSlash);
  209037. else
  209038. path = T("/");
  209039. return true;
  209040. }
  209041. static const String findHeaderItem (const StringArray& lines, const String& itemName)
  209042. {
  209043. for (int i = 0; i < lines.size(); ++i)
  209044. if (lines[i].startsWithIgnoreCase (itemName))
  209045. return lines[i].substring (itemName.length()).trim();
  209046. return String::empty;
  209047. }
  209048. };
  209049. bool juce_isOnLine()
  209050. {
  209051. return true;
  209052. }
  209053. void* juce_openInternetFile (const String& url,
  209054. const String& headers,
  209055. const MemoryBlock& postData,
  209056. const bool isPost,
  209057. URL::OpenStreamProgressCallback* callback,
  209058. void* callbackContext)
  209059. {
  209060. JUCE_HTTPSocketStream* const s = new JUCE_HTTPSocketStream();
  209061. if (s->open (url, headers, postData, isPost,
  209062. callback, callbackContext))
  209063. return s;
  209064. delete s;
  209065. return 0;
  209066. }
  209067. void juce_closeInternetFile (void* handle)
  209068. {
  209069. JUCE_HTTPSocketStream* const s = (JUCE_HTTPSocketStream*) handle;
  209070. if (s != 0)
  209071. delete s;
  209072. }
  209073. int juce_readFromInternetFile (void* handle, void* buffer, int bytesToRead)
  209074. {
  209075. JUCE_HTTPSocketStream* const s = (JUCE_HTTPSocketStream*) handle;
  209076. if (s != 0)
  209077. return s->read (buffer, bytesToRead);
  209078. return 0;
  209079. }
  209080. int juce_seekInInternetFile (void* handle, int newPosition)
  209081. {
  209082. JUCE_HTTPSocketStream* const s = (JUCE_HTTPSocketStream*) handle;
  209083. if (s != 0)
  209084. return s->readPosition;
  209085. return 0;
  209086. }
  209087. /********* End of inlined file: juce_mac_HTTPStream.h *********/
  209088. int SystemStats::getMACAddresses (int64* addresses, int maxNum, const bool littleEndian) throw()
  209089. {
  209090. int numResults = 0;
  209091. const int s = socket (AF_INET, SOCK_DGRAM, 0);
  209092. if (s != -1)
  209093. {
  209094. char buf [1024];
  209095. struct ifconf ifc;
  209096. ifc.ifc_len = sizeof (buf);
  209097. ifc.ifc_buf = buf;
  209098. ioctl (s, SIOCGIFCONF, &ifc);
  209099. for (unsigned int i = 0; i < ifc.ifc_len / sizeof (struct ifreq); ++i)
  209100. {
  209101. struct ifreq ifr;
  209102. strcpy (ifr.ifr_name, ifc.ifc_req[i].ifr_name);
  209103. if (ioctl (s, SIOCGIFFLAGS, &ifr) == 0
  209104. && (ifr.ifr_flags & IFF_LOOPBACK) == 0
  209105. && ioctl (s, SIOCGIFHWADDR, &ifr) == 0
  209106. && numResults < maxNum)
  209107. {
  209108. int64 a = 0;
  209109. for (int j = 6; --j >= 0;)
  209110. a = (a << 8) | ifr.ifr_hwaddr.sa_data[j];
  209111. *addresses++ = a;
  209112. ++numResults;
  209113. }
  209114. }
  209115. close (s);
  209116. }
  209117. return numResults;
  209118. }
  209119. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  209120. const String& emailSubject,
  209121. const String& bodyText,
  209122. const StringArray& filesToAttach)
  209123. {
  209124. jassertfalse // xxx todo
  209125. return false;
  209126. }
  209127. END_JUCE_NAMESPACE
  209128. /********* End of inlined file: juce_linux_Network.cpp *********/
  209129. /********* Start of inlined file: juce_linux_SystemStats.cpp *********/
  209130. #include <sys/sysinfo.h>
  209131. #include <dlfcn.h>
  209132. #ifndef CPU_ISSET
  209133. #undef SUPPORT_AFFINITIES
  209134. #endif
  209135. BEGIN_JUCE_NAMESPACE
  209136. /*static juce_noinline unsigned int getCPUIDWord (int* familyModel, int* extFeatures) throw()
  209137. {
  209138. unsigned int cpu = 0;
  209139. unsigned int ext = 0;
  209140. unsigned int family = 0;
  209141. unsigned int dummy = 0;
  209142. #if JUCE_64BIT
  209143. __asm__ ("cpuid"
  209144. : "=a" (family), "=b" (ext), "=c" (dummy), "=d" (cpu) : "a" (1));
  209145. #else
  209146. __asm__ ("push %%ebx; cpuid; mov %%ebx, %%edi; pop %%ebx"
  209147. : "=a" (family), "=D" (ext), "=c" (dummy), "=d" (cpu) : "a" (1));
  209148. #endif
  209149. if (familyModel != 0)
  209150. *familyModel = family;
  209151. if (extFeatures != 0)
  209152. *extFeatures = ext;
  209153. return cpu;
  209154. }*/
  209155. void Logger::outputDebugString (const String& text) throw()
  209156. {
  209157. fprintf (stdout, text.toUTF8());
  209158. fprintf (stdout, "\n");
  209159. }
  209160. void Logger::outputDebugPrintf (const tchar* format, ...) throw()
  209161. {
  209162. String text;
  209163. va_list args;
  209164. va_start (args, format);
  209165. text.vprintf(format, args);
  209166. outputDebugString(text);
  209167. }
  209168. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType() throw()
  209169. {
  209170. return Linux;
  209171. }
  209172. const String SystemStats::getOperatingSystemName() throw()
  209173. {
  209174. return T("Linux");
  209175. }
  209176. bool SystemStats::isOperatingSystem64Bit() throw()
  209177. {
  209178. #if JUCE_64BIT
  209179. return true;
  209180. #else
  209181. //xxx not sure how to find this out?..
  209182. return false;
  209183. #endif
  209184. }
  209185. static const String getCpuInfo (const char* key, bool lastOne = false) throw()
  209186. {
  209187. String info;
  209188. char buf [256];
  209189. FILE* f = fopen ("/proc/cpuinfo", "r");
  209190. while (f != 0 && fgets (buf, sizeof(buf), f))
  209191. {
  209192. if (strncmp (buf, key, strlen (key)) == 0)
  209193. {
  209194. char* p = buf;
  209195. while (*p && *p != '\n')
  209196. ++p;
  209197. if (*p != 0)
  209198. *p = 0;
  209199. p = buf;
  209200. while (*p != 0 && *p != ':')
  209201. ++p;
  209202. if (*p != 0 && *(p + 1) != 0)
  209203. info = p + 2;
  209204. if (! lastOne)
  209205. break;
  209206. }
  209207. }
  209208. fclose (f);
  209209. return info;
  209210. }
  209211. bool SystemStats::hasMMX() throw()
  209212. {
  209213. return getCpuInfo ("flags").contains (T("mmx"));
  209214. }
  209215. bool SystemStats::hasSSE() throw()
  209216. {
  209217. return getCpuInfo ("flags").contains (T("sse"));
  209218. }
  209219. bool SystemStats::hasSSE2() throw()
  209220. {
  209221. return getCpuInfo ("flags").contains (T("sse2"));
  209222. }
  209223. bool SystemStats::has3DNow() throw()
  209224. {
  209225. return getCpuInfo ("flags").contains (T("3dnow"));
  209226. }
  209227. const String SystemStats::getCpuVendor() throw()
  209228. {
  209229. return getCpuInfo ("vendor_id");
  209230. }
  209231. int SystemStats::getCpuSpeedInMegaherz() throw()
  209232. {
  209233. const String speed (getCpuInfo ("cpu MHz"));
  209234. return (int) (speed.getFloatValue() + 0.5f);
  209235. }
  209236. int SystemStats::getMemorySizeInMegabytes() throw()
  209237. {
  209238. struct sysinfo sysi;
  209239. if (sysinfo (&sysi) == 0)
  209240. return (sysi.totalram * sysi.mem_unit / (1024 * 1024));
  209241. return 0;
  209242. }
  209243. uint32 juce_millisecondsSinceStartup() throw()
  209244. {
  209245. static unsigned int calibrate = 0;
  209246. static bool calibrated = false;
  209247. timeval t;
  209248. unsigned int ret = 0;
  209249. if (! gettimeofday (&t, 0))
  209250. {
  209251. if (! calibrated)
  209252. {
  209253. struct sysinfo sysi;
  209254. if (sysinfo (&sysi) == 0)
  209255. // Safe to assume system was not brought up earlier than 1970!
  209256. calibrate = t.tv_sec - sysi.uptime;
  209257. calibrated = true;
  209258. }
  209259. ret = 1000 * (t.tv_sec - calibrate) + (t.tv_usec / 1000);
  209260. }
  209261. return ret;
  209262. }
  209263. double Time::getMillisecondCounterHiRes() throw()
  209264. {
  209265. return getHighResolutionTicks() * 0.001;
  209266. }
  209267. int64 Time::getHighResolutionTicks() throw()
  209268. {
  209269. timeval t;
  209270. if (gettimeofday (&t, 0))
  209271. return 0;
  209272. return ((int64) t.tv_sec * (int64) 1000000) + (int64) t.tv_usec;
  209273. }
  209274. int64 Time::getHighResolutionTicksPerSecond() throw()
  209275. {
  209276. // Microseconds
  209277. return 1000000;
  209278. }
  209279. bool Time::setSystemTimeToThisTime() const throw()
  209280. {
  209281. timeval t;
  209282. t.tv_sec = millisSinceEpoch % 1000000;
  209283. t.tv_usec = millisSinceEpoch - t.tv_sec;
  209284. return settimeofday (&t, NULL) ? false : true;
  209285. }
  209286. int SystemStats::getPageSize() throw()
  209287. {
  209288. static int systemPageSize = 0;
  209289. if (systemPageSize == 0)
  209290. systemPageSize = sysconf (_SC_PAGESIZE);
  209291. return systemPageSize;
  209292. }
  209293. int SystemStats::getNumCpus() throw()
  209294. {
  209295. const int lastCpu = getCpuInfo ("processor", true).getIntValue();
  209296. return lastCpu + 1;
  209297. }
  209298. void SystemStats::initialiseStats() throw()
  209299. {
  209300. // Process starts off as root when running suid
  209301. Process::lowerPrivilege();
  209302. String s (SystemStats::getJUCEVersion());
  209303. }
  209304. void PlatformUtilities::fpuReset()
  209305. {
  209306. }
  209307. END_JUCE_NAMESPACE
  209308. /********* End of inlined file: juce_linux_SystemStats.cpp *********/
  209309. /********* Start of inlined file: juce_linux_Threads.cpp *********/
  209310. #include <dlfcn.h>
  209311. #include <sys/file.h>
  209312. #include <sys/types.h>
  209313. #include <sys/ptrace.h>
  209314. BEGIN_JUCE_NAMESPACE
  209315. /*
  209316. Note that a lot of methods that you'd expect to find in this file actually
  209317. live in juce_posix_SharedCode.cpp!
  209318. */
  209319. #ifndef CPU_ISSET
  209320. #undef SUPPORT_AFFINITIES
  209321. #endif
  209322. void JUCE_API juce_threadEntryPoint (void*);
  209323. void* threadEntryProc (void* value) throw()
  209324. {
  209325. // New threads start off as root when running suid
  209326. Process::lowerPrivilege();
  209327. juce_threadEntryPoint (value);
  209328. return 0;
  209329. }
  209330. void* juce_createThread (void* userData) throw()
  209331. {
  209332. pthread_t handle = 0;
  209333. if (pthread_create (&handle, 0, threadEntryProc, userData) == 0)
  209334. {
  209335. pthread_detach (handle);
  209336. return (void*)handle;
  209337. }
  209338. return 0;
  209339. }
  209340. void juce_killThread (void* handle) throw()
  209341. {
  209342. if (handle != 0)
  209343. pthread_cancel ((pthread_t)handle);
  209344. }
  209345. void juce_setCurrentThreadName (const String& /*name*/) throw()
  209346. {
  209347. }
  209348. int Thread::getCurrentThreadId() throw()
  209349. {
  209350. return (int) pthread_self();
  209351. }
  209352. /*
  209353. * This is all a bit non-ideal... the trouble is that on Linux you
  209354. * need to call setpriority to affect the dynamic priority for
  209355. * non-realtime processes, but this requires the pid, which is not
  209356. * accessible from the pthread_t. We could get it by calling getpid
  209357. * once each thread has started, but then we would need a list of
  209358. * running threads etc etc.
  209359. * Also there is no such thing as IDLE priority on Linux.
  209360. * For the moment, map idle, low and normal process priorities to
  209361. * SCHED_OTHER, with the thread priority ignored for these classes.
  209362. * Map high priority processes to the lower half of the SCHED_RR
  209363. * range, and realtime to the upper half
  209364. */
  209365. // priority 1 to 10 where 5=normal, 1=low. If the handle is 0, sets the
  209366. // priority of the current thread
  209367. void juce_setThreadPriority (void* handle, int priority) throw()
  209368. {
  209369. struct sched_param param;
  209370. int policy, maxp, minp, pri;
  209371. if (handle == 0)
  209372. handle = (void*) pthread_self();
  209373. if (pthread_getschedparam ((pthread_t) handle, &policy, &param) == 0
  209374. && policy != SCHED_OTHER)
  209375. {
  209376. minp = sched_get_priority_min(policy);
  209377. maxp = sched_get_priority_max(policy);
  209378. pri = ((maxp - minp) / 2) * (priority - 1) / 9;
  209379. if (param.__sched_priority >= (minp + (maxp - minp) / 2))
  209380. // Realtime process priority
  209381. param.__sched_priority = minp + ((maxp - minp) / 2) + pri;
  209382. else
  209383. // High process priority
  209384. param.__sched_priority = minp + pri;
  209385. param.sched_priority = jlimit (1, 127, 1 + (priority * 126) / 11);
  209386. pthread_setschedparam ((pthread_t) handle, policy, &param);
  209387. }
  209388. }
  209389. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask) throw()
  209390. {
  209391. #if SUPPORT_AFFINITIES
  209392. cpu_set_t affinity;
  209393. CPU_ZERO (&affinity);
  209394. for (int i = 0; i < 32; ++i)
  209395. if ((affinityMask & (1 << i)) != 0)
  209396. CPU_SET (i, &affinity);
  209397. /*
  209398. N.B. If this line causes a compile error, then you've probably not got the latest
  209399. version of glibc installed.
  209400. If you don't want to update your copy of glibc and don't care about cpu affinities,
  209401. then you can just disable all this stuff by removing the SUPPORT_AFFINITIES macro
  209402. from the linuxincludes.h file.
  209403. */
  209404. sched_setaffinity (getpid(), sizeof (cpu_set_t), &affinity);
  209405. sched_yield();
  209406. #else
  209407. /* affinities aren't supported because either the appropriate header files weren't found,
  209408. or the SUPPORT_AFFINITIES macro was turned off in linuxheaders.h
  209409. */
  209410. jassertfalse
  209411. #endif
  209412. }
  209413. void Thread::yield() throw()
  209414. {
  209415. sched_yield();
  209416. }
  209417. // sets the process to 0=low priority, 1=normal, 2=high, 3=realtime
  209418. void Process::setPriority (ProcessPriority prior)
  209419. {
  209420. struct sched_param param;
  209421. int policy, maxp, minp;
  209422. const int p = (int) prior;
  209423. if (p <= 1)
  209424. policy = SCHED_OTHER;
  209425. else
  209426. policy = SCHED_RR;
  209427. minp = sched_get_priority_min (policy);
  209428. maxp = sched_get_priority_max (policy);
  209429. if (p < 2)
  209430. param.__sched_priority = 0;
  209431. else if (p == 2 )
  209432. // Set to middle of lower realtime priority range
  209433. param.__sched_priority = minp + (maxp - minp) / 4;
  209434. else
  209435. // Set to middle of higher realtime priority range
  209436. param.__sched_priority = minp + (3 * (maxp - minp) / 4);
  209437. pthread_setschedparam (pthread_self(), policy, &param);
  209438. }
  209439. void Process::terminate()
  209440. {
  209441. exit (0);
  209442. }
  209443. bool JUCE_CALLTYPE juce_isRunningUnderDebugger() throw()
  209444. {
  209445. static char testResult = 0;
  209446. if (testResult == 0)
  209447. {
  209448. testResult = (char) ptrace (PT_TRACE_ME, 0, 0, 0);
  209449. if (testResult >= 0)
  209450. {
  209451. ptrace (PT_DETACH, 0, (caddr_t) 1, 0);
  209452. testResult = 1;
  209453. }
  209454. }
  209455. return testResult < 0;
  209456. }
  209457. bool JUCE_CALLTYPE Process::isRunningUnderDebugger() throw()
  209458. {
  209459. return juce_isRunningUnderDebugger();
  209460. }
  209461. void Process::raisePrivilege()
  209462. {
  209463. // If running suid root, change effective user
  209464. // to root
  209465. if (geteuid() != 0 && getuid() == 0)
  209466. {
  209467. setreuid (geteuid(), getuid());
  209468. setregid (getegid(), getgid());
  209469. }
  209470. }
  209471. void Process::lowerPrivilege()
  209472. {
  209473. // If runing suid root, change effective user
  209474. // back to real user
  209475. if (geteuid() == 0 && getuid() != 0)
  209476. {
  209477. setreuid (geteuid(), getuid());
  209478. setregid (getegid(), getgid());
  209479. }
  209480. }
  209481. #if JUCE_BUILD_GUI_CLASSES
  209482. void* Process::loadDynamicLibrary (const String& name)
  209483. {
  209484. return dlopen ((const char*) name.toUTF8(), RTLD_LOCAL | RTLD_NOW);
  209485. }
  209486. void Process::freeDynamicLibrary (void* handle)
  209487. {
  209488. dlclose(handle);
  209489. }
  209490. void* Process::getProcedureEntryPoint (void* libraryHandle, const String& procedureName)
  209491. {
  209492. return dlsym (libraryHandle, (const char*) procedureName);
  209493. }
  209494. #endif
  209495. END_JUCE_NAMESPACE
  209496. /********* End of inlined file: juce_linux_Threads.cpp *********/
  209497. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  209498. /********* Start of inlined file: juce_linux_Audio.cpp *********/
  209499. #if JUCE_BUILD_GUI_CLASSES
  209500. #if JUCE_ALSA
  209501. /* Got an include error here? If so, you've either not got ALSA installed, or you've
  209502. not got your paths set up correctly to find its header files.
  209503. The package you need to install to get ASLA support is "libasound2-dev".
  209504. If you don't have the ALSA library and don't want to build Juce with audio support,
  209505. just disable the JUCE_ALSA flag in juce_Config.h
  209506. */
  209507. #include <alsa/asoundlib.h>
  209508. BEGIN_JUCE_NAMESPACE
  209509. static const int maxNumChans = 64;
  209510. static void getDeviceSampleRates (snd_pcm_t* handle, Array <int>& rates)
  209511. {
  209512. const int ratesToTry[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  209513. snd_pcm_hw_params_t* hwParams;
  209514. snd_pcm_hw_params_alloca (&hwParams);
  209515. for (int i = 0; ratesToTry[i] != 0; ++i)
  209516. {
  209517. if (snd_pcm_hw_params_any (handle, hwParams) >= 0
  209518. && snd_pcm_hw_params_test_rate (handle, hwParams, ratesToTry[i], 0) == 0)
  209519. {
  209520. rates.add (ratesToTry[i]);
  209521. }
  209522. }
  209523. }
  209524. static void getDeviceNumChannels (snd_pcm_t* handle, unsigned int* minChans, unsigned int* maxChans)
  209525. {
  209526. snd_pcm_hw_params_t *params;
  209527. snd_pcm_hw_params_alloca (&params);
  209528. if (snd_pcm_hw_params_any (handle, params) >= 0)
  209529. {
  209530. snd_pcm_hw_params_get_channels_min (params, minChans);
  209531. snd_pcm_hw_params_get_channels_max (params, maxChans);
  209532. }
  209533. }
  209534. static void getDeviceProperties (const String& id,
  209535. unsigned int& minChansOut,
  209536. unsigned int& maxChansOut,
  209537. unsigned int& minChansIn,
  209538. unsigned int& maxChansIn,
  209539. Array <int>& rates)
  209540. {
  209541. snd_ctl_t* handle;
  209542. if (snd_ctl_open (&handle, id.upToLastOccurrenceOf (T(","), false, false), SND_CTL_NONBLOCK) >= 0)
  209543. {
  209544. snd_pcm_info_t* info;
  209545. snd_pcm_info_alloca (&info);
  209546. snd_pcm_info_set_stream (info, SND_PCM_STREAM_PLAYBACK);
  209547. snd_pcm_info_set_device (info, id.fromLastOccurrenceOf (T(","), false, false).getIntValue());
  209548. snd_pcm_info_set_subdevice (info, 0);
  209549. if (snd_ctl_pcm_info (handle, info) >= 0)
  209550. {
  209551. snd_pcm_t* pcmHandle;
  209552. if (snd_pcm_open (&pcmHandle, id, SND_PCM_STREAM_PLAYBACK, SND_PCM_ASYNC | SND_PCM_NONBLOCK ) >= 0)
  209553. {
  209554. getDeviceNumChannels (pcmHandle, &minChansOut, &maxChansOut);
  209555. getDeviceSampleRates (pcmHandle, rates);
  209556. snd_pcm_close (pcmHandle);
  209557. }
  209558. }
  209559. snd_pcm_info_set_stream (info, SND_PCM_STREAM_CAPTURE);
  209560. if (snd_ctl_pcm_info (handle, info) >= 0)
  209561. {
  209562. snd_pcm_t* pcmHandle;
  209563. if (snd_pcm_open (&pcmHandle, id, SND_PCM_STREAM_CAPTURE, SND_PCM_ASYNC | SND_PCM_NONBLOCK ) >= 0)
  209564. {
  209565. getDeviceNumChannels (pcmHandle, &minChansIn, &maxChansIn);
  209566. if (rates.size() == 0)
  209567. getDeviceSampleRates (pcmHandle, rates);
  209568. snd_pcm_close (pcmHandle);
  209569. }
  209570. }
  209571. snd_ctl_close (handle);
  209572. }
  209573. }
  209574. class ALSADevice
  209575. {
  209576. public:
  209577. ALSADevice (const String& deviceName,
  209578. const bool forInput)
  209579. : handle (0),
  209580. bitDepth (16),
  209581. numChannelsRunning (0),
  209582. isInput (forInput),
  209583. sampleFormat (AudioDataConverters::int16LE)
  209584. {
  209585. failed (snd_pcm_open (&handle, deviceName,
  209586. forInput ? SND_PCM_STREAM_CAPTURE : SND_PCM_STREAM_PLAYBACK,
  209587. SND_PCM_ASYNC));
  209588. }
  209589. ~ALSADevice()
  209590. {
  209591. if (handle != 0)
  209592. snd_pcm_close (handle);
  209593. }
  209594. bool setParameters (unsigned int sampleRate, int numChannels, int bufferSize)
  209595. {
  209596. if (handle == 0)
  209597. return false;
  209598. snd_pcm_hw_params_t* hwParams;
  209599. snd_pcm_hw_params_alloca (&hwParams);
  209600. if (failed (snd_pcm_hw_params_any (handle, hwParams)))
  209601. return false;
  209602. if (snd_pcm_hw_params_set_access (handle, hwParams, SND_PCM_ACCESS_RW_NONINTERLEAVED) >= 0)
  209603. isInterleaved = false;
  209604. else if (snd_pcm_hw_params_set_access (handle, hwParams, SND_PCM_ACCESS_RW_INTERLEAVED) >= 0)
  209605. isInterleaved = true;
  209606. else
  209607. {
  209608. jassertfalse
  209609. return false;
  209610. }
  209611. const int formatsToTry[] = { SND_PCM_FORMAT_FLOAT_LE, 32, AudioDataConverters::float32LE,
  209612. SND_PCM_FORMAT_FLOAT_BE, 32, AudioDataConverters::float32BE,
  209613. SND_PCM_FORMAT_S32_LE, 32, AudioDataConverters::int32LE,
  209614. SND_PCM_FORMAT_S32_BE, 32, AudioDataConverters::int32BE,
  209615. SND_PCM_FORMAT_S24_LE, 24, AudioDataConverters::int24LE,
  209616. SND_PCM_FORMAT_S24_BE, 24, AudioDataConverters::int24BE,
  209617. SND_PCM_FORMAT_S16_LE, 16, AudioDataConverters::int16LE,
  209618. SND_PCM_FORMAT_S16_BE, 16, AudioDataConverters::int16BE };
  209619. bitDepth = 0;
  209620. for (int i = 0; i < numElementsInArray (formatsToTry); i += 3)
  209621. {
  209622. if (snd_pcm_hw_params_set_format (handle, hwParams, (_snd_pcm_format) formatsToTry [i]) >= 0)
  209623. {
  209624. bitDepth = formatsToTry [i + 1];
  209625. sampleFormat = (AudioDataConverters::DataFormat) formatsToTry [i + 2];
  209626. break;
  209627. }
  209628. }
  209629. if (bitDepth == 0)
  209630. {
  209631. error = "device doesn't support a compatible PCM format";
  209632. DBG (T("ALSA error: ") + error + T("\n"));
  209633. return false;
  209634. }
  209635. int dir = 0;
  209636. unsigned int periods = 4;
  209637. snd_pcm_uframes_t samplesPerPeriod = bufferSize;
  209638. if (failed (snd_pcm_hw_params_set_rate_near (handle, hwParams, &sampleRate, 0))
  209639. || failed (snd_pcm_hw_params_set_channels (handle, hwParams, numChannels))
  209640. || failed (snd_pcm_hw_params_set_periods_near (handle, hwParams, &periods, &dir))
  209641. || failed (snd_pcm_hw_params_set_period_size_near (handle, hwParams, &samplesPerPeriod, &dir))
  209642. || failed (snd_pcm_hw_params (handle, hwParams)))
  209643. {
  209644. return false;
  209645. }
  209646. snd_pcm_sw_params_t* swParams;
  209647. snd_pcm_sw_params_alloca (&swParams);
  209648. if (failed (snd_pcm_sw_params_current (handle, swParams))
  209649. || failed (snd_pcm_sw_params_set_silence_threshold (handle, swParams, 0))
  209650. || failed (snd_pcm_sw_params_set_silence_size (handle, swParams, 0))
  209651. || failed (snd_pcm_sw_params_set_start_threshold (handle, swParams, samplesPerPeriod))
  209652. || failed (snd_pcm_sw_params_set_stop_threshold (handle, swParams, INT_MAX))
  209653. || failed (snd_pcm_sw_params (handle, swParams)))
  209654. {
  209655. return false;
  209656. }
  209657. /*
  209658. #ifdef JUCE_DEBUG
  209659. // enable this to dump the config of the devices that get opened
  209660. snd_output_t* out;
  209661. snd_output_stdio_attach (&out, stderr, 0);
  209662. snd_pcm_hw_params_dump (hwParams, out);
  209663. snd_pcm_sw_params_dump (swParams, out);
  209664. #endif
  209665. */
  209666. numChannelsRunning = numChannels;
  209667. return true;
  209668. }
  209669. bool write (float** const data, const int numSamples)
  209670. {
  209671. if (isInterleaved)
  209672. {
  209673. scratch.ensureSize (sizeof (float) * numSamples * numChannelsRunning, false);
  209674. float* interleaved = (float*) scratch;
  209675. AudioDataConverters::interleaveSamples ((const float**) data, interleaved, numSamples, numChannelsRunning);
  209676. AudioDataConverters::convertFloatToFormat (sampleFormat, interleaved, interleaved, numSamples * numChannelsRunning);
  209677. snd_pcm_sframes_t num = snd_pcm_writei (handle, (void*) interleaved, numSamples);
  209678. if (failed (num) && num != -EPIPE && num != -ESTRPIPE)
  209679. return false;
  209680. }
  209681. else
  209682. {
  209683. for (int i = 0; i < numChannelsRunning; ++i)
  209684. if (data[i] != 0)
  209685. AudioDataConverters::convertFloatToFormat (sampleFormat, data[i], data[i], numSamples);
  209686. snd_pcm_sframes_t num = snd_pcm_writen (handle, (void**) data, numSamples);
  209687. if (failed (num))
  209688. {
  209689. if (num == -EPIPE)
  209690. {
  209691. if (failed (snd_pcm_prepare (handle)))
  209692. return false;
  209693. }
  209694. else if (num != -ESTRPIPE)
  209695. return false;
  209696. }
  209697. }
  209698. return true;
  209699. }
  209700. bool read (float** const data, const int numSamples)
  209701. {
  209702. if (isInterleaved)
  209703. {
  209704. scratch.ensureSize (sizeof (float) * numSamples * numChannelsRunning, false);
  209705. float* interleaved = (float*) scratch;
  209706. snd_pcm_sframes_t num = snd_pcm_readi (handle, (void*) interleaved, numSamples);
  209707. if (failed (num))
  209708. {
  209709. if (num == -EPIPE)
  209710. {
  209711. if (failed (snd_pcm_prepare (handle)))
  209712. return false;
  209713. }
  209714. else if (num != -ESTRPIPE)
  209715. return false;
  209716. }
  209717. AudioDataConverters::convertFormatToFloat (sampleFormat, interleaved, interleaved, numSamples * numChannelsRunning);
  209718. AudioDataConverters::deinterleaveSamples (interleaved, data, numSamples, numChannelsRunning);
  209719. }
  209720. else
  209721. {
  209722. snd_pcm_sframes_t num = snd_pcm_readn (handle, (void**) data, numSamples);
  209723. if (failed (num) && num != -EPIPE && num != -ESTRPIPE)
  209724. return false;
  209725. for (int i = 0; i < numChannelsRunning; ++i)
  209726. if (data[i] != 0)
  209727. AudioDataConverters::convertFormatToFloat (sampleFormat, data[i], data[i], numSamples);
  209728. }
  209729. return true;
  209730. }
  209731. juce_UseDebuggingNewOperator
  209732. snd_pcm_t* handle;
  209733. String error;
  209734. int bitDepth, numChannelsRunning;
  209735. private:
  209736. const bool isInput;
  209737. bool isInterleaved;
  209738. MemoryBlock scratch;
  209739. AudioDataConverters::DataFormat sampleFormat;
  209740. bool failed (const int errorNum)
  209741. {
  209742. if (errorNum >= 0)
  209743. return false;
  209744. error = snd_strerror (errorNum);
  209745. DBG (T("ALSA error: ") + error + T("\n"));
  209746. return true;
  209747. }
  209748. };
  209749. class ALSAThread : public Thread
  209750. {
  209751. public:
  209752. ALSAThread (const String& deviceName_)
  209753. : Thread ("Juce ALSA"),
  209754. sampleRate (0),
  209755. bufferSize (0),
  209756. callback (0),
  209757. deviceName (deviceName_),
  209758. outputDevice (0),
  209759. inputDevice (0),
  209760. numCallbacks (0),
  209761. totalNumInputChannels (0),
  209762. totalNumOutputChannels (0)
  209763. {
  209764. zeromem (outputChannelData, sizeof (outputChannelData));
  209765. zeromem (outputChannelDataForCallback, sizeof (outputChannelDataForCallback));
  209766. zeromem (inputChannelData, sizeof (inputChannelData));
  209767. zeromem (inputChannelDataForCallback, sizeof (inputChannelDataForCallback));
  209768. initialiseRatesAndChannels();
  209769. }
  209770. ~ALSAThread()
  209771. {
  209772. close();
  209773. }
  209774. void open (const BitArray& inputChannels,
  209775. const BitArray& outputChannels,
  209776. const double sampleRate_,
  209777. const int bufferSize_)
  209778. {
  209779. close();
  209780. error = String::empty;
  209781. sampleRate = sampleRate_;
  209782. bufferSize = bufferSize_;
  209783. currentInputChans.clear();
  209784. currentOutputChans.clear();
  209785. numChannelsRunning = jmax (inputChannels.getHighestBit(),
  209786. outputChannels.getHighestBit()) + 1;
  209787. numChannelsRunning = jmin (maxNumChans, jlimit ((int) minChansIn,
  209788. (int) maxChansIn,
  209789. numChannelsRunning));
  209790. if (inputChannels.getHighestBit() >= 0)
  209791. {
  209792. for (int i = 0; i < numChannelsRunning; ++i)
  209793. {
  209794. inputChannelData [i] = (float*) juce_calloc (sizeof (float) * bufferSize);
  209795. if (inputChannels[i])
  209796. {
  209797. inputChannelDataForCallback [totalNumInputChannels++] = inputChannelData [i];
  209798. currentInputChans.setBit (i);
  209799. }
  209800. }
  209801. }
  209802. if (outputChannels.getHighestBit() >= 0)
  209803. {
  209804. for (int i = 0; i < numChannelsRunning; ++i)
  209805. {
  209806. outputChannelData [i] = (float*) juce_calloc (sizeof (float) * bufferSize);
  209807. if (outputChannels[i])
  209808. {
  209809. outputChannelDataForCallback [totalNumOutputChannels++] = outputChannelData [i];
  209810. currentOutputChans.setBit (i);
  209811. }
  209812. }
  209813. }
  209814. if (totalNumOutputChannels > 0)
  209815. {
  209816. outputDevice = new ALSADevice (deviceName, false);
  209817. if (outputDevice->error.isNotEmpty())
  209818. {
  209819. error = outputDevice->error;
  209820. deleteAndZero (outputDevice);
  209821. return;
  209822. }
  209823. if (! outputDevice->setParameters ((unsigned int) sampleRate, numChannelsRunning, bufferSize))
  209824. {
  209825. error = outputDevice->error;
  209826. deleteAndZero (outputDevice);
  209827. return;
  209828. }
  209829. }
  209830. if (totalNumInputChannels > 0)
  209831. {
  209832. inputDevice = new ALSADevice (deviceName, true);
  209833. if (inputDevice->error.isNotEmpty())
  209834. {
  209835. error = inputDevice->error;
  209836. deleteAndZero (inputDevice);
  209837. return;
  209838. }
  209839. if (! inputDevice->setParameters ((unsigned int) sampleRate, numChannelsRunning, bufferSize))
  209840. {
  209841. error = inputDevice->error;
  209842. deleteAndZero (inputDevice);
  209843. return;
  209844. }
  209845. }
  209846. if (outputDevice == 0 && inputDevice == 0)
  209847. {
  209848. error = "no channels";
  209849. return;
  209850. }
  209851. if (outputDevice != 0 && inputDevice != 0)
  209852. {
  209853. snd_pcm_link (outputDevice->handle, inputDevice->handle);
  209854. }
  209855. if (inputDevice != 0 && failed (snd_pcm_prepare (inputDevice->handle)))
  209856. return;
  209857. if (outputDevice != 0 && failed (snd_pcm_prepare (outputDevice->handle)))
  209858. return;
  209859. startThread (9);
  209860. int count = 1000;
  209861. while (numCallbacks == 0)
  209862. {
  209863. sleep (5);
  209864. if (--count < 0 || ! isThreadRunning())
  209865. {
  209866. error = "device didn't start";
  209867. break;
  209868. }
  209869. }
  209870. }
  209871. void close()
  209872. {
  209873. stopThread (6000);
  209874. deleteAndZero (inputDevice);
  209875. deleteAndZero (outputDevice);
  209876. for (int i = 0; i < maxNumChans; ++i)
  209877. {
  209878. juce_free (inputChannelData [i]);
  209879. juce_free (outputChannelData [i]);
  209880. }
  209881. zeromem (outputChannelData, sizeof (outputChannelData));
  209882. zeromem (outputChannelDataForCallback, sizeof (outputChannelDataForCallback));
  209883. zeromem (inputChannelData, sizeof (inputChannelData));
  209884. zeromem (inputChannelDataForCallback, sizeof (inputChannelDataForCallback));
  209885. totalNumOutputChannels = 0;
  209886. totalNumInputChannels = 0;
  209887. numChannelsRunning = 0;
  209888. numCallbacks = 0;
  209889. }
  209890. void setCallback (AudioIODeviceCallback* const newCallback) throw()
  209891. {
  209892. const ScopedLock sl (callbackLock);
  209893. callback = newCallback;
  209894. }
  209895. void run()
  209896. {
  209897. while (! threadShouldExit())
  209898. {
  209899. if (inputDevice != 0)
  209900. {
  209901. jassert (numChannelsRunning >= inputDevice->numChannelsRunning);
  209902. if (! inputDevice->read (inputChannelData, bufferSize))
  209903. {
  209904. DBG ("ALSA: read failure");
  209905. break;
  209906. }
  209907. }
  209908. if (threadShouldExit())
  209909. break;
  209910. {
  209911. const ScopedLock sl (callbackLock);
  209912. ++numCallbacks;
  209913. if (callback != 0)
  209914. {
  209915. callback->audioDeviceIOCallback ((const float**) inputChannelDataForCallback,
  209916. totalNumInputChannels,
  209917. outputChannelDataForCallback,
  209918. totalNumOutputChannels,
  209919. bufferSize);
  209920. }
  209921. else
  209922. {
  209923. for (int i = 0; i < totalNumOutputChannels; ++i)
  209924. zeromem (outputChannelDataForCallback[i], sizeof (float) * bufferSize);
  209925. }
  209926. }
  209927. if (outputDevice != 0)
  209928. {
  209929. failed (snd_pcm_wait (outputDevice->handle, 2000));
  209930. if (threadShouldExit())
  209931. break;
  209932. failed (snd_pcm_avail_update (outputDevice->handle));
  209933. jassert (numChannelsRunning >= outputDevice->numChannelsRunning);
  209934. if (! outputDevice->write (outputChannelData, bufferSize))
  209935. {
  209936. DBG ("ALSA: write failure");
  209937. break;
  209938. }
  209939. }
  209940. }
  209941. }
  209942. int getBitDepth() const throw()
  209943. {
  209944. if (outputDevice != 0)
  209945. return outputDevice->bitDepth;
  209946. if (inputDevice != 0)
  209947. return inputDevice->bitDepth;
  209948. return 16;
  209949. }
  209950. juce_UseDebuggingNewOperator
  209951. String error;
  209952. double sampleRate;
  209953. int bufferSize;
  209954. BitArray currentInputChans, currentOutputChans;
  209955. Array <int> sampleRates;
  209956. StringArray channelNamesOut, channelNamesIn;
  209957. AudioIODeviceCallback* callback;
  209958. private:
  209959. const String deviceName;
  209960. ALSADevice* outputDevice;
  209961. ALSADevice* inputDevice;
  209962. int numCallbacks;
  209963. CriticalSection callbackLock;
  209964. float* outputChannelData [maxNumChans];
  209965. float* outputChannelDataForCallback [maxNumChans];
  209966. int totalNumInputChannels;
  209967. float* inputChannelData [maxNumChans];
  209968. float* inputChannelDataForCallback [maxNumChans];
  209969. int totalNumOutputChannels;
  209970. int numChannelsRunning;
  209971. unsigned int minChansOut, maxChansOut;
  209972. unsigned int minChansIn, maxChansIn;
  209973. bool failed (const int errorNum) throw()
  209974. {
  209975. if (errorNum >= 0)
  209976. return false;
  209977. error = snd_strerror (errorNum);
  209978. DBG (T("ALSA error: ") + error + T("\n"));
  209979. return true;
  209980. }
  209981. void initialiseRatesAndChannels() throw()
  209982. {
  209983. sampleRates.clear();
  209984. channelNamesOut.clear();
  209985. channelNamesIn.clear();
  209986. minChansOut = 0;
  209987. maxChansOut = 0;
  209988. minChansIn = 0;
  209989. maxChansIn = 0;
  209990. getDeviceProperties (deviceName, minChansOut, maxChansOut, minChansIn, maxChansIn, sampleRates);
  209991. unsigned int i;
  209992. for (i = 0; i < maxChansOut; ++i)
  209993. channelNamesOut.add (T("channel ") + String ((int) i + 1));
  209994. for (i = 0; i < maxChansIn; ++i)
  209995. channelNamesIn.add (T("channel ") + String ((int) i + 1));
  209996. }
  209997. };
  209998. class ALSAAudioIODevice : public AudioIODevice
  209999. {
  210000. public:
  210001. ALSAAudioIODevice (const String& deviceName,
  210002. const String& deviceId)
  210003. : AudioIODevice (deviceName, T("ALSA")),
  210004. isOpen_ (false),
  210005. isStarted (false),
  210006. internal (0)
  210007. {
  210008. internal = new ALSAThread (deviceId);
  210009. }
  210010. ~ALSAAudioIODevice()
  210011. {
  210012. delete internal;
  210013. }
  210014. const StringArray getOutputChannelNames()
  210015. {
  210016. return internal->channelNamesOut;
  210017. }
  210018. const StringArray getInputChannelNames()
  210019. {
  210020. return internal->channelNamesIn;
  210021. }
  210022. int getNumSampleRates()
  210023. {
  210024. return internal->sampleRates.size();
  210025. }
  210026. double getSampleRate (int index)
  210027. {
  210028. return internal->sampleRates [index];
  210029. }
  210030. int getNumBufferSizesAvailable()
  210031. {
  210032. return 50;
  210033. }
  210034. int getBufferSizeSamples (int index)
  210035. {
  210036. int n = 16;
  210037. for (int i = 0; i < index; ++i)
  210038. n += n < 64 ? 16
  210039. : (n < 512 ? 32
  210040. : (n < 1024 ? 64
  210041. : (n < 2048 ? 128 : 256)));
  210042. return n;
  210043. }
  210044. int getDefaultBufferSize()
  210045. {
  210046. return 512;
  210047. }
  210048. const String open (const BitArray& inputChannels,
  210049. const BitArray& outputChannels,
  210050. double sampleRate,
  210051. int bufferSizeSamples)
  210052. {
  210053. close();
  210054. if (bufferSizeSamples <= 0)
  210055. bufferSizeSamples = getDefaultBufferSize();
  210056. if (sampleRate <= 0)
  210057. {
  210058. for (int i = 0; i < getNumSampleRates(); ++i)
  210059. {
  210060. if (getSampleRate (i) >= 44100)
  210061. {
  210062. sampleRate = getSampleRate (i);
  210063. break;
  210064. }
  210065. }
  210066. }
  210067. internal->open (inputChannels, outputChannels,
  210068. sampleRate, bufferSizeSamples);
  210069. isOpen_ = internal->error.isEmpty();
  210070. return internal->error;
  210071. }
  210072. void close()
  210073. {
  210074. stop();
  210075. internal->close();
  210076. isOpen_ = false;
  210077. }
  210078. bool isOpen()
  210079. {
  210080. return isOpen_;
  210081. }
  210082. int getCurrentBufferSizeSamples()
  210083. {
  210084. return internal->bufferSize;
  210085. }
  210086. double getCurrentSampleRate()
  210087. {
  210088. return internal->sampleRate;
  210089. }
  210090. int getCurrentBitDepth()
  210091. {
  210092. return internal->getBitDepth();
  210093. }
  210094. const BitArray getActiveOutputChannels() const
  210095. {
  210096. return internal->currentOutputChans;
  210097. }
  210098. const BitArray getActiveInputChannels() const
  210099. {
  210100. return internal->currentInputChans;
  210101. }
  210102. int getOutputLatencyInSamples()
  210103. {
  210104. return 0;
  210105. }
  210106. int getInputLatencyInSamples()
  210107. {
  210108. return 0;
  210109. }
  210110. void start (AudioIODeviceCallback* callback)
  210111. {
  210112. if (! isOpen_)
  210113. callback = 0;
  210114. internal->setCallback (callback);
  210115. if (callback != 0)
  210116. callback->audioDeviceAboutToStart (this);
  210117. isStarted = (callback != 0);
  210118. }
  210119. void stop()
  210120. {
  210121. AudioIODeviceCallback* const oldCallback = internal->callback;
  210122. start (0);
  210123. if (oldCallback != 0)
  210124. oldCallback->audioDeviceStopped();
  210125. }
  210126. bool isPlaying()
  210127. {
  210128. return isStarted && internal->error.isEmpty();
  210129. }
  210130. const String getLastError()
  210131. {
  210132. return internal->error;
  210133. }
  210134. private:
  210135. bool isOpen_, isStarted;
  210136. ALSAThread* internal;
  210137. };
  210138. class ALSAAudioIODeviceType : public AudioIODeviceType
  210139. {
  210140. public:
  210141. ALSAAudioIODeviceType()
  210142. : AudioIODeviceType (T("ALSA")),
  210143. hasScanned (false)
  210144. {
  210145. }
  210146. ~ALSAAudioIODeviceType()
  210147. {
  210148. }
  210149. void scanForDevices()
  210150. {
  210151. hasScanned = true;
  210152. names.clear();
  210153. ids.clear();
  210154. snd_ctl_t* handle;
  210155. snd_ctl_card_info_t* info;
  210156. snd_ctl_card_info_alloca (&info);
  210157. int cardNum = -1;
  210158. while (ids.size() <= 24)
  210159. {
  210160. snd_card_next (&cardNum);
  210161. if (cardNum < 0)
  210162. break;
  210163. if (snd_ctl_open (&handle, T("hw:") + String (cardNum), SND_CTL_NONBLOCK) >= 0)
  210164. {
  210165. if (snd_ctl_card_info (handle, info) >= 0)
  210166. {
  210167. String cardId (snd_ctl_card_info_get_id (info));
  210168. if (cardId.removeCharacters (T("0123456789")).isEmpty())
  210169. cardId = String (cardNum);
  210170. int device = -1;
  210171. for (;;)
  210172. {
  210173. if (snd_ctl_pcm_next_device (handle, &device) < 0 || device < 0)
  210174. break;
  210175. String id, name;
  210176. id << "hw:" << cardId << ',' << device;
  210177. if (testDevice (id))
  210178. {
  210179. name << snd_ctl_card_info_get_name (info);
  210180. if (name.isEmpty())
  210181. name = id;
  210182. if (device > 0)
  210183. name << " (" << (device + 1) << ')';
  210184. ids.add (id);
  210185. names.add (name);
  210186. }
  210187. }
  210188. }
  210189. snd_ctl_close (handle);
  210190. }
  210191. }
  210192. }
  210193. const StringArray getDeviceNames (const bool /*preferInputNames*/) const
  210194. {
  210195. jassert (hasScanned); // need to call scanForDevices() before doing this
  210196. StringArray namesCopy (names);
  210197. namesCopy.removeDuplicates (true);
  210198. return namesCopy;
  210199. }
  210200. const String getDefaultDeviceName (const bool /*preferInputNames*/,
  210201. const int /*numInputChannelsNeeded*/,
  210202. const int /*numOutputChannelsNeeded*/) const
  210203. {
  210204. jassert (hasScanned); // need to call scanForDevices() before doing this
  210205. return names[0];
  210206. }
  210207. AudioIODevice* createDevice (const String& deviceName)
  210208. {
  210209. jassert (hasScanned); // need to call scanForDevices() before doing this
  210210. const int index = names.indexOf (deviceName);
  210211. if (index >= 0)
  210212. return new ALSAAudioIODevice (deviceName, ids [index]);
  210213. return 0;
  210214. }
  210215. juce_UseDebuggingNewOperator
  210216. private:
  210217. StringArray names, ids;
  210218. bool hasScanned;
  210219. static bool testDevice (const String& id)
  210220. {
  210221. unsigned int minChansOut = 0, maxChansOut = 0;
  210222. unsigned int minChansIn = 0, maxChansIn = 0;
  210223. Array <int> rates;
  210224. getDeviceProperties (id, minChansOut, maxChansOut, minChansIn, maxChansIn, rates);
  210225. DBG (T("ALSA device: ") + id
  210226. + T(" outs=") + String ((int) minChansOut) + T("-") + String ((int) maxChansOut)
  210227. + T(" ins=") + String ((int) minChansIn) + T("-") + String ((int) maxChansIn)
  210228. + T(" rates=") + String (rates.size()));
  210229. return (maxChansOut > 0 || maxChansIn > 0) && rates.size() > 0;
  210230. }
  210231. ALSAAudioIODeviceType (const ALSAAudioIODeviceType&);
  210232. const ALSAAudioIODeviceType& operator= (const ALSAAudioIODeviceType&);
  210233. };
  210234. AudioIODeviceType* juce_createDefaultAudioIODeviceType()
  210235. {
  210236. return new ALSAAudioIODeviceType();
  210237. }
  210238. END_JUCE_NAMESPACE
  210239. #else // if ALSA is turned off..
  210240. BEGIN_JUCE_NAMESPACE
  210241. AudioIODeviceType* juce_createDefaultAudioIODeviceType() { return 0; }
  210242. END_JUCE_NAMESPACE
  210243. #endif
  210244. #endif
  210245. /********* End of inlined file: juce_linux_Audio.cpp *********/
  210246. /********* Start of inlined file: juce_linux_AudioCDReader.cpp *********/
  210247. BEGIN_JUCE_NAMESPACE
  210248. AudioCDReader::AudioCDReader()
  210249. : AudioFormatReader (0, T("CD Audio"))
  210250. {
  210251. }
  210252. const StringArray AudioCDReader::getAvailableCDNames()
  210253. {
  210254. StringArray names;
  210255. return names;
  210256. }
  210257. AudioCDReader* AudioCDReader::createReaderForCD (const int index)
  210258. {
  210259. return 0;
  210260. }
  210261. AudioCDReader::~AudioCDReader()
  210262. {
  210263. }
  210264. void AudioCDReader::refreshTrackLengths()
  210265. {
  210266. }
  210267. bool AudioCDReader::read (int** destSamples,
  210268. int64 startSampleInFile,
  210269. int numSamples)
  210270. {
  210271. return false;
  210272. }
  210273. bool AudioCDReader::isCDStillPresent() const
  210274. {
  210275. return false;
  210276. }
  210277. int AudioCDReader::getNumTracks() const
  210278. {
  210279. return 0;
  210280. }
  210281. int AudioCDReader::getPositionOfTrackStart (int trackNum) const
  210282. {
  210283. return 0;
  210284. }
  210285. bool AudioCDReader::isTrackAudio (int trackNum) const
  210286. {
  210287. return false;
  210288. }
  210289. void AudioCDReader::enableIndexScanning (bool b)
  210290. {
  210291. }
  210292. int AudioCDReader::getLastIndex() const
  210293. {
  210294. return 0;
  210295. }
  210296. const Array<int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  210297. {
  210298. return Array<int>();
  210299. }
  210300. int AudioCDReader::getCDDBId()
  210301. {
  210302. return 0;
  210303. }
  210304. END_JUCE_NAMESPACE
  210305. /********* End of inlined file: juce_linux_AudioCDReader.cpp *********/
  210306. /********* Start of inlined file: juce_linux_FileChooser.cpp *********/
  210307. #if JUCE_BUILD_GUI_CLASSES
  210308. BEGIN_JUCE_NAMESPACE
  210309. void FileChooser::showPlatformDialog (OwnedArray<File>& results,
  210310. const String& title,
  210311. const File& file,
  210312. const String& filters,
  210313. bool isDirectory,
  210314. bool isSave,
  210315. bool warnAboutOverwritingExistingFiles,
  210316. bool selectMultipleFiles,
  210317. FilePreviewComponent* previewComponent)
  210318. {
  210319. //xxx ain't got one!
  210320. jassertfalse
  210321. }
  210322. END_JUCE_NAMESPACE
  210323. #endif
  210324. /********* End of inlined file: juce_linux_FileChooser.cpp *********/
  210325. /********* Start of inlined file: juce_linux_Fonts.cpp *********/
  210326. #if JUCE_BUILD_GUI_CLASSES
  210327. /* Got a build error here? You'll need to install the freetype library...
  210328. The name of the package to install is "libfreetype6-dev".
  210329. */
  210330. #include <ft2build.h>
  210331. #include FT_FREETYPE_H
  210332. BEGIN_JUCE_NAMESPACE
  210333. class FreeTypeFontFace
  210334. {
  210335. public:
  210336. enum FontStyle
  210337. {
  210338. Plain = 0,
  210339. Bold = 1,
  210340. Italic = 2
  210341. };
  210342. struct FontNameIndex
  210343. {
  210344. String fileName;
  210345. int faceIndex;
  210346. };
  210347. FreeTypeFontFace (const String& familyName)
  210348. : hasSerif (false),
  210349. monospaced (false)
  210350. {
  210351. family = familyName;
  210352. }
  210353. void setFileName (const String& name,
  210354. const int faceIndex,
  210355. FontStyle style)
  210356. {
  210357. if (names[(int) style].fileName.isEmpty())
  210358. {
  210359. names[(int) style].fileName = name;
  210360. names[(int) style].faceIndex = faceIndex;
  210361. }
  210362. }
  210363. const String& getFamilyName() const throw()
  210364. {
  210365. return family;
  210366. }
  210367. const String& getFileName (int style, int* faceIndex) const throw()
  210368. {
  210369. *faceIndex = names [style].faceIndex;
  210370. return names[style].fileName;
  210371. }
  210372. void setMonospaced (bool mono) { monospaced = mono; }
  210373. bool getMonospaced () const throw() { return monospaced; }
  210374. void setSerif (const bool serif) { hasSerif = serif; }
  210375. bool getSerif () const throw() { return hasSerif; }
  210376. private:
  210377. String family;
  210378. FontNameIndex names[4];
  210379. bool hasSerif, monospaced;
  210380. };
  210381. class FreeTypeInterface : public DeletedAtShutdown
  210382. {
  210383. public:
  210384. FreeTypeInterface() throw()
  210385. : lastFace (0),
  210386. lastBold (false),
  210387. lastItalic (false)
  210388. {
  210389. if (FT_Init_FreeType (&ftLib) != 0)
  210390. {
  210391. ftLib = 0;
  210392. DBG (T("Failed to initialize FreeType"));
  210393. }
  210394. StringArray fontDirs;
  210395. fontDirs.addTokens (String (getenv ("JUCE_FONT_PATH")), T(";,"), 0);
  210396. fontDirs.removeEmptyStrings (true);
  210397. if (fontDirs.size() == 0)
  210398. {
  210399. XmlDocument fontsConfig (File ("/etc/fonts/fonts.conf"));
  210400. XmlElement* const fontsInfo = fontsConfig.getDocumentElement();
  210401. if (fontsInfo != 0)
  210402. {
  210403. forEachXmlChildElementWithTagName (*fontsInfo, e, T("dir"))
  210404. {
  210405. fontDirs.add (e->getAllSubText().trim());
  210406. }
  210407. delete fontsInfo;
  210408. }
  210409. }
  210410. if (fontDirs.size() == 0)
  210411. fontDirs.add ("/usr/X11R6/lib/X11/fonts");
  210412. for (int i = 0; i < fontDirs.size(); ++i)
  210413. enumerateFaces (fontDirs[i]);
  210414. }
  210415. ~FreeTypeInterface() throw()
  210416. {
  210417. if (lastFace != 0)
  210418. FT_Done_Face (lastFace);
  210419. if (ftLib != 0)
  210420. FT_Done_FreeType (ftLib);
  210421. clearSingletonInstance();
  210422. }
  210423. FreeTypeFontFace* findOrCreate (const String& familyName,
  210424. const bool create = false) throw()
  210425. {
  210426. for (int i = 0; i < faces.size(); i++)
  210427. if (faces[i]->getFamilyName() == familyName)
  210428. return faces[i];
  210429. if (! create)
  210430. return NULL;
  210431. FreeTypeFontFace* newFace = new FreeTypeFontFace (familyName);
  210432. faces.add (newFace);
  210433. return newFace;
  210434. }
  210435. // Enumerate all font faces available in a given directory
  210436. void enumerateFaces (const String& path) throw()
  210437. {
  210438. File dirPath (path);
  210439. if (path.isEmpty() || ! dirPath.isDirectory())
  210440. return;
  210441. DirectoryIterator di (dirPath, true);
  210442. while (di.next())
  210443. {
  210444. File possible (di.getFile());
  210445. if (possible.hasFileExtension (T("ttf"))
  210446. || possible.hasFileExtension (T("pfb"))
  210447. || possible.hasFileExtension (T("pcf")))
  210448. {
  210449. FT_Face face;
  210450. int faceIndex = 0;
  210451. int numFaces = 0;
  210452. do
  210453. {
  210454. if (FT_New_Face (ftLib,
  210455. possible.getFullPathName(),
  210456. faceIndex,
  210457. &face) == 0)
  210458. {
  210459. if (faceIndex == 0)
  210460. numFaces = face->num_faces;
  210461. if ((face->face_flags & FT_FACE_FLAG_SCALABLE) != 0)
  210462. {
  210463. FreeTypeFontFace* const newFace = findOrCreate (face->family_name, true);
  210464. int style = (int) FreeTypeFontFace::Plain;
  210465. if ((face->style_flags & FT_STYLE_FLAG_BOLD) != 0)
  210466. style |= (int) FreeTypeFontFace::Bold;
  210467. if ((face->style_flags & FT_STYLE_FLAG_ITALIC) != 0)
  210468. style |= (int) FreeTypeFontFace::Italic;
  210469. newFace->setFileName (possible.getFullPathName(), faceIndex, (FreeTypeFontFace::FontStyle) style);
  210470. if ((face->face_flags & FT_FACE_FLAG_FIXED_WIDTH) != 0)
  210471. newFace->setMonospaced (true);
  210472. else
  210473. newFace->setMonospaced (false);
  210474. // Surely there must be a better way to do this?
  210475. if (String (face->family_name).containsIgnoreCase (T("Sans"))
  210476. || String (face->family_name).containsIgnoreCase (T("Verdana"))
  210477. || String (face->family_name).containsIgnoreCase (T("Arial")))
  210478. {
  210479. newFace->setSerif (false);
  210480. }
  210481. else
  210482. {
  210483. newFace->setSerif (true);
  210484. }
  210485. }
  210486. FT_Done_Face (face);
  210487. }
  210488. ++faceIndex;
  210489. }
  210490. while (faceIndex < numFaces);
  210491. }
  210492. }
  210493. }
  210494. // Create a FreeType face object for a given font
  210495. FT_Face createFT_Face (const String& fontName,
  210496. const bool bold,
  210497. const bool italic) throw()
  210498. {
  210499. FT_Face face = NULL;
  210500. if (fontName == lastFontName && bold == lastBold && italic == lastItalic)
  210501. {
  210502. face = lastFace;
  210503. }
  210504. else
  210505. {
  210506. if (lastFace)
  210507. {
  210508. FT_Done_Face (lastFace);
  210509. lastFace = NULL;
  210510. }
  210511. lastFontName = fontName;
  210512. lastBold = bold;
  210513. lastItalic = italic;
  210514. FreeTypeFontFace* const ftFace = findOrCreate (fontName);
  210515. if (ftFace != 0)
  210516. {
  210517. int style = (int) FreeTypeFontFace::Plain;
  210518. if (bold)
  210519. style |= (int) FreeTypeFontFace::Bold;
  210520. if (italic)
  210521. style |= (int) FreeTypeFontFace::Italic;
  210522. int faceIndex;
  210523. String fileName (ftFace->getFileName (style, &faceIndex));
  210524. if (fileName.isEmpty())
  210525. {
  210526. style ^= (int) FreeTypeFontFace::Bold;
  210527. fileName = ftFace->getFileName (style, &faceIndex);
  210528. if (fileName.isEmpty())
  210529. {
  210530. style ^= (int) FreeTypeFontFace::Bold;
  210531. style ^= (int) FreeTypeFontFace::Italic;
  210532. fileName = ftFace->getFileName (style, &faceIndex);
  210533. if (! fileName.length())
  210534. {
  210535. style ^= (int) FreeTypeFontFace::Bold;
  210536. fileName = ftFace->getFileName (style, &faceIndex);
  210537. }
  210538. }
  210539. }
  210540. if (! FT_New_Face (ftLib, (const char*) fileName, faceIndex, &lastFace))
  210541. {
  210542. face = lastFace;
  210543. // If there isn't a unicode charmap then select the first one.
  210544. if (FT_Select_Charmap (face, ft_encoding_unicode))
  210545. FT_Set_Charmap (face, face->charmaps[0]);
  210546. }
  210547. }
  210548. }
  210549. return face;
  210550. }
  210551. bool addGlyph (FT_Face face, Typeface& dest, uint32 character) throw()
  210552. {
  210553. const unsigned int glyphIndex = FT_Get_Char_Index (face, character);
  210554. const float height = (float) (face->ascender - face->descender);
  210555. const float scaleX = 1.0f / height;
  210556. const float scaleY = -1.0f / height;
  210557. Path destShape;
  210558. #define CONVERTX(val) (scaleX * (val).x)
  210559. #define CONVERTY(val) (scaleY * (val).y)
  210560. if (FT_Load_Glyph (face, glyphIndex, FT_LOAD_NO_SCALE
  210561. | FT_LOAD_NO_BITMAP
  210562. | FT_LOAD_IGNORE_TRANSFORM) != 0
  210563. || face->glyph->format != ft_glyph_format_outline)
  210564. {
  210565. return false;
  210566. }
  210567. const FT_Outline* const outline = &face->glyph->outline;
  210568. const short* const contours = outline->contours;
  210569. const char* const tags = outline->tags;
  210570. FT_Vector* const points = outline->points;
  210571. for (int c = 0; c < outline->n_contours; c++)
  210572. {
  210573. const int startPoint = (c == 0) ? 0 : contours [c - 1] + 1;
  210574. const int endPoint = contours[c];
  210575. for (int p = startPoint; p <= endPoint; p++)
  210576. {
  210577. const float x = CONVERTX (points[p]);
  210578. const float y = CONVERTY (points[p]);
  210579. if (p == startPoint)
  210580. {
  210581. if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Conic)
  210582. {
  210583. float x2 = CONVERTX (points [endPoint]);
  210584. float y2 = CONVERTY (points [endPoint]);
  210585. if (FT_CURVE_TAG (tags[endPoint]) != FT_Curve_Tag_On)
  210586. {
  210587. x2 = (x + x2) * 0.5f;
  210588. y2 = (y + y2) * 0.5f;
  210589. }
  210590. destShape.startNewSubPath (x2, y2);
  210591. }
  210592. else
  210593. {
  210594. destShape.startNewSubPath (x, y);
  210595. }
  210596. }
  210597. if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_On)
  210598. {
  210599. if (p != startPoint)
  210600. destShape.lineTo (x, y);
  210601. }
  210602. else if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Conic)
  210603. {
  210604. const int nextIndex = (p == endPoint) ? startPoint : p + 1;
  210605. float x2 = CONVERTX (points [nextIndex]);
  210606. float y2 = CONVERTY (points [nextIndex]);
  210607. if (FT_CURVE_TAG (tags [nextIndex]) == FT_Curve_Tag_Conic)
  210608. {
  210609. x2 = (x + x2) * 0.5f;
  210610. y2 = (y + y2) * 0.5f;
  210611. }
  210612. else
  210613. {
  210614. ++p;
  210615. }
  210616. destShape.quadraticTo (x, y, x2, y2);
  210617. }
  210618. else if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Cubic)
  210619. {
  210620. if (p >= endPoint)
  210621. return false;
  210622. const int next1 = p + 1;
  210623. const int next2 = (p == (endPoint - 1)) ? startPoint : p + 2;
  210624. const float x2 = CONVERTX (points [next1]);
  210625. const float y2 = CONVERTY (points [next1]);
  210626. const float x3 = CONVERTX (points [next2]);
  210627. const float y3 = CONVERTY (points [next2]);
  210628. if (FT_CURVE_TAG (tags[next1]) != FT_Curve_Tag_Cubic
  210629. || FT_CURVE_TAG (tags[next2]) != FT_Curve_Tag_On)
  210630. return false;
  210631. destShape.cubicTo (x, y, x2, y2, x3, y3);
  210632. p += 2;
  210633. }
  210634. }
  210635. destShape.closeSubPath();
  210636. }
  210637. dest.addGlyph (character, destShape, face->glyph->metrics.horiAdvance/height);
  210638. if ((face->face_flags & FT_FACE_FLAG_KERNING) != 0)
  210639. addKerning (face, dest, character, glyphIndex);
  210640. return true;
  210641. }
  210642. void addKerning (FT_Face face, Typeface& dest, const uint32 character, const uint32 glyphIndex) throw()
  210643. {
  210644. const float height = (float) (face->ascender - face->descender);
  210645. uint32 rightGlyphIndex;
  210646. uint32 rightCharCode = FT_Get_First_Char (face, &rightGlyphIndex);
  210647. while (rightGlyphIndex != 0)
  210648. {
  210649. FT_Vector kerning;
  210650. if (FT_Get_Kerning (face, glyphIndex, rightGlyphIndex, ft_kerning_unscaled, &kerning) == 0)
  210651. {
  210652. if (kerning.x != 0)
  210653. dest.addKerningPair (character, rightCharCode, kerning.x / height);
  210654. }
  210655. rightCharCode = FT_Get_Next_Char (face, rightCharCode, &rightGlyphIndex);
  210656. }
  210657. }
  210658. // Add a glyph to a font
  210659. bool addGlyphToFont (const uint32 character,
  210660. const tchar* fontName, bool bold, bool italic,
  210661. Typeface& dest) throw()
  210662. {
  210663. FT_Face face = createFT_Face (fontName, bold, italic);
  210664. if (face != 0)
  210665. return addGlyph (face, dest, character);
  210666. return false;
  210667. }
  210668. // Create a Typeface object for given name/style
  210669. bool createTypeface (const String& fontName,
  210670. const bool bold, const bool italic,
  210671. Typeface& dest,
  210672. const bool addAllGlyphs) throw()
  210673. {
  210674. dest.clear();
  210675. dest.setName (fontName);
  210676. dest.setBold (bold);
  210677. dest.setItalic (italic);
  210678. FT_Face face = createFT_Face (fontName, bold, italic);
  210679. if (face == 0)
  210680. {
  210681. #ifdef JUCE_DEBUG
  210682. String msg (T("Failed to create typeface: "));
  210683. msg << fontName << " " << (bold ? 'B' : ' ') << (italic ? 'I' : ' ');
  210684. DBG (msg);
  210685. #endif
  210686. return face;
  210687. }
  210688. const float height = (float) (face->ascender - face->descender);
  210689. dest.setAscent (face->ascender / height);
  210690. dest.setDefaultCharacter (L' ');
  210691. if (addAllGlyphs)
  210692. {
  210693. uint32 glyphIndex;
  210694. uint32 charCode = FT_Get_First_Char (face, &glyphIndex);
  210695. while (glyphIndex != 0)
  210696. {
  210697. addGlyph (face, dest, charCode);
  210698. charCode = FT_Get_Next_Char (face, charCode, &glyphIndex);
  210699. }
  210700. }
  210701. return true;
  210702. }
  210703. void getFamilyNames (StringArray& familyNames) const throw()
  210704. {
  210705. for (int i = 0; i < faces.size(); i++)
  210706. familyNames.add (faces[i]->getFamilyName());
  210707. }
  210708. void getMonospacedNames (StringArray& monoSpaced) const throw()
  210709. {
  210710. for (int i = 0; i < faces.size(); i++)
  210711. if (faces[i]->getMonospaced())
  210712. monoSpaced.add (faces[i]->getFamilyName());
  210713. }
  210714. void getSerifNames (StringArray& serif) const throw()
  210715. {
  210716. for (int i = 0; i < faces.size(); i++)
  210717. if (faces[i]->getSerif())
  210718. serif.add (faces[i]->getFamilyName());
  210719. }
  210720. void getSansSerifNames (StringArray& sansSerif) const throw()
  210721. {
  210722. for (int i = 0; i < faces.size(); i++)
  210723. if (! faces[i]->getSerif())
  210724. sansSerif.add (faces[i]->getFamilyName());
  210725. }
  210726. juce_DeclareSingleton_SingleThreaded_Minimal (FreeTypeInterface)
  210727. private:
  210728. FT_Library ftLib;
  210729. FT_Face lastFace;
  210730. String lastFontName;
  210731. bool lastBold, lastItalic;
  210732. OwnedArray<FreeTypeFontFace> faces;
  210733. };
  210734. juce_ImplementSingleton_SingleThreaded (FreeTypeInterface)
  210735. void Typeface::initialiseTypefaceCharacteristics (const String& fontName,
  210736. bool bold, bool italic,
  210737. bool addAllGlyphsToFont) throw()
  210738. {
  210739. FreeTypeInterface::getInstance()
  210740. ->createTypeface (fontName, bold, italic, *this, addAllGlyphsToFont);
  210741. }
  210742. bool Typeface::findAndAddSystemGlyph (juce_wchar character) throw()
  210743. {
  210744. return FreeTypeInterface::getInstance()
  210745. ->addGlyphToFont (character, getName(), isBold(), isItalic(), *this);
  210746. }
  210747. const StringArray Font::findAllTypefaceNames() throw()
  210748. {
  210749. StringArray s;
  210750. FreeTypeInterface::getInstance()->getFamilyNames (s);
  210751. s.sort (true);
  210752. return s;
  210753. }
  210754. static const String pickBestFont (const StringArray& names,
  210755. const char* const choicesString)
  210756. {
  210757. StringArray choices;
  210758. choices.addTokens (String (choicesString), T(","), 0);
  210759. choices.trim();
  210760. choices.removeEmptyStrings();
  210761. int i, j;
  210762. for (j = 0; j < choices.size(); ++j)
  210763. if (names.contains (choices[j], true))
  210764. return choices[j];
  210765. for (j = 0; j < choices.size(); ++j)
  210766. for (i = 0; i < names.size(); i++)
  210767. if (names[i].startsWithIgnoreCase (choices[j]))
  210768. return names[i];
  210769. for (j = 0; j < choices.size(); ++j)
  210770. for (i = 0; i < names.size(); i++)
  210771. if (names[i].containsIgnoreCase (choices[j]))
  210772. return names[i];
  210773. return names[0];
  210774. }
  210775. static const String linux_getDefaultSansSerifFontName()
  210776. {
  210777. StringArray allFonts;
  210778. FreeTypeInterface::getInstance()->getSansSerifNames (allFonts);
  210779. return pickBestFont (allFonts, "Verdana, Bitstream Vera Sans, Luxi Sans, Sans");
  210780. }
  210781. static const String linux_getDefaultSerifFontName()
  210782. {
  210783. StringArray allFonts;
  210784. FreeTypeInterface::getInstance()->getSerifNames (allFonts);
  210785. return pickBestFont (allFonts, "Bitstream Vera Serif, Times, Nimbus Roman, Serif");
  210786. }
  210787. static const String linux_getDefaultMonospacedFontName()
  210788. {
  210789. StringArray allFonts;
  210790. FreeTypeInterface::getInstance()->getMonospacedNames (allFonts);
  210791. return pickBestFont (allFonts, "Bitstream Vera Sans Mono, Courier, Sans Mono, Mono");
  210792. }
  210793. void Font::getDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed) throw()
  210794. {
  210795. defaultSans = linux_getDefaultSansSerifFontName();
  210796. defaultSerif = linux_getDefaultSerifFontName();
  210797. defaultFixed = linux_getDefaultMonospacedFontName();
  210798. }
  210799. END_JUCE_NAMESPACE
  210800. #endif
  210801. /********* End of inlined file: juce_linux_Fonts.cpp *********/
  210802. /********* Start of inlined file: juce_linux_Messaging.cpp *********/
  210803. #if JUCE_BUILD_GUI_CLASSES
  210804. #include <stdio.h>
  210805. #include <signal.h>
  210806. #include <X11/Xlib.h>
  210807. #include <X11/Xatom.h>
  210808. #include <X11/Xresource.h>
  210809. #include <X11/Xutil.h>
  210810. BEGIN_JUCE_NAMESPACE
  210811. #ifdef JUCE_DEBUG
  210812. #define JUCE_DEBUG_XERRORS 1
  210813. #endif
  210814. Display* display = 0; // This is also referenced from WindowDriver.cpp
  210815. static Window juce_messageWindowHandle = None;
  210816. #define SpecialAtom "JUCESpecialAtom"
  210817. #define BroadcastAtom "JUCEBroadcastAtom"
  210818. #define SpecialCallbackAtom "JUCESpecialCallbackAtom"
  210819. static Atom specialId;
  210820. static Atom broadcastId;
  210821. static Atom specialCallbackId;
  210822. // This is referenced from WindowDriver.cpp
  210823. XContext improbableNumber;
  210824. // Defined in WindowDriver.cpp
  210825. extern void juce_windowMessageReceive (XEvent* event);
  210826. struct MessageThreadFuncCall
  210827. {
  210828. MessageCallbackFunction* func;
  210829. void* parameter;
  210830. void* result;
  210831. CriticalSection lock;
  210832. WaitableEvent event;
  210833. };
  210834. static bool errorCondition = false;
  210835. // (defined in another file to avoid problems including certain headers in this one)
  210836. extern bool juce_isRunningAsApplication();
  210837. // Usually happens when client-server connection is broken
  210838. static int ioErrorHandler (Display* display)
  210839. {
  210840. DBG (T("ERROR: connection to X server broken.. terminating."));
  210841. errorCondition = true;
  210842. if (! juce_isRunningAsApplication())
  210843. Process::terminate();
  210844. return 0;
  210845. }
  210846. // A protocol error has occurred
  210847. static int errorHandler (Display* display, XErrorEvent* event)
  210848. {
  210849. #ifdef JUCE_DEBUG_XERRORS
  210850. char errorStr[64] = { 0 };
  210851. char requestStr[64] = { 0 };
  210852. XGetErrorText (display, event->error_code, errorStr, 64);
  210853. XGetErrorDatabaseText (display,
  210854. "XRequest",
  210855. (const char*) String (event->request_code),
  210856. "Unknown",
  210857. requestStr,
  210858. 64);
  210859. DBG (T("ERROR: X returned ") + String (errorStr) + T(" for operation ") + String (requestStr));
  210860. #endif
  210861. return 0;
  210862. }
  210863. static bool breakIn = false;
  210864. // Breakin from keyboard
  210865. static void sig_handler (int sig)
  210866. {
  210867. if (sig == SIGINT)
  210868. {
  210869. breakIn = true;
  210870. return;
  210871. }
  210872. static bool reentrant = false;
  210873. if (reentrant == false)
  210874. {
  210875. reentrant = true;
  210876. // Illegal instruction
  210877. fflush (stdout);
  210878. Logger::outputDebugString ("ERROR: Program executed illegal instruction.. terminating");
  210879. errorCondition = true;
  210880. if (juce_isRunningAsApplication())
  210881. Process::terminate();
  210882. }
  210883. else
  210884. {
  210885. if (juce_isRunningAsApplication())
  210886. exit(0);
  210887. }
  210888. }
  210889. void MessageManager::doPlatformSpecificInitialisation()
  210890. {
  210891. // Initialise xlib for multiple thread support
  210892. if (! XInitThreads())
  210893. {
  210894. // This is fatal! Print error and closedown
  210895. Logger::outputDebugString ("Failed to initialise xlib thread support.");
  210896. if (juce_isRunningAsApplication())
  210897. Process::terminate();
  210898. }
  210899. // This is called if the client/server connection is broken
  210900. XSetIOErrorHandler (ioErrorHandler);
  210901. // This is called if a protocol error occurs
  210902. XSetErrorHandler (errorHandler);
  210903. // Install signal handler for break-in
  210904. struct sigaction saction;
  210905. sigset_t maskSet;
  210906. sigemptyset (&maskSet);
  210907. saction.sa_handler = sig_handler;
  210908. saction.sa_mask = maskSet;
  210909. saction.sa_flags = 0;
  210910. sigaction (SIGINT, &saction, NULL);
  210911. #ifndef _DEBUG
  210912. // Setup signal handlers for various fatal errors
  210913. sigaction (SIGILL, &saction, NULL);
  210914. sigaction (SIGBUS, &saction, NULL);
  210915. sigaction (SIGFPE, &saction, NULL);
  210916. sigaction (SIGSEGV, &saction, NULL);
  210917. sigaction (SIGSYS, &saction, NULL);
  210918. #endif
  210919. String displayName (getenv ("DISPLAY"));
  210920. if (displayName.isEmpty())
  210921. displayName = T(":0.0");
  210922. display = XOpenDisplay (displayName);
  210923. if (display == 0)
  210924. {
  210925. // This is fatal! Print error and closedown
  210926. Logger::outputDebugString ("Failed to open the X display.");
  210927. if (juce_isRunningAsApplication())
  210928. Process::terminate();
  210929. }
  210930. // Get defaults for various properties
  210931. int screen = DefaultScreen (display);
  210932. Window root = RootWindow (display, screen);
  210933. Visual* visual = DefaultVisual (display, screen);
  210934. // Create atoms for our ClientMessages (these cannot be deleted)
  210935. specialId = XInternAtom (display, SpecialAtom, false);
  210936. broadcastId = XInternAtom (display, BroadcastAtom, false);
  210937. specialCallbackId = XInternAtom (display, SpecialCallbackAtom, false);
  210938. // Create a context to store user data associated with Windows we
  210939. // create in WindowDriver
  210940. improbableNumber = XUniqueContext();
  210941. // We're only interested in client messages for this window
  210942. // which are always sent
  210943. XSetWindowAttributes swa;
  210944. swa.event_mask = NoEventMask;
  210945. // Create our message window (this will never be mapped)
  210946. juce_messageWindowHandle = XCreateWindow (display, root,
  210947. 0, 0, 1, 1, 0, 0, InputOnly,
  210948. visual, CWEventMask, &swa);
  210949. }
  210950. void MessageManager::doPlatformSpecificShutdown()
  210951. {
  210952. if (errorCondition == false)
  210953. {
  210954. XDestroyWindow (display, juce_messageWindowHandle);
  210955. XCloseDisplay (display);
  210956. }
  210957. }
  210958. bool juce_postMessageToSystemQueue (void* message)
  210959. {
  210960. if (errorCondition)
  210961. return false;
  210962. XClientMessageEvent clientMsg;
  210963. clientMsg.display = display;
  210964. clientMsg.window = juce_messageWindowHandle;
  210965. clientMsg.type = ClientMessage;
  210966. clientMsg.format = 32;
  210967. clientMsg.message_type = specialId;
  210968. #if JUCE_64BIT
  210969. clientMsg.data.l[0] = (long) (0x00000000ffffffff & (((uint64) message) >> 32));
  210970. clientMsg.data.l[1] = (long) (0x00000000ffffffff & (long) message);
  210971. #else
  210972. clientMsg.data.l[0] = (long) message;
  210973. #endif
  210974. XSendEvent (display, juce_messageWindowHandle, false,
  210975. NoEventMask, (XEvent*) &clientMsg);
  210976. XFlush (display); // This is necessary to ensure the event is delivered
  210977. return true;
  210978. }
  210979. void MessageManager::broadcastMessage (const String& value) throw()
  210980. {
  210981. }
  210982. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* func,
  210983. void* parameter)
  210984. {
  210985. void* retVal = 0;
  210986. if (! errorCondition)
  210987. {
  210988. if (! isThisTheMessageThread())
  210989. {
  210990. static MessageThreadFuncCall messageFuncCallContext;
  210991. const ScopedLock sl (messageFuncCallContext.lock);
  210992. XClientMessageEvent clientMsg;
  210993. clientMsg.display = display;
  210994. clientMsg.window = juce_messageWindowHandle;
  210995. clientMsg.type = ClientMessage;
  210996. clientMsg.format = 32;
  210997. clientMsg.message_type = specialCallbackId;
  210998. #if JUCE_64BIT
  210999. clientMsg.data.l[0] = (long) (0x00000000ffffffff & (((uint64) &messageFuncCallContext) >> 32));
  211000. clientMsg.data.l[1] = (long) (0x00000000ffffffff & (uint64) &messageFuncCallContext);
  211001. #else
  211002. clientMsg.data.l[0] = (long) &messageFuncCallContext;
  211003. #endif
  211004. messageFuncCallContext.func = func;
  211005. messageFuncCallContext.parameter = parameter;
  211006. if (XSendEvent (display, juce_messageWindowHandle, false, NoEventMask, (XEvent*) &clientMsg) == 0)
  211007. return 0;
  211008. XFlush (display); // This is necessary to ensure the event is delivered
  211009. // Wait for it to complete before continuing
  211010. messageFuncCallContext.event.wait();
  211011. retVal = messageFuncCallContext.result;
  211012. }
  211013. else
  211014. {
  211015. // Just call the function directly
  211016. retVal = func (parameter);
  211017. }
  211018. }
  211019. return retVal;
  211020. }
  211021. bool juce_dispatchNextMessageOnSystemQueue (bool returnIfNoPendingMessages)
  211022. {
  211023. if (errorCondition)
  211024. return false;
  211025. if (breakIn)
  211026. {
  211027. errorCondition = true;
  211028. if (juce_isRunningAsApplication())
  211029. Process::terminate();
  211030. }
  211031. if (returnIfNoPendingMessages && ! XPending (display))
  211032. return false;
  211033. XEvent evt;
  211034. XNextEvent (display, &evt);
  211035. if (evt.type == ClientMessage && evt.xany.window == juce_messageWindowHandle)
  211036. {
  211037. XClientMessageEvent* const clientMsg = (XClientMessageEvent*) &evt;
  211038. if (clientMsg->format != 32)
  211039. {
  211040. jassertfalse
  211041. DBG ("Error: juce_dispatchNextMessageOnSystemQueue received malformed client message.");
  211042. }
  211043. else
  211044. {
  211045. JUCE_TRY
  211046. {
  211047. #if JUCE_64BIT
  211048. void* const messagePtr
  211049. = (void*) ((0xffffffff00000000 & (((uint64) clientMsg->data.l[0]) << 32))
  211050. | (clientMsg->data.l[1] & 0x00000000ffffffff));
  211051. #else
  211052. void* const messagePtr = (void*) (clientMsg->data.l[0]);
  211053. #endif
  211054. if (clientMsg->message_type == specialId)
  211055. {
  211056. MessageManager::getInstance()->deliverMessage (messagePtr);
  211057. }
  211058. else if (clientMsg->message_type == specialCallbackId)
  211059. {
  211060. MessageThreadFuncCall* const call = (MessageThreadFuncCall*) messagePtr;
  211061. MessageCallbackFunction* func = call->func;
  211062. call->result = (*func) (call->parameter);
  211063. call->event.signal();
  211064. }
  211065. else if (clientMsg->message_type == broadcastId)
  211066. {
  211067. #if 0
  211068. TCHAR buffer[8192];
  211069. zeromem (buffer, sizeof (buffer));
  211070. if (GlobalGetAtomName ((ATOM) lParam, buffer, 8192) != 0)
  211071. mq->deliverBroadcastMessage (String (buffer));
  211072. #endif
  211073. }
  211074. else
  211075. {
  211076. DBG ("Error: juce_dispatchNextMessageOnSystemQueue received unknown client message.");
  211077. }
  211078. }
  211079. JUCE_CATCH_ALL
  211080. }
  211081. }
  211082. else if (evt.xany.window != juce_messageWindowHandle)
  211083. {
  211084. juce_windowMessageReceive (&evt);
  211085. }
  211086. return true;
  211087. }
  211088. END_JUCE_NAMESPACE
  211089. #endif
  211090. /********* End of inlined file: juce_linux_Messaging.cpp *********/
  211091. /********* Start of inlined file: juce_linux_Midi.cpp *********/
  211092. #if JUCE_BUILD_GUI_CLASSES
  211093. #if JUCE_ALSA
  211094. #include <alsa/asoundlib.h>
  211095. BEGIN_JUCE_NAMESPACE
  211096. static snd_seq_t* iterateDevices (const bool forInput,
  211097. StringArray& deviceNamesFound,
  211098. const int deviceIndexToOpen)
  211099. {
  211100. snd_seq_t* returnedHandle = 0;
  211101. snd_seq_t* seqHandle;
  211102. if (snd_seq_open (&seqHandle, "default", forInput ? SND_SEQ_OPEN_INPUT
  211103. : SND_SEQ_OPEN_OUTPUT, 0) == 0)
  211104. {
  211105. snd_seq_system_info_t* systemInfo;
  211106. snd_seq_client_info_t* clientInfo;
  211107. if (snd_seq_system_info_malloc (&systemInfo) == 0)
  211108. {
  211109. if (snd_seq_system_info (seqHandle, systemInfo) == 0
  211110. && snd_seq_client_info_malloc (&clientInfo) == 0)
  211111. {
  211112. int numClients = snd_seq_system_info_get_cur_clients (systemInfo);
  211113. while (--numClients >= 0 && returnedHandle == 0)
  211114. {
  211115. if (snd_seq_query_next_client (seqHandle, clientInfo) == 0)
  211116. {
  211117. snd_seq_port_info_t* portInfo;
  211118. if (snd_seq_port_info_malloc (&portInfo) == 0)
  211119. {
  211120. int numPorts = snd_seq_client_info_get_num_ports (clientInfo);
  211121. const int client = snd_seq_client_info_get_client (clientInfo);
  211122. snd_seq_port_info_set_client (portInfo, client);
  211123. snd_seq_port_info_set_port (portInfo, -1);
  211124. while (--numPorts >= 0)
  211125. {
  211126. if (snd_seq_query_next_port (seqHandle, portInfo) == 0
  211127. && (snd_seq_port_info_get_capability (portInfo)
  211128. & (forInput ? SND_SEQ_PORT_CAP_READ
  211129. : SND_SEQ_PORT_CAP_WRITE)) != 0)
  211130. {
  211131. deviceNamesFound.add (snd_seq_client_info_get_name (clientInfo));
  211132. if (deviceNamesFound.size() == deviceIndexToOpen + 1)
  211133. {
  211134. const int sourcePort = snd_seq_port_info_get_port (portInfo);
  211135. const int sourceClient = snd_seq_client_info_get_client (clientInfo);
  211136. if (sourcePort != -1)
  211137. {
  211138. snd_seq_set_client_name (seqHandle,
  211139. forInput ? "Juce Midi Input"
  211140. : "Juce Midi Output");
  211141. const int portId
  211142. = snd_seq_create_simple_port (seqHandle,
  211143. forInput ? "Juce Midi In Port"
  211144. : "Juce Midi Out Port",
  211145. forInput ? (SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_SUBS_WRITE)
  211146. : (SND_SEQ_PORT_CAP_READ | SND_SEQ_PORT_CAP_SUBS_READ),
  211147. SND_SEQ_PORT_TYPE_MIDI_GENERIC);
  211148. snd_seq_connect_from (seqHandle, portId, sourceClient, sourcePort);
  211149. returnedHandle = seqHandle;
  211150. break;
  211151. }
  211152. }
  211153. }
  211154. }
  211155. snd_seq_port_info_free (portInfo);
  211156. }
  211157. }
  211158. }
  211159. snd_seq_client_info_free (clientInfo);
  211160. }
  211161. snd_seq_system_info_free (systemInfo);
  211162. }
  211163. if (returnedHandle == 0)
  211164. snd_seq_close (seqHandle);
  211165. }
  211166. deviceNamesFound.appendNumbersToDuplicates (true, true);
  211167. return returnedHandle;
  211168. }
  211169. static snd_seq_t* createDevice (const bool forInput,
  211170. const String& deviceNameToOpen)
  211171. {
  211172. snd_seq_t* seqHandle = 0;
  211173. if (snd_seq_open (&seqHandle, "default", forInput ? SND_SEQ_OPEN_INPUT
  211174. : SND_SEQ_OPEN_OUTPUT, 0) == 0)
  211175. {
  211176. snd_seq_set_client_name (seqHandle,
  211177. (const char*) (forInput ? (deviceNameToOpen + T(" Input"))
  211178. : (deviceNameToOpen + T(" Output"))));
  211179. const int portId
  211180. = snd_seq_create_simple_port (seqHandle,
  211181. forInput ? "in"
  211182. : "out",
  211183. forInput ? (SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_SUBS_WRITE)
  211184. : (SND_SEQ_PORT_CAP_READ | SND_SEQ_PORT_CAP_SUBS_READ),
  211185. forInput ? SND_SEQ_PORT_TYPE_APPLICATION
  211186. : SND_SEQ_PORT_TYPE_MIDI_GENERIC);
  211187. if (portId < 0)
  211188. {
  211189. snd_seq_close (seqHandle);
  211190. seqHandle = 0;
  211191. }
  211192. }
  211193. return seqHandle;
  211194. }
  211195. class MidiOutputDevice
  211196. {
  211197. public:
  211198. MidiOutputDevice (MidiOutput* const midiOutput_,
  211199. snd_seq_t* const seqHandle_)
  211200. :
  211201. midiOutput (midiOutput_),
  211202. seqHandle (seqHandle_),
  211203. maxEventSize (16 * 1024)
  211204. {
  211205. jassert (seqHandle != 0 && midiOutput != 0);
  211206. snd_midi_event_new (maxEventSize, &midiParser);
  211207. }
  211208. ~MidiOutputDevice()
  211209. {
  211210. snd_midi_event_free (midiParser);
  211211. snd_seq_close (seqHandle);
  211212. }
  211213. void sendMessageNow (const MidiMessage& message)
  211214. {
  211215. if (message.getRawDataSize() > maxEventSize)
  211216. {
  211217. maxEventSize = message.getRawDataSize();
  211218. snd_midi_event_free (midiParser);
  211219. snd_midi_event_new (maxEventSize, &midiParser);
  211220. }
  211221. snd_seq_event_t event;
  211222. snd_seq_ev_clear (&event);
  211223. snd_midi_event_encode (midiParser,
  211224. message.getRawData(),
  211225. message.getRawDataSize(),
  211226. &event);
  211227. snd_midi_event_reset_encode (midiParser);
  211228. snd_seq_ev_set_source (&event, 0);
  211229. snd_seq_ev_set_subs (&event);
  211230. snd_seq_ev_set_direct (&event);
  211231. snd_seq_event_output_direct (seqHandle, &event);
  211232. }
  211233. juce_UseDebuggingNewOperator
  211234. private:
  211235. MidiOutput* const midiOutput;
  211236. snd_seq_t* const seqHandle;
  211237. snd_midi_event_t* midiParser;
  211238. int maxEventSize;
  211239. };
  211240. const StringArray MidiOutput::getDevices()
  211241. {
  211242. StringArray devices;
  211243. iterateDevices (false, devices, -1);
  211244. return devices;
  211245. }
  211246. int MidiOutput::getDefaultDeviceIndex()
  211247. {
  211248. return 0;
  211249. }
  211250. MidiOutput* MidiOutput::openDevice (int deviceIndex)
  211251. {
  211252. MidiOutput* newDevice = 0;
  211253. StringArray devices;
  211254. snd_seq_t* const handle = iterateDevices (false, devices, deviceIndex);
  211255. if (handle != 0)
  211256. {
  211257. newDevice = new MidiOutput();
  211258. newDevice->internal = new MidiOutputDevice (newDevice, handle);
  211259. }
  211260. return newDevice;
  211261. }
  211262. MidiOutput* MidiOutput::createNewDevice (const String& deviceName)
  211263. {
  211264. MidiOutput* newDevice = 0;
  211265. snd_seq_t* const handle = createDevice (false, deviceName);
  211266. if (handle != 0)
  211267. {
  211268. newDevice = new MidiOutput();
  211269. newDevice->internal = new MidiOutputDevice (newDevice, handle);
  211270. }
  211271. return newDevice;
  211272. }
  211273. MidiOutput::~MidiOutput()
  211274. {
  211275. MidiOutputDevice* const device = (MidiOutputDevice*) internal;
  211276. delete device;
  211277. }
  211278. void MidiOutput::reset()
  211279. {
  211280. }
  211281. bool MidiOutput::getVolume (float& leftVol, float& rightVol)
  211282. {
  211283. return false;
  211284. }
  211285. void MidiOutput::setVolume (float leftVol, float rightVol)
  211286. {
  211287. }
  211288. void MidiOutput::sendMessageNow (const MidiMessage& message)
  211289. {
  211290. ((MidiOutputDevice*) internal)->sendMessageNow (message);
  211291. }
  211292. class MidiInputThread : public Thread
  211293. {
  211294. public:
  211295. MidiInputThread (MidiInput* const midiInput_,
  211296. snd_seq_t* const seqHandle_,
  211297. MidiInputCallback* const callback_)
  211298. : Thread (T("Juce MIDI Input")),
  211299. midiInput (midiInput_),
  211300. seqHandle (seqHandle_),
  211301. callback (callback_)
  211302. {
  211303. jassert (seqHandle != 0 && callback != 0 && midiInput != 0);
  211304. }
  211305. ~MidiInputThread()
  211306. {
  211307. snd_seq_close (seqHandle);
  211308. }
  211309. void run()
  211310. {
  211311. const int maxEventSize = 16 * 1024;
  211312. snd_midi_event_t* midiParser;
  211313. if (snd_midi_event_new (maxEventSize, &midiParser) >= 0)
  211314. {
  211315. uint8* const buffer = (uint8*) juce_malloc (maxEventSize);
  211316. const int numPfds = snd_seq_poll_descriptors_count (seqHandle, POLLIN);
  211317. struct pollfd* const pfd = (struct pollfd*) alloca (numPfds * sizeof (struct pollfd));
  211318. snd_seq_poll_descriptors (seqHandle, pfd, numPfds, POLLIN);
  211319. while (! threadShouldExit())
  211320. {
  211321. if (poll (pfd, numPfds, 500) > 0)
  211322. {
  211323. snd_seq_event_t* inputEvent = 0;
  211324. snd_seq_nonblock (seqHandle, 1);
  211325. do
  211326. {
  211327. if (snd_seq_event_input (seqHandle, &inputEvent) >= 0)
  211328. {
  211329. // xxx what about SYSEXes that are too big for the buffer?
  211330. const int numBytes = snd_midi_event_decode (midiParser, buffer, maxEventSize, inputEvent);
  211331. snd_midi_event_reset_decode (midiParser);
  211332. if (numBytes > 0)
  211333. {
  211334. const MidiMessage message ((const uint8*) buffer,
  211335. numBytes,
  211336. Time::getMillisecondCounter() * 0.001);
  211337. callback->handleIncomingMidiMessage (midiInput, message);
  211338. }
  211339. snd_seq_free_event (inputEvent);
  211340. }
  211341. }
  211342. while (snd_seq_event_input_pending (seqHandle, 0) > 0);
  211343. snd_seq_free_event (inputEvent);
  211344. }
  211345. }
  211346. snd_midi_event_free (midiParser);
  211347. juce_free (buffer);
  211348. }
  211349. };
  211350. juce_UseDebuggingNewOperator
  211351. private:
  211352. MidiInput* const midiInput;
  211353. snd_seq_t* const seqHandle;
  211354. MidiInputCallback* const callback;
  211355. };
  211356. MidiInput::MidiInput (const String& name_)
  211357. : name (name_),
  211358. internal (0)
  211359. {
  211360. }
  211361. MidiInput::~MidiInput()
  211362. {
  211363. stop();
  211364. MidiInputThread* const thread = (MidiInputThread*) internal;
  211365. delete thread;
  211366. }
  211367. void MidiInput::start()
  211368. {
  211369. ((MidiInputThread*) internal)->startThread();
  211370. }
  211371. void MidiInput::stop()
  211372. {
  211373. ((MidiInputThread*) internal)->stopThread (3000);
  211374. }
  211375. int MidiInput::getDefaultDeviceIndex()
  211376. {
  211377. return 0;
  211378. }
  211379. const StringArray MidiInput::getDevices()
  211380. {
  211381. StringArray devices;
  211382. iterateDevices (true, devices, -1);
  211383. return devices;
  211384. }
  211385. MidiInput* MidiInput::openDevice (int deviceIndex, MidiInputCallback* callback)
  211386. {
  211387. MidiInput* newDevice = 0;
  211388. StringArray devices;
  211389. snd_seq_t* const handle = iterateDevices (true, devices, deviceIndex);
  211390. if (handle != 0)
  211391. {
  211392. newDevice = new MidiInput (devices [deviceIndex]);
  211393. newDevice->internal = new MidiInputThread (newDevice, handle, callback);
  211394. }
  211395. return newDevice;
  211396. }
  211397. MidiInput* MidiInput::createNewDevice (const String& deviceName, MidiInputCallback* callback)
  211398. {
  211399. MidiInput* newDevice = 0;
  211400. snd_seq_t* const handle = createDevice (true, deviceName);
  211401. if (handle != 0)
  211402. {
  211403. newDevice = new MidiInput (deviceName);
  211404. newDevice->internal = new MidiInputThread (newDevice, handle, callback);
  211405. }
  211406. return newDevice;
  211407. }
  211408. END_JUCE_NAMESPACE
  211409. #else
  211410. // (These are just stub functions if ALSA is unavailable...)
  211411. BEGIN_JUCE_NAMESPACE
  211412. const StringArray MidiOutput::getDevices() { return StringArray(); }
  211413. int MidiOutput::getDefaultDeviceIndex() { return 0; }
  211414. MidiOutput* MidiOutput::openDevice (int) { return 0; }
  211415. MidiOutput* MidiOutput::createNewDevice (const String&) { return 0; }
  211416. MidiOutput::~MidiOutput() {}
  211417. void MidiOutput::reset() {}
  211418. bool MidiOutput::getVolume (float&, float&) { return false; }
  211419. void MidiOutput::setVolume (float, float) {}
  211420. void MidiOutput::sendMessageNow (const MidiMessage&) {}
  211421. MidiInput::MidiInput (const String& name_)
  211422. : name (name_),
  211423. internal (0)
  211424. {}
  211425. MidiInput::~MidiInput() {}
  211426. void MidiInput::start() {}
  211427. void MidiInput::stop() {}
  211428. int MidiInput::getDefaultDeviceIndex() { return 0; }
  211429. const StringArray MidiInput::getDevices() { return StringArray(); }
  211430. MidiInput* MidiInput::openDevice (int, MidiInputCallback*) { return 0; }
  211431. MidiInput* MidiInput::createNewDevice (const String&, MidiInputCallback*) { return 0; }
  211432. END_JUCE_NAMESPACE
  211433. #endif
  211434. #endif
  211435. /********* End of inlined file: juce_linux_Midi.cpp *********/
  211436. /********* Start of inlined file: juce_linux_WebBrowserComponent.cpp *********/
  211437. BEGIN_JUCE_NAMESPACE
  211438. /*
  211439. Sorry.. This class isn't implemented on Linux!
  211440. */
  211441. WebBrowserComponent::WebBrowserComponent()
  211442. : browser (0),
  211443. blankPageShown (false)
  211444. {
  211445. setOpaque (true);
  211446. }
  211447. WebBrowserComponent::~WebBrowserComponent()
  211448. {
  211449. }
  211450. void WebBrowserComponent::goToURL (const String& url,
  211451. const StringArray* headers,
  211452. const MemoryBlock* postData)
  211453. {
  211454. lastURL = url;
  211455. lastHeaders.clear();
  211456. if (headers != 0)
  211457. lastHeaders = *headers;
  211458. lastPostData.setSize (0);
  211459. if (postData != 0)
  211460. lastPostData = *postData;
  211461. blankPageShown = false;
  211462. }
  211463. void WebBrowserComponent::stop()
  211464. {
  211465. }
  211466. void WebBrowserComponent::goBack()
  211467. {
  211468. lastURL = String::empty;
  211469. blankPageShown = false;
  211470. }
  211471. void WebBrowserComponent::goForward()
  211472. {
  211473. lastURL = String::empty;
  211474. }
  211475. void WebBrowserComponent::paint (Graphics& g)
  211476. {
  211477. g.fillAll (Colours::white);
  211478. }
  211479. void WebBrowserComponent::checkWindowAssociation()
  211480. {
  211481. }
  211482. void WebBrowserComponent::reloadLastURL()
  211483. {
  211484. if (lastURL.isNotEmpty())
  211485. {
  211486. goToURL (lastURL, &lastHeaders, &lastPostData);
  211487. lastURL = String::empty;
  211488. }
  211489. }
  211490. void WebBrowserComponent::parentHierarchyChanged()
  211491. {
  211492. checkWindowAssociation();
  211493. }
  211494. void WebBrowserComponent::moved()
  211495. {
  211496. }
  211497. void WebBrowserComponent::resized()
  211498. {
  211499. }
  211500. void WebBrowserComponent::visibilityChanged()
  211501. {
  211502. checkWindowAssociation();
  211503. }
  211504. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  211505. {
  211506. return true;
  211507. }
  211508. END_JUCE_NAMESPACE
  211509. /********* End of inlined file: juce_linux_WebBrowserComponent.cpp *********/
  211510. /********* Start of inlined file: juce_linux_Windowing.cpp *********/
  211511. #if JUCE_BUILD_GUI_CLASSES
  211512. #include <X11/Xlib.h>
  211513. #include <X11/Xutil.h>
  211514. #include <X11/Xatom.h>
  211515. #include <X11/Xmd.h>
  211516. #include <X11/keysym.h>
  211517. #include <X11/cursorfont.h>
  211518. #include <dlfcn.h>
  211519. #if JUCE_USE_XINERAMA
  211520. /* If you're trying to use Xinerama, you'll need to install the "libxinerama-dev" package..
  211521. */
  211522. #include <X11/extensions/Xinerama.h>
  211523. #endif
  211524. #if JUCE_USE_XSHM
  211525. #include <X11/extensions/XShm.h>
  211526. #include <sys/shm.h>
  211527. #include <sys/ipc.h>
  211528. #endif
  211529. #if JUCE_OPENGL
  211530. /* Got an include error here?
  211531. If you want to install OpenGL support, the packages to get are "mesa-common-dev"
  211532. and "freeglut3-dev".
  211533. Alternatively, you can turn off the JUCE_OPENGL flag in juce_Config.h if you
  211534. want to disable it.
  211535. */
  211536. #include <GL/glx.h>
  211537. #endif
  211538. #undef KeyPress
  211539. BEGIN_JUCE_NAMESPACE
  211540. #define TAKE_FOCUS 0
  211541. #define DELETE_WINDOW 1
  211542. #define SYSTEM_TRAY_REQUEST_DOCK 0
  211543. #define SYSTEM_TRAY_BEGIN_MESSAGE 1
  211544. #define SYSTEM_TRAY_CANCEL_MESSAGE 2
  211545. static const int repaintTimerPeriod = 1000 / 100; // 100 fps maximum
  211546. static Atom wm_ChangeState = None;
  211547. static Atom wm_State = None;
  211548. static Atom wm_Protocols = None;
  211549. static Atom wm_ProtocolList [2] = { None, None };
  211550. static Atom wm_ActiveWin = None;
  211551. #define ourDndVersion 3
  211552. static Atom XA_XdndAware = None;
  211553. static Atom XA_XdndEnter = None;
  211554. static Atom XA_XdndLeave = None;
  211555. static Atom XA_XdndPosition = None;
  211556. static Atom XA_XdndStatus = None;
  211557. static Atom XA_XdndDrop = None;
  211558. static Atom XA_XdndFinished = None;
  211559. static Atom XA_XdndSelection = None;
  211560. static Atom XA_XdndProxy = None;
  211561. static Atom XA_XdndTypeList = None;
  211562. static Atom XA_XdndActionList = None;
  211563. static Atom XA_XdndActionDescription = None;
  211564. static Atom XA_XdndActionCopy = None;
  211565. static Atom XA_XdndActionMove = None;
  211566. static Atom XA_XdndActionLink = None;
  211567. static Atom XA_XdndActionAsk = None;
  211568. static Atom XA_XdndActionPrivate = None;
  211569. static Atom XA_JXSelectionWindowProperty = None;
  211570. static Atom XA_MimeTextPlain = None;
  211571. static Atom XA_MimeTextUriList = None;
  211572. static Atom XA_MimeRootDrop = None;
  211573. static XErrorHandler oldHandler = 0;
  211574. static int trappedErrorCode = 0;
  211575. extern "C" int errorTrapHandler (Display* dpy, XErrorEvent* err)
  211576. {
  211577. trappedErrorCode = err->error_code;
  211578. return 0;
  211579. }
  211580. static void trapErrors()
  211581. {
  211582. trappedErrorCode = 0;
  211583. oldHandler = XSetErrorHandler (errorTrapHandler);
  211584. }
  211585. static bool untrapErrors()
  211586. {
  211587. XSetErrorHandler (oldHandler);
  211588. return (trappedErrorCode == 0);
  211589. }
  211590. static bool isActiveApplication = false;
  211591. bool Process::isForegroundProcess() throw()
  211592. {
  211593. return isActiveApplication;
  211594. }
  211595. // (used in the messaging code, declared here for build reasons)
  211596. bool juce_isRunningAsApplication()
  211597. {
  211598. return JUCEApplication::getInstance() != 0;
  211599. }
  211600. // These are defined in juce_linux_Messaging.cpp
  211601. extern Display* display;
  211602. extern XContext improbableNumber;
  211603. static const int eventMask = NoEventMask | KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask
  211604. | EnterWindowMask | LeaveWindowMask | PointerMotionMask | KeymapStateMask
  211605. | ExposureMask | StructureNotifyMask | FocusChangeMask;
  211606. static int pointerMap[5];
  211607. static int lastMousePosX = 0, lastMousePosY = 0;
  211608. enum MouseButtons
  211609. {
  211610. NoButton = 0,
  211611. LeftButton = 1,
  211612. MiddleButton = 2,
  211613. RightButton = 3,
  211614. WheelUp = 4,
  211615. WheelDown = 5
  211616. };
  211617. static void getMousePos (int& x, int& y, int& mouseMods) throw()
  211618. {
  211619. Window root, child;
  211620. int winx, winy;
  211621. unsigned int mask;
  211622. mouseMods = 0;
  211623. if (XQueryPointer (display,
  211624. RootWindow (display, DefaultScreen (display)),
  211625. &root, &child,
  211626. &x, &y, &winx, &winy, &mask) == False)
  211627. {
  211628. // Pointer not on the default screen
  211629. x = y = -1;
  211630. }
  211631. else
  211632. {
  211633. if ((mask & Button1Mask) != 0)
  211634. mouseMods |= ModifierKeys::leftButtonModifier;
  211635. if ((mask & Button2Mask) != 0)
  211636. mouseMods |= ModifierKeys::middleButtonModifier;
  211637. if ((mask & Button3Mask) != 0)
  211638. mouseMods |= ModifierKeys::rightButtonModifier;
  211639. }
  211640. }
  211641. static int AltMask = 0;
  211642. static int NumLockMask = 0;
  211643. static bool numLock = 0;
  211644. static bool capsLock = 0;
  211645. static char keyStates [32];
  211646. static void updateKeyStates (const int keycode, const bool press) throw()
  211647. {
  211648. const int keybyte = keycode >> 3;
  211649. const int keybit = (1 << (keycode & 7));
  211650. if (press)
  211651. keyStates [keybyte] |= keybit;
  211652. else
  211653. keyStates [keybyte] &= ~keybit;
  211654. }
  211655. static bool keyDown (const int keycode) throw()
  211656. {
  211657. const int keybyte = keycode >> 3;
  211658. const int keybit = (1 << (keycode & 7));
  211659. return (keyStates [keybyte] & keybit) != 0;
  211660. }
  211661. static const int extendedKeyModifier = 0x10000000;
  211662. bool KeyPress::isKeyCurrentlyDown (const int keyCode) throw()
  211663. {
  211664. int keysym;
  211665. if (keyCode & extendedKeyModifier)
  211666. {
  211667. keysym = 0xff00 | (keyCode & 0xff);
  211668. }
  211669. else
  211670. {
  211671. keysym = keyCode;
  211672. if (keysym == (XK_Tab & 0xff)
  211673. || keysym == (XK_Return & 0xff)
  211674. || keysym == (XK_Escape & 0xff)
  211675. || keysym == (XK_BackSpace & 0xff))
  211676. {
  211677. keysym |= 0xff00;
  211678. }
  211679. }
  211680. return keyDown (XKeysymToKeycode (display, keysym));
  211681. }
  211682. // Alt and Num lock are not defined by standard X
  211683. // modifier constants: check what they're mapped to
  211684. static void getModifierMapping() throw()
  211685. {
  211686. const int altLeftCode = XKeysymToKeycode (display, XK_Alt_L);
  211687. const int numLockCode = XKeysymToKeycode (display, XK_Num_Lock);
  211688. AltMask = 0;
  211689. NumLockMask = 0;
  211690. XModifierKeymap* mapping = XGetModifierMapping (display);
  211691. if (mapping)
  211692. {
  211693. for (int i = 0; i < 8; i++)
  211694. {
  211695. if (mapping->modifiermap [i << 1] == altLeftCode)
  211696. AltMask = 1 << i;
  211697. else if (mapping->modifiermap [i << 1] == numLockCode)
  211698. NumLockMask = 1 << i;
  211699. }
  211700. XFreeModifiermap (mapping);
  211701. }
  211702. }
  211703. static int currentModifiers = 0;
  211704. void ModifierKeys::updateCurrentModifiers() throw()
  211705. {
  211706. currentModifierFlags = currentModifiers;
  211707. }
  211708. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  211709. {
  211710. int x, y, mouseMods;
  211711. getMousePos (x, y, mouseMods);
  211712. currentModifiers &= ~ModifierKeys::allMouseButtonModifiers;
  211713. currentModifiers |= mouseMods;
  211714. return ModifierKeys (currentModifiers);
  211715. }
  211716. static void updateKeyModifiers (const int status) throw()
  211717. {
  211718. currentModifiers &= ~(ModifierKeys::shiftModifier
  211719. | ModifierKeys::ctrlModifier
  211720. | ModifierKeys::altModifier);
  211721. if (status & ShiftMask)
  211722. currentModifiers |= ModifierKeys::shiftModifier;
  211723. if (status & ControlMask)
  211724. currentModifiers |= ModifierKeys::ctrlModifier;
  211725. if (status & AltMask)
  211726. currentModifiers |= ModifierKeys::altModifier;
  211727. numLock = ((status & NumLockMask) != 0);
  211728. capsLock = ((status & LockMask) != 0);
  211729. }
  211730. static bool updateKeyModifiersFromSym (KeySym sym, const bool press) throw()
  211731. {
  211732. int modifier = 0;
  211733. bool isModifier = true;
  211734. switch (sym)
  211735. {
  211736. case XK_Shift_L:
  211737. case XK_Shift_R:
  211738. modifier = ModifierKeys::shiftModifier;
  211739. break;
  211740. case XK_Control_L:
  211741. case XK_Control_R:
  211742. modifier = ModifierKeys::ctrlModifier;
  211743. break;
  211744. case XK_Alt_L:
  211745. case XK_Alt_R:
  211746. modifier = ModifierKeys::altModifier;
  211747. break;
  211748. case XK_Num_Lock:
  211749. if (press)
  211750. numLock = ! numLock;
  211751. break;
  211752. case XK_Caps_Lock:
  211753. if (press)
  211754. capsLock = ! capsLock;
  211755. break;
  211756. case XK_Scroll_Lock:
  211757. break;
  211758. default:
  211759. isModifier = false;
  211760. break;
  211761. }
  211762. if (modifier != 0)
  211763. {
  211764. if (press)
  211765. currentModifiers |= modifier;
  211766. else
  211767. currentModifiers &= ~modifier;
  211768. }
  211769. return isModifier;
  211770. }
  211771. #if JUCE_USE_XSHM
  211772. static bool isShmAvailable() throw()
  211773. {
  211774. static bool isChecked = false;
  211775. static bool isAvailable = false;
  211776. if (! isChecked)
  211777. {
  211778. isChecked = true;
  211779. int major, minor;
  211780. Bool pixmaps;
  211781. if (XShmQueryVersion (display, &major, &minor, &pixmaps))
  211782. {
  211783. trapErrors();
  211784. XShmSegmentInfo segmentInfo;
  211785. zerostruct (segmentInfo);
  211786. XImage* xImage = XShmCreateImage (display, DefaultVisual (display, DefaultScreen (display)),
  211787. 24, ZPixmap, 0, &segmentInfo, 50, 50);
  211788. if ((segmentInfo.shmid = shmget (IPC_PRIVATE,
  211789. xImage->bytes_per_line * xImage->height,
  211790. IPC_CREAT | 0777)) >= 0)
  211791. {
  211792. segmentInfo.shmaddr = (char*) shmat (segmentInfo.shmid, 0, 0);
  211793. if (segmentInfo.shmaddr != (void*) -1)
  211794. {
  211795. segmentInfo.readOnly = False;
  211796. xImage->data = segmentInfo.shmaddr;
  211797. XSync (display, False);
  211798. if (XShmAttach (display, &segmentInfo) != 0)
  211799. {
  211800. XSync (display, False);
  211801. XShmDetach (display, &segmentInfo);
  211802. isAvailable = true;
  211803. }
  211804. }
  211805. XFlush (display);
  211806. XDestroyImage (xImage);
  211807. shmdt (segmentInfo.shmaddr);
  211808. }
  211809. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  211810. isAvailable &= untrapErrors();
  211811. }
  211812. }
  211813. return isAvailable;
  211814. }
  211815. #endif
  211816. class XBitmapImage : public Image
  211817. {
  211818. public:
  211819. XBitmapImage (const PixelFormat format_, const int w, const int h,
  211820. const bool clearImage, const bool is16Bit_)
  211821. : Image (format_, w, h),
  211822. is16Bit (is16Bit_)
  211823. {
  211824. jassert (format_ == RGB || format_ == ARGB);
  211825. pixelStride = (format_ == RGB) ? 3 : 4;
  211826. lineStride = ((w * pixelStride + 3) & ~3);
  211827. Visual* const visual = DefaultVisual (display, DefaultScreen (display));
  211828. #if JUCE_USE_XSHM
  211829. usingXShm = false;
  211830. if ((! is16Bit) && isShmAvailable())
  211831. {
  211832. zerostruct (segmentInfo);
  211833. xImage = XShmCreateImage (display, visual, 24, ZPixmap, 0, &segmentInfo, w, h);
  211834. if (xImage != 0)
  211835. {
  211836. if ((segmentInfo.shmid = shmget (IPC_PRIVATE,
  211837. xImage->bytes_per_line * xImage->height,
  211838. IPC_CREAT | 0777)) >= 0)
  211839. {
  211840. segmentInfo.shmaddr = (char*) shmat (segmentInfo.shmid, 0, 0);
  211841. if (segmentInfo.shmaddr != (void*) -1)
  211842. {
  211843. segmentInfo.readOnly = False;
  211844. xImage->data = segmentInfo.shmaddr;
  211845. imageData = (uint8*) segmentInfo.shmaddr;
  211846. XSync (display, False);
  211847. if (XShmAttach (display, &segmentInfo) != 0)
  211848. {
  211849. XSync (display, False);
  211850. usingXShm = true;
  211851. }
  211852. else
  211853. {
  211854. jassertfalse
  211855. }
  211856. }
  211857. else
  211858. {
  211859. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  211860. }
  211861. }
  211862. }
  211863. }
  211864. if (! usingXShm)
  211865. #endif
  211866. {
  211867. imageData = (uint8*) juce_malloc (lineStride * h);
  211868. if (format_ == ARGB && clearImage)
  211869. zeromem (imageData, h * lineStride);
  211870. xImage = (XImage*) juce_calloc (sizeof (XImage));
  211871. xImage->width = w;
  211872. xImage->height = h;
  211873. xImage->xoffset = 0;
  211874. xImage->format = ZPixmap;
  211875. xImage->data = (char*) imageData;
  211876. xImage->byte_order = ImageByteOrder (display);
  211877. xImage->bitmap_unit = BitmapUnit (display);
  211878. xImage->bitmap_bit_order = BitmapBitOrder (display);
  211879. xImage->bitmap_pad = 32;
  211880. xImage->depth = pixelStride * 8;
  211881. xImage->bytes_per_line = lineStride;
  211882. xImage->bits_per_pixel = pixelStride * 8;
  211883. xImage->red_mask = 0x00FF0000;
  211884. xImage->green_mask = 0x0000FF00;
  211885. xImage->blue_mask = 0x000000FF;
  211886. if (is16Bit)
  211887. {
  211888. const int pixelStride = 2;
  211889. const int lineStride = ((w * pixelStride + 3) & ~3);
  211890. xImage->data = (char*) juce_malloc (lineStride * h);
  211891. xImage->bitmap_pad = 16;
  211892. xImage->depth = pixelStride * 8;
  211893. xImage->bytes_per_line = lineStride;
  211894. xImage->bits_per_pixel = pixelStride * 8;
  211895. xImage->red_mask = visual->red_mask;
  211896. xImage->green_mask = visual->green_mask;
  211897. xImage->blue_mask = visual->blue_mask;
  211898. }
  211899. if (! XInitImage (xImage))
  211900. {
  211901. jassertfalse
  211902. }
  211903. }
  211904. }
  211905. ~XBitmapImage()
  211906. {
  211907. #if JUCE_USE_XSHM
  211908. if (usingXShm)
  211909. {
  211910. XShmDetach (display, &segmentInfo);
  211911. XFlush (display);
  211912. XDestroyImage (xImage);
  211913. shmdt (segmentInfo.shmaddr);
  211914. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  211915. }
  211916. else
  211917. #endif
  211918. {
  211919. juce_free (xImage->data);
  211920. xImage->data = 0;
  211921. XDestroyImage (xImage);
  211922. }
  211923. if (! is16Bit)
  211924. imageData = 0; // to stop the base class freeing this (for the 16-bit version we want it to free it)
  211925. }
  211926. void blitToWindow (Window window, int dx, int dy, int dw, int dh, int sx, int sy)
  211927. {
  211928. static GC gc = 0;
  211929. if (gc == 0)
  211930. gc = DefaultGC (display, DefaultScreen (display));
  211931. if (is16Bit)
  211932. {
  211933. const uint32 rMask = xImage->red_mask;
  211934. const uint32 rShiftL = jmax (0, getShiftNeeded (rMask));
  211935. const uint32 rShiftR = jmax (0, -getShiftNeeded (rMask));
  211936. const uint32 gMask = xImage->green_mask;
  211937. const uint32 gShiftL = jmax (0, getShiftNeeded (gMask));
  211938. const uint32 gShiftR = jmax (0, -getShiftNeeded (gMask));
  211939. const uint32 bMask = xImage->blue_mask;
  211940. const uint32 bShiftL = jmax (0, getShiftNeeded (bMask));
  211941. const uint32 bShiftR = jmax (0, -getShiftNeeded (bMask));
  211942. int ls, ps;
  211943. const uint8* const pixels = lockPixelDataReadOnly (0, 0, getWidth(), getHeight(), ls, ps);
  211944. jassert (! isARGB())
  211945. for (int y = sy; y < sy + dh; ++y)
  211946. {
  211947. const uint8* p = pixels + y * ls + sx * ps;
  211948. for (int x = sx; x < sx + dw; ++x)
  211949. {
  211950. const PixelRGB* const pixel = (const PixelRGB*) p;
  211951. p += ps;
  211952. XPutPixel (xImage, x, y,
  211953. (((((uint32) pixel->getRed()) << rShiftL) >> rShiftR) & rMask)
  211954. | (((((uint32) pixel->getGreen()) << gShiftL) >> gShiftR) & gMask)
  211955. | (((((uint32) pixel->getBlue()) << bShiftL) >> bShiftR) & bMask));
  211956. }
  211957. }
  211958. releasePixelDataReadOnly (pixels);
  211959. }
  211960. // blit results to screen.
  211961. #if JUCE_USE_XSHM
  211962. if (usingXShm)
  211963. XShmPutImage (display, (::Drawable) window, gc, xImage, sx, sy, dx, dy, dw, dh, False);
  211964. else
  211965. #endif
  211966. XPutImage (display, (::Drawable) window, gc, xImage, sx, sy, dx, dy, dw, dh);
  211967. }
  211968. juce_UseDebuggingNewOperator
  211969. private:
  211970. XImage* xImage;
  211971. const bool is16Bit;
  211972. #if JUCE_USE_XSHM
  211973. XShmSegmentInfo segmentInfo;
  211974. bool usingXShm;
  211975. #endif
  211976. static int getShiftNeeded (const uint32 mask) throw()
  211977. {
  211978. for (int i = 32; --i >= 0;)
  211979. if (((mask >> i) & 1) != 0)
  211980. return i - 7;
  211981. jassertfalse
  211982. return 0;
  211983. }
  211984. };
  211985. #define checkMessageManagerIsLocked jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  211986. class LinuxComponentPeer : public ComponentPeer
  211987. {
  211988. public:
  211989. LinuxComponentPeer (Component* const component, const int windowStyleFlags)
  211990. : ComponentPeer (component, windowStyleFlags),
  211991. windowH (0),
  211992. parentWindow (0),
  211993. wx (0),
  211994. wy (0),
  211995. ww (0),
  211996. wh (0),
  211997. taskbarImage (0),
  211998. fullScreen (false),
  211999. entered (false),
  212000. mapped (false)
  212001. {
  212002. // it's dangerous to create a window on a thread other than the message thread..
  212003. checkMessageManagerIsLocked
  212004. repainter = new LinuxRepaintManager (this);
  212005. createWindow();
  212006. setTitle (component->getName());
  212007. }
  212008. ~LinuxComponentPeer()
  212009. {
  212010. // it's dangerous to delete a window on a thread other than the message thread..
  212011. checkMessageManagerIsLocked
  212012. deleteTaskBarIcon();
  212013. destroyWindow();
  212014. windowH = 0;
  212015. delete repainter;
  212016. }
  212017. void* getNativeHandle() const
  212018. {
  212019. return (void*) windowH;
  212020. }
  212021. static LinuxComponentPeer* getPeerFor (Window windowHandle) throw()
  212022. {
  212023. XPointer peer = 0;
  212024. if (! XFindContext (display, (XID) windowHandle, improbableNumber, &peer))
  212025. {
  212026. if (peer != 0 && ! ((LinuxComponentPeer*) peer)->isValidMessageListener())
  212027. peer = 0;
  212028. }
  212029. return (LinuxComponentPeer*) peer;
  212030. }
  212031. void setVisible (bool shouldBeVisible)
  212032. {
  212033. if (shouldBeVisible)
  212034. XMapWindow (display, windowH);
  212035. else
  212036. XUnmapWindow (display, windowH);
  212037. }
  212038. void setTitle (const String& title)
  212039. {
  212040. setWindowTitle (windowH, title);
  212041. }
  212042. void setPosition (int x, int y)
  212043. {
  212044. setBounds (x, y, ww, wh, false);
  212045. }
  212046. void setSize (int w, int h)
  212047. {
  212048. setBounds (wx, wy, w, h, false);
  212049. }
  212050. void setBounds (int x, int y, int w, int h, const bool isNowFullScreen)
  212051. {
  212052. fullScreen = isNowFullScreen;
  212053. if (windowH != 0)
  212054. {
  212055. const ComponentDeletionWatcher deletionChecker (component);
  212056. wx = x;
  212057. wy = y;
  212058. ww = jmax (1, w);
  212059. wh = jmax (1, h);
  212060. if (! mapped)
  212061. {
  212062. // Make sure the Window manager does what we want
  212063. XSizeHints* hints = XAllocSizeHints();
  212064. hints->flags = USSize | USPosition;
  212065. hints->width = ww + windowBorder.getLeftAndRight();
  212066. hints->height = wh + windowBorder.getTopAndBottom();
  212067. hints->x = wx - windowBorder.getLeft();
  212068. hints->y = wy - windowBorder.getTop();
  212069. XSetWMNormalHints (display, windowH, hints);
  212070. XFree (hints);
  212071. }
  212072. XMoveResizeWindow (display, windowH,
  212073. wx - windowBorder.getLeft(),
  212074. wy - windowBorder.getTop(),
  212075. ww + windowBorder.getLeftAndRight(),
  212076. wh + windowBorder.getTopAndBottom());
  212077. if (! deletionChecker.hasBeenDeleted())
  212078. {
  212079. updateBorderSize();
  212080. handleMovedOrResized();
  212081. }
  212082. }
  212083. }
  212084. void getBounds (int& x, int& y, int& w, int& h) const
  212085. {
  212086. x = wx;
  212087. y = wy;
  212088. w = ww;
  212089. h = wh;
  212090. }
  212091. int getScreenX() const
  212092. {
  212093. return wx;
  212094. }
  212095. int getScreenY() const
  212096. {
  212097. return wy;
  212098. }
  212099. void relativePositionToGlobal (int& x, int& y)
  212100. {
  212101. x += wx;
  212102. y += wy;
  212103. }
  212104. void globalPositionToRelative (int& x, int& y)
  212105. {
  212106. x -= wx;
  212107. y -= wy;
  212108. }
  212109. void setMinimised (bool shouldBeMinimised)
  212110. {
  212111. if (shouldBeMinimised)
  212112. {
  212113. Window root = RootWindow (display, DefaultScreen (display));
  212114. XClientMessageEvent clientMsg;
  212115. clientMsg.display = display;
  212116. clientMsg.window = windowH;
  212117. clientMsg.type = ClientMessage;
  212118. clientMsg.format = 32;
  212119. clientMsg.message_type = wm_ChangeState;
  212120. clientMsg.data.l[0] = IconicState;
  212121. XSendEvent (display, root, false,
  212122. SubstructureRedirectMask | SubstructureNotifyMask,
  212123. (XEvent*) &clientMsg);
  212124. }
  212125. else
  212126. {
  212127. setVisible (true);
  212128. }
  212129. }
  212130. bool isMinimised() const
  212131. {
  212132. bool minimised = false;
  212133. unsigned char* stateProp;
  212134. unsigned long nitems, bytesLeft;
  212135. Atom actualType;
  212136. int actualFormat;
  212137. if (XGetWindowProperty (display, windowH, wm_State, 0, 64, False,
  212138. wm_State, &actualType, &actualFormat, &nitems, &bytesLeft,
  212139. &stateProp) == Success
  212140. && actualType == wm_State
  212141. && actualFormat == 32
  212142. && nitems > 0)
  212143. {
  212144. if (((unsigned long*) stateProp)[0] == IconicState)
  212145. minimised = true;
  212146. XFree (stateProp);
  212147. }
  212148. return minimised;
  212149. }
  212150. void setFullScreen (const bool shouldBeFullScreen)
  212151. {
  212152. Rectangle r (lastNonFullscreenBounds); // (get a copy of this before de-minimising)
  212153. setMinimised (false);
  212154. if (fullScreen != shouldBeFullScreen)
  212155. {
  212156. if (shouldBeFullScreen)
  212157. r = Desktop::getInstance().getMainMonitorArea();
  212158. if (! r.isEmpty())
  212159. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  212160. getComponent()->repaint();
  212161. }
  212162. }
  212163. bool isFullScreen() const
  212164. {
  212165. return fullScreen;
  212166. }
  212167. bool isChildWindowOf (Window possibleParent) const
  212168. {
  212169. Window* windowList = 0;
  212170. uint32 windowListSize = 0;
  212171. Window parent, root;
  212172. if (XQueryTree (display, windowH, &root, &parent, &windowList, &windowListSize) != 0)
  212173. {
  212174. if (windowList != 0)
  212175. XFree (windowList);
  212176. return parent == possibleParent;
  212177. }
  212178. return false;
  212179. }
  212180. bool isFrontWindow() const
  212181. {
  212182. Window* windowList = 0;
  212183. uint32 windowListSize = 0;
  212184. bool result = false;
  212185. Window parent, root = RootWindow (display, DefaultScreen (display));
  212186. if (XQueryTree (display, root, &root, &parent, &windowList, &windowListSize) != 0)
  212187. {
  212188. for (int i = windowListSize; --i >= 0;)
  212189. {
  212190. LinuxComponentPeer* const peer = LinuxComponentPeer::getPeerFor (windowList[i]);
  212191. if (peer != 0)
  212192. {
  212193. result = (peer == this);
  212194. break;
  212195. }
  212196. }
  212197. }
  212198. if (windowList != 0)
  212199. XFree (windowList);
  212200. return result;
  212201. }
  212202. bool contains (int x, int y, bool trueIfInAChildWindow) const
  212203. {
  212204. jassert (x >= 0 && y >= 0 && x < ww && y < wh); // should only be called for points that are actually inside the bounds
  212205. if (((unsigned int) x) >= (unsigned int) ww
  212206. || ((unsigned int) y) >= (unsigned int) wh)
  212207. return false;
  212208. bool inFront = false;
  212209. for (int i = 0; i < Desktop::getInstance().getNumComponents(); ++i)
  212210. {
  212211. Component* const c = Desktop::getInstance().getComponent (i);
  212212. if (inFront)
  212213. {
  212214. if (c->contains (x + wx - c->getScreenX(),
  212215. y + wy - c->getScreenY()))
  212216. {
  212217. return false;
  212218. }
  212219. }
  212220. else if (c == getComponent())
  212221. {
  212222. inFront = true;
  212223. }
  212224. }
  212225. if (trueIfInAChildWindow)
  212226. return true;
  212227. ::Window root, child;
  212228. unsigned int bw, depth;
  212229. int wx, wy, w, h;
  212230. if (! XGetGeometry (display, (::Drawable) windowH, &root,
  212231. &wx, &wy, (unsigned int*) &w, (unsigned int*) &h,
  212232. &bw, &depth))
  212233. {
  212234. return false;
  212235. }
  212236. if (! XTranslateCoordinates (display, windowH, windowH, x, y, &wx, &wy, &child))
  212237. return false;
  212238. return child == None;
  212239. }
  212240. const BorderSize getFrameSize() const
  212241. {
  212242. return BorderSize();
  212243. }
  212244. bool setAlwaysOnTop (bool alwaysOnTop)
  212245. {
  212246. if (windowH != 0)
  212247. {
  212248. const bool wasVisible = component->isVisible();
  212249. if (wasVisible)
  212250. setVisible (false); // doesn't always seem to work if the window is visible when this is done..
  212251. XSetWindowAttributes swa;
  212252. swa.override_redirect = alwaysOnTop ? True : False;
  212253. XChangeWindowAttributes (display, windowH, CWOverrideRedirect, &swa);
  212254. if (wasVisible)
  212255. setVisible (true);
  212256. }
  212257. return true;
  212258. }
  212259. void toFront (bool makeActive)
  212260. {
  212261. if (makeActive)
  212262. {
  212263. setVisible (true);
  212264. grabFocus();
  212265. }
  212266. XEvent ev;
  212267. ev.xclient.type = ClientMessage;
  212268. ev.xclient.serial = 0;
  212269. ev.xclient.send_event = True;
  212270. ev.xclient.message_type = wm_ActiveWin;
  212271. ev.xclient.window = windowH;
  212272. ev.xclient.format = 32;
  212273. ev.xclient.data.l[0] = 2;
  212274. ev.xclient.data.l[1] = CurrentTime;
  212275. ev.xclient.data.l[2] = 0;
  212276. ev.xclient.data.l[3] = 0;
  212277. ev.xclient.data.l[4] = 0;
  212278. XSendEvent (display, RootWindow (display, DefaultScreen (display)),
  212279. False,
  212280. SubstructureRedirectMask | SubstructureNotifyMask,
  212281. &ev);
  212282. XSync (display, False);
  212283. handleBroughtToFront();
  212284. }
  212285. void toBehind (ComponentPeer* other)
  212286. {
  212287. LinuxComponentPeer* const otherPeer = dynamic_cast <LinuxComponentPeer*> (other);
  212288. jassert (otherPeer != 0); // wrong type of window?
  212289. if (otherPeer != 0)
  212290. {
  212291. setMinimised (false);
  212292. Window newStack[] = { otherPeer->windowH, windowH };
  212293. XRestackWindows (display, newStack, 2);
  212294. }
  212295. }
  212296. bool isFocused() const
  212297. {
  212298. int revert;
  212299. Window focusedWindow = 0;
  212300. XGetInputFocus (display, &focusedWindow, &revert);
  212301. return focusedWindow == windowH;
  212302. }
  212303. void grabFocus()
  212304. {
  212305. XWindowAttributes atts;
  212306. if (windowH != 0
  212307. && XGetWindowAttributes (display, windowH, &atts)
  212308. && atts.map_state == IsViewable
  212309. && ! isFocused())
  212310. {
  212311. XSetInputFocus (display, windowH, RevertToParent, CurrentTime);
  212312. isActiveApplication = true;
  212313. }
  212314. }
  212315. void repaint (int x, int y, int w, int h)
  212316. {
  212317. if (Rectangle::intersectRectangles (x, y, w, h,
  212318. 0, 0,
  212319. getComponent()->getWidth(),
  212320. getComponent()->getHeight()))
  212321. {
  212322. repainter->repaint (x, y, w, h);
  212323. }
  212324. }
  212325. void performAnyPendingRepaintsNow()
  212326. {
  212327. repainter->performAnyPendingRepaintsNow();
  212328. }
  212329. void setIcon (const Image& newIcon)
  212330. {
  212331. const int dataSize = newIcon.getWidth() * newIcon.getHeight() + 2;
  212332. uint32* const data = (uint32*) juce_malloc (dataSize);
  212333. int index = 0;
  212334. data[index++] = newIcon.getWidth();
  212335. data[index++] = newIcon.getHeight();
  212336. for (int y = 0; y < newIcon.getHeight(); ++y)
  212337. for (int x = 0; x < newIcon.getWidth(); ++x)
  212338. data[index++] = newIcon.getPixelAt (x, y).getARGB();
  212339. XChangeProperty (display, windowH,
  212340. XInternAtom (display, "_NET_WM_ICON", False),
  212341. XA_CARDINAL, 32, PropModeReplace,
  212342. (unsigned char*) data, dataSize);
  212343. XSync (display, False);
  212344. juce_free (data);
  212345. }
  212346. void handleWindowMessage (XEvent* event)
  212347. {
  212348. switch (event->xany.type)
  212349. {
  212350. case 2: // 'KeyPress'
  212351. {
  212352. XKeyEvent* const keyEvent = (XKeyEvent*) &event->xkey;
  212353. updateKeyStates (keyEvent->keycode, true);
  212354. char utf8 [64];
  212355. zeromem (utf8, sizeof (utf8));
  212356. KeySym sym;
  212357. XLookupString (keyEvent, utf8, sizeof (utf8), &sym, 0);
  212358. const juce_wchar unicodeChar = *(const juce_wchar*) String::fromUTF8 ((const uint8*) utf8, sizeof (utf8) - 1);
  212359. int keyCode = (int) unicodeChar;
  212360. if (keyCode < 0x20)
  212361. keyCode = XKeycodeToKeysym (display, keyEvent->keycode,
  212362. (currentModifiers & ModifierKeys::shiftModifier) != 0 ? 1 : 0);
  212363. const int oldMods = currentModifiers;
  212364. bool keyPressed = false;
  212365. const bool keyDownChange = (sym != NoSymbol) && ! updateKeyModifiersFromSym (sym, true);
  212366. if ((sym & 0xff00) == 0xff00)
  212367. {
  212368. // Translate keypad
  212369. if (sym == XK_KP_Divide)
  212370. keyCode = XK_slash;
  212371. else if (sym == XK_KP_Multiply)
  212372. keyCode = XK_asterisk;
  212373. else if (sym == XK_KP_Subtract)
  212374. keyCode = XK_hyphen;
  212375. else if (sym == XK_KP_Add)
  212376. keyCode = XK_plus;
  212377. else if (sym == XK_KP_Enter)
  212378. keyCode = XK_Return;
  212379. else if (sym == XK_KP_Decimal)
  212380. keyCode = numLock ? XK_period : XK_Delete;
  212381. else if (sym == XK_KP_0)
  212382. keyCode = numLock ? XK_0 : XK_Insert;
  212383. else if (sym == XK_KP_1)
  212384. keyCode = numLock ? XK_1 : XK_End;
  212385. else if (sym == XK_KP_2)
  212386. keyCode = numLock ? XK_2 : XK_Down;
  212387. else if (sym == XK_KP_3)
  212388. keyCode = numLock ? XK_3 : XK_Page_Down;
  212389. else if (sym == XK_KP_4)
  212390. keyCode = numLock ? XK_4 : XK_Left;
  212391. else if (sym == XK_KP_5)
  212392. keyCode = XK_5;
  212393. else if (sym == XK_KP_6)
  212394. keyCode = numLock ? XK_6 : XK_Right;
  212395. else if (sym == XK_KP_7)
  212396. keyCode = numLock ? XK_7 : XK_Home;
  212397. else if (sym == XK_KP_8)
  212398. keyCode = numLock ? XK_8 : XK_Up;
  212399. else if (sym == XK_KP_9)
  212400. keyCode = numLock ? XK_9 : XK_Page_Up;
  212401. switch (sym)
  212402. {
  212403. case XK_Left:
  212404. case XK_Right:
  212405. case XK_Up:
  212406. case XK_Down:
  212407. case XK_Page_Up:
  212408. case XK_Page_Down:
  212409. case XK_End:
  212410. case XK_Home:
  212411. case XK_Delete:
  212412. case XK_Insert:
  212413. keyPressed = true;
  212414. keyCode = (sym & 0xff) | extendedKeyModifier;
  212415. break;
  212416. case XK_Tab:
  212417. case XK_Return:
  212418. case XK_Escape:
  212419. case XK_BackSpace:
  212420. keyPressed = true;
  212421. keyCode &= 0xff;
  212422. break;
  212423. default:
  212424. {
  212425. if (sym >= XK_F1 && sym <= XK_F16)
  212426. {
  212427. keyPressed = true;
  212428. keyCode = (sym & 0xff) | extendedKeyModifier;
  212429. }
  212430. break;
  212431. }
  212432. }
  212433. }
  212434. if (utf8[0] != 0 || ((sym & 0xff00) == 0 && sym >= 8))
  212435. keyPressed = true;
  212436. if (oldMods != currentModifiers)
  212437. handleModifierKeysChange();
  212438. if (keyDownChange)
  212439. handleKeyUpOrDown();
  212440. if (keyPressed)
  212441. handleKeyPress (keyCode, unicodeChar);
  212442. break;
  212443. }
  212444. case KeyRelease:
  212445. {
  212446. const XKeyEvent* const keyEvent = (const XKeyEvent*) &event->xkey;
  212447. updateKeyStates (keyEvent->keycode, false);
  212448. KeySym sym = XKeycodeToKeysym (display, keyEvent->keycode, 0);
  212449. const int oldMods = currentModifiers;
  212450. const bool keyDownChange = (sym != NoSymbol) && ! updateKeyModifiersFromSym (sym, false);
  212451. if (oldMods != currentModifiers)
  212452. handleModifierKeysChange();
  212453. if (keyDownChange)
  212454. handleKeyUpOrDown();
  212455. break;
  212456. }
  212457. case ButtonPress:
  212458. {
  212459. const XButtonPressedEvent* const buttonPressEvent = (const XButtonPressedEvent*) &event->xbutton;
  212460. bool buttonMsg = false;
  212461. bool wheelUpMsg = false;
  212462. bool wheelDownMsg = false;
  212463. const int map = pointerMap [buttonPressEvent->button - Button1];
  212464. if (map == LeftButton)
  212465. {
  212466. currentModifiers |= ModifierKeys::leftButtonModifier;
  212467. buttonMsg = true;
  212468. }
  212469. else if (map == RightButton)
  212470. {
  212471. currentModifiers |= ModifierKeys::rightButtonModifier;
  212472. buttonMsg = true;
  212473. }
  212474. else if (map == MiddleButton)
  212475. {
  212476. currentModifiers |= ModifierKeys::middleButtonModifier;
  212477. buttonMsg = true;
  212478. }
  212479. else if (map == WheelUp)
  212480. {
  212481. wheelUpMsg = true;
  212482. }
  212483. else if (map == WheelDown)
  212484. {
  212485. wheelDownMsg = true;
  212486. }
  212487. updateKeyModifiers (buttonPressEvent->state);
  212488. if (buttonMsg)
  212489. {
  212490. toFront (true);
  212491. handleMouseDown (buttonPressEvent->x, buttonPressEvent->y,
  212492. getEventTime (buttonPressEvent->time));
  212493. }
  212494. else if (wheelUpMsg || wheelDownMsg)
  212495. {
  212496. handleMouseWheel (0, wheelDownMsg ? -84 : 84,
  212497. getEventTime (buttonPressEvent->time));
  212498. }
  212499. lastMousePosX = lastMousePosY = 0x100000;
  212500. break;
  212501. }
  212502. case ButtonRelease:
  212503. {
  212504. const XButtonReleasedEvent* const buttonRelEvent = (const XButtonReleasedEvent*) &event->xbutton;
  212505. const int oldModifiers = currentModifiers;
  212506. const int map = pointerMap [buttonRelEvent->button - Button1];
  212507. if (map == LeftButton)
  212508. currentModifiers &= ~ModifierKeys::leftButtonModifier;
  212509. else if (map == RightButton)
  212510. currentModifiers &= ~ModifierKeys::rightButtonModifier;
  212511. else if (map == MiddleButton)
  212512. currentModifiers &= ~ModifierKeys::middleButtonModifier;
  212513. updateKeyModifiers (buttonRelEvent->state);
  212514. handleMouseUp (oldModifiers,
  212515. buttonRelEvent->x, buttonRelEvent->y,
  212516. getEventTime (buttonRelEvent->time));
  212517. lastMousePosX = lastMousePosY = 0x100000;
  212518. break;
  212519. }
  212520. case MotionNotify:
  212521. {
  212522. const XPointerMovedEvent* const movedEvent = (const XPointerMovedEvent*) &event->xmotion;
  212523. updateKeyModifiers (movedEvent->state);
  212524. int x, y, mouseMods;
  212525. getMousePos (x, y, mouseMods);
  212526. if (lastMousePosX != x || lastMousePosY != y)
  212527. {
  212528. lastMousePosX = x;
  212529. lastMousePosY = y;
  212530. if (parentWindow != 0 && (styleFlags & windowHasTitleBar) == 0)
  212531. {
  212532. Window wRoot = 0, wParent = 0;
  212533. Window* wChild = 0;
  212534. unsigned int numChildren;
  212535. XQueryTree (display, windowH, &wRoot, &wParent, &wChild, &numChildren);
  212536. if (wParent != 0
  212537. && wParent != windowH
  212538. && wParent != wRoot)
  212539. {
  212540. parentWindow = wParent;
  212541. updateBounds();
  212542. x -= getScreenX();
  212543. y -= getScreenY();
  212544. }
  212545. else
  212546. {
  212547. parentWindow = 0;
  212548. x -= getScreenX();
  212549. y -= getScreenY();
  212550. }
  212551. }
  212552. else
  212553. {
  212554. x -= getScreenX();
  212555. y -= getScreenY();
  212556. }
  212557. if ((currentModifiers & ModifierKeys::allMouseButtonModifiers) == 0)
  212558. handleMouseMove (x, y, getEventTime (movedEvent->time));
  212559. else
  212560. handleMouseDrag (x, y, getEventTime (movedEvent->time));
  212561. }
  212562. break;
  212563. }
  212564. case EnterNotify:
  212565. {
  212566. lastMousePosX = lastMousePosY = 0x100000;
  212567. const XEnterWindowEvent* const enterEvent = (const XEnterWindowEvent*) &event->xcrossing;
  212568. if ((currentModifiers & ModifierKeys::allMouseButtonModifiers) == 0
  212569. && ! entered)
  212570. {
  212571. updateKeyModifiers (enterEvent->state);
  212572. handleMouseEnter (enterEvent->x, enterEvent->y, getEventTime (enterEvent->time));
  212573. entered = true;
  212574. }
  212575. break;
  212576. }
  212577. case LeaveNotify:
  212578. {
  212579. const XLeaveWindowEvent* const leaveEvent = (const XLeaveWindowEvent*) &event->xcrossing;
  212580. // Suppress the normal leave if we've got a pointer grab, or if
  212581. // it's a bogus one caused by clicking a mouse button when running
  212582. // in a Window manager
  212583. if (((currentModifiers & ModifierKeys::allMouseButtonModifiers) == 0
  212584. && leaveEvent->mode == NotifyNormal)
  212585. || leaveEvent->mode == NotifyUngrab)
  212586. {
  212587. updateKeyModifiers (leaveEvent->state);
  212588. handleMouseExit (leaveEvent->x, leaveEvent->y, getEventTime (leaveEvent->time));
  212589. entered = false;
  212590. }
  212591. break;
  212592. }
  212593. case FocusIn:
  212594. {
  212595. isActiveApplication = true;
  212596. if (isFocused())
  212597. handleFocusGain();
  212598. break;
  212599. }
  212600. case FocusOut:
  212601. {
  212602. isActiveApplication = false;
  212603. if (! isFocused())
  212604. handleFocusLoss();
  212605. break;
  212606. }
  212607. case Expose:
  212608. {
  212609. // Batch together all pending expose events
  212610. XExposeEvent* exposeEvent = (XExposeEvent*) &event->xexpose;
  212611. XEvent nextEvent;
  212612. if (exposeEvent->window != windowH)
  212613. {
  212614. Window child;
  212615. XTranslateCoordinates (display, exposeEvent->window, windowH,
  212616. exposeEvent->x, exposeEvent->y, &exposeEvent->x, &exposeEvent->y,
  212617. &child);
  212618. }
  212619. repaint (exposeEvent->x, exposeEvent->y,
  212620. exposeEvent->width, exposeEvent->height);
  212621. while (XEventsQueued (display, QueuedAfterFlush) > 0)
  212622. {
  212623. XPeekEvent (display, (XEvent*) &nextEvent);
  212624. if (nextEvent.type != Expose || nextEvent.xany.window != event->xany.window)
  212625. break;
  212626. XNextEvent (display, (XEvent*) &nextEvent);
  212627. XExposeEvent* nextExposeEvent = (XExposeEvent*) &nextEvent.xexpose;
  212628. repaint (nextExposeEvent->x, nextExposeEvent->y,
  212629. nextExposeEvent->width, nextExposeEvent->height);
  212630. }
  212631. break;
  212632. }
  212633. case CirculateNotify:
  212634. case CreateNotify:
  212635. case DestroyNotify:
  212636. // Think we can ignore these
  212637. break;
  212638. case ConfigureNotify:
  212639. {
  212640. updateBounds();
  212641. updateBorderSize();
  212642. handleMovedOrResized();
  212643. // if the native title bar is dragged, need to tell any active menus, etc.
  212644. if ((styleFlags & windowHasTitleBar) != 0
  212645. && component->isCurrentlyBlockedByAnotherModalComponent())
  212646. {
  212647. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  212648. if (currentModalComp != 0)
  212649. currentModalComp->inputAttemptWhenModal();
  212650. }
  212651. XConfigureEvent* const confEvent = (XConfigureEvent*) &event->xconfigure;
  212652. if (confEvent->window == windowH
  212653. && confEvent->above != 0
  212654. && isFrontWindow())
  212655. {
  212656. handleBroughtToFront();
  212657. }
  212658. break;
  212659. }
  212660. case ReparentNotify:
  212661. case GravityNotify:
  212662. {
  212663. parentWindow = 0;
  212664. Window wRoot = 0;
  212665. Window* wChild = 0;
  212666. unsigned int numChildren;
  212667. XQueryTree (display, windowH, &wRoot, &parentWindow, &wChild, &numChildren);
  212668. if (parentWindow == windowH || parentWindow == wRoot)
  212669. parentWindow = 0;
  212670. updateBounds();
  212671. updateBorderSize();
  212672. handleMovedOrResized();
  212673. break;
  212674. }
  212675. case MapNotify:
  212676. mapped = true;
  212677. handleBroughtToFront();
  212678. break;
  212679. case UnmapNotify:
  212680. mapped = false;
  212681. break;
  212682. case MappingNotify:
  212683. {
  212684. XMappingEvent* mappingEvent = (XMappingEvent*) &event->xmapping;
  212685. if (mappingEvent->request != MappingPointer)
  212686. {
  212687. // Deal with modifier/keyboard mapping
  212688. XRefreshKeyboardMapping (mappingEvent);
  212689. getModifierMapping();
  212690. }
  212691. break;
  212692. }
  212693. case ClientMessage:
  212694. {
  212695. const XClientMessageEvent* const clientMsg = (const XClientMessageEvent*) &event->xclient;
  212696. if (clientMsg->message_type == wm_Protocols && clientMsg->format == 32)
  212697. {
  212698. const Atom atom = (Atom) clientMsg->data.l[0];
  212699. if (atom == wm_ProtocolList [TAKE_FOCUS])
  212700. {
  212701. XWindowAttributes atts;
  212702. if (clientMsg->window != 0
  212703. && XGetWindowAttributes (display, clientMsg->window, &atts))
  212704. {
  212705. if (atts.map_state == IsViewable)
  212706. XSetInputFocus (display, clientMsg->window, RevertToParent, clientMsg->data.l[1]);
  212707. }
  212708. }
  212709. else if (atom == wm_ProtocolList [DELETE_WINDOW])
  212710. {
  212711. handleUserClosingWindow();
  212712. }
  212713. }
  212714. else if (clientMsg->message_type == XA_XdndEnter)
  212715. {
  212716. handleDragAndDropEnter (clientMsg);
  212717. }
  212718. else if (clientMsg->message_type == XA_XdndLeave)
  212719. {
  212720. resetDragAndDrop();
  212721. }
  212722. else if (clientMsg->message_type == XA_XdndPosition)
  212723. {
  212724. handleDragAndDropPosition (clientMsg);
  212725. }
  212726. else if (clientMsg->message_type == XA_XdndDrop)
  212727. {
  212728. handleDragAndDropDrop (clientMsg);
  212729. }
  212730. else if (clientMsg->message_type == XA_XdndStatus)
  212731. {
  212732. handleDragAndDropStatus (clientMsg);
  212733. }
  212734. else if (clientMsg->message_type == XA_XdndFinished)
  212735. {
  212736. resetDragAndDrop();
  212737. }
  212738. break;
  212739. }
  212740. case SelectionNotify:
  212741. handleDragAndDropSelection (event);
  212742. break;
  212743. case SelectionClear:
  212744. case SelectionRequest:
  212745. break;
  212746. default:
  212747. break;
  212748. }
  212749. }
  212750. void showMouseCursor (Cursor cursor) throw()
  212751. {
  212752. XDefineCursor (display, windowH, cursor);
  212753. }
  212754. void setTaskBarIcon (const Image& image)
  212755. {
  212756. deleteTaskBarIcon();
  212757. taskbarImage = image.createCopy();
  212758. Screen* const screen = XDefaultScreenOfDisplay (display);
  212759. const int screenNumber = XScreenNumberOfScreen (screen);
  212760. char screenAtom[32];
  212761. snprintf (screenAtom, sizeof (screenAtom), "_NET_SYSTEM_TRAY_S%d", screenNumber);
  212762. Atom selectionAtom = XInternAtom (display, screenAtom, false);
  212763. XGrabServer (display);
  212764. Window managerWin = XGetSelectionOwner (display, selectionAtom);
  212765. if (managerWin != None)
  212766. XSelectInput (display, managerWin, StructureNotifyMask);
  212767. XUngrabServer (display);
  212768. XFlush (display);
  212769. if (managerWin != None)
  212770. {
  212771. XEvent ev;
  212772. zerostruct (ev);
  212773. ev.xclient.type = ClientMessage;
  212774. ev.xclient.window = managerWin;
  212775. ev.xclient.message_type = XInternAtom (display, "_NET_SYSTEM_TRAY_OPCODE", False);
  212776. ev.xclient.format = 32;
  212777. ev.xclient.data.l[0] = CurrentTime;
  212778. ev.xclient.data.l[1] = SYSTEM_TRAY_REQUEST_DOCK;
  212779. ev.xclient.data.l[2] = windowH;
  212780. ev.xclient.data.l[3] = 0;
  212781. ev.xclient.data.l[4] = 0;
  212782. XSendEvent (display, managerWin, False, NoEventMask, &ev);
  212783. XSync (display, False);
  212784. }
  212785. // For older KDE's ...
  212786. long atomData = 1;
  212787. Atom trayAtom = XInternAtom (display, "KWM_DOCKWINDOW", false);
  212788. XChangeProperty (display, windowH, trayAtom, trayAtom, 32, PropModeReplace, (unsigned char*) &atomData, 1);
  212789. // For more recent KDE's...
  212790. trayAtom = XInternAtom (display, "_KDE_NET_WM_SYSTEM_TRAY_WINDOW_FOR", false);
  212791. XChangeProperty (display, windowH, trayAtom, XA_WINDOW, 32, PropModeReplace, (unsigned char*) &windowH, 1);
  212792. }
  212793. void deleteTaskBarIcon()
  212794. {
  212795. deleteAndZero (taskbarImage);
  212796. }
  212797. const Image* getTaskbarIcon() const throw() { return taskbarImage; }
  212798. juce_UseDebuggingNewOperator
  212799. bool dontRepaint;
  212800. private:
  212801. class LinuxRepaintManager : public Timer
  212802. {
  212803. public:
  212804. LinuxRepaintManager (LinuxComponentPeer* const peer_)
  212805. : peer (peer_),
  212806. image (0),
  212807. lastTimeImageUsed (0)
  212808. {
  212809. #if JUCE_USE_XSHM
  212810. useARGBImagesForRendering = isShmAvailable();
  212811. if (useARGBImagesForRendering)
  212812. {
  212813. XShmSegmentInfo segmentinfo;
  212814. XImage* const testImage
  212815. = XShmCreateImage (display, DefaultVisual (display, DefaultScreen (display)),
  212816. 24, ZPixmap, 0, &segmentinfo, 64, 64);
  212817. useARGBImagesForRendering = (testImage->bits_per_pixel == 32);
  212818. XDestroyImage (testImage);
  212819. }
  212820. #endif
  212821. }
  212822. ~LinuxRepaintManager()
  212823. {
  212824. delete image;
  212825. }
  212826. void timerCallback()
  212827. {
  212828. if (! regionsNeedingRepaint.isEmpty())
  212829. {
  212830. stopTimer();
  212831. performAnyPendingRepaintsNow();
  212832. }
  212833. else if (Time::getApproximateMillisecondCounter() > lastTimeImageUsed + 3000)
  212834. {
  212835. stopTimer();
  212836. deleteAndZero (image);
  212837. }
  212838. }
  212839. void repaint (int x, int y, int w, int h)
  212840. {
  212841. if (! isTimerRunning())
  212842. startTimer (repaintTimerPeriod);
  212843. regionsNeedingRepaint.add (x, y, w, h);
  212844. }
  212845. void performAnyPendingRepaintsNow()
  212846. {
  212847. peer->clearMaskedRegion();
  212848. const Rectangle totalArea (regionsNeedingRepaint.getBounds());
  212849. if (! totalArea.isEmpty())
  212850. {
  212851. if (image == 0 || image->getWidth() < totalArea.getWidth()
  212852. || image->getHeight() < totalArea.getHeight())
  212853. {
  212854. delete image;
  212855. #if JUCE_USE_XSHM
  212856. image = new XBitmapImage (useARGBImagesForRendering ? Image::ARGB
  212857. : Image::RGB,
  212858. #else
  212859. image = new XBitmapImage (Image::RGB,
  212860. #endif
  212861. (totalArea.getWidth() + 31) & ~31,
  212862. (totalArea.getHeight() + 31) & ~31,
  212863. false,
  212864. peer->depthIs16Bit);
  212865. }
  212866. startTimer (repaintTimerPeriod);
  212867. LowLevelGraphicsSoftwareRenderer context (*image);
  212868. context.setOrigin (-totalArea.getX(), -totalArea.getY());
  212869. if (context.reduceClipRegion (regionsNeedingRepaint))
  212870. peer->handlePaint (context);
  212871. if (! peer->maskedRegion.isEmpty())
  212872. regionsNeedingRepaint.subtract (peer->maskedRegion);
  212873. for (RectangleList::Iterator i (regionsNeedingRepaint); i.next();)
  212874. {
  212875. const Rectangle& r = *i.getRectangle();
  212876. image->blitToWindow (peer->windowH,
  212877. r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  212878. r.getX() - totalArea.getX(), r.getY() - totalArea.getY());
  212879. }
  212880. }
  212881. regionsNeedingRepaint.clear();
  212882. lastTimeImageUsed = Time::getApproximateMillisecondCounter();
  212883. startTimer (repaintTimerPeriod);
  212884. }
  212885. private:
  212886. LinuxComponentPeer* const peer;
  212887. XBitmapImage* image;
  212888. uint32 lastTimeImageUsed;
  212889. RectangleList regionsNeedingRepaint;
  212890. #if JUCE_USE_XSHM
  212891. bool useARGBImagesForRendering;
  212892. #endif
  212893. LinuxRepaintManager (const LinuxRepaintManager&);
  212894. const LinuxRepaintManager& operator= (const LinuxRepaintManager&);
  212895. };
  212896. LinuxRepaintManager* repainter;
  212897. friend class LinuxRepaintManager;
  212898. Window windowH, parentWindow;
  212899. int wx, wy, ww, wh;
  212900. Image* taskbarImage;
  212901. bool fullScreen, entered, mapped, depthIs16Bit;
  212902. BorderSize windowBorder;
  212903. void removeWindowDecorations (Window wndH)
  212904. {
  212905. Atom hints = XInternAtom (display, "_MOTIF_WM_HINTS", True);
  212906. if (hints != None)
  212907. {
  212908. typedef struct
  212909. {
  212910. unsigned long flags;
  212911. unsigned long functions;
  212912. unsigned long decorations;
  212913. long input_mode;
  212914. unsigned long status;
  212915. } MotifWmHints;
  212916. MotifWmHints motifHints;
  212917. zerostruct (motifHints);
  212918. motifHints.flags = 2; /* MWM_HINTS_DECORATIONS */
  212919. motifHints.decorations = 0;
  212920. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  212921. (unsigned char*) &motifHints, 4);
  212922. }
  212923. hints = XInternAtom (display, "_WIN_HINTS", True);
  212924. if (hints != None)
  212925. {
  212926. long gnomeHints = 0;
  212927. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  212928. (unsigned char*) &gnomeHints, 1);
  212929. }
  212930. hints = XInternAtom (display, "KWM_WIN_DECORATION", True);
  212931. if (hints != None)
  212932. {
  212933. long kwmHints = 2; /*KDE_tinyDecoration*/
  212934. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  212935. (unsigned char*) &kwmHints, 1);
  212936. }
  212937. hints = XInternAtom (display, "_NET_WM_WINDOW_TYPE", True);
  212938. if (hints != None)
  212939. {
  212940. long netHints [2];
  212941. netHints[0] = XInternAtom (display, "_KDE_NET_WM_WINDOW_TYPE_OVERRIDE", True);
  212942. if ((styleFlags & windowIsTemporary) != 0)
  212943. netHints[1] = XInternAtom (display, "_NET_WM_WINDOW_TYPE_MENU", True);
  212944. else
  212945. netHints[1] = XInternAtom (display, "_NET_WM_WINDOW_TYPE_NORMAL", True);
  212946. XChangeProperty (display, wndH, hints, XA_ATOM, 32, PropModeReplace,
  212947. (unsigned char*) &netHints, 2);
  212948. }
  212949. }
  212950. void addWindowButtons (Window wndH)
  212951. {
  212952. Atom hints = XInternAtom (display, "_MOTIF_WM_HINTS", True);
  212953. if (hints != None)
  212954. {
  212955. typedef struct
  212956. {
  212957. unsigned long flags;
  212958. unsigned long functions;
  212959. unsigned long decorations;
  212960. long input_mode;
  212961. unsigned long status;
  212962. } MotifWmHints;
  212963. MotifWmHints motifHints;
  212964. zerostruct (motifHints);
  212965. motifHints.flags = 1 | 2; /* MWM_HINTS_FUNCTIONS | MWM_HINTS_DECORATIONS */
  212966. motifHints.decorations = 2 /* MWM_DECOR_BORDER */ | 8 /* MWM_DECOR_TITLE */ | 16; /* MWM_DECOR_MENU */
  212967. motifHints.functions = 4 /* MWM_FUNC_MOVE */;
  212968. if ((styleFlags & windowHasCloseButton) != 0)
  212969. motifHints.functions |= 32; /* MWM_FUNC_CLOSE */
  212970. if ((styleFlags & windowHasMinimiseButton) != 0)
  212971. {
  212972. motifHints.functions |= 8; /* MWM_FUNC_MINIMIZE */
  212973. motifHints.decorations |= 0x20; /* MWM_DECOR_MINIMIZE */
  212974. }
  212975. if ((styleFlags & windowHasMaximiseButton) != 0)
  212976. {
  212977. motifHints.functions |= 0x10; /* MWM_FUNC_MAXIMIZE */
  212978. motifHints.decorations |= 0x40; /* MWM_DECOR_MAXIMIZE */
  212979. }
  212980. if ((styleFlags & windowIsResizable) != 0)
  212981. {
  212982. motifHints.functions |= 2; /* MWM_FUNC_RESIZE */
  212983. motifHints.decorations |= 0x4; /* MWM_DECOR_RESIZEH */
  212984. }
  212985. XChangeProperty (display, wndH, hints, hints, 32, 0, (unsigned char*) &motifHints, 5);
  212986. }
  212987. hints = XInternAtom (display, "_NET_WM_ALLOWED_ACTIONS", True);
  212988. if (hints != None)
  212989. {
  212990. long netHints [6];
  212991. int num = 0;
  212992. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_RESIZE", (styleFlags & windowIsResizable) ? True : False);
  212993. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_FULLSCREEN", (styleFlags & windowHasMaximiseButton) ? True : False);
  212994. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_MINIMIZE", (styleFlags & windowHasMinimiseButton) ? True : False);
  212995. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_CLOSE", (styleFlags & windowHasCloseButton) ? True : False);
  212996. XChangeProperty (display, wndH, hints, XA_ATOM, 32, PropModeReplace,
  212997. (unsigned char*) &netHints, num);
  212998. }
  212999. }
  213000. void createWindow()
  213001. {
  213002. static bool atomsInitialised = false;
  213003. if (! atomsInitialised)
  213004. {
  213005. atomsInitialised = true;
  213006. wm_Protocols = XInternAtom (display, "WM_PROTOCOLS", 1);
  213007. wm_ProtocolList [TAKE_FOCUS] = XInternAtom (display, "WM_TAKE_FOCUS", 1);
  213008. wm_ProtocolList [DELETE_WINDOW] = XInternAtom (display, "WM_DELETE_WINDOW", 1);
  213009. wm_ChangeState = XInternAtom (display, "WM_CHANGE_STATE", 1);
  213010. wm_State = XInternAtom (display, "WM_STATE", 1);
  213011. wm_ActiveWin = XInternAtom (display, "_NET_ACTIVE_WINDOW", False);
  213012. XA_XdndAware = XInternAtom (display, "XdndAware", 0);
  213013. XA_XdndEnter = XInternAtom (display, "XdndEnter", 0);
  213014. XA_XdndLeave = XInternAtom (display, "XdndLeave", 0);
  213015. XA_XdndPosition = XInternAtom (display, "XdndPosition", 0);
  213016. XA_XdndStatus = XInternAtom (display, "XdndStatus", 0);
  213017. XA_XdndDrop = XInternAtom (display, "XdndDrop", 0);
  213018. XA_XdndFinished = XInternAtom (display, "XdndFinished", 0);
  213019. XA_XdndSelection = XInternAtom (display, "XdndSelection", 0);
  213020. XA_XdndProxy = XInternAtom (display, "XdndProxy", 0);
  213021. XA_XdndTypeList = XInternAtom (display, "XdndTypeList", 0);
  213022. XA_XdndActionList = XInternAtom (display, "XdndActionList", 0);
  213023. XA_XdndActionCopy = XInternAtom (display, "XdndActionCopy", 0);
  213024. XA_XdndActionMove = XInternAtom (display, "XdndActionMove", 0);
  213025. XA_XdndActionLink = XInternAtom (display, "XdndActionLink", 0);
  213026. XA_XdndActionAsk = XInternAtom (display, "XdndActionAsk", 0);
  213027. XA_XdndActionPrivate = XInternAtom (display, "XdndActionPrivate", 0);
  213028. XA_XdndActionDescription = XInternAtom (display, "XdndActionDescription", 0);
  213029. XA_JXSelectionWindowProperty = XInternAtom (display, "JXSelectionWindowProperty", 0);
  213030. XA_MimeTextPlain = XInternAtom (display, "text/plain", 0);
  213031. XA_MimeTextUriList = XInternAtom (display, "text/uri-list", 0);
  213032. XA_MimeRootDrop = XInternAtom (display, "application/x-rootwindow-drop", 0);
  213033. }
  213034. resetDragAndDrop();
  213035. XA_OtherMime = XA_MimeTextPlain; // xxx why??
  213036. allowedMimeTypeAtoms [0] = XA_MimeTextPlain;
  213037. allowedMimeTypeAtoms [1] = XA_OtherMime;
  213038. allowedMimeTypeAtoms [2] = XA_MimeTextUriList;
  213039. allowedActions [0] = XA_XdndActionMove;
  213040. allowedActions [1] = XA_XdndActionCopy;
  213041. allowedActions [2] = XA_XdndActionLink;
  213042. allowedActions [3] = XA_XdndActionAsk;
  213043. allowedActions [4] = XA_XdndActionPrivate;
  213044. // Get defaults for various properties
  213045. const int screen = DefaultScreen (display);
  213046. Window root = RootWindow (display, screen);
  213047. // Attempt to create a 24-bit window on the default screen. If this is not
  213048. // possible then exit
  213049. XVisualInfo desiredVisual;
  213050. desiredVisual.screen = screen;
  213051. desiredVisual.depth = 24;
  213052. depthIs16Bit = false;
  213053. int numVisuals;
  213054. XVisualInfo* visuals = XGetVisualInfo (display, VisualScreenMask | VisualDepthMask,
  213055. &desiredVisual, &numVisuals);
  213056. if (numVisuals < 1 || visuals == 0)
  213057. {
  213058. XFree (visuals);
  213059. desiredVisual.depth = 16;
  213060. visuals = XGetVisualInfo (display, VisualScreenMask | VisualDepthMask,
  213061. &desiredVisual, &numVisuals);
  213062. if (numVisuals < 1 || visuals == 0)
  213063. {
  213064. Logger::outputDebugString ("ERROR: System doesn't support 24 or 16 bit RGB display.\n");
  213065. Process::terminate();
  213066. }
  213067. depthIs16Bit = true;
  213068. }
  213069. XFree (visuals);
  213070. // Set up the window attributes
  213071. XSetWindowAttributes swa;
  213072. swa.border_pixel = 0;
  213073. swa.background_pixmap = None;
  213074. swa.colormap = DefaultColormap (display, screen);
  213075. swa.override_redirect = getComponent()->isAlwaysOnTop() ? True : False;
  213076. swa.event_mask = eventMask;
  213077. Window wndH = XCreateWindow (display, root,
  213078. 0, 0, 1, 1,
  213079. 0, 0, InputOutput, (Visual*) CopyFromParent,
  213080. CWBorderPixel | CWColormap | CWBackPixmap | CWEventMask | CWOverrideRedirect,
  213081. &swa);
  213082. XGrabButton (display, AnyButton, AnyModifier, wndH, False,
  213083. ButtonPressMask | ButtonReleaseMask | EnterWindowMask | LeaveWindowMask | PointerMotionMask,
  213084. GrabModeAsync, GrabModeAsync, None, None);
  213085. // Set the window context to identify the window handle object
  213086. if (XSaveContext (display, (XID) wndH, improbableNumber, (XPointer) this))
  213087. {
  213088. // Failed
  213089. jassertfalse
  213090. Logger::outputDebugString ("Failed to create context information for window.\n");
  213091. XDestroyWindow (display, wndH);
  213092. wndH = 0;
  213093. }
  213094. // Set window manager hints
  213095. XWMHints* wmHints = XAllocWMHints();
  213096. wmHints->flags = InputHint | StateHint;
  213097. wmHints->input = True; // Locally active input model
  213098. wmHints->initial_state = NormalState;
  213099. XSetWMHints (display, wndH, wmHints);
  213100. XFree (wmHints);
  213101. if ((styleFlags & windowIsSemiTransparent) != 0)
  213102. {
  213103. //xxx
  213104. }
  213105. if ((styleFlags & windowAppearsOnTaskbar) != 0)
  213106. {
  213107. //xxx
  213108. }
  213109. //XSetTransientForHint (display, wndH, RootWindow (display, DefaultScreen (display)));
  213110. if ((styleFlags & windowHasTitleBar) == 0)
  213111. removeWindowDecorations (wndH);
  213112. else
  213113. addWindowButtons (wndH);
  213114. // Set window manager protocols
  213115. XChangeProperty (display, wndH, wm_Protocols, XA_ATOM, 32, PropModeReplace,
  213116. (unsigned char*) wm_ProtocolList, 2);
  213117. // Set drag and drop flags
  213118. XChangeProperty (display, wndH, XA_XdndTypeList, XA_ATOM, 32, PropModeReplace,
  213119. (const unsigned char*) allowedMimeTypeAtoms, numElementsInArray (allowedMimeTypeAtoms));
  213120. XChangeProperty (display, wndH, XA_XdndActionList, XA_ATOM, 32, PropModeReplace,
  213121. (const unsigned char*) allowedActions, numElementsInArray (allowedActions));
  213122. XChangeProperty (display, wndH, XA_XdndActionDescription, XA_STRING, 8, PropModeReplace,
  213123. (const unsigned char*) "", 0);
  213124. unsigned long dndVersion = ourDndVersion;
  213125. XChangeProperty (display, wndH, XA_XdndAware, XA_ATOM, 32, PropModeReplace,
  213126. (const unsigned char*) &dndVersion, 1);
  213127. // Set window name
  213128. setWindowTitle (wndH, getComponent()->getName());
  213129. // Initialise the pointer and keyboard mapping
  213130. // This is not the same as the logical pointer mapping the X server uses:
  213131. // we don't mess with this.
  213132. static bool mappingInitialised = false;
  213133. if (! mappingInitialised)
  213134. {
  213135. mappingInitialised = true;
  213136. const int numButtons = XGetPointerMapping (display, 0, 0);
  213137. if (numButtons == 2)
  213138. {
  213139. pointerMap[0] = LeftButton;
  213140. pointerMap[1] = RightButton;
  213141. pointerMap[2] = pointerMap[3] = pointerMap[4] = NoButton;
  213142. }
  213143. else if (numButtons >= 3)
  213144. {
  213145. pointerMap[0] = LeftButton;
  213146. pointerMap[1] = MiddleButton;
  213147. pointerMap[2] = RightButton;
  213148. if (numButtons >= 5)
  213149. {
  213150. pointerMap[3] = WheelUp;
  213151. pointerMap[4] = WheelDown;
  213152. }
  213153. }
  213154. getModifierMapping();
  213155. }
  213156. windowH = wndH;
  213157. }
  213158. void destroyWindow()
  213159. {
  213160. XPointer handlePointer;
  213161. if (! XFindContext (display, (XID) windowH, improbableNumber, &handlePointer))
  213162. XDeleteContext (display, (XID) windowH, improbableNumber);
  213163. XDestroyWindow (display, windowH);
  213164. // Wait for it to complete and then remove any events for this
  213165. // window from the event queue.
  213166. XSync (display, false);
  213167. XEvent event;
  213168. while (XCheckWindowEvent (display, windowH, eventMask, &event) == True)
  213169. {}
  213170. }
  213171. static int64 getEventTime (::Time t) throw()
  213172. {
  213173. static int64 eventTimeOffset = 0x12345678;
  213174. const int64 thisMessageTime = t;
  213175. if (eventTimeOffset == 0x12345678)
  213176. eventTimeOffset = Time::currentTimeMillis() - thisMessageTime;
  213177. return eventTimeOffset + thisMessageTime;
  213178. }
  213179. static void setWindowTitle (Window xwin, const char* const title) throw()
  213180. {
  213181. XTextProperty nameProperty;
  213182. char* strings[] = { (char*) title };
  213183. if (XStringListToTextProperty (strings, 1, &nameProperty))
  213184. {
  213185. XSetWMName (display, xwin, &nameProperty);
  213186. XSetWMIconName (display, xwin, &nameProperty);
  213187. XFree (nameProperty.value);
  213188. }
  213189. }
  213190. void updateBorderSize()
  213191. {
  213192. if ((styleFlags & windowHasTitleBar) == 0)
  213193. {
  213194. windowBorder = BorderSize (0);
  213195. }
  213196. else if (windowBorder.getTopAndBottom() == 0 && windowBorder.getLeftAndRight() == 0)
  213197. {
  213198. Atom hints = XInternAtom (display, "_NET_FRAME_EXTENTS", True);
  213199. if (hints != None)
  213200. {
  213201. unsigned char* data = 0;
  213202. unsigned long nitems, bytesLeft;
  213203. Atom actualType;
  213204. int actualFormat;
  213205. if (XGetWindowProperty (display, windowH, hints, 0, 4, False,
  213206. XA_CARDINAL, &actualType, &actualFormat, &nitems, &bytesLeft,
  213207. &data) == Success)
  213208. {
  213209. const unsigned long* const sizes = (const unsigned long*) data;
  213210. if (actualFormat == 32)
  213211. windowBorder = BorderSize ((int) sizes[2], (int) sizes[0],
  213212. (int) sizes[3], (int) sizes[1]);
  213213. XFree (data);
  213214. }
  213215. }
  213216. }
  213217. }
  213218. void updateBounds()
  213219. {
  213220. jassert (windowH != 0);
  213221. if (windowH != 0)
  213222. {
  213223. Window root, child;
  213224. unsigned int bw, depth;
  213225. if (! XGetGeometry (display, (::Drawable) windowH, &root,
  213226. &wx, &wy, (unsigned int*) &ww, (unsigned int*) &wh,
  213227. &bw, &depth))
  213228. {
  213229. wx = wy = ww = wh = 0;
  213230. }
  213231. else if (! XTranslateCoordinates (display, windowH, root, 0, 0, &wx, &wy, &child))
  213232. {
  213233. wx = wy = 0;
  213234. }
  213235. }
  213236. }
  213237. void resetDragAndDrop()
  213238. {
  213239. dragAndDropFiles.clear();
  213240. lastDropX = lastDropY = -1;
  213241. dragAndDropCurrentMimeType = 0;
  213242. dragAndDropSourceWindow = 0;
  213243. srcMimeTypeAtomList.clear();
  213244. }
  213245. void sendDragAndDropMessage (XClientMessageEvent& msg)
  213246. {
  213247. msg.type = ClientMessage;
  213248. msg.display = display;
  213249. msg.window = dragAndDropSourceWindow;
  213250. msg.format = 32;
  213251. msg.data.l[0] = windowH;
  213252. XSendEvent (display, dragAndDropSourceWindow, False, 0, (XEvent*) &msg);
  213253. }
  213254. void sendDragAndDropStatus (const bool acceptDrop, Atom dropAction)
  213255. {
  213256. XClientMessageEvent msg;
  213257. zerostruct (msg);
  213258. msg.message_type = XA_XdndStatus;
  213259. msg.data.l[1] = (acceptDrop ? 1 : 0) | 2; // 2 indicates that we want to receive position messages
  213260. msg.data.l[4] = dropAction;
  213261. sendDragAndDropMessage (msg);
  213262. }
  213263. void sendDragAndDropLeave()
  213264. {
  213265. XClientMessageEvent msg;
  213266. zerostruct (msg);
  213267. msg.message_type = XA_XdndLeave;
  213268. sendDragAndDropMessage (msg);
  213269. }
  213270. void sendDragAndDropFinish()
  213271. {
  213272. XClientMessageEvent msg;
  213273. zerostruct (msg);
  213274. msg.message_type = XA_XdndFinished;
  213275. sendDragAndDropMessage (msg);
  213276. }
  213277. void handleDragAndDropStatus (const XClientMessageEvent* const clientMsg)
  213278. {
  213279. if ((clientMsg->data.l[1] & 1) == 0)
  213280. {
  213281. sendDragAndDropLeave();
  213282. if (dragAndDropFiles.size() > 0)
  213283. handleFileDragExit (dragAndDropFiles);
  213284. dragAndDropFiles.clear();
  213285. }
  213286. }
  213287. void handleDragAndDropPosition (const XClientMessageEvent* const clientMsg)
  213288. {
  213289. if (dragAndDropSourceWindow == 0)
  213290. return;
  213291. dragAndDropSourceWindow = clientMsg->data.l[0];
  213292. const int dropX = ((int) clientMsg->data.l[2] >> 16) - getScreenX();
  213293. const int dropY = ((int) clientMsg->data.l[2] & 0xffff) - getScreenY();
  213294. if (lastDropX != dropX || lastDropY != dropY)
  213295. {
  213296. lastDropX = dropX;
  213297. lastDropY = dropY;
  213298. dragAndDropTimestamp = clientMsg->data.l[3];
  213299. Atom targetAction = XA_XdndActionCopy;
  213300. for (int i = numElementsInArray (allowedActions); --i >= 0;)
  213301. {
  213302. if ((Atom) clientMsg->data.l[4] == allowedActions[i])
  213303. {
  213304. targetAction = allowedActions[i];
  213305. break;
  213306. }
  213307. }
  213308. sendDragAndDropStatus (true, targetAction);
  213309. if (dragAndDropFiles.size() == 0)
  213310. updateDraggedFileList (clientMsg);
  213311. if (dragAndDropFiles.size() > 0)
  213312. handleFileDragMove (dragAndDropFiles, dropX, dropY);
  213313. }
  213314. }
  213315. void handleDragAndDropDrop (const XClientMessageEvent* const clientMsg)
  213316. {
  213317. if (dragAndDropFiles.size() == 0)
  213318. updateDraggedFileList (clientMsg);
  213319. const StringArray files (dragAndDropFiles);
  213320. const int lastX = lastDropX, lastY = lastDropY;
  213321. sendDragAndDropFinish();
  213322. resetDragAndDrop();
  213323. if (files.size() > 0)
  213324. handleFileDragDrop (files, lastX, lastY);
  213325. }
  213326. void handleDragAndDropEnter (const XClientMessageEvent* const clientMsg)
  213327. {
  213328. dragAndDropFiles.clear();
  213329. srcMimeTypeAtomList.clear();
  213330. dragAndDropCurrentMimeType = 0;
  213331. const int dndCurrentVersion = (int) (clientMsg->data.l[1] & 0xff000000) >> 24;
  213332. if (dndCurrentVersion < 3 || dndCurrentVersion > ourDndVersion)
  213333. {
  213334. dragAndDropSourceWindow = 0;
  213335. return;
  213336. }
  213337. dragAndDropSourceWindow = clientMsg->data.l[0];
  213338. if ((clientMsg->data.l[1] & 1) != 0)
  213339. {
  213340. Atom actual;
  213341. int format;
  213342. unsigned long count = 0, remaining = 0;
  213343. unsigned char* data = 0;
  213344. XGetWindowProperty (display, dragAndDropSourceWindow, XA_XdndTypeList,
  213345. 0, 0x8000000L, False, XA_ATOM, &actual, &format,
  213346. &count, &remaining, &data);
  213347. if (data != 0)
  213348. {
  213349. if (actual == XA_ATOM && format == 32 && count != 0)
  213350. {
  213351. const unsigned long* const types = (const unsigned long*) data;
  213352. for (unsigned int i = 0; i < count; ++i)
  213353. if (types[i] != None)
  213354. srcMimeTypeAtomList.add (types[i]);
  213355. }
  213356. XFree (data);
  213357. }
  213358. }
  213359. if (srcMimeTypeAtomList.size() == 0)
  213360. {
  213361. for (int i = 2; i < 5; ++i)
  213362. if (clientMsg->data.l[i] != None)
  213363. srcMimeTypeAtomList.add (clientMsg->data.l[i]);
  213364. if (srcMimeTypeAtomList.size() == 0)
  213365. {
  213366. dragAndDropSourceWindow = 0;
  213367. return;
  213368. }
  213369. }
  213370. for (int i = 0; i < srcMimeTypeAtomList.size() && dragAndDropCurrentMimeType == 0; ++i)
  213371. for (int j = 0; j < numElementsInArray (allowedMimeTypeAtoms); ++j)
  213372. if (srcMimeTypeAtomList[i] == allowedMimeTypeAtoms[j])
  213373. dragAndDropCurrentMimeType = allowedMimeTypeAtoms[j];
  213374. handleDragAndDropPosition (clientMsg);
  213375. }
  213376. void handleDragAndDropSelection (const XEvent* const evt)
  213377. {
  213378. dragAndDropFiles.clear();
  213379. if (evt->xselection.property != 0)
  213380. {
  213381. StringArray lines;
  213382. {
  213383. MemoryBlock dropData;
  213384. for (;;)
  213385. {
  213386. Atom actual;
  213387. uint8* data = 0;
  213388. unsigned long count = 0, remaining = 0;
  213389. int format = 0;
  213390. if (XGetWindowProperty (display, evt->xany.window, evt->xselection.property,
  213391. dropData.getSize() / 4, 65536, 1, AnyPropertyType, &actual,
  213392. &format, &count, &remaining, &data) == Success)
  213393. {
  213394. dropData.append (data, count * format / 8);
  213395. XFree (data);
  213396. if (remaining == 0)
  213397. break;
  213398. }
  213399. else
  213400. {
  213401. XFree (data);
  213402. break;
  213403. }
  213404. }
  213405. lines.addLines (dropData.toString());
  213406. }
  213407. for (int i = 0; i < lines.size(); ++i)
  213408. dragAndDropFiles.add (URL::removeEscapeChars (lines[i].fromFirstOccurrenceOf (T("file://"), false, true)));
  213409. dragAndDropFiles.trim();
  213410. dragAndDropFiles.removeEmptyStrings();
  213411. }
  213412. }
  213413. void updateDraggedFileList (const XClientMessageEvent* const clientMsg)
  213414. {
  213415. dragAndDropFiles.clear();
  213416. if (dragAndDropSourceWindow != None
  213417. && dragAndDropCurrentMimeType != 0)
  213418. {
  213419. dragAndDropTimestamp = clientMsg->data.l[2];
  213420. XConvertSelection (display,
  213421. XA_XdndSelection,
  213422. dragAndDropCurrentMimeType,
  213423. XA_JXSelectionWindowProperty,
  213424. windowH,
  213425. dragAndDropTimestamp);
  213426. }
  213427. }
  213428. StringArray dragAndDropFiles;
  213429. int dragAndDropTimestamp, lastDropX, lastDropY;
  213430. Atom XA_OtherMime, dragAndDropCurrentMimeType;
  213431. Window dragAndDropSourceWindow;
  213432. unsigned long allowedActions [5];
  213433. unsigned long allowedMimeTypeAtoms [3];
  213434. Array <Atom> srcMimeTypeAtomList;
  213435. };
  213436. ComponentPeer* Component::createNewPeer (int styleFlags, void* /*nativeWindowToAttachTo*/)
  213437. {
  213438. return new LinuxComponentPeer (this, styleFlags);
  213439. }
  213440. // (this callback is hooked up in the messaging code)
  213441. void juce_windowMessageReceive (XEvent* event)
  213442. {
  213443. if (event->xany.window != None)
  213444. {
  213445. LinuxComponentPeer* const peer = LinuxComponentPeer::getPeerFor (event->xany.window);
  213446. const MessageManagerLock messLock;
  213447. if (ComponentPeer::isValidPeer (peer))
  213448. peer->handleWindowMessage (event);
  213449. }
  213450. else
  213451. {
  213452. switch (event->xany.type)
  213453. {
  213454. case KeymapNotify:
  213455. {
  213456. const XKeymapEvent* const keymapEvent = (const XKeymapEvent*) &event->xkeymap;
  213457. memcpy (keyStates, keymapEvent->key_vector, 32);
  213458. break;
  213459. }
  213460. default:
  213461. break;
  213462. }
  213463. }
  213464. }
  213465. void juce_updateMultiMonitorInfo (Array <Rectangle>& monitorCoords, const bool /*clipToWorkArea*/) throw()
  213466. {
  213467. #if JUCE_USE_XINERAMA
  213468. int major_opcode, first_event, first_error;
  213469. if (XQueryExtension (display, "XINERAMA", &major_opcode, &first_event, &first_error)
  213470. && XineramaIsActive (display))
  213471. {
  213472. int numMonitors = 0;
  213473. XineramaScreenInfo* const screens = XineramaQueryScreens (display, &numMonitors);
  213474. if (screens != 0)
  213475. {
  213476. for (int i = numMonitors; --i >= 0;)
  213477. {
  213478. int index = screens[i].screen_number;
  213479. if (index >= 0)
  213480. {
  213481. while (monitorCoords.size() < index)
  213482. monitorCoords.add (Rectangle (0, 0, 0, 0));
  213483. monitorCoords.set (index, Rectangle (screens[i].x_org,
  213484. screens[i].y_org,
  213485. screens[i].width,
  213486. screens[i].height));
  213487. }
  213488. }
  213489. XFree (screens);
  213490. }
  213491. }
  213492. if (monitorCoords.size() == 0)
  213493. #endif
  213494. {
  213495. Atom hints = XInternAtom (display, "_NET_WORKAREA", True);
  213496. if (hints != None)
  213497. {
  213498. const int numMonitors = ScreenCount (display);
  213499. for (int i = 0; i < numMonitors; ++i)
  213500. {
  213501. Window root = RootWindow (display, i);
  213502. unsigned long nitems, bytesLeft;
  213503. Atom actualType;
  213504. int actualFormat;
  213505. unsigned char* data = 0;
  213506. if (XGetWindowProperty (display, root, hints, 0, 4, False,
  213507. XA_CARDINAL, &actualType, &actualFormat, &nitems, &bytesLeft,
  213508. &data) == Success)
  213509. {
  213510. const long* const position = (const long*) data;
  213511. if (actualType == XA_CARDINAL && actualFormat == 32 && nitems == 4)
  213512. monitorCoords.add (Rectangle (position[0], position[1],
  213513. position[2], position[3]));
  213514. XFree (data);
  213515. }
  213516. }
  213517. }
  213518. if (monitorCoords.size() == 0)
  213519. {
  213520. monitorCoords.add (Rectangle (0, 0,
  213521. DisplayWidth (display, DefaultScreen (display)),
  213522. DisplayHeight (display, DefaultScreen (display))));
  213523. }
  213524. }
  213525. }
  213526. bool Desktop::canUseSemiTransparentWindows() throw()
  213527. {
  213528. return false;
  213529. }
  213530. void Desktop::getMousePosition (int& x, int& y) throw()
  213531. {
  213532. int mouseMods;
  213533. getMousePos (x, y, mouseMods);
  213534. }
  213535. void Desktop::setMousePosition (int x, int y) throw()
  213536. {
  213537. Window root = RootWindow (display, DefaultScreen (display));
  213538. XWarpPointer (display, None, root, 0, 0, 0, 0, x, y);
  213539. }
  213540. static bool screenSaverAllowed = true;
  213541. void Desktop::setScreenSaverEnabled (const bool isEnabled) throw()
  213542. {
  213543. if (screenSaverAllowed != isEnabled)
  213544. {
  213545. screenSaverAllowed = isEnabled;
  213546. typedef void (*tXScreenSaverSuspend) (Display*, Bool);
  213547. static tXScreenSaverSuspend xScreenSaverSuspend = 0;
  213548. if (xScreenSaverSuspend == 0)
  213549. {
  213550. void* h = dlopen ("libXss.so", RTLD_GLOBAL | RTLD_NOW);
  213551. if (h != 0)
  213552. xScreenSaverSuspend = (tXScreenSaverSuspend) dlsym (h, "XScreenSaverSuspend");
  213553. }
  213554. if (xScreenSaverSuspend != 0)
  213555. xScreenSaverSuspend (display, ! isEnabled);
  213556. }
  213557. }
  213558. bool Desktop::isScreenSaverEnabled() throw()
  213559. {
  213560. return screenSaverAllowed;
  213561. }
  213562. void* juce_createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) throw()
  213563. {
  213564. Window root = RootWindow (display, DefaultScreen (display));
  213565. const unsigned int imageW = image.getWidth();
  213566. const unsigned int imageH = image.getHeight();
  213567. unsigned int cursorW, cursorH;
  213568. if (! XQueryBestCursor (display, root, imageW, imageH, &cursorW, &cursorH))
  213569. return 0;
  213570. Image im (Image::ARGB, cursorW, cursorH, true);
  213571. Graphics g (im);
  213572. if (imageW > cursorW || imageH > cursorH)
  213573. {
  213574. hotspotX = (hotspotX * cursorW) / imageW;
  213575. hotspotY = (hotspotY * cursorH) / imageH;
  213576. g.drawImageWithin (&image, 0, 0, imageW, imageH,
  213577. RectanglePlacement::xLeft | RectanglePlacement::yTop | RectanglePlacement::onlyReduceInSize,
  213578. false);
  213579. }
  213580. else
  213581. {
  213582. g.drawImageAt (&image, 0, 0);
  213583. }
  213584. const int stride = (cursorW + 7) >> 3;
  213585. uint8* const maskPlane = (uint8*) juce_calloc (stride * cursorH);
  213586. uint8* const sourcePlane = (uint8*) juce_calloc (stride * cursorH);
  213587. bool msbfirst = (BitmapBitOrder (display) == MSBFirst);
  213588. for (int y = cursorH; --y >= 0;)
  213589. {
  213590. for (int x = cursorW; --x >= 0;)
  213591. {
  213592. const uint8 mask = (uint8) (1 << (msbfirst ? (7 - (x & 7)) : (x & 7)));
  213593. const int offset = y * stride + (x >> 3);
  213594. const Colour c (im.getPixelAt (x, y));
  213595. if (c.getAlpha() >= 128)
  213596. maskPlane[offset] |= mask;
  213597. if (c.getBrightness() >= 0.5f)
  213598. sourcePlane[offset] |= mask;
  213599. }
  213600. }
  213601. Pixmap sourcePixmap = XCreatePixmapFromBitmapData (display, root, (char*) sourcePlane, cursorW, cursorH, 0xffff, 0, 1);
  213602. Pixmap maskPixmap = XCreatePixmapFromBitmapData (display, root, (char*) maskPlane, cursorW, cursorH, 0xffff, 0, 1);
  213603. juce_free (maskPlane);
  213604. juce_free (sourcePlane);
  213605. XColor white, black;
  213606. black.red = black.green = black.blue = 0;
  213607. white.red = white.green = white.blue = 0xffff;
  213608. void* result = (void*) XCreatePixmapCursor (display, sourcePixmap, maskPixmap, &white, &black, hotspotX, hotspotY);
  213609. XFreePixmap (display, sourcePixmap);
  213610. XFreePixmap (display, maskPixmap);
  213611. return result;
  213612. }
  213613. void juce_deleteMouseCursor (void* const cursorHandle, const bool) throw()
  213614. {
  213615. if (cursorHandle != None)
  213616. XFreeCursor (display, (Cursor) cursorHandle);
  213617. }
  213618. void* juce_createStandardMouseCursor (MouseCursor::StandardCursorType type) throw()
  213619. {
  213620. unsigned int shape;
  213621. switch (type)
  213622. {
  213623. case MouseCursor::NoCursor:
  213624. {
  213625. const Image im (Image::ARGB, 16, 16, true);
  213626. return juce_createMouseCursorFromImage (im, 0, 0);
  213627. }
  213628. case MouseCursor::NormalCursor:
  213629. return (void*) None; // Use parent cursor
  213630. case MouseCursor::DraggingHandCursor:
  213631. {
  213632. static unsigned char dragHandData[] = {71,73,70,56,57,97,16,0,16,0,145,2,0,0,0,0,255,255,255,0,
  213633. 0,0,0,0,0,33,249,4,1,0,0,2,0,44,0,0,0,0,16,0,
  213634. 16,0,0,2,52,148,47,0,200,185,16,130,90,12,74,139,107,84,123,39,
  213635. 132,117,151,116,132,146,248,60,209,138,98,22,203,114,34,236,37,52,77,217,
  213636. 247,154,191,119,110,240,193,128,193,95,163,56,60,234,98,135,2,0,59 };
  213637. const int dragHandDataSize = 99;
  213638. Image* const im = ImageFileFormat::loadFrom ((const char*) dragHandData, dragHandDataSize);
  213639. void* const dragHandCursor = juce_createMouseCursorFromImage (*im, 8, 7);
  213640. delete im;
  213641. return dragHandCursor;
  213642. }
  213643. case MouseCursor::CopyingCursor:
  213644. {
  213645. static unsigned char copyCursorData[] = {71,73,70,56,57,97,21,0,21,0,145,0,0,0,0,0,255,255,255,0,
  213646. 128,128,255,255,255,33,249,4,1,0,0,3,0,44,0,0,0,0,21,0,
  213647. 21,0,0,2,72,4,134,169,171,16,199,98,11,79,90,71,161,93,56,111,
  213648. 78,133,218,215,137,31,82,154,100,200,86,91,202,142,12,108,212,87,235,174,
  213649. 15,54,214,126,237,226,37,96,59,141,16,37,18,201,142,157,230,204,51,112,
  213650. 252,114,147,74,83,5,50,68,147,208,217,16,71,149,252,124,5,0,59,0,0 };
  213651. const int copyCursorSize = 119;
  213652. Image* const im = ImageFileFormat::loadFrom ((const char*) copyCursorData, copyCursorSize);
  213653. void* const copyCursor = juce_createMouseCursorFromImage (*im, 1, 3);
  213654. delete im;
  213655. return copyCursor;
  213656. }
  213657. case MouseCursor::WaitCursor:
  213658. shape = XC_watch;
  213659. break;
  213660. case MouseCursor::IBeamCursor:
  213661. shape = XC_xterm;
  213662. break;
  213663. case MouseCursor::PointingHandCursor:
  213664. shape = XC_hand2;
  213665. break;
  213666. case MouseCursor::LeftRightResizeCursor:
  213667. shape = XC_sb_h_double_arrow;
  213668. break;
  213669. case MouseCursor::UpDownResizeCursor:
  213670. shape = XC_sb_v_double_arrow;
  213671. break;
  213672. case MouseCursor::UpDownLeftRightResizeCursor:
  213673. shape = XC_fleur;
  213674. break;
  213675. case MouseCursor::TopEdgeResizeCursor:
  213676. shape = XC_top_side;
  213677. break;
  213678. case MouseCursor::BottomEdgeResizeCursor:
  213679. shape = XC_bottom_side;
  213680. break;
  213681. case MouseCursor::LeftEdgeResizeCursor:
  213682. shape = XC_left_side;
  213683. break;
  213684. case MouseCursor::RightEdgeResizeCursor:
  213685. shape = XC_right_side;
  213686. break;
  213687. case MouseCursor::TopLeftCornerResizeCursor:
  213688. shape = XC_top_left_corner;
  213689. break;
  213690. case MouseCursor::TopRightCornerResizeCursor:
  213691. shape = XC_top_right_corner;
  213692. break;
  213693. case MouseCursor::BottomLeftCornerResizeCursor:
  213694. shape = XC_bottom_left_corner;
  213695. break;
  213696. case MouseCursor::BottomRightCornerResizeCursor:
  213697. shape = XC_bottom_right_corner;
  213698. break;
  213699. case MouseCursor::CrosshairCursor:
  213700. shape = XC_crosshair;
  213701. break;
  213702. default:
  213703. return (void*) None; // Use parent cursor
  213704. }
  213705. return (void*) XCreateFontCursor (display, shape);
  213706. }
  213707. void MouseCursor::showInWindow (ComponentPeer* peer) const throw()
  213708. {
  213709. LinuxComponentPeer* const lp = dynamic_cast <LinuxComponentPeer*> (peer);
  213710. if (lp != 0)
  213711. lp->showMouseCursor ((Cursor) getHandle());
  213712. }
  213713. void MouseCursor::showInAllWindows() const throw()
  213714. {
  213715. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  213716. showInWindow (ComponentPeer::getPeer (i));
  213717. }
  213718. Image* juce_createIconForFile (const File& file)
  213719. {
  213720. return 0;
  213721. }
  213722. #if JUCE_OPENGL
  213723. class WindowedGLContext : public OpenGLContext
  213724. {
  213725. public:
  213726. WindowedGLContext (Component* const component,
  213727. const OpenGLPixelFormat& pixelFormat_,
  213728. GLXContext sharedContext)
  213729. : renderContext (0),
  213730. embeddedWindow (0),
  213731. pixelFormat (pixelFormat_)
  213732. {
  213733. jassert (component != 0);
  213734. LinuxComponentPeer* const peer = dynamic_cast <LinuxComponentPeer*> (component->getTopLevelComponent()->getPeer());
  213735. if (peer == 0)
  213736. return;
  213737. XSync (display, False);
  213738. GLint attribs [64];
  213739. int n = 0;
  213740. attribs[n++] = GLX_RGBA;
  213741. attribs[n++] = GLX_DOUBLEBUFFER;
  213742. attribs[n++] = GLX_RED_SIZE;
  213743. attribs[n++] = pixelFormat.redBits;
  213744. attribs[n++] = GLX_GREEN_SIZE;
  213745. attribs[n++] = pixelFormat.greenBits;
  213746. attribs[n++] = GLX_BLUE_SIZE;
  213747. attribs[n++] = pixelFormat.blueBits;
  213748. attribs[n++] = GLX_ALPHA_SIZE;
  213749. attribs[n++] = pixelFormat.alphaBits;
  213750. attribs[n++] = GLX_DEPTH_SIZE;
  213751. attribs[n++] = pixelFormat.depthBufferBits;
  213752. attribs[n++] = GLX_STENCIL_SIZE;
  213753. attribs[n++] = pixelFormat.stencilBufferBits;
  213754. attribs[n++] = GLX_ACCUM_RED_SIZE;
  213755. attribs[n++] = pixelFormat.accumulationBufferRedBits;
  213756. attribs[n++] = GLX_ACCUM_GREEN_SIZE;
  213757. attribs[n++] = pixelFormat.accumulationBufferGreenBits;
  213758. attribs[n++] = GLX_ACCUM_BLUE_SIZE;
  213759. attribs[n++] = pixelFormat.accumulationBufferBlueBits;
  213760. attribs[n++] = GLX_ACCUM_ALPHA_SIZE;
  213761. attribs[n++] = pixelFormat.accumulationBufferAlphaBits;
  213762. // xxx not sure how to do fullSceneAntiAliasingNumSamples on linux..
  213763. attribs[n++] = None;
  213764. XVisualInfo* const bestVisual = glXChooseVisual (display, DefaultScreen (display), attribs);
  213765. if (bestVisual == 0)
  213766. return;
  213767. renderContext = glXCreateContext (display, bestVisual, sharedContext, GL_TRUE);
  213768. Window windowH = (Window) peer->getNativeHandle();
  213769. Colormap colourMap = XCreateColormap (display, windowH, bestVisual->visual, AllocNone);
  213770. XSetWindowAttributes swa;
  213771. swa.colormap = colourMap;
  213772. swa.border_pixel = 0;
  213773. swa.event_mask = ExposureMask | StructureNotifyMask;
  213774. embeddedWindow = XCreateWindow (display, windowH,
  213775. 0, 0, 1, 1, 0,
  213776. bestVisual->depth,
  213777. InputOutput,
  213778. bestVisual->visual,
  213779. CWBorderPixel | CWColormap | CWEventMask,
  213780. &swa);
  213781. XSaveContext (display, (XID) embeddedWindow, improbableNumber, (XPointer) peer);
  213782. XMapWindow (display, embeddedWindow);
  213783. XFreeColormap (display, colourMap);
  213784. XFree (bestVisual);
  213785. XSync (display, False);
  213786. }
  213787. ~WindowedGLContext()
  213788. {
  213789. makeInactive();
  213790. glXDestroyContext (display, renderContext);
  213791. XUnmapWindow (display, embeddedWindow);
  213792. XDestroyWindow (display, embeddedWindow);
  213793. }
  213794. bool makeActive() const throw()
  213795. {
  213796. jassert (renderContext != 0);
  213797. return glXMakeCurrent (display, embeddedWindow, renderContext)
  213798. && XSync (display, False);
  213799. }
  213800. bool makeInactive() const throw()
  213801. {
  213802. return (! isActive()) || glXMakeCurrent (display, None, 0);
  213803. }
  213804. bool isActive() const throw()
  213805. {
  213806. return glXGetCurrentContext() == renderContext;
  213807. }
  213808. const OpenGLPixelFormat getPixelFormat() const
  213809. {
  213810. return pixelFormat;
  213811. }
  213812. void* getRawContext() const throw()
  213813. {
  213814. return renderContext;
  213815. }
  213816. void updateWindowPosition (int x, int y, int w, int h, int)
  213817. {
  213818. XMoveResizeWindow (display, embeddedWindow,
  213819. x, y, jmax (1, w), jmax (1, h));
  213820. }
  213821. void swapBuffers()
  213822. {
  213823. glXSwapBuffers (display, embeddedWindow);
  213824. }
  213825. bool setSwapInterval (const int numFramesPerSwap)
  213826. {
  213827. // xxx needs doing..
  213828. return false;
  213829. }
  213830. int getSwapInterval() const
  213831. {
  213832. // xxx needs doing..
  213833. return 0;
  213834. }
  213835. void repaint()
  213836. {
  213837. }
  213838. juce_UseDebuggingNewOperator
  213839. GLXContext renderContext;
  213840. private:
  213841. Window embeddedWindow;
  213842. OpenGLPixelFormat pixelFormat;
  213843. WindowedGLContext (const WindowedGLContext&);
  213844. const WindowedGLContext& operator= (const WindowedGLContext&);
  213845. };
  213846. OpenGLContext* OpenGLContext::createContextForWindow (Component* const component,
  213847. const OpenGLPixelFormat& pixelFormat,
  213848. const OpenGLContext* const contextToShareWith)
  213849. {
  213850. WindowedGLContext* c = new WindowedGLContext (component, pixelFormat,
  213851. contextToShareWith != 0 ? (GLXContext) contextToShareWith->getRawContext() : 0);
  213852. if (c->renderContext == 0)
  213853. deleteAndZero (c);
  213854. return c;
  213855. }
  213856. void juce_glViewport (const int w, const int h)
  213857. {
  213858. glViewport (0, 0, w, h);
  213859. }
  213860. void OpenGLPixelFormat::getAvailablePixelFormats (Component* component,
  213861. OwnedArray <OpenGLPixelFormat>& results)
  213862. {
  213863. results.add (new OpenGLPixelFormat()); // xxx
  213864. }
  213865. #endif
  213866. static void initClipboard (Window root, Atom* cutBuffers) throw()
  213867. {
  213868. static bool init = false;
  213869. if (! init)
  213870. {
  213871. init = true;
  213872. // Make sure all cut buffers exist before use
  213873. for (int i = 0; i < 8; i++)
  213874. {
  213875. XChangeProperty (display, root, cutBuffers[i],
  213876. XA_STRING, 8, PropModeAppend, NULL, 0);
  213877. }
  213878. }
  213879. }
  213880. // Clipboard implemented currently using cut buffers
  213881. // rather than the more powerful selection method
  213882. void SystemClipboard::copyTextToClipboard (const String& clipText) throw()
  213883. {
  213884. Window root = RootWindow (display, DefaultScreen (display));
  213885. Atom cutBuffers[8] = { XA_CUT_BUFFER0, XA_CUT_BUFFER1, XA_CUT_BUFFER2, XA_CUT_BUFFER3,
  213886. XA_CUT_BUFFER4, XA_CUT_BUFFER5, XA_CUT_BUFFER6, XA_CUT_BUFFER7 };
  213887. initClipboard (root, cutBuffers);
  213888. XRotateWindowProperties (display, root, cutBuffers, 8, 1);
  213889. XChangeProperty (display, root, cutBuffers[0],
  213890. XA_STRING, 8, PropModeReplace, (const unsigned char*) (const char*) clipText,
  213891. clipText.length());
  213892. }
  213893. const String SystemClipboard::getTextFromClipboard() throw()
  213894. {
  213895. const int bufSize = 64; // in words
  213896. String returnData;
  213897. int byteOffset = 0;
  213898. Window root = RootWindow (display, DefaultScreen (display));
  213899. Atom cutBuffers[8] = { XA_CUT_BUFFER0, XA_CUT_BUFFER1, XA_CUT_BUFFER2, XA_CUT_BUFFER3,
  213900. XA_CUT_BUFFER4, XA_CUT_BUFFER5, XA_CUT_BUFFER6, XA_CUT_BUFFER7 };
  213901. initClipboard (root, cutBuffers);
  213902. for (;;)
  213903. {
  213904. unsigned long bytesLeft = 0, nitems = 0;
  213905. unsigned char* clipData = 0;
  213906. int actualFormat = 0;
  213907. Atom actualType;
  213908. if (XGetWindowProperty (display, root, cutBuffers[0], byteOffset >> 2, bufSize,
  213909. False, XA_STRING, &actualType, &actualFormat, &nitems, &bytesLeft,
  213910. &clipData) == Success)
  213911. {
  213912. if (actualType == XA_STRING && actualFormat == 8)
  213913. {
  213914. byteOffset += nitems;
  213915. returnData += String ((const char*) clipData, nitems);
  213916. }
  213917. else
  213918. {
  213919. bytesLeft = 0;
  213920. }
  213921. if (clipData != 0)
  213922. XFree (clipData);
  213923. }
  213924. if (bytesLeft == 0)
  213925. break;
  213926. }
  213927. return returnData;
  213928. }
  213929. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMoveFiles)
  213930. {
  213931. jassertfalse // not implemented!
  213932. return false;
  213933. }
  213934. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  213935. {
  213936. jassertfalse // not implemented!
  213937. return false;
  213938. }
  213939. void SystemTrayIconComponent::setIconImage (const Image& newImage)
  213940. {
  213941. if (! isOnDesktop ())
  213942. addToDesktop (0);
  213943. LinuxComponentPeer* const wp = dynamic_cast <LinuxComponentPeer*> (getPeer());
  213944. if (wp != 0)
  213945. {
  213946. wp->setTaskBarIcon (newImage);
  213947. setVisible (true);
  213948. toFront (false);
  213949. repaint();
  213950. }
  213951. }
  213952. void SystemTrayIconComponent::paint (Graphics& g)
  213953. {
  213954. LinuxComponentPeer* const wp = dynamic_cast <LinuxComponentPeer*> (getPeer());
  213955. if (wp != 0)
  213956. {
  213957. const Image* const image = wp->getTaskbarIcon();
  213958. if (image != 0)
  213959. g.drawImageAt (image, 0, 0, false);
  213960. }
  213961. }
  213962. void SystemTrayIconComponent::setIconTooltip (const String& tooltip)
  213963. {
  213964. // xxx not yet implemented!
  213965. }
  213966. void PlatformUtilities::beep()
  213967. {
  213968. fprintf (stdout, "\a");
  213969. fflush (stdout);
  213970. }
  213971. bool AlertWindow::showNativeDialogBox (const String& title,
  213972. const String& bodyText,
  213973. bool isOkCancel)
  213974. {
  213975. // xxx this is supposed to pop up an alert!
  213976. Logger::outputDebugString (title + ": " + bodyText);
  213977. // use a non-native one for the time being..
  213978. if (isOkCancel)
  213979. return AlertWindow::showOkCancelBox (AlertWindow::NoIcon, title, bodyText);
  213980. else
  213981. AlertWindow::showMessageBox (AlertWindow::NoIcon, title, bodyText);
  213982. return true;
  213983. }
  213984. const int KeyPress::spaceKey = XK_space & 0xff;
  213985. const int KeyPress::returnKey = XK_Return & 0xff;
  213986. const int KeyPress::escapeKey = XK_Escape & 0xff;
  213987. const int KeyPress::backspaceKey = XK_BackSpace & 0xff;
  213988. const int KeyPress::leftKey = (XK_Left & 0xff) | extendedKeyModifier;
  213989. const int KeyPress::rightKey = (XK_Right & 0xff) | extendedKeyModifier;
  213990. const int KeyPress::upKey = (XK_Up & 0xff) | extendedKeyModifier;
  213991. const int KeyPress::downKey = (XK_Down & 0xff) | extendedKeyModifier;
  213992. const int KeyPress::pageUpKey = (XK_Page_Up & 0xff) | extendedKeyModifier;
  213993. const int KeyPress::pageDownKey = (XK_Page_Down & 0xff) | extendedKeyModifier;
  213994. const int KeyPress::endKey = (XK_End & 0xff) | extendedKeyModifier;
  213995. const int KeyPress::homeKey = (XK_Home & 0xff) | extendedKeyModifier;
  213996. const int KeyPress::insertKey = (XK_Insert & 0xff) | extendedKeyModifier;
  213997. const int KeyPress::deleteKey = (XK_Delete & 0xff) | extendedKeyModifier;
  213998. const int KeyPress::tabKey = XK_Tab & 0xff;
  213999. const int KeyPress::F1Key = (XK_F1 & 0xff) | extendedKeyModifier;
  214000. const int KeyPress::F2Key = (XK_F2 & 0xff) | extendedKeyModifier;
  214001. const int KeyPress::F3Key = (XK_F3 & 0xff) | extendedKeyModifier;
  214002. const int KeyPress::F4Key = (XK_F4 & 0xff) | extendedKeyModifier;
  214003. const int KeyPress::F5Key = (XK_F5 & 0xff) | extendedKeyModifier;
  214004. const int KeyPress::F6Key = (XK_F6 & 0xff) | extendedKeyModifier;
  214005. const int KeyPress::F7Key = (XK_F7 & 0xff) | extendedKeyModifier;
  214006. const int KeyPress::F8Key = (XK_F8 & 0xff) | extendedKeyModifier;
  214007. const int KeyPress::F9Key = (XK_F9 & 0xff) | extendedKeyModifier;
  214008. const int KeyPress::F10Key = (XK_F10 & 0xff) | extendedKeyModifier;
  214009. const int KeyPress::F11Key = (XK_F11 & 0xff) | extendedKeyModifier;
  214010. const int KeyPress::F12Key = (XK_F12 & 0xff) | extendedKeyModifier;
  214011. const int KeyPress::F13Key = (XK_F13 & 0xff) | extendedKeyModifier;
  214012. const int KeyPress::F14Key = (XK_F14 & 0xff) | extendedKeyModifier;
  214013. const int KeyPress::F15Key = (XK_F15 & 0xff) | extendedKeyModifier;
  214014. const int KeyPress::F16Key = (XK_F16 & 0xff) | extendedKeyModifier;
  214015. const int KeyPress::numberPad0 = (XK_KP_0 & 0xff) | extendedKeyModifier;
  214016. const int KeyPress::numberPad1 = (XK_KP_1 & 0xff) | extendedKeyModifier;
  214017. const int KeyPress::numberPad2 = (XK_KP_2 & 0xff) | extendedKeyModifier;
  214018. const int KeyPress::numberPad3 = (XK_KP_3 & 0xff) | extendedKeyModifier;
  214019. const int KeyPress::numberPad4 = (XK_KP_4 & 0xff) | extendedKeyModifier;
  214020. const int KeyPress::numberPad5 = (XK_KP_5 & 0xff) | extendedKeyModifier;
  214021. const int KeyPress::numberPad6 = (XK_KP_6 & 0xff) | extendedKeyModifier;
  214022. const int KeyPress::numberPad7 = (XK_KP_7 & 0xff)| extendedKeyModifier;
  214023. const int KeyPress::numberPad8 = (XK_KP_8 & 0xff)| extendedKeyModifier;
  214024. const int KeyPress::numberPad9 = (XK_KP_9 & 0xff)| extendedKeyModifier;
  214025. const int KeyPress::numberPadAdd = (XK_KP_Add & 0xff)| extendedKeyModifier;
  214026. const int KeyPress::numberPadSubtract = (XK_KP_Subtract & 0xff)| extendedKeyModifier;
  214027. const int KeyPress::numberPadMultiply = (XK_KP_Multiply & 0xff)| extendedKeyModifier;
  214028. const int KeyPress::numberPadDivide = (XK_KP_Divide & 0xff)| extendedKeyModifier;
  214029. const int KeyPress::numberPadSeparator = (XK_KP_Separator & 0xff)| extendedKeyModifier;
  214030. const int KeyPress::numberPadDecimalPoint = (XK_KP_Decimal & 0xff)| extendedKeyModifier;
  214031. const int KeyPress::numberPadEquals = (XK_KP_Equal & 0xff)| extendedKeyModifier;
  214032. const int KeyPress::numberPadDelete = (XK_KP_Delete & 0xff)| extendedKeyModifier;
  214033. const int KeyPress::playKey = (0xffeeff00) | extendedKeyModifier;
  214034. const int KeyPress::stopKey = (0xffeeff01) | extendedKeyModifier;
  214035. const int KeyPress::fastForwardKey = (0xffeeff02) | extendedKeyModifier;
  214036. const int KeyPress::rewindKey = (0xffeeff03) | extendedKeyModifier;
  214037. END_JUCE_NAMESPACE
  214038. #endif
  214039. /********* End of inlined file: juce_linux_Windowing.cpp *********/
  214040. #endif
  214041. #endif
  214042. //==============================================================================
  214043. #if JUCE_MAC
  214044. /********* Start of inlined file: juce_mac_Files.cpp *********/
  214045. #include <sys/stat.h>
  214046. #include <sys/dir.h>
  214047. #include <sys/param.h>
  214048. #include <sys/mount.h>
  214049. #include <unistd.h>
  214050. #include <fnmatch.h>
  214051. #include <utime.h>
  214052. #include <pwd.h>
  214053. #include <fcntl.h>
  214054. #include <Carbon/Carbon.h>
  214055. BEGIN_JUCE_NAMESPACE
  214056. /*
  214057. Note that a lot of methods that you'd expect to find in this file actually
  214058. live in juce_posix_SharedCode.cpp!
  214059. */
  214060. /********* Start of inlined file: juce_posix_SharedCode.cpp *********/
  214061. /*
  214062. This file contains posix routines that are common to both the Linux and Mac builds.
  214063. It gets included directly in the cpp files for these platforms.
  214064. */
  214065. CriticalSection::CriticalSection() throw()
  214066. {
  214067. pthread_mutexattr_t atts;
  214068. pthread_mutexattr_init (&atts);
  214069. pthread_mutexattr_settype (&atts, PTHREAD_MUTEX_RECURSIVE);
  214070. pthread_mutex_init (&internal, &atts);
  214071. }
  214072. CriticalSection::~CriticalSection() throw()
  214073. {
  214074. pthread_mutex_destroy (&internal);
  214075. }
  214076. void CriticalSection::enter() const throw()
  214077. {
  214078. pthread_mutex_lock (&internal);
  214079. }
  214080. bool CriticalSection::tryEnter() const throw()
  214081. {
  214082. return pthread_mutex_trylock (&internal) == 0;
  214083. }
  214084. void CriticalSection::exit() const throw()
  214085. {
  214086. pthread_mutex_unlock (&internal);
  214087. }
  214088. struct EventStruct
  214089. {
  214090. pthread_cond_t condition;
  214091. pthread_mutex_t mutex;
  214092. bool triggered;
  214093. };
  214094. WaitableEvent::WaitableEvent() throw()
  214095. {
  214096. EventStruct* const es = new EventStruct();
  214097. es->triggered = false;
  214098. pthread_cond_init (&es->condition, 0);
  214099. pthread_mutex_init (&es->mutex, 0);
  214100. internal = es;
  214101. }
  214102. WaitableEvent::~WaitableEvent() throw()
  214103. {
  214104. EventStruct* const es = (EventStruct*) internal;
  214105. pthread_cond_destroy (&es->condition);
  214106. pthread_mutex_destroy (&es->mutex);
  214107. delete es;
  214108. }
  214109. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  214110. {
  214111. EventStruct* const es = (EventStruct*) internal;
  214112. bool ok = true;
  214113. pthread_mutex_lock (&es->mutex);
  214114. if (! es->triggered)
  214115. {
  214116. if (timeOutMillisecs < 0)
  214117. {
  214118. pthread_cond_wait (&es->condition, &es->mutex);
  214119. }
  214120. else
  214121. {
  214122. struct timespec time;
  214123. #if JUCE_MAC
  214124. time.tv_sec = timeOutMillisecs / 1000;
  214125. time.tv_nsec = (timeOutMillisecs % 1000) * 1000000;
  214126. pthread_cond_timedwait_relative_np (&es->condition, &es->mutex, &time);
  214127. #else
  214128. struct timeval t;
  214129. int timeout = 0;
  214130. gettimeofday (&t, 0);
  214131. time.tv_sec = t.tv_sec + (timeOutMillisecs / 1000);
  214132. time.tv_nsec = (t.tv_usec + ((timeOutMillisecs % 1000) * 1000)) * 1000;
  214133. while (time.tv_nsec >= 1000000000)
  214134. {
  214135. time.tv_nsec -= 1000000000;
  214136. time.tv_sec++;
  214137. }
  214138. while (! timeout)
  214139. {
  214140. timeout = pthread_cond_timedwait (&es->condition, &es->mutex, &time);
  214141. if (! timeout)
  214142. // Success
  214143. break;
  214144. if (timeout == EINTR)
  214145. // Go round again
  214146. timeout = 0;
  214147. }
  214148. #endif
  214149. }
  214150. ok = es->triggered;
  214151. }
  214152. es->triggered = false;
  214153. pthread_mutex_unlock (&es->mutex);
  214154. return ok;
  214155. }
  214156. void WaitableEvent::signal() const throw()
  214157. {
  214158. EventStruct* const es = (EventStruct*) internal;
  214159. pthread_mutex_lock (&es->mutex);
  214160. es->triggered = true;
  214161. pthread_cond_broadcast (&es->condition);
  214162. pthread_mutex_unlock (&es->mutex);
  214163. }
  214164. void WaitableEvent::reset() const throw()
  214165. {
  214166. EventStruct* const es = (EventStruct*) internal;
  214167. pthread_mutex_lock (&es->mutex);
  214168. es->triggered = false;
  214169. pthread_mutex_unlock (&es->mutex);
  214170. }
  214171. void JUCE_CALLTYPE Thread::sleep (int millisecs) throw()
  214172. {
  214173. struct timespec time;
  214174. time.tv_sec = millisecs / 1000;
  214175. time.tv_nsec = (millisecs % 1000) * 1000000;
  214176. nanosleep (&time, 0);
  214177. }
  214178. const tchar File::separator = T('/');
  214179. const tchar* File::separatorString = T("/");
  214180. bool juce_copyFile (const String& s, const String& d) throw();
  214181. static bool juce_stat (const String& fileName, struct stat& info) throw()
  214182. {
  214183. return fileName.isNotEmpty()
  214184. && (stat (fileName.toUTF8(), &info) == 0);
  214185. }
  214186. bool juce_isDirectory (const String& fileName) throw()
  214187. {
  214188. struct stat info;
  214189. return fileName.isEmpty()
  214190. || (juce_stat (fileName, info)
  214191. && ((info.st_mode & S_IFDIR) != 0));
  214192. }
  214193. bool juce_fileExists (const String& fileName, const bool dontCountDirectories) throw()
  214194. {
  214195. if (fileName.isEmpty())
  214196. return false;
  214197. const char* const fileNameUTF8 = fileName.toUTF8();
  214198. bool exists = access (fileNameUTF8, F_OK) == 0;
  214199. if (exists && dontCountDirectories)
  214200. {
  214201. struct stat info;
  214202. const int res = stat (fileNameUTF8, &info);
  214203. if (res == 0 && (info.st_mode & S_IFDIR) != 0)
  214204. exists = false;
  214205. }
  214206. return exists;
  214207. }
  214208. int64 juce_getFileSize (const String& fileName) throw()
  214209. {
  214210. struct stat info;
  214211. return juce_stat (fileName, info) ? info.st_size : 0;
  214212. }
  214213. bool juce_canWriteToFile (const String& fileName) throw()
  214214. {
  214215. return access (fileName.toUTF8(), W_OK) == 0;
  214216. }
  214217. bool juce_deleteFile (const String& fileName) throw()
  214218. {
  214219. const char* const fileNameUTF8 = fileName.toUTF8();
  214220. if (juce_isDirectory (fileName))
  214221. return rmdir (fileNameUTF8) == 0;
  214222. else
  214223. return remove (fileNameUTF8) == 0;
  214224. }
  214225. bool juce_moveFile (const String& source, const String& dest) throw()
  214226. {
  214227. if (rename (source.toUTF8(), dest.toUTF8()) == 0)
  214228. return true;
  214229. if (juce_canWriteToFile (source)
  214230. && juce_copyFile (source, dest))
  214231. {
  214232. if (juce_deleteFile (source))
  214233. return true;
  214234. juce_deleteFile (dest);
  214235. }
  214236. return false;
  214237. }
  214238. void juce_createDirectory (const String& fileName) throw()
  214239. {
  214240. mkdir (fileName.toUTF8(), 0777);
  214241. }
  214242. void* juce_fileOpen (const String& fileName, bool forWriting) throw()
  214243. {
  214244. const char* const fileNameUTF8 = fileName.toUTF8();
  214245. int flags = O_RDONLY;
  214246. if (forWriting)
  214247. {
  214248. if (juce_fileExists (fileName, false))
  214249. {
  214250. const int f = open (fileNameUTF8, O_RDWR, 00644);
  214251. if (f != -1)
  214252. lseek (f, 0, SEEK_END);
  214253. return (void*) f;
  214254. }
  214255. else
  214256. {
  214257. flags = O_RDWR + O_CREAT;
  214258. }
  214259. }
  214260. return (void*) open (fileNameUTF8, flags, 00644);
  214261. }
  214262. void juce_fileClose (void* handle) throw()
  214263. {
  214264. if (handle != 0)
  214265. close ((int) (pointer_sized_int) handle);
  214266. }
  214267. int juce_fileRead (void* handle, void* buffer, int size) throw()
  214268. {
  214269. if (handle != 0)
  214270. return read ((int) (pointer_sized_int) handle, buffer, size);
  214271. return 0;
  214272. }
  214273. int juce_fileWrite (void* handle, const void* buffer, int size) throw()
  214274. {
  214275. if (handle != 0)
  214276. return write ((int) (pointer_sized_int) handle, buffer, size);
  214277. return 0;
  214278. }
  214279. int64 juce_fileSetPosition (void* handle, int64 pos) throw()
  214280. {
  214281. if (handle != 0 && lseek ((int) (pointer_sized_int) handle, pos, SEEK_SET) == pos)
  214282. return pos;
  214283. return -1;
  214284. }
  214285. int64 juce_fileGetPosition (void* handle) throw()
  214286. {
  214287. if (handle != 0)
  214288. return lseek ((int) (pointer_sized_int) handle, 0, SEEK_CUR);
  214289. else
  214290. return -1;
  214291. }
  214292. void juce_fileFlush (void* handle) throw()
  214293. {
  214294. if (handle != 0)
  214295. fsync ((int) (pointer_sized_int) handle);
  214296. }
  214297. // if this file doesn't exist, find a parent of it that does..
  214298. static bool doStatFS (const File* file, struct statfs& result) throw()
  214299. {
  214300. File f (*file);
  214301. for (int i = 5; --i >= 0;)
  214302. {
  214303. if (f.exists())
  214304. break;
  214305. f = f.getParentDirectory();
  214306. }
  214307. return statfs (f.getFullPathName().toUTF8(), &result) == 0;
  214308. }
  214309. int64 File::getBytesFreeOnVolume() const throw()
  214310. {
  214311. int64 free_space = 0;
  214312. struct statfs buf;
  214313. if (doStatFS (this, buf))
  214314. // Note: this returns space available to non-super user
  214315. free_space = (int64) buf.f_bsize * (int64) buf.f_bavail;
  214316. return free_space;
  214317. }
  214318. const String juce_getVolumeLabel (const String& filenameOnVolume,
  214319. int& volumeSerialNumber) throw()
  214320. {
  214321. // There is no equivalent on Linux
  214322. volumeSerialNumber = 0;
  214323. return String::empty;
  214324. }
  214325. #if JUCE_64BIT
  214326. #define filedesc ((long long) internal)
  214327. #else
  214328. #define filedesc ((int) internal)
  214329. #endif
  214330. InterProcessLock::InterProcessLock (const String& name_) throw()
  214331. : internal (0),
  214332. name (name_),
  214333. reentrancyLevel (0)
  214334. {
  214335. #if JUCE_MAC
  214336. // (don't use getSpecialLocation() to avoid the temp folder being different for each app)
  214337. const File temp (File (T("~/Library/Caches/Juce")).getChildFile (name));
  214338. #else
  214339. const File temp (File::getSpecialLocation (File::tempDirectory).getChildFile (name));
  214340. #endif
  214341. temp.create();
  214342. internal = (void*) open (temp.getFullPathName().toUTF8(), O_RDWR);
  214343. }
  214344. InterProcessLock::~InterProcessLock() throw()
  214345. {
  214346. while (reentrancyLevel > 0)
  214347. this->exit();
  214348. close (filedesc);
  214349. }
  214350. bool InterProcessLock::enter (const int timeOutMillisecs) throw()
  214351. {
  214352. if (internal == 0)
  214353. return false;
  214354. if (reentrancyLevel != 0)
  214355. return true;
  214356. const int64 endTime = Time::currentTimeMillis() + timeOutMillisecs;
  214357. struct flock fl;
  214358. zerostruct (fl);
  214359. fl.l_whence = SEEK_SET;
  214360. fl.l_type = F_WRLCK;
  214361. for (;;)
  214362. {
  214363. const int result = fcntl (filedesc, F_SETLK, &fl);
  214364. if (result >= 0)
  214365. {
  214366. ++reentrancyLevel;
  214367. return true;
  214368. }
  214369. if (errno != EINTR)
  214370. {
  214371. if (timeOutMillisecs == 0
  214372. || (timeOutMillisecs > 0 && Time::currentTimeMillis() >= endTime))
  214373. break;
  214374. Thread::sleep (10);
  214375. }
  214376. }
  214377. return false;
  214378. }
  214379. void InterProcessLock::exit() throw()
  214380. {
  214381. if (reentrancyLevel > 0 && internal != 0)
  214382. {
  214383. --reentrancyLevel;
  214384. struct flock fl;
  214385. zerostruct (fl);
  214386. fl.l_whence = SEEK_SET;
  214387. fl.l_type = F_UNLCK;
  214388. for (;;)
  214389. {
  214390. const int result = fcntl (filedesc, F_SETLKW, &fl);
  214391. if (result >= 0 || errno != EINTR)
  214392. break;
  214393. }
  214394. }
  214395. }
  214396. /********* End of inlined file: juce_posix_SharedCode.cpp *********/
  214397. static File executableFile;
  214398. void PlatformUtilities::copyToStr255 (Str255& d, const String& s)
  214399. {
  214400. unsigned char* t = (unsigned char*) d;
  214401. t[0] = jmin (254, s.length());
  214402. s.copyToBuffer ((char*) t + 1, 254);
  214403. }
  214404. void PlatformUtilities::copyToStr63 (Str63& d, const String& s)
  214405. {
  214406. unsigned char* t = (unsigned char*) d;
  214407. t[0] = jmin (62, s.length());
  214408. s.copyToBuffer ((char*) t + 1, 62);
  214409. }
  214410. const String PlatformUtilities::cfStringToJuceString (CFStringRef cfString)
  214411. {
  214412. String result;
  214413. if (cfString != 0)
  214414. {
  214415. #if JUCE_STRINGS_ARE_UNICODE
  214416. CFRange range = { 0, CFStringGetLength (cfString) };
  214417. UniChar* const u = (UniChar*) juce_malloc (sizeof (UniChar) * (range.length + 1));
  214418. CFStringGetCharacters (cfString, range, u);
  214419. u[range.length] = 0;
  214420. result = convertUTF16ToString (u);
  214421. juce_free (u);
  214422. #else
  214423. const int len = CFStringGetLength (cfString);
  214424. char* buffer = (char*) juce_malloc (len + 1);
  214425. CFStringGetCString (cfString, buffer, len + 1, CFStringGetSystemEncoding());
  214426. result = buffer;
  214427. juce_free (buffer);
  214428. #endif
  214429. }
  214430. return result;
  214431. }
  214432. CFStringRef PlatformUtilities::juceStringToCFString (const String& s)
  214433. {
  214434. #if JUCE_STRINGS_ARE_UNICODE
  214435. const int len = s.length();
  214436. const juce_wchar* t = (const juce_wchar*) s;
  214437. UniChar* temp = (UniChar*) juce_malloc (sizeof (UniChar) * len + 4);
  214438. for (int i = 0; i <= len; ++i)
  214439. temp[i] = t[i];
  214440. CFStringRef result = CFStringCreateWithCharacters (kCFAllocatorDefault, temp, len);
  214441. juce_free (temp);
  214442. return result;
  214443. #else
  214444. return CFStringCreateWithCString (kCFAllocatorDefault,
  214445. (const char*) s,
  214446. CFStringGetSystemEncoding());
  214447. #endif
  214448. }
  214449. const String PlatformUtilities::convertUTF16ToString (const UniChar* utf16)
  214450. {
  214451. String s;
  214452. while (*utf16 != 0)
  214453. s += (juce_wchar) *utf16++;
  214454. return s;
  214455. }
  214456. const String PlatformUtilities::convertToPrecomposedUnicode (const String& s)
  214457. {
  214458. UnicodeMapping map;
  214459. map.unicodeEncoding = CreateTextEncoding (kTextEncodingUnicodeDefault,
  214460. kUnicodeNoSubset,
  214461. kTextEncodingDefaultFormat);
  214462. map.otherEncoding = CreateTextEncoding (kTextEncodingUnicodeDefault,
  214463. kUnicodeCanonicalCompVariant,
  214464. kTextEncodingDefaultFormat);
  214465. map.mappingVersion = kUnicodeUseLatestMapping;
  214466. UnicodeToTextInfo conversionInfo = 0;
  214467. String result;
  214468. if (CreateUnicodeToTextInfo (&map, &conversionInfo) == noErr)
  214469. {
  214470. const int len = s.length();
  214471. UniChar* const tempIn = (UniChar*) juce_calloc (sizeof (UniChar) * len + 4);
  214472. UniChar* const tempOut = (UniChar*) juce_calloc (sizeof (UniChar) * len + 4);
  214473. for (int i = 0; i <= len; ++i)
  214474. tempIn[i] = s[i];
  214475. ByteCount bytesRead = 0;
  214476. ByteCount outputBufferSize = 0;
  214477. if (ConvertFromUnicodeToText (conversionInfo,
  214478. len * sizeof (UniChar), tempIn,
  214479. kUnicodeDefaultDirectionMask,
  214480. 0, 0, 0, 0,
  214481. len * sizeof (UniChar), &bytesRead,
  214482. &outputBufferSize, tempOut) == noErr)
  214483. {
  214484. result.preallocateStorage (bytesRead / sizeof (UniChar) + 2);
  214485. tchar* t = const_cast <tchar*> ((const tchar*) result);
  214486. int i;
  214487. for (i = 0; i < bytesRead / sizeof (UniChar); ++i)
  214488. t[i] = (tchar) tempOut[i];
  214489. t[i] = 0;
  214490. }
  214491. juce_free (tempIn);
  214492. juce_free (tempOut);
  214493. DisposeUnicodeToTextInfo (&conversionInfo);
  214494. }
  214495. return result;
  214496. }
  214497. const unsigned int macTimeToUnixTimeDiff = 0x7c25be90;
  214498. static uint64 utcDateTimeToUnixTime (const UTCDateTime& d) throw()
  214499. {
  214500. if (d.highSeconds == 0 && d.lowSeconds == 0 && d.fraction == 0)
  214501. return 0;
  214502. return (((((uint64) d.highSeconds) << 32) | (uint64) d.lowSeconds) * 1000)
  214503. + ((d.fraction * 1000) >> 16)
  214504. - 2082844800000ll;
  214505. }
  214506. static void unixTimeToUtcDateTime (uint64 t, UTCDateTime& d) throw()
  214507. {
  214508. if (t != 0)
  214509. t += 2082844800000ll;
  214510. d.highSeconds = (t / 1000) >> 32;
  214511. d.lowSeconds = (t / 1000) & (uint64) 0xffffffff;
  214512. d.fraction = ((t % 1000) << 16) / 1000;
  214513. }
  214514. void juce_getFileTimes (const String& fileName,
  214515. int64& modificationTime,
  214516. int64& accessTime,
  214517. int64& creationTime) throw()
  214518. {
  214519. modificationTime = 0;
  214520. accessTime = 0;
  214521. creationTime = 0;
  214522. FSRef fileRef;
  214523. if (PlatformUtilities::makeFSRefFromPath (&fileRef, fileName))
  214524. {
  214525. FSRefParam info;
  214526. zerostruct (info);
  214527. info.ref = &fileRef;
  214528. info.whichInfo = kFSCatInfoAllDates;
  214529. FSCatalogInfo catInfo;
  214530. info.catInfo = &catInfo;
  214531. if (PBGetCatalogInfoSync (&info) == noErr)
  214532. {
  214533. creationTime = utcDateTimeToUnixTime (catInfo.createDate);
  214534. accessTime = utcDateTimeToUnixTime (catInfo.accessDate);
  214535. modificationTime = utcDateTimeToUnixTime (catInfo.contentModDate);
  214536. }
  214537. }
  214538. }
  214539. bool juce_setFileTimes (const String& fileName,
  214540. int64 modificationTime,
  214541. int64 accessTime,
  214542. int64 creationTime) throw()
  214543. {
  214544. FSRef fileRef;
  214545. if (PlatformUtilities::makeFSRefFromPath (&fileRef, fileName))
  214546. {
  214547. FSRefParam info;
  214548. zerostruct (info);
  214549. info.ref = &fileRef;
  214550. info.whichInfo = kFSCatInfoAllDates;
  214551. FSCatalogInfo catInfo;
  214552. info.catInfo = &catInfo;
  214553. if (PBGetCatalogInfoSync (&info) == noErr)
  214554. {
  214555. if (creationTime != 0)
  214556. unixTimeToUtcDateTime (creationTime, catInfo.createDate);
  214557. if (modificationTime != 0)
  214558. unixTimeToUtcDateTime (modificationTime, catInfo.contentModDate);
  214559. if (accessTime != 0)
  214560. unixTimeToUtcDateTime (accessTime, catInfo.accessDate);
  214561. return PBSetCatalogInfoSync (&info) == noErr;
  214562. }
  214563. }
  214564. return false;
  214565. }
  214566. bool juce_setFileReadOnly (const String& fileName, bool isReadOnly) throw()
  214567. {
  214568. const char* const fileNameUTF8 = fileName.toUTF8();
  214569. struct stat info;
  214570. const int res = stat (fileNameUTF8, &info);
  214571. bool ok = false;
  214572. if (res == 0)
  214573. {
  214574. info.st_mode &= 0777; // Just permissions
  214575. if (isReadOnly)
  214576. info.st_mode &= ~(S_IWUSR | S_IWGRP | S_IWOTH);
  214577. else
  214578. // Give everybody write permission?
  214579. info.st_mode |= S_IWUSR | S_IWGRP | S_IWOTH;
  214580. ok = chmod (fileNameUTF8, info.st_mode) == 0;
  214581. }
  214582. return ok;
  214583. }
  214584. bool juce_copyFile (const String& src, const String& dst) throw()
  214585. {
  214586. const File destFile (dst);
  214587. if (! destFile.create())
  214588. return false;
  214589. FSRef srcRef, dstRef;
  214590. if (! (PlatformUtilities::makeFSRefFromPath (&srcRef, src)
  214591. && PlatformUtilities::makeFSRefFromPath (&dstRef, dst)))
  214592. {
  214593. return false;
  214594. }
  214595. int okForks = 0;
  214596. CatPositionRec iter;
  214597. iter.initialize = 0;
  214598. HFSUniStr255 forkName;
  214599. // can't just copy the data because this is a bloody Mac, so we need to copy each
  214600. // fork separately...
  214601. while (FSIterateForks (&srcRef, &iter, &forkName, 0, 0) == noErr)
  214602. {
  214603. SInt16 srcForkNum = 0, dstForkNum = 0;
  214604. OSErr err = FSOpenFork (&srcRef, forkName.length, forkName.unicode, fsRdPerm, &srcForkNum);
  214605. if (err == noErr)
  214606. {
  214607. err = FSOpenFork (&dstRef, forkName.length, forkName.unicode, fsRdWrPerm, &dstForkNum);
  214608. if (err == noErr)
  214609. {
  214610. MemoryBlock buf (32768);
  214611. SInt64 pos = 0;
  214612. for (;;)
  214613. {
  214614. ByteCount bytesRead = 0;
  214615. err = FSReadFork (srcForkNum, fsFromStart, pos, buf.getSize(), (char*) buf, &bytesRead);
  214616. if (bytesRead > 0)
  214617. {
  214618. err = FSWriteFork (dstForkNum, fsFromStart, pos, bytesRead, (const char*) buf, &bytesRead);
  214619. pos += bytesRead;
  214620. }
  214621. if (err != noErr)
  214622. {
  214623. if (err == eofErr)
  214624. ++okForks;
  214625. break;
  214626. }
  214627. }
  214628. FSFlushFork (dstForkNum);
  214629. FSCloseFork (dstForkNum);
  214630. }
  214631. FSCloseFork (srcForkNum);
  214632. }
  214633. }
  214634. if (okForks > 0) // some files seem to be ok even if not all their forks get copied..
  214635. {
  214636. // copy permissions..
  214637. struct stat info;
  214638. if (juce_stat (src, info))
  214639. chmod (dst.toUTF8(), info.st_mode & 0777);
  214640. return true;
  214641. }
  214642. return false;
  214643. }
  214644. const StringArray juce_getFileSystemRoots() throw()
  214645. {
  214646. StringArray s;
  214647. s.add (T("/"));
  214648. return s;
  214649. }
  214650. static bool isFileOnDriveType (const File* const f, const char** types) throw()
  214651. {
  214652. struct statfs buf;
  214653. if (doStatFS (f, buf))
  214654. {
  214655. const String type (buf.f_fstypename);
  214656. while (*types != 0)
  214657. if (type.equalsIgnoreCase (*types++))
  214658. return true;
  214659. }
  214660. return false;
  214661. }
  214662. bool File::isOnCDRomDrive() const throw()
  214663. {
  214664. static const char* const cdTypes[] = { "cd9660", "cdfs", "cddafs", "udf", 0 };
  214665. return isFileOnDriveType (this, (const char**) cdTypes);
  214666. }
  214667. bool File::isOnHardDisk() const throw()
  214668. {
  214669. static const char* const nonHDTypes[] = { "nfs", "smbfs", "ramfs", 0 };
  214670. return ! (isOnCDRomDrive() || isFileOnDriveType (this, (const char**) nonHDTypes));
  214671. }
  214672. static bool juce_isHiddenFile (const String& path) throw()
  214673. {
  214674. FSRef ref;
  214675. if (! PlatformUtilities::makeFSRefFromPath (&ref, path))
  214676. return false;
  214677. FSCatalogInfo info;
  214678. FSGetCatalogInfo (&ref, kFSCatInfoNodeFlags | kFSCatInfoFinderInfo, &info, 0, 0, 0);
  214679. if ((info.nodeFlags & kFSNodeIsDirectoryBit) != 0)
  214680. return (((FolderInfo*) &info.finderInfo)->finderFlags & kIsInvisible) != 0;
  214681. return (((FileInfo*) &info.finderInfo)->finderFlags & kIsInvisible) != 0;
  214682. }
  214683. bool File::isHidden() const throw()
  214684. {
  214685. return juce_isHiddenFile (getFullPathName());
  214686. }
  214687. const File File::getSpecialLocation (const SpecialLocationType type)
  214688. {
  214689. const char* resultPath = 0;
  214690. switch (type)
  214691. {
  214692. case userHomeDirectory:
  214693. resultPath = getenv ("HOME");
  214694. if (resultPath == 0)
  214695. {
  214696. struct passwd* const pw = getpwuid (getuid());
  214697. if (pw != 0)
  214698. resultPath = pw->pw_dir;
  214699. }
  214700. break;
  214701. case userDocumentsDirectory:
  214702. resultPath = "~/Documents";
  214703. break;
  214704. case userDesktopDirectory:
  214705. resultPath = "~/Desktop";
  214706. break;
  214707. case userApplicationDataDirectory:
  214708. resultPath = "~/Library";
  214709. break;
  214710. case commonApplicationDataDirectory:
  214711. resultPath = "/Library";
  214712. break;
  214713. case globalApplicationsDirectory:
  214714. resultPath = "/Applications";
  214715. break;
  214716. case userMusicDirectory:
  214717. resultPath = "~/Music";
  214718. break;
  214719. case userMoviesDirectory:
  214720. resultPath = "~/Movies";
  214721. break;
  214722. case tempDirectory:
  214723. {
  214724. File tmp (T("~/Library/Caches/") + executableFile.getFileNameWithoutExtension());
  214725. tmp.createDirectory();
  214726. return tmp.getFullPathName();
  214727. }
  214728. case currentExecutableFile:
  214729. return executableFile;
  214730. case currentApplicationFile:
  214731. {
  214732. const File parent (executableFile.getParentDirectory());
  214733. return parent.getFullPathName().endsWithIgnoreCase (T("Contents/MacOS"))
  214734. ? parent.getParentDirectory().getParentDirectory()
  214735. : executableFile;
  214736. }
  214737. default:
  214738. jassertfalse // unknown type?
  214739. break;
  214740. }
  214741. if (resultPath != 0)
  214742. return File (PlatformUtilities::convertToPrecomposedUnicode (resultPath));
  214743. return File::nonexistent;
  214744. }
  214745. void juce_setCurrentExecutableFileName (const String& filename) throw()
  214746. {
  214747. executableFile = File::getCurrentWorkingDirectory()
  214748. .getChildFile (PlatformUtilities::convertToPrecomposedUnicode (filename));
  214749. }
  214750. void juce_setCurrentExecutableFileNameFromBundleId (const String& bundleId) throw()
  214751. {
  214752. CFStringRef bundleIdStringRef = PlatformUtilities::juceStringToCFString (bundleId);
  214753. CFBundleRef bundleRef = CFBundleGetBundleWithIdentifier (bundleIdStringRef);
  214754. CFRelease (bundleIdStringRef);
  214755. if (bundleRef != 0)
  214756. {
  214757. CFURLRef exeURLRef = CFBundleCopyExecutableURL (bundleRef);
  214758. if (exeURLRef != 0)
  214759. {
  214760. CFStringRef pathStringRef = CFURLCopyFileSystemPath (exeURLRef, kCFURLPOSIXPathStyle);
  214761. CFRelease (exeURLRef);
  214762. if (pathStringRef != 0)
  214763. {
  214764. juce_setCurrentExecutableFileName (PlatformUtilities::cfStringToJuceString (pathStringRef));
  214765. CFRelease (pathStringRef);
  214766. }
  214767. }
  214768. }
  214769. }
  214770. const File File::getCurrentWorkingDirectory() throw()
  214771. {
  214772. char buf [2048];
  214773. getcwd (buf, sizeof(buf));
  214774. return File (PlatformUtilities::convertToPrecomposedUnicode (buf));
  214775. }
  214776. bool File::setAsCurrentWorkingDirectory() const throw()
  214777. {
  214778. return chdir (getFullPathName().toUTF8()) == 0;
  214779. }
  214780. struct FindFileStruct
  214781. {
  214782. String parentDir, wildCard;
  214783. DIR* dir;
  214784. bool getNextMatch (String& result, bool* const isDir, bool* const isHidden, int64* const fileSize,
  214785. Time* const modTime, Time* const creationTime, bool* const isReadOnly) throw()
  214786. {
  214787. const char* const wildCardUTF8 = wildCard.toUTF8();
  214788. for (;;)
  214789. {
  214790. struct dirent* const de = readdir (dir);
  214791. if (de == 0)
  214792. break;
  214793. if (fnmatch (wildCardUTF8, de->d_name, 0) == 0)
  214794. {
  214795. result = PlatformUtilities::convertToPrecomposedUnicode (String::fromUTF8 ((const uint8*) de->d_name));
  214796. const String path (parentDir + result);
  214797. if (isDir != 0 || fileSize != 0)
  214798. {
  214799. struct stat info;
  214800. const bool statOk = juce_stat (path, info);
  214801. if (isDir != 0)
  214802. *isDir = path.isEmpty() || (statOk && ((info.st_mode & S_IFDIR) != 0));
  214803. if (isHidden != 0)
  214804. *isHidden = (de->d_name[0] == '.')
  214805. || juce_isHiddenFile (path);
  214806. if (fileSize != 0)
  214807. *fileSize = statOk ? info.st_size : 0;
  214808. }
  214809. if (modTime != 0 || creationTime != 0)
  214810. {
  214811. int64 m, a, c;
  214812. juce_getFileTimes (path, m, a, c);
  214813. if (modTime != 0)
  214814. *modTime = m;
  214815. if (creationTime != 0)
  214816. *creationTime = c;
  214817. }
  214818. if (isReadOnly != 0)
  214819. *isReadOnly = ! juce_canWriteToFile (path);
  214820. return true;
  214821. }
  214822. }
  214823. return false;
  214824. }
  214825. };
  214826. // returns 0 on failure
  214827. void* juce_findFileStart (const String& directory, const String& wildCard, String& firstResultFile,
  214828. bool* isDir, bool* isHidden, int64* fileSize, Time* modTime,
  214829. Time* creationTime, bool* isReadOnly) throw()
  214830. {
  214831. DIR* const d = opendir (directory.toUTF8());
  214832. if (d != 0)
  214833. {
  214834. FindFileStruct* const ff = new FindFileStruct();
  214835. ff->parentDir = directory;
  214836. if (!ff->parentDir.endsWithChar (File::separator))
  214837. ff->parentDir += File::separator;
  214838. ff->wildCard = wildCard;
  214839. ff->dir = d;
  214840. if (ff->getNextMatch (firstResultFile, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly))
  214841. {
  214842. return ff;
  214843. }
  214844. else
  214845. {
  214846. firstResultFile = String::empty;
  214847. isDir = false;
  214848. closedir (d);
  214849. delete ff;
  214850. }
  214851. }
  214852. return 0;
  214853. }
  214854. bool juce_findFileNext (void* handle, String& resultFile,
  214855. bool* isDir, bool* isHidden, int64* fileSize, Time* modTime, Time* creationTime, bool* isReadOnly) throw()
  214856. {
  214857. FindFileStruct* const ff = (FindFileStruct*) handle;
  214858. if (ff != 0)
  214859. return ff->getNextMatch (resultFile, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  214860. return false;
  214861. }
  214862. void juce_findFileClose (void* handle) throw()
  214863. {
  214864. FindFileStruct* const ff = (FindFileStruct*)handle;
  214865. if (ff != 0)
  214866. {
  214867. closedir (ff->dir);
  214868. delete ff;
  214869. }
  214870. }
  214871. bool juce_launchExecutable (const String& pathAndArguments) throw()
  214872. {
  214873. char* const argv[4] = { "/bin/sh", "-c", (char*) (const char*) pathAndArguments, 0 };
  214874. const int cpid = fork();
  214875. if (cpid == 0)
  214876. {
  214877. // Child process
  214878. if (execve (argv[0], argv, 0) < 0)
  214879. exit (0);
  214880. }
  214881. else
  214882. {
  214883. if (cpid < 0)
  214884. return false;
  214885. }
  214886. return true;
  214887. }
  214888. bool juce_launchFile (const String& fileName,
  214889. const String& parameters) throw()
  214890. {
  214891. bool ok = false;
  214892. if (fileName.startsWithIgnoreCase (T("http:"))
  214893. || fileName.startsWithIgnoreCase (T("https:"))
  214894. || fileName.startsWithIgnoreCase (T("ftp:"))
  214895. || fileName.startsWithIgnoreCase (T("file:")))
  214896. {
  214897. CFStringRef urlString = PlatformUtilities::juceStringToCFString (fileName);
  214898. if (urlString != 0)
  214899. {
  214900. CFURLRef url = CFURLCreateWithString (kCFAllocatorDefault,
  214901. urlString, 0);
  214902. CFRelease (urlString);
  214903. if (url != 0)
  214904. {
  214905. ok = (LSOpenCFURLRef (url, 0) == noErr);
  214906. CFRelease (url);
  214907. }
  214908. }
  214909. }
  214910. else
  214911. {
  214912. FSRef ref;
  214913. if (PlatformUtilities::makeFSRefFromPath (&ref, fileName))
  214914. {
  214915. if (juce_isDirectory (fileName) && parameters.isNotEmpty())
  214916. {
  214917. // if we're launching a bundled app with a document..
  214918. StringArray docs;
  214919. docs.addTokens (parameters, true);
  214920. FSRef* docRefs = new FSRef [docs.size()];
  214921. for (int i = 0; i < docs.size(); ++i)
  214922. PlatformUtilities::makeFSRefFromPath (docRefs + i, docs[i]);
  214923. LSLaunchFSRefSpec ors;
  214924. ors.appRef = &ref;
  214925. ors.numDocs = docs.size();
  214926. ors.itemRefs = docRefs;
  214927. ors.passThruParams = 0;
  214928. ors.launchFlags = kLSLaunchDefaults;
  214929. ors.asyncRefCon = 0;
  214930. FSRef actual;
  214931. ok = (LSOpenFromRefSpec (&ors, &actual) == noErr);
  214932. delete docRefs;
  214933. }
  214934. else
  214935. {
  214936. if (parameters.isNotEmpty())
  214937. ok = juce_launchExecutable (T("\"") + fileName + T("\" ") + parameters);
  214938. else
  214939. ok = (LSOpenFSRef (&ref, 0) == noErr);
  214940. }
  214941. }
  214942. }
  214943. return ok;
  214944. }
  214945. bool PlatformUtilities::makeFSSpecFromPath (FSSpec* fs, const String& path)
  214946. {
  214947. FSRef ref;
  214948. return makeFSRefFromPath (&ref, path)
  214949. && FSGetCatalogInfo (&ref, kFSCatInfoNone, 0, 0, fs, 0) == noErr;
  214950. }
  214951. bool PlatformUtilities::makeFSRefFromPath (FSRef* destFSRef, const String& path)
  214952. {
  214953. return FSPathMakeRef ((const UInt8*) path.toUTF8(), destFSRef, 0) == noErr;
  214954. }
  214955. const String PlatformUtilities::makePathFromFSRef (FSRef* file)
  214956. {
  214957. uint8 path [2048];
  214958. zeromem (path, sizeof (path));
  214959. String result;
  214960. if (FSRefMakePath (file, (UInt8*) path, sizeof (path) - 1) == noErr)
  214961. result = String::fromUTF8 (path);
  214962. return PlatformUtilities::convertToPrecomposedUnicode (result);
  214963. }
  214964. OSType PlatformUtilities::getTypeOfFile (const String& filename)
  214965. {
  214966. FSRef fs;
  214967. if (makeFSRefFromPath (&fs, filename))
  214968. {
  214969. LSItemInfoRecord info;
  214970. if (LSCopyItemInfoForRef (&fs, kLSRequestTypeCreator, &info) == noErr)
  214971. return info.filetype;
  214972. }
  214973. return 0;
  214974. }
  214975. bool PlatformUtilities::isBundle (const String& filename)
  214976. {
  214977. FSRef fs;
  214978. if (makeFSRefFromPath (&fs, filename))
  214979. {
  214980. LSItemInfoRecord info;
  214981. if (LSCopyItemInfoForRef (&fs, kLSItemInfoIsPackage, &info) == noErr)
  214982. return (info.flags & kLSItemInfoIsPackage) != 0;
  214983. }
  214984. return false;
  214985. }
  214986. END_JUCE_NAMESPACE
  214987. /********* End of inlined file: juce_mac_Files.cpp *********/
  214988. /********* Start of inlined file: juce_mac_NamedPipe.cpp *********/
  214989. #include <sys/stat.h>
  214990. #include <sys/dir.h>
  214991. #include <fcntl.h>
  214992. // As well as being for the mac, this file is included by the linux build.
  214993. #if JUCE_MAC
  214994. #include <Carbon/Carbon.h>
  214995. #else
  214996. #include <sys/wait.h>
  214997. #include <errno.h>
  214998. #include <unistd.h>
  214999. #endif
  215000. BEGIN_JUCE_NAMESPACE
  215001. struct NamedPipeInternal
  215002. {
  215003. String pipeInName, pipeOutName;
  215004. int pipeIn, pipeOut;
  215005. bool volatile createdPipe, blocked, stopReadOperation;
  215006. static void signalHandler (int) {}
  215007. };
  215008. void NamedPipe::cancelPendingReads()
  215009. {
  215010. while (internal != 0 && ((NamedPipeInternal*) internal)->blocked)
  215011. {
  215012. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  215013. intern->stopReadOperation = true;
  215014. char buffer [1] = { 0 };
  215015. ::write (intern->pipeIn, buffer, 1);
  215016. int timeout = 2000;
  215017. while (intern->blocked && --timeout >= 0)
  215018. sleep (2);
  215019. intern->stopReadOperation = false;
  215020. }
  215021. }
  215022. void NamedPipe::close()
  215023. {
  215024. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  215025. if (intern != 0)
  215026. {
  215027. internal = 0;
  215028. if (intern->pipeIn != -1)
  215029. ::close (intern->pipeIn);
  215030. if (intern->pipeOut != -1)
  215031. ::close (intern->pipeOut);
  215032. if (intern->createdPipe)
  215033. {
  215034. unlink (intern->pipeInName);
  215035. unlink (intern->pipeOutName);
  215036. }
  215037. delete intern;
  215038. }
  215039. }
  215040. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  215041. {
  215042. close();
  215043. NamedPipeInternal* const intern = new NamedPipeInternal();
  215044. internal = intern;
  215045. intern->createdPipe = createPipe;
  215046. intern->blocked = false;
  215047. intern->stopReadOperation = false;
  215048. signal (SIGPIPE, NamedPipeInternal::signalHandler);
  215049. siginterrupt (SIGPIPE, 1);
  215050. const String pipePath (T("/tmp/") + File::createLegalFileName (pipeName));
  215051. intern->pipeInName = pipePath + T("_in");
  215052. intern->pipeOutName = pipePath + T("_out");
  215053. intern->pipeIn = -1;
  215054. intern->pipeOut = -1;
  215055. if (createPipe)
  215056. {
  215057. if ((mkfifo (intern->pipeInName, 0666) && errno != EEXIST)
  215058. || (mkfifo (intern->pipeOutName, 0666) && errno != EEXIST))
  215059. {
  215060. delete intern;
  215061. internal = 0;
  215062. return false;
  215063. }
  215064. }
  215065. return true;
  215066. }
  215067. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int /*timeOutMilliseconds*/)
  215068. {
  215069. int bytesRead = -1;
  215070. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  215071. if (intern != 0)
  215072. {
  215073. intern->blocked = true;
  215074. if (intern->pipeIn == -1)
  215075. {
  215076. if (intern->createdPipe)
  215077. intern->pipeIn = ::open (intern->pipeInName, O_RDWR);
  215078. else
  215079. intern->pipeIn = ::open (intern->pipeOutName, O_RDWR);
  215080. if (intern->pipeIn == -1)
  215081. {
  215082. intern->blocked = false;
  215083. return -1;
  215084. }
  215085. }
  215086. bytesRead = 0;
  215087. char* p = (char*) destBuffer;
  215088. while (bytesRead < maxBytesToRead)
  215089. {
  215090. const int bytesThisTime = maxBytesToRead - bytesRead;
  215091. const int numRead = ::read (intern->pipeIn, p, bytesThisTime);
  215092. if (numRead <= 0 || intern->stopReadOperation)
  215093. {
  215094. bytesRead = -1;
  215095. break;
  215096. }
  215097. bytesRead += numRead;
  215098. p += bytesRead;
  215099. }
  215100. intern->blocked = false;
  215101. }
  215102. return bytesRead;
  215103. }
  215104. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  215105. {
  215106. int bytesWritten = -1;
  215107. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  215108. if (intern != 0)
  215109. {
  215110. if (intern->pipeOut == -1)
  215111. {
  215112. if (intern->createdPipe)
  215113. intern->pipeOut = ::open (intern->pipeOutName, O_WRONLY);
  215114. else
  215115. intern->pipeOut = ::open (intern->pipeInName, O_WRONLY);
  215116. if (intern->pipeOut == -1)
  215117. {
  215118. return -1;
  215119. }
  215120. }
  215121. const char* p = (const char*) sourceBuffer;
  215122. bytesWritten = 0;
  215123. const uint32 timeOutTime = Time::getMillisecondCounter() + timeOutMilliseconds;
  215124. while (bytesWritten < numBytesToWrite
  215125. && (timeOutMilliseconds < 0 || Time::getMillisecondCounter() < timeOutTime))
  215126. {
  215127. const int bytesThisTime = numBytesToWrite - bytesWritten;
  215128. const int numWritten = ::write (intern->pipeOut, p, bytesThisTime);
  215129. if (numWritten <= 0)
  215130. {
  215131. bytesWritten = -1;
  215132. break;
  215133. }
  215134. bytesWritten += numWritten;
  215135. p += bytesWritten;
  215136. }
  215137. }
  215138. return bytesWritten;
  215139. }
  215140. END_JUCE_NAMESPACE
  215141. /********* End of inlined file: juce_mac_NamedPipe.cpp *********/
  215142. /********* Start of inlined file: juce_mac_SystemStats.mm *********/
  215143. #include <AppKit/AppKit.h>
  215144. #include <Carbon/Carbon.h>
  215145. #include <CoreAudio/HostTime.h>
  215146. #include <ctime>
  215147. #include <sys/resource.h>
  215148. BEGIN_JUCE_NAMESPACE
  215149. static int64 highResTimerFrequency;
  215150. #if JUCE_INTEL
  215151. static void juce_getCpuVendor (char* const v) throw()
  215152. {
  215153. int vendor[4];
  215154. zerostruct (vendor);
  215155. int dummy = 0;
  215156. asm ("mov %%ebx, %%esi \n\t"
  215157. "cpuid \n\t"
  215158. "xchg %%esi, %%ebx"
  215159. : "=a" (dummy), "=S" (vendor[0]), "=c" (vendor[2]), "=d" (vendor[1]) : "a" (0));
  215160. memcpy (v, vendor, 16);
  215161. }
  215162. static unsigned int getCPUIDWord (unsigned int& familyModel, unsigned int& extFeatures) throw()
  215163. {
  215164. unsigned int cpu = 0;
  215165. unsigned int ext = 0;
  215166. unsigned int family = 0;
  215167. unsigned int dummy = 0;
  215168. asm ("mov %%ebx, %%esi \n\t"
  215169. "cpuid \n\t"
  215170. "xchg %%esi, %%ebx"
  215171. : "=a" (family), "=S" (ext), "=c" (dummy), "=d" (cpu) : "a" (1));
  215172. familyModel = family;
  215173. extFeatures = ext;
  215174. return cpu;
  215175. }
  215176. struct CPUFlags
  215177. {
  215178. bool hasMMX : 1;
  215179. bool hasSSE : 1;
  215180. bool hasSSE2 : 1;
  215181. bool has3DNow : 1;
  215182. };
  215183. static CPUFlags cpuFlags;
  215184. #endif
  215185. void Logger::outputDebugString (const String& text) throw()
  215186. {
  215187. String withLineFeed (text + T("\n"));
  215188. const char* const utf8 = withLineFeed.toUTF8();
  215189. fwrite (utf8, strlen (utf8), 1, stdout);
  215190. }
  215191. void Logger::outputDebugPrintf (const tchar* format, ...) throw()
  215192. {
  215193. String text;
  215194. va_list args;
  215195. va_start (args, format);
  215196. text.vprintf(format, args);
  215197. outputDebugString (text);
  215198. }
  215199. int SystemStats::getMemorySizeInMegabytes() throw()
  215200. {
  215201. long bytes;
  215202. if (Gestalt (gestaltPhysicalRAMSize, &bytes) == noErr)
  215203. return (int) (((unsigned long) bytes) / (1024 * 1024));
  215204. return 0;
  215205. }
  215206. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType() throw()
  215207. {
  215208. return MacOSX;
  215209. }
  215210. const String SystemStats::getOperatingSystemName() throw()
  215211. {
  215212. return T("Mac OS X");
  215213. }
  215214. bool SystemStats::isOperatingSystem64Bit() throw()
  215215. {
  215216. #if JUCE_64BIT
  215217. return true;
  215218. #else
  215219. //xxx not sure how to find this out?..
  215220. return false;
  215221. #endif
  215222. }
  215223. void SystemStats::initialiseStats() throw()
  215224. {
  215225. static bool initialised = false;
  215226. if (! initialised)
  215227. {
  215228. initialised = true;
  215229. NSApplicationLoad();
  215230. #if JUCE_INTEL
  215231. {
  215232. unsigned int familyModel, extFeatures;
  215233. const unsigned int features = getCPUIDWord (familyModel, extFeatures);
  215234. cpuFlags.hasMMX = ((features & (1 << 23)) != 0);
  215235. cpuFlags.hasSSE = ((features & (1 << 25)) != 0);
  215236. cpuFlags.hasSSE2 = ((features & (1 << 26)) != 0);
  215237. cpuFlags.has3DNow = ((extFeatures & (1 << 31)) != 0);
  215238. }
  215239. #endif
  215240. highResTimerFrequency = (int64) AudioGetHostClockFrequency();
  215241. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  215242. if (JUCEApplication::getInstance() != 0)
  215243. RegisterAppearanceClient();
  215244. #endif
  215245. TXNInitTextension (0, 0, kTXNWantMoviesMask | kTXNWantGraphicsMask);
  215246. String s (SystemStats::getJUCEVersion());
  215247. rlimit lim;
  215248. getrlimit (RLIMIT_NOFILE, &lim);
  215249. lim.rlim_cur = lim.rlim_max = RLIM_INFINITY;
  215250. setrlimit (RLIMIT_NOFILE, &lim);
  215251. }
  215252. }
  215253. bool SystemStats::hasMMX() throw()
  215254. {
  215255. #if JUCE_INTEL
  215256. return cpuFlags.hasMMX;
  215257. #else
  215258. return false;
  215259. #endif
  215260. }
  215261. bool SystemStats::hasSSE() throw()
  215262. {
  215263. #if JUCE_INTEL
  215264. return cpuFlags.hasSSE;
  215265. #else
  215266. return false;
  215267. #endif
  215268. }
  215269. bool SystemStats::hasSSE2() throw()
  215270. {
  215271. #if JUCE_INTEL
  215272. return cpuFlags.hasSSE2;
  215273. #else
  215274. return false;
  215275. #endif
  215276. }
  215277. bool SystemStats::has3DNow() throw()
  215278. {
  215279. #if JUCE_INTEL
  215280. return cpuFlags.has3DNow;
  215281. #else
  215282. return false;
  215283. #endif
  215284. }
  215285. const String SystemStats::getCpuVendor() throw()
  215286. {
  215287. #if JUCE_INTEL
  215288. char v [16];
  215289. juce_getCpuVendor (v);
  215290. return String (v, 16);
  215291. #else
  215292. return String::empty;
  215293. #endif
  215294. }
  215295. int SystemStats::getCpuSpeedInMegaherz() throw()
  215296. {
  215297. return GetCPUSpeed();
  215298. }
  215299. int SystemStats::getNumCpus() throw()
  215300. {
  215301. return MPProcessors();
  215302. }
  215303. static int64 juce_getMicroseconds() throw()
  215304. {
  215305. UnsignedWide t;
  215306. Microseconds (&t);
  215307. return (((int64) t.hi) << 32) | t.lo;
  215308. }
  215309. uint32 juce_millisecondsSinceStartup() throw()
  215310. {
  215311. return (uint32) (juce_getMicroseconds() / 1000);
  215312. }
  215313. double Time::getMillisecondCounterHiRes() throw()
  215314. {
  215315. // xxx might be more accurate to use a scaled AudioGetCurrentHostTime?
  215316. return juce_getMicroseconds() * 0.001;
  215317. }
  215318. int64 Time::getHighResolutionTicks() throw()
  215319. {
  215320. return (int64) AudioGetCurrentHostTime();
  215321. }
  215322. int64 Time::getHighResolutionTicksPerSecond() throw()
  215323. {
  215324. return highResTimerFrequency;
  215325. }
  215326. int64 SystemStats::getClockCycleCounter() throw()
  215327. {
  215328. jassertfalse
  215329. return 0;
  215330. }
  215331. bool Time::setSystemTimeToThisTime() const throw()
  215332. {
  215333. jassertfalse
  215334. return false;
  215335. }
  215336. int SystemStats::getPageSize() throw()
  215337. {
  215338. jassertfalse
  215339. return 512; //xxx
  215340. }
  215341. void PlatformUtilities::fpuReset()
  215342. {
  215343. }
  215344. END_JUCE_NAMESPACE
  215345. /********* End of inlined file: juce_mac_SystemStats.mm *********/
  215346. /********* Start of inlined file: juce_mac_Threads.cpp *********/
  215347. #include <pthread.h>
  215348. #include <sched.h>
  215349. #include <sys/file.h>
  215350. #include <sys/types.h>
  215351. #include <sys/sysctl.h>
  215352. #include <Carbon/Carbon.h>
  215353. BEGIN_JUCE_NAMESPACE
  215354. /*
  215355. Note that a lot of methods that you'd expect to find in this file actually
  215356. live in juce_posix_SharedCode.cpp!
  215357. */
  215358. void JUCE_API juce_threadEntryPoint (void*);
  215359. void* threadEntryProc (void* userData) throw()
  215360. {
  215361. juce_threadEntryPoint (userData);
  215362. return 0;
  215363. }
  215364. void* juce_createThread (void* userData) throw()
  215365. {
  215366. pthread_t handle = 0;
  215367. if (pthread_create (&handle, 0, threadEntryProc, userData) == 0)
  215368. {
  215369. pthread_detach (handle);
  215370. return (void*) handle;
  215371. }
  215372. return 0;
  215373. }
  215374. void juce_killThread (void* handle) throw()
  215375. {
  215376. if (handle != 0)
  215377. pthread_cancel ((pthread_t) handle);
  215378. }
  215379. void juce_setCurrentThreadName (const String& /*name*/) throw()
  215380. {
  215381. }
  215382. int Thread::getCurrentThreadId() throw()
  215383. {
  215384. return (int) pthread_self();
  215385. }
  215386. void juce_setThreadPriority (void* handle, int priority) throw()
  215387. {
  215388. if (handle == 0)
  215389. handle = (void*) pthread_self();
  215390. struct sched_param param;
  215391. int policy;
  215392. pthread_getschedparam ((pthread_t) handle, &policy, &param);
  215393. param.sched_priority = jlimit (1, 127, 1 + (priority * 126) / 11);
  215394. pthread_setschedparam ((pthread_t) handle, policy, &param);
  215395. }
  215396. void Thread::yield() throw()
  215397. {
  215398. sched_yield();
  215399. }
  215400. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask) throw()
  215401. {
  215402. // xxx
  215403. jassertfalse
  215404. }
  215405. bool JUCE_CALLTYPE juce_isRunningUnderDebugger() throw()
  215406. {
  215407. static char testResult = 0;
  215408. if (testResult == 0)
  215409. {
  215410. struct kinfo_proc info;
  215411. int m[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, getpid() };
  215412. size_t sz = sizeof (info);
  215413. sysctl (m, 4, &info, &sz, 0, 0);
  215414. testResult = ((info.kp_proc.p_flag & P_TRACED) != 0) ? 1 : -1;
  215415. }
  215416. return testResult > 0;
  215417. }
  215418. bool JUCE_CALLTYPE Process::isRunningUnderDebugger() throw()
  215419. {
  215420. return juce_isRunningUnderDebugger();
  215421. }
  215422. void Process::raisePrivilege()
  215423. {
  215424. jassertfalse
  215425. }
  215426. void Process::lowerPrivilege()
  215427. {
  215428. jassertfalse
  215429. }
  215430. void Process::terminate()
  215431. {
  215432. ExitToShell();
  215433. }
  215434. void Process::setPriority (ProcessPriority p)
  215435. {
  215436. // xxx
  215437. }
  215438. void* Process::loadDynamicLibrary (const String& name)
  215439. {
  215440. // xxx needs to use bundles
  215441. FSSpec fs;
  215442. if (PlatformUtilities::makeFSSpecFromPath (&fs, name))
  215443. {
  215444. CFragConnectionID connID;
  215445. Ptr mainPtr;
  215446. Str255 errorMessage;
  215447. Str63 nm;
  215448. PlatformUtilities::copyToStr63 (nm, name);
  215449. const OSErr err = GetDiskFragment (&fs, 0, kCFragGoesToEOF, nm, kReferenceCFrag, &connID, &mainPtr, errorMessage);
  215450. if (err == noErr)
  215451. return (void*)connID;
  215452. }
  215453. return 0;
  215454. }
  215455. void Process::freeDynamicLibrary (void* handle)
  215456. {
  215457. if (handle != 0)
  215458. CloseConnection ((CFragConnectionID*)&handle);
  215459. }
  215460. void* Process::getProcedureEntryPoint (void* h, const String& procedureName)
  215461. {
  215462. if (h != 0)
  215463. {
  215464. CFragSymbolClass cl;
  215465. Ptr ptr;
  215466. Str255 name;
  215467. PlatformUtilities::copyToStr255 (name, procedureName);
  215468. if (FindSymbol ((CFragConnectionID) h, name, &ptr, &cl) == noErr)
  215469. {
  215470. return ptr;
  215471. }
  215472. }
  215473. return 0;
  215474. }
  215475. END_JUCE_NAMESPACE
  215476. /********* End of inlined file: juce_mac_Threads.cpp *********/
  215477. /********* Start of inlined file: juce_mac_Network.mm *********/
  215478. #include <Cocoa/Cocoa.h>
  215479. #include <IOKit/IOKitLib.h>
  215480. #include <IOKit/network/IOEthernetInterface.h>
  215481. #include <IOKit/network/IONetworkInterface.h>
  215482. #include <IOKit/network/IOEthernetController.h>
  215483. #include <netdb.h>
  215484. #include <arpa/inet.h>
  215485. #include <netinet/in.h>
  215486. #include <sys/types.h>
  215487. #include <sys/socket.h>
  215488. #include <sys/wait.h>
  215489. BEGIN_JUCE_NAMESPACE
  215490. /********* Start of inlined file: juce_mac_HTTPStream.h *********/
  215491. // (This file gets included by the mac + linux networking code)
  215492. /** A HTTP input stream that uses sockets.
  215493. */
  215494. class JUCE_HTTPSocketStream
  215495. {
  215496. public:
  215497. JUCE_HTTPSocketStream()
  215498. : readPosition (0),
  215499. socketHandle (-1),
  215500. levelsOfRedirection (0),
  215501. timeoutSeconds (15)
  215502. {
  215503. }
  215504. ~JUCE_HTTPSocketStream()
  215505. {
  215506. closeSocket();
  215507. }
  215508. bool open (const String& url,
  215509. const String& headers,
  215510. const MemoryBlock& postData,
  215511. const bool isPost,
  215512. URL::OpenStreamProgressCallback* callback,
  215513. void* callbackContext)
  215514. {
  215515. closeSocket();
  215516. String hostName, hostPath;
  215517. int hostPort;
  215518. if (! decomposeURL (url, hostName, hostPath, hostPort))
  215519. return false;
  215520. struct hostent* const host
  215521. = gethostbyname ((const char*) hostName.toUTF8());
  215522. if (host == 0)
  215523. return false;
  215524. struct sockaddr_in address;
  215525. zerostruct (address);
  215526. memcpy ((void*) &address.sin_addr, (const void*) host->h_addr, host->h_length);
  215527. address.sin_family = host->h_addrtype;
  215528. address.sin_port = htons (hostPort);
  215529. socketHandle = socket (host->h_addrtype, SOCK_STREAM, 0);
  215530. if (socketHandle == -1)
  215531. return false;
  215532. int receiveBufferSize = 16384;
  215533. setsockopt (socketHandle, SOL_SOCKET, SO_RCVBUF, (char*) &receiveBufferSize, sizeof (receiveBufferSize));
  215534. setsockopt (socketHandle, SOL_SOCKET, SO_KEEPALIVE, 0, 0);
  215535. #if JUCE_MAC
  215536. setsockopt (socketHandle, SOL_SOCKET, SO_NOSIGPIPE, 0, 0);
  215537. #endif
  215538. if (connect (socketHandle, (struct sockaddr*) &address, sizeof (address)) == -1)
  215539. {
  215540. closeSocket();
  215541. return false;
  215542. }
  215543. String proxyURL (getenv ("http_proxy"));
  215544. if (! proxyURL.startsWithIgnoreCase (T("http://")))
  215545. proxyURL = String::empty;
  215546. const MemoryBlock requestHeader (createRequestHeader (hostName, hostPath,
  215547. proxyURL, url,
  215548. hostPort,
  215549. headers, postData,
  215550. isPost));
  215551. int totalHeaderSent = 0;
  215552. while (totalHeaderSent < requestHeader.getSize())
  215553. {
  215554. const int numToSend = jmin (1024, requestHeader.getSize() - totalHeaderSent);
  215555. if (send (socketHandle,
  215556. ((const char*) requestHeader.getData()) + totalHeaderSent,
  215557. numToSend, 0)
  215558. != numToSend)
  215559. {
  215560. closeSocket();
  215561. return false;
  215562. }
  215563. totalHeaderSent += numToSend;
  215564. if (callback != 0 && ! callback (callbackContext, totalHeaderSent, requestHeader.getSize()))
  215565. {
  215566. closeSocket();
  215567. return false;
  215568. }
  215569. }
  215570. const String responseHeader (readResponse());
  215571. if (responseHeader.isNotEmpty())
  215572. {
  215573. //DBG (responseHeader);
  215574. StringArray lines;
  215575. lines.addLines (responseHeader);
  215576. // NB - using charToString() here instead of just T(" "), because that was
  215577. // causing a mysterious gcc internal compiler error...
  215578. const int statusCode = responseHeader.fromFirstOccurrenceOf (String::charToString (T(' ')), false, false)
  215579. .substring (0, 3)
  215580. .getIntValue();
  215581. //int contentLength = findHeaderItem (lines, T("Content-Length:")).getIntValue();
  215582. //bool isChunked = findHeaderItem (lines, T("Transfer-Encoding:")).equalsIgnoreCase ("chunked");
  215583. String location (findHeaderItem (lines, T("Location:")));
  215584. if (statusCode >= 300 && statusCode < 400
  215585. && location.isNotEmpty())
  215586. {
  215587. if (! location.startsWithIgnoreCase (T("http://")))
  215588. location = T("http://") + location;
  215589. if (levelsOfRedirection++ < 3)
  215590. return open (location, headers, postData, isPost, callback, callbackContext);
  215591. }
  215592. else
  215593. {
  215594. levelsOfRedirection = 0;
  215595. return true;
  215596. }
  215597. }
  215598. closeSocket();
  215599. return false;
  215600. }
  215601. int read (void* buffer, int bytesToRead)
  215602. {
  215603. fd_set readbits;
  215604. FD_ZERO (&readbits);
  215605. FD_SET (socketHandle, &readbits);
  215606. struct timeval tv;
  215607. tv.tv_sec = timeoutSeconds;
  215608. tv.tv_usec = 0;
  215609. if (select (socketHandle + 1, &readbits, 0, 0, &tv) <= 0)
  215610. return 0; // (timeout)
  215611. const int bytesRead = jmax (0, recv (socketHandle, buffer, bytesToRead, MSG_WAITALL));
  215612. readPosition += bytesRead;
  215613. return bytesRead;
  215614. }
  215615. int readPosition;
  215616. juce_UseDebuggingNewOperator
  215617. private:
  215618. int socketHandle, levelsOfRedirection;
  215619. const int timeoutSeconds;
  215620. void closeSocket()
  215621. {
  215622. if (socketHandle >= 0)
  215623. close (socketHandle);
  215624. socketHandle = -1;
  215625. }
  215626. const MemoryBlock createRequestHeader (const String& hostName,
  215627. const String& hostPath,
  215628. const String& proxyURL,
  215629. const String& originalURL,
  215630. const int hostPort,
  215631. const String& headers,
  215632. const MemoryBlock& postData,
  215633. const bool isPost)
  215634. {
  215635. String header (isPost ? "POST " : "GET ");
  215636. if (proxyURL.isEmpty())
  215637. {
  215638. header << hostPath << " HTTP/1.0\r\nHost: "
  215639. << hostName << ':' << hostPort;
  215640. }
  215641. else
  215642. {
  215643. String proxyName, proxyPath;
  215644. int proxyPort;
  215645. if (! decomposeURL (proxyURL, proxyName, proxyPath, proxyPort))
  215646. return MemoryBlock();
  215647. header << originalURL << " HTTP/1.0\r\nHost: "
  215648. << proxyName << ':' << proxyPort;
  215649. /* xxx needs finishing
  215650. const char* proxyAuth = getenv ("http_proxy_auth");
  215651. if (proxyAuth != 0)
  215652. header << T("\r\nProxy-Authorization: ") << Base64Encode (proxyAuth);
  215653. */
  215654. }
  215655. header << "\r\nUser-Agent: JUCE/"
  215656. << JUCE_MAJOR_VERSION << '.' << JUCE_MINOR_VERSION
  215657. << "\r\nConnection: Close\r\nContent-Length: "
  215658. << postData.getSize() << "\r\n"
  215659. << headers << "\r\n";
  215660. MemoryBlock mb;
  215661. mb.append (header.toUTF8(), (int) strlen (header.toUTF8()));
  215662. mb.append (postData.getData(), postData.getSize());
  215663. return mb;
  215664. }
  215665. const String readResponse()
  215666. {
  215667. int bytesRead = 0, numConsecutiveLFs = 0;
  215668. MemoryBlock buffer (1024, true);
  215669. while (numConsecutiveLFs < 2 && bytesRead < 32768)
  215670. {
  215671. fd_set readbits;
  215672. FD_ZERO (&readbits);
  215673. FD_SET (socketHandle, &readbits);
  215674. struct timeval tv;
  215675. tv.tv_sec = timeoutSeconds;
  215676. tv.tv_usec = 0;
  215677. if (select (socketHandle + 1, &readbits, 0, 0, &tv) <= 0)
  215678. return String::empty; // (timeout)
  215679. buffer.ensureSize (bytesRead + 8, true);
  215680. char* const dest = (char*) buffer.getData() + bytesRead;
  215681. if (recv (socketHandle, dest, 1, 0) == -1)
  215682. return String::empty;
  215683. const char lastByte = *dest;
  215684. ++bytesRead;
  215685. if (lastByte == '\n')
  215686. ++numConsecutiveLFs;
  215687. else if (lastByte != '\r')
  215688. numConsecutiveLFs = 0;
  215689. }
  215690. const String header (String::fromUTF8 ((const uint8*) buffer.getData()));
  215691. if (header.startsWithIgnoreCase (T("HTTP/")))
  215692. return header.trimEnd();
  215693. return String::empty;
  215694. }
  215695. static bool decomposeURL (const String& url,
  215696. String& host, String& path, int& port)
  215697. {
  215698. if (! url.startsWithIgnoreCase (T("http://")))
  215699. return false;
  215700. const int nextSlash = url.indexOfChar (7, '/');
  215701. int nextColon = url.indexOfChar (7, ':');
  215702. if (nextColon > nextSlash && nextSlash > 0)
  215703. nextColon = -1;
  215704. if (nextColon >= 0)
  215705. {
  215706. host = url.substring (7, nextColon);
  215707. if (nextSlash >= 0)
  215708. port = url.substring (nextColon + 1, nextSlash).getIntValue();
  215709. else
  215710. port = url.substring (nextColon + 1).getIntValue();
  215711. }
  215712. else
  215713. {
  215714. port = 80;
  215715. if (nextSlash >= 0)
  215716. host = url.substring (7, nextSlash);
  215717. else
  215718. host = url.substring (7);
  215719. }
  215720. if (nextSlash >= 0)
  215721. path = url.substring (nextSlash);
  215722. else
  215723. path = T("/");
  215724. return true;
  215725. }
  215726. static const String findHeaderItem (const StringArray& lines, const String& itemName)
  215727. {
  215728. for (int i = 0; i < lines.size(); ++i)
  215729. if (lines[i].startsWithIgnoreCase (itemName))
  215730. return lines[i].substring (itemName.length()).trim();
  215731. return String::empty;
  215732. }
  215733. };
  215734. bool juce_isOnLine()
  215735. {
  215736. return true;
  215737. }
  215738. void* juce_openInternetFile (const String& url,
  215739. const String& headers,
  215740. const MemoryBlock& postData,
  215741. const bool isPost,
  215742. URL::OpenStreamProgressCallback* callback,
  215743. void* callbackContext)
  215744. {
  215745. JUCE_HTTPSocketStream* const s = new JUCE_HTTPSocketStream();
  215746. if (s->open (url, headers, postData, isPost,
  215747. callback, callbackContext))
  215748. return s;
  215749. delete s;
  215750. return 0;
  215751. }
  215752. void juce_closeInternetFile (void* handle)
  215753. {
  215754. JUCE_HTTPSocketStream* const s = (JUCE_HTTPSocketStream*) handle;
  215755. if (s != 0)
  215756. delete s;
  215757. }
  215758. int juce_readFromInternetFile (void* handle, void* buffer, int bytesToRead)
  215759. {
  215760. JUCE_HTTPSocketStream* const s = (JUCE_HTTPSocketStream*) handle;
  215761. if (s != 0)
  215762. return s->read (buffer, bytesToRead);
  215763. return 0;
  215764. }
  215765. int juce_seekInInternetFile (void* handle, int newPosition)
  215766. {
  215767. JUCE_HTTPSocketStream* const s = (JUCE_HTTPSocketStream*) handle;
  215768. if (s != 0)
  215769. return s->readPosition;
  215770. return 0;
  215771. }
  215772. /********* End of inlined file: juce_mac_HTTPStream.h *********/
  215773. static bool GetEthernetIterator (io_iterator_t* matchingServices) throw()
  215774. {
  215775. mach_port_t masterPort;
  215776. if (IOMasterPort (MACH_PORT_NULL, &masterPort) == KERN_SUCCESS)
  215777. {
  215778. CFMutableDictionaryRef dict = IOServiceMatching (kIOEthernetInterfaceClass);
  215779. if (dict != 0)
  215780. {
  215781. CFMutableDictionaryRef propDict = CFDictionaryCreateMutable (kCFAllocatorDefault,
  215782. 0,
  215783. &kCFTypeDictionaryKeyCallBacks,
  215784. &kCFTypeDictionaryValueCallBacks);
  215785. if (propDict != 0)
  215786. {
  215787. CFDictionarySetValue (propDict, CFSTR (kIOPrimaryInterface), kCFBooleanTrue);
  215788. CFDictionarySetValue (dict, CFSTR (kIOPropertyMatchKey), propDict);
  215789. CFRelease (propDict);
  215790. }
  215791. }
  215792. return IOServiceGetMatchingServices (masterPort, dict, matchingServices) == KERN_SUCCESS;
  215793. }
  215794. return false;
  215795. }
  215796. int SystemStats::getMACAddresses (int64* addresses, int maxNum, const bool littleEndian) throw()
  215797. {
  215798. int numResults = 0;
  215799. io_iterator_t it;
  215800. if (GetEthernetIterator (&it))
  215801. {
  215802. io_object_t i;
  215803. while ((i = IOIteratorNext (it)) != 0)
  215804. {
  215805. io_object_t controller;
  215806. if (IORegistryEntryGetParentEntry (i, kIOServicePlane, &controller) == KERN_SUCCESS)
  215807. {
  215808. CFTypeRef data = IORegistryEntryCreateCFProperty (controller,
  215809. CFSTR (kIOMACAddress),
  215810. kCFAllocatorDefault,
  215811. 0);
  215812. if (data != 0)
  215813. {
  215814. UInt8 addr [kIOEthernetAddressSize];
  215815. zeromem (addr, sizeof (addr));
  215816. CFDataGetBytes ((CFDataRef) data, CFRangeMake (0, sizeof (addr)), addr);
  215817. CFRelease (data);
  215818. int64 a = 0;
  215819. for (int i = 6; --i >= 0;)
  215820. a = (a << 8) | addr[i];
  215821. if (! littleEndian)
  215822. a = (int64) swapByteOrder ((uint64) a);
  215823. if (numResults < maxNum)
  215824. {
  215825. *addresses++ = a;
  215826. ++numResults;
  215827. }
  215828. }
  215829. IOObjectRelease (controller);
  215830. }
  215831. IOObjectRelease (i);
  215832. }
  215833. IOObjectRelease (it);
  215834. }
  215835. return numResults;
  215836. }
  215837. class AutoPool
  215838. {
  215839. public:
  215840. AutoPool() { pool = [[NSAutoreleasePool alloc] init]; }
  215841. ~AutoPool() { [pool release]; }
  215842. private:
  215843. NSAutoreleasePool* pool;
  215844. };
  215845. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  215846. const String& emailSubject,
  215847. const String& bodyText,
  215848. const StringArray& filesToAttach)
  215849. {
  215850. const AutoPool pool;
  215851. String script;
  215852. script << "tell application \"Mail\"\r\n"
  215853. "set newMessage to make new outgoing message with properties {subject:\""
  215854. << emailSubject.replace (T("\""), T("\\\""))
  215855. << "\", content:\""
  215856. << bodyText.replace (T("\""), T("\\\""))
  215857. << "\" & return & return}\r\n"
  215858. "tell newMessage\r\n"
  215859. "set visible to true\r\n"
  215860. "set sender to \"sdfsdfsdfewf\"\r\n"
  215861. "make new to recipient at end of to recipients with properties {address:\""
  215862. << targetEmailAddress
  215863. << "\"}\r\n";
  215864. for (int i = 0; i < filesToAttach.size(); ++i)
  215865. {
  215866. script << "tell content\r\n"
  215867. "make new attachment with properties {file name:\""
  215868. << filesToAttach[i].replace (T("\""), T("\\\""))
  215869. << "\"} at after the last paragraph\r\n"
  215870. "end tell\r\n";
  215871. }
  215872. script << "end tell\r\n"
  215873. "end tell\r\n";
  215874. NSAppleScript* s = [[NSAppleScript alloc]
  215875. initWithSource: [NSString stringWithUTF8String: (const char*) script.toUTF8()]];
  215876. NSDictionary* error = 0;
  215877. const bool ok = [s executeAndReturnError: &error] != nil;
  215878. [s release];
  215879. return ok;
  215880. }
  215881. END_JUCE_NAMESPACE
  215882. /********* End of inlined file: juce_mac_Network.mm *********/
  215883. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  215884. /********* Start of inlined file: juce_mac_AudioCDBurner.mm *********/
  215885. #if JUCE_USE_CDBURNER
  215886. #import <Cocoa/Cocoa.h>
  215887. #import <DiscRecording/DiscRecording.h>
  215888. BEGIN_JUCE_NAMESPACE
  215889. END_JUCE_NAMESPACE
  215890. @interface OpenDiskDevice : NSObject
  215891. {
  215892. DRDevice* device;
  215893. NSMutableArray* tracks;
  215894. }
  215895. - (OpenDiskDevice*) initWithDevice: (DRDevice*) device;
  215896. - (void) dealloc;
  215897. - (bool) isDiskPresent;
  215898. - (int) getNumAvailableAudioBlocks;
  215899. - (void) addSourceTrack: (juce::AudioSource*) source numSamples: (int) numSamples_;
  215900. - (void) burn: (juce::AudioCDBurner::BurnProgressListener*) listener errorString: (juce::String*) error
  215901. ejectAfterwards: (bool) shouldEject isFake: (bool) peformFakeBurnForTesting;
  215902. @end
  215903. @interface AudioTrackProducer : NSObject
  215904. {
  215905. juce::AudioSource* source;
  215906. int readPosition, lengthInFrames;
  215907. }
  215908. - (AudioTrackProducer*) init: (int) lengthInFrames;
  215909. - (AudioTrackProducer*) initWithAudioSource: (juce::AudioSource*) source numSamples: (int) lengthInSamples;
  215910. - (void) dealloc;
  215911. - (void) setupTrackProperties: (DRTrack*) track;
  215912. - (void) cleanupTrackAfterBurn: (DRTrack*) track;
  215913. - (BOOL) cleanupTrackAfterVerification:(DRTrack*)track;
  215914. - (uint64_t) estimateLengthOfTrack:(DRTrack*)track;
  215915. - (BOOL) prepareTrack:(DRTrack*)track forBurn:(DRBurn*)burn
  215916. toMedia:(NSDictionary*)mediaInfo;
  215917. - (BOOL) prepareTrackForVerification:(DRTrack*)track;
  215918. - (uint32_t) produceDataForTrack:(DRTrack*)track intoBuffer:(char*)buffer
  215919. length:(uint32_t)bufferLength atAddress:(uint64_t)address
  215920. blockSize:(uint32_t)blockSize ioFlags:(uint32_t*)flags;
  215921. - (uint32_t) producePreGapForTrack:(DRTrack*)track
  215922. intoBuffer:(char*)buffer length:(uint32_t)bufferLength
  215923. atAddress:(uint64_t)address blockSize:(uint32_t)blockSize
  215924. ioFlags:(uint32_t*)flags;
  215925. - (BOOL) verifyDataForTrack:(DRTrack*)track inBuffer:(const char*)buffer
  215926. length:(uint32_t)bufferLength atAddress:(uint64_t)address
  215927. blockSize:(uint32_t)blockSize ioFlags:(uint32_t*)flags;
  215928. - (uint32_t) producePreGapForTrack:(DRTrack*)track
  215929. intoBuffer:(char*)buffer length:(uint32_t)bufferLength
  215930. atAddress:(uint64_t)address blockSize:(uint32_t)blockSize
  215931. ioFlags:(uint32_t*)flags;
  215932. @end
  215933. @implementation OpenDiskDevice
  215934. - (OpenDiskDevice*) initWithDevice: (DRDevice*) device_
  215935. {
  215936. [super init];
  215937. device = device_;
  215938. tracks = [[NSMutableArray alloc] init];
  215939. return self;
  215940. }
  215941. - (void) dealloc
  215942. {
  215943. [tracks release];
  215944. [super dealloc];
  215945. }
  215946. - (bool) isDiskPresent
  215947. {
  215948. return [device isValid]
  215949. && [[[device status] objectForKey: DRDeviceMediaStateKey]
  215950. isEqualTo: DRDeviceMediaStateMediaPresent];
  215951. }
  215952. - (int) getNumAvailableAudioBlocks
  215953. {
  215954. return [[[[device status] objectForKey: DRDeviceMediaInfoKey]
  215955. objectForKey: DRDeviceMediaBlocksFreeKey] intValue];
  215956. }
  215957. - (void) addSourceTrack: (juce::AudioSource*) source_ numSamples: (int) numSamples_
  215958. {
  215959. AudioTrackProducer* p = [[AudioTrackProducer alloc] initWithAudioSource: source_ numSamples: numSamples_];
  215960. DRTrack* t = [[DRTrack alloc] initWithProducer: p];
  215961. [p setupTrackProperties: t];
  215962. [tracks addObject: t];
  215963. [t release];
  215964. [p release];
  215965. }
  215966. - (void) burn: (juce::AudioCDBurner::BurnProgressListener*) listener errorString: (juce::String*) error
  215967. ejectAfterwards: (bool) shouldEject isFake: (bool) peformFakeBurnForTesting
  215968. {
  215969. DRBurn* burn = [DRBurn burnForDevice: device];
  215970. if (! [device acquireExclusiveAccess])
  215971. {
  215972. *error = "Couldn't open or write to the CD device";
  215973. return;
  215974. }
  215975. [device acquireMediaReservation];
  215976. NSMutableDictionary* d = [[burn properties] mutableCopy];
  215977. [d autorelease];
  215978. [d setObject: [NSNumber numberWithBool: peformFakeBurnForTesting] forKey: DRBurnTestingKey];
  215979. [d setObject: [NSNumber numberWithBool: false] forKey: DRBurnVerifyDiscKey];
  215980. [d setObject: (shouldEject ? DRBurnCompletionActionEject : DRBurnCompletionActionMount)
  215981. forKey: DRBurnCompletionActionKey];
  215982. [burn setProperties: d];
  215983. [burn writeLayout: tracks];
  215984. for (;;)
  215985. {
  215986. juce::Thread::sleep (300);
  215987. float progress = [[[burn status] objectForKey: DRStatusPercentCompleteKey] floatValue];
  215988. NSLog ([[burn status] description]);
  215989. if (listener != 0 && listener->audioCDBurnProgress (progress))
  215990. {
  215991. [burn abort];
  215992. *error = "User cancelled the write operation";
  215993. break;
  215994. }
  215995. if ([[[burn status] objectForKey: DRStatusStateKey] isEqualTo: DRStatusStateFailed])
  215996. {
  215997. *error = "Write operation failed";
  215998. break;
  215999. }
  216000. else if ([[[burn status] objectForKey: DRStatusStateKey] isEqualTo: DRStatusStateDone])
  216001. {
  216002. break;
  216003. }
  216004. NSString* err = (NSString*) [[[burn status] objectForKey: DRErrorStatusKey]
  216005. objectForKey: DRErrorStatusErrorStringKey];
  216006. if ([err length] > 0)
  216007. {
  216008. *error = juce::String::fromUTF8 ((juce::uint8*) [err UTF8String]);
  216009. break;
  216010. }
  216011. }
  216012. [device releaseMediaReservation];
  216013. [device releaseExclusiveAccess];
  216014. }
  216015. @end
  216016. @implementation AudioTrackProducer
  216017. - (AudioTrackProducer*) init: (int) lengthInFrames_
  216018. {
  216019. lengthInFrames = lengthInFrames_;
  216020. readPosition = 0;
  216021. return self;
  216022. }
  216023. - (void) setupTrackProperties: (DRTrack*) track
  216024. {
  216025. NSMutableDictionary* p = [[track properties] mutableCopy];
  216026. [p setObject:[DRMSF msfWithFrames: lengthInFrames] forKey: DRTrackLengthKey];
  216027. [p setObject:[NSNumber numberWithUnsignedShort:2352] forKey: DRBlockSizeKey];
  216028. [p setObject:[NSNumber numberWithInt:0] forKey: DRDataFormKey];
  216029. [p setObject:[NSNumber numberWithInt:0] forKey: DRBlockTypeKey];
  216030. [p setObject:[NSNumber numberWithInt:0] forKey: DRTrackModeKey];
  216031. [p setObject:[NSNumber numberWithInt:0] forKey: DRSessionFormatKey];
  216032. [track setProperties: p];
  216033. [p release];
  216034. }
  216035. - (AudioTrackProducer*) initWithAudioSource: (juce::AudioSource*) source_ numSamples: (int) lengthInSamples
  216036. {
  216037. AudioTrackProducer* s = [self init: (lengthInSamples + 587) / 588];
  216038. if (s != nil)
  216039. s->source = source_;
  216040. return s;
  216041. }
  216042. - (void) dealloc
  216043. {
  216044. if (source != 0)
  216045. {
  216046. source->releaseResources();
  216047. delete source;
  216048. }
  216049. [super dealloc];
  216050. }
  216051. - (void) cleanupTrackAfterBurn: (DRTrack*) track
  216052. {
  216053. }
  216054. - (BOOL) cleanupTrackAfterVerification:(DRTrack*)track
  216055. {
  216056. return true;
  216057. }
  216058. - (uint64_t) estimateLengthOfTrack:(DRTrack*)track
  216059. {
  216060. return lengthInFrames;
  216061. }
  216062. - (BOOL) prepareTrack:(DRTrack*)track forBurn:(DRBurn*)burn
  216063. toMedia:(NSDictionary*)mediaInfo
  216064. {
  216065. if (source != 0)
  216066. source->prepareToPlay (44100 / 75, 44100);
  216067. readPosition = 0;
  216068. return true;
  216069. }
  216070. - (BOOL) prepareTrackForVerification:(DRTrack*)track
  216071. {
  216072. if (source != 0)
  216073. source->prepareToPlay (44100 / 75, 44100);
  216074. return true;
  216075. }
  216076. - (uint32_t) produceDataForTrack:(DRTrack*)track intoBuffer:(char*)buffer
  216077. length:(uint32_t)bufferLength atAddress:(uint64_t)address
  216078. blockSize:(uint32_t)blockSize ioFlags:(uint32_t*)flags
  216079. {
  216080. if (source != 0)
  216081. {
  216082. const int numSamples = juce::jmin (bufferLength / 4, (lengthInFrames * (44100 / 75)) - readPosition);
  216083. if (numSamples > 0)
  216084. {
  216085. juce::AudioSampleBuffer tempBuffer (2, numSamples);
  216086. juce::AudioSourceChannelInfo info;
  216087. info.buffer = &tempBuffer;
  216088. info.startSample = 0;
  216089. info.numSamples = numSamples;
  216090. source->getNextAudioBlock (info);
  216091. juce::AudioDataConverters::convertFloatToInt16LE (tempBuffer.getSampleData (0),
  216092. buffer, numSamples, 4);
  216093. juce::AudioDataConverters::convertFloatToInt16LE (tempBuffer.getSampleData (1),
  216094. buffer + 2, numSamples, 4);
  216095. readPosition += numSamples;
  216096. }
  216097. return numSamples * 4;
  216098. }
  216099. return 0;
  216100. }
  216101. - (uint32_t) producePreGapForTrack:(DRTrack*)track
  216102. intoBuffer:(char*)buffer length:(uint32_t)bufferLength
  216103. atAddress:(uint64_t)address blockSize:(uint32_t)blockSize
  216104. ioFlags:(uint32_t*)flags
  216105. {
  216106. zeromem (buffer, bufferLength);
  216107. return bufferLength;
  216108. }
  216109. - (BOOL) verifyDataForTrack:(DRTrack*)track inBuffer:(const char*)buffer
  216110. length:(uint32_t)bufferLength atAddress:(uint64_t)address
  216111. blockSize:(uint32_t)blockSize ioFlags:(uint32_t*)flags
  216112. {
  216113. return true;
  216114. }
  216115. @end
  216116. BEGIN_JUCE_NAMESPACE
  216117. AudioCDBurner::AudioCDBurner (const int deviceIndex)
  216118. : internal (0)
  216119. {
  216120. NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
  216121. OpenDiskDevice* dev = [[OpenDiskDevice alloc] initWithDevice: [[DRDevice devices] objectAtIndex: deviceIndex]];
  216122. internal = (void*) dev;
  216123. [pool release];
  216124. }
  216125. AudioCDBurner::~AudioCDBurner()
  216126. {
  216127. NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
  216128. OpenDiskDevice* dev = (OpenDiskDevice*) internal;
  216129. if (dev != 0)
  216130. [dev release];
  216131. [pool release];
  216132. }
  216133. AudioCDBurner* AudioCDBurner::openDevice (const int deviceIndex)
  216134. {
  216135. NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
  216136. AudioCDBurner* b = new AudioCDBurner (deviceIndex);
  216137. if (b->internal == 0)
  216138. deleteAndZero (b);
  216139. [pool release];
  216140. return b;
  216141. }
  216142. static NSArray* findDiskBurnerDevices()
  216143. {
  216144. NSMutableArray* results = [NSMutableArray array];
  216145. NSArray* devs = [DRDevice devices];
  216146. if (devs != 0)
  216147. {
  216148. int num = [devs count];
  216149. int i;
  216150. for (i = 0; i < num; ++i)
  216151. {
  216152. NSDictionary* dic = [[devs objectAtIndex: i] info];
  216153. NSString* name = [dic valueForKey: DRDeviceProductNameKey];
  216154. if (name != nil)
  216155. [results addObject: name];
  216156. }
  216157. }
  216158. return results;
  216159. }
  216160. const StringArray AudioCDBurner::findAvailableDevices()
  216161. {
  216162. NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
  216163. NSArray* names = findDiskBurnerDevices();
  216164. StringArray s;
  216165. for (int i = 0; i < [names count]; ++i)
  216166. s.add (String::fromUTF8 ((juce::uint8*) [[names objectAtIndex: i] UTF8String]));
  216167. [pool release];
  216168. return s;
  216169. }
  216170. bool AudioCDBurner::isDiskPresent() const
  216171. {
  216172. OpenDiskDevice* dev = (OpenDiskDevice*) internal;
  216173. return dev != 0 && [dev isDiskPresent];
  216174. }
  216175. int AudioCDBurner::getNumAvailableAudioBlocks() const
  216176. {
  216177. OpenDiskDevice* dev = (OpenDiskDevice*) internal;
  216178. return [dev getNumAvailableAudioBlocks];
  216179. }
  216180. bool AudioCDBurner::addAudioTrack (AudioSource* source, int numSamps)
  216181. {
  216182. NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
  216183. OpenDiskDevice* dev = (OpenDiskDevice*) internal;
  216184. if (dev != 0)
  216185. {
  216186. [dev addSourceTrack: source numSamples: numSamps];
  216187. [pool release];
  216188. return true;
  216189. }
  216190. [pool release];
  216191. return false;
  216192. }
  216193. const String AudioCDBurner::burn (juce::AudioCDBurner::BurnProgressListener* listener,
  216194. const bool ejectDiscAfterwards,
  216195. const bool peformFakeBurnForTesting)
  216196. {
  216197. NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
  216198. juce::String error ("Couldn't open or write to the CD device");
  216199. OpenDiskDevice* dev = (OpenDiskDevice*) internal;
  216200. if (dev != 0)
  216201. {
  216202. error = juce::String::empty;
  216203. [dev burn: listener
  216204. errorString: &error
  216205. ejectAfterwards: ejectDiscAfterwards
  216206. isFake: peformFakeBurnForTesting];
  216207. }
  216208. [pool release];
  216209. return error;
  216210. }
  216211. END_JUCE_NAMESPACE
  216212. #endif
  216213. /********* End of inlined file: juce_mac_AudioCDBurner.mm *********/
  216214. /********* Start of inlined file: juce_mac_CoreAudio.cpp *********/
  216215. #include <CoreAudio/AudioHardware.h>
  216216. BEGIN_JUCE_NAMESPACE
  216217. #ifndef JUCE_COREAUDIO_ERROR_LOGGING_ENABLED
  216218. #define JUCE_COREAUDIO_ERROR_LOGGING_ENABLED 1
  216219. #endif
  216220. #undef log
  216221. #if JUCE_COREAUDIO_LOGGING_ENABLED
  216222. #define log(a) Logger::writeToLog (a)
  216223. #else
  216224. #define log(a)
  216225. #endif
  216226. #undef OK
  216227. #if JUCE_COREAUDIO_ERROR_LOGGING_ENABLED
  216228. static bool logAnyErrors_CoreAudio (const OSStatus err, const int lineNum)
  216229. {
  216230. if (err == noErr)
  216231. return true;
  216232. Logger::writeToLog (T("CoreAudio error: ") + String (lineNum) + T(" - ") + String::toHexString ((int)err));
  216233. jassertfalse
  216234. return false;
  216235. }
  216236. #define OK(a) logAnyErrors_CoreAudio (a, __LINE__)
  216237. #else
  216238. #define OK(a) (a == noErr)
  216239. #endif
  216240. static const int maxNumChans = 96;
  216241. class CoreAudioInternal : public Timer
  216242. {
  216243. public:
  216244. CoreAudioInternal (AudioDeviceID id)
  216245. : deviceID (id),
  216246. started (false),
  216247. audioBuffer (0),
  216248. numInputChans (0),
  216249. numOutputChans (0),
  216250. callbacksAllowed (true),
  216251. numInputChannelInfos (0),
  216252. numOutputChannelInfos (0),
  216253. inputLatency (0),
  216254. outputLatency (0),
  216255. callback (0),
  216256. inputDevice (0),
  216257. isSlaveDevice (false)
  216258. {
  216259. sampleRate = 0;
  216260. bufferSize = 512;
  216261. if (deviceID == 0)
  216262. {
  216263. error = TRANS("can't open device");
  216264. }
  216265. else
  216266. {
  216267. updateDetailsFromDevice();
  216268. AudioDeviceAddPropertyListener (deviceID,
  216269. kAudioPropertyWildcardChannel,
  216270. kAudioPropertyWildcardSection,
  216271. kAudioPropertyWildcardPropertyID,
  216272. deviceListenerProc, this);
  216273. }
  216274. }
  216275. ~CoreAudioInternal()
  216276. {
  216277. AudioDeviceRemovePropertyListener (deviceID,
  216278. kAudioPropertyWildcardChannel,
  216279. kAudioPropertyWildcardSection,
  216280. kAudioPropertyWildcardPropertyID,
  216281. deviceListenerProc);
  216282. stop (false);
  216283. juce_free (audioBuffer);
  216284. delete inputDevice;
  216285. }
  216286. void setTempBufferSize (const int numChannels, const int numSamples)
  216287. {
  216288. juce_free (audioBuffer);
  216289. audioBuffer = (float*) juce_calloc (32 + numChannels * numSamples * sizeof (float));
  216290. zeromem (tempInputBuffers, sizeof (tempInputBuffers));
  216291. zeromem (tempOutputBuffers, sizeof (tempOutputBuffers));
  216292. int count = 0;
  216293. int i;
  216294. for (i = 0; i < numInputChans; ++i)
  216295. tempInputBuffers[i] = audioBuffer + count++ * numSamples;
  216296. for (i = 0; i < numOutputChans; ++i)
  216297. tempOutputBuffers[i] = audioBuffer + count++ * numSamples;
  216298. }
  216299. // returns the number of actual available channels
  216300. void fillInChannelInfo (bool input)
  216301. {
  216302. int chanNum = 0, activeChans = 0;
  216303. UInt32 size;
  216304. if (OK (AudioDeviceGetPropertyInfo (deviceID, 0, input, kAudioDevicePropertyStreamConfiguration, &size, 0)))
  216305. {
  216306. AudioBufferList* const bufList = (AudioBufferList*) juce_calloc (size);
  216307. if (OK (AudioDeviceGetProperty (deviceID, 0, input, kAudioDevicePropertyStreamConfiguration, &size, bufList)))
  216308. {
  216309. const int numStreams = bufList->mNumberBuffers;
  216310. for (int i = 0; i < numStreams; ++i)
  216311. {
  216312. const AudioBuffer& b = bufList->mBuffers[i];
  216313. for (unsigned int j = 0; j < b.mNumberChannels; ++j)
  216314. {
  216315. if (input)
  216316. {
  216317. if (activeInputChans[chanNum])
  216318. {
  216319. inputChannelInfo [activeChans].sourceChannelNum = chanNum;
  216320. inputChannelInfo [activeChans].streamNum = i;
  216321. inputChannelInfo [activeChans].dataOffsetSamples = j;
  216322. inputChannelInfo [activeChans].dataStrideSamples = b.mNumberChannels;
  216323. ++activeChans;
  216324. numInputChannelInfos = activeChans;
  216325. }
  216326. inChanNames.add (T("input ") + String (chanNum + 1));
  216327. }
  216328. else
  216329. {
  216330. if (activeOutputChans[chanNum])
  216331. {
  216332. outputChannelInfo [activeChans].sourceChannelNum = chanNum;
  216333. outputChannelInfo [activeChans].streamNum = i;
  216334. outputChannelInfo [activeChans].dataOffsetSamples = j;
  216335. outputChannelInfo [activeChans].dataStrideSamples = b.mNumberChannels;
  216336. ++activeChans;
  216337. numOutputChannelInfos = activeChans;
  216338. }
  216339. outChanNames.add (T("output ") + String (chanNum + 1));
  216340. }
  216341. ++chanNum;
  216342. }
  216343. }
  216344. }
  216345. juce_free (bufList);
  216346. }
  216347. }
  216348. void updateDetailsFromDevice()
  216349. {
  216350. stopTimer();
  216351. if (deviceID == 0)
  216352. return;
  216353. const ScopedLock sl (callbackLock);
  216354. Float64 sr;
  216355. UInt32 size = sizeof (Float64);
  216356. if (OK (AudioDeviceGetProperty (deviceID, 0, false, kAudioDevicePropertyNominalSampleRate, &size, &sr)))
  216357. sampleRate = sr;
  216358. UInt32 framesPerBuf;
  216359. size = sizeof (framesPerBuf);
  216360. if (OK (AudioDeviceGetProperty (deviceID, 0, false, kAudioDevicePropertyBufferFrameSize, &size, &framesPerBuf)))
  216361. {
  216362. bufferSize = framesPerBuf;
  216363. if (bufferSize > 0)
  216364. setTempBufferSize (numInputChans + numOutputChans, bufferSize);
  216365. }
  216366. bufferSizes.clear();
  216367. if (OK (AudioDeviceGetPropertyInfo (deviceID, 0, false, kAudioDevicePropertyBufferFrameSizeRange, &size, 0)))
  216368. {
  216369. AudioValueRange* ranges = (AudioValueRange*) juce_calloc (size);
  216370. if (OK (AudioDeviceGetProperty (deviceID, 0, false, kAudioDevicePropertyBufferFrameSizeRange, &size, ranges)))
  216371. {
  216372. bufferSizes.add ((int) ranges[0].mMinimum);
  216373. for (int i = 32; i < 8192; i += 32)
  216374. {
  216375. for (int j = size / sizeof (AudioValueRange); --j >= 0;)
  216376. {
  216377. if (i >= ranges[j].mMinimum && i <= ranges[j].mMaximum)
  216378. {
  216379. bufferSizes.addIfNotAlreadyThere (i);
  216380. break;
  216381. }
  216382. }
  216383. }
  216384. if (bufferSize > 0)
  216385. bufferSizes.addIfNotAlreadyThere (bufferSize);
  216386. }
  216387. juce_free (ranges);
  216388. }
  216389. if (bufferSizes.size() == 0 && bufferSize > 0)
  216390. bufferSizes.add (bufferSize);
  216391. sampleRates.clear();
  216392. const double possibleRates[] = { 44100.0, 48000.0, 88200.0, 96000.0, 176400.0, 192000.0 };
  216393. String rates;
  216394. if (OK (AudioDeviceGetPropertyInfo (deviceID, 0, false, kAudioDevicePropertyAvailableNominalSampleRates, &size, 0)))
  216395. {
  216396. AudioValueRange* ranges = (AudioValueRange*) juce_calloc (size);
  216397. if (OK (AudioDeviceGetProperty (deviceID, 0, false, kAudioDevicePropertyAvailableNominalSampleRates, &size, ranges)))
  216398. {
  216399. for (int i = 0; i < numElementsInArray (possibleRates); ++i)
  216400. {
  216401. bool ok = false;
  216402. for (int j = size / sizeof (AudioValueRange); --j >= 0;)
  216403. if (possibleRates[i] >= ranges[j].mMinimum - 2 && possibleRates[i] <= ranges[j].mMaximum + 2)
  216404. ok = true;
  216405. if (ok)
  216406. {
  216407. sampleRates.add (possibleRates[i]);
  216408. rates << possibleRates[i] << T(" ");
  216409. }
  216410. }
  216411. }
  216412. juce_free (ranges);
  216413. }
  216414. if (sampleRates.size() == 0 && sampleRate > 0)
  216415. {
  216416. sampleRates.add (sampleRate);
  216417. rates << sampleRate;
  216418. }
  216419. log (T("sr: ") + rates);
  216420. inputLatency = 0;
  216421. outputLatency = 0;
  216422. UInt32 lat;
  216423. size = sizeof (UInt32);
  216424. if (AudioDeviceGetProperty (deviceID, 0, true, kAudioDevicePropertyLatency, &size, &lat) == noErr)
  216425. inputLatency = (int) lat;
  216426. if (AudioDeviceGetProperty (deviceID, 0, false, kAudioDevicePropertyLatency, &size, &lat) == noErr)
  216427. outputLatency = (int) lat;
  216428. log (T("lat: ") + String (inputLatency) + T(" ") + String (outputLatency));
  216429. inChanNames.clear();
  216430. outChanNames.clear();
  216431. zeromem (inputChannelInfo, sizeof (inputChannelInfo));
  216432. zeromem (outputChannelInfo, sizeof (outputChannelInfo));
  216433. fillInChannelInfo (true);
  216434. fillInChannelInfo (false);
  216435. }
  216436. const StringArray getSources (bool input)
  216437. {
  216438. StringArray s;
  216439. int num = 0;
  216440. OSType* types = getAllDataSourcesForDevice (deviceID, input, num);
  216441. if (types != 0)
  216442. {
  216443. for (int i = 0; i < num; ++i)
  216444. {
  216445. AudioValueTranslation avt;
  216446. char buffer[256];
  216447. avt.mInputData = (void*) &(types[i]);
  216448. avt.mInputDataSize = sizeof (UInt32);
  216449. avt.mOutputData = buffer;
  216450. avt.mOutputDataSize = 256;
  216451. UInt32 transSize = sizeof (avt);
  216452. if (OK (AudioDeviceGetProperty (deviceID, 0, input, kAudioDevicePropertyDataSourceNameForID, &transSize, &avt)))
  216453. {
  216454. DBG (buffer);
  216455. s.add (buffer);
  216456. }
  216457. }
  216458. juce_free (types);
  216459. }
  216460. return s;
  216461. }
  216462. int getCurrentSourceIndex (bool input) const
  216463. {
  216464. OSType currentSourceID = 0;
  216465. UInt32 size = 0;
  216466. int result = -1;
  216467. if (deviceID != 0
  216468. && OK (AudioDeviceGetPropertyInfo (deviceID, 0, input, kAudioDevicePropertyDataSource, &size, 0)))
  216469. {
  216470. if (OK (AudioDeviceGetProperty (deviceID, 0, input, kAudioDevicePropertyDataSource, &size, &currentSourceID)))
  216471. {
  216472. int num = 0;
  216473. OSType* const types = getAllDataSourcesForDevice (deviceID, input, num);
  216474. if (types != 0)
  216475. {
  216476. for (int i = 0; i < num; ++i)
  216477. {
  216478. if (types[num] == currentSourceID)
  216479. {
  216480. result = i;
  216481. break;
  216482. }
  216483. }
  216484. juce_free (types);
  216485. }
  216486. }
  216487. }
  216488. return result;
  216489. }
  216490. void setCurrentSourceIndex (int index, bool input)
  216491. {
  216492. if (deviceID != 0)
  216493. {
  216494. int num = 0;
  216495. OSType* types = getAllDataSourcesForDevice (deviceID, input, num);
  216496. if (types != 0)
  216497. {
  216498. if (((unsigned int) index) < num)
  216499. {
  216500. OSType typeId = types[index];
  216501. AudioDeviceSetProperty (deviceID, 0, 0, input, kAudioDevicePropertyDataSource, sizeof (typeId), &typeId);
  216502. }
  216503. juce_free (types);
  216504. }
  216505. }
  216506. }
  216507. const String reopen (const BitArray& inputChannels,
  216508. const BitArray& outputChannels,
  216509. double newSampleRate,
  216510. int bufferSizeSamples)
  216511. {
  216512. error = String::empty;
  216513. log ("CoreAudio reopen");
  216514. callbacksAllowed = false;
  216515. stopTimer();
  216516. stop (false);
  216517. activeInputChans = inputChannels;
  216518. activeOutputChans = outputChannels;
  216519. activeInputChans.setRange (inChanNames.size(),
  216520. activeInputChans.getHighestBit() + 1 - inChanNames.size(),
  216521. false);
  216522. activeOutputChans.setRange (outChanNames.size(),
  216523. activeOutputChans.getHighestBit() + 1 - outChanNames.size(),
  216524. false);
  216525. numInputChans = activeInputChans.countNumberOfSetBits();
  216526. numOutputChans = activeOutputChans.countNumberOfSetBits();
  216527. // set sample rate
  216528. Float64 sr = newSampleRate;
  216529. UInt32 size = sizeof (sr);
  216530. OK (AudioDeviceSetProperty (deviceID, 0, 0, false, kAudioDevicePropertyNominalSampleRate, size, &sr));
  216531. OK (AudioDeviceSetProperty (deviceID, 0, 0, true, kAudioDevicePropertyNominalSampleRate, size, &sr));
  216532. // change buffer size
  216533. UInt32 framesPerBuf = bufferSizeSamples;
  216534. size = sizeof (framesPerBuf);
  216535. OK (AudioDeviceSetProperty (deviceID, 0, 0, false, kAudioDevicePropertyBufferFrameSize, size, &framesPerBuf));
  216536. OK (AudioDeviceSetProperty (deviceID, 0, 0, true, kAudioDevicePropertyBufferFrameSize, size, &framesPerBuf));
  216537. // wait for the changes to happen (on some devices)
  216538. int i = 30;
  216539. while (--i >= 0)
  216540. {
  216541. updateDetailsFromDevice();
  216542. if (sampleRate == newSampleRate && bufferSizeSamples == bufferSize)
  216543. break;
  216544. Thread::sleep (100);
  216545. }
  216546. if (i < 0)
  216547. error = "Couldn't change sample rate/buffer size";
  216548. if (sampleRates.size() == 0)
  216549. error = "Device has no available sample-rates";
  216550. if (bufferSizes.size() == 0)
  216551. error = "Device has no available buffer-sizes";
  216552. if (inputDevice != 0 && error.isEmpty())
  216553. error = inputDevice->reopen (inputChannels,
  216554. outputChannels,
  216555. newSampleRate,
  216556. bufferSizeSamples);
  216557. callbacksAllowed = true;
  216558. return error;
  216559. }
  216560. bool start (AudioIODeviceCallback* cb)
  216561. {
  216562. if (! started)
  216563. {
  216564. callback = 0;
  216565. if (deviceID != 0)
  216566. {
  216567. if (OK (AudioDeviceAddIOProc (deviceID, audioIOProc, (void*) this)))
  216568. {
  216569. if (OK (AudioDeviceStart (deviceID, audioIOProc)))
  216570. {
  216571. started = true;
  216572. }
  216573. else
  216574. {
  216575. OK (AudioDeviceRemoveIOProc (deviceID, audioIOProc));
  216576. }
  216577. }
  216578. }
  216579. }
  216580. if (started)
  216581. {
  216582. const ScopedLock sl (callbackLock);
  216583. callback = cb;
  216584. }
  216585. if (inputDevice != 0)
  216586. return started && inputDevice->start (cb);
  216587. else
  216588. return started;
  216589. }
  216590. void stop (bool leaveInterruptRunning)
  216591. {
  216592. callbackLock.enter();
  216593. callback = 0;
  216594. callbackLock.exit();
  216595. if (started
  216596. && (deviceID != 0)
  216597. && ! leaveInterruptRunning)
  216598. {
  216599. OK (AudioDeviceStop (deviceID, audioIOProc));
  216600. OK (AudioDeviceRemoveIOProc (deviceID, audioIOProc));
  216601. started = false;
  216602. callbackLock.enter();
  216603. callbackLock.exit();
  216604. // wait until it's definately stopped calling back..
  216605. for (int i = 40; --i >= 0;)
  216606. {
  216607. Thread::sleep (50);
  216608. UInt32 running = 0;
  216609. UInt32 size = sizeof (running);
  216610. OK (AudioDeviceGetProperty (deviceID, 0, false, kAudioDevicePropertyDeviceIsRunning, &size, &running));
  216611. if (running == 0)
  216612. break;
  216613. }
  216614. callbackLock.enter();
  216615. callbackLock.exit();
  216616. }
  216617. if (inputDevice != 0)
  216618. inputDevice->stop (leaveInterruptRunning);
  216619. }
  216620. double getSampleRate() const
  216621. {
  216622. return sampleRate;
  216623. }
  216624. int getBufferSize() const
  216625. {
  216626. return bufferSize;
  216627. }
  216628. void audioCallback (const AudioBufferList* inInputData,
  216629. AudioBufferList* outOutputData)
  216630. {
  216631. int i;
  216632. const ScopedLock sl (callbackLock);
  216633. if (callback != 0)
  216634. {
  216635. if (inputDevice == 0)
  216636. {
  216637. for (i = numInputChans; --i >= 0;)
  216638. {
  216639. const CallbackDetailsForChannel& info = inputChannelInfo[i];
  216640. float* dest = tempInputBuffers [info.sourceChannelNum];
  216641. const float* src = ((const float*) inInputData->mBuffers[info.streamNum].mData)
  216642. + info.dataOffsetSamples;
  216643. const int stride = info.dataStrideSamples;
  216644. if (stride != 0) // if this is zero, info is invalid
  216645. {
  216646. for (int j = bufferSize; --j >= 0;)
  216647. {
  216648. *dest++ = *src;
  216649. src += stride;
  216650. }
  216651. }
  216652. }
  216653. }
  216654. if (! isSlaveDevice)
  216655. {
  216656. if (inputDevice == 0)
  216657. {
  216658. callback->audioDeviceIOCallback ((const float**) tempInputBuffers,
  216659. numInputChans,
  216660. tempOutputBuffers,
  216661. numOutputChans,
  216662. bufferSize);
  216663. }
  216664. else
  216665. {
  216666. jassert (inputDevice->bufferSize == bufferSize);
  216667. callback->audioDeviceIOCallback ((const float**) inputDevice->tempInputBuffers,
  216668. inputDevice->numInputChans,
  216669. tempOutputBuffers,
  216670. numOutputChans,
  216671. bufferSize);
  216672. }
  216673. for (i = numOutputChans; --i >= 0;)
  216674. {
  216675. const CallbackDetailsForChannel& info = outputChannelInfo[i];
  216676. const float* src = tempOutputBuffers [info.sourceChannelNum];
  216677. float* dest = ((float*) outOutputData->mBuffers[info.streamNum].mData)
  216678. + info.dataOffsetSamples;
  216679. const int stride = info.dataStrideSamples;
  216680. if (stride != 0) // if this is zero, info is invalid
  216681. {
  216682. for (int j = bufferSize; --j >= 0;)
  216683. {
  216684. *dest = *src++;
  216685. dest += stride;
  216686. }
  216687. }
  216688. }
  216689. }
  216690. }
  216691. else
  216692. {
  216693. for (i = jmin (numOutputChans, numOutputChannelInfos); --i >= 0;)
  216694. {
  216695. const CallbackDetailsForChannel& info = outputChannelInfo[i];
  216696. float* dest = ((float*) outOutputData->mBuffers[info.streamNum].mData)
  216697. + info.dataOffsetSamples;
  216698. const int stride = info.dataStrideSamples;
  216699. if (stride != 0) // if this is zero, info is invalid
  216700. {
  216701. for (int j = bufferSize; --j >= 0;)
  216702. {
  216703. *dest = 0.0f;
  216704. dest += stride;
  216705. }
  216706. }
  216707. }
  216708. }
  216709. }
  216710. // called by callbacks
  216711. void deviceDetailsChanged()
  216712. {
  216713. if (callbacksAllowed)
  216714. startTimer (100);
  216715. }
  216716. void timerCallback()
  216717. {
  216718. stopTimer();
  216719. log ("CoreAudio device changed callback");
  216720. const double oldSampleRate = sampleRate;
  216721. const int oldBufferSize = bufferSize;
  216722. updateDetailsFromDevice();
  216723. if (oldBufferSize != bufferSize || oldSampleRate != sampleRate)
  216724. {
  216725. callbacksAllowed = false;
  216726. stop (false);
  216727. updateDetailsFromDevice();
  216728. callbacksAllowed = true;
  216729. }
  216730. }
  216731. CoreAudioInternal* getRelatedDevice() const
  216732. {
  216733. UInt32 size = 0;
  216734. CoreAudioInternal* result = 0;
  216735. if (deviceID != 0
  216736. && AudioDeviceGetPropertyInfo (deviceID, 0, false, kAudioDevicePropertyRelatedDevices, &size, 0) == noErr
  216737. && size > 0)
  216738. {
  216739. AudioDeviceID* devs = (AudioDeviceID*) juce_calloc (size);
  216740. if (OK (AudioDeviceGetProperty (deviceID, 0, false, kAudioDevicePropertyRelatedDevices, &size, devs)))
  216741. {
  216742. for (unsigned int i = 0; i < size / sizeof (AudioDeviceID); ++i)
  216743. {
  216744. if (devs[i] != deviceID && devs[i] != 0)
  216745. {
  216746. result = new CoreAudioInternal (devs[i]);
  216747. if (result->error.isEmpty())
  216748. {
  216749. const bool thisIsInput = inChanNames.size() > 0 && outChanNames.size() == 0;
  216750. const bool otherIsInput = result->inChanNames.size() > 0 && result->outChanNames.size() == 0;
  216751. if (thisIsInput != otherIsInput
  216752. || (inChanNames.size() + outChanNames.size() == 0)
  216753. || (result->inChanNames.size() + result->outChanNames.size()) == 0)
  216754. break;
  216755. }
  216756. deleteAndZero (result);
  216757. }
  216758. }
  216759. }
  216760. juce_free (devs);
  216761. }
  216762. return result;
  216763. }
  216764. juce_UseDebuggingNewOperator
  216765. String error;
  216766. int inputLatency, outputLatency;
  216767. BitArray activeInputChans, activeOutputChans;
  216768. StringArray inChanNames, outChanNames;
  216769. Array <double> sampleRates;
  216770. Array <int> bufferSizes;
  216771. AudioIODeviceCallback* callback;
  216772. CoreAudioInternal* inputDevice;
  216773. bool isSlaveDevice;
  216774. private:
  216775. CriticalSection callbackLock;
  216776. AudioDeviceID deviceID;
  216777. bool started;
  216778. double sampleRate;
  216779. int bufferSize;
  216780. float* audioBuffer;
  216781. int numInputChans, numOutputChans;
  216782. bool callbacksAllowed;
  216783. struct CallbackDetailsForChannel
  216784. {
  216785. int sourceChannelNum;
  216786. int streamNum;
  216787. int dataOffsetSamples;
  216788. int dataStrideSamples;
  216789. };
  216790. int numInputChannelInfos, numOutputChannelInfos;
  216791. CallbackDetailsForChannel inputChannelInfo [maxNumChans];
  216792. CallbackDetailsForChannel outputChannelInfo [maxNumChans];
  216793. float* tempInputBuffers [maxNumChans];
  216794. float* tempOutputBuffers [maxNumChans];
  216795. CoreAudioInternal (const CoreAudioInternal&);
  216796. const CoreAudioInternal& operator= (const CoreAudioInternal&);
  216797. static OSStatus audioIOProc (AudioDeviceID inDevice,
  216798. const AudioTimeStamp* inNow,
  216799. const AudioBufferList* inInputData,
  216800. const AudioTimeStamp* inInputTime,
  216801. AudioBufferList* outOutputData,
  216802. const AudioTimeStamp* inOutputTime,
  216803. void* device)
  216804. {
  216805. ((CoreAudioInternal*) device)->audioCallback (inInputData, outOutputData);
  216806. return noErr;
  216807. }
  216808. static OSStatus deviceListenerProc (AudioDeviceID inDevice,
  216809. UInt32 inLine,
  216810. Boolean isInput,
  216811. AudioDevicePropertyID inPropertyID,
  216812. void* inClientData)
  216813. {
  216814. CoreAudioInternal* const intern = (CoreAudioInternal*) inClientData;
  216815. switch (inPropertyID)
  216816. {
  216817. case kAudioDevicePropertyBufferSize:
  216818. case kAudioDevicePropertyBufferFrameSize:
  216819. case kAudioDevicePropertyNominalSampleRate:
  216820. case kAudioDevicePropertyStreamFormat:
  216821. case kAudioDevicePropertyDeviceIsAlive:
  216822. intern->deviceDetailsChanged();
  216823. break;
  216824. case kAudioDevicePropertyBufferSizeRange:
  216825. case kAudioDevicePropertyVolumeScalar:
  216826. case kAudioDevicePropertyMute:
  216827. case kAudioDevicePropertyPlayThru:
  216828. case kAudioDevicePropertyDataSource:
  216829. case kAudioDevicePropertyDeviceIsRunning:
  216830. break;
  216831. }
  216832. return noErr;
  216833. }
  216834. static OSType* getAllDataSourcesForDevice (AudioDeviceID deviceID, const bool input, int& num)
  216835. {
  216836. OSType* types = 0;
  216837. UInt32 size = 0;
  216838. num = 0;
  216839. if (deviceID != 0
  216840. && OK (AudioDeviceGetPropertyInfo (deviceID, 0, input, kAudioDevicePropertyDataSources, &size, 0)))
  216841. {
  216842. types = (OSType*) juce_calloc (size);
  216843. if (OK (AudioDeviceGetProperty (deviceID, 0, input, kAudioDevicePropertyDataSources, &size, types)))
  216844. {
  216845. num = size / sizeof (OSType);
  216846. }
  216847. else
  216848. {
  216849. juce_free (types);
  216850. types = 0;
  216851. }
  216852. }
  216853. return types;
  216854. }
  216855. };
  216856. class CoreAudioIODevice : public AudioIODevice
  216857. {
  216858. public:
  216859. CoreAudioIODevice (const String& deviceName,
  216860. AudioDeviceID deviceId1)
  216861. : AudioIODevice (deviceName, "CoreAudio"),
  216862. isOpen_ (false),
  216863. isStarted (false)
  216864. {
  216865. internal = 0;
  216866. CoreAudioInternal* device = new CoreAudioInternal (deviceId1);
  216867. lastError = device->error;
  216868. if (lastError.isNotEmpty())
  216869. {
  216870. deleteAndZero (device);
  216871. }
  216872. else
  216873. {
  216874. CoreAudioInternal* secondDevice = device->getRelatedDevice();
  216875. if (secondDevice != 0)
  216876. {
  216877. if (device->inChanNames.size() > secondDevice->inChanNames.size())
  216878. swapVariables (device, secondDevice);
  216879. device->inputDevice = secondDevice;
  216880. secondDevice->isSlaveDevice = true;
  216881. }
  216882. }
  216883. internal = device;
  216884. AudioHardwareAddPropertyListener (kAudioPropertyWildcardPropertyID,
  216885. hardwareListenerProc, internal);
  216886. }
  216887. ~CoreAudioIODevice()
  216888. {
  216889. AudioHardwareRemovePropertyListener (kAudioPropertyWildcardPropertyID,
  216890. hardwareListenerProc);
  216891. delete internal;
  216892. }
  216893. const StringArray getOutputChannelNames()
  216894. {
  216895. return internal->outChanNames;
  216896. }
  216897. const StringArray getInputChannelNames()
  216898. {
  216899. if (internal->inputDevice != 0)
  216900. return internal->inputDevice->inChanNames;
  216901. else
  216902. return internal->inChanNames;
  216903. }
  216904. int getNumSampleRates()
  216905. {
  216906. return internal->sampleRates.size();
  216907. }
  216908. double getSampleRate (int index)
  216909. {
  216910. return internal->sampleRates [index];
  216911. }
  216912. int getNumBufferSizesAvailable()
  216913. {
  216914. return internal->bufferSizes.size();
  216915. }
  216916. int getBufferSizeSamples (int index)
  216917. {
  216918. return internal->bufferSizes [index];
  216919. }
  216920. int getDefaultBufferSize()
  216921. {
  216922. for (int i = 0; i < getNumBufferSizesAvailable(); ++i)
  216923. if (getBufferSizeSamples(i) >= 512)
  216924. return getBufferSizeSamples(i);
  216925. return 512;
  216926. }
  216927. const String open (const BitArray& inputChannels,
  216928. const BitArray& outputChannels,
  216929. double sampleRate,
  216930. int bufferSizeSamples)
  216931. {
  216932. isOpen_ = true;
  216933. if (bufferSizeSamples <= 0)
  216934. bufferSizeSamples = getDefaultBufferSize();
  216935. internal->reopen (inputChannels, outputChannels, sampleRate, bufferSizeSamples);
  216936. lastError = internal->error;
  216937. return lastError;
  216938. }
  216939. void close()
  216940. {
  216941. isOpen_ = false;
  216942. }
  216943. bool isOpen()
  216944. {
  216945. return isOpen_;
  216946. }
  216947. int getCurrentBufferSizeSamples()
  216948. {
  216949. return internal != 0 ? internal->getBufferSize() : 512;
  216950. }
  216951. double getCurrentSampleRate()
  216952. {
  216953. return internal != 0 ? internal->getSampleRate() : 0;
  216954. }
  216955. int getCurrentBitDepth()
  216956. {
  216957. return 32; // no way to find out, so just assume it's high..
  216958. }
  216959. const BitArray getActiveOutputChannels() const
  216960. {
  216961. return internal != 0 ? internal->activeOutputChans : BitArray();
  216962. }
  216963. const BitArray getActiveInputChannels() const
  216964. {
  216965. BitArray chans;
  216966. if (internal != 0)
  216967. {
  216968. chans = internal->activeInputChans;
  216969. if (internal->inputDevice != 0)
  216970. chans.orWith (internal->inputDevice->activeInputChans);
  216971. }
  216972. return chans;
  216973. }
  216974. int getOutputLatencyInSamples()
  216975. {
  216976. if (internal == 0)
  216977. return 0;
  216978. // this seems like a good guess at getting the latency right - comparing
  216979. // this with a round-trip measurement, it gets it to within a few millisecs
  216980. // for the built-in mac soundcard
  216981. return internal->outputLatency + internal->getBufferSize() * 2;
  216982. }
  216983. int getInputLatencyInSamples()
  216984. {
  216985. if (internal == 0)
  216986. return 0;
  216987. return internal->inputLatency + internal->getBufferSize() * 2;
  216988. }
  216989. void start (AudioIODeviceCallback* callback)
  216990. {
  216991. if (internal != 0 && ! isStarted)
  216992. {
  216993. if (callback != 0)
  216994. callback->audioDeviceAboutToStart (this);
  216995. isStarted = true;
  216996. internal->start (callback);
  216997. }
  216998. }
  216999. void stop()
  217000. {
  217001. if (isStarted && internal != 0)
  217002. {
  217003. AudioIODeviceCallback* const lastCallback = internal->callback;
  217004. isStarted = false;
  217005. internal->stop (true);
  217006. if (lastCallback != 0)
  217007. lastCallback->audioDeviceStopped();
  217008. }
  217009. }
  217010. bool isPlaying()
  217011. {
  217012. if (internal->callback == 0)
  217013. isStarted = false;
  217014. return isStarted;
  217015. }
  217016. const String getLastError()
  217017. {
  217018. return lastError;
  217019. }
  217020. juce_UseDebuggingNewOperator
  217021. private:
  217022. CoreAudioInternal* internal;
  217023. bool isOpen_, isStarted;
  217024. String lastError;
  217025. static OSStatus hardwareListenerProc (AudioHardwarePropertyID inPropertyID, void* inClientData)
  217026. {
  217027. CoreAudioInternal* const intern = (CoreAudioInternal*) inClientData;
  217028. switch (inPropertyID)
  217029. {
  217030. case kAudioHardwarePropertyDevices:
  217031. intern->deviceDetailsChanged();
  217032. break;
  217033. case kAudioHardwarePropertyDefaultOutputDevice:
  217034. case kAudioHardwarePropertyDefaultInputDevice:
  217035. case kAudioHardwarePropertyDefaultSystemOutputDevice:
  217036. break;
  217037. }
  217038. return noErr;
  217039. }
  217040. CoreAudioIODevice (const CoreAudioIODevice&);
  217041. const CoreAudioIODevice& operator= (const CoreAudioIODevice&);
  217042. };
  217043. class CoreAudioIODeviceType : public AudioIODeviceType
  217044. {
  217045. public:
  217046. CoreAudioIODeviceType()
  217047. : AudioIODeviceType (T("CoreAudio")),
  217048. hasScanned (false)
  217049. {
  217050. }
  217051. ~CoreAudioIODeviceType()
  217052. {
  217053. }
  217054. void scanForDevices()
  217055. {
  217056. hasScanned = true;
  217057. names.clear();
  217058. ids.clear();
  217059. UInt32 size;
  217060. if (OK (AudioHardwareGetPropertyInfo (kAudioHardwarePropertyDevices, &size, 0)))
  217061. {
  217062. AudioDeviceID* const devs = (AudioDeviceID*) juce_calloc (size);
  217063. if (OK (AudioHardwareGetProperty (kAudioHardwarePropertyDevices, &size, devs)))
  217064. {
  217065. static bool alreadyLogged = false;
  217066. const int num = size / sizeof (AudioDeviceID);
  217067. for (int i = 0; i < num; ++i)
  217068. {
  217069. char name[1024];
  217070. size = sizeof (name);
  217071. if (OK (AudioDeviceGetProperty (devs[i], 0, false, kAudioDevicePropertyDeviceName, &size, name)))
  217072. {
  217073. const String nameString (String::fromUTF8 ((const uint8*) name, strlen (name)));
  217074. if (! alreadyLogged)
  217075. log (T("CoreAudio device: ") + nameString);
  217076. names.add (nameString);
  217077. ids.add (devs[i]);
  217078. }
  217079. }
  217080. alreadyLogged = true;
  217081. }
  217082. juce_free (devs);
  217083. }
  217084. }
  217085. const StringArray getDeviceNames (const bool /*preferInputNames*/) const
  217086. {
  217087. jassert (hasScanned); // need to call scanForDevices() before doing this
  217088. StringArray namesCopy (names);
  217089. namesCopy.removeDuplicates (true);
  217090. return namesCopy;
  217091. }
  217092. const String getDefaultDeviceName (const bool preferInputNames,
  217093. const int numInputChannelsNeeded,
  217094. const int numOutputChannelsNeeded) const
  217095. {
  217096. jassert (hasScanned); // need to call scanForDevices() before doing this
  217097. String result (names[0]);
  217098. AudioDeviceID deviceID;
  217099. UInt32 size = sizeof (deviceID);
  217100. // if they're asking for any input channels at all, use the default input, so we
  217101. // get the built-in mic rather than the built-in output with no inputs..
  217102. if (AudioHardwareGetProperty (numInputChannelsNeeded > 0
  217103. ? kAudioHardwarePropertyDefaultInputDevice
  217104. : kAudioHardwarePropertyDefaultOutputDevice,
  217105. &size, &deviceID) == noErr)
  217106. {
  217107. for (int i = ids.size(); --i >= 0;)
  217108. if (ids[i] == deviceID)
  217109. result = names[i];
  217110. }
  217111. return result;
  217112. }
  217113. AudioIODevice* createDevice (const String& deviceName)
  217114. {
  217115. jassert (hasScanned); // need to call scanForDevices() before doing this
  217116. const int index = names.indexOf (deviceName);
  217117. if (index >= 0)
  217118. return new CoreAudioIODevice (deviceName, ids [index]);
  217119. return 0;
  217120. }
  217121. juce_UseDebuggingNewOperator
  217122. private:
  217123. StringArray names;
  217124. Array <AudioDeviceID> ids;
  217125. bool hasScanned;
  217126. CoreAudioIODeviceType (const CoreAudioIODeviceType&);
  217127. const CoreAudioIODeviceType& operator= (const CoreAudioIODeviceType&);
  217128. };
  217129. AudioIODeviceType* juce_createDefaultAudioIODeviceType()
  217130. {
  217131. return new CoreAudioIODeviceType();
  217132. }
  217133. #undef log
  217134. END_JUCE_NAMESPACE
  217135. /********* End of inlined file: juce_mac_CoreAudio.cpp *********/
  217136. /********* Start of inlined file: juce_mac_CoreMidi.cpp *********/
  217137. #include <CoreMIDI/MIDIServices.h>
  217138. BEGIN_JUCE_NAMESPACE
  217139. #undef log
  217140. #define log(a) Logger::writeToLog(a)
  217141. static bool logAnyErrorsMidi (const OSStatus err, const int lineNum)
  217142. {
  217143. if (err == noErr)
  217144. return true;
  217145. log (T("CoreMidi error: ") + String (lineNum) + T(" - ") + String::toHexString ((int)err));
  217146. jassertfalse
  217147. return false;
  217148. }
  217149. #undef OK
  217150. #define OK(a) logAnyErrorsMidi(a, __LINE__)
  217151. static const String getEndpointName (MIDIEndpointRef endpoint, bool isExternal)
  217152. {
  217153. String result;
  217154. CFStringRef str = 0;
  217155. MIDIObjectGetStringProperty (endpoint, kMIDIPropertyName, &str);
  217156. if (str != 0)
  217157. {
  217158. result = PlatformUtilities::cfStringToJuceString (str);
  217159. CFRelease (str);
  217160. str = 0;
  217161. }
  217162. MIDIEntityRef entity = 0;
  217163. MIDIEndpointGetEntity (endpoint, &entity);
  217164. if (entity == 0)
  217165. return result; // probably virtual
  217166. if (result.isEmpty())
  217167. {
  217168. // endpoint name has zero length - try the entity
  217169. MIDIObjectGetStringProperty (entity, kMIDIPropertyName, &str);
  217170. if (str != 0)
  217171. {
  217172. result += PlatformUtilities::cfStringToJuceString (str);
  217173. CFRelease (str);
  217174. str = 0;
  217175. }
  217176. }
  217177. // now consider the device's name
  217178. MIDIDeviceRef device = 0;
  217179. MIDIEntityGetDevice (entity, &device);
  217180. if (device == 0)
  217181. return result;
  217182. MIDIObjectGetStringProperty (device, kMIDIPropertyName, &str);
  217183. if (str != 0)
  217184. {
  217185. const String s (PlatformUtilities::cfStringToJuceString (str));
  217186. CFRelease (str);
  217187. // if an external device has only one entity, throw away
  217188. // the endpoint name and just use the device name
  217189. if (isExternal && MIDIDeviceGetNumberOfEntities (device) < 2)
  217190. {
  217191. result = s;
  217192. }
  217193. else if (! result.startsWithIgnoreCase (s))
  217194. {
  217195. // prepend the device name to the entity name
  217196. result = (s + T(" ") + result).trimEnd();
  217197. }
  217198. }
  217199. return result;
  217200. }
  217201. static const String getConnectedEndpointName (MIDIEndpointRef endpoint)
  217202. {
  217203. String result;
  217204. // Does the endpoint have connections?
  217205. CFDataRef connections = 0;
  217206. int numConnections = 0;
  217207. MIDIObjectGetDataProperty (endpoint, kMIDIPropertyConnectionUniqueID, &connections);
  217208. if (connections != 0)
  217209. {
  217210. numConnections = CFDataGetLength (connections) / sizeof (MIDIUniqueID);
  217211. if (numConnections > 0)
  217212. {
  217213. const SInt32* pid = reinterpret_cast <const SInt32*> (CFDataGetBytePtr (connections));
  217214. for (int i = 0; i < numConnections; ++i, ++pid)
  217215. {
  217216. MIDIUniqueID uid = EndianS32_BtoN (*pid);
  217217. MIDIObjectRef connObject;
  217218. MIDIObjectType connObjectType;
  217219. OSStatus err = MIDIObjectFindByUniqueID (uid, &connObject, &connObjectType);
  217220. if (err == noErr)
  217221. {
  217222. String s;
  217223. if (connObjectType == kMIDIObjectType_ExternalSource
  217224. || connObjectType == kMIDIObjectType_ExternalDestination)
  217225. {
  217226. // Connected to an external device's endpoint (10.3 and later).
  217227. s = getEndpointName (static_cast <MIDIEndpointRef> (connObject), true);
  217228. }
  217229. else
  217230. {
  217231. // Connected to an external device (10.2) (or something else, catch-all)
  217232. CFStringRef str = 0;
  217233. MIDIObjectGetStringProperty (connObject, kMIDIPropertyName, &str);
  217234. if (str != 0)
  217235. {
  217236. s = PlatformUtilities::cfStringToJuceString (str);
  217237. CFRelease (str);
  217238. }
  217239. }
  217240. if (s.isNotEmpty())
  217241. {
  217242. if (result.isNotEmpty())
  217243. result += (", ");
  217244. result += s;
  217245. }
  217246. }
  217247. }
  217248. }
  217249. CFRelease (connections);
  217250. }
  217251. if (result.isNotEmpty())
  217252. return result;
  217253. // Here, either the endpoint had no connections, or we failed to obtain names for any of them.
  217254. return getEndpointName (endpoint, false);
  217255. }
  217256. const StringArray MidiOutput::getDevices()
  217257. {
  217258. StringArray s;
  217259. const ItemCount num = MIDIGetNumberOfDestinations();
  217260. for (ItemCount i = 0; i < num; ++i)
  217261. {
  217262. MIDIEndpointRef dest = MIDIGetDestination (i);
  217263. if (dest != 0)
  217264. {
  217265. String name (getConnectedEndpointName (dest));
  217266. if (name.isEmpty())
  217267. name = "<error>";
  217268. s.add (name);
  217269. }
  217270. else
  217271. {
  217272. s.add ("<error>");
  217273. }
  217274. }
  217275. return s;
  217276. }
  217277. int MidiOutput::getDefaultDeviceIndex()
  217278. {
  217279. return 0;
  217280. }
  217281. static MIDIClientRef globalMidiClient;
  217282. static bool hasGlobalClientBeenCreated = false;
  217283. static bool makeSureClientExists()
  217284. {
  217285. if (! hasGlobalClientBeenCreated)
  217286. {
  217287. String name (T("JUCE"));
  217288. if (JUCEApplication::getInstance() != 0)
  217289. name = JUCEApplication::getInstance()->getApplicationName();
  217290. CFStringRef appName = PlatformUtilities::juceStringToCFString (name);
  217291. hasGlobalClientBeenCreated = OK (MIDIClientCreate (appName, 0, 0, &globalMidiClient));
  217292. CFRelease (appName);
  217293. }
  217294. return hasGlobalClientBeenCreated;
  217295. }
  217296. struct MidiPortAndEndpoint
  217297. {
  217298. MIDIPortRef port;
  217299. MIDIEndpointRef endPoint;
  217300. };
  217301. MidiOutput* MidiOutput::openDevice (int index)
  217302. {
  217303. MidiOutput* mo = 0;
  217304. if (((unsigned int) index) < (unsigned int) MIDIGetNumberOfDestinations())
  217305. {
  217306. MIDIEndpointRef endPoint = MIDIGetDestination (index);
  217307. CFStringRef pname;
  217308. if (OK (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  217309. {
  217310. log (T("CoreMidi - opening out: ") + PlatformUtilities::cfStringToJuceString (pname));
  217311. if (makeSureClientExists())
  217312. {
  217313. MIDIPortRef port;
  217314. if (OK (MIDIOutputPortCreate (globalMidiClient, pname, &port)))
  217315. {
  217316. MidiPortAndEndpoint* mpe = new MidiPortAndEndpoint();
  217317. mpe->port = port;
  217318. mpe->endPoint = endPoint;
  217319. mo = new MidiOutput();
  217320. mo->internal = (void*)mpe;
  217321. }
  217322. }
  217323. CFRelease (pname);
  217324. }
  217325. }
  217326. return mo;
  217327. }
  217328. MidiOutput::~MidiOutput()
  217329. {
  217330. MidiPortAndEndpoint* const mpe = (MidiPortAndEndpoint*)internal;
  217331. MIDIPortDispose (mpe->port);
  217332. delete mpe;
  217333. }
  217334. void MidiOutput::reset()
  217335. {
  217336. }
  217337. bool MidiOutput::getVolume (float& leftVol, float& rightVol)
  217338. {
  217339. return false;
  217340. }
  217341. void MidiOutput::setVolume (float leftVol, float rightVol)
  217342. {
  217343. }
  217344. void MidiOutput::sendMessageNow (const MidiMessage& message)
  217345. {
  217346. MidiPortAndEndpoint* const mpe = (MidiPortAndEndpoint*)internal;
  217347. if (message.isSysEx())
  217348. {
  217349. MIDIPacketList* const packets = (MIDIPacketList*) juce_malloc (32 + message.getRawDataSize());
  217350. packets->numPackets = 1;
  217351. packets->packet[0].timeStamp = 0;
  217352. packets->packet[0].length = message.getRawDataSize();
  217353. memcpy (packets->packet[0].data, message.getRawData(), message.getRawDataSize());
  217354. MIDISend (mpe->port, mpe->endPoint, packets);
  217355. juce_free (packets);
  217356. }
  217357. else
  217358. {
  217359. MIDIPacketList packets;
  217360. packets.numPackets = 1;
  217361. packets.packet[0].timeStamp = 0;
  217362. packets.packet[0].length = message.getRawDataSize();
  217363. *(int*) (packets.packet[0].data) = *(const int*) message.getRawData();
  217364. MIDISend (mpe->port, mpe->endPoint, &packets);
  217365. }
  217366. }
  217367. const StringArray MidiInput::getDevices()
  217368. {
  217369. StringArray s;
  217370. const ItemCount num = MIDIGetNumberOfSources();
  217371. for (ItemCount i = 0; i < num; ++i)
  217372. {
  217373. MIDIEndpointRef source = MIDIGetSource (i);
  217374. if (source != 0)
  217375. {
  217376. String name (getConnectedEndpointName (source));
  217377. if (name.isEmpty())
  217378. name = "<error>";
  217379. s.add (name);
  217380. }
  217381. else
  217382. {
  217383. s.add ("<error>");
  217384. }
  217385. }
  217386. return s;
  217387. }
  217388. int MidiInput::getDefaultDeviceIndex()
  217389. {
  217390. return 0;
  217391. }
  217392. struct MidiPortAndCallback
  217393. {
  217394. MidiInput* input;
  217395. MIDIPortRef port;
  217396. MIDIEndpointRef endPoint;
  217397. MidiInputCallback* callback;
  217398. MemoryBlock pendingData;
  217399. int pendingBytes;
  217400. double pendingDataTime;
  217401. bool active;
  217402. };
  217403. static CriticalSection callbackLock;
  217404. static VoidArray activeCallbacks;
  217405. static void processSysex (MidiPortAndCallback* const mpe, const uint8*& d, int& size, const double time)
  217406. {
  217407. if (*d == 0xf0)
  217408. {
  217409. mpe->pendingBytes = 0;
  217410. mpe->pendingDataTime = time;
  217411. }
  217412. mpe->pendingData.ensureSize (mpe->pendingBytes + size, false);
  217413. uint8* totalMessage = (uint8*) mpe->pendingData.getData();
  217414. uint8* dest = totalMessage + mpe->pendingBytes;
  217415. while (size > 0)
  217416. {
  217417. if (mpe->pendingBytes > 0 && *d >= 0x80)
  217418. {
  217419. if (*d >= 0xfa || *d == 0xf8)
  217420. {
  217421. mpe->callback->handleIncomingMidiMessage (mpe->input, MidiMessage (*d, time));
  217422. ++d;
  217423. --size;
  217424. }
  217425. else
  217426. {
  217427. if (*d == 0xf7)
  217428. {
  217429. *dest++ = *d++;
  217430. mpe->pendingBytes++;
  217431. --size;
  217432. }
  217433. break;
  217434. }
  217435. }
  217436. else
  217437. {
  217438. *dest++ = *d++;
  217439. mpe->pendingBytes++;
  217440. --size;
  217441. }
  217442. }
  217443. if (totalMessage [mpe->pendingBytes - 1] == 0xf7)
  217444. {
  217445. mpe->callback->handleIncomingMidiMessage (mpe->input, MidiMessage (totalMessage,
  217446. mpe->pendingBytes,
  217447. mpe->pendingDataTime));
  217448. mpe->pendingBytes = 0;
  217449. }
  217450. else
  217451. {
  217452. mpe->callback->handlePartialSysexMessage (mpe->input,
  217453. totalMessage,
  217454. mpe->pendingBytes,
  217455. mpe->pendingDataTime);
  217456. }
  217457. }
  217458. static void midiInputProc (const MIDIPacketList* pktlist,
  217459. void* readProcRefCon,
  217460. void* srcConnRefCon)
  217461. {
  217462. double time = Time::getMillisecondCounterHiRes() * 0.001;
  217463. const double originalTime = time;
  217464. MidiPortAndCallback* const mpe = (MidiPortAndCallback*) readProcRefCon;
  217465. const ScopedLock sl (callbackLock);
  217466. if (activeCallbacks.contains (mpe) && mpe->active)
  217467. {
  217468. const MIDIPacket* packet = &pktlist->packet[0];
  217469. for (unsigned int i = 0; i < pktlist->numPackets; ++i)
  217470. {
  217471. const uint8* d = (const uint8*) (packet->data);
  217472. int size = packet->length;
  217473. while (size > 0)
  217474. {
  217475. time = originalTime;
  217476. if (mpe->pendingBytes > 0 || d[0] == 0xf0)
  217477. {
  217478. processSysex (mpe, d, size, time);
  217479. }
  217480. else
  217481. {
  217482. int used = 0;
  217483. const MidiMessage m (d, size, used, 0, time);
  217484. if (used <= 0)
  217485. {
  217486. jassertfalse // malformed midi message
  217487. break;
  217488. }
  217489. else
  217490. {
  217491. mpe->callback->handleIncomingMidiMessage (mpe->input, m);
  217492. }
  217493. size -= used;
  217494. d += used;
  217495. }
  217496. }
  217497. packet = MIDIPacketNext (packet);
  217498. }
  217499. }
  217500. }
  217501. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback)
  217502. {
  217503. MidiInput* mi = 0;
  217504. if (((unsigned int) index) < (unsigned int) MIDIGetNumberOfSources())
  217505. {
  217506. MIDIEndpointRef endPoint = MIDIGetSource (index);
  217507. if (endPoint != 0)
  217508. {
  217509. CFStringRef pname;
  217510. if (OK (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  217511. {
  217512. log (T("CoreMidi - opening inp: ") + PlatformUtilities::cfStringToJuceString (pname));
  217513. if (makeSureClientExists())
  217514. {
  217515. MIDIPortRef port;
  217516. MidiPortAndCallback* const mpe = new MidiPortAndCallback();
  217517. mpe->active = false;
  217518. if (OK (MIDIInputPortCreate (globalMidiClient, pname, midiInputProc, mpe, &port)))
  217519. {
  217520. if (OK (MIDIPortConnectSource (port, endPoint, 0)))
  217521. {
  217522. mpe->port = port;
  217523. mpe->endPoint = endPoint;
  217524. mpe->callback = callback;
  217525. mpe->pendingBytes = 0;
  217526. mpe->pendingData.ensureSize (128);
  217527. mi = new MidiInput (getDevices() [index]);
  217528. mpe->input = mi;
  217529. mi->internal = (void*) mpe;
  217530. const ScopedLock sl (callbackLock);
  217531. activeCallbacks.add (mpe);
  217532. }
  217533. else
  217534. {
  217535. OK (MIDIPortDispose (port));
  217536. delete mpe;
  217537. }
  217538. }
  217539. else
  217540. {
  217541. delete mpe;
  217542. }
  217543. }
  217544. }
  217545. CFRelease (pname);
  217546. }
  217547. }
  217548. return mi;
  217549. }
  217550. MidiInput::MidiInput (const String& name_)
  217551. : name (name_)
  217552. {
  217553. }
  217554. MidiInput::~MidiInput()
  217555. {
  217556. MidiPortAndCallback* const mpe = (MidiPortAndCallback*) internal;
  217557. mpe->active = false;
  217558. callbackLock.enter();
  217559. activeCallbacks.removeValue (mpe);
  217560. callbackLock.exit();
  217561. OK (MIDIPortDisconnectSource (mpe->port, mpe->endPoint));
  217562. OK (MIDIPortDispose (mpe->port));
  217563. delete mpe;
  217564. }
  217565. void MidiInput::start()
  217566. {
  217567. MidiPortAndCallback* const mpe = (MidiPortAndCallback*) internal;
  217568. const ScopedLock sl (callbackLock);
  217569. mpe->active = true;
  217570. }
  217571. void MidiInput::stop()
  217572. {
  217573. MidiPortAndCallback* const mpe = (MidiPortAndCallback*) internal;
  217574. const ScopedLock sl (callbackLock);
  217575. mpe->active = false;
  217576. }
  217577. #undef log
  217578. END_JUCE_NAMESPACE
  217579. /********* End of inlined file: juce_mac_CoreMidi.cpp *********/
  217580. /********* Start of inlined file: juce_mac_FileChooser.cpp *********/
  217581. #include <Carbon/Carbon.h>
  217582. #include <fnmatch.h>
  217583. BEGIN_JUCE_NAMESPACE
  217584. struct JuceNavInfo
  217585. {
  217586. StringArray filters;
  217587. AEDesc defaultLocation;
  217588. bool defaultLocationValid;
  217589. };
  217590. static void pascal juceNavEventProc (NavEventCallbackMessage callbackSelector,
  217591. NavCBRecPtr callbackParms,
  217592. void *callBackUD)
  217593. {
  217594. if (callbackSelector == kNavCBStart)
  217595. {
  217596. if (((JuceNavInfo*) callBackUD)->defaultLocationValid)
  217597. {
  217598. NavCustomControl (callbackParms->context,
  217599. kNavCtlSetLocation,
  217600. (void*) &((JuceNavInfo*) callBackUD)->defaultLocation);
  217601. }
  217602. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  217603. {
  217604. Component* const c = Desktop::getInstance().getComponent (i);
  217605. if (c != 0 && c->isAlwaysOnTop() && c->isVisible())
  217606. {
  217607. SetWindowGroup (callbackParms->window,
  217608. GetWindowGroup ((WindowRef) c->getWindowHandle()));
  217609. break;
  217610. }
  217611. }
  217612. BringToFront (callbackParms->window);
  217613. SelectWindow (callbackParms->window);
  217614. SetUserFocusWindow (callbackParms->window);
  217615. }
  217616. }
  217617. static Boolean pascal juceNavFilterProc (AEDesc* theItem,
  217618. void*,
  217619. void* callBackUD,
  217620. NavFilterModes filterMode)
  217621. {
  217622. // must return true if we don't understand the object
  217623. bool result = true;
  217624. if (filterMode == kNavFilteringBrowserList)
  217625. {
  217626. AEDesc desc;
  217627. if (AECoerceDesc (theItem, typeFSRef, &desc) == noErr)
  217628. {
  217629. Size size = AEGetDescDataSize (&desc);
  217630. if (size > 0)
  217631. {
  217632. void* data = juce_calloc (size);
  217633. if (AEGetDescData (&desc, data, size) == noErr)
  217634. {
  217635. const String path (PlatformUtilities::makePathFromFSRef ((FSRef*) data));
  217636. if (path.isNotEmpty())
  217637. {
  217638. const File file (path);
  217639. if ((! file.isDirectory()) || PlatformUtilities::isBundle (path))
  217640. {
  217641. const String filename (file.getFileName().toLowerCase());
  217642. const char* const filenameUTF8 = filename.toUTF8();
  217643. const JuceNavInfo* const info = (const JuceNavInfo*) callBackUD;
  217644. if (info != 0)
  217645. {
  217646. result = false;
  217647. for (int i = info->filters.size(); --i >= 0;)
  217648. {
  217649. const String wildcard (info->filters[i].toLowerCase());
  217650. if (fnmatch (wildcard.toUTF8(), filenameUTF8, 0) == 0)
  217651. {
  217652. result = true;
  217653. break;
  217654. }
  217655. }
  217656. }
  217657. }
  217658. }
  217659. }
  217660. juce_free (data);
  217661. }
  217662. AEDisposeDesc (&desc);
  217663. }
  217664. }
  217665. return result;
  217666. }
  217667. void FileChooser::showPlatformDialog (OwnedArray<File>& results,
  217668. const String& title,
  217669. const File& currentFileOrDirectory,
  217670. const String& filter,
  217671. bool selectsDirectory,
  217672. bool isSaveDialogue,
  217673. bool warnAboutOverwritingExistingFiles,
  217674. bool selectMultipleFiles,
  217675. FilePreviewComponent* extraInfoComponent)
  217676. {
  217677. JuceNavInfo userInfo;
  217678. userInfo.filters.addTokens (filter.replaceCharacters (T(",:"), T(";;")), T(";"), 0);
  217679. userInfo.filters.trim();
  217680. userInfo.filters.removeEmptyStrings();
  217681. userInfo.defaultLocationValid = false;
  217682. void* const userInfoPtr = (void*) &userInfo;
  217683. const int oldTimeBeforeWaitCursor = MessageManager::getInstance()->getTimeBeforeShowingWaitCursor();
  217684. MessageManager::getInstance()->setTimeBeforeShowingWaitCursor (0);
  217685. NavEventUPP eventProc = NewNavEventUPP (juceNavEventProc);
  217686. NavObjectFilterUPP filterProc = NewNavObjectFilterUPP (juceNavFilterProc);
  217687. FSRef defaultRef;
  217688. if ((currentFileOrDirectory.isOnHardDisk()
  217689. && PlatformUtilities::makeFSRefFromPath (&defaultRef,
  217690. currentFileOrDirectory.getFullPathName()))
  217691. || (currentFileOrDirectory.getParentDirectory().isOnHardDisk()
  217692. && PlatformUtilities::makeFSRefFromPath (&defaultRef,
  217693. currentFileOrDirectory.getParentDirectory().getFullPathName())))
  217694. {
  217695. if (AECreateDesc (typeFSRef, &defaultRef, sizeof (defaultRef), &userInfo.defaultLocation) == noErr)
  217696. {
  217697. userInfo.defaultLocationValid = true;
  217698. }
  217699. }
  217700. WindowRef lastFocused = GetUserFocusWindow();
  217701. NavDialogCreationOptions options;
  217702. if (NavGetDefaultDialogCreationOptions (&options) == noErr)
  217703. {
  217704. options.optionFlags |= kNavSelectDefaultLocation
  217705. | kNavSupportPackages
  217706. | kNavAllowPreviews;
  217707. if (! warnAboutOverwritingExistingFiles)
  217708. options.optionFlags |= kNavDontConfirmReplacement;
  217709. if (selectMultipleFiles)
  217710. options.optionFlags |= kNavAllowMultipleFiles;
  217711. const String name (selectsDirectory ? TRANS("Choose folder")
  217712. : TRANS("Choose file"));
  217713. options.clientName = PlatformUtilities::juceStringToCFString (name);
  217714. CFStringRef message = PlatformUtilities::juceStringToCFString (title);
  217715. // nasty layout bug if the message text is set for a directory browser..
  217716. if (selectsDirectory)
  217717. options.windowTitle = message;
  217718. else
  217719. options.message = message;
  217720. NavDialogRef dialog = 0;
  217721. bool ok = false;
  217722. if (selectsDirectory)
  217723. {
  217724. ok = (NavCreateChooseFolderDialog (&options, eventProc, 0, userInfoPtr, &dialog) == noErr);
  217725. }
  217726. else if (isSaveDialogue)
  217727. {
  217728. ok = (NavCreatePutFileDialog (&options, 0, 0, eventProc, userInfoPtr, &dialog) == noErr);
  217729. }
  217730. else
  217731. {
  217732. ok = (NavCreateGetFileDialog (&options, 0, eventProc, 0, filterProc, userInfoPtr, &dialog) == noErr);
  217733. }
  217734. if (ok && (NavDialogRun (dialog) == noErr))
  217735. {
  217736. NavReplyRecord reply;
  217737. if (NavDialogGetReply (dialog, &reply) == noErr)
  217738. {
  217739. if (reply.validRecord)
  217740. {
  217741. long count;
  217742. if (AECountItems (&(reply.selection), &count) == noErr
  217743. && count > 0)
  217744. {
  217745. AEKeyword theKeyword;
  217746. DescType actualType;
  217747. Size actualSize;
  217748. FSRef file;
  217749. for (int i = 1; i <= count; ++i)
  217750. {
  217751. // Get a pointer to selected file
  217752. if (AEGetNthPtr (&(reply.selection),
  217753. i,
  217754. typeFSRef,
  217755. &theKeyword,
  217756. &actualType,
  217757. &file,
  217758. sizeof (file),
  217759. &actualSize) == noErr)
  217760. {
  217761. String result (PlatformUtilities::makePathFromFSRef (&file));
  217762. if (result.isNotEmpty() && isSaveDialogue && ! selectsDirectory)
  217763. {
  217764. CFStringRef saveName = NavDialogGetSaveFileName (dialog);
  217765. result = File (result)
  217766. .getChildFile (PlatformUtilities::convertToPrecomposedUnicode (PlatformUtilities::cfStringToJuceString (saveName)))
  217767. .getFullPathName();
  217768. }
  217769. results.add (new File (result));
  217770. }
  217771. }
  217772. }
  217773. }
  217774. NavDisposeReply (&reply);
  217775. }
  217776. }
  217777. if (dialog != 0)
  217778. NavDialogDispose (dialog);
  217779. CFRelease (message);
  217780. CFRelease (options.clientName);
  217781. }
  217782. if (userInfo.defaultLocationValid)
  217783. AEDisposeDesc (&userInfo.defaultLocation);
  217784. DisposeNavEventUPP (eventProc);
  217785. DisposeNavObjectFilterUPP (filterProc);
  217786. MessageManager::getInstance()->setTimeBeforeShowingWaitCursor (oldTimeBeforeWaitCursor);
  217787. SetUserFocusWindow (lastFocused);
  217788. }
  217789. END_JUCE_NAMESPACE
  217790. /********* End of inlined file: juce_mac_FileChooser.cpp *********/
  217791. /********* Start of inlined file: juce_mac_Fonts.cpp *********/
  217792. #include <ApplicationServices/ApplicationServices.h>
  217793. BEGIN_JUCE_NAMESPACE
  217794. static OSStatus pascal CubicMoveTo (const Float32Point *pt,
  217795. void* callBackDataPtr)
  217796. {
  217797. Path* const p = (Path*) callBackDataPtr;
  217798. p->startNewSubPath (pt->x, pt->y);
  217799. return noErr;
  217800. }
  217801. static OSStatus pascal CubicLineTo (const Float32Point *pt,
  217802. void* callBackDataPtr)
  217803. {
  217804. Path* const p = (Path*) callBackDataPtr;
  217805. p->lineTo (pt->x, pt->y);
  217806. return noErr;
  217807. }
  217808. static OSStatus pascal CubicCurveTo (const Float32Point *pt1,
  217809. const Float32Point *pt2,
  217810. const Float32Point *pt3,
  217811. void* callBackDataPtr)
  217812. {
  217813. Path* const p = (Path*) callBackDataPtr;
  217814. p->cubicTo (pt1->x, pt1->y,
  217815. pt2->x, pt2->y,
  217816. pt3->x, pt3->y);
  217817. return noErr;
  217818. }
  217819. static OSStatus pascal CubicClosePath (void* callBackDataPtr)
  217820. {
  217821. Path* const p = (Path*) callBackDataPtr;
  217822. p->closeSubPath();
  217823. return noErr;
  217824. }
  217825. class ATSFontHelper
  217826. {
  217827. ATSUFontID fontId;
  217828. ATSUStyle style;
  217829. ATSCubicMoveToUPP moveToProc;
  217830. ATSCubicLineToUPP lineToProc;
  217831. ATSCubicCurveToUPP curveToProc;
  217832. ATSCubicClosePathUPP closePathProc;
  217833. float totalSize, ascent;
  217834. TextToUnicodeInfo encodingInfo;
  217835. public:
  217836. String name;
  217837. bool isBold, isItalic;
  217838. float fontSize;
  217839. int refCount;
  217840. ATSFontHelper (const String& name_,
  217841. const bool bold_,
  217842. const bool italic_,
  217843. const float size_)
  217844. : fontId (0),
  217845. name (name_),
  217846. isBold (bold_),
  217847. isItalic (italic_),
  217848. fontSize (size_),
  217849. refCount (1)
  217850. {
  217851. const char* const nameUtf8 = name_.toUTF8();
  217852. ATSUFindFontFromName (const_cast <char*> (nameUtf8),
  217853. strlen (nameUtf8),
  217854. kFontFullName,
  217855. kFontNoPlatformCode,
  217856. kFontNoScriptCode,
  217857. kFontNoLanguageCode,
  217858. &fontId);
  217859. ATSUCreateStyle (&style);
  217860. ATSUAttributeTag attTypes[] = { kATSUFontTag,
  217861. kATSUQDBoldfaceTag,
  217862. kATSUQDItalicTag,
  217863. kATSUSizeTag };
  217864. ByteCount attSizes[] = { sizeof (ATSUFontID),
  217865. sizeof (Boolean),
  217866. sizeof (Boolean),
  217867. sizeof (Fixed) };
  217868. Boolean bold = bold_, italic = italic_;
  217869. Fixed size = X2Fix (size_);
  217870. ATSUAttributeValuePtr attValues[] = { &fontId,
  217871. &bold,
  217872. &italic,
  217873. &size };
  217874. ATSUSetAttributes (style, 4, attTypes, attSizes, attValues);
  217875. moveToProc = NewATSCubicMoveToUPP (CubicMoveTo);
  217876. lineToProc = NewATSCubicLineToUPP (CubicLineTo);
  217877. curveToProc = NewATSCubicCurveToUPP (CubicCurveTo);
  217878. closePathProc = NewATSCubicClosePathUPP (CubicClosePath);
  217879. ascent = 0.0f;
  217880. float kern, descent = 0.0f;
  217881. getPathAndKerning (T('N'), T('O'), 0, kern, &ascent, &descent);
  217882. totalSize = ascent + descent;
  217883. }
  217884. ~ATSFontHelper()
  217885. {
  217886. ATSUDisposeStyle (style);
  217887. DisposeATSCubicMoveToUPP (moveToProc);
  217888. DisposeATSCubicLineToUPP (lineToProc);
  217889. DisposeATSCubicCurveToUPP (curveToProc);
  217890. DisposeATSCubicClosePathUPP (closePathProc);
  217891. }
  217892. bool getPathAndKerning (const juce_wchar char1,
  217893. const juce_wchar char2,
  217894. Path* path,
  217895. float& kerning,
  217896. float* ascent,
  217897. float* descent)
  217898. {
  217899. bool ok = false;
  217900. UniChar buffer[4];
  217901. buffer[0] = T(' ');
  217902. buffer[1] = char1;
  217903. buffer[2] = char2;
  217904. buffer[3] = 0;
  217905. UniCharCount count = kATSUToTextEnd;
  217906. ATSUTextLayout layout;
  217907. OSStatus err = ATSUCreateTextLayoutWithTextPtr (buffer,
  217908. 0,
  217909. 2,
  217910. 2,
  217911. 1,
  217912. &count,
  217913. &style,
  217914. &layout);
  217915. if (err == noErr)
  217916. {
  217917. ATSUSetTransientFontMatching (layout, true);
  217918. ATSLayoutRecord* layoutRecords;
  217919. ItemCount numRecords;
  217920. Fixed* deltaYs;
  217921. ItemCount numDeltaYs;
  217922. ATSUDirectGetLayoutDataArrayPtrFromTextLayout (layout,
  217923. 0,
  217924. kATSUDirectDataLayoutRecordATSLayoutRecordCurrent,
  217925. (void**) &layoutRecords,
  217926. &numRecords);
  217927. ATSUDirectGetLayoutDataArrayPtrFromTextLayout (layout,
  217928. 0,
  217929. kATSUDirectDataBaselineDeltaFixedArray,
  217930. (void**) &deltaYs,
  217931. &numDeltaYs);
  217932. if (numRecords > 2)
  217933. {
  217934. kerning = (float) (Fix2X (layoutRecords[2].realPos)
  217935. - Fix2X (layoutRecords[1].realPos));
  217936. if (ascent != 0)
  217937. {
  217938. ATSUTextMeasurement asc;
  217939. ByteCount actualSize;
  217940. ATSUGetLineControl (layout,
  217941. 0,
  217942. kATSULineAscentTag,
  217943. sizeof (ATSUTextMeasurement),
  217944. &asc,
  217945. &actualSize);
  217946. *ascent = (float) Fix2X (asc);
  217947. }
  217948. if (descent != 0)
  217949. {
  217950. ATSUTextMeasurement desc;
  217951. ByteCount actualSize;
  217952. ATSUGetLineControl (layout,
  217953. 0,
  217954. kATSULineDescentTag,
  217955. sizeof (ATSUTextMeasurement),
  217956. &desc,
  217957. &actualSize);
  217958. *descent = (float) Fix2X (desc);
  217959. }
  217960. if (path != 0)
  217961. {
  217962. OSStatus callbackResult;
  217963. ok = (ATSUGlyphGetCubicPaths (style,
  217964. layoutRecords[1].glyphID,
  217965. moveToProc,
  217966. lineToProc,
  217967. curveToProc,
  217968. closePathProc,
  217969. (void*) path,
  217970. &callbackResult) == noErr);
  217971. if (numDeltaYs > 0 && ok)
  217972. {
  217973. const float dy = (float) Fix2X (deltaYs[1]);
  217974. path->applyTransform (AffineTransform::translation (0.0f, dy));
  217975. }
  217976. }
  217977. else
  217978. {
  217979. ok = true;
  217980. }
  217981. }
  217982. if (deltaYs != 0)
  217983. ATSUDirectReleaseLayoutDataArrayPtr (0, kATSUDirectDataBaselineDeltaFixedArray,
  217984. (void**) &deltaYs);
  217985. if (layoutRecords != 0)
  217986. ATSUDirectReleaseLayoutDataArrayPtr (0, kATSUDirectDataLayoutRecordATSLayoutRecordCurrent,
  217987. (void**) &layoutRecords);
  217988. ATSUDisposeTextLayout (layout);
  217989. }
  217990. return kerning;
  217991. }
  217992. float getAscent()
  217993. {
  217994. return ascent;
  217995. }
  217996. float getTotalHeight()
  217997. {
  217998. return totalSize;
  217999. }
  218000. juce_wchar getDefaultChar()
  218001. {
  218002. return 0;
  218003. }
  218004. };
  218005. class ATSFontHelperCache : public Timer,
  218006. public DeletedAtShutdown
  218007. {
  218008. VoidArray cache;
  218009. public:
  218010. ATSFontHelperCache()
  218011. {
  218012. }
  218013. ~ATSFontHelperCache()
  218014. {
  218015. for (int i = cache.size(); --i >= 0;)
  218016. {
  218017. ATSFontHelper* const f = (ATSFontHelper*) cache.getUnchecked(i);
  218018. delete f;
  218019. }
  218020. clearSingletonInstance();
  218021. }
  218022. ATSFontHelper* getFont (const String& name,
  218023. const bool bold,
  218024. const bool italic,
  218025. const float size = 1024)
  218026. {
  218027. for (int i = cache.size(); --i >= 0;)
  218028. {
  218029. ATSFontHelper* const f = (ATSFontHelper*) cache.getUnchecked(i);
  218030. if (f->name == name
  218031. && f->isBold == bold
  218032. && f->isItalic == italic
  218033. && f->fontSize == size)
  218034. {
  218035. f->refCount++;
  218036. return f;
  218037. }
  218038. }
  218039. ATSFontHelper* const f = new ATSFontHelper (name, bold, italic, size);
  218040. cache.add (f);
  218041. return f;
  218042. }
  218043. void releaseFont (ATSFontHelper* f)
  218044. {
  218045. for (int i = cache.size(); --i >= 0;)
  218046. {
  218047. ATSFontHelper* const f2 = (ATSFontHelper*) cache.getUnchecked(i);
  218048. if (f == f2)
  218049. {
  218050. f->refCount--;
  218051. if (f->refCount == 0)
  218052. startTimer (5000);
  218053. break;
  218054. }
  218055. }
  218056. }
  218057. void timerCallback()
  218058. {
  218059. stopTimer();
  218060. for (int i = cache.size(); --i >= 0;)
  218061. {
  218062. ATSFontHelper* const f = (ATSFontHelper*) cache.getUnchecked(i);
  218063. if (f->refCount == 0)
  218064. {
  218065. cache.remove (i);
  218066. delete f;
  218067. }
  218068. }
  218069. if (cache.size() == 0)
  218070. delete this;
  218071. }
  218072. juce_DeclareSingleton_SingleThreaded_Minimal (ATSFontHelperCache)
  218073. };
  218074. juce_ImplementSingleton_SingleThreaded (ATSFontHelperCache)
  218075. void Typeface::initialiseTypefaceCharacteristics (const String& fontName,
  218076. bool bold,
  218077. bool italic,
  218078. bool addAllGlyphsToFont) throw()
  218079. {
  218080. // This method is only safe to be called from the normal UI thread..
  218081. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  218082. ATSFontHelper* const helper = ATSFontHelperCache::getInstance()
  218083. ->getFont (fontName, bold, italic);
  218084. clear();
  218085. setAscent (helper->getAscent() / helper->getTotalHeight());
  218086. setName (fontName);
  218087. setDefaultCharacter (helper->getDefaultChar());
  218088. setBold (bold);
  218089. setItalic (italic);
  218090. if (addAllGlyphsToFont)
  218091. {
  218092. //xxx
  218093. jassertfalse
  218094. }
  218095. ATSFontHelperCache::getInstance()->releaseFont (helper);
  218096. }
  218097. bool Typeface::findAndAddSystemGlyph (juce_wchar character) throw()
  218098. {
  218099. // This method is only safe to be called from the normal UI thread..
  218100. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  218101. ATSFontHelper* const helper = ATSFontHelperCache::getInstance()
  218102. ->getFont (getName(), isBold(), isItalic());
  218103. Path path;
  218104. float width;
  218105. bool foundOne = false;
  218106. if (helper->getPathAndKerning (character, T('I'), &path, width, 0, 0))
  218107. {
  218108. path.applyTransform (AffineTransform::scale (1.0f / helper->getTotalHeight(),
  218109. 1.0f / helper->getTotalHeight()));
  218110. addGlyph (character, path, width / helper->getTotalHeight());
  218111. for (int i = 0; i < glyphs.size(); ++i)
  218112. {
  218113. const TypefaceGlyphInfo* const g = (const TypefaceGlyphInfo*) glyphs.getUnchecked(i);
  218114. float kerning;
  218115. if (helper->getPathAndKerning (character, g->getCharacter(), 0, kerning, 0, 0))
  218116. {
  218117. kerning = (kerning - width) / helper->getTotalHeight();
  218118. if (kerning != 0)
  218119. addKerningPair (character, g->getCharacter(), kerning);
  218120. }
  218121. if (helper->getPathAndKerning (g->getCharacter(), character, 0, kerning, 0, 0))
  218122. {
  218123. kerning = kerning / helper->getTotalHeight() - g->width;
  218124. if (kerning != 0)
  218125. addKerningPair (g->getCharacter(), character, kerning);
  218126. }
  218127. }
  218128. foundOne = true;
  218129. }
  218130. ATSFontHelperCache::getInstance()->releaseFont (helper);
  218131. return foundOne;
  218132. }
  218133. const StringArray Font::findAllTypefaceNames() throw()
  218134. {
  218135. StringArray names;
  218136. ATSFontIterator iter;
  218137. if (ATSFontIteratorCreate (kATSFontContextGlobal,
  218138. 0,
  218139. 0,
  218140. kATSOptionFlagsRestrictedScope,
  218141. &iter) == noErr)
  218142. {
  218143. ATSFontRef font;
  218144. while (ATSFontIteratorNext (iter, &font) == noErr)
  218145. {
  218146. CFStringRef name;
  218147. if (ATSFontGetName (font,
  218148. kATSOptionFlagsDefault,
  218149. &name) == noErr)
  218150. {
  218151. const String nm (PlatformUtilities::cfStringToJuceString (name));
  218152. if (nm.isNotEmpty())
  218153. names.add (nm);
  218154. CFRelease (name);
  218155. }
  218156. }
  218157. ATSFontIteratorRelease (&iter);
  218158. }
  218159. // Use some totuous logic to eliminate bold/italic versions of fonts that we've already got
  218160. // a plain version of. This is only necessary because of Carbon's total lack of support
  218161. // for dealing with font families...
  218162. for (int j = names.size(); --j >= 0;)
  218163. {
  218164. const char* const endings[] = { " bold", " italic", " bold italic", " bolditalic",
  218165. " oblque", " bold oblique", " boldoblique" };
  218166. for (int i = 0; i < numElementsInArray (endings); ++i)
  218167. {
  218168. const String ending (endings[i]);
  218169. if (names[j].endsWithIgnoreCase (ending))
  218170. {
  218171. const String root (names[j].dropLastCharacters (ending.length()).trimEnd());
  218172. if (names.contains (root)
  218173. || names.contains (root + T(" plain"), true))
  218174. {
  218175. names.remove (j);
  218176. break;
  218177. }
  218178. }
  218179. }
  218180. }
  218181. names.sort (true);
  218182. return names;
  218183. }
  218184. void Font::getDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed) throw()
  218185. {
  218186. defaultSans = "Lucida Grande";
  218187. defaultSerif = "Times New Roman";
  218188. defaultFixed = "Monaco";
  218189. }
  218190. END_JUCE_NAMESPACE
  218191. /********* End of inlined file: juce_mac_Fonts.cpp *********/
  218192. /********* Start of inlined file: juce_mac_Messaging.cpp *********/
  218193. #include <Carbon/Carbon.h>
  218194. BEGIN_JUCE_NAMESPACE
  218195. #undef Point
  218196. static int kJUCEClass = FOUR_CHAR_CODE ('JUCE');
  218197. const int kJUCEKind = 1;
  218198. const int kCallbackKind = 2;
  218199. extern void juce_HandleProcessFocusChange();
  218200. extern void juce_maximiseAllMinimisedWindows();
  218201. extern void juce_InvokeMainMenuCommand (const HICommand& command);
  218202. extern void juce_MainMenuAboutToBeUsed();
  218203. static pascal OSStatus EventHandlerProc (EventHandlerCallRef, EventRef theEvent, void* userData)
  218204. {
  218205. void* event = 0;
  218206. GetEventParameter (theEvent, 'mess', typeVoidPtr, 0, sizeof (void*), 0, &event);
  218207. if (event != 0)
  218208. MessageManager::getInstance()->deliverMessage (event);
  218209. return noErr;
  218210. }
  218211. struct CallbackMessagePayload
  218212. {
  218213. MessageCallbackFunction* function;
  218214. void* parameter;
  218215. void* volatile result;
  218216. bool volatile hasBeenExecuted;
  218217. };
  218218. static pascal OSStatus CallbackHandlerProc (EventHandlerCallRef, EventRef theEvent, void* userData)
  218219. {
  218220. CallbackMessagePayload* pl = 0;
  218221. GetEventParameter (theEvent, 'mess', typeVoidPtr, 0, sizeof(pl), 0, &pl);
  218222. if (pl != 0)
  218223. {
  218224. pl->result = (*pl->function) (pl->parameter);
  218225. pl->hasBeenExecuted = true;
  218226. }
  218227. return noErr;
  218228. }
  218229. static pascal OSStatus MouseClickHandlerProc (EventHandlerCallRef, EventRef theEvent, void* userData)
  218230. {
  218231. ::Point where;
  218232. GetEventParameter (theEvent, kEventParamMouseLocation, typeQDPoint, 0, sizeof(::Point), 0, &where);
  218233. WindowRef window;
  218234. if (FindWindow (where, &window) == inMenuBar)
  218235. {
  218236. // turn off the wait cursor before going in here..
  218237. const int oldTimeBeforeWaitCursor = MessageManager::getInstance()->getTimeBeforeShowingWaitCursor();
  218238. MessageManager::getInstance()->setTimeBeforeShowingWaitCursor (0);
  218239. if (Component::getCurrentlyModalComponent() != 0)
  218240. Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  218241. juce_MainMenuAboutToBeUsed();
  218242. MenuSelect (where);
  218243. HiliteMenu (0);
  218244. MessageManager::getInstance()->setTimeBeforeShowingWaitCursor (oldTimeBeforeWaitCursor);
  218245. return noErr;
  218246. }
  218247. return eventNotHandledErr;
  218248. }
  218249. static pascal OSErr QuitAppleEventHandler (const AppleEvent *appleEvt, AppleEvent* reply, long refcon)
  218250. {
  218251. if (JUCEApplication::getInstance() != 0)
  218252. JUCEApplication::getInstance()->systemRequestedQuit();
  218253. return noErr;
  218254. }
  218255. static pascal OSErr OpenDocEventHandler (const AppleEvent *appleEvt, AppleEvent* reply, long refcon)
  218256. {
  218257. AEDescList docs;
  218258. StringArray files;
  218259. if (AEGetParamDesc (appleEvt, keyDirectObject, typeAEList, &docs) == noErr)
  218260. {
  218261. long num;
  218262. if (AECountItems (&docs, &num) == noErr)
  218263. {
  218264. for (int i = 1; i <= num; ++i)
  218265. {
  218266. FSRef file;
  218267. AEKeyword keyword;
  218268. DescType type;
  218269. Size size;
  218270. if (AEGetNthPtr (&docs, i, typeFSRef, &keyword, &type,
  218271. &file, sizeof (file), &size) == noErr)
  218272. {
  218273. const String path (PlatformUtilities::makePathFromFSRef (&file));
  218274. if (path.isNotEmpty())
  218275. files.add (path.quoted());
  218276. }
  218277. }
  218278. if (files.size() > 0
  218279. && JUCEApplication::getInstance() != 0)
  218280. {
  218281. JUCE_TRY
  218282. {
  218283. JUCEApplication::getInstance()
  218284. ->anotherInstanceStarted (files.joinIntoString (T(" ")));
  218285. }
  218286. JUCE_CATCH_ALL
  218287. }
  218288. }
  218289. AEDisposeDesc (&docs);
  218290. };
  218291. return noErr;
  218292. }
  218293. static pascal OSStatus AppEventHandlerProc (EventHandlerCallRef, EventRef theEvent, void* userData)
  218294. {
  218295. const UInt32 eventClass = GetEventClass (theEvent);
  218296. if (eventClass == kEventClassCommand)
  218297. {
  218298. HICommand command;
  218299. if (GetEventParameter (theEvent, kEventParamHICommand, typeHICommand, 0, sizeof (command), 0, &command) == noErr
  218300. || GetEventParameter (theEvent, kEventParamDirectObject, typeHICommand, 0, sizeof (command), 0, &command) == noErr)
  218301. {
  218302. if (command.commandID == kHICommandQuit)
  218303. {
  218304. if (JUCEApplication::getInstance() != 0)
  218305. JUCEApplication::getInstance()->systemRequestedQuit();
  218306. return noErr;
  218307. }
  218308. else if (command.commandID == kHICommandMaximizeAll
  218309. || command.commandID == kHICommandMaximizeWindow
  218310. || command.commandID == kHICommandBringAllToFront)
  218311. {
  218312. juce_maximiseAllMinimisedWindows();
  218313. return noErr;
  218314. }
  218315. else
  218316. {
  218317. juce_InvokeMainMenuCommand (command);
  218318. }
  218319. }
  218320. }
  218321. else if (eventClass == kEventClassApplication)
  218322. {
  218323. if (GetEventKind (theEvent) == kEventAppFrontSwitched)
  218324. {
  218325. juce_HandleProcessFocusChange();
  218326. }
  218327. else if (GetEventKind (theEvent) == kEventAppShown)
  218328. {
  218329. // this seems to blank the windows, so we need to do a repaint..
  218330. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  218331. {
  218332. Component* const c = Desktop::getInstance().getComponent (i);
  218333. if (c != 0)
  218334. c->repaint();
  218335. }
  218336. }
  218337. }
  218338. return eventNotHandledErr;
  218339. }
  218340. static EventQueueRef mainQueue;
  218341. static EventHandlerRef juceEventHandler = 0;
  218342. static EventHandlerRef callbackEventHandler = 0;
  218343. void MessageManager::doPlatformSpecificInitialisation()
  218344. {
  218345. static bool initialised = false;
  218346. if (! initialised)
  218347. {
  218348. initialised = true;
  218349. #if MACOS_10_3_OR_EARLIER
  218350. // work-around for a bug in MacOS 10.2..
  218351. ProcessSerialNumber junkPSN;
  218352. (void) GetCurrentProcess (&junkPSN);
  218353. #endif
  218354. mainQueue = GetMainEventQueue();
  218355. // if we're linking a Juce app to one or more dynamic libraries, we'll need different values
  218356. // for this so each module doesn't interfere with the others.
  218357. UnsignedWide t;
  218358. Microseconds (&t);
  218359. kJUCEClass ^= t.lo;
  218360. }
  218361. const EventTypeSpec type1 = { kJUCEClass, kJUCEKind };
  218362. InstallApplicationEventHandler (NewEventHandlerUPP (EventHandlerProc), 1, &type1, 0, &juceEventHandler);
  218363. const EventTypeSpec type2 = { kJUCEClass, kCallbackKind };
  218364. InstallApplicationEventHandler (NewEventHandlerUPP (CallbackHandlerProc), 1, &type2, 0, &callbackEventHandler);
  218365. // only do this stuff if we're running as an application rather than a library..
  218366. if (JUCEApplication::getInstance() != 0)
  218367. {
  218368. const EventTypeSpec type3 = { kEventClassMouse, kEventMouseDown };
  218369. InstallApplicationEventHandler (NewEventHandlerUPP (MouseClickHandlerProc), 1, &type3, 0, 0);
  218370. const EventTypeSpec type4[] = { { kEventClassApplication, kEventAppShown },
  218371. { kEventClassApplication, kEventAppFrontSwitched },
  218372. { kEventClassCommand, kEventProcessCommand } };
  218373. InstallApplicationEventHandler (NewEventHandlerUPP (AppEventHandlerProc), 3, type4, 0, 0);
  218374. AEInstallEventHandler (kCoreEventClass, kAEQuitApplication,
  218375. NewAEEventHandlerUPP (QuitAppleEventHandler), 0, false);
  218376. AEInstallEventHandler (kCoreEventClass, kAEOpenDocuments,
  218377. NewAEEventHandlerUPP (OpenDocEventHandler), 0, false);
  218378. }
  218379. }
  218380. void MessageManager::doPlatformSpecificShutdown()
  218381. {
  218382. if (juceEventHandler != 0)
  218383. {
  218384. RemoveEventHandler (juceEventHandler);
  218385. juceEventHandler = 0;
  218386. }
  218387. if (callbackEventHandler != 0)
  218388. {
  218389. RemoveEventHandler (callbackEventHandler);
  218390. callbackEventHandler = 0;
  218391. }
  218392. }
  218393. bool juce_postMessageToSystemQueue (void* message)
  218394. {
  218395. jassert (mainQueue == GetMainEventQueue());
  218396. EventRef event;
  218397. if (CreateEvent (0, kJUCEClass, kJUCEKind, 0, kEventAttributeUserEvent, &event) == noErr)
  218398. {
  218399. SetEventParameter (event, 'mess', typeVoidPtr, sizeof (void*), &message);
  218400. const bool ok = PostEventToQueue (mainQueue, event, kEventPriorityStandard) == noErr;
  218401. ReleaseEvent (event);
  218402. return ok;
  218403. }
  218404. return false;
  218405. }
  218406. void MessageManager::broadcastMessage (const String& value) throw()
  218407. {
  218408. }
  218409. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback,
  218410. void* data)
  218411. {
  218412. if (isThisTheMessageThread())
  218413. {
  218414. return (*callback) (data);
  218415. }
  218416. else
  218417. {
  218418. jassert (mainQueue == GetMainEventQueue());
  218419. CallbackMessagePayload cmp;
  218420. cmp.function = callback;
  218421. cmp.parameter = data;
  218422. cmp.result = 0;
  218423. cmp.hasBeenExecuted = false;
  218424. EventRef event;
  218425. if (CreateEvent (0, kJUCEClass, kCallbackKind, 0, kEventAttributeUserEvent, &event) == noErr)
  218426. {
  218427. void* v = &cmp;
  218428. SetEventParameter (event, 'mess', typeVoidPtr, sizeof (void*), &v);
  218429. if (PostEventToQueue (mainQueue, event, kEventPriorityStandard) == noErr)
  218430. {
  218431. while (! cmp.hasBeenExecuted)
  218432. Thread::yield();
  218433. return cmp.result;
  218434. }
  218435. }
  218436. return 0;
  218437. }
  218438. }
  218439. END_JUCE_NAMESPACE
  218440. /********* End of inlined file: juce_mac_Messaging.cpp *********/
  218441. /********* Start of inlined file: juce_mac_WebBrowserComponent.mm *********/
  218442. #include <Cocoa/Cocoa.h>
  218443. #include <WebKit/WebKit.h>
  218444. #include <WebKit/HIWebView.h>
  218445. #include <WebKit/WebPolicyDelegate.h>
  218446. #include <WebKit/CarbonUtils.h>
  218447. BEGIN_JUCE_NAMESPACE
  218448. END_JUCE_NAMESPACE
  218449. @interface DownloadClickDetector : NSObject
  218450. {
  218451. juce::WebBrowserComponent* ownerComponent;
  218452. }
  218453. - (DownloadClickDetector*) initWithOwner: (juce::WebBrowserComponent*) ownerComponent;
  218454. - (void) webView: (WebView*) webView decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  218455. request: (NSURLRequest*) request
  218456. frame: (WebFrame*) frame
  218457. decisionListener: (id<WebPolicyDecisionListener>) listener;
  218458. @end
  218459. @implementation DownloadClickDetector
  218460. - (DownloadClickDetector*) initWithOwner: (juce::WebBrowserComponent*) ownerComponent_
  218461. {
  218462. [super init];
  218463. ownerComponent = ownerComponent_;
  218464. return self;
  218465. }
  218466. - (void) webView: (WebView*) sender decidePolicyForNavigationAction: (NSDictionary *)actionInformation request:(NSURLRequest *)request frame:(WebFrame *)frame decisionListener:(id < WebPolicyDecisionListener >)listener
  218467. {
  218468. NSURL* url = [actionInformation valueForKey: @"WebActionOriginalURLKey"];
  218469. if (ownerComponent->pageAboutToLoad (juce::String::fromUTF8 ((const juce::uint8*) [[url absoluteString] UTF8String])))
  218470. [listener use];
  218471. else
  218472. [listener ignore];
  218473. }
  218474. @end
  218475. BEGIN_JUCE_NAMESPACE
  218476. class WebBrowserComponentInternal : public Timer
  218477. {
  218478. public:
  218479. WebBrowserComponentInternal (WebBrowserComponent* owner_)
  218480. : owner (owner_),
  218481. view (0),
  218482. webView (0)
  218483. {
  218484. HIWebViewCreate (&view);
  218485. ComponentPeer* const peer = owner_->getPeer();
  218486. jassert (peer != 0);
  218487. if (view != 0 && peer != 0)
  218488. {
  218489. WindowRef parentWindow = (WindowRef) peer->getNativeHandle();
  218490. WindowAttributes attributes;
  218491. GetWindowAttributes (parentWindow, &attributes);
  218492. HIViewRef parentView = 0;
  218493. if ((attributes & kWindowCompositingAttribute) != 0)
  218494. {
  218495. HIViewRef root = HIViewGetRoot (parentWindow);
  218496. HIViewFindByID (root, kHIViewWindowContentID, &parentView);
  218497. if (parentView == 0)
  218498. parentView = root;
  218499. }
  218500. else
  218501. {
  218502. GetRootControl (parentWindow, (ControlRef*) &parentView);
  218503. if (parentView == 0)
  218504. CreateRootControl (parentWindow, (ControlRef*) &parentView);
  218505. }
  218506. HIViewAddSubview (parentView, view);
  218507. updateBounds();
  218508. show();
  218509. webView = HIWebViewGetWebView (view);
  218510. clickListener = [[DownloadClickDetector alloc] initWithOwner: owner_];
  218511. [webView setPolicyDelegate: clickListener];
  218512. }
  218513. startTimer (500);
  218514. }
  218515. ~WebBrowserComponentInternal()
  218516. {
  218517. [webView setPolicyDelegate: nil];
  218518. [clickListener release];
  218519. if (view != 0)
  218520. CFRelease (view);
  218521. }
  218522. // Horrific bodge-workaround for the fact that the webview somehow hangs onto key
  218523. // focus when you pop up a new window, no matter what that window does to
  218524. // try to grab focus for itself. This catches such a situation and forces
  218525. // focus away from the webview, then back to the place it should be..
  218526. void timerCallback()
  218527. {
  218528. WindowRef viewWindow = HIViewGetWindow (view);
  218529. WindowRef focusedWindow = GetUserFocusWindow();
  218530. if (focusedWindow != viewWindow)
  218531. {
  218532. if (HIViewSubtreeContainsFocus (view))
  218533. {
  218534. HIViewAdvanceFocus (HIViewGetRoot (viewWindow), 0);
  218535. HIViewAdvanceFocus (HIViewGetRoot (focusedWindow), 0);
  218536. }
  218537. }
  218538. }
  218539. void show()
  218540. {
  218541. HIViewSetVisible (view, true);
  218542. }
  218543. void hide()
  218544. {
  218545. HIViewSetVisible (view, false);
  218546. }
  218547. void goToURL (const String& url,
  218548. const StringArray* headers,
  218549. const MemoryBlock* postData)
  218550. {
  218551. char** headerNamesAsChars = 0;
  218552. char** headerValuesAsChars = 0;
  218553. int numHeaders = 0;
  218554. if (headers != 0)
  218555. {
  218556. numHeaders = headers->size();
  218557. headerNamesAsChars = (char**) juce_malloc (sizeof (char*) * numHeaders);
  218558. headerValuesAsChars = (char**) juce_malloc (sizeof (char*) * numHeaders);
  218559. int i;
  218560. for (i = 0; i < numHeaders; ++i)
  218561. {
  218562. const String headerName ((*headers)[i].upToFirstOccurrenceOf (T(":"), false, false).trim());
  218563. headerNamesAsChars[i] = (char*) juce_calloc (headerName.copyToUTF8 (0));
  218564. headerName.copyToUTF8 ((juce::uint8*) headerNamesAsChars[i]);
  218565. const String headerValue ((*headers)[i].fromFirstOccurrenceOf (T(":"), false, false).trim());
  218566. headerValuesAsChars[i] = (char*) juce_calloc (headerValue.copyToUTF8 (0));
  218567. headerValue.copyToUTF8 ((juce::uint8*) headerValuesAsChars[i]);
  218568. }
  218569. }
  218570. sendWebViewToURL ((const char*) url.toUTF8(),
  218571. (const char**) headerNamesAsChars,
  218572. (const char**) headerValuesAsChars,
  218573. numHeaders,
  218574. postData != 0 ? (const char*) postData->getData() : 0,
  218575. postData != 0 ? postData->getSize() : 0);
  218576. for (int i = 0; i < numHeaders; ++i)
  218577. {
  218578. juce_free (headerNamesAsChars[i]);
  218579. juce_free (headerValuesAsChars[i]);
  218580. }
  218581. juce_free (headerNamesAsChars);
  218582. juce_free (headerValuesAsChars);
  218583. }
  218584. void goBack()
  218585. {
  218586. [webView goBack];
  218587. }
  218588. void goForward()
  218589. {
  218590. [webView goForward];
  218591. }
  218592. void stop()
  218593. {
  218594. [webView stopLoading: nil];
  218595. }
  218596. void updateBounds()
  218597. {
  218598. HIRect r;
  218599. r.origin.x = (float) owner->getScreenX() - owner->getTopLevelComponent()->getScreenX();
  218600. r.origin.y = (float) owner->getScreenY() - owner->getTopLevelComponent()->getScreenY();
  218601. r.size.width = (float) owner->getWidth();
  218602. r.size.height = (float) owner->getHeight();
  218603. HIViewSetFrame (view, &r);
  218604. }
  218605. private:
  218606. WebBrowserComponent* const owner;
  218607. HIViewRef view;
  218608. WebView* webView;
  218609. DownloadClickDetector* clickListener;
  218610. void sendWebViewToURL (const char* utf8URL,
  218611. const char** headerNames,
  218612. const char** headerValues,
  218613. int numHeaders,
  218614. const char* postData,
  218615. int postDataSize)
  218616. {
  218617. NSMutableURLRequest* r = [NSMutableURLRequest
  218618. requestWithURL: [NSURL URLWithString: [NSString stringWithUTF8String: utf8URL]]
  218619. cachePolicy: NSURLRequestUseProtocolCachePolicy
  218620. timeoutInterval: 30.0];
  218621. if (postDataSize > 0)
  218622. {
  218623. [ r setHTTPMethod: @"POST"];
  218624. [ r setHTTPBody: [NSData dataWithBytes: postData length: postDataSize]];
  218625. }
  218626. int i;
  218627. for (i = 0; i < numHeaders; ++i)
  218628. {
  218629. [ r setValue: [NSString stringWithUTF8String: headerValues[i]]
  218630. forHTTPHeaderField: [NSString stringWithUTF8String: headerNames[i]]];
  218631. }
  218632. [[webView mainFrame] stopLoading ];
  218633. [[webView mainFrame] loadRequest: r];
  218634. }
  218635. WebBrowserComponentInternal (const WebBrowserComponentInternal&);
  218636. const WebBrowserComponentInternal& operator= (const WebBrowserComponentInternal&);
  218637. };
  218638. WebBrowserComponent::WebBrowserComponent()
  218639. : browser (0),
  218640. associatedWindow (0),
  218641. blankPageShown (false)
  218642. {
  218643. setOpaque (true);
  218644. }
  218645. WebBrowserComponent::~WebBrowserComponent()
  218646. {
  218647. deleteBrowser();
  218648. }
  218649. void WebBrowserComponent::goToURL (const String& url,
  218650. const StringArray* headers,
  218651. const MemoryBlock* postData)
  218652. {
  218653. lastURL = url;
  218654. lastHeaders.clear();
  218655. if (headers != 0)
  218656. lastHeaders = *headers;
  218657. lastPostData.setSize (0);
  218658. if (postData != 0)
  218659. lastPostData = *postData;
  218660. blankPageShown = false;
  218661. if (browser != 0)
  218662. browser->goToURL (url, headers, postData);
  218663. }
  218664. void WebBrowserComponent::stop()
  218665. {
  218666. if (browser != 0)
  218667. browser->stop();
  218668. }
  218669. void WebBrowserComponent::goBack()
  218670. {
  218671. lastURL = String::empty;
  218672. blankPageShown = false;
  218673. if (browser != 0)
  218674. browser->goBack();
  218675. }
  218676. void WebBrowserComponent::goForward()
  218677. {
  218678. lastURL = String::empty;
  218679. if (browser != 0)
  218680. browser->goForward();
  218681. }
  218682. void WebBrowserComponent::paint (Graphics& g)
  218683. {
  218684. if (browser == 0)
  218685. g.fillAll (Colours::white);
  218686. }
  218687. void WebBrowserComponent::checkWindowAssociation()
  218688. {
  218689. void* const window = getWindowHandle();
  218690. if (window != associatedWindow
  218691. || (browser == 0 && window != 0))
  218692. {
  218693. associatedWindow = window;
  218694. deleteBrowser();
  218695. createBrowser();
  218696. }
  218697. if (browser != 0)
  218698. {
  218699. if (associatedWindow != 0 && isShowing())
  218700. {
  218701. browser->show();
  218702. if (blankPageShown)
  218703. goBack();
  218704. }
  218705. else
  218706. {
  218707. if (! blankPageShown)
  218708. {
  218709. // when the component becomes invisible, some stuff like flash
  218710. // carries on playing audio, so we need to force it onto a blank
  218711. // page to avoid this..
  218712. blankPageShown = true;
  218713. browser->goToURL ("about:blank", 0, 0);
  218714. }
  218715. browser->hide();
  218716. }
  218717. }
  218718. }
  218719. void WebBrowserComponent::createBrowser()
  218720. {
  218721. deleteBrowser();
  218722. if (isShowing())
  218723. {
  218724. WebInitForCarbon();
  218725. browser = new WebBrowserComponentInternal (this);
  218726. reloadLastURL();
  218727. }
  218728. }
  218729. void WebBrowserComponent::deleteBrowser()
  218730. {
  218731. deleteAndZero (browser);
  218732. }
  218733. void WebBrowserComponent::reloadLastURL()
  218734. {
  218735. if (lastURL.isNotEmpty())
  218736. {
  218737. goToURL (lastURL, &lastHeaders, &lastPostData);
  218738. lastURL = String::empty;
  218739. }
  218740. }
  218741. void WebBrowserComponent::updateBrowserPosition()
  218742. {
  218743. if (getPeer() != 0 && browser != 0)
  218744. browser->updateBounds();
  218745. }
  218746. void WebBrowserComponent::parentHierarchyChanged()
  218747. {
  218748. checkWindowAssociation();
  218749. }
  218750. void WebBrowserComponent::moved()
  218751. {
  218752. updateBrowserPosition();
  218753. }
  218754. void WebBrowserComponent::resized()
  218755. {
  218756. updateBrowserPosition();
  218757. }
  218758. void WebBrowserComponent::visibilityChanged()
  218759. {
  218760. checkWindowAssociation();
  218761. }
  218762. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  218763. {
  218764. return true;
  218765. }
  218766. END_JUCE_NAMESPACE
  218767. /********* End of inlined file: juce_mac_WebBrowserComponent.mm *********/
  218768. /********* Start of inlined file: juce_mac_Windowing.cpp *********/
  218769. #include <Carbon/Carbon.h>
  218770. #include <IOKit/IOKitLib.h>
  218771. #include <IOKit/IOCFPlugIn.h>
  218772. #include <IOKit/hid/IOHIDLib.h>
  218773. #include <IOKit/hid/IOHIDKeys.h>
  218774. #include <fnmatch.h>
  218775. #if JUCE_OPENGL
  218776. #include <AGL/agl.h>
  218777. #endif
  218778. BEGIN_JUCE_NAMESPACE
  218779. #undef Point
  218780. const WindowRegionCode windowRegionToUse = kWindowContentRgn;
  218781. static HIObjectClassRef viewClassRef = 0;
  218782. static CFStringRef juceHiViewClassNameCFString = 0;
  218783. static ComponentPeer* juce_currentMouseTrackingPeer = 0;
  218784. static VoidArray keysCurrentlyDown;
  218785. bool KeyPress::isKeyCurrentlyDown (const int keyCode) throw()
  218786. {
  218787. if (keysCurrentlyDown.contains ((void*) keyCode))
  218788. return true;
  218789. if (keyCode >= 'A' && keyCode <= 'Z'
  218790. && keysCurrentlyDown.contains ((void*) (int) CharacterFunctions::toLowerCase ((tchar) keyCode)))
  218791. return true;
  218792. if (keyCode >= 'a' && keyCode <= 'z'
  218793. && keysCurrentlyDown.contains ((void*) (int) CharacterFunctions::toUpperCase ((tchar) keyCode)))
  218794. return true;
  218795. return false;
  218796. }
  218797. static VoidArray minimisedWindows;
  218798. static void setWindowMinimised (WindowRef ref, const bool isMinimised)
  218799. {
  218800. if (isMinimised != minimisedWindows.contains (ref))
  218801. CollapseWindow (ref, isMinimised);
  218802. }
  218803. void juce_maximiseAllMinimisedWindows()
  218804. {
  218805. const VoidArray minWin (minimisedWindows);
  218806. for (int i = minWin.size(); --i >= 0;)
  218807. setWindowMinimised ((WindowRef) (minWin[i]), false);
  218808. }
  218809. class HIViewComponentPeer;
  218810. static HIViewComponentPeer* currentlyFocusedPeer = 0;
  218811. static int currentModifiers = 0;
  218812. static void updateModifiers (EventRef theEvent)
  218813. {
  218814. currentModifiers &= ~ (ModifierKeys::shiftModifier | ModifierKeys::ctrlModifier
  218815. | ModifierKeys::altModifier | ModifierKeys::commandModifier);
  218816. UInt32 m;
  218817. if (theEvent != 0)
  218818. GetEventParameter (theEvent, kEventParamKeyModifiers, typeUInt32, 0, sizeof(m), 0, &m);
  218819. else
  218820. m = GetCurrentEventKeyModifiers();
  218821. if ((m & (shiftKey | rightShiftKey)) != 0)
  218822. currentModifiers |= ModifierKeys::shiftModifier;
  218823. if ((m & (controlKey | rightControlKey)) != 0)
  218824. currentModifiers |= ModifierKeys::ctrlModifier;
  218825. if ((m & (optionKey | rightOptionKey)) != 0)
  218826. currentModifiers |= ModifierKeys::altModifier;
  218827. if ((m & cmdKey) != 0)
  218828. currentModifiers |= ModifierKeys::commandModifier;
  218829. }
  218830. void ModifierKeys::updateCurrentModifiers() throw()
  218831. {
  218832. currentModifierFlags = currentModifiers;
  218833. }
  218834. static int64 getEventTime (EventRef event)
  218835. {
  218836. const int64 millis = (int64) (1000.0 * (event != 0 ? GetEventTime (event)
  218837. : GetCurrentEventTime()));
  218838. static int64 offset = 0;
  218839. if (offset == 0)
  218840. offset = Time::currentTimeMillis() - millis;
  218841. return offset + millis;
  218842. }
  218843. class MacBitmapImage : public Image
  218844. {
  218845. public:
  218846. CGColorSpaceRef colourspace;
  218847. CGDataProviderRef provider;
  218848. MacBitmapImage (const PixelFormat format_,
  218849. const int w, const int h, const bool clearImage)
  218850. : Image (format_, w, h)
  218851. {
  218852. jassert (format_ == RGB || format_ == ARGB);
  218853. pixelStride = (format_ == RGB) ? 3 : 4;
  218854. lineStride = (w * pixelStride + 3) & ~3;
  218855. const int imageSize = lineStride * h;
  218856. if (clearImage)
  218857. imageData = (uint8*) juce_calloc (imageSize);
  218858. else
  218859. imageData = (uint8*) juce_malloc (imageSize);
  218860. //colourspace = CGColorSpaceCreateWithName (kCGColorSpaceUserRGB);
  218861. CMProfileRef prof;
  218862. CMGetSystemProfile (&prof);
  218863. colourspace = CGColorSpaceCreateWithPlatformColorSpace (prof);
  218864. provider = CGDataProviderCreateWithData (0, imageData, h * lineStride, 0);
  218865. CMCloseProfile (prof);
  218866. }
  218867. MacBitmapImage::~MacBitmapImage()
  218868. {
  218869. CGDataProviderRelease (provider);
  218870. CGColorSpaceRelease (colourspace);
  218871. juce_free (imageData);
  218872. imageData = 0; // to stop the base class freeing this
  218873. }
  218874. void blitToContext (CGContextRef context, const float dx, const float dy)
  218875. {
  218876. CGImageRef tempImage = CGImageCreate (getWidth(), getHeight(),
  218877. 8, pixelStride << 3, lineStride, colourspace,
  218878. #if MACOS_10_3_OR_EARLIER || JUCE_BIG_ENDIAN
  218879. hasAlphaChannel() ? kCGImageAlphaPremultipliedFirst
  218880. : kCGImageAlphaNone,
  218881. #else
  218882. hasAlphaChannel() ? kCGBitmapByteOrder32Little | kCGImageAlphaPremultipliedFirst
  218883. : kCGImageAlphaNone,
  218884. #endif
  218885. provider, 0, false,
  218886. kCGRenderingIntentDefault);
  218887. HIRect r;
  218888. r.origin.x = dx;
  218889. r.origin.y = dy;
  218890. r.size.width = (float) getWidth();
  218891. r.size.height = (float) getHeight();
  218892. HIViewDrawCGImage (context, &r, tempImage);
  218893. CGImageRelease (tempImage);
  218894. }
  218895. juce_UseDebuggingNewOperator
  218896. };
  218897. class MouseCheckTimer : private Timer,
  218898. private DeletedAtShutdown
  218899. {
  218900. public:
  218901. MouseCheckTimer()
  218902. : lastX (0),
  218903. lastY (0)
  218904. {
  218905. lastPeerUnderMouse = 0;
  218906. resetMouseMoveChecker();
  218907. #if ! MACOS_10_2_OR_EARLIER
  218908. // Just putting this in here because it's a convenient object that'll get deleted at shutdown
  218909. CGDisplayRegisterReconfigurationCallback (&displayChangeCallback, 0);
  218910. #endif
  218911. }
  218912. ~MouseCheckTimer()
  218913. {
  218914. #if ! MACOS_10_2_OR_EARLIER
  218915. CGDisplayRemoveReconfigurationCallback (&displayChangeCallback, 0);
  218916. #endif
  218917. clearSingletonInstance();
  218918. }
  218919. juce_DeclareSingleton_SingleThreaded_Minimal (MouseCheckTimer)
  218920. bool hasEverHadAMouseMove;
  218921. void moved (HIViewComponentPeer* const peer)
  218922. {
  218923. if (hasEverHadAMouseMove)
  218924. startTimer (200);
  218925. lastPeerUnderMouse = peer;
  218926. }
  218927. void resetMouseMoveChecker()
  218928. {
  218929. hasEverHadAMouseMove = false;
  218930. startTimer (1000 / 16);
  218931. }
  218932. void timerCallback();
  218933. private:
  218934. HIViewComponentPeer* lastPeerUnderMouse;
  218935. int lastX, lastY;
  218936. #if ! MACOS_10_2_OR_EARLIER
  218937. static void displayChangeCallback (CGDirectDisplayID, CGDisplayChangeSummaryFlags flags, void*)
  218938. {
  218939. Desktop::getInstance().refreshMonitorSizes();
  218940. }
  218941. #endif
  218942. };
  218943. juce_ImplementSingleton_SingleThreaded (MouseCheckTimer)
  218944. #if JUCE_QUICKTIME
  218945. extern void OfferMouseClickToQuickTime (WindowRef window, ::Point where, long when, long modifiers,
  218946. Component* topLevelComp);
  218947. #endif
  218948. class HIViewComponentPeer : public ComponentPeer,
  218949. private Timer
  218950. {
  218951. public:
  218952. HIViewComponentPeer (Component* const component,
  218953. const int windowStyleFlags,
  218954. HIViewRef viewToAttachTo)
  218955. : ComponentPeer (component, windowStyleFlags),
  218956. fullScreen (false),
  218957. isCompositingWindow (false),
  218958. windowRef (0),
  218959. viewRef (0)
  218960. {
  218961. repainter = new RepaintManager (this);
  218962. eventHandlerRef = 0;
  218963. if (viewToAttachTo != 0)
  218964. {
  218965. isSharedWindow = true;
  218966. }
  218967. else
  218968. {
  218969. isSharedWindow = false;
  218970. WindowRef newWindow = createNewWindow (windowStyleFlags);
  218971. GetRootControl (newWindow, (ControlRef*) &viewToAttachTo);
  218972. jassert (viewToAttachTo != 0);
  218973. HIViewRef growBox = 0;
  218974. HIViewFindByID (HIViewGetRoot (newWindow), kHIViewWindowGrowBoxID, &growBox);
  218975. if (growBox != 0)
  218976. HIGrowBoxViewSetTransparent (growBox, true);
  218977. }
  218978. createNewHIView();
  218979. HIViewAddSubview (viewToAttachTo, viewRef);
  218980. HIViewSetVisible (viewRef, component->isVisible());
  218981. setTitle (component->getName());
  218982. if (component->isVisible() && ! isSharedWindow)
  218983. {
  218984. ShowWindow (windowRef);
  218985. ActivateWindow (windowRef, component->getWantsKeyboardFocus());
  218986. }
  218987. }
  218988. ~HIViewComponentPeer()
  218989. {
  218990. minimisedWindows.removeValue (windowRef);
  218991. if (IsValidWindowPtr (windowRef))
  218992. {
  218993. if (! isSharedWindow)
  218994. {
  218995. CFRelease (viewRef);
  218996. viewRef = 0;
  218997. DisposeWindow (windowRef);
  218998. }
  218999. else
  219000. {
  219001. if (eventHandlerRef != 0)
  219002. RemoveEventHandler (eventHandlerRef);
  219003. CFRelease (viewRef);
  219004. viewRef = 0;
  219005. }
  219006. windowRef = 0;
  219007. }
  219008. if (currentlyFocusedPeer == this)
  219009. currentlyFocusedPeer = 0;
  219010. delete repainter;
  219011. }
  219012. void* getNativeHandle() const
  219013. {
  219014. return windowRef;
  219015. }
  219016. void setVisible (bool shouldBeVisible)
  219017. {
  219018. HIViewSetVisible (viewRef, shouldBeVisible);
  219019. if ((! isSharedWindow) && IsValidWindowPtr (windowRef))
  219020. {
  219021. if (shouldBeVisible)
  219022. ShowWindow (windowRef);
  219023. else
  219024. HideWindow (windowRef);
  219025. resizeViewToFitWindow();
  219026. // If nothing else is focused, then grab the focus too
  219027. if (shouldBeVisible
  219028. && Component::getCurrentlyFocusedComponent() == 0
  219029. && Process::isForegroundProcess())
  219030. {
  219031. component->toFront (true);
  219032. }
  219033. }
  219034. }
  219035. void setTitle (const String& title)
  219036. {
  219037. if ((! isSharedWindow) && IsValidWindowPtr (windowRef))
  219038. {
  219039. CFStringRef t = PlatformUtilities::juceStringToCFString (title);
  219040. SetWindowTitleWithCFString (windowRef, t);
  219041. CFRelease (t);
  219042. }
  219043. }
  219044. void setPosition (int x, int y)
  219045. {
  219046. if (isSharedWindow)
  219047. {
  219048. HIViewPlaceInSuperviewAt (viewRef, x, y);
  219049. }
  219050. else if (IsValidWindowPtr (windowRef))
  219051. {
  219052. Rect r;
  219053. GetWindowBounds (windowRef, windowRegionToUse, &r);
  219054. r.right += x - r.left;
  219055. r.bottom += y - r.top;
  219056. r.left = x;
  219057. r.top = y;
  219058. SetWindowBounds (windowRef, windowRegionToUse, &r);
  219059. }
  219060. }
  219061. void setSize (int w, int h)
  219062. {
  219063. w = jmax (0, w);
  219064. h = jmax (0, h);
  219065. if (w != getComponent()->getWidth()
  219066. || h != getComponent()->getHeight())
  219067. {
  219068. repainter->repaint (0, 0, w, h);
  219069. }
  219070. if (isSharedWindow)
  219071. {
  219072. HIRect r;
  219073. HIViewGetFrame (viewRef, &r);
  219074. r.size.width = (float) w;
  219075. r.size.height = (float) h;
  219076. HIViewSetFrame (viewRef, &r);
  219077. }
  219078. else if (IsValidWindowPtr (windowRef))
  219079. {
  219080. Rect r;
  219081. GetWindowBounds (windowRef, windowRegionToUse, &r);
  219082. r.right = r.left + w;
  219083. r.bottom = r.top + h;
  219084. SetWindowBounds (windowRef, windowRegionToUse, &r);
  219085. }
  219086. }
  219087. void setBounds (int x, int y, int w, int h, const bool isNowFullScreen)
  219088. {
  219089. fullScreen = isNowFullScreen;
  219090. w = jmax (0, w);
  219091. h = jmax (0, h);
  219092. if (w != getComponent()->getWidth()
  219093. || h != getComponent()->getHeight())
  219094. {
  219095. repainter->repaint (0, 0, w, h);
  219096. }
  219097. if (isSharedWindow)
  219098. {
  219099. HIRect r;
  219100. r.origin.x = (float) x;
  219101. r.origin.y = (float) y;
  219102. r.size.width = (float) w;
  219103. r.size.height = (float) h;
  219104. HIViewSetFrame (viewRef, &r);
  219105. }
  219106. else if (IsValidWindowPtr (windowRef))
  219107. {
  219108. Rect r;
  219109. r.left = x;
  219110. r.top = y;
  219111. r.right = x + w;
  219112. r.bottom = y + h;
  219113. SetWindowBounds (windowRef, windowRegionToUse, &r);
  219114. }
  219115. }
  219116. void getBounds (int& x, int& y, int& w, int& h, const bool global) const
  219117. {
  219118. HIRect hiViewPos;
  219119. HIViewGetFrame (viewRef, &hiViewPos);
  219120. if (global)
  219121. {
  219122. HIViewRef content = 0;
  219123. HIViewFindByID (HIViewGetRoot (windowRef), kHIViewWindowContentID, &content);
  219124. HIPoint p = { 0.0f, 0.0f };
  219125. HIViewConvertPoint (&p, viewRef, content);
  219126. x = (int) p.x;
  219127. y = (int) p.y;
  219128. if (IsValidWindowPtr (windowRef))
  219129. {
  219130. Rect windowPos;
  219131. GetWindowBounds (windowRef, kWindowContentRgn, &windowPos);
  219132. x += windowPos.left;
  219133. y += windowPos.top;
  219134. }
  219135. }
  219136. else
  219137. {
  219138. x = (int) hiViewPos.origin.x;
  219139. y = (int) hiViewPos.origin.y;
  219140. }
  219141. w = (int) hiViewPos.size.width;
  219142. h = (int) hiViewPos.size.height;
  219143. }
  219144. void getBounds (int& x, int& y, int& w, int& h) const
  219145. {
  219146. getBounds (x, y, w, h, ! isSharedWindow);
  219147. }
  219148. int getScreenX() const
  219149. {
  219150. int x, y, w, h;
  219151. getBounds (x, y, w, h, true);
  219152. return x;
  219153. }
  219154. int getScreenY() const
  219155. {
  219156. int x, y, w, h;
  219157. getBounds (x, y, w, h, true);
  219158. return y;
  219159. }
  219160. void relativePositionToGlobal (int& x, int& y)
  219161. {
  219162. int wx, wy, ww, wh;
  219163. getBounds (wx, wy, ww, wh, true);
  219164. x += wx;
  219165. y += wy;
  219166. }
  219167. void globalPositionToRelative (int& x, int& y)
  219168. {
  219169. int wx, wy, ww, wh;
  219170. getBounds (wx, wy, ww, wh, true);
  219171. x -= wx;
  219172. y -= wy;
  219173. }
  219174. void setMinimised (bool shouldBeMinimised)
  219175. {
  219176. if (! isSharedWindow)
  219177. setWindowMinimised (windowRef, shouldBeMinimised);
  219178. }
  219179. bool isMinimised() const
  219180. {
  219181. return minimisedWindows.contains (windowRef);
  219182. }
  219183. void setFullScreen (bool shouldBeFullScreen)
  219184. {
  219185. if (! isSharedWindow)
  219186. {
  219187. Rectangle r (lastNonFullscreenBounds);
  219188. setMinimised (false);
  219189. if (fullScreen != shouldBeFullScreen)
  219190. {
  219191. if (shouldBeFullScreen)
  219192. r = Desktop::getInstance().getMainMonitorArea();
  219193. // (can't call the component's setBounds method because that'll reset our fullscreen flag)
  219194. if (r != getComponent()->getBounds() && ! r.isEmpty())
  219195. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  219196. }
  219197. }
  219198. }
  219199. bool isFullScreen() const
  219200. {
  219201. return fullScreen;
  219202. }
  219203. bool contains (int x, int y, bool trueIfInAChildWindow) const
  219204. {
  219205. if (((unsigned int) x) >= (unsigned int) component->getWidth()
  219206. || ((unsigned int) y) >= (unsigned int) component->getHeight()
  219207. || ! IsValidWindowPtr (windowRef))
  219208. return false;
  219209. Rect r;
  219210. GetWindowBounds (windowRef, windowRegionToUse, &r);
  219211. ::Point p;
  219212. p.h = r.left + x;
  219213. p.v = r.top + y;
  219214. WindowRef ref2 = 0;
  219215. FindWindow (p, &ref2);
  219216. if (windowRef != ref2)
  219217. return false;
  219218. if (trueIfInAChildWindow)
  219219. return true;
  219220. HIPoint p2;
  219221. p2.x = (float) x;
  219222. p2.y = (float) y;
  219223. HIViewRef hit;
  219224. HIViewGetSubviewHit (viewRef, &p2, true, &hit);
  219225. return hit == 0 || hit == viewRef;
  219226. }
  219227. const BorderSize getFrameSize() const
  219228. {
  219229. return BorderSize();
  219230. }
  219231. bool setAlwaysOnTop (bool alwaysOnTop)
  219232. {
  219233. // can't do this so return false and let the component create a new window
  219234. return false;
  219235. }
  219236. void toFront (bool makeActiveWindow)
  219237. {
  219238. makeActiveWindow = makeActiveWindow
  219239. && component->isValidComponent()
  219240. && (component->getWantsKeyboardFocus()
  219241. || component->isCurrentlyModal());
  219242. if (windowRef != FrontWindow()
  219243. || (makeActiveWindow && ! IsWindowActive (windowRef))
  219244. || ! Process::isForegroundProcess())
  219245. {
  219246. if (! Process::isForegroundProcess())
  219247. {
  219248. ProcessSerialNumber psn;
  219249. GetCurrentProcess (&psn);
  219250. SetFrontProcessWithOptions (&psn, kSetFrontProcessFrontWindowOnly);
  219251. }
  219252. if (IsValidWindowPtr (windowRef))
  219253. {
  219254. if (makeActiveWindow)
  219255. {
  219256. SelectWindow (windowRef);
  219257. SetUserFocusWindow (windowRef);
  219258. HIViewAdvanceFocus (viewRef, 0);
  219259. }
  219260. else
  219261. {
  219262. BringToFront (windowRef);
  219263. }
  219264. handleBroughtToFront();
  219265. }
  219266. }
  219267. }
  219268. void toBehind (ComponentPeer* other)
  219269. {
  219270. HIViewComponentPeer* const otherWindow = dynamic_cast <HIViewComponentPeer*> (other);
  219271. if (other != 0 && windowRef != 0 && otherWindow->windowRef != 0)
  219272. {
  219273. if (windowRef == otherWindow->windowRef)
  219274. {
  219275. HIViewSetZOrder (viewRef, kHIViewZOrderBelow, otherWindow->viewRef);
  219276. }
  219277. else
  219278. {
  219279. SendBehind (windowRef, otherWindow->windowRef);
  219280. }
  219281. }
  219282. }
  219283. void setIcon (const Image& /*newIcon*/)
  219284. {
  219285. // to do..
  219286. }
  219287. void viewFocusGain()
  219288. {
  219289. const MessageManagerLock messLock;
  219290. if (currentlyFocusedPeer != this)
  219291. {
  219292. if (ComponentPeer::isValidPeer (currentlyFocusedPeer))
  219293. currentlyFocusedPeer->handleFocusLoss();
  219294. currentlyFocusedPeer = this;
  219295. handleFocusGain();
  219296. }
  219297. }
  219298. void viewFocusLoss()
  219299. {
  219300. if (currentlyFocusedPeer == this)
  219301. {
  219302. currentlyFocusedPeer = 0;
  219303. handleFocusLoss();
  219304. }
  219305. }
  219306. bool isFocused() const
  219307. {
  219308. return windowRef == GetUserFocusWindow()
  219309. && HIViewSubtreeContainsFocus (viewRef);
  219310. }
  219311. void grabFocus()
  219312. {
  219313. if ((! isFocused()) && IsValidWindowPtr (windowRef))
  219314. {
  219315. SetUserFocusWindow (windowRef);
  219316. HIViewAdvanceFocus (viewRef, 0);
  219317. }
  219318. }
  219319. void repaint (int x, int y, int w, int h)
  219320. {
  219321. if (Rectangle::intersectRectangles (x, y, w, h,
  219322. 0, 0,
  219323. getComponent()->getWidth(),
  219324. getComponent()->getHeight()))
  219325. {
  219326. if ((getStyleFlags() & windowRepaintedExplictly) == 0)
  219327. {
  219328. if (isCompositingWindow)
  219329. {
  219330. #if MACOS_10_3_OR_EARLIER
  219331. RgnHandle rgn = NewRgn();
  219332. SetRectRgn (rgn, x, y, x + w, y + h);
  219333. HIViewSetNeedsDisplayInRegion (viewRef, rgn, true);
  219334. DisposeRgn (rgn);
  219335. #else
  219336. HIRect r;
  219337. r.origin.x = x;
  219338. r.origin.y = y;
  219339. r.size.width = w;
  219340. r.size.height = h;
  219341. HIViewSetNeedsDisplayInRect (viewRef, &r, true);
  219342. #endif
  219343. }
  219344. else
  219345. {
  219346. if (! isTimerRunning())
  219347. startTimer (20);
  219348. }
  219349. }
  219350. repainter->repaint (x, y, w, h);
  219351. }
  219352. }
  219353. void timerCallback()
  219354. {
  219355. performAnyPendingRepaintsNow();
  219356. }
  219357. void performAnyPendingRepaintsNow()
  219358. {
  219359. stopTimer();
  219360. if (component->isVisible())
  219361. {
  219362. #if MACOS_10_2_OR_EARLIER
  219363. if (! isCompositingWindow)
  219364. {
  219365. Rect w;
  219366. GetWindowBounds (windowRef, windowRegionToUse, &w);
  219367. const int offsetInWindowX = component->getScreenX() - getScreenX();
  219368. const int offsetInWindowY = component->getScreenY() - getScreenY();
  219369. for (RectangleList::Iterator i (repainter->getRegionsNeedingRepaint()); i.next();)
  219370. {
  219371. const Rectangle& r = *i.getRectangle();
  219372. w.left = offsetInWindowX + r.getX();
  219373. w.top = offsetInWindowY + r.getY();
  219374. w.right = offsetInWindowX + r.getRight();
  219375. w.bottom = offsetInWindowY + r.getBottom();
  219376. InvalWindowRect (windowRef, &w);
  219377. }
  219378. }
  219379. else
  219380. {
  219381. EventRef theEvent;
  219382. EventTypeSpec eventTypes[1];
  219383. eventTypes[0].eventClass = kEventClassControl;
  219384. eventTypes[0].eventKind = kEventControlDraw;
  219385. int n = 3;
  219386. while (--n >= 0
  219387. && ReceiveNextEvent (1, eventTypes, kEventDurationNoWait, true, &theEvent) == noErr)
  219388. {
  219389. if (GetEventClass (theEvent) == kEventClassAppleEvent)
  219390. {
  219391. EventRecord eventRec;
  219392. if (ConvertEventRefToEventRecord (theEvent, &eventRec))
  219393. AEProcessAppleEvent (&eventRec);
  219394. }
  219395. else
  219396. {
  219397. EventTargetRef theTarget = GetEventDispatcherTarget();
  219398. SendEventToEventTarget (theEvent, theTarget);
  219399. }
  219400. ReleaseEvent (theEvent);
  219401. }
  219402. }
  219403. #else
  219404. if (HIViewGetNeedsDisplay (viewRef) || repainter->isRepaintNeeded())
  219405. HIViewRender (viewRef);
  219406. #endif
  219407. }
  219408. }
  219409. juce_UseDebuggingNewOperator
  219410. WindowRef windowRef;
  219411. HIViewRef viewRef;
  219412. private:
  219413. EventHandlerRef eventHandlerRef;
  219414. bool fullScreen, isSharedWindow, isCompositingWindow;
  219415. StringArray dragAndDropFiles;
  219416. class RepaintManager : public Timer
  219417. {
  219418. public:
  219419. RepaintManager (HIViewComponentPeer* const peer_)
  219420. : peer (peer_),
  219421. image (0)
  219422. {
  219423. }
  219424. ~RepaintManager()
  219425. {
  219426. delete image;
  219427. }
  219428. void timerCallback()
  219429. {
  219430. stopTimer();
  219431. deleteAndZero (image);
  219432. }
  219433. void repaint (int x, int y, int w, int h)
  219434. {
  219435. regionsNeedingRepaint.add (x, y, w, h);
  219436. }
  219437. bool isRepaintNeeded() const throw()
  219438. {
  219439. return ! regionsNeedingRepaint.isEmpty();
  219440. }
  219441. void repaintAnyRemainingRegions()
  219442. {
  219443. // if any regions have been invaldated during the paint callback,
  219444. // we need to repaint them explicitly because the mac throws this
  219445. // stuff away
  219446. for (RectangleList::Iterator i (regionsNeedingRepaint); i.next();)
  219447. {
  219448. const Rectangle& r = *i.getRectangle();
  219449. peer->repaint (r.getX(), r.getY(), r.getWidth(), r.getHeight());
  219450. }
  219451. }
  219452. void paint (CGContextRef cgContext, int x, int y, int w, int h)
  219453. {
  219454. if (w > 0 && h > 0)
  219455. {
  219456. bool refresh = false;
  219457. int imW = image != 0 ? image->getWidth() : 0;
  219458. int imH = image != 0 ? image->getHeight() : 0;
  219459. if (imW < w || imH < h)
  219460. {
  219461. imW = jmin (peer->getComponent()->getWidth(), (w + 31) & ~31);
  219462. imH = jmin (peer->getComponent()->getHeight(), (h + 31) & ~31);
  219463. delete image;
  219464. image = new MacBitmapImage (peer->getComponent()->isOpaque() ? Image::RGB
  219465. : Image::ARGB,
  219466. imW, imH, false);
  219467. refresh = true;
  219468. }
  219469. else if (imageX > x || imageY > y
  219470. || imageX + imW < x + w
  219471. || imageY + imH < y + h)
  219472. {
  219473. refresh = true;
  219474. }
  219475. if (refresh)
  219476. {
  219477. regionsNeedingRepaint.clear();
  219478. regionsNeedingRepaint.addWithoutMerging (Rectangle (x, y, imW, imH));
  219479. imageX = x;
  219480. imageY = y;
  219481. }
  219482. LowLevelGraphicsSoftwareRenderer context (*image);
  219483. context.setOrigin (-imageX, -imageY);
  219484. if (context.reduceClipRegion (regionsNeedingRepaint))
  219485. {
  219486. regionsNeedingRepaint.clear();
  219487. if (! peer->getComponent()->isOpaque())
  219488. {
  219489. for (RectangleList::Iterator i (*context.getRawClipRegion()); i.next();)
  219490. {
  219491. const Rectangle& r = *i.getRectangle();
  219492. image->clear (r.getX(), r.getY(), r.getWidth(), r.getHeight());
  219493. }
  219494. }
  219495. regionsNeedingRepaint.clear();
  219496. peer->clearMaskedRegion();
  219497. peer->handlePaint (context);
  219498. }
  219499. else
  219500. {
  219501. regionsNeedingRepaint.clear();
  219502. }
  219503. if (! peer->maskedRegion.isEmpty())
  219504. {
  219505. RectangleList total (Rectangle (x, y, w, h));
  219506. total.subtract (peer->maskedRegion);
  219507. CGRect* rects = (CGRect*) juce_malloc (sizeof (CGRect) * total.getNumRectangles());
  219508. int n = 0;
  219509. for (RectangleList::Iterator i (total); i.next();)
  219510. {
  219511. const Rectangle& r = *i.getRectangle();
  219512. rects[n].origin.x = (int) r.getX();
  219513. rects[n].origin.y = (int) r.getY();
  219514. rects[n].size.width = roundFloatToInt (r.getWidth());
  219515. rects[n++].size.height = roundFloatToInt (r.getHeight());
  219516. }
  219517. CGContextClipToRects (cgContext, rects, n);
  219518. juce_free (rects);
  219519. }
  219520. if (peer->isSharedWindow)
  219521. {
  219522. CGRect clip;
  219523. clip.origin.x = x;
  219524. clip.origin.y = y;
  219525. clip.size.width = jmin (w, peer->getComponent()->getWidth() - x);
  219526. clip.size.height = jmin (h, peer->getComponent()->getHeight() - y);
  219527. CGContextClipToRect (cgContext, clip);
  219528. }
  219529. image->blitToContext (cgContext, imageX, imageY);
  219530. }
  219531. startTimer (3000);
  219532. }
  219533. private:
  219534. HIViewComponentPeer* const peer;
  219535. MacBitmapImage* image;
  219536. int imageX, imageY;
  219537. RectangleList regionsNeedingRepaint;
  219538. RepaintManager (const RepaintManager&);
  219539. const RepaintManager& operator= (const RepaintManager&);
  219540. };
  219541. RepaintManager* repainter;
  219542. friend class RepaintManager;
  219543. static OSStatus handleFrameRepaintEvent (EventHandlerCallRef myHandler,
  219544. EventRef theEvent,
  219545. void* userData)
  219546. {
  219547. // don't draw the frame..
  219548. return noErr;
  219549. }
  219550. OSStatus handleKeyEvent (EventRef theEvent, juce_wchar textCharacter)
  219551. {
  219552. updateModifiers (theEvent);
  219553. UniChar unicodeChars [4];
  219554. zeromem (unicodeChars, sizeof (unicodeChars));
  219555. GetEventParameter (theEvent, kEventParamKeyUnicodes, typeUnicodeText, 0, sizeof (unicodeChars), 0, unicodeChars);
  219556. int keyCode = (int) (unsigned int) unicodeChars[0];
  219557. UInt32 rawKey = 0;
  219558. GetEventParameter (theEvent, kEventParamKeyCode, typeUInt32, 0, sizeof (UInt32), 0, &rawKey);
  219559. if ((currentModifiers & ModifierKeys::ctrlModifier) != 0
  219560. && keyCode >= 1 && keyCode <= 26)
  219561. {
  219562. keyCode += ('A' - 1);
  219563. }
  219564. else
  219565. {
  219566. static const int keyTranslations[] =
  219567. {
  219568. 0, 's', 'd', 'f', 'h', 'g', 'z', 'x', 'c', 'v', 0xa7, 'b',
  219569. 'q', 'w', 'e', 'r', 'y', 't', '1', '2', '3', '4', '6', '5',
  219570. '=', '9', '7', '-', '8', '0', ']', 'o', 'u', '[', 'i', 'p',
  219571. KeyPress::returnKey, 'l', 'j', '\'', 'k', ';', '\\', ',', '/',
  219572. 'n', 'm', '.', 0, KeyPress::spaceKey, '`', KeyPress::backspaceKey, 0, 0, 0, 0,
  219573. 0, 0, 0, 0, 0, 0, 0, 0, 0, KeyPress::numberPadDecimalPoint,
  219574. 0, KeyPress::numberPadMultiply, 0, KeyPress::numberPadAdd,
  219575. 0, KeyPress::numberPadDelete, 0, 0, 0, KeyPress::numberPadDivide, KeyPress::returnKey,
  219576. 0, KeyPress::numberPadSubtract, 0, 0, KeyPress::numberPadEquals, KeyPress::numberPad0,
  219577. KeyPress::numberPad1, KeyPress::numberPad2, KeyPress::numberPad3,
  219578. KeyPress::numberPad4, KeyPress::numberPad5, KeyPress::numberPad6,
  219579. KeyPress::numberPad7, 0, KeyPress::numberPad8, KeyPress::numberPad9,
  219580. 0, 0, 0, KeyPress::F5Key, KeyPress::F6Key, KeyPress::F7Key, KeyPress::F3Key,
  219581. KeyPress::F8Key, KeyPress::F9Key, 0, KeyPress::F11Key, 0, KeyPress::F13Key,
  219582. KeyPress::F16Key, KeyPress::F14Key, 0, KeyPress::F10Key, 0, KeyPress::F12Key,
  219583. 0, KeyPress::F15Key, 0, KeyPress::homeKey, KeyPress::pageUpKey, 0, KeyPress::F4Key,
  219584. KeyPress::endKey, KeyPress::F2Key, KeyPress::pageDownKey, KeyPress::F1Key,
  219585. KeyPress::leftKey, KeyPress::rightKey, KeyPress::downKey, KeyPress::upKey, 0
  219586. };
  219587. if (((unsigned int) rawKey) < (unsigned int) numElementsInArray (keyTranslations)
  219588. && keyTranslations [rawKey] != 0)
  219589. {
  219590. keyCode = keyTranslations [rawKey];
  219591. }
  219592. if ((rawKey == 0 && textCharacter != 0)
  219593. || (CharacterFunctions::isLetterOrDigit ((juce_wchar) keyCode)
  219594. && CharacterFunctions::isLetterOrDigit (textCharacter))) // correction for azerty-type layouts..
  219595. {
  219596. keyCode = CharacterFunctions::toLowerCase (textCharacter);
  219597. }
  219598. }
  219599. if ((currentModifiers & (ModifierKeys::commandModifier | ModifierKeys::ctrlModifier)) != 0)
  219600. textCharacter = 0;
  219601. static juce_wchar lastTextCharacter = 0;
  219602. switch (GetEventKind (theEvent))
  219603. {
  219604. case kEventRawKeyDown:
  219605. {
  219606. keysCurrentlyDown.addIfNotAlreadyThere ((void*) keyCode);
  219607. lastTextCharacter = textCharacter;
  219608. const bool used1 = handleKeyUpOrDown();
  219609. const bool used2 = handleKeyPress (keyCode, textCharacter);
  219610. if (used1 || used2)
  219611. return noErr;
  219612. break;
  219613. }
  219614. case kEventRawKeyUp:
  219615. keysCurrentlyDown.removeValue ((void*) keyCode);
  219616. lastTextCharacter = 0;
  219617. if (handleKeyUpOrDown())
  219618. return noErr;
  219619. break;
  219620. case kEventRawKeyRepeat:
  219621. if (handleKeyPress (keyCode, lastTextCharacter))
  219622. return noErr;
  219623. break;
  219624. case kEventRawKeyModifiersChanged:
  219625. handleModifierKeysChange();
  219626. break;
  219627. default:
  219628. jassertfalse
  219629. break;
  219630. }
  219631. return eventNotHandledErr;
  219632. }
  219633. OSStatus handleTextInputEvent (EventRef theEvent)
  219634. {
  219635. UInt32 numBytesRequired = 0;
  219636. GetEventParameter (theEvent, kEventParamTextInputSendText, typeUnicodeText, 0, 0, &numBytesRequired, 0);
  219637. MemoryBlock buffer (numBytesRequired, true);
  219638. UniChar* const uc = (UniChar*) buffer.getData();
  219639. GetEventParameter (theEvent, kEventParamTextInputSendText, typeUnicodeText, 0, numBytesRequired, &numBytesRequired, uc);
  219640. EventRef originalEvent;
  219641. GetEventParameter (theEvent, kEventParamTextInputSendKeyboardEvent, typeEventRef, 0, sizeof (originalEvent), 0, &originalEvent);
  219642. OSStatus res = noErr;
  219643. for (int i = 0; i < numBytesRequired / sizeof (UniChar); ++i)
  219644. res = handleKeyEvent (originalEvent, (juce_wchar) uc[i]);
  219645. return res;
  219646. }
  219647. OSStatus handleMouseEvent (EventHandlerCallRef callRef, EventRef theEvent)
  219648. {
  219649. MouseCheckTimer::getInstance()->moved (this);
  219650. ::Point where;
  219651. GetEventParameter (theEvent, kEventParamMouseLocation, typeQDPoint, 0, sizeof (::Point), 0, &where);
  219652. int x = where.h;
  219653. int y = where.v;
  219654. globalPositionToRelative (x, y);
  219655. int64 time = getEventTime (theEvent);
  219656. switch (GetEventKind (theEvent))
  219657. {
  219658. case kEventMouseMoved:
  219659. MouseCheckTimer::getInstance()->hasEverHadAMouseMove = true;
  219660. updateModifiers (theEvent);
  219661. handleMouseMove (x, y, time);
  219662. break;
  219663. case kEventMouseDragged:
  219664. updateModifiers (theEvent);
  219665. handleMouseDrag (x, y, time);
  219666. break;
  219667. case kEventMouseDown:
  219668. {
  219669. if (! Process::isForegroundProcess())
  219670. {
  219671. ProcessSerialNumber psn;
  219672. GetCurrentProcess (&psn);
  219673. SetFrontProcessWithOptions (&psn, kSetFrontProcessFrontWindowOnly);
  219674. toFront (true);
  219675. }
  219676. #if JUCE_QUICKTIME
  219677. {
  219678. long mods;
  219679. GetEventParameter (theEvent, kEventParamKeyModifiers, typeUInt32, 0, sizeof (mods), 0, &mods);
  219680. ::Point where;
  219681. GetEventParameter (theEvent, kEventParamMouseLocation, typeQDPoint, 0, sizeof (::Point), 0, &where);
  219682. OfferMouseClickToQuickTime (windowRef, where, EventTimeToTicks (GetEventTime (theEvent)), mods, component);
  219683. }
  219684. #endif
  219685. if (component->isBroughtToFrontOnMouseClick()
  219686. && ! component->isCurrentlyBlockedByAnotherModalComponent())
  219687. {
  219688. //ActivateWindow (windowRef, true);
  219689. SelectWindow (windowRef);
  219690. }
  219691. EventMouseButton button;
  219692. GetEventParameter (theEvent, kEventParamMouseButton, typeMouseButton, 0, sizeof (EventMouseButton), 0, &button);
  219693. // need to clear all these flags because sometimes the mac can swallow (right) mouse-up events and
  219694. // this makes a button get stuck down. Since there's no other way to tell what buttons are down,
  219695. // this is all I can think of doing about it..
  219696. currentModifiers &= ~(ModifierKeys::leftButtonModifier | ModifierKeys::rightButtonModifier | ModifierKeys::middleButtonModifier);
  219697. if (button == kEventMouseButtonPrimary)
  219698. currentModifiers |= ModifierKeys::leftButtonModifier;
  219699. else if (button == kEventMouseButtonSecondary)
  219700. currentModifiers |= ModifierKeys::rightButtonModifier;
  219701. else if (button == kEventMouseButtonTertiary)
  219702. currentModifiers |= ModifierKeys::middleButtonModifier;
  219703. updateModifiers (theEvent);
  219704. juce_currentMouseTrackingPeer = this; // puts the message dispatcher into mouse-tracking mode..
  219705. handleMouseDown (x, y, time);
  219706. break;
  219707. }
  219708. case kEventMouseUp:
  219709. {
  219710. const int oldModifiers = currentModifiers;
  219711. EventMouseButton button;
  219712. GetEventParameter (theEvent, kEventParamMouseButton, typeMouseButton, 0, sizeof (EventMouseButton), 0, &button);
  219713. if (button == kEventMouseButtonPrimary)
  219714. currentModifiers &= ~ModifierKeys::leftButtonModifier;
  219715. else if (button == kEventMouseButtonSecondary)
  219716. currentModifiers &= ~ModifierKeys::rightButtonModifier;
  219717. updateModifiers (theEvent);
  219718. juce_currentMouseTrackingPeer = 0;
  219719. handleMouseUp (oldModifiers, x, y, time);
  219720. break;
  219721. }
  219722. case kEventMouseWheelMoved:
  219723. {
  219724. EventMouseWheelAxis axis;
  219725. GetEventParameter (theEvent, kEventParamMouseWheelAxis, typeMouseWheelAxis, 0, sizeof (axis), 0, &axis);
  219726. SInt32 delta;
  219727. GetEventParameter (theEvent, kEventParamMouseWheelDelta,
  219728. typeLongInteger, 0, sizeof (delta), 0, &delta);
  219729. updateModifiers (theEvent);
  219730. handleMouseWheel (axis == kEventMouseWheelAxisX ? delta * 10 : 0,
  219731. axis == kEventMouseWheelAxisX ? 0 : delta * 10,
  219732. time);
  219733. break;
  219734. }
  219735. }
  219736. return noErr;
  219737. }
  219738. void doDragDropEnter (EventRef theEvent)
  219739. {
  219740. updateDragAndDropFileList (theEvent);
  219741. if (dragAndDropFiles.size() > 0)
  219742. {
  219743. int x, y;
  219744. component->getMouseXYRelative (x, y);
  219745. handleFileDragMove (dragAndDropFiles, x, y);
  219746. }
  219747. }
  219748. void doDragDropMove (EventRef theEvent)
  219749. {
  219750. if (dragAndDropFiles.size() > 0)
  219751. {
  219752. int x, y;
  219753. component->getMouseXYRelative (x, y);
  219754. handleFileDragMove (dragAndDropFiles, x, y);
  219755. }
  219756. }
  219757. void doDragDropExit (EventRef theEvent)
  219758. {
  219759. if (dragAndDropFiles.size() > 0)
  219760. handleFileDragExit (dragAndDropFiles);
  219761. }
  219762. void doDragDrop (EventRef theEvent)
  219763. {
  219764. updateDragAndDropFileList (theEvent);
  219765. if (dragAndDropFiles.size() > 0)
  219766. {
  219767. int x, y;
  219768. component->getMouseXYRelative (x, y);
  219769. handleFileDragDrop (dragAndDropFiles, x, y);
  219770. }
  219771. }
  219772. void updateDragAndDropFileList (EventRef theEvent)
  219773. {
  219774. dragAndDropFiles.clear();
  219775. DragRef dragRef;
  219776. if (GetEventParameter (theEvent, kEventParamDragRef, typeDragRef, 0, sizeof (dragRef), 0, &dragRef) == noErr)
  219777. {
  219778. UInt16 numItems = 0;
  219779. if (CountDragItems (dragRef, &numItems) == noErr)
  219780. {
  219781. for (int i = 0; i < (int) numItems; ++i)
  219782. {
  219783. DragItemRef ref;
  219784. if (GetDragItemReferenceNumber (dragRef, i + 1, &ref) == noErr)
  219785. {
  219786. const FlavorType flavorType = kDragFlavorTypeHFS;
  219787. Size size = 0;
  219788. if (GetFlavorDataSize (dragRef, ref, flavorType, &size) == noErr)
  219789. {
  219790. void* data = juce_calloc (size);
  219791. if (GetFlavorData (dragRef, ref, flavorType, data, &size, 0) == noErr)
  219792. {
  219793. HFSFlavor* f = (HFSFlavor*) data;
  219794. FSRef fsref;
  219795. if (FSpMakeFSRef (&f->fileSpec, &fsref) == noErr)
  219796. {
  219797. const String path (PlatformUtilities::makePathFromFSRef (&fsref));
  219798. if (path.isNotEmpty())
  219799. dragAndDropFiles.add (path);
  219800. }
  219801. }
  219802. juce_free (data);
  219803. }
  219804. }
  219805. }
  219806. dragAndDropFiles.trim();
  219807. dragAndDropFiles.removeEmptyStrings();
  219808. }
  219809. }
  219810. }
  219811. void resizeViewToFitWindow()
  219812. {
  219813. HIRect r;
  219814. if (isSharedWindow)
  219815. {
  219816. HIViewGetFrame (viewRef, &r);
  219817. r.size.width = (float) component->getWidth();
  219818. r.size.height = (float) component->getHeight();
  219819. }
  219820. else
  219821. {
  219822. r.origin.x = 0;
  219823. r.origin.y = 0;
  219824. Rect w;
  219825. GetWindowBounds (windowRef, windowRegionToUse, &w);
  219826. r.size.width = (float) (w.right - w.left);
  219827. r.size.height = (float) (w.bottom - w.top);
  219828. }
  219829. HIViewSetFrame (viewRef, &r);
  219830. #if MACOS_10_3_OR_EARLIER
  219831. component->repaint();
  219832. #endif
  219833. }
  219834. OSStatus hiViewDraw (EventRef theEvent)
  219835. {
  219836. CGContextRef context = 0;
  219837. GetEventParameter (theEvent, kEventParamCGContextRef, typeCGContextRef, 0, sizeof (CGContextRef), 0, &context);
  219838. CGrafPtr oldPort;
  219839. CGrafPtr port = 0;
  219840. if (context == 0)
  219841. {
  219842. GetEventParameter (theEvent, kEventParamGrafPort, typeGrafPtr, 0, sizeof (CGrafPtr), 0, &port);
  219843. GetPort (&oldPort);
  219844. SetPort (port);
  219845. if (port != 0)
  219846. QDBeginCGContext (port, &context);
  219847. if (! isCompositingWindow)
  219848. {
  219849. Rect bounds;
  219850. GetWindowBounds (windowRef, windowRegionToUse, &bounds);
  219851. CGContextTranslateCTM (context, 0, bounds.bottom - bounds.top);
  219852. CGContextScaleCTM (context, 1.0, -1.0);
  219853. }
  219854. if (isSharedWindow)
  219855. {
  219856. // NB - Had terrible problems trying to correctly get the position
  219857. // of this view relative to the window, and this seems wrong, but
  219858. // works better than any other method I've tried..
  219859. HIRect hiViewPos;
  219860. HIViewGetFrame (viewRef, &hiViewPos);
  219861. CGContextTranslateCTM (context, hiViewPos.origin.x, hiViewPos.origin.y);
  219862. }
  219863. }
  219864. #if MACOS_10_2_OR_EARLIER
  219865. RgnHandle rgn = 0;
  219866. GetEventParameter (theEvent, kEventParamRgnHandle, typeQDRgnHandle, 0, sizeof (RgnHandle), 0, &rgn);
  219867. CGRect clip;
  219868. // (avoid doing this in plugins because of some strange redraw bugs..)
  219869. if (rgn != 0 && JUCEApplication::getInstance() != 0)
  219870. {
  219871. Rect bounds;
  219872. GetRegionBounds (rgn, &bounds);
  219873. clip.origin.x = bounds.left;
  219874. clip.origin.y = bounds.top;
  219875. clip.size.width = bounds.right - bounds.left;
  219876. clip.size.height = bounds.bottom - bounds.top;
  219877. }
  219878. else
  219879. {
  219880. HIViewGetBounds (viewRef, &clip);
  219881. clip.origin.x = 0;
  219882. clip.origin.y = 0;
  219883. }
  219884. #else
  219885. CGRect clip (CGContextGetClipBoundingBox (context));
  219886. #endif
  219887. clip = CGRectIntegral (clip);
  219888. if (clip.origin.x < 0)
  219889. {
  219890. clip.size.width += clip.origin.x;
  219891. clip.origin.x = 0;
  219892. }
  219893. if (clip.origin.y < 0)
  219894. {
  219895. clip.size.height += clip.origin.y;
  219896. clip.origin.y = 0;
  219897. }
  219898. if (! component->isOpaque())
  219899. CGContextClearRect (context, clip);
  219900. repainter->paint (context,
  219901. (int) clip.origin.x, (int) clip.origin.y,
  219902. (int) clip.size.width, (int) clip.size.height);
  219903. if (port != 0)
  219904. {
  219905. CGContextFlush (context);
  219906. QDEndCGContext (port, &context);
  219907. SetPort (oldPort);
  219908. }
  219909. repainter->repaintAnyRemainingRegions();
  219910. return noErr;
  219911. }
  219912. OSStatus handleWindowClassEvent (EventRef theEvent)
  219913. {
  219914. switch (GetEventKind (theEvent))
  219915. {
  219916. case kEventWindowBoundsChanged:
  219917. resizeViewToFitWindow();
  219918. break; // allow other handlers in the event chain to also get a look at the events
  219919. case kEventWindowBoundsChanging:
  219920. if ((styleFlags & (windowIsResizable | windowHasTitleBar)) == (windowIsResizable | windowHasTitleBar))
  219921. {
  219922. UInt32 atts = 0;
  219923. GetEventParameter (theEvent, kEventParamAttributes, typeUInt32,
  219924. 0, sizeof (UInt32), 0, &atts);
  219925. if ((atts & (kWindowBoundsChangeUserDrag | kWindowBoundsChangeUserResize)) != 0)
  219926. {
  219927. if (component->isCurrentlyBlockedByAnotherModalComponent())
  219928. {
  219929. Component* const modal = Component::getCurrentlyModalComponent();
  219930. if (modal != 0)
  219931. {
  219932. static uint32 lastDragTime = 0;
  219933. const uint32 now = Time::currentTimeMillis();
  219934. if (now > lastDragTime + 1000)
  219935. {
  219936. lastDragTime = now;
  219937. modal->inputAttemptWhenModal();
  219938. }
  219939. const Rectangle currentRect (getComponent()->getBounds());
  219940. Rect current;
  219941. current.left = currentRect.getX();
  219942. current.top = currentRect.getY();
  219943. current.right = currentRect.getRight();
  219944. current.bottom = currentRect.getBottom();
  219945. // stop the window getting dragged..
  219946. SetEventParameter (theEvent, kEventParamCurrentBounds, typeQDRectangle,
  219947. sizeof (Rect), &current);
  219948. return noErr;
  219949. }
  219950. }
  219951. if ((atts & kWindowBoundsChangeUserResize) != 0
  219952. && constrainer != 0 && ! isSharedWindow)
  219953. {
  219954. Rect current;
  219955. GetEventParameter (theEvent, kEventParamCurrentBounds, typeQDRectangle,
  219956. 0, sizeof (Rect), 0, &current);
  219957. int x = current.left;
  219958. int y = current.top;
  219959. int w = current.right - current.left;
  219960. int h = current.bottom - current.top;
  219961. const Rectangle currentRect (getComponent()->getBounds());
  219962. constrainer->checkBounds (x, y, w, h, currentRect,
  219963. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  219964. y != currentRect.getY() && y + h == currentRect.getBottom(),
  219965. x != currentRect.getX() && x + w == currentRect.getRight(),
  219966. y == currentRect.getY() && y + h != currentRect.getBottom(),
  219967. x == currentRect.getX() && x + w != currentRect.getRight());
  219968. current.left = x;
  219969. current.top = y;
  219970. current.right = x + w;
  219971. current.bottom = y + h;
  219972. SetEventParameter (theEvent, kEventParamCurrentBounds, typeQDRectangle,
  219973. sizeof (Rect), &current);
  219974. return noErr;
  219975. }
  219976. }
  219977. }
  219978. break;
  219979. case kEventWindowFocusAcquired:
  219980. keysCurrentlyDown.clear();
  219981. if ((! isSharedWindow) || HIViewSubtreeContainsFocus (viewRef))
  219982. viewFocusGain();
  219983. break; // allow other handlers in the event chain to also get a look at the events
  219984. case kEventWindowFocusRelinquish:
  219985. keysCurrentlyDown.clear();
  219986. viewFocusLoss();
  219987. break; // allow other handlers in the event chain to also get a look at the events
  219988. case kEventWindowCollapsed:
  219989. minimisedWindows.addIfNotAlreadyThere (windowRef);
  219990. handleMovedOrResized();
  219991. break; // allow other handlers in the event chain to also get a look at the events
  219992. case kEventWindowExpanded:
  219993. minimisedWindows.removeValue (windowRef);
  219994. handleMovedOrResized();
  219995. break; // allow other handlers in the event chain to also get a look at the events
  219996. case kEventWindowShown:
  219997. break; // allow other handlers in the event chain to also get a look at the events
  219998. case kEventWindowClose:
  219999. if (isSharedWindow)
  220000. break; // break to let the OS delete the window
  220001. handleUserClosingWindow();
  220002. return noErr; // avoids letting the OS to delete the window, we'll do that ourselves.
  220003. default:
  220004. break;
  220005. }
  220006. return eventNotHandledErr;
  220007. }
  220008. OSStatus handleWindowEventForPeer (EventHandlerCallRef callRef, EventRef theEvent)
  220009. {
  220010. switch (GetEventClass (theEvent))
  220011. {
  220012. case kEventClassMouse:
  220013. {
  220014. static HIViewComponentPeer* lastMouseDownPeer = 0;
  220015. const UInt32 eventKind = GetEventKind (theEvent);
  220016. HIViewRef view = 0;
  220017. if (eventKind == kEventMouseDragged)
  220018. {
  220019. view = viewRef;
  220020. }
  220021. else
  220022. {
  220023. HIViewGetViewForMouseEvent (HIViewGetRoot (windowRef), theEvent, &view);
  220024. if (view != viewRef)
  220025. {
  220026. if ((eventKind == kEventMouseUp
  220027. || eventKind == kEventMouseExited)
  220028. && ComponentPeer::isValidPeer (lastMouseDownPeer))
  220029. {
  220030. return lastMouseDownPeer->handleMouseEvent (callRef, theEvent);
  220031. }
  220032. return eventNotHandledErr;
  220033. }
  220034. }
  220035. if (eventKind == kEventMouseDown
  220036. || eventKind == kEventMouseDragged
  220037. || eventKind == kEventMouseEntered)
  220038. {
  220039. lastMouseDownPeer = this;
  220040. }
  220041. return handleMouseEvent (callRef, theEvent);
  220042. }
  220043. break;
  220044. case kEventClassWindow:
  220045. return handleWindowClassEvent (theEvent);
  220046. case kEventClassKeyboard:
  220047. if (isFocused())
  220048. return handleKeyEvent (theEvent, 0);
  220049. break;
  220050. case kEventClassTextInput:
  220051. if (isFocused())
  220052. return handleTextInputEvent (theEvent);
  220053. break;
  220054. default:
  220055. break;
  220056. }
  220057. return eventNotHandledErr;
  220058. }
  220059. static pascal OSStatus handleWindowEvent (EventHandlerCallRef callRef, EventRef theEvent, void* userData)
  220060. {
  220061. MessageManager::delayWaitCursor();
  220062. HIViewComponentPeer* const peer = (HIViewComponentPeer*) userData;
  220063. const MessageManagerLock messLock;
  220064. if (ComponentPeer::isValidPeer (peer))
  220065. return peer->handleWindowEventForPeer (callRef, theEvent);
  220066. return eventNotHandledErr;
  220067. }
  220068. static pascal OSStatus hiViewEventHandler (EventHandlerCallRef myHandler, EventRef theEvent, void* userData)
  220069. {
  220070. MessageManager::delayWaitCursor();
  220071. const UInt32 eventKind = GetEventKind (theEvent);
  220072. const UInt32 eventClass = GetEventClass (theEvent);
  220073. if (eventClass == kEventClassHIObject)
  220074. {
  220075. switch (eventKind)
  220076. {
  220077. case kEventHIObjectConstruct:
  220078. {
  220079. void* data = juce_calloc (sizeof (void*));
  220080. SetEventParameter (theEvent, kEventParamHIObjectInstance,
  220081. typeVoidPtr, sizeof (void*), &data);
  220082. return noErr;
  220083. }
  220084. case kEventHIObjectInitialize:
  220085. GetEventParameter (theEvent, 'peer', typeVoidPtr, 0, sizeof (void*), 0, (void**) userData);
  220086. return noErr;
  220087. case kEventHIObjectDestruct:
  220088. juce_free (userData);
  220089. return noErr;
  220090. default:
  220091. break;
  220092. }
  220093. }
  220094. else if (eventClass == kEventClassControl)
  220095. {
  220096. HIViewComponentPeer* const peer = *(HIViewComponentPeer**) userData;
  220097. const MessageManagerLock messLock;
  220098. if (! ComponentPeer::isValidPeer (peer))
  220099. return eventNotHandledErr;
  220100. switch (eventKind)
  220101. {
  220102. case kEventControlDraw:
  220103. return peer->hiViewDraw (theEvent);
  220104. case kEventControlBoundsChanged:
  220105. {
  220106. HIRect bounds;
  220107. HIViewGetBounds (peer->viewRef, &bounds);
  220108. peer->repaint (0, 0, roundFloatToInt (bounds.size.width), roundFloatToInt (bounds.size.height));
  220109. peer->handleMovedOrResized();
  220110. return noErr;
  220111. }
  220112. case kEventControlHitTest:
  220113. {
  220114. HIPoint where;
  220115. GetEventParameter (theEvent, kEventParamMouseLocation, typeHIPoint, 0, sizeof (HIPoint), 0, &where);
  220116. HIRect bounds;
  220117. HIViewGetBounds (peer->viewRef, &bounds);
  220118. ControlPartCode part = kControlNoPart;
  220119. if (CGRectContainsPoint (bounds, where))
  220120. part = 1;
  220121. SetEventParameter (theEvent, kEventParamControlPart, typeControlPartCode, sizeof (ControlPartCode), &part);
  220122. return noErr;
  220123. }
  220124. break;
  220125. case kEventControlSetFocusPart:
  220126. {
  220127. ControlPartCode desiredFocus;
  220128. if (GetEventParameter (theEvent, kEventParamControlPart, typeControlPartCode, 0, sizeof (ControlPartCode), 0, &desiredFocus) != noErr)
  220129. break;
  220130. if (desiredFocus == kControlNoPart)
  220131. peer->viewFocusLoss();
  220132. else
  220133. peer->viewFocusGain();
  220134. return noErr;
  220135. }
  220136. break;
  220137. case kEventControlDragEnter:
  220138. {
  220139. #if MACOS_10_2_OR_EARLIER
  220140. enum { kEventParamControlWouldAcceptDrop = 'cldg' };
  220141. #endif
  220142. Boolean accept = true;
  220143. SetEventParameter (theEvent, kEventParamControlWouldAcceptDrop, typeBoolean, sizeof (accept), &accept);
  220144. peer->doDragDropEnter (theEvent);
  220145. return noErr;
  220146. }
  220147. case kEventControlDragWithin:
  220148. peer->doDragDropMove (theEvent);
  220149. return noErr;
  220150. case kEventControlDragLeave:
  220151. peer->doDragDropExit (theEvent);
  220152. return noErr;
  220153. case kEventControlDragReceive:
  220154. peer->doDragDrop (theEvent);
  220155. return noErr;
  220156. case kEventControlOwningWindowChanged:
  220157. return peer->ownerWindowChanged (theEvent);
  220158. #if ! MACOS_10_2_OR_EARLIER
  220159. case kEventControlGetFrameMetrics:
  220160. {
  220161. CallNextEventHandler (myHandler, theEvent);
  220162. HIViewFrameMetrics metrics;
  220163. GetEventParameter (theEvent, kEventParamControlFrameMetrics, typeControlFrameMetrics, 0, sizeof (metrics), 0, &metrics);
  220164. metrics.top = metrics.bottom = 0;
  220165. SetEventParameter (theEvent, kEventParamControlFrameMetrics, typeControlFrameMetrics, sizeof (metrics), &metrics);
  220166. return noErr;
  220167. }
  220168. #endif
  220169. case kEventControlInitialize:
  220170. {
  220171. UInt32 features = kControlSupportsDragAndDrop
  220172. | kControlSupportsFocus
  220173. | kControlHandlesTracking
  220174. | kControlSupportsEmbedding
  220175. | (1 << 8) /*kHIViewFeatureGetsFocusOnClick*/;
  220176. SetEventParameter (theEvent, kEventParamControlFeatures, typeUInt32, sizeof (UInt32), &features);
  220177. return noErr;
  220178. }
  220179. default:
  220180. break;
  220181. }
  220182. }
  220183. return eventNotHandledErr;
  220184. }
  220185. WindowRef createNewWindow (const int windowStyleFlags)
  220186. {
  220187. jassert (windowRef == 0);
  220188. static ToolboxObjectClassRef customWindowClass = 0;
  220189. if (customWindowClass == 0)
  220190. {
  220191. // Register our window class
  220192. const EventTypeSpec customTypes[] = { { kEventClassWindow, kEventWindowDrawFrame } };
  220193. UnsignedWide t;
  220194. Microseconds (&t);
  220195. const String randomString ((int) (t.lo & 0x7ffffff));
  220196. const String juceWindowClassName (T("JUCEWindowClass_") + randomString);
  220197. CFStringRef juceWindowClassNameCFString = PlatformUtilities::juceStringToCFString (juceWindowClassName);
  220198. RegisterToolboxObjectClass (juceWindowClassNameCFString,
  220199. 0, 1, customTypes,
  220200. NewEventHandlerUPP (handleFrameRepaintEvent),
  220201. 0, &customWindowClass);
  220202. CFRelease (juceWindowClassNameCFString);
  220203. }
  220204. Rect pos;
  220205. pos.left = getComponent()->getX();
  220206. pos.top = getComponent()->getY();
  220207. pos.right = getComponent()->getRight();
  220208. pos.bottom = getComponent()->getBottom();
  220209. int attributes = kWindowStandardHandlerAttribute | kWindowCompositingAttribute;
  220210. if ((windowStyleFlags & windowHasDropShadow) == 0)
  220211. attributes |= kWindowNoShadowAttribute;
  220212. if ((windowStyleFlags & windowIgnoresMouseClicks) != 0)
  220213. attributes |= kWindowIgnoreClicksAttribute;
  220214. #if ! MACOS_10_3_OR_EARLIER
  220215. if ((windowStyleFlags & windowIsTemporary) != 0)
  220216. attributes |= kWindowDoesNotCycleAttribute;
  220217. #endif
  220218. WindowRef newWindow = 0;
  220219. if ((windowStyleFlags & windowHasTitleBar) == 0)
  220220. {
  220221. attributes |= kWindowCollapseBoxAttribute;
  220222. WindowDefSpec customWindowSpec;
  220223. customWindowSpec.defType = kWindowDefObjectClass;
  220224. customWindowSpec.u.classRef = customWindowClass;
  220225. CreateCustomWindow (&customWindowSpec,
  220226. ((windowStyleFlags & windowIsTemporary) != 0) ? kUtilityWindowClass :
  220227. (getComponent()->isAlwaysOnTop() ? kUtilityWindowClass
  220228. : kDocumentWindowClass),
  220229. attributes,
  220230. &pos,
  220231. &newWindow);
  220232. }
  220233. else
  220234. {
  220235. if ((windowStyleFlags & windowHasCloseButton) != 0)
  220236. attributes |= kWindowCloseBoxAttribute;
  220237. if ((windowStyleFlags & windowHasMinimiseButton) != 0)
  220238. attributes |= kWindowCollapseBoxAttribute;
  220239. if ((windowStyleFlags & windowHasMaximiseButton) != 0)
  220240. attributes |= kWindowFullZoomAttribute;
  220241. if ((windowStyleFlags & windowIsResizable) != 0)
  220242. attributes |= kWindowResizableAttribute | kWindowLiveResizeAttribute;
  220243. CreateNewWindow (kDocumentWindowClass, attributes, &pos, &newWindow);
  220244. }
  220245. jassert (newWindow != 0);
  220246. if (newWindow != 0)
  220247. {
  220248. HideWindow (newWindow);
  220249. SetAutomaticControlDragTrackingEnabledForWindow (newWindow, true);
  220250. if (! getComponent()->isOpaque())
  220251. SetWindowAlpha (newWindow, 0.9999999f); // to fool it into giving the window an alpha-channel
  220252. }
  220253. return newWindow;
  220254. }
  220255. OSStatus ownerWindowChanged (EventRef theEvent)
  220256. {
  220257. WindowRef newWindow = 0;
  220258. GetEventParameter (theEvent, kEventParamControlCurrentOwningWindow, typeWindowRef, 0, sizeof (newWindow), 0, &newWindow);
  220259. if (windowRef != newWindow)
  220260. {
  220261. if (eventHandlerRef != 0)
  220262. {
  220263. RemoveEventHandler (eventHandlerRef);
  220264. eventHandlerRef = 0;
  220265. }
  220266. windowRef = newWindow;
  220267. if (windowRef != 0)
  220268. {
  220269. const EventTypeSpec eventTypes[] =
  220270. {
  220271. { kEventClassWindow, kEventWindowBoundsChanged },
  220272. { kEventClassWindow, kEventWindowBoundsChanging },
  220273. { kEventClassWindow, kEventWindowFocusAcquired },
  220274. { kEventClassWindow, kEventWindowFocusRelinquish },
  220275. { kEventClassWindow, kEventWindowCollapsed },
  220276. { kEventClassWindow, kEventWindowExpanded },
  220277. { kEventClassWindow, kEventWindowShown },
  220278. { kEventClassWindow, kEventWindowClose },
  220279. { kEventClassMouse, kEventMouseDown },
  220280. { kEventClassMouse, kEventMouseUp },
  220281. { kEventClassMouse, kEventMouseMoved },
  220282. { kEventClassMouse, kEventMouseDragged },
  220283. { kEventClassMouse, kEventMouseEntered },
  220284. { kEventClassMouse, kEventMouseExited },
  220285. { kEventClassMouse, kEventMouseWheelMoved },
  220286. { kEventClassKeyboard, kEventRawKeyUp },
  220287. { kEventClassKeyboard, kEventRawKeyRepeat },
  220288. { kEventClassKeyboard, kEventRawKeyModifiersChanged },
  220289. { kEventClassTextInput, kEventTextInputUnicodeForKeyEvent }
  220290. };
  220291. static EventHandlerUPP handleWindowEventUPP = 0;
  220292. if (handleWindowEventUPP == 0)
  220293. handleWindowEventUPP = NewEventHandlerUPP (handleWindowEvent);
  220294. InstallWindowEventHandler (windowRef, handleWindowEventUPP,
  220295. GetEventTypeCount (eventTypes), eventTypes,
  220296. (void*) this, (EventHandlerRef*) &eventHandlerRef);
  220297. WindowAttributes attributes;
  220298. GetWindowAttributes (windowRef, &attributes);
  220299. #if MACOS_10_3_OR_EARLIER
  220300. isCompositingWindow = ((attributes & kWindowCompositingAttribute) != 0);
  220301. #else
  220302. isCompositingWindow = HIViewIsCompositingEnabled (viewRef);
  220303. #endif
  220304. SetAutomaticControlDragTrackingEnabledForWindow (newWindow, true);
  220305. MouseCheckTimer::getInstance()->resetMouseMoveChecker();
  220306. }
  220307. }
  220308. resizeViewToFitWindow();
  220309. return noErr;
  220310. }
  220311. void createNewHIView()
  220312. {
  220313. jassert (viewRef == 0);
  220314. if (viewClassRef == 0)
  220315. {
  220316. // Register our HIView class
  220317. EventTypeSpec viewEvents[] =
  220318. {
  220319. { kEventClassHIObject, kEventHIObjectConstruct },
  220320. { kEventClassHIObject, kEventHIObjectInitialize },
  220321. { kEventClassHIObject, kEventHIObjectDestruct },
  220322. { kEventClassControl, kEventControlInitialize },
  220323. { kEventClassControl, kEventControlDraw },
  220324. { kEventClassControl, kEventControlBoundsChanged },
  220325. { kEventClassControl, kEventControlSetFocusPart },
  220326. { kEventClassControl, kEventControlHitTest },
  220327. { kEventClassControl, kEventControlDragEnter },
  220328. { kEventClassControl, kEventControlDragLeave },
  220329. { kEventClassControl, kEventControlDragWithin },
  220330. { kEventClassControl, kEventControlDragReceive },
  220331. { kEventClassControl, kEventControlOwningWindowChanged }
  220332. };
  220333. UnsignedWide t;
  220334. Microseconds (&t);
  220335. const String randomString ((int) (t.lo & 0x7ffffff));
  220336. const String juceHiViewClassName (T("JUCEHIViewClass_") + randomString);
  220337. juceHiViewClassNameCFString = PlatformUtilities::juceStringToCFString (juceHiViewClassName);
  220338. HIObjectRegisterSubclass (juceHiViewClassNameCFString,
  220339. kHIViewClassID, 0,
  220340. NewEventHandlerUPP (hiViewEventHandler),
  220341. GetEventTypeCount (viewEvents),
  220342. viewEvents, 0,
  220343. &viewClassRef);
  220344. }
  220345. EventRef event;
  220346. CreateEvent (0, kEventClassHIObject, kEventHIObjectInitialize, GetCurrentEventTime(), kEventAttributeNone, &event);
  220347. void* thisPointer = this;
  220348. SetEventParameter (event, 'peer', typeVoidPtr, sizeof (void*), &thisPointer);
  220349. HIObjectCreate (juceHiViewClassNameCFString, event, (HIObjectRef*) &viewRef);
  220350. SetControlDragTrackingEnabled (viewRef, true);
  220351. if (isSharedWindow)
  220352. {
  220353. setBounds (component->getX(), component->getY(),
  220354. component->getWidth(), component->getHeight(), false);
  220355. }
  220356. }
  220357. };
  220358. bool juce_isHIViewCreatedByJuce (HIViewRef view)
  220359. {
  220360. return juceHiViewClassNameCFString != 0
  220361. && HIObjectIsOfClass ((HIObjectRef) view, juceHiViewClassNameCFString);
  220362. }
  220363. bool juce_isWindowCreatedByJuce (WindowRef window)
  220364. {
  220365. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  220366. if (ComponentPeer::getPeer(i)->getNativeHandle() == window)
  220367. return true;
  220368. return false;
  220369. }
  220370. static void trackNextMouseEvent()
  220371. {
  220372. UInt32 mods;
  220373. MouseTrackingResult result;
  220374. ::Point where;
  220375. if (TrackMouseLocationWithOptions ((GrafPtr) -1, 0, 0.01, //kEventDurationForever,
  220376. &where, &mods, &result) != noErr
  220377. || ! ComponentPeer::isValidPeer (juce_currentMouseTrackingPeer))
  220378. {
  220379. juce_currentMouseTrackingPeer = 0;
  220380. return;
  220381. }
  220382. if (result == kMouseTrackingTimedOut)
  220383. return;
  220384. #if MACOS_10_3_OR_EARLIER
  220385. const int x = where.h - juce_currentMouseTrackingPeer->getScreenX();
  220386. const int y = where.v - juce_currentMouseTrackingPeer->getScreenY();
  220387. #else
  220388. HIPoint p;
  220389. p.x = where.h;
  220390. p.y = where.v;
  220391. HIPointConvert (&p, kHICoordSpaceScreenPixel, 0,
  220392. kHICoordSpaceView, ((HIViewComponentPeer*) juce_currentMouseTrackingPeer)->viewRef);
  220393. const int x = p.x;
  220394. const int y = p.y;
  220395. #endif
  220396. if (result == kMouseTrackingMouseDragged)
  220397. {
  220398. updateModifiers (0);
  220399. juce_currentMouseTrackingPeer->handleMouseDrag (x, y, getEventTime (0));
  220400. if (! ComponentPeer::isValidPeer (juce_currentMouseTrackingPeer))
  220401. {
  220402. juce_currentMouseTrackingPeer = 0;
  220403. return;
  220404. }
  220405. }
  220406. else if (result == kMouseTrackingMouseUp
  220407. || result == kMouseTrackingUserCancelled
  220408. || result == kMouseTrackingMouseMoved)
  220409. {
  220410. ComponentPeer* const oldPeer = juce_currentMouseTrackingPeer;
  220411. juce_currentMouseTrackingPeer = 0;
  220412. if (ComponentPeer::isValidPeer (oldPeer))
  220413. {
  220414. const int oldModifiers = currentModifiers;
  220415. currentModifiers &= ~(ModifierKeys::leftButtonModifier | ModifierKeys::rightButtonModifier | ModifierKeys::middleButtonModifier);
  220416. updateModifiers (0);
  220417. oldPeer->handleMouseUp (oldModifiers, x, y, getEventTime (0));
  220418. }
  220419. }
  220420. }
  220421. bool juce_dispatchNextMessageOnSystemQueue (bool returnIfNoPendingMessages)
  220422. {
  220423. if (juce_currentMouseTrackingPeer != 0)
  220424. trackNextMouseEvent();
  220425. EventRef theEvent;
  220426. if (ReceiveNextEvent (0, 0, (returnIfNoPendingMessages) ? kEventDurationNoWait
  220427. : kEventDurationForever,
  220428. true, &theEvent) == noErr)
  220429. {
  220430. if (GetEventClass (theEvent) == kEventClassAppleEvent)
  220431. {
  220432. EventRecord eventRec;
  220433. if (ConvertEventRefToEventRecord (theEvent, &eventRec))
  220434. AEProcessAppleEvent (&eventRec);
  220435. }
  220436. else
  220437. {
  220438. EventTargetRef theTarget = GetEventDispatcherTarget();
  220439. SendEventToEventTarget (theEvent, theTarget);
  220440. }
  220441. ReleaseEvent (theEvent);
  220442. return true;
  220443. }
  220444. return false;
  220445. }
  220446. ComponentPeer* Component::createNewPeer (int styleFlags, void* windowToAttachTo)
  220447. {
  220448. return new HIViewComponentPeer (this, styleFlags, (HIViewRef) windowToAttachTo);
  220449. }
  220450. void MouseCheckTimer::timerCallback()
  220451. {
  220452. if (ModifierKeys::getCurrentModifiersRealtime().isAnyMouseButtonDown())
  220453. return;
  220454. if (Process::isForegroundProcess())
  220455. {
  220456. bool stillOver = false;
  220457. int x = 0, y = 0, w = 0, h = 0;
  220458. int mx = 0, my = 0;
  220459. const bool validWindow = ComponentPeer::isValidPeer (lastPeerUnderMouse);
  220460. if (validWindow)
  220461. {
  220462. lastPeerUnderMouse->getBounds (x, y, w, h, true);
  220463. Desktop::getMousePosition (mx, my);
  220464. stillOver = (mx >= x && my >= y && mx < x + w && my < y + h);
  220465. if (stillOver)
  220466. {
  220467. // check if it's over an embedded HIView
  220468. int rx = mx, ry = my;
  220469. lastPeerUnderMouse->globalPositionToRelative (rx, ry);
  220470. HIPoint hipoint;
  220471. hipoint.x = rx;
  220472. hipoint.y = ry;
  220473. HIViewRef root;
  220474. GetRootControl ((WindowRef) lastPeerUnderMouse->getNativeHandle(), &root);
  220475. HIViewRef hitview;
  220476. if (HIViewGetSubviewHit (root, &hipoint, true, &hitview) == noErr && hitview != 0)
  220477. {
  220478. stillOver = HIObjectIsOfClass ((HIObjectRef) hitview, juceHiViewClassNameCFString);
  220479. }
  220480. }
  220481. }
  220482. if (! stillOver)
  220483. {
  220484. // mouse is outside our windows so set a normal cursor (only
  220485. // if we're running as an app, not a plugin)
  220486. if (JUCEApplication::getInstance() != 0)
  220487. SetThemeCursor (kThemeArrowCursor);
  220488. if (validWindow)
  220489. lastPeerUnderMouse->handleMouseExit (mx - x, my - y, Time::currentTimeMillis());
  220490. if (hasEverHadAMouseMove)
  220491. stopTimer();
  220492. }
  220493. if ((! hasEverHadAMouseMove) && validWindow
  220494. && (mx != lastX || my != lastY))
  220495. {
  220496. lastX = mx;
  220497. lastY = my;
  220498. if (stillOver)
  220499. lastPeerUnderMouse->handleMouseMove (mx - x, my - y, Time::currentTimeMillis());
  220500. }
  220501. }
  220502. }
  220503. // called from juce_Messaging.cpp
  220504. void juce_HandleProcessFocusChange()
  220505. {
  220506. keysCurrentlyDown.clear();
  220507. if (HIViewComponentPeer::isValidPeer (currentlyFocusedPeer))
  220508. {
  220509. if (Process::isForegroundProcess())
  220510. currentlyFocusedPeer->handleFocusGain();
  220511. else
  220512. currentlyFocusedPeer->handleFocusLoss();
  220513. }
  220514. }
  220515. static bool performDrag (DragRef drag)
  220516. {
  220517. EventRecord event;
  220518. event.what = mouseDown;
  220519. event.message = 0;
  220520. event.when = TickCount();
  220521. int x, y;
  220522. Desktop::getMousePosition (x, y);
  220523. event.where.h = x;
  220524. event.where.v = y;
  220525. event.modifiers = GetCurrentKeyModifiers();
  220526. RgnHandle rgn = NewRgn();
  220527. RgnHandle rgn2 = NewRgn();
  220528. SetRectRgn (rgn,
  220529. event.where.h - 8, event.where.v - 8,
  220530. event.where.h + 8, event.where.v + 8);
  220531. CopyRgn (rgn, rgn2);
  220532. InsetRgn (rgn2, 1, 1);
  220533. DiffRgn (rgn, rgn2, rgn);
  220534. DisposeRgn (rgn2);
  220535. bool result = TrackDrag (drag, &event, rgn) == noErr;
  220536. DisposeRgn (rgn);
  220537. return result;
  220538. }
  220539. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMoveFiles)
  220540. {
  220541. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  220542. ComponentPeer::getPeer (i)->performAnyPendingRepaintsNow();
  220543. DragRef drag;
  220544. bool result = false;
  220545. if (NewDrag (&drag) == noErr)
  220546. {
  220547. for (int i = 0; i < files.size(); ++i)
  220548. {
  220549. HFSFlavor hfsData;
  220550. if (PlatformUtilities::makeFSSpecFromPath (&hfsData.fileSpec, files[i]))
  220551. {
  220552. FInfo info;
  220553. if (FSpGetFInfo (&hfsData.fileSpec, &info) == noErr)
  220554. {
  220555. hfsData.fileType = info.fdType;
  220556. hfsData.fileCreator = info.fdCreator;
  220557. hfsData.fdFlags = info.fdFlags;
  220558. AddDragItemFlavor (drag, i + 1, kDragFlavorTypeHFS, &hfsData, sizeof (hfsData), 0);
  220559. result = true;
  220560. }
  220561. }
  220562. }
  220563. SetDragAllowableActions (drag, canMoveFiles ? kDragActionAll
  220564. : kDragActionCopy, false);
  220565. if (result)
  220566. result = performDrag (drag);
  220567. DisposeDrag (drag);
  220568. }
  220569. return result;
  220570. }
  220571. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  220572. {
  220573. jassertfalse // not implemented!
  220574. return false;
  220575. }
  220576. bool Process::isForegroundProcess() throw()
  220577. {
  220578. ProcessSerialNumber psn, front;
  220579. GetCurrentProcess (&psn);
  220580. GetFrontProcess (&front);
  220581. Boolean b;
  220582. return (SameProcess (&psn, &front, &b) == noErr) && b;
  220583. }
  220584. bool Desktop::canUseSemiTransparentWindows() throw()
  220585. {
  220586. return true;
  220587. }
  220588. void Desktop::getMousePosition (int& x, int& y) throw()
  220589. {
  220590. CGrafPtr currentPort;
  220591. GetPort (&currentPort);
  220592. if (! IsValidPort (currentPort))
  220593. {
  220594. WindowRef front = FrontWindow();
  220595. if (front != 0)
  220596. {
  220597. SetPortWindowPort (front);
  220598. }
  220599. else
  220600. {
  220601. x = y = 0;
  220602. return;
  220603. }
  220604. }
  220605. ::Point p;
  220606. GetMouse (&p);
  220607. LocalToGlobal (&p);
  220608. x = p.h;
  220609. y = p.v;
  220610. SetPort (currentPort);
  220611. }
  220612. void Desktop::setMousePosition (int x, int y) throw()
  220613. {
  220614. // this rubbish needs to be done around the warp call, to avoid causing a
  220615. // bizarre glitch..
  220616. CGAssociateMouseAndMouseCursorPosition (false);
  220617. CGSetLocalEventsSuppressionInterval (0);
  220618. CGPoint pos = { x, y };
  220619. CGWarpMouseCursorPosition (pos);
  220620. CGAssociateMouseAndMouseCursorPosition (true);
  220621. }
  220622. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  220623. {
  220624. return ModifierKeys (currentModifiers);
  220625. }
  220626. class ScreenSaverDefeater : public Timer,
  220627. public DeletedAtShutdown
  220628. {
  220629. public:
  220630. ScreenSaverDefeater() throw()
  220631. {
  220632. startTimer (10000);
  220633. timerCallback();
  220634. }
  220635. ~ScreenSaverDefeater()
  220636. {
  220637. }
  220638. void timerCallback()
  220639. {
  220640. if (Process::isForegroundProcess())
  220641. UpdateSystemActivity (UsrActivity);
  220642. }
  220643. };
  220644. static ScreenSaverDefeater* screenSaverDefeater = 0;
  220645. void Desktop::setScreenSaverEnabled (const bool isEnabled) throw()
  220646. {
  220647. if (screenSaverDefeater == 0)
  220648. screenSaverDefeater = new ScreenSaverDefeater();
  220649. }
  220650. bool Desktop::isScreenSaverEnabled() throw()
  220651. {
  220652. return screenSaverDefeater == 0;
  220653. }
  220654. void juce_updateMultiMonitorInfo (Array <Rectangle>& monitorCoords, const bool clipToWorkArea) throw()
  220655. {
  220656. int mainMonitorIndex = 0;
  220657. CGDirectDisplayID mainDisplayID = CGMainDisplayID();
  220658. CGDisplayCount count = 0;
  220659. CGDirectDisplayID disps [8];
  220660. if (CGGetOnlineDisplayList (numElementsInArray (disps), disps, &count) == noErr)
  220661. {
  220662. for (int i = 0; i < count; ++i)
  220663. {
  220664. if (mainDisplayID == disps[i])
  220665. mainMonitorIndex = monitorCoords.size();
  220666. GDHandle hGDevice;
  220667. if (clipToWorkArea
  220668. && DMGetGDeviceByDisplayID ((DisplayIDType) disps[i], &hGDevice, false) == noErr)
  220669. {
  220670. Rect rect;
  220671. GetAvailableWindowPositioningBounds (hGDevice, &rect);
  220672. monitorCoords.add (Rectangle (rect.left,
  220673. rect.top,
  220674. rect.right - rect.left,
  220675. rect.bottom - rect.top));
  220676. }
  220677. else
  220678. {
  220679. const CGRect r (CGDisplayBounds (disps[i]));
  220680. monitorCoords.add (Rectangle ((int) r.origin.x,
  220681. (int) r.origin.y,
  220682. (int) r.size.width,
  220683. (int) r.size.height));
  220684. }
  220685. }
  220686. }
  220687. // make sure the first in the list is the main monitor
  220688. if (mainMonitorIndex > 0)
  220689. monitorCoords.swap (mainMonitorIndex, 0);
  220690. jassert (monitorCoords.size() > 0);
  220691. if (monitorCoords.size() == 0)
  220692. monitorCoords.add (Rectangle (0, 0, 1024, 768));
  220693. }
  220694. struct CursorWrapper
  220695. {
  220696. Cursor* cursor;
  220697. ThemeCursor themeCursor;
  220698. };
  220699. void* juce_createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) throw()
  220700. {
  220701. const int maxW = 16;
  220702. const int maxH = 16;
  220703. const Image* im = &image;
  220704. Image* newIm = 0;
  220705. if (image.getWidth() > maxW || image.getHeight() > maxH)
  220706. {
  220707. im = newIm = image.createCopy (maxW, maxH);
  220708. hotspotX = (hotspotX * maxW) / image.getWidth();
  220709. hotspotY = (hotspotY * maxH) / image.getHeight();
  220710. }
  220711. Cursor* const c = new Cursor();
  220712. c->hotSpot.h = hotspotX;
  220713. c->hotSpot.v = hotspotY;
  220714. for (int y = 0; y < maxH; ++y)
  220715. {
  220716. c->data[y] = 0;
  220717. c->mask[y] = 0;
  220718. for (int x = 0; x < maxW; ++x)
  220719. {
  220720. const Colour pixelColour (im->getPixelAt (15 - x, y));
  220721. if (pixelColour.getAlpha() > 0.5f)
  220722. {
  220723. c->mask[y] |= (1 << x);
  220724. if (pixelColour.getBrightness() < 0.5f)
  220725. c->data[y] |= (1 << x);
  220726. }
  220727. }
  220728. c->data[y] = CFSwapInt16BigToHost (c->data[y]);
  220729. c->mask[y] = CFSwapInt16BigToHost (c->mask[y]);
  220730. }
  220731. if (newIm != 0)
  220732. delete newIm;
  220733. CursorWrapper* const cw = new CursorWrapper();
  220734. cw->cursor = c;
  220735. cw->themeCursor = kThemeArrowCursor;
  220736. return (void*) cw;
  220737. }
  220738. static void* cursorFromData (const unsigned char* data, const int size, int hx, int hy) throw()
  220739. {
  220740. Image* const im = ImageFileFormat::loadFrom ((const char*) data, size);
  220741. jassert (im != 0);
  220742. void* curs = juce_createMouseCursorFromImage (*im, hx, hy);
  220743. delete im;
  220744. return curs;
  220745. }
  220746. const unsigned int kSpecialNoCursor = 'nocr';
  220747. void* juce_createStandardMouseCursor (MouseCursor::StandardCursorType type) throw()
  220748. {
  220749. ThemeCursor cursorId = kThemeArrowCursor;
  220750. switch (type)
  220751. {
  220752. case MouseCursor::NormalCursor:
  220753. cursorId = kThemeArrowCursor;
  220754. break;
  220755. case MouseCursor::NoCursor:
  220756. cursorId = kSpecialNoCursor;
  220757. break;
  220758. case MouseCursor::DraggingHandCursor:
  220759. {
  220760. 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,
  220761. 0,0,0,0,0,33,249,4,1,0,0,2,0,44,0,0,0,0,16,0,
  220762. 16,0,0,2,52,148,47,0,200,185,16,130,90,12,74,139,107,84,123,39,
  220763. 132,117,151,116,132,146,248,60,209,138,98,22,203,114,34,236,37,52,77,217,
  220764. 247,154,191,119,110,240,193,128,193,95,163,56,60,234,98,135,2,0,59 };
  220765. const int cursDataSize = 99;
  220766. return cursorFromData (cursData, cursDataSize, 8, 8);
  220767. }
  220768. break;
  220769. case MouseCursor::CopyingCursor:
  220770. cursorId = kThemeCopyArrowCursor;
  220771. break;
  220772. case MouseCursor::WaitCursor:
  220773. cursorId = kThemeWatchCursor;
  220774. break;
  220775. case MouseCursor::IBeamCursor:
  220776. cursorId = kThemeIBeamCursor;
  220777. break;
  220778. case MouseCursor::PointingHandCursor:
  220779. cursorId = kThemePointingHandCursor;
  220780. break;
  220781. case MouseCursor::LeftRightResizeCursor:
  220782. case MouseCursor::LeftEdgeResizeCursor:
  220783. case MouseCursor::RightEdgeResizeCursor:
  220784. {
  220785. 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,
  220786. 255,255,0,0,0,33,249,4,1,0,0,2,0,44,0,0,0,0,16,0,
  220787. 16,0,0,2,38,148,143,169,203,237,15,19,0,106,202,64,111,22,32,224,
  220788. 9,78,30,213,121,230,121,146,99,8,142,71,183,189,152,20,27,86,132,231,
  220789. 58,83,0,0,59 };
  220790. const int cursDataSize = 85;
  220791. return cursorFromData (cursData, cursDataSize, 8, 8);
  220792. }
  220793. case MouseCursor::UpDownResizeCursor:
  220794. case MouseCursor::TopEdgeResizeCursor:
  220795. case MouseCursor::BottomEdgeResizeCursor:
  220796. {
  220797. 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,
  220798. 255,255,0,0,0,33,249,4,1,0,0,2,0,44,0,0,0,0,16,0,
  220799. 16,0,0,2,38,148,111,128,187,16,202,90,152,48,10,55,169,189,192,245,
  220800. 106,121,27,34,142,201,99,158,224,86,154,109,216,61,29,155,105,180,61,190,
  220801. 121,84,0,0,59 };
  220802. const int cursDataSize = 85;
  220803. return cursorFromData (cursData, cursDataSize, 8, 8);
  220804. }
  220805. case MouseCursor::TopLeftCornerResizeCursor:
  220806. case MouseCursor::BottomRightCornerResizeCursor:
  220807. {
  220808. 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,
  220809. 255,255,0,0,0,33,249,4,1,0,0,2,0,44,0,0,0,0,16,0,
  220810. 16,0,0,2,43,132,15,162,187,16,255,18,99,14,202,217,44,158,213,221,
  220811. 237,9,225,38,94,35,73,5,31,42,170,108,106,174,112,43,195,209,91,185,
  220812. 104,174,131,208,77,66,28,10,0,59 };
  220813. const int cursDataSize = 90;
  220814. return cursorFromData (cursData, cursDataSize, 8, 8);
  220815. }
  220816. case MouseCursor::TopRightCornerResizeCursor:
  220817. case MouseCursor::BottomLeftCornerResizeCursor:
  220818. {
  220819. 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,
  220820. 255,255,0,0,0,33,249,4,1,0,0,2,0,44,0,0,0,0,16,0,
  220821. 16,0,0,2,45,148,127,160,11,232,16,98,108,14,65,73,107,194,122,223,
  220822. 92,65,141,216,145,134,162,153,221,25,128,73,166,62,173,16,203,237,188,94,
  220823. 120,46,237,105,239,123,48,80,157,2,0,59 };
  220824. const int cursDataSize = 92;
  220825. return cursorFromData (cursData, cursDataSize, 8, 8);
  220826. }
  220827. case MouseCursor::UpDownLeftRightResizeCursor:
  220828. {
  220829. 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,
  220830. 128,128,255,255,255,33,249,4,1,0,0,3,0,44,0,0,0,0,15,0,
  220831. 15,0,0,2,46,156,63,129,139,1,202,26,152,48,186,73,109,114,65,85,
  220832. 195,37,143,88,93,29,215,101,23,198,178,30,149,158,25,56,134,97,179,61,
  220833. 158,213,126,203,234,99,220,34,56,70,1,0,59,0,0 };
  220834. const int cursDataSize = 93;
  220835. return cursorFromData (cursData, cursDataSize, 7, 7);
  220836. }
  220837. case MouseCursor::CrosshairCursor:
  220838. cursorId = kThemeCrossCursor;
  220839. break;
  220840. }
  220841. CursorWrapper* cw = new CursorWrapper();
  220842. cw->cursor = 0;
  220843. cw->themeCursor = cursorId;
  220844. return (void*) cw;
  220845. }
  220846. void juce_deleteMouseCursor (void* const cursorHandle, const bool isStandard) throw()
  220847. {
  220848. CursorWrapper* const cw = (CursorWrapper*) cursorHandle;
  220849. if (cw != 0)
  220850. {
  220851. delete cw->cursor;
  220852. delete cw;
  220853. }
  220854. }
  220855. void MouseCursor::showInAllWindows() const throw()
  220856. {
  220857. showInWindow (0);
  220858. }
  220859. void MouseCursor::showInWindow (ComponentPeer*) const throw()
  220860. {
  220861. const CursorWrapper* const cw = (CursorWrapper*) getHandle();
  220862. if (cw != 0)
  220863. {
  220864. static bool isCursorHidden = false;
  220865. static bool showingWaitCursor = false;
  220866. const bool shouldShowWaitCursor = (cw->themeCursor == kThemeWatchCursor);
  220867. const bool shouldHideCursor = (cw->themeCursor == kSpecialNoCursor);
  220868. if (shouldShowWaitCursor != showingWaitCursor
  220869. && Process::isForegroundProcess())
  220870. {
  220871. showingWaitCursor = shouldShowWaitCursor;
  220872. QDDisplayWaitCursor (shouldShowWaitCursor);
  220873. }
  220874. if (shouldHideCursor != isCursorHidden)
  220875. {
  220876. isCursorHidden = shouldHideCursor;
  220877. if (shouldHideCursor)
  220878. HideCursor();
  220879. else
  220880. ShowCursor();
  220881. }
  220882. if (cw->cursor != 0)
  220883. SetCursor (cw->cursor);
  220884. else if (! (shouldShowWaitCursor || shouldHideCursor))
  220885. SetThemeCursor (cw->themeCursor);
  220886. }
  220887. }
  220888. Image* juce_createIconForFile (const File& file)
  220889. {
  220890. return 0;
  220891. }
  220892. class MainMenuHandler;
  220893. static MainMenuHandler* mainMenu = 0;
  220894. class MainMenuHandler : private MenuBarModelListener,
  220895. private DeletedAtShutdown
  220896. {
  220897. public:
  220898. MainMenuHandler() throw()
  220899. : currentModel (0)
  220900. {
  220901. }
  220902. ~MainMenuHandler() throw()
  220903. {
  220904. setMenu (0);
  220905. jassert (mainMenu == this);
  220906. mainMenu = 0;
  220907. }
  220908. void setMenu (MenuBarModel* const newMenuBarModel) throw()
  220909. {
  220910. if (currentModel != newMenuBarModel)
  220911. {
  220912. if (currentModel != 0)
  220913. currentModel->removeListener (this);
  220914. currentModel = newMenuBarModel;
  220915. if (currentModel != 0)
  220916. currentModel->addListener (this);
  220917. menuBarItemsChanged (0);
  220918. }
  220919. }
  220920. void menuBarItemsChanged (MenuBarModel*)
  220921. {
  220922. ClearMenuBar();
  220923. if (currentModel != 0)
  220924. {
  220925. int menuId = 1000;
  220926. const StringArray menuNames (currentModel->getMenuBarNames());
  220927. for (int i = 0; i < menuNames.size(); ++i)
  220928. {
  220929. const PopupMenu menu (currentModel->getMenuForIndex (i, menuNames [i]));
  220930. MenuRef m = createMenu (menu, menuNames [i], menuId, i);
  220931. InsertMenu (m, 0);
  220932. CFRelease (m);
  220933. }
  220934. }
  220935. }
  220936. void menuCommandInvoked (MenuBarModel*, const ApplicationCommandTarget::InvocationInfo& info)
  220937. {
  220938. MenuRef menu = 0;
  220939. MenuItemIndex index = 0;
  220940. GetIndMenuItemWithCommandID (0, info.commandID, 1, &menu, &index);
  220941. if (menu != 0)
  220942. {
  220943. FlashMenuBar (GetMenuID (menu));
  220944. FlashMenuBar (GetMenuID (menu));
  220945. }
  220946. }
  220947. void invoke (const int commandId, ApplicationCommandManager* const commandManager, const int topLevelIndex) const
  220948. {
  220949. if (currentModel != 0)
  220950. {
  220951. if (commandManager != 0)
  220952. {
  220953. ApplicationCommandTarget::InvocationInfo info (commandId);
  220954. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromMenu;
  220955. commandManager->invoke (info, true);
  220956. }
  220957. currentModel->menuItemSelected (commandId, topLevelIndex);
  220958. }
  220959. }
  220960. MenuBarModel* currentModel;
  220961. private:
  220962. static MenuRef createMenu (const PopupMenu menu,
  220963. const String& menuName,
  220964. int& id,
  220965. const int topLevelIndex)
  220966. {
  220967. MenuRef m = 0;
  220968. if (CreateNewMenu (id++, kMenuAttrAutoDisable, &m) == noErr)
  220969. {
  220970. CFStringRef name = PlatformUtilities::juceStringToCFString (menuName);
  220971. SetMenuTitleWithCFString (m, name);
  220972. CFRelease (name);
  220973. PopupMenu::MenuItemIterator iter (menu);
  220974. while (iter.next())
  220975. {
  220976. MenuItemIndex index = 0;
  220977. int flags = kMenuAttrAutoDisable | kMenuItemAttrIgnoreMeta | kMenuItemAttrNotPreviousAlternate;
  220978. if (! iter.isEnabled)
  220979. flags |= kMenuItemAttrDisabled;
  220980. CFStringRef text = PlatformUtilities::juceStringToCFString (iter.itemName.upToFirstOccurrenceOf (T("<end>"), false, true));
  220981. if (iter.isSeparator)
  220982. {
  220983. AppendMenuItemTextWithCFString (m, text, kMenuItemAttrSeparator, 0, &index);
  220984. }
  220985. else if (iter.isSectionHeader)
  220986. {
  220987. AppendMenuItemTextWithCFString (m, text, kMenuItemAttrSectionHeader, 0, &index);
  220988. }
  220989. else if (iter.subMenu != 0)
  220990. {
  220991. AppendMenuItemTextWithCFString (m, text, flags, id++, &index);
  220992. MenuRef sub = createMenu (*iter.subMenu, iter.itemName, id, topLevelIndex);
  220993. SetMenuItemHierarchicalMenu (m, index, sub);
  220994. CFRelease (sub);
  220995. }
  220996. else
  220997. {
  220998. AppendMenuItemTextWithCFString (m, text, flags, iter.itemId, &index);
  220999. if (iter.isTicked)
  221000. CheckMenuItem (m, index, true);
  221001. SetMenuItemProperty (m, index, 'juce', 'apcm', sizeof (void*), &iter.commandManager);
  221002. SetMenuItemProperty (m, index, 'juce', 'topi', sizeof (int), &topLevelIndex);
  221003. if (iter.commandManager != 0)
  221004. {
  221005. const Array <KeyPress> keyPresses (iter.commandManager->getKeyMappings()
  221006. ->getKeyPressesAssignedToCommand (iter.itemId));
  221007. if (keyPresses.size() > 0)
  221008. {
  221009. const KeyPress& kp = keyPresses.getReference(0);
  221010. int mods = 0;
  221011. if (kp.getModifiers().isShiftDown())
  221012. mods |= kMenuShiftModifier;
  221013. if (kp.getModifiers().isCtrlDown())
  221014. mods |= kMenuControlModifier;
  221015. if (kp.getModifiers().isAltDown())
  221016. mods |= kMenuOptionModifier;
  221017. if (! kp.getModifiers().isCommandDown())
  221018. mods |= kMenuNoCommandModifier;
  221019. tchar keyCode = (tchar) kp.getKeyCode();
  221020. if (kp.getKeyCode() >= KeyPress::numberPad0
  221021. && kp.getKeyCode() <= KeyPress::numberPad9)
  221022. {
  221023. keyCode = (tchar) ((T('0') - KeyPress::numberPad0) + kp.getKeyCode());
  221024. }
  221025. SetMenuItemCommandKey (m, index, true, 255);
  221026. if (CharacterFunctions::isLetterOrDigit (keyCode)
  221027. || CharacterFunctions::indexOfChar (T(",.;/\\'[]=-+_<>?{}\":"), keyCode, false) >= 0)
  221028. {
  221029. SetMenuItemModifiers (m, index, mods);
  221030. SetMenuItemCommandKey (m, index, false, CharacterFunctions::toUpperCase (keyCode));
  221031. }
  221032. else
  221033. {
  221034. const SInt16 glyph = getGlyphForKeyCode (kp.getKeyCode());
  221035. if (glyph != 0)
  221036. {
  221037. SetMenuItemModifiers (m, index, mods);
  221038. SetMenuItemKeyGlyph (m, index, glyph);
  221039. }
  221040. }
  221041. // if we set the key glyph to be a text char, and enable virtual
  221042. // key triggering, it stops the menu automatically triggering the callback
  221043. ChangeMenuItemAttributes (m, index, kMenuItemAttrUseVirtualKey, 0);
  221044. }
  221045. }
  221046. }
  221047. CFRelease (text);
  221048. }
  221049. }
  221050. return m;
  221051. }
  221052. static SInt16 getGlyphForKeyCode (const int keyCode) throw()
  221053. {
  221054. if (keyCode == KeyPress::spaceKey)
  221055. return kMenuSpaceGlyph;
  221056. else if (keyCode == KeyPress::returnKey)
  221057. return kMenuReturnGlyph;
  221058. else if (keyCode == KeyPress::escapeKey)
  221059. return kMenuEscapeGlyph;
  221060. else if (keyCode == KeyPress::backspaceKey)
  221061. return kMenuDeleteLeftGlyph;
  221062. else if (keyCode == KeyPress::leftKey)
  221063. return kMenuLeftArrowGlyph;
  221064. else if (keyCode == KeyPress::rightKey)
  221065. return kMenuRightArrowGlyph;
  221066. else if (keyCode == KeyPress::upKey)
  221067. return kMenuUpArrowGlyph;
  221068. else if (keyCode == KeyPress::downKey)
  221069. return kMenuDownArrowGlyph;
  221070. else if (keyCode == KeyPress::pageUpKey)
  221071. return kMenuPageUpGlyph;
  221072. else if (keyCode == KeyPress::pageDownKey)
  221073. return kMenuPageDownGlyph;
  221074. else if (keyCode == KeyPress::endKey)
  221075. return kMenuSoutheastArrowGlyph;
  221076. else if (keyCode == KeyPress::homeKey)
  221077. return kMenuNorthwestArrowGlyph;
  221078. else if (keyCode == KeyPress::deleteKey)
  221079. return kMenuDeleteRightGlyph;
  221080. else if (keyCode == KeyPress::tabKey)
  221081. return kMenuTabRightGlyph;
  221082. else if (keyCode == KeyPress::F1Key)
  221083. return kMenuF1Glyph;
  221084. else if (keyCode == KeyPress::F2Key)
  221085. return kMenuF2Glyph;
  221086. else if (keyCode == KeyPress::F3Key)
  221087. return kMenuF3Glyph;
  221088. else if (keyCode == KeyPress::F4Key)
  221089. return kMenuF4Glyph;
  221090. else if (keyCode == KeyPress::F5Key)
  221091. return kMenuF5Glyph;
  221092. else if (keyCode == KeyPress::F6Key)
  221093. return kMenuF6Glyph;
  221094. else if (keyCode == KeyPress::F7Key)
  221095. return kMenuF7Glyph;
  221096. else if (keyCode == KeyPress::F8Key)
  221097. return kMenuF8Glyph;
  221098. else if (keyCode == KeyPress::F9Key)
  221099. return kMenuF9Glyph;
  221100. else if (keyCode == KeyPress::F10Key)
  221101. return kMenuF10Glyph;
  221102. else if (keyCode == KeyPress::F11Key)
  221103. return kMenuF11Glyph;
  221104. else if (keyCode == KeyPress::F12Key)
  221105. return kMenuF12Glyph;
  221106. else if (keyCode == KeyPress::F13Key)
  221107. return kMenuF13Glyph;
  221108. else if (keyCode == KeyPress::F14Key)
  221109. return kMenuF14Glyph;
  221110. else if (keyCode == KeyPress::F15Key)
  221111. return kMenuF15Glyph;
  221112. return 0;
  221113. }
  221114. };
  221115. void MenuBarModel::setMacMainMenu (MenuBarModel* newMenuBarModel) throw()
  221116. {
  221117. if (getMacMainMenu() != newMenuBarModel)
  221118. {
  221119. if (newMenuBarModel == 0)
  221120. {
  221121. delete mainMenu;
  221122. jassert (mainMenu == 0); // should be zeroed in the destructor
  221123. }
  221124. else
  221125. {
  221126. if (mainMenu == 0)
  221127. mainMenu = new MainMenuHandler();
  221128. mainMenu->setMenu (newMenuBarModel);
  221129. }
  221130. }
  221131. }
  221132. MenuBarModel* MenuBarModel::getMacMainMenu() throw()
  221133. {
  221134. return mainMenu != 0 ? mainMenu->currentModel : 0;
  221135. }
  221136. // these functions are called externally from the message handling code
  221137. void juce_MainMenuAboutToBeUsed()
  221138. {
  221139. // force an update of the items just before the menu appears..
  221140. if (mainMenu != 0)
  221141. mainMenu->menuBarItemsChanged (0);
  221142. }
  221143. void juce_InvokeMainMenuCommand (const HICommand& command)
  221144. {
  221145. if (mainMenu != 0)
  221146. {
  221147. ApplicationCommandManager* commandManager = 0;
  221148. int topLevelIndex = 0;
  221149. if (GetMenuItemProperty (command.menu.menuRef, command.menu.menuItemIndex,
  221150. 'juce', 'apcm', sizeof (commandManager), 0, &commandManager) == noErr
  221151. && GetMenuItemProperty (command.menu.menuRef, command.menu.menuItemIndex,
  221152. 'juce', 'topi', sizeof (topLevelIndex), 0, &topLevelIndex) == noErr)
  221153. {
  221154. mainMenu->invoke (command.commandID, commandManager, topLevelIndex);
  221155. }
  221156. }
  221157. }
  221158. void PlatformUtilities::beep()
  221159. {
  221160. SysBeep (30);
  221161. }
  221162. void SystemClipboard::copyTextToClipboard (const String& text) throw()
  221163. {
  221164. ClearCurrentScrap();
  221165. ScrapRef ref;
  221166. GetCurrentScrap (&ref);
  221167. const int len = text.length();
  221168. const int numBytes = sizeof (UniChar) * len;
  221169. UniChar* const temp = (UniChar*) juce_calloc (numBytes);
  221170. for (int i = 0; i < len; ++i)
  221171. temp[i] = (UniChar) text[i];
  221172. PutScrapFlavor (ref,
  221173. kScrapFlavorTypeUnicode,
  221174. kScrapFlavorMaskNone,
  221175. numBytes,
  221176. temp);
  221177. juce_free (temp);
  221178. }
  221179. const String SystemClipboard::getTextFromClipboard() throw()
  221180. {
  221181. String result;
  221182. ScrapRef ref;
  221183. GetCurrentScrap (&ref);
  221184. Size size = 0;
  221185. if (GetScrapFlavorSize (ref, kScrapFlavorTypeUnicode, &size) == noErr
  221186. && size > 0)
  221187. {
  221188. void* const data = juce_calloc (size + 8);
  221189. if (GetScrapFlavorData (ref, kScrapFlavorTypeUnicode, &size, data) == noErr)
  221190. {
  221191. result = PlatformUtilities::convertUTF16ToString ((UniChar*) data);
  221192. }
  221193. juce_free (data);
  221194. }
  221195. return result;
  221196. }
  221197. bool AlertWindow::showNativeDialogBox (const String& title,
  221198. const String& bodyText,
  221199. bool isOkCancel)
  221200. {
  221201. Str255 tit, txt;
  221202. PlatformUtilities::copyToStr255 (tit, title);
  221203. PlatformUtilities::copyToStr255 (txt, bodyText);
  221204. AlertStdAlertParamRec ar;
  221205. ar.movable = true;
  221206. ar.helpButton = false;
  221207. ar.filterProc = 0;
  221208. ar.defaultText = (const unsigned char*)-1;
  221209. ar.cancelText = (const unsigned char*)((isOkCancel) ? -1 : 0);
  221210. ar.otherText = 0;
  221211. ar.defaultButton = kAlertStdAlertOKButton;
  221212. ar.cancelButton = 0;
  221213. ar.position = kWindowDefaultPosition;
  221214. SInt16 result;
  221215. StandardAlert (kAlertNoteAlert, tit, txt, &ar, &result);
  221216. return result == kAlertStdAlertOKButton;
  221217. }
  221218. const int KeyPress::spaceKey = ' ';
  221219. const int KeyPress::returnKey = kReturnCharCode;
  221220. const int KeyPress::escapeKey = kEscapeCharCode;
  221221. const int KeyPress::backspaceKey = kBackspaceCharCode;
  221222. const int KeyPress::leftKey = kLeftArrowCharCode;
  221223. const int KeyPress::rightKey = kRightArrowCharCode;
  221224. const int KeyPress::upKey = kUpArrowCharCode;
  221225. const int KeyPress::downKey = kDownArrowCharCode;
  221226. const int KeyPress::pageUpKey = kPageUpCharCode;
  221227. const int KeyPress::pageDownKey = kPageDownCharCode;
  221228. const int KeyPress::endKey = kEndCharCode;
  221229. const int KeyPress::homeKey = kHomeCharCode;
  221230. const int KeyPress::deleteKey = kDeleteCharCode;
  221231. const int KeyPress::insertKey = -1;
  221232. const int KeyPress::tabKey = kTabCharCode;
  221233. const int KeyPress::F1Key = 0x10110;
  221234. const int KeyPress::F2Key = 0x10111;
  221235. const int KeyPress::F3Key = 0x10112;
  221236. const int KeyPress::F4Key = 0x10113;
  221237. const int KeyPress::F5Key = 0x10114;
  221238. const int KeyPress::F6Key = 0x10115;
  221239. const int KeyPress::F7Key = 0x10116;
  221240. const int KeyPress::F8Key = 0x10117;
  221241. const int KeyPress::F9Key = 0x10118;
  221242. const int KeyPress::F10Key = 0x10119;
  221243. const int KeyPress::F11Key = 0x1011a;
  221244. const int KeyPress::F12Key = 0x1011b;
  221245. const int KeyPress::F13Key = 0x1011c;
  221246. const int KeyPress::F14Key = 0x1011d;
  221247. const int KeyPress::F15Key = 0x1011e;
  221248. const int KeyPress::F16Key = 0x1011f;
  221249. const int KeyPress::numberPad0 = 0x30020;
  221250. const int KeyPress::numberPad1 = 0x30021;
  221251. const int KeyPress::numberPad2 = 0x30022;
  221252. const int KeyPress::numberPad3 = 0x30023;
  221253. const int KeyPress::numberPad4 = 0x30024;
  221254. const int KeyPress::numberPad5 = 0x30025;
  221255. const int KeyPress::numberPad6 = 0x30026;
  221256. const int KeyPress::numberPad7 = 0x30027;
  221257. const int KeyPress::numberPad8 = 0x30028;
  221258. const int KeyPress::numberPad9 = 0x30029;
  221259. const int KeyPress::numberPadAdd = 0x3002a;
  221260. const int KeyPress::numberPadSubtract = 0x3002b;
  221261. const int KeyPress::numberPadMultiply = 0x3002c;
  221262. const int KeyPress::numberPadDivide = 0x3002d;
  221263. const int KeyPress::numberPadSeparator = 0x3002e;
  221264. const int KeyPress::numberPadDecimalPoint = 0x3002f;
  221265. const int KeyPress::numberPadEquals = 0x30030;
  221266. const int KeyPress::numberPadDelete = 0x30031;
  221267. const int KeyPress::playKey = 0x30000;
  221268. const int KeyPress::stopKey = 0x30001;
  221269. const int KeyPress::fastForwardKey = 0x30002;
  221270. const int KeyPress::rewindKey = 0x30003;
  221271. AppleRemoteDevice::AppleRemoteDevice()
  221272. : device (0),
  221273. queue (0),
  221274. remoteId (0)
  221275. {
  221276. }
  221277. AppleRemoteDevice::~AppleRemoteDevice()
  221278. {
  221279. stop();
  221280. }
  221281. static io_object_t getAppleRemoteDevice() throw()
  221282. {
  221283. CFMutableDictionaryRef dict = IOServiceMatching ("AppleIRController");
  221284. io_iterator_t iter = 0;
  221285. io_object_t iod = 0;
  221286. if (IOServiceGetMatchingServices (kIOMasterPortDefault, dict, &iter) == kIOReturnSuccess
  221287. && iter != 0)
  221288. {
  221289. iod = IOIteratorNext (iter);
  221290. }
  221291. IOObjectRelease (iter);
  221292. return iod;
  221293. }
  221294. static bool createAppleRemoteInterface (io_object_t iod, void** device) throw()
  221295. {
  221296. jassert (*device == 0);
  221297. io_name_t classname;
  221298. if (IOObjectGetClass (iod, classname) == kIOReturnSuccess)
  221299. {
  221300. IOCFPlugInInterface** cfPlugInInterface = 0;
  221301. SInt32 score = 0;
  221302. if (IOCreatePlugInInterfaceForService (iod,
  221303. kIOHIDDeviceUserClientTypeID,
  221304. kIOCFPlugInInterfaceID,
  221305. &cfPlugInInterface,
  221306. &score) == kIOReturnSuccess)
  221307. {
  221308. HRESULT hr = (*cfPlugInInterface)->QueryInterface (cfPlugInInterface,
  221309. CFUUIDGetUUIDBytes (kIOHIDDeviceInterfaceID),
  221310. device);
  221311. (void) hr;
  221312. (*cfPlugInInterface)->Release (cfPlugInInterface);
  221313. }
  221314. }
  221315. return *device != 0;
  221316. }
  221317. bool AppleRemoteDevice::start (const bool inExclusiveMode) throw()
  221318. {
  221319. if (queue != 0)
  221320. return true;
  221321. stop();
  221322. bool result = false;
  221323. io_object_t iod = getAppleRemoteDevice();
  221324. if (iod != 0)
  221325. {
  221326. if (createAppleRemoteInterface (iod, &device) && open (inExclusiveMode))
  221327. result = true;
  221328. else
  221329. stop();
  221330. IOObjectRelease (iod);
  221331. }
  221332. return result;
  221333. }
  221334. void AppleRemoteDevice::stop() throw()
  221335. {
  221336. if (queue != 0)
  221337. {
  221338. (*(IOHIDQueueInterface**) queue)->stop ((IOHIDQueueInterface**) queue);
  221339. (*(IOHIDQueueInterface**) queue)->dispose ((IOHIDQueueInterface**) queue);
  221340. (*(IOHIDQueueInterface**) queue)->Release ((IOHIDQueueInterface**) queue);
  221341. queue = 0;
  221342. }
  221343. if (device != 0)
  221344. {
  221345. (*(IOHIDDeviceInterface**) device)->close ((IOHIDDeviceInterface**) device);
  221346. (*(IOHIDDeviceInterface**) device)->Release ((IOHIDDeviceInterface**) device);
  221347. device = 0;
  221348. }
  221349. }
  221350. bool AppleRemoteDevice::isActive() const throw()
  221351. {
  221352. return queue != 0;
  221353. }
  221354. static void appleRemoteQueueCallback (void* const target, const IOReturn result, void*, void*)
  221355. {
  221356. if (result == kIOReturnSuccess)
  221357. ((AppleRemoteDevice*) target)->handleCallbackInternal();
  221358. }
  221359. bool AppleRemoteDevice::open (const bool openInExclusiveMode) throw()
  221360. {
  221361. #if ! MACOS_10_2_OR_EARLIER
  221362. Array <int> cookies;
  221363. CFArrayRef elements;
  221364. IOHIDDeviceInterface122** const device122 = (IOHIDDeviceInterface122**) device;
  221365. if ((*device122)->copyMatchingElements (device122, 0, &elements) != kIOReturnSuccess)
  221366. return false;
  221367. for (int i = 0; i < CFArrayGetCount (elements); ++i)
  221368. {
  221369. CFDictionaryRef element = (CFDictionaryRef) CFArrayGetValueAtIndex (elements, i);
  221370. // get the cookie
  221371. CFTypeRef object = CFDictionaryGetValue (element, CFSTR (kIOHIDElementCookieKey));
  221372. if (object == 0 || CFGetTypeID (object) != CFNumberGetTypeID())
  221373. continue;
  221374. long number;
  221375. if (! CFNumberGetValue ((CFNumberRef) object, kCFNumberLongType, &number))
  221376. continue;
  221377. cookies.add ((int) number);
  221378. }
  221379. CFRelease (elements);
  221380. if ((*(IOHIDDeviceInterface**) device)
  221381. ->open ((IOHIDDeviceInterface**) device,
  221382. openInExclusiveMode ? kIOHIDOptionsTypeSeizeDevice
  221383. : kIOHIDOptionsTypeNone) == KERN_SUCCESS)
  221384. {
  221385. queue = (*(IOHIDDeviceInterface**) device)->allocQueue ((IOHIDDeviceInterface**) device);
  221386. if (queue != 0)
  221387. {
  221388. (*(IOHIDQueueInterface**) queue)->create ((IOHIDQueueInterface**) queue, 0, 12);
  221389. for (int i = 0; i < cookies.size(); ++i)
  221390. {
  221391. IOHIDElementCookie cookie = (IOHIDElementCookie) cookies.getUnchecked(i);
  221392. (*(IOHIDQueueInterface**) queue)->addElement ((IOHIDQueueInterface**) queue, cookie, 0);
  221393. }
  221394. CFRunLoopSourceRef eventSource;
  221395. if ((*(IOHIDQueueInterface**) queue)
  221396. ->createAsyncEventSource ((IOHIDQueueInterface**) queue, &eventSource) == KERN_SUCCESS)
  221397. {
  221398. if ((*(IOHIDQueueInterface**) queue)->setEventCallout ((IOHIDQueueInterface**) queue,
  221399. appleRemoteQueueCallback, this, 0) == KERN_SUCCESS)
  221400. {
  221401. CFRunLoopAddSource (CFRunLoopGetCurrent(), eventSource, kCFRunLoopDefaultMode);
  221402. (*(IOHIDQueueInterface**) queue)->start ((IOHIDQueueInterface**) queue);
  221403. return true;
  221404. }
  221405. }
  221406. }
  221407. }
  221408. #endif
  221409. return false;
  221410. }
  221411. void AppleRemoteDevice::handleCallbackInternal()
  221412. {
  221413. int totalValues = 0;
  221414. AbsoluteTime nullTime = { 0, 0 };
  221415. char cookies [12];
  221416. int numCookies = 0;
  221417. while (numCookies < numElementsInArray (cookies))
  221418. {
  221419. IOHIDEventStruct e;
  221420. if ((*(IOHIDQueueInterface**) queue)->getNextEvent ((IOHIDQueueInterface**) queue, &e, nullTime, 0) != kIOReturnSuccess)
  221421. break;
  221422. if ((int) e.elementCookie == 19)
  221423. {
  221424. remoteId = e.value;
  221425. buttonPressed (switched, false);
  221426. }
  221427. else
  221428. {
  221429. totalValues += e.value;
  221430. cookies [numCookies++] = (char) (pointer_sized_int) e.elementCookie;
  221431. }
  221432. }
  221433. cookies [numCookies++] = 0;
  221434. static const char buttonPatterns[] =
  221435. {
  221436. 14, 7, 6, 5, 14, 7, 6, 5, 0,
  221437. 14, 8, 6, 5, 14, 8, 6, 5, 0,
  221438. 14, 12, 11, 6, 5, 0,
  221439. 14, 13, 11, 6, 5, 0,
  221440. 14, 9, 6, 5, 14, 9, 6, 5, 0,
  221441. 14, 10, 6, 5, 14, 10, 6, 5, 0,
  221442. 14, 6, 5, 4, 2, 0,
  221443. 14, 6, 5, 3, 2, 0,
  221444. 14, 6, 5, 14, 6, 5, 0,
  221445. 18, 14, 6, 5, 18, 14, 6, 5, 0,
  221446. 19, 0
  221447. };
  221448. int buttonNum = (int) menuButton;
  221449. int i = 0;
  221450. while (i < numElementsInArray (buttonPatterns))
  221451. {
  221452. if (strcmp (cookies, buttonPatterns + i) == 0)
  221453. {
  221454. buttonPressed ((ButtonType) buttonNum, totalValues > 0);
  221455. break;
  221456. }
  221457. i += strlen (buttonPatterns + i) + 1;
  221458. ++buttonNum;
  221459. }
  221460. }
  221461. #if JUCE_OPENGL
  221462. class WindowedGLContext : public OpenGLContext
  221463. {
  221464. public:
  221465. WindowedGLContext (Component* const component,
  221466. const OpenGLPixelFormat& pixelFormat_,
  221467. AGLContext sharedContext)
  221468. : renderContext (0),
  221469. pixelFormat (pixelFormat_)
  221470. {
  221471. jassert (component != 0);
  221472. HIViewComponentPeer* const peer = dynamic_cast <HIViewComponentPeer*> (component->getTopLevelComponent()->getPeer());
  221473. if (peer == 0)
  221474. return;
  221475. GLint attribs [64];
  221476. int n = 0;
  221477. attribs[n++] = AGL_RGBA;
  221478. attribs[n++] = AGL_DOUBLEBUFFER;
  221479. attribs[n++] = AGL_ACCELERATED;
  221480. attribs[n++] = AGL_RED_SIZE;
  221481. attribs[n++] = pixelFormat.redBits;
  221482. attribs[n++] = AGL_GREEN_SIZE;
  221483. attribs[n++] = pixelFormat.greenBits;
  221484. attribs[n++] = AGL_BLUE_SIZE;
  221485. attribs[n++] = pixelFormat.blueBits;
  221486. attribs[n++] = AGL_ALPHA_SIZE;
  221487. attribs[n++] = pixelFormat.alphaBits;
  221488. attribs[n++] = AGL_DEPTH_SIZE;
  221489. attribs[n++] = pixelFormat.depthBufferBits;
  221490. attribs[n++] = AGL_STENCIL_SIZE;
  221491. attribs[n++] = pixelFormat.stencilBufferBits;
  221492. attribs[n++] = AGL_ACCUM_RED_SIZE;
  221493. attribs[n++] = pixelFormat.accumulationBufferRedBits;
  221494. attribs[n++] = AGL_ACCUM_GREEN_SIZE;
  221495. attribs[n++] = pixelFormat.accumulationBufferGreenBits;
  221496. attribs[n++] = AGL_ACCUM_BLUE_SIZE;
  221497. attribs[n++] = pixelFormat.accumulationBufferBlueBits;
  221498. attribs[n++] = AGL_ACCUM_ALPHA_SIZE;
  221499. attribs[n++] = pixelFormat.accumulationBufferAlphaBits;
  221500. // xxx not sure how to do fullSceneAntiAliasingNumSamples..
  221501. attribs[n++] = AGL_SAMPLE_BUFFERS_ARB;
  221502. attribs[n++] = 1;
  221503. attribs[n++] = AGL_SAMPLES_ARB;
  221504. attribs[n++] = 4;
  221505. attribs[n++] = AGL_CLOSEST_POLICY;
  221506. attribs[n++] = AGL_NO_RECOVERY;
  221507. attribs[n++] = AGL_NONE;
  221508. renderContext = aglCreateContext (aglChoosePixelFormat (0, 0, attribs),
  221509. sharedContext);
  221510. aglSetDrawable (renderContext, GetWindowPort (peer->windowRef));
  221511. }
  221512. ~WindowedGLContext()
  221513. {
  221514. makeInactive();
  221515. aglSetDrawable (renderContext, 0);
  221516. aglDestroyContext (renderContext);
  221517. }
  221518. bool makeActive() const throw()
  221519. {
  221520. jassert (renderContext != 0);
  221521. return aglSetCurrentContext (renderContext);
  221522. }
  221523. bool makeInactive() const throw()
  221524. {
  221525. return (! isActive()) || aglSetCurrentContext (0);
  221526. }
  221527. bool isActive() const throw()
  221528. {
  221529. return aglGetCurrentContext() == renderContext;
  221530. }
  221531. const OpenGLPixelFormat getPixelFormat() const
  221532. {
  221533. return pixelFormat;
  221534. }
  221535. void* getRawContext() const throw()
  221536. {
  221537. return renderContext;
  221538. }
  221539. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  221540. {
  221541. GLint bufferRect[4];
  221542. bufferRect[0] = x;
  221543. bufferRect[1] = outerWindowHeight - (y + h);
  221544. bufferRect[2] = w;
  221545. bufferRect[3] = h;
  221546. aglSetInteger (renderContext, AGL_BUFFER_RECT, bufferRect);
  221547. aglEnable (renderContext, AGL_BUFFER_RECT);
  221548. }
  221549. void swapBuffers()
  221550. {
  221551. aglSwapBuffers (renderContext);
  221552. }
  221553. bool setSwapInterval (const int numFramesPerSwap)
  221554. {
  221555. return aglSetInteger (renderContext, AGL_SWAP_INTERVAL, (const GLint*) &numFramesPerSwap);
  221556. }
  221557. int getSwapInterval() const
  221558. {
  221559. GLint numFrames = 0;
  221560. aglGetInteger (renderContext, AGL_SWAP_INTERVAL, &numFrames);
  221561. return numFrames;
  221562. }
  221563. void repaint()
  221564. {
  221565. }
  221566. juce_UseDebuggingNewOperator
  221567. AGLContext renderContext;
  221568. private:
  221569. OpenGLPixelFormat pixelFormat;
  221570. WindowedGLContext (const WindowedGLContext&);
  221571. const WindowedGLContext& operator= (const WindowedGLContext&);
  221572. };
  221573. OpenGLContext* OpenGLContext::createContextForWindow (Component* const component,
  221574. const OpenGLPixelFormat& pixelFormat,
  221575. const OpenGLContext* const contextToShareWith)
  221576. {
  221577. WindowedGLContext* c = new WindowedGLContext (component, pixelFormat,
  221578. contextToShareWith != 0 ? (AGLContext) contextToShareWith->getRawContext() : 0);
  221579. if (c->renderContext == 0)
  221580. deleteAndZero (c);
  221581. return c;
  221582. }
  221583. void juce_glViewport (const int w, const int h)
  221584. {
  221585. glViewport (0, 0, w, h);
  221586. }
  221587. static int getAGLAttribute (AGLPixelFormat p, const GLint attrib)
  221588. {
  221589. GLint result = 0;
  221590. aglDescribePixelFormat (p, attrib, &result);
  221591. return result;
  221592. }
  221593. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  221594. OwnedArray <OpenGLPixelFormat>& results)
  221595. {
  221596. GLint attribs [64];
  221597. int n = 0;
  221598. attribs[n++] = AGL_RGBA;
  221599. attribs[n++] = AGL_DOUBLEBUFFER;
  221600. attribs[n++] = AGL_ACCELERATED;
  221601. attribs[n++] = AGL_NO_RECOVERY;
  221602. attribs[n++] = AGL_NONE;
  221603. AGLPixelFormat p = aglChoosePixelFormat (0, 0, attribs);
  221604. while (p != 0)
  221605. {
  221606. OpenGLPixelFormat* const pf = new OpenGLPixelFormat();
  221607. pf->redBits = getAGLAttribute (p, AGL_RED_SIZE);
  221608. pf->greenBits = getAGLAttribute (p, AGL_GREEN_SIZE);
  221609. pf->blueBits = getAGLAttribute (p, AGL_BLUE_SIZE);
  221610. pf->alphaBits = getAGLAttribute (p, AGL_ALPHA_SIZE);
  221611. pf->depthBufferBits = getAGLAttribute (p, AGL_DEPTH_SIZE);
  221612. pf->stencilBufferBits = getAGLAttribute (p, AGL_STENCIL_SIZE);
  221613. pf->accumulationBufferRedBits = getAGLAttribute (p, AGL_ACCUM_RED_SIZE);
  221614. pf->accumulationBufferGreenBits = getAGLAttribute (p, AGL_ACCUM_GREEN_SIZE);
  221615. pf->accumulationBufferBlueBits = getAGLAttribute (p, AGL_ACCUM_BLUE_SIZE);
  221616. pf->accumulationBufferAlphaBits = getAGLAttribute (p, AGL_ACCUM_ALPHA_SIZE);
  221617. results.add (pf);
  221618. p = aglNextPixelFormat (p);
  221619. }
  221620. }
  221621. #endif
  221622. END_JUCE_NAMESPACE
  221623. /********* End of inlined file: juce_mac_Windowing.cpp *********/
  221624. #endif
  221625. #endif